@stackframe/dashboard-ui-components 2.8.76

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/LICENSE +5 -0
  2. package/dist/chunk-BE-pF4vm.js +34 -0
  3. package/dist/components/alert.d.ts +22 -0
  4. package/dist/components/alert.d.ts.map +1 -0
  5. package/dist/components/alert.js +75 -0
  6. package/dist/components/alert.js.map +1 -0
  7. package/dist/components/badge.d.ts +24 -0
  8. package/dist/components/badge.d.ts.map +1 -0
  9. package/dist/components/badge.js +59 -0
  10. package/dist/components/badge.js.map +1 -0
  11. package/dist/components/button.d.ts +32 -0
  12. package/dist/components/button.d.ts.map +1 -0
  13. package/dist/components/button.js +68 -0
  14. package/dist/components/button.js.map +1 -0
  15. package/dist/components/card.d.ts +59 -0
  16. package/dist/components/card.d.ts.map +1 -0
  17. package/dist/components/card.js +133 -0
  18. package/dist/components/card.js.map +1 -0
  19. package/dist/components/chart-card.d.ts +21 -0
  20. package/dist/components/chart-card.d.ts.map +1 -0
  21. package/dist/components/chart-card.js +54 -0
  22. package/dist/components/chart-card.js.map +1 -0
  23. package/dist/components/chart-container.d.ts +51 -0
  24. package/dist/components/chart-container.d.ts.map +1 -0
  25. package/dist/components/chart-container.js +77 -0
  26. package/dist/components/chart-container.js.map +1 -0
  27. package/dist/components/chart-legend.d.ts +12 -0
  28. package/dist/components/chart-legend.d.ts.map +1 -0
  29. package/dist/components/chart-legend.js +41 -0
  30. package/dist/components/chart-legend.js.map +1 -0
  31. package/dist/components/chart-theme.d.ts +26 -0
  32. package/dist/components/chart-theme.d.ts.map +1 -0
  33. package/dist/components/chart-theme.js +64 -0
  34. package/dist/components/chart-theme.js.map +1 -0
  35. package/dist/components/chart-tooltip.d.ts +41 -0
  36. package/dist/components/chart-tooltip.d.ts.map +1 -0
  37. package/dist/components/chart-tooltip.js +89 -0
  38. package/dist/components/chart-tooltip.js.map +1 -0
  39. package/dist/components/cursor-blast-effect.d.ts +27 -0
  40. package/dist/components/cursor-blast-effect.d.ts.map +1 -0
  41. package/dist/components/cursor-blast-effect.js +243 -0
  42. package/dist/components/cursor-blast-effect.js.map +1 -0
  43. package/dist/components/edit-mode.d.ts +12 -0
  44. package/dist/components/edit-mode.d.ts.map +1 -0
  45. package/dist/components/edit-mode.js +23 -0
  46. package/dist/components/edit-mode.js.map +1 -0
  47. package/dist/components/empty-state.d.ts +21 -0
  48. package/dist/components/empty-state.d.ts.map +1 -0
  49. package/dist/components/empty-state.js +37 -0
  50. package/dist/components/empty-state.js.map +1 -0
  51. package/dist/components/input.d.ts +18 -0
  52. package/dist/components/input.d.ts.map +1 -0
  53. package/dist/components/input.js +53 -0
  54. package/dist/components/input.js.map +1 -0
  55. package/dist/components/metric-card.d.ts +31 -0
  56. package/dist/components/metric-card.d.ts.map +1 -0
  57. package/dist/components/metric-card.js +88 -0
  58. package/dist/components/metric-card.js.map +1 -0
  59. package/dist/components/pill-toggle.d.ts +33 -0
  60. package/dist/components/pill-toggle.d.ts.map +1 -0
  61. package/dist/components/pill-toggle.js +86 -0
  62. package/dist/components/pill-toggle.js.map +1 -0
  63. package/dist/components/progress-bar.d.ts +25 -0
  64. package/dist/components/progress-bar.d.ts.map +1 -0
  65. package/dist/components/progress-bar.js +44 -0
  66. package/dist/components/progress-bar.js.map +1 -0
  67. package/dist/components/separator.d.ts +14 -0
  68. package/dist/components/separator.d.ts.map +1 -0
  69. package/dist/components/separator.js +20 -0
  70. package/dist/components/separator.js.map +1 -0
  71. package/dist/components/skeleton.d.ts +12 -0
  72. package/dist/components/skeleton.d.ts.map +1 -0
  73. package/dist/components/skeleton.js +18 -0
  74. package/dist/components/skeleton.js.map +1 -0
  75. package/dist/components/table.d.ts +24 -0
  76. package/dist/components/table.d.ts.map +1 -0
  77. package/dist/components/table.js +59 -0
  78. package/dist/components/table.js.map +1 -0
  79. package/dist/components/tabs.d.ts +34 -0
  80. package/dist/components/tabs.d.ts.map +1 -0
  81. package/dist/components/tabs.js +100 -0
  82. package/dist/components/tabs.js.map +1 -0
  83. package/dist/dashboard-ui-components.global.js +15232 -0
  84. package/dist/dashboard-ui-components.global.js.map +7 -0
  85. package/dist/esm/components/alert.d.ts +22 -0
  86. package/dist/esm/components/alert.d.ts.map +1 -0
  87. package/dist/esm/components/alert.js +73 -0
  88. package/dist/esm/components/alert.js.map +1 -0
  89. package/dist/esm/components/badge.d.ts +24 -0
  90. package/dist/esm/components/badge.d.ts.map +1 -0
  91. package/dist/esm/components/badge.js +57 -0
  92. package/dist/esm/components/badge.js.map +1 -0
  93. package/dist/esm/components/button.d.ts +32 -0
  94. package/dist/esm/components/button.d.ts.map +1 -0
  95. package/dist/esm/components/button.js +65 -0
  96. package/dist/esm/components/button.js.map +1 -0
  97. package/dist/esm/components/card.d.ts +59 -0
  98. package/dist/esm/components/card.d.ts.map +1 -0
  99. package/dist/esm/components/card.js +127 -0
  100. package/dist/esm/components/card.js.map +1 -0
  101. package/dist/esm/components/chart-card.d.ts +21 -0
  102. package/dist/esm/components/chart-card.d.ts.map +1 -0
  103. package/dist/esm/components/chart-card.js +51 -0
  104. package/dist/esm/components/chart-card.js.map +1 -0
  105. package/dist/esm/components/chart-container.d.ts +51 -0
  106. package/dist/esm/components/chart-container.d.ts.map +1 -0
  107. package/dist/esm/components/chart-container.js +70 -0
  108. package/dist/esm/components/chart-container.js.map +1 -0
  109. package/dist/esm/components/chart-legend.d.ts +12 -0
  110. package/dist/esm/components/chart-legend.d.ts.map +1 -0
  111. package/dist/esm/components/chart-legend.js +36 -0
  112. package/dist/esm/components/chart-legend.js.map +1 -0
  113. package/dist/esm/components/chart-theme.d.ts +26 -0
  114. package/dist/esm/components/chart-theme.d.ts.map +1 -0
  115. package/dist/esm/components/chart-theme.js +59 -0
  116. package/dist/esm/components/chart-theme.js.map +1 -0
  117. package/dist/esm/components/chart-tooltip.d.ts +41 -0
  118. package/dist/esm/components/chart-tooltip.d.ts.map +1 -0
  119. package/dist/esm/components/chart-tooltip.js +84 -0
  120. package/dist/esm/components/chart-tooltip.js.map +1 -0
  121. package/dist/esm/components/cursor-blast-effect.d.ts +27 -0
  122. package/dist/esm/components/cursor-blast-effect.d.ts.map +1 -0
  123. package/dist/esm/components/cursor-blast-effect.js +241 -0
  124. package/dist/esm/components/cursor-blast-effect.js.map +1 -0
  125. package/dist/esm/components/edit-mode.d.ts +12 -0
  126. package/dist/esm/components/edit-mode.d.ts.map +1 -0
  127. package/dist/esm/components/edit-mode.js +20 -0
  128. package/dist/esm/components/edit-mode.js.map +1 -0
  129. package/dist/esm/components/empty-state.d.ts +21 -0
  130. package/dist/esm/components/empty-state.d.ts.map +1 -0
  131. package/dist/esm/components/empty-state.js +34 -0
  132. package/dist/esm/components/empty-state.js.map +1 -0
  133. package/dist/esm/components/input.d.ts +18 -0
  134. package/dist/esm/components/input.d.ts.map +1 -0
  135. package/dist/esm/components/input.js +50 -0
  136. package/dist/esm/components/input.js.map +1 -0
  137. package/dist/esm/components/metric-card.d.ts +31 -0
  138. package/dist/esm/components/metric-card.d.ts.map +1 -0
  139. package/dist/esm/components/metric-card.js +85 -0
  140. package/dist/esm/components/metric-card.js.map +1 -0
  141. package/dist/esm/components/pill-toggle.d.ts +33 -0
  142. package/dist/esm/components/pill-toggle.d.ts.map +1 -0
  143. package/dist/esm/components/pill-toggle.js +84 -0
  144. package/dist/esm/components/pill-toggle.js.map +1 -0
  145. package/dist/esm/components/progress-bar.d.ts +25 -0
  146. package/dist/esm/components/progress-bar.d.ts.map +1 -0
  147. package/dist/esm/components/progress-bar.js +42 -0
  148. package/dist/esm/components/progress-bar.js.map +1 -0
  149. package/dist/esm/components/separator.d.ts +14 -0
  150. package/dist/esm/components/separator.d.ts.map +1 -0
  151. package/dist/esm/components/separator.js +18 -0
  152. package/dist/esm/components/separator.js.map +1 -0
  153. package/dist/esm/components/skeleton.d.ts +12 -0
  154. package/dist/esm/components/skeleton.d.ts.map +1 -0
  155. package/dist/esm/components/skeleton.js +16 -0
  156. package/dist/esm/components/skeleton.js.map +1 -0
  157. package/dist/esm/components/table.d.ts +24 -0
  158. package/dist/esm/components/table.d.ts.map +1 -0
  159. package/dist/esm/components/table.js +51 -0
  160. package/dist/esm/components/table.js.map +1 -0
  161. package/dist/esm/components/tabs.d.ts +34 -0
  162. package/dist/esm/components/tabs.d.ts.map +1 -0
  163. package/dist/esm/components/tabs.js +98 -0
  164. package/dist/esm/components/tabs.js.map +1 -0
  165. package/dist/esm/index.d.ts +21 -0
  166. package/dist/esm/index.js +22 -0
  167. package/dist/index.d.ts +21 -0
  168. package/dist/index.js +245 -0
  169. package/package.json +71 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["global-react:react", "../../../node_modules/.pnpm/property-expr@2.0.6/node_modules/property-expr/index.js", "../../../node_modules/.pnpm/tiny-case@1.0.3/node_modules/tiny-case/index.js", "../../../node_modules/.pnpm/toposort@2.0.2/node_modules/toposort/index.js", "global-react-dom:react-dom", "global-recharts:recharts", "../src/index.ts", "../../../node_modules/.pnpm/@phosphor-icons+react@2.1.10_react-dom@19.2.3_react@19.2.3__react@19.2.3/node_modules/@phosphor-icons/react/dist/defs/CheckCircle.es.js", "../../../node_modules/.pnpm/@phosphor-icons+react@2.1.10_react-dom@19.2.3_react@19.2.3__react@19.2.3/node_modules/@phosphor-icons/react/dist/defs/Info.es.js", "../../../node_modules/.pnpm/@phosphor-icons+react@2.1.10_react-dom@19.2.3_react@19.2.3__react@19.2.3/node_modules/@phosphor-icons/react/dist/defs/WarningCircle.es.js", "../../../node_modules/.pnpm/@phosphor-icons+react@2.1.10_react-dom@19.2.3_react@19.2.3__react@19.2.3/node_modules/@phosphor-icons/react/dist/defs/XCircle.es.js", "../../../node_modules/.pnpm/@phosphor-icons+react@2.1.10_react-dom@19.2.3_react@19.2.3__react@19.2.3/node_modules/@phosphor-icons/react/dist/lib/IconBase.es.js", "../../../node_modules/.pnpm/@phosphor-icons+react@2.1.10_react-dom@19.2.3_react@19.2.3__react@19.2.3/node_modules/@phosphor-icons/react/dist/lib/context.es.js", "../../../node_modules/.pnpm/@phosphor-icons+react@2.1.10_react-dom@19.2.3_react@19.2.3__react@19.2.3/node_modules/@phosphor-icons/react/dist/csr/CheckCircle.es.js", "../../../node_modules/.pnpm/@phosphor-icons+react@2.1.10_react-dom@19.2.3_react@19.2.3__react@19.2.3/node_modules/@phosphor-icons/react/dist/csr/Info.es.js", "../../../node_modules/.pnpm/@phosphor-icons+react@2.1.10_react-dom@19.2.3_react@19.2.3__react@19.2.3/node_modules/@phosphor-icons/react/dist/csr/WarningCircle.es.js", "../../../node_modules/.pnpm/@phosphor-icons+react@2.1.10_react-dom@19.2.3_react@19.2.3__react@19.2.3/node_modules/@phosphor-icons/react/dist/csr/XCircle.es.js", "jsx-shim:react/jsx-runtime", "../../stack-shared/src/utils/arrays.tsx", "../../stack-shared/src/utils/strings.tsx", "../../stack-shared/src/utils/functions.tsx", "../../stack-shared/src/utils/types.tsx", "../../stack-shared/src/utils/objects.tsx", "../../stack-shared/src/utils/globals.tsx", "../../stack-shared/src/utils/errors.tsx", "../../../node_modules/.pnpm/clsx@2.1.1/node_modules/clsx/dist/clsx.mjs", "../../../node_modules/.pnpm/tailwind-merge@2.5.4/node_modules/tailwind-merge/src/lib/class-group-utils.ts", "../../../node_modules/.pnpm/tailwind-merge@2.5.4/node_modules/tailwind-merge/src/lib/lru-cache.ts", "../../../node_modules/.pnpm/tailwind-merge@2.5.4/node_modules/tailwind-merge/src/lib/parse-class-name.ts", "../../../node_modules/.pnpm/tailwind-merge@2.5.4/node_modules/tailwind-merge/src/lib/config-utils.ts", "../../../node_modules/.pnpm/tailwind-merge@2.5.4/node_modules/tailwind-merge/src/lib/merge-classlist.ts", "../../../node_modules/.pnpm/tailwind-merge@2.5.4/node_modules/tailwind-merge/src/lib/tw-join.ts", "../../../node_modules/.pnpm/tailwind-merge@2.5.4/node_modules/tailwind-merge/src/lib/create-tailwind-merge.ts", "../../../node_modules/.pnpm/tailwind-merge@2.5.4/node_modules/tailwind-merge/src/lib/from-theme.ts", "../../../node_modules/.pnpm/tailwind-merge@2.5.4/node_modules/tailwind-merge/src/lib/validators.ts", "../../../node_modules/.pnpm/tailwind-merge@2.5.4/node_modules/tailwind-merge/src/lib/default-config.ts", "../../../node_modules/.pnpm/tailwind-merge@2.5.4/node_modules/tailwind-merge/src/lib/merge-configs.ts", "../../../node_modules/.pnpm/tailwind-merge@2.5.4/node_modules/tailwind-merge/src/lib/extend-tailwind-merge.ts", "../../../node_modules/.pnpm/tailwind-merge@2.5.4/node_modules/tailwind-merge/src/lib/tw-merge.ts", "../../stack-ui/src/lib/utils.tsx", "../../stack-shared/src/utils/results.tsx", "../../stack-shared/src/known-errors.tsx", "../../stack-shared/src/utils/bytes.tsx", "../../stack-shared/src/utils/urls.tsx", "../../../node_modules/.pnpm/yup@1.7.1/node_modules/yup/index.esm.js", "../../stack-shared/src/utils/currency-constants.tsx", "../../stack-shared/src/utils/http.tsx", "../../stack-shared/src/utils/oauth.tsx", "../../stack-shared/src/utils/uuids.tsx", "../../stack-shared/src/schema-fields.ts", "../../../node_modules/.pnpm/async-mutex@0.5.0/node_modules/async-mutex/index.mjs", "../../stack-shared/src/utils/locks.tsx", "../../stack-shared/src/utils/stores.tsx", "../../../node_modules/.pnpm/oauth4webapi@3.8.3/node_modules/oauth4webapi/build/index.js", "../../stack-shared/src/interface/client-interface.ts", "../../stack-shared/src/utils/maps.tsx", "../../stack-shared/src/utils/promises.tsx", "../../../node_modules/.pnpm/@radix-ui+react-slot@1.1.0_@types+react@18.3.12_react@19.2.1/node_modules/@radix-ui/react-slot/src/Slot.tsx", "../../../node_modules/.pnpm/@radix-ui+react-compose-refs@1.1.0_@types+react@18.3.12_react@19.2.1/node_modules/@radix-ui/react-compose-refs/src/composeRefs.tsx", "../../../node_modules/.pnpm/@radix-ui+primitive@1.1.0/node_modules/@radix-ui/primitive/src/primitive.tsx", "../../../node_modules/.pnpm/@radix-ui+react-context@1.1.0_@types+react@18.3.12_react@19.2.1/node_modules/@radix-ui/react-context/src/createContext.tsx", "../../../node_modules/.pnpm/@radix-ui+react-context@1.1.1_@types+react@18.3.12_react@19.2.1/node_modules/@radix-ui/react-context/src/createContext.tsx", "../../../node_modules/.pnpm/@radix-ui+react-dismissable-layer@1.1.1_@types+react-dom@18.3.1_@types+react@18.3.12_re_f005e7f95aa2eec7605cf7f5e28f987f/node_modules/@radix-ui/react-dismissable-layer/src/DismissableLayer.tsx", "../../../node_modules/.pnpm/@radix-ui+react-primitive@2.0.0_@types+react-dom@18.3.1_@types+react@18.3.12_react-dom@19.2.1_react@19.2.1__react@19.2.1/node_modules/@radix-ui/react-primitive/src/Primitive.tsx", "../../../node_modules/.pnpm/@radix-ui+react-use-callback-ref@1.1.0_@types+react@18.3.12_react@19.2.1/node_modules/@radix-ui/react-use-callback-ref/src/useCallbackRef.tsx", "../../../node_modules/.pnpm/@radix-ui+react-use-escape-keydown@1.1.0_@types+react@18.3.12_react@19.2.1/node_modules/@radix-ui/react-use-escape-keydown/src/useEscapeKeydown.tsx", "../../../node_modules/.pnpm/@radix-ui+react-id@1.1.0_@types+react@18.3.12_react@19.2.1/node_modules/@radix-ui/react-id/src/id.tsx", "../../../node_modules/.pnpm/@radix-ui+react-use-layout-effect@1.1.0_@types+react@18.3.12_react@19.2.1/node_modules/@radix-ui/react-use-layout-effect/src/useLayoutEffect.tsx", "../../../node_modules/.pnpm/@radix-ui+react-popper@1.2.0_@types+react-dom@18.3.1_@types+react@18.3.12_react-dom@19.2.1_react@19.2.1__react@19.2.1/node_modules/@radix-ui/react-popper/src/Popper.tsx", "../../../node_modules/.pnpm/@floating-ui+utils@0.2.8/node_modules/@floating-ui/utils/dist/floating-ui.utils.mjs", "../../../node_modules/.pnpm/@floating-ui+core@1.6.8/node_modules/@floating-ui/core/dist/floating-ui.core.mjs", "../../../node_modules/.pnpm/@floating-ui+utils@0.2.8/node_modules/@floating-ui/utils/dist/floating-ui.utils.dom.mjs", "../../../node_modules/.pnpm/@floating-ui+dom@1.6.12/node_modules/@floating-ui/dom/dist/floating-ui.dom.mjs", "../../../node_modules/.pnpm/@floating-ui+react-dom@2.1.2_react-dom@19.2.1_react@19.2.1__react@19.2.1/node_modules/@floating-ui/react-dom/dist/floating-ui.react-dom.mjs", "../../../node_modules/.pnpm/@radix-ui+react-arrow@1.1.0_@types+react-dom@18.3.1_@types+react@18.3.12_react-dom@19.2.1_react@19.2.1__react@19.2.1/node_modules/@radix-ui/react-arrow/src/Arrow.tsx", "../../../node_modules/.pnpm/@radix-ui+react-use-size@1.1.0_@types+react@18.3.12_react@19.2.1/node_modules/@radix-ui/react-use-size/src/useSize.tsx", "../../../node_modules/.pnpm/@radix-ui+react-portal@1.1.2_@types+react-dom@18.3.1_@types+react@18.3.12_react-dom@19.2.1_react@19.2.1__react@19.2.1/node_modules/@radix-ui/react-portal/src/Portal.tsx", "../../../node_modules/.pnpm/@radix-ui+react-use-controllable-state@1.1.0_@types+react@18.3.12_react@19.2.1/node_modules/@radix-ui/react-use-controllable-state/src/useControllableState.tsx", "../../../node_modules/.pnpm/@radix-ui+react-visually-hidden@1.1.0_@types+react-dom@18.3.1_@types+react@18.3.12_reac_5bb0983b1979feb277f3f775d43a4c59/node_modules/@radix-ui/react-visually-hidden/src/VisuallyHidden.tsx", "../../../node_modules/.pnpm/@radix-ui+react-presence@1.1.1_@types+react-dom@18.3.1_@types+react@18.3.12_react-dom@19.2.1_react@19.2.1__react@19.2.1/node_modules/@radix-ui/react-presence/src/Presence.tsx", "../../../node_modules/.pnpm/@radix-ui+react-presence@1.1.1_@types+react-dom@18.3.1_@types+react@18.3.12_react-dom@19.2.1_react@19.2.1__react@19.2.1/node_modules/@radix-ui/react-presence/src/useStateMachine.tsx", "../../../node_modules/.pnpm/@radix-ui+primitive@1.1.3/node_modules/@radix-ui/primitive/src/primitive.tsx", "../../../node_modules/.pnpm/@radix-ui+react-tooltip@1.1.3_@types+react-dom@18.3.1_@types+react@18.3.12_react-dom@19.2.1_react@19.2.1__react@19.2.1/node_modules/@radix-ui/react-tooltip/src/Tooltip.tsx", "../../stack-ui/src/components/ui/card.tsx", "../src/components/alert.tsx", "../src/components/badge.tsx", "../../../node_modules/.pnpm/@radix-ui+react-slot@1.2.4_@types+react@18.3.12_react@19.2.3/node_modules/@radix-ui/react-slot/src/slot.tsx", "../../../node_modules/.pnpm/@radix-ui+react-compose-refs@1.1.2_@types+react@18.3.12_react@19.2.3/node_modules/@radix-ui/react-compose-refs/src/compose-refs.tsx", "../../../node_modules/.pnpm/class-variance-authority@0.7.1/node_modules/class-variance-authority/dist/index.mjs", "../src/components/button.tsx", "../src/components/card.tsx", "../src/components/cursor-blast-effect.tsx", "../src/components/edit-mode.tsx", "../src/components/input.tsx", "../src/components/pill-toggle.tsx", "../../../node_modules/.pnpm/@radix-ui+react-tooltip@1.2.8_@types+react-dom@18.3.1_@types+react@18.3.12_react-dom@19.2.3_react@19.2.3__react@19.2.3/node_modules/@radix-ui/react-tooltip/src/tooltip.tsx", "../../../node_modules/.pnpm/@radix-ui+react-context@1.1.2_@types+react@18.3.12_react@19.2.3/node_modules/@radix-ui/react-context/src/create-context.tsx", "../../../node_modules/.pnpm/@radix-ui+react-dismissable-layer@1.1.11_@types+react-dom@18.3.1_@types+react@18.3.12_r_e4093f5981aea34e35803c4408f783d9/node_modules/@radix-ui/react-dismissable-layer/src/dismissable-layer.tsx", "../../../node_modules/.pnpm/@radix-ui+react-primitive@2.1.3_@types+react-dom@18.3.1_@types+react@18.3.12_react-dom@19.2.3_react@19.2.3__react@19.2.3/node_modules/@radix-ui/react-primitive/src/primitive.tsx", "../../../node_modules/.pnpm/@radix-ui+react-slot@1.2.3_@types+react@18.3.12_react@19.2.3/node_modules/@radix-ui/react-slot/src/slot.tsx", "../../../node_modules/.pnpm/@radix-ui+react-use-callback-ref@1.1.1_@types+react@18.3.12_react@19.2.3/node_modules/@radix-ui/react-use-callback-ref/src/use-callback-ref.tsx", "../../../node_modules/.pnpm/@radix-ui+react-use-escape-keydown@1.1.1_@types+react@18.3.12_react@19.2.3/node_modules/@radix-ui/react-use-escape-keydown/src/use-escape-keydown.tsx", "../../../node_modules/.pnpm/@radix-ui+react-id@1.1.1_@types+react@18.3.12_react@19.2.3/node_modules/@radix-ui/react-id/src/id.tsx", "../../../node_modules/.pnpm/@radix-ui+react-use-layout-effect@1.1.1_@types+react@18.3.12_react@19.2.3/node_modules/@radix-ui/react-use-layout-effect/src/use-layout-effect.tsx", "../../../node_modules/.pnpm/@radix-ui+react-popper@1.2.8_@types+react-dom@18.3.1_@types+react@18.3.12_react-dom@19.2.3_react@19.2.3__react@19.2.3/node_modules/@radix-ui/react-popper/src/popper.tsx", "../../../node_modules/.pnpm/@floating-ui+react-dom@2.1.2_react-dom@19.2.3_react@19.2.3__react@19.2.3/node_modules/@floating-ui/react-dom/dist/floating-ui.react-dom.mjs", "../../../node_modules/.pnpm/@radix-ui+react-arrow@1.1.7_@types+react-dom@18.3.1_@types+react@18.3.12_react-dom@19.2.3_react@19.2.3__react@19.2.3/node_modules/@radix-ui/react-arrow/src/arrow.tsx", "../../../node_modules/.pnpm/@radix-ui+react-use-size@1.1.1_@types+react@18.3.12_react@19.2.3/node_modules/@radix-ui/react-use-size/src/use-size.tsx", "../../../node_modules/.pnpm/@radix-ui+react-portal@1.1.9_@types+react-dom@18.3.1_@types+react@18.3.12_react-dom@19.2.3_react@19.2.3__react@19.2.3/node_modules/@radix-ui/react-portal/src/portal.tsx", "../../../node_modules/.pnpm/@radix-ui+react-presence@1.1.5_@types+react-dom@18.3.1_@types+react@18.3.12_react-dom@19.2.3_react@19.2.3__react@19.2.3/node_modules/@radix-ui/react-presence/src/presence.tsx", "../../../node_modules/.pnpm/@radix-ui+react-presence@1.1.5_@types+react-dom@18.3.1_@types+react@18.3.12_react-dom@19.2.3_react@19.2.3__react@19.2.3/node_modules/@radix-ui/react-presence/src/use-state-machine.tsx", "../../../node_modules/.pnpm/@radix-ui+react-use-controllable-state@1.2.2_@types+react@18.3.12_react@19.2.3/node_modules/@radix-ui/react-use-controllable-state/src/use-controllable-state.tsx", "../../../node_modules/.pnpm/@radix-ui+react-use-controllable-state@1.2.2_@types+react@18.3.12_react@19.2.3/node_modules/@radix-ui/react-use-controllable-state/src/use-controllable-state-reducer.tsx", "../../../node_modules/.pnpm/@radix-ui+react-visually-hidden@1.2.3_@types+react-dom@18.3.1_@types+react@18.3.12_reac_3795bdad014cb2641d7688daa1175481/node_modules/@radix-ui/react-visually-hidden/src/visually-hidden.tsx", "../src/components/separator.tsx", "../src/components/skeleton.tsx", "../src/components/table.tsx", "../src/components/tabs.tsx", "../src/components/chart-theme.tsx", "../src/components/chart-container.tsx", "../src/components/chart-tooltip.tsx", "../src/components/chart-legend.tsx", "../src/components/chart-card.tsx", "../src/components/metric-card.tsx", "../src/components/progress-bar.tsx", "../src/components/empty-state.tsx"],
4
+ "sourcesContent": ["module.exports = globalThis.React;", "/**\n * Based on Kendo UI Core expression code <https://github.com/telerik/kendo-ui-core#license-information>\n */\n'use strict'\n\nfunction Cache(maxSize) {\n this._maxSize = maxSize\n this.clear()\n}\nCache.prototype.clear = function () {\n this._size = 0\n this._values = Object.create(null)\n}\nCache.prototype.get = function (key) {\n return this._values[key]\n}\nCache.prototype.set = function (key, value) {\n this._size >= this._maxSize && this.clear()\n if (!(key in this._values)) this._size++\n\n return (this._values[key] = value)\n}\n\nvar SPLIT_REGEX = /[^.^\\]^[]+|(?=\\[\\]|\\.\\.)/g,\n DIGIT_REGEX = /^\\d+$/,\n LEAD_DIGIT_REGEX = /^\\d/,\n SPEC_CHAR_REGEX = /[~`!#$%\\^&*+=\\-\\[\\]\\\\';,/{}|\\\\\":<>\\?]/g,\n CLEAN_QUOTES_REGEX = /^\\s*(['\"]?)(.*?)(\\1)\\s*$/,\n MAX_CACHE_SIZE = 512\n\nvar pathCache = new Cache(MAX_CACHE_SIZE),\n setCache = new Cache(MAX_CACHE_SIZE),\n getCache = new Cache(MAX_CACHE_SIZE)\n\nvar config\n\nmodule.exports = {\n Cache: Cache,\n\n split: split,\n\n normalizePath: normalizePath,\n\n setter: function (path) {\n var parts = normalizePath(path)\n\n return (\n setCache.get(path) ||\n setCache.set(path, function setter(obj, value) {\n var index = 0\n var len = parts.length\n var data = obj\n\n while (index < len - 1) {\n var part = parts[index]\n if (\n part === '__proto__' ||\n part === 'constructor' ||\n part === 'prototype'\n ) {\n return obj\n }\n\n data = data[parts[index++]]\n }\n data[parts[index]] = value\n })\n )\n },\n\n getter: function (path, safe) {\n var parts = normalizePath(path)\n return (\n getCache.get(path) ||\n getCache.set(path, function getter(data) {\n var index = 0,\n len = parts.length\n while (index < len) {\n if (data != null || !safe) data = data[parts[index++]]\n else return\n }\n return data\n })\n )\n },\n\n join: function (segments) {\n return segments.reduce(function (path, part) {\n return (\n path +\n (isQuoted(part) || DIGIT_REGEX.test(part)\n ? '[' + part + ']'\n : (path ? '.' : '') + part)\n )\n }, '')\n },\n\n forEach: function (path, cb, thisArg) {\n forEach(Array.isArray(path) ? path : split(path), cb, thisArg)\n },\n}\n\nfunction normalizePath(path) {\n return (\n pathCache.get(path) ||\n pathCache.set(\n path,\n split(path).map(function (part) {\n return part.replace(CLEAN_QUOTES_REGEX, '$2')\n })\n )\n )\n}\n\nfunction split(path) {\n return path.match(SPLIT_REGEX) || ['']\n}\n\nfunction forEach(parts, iter, thisArg) {\n var len = parts.length,\n part,\n idx,\n isArray,\n isBracket\n\n for (idx = 0; idx < len; idx++) {\n part = parts[idx]\n\n if (part) {\n if (shouldBeQuoted(part)) {\n part = '\"' + part + '\"'\n }\n\n isBracket = isQuoted(part)\n isArray = !isBracket && /^\\d+$/.test(part)\n\n iter.call(thisArg, part, isBracket, isArray, idx, parts)\n }\n }\n}\n\nfunction isQuoted(str) {\n return (\n typeof str === 'string' && str && [\"'\", '\"'].indexOf(str.charAt(0)) !== -1\n )\n}\n\nfunction hasLeadingNumber(part) {\n return part.match(LEAD_DIGIT_REGEX) && !part.match(DIGIT_REGEX)\n}\n\nfunction hasSpecialChars(part) {\n return SPEC_CHAR_REGEX.test(part)\n}\n\nfunction shouldBeQuoted(part) {\n return !isQuoted(part) && (hasLeadingNumber(part) || hasSpecialChars(part))\n}\n", "const reWords = /[A-Z\\xc0-\\xd6\\xd8-\\xde]?[a-z\\xdf-\\xf6\\xf8-\\xff]+(?:['\u2019](?:d|ll|m|re|s|t|ve))?(?=[\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000]|[A-Z\\xc0-\\xd6\\xd8-\\xde]|$)|(?:[A-Z\\xc0-\\xd6\\xd8-\\xde]|[^\\ud800-\\udfff\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000\\d+\\u2700-\\u27bfa-z\\xdf-\\xf6\\xf8-\\xffA-Z\\xc0-\\xd6\\xd8-\\xde])+(?:['\u2019](?:D|LL|M|RE|S|T|VE))?(?=[\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000]|[A-Z\\xc0-\\xd6\\xd8-\\xde](?:[a-z\\xdf-\\xf6\\xf8-\\xff]|[^\\ud800-\\udfff\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000\\d+\\u2700-\\u27bfa-z\\xdf-\\xf6\\xf8-\\xffA-Z\\xc0-\\xd6\\xd8-\\xde])|$)|[A-Z\\xc0-\\xd6\\xd8-\\xde]?(?:[a-z\\xdf-\\xf6\\xf8-\\xff]|[^\\ud800-\\udfff\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000\\d+\\u2700-\\u27bfa-z\\xdf-\\xf6\\xf8-\\xffA-Z\\xc0-\\xd6\\xd8-\\xde])+(?:['\u2019](?:d|ll|m|re|s|t|ve))?|[A-Z\\xc0-\\xd6\\xd8-\\xde]+(?:['\u2019](?:D|LL|M|RE|S|T|VE))?|\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])|\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])|\\d+|(?:[\\u2700-\\u27bf]|(?:\\ud83c[\\udde6-\\uddff]){2}|[\\ud800-\\udbff][\\udc00-\\udfff])[\\ufe0e\\ufe0f]?(?:[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]|\\ud83c[\\udffb-\\udfff])?(?:\\u200d(?:[^\\ud800-\\udfff]|(?:\\ud83c[\\udde6-\\uddff]){2}|[\\ud800-\\udbff][\\udc00-\\udfff])[\\ufe0e\\ufe0f]?(?:[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]|\\ud83c[\\udffb-\\udfff])?)*/g\n\nconst words = (str) => str.match(reWords) || []\n\nconst upperFirst = (str) => str[0].toUpperCase() + str.slice(1)\n\nconst join = (str, d) => words(str).join(d).toLowerCase()\n\nconst camelCase = (str) =>\n words(str).reduce(\n (acc, next) =>\n `${acc}${\n !acc\n ? next.toLowerCase()\n : next[0].toUpperCase() + next.slice(1).toLowerCase()\n }`,\n '',\n )\n\nconst pascalCase = (str) => upperFirst(camelCase(str))\n\nconst snakeCase = (str) => join(str, '_')\n\nconst kebabCase = (str) => join(str, '-')\n\nconst sentenceCase = (str) => upperFirst(join(str, ' '))\n\nconst titleCase = (str) => words(str).map(upperFirst).join(' ')\n\nmodule.exports = {\n words,\n upperFirst,\n camelCase,\n pascalCase,\n snakeCase,\n kebabCase,\n sentenceCase,\n titleCase,\n}\n", "\n/**\n * Topological sorting function\n *\n * @param {Array} edges\n * @returns {Array}\n */\n\nmodule.exports = function(edges) {\n return toposort(uniqueNodes(edges), edges)\n}\n\nmodule.exports.array = toposort\n\nfunction toposort(nodes, edges) {\n var cursor = nodes.length\n , sorted = new Array(cursor)\n , visited = {}\n , i = cursor\n // Better data structures make algorithm much faster.\n , outgoingEdges = makeOutgoingEdges(edges)\n , nodesHash = makeNodesHash(nodes)\n\n // check for unknown nodes\n edges.forEach(function(edge) {\n if (!nodesHash.has(edge[0]) || !nodesHash.has(edge[1])) {\n throw new Error('Unknown node. There is an unknown node in the supplied edges.')\n }\n })\n\n while (i--) {\n if (!visited[i]) visit(nodes[i], i, new Set())\n }\n\n return sorted\n\n function visit(node, i, predecessors) {\n if(predecessors.has(node)) {\n var nodeRep\n try {\n nodeRep = \", node was:\" + JSON.stringify(node)\n } catch(e) {\n nodeRep = \"\"\n }\n throw new Error('Cyclic dependency' + nodeRep)\n }\n\n if (!nodesHash.has(node)) {\n throw new Error('Found unknown node. Make sure to provided all involved nodes. Unknown node: '+JSON.stringify(node))\n }\n\n if (visited[i]) return;\n visited[i] = true\n\n var outgoing = outgoingEdges.get(node) || new Set()\n outgoing = Array.from(outgoing)\n\n if (i = outgoing.length) {\n predecessors.add(node)\n do {\n var child = outgoing[--i]\n visit(child, nodesHash.get(child), predecessors)\n } while (i)\n predecessors.delete(node)\n }\n\n sorted[--cursor] = node\n }\n}\n\nfunction uniqueNodes(arr){\n var res = new Set()\n for (var i = 0, len = arr.length; i < len; i++) {\n var edge = arr[i]\n res.add(edge[0])\n res.add(edge[1])\n }\n return Array.from(res)\n}\n\nfunction makeOutgoingEdges(arr){\n var edges = new Map()\n for (var i = 0, len = arr.length; i < len; i++) {\n var edge = arr[i]\n if (!edges.has(edge[0])) edges.set(edge[0], new Set())\n if (!edges.has(edge[1])) edges.set(edge[1], new Set())\n edges.get(edge[0]).add(edge[1])\n }\n return edges\n}\n\nfunction makeNodesHash(arr){\n var res = new Map()\n for (var i = 0, len = arr.length; i < len; i++) {\n res.set(arr[i], i)\n }\n return res\n}\n", "module.exports = globalThis.ReactDOM;", "module.exports = globalThis.Recharts;", "export { DesignAlert } from \"./components/alert\";\nexport type { DesignAlertProps } from \"./components/alert\";\n\nexport { DesignBadge } from \"./components/badge\";\nexport type { DesignBadgeColor, DesignBadgeSize, DesignBadgeContentMode, DesignBadgeProps } from \"./components/badge\";\n\nexport { DesignButton } from \"./components/button\";\nexport type { DesignOriginalButtonProps, DesignButtonProps } from \"./components/button\";\n\nexport { DesignCard, DesignCardTint, useInsideDesignCard, useGlassmorphicDefault } from \"./components/card\";\nexport type { DesignCardProps, DesignCardTintProps } from \"./components/card\";\n\nexport { CursorBlastEffect } from \"./components/cursor-blast-effect\";\nexport type { CursorBlastEffectProps } from \"./components/cursor-blast-effect\";\n\nexport { DesignEditMode, useDesignEditMode } from \"./components/edit-mode\";\n\nexport { DesignInput } from \"./components/input\";\nexport type { DesignInputProps } from \"./components/input\";\n\nexport { DesignPillToggle } from \"./components/pill-toggle\";\nexport type { DesignPillToggleOption, DesignPillToggleProps } from \"./components/pill-toggle\";\n\nexport { DesignSeparator } from \"./components/separator\";\nexport type { DesignSeparatorProps } from \"./components/separator\";\n\nexport { DesignSkeleton } from \"./components/skeleton\";\nexport type { DesignSkeletonProps } from \"./components/skeleton\";\n\nexport { DesignTable, DesignTableHeader, DesignTableBody, DesignTableRow, DesignTableHead, DesignTableCell } from \"./components/table\";\n\nexport { DesignCategoryTabs } from \"./components/tabs\";\nexport type { DesignCategoryTabItem, DesignCategoryTabsProps } from \"./components/tabs\";\n\nexport { DESIGN_CHART_COLORS, getDesignChartColor, DESIGN_CHART_GRID_COLOR, DESIGN_CHART_AXIS_TICK_STYLE } from \"./components/chart-theme\";\nexport type { DesignChartColorEntry, DesignChartColorName } from \"./components/chart-theme\";\n\nexport { DesignChartContainer, DesignChartStyle, useDesignChart, getPayloadConfigFromPayload } from \"./components/chart-container\";\nexport type { DesignChartConfig } from \"./components/chart-container\";\n\nexport { DesignChartTooltip, DesignChartTooltipContent } from \"./components/chart-tooltip\";\n\nexport { DesignChartLegend, DesignChartLegendContent } from \"./components/chart-legend\";\n\nexport { DesignChartCard } from \"./components/chart-card\";\nexport type { DesignChartCardProps } from \"./components/chart-card\";\n\nexport { DesignMetricCard } from \"./components/metric-card\";\nexport type { DesignMetricCardProps, DesignMetricCardTrend } from \"./components/metric-card\";\n\nexport { DesignProgressBar } from \"./components/progress-bar\";\nexport type { DesignProgressBarProps } from \"./components/progress-bar\";\n\nexport { DesignEmptyState } from \"./components/empty-state\";\nexport type { DesignEmptyStateProps } from \"./components/empty-state\";\n", "import * as e from \"react\";\nconst a = /* @__PURE__ */ new Map([\n [\n \"bold\",\n /* @__PURE__ */ e.createElement(e.Fragment, null, /* @__PURE__ */ e.createElement(\"path\", { d: \"M176.49,95.51a12,12,0,0,1,0,17l-56,56a12,12,0,0,1-17,0l-24-24a12,12,0,1,1,17-17L112,143l47.51-47.52A12,12,0,0,1,176.49,95.51ZM236,128A108,108,0,1,1,128,20,108.12,108.12,0,0,1,236,128Zm-24,0a84,84,0,1,0-84,84A84.09,84.09,0,0,0,212,128Z\" }))\n ],\n [\n \"duotone\",\n /* @__PURE__ */ e.createElement(e.Fragment, null, /* @__PURE__ */ e.createElement(\"path\", { d: \"M224,128a96,96,0,1,1-96-96A96,96,0,0,1,224,128Z\", opacity: \"0.2\" }), /* @__PURE__ */ e.createElement(\"path\", { d: \"M173.66,98.34a8,8,0,0,1,0,11.32l-56,56a8,8,0,0,1-11.32,0l-24-24a8,8,0,0,1,11.32-11.32L112,148.69l50.34-50.35A8,8,0,0,1,173.66,98.34ZM232,128A104,104,0,1,1,128,24,104.11,104.11,0,0,1,232,128Zm-16,0a88,88,0,1,0-88,88A88.1,88.1,0,0,0,216,128Z\" }))\n ],\n [\n \"fill\",\n /* @__PURE__ */ e.createElement(e.Fragment, null, /* @__PURE__ */ e.createElement(\"path\", { d: \"M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm45.66,85.66-56,56a8,8,0,0,1-11.32,0l-24-24a8,8,0,0,1,11.32-11.32L112,148.69l50.34-50.35a8,8,0,0,1,11.32,11.32Z\" }))\n ],\n [\n \"light\",\n /* @__PURE__ */ e.createElement(e.Fragment, null, /* @__PURE__ */ e.createElement(\"path\", { d: \"M172.24,99.76a6,6,0,0,1,0,8.48l-56,56a6,6,0,0,1-8.48,0l-24-24a6,6,0,0,1,8.48-8.48L112,151.51l51.76-51.75A6,6,0,0,1,172.24,99.76ZM230,128A102,102,0,1,1,128,26,102.12,102.12,0,0,1,230,128Zm-12,0a90,90,0,1,0-90,90A90.1,90.1,0,0,0,218,128Z\" }))\n ],\n [\n \"regular\",\n /* @__PURE__ */ e.createElement(e.Fragment, null, /* @__PURE__ */ e.createElement(\"path\", { d: \"M173.66,98.34a8,8,0,0,1,0,11.32l-56,56a8,8,0,0,1-11.32,0l-24-24a8,8,0,0,1,11.32-11.32L112,148.69l50.34-50.35A8,8,0,0,1,173.66,98.34ZM232,128A104,104,0,1,1,128,24,104.11,104.11,0,0,1,232,128Zm-16,0a88,88,0,1,0-88,88A88.1,88.1,0,0,0,216,128Z\" }))\n ],\n [\n \"thin\",\n /* @__PURE__ */ e.createElement(e.Fragment, null, /* @__PURE__ */ e.createElement(\"path\", { d: \"M170.83,101.17a4,4,0,0,1,0,5.66l-56,56a4,4,0,0,1-5.66,0l-24-24a4,4,0,0,1,5.66-5.66L112,154.34l53.17-53.17A4,4,0,0,1,170.83,101.17ZM228,128A100,100,0,1,1,128,28,100.11,100.11,0,0,1,228,128Zm-8,0a92,92,0,1,0-92,92A92.1,92.1,0,0,0,220,128Z\" }))\n ]\n]);\nexport {\n a as default\n};\n", "import * as e from \"react\";\nconst a = /* @__PURE__ */ new Map([\n [\n \"bold\",\n /* @__PURE__ */ e.createElement(e.Fragment, null, /* @__PURE__ */ e.createElement(\"path\", { d: \"M108,84a16,16,0,1,1,16,16A16,16,0,0,1,108,84Zm128,44A108,108,0,1,1,128,20,108.12,108.12,0,0,1,236,128Zm-24,0a84,84,0,1,0-84,84A84.09,84.09,0,0,0,212,128Zm-72,36.68V132a20,20,0,0,0-20-20,12,12,0,0,0-4,23.32V168a20,20,0,0,0,20,20,12,12,0,0,0,4-23.32Z\" }))\n ],\n [\n \"duotone\",\n /* @__PURE__ */ e.createElement(e.Fragment, null, /* @__PURE__ */ e.createElement(\"path\", { d: \"M224,128a96,96,0,1,1-96-96A96,96,0,0,1,224,128Z\", opacity: \"0.2\" }), /* @__PURE__ */ e.createElement(\"path\", { d: \"M144,176a8,8,0,0,1-8,8,16,16,0,0,1-16-16V128a8,8,0,0,1,0-16,16,16,0,0,1,16,16v40A8,8,0,0,1,144,176Zm88-48A104,104,0,1,1,128,24,104.11,104.11,0,0,1,232,128Zm-16,0a88,88,0,1,0-88,88A88.1,88.1,0,0,0,216,128ZM124,96a12,12,0,1,0-12-12A12,12,0,0,0,124,96Z\" }))\n ],\n [\n \"fill\",\n /* @__PURE__ */ e.createElement(e.Fragment, null, /* @__PURE__ */ e.createElement(\"path\", { d: \"M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm-4,48a12,12,0,1,1-12,12A12,12,0,0,1,124,72Zm12,112a16,16,0,0,1-16-16V128a8,8,0,0,1,0-16,16,16,0,0,1,16,16v40a8,8,0,0,1,0,16Z\" }))\n ],\n [\n \"light\",\n /* @__PURE__ */ e.createElement(e.Fragment, null, /* @__PURE__ */ e.createElement(\"path\", { d: \"M142,176a6,6,0,0,1-6,6,14,14,0,0,1-14-14V128a2,2,0,0,0-2-2,6,6,0,0,1,0-12,14,14,0,0,1,14,14v40a2,2,0,0,0,2,2A6,6,0,0,1,142,176ZM124,94a10,10,0,1,0-10-10A10,10,0,0,0,124,94Zm106,34A102,102,0,1,1,128,26,102.12,102.12,0,0,1,230,128Zm-12,0a90,90,0,1,0-90,90A90.1,90.1,0,0,0,218,128Z\" }))\n ],\n [\n \"regular\",\n /* @__PURE__ */ e.createElement(e.Fragment, null, /* @__PURE__ */ e.createElement(\"path\", { d: \"M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm0,192a88,88,0,1,1,88-88A88.1,88.1,0,0,1,128,216Zm16-40a8,8,0,0,1-8,8,16,16,0,0,1-16-16V128a8,8,0,0,1,0-16,16,16,0,0,1,16,16v40A8,8,0,0,1,144,176ZM112,84a12,12,0,1,1,12,12A12,12,0,0,1,112,84Z\" }))\n ],\n [\n \"thin\",\n /* @__PURE__ */ e.createElement(e.Fragment, null, /* @__PURE__ */ e.createElement(\"path\", { d: \"M140,176a4,4,0,0,1-4,4,12,12,0,0,1-12-12V128a4,4,0,0,0-4-4,4,4,0,0,1,0-8,12,12,0,0,1,12,12v40a4,4,0,0,0,4,4A4,4,0,0,1,140,176ZM124,92a8,8,0,1,0-8-8A8,8,0,0,0,124,92Zm104,36A100,100,0,1,1,128,28,100.11,100.11,0,0,1,228,128Zm-8,0a92,92,0,1,0-92,92A92.1,92.1,0,0,0,220,128Z\" }))\n ]\n]);\nexport {\n a as default\n};\n", "import * as e from \"react\";\nconst a = /* @__PURE__ */ new Map([\n [\n \"bold\",\n /* @__PURE__ */ e.createElement(e.Fragment, null, /* @__PURE__ */ e.createElement(\"path\", { d: \"M128,20A108,108,0,1,0,236,128,108.12,108.12,0,0,0,128,20Zm0,192a84,84,0,1,1,84-84A84.09,84.09,0,0,1,128,212Zm-12-80V80a12,12,0,0,1,24,0v52a12,12,0,0,1-24,0Zm28,40a16,16,0,1,1-16-16A16,16,0,0,1,144,172Z\" }))\n ],\n [\n \"duotone\",\n /* @__PURE__ */ e.createElement(e.Fragment, null, /* @__PURE__ */ e.createElement(\"path\", { d: \"M224,128a96,96,0,1,1-96-96A96,96,0,0,1,224,128Z\", opacity: \"0.2\" }), /* @__PURE__ */ e.createElement(\"path\", { d: \"M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm0,192a88,88,0,1,1,88-88A88.1,88.1,0,0,1,128,216Zm-8-80V80a8,8,0,0,1,16,0v56a8,8,0,0,1-16,0Zm20,36a12,12,0,1,1-12-12A12,12,0,0,1,140,172Z\" }))\n ],\n [\n \"fill\",\n /* @__PURE__ */ e.createElement(e.Fragment, null, /* @__PURE__ */ e.createElement(\"path\", { d: \"M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm-8,56a8,8,0,0,1,16,0v56a8,8,0,0,1-16,0Zm8,104a12,12,0,1,1,12-12A12,12,0,0,1,128,184Z\" }))\n ],\n [\n \"light\",\n /* @__PURE__ */ e.createElement(e.Fragment, null, /* @__PURE__ */ e.createElement(\"path\", { d: \"M128,26A102,102,0,1,0,230,128,102.12,102.12,0,0,0,128,26Zm0,192a90,90,0,1,1,90-90A90.1,90.1,0,0,1,128,218Zm-6-82V80a6,6,0,0,1,12,0v56a6,6,0,0,1-12,0Zm16,36a10,10,0,1,1-10-10A10,10,0,0,1,138,172Z\" }))\n ],\n [\n \"regular\",\n /* @__PURE__ */ e.createElement(e.Fragment, null, /* @__PURE__ */ e.createElement(\"path\", { d: \"M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm0,192a88,88,0,1,1,88-88A88.1,88.1,0,0,1,128,216Zm-8-80V80a8,8,0,0,1,16,0v56a8,8,0,0,1-16,0Zm20,36a12,12,0,1,1-12-12A12,12,0,0,1,140,172Z\" }))\n ],\n [\n \"thin\",\n /* @__PURE__ */ e.createElement(e.Fragment, null, /* @__PURE__ */ e.createElement(\"path\", { d: \"M128,28A100,100,0,1,0,228,128,100.11,100.11,0,0,0,128,28Zm0,192a92,92,0,1,1,92-92A92.1,92.1,0,0,1,128,220Zm-4-84V80a4,4,0,0,1,8,0v56a4,4,0,0,1-8,0Zm12,36a8,8,0,1,1-8-8A8,8,0,0,1,136,172Z\" }))\n ]\n]);\nexport {\n a as default\n};\n", "import * as e from \"react\";\nconst a = /* @__PURE__ */ new Map([\n [\n \"bold\",\n /* @__PURE__ */ e.createElement(e.Fragment, null, /* @__PURE__ */ e.createElement(\"path\", { d: \"M168.49,104.49,145,128l23.52,23.51a12,12,0,0,1-17,17L128,145l-23.51,23.52a12,12,0,0,1-17-17L111,128,87.51,104.49a12,12,0,0,1,17-17L128,111l23.51-23.52a12,12,0,0,1,17,17ZM236,128A108,108,0,1,1,128,20,108.12,108.12,0,0,1,236,128Zm-24,0a84,84,0,1,0-84,84A84.09,84.09,0,0,0,212,128Z\" }))\n ],\n [\n \"duotone\",\n /* @__PURE__ */ e.createElement(e.Fragment, null, /* @__PURE__ */ e.createElement(\"path\", { d: \"M224,128a96,96,0,1,1-96-96A96,96,0,0,1,224,128Z\", opacity: \"0.2\" }), /* @__PURE__ */ e.createElement(\"path\", { d: \"M165.66,101.66,139.31,128l26.35,26.34a8,8,0,0,1-11.32,11.32L128,139.31l-26.34,26.35a8,8,0,0,1-11.32-11.32L116.69,128,90.34,101.66a8,8,0,0,1,11.32-11.32L128,116.69l26.34-26.35a8,8,0,0,1,11.32,11.32ZM232,128A104,104,0,1,1,128,24,104.11,104.11,0,0,1,232,128Zm-16,0a88,88,0,1,0-88,88A88.1,88.1,0,0,0,216,128Z\" }))\n ],\n [\n \"fill\",\n /* @__PURE__ */ e.createElement(e.Fragment, null, /* @__PURE__ */ e.createElement(\"path\", { d: \"M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm37.66,130.34a8,8,0,0,1-11.32,11.32L128,139.31l-26.34,26.35a8,8,0,0,1-11.32-11.32L116.69,128,90.34,101.66a8,8,0,0,1,11.32-11.32L128,116.69l26.34-26.35a8,8,0,0,1,11.32,11.32L139.31,128Z\" }))\n ],\n [\n \"light\",\n /* @__PURE__ */ e.createElement(e.Fragment, null, /* @__PURE__ */ e.createElement(\"path\", { d: \"M164.24,100.24,136.48,128l27.76,27.76a6,6,0,1,1-8.48,8.48L128,136.48l-27.76,27.76a6,6,0,0,1-8.48-8.48L119.52,128,91.76,100.24a6,6,0,0,1,8.48-8.48L128,119.52l27.76-27.76a6,6,0,0,1,8.48,8.48ZM230,128A102,102,0,1,1,128,26,102.12,102.12,0,0,1,230,128Zm-12,0a90,90,0,1,0-90,90A90.1,90.1,0,0,0,218,128Z\" }))\n ],\n [\n \"regular\",\n /* @__PURE__ */ e.createElement(e.Fragment, null, /* @__PURE__ */ e.createElement(\"path\", { d: \"M165.66,101.66,139.31,128l26.35,26.34a8,8,0,0,1-11.32,11.32L128,139.31l-26.34,26.35a8,8,0,0,1-11.32-11.32L116.69,128,90.34,101.66a8,8,0,0,1,11.32-11.32L128,116.69l26.34-26.35a8,8,0,0,1,11.32,11.32ZM232,128A104,104,0,1,1,128,24,104.11,104.11,0,0,1,232,128Zm-16,0a88,88,0,1,0-88,88A88.1,88.1,0,0,0,216,128Z\" }))\n ],\n [\n \"thin\",\n /* @__PURE__ */ e.createElement(e.Fragment, null, /* @__PURE__ */ e.createElement(\"path\", { d: \"M162.83,98.83,133.66,128l29.17,29.17a4,4,0,0,1-5.66,5.66L128,133.66,98.83,162.83a4,4,0,0,1-5.66-5.66L122.34,128,93.17,98.83a4,4,0,0,1,5.66-5.66L128,122.34l29.17-29.17a4,4,0,1,1,5.66,5.66ZM228,128A100,100,0,1,1,128,28,100.11,100.11,0,0,1,228,128Zm-8,0a92,92,0,1,0-92,92A92.1,92.1,0,0,0,220,128Z\" }))\n ]\n]);\nexport {\n a as default\n};\n", "import * as e from \"react\";\nimport { IconContext as h } from \"./context.es.js\";\nconst p = e.forwardRef(\n (s, a) => {\n const {\n alt: n,\n color: r,\n size: t,\n weight: o,\n mirrored: c,\n children: i,\n weights: m,\n ...x\n } = s, {\n color: d = \"currentColor\",\n size: l,\n weight: f = \"regular\",\n mirrored: g = !1,\n ...w\n } = e.useContext(h);\n return /* @__PURE__ */ e.createElement(\n \"svg\",\n {\n ref: a,\n xmlns: \"http://www.w3.org/2000/svg\",\n width: t != null ? t : l,\n height: t != null ? t : l,\n fill: r != null ? r : d,\n viewBox: \"0 0 256 256\",\n transform: c || g ? \"scale(-1, 1)\" : void 0,\n ...w,\n ...x\n },\n !!n && /* @__PURE__ */ e.createElement(\"title\", null, n),\n i,\n m.get(o != null ? o : f)\n );\n }\n);\np.displayName = \"IconBase\";\nexport {\n p as default\n};\n", "import { createContext as r } from \"react\";\nconst o = r({\n color: \"currentColor\",\n size: \"1em\",\n weight: \"regular\",\n mirrored: !1\n});\nexport {\n o as IconContext\n};\n", "import * as e from \"react\";\nimport t from \"../lib/IconBase.es.js\";\nimport a from \"../defs/CheckCircle.es.js\";\nconst c = e.forwardRef((o, r) => /* @__PURE__ */ e.createElement(t, { ref: r, ...o, weights: a }));\nc.displayName = \"CheckCircleIcon\";\nconst s = c;\nexport {\n s as CheckCircle,\n c as CheckCircleIcon\n};\n", "import * as o from \"react\";\nimport n from \"../lib/IconBase.es.js\";\nimport a from \"../defs/Info.es.js\";\nconst e = o.forwardRef((r, t) => /* @__PURE__ */ o.createElement(n, { ref: t, ...r, weights: a }));\ne.displayName = \"InfoIcon\";\nconst c = e;\nexport {\n c as Info,\n e as InfoIcon\n};\n", "import * as r from \"react\";\nimport a from \"../lib/IconBase.es.js\";\nimport i from \"../defs/WarningCircle.es.js\";\nconst e = r.forwardRef((o, n) => /* @__PURE__ */ r.createElement(a, { ref: n, ...o, weights: i }));\ne.displayName = \"WarningCircleIcon\";\nconst m = e;\nexport {\n m as WarningCircle,\n e as WarningCircleIcon\n};\n", "import * as e from \"react\";\nimport t from \"../lib/IconBase.es.js\";\nimport a from \"../defs/XCircle.es.js\";\nconst o = e.forwardRef((r, c) => /* @__PURE__ */ e.createElement(t, { ref: c, ...r, weights: a }));\no.displayName = \"XCircleIcon\";\nconst s = o;\nexport {\n s as XCircle,\n o as XCircleIcon\n};\n", "\nimport React from \"react\";\n// jsx(type, props, key) differs from createElement(type, props, ...children):\n// the third arg in jsx is the key, but in createElement it's treated as children.\n// We must merge the key into props instead of passing it as a positional arg.\nexport function jsx(type, props, key) {\n return React.createElement(type, key !== undefined ? Object.assign({}, props, { key }) : props);\n}\nexport function jsxs(type, props, key) {\n return React.createElement(type, key !== undefined ? Object.assign({}, props, { key }) : props);\n}\nexport function jsxDEV(type, props, key) {\n return React.createElement(type, key !== undefined ? Object.assign({}, props, { key }) : props);\n}\nexport var Fragment = React.Fragment;\n", "import { remainder } from \"./math\";\n\nexport function typedIncludes<T extends readonly any[]>(arr: T, item: unknown): item is T[number] {\n return arr.includes(item);\n}\nimport.meta.vitest?.test(\"typedIncludes\", ({ expect }) => {\n const arr = [1, 2, 3] as const;\n expect(typedIncludes(arr, 1)).toBe(true);\n expect(typedIncludes(arr, 4)).toBe(false);\n expect(typedIncludes(arr, \"1\")).toBe(false);\n\n const strArr = [\"a\", \"b\", \"c\"] as const;\n expect(typedIncludes(strArr, \"a\")).toBe(true);\n expect(typedIncludes(strArr, \"d\")).toBe(false);\n});\n\nexport function enumerate<T extends readonly any[]>(arr: T): [number, T[number]][] {\n return arr.map((item, index) => [index, item]);\n}\nimport.meta.vitest?.test(\"enumerate\", ({ expect }) => {\n expect(enumerate([])).toEqual([]);\n expect(enumerate([1, 2, 3])).toEqual([[0, 1], [1, 2], [2, 3]]);\n expect(enumerate([\"a\", \"b\", \"c\"])).toEqual([[0, \"a\"], [1, \"b\"], [2, \"c\"]]);\n});\n\nexport function isShallowEqual(a: readonly any[], b: readonly any[]): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n}\nimport.meta.vitest?.test(\"isShallowEqual\", ({ expect }) => {\n expect(isShallowEqual([], [])).toBe(true);\n expect(isShallowEqual([1, 2, 3], [1, 2, 3])).toBe(true);\n expect(isShallowEqual([1, 2, 3], [1, 2, 4])).toBe(false);\n expect(isShallowEqual([1, 2, 3], [1, 2])).toBe(false);\n expect(isShallowEqual([1, 2], [1, 2, 3])).toBe(false);\n // Test with objects (reference equality)\n const obj1 = { a: 1 };\n const obj2 = { a: 1 };\n expect(isShallowEqual([obj1], [obj1])).toBe(true);\n expect(isShallowEqual([obj1], [obj2])).toBe(false);\n});\n\n/**\n * Ponyfill for ES2023's findLastIndex.\n */\nexport function findLastIndex<T>(arr: readonly T[], predicate: (item: T) => boolean): number {\n for (let i = arr.length - 1; i >= 0; i--) {\n if (predicate(arr[i])) return i;\n }\n return -1;\n}\nimport.meta.vitest?.test(\"findLastIndex\", ({ expect }) => {\n expect(findLastIndex([], () => true)).toBe(-1);\n expect(findLastIndex([1, 2, 3, 4, 5], x => x % 2 === 0)).toBe(3); // 4 is at index 3\n expect(findLastIndex([1, 2, 3, 4, 5], x => x > 10)).toBe(-1);\n expect(findLastIndex([1, 2, 3, 2, 1], x => x === 2)).toBe(3);\n expect(findLastIndex([1, 2, 3], x => x === 1)).toBe(0);\n});\n\nexport function groupBy<T extends any, K>(\n arr: Iterable<T>,\n key: (item: T) => K,\n): Map<K, T[]> {\n const result = new Map<K, T[]>;\n for (const item of arr) {\n const k = key(item);\n if (result.get(k) === undefined) result.set(k, []);\n result.get(k)!.push(item);\n }\n return result;\n}\nimport.meta.vitest?.test(\"groupBy\", ({ expect }) => {\n expect(groupBy([], (x) => x)).toEqual(new Map());\n\n const numbers = [1, 2, 3, 4, 5, 6];\n const grouped = groupBy(numbers, (n) => n % 2 === 0 ? \"even\" : \"odd\");\n expect(grouped.get(\"even\")).toEqual([2, 4, 6]);\n expect(grouped.get(\"odd\")).toEqual([1, 3, 5]);\n\n // Check the actual lengths of the words to ensure our test is correct\n const words = [\"apple\", \"banana\", \"cherry\", \"date\", \"elderberry\"];\n\n const byLength = groupBy(words, (w) => w.length);\n // Adjust expectations based on actual word lengths\n expect(byLength.get(5)).toEqual([\"apple\"]);\n expect(byLength.get(6)).toEqual([\"banana\", \"cherry\"]);\n expect(byLength.get(4)).toEqual([\"date\"]);\n expect(byLength.get(10)).toEqual([\"elderberry\"]);\n});\n\nexport function range(endExclusive: number): number[];\nexport function range(startInclusive: number, endExclusive: number): number[];\nexport function range(startInclusive: number, endExclusive: number, step: number): number[];\nexport function range(startInclusive: number, endExclusive?: number, step?: number): number[] {\n if (endExclusive === undefined) {\n endExclusive = startInclusive;\n startInclusive = 0;\n }\n if (step === undefined) step = 1;\n\n const result = [];\n for (let i = startInclusive; step > 0 ? (i < endExclusive) : (i > endExclusive); i += step) {\n result.push(i);\n }\n return result;\n}\nimport.meta.vitest?.test(\"range\", ({ expect }) => {\n expect(range(5)).toEqual([0, 1, 2, 3, 4]);\n expect(range(2, 5)).toEqual([2, 3, 4]);\n expect(range(1, 10, 2)).toEqual([1, 3, 5, 7, 9]);\n expect(range(5, 0, -1)).toEqual([5, 4, 3, 2, 1]);\n expect(range(0, 0)).toEqual([]);\n expect(range(0, 10, 3)).toEqual([0, 3, 6, 9]);\n});\n\n\nexport function rotateLeft(arr: readonly any[], n: number): any[] {\n if (arr.length === 0) return [];\n const index = remainder(n, arr.length);\n return [...arr.slice(index), ...arr.slice(0, index)];\n}\nimport.meta.vitest?.test(\"rotateLeft\", ({ expect }) => {\n expect(rotateLeft([], 1)).toEqual([]);\n expect(rotateLeft([1, 2, 3, 4, 5], 0)).toEqual([1, 2, 3, 4, 5]);\n expect(rotateLeft([1, 2, 3, 4, 5], 1)).toEqual([2, 3, 4, 5, 1]);\n expect(rotateLeft([1, 2, 3, 4, 5], 3)).toEqual([4, 5, 1, 2, 3]);\n expect(rotateLeft([1, 2, 3, 4, 5], 5)).toEqual([1, 2, 3, 4, 5]);\n expect(rotateLeft([1, 2, 3, 4, 5], 6)).toEqual([2, 3, 4, 5, 1]);\n});\n\nexport function rotateRight(arr: readonly any[], n: number): any[] {\n return rotateLeft(arr, -n);\n}\nimport.meta.vitest?.test(\"rotateRight\", ({ expect }) => {\n expect(rotateRight([], 1)).toEqual([]);\n expect(rotateRight([1, 2, 3, 4, 5], 0)).toEqual([1, 2, 3, 4, 5]);\n expect(rotateRight([1, 2, 3, 4, 5], 1)).toEqual([5, 1, 2, 3, 4]);\n expect(rotateRight([1, 2, 3, 4, 5], 3)).toEqual([3, 4, 5, 1, 2]);\n expect(rotateRight([1, 2, 3, 4, 5], 5)).toEqual([1, 2, 3, 4, 5]);\n expect(rotateRight([1, 2, 3, 4, 5], 6)).toEqual([5, 1, 2, 3, 4]);\n});\n\n\nexport function shuffle<T>(arr: readonly T[]): T[] {\n const result = [...arr];\n for (let i = result.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * (i + 1));\n [result[i], result[j]] = [result[j], result[i]];\n }\n return result;\n}\nimport.meta.vitest?.test(\"shuffle\", ({ expect }) => {\n // Test empty array\n expect(shuffle([])).toEqual([]);\n\n // Test single element array\n expect(shuffle([1])).toEqual([1]);\n\n // Test that shuffle returns a new array\n const original = [1, 2, 3, 4, 5];\n const shuffled = shuffle(original);\n expect(shuffled).not.toBe(original);\n\n // Test that all elements are preserved\n expect(shuffled.sort((a, b) => a - b)).toEqual(original);\n\n // Test with a larger array to ensure randomness\n // This is a probabilistic test, but it's very unlikely to fail\n const large = Array.from({ length: 100 }, (_, i) => i);\n const shuffledLarge = shuffle(large);\n expect(shuffledLarge).not.toEqual(large);\n expect(shuffledLarge.sort((a, b) => a - b)).toEqual(large);\n});\n\n\nexport function outerProduct<T, U>(arr1: readonly T[], arr2: readonly U[]): [T, U][] {\n return arr1.flatMap((item1) => arr2.map((item2) => [item1, item2] as [T, U]));\n}\nimport.meta.vitest?.test(\"outerProduct\", ({ expect }) => {\n expect(outerProduct([], [])).toEqual([]);\n expect(outerProduct([1], [])).toEqual([]);\n expect(outerProduct([], [1])).toEqual([]);\n expect(outerProduct([1], [2])).toEqual([[1, 2]]);\n expect(outerProduct([1, 2], [3, 4])).toEqual([[1, 3], [1, 4], [2, 3], [2, 4]]);\n expect(outerProduct([\"a\", \"b\"], [1, 2])).toEqual([[\"a\", 1], [\"a\", 2], [\"b\", 1], [\"b\", 2]]);\n});\n\nexport function unique<T>(arr: readonly T[]): T[] {\n return [...new Set(arr)];\n}\nimport.meta.vitest?.test(\"unique\", ({ expect }) => {\n expect(unique([])).toEqual([]);\n expect(unique([1, 2, 3])).toEqual([1, 2, 3]);\n expect(unique([1, 2, 2, 3, 1, 3])).toEqual([1, 2, 3]);\n // Test with objects (reference equality)\n const obj = { a: 1 };\n expect(unique([obj, obj])).toEqual([obj]);\n // Test with different types\n expect(unique([1, \"1\", true, 1, \"1\", true])).toEqual([1, \"1\", true]);\n});\n\n\nexport function getChunks<T>(arr: readonly T[], size: number): T[][] {\n const result: T[][] = [];\n if (size <= 0) return result;\n for (let i = 0; i < arr.length; i += size) {\n result.push(arr.slice(i, i + size));\n }\n return result;\n}\nimport.meta.vitest?.test(\"getChunks\", ({ expect }) => {\n expect(getChunks([], 2)).toEqual([]);\n expect(getChunks([1], 2)).toEqual([[1]]);\n expect(getChunks([1, 2], 2)).toEqual([[1, 2]]);\n expect(getChunks([1, 2, 3], 2)).toEqual([[1, 2], [3]]);\n expect(getChunks([1, 2, 3, 4, 5], 2)).toEqual([[1, 2], [3, 4], [5]]);\n expect(getChunks([1, 2, 3, 4], 3)).toEqual([[1, 2, 3], [4]]);\n expect(getChunks([1, 2, 3], 0)).toEqual([]);\n expect(getChunks([1, 2, 3], -1)).toEqual([]);\n});\n\nexport function isStringArray(arr: unknown): arr is string[] {\n return Array.isArray(arr) && arr.every((item) => typeof item === \"string\");\n}\nexport function isNumberArray(arr: unknown): arr is number[] {\n return Array.isArray(arr) && arr.every((item) => typeof item === \"number\");\n}\nexport function isBooleanArray(arr: unknown): arr is boolean[] {\n return Array.isArray(arr) && arr.every((item) => typeof item === \"boolean\");\n}\nexport function isObjectArray(arr: unknown): arr is object[] {\n return Array.isArray(arr) && arr.every((item) => typeof item === \"object\" && item !== null);\n}\nimport.meta.vitest?.test(\"is<Type>Array\", ({ expect }) => {\n expect(isStringArray([])).toBe(true);\n expect(isNumberArray([1, 2, 3])).toBe(true);\n expect(isBooleanArray([true, false, true])).toBe(true);\n expect(isObjectArray([{ a: 1 }, { b: 2 }, { c: 3 }])).toBe(true);\n expect(isStringArray([1, 2, 3])).toBe(false);\n expect(isNumberArray([\"a\", \"b\", \"c\"])).toBe(false);\n expect(isBooleanArray([1, 2, 3])).toBe(false);\n expect(isObjectArray([1, 2, 3])).toBe(false);\n expect(isObjectArray([{ a: 1 }, null, { b: 2 }])).toBe(false);\n expect(isObjectArray([{ a: 1 }, undefined, { b: 2 }])).toBe(false);\n});\n", "import { findLastIndex, unique } from \"./arrays\";\nimport { StackAssertionError } from \"./errors\";\nimport { filterUndefined } from \"./objects\";\n\nexport type Join<T extends string[], Separator extends string> =\n T extends [] ? \"\"\n : T extends [infer U extends string, ...infer Rest extends string[]]\n ? `${U}${Rest extends [any, ...any[]] ? `${Separator}${Join<Rest, Separator>}` : \"\"}`\n : \"<error-joining-strings>\";\n\nexport function typedJoin<T extends string[], Separator extends string>(strings: T, separator: Separator): Join<T, Separator> {\n return strings.join(separator) as Join<T, Separator>;\n}\n\nexport function typedToLowercase<S extends string>(s: S): Lowercase<S> {\n if (typeof s !== \"string\") throw new StackAssertionError(\"Expected a string for typedToLowercase\", { s });\n return s.toLowerCase() as Lowercase<S>;\n}\nimport.meta.vitest?.test(\"typedToLowercase\", ({ expect }) => {\n expect(typedToLowercase(\"\")).toBe(\"\");\n expect(typedToLowercase(\"HELLO\")).toBe(\"hello\");\n expect(typedToLowercase(\"Hello World\")).toBe(\"hello world\");\n expect(typedToLowercase(\"hello\")).toBe(\"hello\");\n expect(typedToLowercase(\"123\")).toBe(\"123\");\n expect(typedToLowercase(\"MIXED123case\")).toBe(\"mixed123case\");\n expect(typedToLowercase(\"Special@Chars!\")).toBe(\"special@chars!\");\n expect(() => typedToLowercase(123 as any)).toThrow(\"Expected a string for typedToLowercase\");\n});\n\nexport function typedToUppercase<S extends string>(s: S): Uppercase<S> {\n if (typeof s !== \"string\") throw new StackAssertionError(\"Expected a string for typedToUppercase\", { s });\n return s.toUpperCase() as Uppercase<S>;\n}\nimport.meta.vitest?.test(\"typedToUppercase\", ({ expect }) => {\n expect(typedToUppercase(\"\")).toBe(\"\");\n expect(typedToUppercase(\"hello\")).toBe(\"HELLO\");\n expect(typedToUppercase(\"Hello World\")).toBe(\"HELLO WORLD\");\n expect(typedToUppercase(\"HELLO\")).toBe(\"HELLO\");\n expect(typedToUppercase(\"123\")).toBe(\"123\");\n expect(typedToUppercase(\"mixed123Case\")).toBe(\"MIXED123CASE\");\n expect(typedToUppercase(\"special@chars!\")).toBe(\"SPECIAL@CHARS!\");\n expect(() => typedToUppercase(123 as any)).toThrow(\"Expected a string for typedToUppercase\");\n});\n\nexport function typedCapitalize<S extends string>(s: S): Capitalize<S> {\n return s.charAt(0).toUpperCase() + s.slice(1) as Capitalize<S>;\n}\nimport.meta.vitest?.test(\"typedCapitalize\", ({ expect }) => {\n expect(typedCapitalize(\"\")).toBe(\"\");\n expect(typedCapitalize(\"hello\")).toBe(\"Hello\");\n expect(typedCapitalize(\"hello world\")).toBe(\"Hello world\");\n expect(typedCapitalize(\"HELLO\")).toBe(\"HELLO\");\n expect(typedCapitalize(\"123test\")).toBe(\"123test\");\n expect(typedCapitalize(\"already Capitalized\")).toBe(\"Already Capitalized\");\n expect(typedCapitalize(\"h\")).toBe(\"H\");\n});\n\n/**\n * Compares two strings in a way that is not dependent on the current locale.\n */\nexport function stringCompare(a: string, b: string): number {\n if (typeof a !== \"string\" || typeof b !== \"string\") throw new StackAssertionError(`Expected two strings for stringCompare, found ${typeof a} and ${typeof b}`, { a, b });\n const cmp = (a: string, b: string) => a < b ? -1 : a > b ? 1 : 0;\n return cmp(a.toUpperCase(), b.toUpperCase()) || cmp(b, a);\n}\nimport.meta.vitest?.test(\"stringCompare\", ({ expect }) => {\n // Equal strings\n expect(stringCompare(\"a\", \"a\")).toBe(0);\n expect(stringCompare(\"\", \"\")).toBe(0);\n\n // Case comparison - note that this function is NOT case-insensitive\n // It compares uppercase versions first, then original strings\n expect(stringCompare(\"a\", \"A\")).toBe(-1); // lowercase comes after uppercase\n expect(stringCompare(\"A\", \"a\")).toBe(1); // uppercase comes before lowercase\n expect(stringCompare(\"abc\", \"ABC\")).toBe(-1);\n expect(stringCompare(\"ABC\", \"abc\")).toBe(1);\n\n // Different strings\n expect(stringCompare(\"a\", \"b\")).toBe(-1);\n expect(stringCompare(\"b\", \"a\")).toBe(1);\n\n // Strings with different lengths\n expect(stringCompare(\"abc\", \"abcd\")).toBe(-1);\n expect(stringCompare(\"abcd\", \"abc\")).toBe(1);\n\n // Strings with numbers\n expect(stringCompare(\"a1\", \"a2\")).toBe(-1);\n expect(stringCompare(\"a10\", \"a2\")).toBe(-1);\n\n // Strings with special characters\n expect(stringCompare(\"a\", \"a!\")).toBe(-1);\n expect(stringCompare(\"a!\", \"a\")).toBe(1);\n});\n\n/**\n * Returns all whitespace character at the start of the string.\n *\n * Uses the same definition for whitespace as `String.prototype.trim()`.\n */\nexport function getWhitespacePrefix(s: string): string {\n return s.substring(0, s.length - s.trimStart().length);\n}\nimport.meta.vitest?.test(\"getWhitespacePrefix\", ({ expect }) => {\n expect(getWhitespacePrefix(\"\")).toBe(\"\");\n expect(getWhitespacePrefix(\"hello\")).toBe(\"\");\n expect(getWhitespacePrefix(\" hello\")).toBe(\" \");\n expect(getWhitespacePrefix(\" hello\")).toBe(\" \");\n expect(getWhitespacePrefix(\"\\thello\")).toBe(\"\\t\");\n expect(getWhitespacePrefix(\"\\n hello\")).toBe(\"\\n \");\n expect(getWhitespacePrefix(\" \")).toBe(\" \");\n expect(getWhitespacePrefix(\" \\t\\n\\r\")).toBe(\" \\t\\n\\r\");\n});\n\n/**\n * Returns all whitespace character at the end of the string.\n *\n * Uses the same definition for whitespace as `String.prototype.trim()`.\n */\nexport function getWhitespaceSuffix(s: string): string {\n return s.substring(s.trimEnd().length);\n}\nimport.meta.vitest?.test(\"getWhitespaceSuffix\", ({ expect }) => {\n expect(getWhitespaceSuffix(\"\")).toBe(\"\");\n expect(getWhitespaceSuffix(\"hello\")).toBe(\"\");\n expect(getWhitespaceSuffix(\"hello \")).toBe(\" \");\n expect(getWhitespaceSuffix(\"hello \")).toBe(\" \");\n expect(getWhitespaceSuffix(\"hello\\t\")).toBe(\"\\t\");\n expect(getWhitespaceSuffix(\"hello \\n\")).toBe(\" \\n\");\n expect(getWhitespaceSuffix(\" \")).toBe(\" \");\n expect(getWhitespaceSuffix(\" \\t\\n\\r\")).toBe(\" \\t\\n\\r\");\n});\n\n/**\n * Returns a string with all empty or whitespace-only lines at the start removed.\n *\n * Uses the same definition for whitespace as `String.prototype.trim()`.\n */\nexport function trimEmptyLinesStart(s: string): string {\n const lines = s.split(\"\\n\");\n const firstNonEmptyLineIndex = lines.findIndex((line) => line.trim() !== \"\");\n // If all lines are empty or whitespace-only, return an empty string\n if (firstNonEmptyLineIndex === -1) return \"\";\n return lines.slice(firstNonEmptyLineIndex).join(\"\\n\");\n}\nimport.meta.vitest?.test(\"trimEmptyLinesStart\", ({ expect }) => {\n expect(trimEmptyLinesStart(\"\")).toBe(\"\");\n expect(trimEmptyLinesStart(\"hello\")).toBe(\"hello\");\n expect(trimEmptyLinesStart(\"\\nhello\")).toBe(\"hello\");\n expect(trimEmptyLinesStart(\"\\n\\nhello\")).toBe(\"hello\");\n expect(trimEmptyLinesStart(\" \\n\\t\\nhello\")).toBe(\"hello\");\n expect(trimEmptyLinesStart(\"\\n\\nhello\\nworld\")).toBe(\"hello\\nworld\");\n expect(trimEmptyLinesStart(\"hello\\n\\nworld\")).toBe(\"hello\\n\\nworld\");\n expect(trimEmptyLinesStart(\"hello\\nworld\\n\")).toBe(\"hello\\nworld\\n\");\n expect(trimEmptyLinesStart(\"\\n \\n\\nhello\\n \\nworld\")).toBe(\"hello\\n \\nworld\");\n // Edge case: all lines are empty\n expect(trimEmptyLinesStart(\"\\n\\n \\n\\t\")).toBe(\"\");\n});\n\n/**\n * Returns a string with all empty or whitespace-only lines at the end removed.\n *\n * Uses the same definition for whitespace as `String.prototype.trim()`.\n */\nexport function trimEmptyLinesEnd(s: string): string {\n const lines = s.split(\"\\n\");\n const lastNonEmptyLineIndex = findLastIndex(lines, (line) => line.trim() !== \"\");\n return lines.slice(0, lastNonEmptyLineIndex + 1).join(\"\\n\");\n}\nimport.meta.vitest?.test(\"trimEmptyLinesEnd\", ({ expect }) => {\n expect(trimEmptyLinesEnd(\"\")).toBe(\"\");\n expect(trimEmptyLinesEnd(\"hello\")).toBe(\"hello\");\n expect(trimEmptyLinesEnd(\"hello\\n\")).toBe(\"hello\");\n expect(trimEmptyLinesEnd(\"hello\\n\\n\")).toBe(\"hello\");\n expect(trimEmptyLinesEnd(\"hello\\n \\n\\t\")).toBe(\"hello\");\n expect(trimEmptyLinesEnd(\"hello\\nworld\\n\\n\")).toBe(\"hello\\nworld\");\n expect(trimEmptyLinesEnd(\"hello\\n\\nworld\")).toBe(\"hello\\n\\nworld\");\n expect(trimEmptyLinesEnd(\"\\nhello\\nworld\")).toBe(\"\\nhello\\nworld\");\n expect(trimEmptyLinesEnd(\"hello\\n \\nworld\\n\\n \")).toBe(\"hello\\n \\nworld\");\n // Edge case: all lines are empty\n expect(trimEmptyLinesEnd(\"\\n\\n \\n\\t\")).toBe(\"\");\n});\n\n/**\n * Returns a string with all empty or whitespace-only lines trimmed at the start and end.\n *\n * Uses the same definition for whitespace as `String.prototype.trim()`.\n */\nexport function trimLines(s: string): string {\n return trimEmptyLinesEnd(trimEmptyLinesStart(s));\n}\nimport.meta.vitest?.test(\"trimLines\", ({ expect }) => {\n expect(trimLines(\"\")).toBe(\"\");\n expect(trimLines(\" \")).toBe(\"\");\n expect(trimLines(\" \\n \")).toBe(\"\");\n expect(trimLines(\" abc \")).toBe(\" abc \");\n expect(trimLines(\"\\n \\nLine1\\nLine2\\n \\n\")).toBe(\"Line1\\nLine2\");\n expect(trimLines(\"Line1\\n \\nLine2\")).toBe(\"Line1\\n \\nLine2\");\n expect(trimLines(\" \\n \\n\\t\")).toBe(\"\");\n expect(trimLines(\" Hello World\")).toBe(\" Hello World\");\n expect(trimLines(\"\\n\")).toBe(\"\");\n expect(trimLines(\"\\t \\n\\t\\tLine1 \\n \\nLine2\\t\\t\\n\\t \")).toBe(\"\\t\\tLine1 \\n \\nLine2\\t\\t\");\n});\n\n\n/**\n * A template literal tag that returns the same string as the template literal without a tag.\n *\n * Useful for implementing your own template literal tags.\n */\nexport function templateIdentity(strings: TemplateStringsArray | readonly string[], ...values: string[]): string {\n if (values.length !== strings.length - 1) throw new StackAssertionError(\"Invalid number of values; must be one less than strings\", { strings, values });\n\n return strings.reduce((result, str, i) => result + str + (values[i] ?? ''), '');\n}\nimport.meta.vitest?.test(\"templateIdentity\", ({ expect }) => {\n expect(templateIdentity`Hello World`).toBe(\"Hello World\");\n expect(templateIdentity`${\"Hello\"}`).toBe(\"Hello\");\n const greeting = \"Hello\";\n const subject = \"World\";\n expect(templateIdentity`${greeting}, ${subject}!`).toBe(\"Hello, World!\");\n expect(templateIdentity`${\"A\"}${\"B\"}${\"C\"}`).toBe(\"ABC\");\n expect(templateIdentity`Start${\"\"}Middle${\"\"}End`).toBe(\"StartMiddleEnd\");\n expect(templateIdentity``).toBe(\"\");\n expect(templateIdentity`Line1\nLine2`).toBe(\"Line1\\nLine2\");\n expect(templateIdentity([\"a \", \" scientific \", \"gun\"], \"certain\", \"rail\")).toBe(\"a certain scientific railgun\");\n expect(templateIdentity([\"only one part\"])).toBe(\"only one part\");\n expect(() => templateIdentity([\"a \", \"b\", \"c\"], \"only one\")).toThrow(\"Invalid number of values\");\n expect(() => templateIdentity([\"a\", \"b\"], \"x\", \"y\")).toThrow(\"Invalid number of values\");\n});\n\n\nexport function deindent(code: string): string;\nexport function deindent(strings: TemplateStringsArray | readonly string[], ...values: any[]): string;\nexport function deindent(strings: string | readonly string[], ...values: any[]): string {\n if (typeof strings === \"string\") return deindent([strings]);\n return templateIdentity(...deindentTemplate(strings, ...values));\n}\n\nexport function deindentTemplate(strings: TemplateStringsArray | readonly string[], ...values: any[]): [string[], ...string[]] {\n if (values.length !== strings.length - 1) throw new StackAssertionError(\"Invalid number of values; must be one less than strings\", { strings, values });\n\n const trimmedStrings = [...strings];\n trimmedStrings[0] = trimEmptyLinesStart(trimmedStrings[0] + \"+\").slice(0, -1);\n trimmedStrings[trimmedStrings.length - 1] = trimEmptyLinesEnd(\"+\" + trimmedStrings[trimmedStrings.length - 1]).slice(1);\n\n const indentation = trimmedStrings\n .join(\"${SOME_VALUE}\")\n .split(\"\\n\")\n .filter((line) => line.trim() !== \"\")\n .map((line) => getWhitespacePrefix(line).length)\n .reduce((min, current) => Math.min(min, current), Infinity);\n\n const deindentedStrings = trimmedStrings\n .map((string, stringIndex) => {\n return string\n .split(\"\\n\")\n .map((line, lineIndex) => stringIndex !== 0 && lineIndex === 0 ? line : line.substring(indentation))\n .join(\"\\n\");\n });\n\n const indentedValues = values.map((value, i) => {\n const firstLineIndentation = getWhitespacePrefix(deindentedStrings[i].split(\"\\n\").at(-1)!);\n return `${value}`.replaceAll(\"\\n\", `\\n${firstLineIndentation}`);\n });\n\n return [deindentedStrings, ...indentedValues];\n}\nimport.meta.vitest?.test(\"deindent\", ({ expect }) => {\n // Test with string input\n expect(deindent(\" hello\")).toBe(\"hello\");\n expect(deindent(\" hello\\n world\")).toBe(\"hello\\nworld\");\n expect(deindent(\" hello\\n world\")).toBe(\"hello\\n world\");\n expect(deindent(\"\\n hello\\n world\\n\")).toBe(\"hello\\nworld\");\n\n // Test with empty input\n expect(deindent(\"\")).toBe(\"\");\n\n // Test with template literal\n expect(deindent`\n hello\n world\n `).toBe(\"hello\\nworld\");\n\n expect(deindent`\n hello\n world\n `).toBe(\"hello\\n world\");\n\n // Test with values\n const value = \"test\";\n expect(deindent`\n hello ${value}\n world\n `).toBe(`hello ${value}\\nworld`);\n\n // Test with multiline values\n expect(deindent`\n hello\n to ${\"line1\\n line2\"}\n world\n `).toBe(`hello\\n to line1\\n line2\\nworld`);\n\n // Leading whitespace values\n expect(deindent`\n ${\" \"}A\n ${\" \"}B\n ${\" \"}C\n `).toBe(` A\\n B\\n C`);\n\n // Trailing whitespaces (note: there are two whitespaces each after A and after C)\n expect(deindent`\n A \n B ${\" \"}\n C \n `).toBe(`A \\nB \\nC `);\n\n // Test with mixed indentation\n expect(deindent`\n hello\n world\n !\n `).toBe(\"hello\\n world\\n !\");\n\n // Test error cases\n expect(() => deindent([\"a\", \"b\", \"c\"], \"too\", \"many\", \"values\")).toThrow(\"Invalid number of values\");\n});\n\nexport function extractScopes(scope: string, removeDuplicates=true): string[] {\n // TODO what is this for? can we move this into the OAuth code in the backend?\n const trimmedString = scope.trim();\n const scopesArray = trimmedString.split(/\\s+/);\n const filtered = scopesArray.filter(scope => scope.length > 0);\n return removeDuplicates ? [...new Set(filtered)] : filtered;\n}\nimport.meta.vitest?.test(\"extractScopes\", ({ expect }) => {\n // Test with empty string\n expect(extractScopes(\"\")).toEqual([]);\n\n // Test with single scope\n expect(extractScopes(\"read\")).toEqual([\"read\"]);\n\n // Test with multiple scopes\n expect(extractScopes(\"read write\")).toEqual([\"read\", \"write\"]);\n\n // Test with extra whitespace\n expect(extractScopes(\" read write \")).toEqual([\"read\", \"write\"]);\n\n // Test with newlines and tabs\n expect(extractScopes(\"read\\nwrite\\tdelete\")).toEqual([\"read\", \"write\", \"delete\"]);\n\n // Test with duplicates (default behavior)\n expect(extractScopes(\"read write read\")).toEqual([\"read\", \"write\"]);\n\n // Test with duplicates (explicitly set to remove)\n expect(extractScopes(\"read write read\", true)).toEqual([\"read\", \"write\"]);\n\n // Test with duplicates (explicitly set to keep)\n expect(extractScopes(\"read write read\", false)).toEqual([\"read\", \"write\", \"read\"]);\n});\n\nexport function mergeScopeStrings(...scopes: string[]): string {\n // TODO what is this for? can we move this into the OAuth code in the backend?\n const allScope = scopes.map((s) => extractScopes(s)).flat().join(\" \");\n return extractScopes(allScope).join(\" \");\n}\nimport.meta.vitest?.test(\"mergeScopeStrings\", ({ expect }) => {\n // Test with empty input\n expect(mergeScopeStrings()).toBe(\"\");\n\n // Test with single scope string\n expect(mergeScopeStrings(\"read write\")).toBe(\"read write\");\n\n // Test with multiple scope strings\n expect(mergeScopeStrings(\"read\", \"write\")).toBe(\"read write\");\n\n // Test with overlapping scopes\n expect(mergeScopeStrings(\"read write\", \"write delete\")).toBe(\"read write delete\");\n\n // Test with extra whitespace\n expect(mergeScopeStrings(\" read write \", \" delete \")).toBe(\"read write delete\");\n\n // Test with duplicates across strings\n expect(mergeScopeStrings(\"read write\", \"write delete\", \"read\")).toBe(\"read write delete\");\n\n // Test with empty strings\n expect(mergeScopeStrings(\"read write\", \"\", \"delete\")).toBe(\"read write delete\");\n});\n\nexport function escapeTemplateLiteral(s: string): string {\n return s.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll(\"`\", \"\\\\`\").replaceAll(\"${\", \"\\\\${\");\n}\nimport.meta.vitest?.test(\"escapeTemplateLiteral\", ({ expect }) => {\n // Test with empty string\n expect(escapeTemplateLiteral(\"\")).toBe(\"\");\n\n // Test with normal string (no special characters)\n expect(escapeTemplateLiteral(\"hello world\")).toBe(\"hello world\");\n\n // Test with backtick\n const input1 = \"hello `world`\";\n const output1 = escapeTemplateLiteral(input1);\n // Verify backticks are escaped\n expect(output1).toBe(\"hello \\\\`world\\\\`\");\n\n // Test with backslash\n const input2 = \"hello \\\\world\";\n const output2 = escapeTemplateLiteral(input2);\n // Verify backslashes are escaped\n expect(output2).toBe(\"hello \\\\\\\\world\");\n\n // Test with dollar sign\n const input3 = \"hello $world\";\n const output3 = escapeTemplateLiteral(input3);\n // Verify dollar signs are escaped\n expect(output3).toBe(\"hello $world\");\n\n // Test with dollar sign in interpolation\n const input4 = \"hello ${$world\";\n const output4 = escapeTemplateLiteral(input4);\n // Verify dollar signs are escaped\n expect(output4).toBe(\"hello \\\\${$world\");\n\n // Test with multiple special characters\n const input5 = \"`hello` ${world\\\\\";\n const output5 = escapeTemplateLiteral(input5);\n // Verify all special characters are escaped\n expect(output5).toBe(\"\\\\`hello\\\\` \\\\${world\\\\\\\\\");\n\n // Test with already escaped characters\n const input6 = \"\\\\`hello\\\\`\";\n const output6 = escapeTemplateLiteral(input6);\n expect(output6).toBe(\"\\\\\\\\\\\\`hello\\\\\\\\\\\\`\");\n});\n\n/**\n * Some classes have different constructor names in different environments (eg. `Headers` is sometimes called `_Headers`,\n * so we create an object of overrides to handle these cases.\n */\nconst nicifiableClassNameOverrides = new Map(Object.entries({\n Headers,\n} as Record<string, unknown>).map(([k, v]) => [v, k]));\nexport type Nicifiable = {\n getNicifiableKeys?(): PropertyKey[],\n getNicifiedObjectExtraLines?(): string[],\n};\nexport type NicifyOptions = {\n maxDepth: number,\n currentIndent: string,\n lineIndent: string,\n multiline: boolean,\n refs: Map<unknown, string>,\n path: string,\n parent: null | {\n options: NicifyOptions,\n value: unknown,\n },\n keyInParent: PropertyKey | null,\n hideFields: PropertyKey[],\n overrides: (...args: Parameters<typeof nicify>) => string | null,\n};\nexport function nicify(\n value: unknown,\n options: Partial<NicifyOptions> = {},\n): string {\n const fullOptions: NicifyOptions = {\n maxDepth: 5,\n currentIndent: \"\",\n lineIndent: \" \",\n multiline: true,\n refs: new Map(),\n path: \"value\",\n parent: null,\n overrides: () => null,\n keyInParent: null,\n hideFields: [],\n ...filterUndefined(options),\n };\n const {\n maxDepth,\n currentIndent,\n lineIndent,\n multiline,\n refs,\n path,\n overrides,\n hideFields,\n } = fullOptions;\n const nl = `\\n${currentIndent}`;\n\n const overrideResult = overrides(value, options);\n if (overrideResult !== null) return overrideResult;\n\n if ([\"function\", \"object\", \"symbol\"].includes(typeof value) && value !== null) {\n if (refs.has(value)) {\n return `Ref<${refs.get(value)}>`;\n }\n refs.set(value, path);\n }\n\n const newOptions: NicifyOptions = {\n maxDepth: maxDepth - 1,\n currentIndent,\n lineIndent,\n multiline,\n refs,\n path: path + \"->[unknown property]\",\n overrides,\n parent: { value, options: fullOptions },\n keyInParent: null,\n hideFields: [],\n };\n const nestedNicify = (newValue: unknown, newPath: string, keyInParent: PropertyKey | null, options: Partial<NicifyOptions> = {}) => {\n return nicify(newValue, {\n ...newOptions,\n path: newPath,\n currentIndent: currentIndent + lineIndent,\n keyInParent,\n ...options,\n });\n };\n\n switch (typeof value) {\n case \"boolean\": case \"number\": {\n return JSON.stringify(value);\n }\n case \"string\": {\n const isDeindentable = (v: string) => deindent(v) === v && v.includes(\"\\n\");\n const wrapInDeindent = (v: string) => deindent`\n deindent\\`\n ${currentIndent + lineIndent}${escapeTemplateLiteral(v).replaceAll(\"\\n\", nl + lineIndent)}\n ${currentIndent}\\`\n `;\n if (isDeindentable(value)) {\n return wrapInDeindent(value);\n } else if (value.endsWith(\"\\n\") && isDeindentable(value.slice(0, -1))) {\n return wrapInDeindent(value.slice(0, -1)) + ' + \"\\\\n\"';\n } else {\n return JSON.stringify(value);\n }\n }\n case \"undefined\": {\n return \"undefined\";\n }\n case \"symbol\": {\n return value.toString();\n }\n case \"bigint\": {\n return `${value}n`;\n }\n case \"function\": {\n if (value.name) return `function ${value.name}(...) { ... }`;\n return `(...) => { ... }`;\n }\n case \"object\": {\n if (value === null) return \"null\";\n if (Array.isArray(value)) {\n const extraLines = getNicifiedObjectExtraLines(value);\n const resValueLength = value.length + extraLines.length;\n if (resValueLength === 0) return \"[]\"; // early return in case maxDepth <= 0\n if (maxDepth <= 0) return `[...]`;\n const resValues = value.map((v, i) => nestedNicify(v, `${path}[${i}]`, i));\n resValues.push(...extraLines);\n if (resValues.length !== resValueLength) throw new StackAssertionError(\"nicify of object: resValues.length !== resValueLength\", { value, resValues, resValueLength });\n const shouldIndent = resValues.length > 4 || resValues.some(x => (resValues.length > 1 && x.length > 4) || x.includes(\"\\n\"));\n if (shouldIndent) {\n return `[${nl}${resValues.map(x => `${lineIndent}${x},${nl}`).join(\"\")}]`;\n } else {\n return `[${resValues.join(\", \")}]`;\n }\n }\n if (value instanceof Date) {\n return `Date(${nestedNicify(value.toISOString(), `${path}.toISOString()`, null)})`;\n }\n if (value instanceof URL) {\n return `URL(${nestedNicify(value.toString(), `${path}.toString()`, null)})`;\n }\n if (ArrayBuffer.isView(value)) {\n return `${value.constructor.name}([${value.toString()}])`;\n }\n if (value instanceof ArrayBuffer) {\n return `ArrayBuffer [${new Uint8Array(value).toString()}]`;\n }\n if (value instanceof Error) {\n let stack = value.stack ?? \"\";\n const toString = value.toString();\n if (!stack.startsWith(toString)) stack = `${toString}\\n${stack}`; // some browsers don't include the error message in the stack, some do\n stack = stack.trimEnd();\n stack = stack.replace(/\\n\\s+/g, `\\n${lineIndent}${lineIndent}`);\n stack = stack.replace(\"\\n\", `\\n${lineIndent}Stack:\\n`);\n if (Object.keys(value).length > 0) {\n stack += `\\n${lineIndent}Extra properties: ${nestedNicify(Object.fromEntries(Object.entries(value)), path, null)}`;\n }\n if (value.cause) {\n stack += `\\n${lineIndent}Cause:\\n${lineIndent}${lineIndent}${nestedNicify(value.cause, path, null, { currentIndent: currentIndent + lineIndent + lineIndent })}`;\n }\n stack = stack.replaceAll(\"\\n\", `\\n${currentIndent}`);\n return stack;\n }\n\n const constructorName = [null, Object.prototype].includes(Object.getPrototypeOf(value)) ? null : (nicifiableClassNameOverrides.get(value.constructor) ?? value.constructor.name);\n const constructorString = constructorName ? `${constructorName} ` : \"\";\n\n const entries = getNicifiableEntries(value).filter(([k]) => !hideFields.includes(k));\n const extraLines = [\n ...getNicifiedObjectExtraLines(value),\n ...hideFields.length > 0 ? [`<some fields may have been hidden>`] : [],\n ];\n const resValueLength = entries.length + extraLines.length;\n if (resValueLength === 0) return `${constructorString}{}`;\n if (maxDepth <= 0) return `${constructorString}{ ... }`;\n const resValues = entries.map(([k, v], keyIndex) => {\n const keyNicified = nestedNicify(k, `Object.keys(${path})[${keyIndex}]`, null);\n const keyInObjectLiteral = typeof k === \"string\" ? nicifyPropertyString(k) : `[${keyNicified}]`;\n if (typeof v === \"function\" && v.name === k) {\n return `${keyInObjectLiteral}(...): { ... }`;\n } else {\n return `${keyInObjectLiteral}: ${nestedNicify(v, `${path}[${keyNicified}]`, k)}`;\n }\n });\n resValues.push(...extraLines);\n if (resValues.length !== resValueLength) throw new StackAssertionError(\"nicify of object: resValues.length !== resValueLength\", { value, resValues, resValueLength });\n const shouldIndent = resValues.length > 1 || resValues.some(x => x.includes(\"\\n\"));\n\n if (resValues.length === 0) return `${constructorString}{}`;\n if (shouldIndent) {\n return `${constructorString}{${nl}${resValues.map(x => `${lineIndent}${x},${nl}`).join(\"\")}}`;\n } else {\n return `${constructorString}{ ${resValues.join(\", \")} }`;\n }\n }\n default: {\n return `${typeof value}<${value}>`;\n }\n }\n}\n\nexport function replaceAll(input: string, searchValue: string, replaceValue: string): string {\n if (searchValue === \"\") throw new StackAssertionError(\"replaceAll: searchValue is empty\");\n return input.split(searchValue).join(replaceValue);\n}\nimport.meta.vitest?.test(\"replaceAll\", ({ expect }) => {\n expect(replaceAll(\"hello world\", \"o\", \"x\")).toBe(\"hellx wxrld\");\n expect(replaceAll(\"aaa\", \"a\", \"b\")).toBe(\"bbb\");\n expect(replaceAll(\"\", \"a\", \"b\")).toBe(\"\");\n expect(replaceAll(\"abc\", \"b\", \"\")).toBe(\"ac\");\n expect(replaceAll(\"test.test.test\", \".\", \"_\")).toBe(\"test_test_test\");\n expect(replaceAll(\"a.b*c\", \".\", \"x\")).toBe(\"axb*c\");\n expect(replaceAll(\"a*b*c\", \"*\", \"x\")).toBe(\"axbxc\");\n expect(replaceAll(\"hello hello\", \"hello\", \"hi\")).toBe(\"hi hi\");\n});\n\nfunction nicifyPropertyString(str: string) {\n return JSON.stringify(str);\n}\nimport.meta.vitest?.test(\"nicifyPropertyString\", ({ expect }) => {\n // Test valid identifiers\n expect(nicifyPropertyString(\"validName\")).toBe('\"validName\"');\n expect(nicifyPropertyString(\"_validName\")).toBe('\"_validName\"');\n expect(nicifyPropertyString(\"valid123Name\")).toBe('\"valid123Name\"');\n\n // Test invalid identifiers\n expect(nicifyPropertyString(\"123invalid\")).toBe('\"123invalid\"');\n expect(nicifyPropertyString(\"invalid-name\")).toBe('\"invalid-name\"');\n expect(nicifyPropertyString(\"invalid space\")).toBe('\"invalid space\"');\n expect(nicifyPropertyString(\"$invalid\")).toBe('\"$invalid\"');\n expect(nicifyPropertyString(\"\")).toBe('\"\"');\n\n // Test with special characters\n expect(nicifyPropertyString(\"property!\")).toBe('\"property!\"');\n expect(nicifyPropertyString(\"property.name\")).toBe('\"property.name\"');\n\n // Test with escaped characters\n expect(nicifyPropertyString(\"\\\\\")).toBe('\"\\\\\\\\\"');\n expect(nicifyPropertyString('\"')).toBe('\"\\\\\"\"');\n});\n\nfunction getNicifiableKeys(value: Nicifiable | object) {\n const overridden = (\"getNicifiableKeys\" in value ? value.getNicifiableKeys?.bind(value) : null)?.();\n if (overridden != null) return overridden;\n if (value instanceof Response) {\n return ['status', 'headers'];\n }\n const keys = Object.keys(value).sort();\n return unique(keys);\n}\nimport.meta.vitest?.test(\"getNicifiableKeys\", ({ expect }) => {\n // Test regular object\n expect(getNicifiableKeys({ b: 1, a: 2, c: 3 })).toEqual([\"a\", \"b\", \"c\"]);\n\n // Test empty object\n expect(getNicifiableKeys({})).toEqual([]);\n\n\n expect(getNicifiableKeys(new Response())).toEqual([\"status\", \"headers\"]);\n\n // Test object with custom getNicifiableKeys\n const customObject = {\n a: 1,\n b: 2,\n getNicifiableKeys() {\n return [\"customKey1\", \"customKey2\"];\n }\n };\n expect(getNicifiableKeys(customObject)).toEqual([\"customKey1\", \"customKey2\"]);\n});\n\nfunction getNicifiableEntries(value: Nicifiable | object): [PropertyKey, unknown][] {\n const recordLikes = [Headers];\n function isRecordLike(value: unknown): value is InstanceType<typeof recordLikes[number]> {\n return recordLikes.some(x => value instanceof x);\n }\n\n if (isRecordLike(value)) {\n return [...value.entries()].sort(([a], [b]) => stringCompare(`${a}`, `${b}`));\n }\n const keys = getNicifiableKeys(value);\n return keys.map((k) => [k, value[k as never]] as [PropertyKey, unknown]);\n}\n\nfunction getNicifiedObjectExtraLines(value: Nicifiable | object) {\n return (\"getNicifiedObjectExtraLines\" in value ? value.getNicifiedObjectExtraLines : null)?.() ?? [];\n}\n", "export function identity<T>(t: T): T {\n return t;\n}\nimport.meta.vitest?.test(\"identity\", ({ expect }) => {\n expect(identity(1)).toBe(1);\n expect(identity(\"test\")).toBe(\"test\");\n expect(identity(null)).toBe(null);\n expect(identity(undefined)).toBe(undefined);\n const obj = { a: 1 };\n expect(identity(obj)).toBe(obj);\n});\n\nexport function identityArgs<T extends any[]>(...args: T): T {\n return args;\n}\nimport.meta.vitest?.test(\"identityArgs\", ({ expect }) => {\n expect(identityArgs()).toEqual([]);\n expect(identityArgs(1)).toEqual([1]);\n expect(identityArgs(1, 2, 3)).toEqual([1, 2, 3]);\n expect(identityArgs(\"a\", \"b\", \"c\")).toEqual([\"a\", \"b\", \"c\"]);\n expect(identityArgs(null, undefined)).toEqual([null, undefined]);\n});\n", "import { DeepPartial } from \"./objects\";\nimport { Join } from \"./strings\";\n\nexport type IsAny<T> = 0 extends (1 & T) ? true : false;\nexport type IsNever<T> = [T] extends [never] ? true : false;\nexport type IsNullish<T> = [T] extends [null | undefined] ? true : false;\nexport type IsUnion<T, U = T> =\n IsNever<T> extends true ? false\n : IsAny<T> extends true ? false\n : T extends U // distributive conditional https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types\n ? /* if the *whole* original type (`U`) still fits inside the current variant, then `T` wasn’t a union */ ([U] extends [T] ? false : true)\n : never;\n\nexport type NullishCoalesce<T, U> = T extends null | undefined ? U : T;\n\nexport type LastUnionElement<U> = UnionToIntersection<U extends any ? (x: U) => 0 : never> extends (x: infer L) => 0 ? L & U : never;\n\ntype primitive = string | number | boolean | bigint | symbol | null | undefined;\n\n/**\n * Makes a type prettier by recursively expanding all object types. For example, `Omit<{ a: 1 }, \"a\">` becomes just `{}`.\n */\nexport type Expand<T> = T extends (...args: infer A) => infer R\n ? ((...args: A) => R) extends T\n ? (...args: Expand<A>) => Expand<R>\n : ((...args: Expand<A>) => Expand<R>) & { [K in keyof T]: Expand<T[K]> }\n : T extends object\n ? T extends primitive\n ? T\n : T extends infer O\n ? { [K in keyof O]: Expand<O[K]> }\n : never\n : T;\n\n\n/**\n * Removes all optional undefined/never keys from an object.\n */\nexport type DeepRemoveOptionalUndefined<T> = T extends object ? { [K in keyof T]: DeepRemoveOptionalUndefined<T[K]> } : T;\n\n// why this works: https://stackoverflow.com/a/50375286\nexport type UnionToIntersection<U> =\n (U extends any ? (x: U) => void : never) extends ((x: infer I) => void) ? I : never\n\ntype _UnionToTupleInner<U, R extends any[], Last> = UnionToTuple<Exclude<U, Last>, [...R, Last]>\nexport type UnionToTuple<U, R extends any[] = []> = [U] extends [never] ? R : _UnionToTupleInner<U, R, LastUnionElement<U>>;\n\nexport type CollapseObjectUnion<T extends object> = {\n [K in AllUnionKeys<T>]?: T extends Record<K, infer V> ? V : never;\n};\ntypeAssertIs<CollapseObjectUnion<{ a: string } | { b: number }>, { a?: string, b?: number }>()();\ntypeAssertIs<CollapseObjectUnion<{ a: string } | { a: number }>, { a?: string | number }>()();\n\nexport type IntersectAll<T extends any[]> = UnionToIntersection<T[number]>;\n\nexport type OptionalKeys<T> = {\n [K in keyof T]: {} extends Pick<T, K> ? K : never;\n}[keyof T];\nexport type RequiredKeys<T> = {\n [K in keyof T]: {} extends Pick<T, K> ? never : K;\n}[keyof T];\n\n/**\n * Returns a type whose keys are the intersection of the keys of T and U, deeply.\n */\nexport type KeyIntersect<T, U> =\n & { [K in keyof T & keyof U]?: T[K] & U[K] }\n & { [K in RequiredKeys<T> & keyof U]: T[K] & U[K] }\n & { [K in RequiredKeys<U> & keyof T]: U[K] & T[K] }\n\n/**\n * Returns ALL keys of all union elements.\n */\nexport type AllUnionKeys<T extends object> = T extends T ? keyof T : never;\ntypeAssertIs<AllUnionKeys<{ a: string } | { b: number }>, \"a\" | \"b\">()();\n\nexport type SubtractType<T, U> = T extends object ? { [K in keyof T]: K extends keyof U ? SubtractType<T[K], U[K]> : T[K] } : (T extends U ? never : T); // note: this only works due to the distributive property of conditional types https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types\n\nexport type XOR<T extends readonly any[]> = T extends readonly [infer A, infer B, ...infer Rest]\n ? Rest extends []\n ? (A & { [K in keyof B]?: never }) | (B & { [K in keyof A]?: never })\n : XOR<[(A & { [K in keyof B]?: never }) | (B & { [K in keyof A]?: never }), ...Rest]>\n : T[0];\n\n\ntype _AntiIntersectInner<T, U> = T extends object ? (\n & Omit<U, keyof T>\n & { [K in keyof Pick<U, { [K in keyof T & keyof U]: U[K] extends T[K] ? (T[K] extends U[K] ? never : K) : never }[keyof T & keyof U]>]: PseudoAntiIntersect<T[K], U[K]> }\n & { [K in keyof Pick<U, keyof T & keyof U>]?: PseudoAntiIntersect<T[K], U[K]> }\n) : U;\n/**\n * Returns a type R such that T & R = U.\n */\nexport type AntiIntersect<T, U> = U extends T ? _AntiIntersectInner<T, U> : \"Cannot anti-intersect a type with a type that is not a subtype of it\"; // NOTE: This type is mostly untested — not sure how well it works on the edge cases\nexport type PseudoAntiIntersect<T, U> = _AntiIntersectInner<T, T & U>;\n\n/**\n * A variation of TypeScript's conditionals with slightly different semantics. It is the perfect type for cases where:\n *\n * - If all possible values are contained in `Extends`, then it will be mapped to `Then`.\n * - If all possible values are not contained in `Extends`, then it will be mapped to `Otherwise`.\n * - If some possible values are contained in `Extends` and some are not, then it will be mapped to `Then | Otherwise`.\n *\n * This is different from TypeScript's built-in conditional types (`Value extends Extends ? Then : Otherwise`), which\n * returns `Otherwise` for the third case (causing unsoundness in many real-world cases).\n */\nexport type IfAndOnlyIf<Value, Extends, Then, Otherwise> =\n | (Value extends Extends ? never : Otherwise)\n | (Value & Extends extends never ? never : Then);\n\n\n/**\n * Can be used to prettify a type in the IDE; for example, some complicated intersected types can be flattened into a single type.\n */\nexport type PrettifyType<T> = T extends object ? { [K in keyof T]: T[K] } & {} : T;\n\ntype _ToStringAndJoin<T extends any[], Separator extends string> =\n T extends [infer U, ...infer Rest extends any[]]\n ? `${TypeToString<U>}${Rest extends [any, ...any[]] ? `${Separator}${_ToStringAndJoin<Rest, Separator>}` : \"\"}`\n : \"<error-joining-tuple-elements>\";\ntype _TypeToStringInner<T> =\n IsAny<T> extends true ? \"any\"\n : IsNever<T> extends true ? \"never\"\n : IsUnion<T> extends true ? _ToStringAndJoin<UnionToTuple<T>, \" | \">\n : [T] extends [number] ? (number extends T ? \"number\" : `${T}`)\n : [T] extends [boolean] ? `${T}`\n : [T] extends [undefined] ? \"undefined\"\n : [T] extends [null] ? \"null\"\n : [T] extends [string] ? (string extends T ? \"string\" : `'${T}'`)\n : [T] extends [[]] ? \"[]\"\n : [T] extends [[any, ...any[]]] ? `[${_ToStringAndJoin<T, \", \">}]`\n : [T] extends [(infer E)[]] ? `${TypeToString<E>}[]`\n : [T] extends [Function] ? \"function\"\n : [T] extends [symbol] ? `symbol(${T['description']})`\n : [T] extends [object] ? `{ ${Join<UnionToTuple<{ [K in keyof T]: `${TypeToString<K>}: ${TypeToString<T[K]>}` }[keyof T]>, \", \">} }`\n : \"<unknown-type>\"\nexport type TypeToString<T> = _TypeToStringInner<T> extends `${infer S}` ? S : never;\n\n/**\n * Can be used to create assertions on types. For example, if passed any T other than `true`, the following will\n * show a type error:\n *\n * ```ts\n * typeAssert<T>()(); // the second pair of braces is important!\n * ```\n */\nexport function typeAssert<T>(): (\n IsAny<T> extends true ? TypeAssertionError<`Type assertion failed. Expected true, but got any.`>\n : IsNever<T> extends true ? TypeAssertionError<`Type assertion failed. Expected true, but got never.`>\n : T extends true ? (() => undefined)\n : TypeAssertionError<`Type assertion failed. Expected true, but got: ${TypeToString<T>}`>\n) {\n return (() => undefined) as any;\n}\ntype TypeAssertionError<T> =\n & [T]\n & /* this promise makes sure that if we accidentally forget the second pair of braces, eslint will complain (if we have no-floating-promises enabled) */ Promise<any>;\n\n\ntypeAssertExtends<ReturnType<typeof typeAssert<true>>, () => undefined>()();\ntypeAssertExtends<ReturnType<typeof typeAssert<false>>, TypeAssertionError<`Type assertion failed. Expected true, but got: false`>>()();\ntypeAssertExtends<ReturnType<typeof typeAssert<never>>, TypeAssertionError<`Type assertion failed. Expected true, but got never.`>>()();\ntypeAssertExtends<ReturnType<typeof typeAssert<any>>, TypeAssertionError<`Type assertion failed. Expected true, but got any.`>>()();\n\n/**\n * Functionally equivalent to `typeAssert<T extends S ? true : false>()()`, but with better error messages.\n */\nexport function typeAssertExtends<T, S>(): (\n [T] extends [S] ? (() => undefined) : TypeAssertionError<`Type assertion failed. Expected ${TypeToString<T>} to extend ${TypeToString<S>}`>\n) {\n return (() => undefined) as any;\n}\n\ntypeAssertExtends<ReturnType<typeof typeAssertExtends<never, true>>, () => undefined>()();\ntypeAssertExtends<ReturnType<typeof typeAssertExtends<any, true>>, () => undefined>()();\ntypeAssertExtends<ReturnType<typeof typeAssertExtends<false, false>>, () => undefined>()();\ntypeAssertExtends<ReturnType<typeof typeAssertExtends<\"abc\", string>>, () => undefined>()();\ntypeAssertExtends<ReturnType<typeof typeAssertExtends<{a: 1, b: 123}, {a: number}>>, () => undefined>()();\ntypeAssertExtends<ReturnType<typeof typeAssertExtends<never, never>>, () => undefined>()();\ntypeAssertExtends<ReturnType<typeof typeAssertExtends<true, any>>, () => undefined>()();\n\ntypeAssertExtends<ReturnType<typeof typeAssertExtends<{a: number}, {a: 1}>>, [\"Type assertion failed. Expected { 'a': number } to extend { 'a': 1 }\"]>()();\ntypeAssertExtends<ReturnType<typeof typeAssertExtends<any, never>>, [\"Type assertion failed. Expected any to extend never\"]>()();\ntypeAssertExtends<ReturnType<typeof typeAssertExtends<false, true>>, [\"Type assertion failed. Expected false to extend true\"]>()();\ntypeAssertExtends<ReturnType<typeof typeAssertExtends<false, never>>, [\"Type assertion failed. Expected false to extend never\"]>()();\n\n\nexport function typeAssertIs<T, U>(): (\n IsAny<T> extends true ? (IsAny<U> extends true ? (() => undefined) : TypeAssertionError<`Type assertion failed. Expected ${TypeToString<T>} to be ${TypeToString<U>}`>)\n : IsAny<U> extends true ? TypeAssertionError<`Type assertion failed. Expected ${TypeToString<T>} to be ${TypeToString<U>}`>\n : [T] extends [U] ? ([U] extends [T] ? (() => undefined) : TypeAssertionError<`Type assertion failed. Expected ${TypeToString<T>} to be ${TypeToString<U>}`>)\n : TypeAssertionError<`Type assertion failed. Expected ${TypeToString<T>} to be ${TypeToString<U>}`>\n) {\n return (() => undefined) as any;\n}\n\ntypeAssertExtends<ReturnType<typeof typeAssertIs<\"123\", \"123\">>, () => undefined>()();\ntypeAssertExtends<ReturnType<typeof typeAssertIs<{a: 1}, {a: 1}>>, () => undefined>()();\ntypeAssertExtends<ReturnType<typeof typeAssertIs<DeepPartial<{a: 1}>, {a?: 1}>>, () => undefined>()();\ntypeAssertExtends<ReturnType<typeof typeAssertIs<any, any>>, () => undefined>()();\ntypeAssertExtends<ReturnType<typeof typeAssertIs<never, never>>, () => undefined>()();\ntypeAssertExtends<ReturnType<typeof typeAssertIs<1, any>>, [\"Type assertion failed. Expected 1 to be any\"]>()();\ntypeAssertExtends<ReturnType<typeof typeAssertIs<any, 1>>, [\"Type assertion failed. Expected any to be 1\"]>()();\ntypeAssertExtends<ReturnType<typeof typeAssertIs<false, true>>, [\"Type assertion failed. Expected false to be true\"]>()();\ntypeAssertExtends<ReturnType<typeof typeAssertIs<{a: number}, {a: 1}>>, [\"Type assertion failed. Expected { 'a': number } to be { 'a': 1 }\"]>()();\ntypeAssertExtends<ReturnType<typeof typeAssertIs<any, never>>, [\"Type assertion failed. Expected any to be never\"]>()();\ntypeAssertExtends<ReturnType<typeof typeAssertIs<false, true>>, [\"Type assertion failed. Expected false to be true\"]>()();\ntypeAssertExtends<ReturnType<typeof typeAssertIs<false, never>>, [\"Type assertion failed. Expected false to be never\"]>()();\n", "import { StackAssertionError } from \"./errors\";\nimport { identity } from \"./functions\";\nimport { stringCompare } from \"./strings\";\nimport { typeAssertIs } from \"./types\";\n\nexport function isNotNull<T>(value: T): value is NonNullable<T> {\n return value !== null && value !== undefined;\n}\nimport.meta.vitest?.test(\"isNotNull\", ({ expect }) => {\n expect(isNotNull(null)).toBe(false);\n expect(isNotNull(undefined)).toBe(false);\n expect(isNotNull(0)).toBe(true);\n expect(isNotNull(\"\")).toBe(true);\n expect(isNotNull(false)).toBe(true);\n expect(isNotNull({})).toBe(true);\n expect(isNotNull([])).toBe(true);\n});\n\nexport type DeepPartial<T> = T extends object ? (T extends any[] ? { [P in keyof T]: DeepPartial<T[P]> } : { [P in keyof T]?: DeepPartial<T[P]> }) : T;\nexport type DeepRequired<T> = T extends object ? { [P in keyof T]-?: DeepRequired<T[P]> } : T;\nexport type DeepRequiredOrUndefined<T> = T extends object ? { [P in keyof { [K in keyof T]-?: K}]: DeepRequiredOrUndefined<T[P]> } : T;\n\n\n/**\n * Assumes both objects are primitives, arrays, or non-function plain objects, and compares them deeply.\n *\n * Note that since they are assumed to be plain objects, this function does not compare prototypes.\n */\nexport function deepPlainEquals<T>(obj1: T, obj2: unknown, options: { ignoreUndefinedValues?: boolean } = {}): obj2 is T {\n if (typeof obj1 !== typeof obj2) return false;\n if (obj1 === obj2) return true;\n\n switch (typeof obj1) {\n case 'object': {\n if (!obj1 || !obj2) return false;\n\n if (Array.isArray(obj1) || Array.isArray(obj2)) {\n if (!Array.isArray(obj1) || !Array.isArray(obj2)) return false;\n if (obj1.length !== obj2.length) return false;\n return obj1.every((v, i) => deepPlainEquals(v, obj2[i], options));\n }\n\n const entries1 = Object.entries(obj1).filter(([k, v]) => !options.ignoreUndefinedValues || v !== undefined);\n const entries2 = Object.entries(obj2).filter(([k, v]) => !options.ignoreUndefinedValues || v !== undefined);\n if (entries1.length !== entries2.length) return false;\n return entries1.every(([k, v1]) => {\n const e2 = entries2.find(([k2]) => k === k2);\n if (!e2) return false;\n return deepPlainEquals(v1, e2[1], options);\n });\n }\n case 'undefined':\n case 'string':\n case 'number':\n case 'boolean':\n case 'bigint':\n case 'symbol':\n case 'function':{\n return false;\n }\n default: {\n throw new Error(\"Unexpected typeof \" + typeof obj1);\n }\n }\n}\nimport.meta.vitest?.test(\"deepPlainEquals\", ({ expect }) => {\n // Simple values\n expect(deepPlainEquals(1, 1)).toBe(true);\n expect(deepPlainEquals(\"test\", \"test\")).toBe(true);\n expect(deepPlainEquals(1, 2)).toBe(false);\n expect(deepPlainEquals(\"test\", \"other\")).toBe(false);\n\n // Arrays\n expect(deepPlainEquals([1, 2, 3], [1, 2, 3])).toBe(true);\n expect(deepPlainEquals([1, 2, 3], [1, 2, 4])).toBe(false);\n expect(deepPlainEquals([1, 2, 3], [1, 2])).toBe(false);\n\n // Objects\n expect(deepPlainEquals({ a: 1, b: 2 }, { a: 1, b: 2 })).toBe(true);\n expect(deepPlainEquals({ a: 1, b: 2 }, { a: 1, b: 3 })).toBe(false);\n expect(deepPlainEquals({ a: 1, b: 2 }, { a: 1 })).toBe(false);\n\n // Nested structures\n expect(deepPlainEquals({ a: 1, b: [1, 2, { c: 3 }] }, { a: 1, b: [1, 2, { c: 3 }] })).toBe(true);\n expect(deepPlainEquals({ a: 1, b: [1, 2, { c: 3 }] }, { a: 1, b: [1, 2, { c: 4 }] })).toBe(false);\n\n // With options\n expect(deepPlainEquals({ a: 1, b: undefined }, { a: 1 }, { ignoreUndefinedValues: true })).toBe(true);\n expect(deepPlainEquals({ a: 1, b: undefined }, { a: 1 })).toBe(false);\n});\n\nexport function isCloneable<T>(obj: T): obj is Exclude<T, symbol | Function> {\n return typeof obj !== 'symbol' && typeof obj !== 'function';\n}\n\nexport function shallowClone<T extends object>(obj: T): T {\n if (!isCloneable(obj)) throw new StackAssertionError(\"shallowClone does not support symbols or functions\", { obj });\n\n if (Array.isArray(obj)) return obj.map(identity) as T;\n return { ...obj };\n}\nimport.meta.vitest?.test(\"shallowClone\", ({ expect }) => {\n expect(shallowClone({ a: 1, b: 2 })).toEqual({ a: 1, b: 2 });\n expect(shallowClone([1, 2, 3])).toEqual([1, 2, 3]);\n expect(() => shallowClone(() => {})).toThrow();\n});\n\nexport function deepPlainClone<T>(obj: T): T {\n if (typeof obj === 'function') throw new StackAssertionError(\"deepPlainClone does not support functions\");\n if (typeof obj === 'symbol') throw new StackAssertionError(\"deepPlainClone does not support symbols\");\n if (typeof obj !== 'object' || !obj) return obj;\n if (Array.isArray(obj)) return obj.map(deepPlainClone) as any;\n return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, deepPlainClone(v)])) as any;\n}\nimport.meta.vitest?.test(\"deepPlainClone\", ({ expect }) => {\n // Primitive values\n expect(deepPlainClone(1)).toBe(1);\n expect(deepPlainClone(\"test\")).toBe(\"test\");\n expect(deepPlainClone(null)).toBe(null);\n expect(deepPlainClone(undefined)).toBe(undefined);\n\n // Arrays\n const arr = [1, 2, 3];\n const clonedArr = deepPlainClone(arr);\n expect(clonedArr).toEqual(arr);\n expect(clonedArr).not.toBe(arr); // Different reference\n\n // Objects\n const obj = { a: 1, b: 2 };\n const clonedObj = deepPlainClone(obj);\n expect(clonedObj).toEqual(obj);\n expect(clonedObj).not.toBe(obj); // Different reference\n\n // Nested structures\n const nested = { a: 1, b: [1, 2, { c: 3 }] };\n const clonedNested = deepPlainClone(nested);\n expect(clonedNested).toEqual(nested);\n expect(clonedNested).not.toBe(nested); // Different reference\n expect(clonedNested.b).not.toBe(nested.b); // Different reference for nested array\n expect(clonedNested.b[2]).not.toBe(nested.b[2]); // Different reference for nested object\n\n // Error cases\n expect(() => deepPlainClone(() => {})).toThrow();\n expect(() => deepPlainClone(Symbol())).toThrow();\n});\n\nexport type DeepMerge<T, U> = U extends any ? DeepMergeNonDistributive<T, U> : never; // distributive conditional type https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types\ntype DeepMergeNonDistributive<T, U> = Omit<T, keyof U> & Omit<U, keyof T> & DeepMergeInner<Pick<T, keyof U & keyof T>, Pick<U, keyof U & keyof T>>;\ntype DeepMergeInner<T, U> = {\n [K in { [Ki in keyof U]-?: Ki }[keyof U]]: // we use this weird construct instead of just `keyof U` because TypeScript automatically removes the `undefined` key when using `-?` as a modifier; this is a workaround to make TypeScript not recognize the -? and for us to get the `undefined` key back\n undefined extends U[K]\n ? K extends keyof T\n ? T[K] extends object\n ? Exclude<U[K], undefined> extends object\n ? DeepMerge<T[K], Exclude<U[K], undefined>>\n : T[K] | Exclude<U[K], undefined>\n : T[K] | Exclude<U[K], undefined>\n : Exclude<U[K], undefined>\n : K extends keyof T\n ? T[K] extends object\n ? U[K] extends object\n ? DeepMerge<T[K], U[K]>\n : U[K]\n : U[K]\n : U[K];\n};\nexport function deepMerge<T extends {}, U extends {}>(baseObj: T, mergeObj: U): DeepMerge<T, U> {\n if ([baseObj, mergeObj, ...Object.values(baseObj), ...Object.values(mergeObj)].some(o => !isCloneable(o))) throw new StackAssertionError(\"deepMerge does not support functions or symbols\", { baseObj, mergeObj });\n\n const res: any = shallowClone(baseObj);\n for (const [key, mergeValue] of Object.entries(mergeObj)) {\n if (has(res, key as any)) {\n const baseValue = get(res, key as any);\n if (isObjectLike(baseValue) && isObjectLike(mergeValue)) {\n set(res, key, deepMerge(baseValue, mergeValue));\n continue;\n }\n }\n set(res, key, mergeValue);\n }\n return res as any;\n}\nimport.meta.vitest?.test(\"deepMerge\", ({ expect }) => {\n // Test merging flat objects\n expect(deepMerge({ a: 1 }, { b: 2 })).toEqual({ a: 1, b: 2 });\n expect(deepMerge({ a: 1 }, { a: 2 })).toEqual({ a: 2 });\n expect(deepMerge({ a: 1, b: 2 }, { b: 3, c: 4 })).toEqual({ a: 1, b: 3, c: 4 });\n\n // Test with nested objects\n expect(deepMerge(\n { a: { x: 1, y: 2 }, b: 3 },\n { a: { y: 3, z: 4 }, c: 5 }\n )).toEqual({ a: { x: 1, y: 3, z: 4 }, b: 3, c: 5 });\n\n // Test with arrays\n expect(deepMerge(\n { a: [1, 2], b: 3 },\n { a: [3, 4], c: 5 }\n )).toEqual({ a: [3, 4], b: 3, c: 5 });\n\n // Test with null values\n expect(deepMerge(\n { a: { x: 1 }, b: null },\n { a: { y: 2 }, b: { z: 3 } }\n )).toEqual({ a: { x: 1, y: 2 }, b: { z: 3 } });\n\n // Test with undefined values\n expect(deepMerge(\n { a: 1, b: undefined },\n { b: 2, c: 3 }\n )).toEqual({ a: 1, b: 2, c: 3 });\n\n // Test deeply nested structures\n expect(deepMerge(\n {\n a: {\n x: { deep: 1 },\n y: [1, 2]\n },\n b: 2\n },\n {\n a: {\n x: { deeper: 3 },\n y: [3, 4]\n },\n c: 3\n }\n )).toEqual({\n a: {\n x: { deep: 1, deeper: 3 },\n y: [3, 4]\n },\n b: 2,\n c: 3\n });\n\n // Test with empty objects\n expect(deepMerge({}, { a: 1 })).toEqual({ a: 1 });\n expect(deepMerge({ a: 1 }, {})).toEqual({ a: 1 });\n expect(deepMerge({}, {})).toEqual({});\n\n // Test that original objects are not modified\n const base = { a: { x: 1 }, b: 2 };\n const merge = { a: { y: 2 }, c: 3 };\n const baseClone = deepPlainClone(base);\n const mergeClone = deepPlainClone(merge);\n\n const result = deepMerge(base, merge);\n expect(base).toEqual(baseClone);\n expect(merge).toEqual(mergeClone);\n expect(result).toEqual({ a: { x: 1, y: 2 }, b: 2, c: 3 });\n\n // Test error cases\n expect(() => deepMerge({ a: () => {} }, { b: 2 })).toThrow();\n expect(() => deepMerge({ a: 1 }, { b: () => {} })).toThrow();\n expect(() => deepMerge({ a: Symbol() }, { b: 2 })).toThrow();\n expect(() => deepMerge({ a: 1 }, { b: Symbol() })).toThrow();\n});\n\nexport type DeepOmit<T, U> = T extends object ? { [K in keyof T]: K extends keyof U ? (T[K] extends U[K] ? undefined : T[K]) : T[K] } : (T extends U ? undefined : T);\n\nexport function typedEntries<T extends {}>(obj: T): [Exclude<keyof T, number>, T[keyof T]][] {\n return Object.entries(obj) as any;\n}\nimport.meta.vitest?.test(\"typedEntries\", ({ expect }) => {\n expect(typedEntries({})).toEqual([]);\n expect(typedEntries({ a: 1, b: 2 })).toEqual([[\"a\", 1], [\"b\", 2]]);\n expect(typedEntries({ a: \"hello\", b: true, c: null })).toEqual([[\"a\", \"hello\"], [\"b\", true], [\"c\", null]]);\n\n // Test with object containing methods\n const objWithMethod = { a: 1, b: () => \"test\" };\n const entries = typedEntries(objWithMethod);\n expect(entries.length).toBe(2);\n expect(entries[0][0]).toBe(\"a\");\n expect(entries[0][1]).toBe(1);\n expect(entries[1][0]).toBe(\"b\");\n expect(typeof entries[1][1]).toBe(\"function\");\n});\n\nexport function typedFromEntries<K extends PropertyKey, V>(entries: (readonly [K, V])[]): Record<K, V> {\n return Object.fromEntries(entries) as any;\n}\nimport.meta.vitest?.test(\"typedFromEntries\", ({ expect }) => {\n expect(typedFromEntries([])).toEqual({});\n expect(typedFromEntries([[\"a\", 1], [\"b\", 2]])).toEqual({ a: 1, b: 2 });\n\n // Test with mixed types (using type assertion)\n const mixedEntries = [[\"a\", \"hello\"], [\"b\", true], [\"c\", null]] as [string, string | boolean | null][];\n const mixedObj = typedFromEntries(mixedEntries);\n expect(mixedObj).toEqual({ a: \"hello\", b: true, c: null });\n\n // Test with function values\n const fn = () => \"test\";\n type MixedValue = number | (() => string);\n const fnEntries: [string, MixedValue][] = [[\"a\", 1], [\"b\", fn]];\n const obj = typedFromEntries(fnEntries);\n expect(obj.a).toBe(1);\n expect(typeof obj.b).toBe(\"function\");\n // Type assertion needed for the function call\n expect((obj.b as () => string)()).toBe(\"test\");\n});\n\nexport function typedKeys<T extends {}>(obj: T): (Exclude<keyof T, number>)[] {\n return Object.keys(obj) as any;\n}\nimport.meta.vitest?.test(\"typedKeys\", ({ expect }) => {\n expect(typedKeys({})).toEqual([]);\n expect(typedKeys({ a: 1, b: 2 })).toEqual([\"a\", \"b\"]);\n expect(typedKeys({ a: \"hello\", b: true, c: null })).toEqual([\"a\", \"b\", \"c\"]);\n\n // Test with object containing methods\n const objWithMethod = { a: 1, b: () => \"test\" };\n expect(typedKeys(objWithMethod)).toEqual([\"a\", \"b\"]);\n});\n\nexport function typedValues<T extends {}>(obj: T): T[keyof T][] {\n return Object.values(obj) as any;\n}\nimport.meta.vitest?.test(\"typedValues\", ({ expect }) => {\n expect(typedValues({})).toEqual([]);\n expect(typedValues({ a: 1, b: 2 })).toEqual([1, 2]);\n\n // Test with mixed types\n type MixedObj = { a: string, b: boolean, c: null };\n const mixedObj: MixedObj = { a: \"hello\", b: true, c: null };\n expect(typedValues(mixedObj)).toEqual([\"hello\", true, null]);\n\n // Test with object containing methods\n type ObjWithFn = { a: number, b: () => string };\n const fn = () => \"test\";\n const objWithMethod: ObjWithFn = { a: 1, b: fn };\n const values = typedValues(objWithMethod);\n expect(values.length).toBe(2);\n expect(values[0]).toBe(1);\n expect(typeof values[1]).toBe(\"function\");\n // Need to cast to the correct type\n const fnValue = values[1] as () => string;\n expect(fnValue()).toBe(\"test\");\n});\n\nexport function typedAssign<T extends {}, U extends {}>(target: T, source: U): T & U {\n return Object.assign(target, source);\n}\nimport.meta.vitest?.test(\"typedAssign\", ({ expect }) => {\n // Test with empty objects\n const emptyTarget = {};\n const emptyResult = typedAssign(emptyTarget, { a: 1 });\n expect(emptyResult).toEqual({ a: 1 });\n expect(emptyResult).toBe(emptyTarget); // Same reference\n\n // Test with non-empty target\n const target = { a: 1, b: 2 };\n const result = typedAssign(target, { c: 3, d: 4 });\n expect(result).toEqual({ a: 1, b: 2, c: 3, d: 4 });\n expect(result).toBe(target); // Same reference\n\n // Test with overlapping properties\n const targetWithOverlap = { a: 1, b: 2 };\n const resultWithOverlap = typedAssign(targetWithOverlap, { b: 3, c: 4 });\n expect(resultWithOverlap).toEqual({ a: 1, b: 3, c: 4 });\n expect(resultWithOverlap).toBe(targetWithOverlap); // Same reference\n});\n\nexport type FilterUndefined<T> =\n & { [k in keyof T as (undefined extends T[k] ? (T[k] extends undefined | void ? never : k) : never)]+?: T[k] & ({} | null) }\n & { [k in keyof T as (undefined extends T[k] ? never : k)]: T[k] & ({} | null) }\n\n/**\n * Returns a new object with all undefined values removed. Useful when spreading optional parameters on an object, as\n * TypeScript's `Partial<XYZ>` type allows `undefined` values.\n */\nexport function filterUndefined<T extends object>(obj: T): FilterUndefined<T> {\n return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined)) as any;\n}\nimport.meta.vitest?.test(\"filterUndefined\", ({ expect }) => {\n expect(filterUndefined({})).toEqual({});\n expect(filterUndefined({ a: 1, b: 2 })).toEqual({ a: 1, b: 2 });\n expect(filterUndefined({ a: 1, b: undefined })).toEqual({ a: 1 });\n expect(filterUndefined({ a: undefined, b: undefined })).toEqual({});\n expect(filterUndefined({ a: null, b: undefined })).toEqual({ a: null });\n expect(filterUndefined({ a: 0, b: \"\", c: false, d: undefined })).toEqual({ a: 0, b: \"\", c: false });\n});\n\nexport type FilterUndefinedOrNull<T> = FilterUndefined<{ [k in keyof T]: null extends T[k] ? NonNullable<T[k]> | undefined : T[k] }>;\n\n/**\n * Returns a new object with all undefined and null values removed. Useful when spreading optional parameters on an object, as\n * TypeScript's `Partial<XYZ>` type allows `undefined` values.\n */\nexport function filterUndefinedOrNull<T extends object>(obj: T): FilterUndefinedOrNull<T> {\n return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined && v !== null)) as any;\n}\nimport.meta.vitest?.test(\"filterUndefinedOrNull\", ({ expect }) => {\n expect(filterUndefinedOrNull({})).toEqual({});\n expect(filterUndefinedOrNull({ a: 1, b: 2 })).toEqual({ a: 1, b: 2 });\n});\n\nexport type DeepFilterUndefined<T> = T extends object ? FilterUndefined<{ [K in keyof T]: DeepFilterUndefined<T[K]> }> : T;\ntypeAssertIs<DeepFilterUndefined<{ a: { b: { c?: undefined, d?: 123 } } }>, { a: { b: { d?: 123 } } }>()();\n\nexport function deepFilterUndefined<T extends object>(obj: T): DeepFilterUndefined<T> {\n return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined).map(([k, v]) => [k, isObjectLike(v) ? deepFilterUndefined(v) : v])) as any;\n}\nimport.meta.vitest?.test(\"deepFilterUndefined\", ({ expect }) => {\n expect(deepFilterUndefined({ a: 1, b: undefined })).toEqual({ a: 1 });\n});\n\nexport function pick<T extends {}, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {\n return Object.fromEntries(Object.entries(obj).filter(([k]) => keys.includes(k as K))) as any;\n}\nimport.meta.vitest?.test(\"pick\", ({ expect }) => {\n const obj = { a: 1, b: 2, c: 3, d: 4 };\n expect(pick(obj, [\"a\", \"c\"])).toEqual({ a: 1, c: 3 });\n expect(pick(obj, [])).toEqual({});\n expect(pick(obj, [\"a\", \"e\" as keyof typeof obj])).toEqual({ a: 1 });\n // Use type assertion for empty object to avoid TypeScript error\n expect(pick({} as Record<string, unknown>, [\"a\"])).toEqual({});\n});\n\nexport function omit<T extends {}, K extends keyof T>(obj: T, keys: K[]): Omit<T, K> {\n if (!Array.isArray(keys)) throw new StackAssertionError(\"omit: keys must be an array\", { obj, keys });\n return Object.fromEntries(Object.entries(obj).filter(([k]) => !keys.includes(k as K))) as any;\n}\nimport.meta.vitest?.test(\"omit\", ({ expect }) => {\n const obj = { a: 1, b: 2, c: 3, d: 4 };\n expect(omit(obj, [\"a\", \"c\"])).toEqual({ b: 2, d: 4 });\n expect(omit(obj, [])).toEqual(obj);\n expect(omit(obj, [\"a\", \"e\" as keyof typeof obj])).toEqual({ b: 2, c: 3, d: 4 });\n // Use type assertion for empty object to avoid TypeScript error\n expect(omit({} as Record<string, unknown>, [\"a\"])).toEqual({});\n});\n\nexport function split<T extends {}, K extends keyof T>(obj: T, keys: K[]): [Pick<T, K>, Omit<T, K>] {\n return [pick(obj, keys), omit(obj, keys)];\n}\nimport.meta.vitest?.test(\"split\", ({ expect }) => {\n const obj = { a: 1, b: 2, c: 3, d: 4 };\n expect(split(obj, [\"a\", \"c\"])).toEqual([{ a: 1, c: 3 }, { b: 2, d: 4 }]);\n expect(split(obj, [])).toEqual([{}, obj]);\n expect(split(obj, [\"a\", \"e\" as keyof typeof obj])).toEqual([{ a: 1 }, { b: 2, c: 3, d: 4 }]);\n // Use type assertion for empty object to avoid TypeScript error\n expect(split({} as Record<string, unknown>, [\"a\"])).toEqual([{}, {}]);\n});\n\nexport function mapValues<T extends object, U>(obj: T, fn: (value: T extends (infer E)[] ? E : T[keyof T], key: keyof T) => U): Record<keyof T, U> {\n if (Array.isArray(obj)) {\n return obj.map((v, i) => fn(v, i as keyof T)) as any;\n }\n return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, fn(v, k as keyof T)])) as any;\n}\nimport.meta.vitest?.test(\"mapValues\", ({ expect }) => {\n expect(mapValues({ a: 1, b: 2 }, v => v * 2)).toEqual({ a: 2, b: 4 });\n expect(mapValues([1, 2, 3], v => v * 2)).toEqual([2, 4, 6]);\n});\n\nexport function sortKeys<T extends object>(obj: T): T {\n if (Array.isArray(obj)) {\n return [...obj] as any;\n }\n return Object.fromEntries(Object.entries(obj).sort(([a], [b]) => stringCompare(a, b))) as any;\n}\nimport.meta.vitest?.test(\"sortKeys\", ({ expect }) => {\n const obj = {\n \"1\": 0,\n \"10\": 1,\n b: 2,\n \"2\": 3,\n a: 4,\n \"-3.33\": 5,\n \"-4\": 6,\n \"-3\": 7,\n abc: 8,\n \"a-b\": 9,\n ab: 10,\n ac: 11,\n aa: 12,\n aab: 13,\n };\n expect(Object.entries(sortKeys(obj))).toEqual([\n [\"1\", 0],\n [\"2\", 3],\n [\"10\", 1],\n [\"-3\", 7],\n [\"-3.33\", 5],\n [\"-4\", 6],\n [\"a\", 4],\n [\"a-b\", 9],\n [\"aa\", 12],\n [\"aab\", 13],\n [\"ab\", 10],\n [\"abc\", 8],\n [\"ac\", 11],\n [\"b\", 2],\n ]);\n});\n\nexport function deepSortKeys<T extends object>(obj: T): T {\n return sortKeys(mapValues(obj, v => isObjectLike(v) ? deepSortKeys(v) : v)) as any;\n}\nimport.meta.vitest?.test(\"deepSortKeys\", ({ expect }) => {\n const obj = {\n h: { i: { k: 9, j: 8 }, l: 10 },\n b: { d: 3, c: 2 },\n a: 1,\n e: [4, 5, { g: 7, f: 6 }],\n };\n const sorted = deepSortKeys(obj);\n expect(Object.entries(sorted)).toEqual([\n [\"a\", 1],\n [\"b\", { c: 2, d: 3 }],\n [\"e\", [4, 5, { f: 6, g: 7 }]],\n [\"h\", { i: { j: 8, k: 9 }, l: 10 }],\n ]);\n expect(Object.entries(sorted.b)).toEqual([\n [\"c\", 2],\n [\"d\", 3],\n ]);\n expect(Object.entries(sorted.e[2])).toEqual([\n [\"f\", 6],\n [\"g\", 7],\n ]);\n expect(Object.entries(sorted.h)).toEqual([\n [\"i\", { j: 8, k: 9 }],\n [\"l\", 10],\n ]);\n expect(Object.entries(sorted.h.i)).toEqual([\n [\"j\", 8],\n [\"k\", 9],\n ]);\n});\n\nexport function set<T extends object, K extends PropertyKey = keyof T>(obj: T, key: K, value: T[K & keyof T]) {\n if (!isObjectLike(obj)) throw new StackAssertionError(`set: obj is not an object (found: ${(obj as any) === null ? \"null\" : typeof obj})`, { obj, key, value });\n Object.defineProperty(obj, key, { value, writable: true, configurable: true, enumerable: true });\n}\n\nexport function get<T extends object, K extends PropertyKey = keyof T>(obj: T, key: K): T[K & keyof T] {\n if ((obj as any) == null) throw new StackAssertionError(\"get: obj is null or undefined\", { obj, key });\n const descriptor = Object.getOwnPropertyDescriptor(obj, key);\n if (!descriptor) throw new StackAssertionError(`get: key ${String(key)} does not exist`, { obj, key });\n return descriptor.value;\n}\n\nexport function getOrUndefined<T extends object, K extends PropertyKey = keyof T>(obj: T, key: K): T[K & keyof T] | undefined {\n if ((obj as any) == null) throw new StackAssertionError(\"getOrUndefined: obj is null or undefined\", { obj, key });\n return has(obj, key) ? get(obj, key) : undefined;\n}\n\nexport function has<T extends object, K extends PropertyKey = keyof T>(obj: T, key: K): obj is T & { [k in K & keyof T]: unknown } {\n if ((obj as any) == null) throw new StackAssertionError(\"has: obj is null or undefined\", { obj, key });\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nimport.meta.vitest?.test(\"has\", ({ expect }) => {\n const obj = { a: 1, b: undefined, c: null };\n expect(has(obj, \"a\")).toBe(true);\n expect(has(obj, \"b\")).toBe(true);\n expect(has(obj, \"c\")).toBe(true);\n expect(has(obj, \"d\" as keyof typeof obj)).toBe(false);\n});\n\n\nexport function hasAndNotUndefined<T extends object, K extends keyof T>(obj: T, key: K): obj is T & { [k in K]: Exclude<T[K], undefined> } {\n return has(obj, key) && get(obj, key) !== undefined;\n}\n\nexport function deleteKey<T extends object, K extends keyof T>(obj: T, key: K) {\n if (has(obj, key)) {\n Reflect.deleteProperty(obj, key);\n } else {\n throw new StackAssertionError(`deleteKey: key ${String(key)} does not exist`, { obj, key });\n }\n}\n\n/**\n * Returns true iff the value is an object or a function, but not null.\n */\nexport function isObjectLike(value: unknown): value is object | Function {\n return (typeof value === 'object' || typeof value === 'function') && value !== null;\n}\n", "const globalVar: any =\n typeof globalThis !== 'undefined' ? globalThis :\n typeof global !== 'undefined' ? global :\n typeof window !== 'undefined' ? window :\n typeof self !== 'undefined' ? self :\n {};\nexport {\n globalVar\n};\n\nif (typeof globalThis === 'undefined') {\n (globalVar as any).globalThis = globalVar;\n}\n\nconst stackGlobalsSymbol = Symbol.for('__stack-globals');\nglobalVar[stackGlobalsSymbol] ??= {};\n\nexport function createGlobal<T>(key: string, init: () => T) {\n if (!globalVar[stackGlobalsSymbol][key]) {\n globalVar[stackGlobalsSymbol][key] = init();\n }\n return globalVar[stackGlobalsSymbol][key] as T;\n}\n\n/**\n * Like createGlobal, but if the asynchronous initialization fails, the global will be reset and recomputed on the next\n * invocation.\n */\nexport function createGlobalAsync<T>(key: string, init: () => Promise<T>): Promise<T> {\n let promise: Promise<T> | null = null;\n if (!globalVar[stackGlobalsSymbol][key]) {\n promise = init().catch((e) => {\n delete globalVar[stackGlobalsSymbol][key];\n throw e;\n });\n globalVar[stackGlobalsSymbol][key] = promise;\n }\n return promise ?? globalVar[stackGlobalsSymbol][key] as Promise<T>;\n}\n\nexport function getGlobal(key: string): any {\n return globalVar[stackGlobalsSymbol][key];\n}\n\nexport function setGlobal(key: string, value: any) {\n globalVar[stackGlobalsSymbol][key] = value;\n}\n", "import { globalVar } from \"./globals\";\nimport { Json } from \"./json\";\nimport { pick } from \"./objects\";\nimport { nicify } from \"./strings\";\n\n\nexport function throwErr(errorMessage: string, extraData?: any): never;\nexport function throwErr(error: Error): never;\nexport function throwErr(...args: StatusErrorConstructorParameters): never;\nexport function throwErr(...args: any[]): never {\n if (typeof args[0] === \"string\") {\n throw new StackAssertionError(args[0], args[1]);\n } else if (args[0] instanceof Error) {\n throw args[0];\n } else {\n // @ts-expect-error\n throw new StatusError(...args);\n }\n}\n\nfunction removeStacktraceNameLine(stack: string): string {\n // some browsers (eg. Chrome) prepend the stack with an extra line with the error name\n const addsNameLine = new Error().stack?.startsWith(\"Error\\n\");\n return stack.split(\"\\n\").slice(addsNameLine ? 1 : 0).join(\"\\n\");\n}\n\n\n/**\n * Concatenates the (original) stacktraces of the given errors onto the first.\n *\n * Note: Very often, the concatStacktracesIfRejected function in promises.tsx is an easier way to use this function.\n *\n * Useful when you invoke an async function to receive a promise without awaiting it immediately. Browsers are smart\n * enough to keep track of the call stack in async function calls when you invoke `.then` within the same async tick,\n * but if you don't, the stacktrace will be lost.\n *\n * Here's an example of the unwanted behavior:\n *\n * ```tsx\n * async function log() {\n * await wait(0); // put the task on the event loop\n * console.log(new Error().stack);\n * }\n *\n * async function main() {\n * await log(); // good; prints both \"log\" and \"main\" on the stacktrace\n * log(); // bad; prints only \"log\" on the stacktrace\n * }\n * ```\n */\nexport function concatStacktraces(first: Error, ...errors: Error[]): void {\n // some browsers (eg. Firefox) add an extra empty line at the end\n const addsEmptyLineAtEnd = first.stack?.endsWith(\"\\n\");\n\n\n // Add a reference to this function itself so that we know that stacktraces were concatenated\n // If you are coming here from a stacktrace, please know that the two parts before and after this line are different\n // stacktraces that were concatenated with concatStacktraces\n const separator = removeStacktraceNameLine(new Error().stack ?? \"\").split(\"\\n\")[0];\n\n\n for (const error of errors) {\n const toAppend = removeStacktraceNameLine(error.stack ?? \"\");\n first.stack += (addsEmptyLineAtEnd ? \"\" : \"\\n\") + separator + \"\\n\" + toAppend;\n }\n}\n\n\nexport class StackAssertionError extends Error {\n constructor(message: string, public readonly extraData?: Record<string, any> & ErrorOptions) {\n const disclaimer = `\\n\\nThis is likely an error in Stack. Please make sure you are running the newest version and report it.`;\n super(`${message}${message.endsWith(disclaimer) ? \"\" : disclaimer}`, pick(extraData ?? {}, [\"cause\"]));\n\n Object.defineProperty(this, \"customCaptureExtraArgs\", {\n get() {\n return [this.extraData];\n },\n enumerable: false,\n });\n\n if (process.env.NEXT_PUBLIC_STACK_DEBUGGER_ON_ASSERTION_ERROR === \"true\") {\n debugger;\n }\n }\n}\nStackAssertionError.prototype.name = \"StackAssertionError\";\n\n\nexport function errorToNiceString(error: unknown): string {\n if (!(error instanceof Error)) return `${typeof error}<${nicify(error)}>`;\n return nicify(error, { maxDepth: 8 });\n}\n\n\nconst errorSinks = new Set<(location: string, error: unknown, ...extraArgs: unknown[]) => void>();\nexport function registerErrorSink(sink: (location: string, error: unknown) => void): void {\n if (errorSinks.has(sink)) {\n return;\n }\n errorSinks.add(sink);\n}\nregisterErrorSink((location, error, ...extraArgs) => {\n console.error(\n `\\x1b[41mCaptured error in ${location}:`,\n // HACK: Log a nicified version of the error to get around buggy Next.js pretty-printing\n // https://www.reddit.com/r/nextjs/comments/1gkxdqe/comment/m19kxgn/?utm_source=share&utm_medium=web3x&utm_name=web3xcss&utm_term=1&utm_content=share_button\n errorToNiceString(error),\n ...extraArgs,\n \"\\x1b[0m\",\n );\n});\nregisterErrorSink((location, error, ...extraArgs) => {\n globalVar.stackCapturedErrors = globalVar.stackCapturedErrors ?? [];\n globalVar.stackCapturedErrors.push({ location, error, extraArgs });\n});\n\n/**\n * Captures an error and sends it to the error sinks (most notably, Sentry). Errors caught with captureError are\n * supposed to be seen by an engineer, so they should be actionable and important.\n *\n * The location string is a machine-readable ID, and should hence not contain spaces or anything like that. Good\n * examples are: \"api-route-handler\", \"renderPart()\", etc.\n *\n * Errors that bubble up to the top of runAsynchronously or a route handler are already captured with captureError.\n */\nexport function captureError(location: string, error: unknown): void {\n for (const sink of errorSinks) {\n sink(\n location,\n error,\n ...error && (typeof error === 'object' || typeof error === 'function') && \"customCaptureExtraArgs\" in error && Array.isArray(error.customCaptureExtraArgs) ? (error.customCaptureExtraArgs as any[]) : [],\n );\n }\n}\n\n\ntype Status = {\n statusCode: number,\n message: string,\n};\n\ntype StatusErrorConstructorParameters =\n| [\n status: Status,\n message?: string\n]\n| [\n statusCode: number | Status,\n message: string,\n];\n\nexport class StatusError extends Error {\n private readonly __stackStatusErrorBrand = \"stack-status-error-brand-sentinel\" as const;\n public name = \"StatusError\";\n public readonly statusCode: number;\n\n public static BadRequest = { statusCode: 400, message: \"Bad Request\" };\n public static Unauthorized = { statusCode: 401, message: \"Unauthorized\" };\n public static PaymentRequired = { statusCode: 402, message: \"Payment Required\" };\n public static Forbidden = { statusCode: 403, message: \"Forbidden\" };\n public static NotFound = { statusCode: 404, message: \"Not Found\" };\n public static MethodNotAllowed = { statusCode: 405, message: \"Method Not Allowed\" };\n public static NotAcceptable = { statusCode: 406, message: \"Not Acceptable\" };\n public static ProxyAuthenticationRequired = { statusCode: 407, message: \"Proxy Authentication Required\" };\n public static RequestTimeout = { statusCode: 408, message: \"Request Timeout\" };\n public static Conflict = { statusCode: 409, message: \"Conflict\" };\n public static Gone = { statusCode: 410, message: \"Gone\" };\n public static LengthRequired = { statusCode: 411, message: \"Length Required\" };\n public static PreconditionFailed = { statusCode: 412, message: \"Precondition Failed\" };\n public static PayloadTooLarge = { statusCode: 413, message: \"Payload Too Large\" };\n public static URITooLong = { statusCode: 414, message: \"URI Too Long\" };\n public static UnsupportedMediaType = { statusCode: 415, message: \"Unsupported Media Type\" };\n public static RangeNotSatisfiable = { statusCode: 416, message: \"Range Not Satisfiable\" };\n public static ExpectationFailed = { statusCode: 417, message: \"Expectation Failed\" };\n public static ImATeapot = { statusCode: 418, message: \"I'm a teapot\" };\n public static MisdirectedRequest = { statusCode: 421, message: \"Misdirected Request\" };\n public static UnprocessableEntity = { statusCode: 422, message: \"Unprocessable Entity\" };\n public static Locked = { statusCode: 423, message: \"Locked\" };\n public static FailedDependency = { statusCode: 424, message: \"Failed Dependency\" };\n public static TooEarly = { statusCode: 425, message: \"Too Early\" };\n public static UpgradeRequired = { statusCode: 426, message: \"Upgrade Required\" };\n public static PreconditionRequired = { statusCode: 428, message: \"Precondition Required\" };\n public static TooManyRequests = { statusCode: 429, message: \"Too Many Requests\" };\n public static RequestHeaderFieldsTooLarge = { statusCode: 431, message: \"Request Header Fields Too Large\" };\n public static UnavailableForLegalReasons = { statusCode: 451, message: \"Unavailable For Legal Reasons\" };\n\n public static InternalServerError = { statusCode: 500, message: \"Internal Server Error\" };\n public static NotImplemented = { statusCode: 501, message: \"Not Implemented\" };\n public static BadGateway = { statusCode: 502, message: \"Bad Gateway\" };\n public static ServiceUnavailable = { statusCode: 503, message: \"Service Unavailable\" };\n public static GatewayTimeout = { statusCode: 504, message: \"Gateway Timeout\" };\n public static HTTPVersionNotSupported = { statusCode: 505, message: \"HTTP Version Not Supported\" };\n public static VariantAlsoNegotiates = { statusCode: 506, message: \"Variant Also Negotiates\" };\n public static InsufficientStorage = { statusCode: 507, message: \"Insufficient Storage\" };\n public static LoopDetected = { statusCode: 508, message: \"Loop Detected\" };\n public static NotExtended = { statusCode: 510, message: \"Not Extended\" };\n public static NetworkAuthenticationRequired = { statusCode: 511, message: \"Network Authentication Required\" };\n\n\n constructor(...args: StatusErrorConstructorParameters);\n constructor(\n status: number | Status,\n message?: string,\n ) {\n if (typeof status === \"object\") {\n message ??= status.message;\n status = status.statusCode;\n }\n super(message);\n this.statusCode = status;\n if (!message) {\n throw new StackAssertionError(\"StatusError always requires a message unless a Status object is passed\", { cause: this });\n }\n }\n\n public static isStatusError(error: unknown): error is StatusError {\n // like instanceof, but also works for errors thrown in other realms or by different versions of the same package\n return typeof error === \"object\" && error !== null && \"__stackStatusErrorBrand\" in error && error.__stackStatusErrorBrand === \"stack-status-error-brand-sentinel\";\n }\n\n public isClientError() {\n return this.statusCode >= 400 && this.statusCode < 500;\n }\n\n public isServerError() {\n return !this.isClientError();\n }\n\n public getStatusCode(): number {\n return this.statusCode;\n }\n\n public getBody(): Uint8Array {\n return new TextEncoder().encode(this.message);\n }\n\n public getHeaders(): Record<string, string[]> {\n return {\n \"Content-Type\": [\"text/plain; charset=utf-8\"],\n };\n }\n\n public toDescriptiveJson(): Json {\n return {\n status_code: this.getStatusCode(),\n message: this.message,\n headers: this.getHeaders(),\n };\n }\n\n /**\n * @deprecated this is not a good way to make status errors human-readable, use toDescriptiveJson instead\n */\n public toHttpJson(): Json {\n return {\n status_code: this.statusCode,\n body: this.message,\n headers: this.getHeaders(),\n };\n }\n}\nStatusError.prototype.name = \"StatusError\";\n", "function r(e){var t,f,n=\"\";if(\"string\"==typeof e||\"number\"==typeof e)n+=e;else if(\"object\"==typeof e)if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(f=r(e[t]))&&(n&&(n+=\" \"),n+=f)}else for(f in e)e[f]&&(n&&(n+=\" \"),n+=f);return n}export function clsx(){for(var e,t,f=0,n=\"\",o=arguments.length;f<o;f++)(e=arguments[f])&&(t=r(e))&&(n&&(n+=\" \"),n+=t);return n}export default clsx;", "import {\n ClassGroup,\n ClassValidator,\n Config,\n GenericClassGroupIds,\n GenericConfig,\n GenericThemeGroupIds,\n ThemeGetter,\n ThemeObject,\n} from './types'\n\nexport interface ClassPartObject {\n nextPart: Map<string, ClassPartObject>\n validators: ClassValidatorObject[]\n classGroupId?: GenericClassGroupIds\n}\n\ninterface ClassValidatorObject {\n classGroupId: GenericClassGroupIds\n validator: ClassValidator\n}\n\nconst CLASS_PART_SEPARATOR = '-'\n\nexport const createClassGroupUtils = (config: GenericConfig) => {\n const classMap = createClassMap(config)\n const { conflictingClassGroups, conflictingClassGroupModifiers } = config\n\n const getClassGroupId = (className: string) => {\n const classParts = className.split(CLASS_PART_SEPARATOR)\n\n // Classes like `-inset-1` produce an empty string as first classPart. We assume that classes for negative values are used correctly and remove it from classParts.\n if (classParts[0] === '' && classParts.length !== 1) {\n classParts.shift()\n }\n\n return getGroupRecursive(classParts, classMap) || getGroupIdForArbitraryProperty(className)\n }\n\n const getConflictingClassGroupIds = (\n classGroupId: GenericClassGroupIds,\n hasPostfixModifier: boolean,\n ) => {\n const conflicts = conflictingClassGroups[classGroupId] || []\n\n if (hasPostfixModifier && conflictingClassGroupModifiers[classGroupId]) {\n return [...conflicts, ...conflictingClassGroupModifiers[classGroupId]!]\n }\n\n return conflicts\n }\n\n return {\n getClassGroupId,\n getConflictingClassGroupIds,\n }\n}\n\nconst getGroupRecursive = (\n classParts: string[],\n classPartObject: ClassPartObject,\n): GenericClassGroupIds | undefined => {\n if (classParts.length === 0) {\n return classPartObject.classGroupId\n }\n\n const currentClassPart = classParts[0]!\n const nextClassPartObject = classPartObject.nextPart.get(currentClassPart)\n const classGroupFromNextClassPart = nextClassPartObject\n ? getGroupRecursive(classParts.slice(1), nextClassPartObject)\n : undefined\n\n if (classGroupFromNextClassPart) {\n return classGroupFromNextClassPart\n }\n\n if (classPartObject.validators.length === 0) {\n return undefined\n }\n\n const classRest = classParts.join(CLASS_PART_SEPARATOR)\n\n return classPartObject.validators.find(({ validator }) => validator(classRest))?.classGroupId\n}\n\nconst arbitraryPropertyRegex = /^\\[(.+)\\]$/\n\nconst getGroupIdForArbitraryProperty = (className: string) => {\n if (arbitraryPropertyRegex.test(className)) {\n const arbitraryPropertyClassName = arbitraryPropertyRegex.exec(className)![1]\n const property = arbitraryPropertyClassName?.substring(\n 0,\n arbitraryPropertyClassName.indexOf(':'),\n )\n\n if (property) {\n // I use two dots here because one dot is used as prefix for class groups in plugins\n return 'arbitrary..' + property\n }\n }\n}\n\n/**\n * Exported for testing only\n */\nexport const createClassMap = (config: Config<GenericClassGroupIds, GenericThemeGroupIds>) => {\n const { theme, prefix } = config\n const classMap: ClassPartObject = {\n nextPart: new Map<string, ClassPartObject>(),\n validators: [],\n }\n\n const prefixedClassGroupEntries = getPrefixedClassGroupEntries(\n Object.entries(config.classGroups),\n prefix,\n )\n\n prefixedClassGroupEntries.forEach(([classGroupId, classGroup]) => {\n processClassesRecursively(classGroup, classMap, classGroupId, theme)\n })\n\n return classMap\n}\n\nconst processClassesRecursively = (\n classGroup: ClassGroup<GenericThemeGroupIds>,\n classPartObject: ClassPartObject,\n classGroupId: GenericClassGroupIds,\n theme: ThemeObject<GenericThemeGroupIds>,\n) => {\n classGroup.forEach((classDefinition) => {\n if (typeof classDefinition === 'string') {\n const classPartObjectToEdit =\n classDefinition === '' ? classPartObject : getPart(classPartObject, classDefinition)\n classPartObjectToEdit.classGroupId = classGroupId\n return\n }\n\n if (typeof classDefinition === 'function') {\n if (isThemeGetter(classDefinition)) {\n processClassesRecursively(\n classDefinition(theme),\n classPartObject,\n classGroupId,\n theme,\n )\n return\n }\n\n classPartObject.validators.push({\n validator: classDefinition,\n classGroupId,\n })\n\n return\n }\n\n Object.entries(classDefinition).forEach(([key, classGroup]) => {\n processClassesRecursively(\n classGroup,\n getPart(classPartObject, key),\n classGroupId,\n theme,\n )\n })\n })\n}\n\nconst getPart = (classPartObject: ClassPartObject, path: string) => {\n let currentClassPartObject = classPartObject\n\n path.split(CLASS_PART_SEPARATOR).forEach((pathPart) => {\n if (!currentClassPartObject.nextPart.has(pathPart)) {\n currentClassPartObject.nextPart.set(pathPart, {\n nextPart: new Map(),\n validators: [],\n })\n }\n\n currentClassPartObject = currentClassPartObject.nextPart.get(pathPart)!\n })\n\n return currentClassPartObject\n}\n\nconst isThemeGetter = (func: ClassValidator | ThemeGetter): func is ThemeGetter =>\n (func as ThemeGetter).isThemeGetter\n\nconst getPrefixedClassGroupEntries = (\n classGroupEntries: Array<[classGroupId: string, classGroup: ClassGroup<GenericThemeGroupIds>]>,\n prefix: string | undefined,\n): Array<[classGroupId: string, classGroup: ClassGroup<GenericThemeGroupIds>]> => {\n if (!prefix) {\n return classGroupEntries\n }\n\n return classGroupEntries.map(([classGroupId, classGroup]) => {\n const prefixedClassGroup = classGroup.map((classDefinition) => {\n if (typeof classDefinition === 'string') {\n return prefix + classDefinition\n }\n\n if (typeof classDefinition === 'object') {\n return Object.fromEntries(\n Object.entries(classDefinition).map(([key, value]) => [prefix + key, value]),\n )\n }\n\n return classDefinition\n })\n\n return [classGroupId, prefixedClassGroup]\n })\n}\n", "// Export is needed because TypeScript complains about an error otherwise:\n// Error: \u2026/tailwind-merge/src/config-utils.ts(8,17): semantic error TS4058: Return type of exported function has or is using name 'LruCache' from external module \"\u2026/tailwind-merge/src/lru-cache\" but cannot be named.\nexport interface LruCache<Key, Value> {\n get(key: Key): Value | undefined\n set(key: Key, value: Value): void\n}\n\n// LRU cache inspired from hashlru (https://github.com/dominictarr/hashlru/blob/v1.0.4/index.js) but object replaced with Map to improve performance\nexport const createLruCache = <Key, Value>(maxCacheSize: number): LruCache<Key, Value> => {\n if (maxCacheSize < 1) {\n return {\n get: () => undefined,\n set: () => {},\n }\n }\n\n let cacheSize = 0\n let cache = new Map<Key, Value>()\n let previousCache = new Map<Key, Value>()\n\n const update = (key: Key, value: Value) => {\n cache.set(key, value)\n cacheSize++\n\n if (cacheSize > maxCacheSize) {\n cacheSize = 0\n previousCache = cache\n cache = new Map()\n }\n }\n\n return {\n get(key) {\n let value = cache.get(key)\n\n if (value !== undefined) {\n return value\n }\n if ((value = previousCache.get(key)) !== undefined) {\n update(key, value)\n return value\n }\n },\n set(key, value) {\n if (cache.has(key)) {\n cache.set(key, value)\n } else {\n update(key, value)\n }\n },\n }\n}\n", "import { GenericConfig } from './types'\n\nexport const IMPORTANT_MODIFIER = '!'\n\nexport const createParseClassName = (config: GenericConfig) => {\n const { separator, experimentalParseClassName } = config\n const isSeparatorSingleCharacter = separator.length === 1\n const firstSeparatorCharacter = separator[0]\n const separatorLength = separator.length\n\n // parseClassName inspired by https://github.com/tailwindlabs/tailwindcss/blob/v3.2.2/src/util/splitAtTopLevelOnly.js\n const parseClassName = (className: string) => {\n const modifiers = []\n\n let bracketDepth = 0\n let modifierStart = 0\n let postfixModifierPosition: number | undefined\n\n for (let index = 0; index < className.length; index++) {\n let currentCharacter = className[index]\n\n if (bracketDepth === 0) {\n if (\n currentCharacter === firstSeparatorCharacter &&\n (isSeparatorSingleCharacter ||\n className.slice(index, index + separatorLength) === separator)\n ) {\n modifiers.push(className.slice(modifierStart, index))\n modifierStart = index + separatorLength\n continue\n }\n\n if (currentCharacter === '/') {\n postfixModifierPosition = index\n continue\n }\n }\n\n if (currentCharacter === '[') {\n bracketDepth++\n } else if (currentCharacter === ']') {\n bracketDepth--\n }\n }\n\n const baseClassNameWithImportantModifier =\n modifiers.length === 0 ? className : className.substring(modifierStart)\n const hasImportantModifier =\n baseClassNameWithImportantModifier.startsWith(IMPORTANT_MODIFIER)\n const baseClassName = hasImportantModifier\n ? baseClassNameWithImportantModifier.substring(1)\n : baseClassNameWithImportantModifier\n\n const maybePostfixModifierPosition =\n postfixModifierPosition && postfixModifierPosition > modifierStart\n ? postfixModifierPosition - modifierStart\n : undefined\n\n return {\n modifiers,\n hasImportantModifier,\n baseClassName,\n maybePostfixModifierPosition,\n }\n }\n\n if (experimentalParseClassName) {\n return (className: string) => experimentalParseClassName({ className, parseClassName })\n }\n\n return parseClassName\n}\n\n/**\n * Sorts modifiers according to following schema:\n * - Predefined modifiers are sorted alphabetically\n * - When an arbitrary variant appears, it must be preserved which modifiers are before and after it\n */\nexport const sortModifiers = (modifiers: string[]) => {\n if (modifiers.length <= 1) {\n return modifiers\n }\n\n const sortedModifiers: string[] = []\n let unsortedModifiers: string[] = []\n\n modifiers.forEach((modifier) => {\n const isArbitraryVariant = modifier[0] === '['\n\n if (isArbitraryVariant) {\n sortedModifiers.push(...unsortedModifiers.sort(), modifier)\n unsortedModifiers = []\n } else {\n unsortedModifiers.push(modifier)\n }\n })\n\n sortedModifiers.push(...unsortedModifiers.sort())\n\n return sortedModifiers\n}\n", "import { createClassGroupUtils } from './class-group-utils'\nimport { createLruCache } from './lru-cache'\nimport { createParseClassName } from './parse-class-name'\nimport { GenericConfig } from './types'\n\nexport type ConfigUtils = ReturnType<typeof createConfigUtils>\n\nexport const createConfigUtils = (config: GenericConfig) => ({\n cache: createLruCache<string, string>(config.cacheSize),\n parseClassName: createParseClassName(config),\n ...createClassGroupUtils(config),\n})\n", "import { ConfigUtils } from './config-utils'\nimport { IMPORTANT_MODIFIER, sortModifiers } from './parse-class-name'\n\nconst SPLIT_CLASSES_REGEX = /\\s+/\n\nexport const mergeClassList = (classList: string, configUtils: ConfigUtils) => {\n const { parseClassName, getClassGroupId, getConflictingClassGroupIds } = configUtils\n\n /**\n * Set of classGroupIds in following format:\n * `{importantModifier}{variantModifiers}{classGroupId}`\n * @example 'float'\n * @example 'hover:focus:bg-color'\n * @example 'md:!pr'\n */\n const classGroupsInConflict: string[] = []\n const classNames = classList.trim().split(SPLIT_CLASSES_REGEX)\n\n let result = ''\n\n for (let index = classNames.length - 1; index >= 0; index -= 1) {\n const originalClassName = classNames[index]!\n\n const { modifiers, hasImportantModifier, baseClassName, maybePostfixModifierPosition } =\n parseClassName(originalClassName)\n\n let hasPostfixModifier = Boolean(maybePostfixModifierPosition)\n let classGroupId = getClassGroupId(\n hasPostfixModifier\n ? baseClassName.substring(0, maybePostfixModifierPosition)\n : baseClassName,\n )\n\n if (!classGroupId) {\n if (!hasPostfixModifier) {\n // Not a Tailwind class\n result = originalClassName + (result.length > 0 ? ' ' + result : result)\n continue\n }\n\n classGroupId = getClassGroupId(baseClassName)\n\n if (!classGroupId) {\n // Not a Tailwind class\n result = originalClassName + (result.length > 0 ? ' ' + result : result)\n continue\n }\n\n hasPostfixModifier = false\n }\n\n const variantModifier = sortModifiers(modifiers).join(':')\n\n const modifierId = hasImportantModifier\n ? variantModifier + IMPORTANT_MODIFIER\n : variantModifier\n\n const classId = modifierId + classGroupId\n\n if (classGroupsInConflict.includes(classId)) {\n // Tailwind class omitted due to conflict\n continue\n }\n\n classGroupsInConflict.push(classId)\n\n const conflictGroups = getConflictingClassGroupIds(classGroupId, hasPostfixModifier)\n for (let i = 0; i < conflictGroups.length; ++i) {\n const group = conflictGroups[i]!\n classGroupsInConflict.push(modifierId + group)\n }\n\n // Tailwind class not in conflict\n result = originalClassName + (result.length > 0 ? ' ' + result : result)\n }\n\n return result\n}\n", "/**\n * The code in this file is copied from https://github.com/lukeed/clsx and modified to suit the needs of tailwind-merge better.\n *\n * Specifically:\n * - Runtime code from https://github.com/lukeed/clsx/blob/v1.2.1/src/index.js\n * - TypeScript types from https://github.com/lukeed/clsx/blob/v1.2.1/clsx.d.ts\n *\n * Original code has MIT license: Copyright (c) Luke Edwards <luke.edwards05@gmail.com> (lukeed.com)\n */\n\nexport type ClassNameValue = ClassNameArray | string | null | undefined | 0 | 0n | false\ntype ClassNameArray = ClassNameValue[]\n\nexport function twJoin(...classLists: ClassNameValue[]): string\nexport function twJoin() {\n let index = 0\n let argument: ClassNameValue\n let resolvedValue: string\n let string = ''\n\n while (index < arguments.length) {\n if ((argument = arguments[index++])) {\n if ((resolvedValue = toValue(argument))) {\n string && (string += ' ')\n string += resolvedValue\n }\n }\n }\n return string\n}\n\nconst toValue = (mix: ClassNameArray | string) => {\n if (typeof mix === 'string') {\n return mix\n }\n\n let resolvedValue: string\n let string = ''\n\n for (let k = 0; k < mix.length; k++) {\n if (mix[k]) {\n if ((resolvedValue = toValue(mix[k] as ClassNameArray | string))) {\n string && (string += ' ')\n string += resolvedValue\n }\n }\n }\n\n return string\n}\n", "import { createConfigUtils } from './config-utils'\nimport { mergeClassList } from './merge-classlist'\nimport { ClassNameValue, twJoin } from './tw-join'\nimport { GenericConfig } from './types'\n\ntype CreateConfigFirst = () => GenericConfig\ntype CreateConfigSubsequent = (config: GenericConfig) => GenericConfig\ntype TailwindMerge = (...classLists: ClassNameValue[]) => string\ntype ConfigUtils = ReturnType<typeof createConfigUtils>\n\nexport function createTailwindMerge(\n createConfigFirst: CreateConfigFirst,\n ...createConfigRest: CreateConfigSubsequent[]\n): TailwindMerge {\n let configUtils: ConfigUtils\n let cacheGet: ConfigUtils['cache']['get']\n let cacheSet: ConfigUtils['cache']['set']\n let functionToCall = initTailwindMerge\n\n function initTailwindMerge(classList: string) {\n const config = createConfigRest.reduce(\n (previousConfig, createConfigCurrent) => createConfigCurrent(previousConfig),\n createConfigFirst() as GenericConfig,\n )\n\n configUtils = createConfigUtils(config)\n cacheGet = configUtils.cache.get\n cacheSet = configUtils.cache.set\n functionToCall = tailwindMerge\n\n return tailwindMerge(classList)\n }\n\n function tailwindMerge(classList: string) {\n const cachedResult = cacheGet(classList)\n\n if (cachedResult) {\n return cachedResult\n }\n\n const result = mergeClassList(classList, configUtils)\n cacheSet(classList, result)\n\n return result\n }\n\n return function callTailwindMerge() {\n return functionToCall(twJoin.apply(null, arguments as any))\n }\n}\n", "import { DefaultThemeGroupIds, NoInfer, ThemeGetter, ThemeObject } from './types'\n\nexport const fromTheme = <\n AdditionalThemeGroupIds extends string = never,\n DefaultThemeGroupIdsInner extends string = DefaultThemeGroupIds,\n>(key: NoInfer<DefaultThemeGroupIdsInner | AdditionalThemeGroupIds>): ThemeGetter => {\n const themeGetter = (theme: ThemeObject<DefaultThemeGroupIdsInner | AdditionalThemeGroupIds>) =>\n theme[key] || []\n\n themeGetter.isThemeGetter = true as const\n\n return themeGetter\n}\n", "const arbitraryValueRegex = /^\\[(?:([a-z-]+):)?(.+)\\]$/i\nconst fractionRegex = /^\\d+\\/\\d+$/\nconst stringLengths = new Set(['px', 'full', 'screen'])\nconst tshirtUnitRegex = /^(\\d+(\\.\\d+)?)?(xs|sm|md|lg|xl)$/\nconst lengthUnitRegex =\n /\\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\\b(calc|min|max|clamp)\\(.+\\)|^0$/\nconst colorFunctionRegex = /^(rgba?|hsla?|hwb|(ok)?(lab|lch))\\(.+\\)$/\n// Shadow always begins with x and y offset separated by underscore optionally prepended by inset\nconst shadowRegex = /^(inset_)?-?((\\d+)?\\.?(\\d+)[a-z]+|0)_-?((\\d+)?\\.?(\\d+)[a-z]+|0)/\nconst imageRegex =\n /^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\\(.+\\)$/\n\nexport const isLength = (value: string) =>\n isNumber(value) || stringLengths.has(value) || fractionRegex.test(value)\n\nexport const isArbitraryLength = (value: string) =>\n getIsArbitraryValue(value, 'length', isLengthOnly)\n\nexport const isNumber = (value: string) => Boolean(value) && !Number.isNaN(Number(value))\n\nexport const isArbitraryNumber = (value: string) => getIsArbitraryValue(value, 'number', isNumber)\n\nexport const isInteger = (value: string) => Boolean(value) && Number.isInteger(Number(value))\n\nexport const isPercent = (value: string) => value.endsWith('%') && isNumber(value.slice(0, -1))\n\nexport const isArbitraryValue = (value: string) => arbitraryValueRegex.test(value)\n\nexport const isTshirtSize = (value: string) => tshirtUnitRegex.test(value)\n\nconst sizeLabels = new Set(['length', 'size', 'percentage'])\n\nexport const isArbitrarySize = (value: string) => getIsArbitraryValue(value, sizeLabels, isNever)\n\nexport const isArbitraryPosition = (value: string) =>\n getIsArbitraryValue(value, 'position', isNever)\n\nconst imageLabels = new Set(['image', 'url'])\n\nexport const isArbitraryImage = (value: string) => getIsArbitraryValue(value, imageLabels, isImage)\n\nexport const isArbitraryShadow = (value: string) => getIsArbitraryValue(value, '', isShadow)\n\nexport const isAny = () => true\n\nconst getIsArbitraryValue = (\n value: string,\n label: string | Set<string>,\n testValue: (value: string) => boolean,\n) => {\n const result = arbitraryValueRegex.exec(value)\n\n if (result) {\n if (result[1]) {\n return typeof label === 'string' ? result[1] === label : label.has(result[1])\n }\n\n return testValue(result[2]!)\n }\n\n return false\n}\n\nconst isLengthOnly = (value: string) =>\n // `colorFunctionRegex` check is necessary because color functions can have percentages in them which which would be incorrectly classified as lengths.\n // For example, `hsl(0 0% 0%)` would be classified as a length without this check.\n // I could also use lookbehind assertion in `lengthUnitRegex` but that isn't supported widely enough.\n lengthUnitRegex.test(value) && !colorFunctionRegex.test(value)\n\nconst isNever = () => false\n\nconst isShadow = (value: string) => shadowRegex.test(value)\n\nconst isImage = (value: string) => imageRegex.test(value)\n", "import { fromTheme } from './from-theme'\nimport { Config, DefaultClassGroupIds, DefaultThemeGroupIds } from './types'\nimport {\n isAny,\n isArbitraryImage,\n isArbitraryLength,\n isArbitraryNumber,\n isArbitraryPosition,\n isArbitraryShadow,\n isArbitrarySize,\n isArbitraryValue,\n isInteger,\n isLength,\n isNumber,\n isPercent,\n isTshirtSize,\n} from './validators'\n\nexport const getDefaultConfig = () => {\n const colors = fromTheme('colors')\n const spacing = fromTheme('spacing')\n const blur = fromTheme('blur')\n const brightness = fromTheme('brightness')\n const borderColor = fromTheme('borderColor')\n const borderRadius = fromTheme('borderRadius')\n const borderSpacing = fromTheme('borderSpacing')\n const borderWidth = fromTheme('borderWidth')\n const contrast = fromTheme('contrast')\n const grayscale = fromTheme('grayscale')\n const hueRotate = fromTheme('hueRotate')\n const invert = fromTheme('invert')\n const gap = fromTheme('gap')\n const gradientColorStops = fromTheme('gradientColorStops')\n const gradientColorStopPositions = fromTheme('gradientColorStopPositions')\n const inset = fromTheme('inset')\n const margin = fromTheme('margin')\n const opacity = fromTheme('opacity')\n const padding = fromTheme('padding')\n const saturate = fromTheme('saturate')\n const scale = fromTheme('scale')\n const sepia = fromTheme('sepia')\n const skew = fromTheme('skew')\n const space = fromTheme('space')\n const translate = fromTheme('translate')\n\n const getOverscroll = () => ['auto', 'contain', 'none'] as const\n const getOverflow = () => ['auto', 'hidden', 'clip', 'visible', 'scroll'] as const\n const getSpacingWithAutoAndArbitrary = () => ['auto', isArbitraryValue, spacing] as const\n const getSpacingWithArbitrary = () => [isArbitraryValue, spacing] as const\n const getLengthWithEmptyAndArbitrary = () => ['', isLength, isArbitraryLength] as const\n const getNumberWithAutoAndArbitrary = () => ['auto', isNumber, isArbitraryValue] as const\n const getPositions = () =>\n [\n 'bottom',\n 'center',\n 'left',\n 'left-bottom',\n 'left-top',\n 'right',\n 'right-bottom',\n 'right-top',\n 'top',\n ] as const\n const getLineStyles = () => ['solid', 'dashed', 'dotted', 'double', 'none'] as const\n const getBlendModes = () =>\n [\n 'normal',\n 'multiply',\n 'screen',\n 'overlay',\n 'darken',\n 'lighten',\n 'color-dodge',\n 'color-burn',\n 'hard-light',\n 'soft-light',\n 'difference',\n 'exclusion',\n 'hue',\n 'saturation',\n 'color',\n 'luminosity',\n ] as const\n const getAlign = () =>\n ['start', 'end', 'center', 'between', 'around', 'evenly', 'stretch'] as const\n const getZeroAndEmpty = () => ['', '0', isArbitraryValue] as const\n const getBreaks = () =>\n ['auto', 'avoid', 'all', 'avoid-page', 'page', 'left', 'right', 'column'] as const\n const getNumberAndArbitrary = () => [isNumber, isArbitraryValue]\n\n return {\n cacheSize: 500,\n separator: ':',\n theme: {\n colors: [isAny],\n spacing: [isLength, isArbitraryLength],\n blur: ['none', '', isTshirtSize, isArbitraryValue],\n brightness: getNumberAndArbitrary(),\n borderColor: [colors],\n borderRadius: ['none', '', 'full', isTshirtSize, isArbitraryValue],\n borderSpacing: getSpacingWithArbitrary(),\n borderWidth: getLengthWithEmptyAndArbitrary(),\n contrast: getNumberAndArbitrary(),\n grayscale: getZeroAndEmpty(),\n hueRotate: getNumberAndArbitrary(),\n invert: getZeroAndEmpty(),\n gap: getSpacingWithArbitrary(),\n gradientColorStops: [colors],\n gradientColorStopPositions: [isPercent, isArbitraryLength],\n inset: getSpacingWithAutoAndArbitrary(),\n margin: getSpacingWithAutoAndArbitrary(),\n opacity: getNumberAndArbitrary(),\n padding: getSpacingWithArbitrary(),\n saturate: getNumberAndArbitrary(),\n scale: getNumberAndArbitrary(),\n sepia: getZeroAndEmpty(),\n skew: getNumberAndArbitrary(),\n space: getSpacingWithArbitrary(),\n translate: getSpacingWithArbitrary(),\n },\n classGroups: {\n // Layout\n /**\n * Aspect Ratio\n * @see https://tailwindcss.com/docs/aspect-ratio\n */\n aspect: [{ aspect: ['auto', 'square', 'video', isArbitraryValue] }],\n /**\n * Container\n * @see https://tailwindcss.com/docs/container\n */\n container: ['container'],\n /**\n * Columns\n * @see https://tailwindcss.com/docs/columns\n */\n columns: [{ columns: [isTshirtSize] }],\n /**\n * Break After\n * @see https://tailwindcss.com/docs/break-after\n */\n 'break-after': [{ 'break-after': getBreaks() }],\n /**\n * Break Before\n * @see https://tailwindcss.com/docs/break-before\n */\n 'break-before': [{ 'break-before': getBreaks() }],\n /**\n * Break Inside\n * @see https://tailwindcss.com/docs/break-inside\n */\n 'break-inside': [{ 'break-inside': ['auto', 'avoid', 'avoid-page', 'avoid-column'] }],\n /**\n * Box Decoration Break\n * @see https://tailwindcss.com/docs/box-decoration-break\n */\n 'box-decoration': [{ 'box-decoration': ['slice', 'clone'] }],\n /**\n * Box Sizing\n * @see https://tailwindcss.com/docs/box-sizing\n */\n box: [{ box: ['border', 'content'] }],\n /**\n * Display\n * @see https://tailwindcss.com/docs/display\n */\n display: [\n 'block',\n 'inline-block',\n 'inline',\n 'flex',\n 'inline-flex',\n 'table',\n 'inline-table',\n 'table-caption',\n 'table-cell',\n 'table-column',\n 'table-column-group',\n 'table-footer-group',\n 'table-header-group',\n 'table-row-group',\n 'table-row',\n 'flow-root',\n 'grid',\n 'inline-grid',\n 'contents',\n 'list-item',\n 'hidden',\n ],\n /**\n * Floats\n * @see https://tailwindcss.com/docs/float\n */\n float: [{ float: ['right', 'left', 'none', 'start', 'end'] }],\n /**\n * Clear\n * @see https://tailwindcss.com/docs/clear\n */\n clear: [{ clear: ['left', 'right', 'both', 'none', 'start', 'end'] }],\n /**\n * Isolation\n * @see https://tailwindcss.com/docs/isolation\n */\n isolation: ['isolate', 'isolation-auto'],\n /**\n * Object Fit\n * @see https://tailwindcss.com/docs/object-fit\n */\n 'object-fit': [{ object: ['contain', 'cover', 'fill', 'none', 'scale-down'] }],\n /**\n * Object Position\n * @see https://tailwindcss.com/docs/object-position\n */\n 'object-position': [{ object: [...getPositions(), isArbitraryValue] }],\n /**\n * Overflow\n * @see https://tailwindcss.com/docs/overflow\n */\n overflow: [{ overflow: getOverflow() }],\n /**\n * Overflow X\n * @see https://tailwindcss.com/docs/overflow\n */\n 'overflow-x': [{ 'overflow-x': getOverflow() }],\n /**\n * Overflow Y\n * @see https://tailwindcss.com/docs/overflow\n */\n 'overflow-y': [{ 'overflow-y': getOverflow() }],\n /**\n * Overscroll Behavior\n * @see https://tailwindcss.com/docs/overscroll-behavior\n */\n overscroll: [{ overscroll: getOverscroll() }],\n /**\n * Overscroll Behavior X\n * @see https://tailwindcss.com/docs/overscroll-behavior\n */\n 'overscroll-x': [{ 'overscroll-x': getOverscroll() }],\n /**\n * Overscroll Behavior Y\n * @see https://tailwindcss.com/docs/overscroll-behavior\n */\n 'overscroll-y': [{ 'overscroll-y': getOverscroll() }],\n /**\n * Position\n * @see https://tailwindcss.com/docs/position\n */\n position: ['static', 'fixed', 'absolute', 'relative', 'sticky'],\n /**\n * Top / Right / Bottom / Left\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n inset: [{ inset: [inset] }],\n /**\n * Right / Left\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n 'inset-x': [{ 'inset-x': [inset] }],\n /**\n * Top / Bottom\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n 'inset-y': [{ 'inset-y': [inset] }],\n /**\n * Start\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n start: [{ start: [inset] }],\n /**\n * End\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n end: [{ end: [inset] }],\n /**\n * Top\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n top: [{ top: [inset] }],\n /**\n * Right\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n right: [{ right: [inset] }],\n /**\n * Bottom\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n bottom: [{ bottom: [inset] }],\n /**\n * Left\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n left: [{ left: [inset] }],\n /**\n * Visibility\n * @see https://tailwindcss.com/docs/visibility\n */\n visibility: ['visible', 'invisible', 'collapse'],\n /**\n * Z-Index\n * @see https://tailwindcss.com/docs/z-index\n */\n z: [{ z: ['auto', isInteger, isArbitraryValue] }],\n // Flexbox and Grid\n /**\n * Flex Basis\n * @see https://tailwindcss.com/docs/flex-basis\n */\n basis: [{ basis: getSpacingWithAutoAndArbitrary() }],\n /**\n * Flex Direction\n * @see https://tailwindcss.com/docs/flex-direction\n */\n 'flex-direction': [{ flex: ['row', 'row-reverse', 'col', 'col-reverse'] }],\n /**\n * Flex Wrap\n * @see https://tailwindcss.com/docs/flex-wrap\n */\n 'flex-wrap': [{ flex: ['wrap', 'wrap-reverse', 'nowrap'] }],\n /**\n * Flex\n * @see https://tailwindcss.com/docs/flex\n */\n flex: [{ flex: ['1', 'auto', 'initial', 'none', isArbitraryValue] }],\n /**\n * Flex Grow\n * @see https://tailwindcss.com/docs/flex-grow\n */\n grow: [{ grow: getZeroAndEmpty() }],\n /**\n * Flex Shrink\n * @see https://tailwindcss.com/docs/flex-shrink\n */\n shrink: [{ shrink: getZeroAndEmpty() }],\n /**\n * Order\n * @see https://tailwindcss.com/docs/order\n */\n order: [{ order: ['first', 'last', 'none', isInteger, isArbitraryValue] }],\n /**\n * Grid Template Columns\n * @see https://tailwindcss.com/docs/grid-template-columns\n */\n 'grid-cols': [{ 'grid-cols': [isAny] }],\n /**\n * Grid Column Start / End\n * @see https://tailwindcss.com/docs/grid-column\n */\n 'col-start-end': [\n {\n col: [\n 'auto',\n { span: ['full', isInteger, isArbitraryValue] },\n isArbitraryValue,\n ],\n },\n ],\n /**\n * Grid Column Start\n * @see https://tailwindcss.com/docs/grid-column\n */\n 'col-start': [{ 'col-start': getNumberWithAutoAndArbitrary() }],\n /**\n * Grid Column End\n * @see https://tailwindcss.com/docs/grid-column\n */\n 'col-end': [{ 'col-end': getNumberWithAutoAndArbitrary() }],\n /**\n * Grid Template Rows\n * @see https://tailwindcss.com/docs/grid-template-rows\n */\n 'grid-rows': [{ 'grid-rows': [isAny] }],\n /**\n * Grid Row Start / End\n * @see https://tailwindcss.com/docs/grid-row\n */\n 'row-start-end': [\n { row: ['auto', { span: [isInteger, isArbitraryValue] }, isArbitraryValue] },\n ],\n /**\n * Grid Row Start\n * @see https://tailwindcss.com/docs/grid-row\n */\n 'row-start': [{ 'row-start': getNumberWithAutoAndArbitrary() }],\n /**\n * Grid Row End\n * @see https://tailwindcss.com/docs/grid-row\n */\n 'row-end': [{ 'row-end': getNumberWithAutoAndArbitrary() }],\n /**\n * Grid Auto Flow\n * @see https://tailwindcss.com/docs/grid-auto-flow\n */\n 'grid-flow': [{ 'grid-flow': ['row', 'col', 'dense', 'row-dense', 'col-dense'] }],\n /**\n * Grid Auto Columns\n * @see https://tailwindcss.com/docs/grid-auto-columns\n */\n 'auto-cols': [{ 'auto-cols': ['auto', 'min', 'max', 'fr', isArbitraryValue] }],\n /**\n * Grid Auto Rows\n * @see https://tailwindcss.com/docs/grid-auto-rows\n */\n 'auto-rows': [{ 'auto-rows': ['auto', 'min', 'max', 'fr', isArbitraryValue] }],\n /**\n * Gap\n * @see https://tailwindcss.com/docs/gap\n */\n gap: [{ gap: [gap] }],\n /**\n * Gap X\n * @see https://tailwindcss.com/docs/gap\n */\n 'gap-x': [{ 'gap-x': [gap] }],\n /**\n * Gap Y\n * @see https://tailwindcss.com/docs/gap\n */\n 'gap-y': [{ 'gap-y': [gap] }],\n /**\n * Justify Content\n * @see https://tailwindcss.com/docs/justify-content\n */\n 'justify-content': [{ justify: ['normal', ...getAlign()] }],\n /**\n * Justify Items\n * @see https://tailwindcss.com/docs/justify-items\n */\n 'justify-items': [{ 'justify-items': ['start', 'end', 'center', 'stretch'] }],\n /**\n * Justify Self\n * @see https://tailwindcss.com/docs/justify-self\n */\n 'justify-self': [{ 'justify-self': ['auto', 'start', 'end', 'center', 'stretch'] }],\n /**\n * Align Content\n * @see https://tailwindcss.com/docs/align-content\n */\n 'align-content': [{ content: ['normal', ...getAlign(), 'baseline'] }],\n /**\n * Align Items\n * @see https://tailwindcss.com/docs/align-items\n */\n 'align-items': [{ items: ['start', 'end', 'center', 'baseline', 'stretch'] }],\n /**\n * Align Self\n * @see https://tailwindcss.com/docs/align-self\n */\n 'align-self': [{ self: ['auto', 'start', 'end', 'center', 'stretch', 'baseline'] }],\n /**\n * Place Content\n * @see https://tailwindcss.com/docs/place-content\n */\n 'place-content': [{ 'place-content': [...getAlign(), 'baseline'] }],\n /**\n * Place Items\n * @see https://tailwindcss.com/docs/place-items\n */\n 'place-items': [{ 'place-items': ['start', 'end', 'center', 'baseline', 'stretch'] }],\n /**\n * Place Self\n * @see https://tailwindcss.com/docs/place-self\n */\n 'place-self': [{ 'place-self': ['auto', 'start', 'end', 'center', 'stretch'] }],\n // Spacing\n /**\n * Padding\n * @see https://tailwindcss.com/docs/padding\n */\n p: [{ p: [padding] }],\n /**\n * Padding X\n * @see https://tailwindcss.com/docs/padding\n */\n px: [{ px: [padding] }],\n /**\n * Padding Y\n * @see https://tailwindcss.com/docs/padding\n */\n py: [{ py: [padding] }],\n /**\n * Padding Start\n * @see https://tailwindcss.com/docs/padding\n */\n ps: [{ ps: [padding] }],\n /**\n * Padding End\n * @see https://tailwindcss.com/docs/padding\n */\n pe: [{ pe: [padding] }],\n /**\n * Padding Top\n * @see https://tailwindcss.com/docs/padding\n */\n pt: [{ pt: [padding] }],\n /**\n * Padding Right\n * @see https://tailwindcss.com/docs/padding\n */\n pr: [{ pr: [padding] }],\n /**\n * Padding Bottom\n * @see https://tailwindcss.com/docs/padding\n */\n pb: [{ pb: [padding] }],\n /**\n * Padding Left\n * @see https://tailwindcss.com/docs/padding\n */\n pl: [{ pl: [padding] }],\n /**\n * Margin\n * @see https://tailwindcss.com/docs/margin\n */\n m: [{ m: [margin] }],\n /**\n * Margin X\n * @see https://tailwindcss.com/docs/margin\n */\n mx: [{ mx: [margin] }],\n /**\n * Margin Y\n * @see https://tailwindcss.com/docs/margin\n */\n my: [{ my: [margin] }],\n /**\n * Margin Start\n * @see https://tailwindcss.com/docs/margin\n */\n ms: [{ ms: [margin] }],\n /**\n * Margin End\n * @see https://tailwindcss.com/docs/margin\n */\n me: [{ me: [margin] }],\n /**\n * Margin Top\n * @see https://tailwindcss.com/docs/margin\n */\n mt: [{ mt: [margin] }],\n /**\n * Margin Right\n * @see https://tailwindcss.com/docs/margin\n */\n mr: [{ mr: [margin] }],\n /**\n * Margin Bottom\n * @see https://tailwindcss.com/docs/margin\n */\n mb: [{ mb: [margin] }],\n /**\n * Margin Left\n * @see https://tailwindcss.com/docs/margin\n */\n ml: [{ ml: [margin] }],\n /**\n * Space Between X\n * @see https://tailwindcss.com/docs/space\n */\n 'space-x': [{ 'space-x': [space] }],\n /**\n * Space Between X Reverse\n * @see https://tailwindcss.com/docs/space\n */\n 'space-x-reverse': ['space-x-reverse'],\n /**\n * Space Between Y\n * @see https://tailwindcss.com/docs/space\n */\n 'space-y': [{ 'space-y': [space] }],\n /**\n * Space Between Y Reverse\n * @see https://tailwindcss.com/docs/space\n */\n 'space-y-reverse': ['space-y-reverse'],\n // Sizing\n /**\n * Width\n * @see https://tailwindcss.com/docs/width\n */\n w: [\n {\n w: [\n 'auto',\n 'min',\n 'max',\n 'fit',\n 'svw',\n 'lvw',\n 'dvw',\n isArbitraryValue,\n spacing,\n ],\n },\n ],\n /**\n * Min-Width\n * @see https://tailwindcss.com/docs/min-width\n */\n 'min-w': [{ 'min-w': [isArbitraryValue, spacing, 'min', 'max', 'fit'] }],\n /**\n * Max-Width\n * @see https://tailwindcss.com/docs/max-width\n */\n 'max-w': [\n {\n 'max-w': [\n isArbitraryValue,\n spacing,\n 'none',\n 'full',\n 'min',\n 'max',\n 'fit',\n 'prose',\n { screen: [isTshirtSize] },\n isTshirtSize,\n ],\n },\n ],\n /**\n * Height\n * @see https://tailwindcss.com/docs/height\n */\n h: [\n {\n h: [\n isArbitraryValue,\n spacing,\n 'auto',\n 'min',\n 'max',\n 'fit',\n 'svh',\n 'lvh',\n 'dvh',\n ],\n },\n ],\n /**\n * Min-Height\n * @see https://tailwindcss.com/docs/min-height\n */\n 'min-h': [\n { 'min-h': [isArbitraryValue, spacing, 'min', 'max', 'fit', 'svh', 'lvh', 'dvh'] },\n ],\n /**\n * Max-Height\n * @see https://tailwindcss.com/docs/max-height\n */\n 'max-h': [\n { 'max-h': [isArbitraryValue, spacing, 'min', 'max', 'fit', 'svh', 'lvh', 'dvh'] },\n ],\n /**\n * Size\n * @see https://tailwindcss.com/docs/size\n */\n size: [{ size: [isArbitraryValue, spacing, 'auto', 'min', 'max', 'fit'] }],\n // Typography\n /**\n * Font Size\n * @see https://tailwindcss.com/docs/font-size\n */\n 'font-size': [{ text: ['base', isTshirtSize, isArbitraryLength] }],\n /**\n * Font Smoothing\n * @see https://tailwindcss.com/docs/font-smoothing\n */\n 'font-smoothing': ['antialiased', 'subpixel-antialiased'],\n /**\n * Font Style\n * @see https://tailwindcss.com/docs/font-style\n */\n 'font-style': ['italic', 'not-italic'],\n /**\n * Font Weight\n * @see https://tailwindcss.com/docs/font-weight\n */\n 'font-weight': [\n {\n font: [\n 'thin',\n 'extralight',\n 'light',\n 'normal',\n 'medium',\n 'semibold',\n 'bold',\n 'extrabold',\n 'black',\n isArbitraryNumber,\n ],\n },\n ],\n /**\n * Font Family\n * @see https://tailwindcss.com/docs/font-family\n */\n 'font-family': [{ font: [isAny] }],\n /**\n * Font Variant Numeric\n * @see https://tailwindcss.com/docs/font-variant-numeric\n */\n 'fvn-normal': ['normal-nums'],\n /**\n * Font Variant Numeric\n * @see https://tailwindcss.com/docs/font-variant-numeric\n */\n 'fvn-ordinal': ['ordinal'],\n /**\n * Font Variant Numeric\n * @see https://tailwindcss.com/docs/font-variant-numeric\n */\n 'fvn-slashed-zero': ['slashed-zero'],\n /**\n * Font Variant Numeric\n * @see https://tailwindcss.com/docs/font-variant-numeric\n */\n 'fvn-figure': ['lining-nums', 'oldstyle-nums'],\n /**\n * Font Variant Numeric\n * @see https://tailwindcss.com/docs/font-variant-numeric\n */\n 'fvn-spacing': ['proportional-nums', 'tabular-nums'],\n /**\n * Font Variant Numeric\n * @see https://tailwindcss.com/docs/font-variant-numeric\n */\n 'fvn-fraction': ['diagonal-fractions', 'stacked-fractons'],\n /**\n * Letter Spacing\n * @see https://tailwindcss.com/docs/letter-spacing\n */\n tracking: [\n {\n tracking: [\n 'tighter',\n 'tight',\n 'normal',\n 'wide',\n 'wider',\n 'widest',\n isArbitraryValue,\n ],\n },\n ],\n /**\n * Line Clamp\n * @see https://tailwindcss.com/docs/line-clamp\n */\n 'line-clamp': [{ 'line-clamp': ['none', isNumber, isArbitraryNumber] }],\n /**\n * Line Height\n * @see https://tailwindcss.com/docs/line-height\n */\n leading: [\n {\n leading: [\n 'none',\n 'tight',\n 'snug',\n 'normal',\n 'relaxed',\n 'loose',\n isLength,\n isArbitraryValue,\n ],\n },\n ],\n /**\n * List Style Image\n * @see https://tailwindcss.com/docs/list-style-image\n */\n 'list-image': [{ 'list-image': ['none', isArbitraryValue] }],\n /**\n * List Style Type\n * @see https://tailwindcss.com/docs/list-style-type\n */\n 'list-style-type': [{ list: ['none', 'disc', 'decimal', isArbitraryValue] }],\n /**\n * List Style Position\n * @see https://tailwindcss.com/docs/list-style-position\n */\n 'list-style-position': [{ list: ['inside', 'outside'] }],\n /**\n * Placeholder Color\n * @deprecated since Tailwind CSS v3.0.0\n * @see https://tailwindcss.com/docs/placeholder-color\n */\n 'placeholder-color': [{ placeholder: [colors] }],\n /**\n * Placeholder Opacity\n * @see https://tailwindcss.com/docs/placeholder-opacity\n */\n 'placeholder-opacity': [{ 'placeholder-opacity': [opacity] }],\n /**\n * Text Alignment\n * @see https://tailwindcss.com/docs/text-align\n */\n 'text-alignment': [{ text: ['left', 'center', 'right', 'justify', 'start', 'end'] }],\n /**\n * Text Color\n * @see https://tailwindcss.com/docs/text-color\n */\n 'text-color': [{ text: [colors] }],\n /**\n * Text Opacity\n * @see https://tailwindcss.com/docs/text-opacity\n */\n 'text-opacity': [{ 'text-opacity': [opacity] }],\n /**\n * Text Decoration\n * @see https://tailwindcss.com/docs/text-decoration\n */\n 'text-decoration': ['underline', 'overline', 'line-through', 'no-underline'],\n /**\n * Text Decoration Style\n * @see https://tailwindcss.com/docs/text-decoration-style\n */\n 'text-decoration-style': [{ decoration: [...getLineStyles(), 'wavy'] }],\n /**\n * Text Decoration Thickness\n * @see https://tailwindcss.com/docs/text-decoration-thickness\n */\n 'text-decoration-thickness': [\n { decoration: ['auto', 'from-font', isLength, isArbitraryLength] },\n ],\n /**\n * Text Underline Offset\n * @see https://tailwindcss.com/docs/text-underline-offset\n */\n 'underline-offset': [{ 'underline-offset': ['auto', isLength, isArbitraryValue] }],\n /**\n * Text Decoration Color\n * @see https://tailwindcss.com/docs/text-decoration-color\n */\n 'text-decoration-color': [{ decoration: [colors] }],\n /**\n * Text Transform\n * @see https://tailwindcss.com/docs/text-transform\n */\n 'text-transform': ['uppercase', 'lowercase', 'capitalize', 'normal-case'],\n /**\n * Text Overflow\n * @see https://tailwindcss.com/docs/text-overflow\n */\n 'text-overflow': ['truncate', 'text-ellipsis', 'text-clip'],\n /**\n * Text Wrap\n * @see https://tailwindcss.com/docs/text-wrap\n */\n 'text-wrap': [{ text: ['wrap', 'nowrap', 'balance', 'pretty'] }],\n /**\n * Text Indent\n * @see https://tailwindcss.com/docs/text-indent\n */\n indent: [{ indent: getSpacingWithArbitrary() }],\n /**\n * Vertical Alignment\n * @see https://tailwindcss.com/docs/vertical-align\n */\n 'vertical-align': [\n {\n align: [\n 'baseline',\n 'top',\n 'middle',\n 'bottom',\n 'text-top',\n 'text-bottom',\n 'sub',\n 'super',\n isArbitraryValue,\n ],\n },\n ],\n /**\n * Whitespace\n * @see https://tailwindcss.com/docs/whitespace\n */\n whitespace: [\n { whitespace: ['normal', 'nowrap', 'pre', 'pre-line', 'pre-wrap', 'break-spaces'] },\n ],\n /**\n * Word Break\n * @see https://tailwindcss.com/docs/word-break\n */\n break: [{ break: ['normal', 'words', 'all', 'keep'] }],\n /**\n * Hyphens\n * @see https://tailwindcss.com/docs/hyphens\n */\n hyphens: [{ hyphens: ['none', 'manual', 'auto'] }],\n /**\n * Content\n * @see https://tailwindcss.com/docs/content\n */\n content: [{ content: ['none', isArbitraryValue] }],\n // Backgrounds\n /**\n * Background Attachment\n * @see https://tailwindcss.com/docs/background-attachment\n */\n 'bg-attachment': [{ bg: ['fixed', 'local', 'scroll'] }],\n /**\n * Background Clip\n * @see https://tailwindcss.com/docs/background-clip\n */\n 'bg-clip': [{ 'bg-clip': ['border', 'padding', 'content', 'text'] }],\n /**\n * Background Opacity\n * @deprecated since Tailwind CSS v3.0.0\n * @see https://tailwindcss.com/docs/background-opacity\n */\n 'bg-opacity': [{ 'bg-opacity': [opacity] }],\n /**\n * Background Origin\n * @see https://tailwindcss.com/docs/background-origin\n */\n 'bg-origin': [{ 'bg-origin': ['border', 'padding', 'content'] }],\n /**\n * Background Position\n * @see https://tailwindcss.com/docs/background-position\n */\n 'bg-position': [{ bg: [...getPositions(), isArbitraryPosition] }],\n /**\n * Background Repeat\n * @see https://tailwindcss.com/docs/background-repeat\n */\n 'bg-repeat': [{ bg: ['no-repeat', { repeat: ['', 'x', 'y', 'round', 'space'] }] }],\n /**\n * Background Size\n * @see https://tailwindcss.com/docs/background-size\n */\n 'bg-size': [{ bg: ['auto', 'cover', 'contain', isArbitrarySize] }],\n /**\n * Background Image\n * @see https://tailwindcss.com/docs/background-image\n */\n 'bg-image': [\n {\n bg: [\n 'none',\n { 'gradient-to': ['t', 'tr', 'r', 'br', 'b', 'bl', 'l', 'tl'] },\n isArbitraryImage,\n ],\n },\n ],\n /**\n * Background Color\n * @see https://tailwindcss.com/docs/background-color\n */\n 'bg-color': [{ bg: [colors] }],\n /**\n * Gradient Color Stops From Position\n * @see https://tailwindcss.com/docs/gradient-color-stops\n */\n 'gradient-from-pos': [{ from: [gradientColorStopPositions] }],\n /**\n * Gradient Color Stops Via Position\n * @see https://tailwindcss.com/docs/gradient-color-stops\n */\n 'gradient-via-pos': [{ via: [gradientColorStopPositions] }],\n /**\n * Gradient Color Stops To Position\n * @see https://tailwindcss.com/docs/gradient-color-stops\n */\n 'gradient-to-pos': [{ to: [gradientColorStopPositions] }],\n /**\n * Gradient Color Stops From\n * @see https://tailwindcss.com/docs/gradient-color-stops\n */\n 'gradient-from': [{ from: [gradientColorStops] }],\n /**\n * Gradient Color Stops Via\n * @see https://tailwindcss.com/docs/gradient-color-stops\n */\n 'gradient-via': [{ via: [gradientColorStops] }],\n /**\n * Gradient Color Stops To\n * @see https://tailwindcss.com/docs/gradient-color-stops\n */\n 'gradient-to': [{ to: [gradientColorStops] }],\n // Borders\n /**\n * Border Radius\n * @see https://tailwindcss.com/docs/border-radius\n */\n rounded: [{ rounded: [borderRadius] }],\n /**\n * Border Radius Start\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-s': [{ 'rounded-s': [borderRadius] }],\n /**\n * Border Radius End\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-e': [{ 'rounded-e': [borderRadius] }],\n /**\n * Border Radius Top\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-t': [{ 'rounded-t': [borderRadius] }],\n /**\n * Border Radius Right\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-r': [{ 'rounded-r': [borderRadius] }],\n /**\n * Border Radius Bottom\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-b': [{ 'rounded-b': [borderRadius] }],\n /**\n * Border Radius Left\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-l': [{ 'rounded-l': [borderRadius] }],\n /**\n * Border Radius Start Start\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-ss': [{ 'rounded-ss': [borderRadius] }],\n /**\n * Border Radius Start End\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-se': [{ 'rounded-se': [borderRadius] }],\n /**\n * Border Radius End End\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-ee': [{ 'rounded-ee': [borderRadius] }],\n /**\n * Border Radius End Start\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-es': [{ 'rounded-es': [borderRadius] }],\n /**\n * Border Radius Top Left\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-tl': [{ 'rounded-tl': [borderRadius] }],\n /**\n * Border Radius Top Right\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-tr': [{ 'rounded-tr': [borderRadius] }],\n /**\n * Border Radius Bottom Right\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-br': [{ 'rounded-br': [borderRadius] }],\n /**\n * Border Radius Bottom Left\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-bl': [{ 'rounded-bl': [borderRadius] }],\n /**\n * Border Width\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w': [{ border: [borderWidth] }],\n /**\n * Border Width X\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-x': [{ 'border-x': [borderWidth] }],\n /**\n * Border Width Y\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-y': [{ 'border-y': [borderWidth] }],\n /**\n * Border Width Start\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-s': [{ 'border-s': [borderWidth] }],\n /**\n * Border Width End\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-e': [{ 'border-e': [borderWidth] }],\n /**\n * Border Width Top\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-t': [{ 'border-t': [borderWidth] }],\n /**\n * Border Width Right\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-r': [{ 'border-r': [borderWidth] }],\n /**\n * Border Width Bottom\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-b': [{ 'border-b': [borderWidth] }],\n /**\n * Border Width Left\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-l': [{ 'border-l': [borderWidth] }],\n /**\n * Border Opacity\n * @see https://tailwindcss.com/docs/border-opacity\n */\n 'border-opacity': [{ 'border-opacity': [opacity] }],\n /**\n * Border Style\n * @see https://tailwindcss.com/docs/border-style\n */\n 'border-style': [{ border: [...getLineStyles(), 'hidden'] }],\n /**\n * Divide Width X\n * @see https://tailwindcss.com/docs/divide-width\n */\n 'divide-x': [{ 'divide-x': [borderWidth] }],\n /**\n * Divide Width X Reverse\n * @see https://tailwindcss.com/docs/divide-width\n */\n 'divide-x-reverse': ['divide-x-reverse'],\n /**\n * Divide Width Y\n * @see https://tailwindcss.com/docs/divide-width\n */\n 'divide-y': [{ 'divide-y': [borderWidth] }],\n /**\n * Divide Width Y Reverse\n * @see https://tailwindcss.com/docs/divide-width\n */\n 'divide-y-reverse': ['divide-y-reverse'],\n /**\n * Divide Opacity\n * @see https://tailwindcss.com/docs/divide-opacity\n */\n 'divide-opacity': [{ 'divide-opacity': [opacity] }],\n /**\n * Divide Style\n * @see https://tailwindcss.com/docs/divide-style\n */\n 'divide-style': [{ divide: getLineStyles() }],\n /**\n * Border Color\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color': [{ border: [borderColor] }],\n /**\n * Border Color X\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color-x': [{ 'border-x': [borderColor] }],\n /**\n * Border Color Y\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color-y': [{ 'border-y': [borderColor] }],\n /**\n * Border Color S\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color-s': [{ 'border-s': [borderColor] }],\n /**\n * Border Color E\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color-e': [{ 'border-e': [borderColor] }],\n /**\n * Border Color Top\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color-t': [{ 'border-t': [borderColor] }],\n /**\n * Border Color Right\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color-r': [{ 'border-r': [borderColor] }],\n /**\n * Border Color Bottom\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color-b': [{ 'border-b': [borderColor] }],\n /**\n * Border Color Left\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color-l': [{ 'border-l': [borderColor] }],\n /**\n * Divide Color\n * @see https://tailwindcss.com/docs/divide-color\n */\n 'divide-color': [{ divide: [borderColor] }],\n /**\n * Outline Style\n * @see https://tailwindcss.com/docs/outline-style\n */\n 'outline-style': [{ outline: ['', ...getLineStyles()] }],\n /**\n * Outline Offset\n * @see https://tailwindcss.com/docs/outline-offset\n */\n 'outline-offset': [{ 'outline-offset': [isLength, isArbitraryValue] }],\n /**\n * Outline Width\n * @see https://tailwindcss.com/docs/outline-width\n */\n 'outline-w': [{ outline: [isLength, isArbitraryLength] }],\n /**\n * Outline Color\n * @see https://tailwindcss.com/docs/outline-color\n */\n 'outline-color': [{ outline: [colors] }],\n /**\n * Ring Width\n * @see https://tailwindcss.com/docs/ring-width\n */\n 'ring-w': [{ ring: getLengthWithEmptyAndArbitrary() }],\n /**\n * Ring Width Inset\n * @see https://tailwindcss.com/docs/ring-width\n */\n 'ring-w-inset': ['ring-inset'],\n /**\n * Ring Color\n * @see https://tailwindcss.com/docs/ring-color\n */\n 'ring-color': [{ ring: [colors] }],\n /**\n * Ring Opacity\n * @see https://tailwindcss.com/docs/ring-opacity\n */\n 'ring-opacity': [{ 'ring-opacity': [opacity] }],\n /**\n * Ring Offset Width\n * @see https://tailwindcss.com/docs/ring-offset-width\n */\n 'ring-offset-w': [{ 'ring-offset': [isLength, isArbitraryLength] }],\n /**\n * Ring Offset Color\n * @see https://tailwindcss.com/docs/ring-offset-color\n */\n 'ring-offset-color': [{ 'ring-offset': [colors] }],\n // Effects\n /**\n * Box Shadow\n * @see https://tailwindcss.com/docs/box-shadow\n */\n shadow: [{ shadow: ['', 'inner', 'none', isTshirtSize, isArbitraryShadow] }],\n /**\n * Box Shadow Color\n * @see https://tailwindcss.com/docs/box-shadow-color\n */\n 'shadow-color': [{ shadow: [isAny] }],\n /**\n * Opacity\n * @see https://tailwindcss.com/docs/opacity\n */\n opacity: [{ opacity: [opacity] }],\n /**\n * Mix Blend Mode\n * @see https://tailwindcss.com/docs/mix-blend-mode\n */\n 'mix-blend': [{ 'mix-blend': [...getBlendModes(), 'plus-lighter', 'plus-darker'] }],\n /**\n * Background Blend Mode\n * @see https://tailwindcss.com/docs/background-blend-mode\n */\n 'bg-blend': [{ 'bg-blend': getBlendModes() }],\n // Filters\n /**\n * Filter\n * @deprecated since Tailwind CSS v3.0.0\n * @see https://tailwindcss.com/docs/filter\n */\n filter: [{ filter: ['', 'none'] }],\n /**\n * Blur\n * @see https://tailwindcss.com/docs/blur\n */\n blur: [{ blur: [blur] }],\n /**\n * Brightness\n * @see https://tailwindcss.com/docs/brightness\n */\n brightness: [{ brightness: [brightness] }],\n /**\n * Contrast\n * @see https://tailwindcss.com/docs/contrast\n */\n contrast: [{ contrast: [contrast] }],\n /**\n * Drop Shadow\n * @see https://tailwindcss.com/docs/drop-shadow\n */\n 'drop-shadow': [{ 'drop-shadow': ['', 'none', isTshirtSize, isArbitraryValue] }],\n /**\n * Grayscale\n * @see https://tailwindcss.com/docs/grayscale\n */\n grayscale: [{ grayscale: [grayscale] }],\n /**\n * Hue Rotate\n * @see https://tailwindcss.com/docs/hue-rotate\n */\n 'hue-rotate': [{ 'hue-rotate': [hueRotate] }],\n /**\n * Invert\n * @see https://tailwindcss.com/docs/invert\n */\n invert: [{ invert: [invert] }],\n /**\n * Saturate\n * @see https://tailwindcss.com/docs/saturate\n */\n saturate: [{ saturate: [saturate] }],\n /**\n * Sepia\n * @see https://tailwindcss.com/docs/sepia\n */\n sepia: [{ sepia: [sepia] }],\n /**\n * Backdrop Filter\n * @deprecated since Tailwind CSS v3.0.0\n * @see https://tailwindcss.com/docs/backdrop-filter\n */\n 'backdrop-filter': [{ 'backdrop-filter': ['', 'none'] }],\n /**\n * Backdrop Blur\n * @see https://tailwindcss.com/docs/backdrop-blur\n */\n 'backdrop-blur': [{ 'backdrop-blur': [blur] }],\n /**\n * Backdrop Brightness\n * @see https://tailwindcss.com/docs/backdrop-brightness\n */\n 'backdrop-brightness': [{ 'backdrop-brightness': [brightness] }],\n /**\n * Backdrop Contrast\n * @see https://tailwindcss.com/docs/backdrop-contrast\n */\n 'backdrop-contrast': [{ 'backdrop-contrast': [contrast] }],\n /**\n * Backdrop Grayscale\n * @see https://tailwindcss.com/docs/backdrop-grayscale\n */\n 'backdrop-grayscale': [{ 'backdrop-grayscale': [grayscale] }],\n /**\n * Backdrop Hue Rotate\n * @see https://tailwindcss.com/docs/backdrop-hue-rotate\n */\n 'backdrop-hue-rotate': [{ 'backdrop-hue-rotate': [hueRotate] }],\n /**\n * Backdrop Invert\n * @see https://tailwindcss.com/docs/backdrop-invert\n */\n 'backdrop-invert': [{ 'backdrop-invert': [invert] }],\n /**\n * Backdrop Opacity\n * @see https://tailwindcss.com/docs/backdrop-opacity\n */\n 'backdrop-opacity': [{ 'backdrop-opacity': [opacity] }],\n /**\n * Backdrop Saturate\n * @see https://tailwindcss.com/docs/backdrop-saturate\n */\n 'backdrop-saturate': [{ 'backdrop-saturate': [saturate] }],\n /**\n * Backdrop Sepia\n * @see https://tailwindcss.com/docs/backdrop-sepia\n */\n 'backdrop-sepia': [{ 'backdrop-sepia': [sepia] }],\n // Tables\n /**\n * Border Collapse\n * @see https://tailwindcss.com/docs/border-collapse\n */\n 'border-collapse': [{ border: ['collapse', 'separate'] }],\n /**\n * Border Spacing\n * @see https://tailwindcss.com/docs/border-spacing\n */\n 'border-spacing': [{ 'border-spacing': [borderSpacing] }],\n /**\n * Border Spacing X\n * @see https://tailwindcss.com/docs/border-spacing\n */\n 'border-spacing-x': [{ 'border-spacing-x': [borderSpacing] }],\n /**\n * Border Spacing Y\n * @see https://tailwindcss.com/docs/border-spacing\n */\n 'border-spacing-y': [{ 'border-spacing-y': [borderSpacing] }],\n /**\n * Table Layout\n * @see https://tailwindcss.com/docs/table-layout\n */\n 'table-layout': [{ table: ['auto', 'fixed'] }],\n /**\n * Caption Side\n * @see https://tailwindcss.com/docs/caption-side\n */\n caption: [{ caption: ['top', 'bottom'] }],\n // Transitions and Animation\n /**\n * Tranisition Property\n * @see https://tailwindcss.com/docs/transition-property\n */\n transition: [\n {\n transition: [\n 'none',\n 'all',\n '',\n 'colors',\n 'opacity',\n 'shadow',\n 'transform',\n isArbitraryValue,\n ],\n },\n ],\n /**\n * Transition Duration\n * @see https://tailwindcss.com/docs/transition-duration\n */\n duration: [{ duration: getNumberAndArbitrary() }],\n /**\n * Transition Timing Function\n * @see https://tailwindcss.com/docs/transition-timing-function\n */\n ease: [{ ease: ['linear', 'in', 'out', 'in-out', isArbitraryValue] }],\n /**\n * Transition Delay\n * @see https://tailwindcss.com/docs/transition-delay\n */\n delay: [{ delay: getNumberAndArbitrary() }],\n /**\n * Animation\n * @see https://tailwindcss.com/docs/animation\n */\n animate: [{ animate: ['none', 'spin', 'ping', 'pulse', 'bounce', isArbitraryValue] }],\n // Transforms\n /**\n * Transform\n * @see https://tailwindcss.com/docs/transform\n */\n transform: [{ transform: ['', 'gpu', 'none'] }],\n /**\n * Scale\n * @see https://tailwindcss.com/docs/scale\n */\n scale: [{ scale: [scale] }],\n /**\n * Scale X\n * @see https://tailwindcss.com/docs/scale\n */\n 'scale-x': [{ 'scale-x': [scale] }],\n /**\n * Scale Y\n * @see https://tailwindcss.com/docs/scale\n */\n 'scale-y': [{ 'scale-y': [scale] }],\n /**\n * Rotate\n * @see https://tailwindcss.com/docs/rotate\n */\n rotate: [{ rotate: [isInteger, isArbitraryValue] }],\n /**\n * Translate X\n * @see https://tailwindcss.com/docs/translate\n */\n 'translate-x': [{ 'translate-x': [translate] }],\n /**\n * Translate Y\n * @see https://tailwindcss.com/docs/translate\n */\n 'translate-y': [{ 'translate-y': [translate] }],\n /**\n * Skew X\n * @see https://tailwindcss.com/docs/skew\n */\n 'skew-x': [{ 'skew-x': [skew] }],\n /**\n * Skew Y\n * @see https://tailwindcss.com/docs/skew\n */\n 'skew-y': [{ 'skew-y': [skew] }],\n /**\n * Transform Origin\n * @see https://tailwindcss.com/docs/transform-origin\n */\n 'transform-origin': [\n {\n origin: [\n 'center',\n 'top',\n 'top-right',\n 'right',\n 'bottom-right',\n 'bottom',\n 'bottom-left',\n 'left',\n 'top-left',\n isArbitraryValue,\n ],\n },\n ],\n // Interactivity\n /**\n * Accent Color\n * @see https://tailwindcss.com/docs/accent-color\n */\n accent: [{ accent: ['auto', colors] }],\n /**\n * Appearance\n * @see https://tailwindcss.com/docs/appearance\n */\n appearance: [{ appearance: ['none', 'auto'] }],\n /**\n * Cursor\n * @see https://tailwindcss.com/docs/cursor\n */\n cursor: [\n {\n cursor: [\n 'auto',\n 'default',\n 'pointer',\n 'wait',\n 'text',\n 'move',\n 'help',\n 'not-allowed',\n 'none',\n 'context-menu',\n 'progress',\n 'cell',\n 'crosshair',\n 'vertical-text',\n 'alias',\n 'copy',\n 'no-drop',\n 'grab',\n 'grabbing',\n 'all-scroll',\n 'col-resize',\n 'row-resize',\n 'n-resize',\n 'e-resize',\n 's-resize',\n 'w-resize',\n 'ne-resize',\n 'nw-resize',\n 'se-resize',\n 'sw-resize',\n 'ew-resize',\n 'ns-resize',\n 'nesw-resize',\n 'nwse-resize',\n 'zoom-in',\n 'zoom-out',\n isArbitraryValue,\n ],\n },\n ],\n /**\n * Caret Color\n * @see https://tailwindcss.com/docs/just-in-time-mode#caret-color-utilities\n */\n 'caret-color': [{ caret: [colors] }],\n /**\n * Pointer Events\n * @see https://tailwindcss.com/docs/pointer-events\n */\n 'pointer-events': [{ 'pointer-events': ['none', 'auto'] }],\n /**\n * Resize\n * @see https://tailwindcss.com/docs/resize\n */\n resize: [{ resize: ['none', 'y', 'x', ''] }],\n /**\n * Scroll Behavior\n * @see https://tailwindcss.com/docs/scroll-behavior\n */\n 'scroll-behavior': [{ scroll: ['auto', 'smooth'] }],\n /**\n * Scroll Margin\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-m': [{ 'scroll-m': getSpacingWithArbitrary() }],\n /**\n * Scroll Margin X\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-mx': [{ 'scroll-mx': getSpacingWithArbitrary() }],\n /**\n * Scroll Margin Y\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-my': [{ 'scroll-my': getSpacingWithArbitrary() }],\n /**\n * Scroll Margin Start\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-ms': [{ 'scroll-ms': getSpacingWithArbitrary() }],\n /**\n * Scroll Margin End\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-me': [{ 'scroll-me': getSpacingWithArbitrary() }],\n /**\n * Scroll Margin Top\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-mt': [{ 'scroll-mt': getSpacingWithArbitrary() }],\n /**\n * Scroll Margin Right\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-mr': [{ 'scroll-mr': getSpacingWithArbitrary() }],\n /**\n * Scroll Margin Bottom\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-mb': [{ 'scroll-mb': getSpacingWithArbitrary() }],\n /**\n * Scroll Margin Left\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-ml': [{ 'scroll-ml': getSpacingWithArbitrary() }],\n /**\n * Scroll Padding\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-p': [{ 'scroll-p': getSpacingWithArbitrary() }],\n /**\n * Scroll Padding X\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-px': [{ 'scroll-px': getSpacingWithArbitrary() }],\n /**\n * Scroll Padding Y\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-py': [{ 'scroll-py': getSpacingWithArbitrary() }],\n /**\n * Scroll Padding Start\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-ps': [{ 'scroll-ps': getSpacingWithArbitrary() }],\n /**\n * Scroll Padding End\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-pe': [{ 'scroll-pe': getSpacingWithArbitrary() }],\n /**\n * Scroll Padding Top\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-pt': [{ 'scroll-pt': getSpacingWithArbitrary() }],\n /**\n * Scroll Padding Right\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-pr': [{ 'scroll-pr': getSpacingWithArbitrary() }],\n /**\n * Scroll Padding Bottom\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-pb': [{ 'scroll-pb': getSpacingWithArbitrary() }],\n /**\n * Scroll Padding Left\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-pl': [{ 'scroll-pl': getSpacingWithArbitrary() }],\n /**\n * Scroll Snap Align\n * @see https://tailwindcss.com/docs/scroll-snap-align\n */\n 'snap-align': [{ snap: ['start', 'end', 'center', 'align-none'] }],\n /**\n * Scroll Snap Stop\n * @see https://tailwindcss.com/docs/scroll-snap-stop\n */\n 'snap-stop': [{ snap: ['normal', 'always'] }],\n /**\n * Scroll Snap Type\n * @see https://tailwindcss.com/docs/scroll-snap-type\n */\n 'snap-type': [{ snap: ['none', 'x', 'y', 'both'] }],\n /**\n * Scroll Snap Type Strictness\n * @see https://tailwindcss.com/docs/scroll-snap-type\n */\n 'snap-strictness': [{ snap: ['mandatory', 'proximity'] }],\n /**\n * Touch Action\n * @see https://tailwindcss.com/docs/touch-action\n */\n touch: [\n {\n touch: ['auto', 'none', 'manipulation'],\n },\n ],\n /**\n * Touch Action X\n * @see https://tailwindcss.com/docs/touch-action\n */\n 'touch-x': [\n {\n 'touch-pan': ['x', 'left', 'right'],\n },\n ],\n /**\n * Touch Action Y\n * @see https://tailwindcss.com/docs/touch-action\n */\n 'touch-y': [\n {\n 'touch-pan': ['y', 'up', 'down'],\n },\n ],\n /**\n * Touch Action Pinch Zoom\n * @see https://tailwindcss.com/docs/touch-action\n */\n 'touch-pz': ['touch-pinch-zoom'],\n /**\n * User Select\n * @see https://tailwindcss.com/docs/user-select\n */\n select: [{ select: ['none', 'text', 'all', 'auto'] }],\n /**\n * Will Change\n * @see https://tailwindcss.com/docs/will-change\n */\n 'will-change': [\n { 'will-change': ['auto', 'scroll', 'contents', 'transform', isArbitraryValue] },\n ],\n // SVG\n /**\n * Fill\n * @see https://tailwindcss.com/docs/fill\n */\n fill: [{ fill: [colors, 'none'] }],\n /**\n * Stroke Width\n * @see https://tailwindcss.com/docs/stroke-width\n */\n 'stroke-w': [{ stroke: [isLength, isArbitraryLength, isArbitraryNumber] }],\n /**\n * Stroke\n * @see https://tailwindcss.com/docs/stroke\n */\n stroke: [{ stroke: [colors, 'none'] }],\n // Accessibility\n /**\n * Screen Readers\n * @see https://tailwindcss.com/docs/screen-readers\n */\n sr: ['sr-only', 'not-sr-only'],\n /**\n * Forced Color Adjust\n * @see https://tailwindcss.com/docs/forced-color-adjust\n */\n 'forced-color-adjust': [{ 'forced-color-adjust': ['auto', 'none'] }],\n },\n conflictingClassGroups: {\n overflow: ['overflow-x', 'overflow-y'],\n overscroll: ['overscroll-x', 'overscroll-y'],\n inset: ['inset-x', 'inset-y', 'start', 'end', 'top', 'right', 'bottom', 'left'],\n 'inset-x': ['right', 'left'],\n 'inset-y': ['top', 'bottom'],\n flex: ['basis', 'grow', 'shrink'],\n gap: ['gap-x', 'gap-y'],\n p: ['px', 'py', 'ps', 'pe', 'pt', 'pr', 'pb', 'pl'],\n px: ['pr', 'pl'],\n py: ['pt', 'pb'],\n m: ['mx', 'my', 'ms', 'me', 'mt', 'mr', 'mb', 'ml'],\n mx: ['mr', 'ml'],\n my: ['mt', 'mb'],\n size: ['w', 'h'],\n 'font-size': ['leading'],\n 'fvn-normal': [\n 'fvn-ordinal',\n 'fvn-slashed-zero',\n 'fvn-figure',\n 'fvn-spacing',\n 'fvn-fraction',\n ],\n 'fvn-ordinal': ['fvn-normal'],\n 'fvn-slashed-zero': ['fvn-normal'],\n 'fvn-figure': ['fvn-normal'],\n 'fvn-spacing': ['fvn-normal'],\n 'fvn-fraction': ['fvn-normal'],\n 'line-clamp': ['display', 'overflow'],\n rounded: [\n 'rounded-s',\n 'rounded-e',\n 'rounded-t',\n 'rounded-r',\n 'rounded-b',\n 'rounded-l',\n 'rounded-ss',\n 'rounded-se',\n 'rounded-ee',\n 'rounded-es',\n 'rounded-tl',\n 'rounded-tr',\n 'rounded-br',\n 'rounded-bl',\n ],\n 'rounded-s': ['rounded-ss', 'rounded-es'],\n 'rounded-e': ['rounded-se', 'rounded-ee'],\n 'rounded-t': ['rounded-tl', 'rounded-tr'],\n 'rounded-r': ['rounded-tr', 'rounded-br'],\n 'rounded-b': ['rounded-br', 'rounded-bl'],\n 'rounded-l': ['rounded-tl', 'rounded-bl'],\n 'border-spacing': ['border-spacing-x', 'border-spacing-y'],\n 'border-w': [\n 'border-w-s',\n 'border-w-e',\n 'border-w-t',\n 'border-w-r',\n 'border-w-b',\n 'border-w-l',\n ],\n 'border-w-x': ['border-w-r', 'border-w-l'],\n 'border-w-y': ['border-w-t', 'border-w-b'],\n 'border-color': [\n 'border-color-s',\n 'border-color-e',\n 'border-color-t',\n 'border-color-r',\n 'border-color-b',\n 'border-color-l',\n ],\n 'border-color-x': ['border-color-r', 'border-color-l'],\n 'border-color-y': ['border-color-t', 'border-color-b'],\n 'scroll-m': [\n 'scroll-mx',\n 'scroll-my',\n 'scroll-ms',\n 'scroll-me',\n 'scroll-mt',\n 'scroll-mr',\n 'scroll-mb',\n 'scroll-ml',\n ],\n 'scroll-mx': ['scroll-mr', 'scroll-ml'],\n 'scroll-my': ['scroll-mt', 'scroll-mb'],\n 'scroll-p': [\n 'scroll-px',\n 'scroll-py',\n 'scroll-ps',\n 'scroll-pe',\n 'scroll-pt',\n 'scroll-pr',\n 'scroll-pb',\n 'scroll-pl',\n ],\n 'scroll-px': ['scroll-pr', 'scroll-pl'],\n 'scroll-py': ['scroll-pt', 'scroll-pb'],\n touch: ['touch-x', 'touch-y', 'touch-pz'],\n 'touch-x': ['touch'],\n 'touch-y': ['touch'],\n 'touch-pz': ['touch'],\n },\n conflictingClassGroupModifiers: {\n 'font-size': ['leading'],\n },\n } as const satisfies Config<DefaultClassGroupIds, DefaultThemeGroupIds>\n}\n", "import { ConfigExtension, GenericConfig } from './types'\n\n/**\n * @param baseConfig Config where other config will be merged into. This object will be mutated.\n * @param configExtension Partial config to merge into the `baseConfig`.\n */\nexport const mergeConfigs = <ClassGroupIds extends string, ThemeGroupIds extends string = never>(\n baseConfig: GenericConfig,\n {\n cacheSize,\n prefix,\n separator,\n experimentalParseClassName,\n extend = {},\n override = {},\n }: ConfigExtension<ClassGroupIds, ThemeGroupIds>,\n) => {\n overrideProperty(baseConfig, 'cacheSize', cacheSize)\n overrideProperty(baseConfig, 'prefix', prefix)\n overrideProperty(baseConfig, 'separator', separator)\n overrideProperty(baseConfig, 'experimentalParseClassName', experimentalParseClassName)\n\n for (const configKey in override) {\n overrideConfigProperties(\n baseConfig[configKey as keyof typeof override],\n override[configKey as keyof typeof override],\n )\n }\n\n for (const key in extend) {\n mergeConfigProperties(\n baseConfig[key as keyof typeof extend],\n extend[key as keyof typeof extend],\n )\n }\n\n return baseConfig\n}\n\nconst overrideProperty = <T extends object, K extends keyof T>(\n baseObject: T,\n overrideKey: K,\n overrideValue: T[K] | undefined,\n) => {\n if (overrideValue !== undefined) {\n baseObject[overrideKey] = overrideValue\n }\n}\n\nconst overrideConfigProperties = (\n baseObject: Partial<Record<string, readonly unknown[]>>,\n overrideObject: Partial<Record<string, readonly unknown[]>> | undefined,\n) => {\n if (overrideObject) {\n for (const key in overrideObject) {\n overrideProperty(baseObject, key, overrideObject[key])\n }\n }\n}\n\nconst mergeConfigProperties = (\n baseObject: Partial<Record<string, readonly unknown[]>>,\n mergeObject: Partial<Record<string, readonly unknown[]>> | undefined,\n) => {\n if (mergeObject) {\n for (const key in mergeObject) {\n const mergeValue = mergeObject[key]\n\n if (mergeValue !== undefined) {\n baseObject[key] = (baseObject[key] || []).concat(mergeValue)\n }\n }\n }\n}\n", "import { createTailwindMerge } from './create-tailwind-merge'\nimport { getDefaultConfig } from './default-config'\nimport { mergeConfigs } from './merge-configs'\nimport { ConfigExtension, DefaultClassGroupIds, DefaultThemeGroupIds, GenericConfig } from './types'\n\ntype CreateConfigSubsequent = (config: GenericConfig) => GenericConfig\n\nexport const extendTailwindMerge = <\n AdditionalClassGroupIds extends string = never,\n AdditionalThemeGroupIds extends string = never,\n>(\n configExtension:\n | ConfigExtension<\n DefaultClassGroupIds | AdditionalClassGroupIds,\n DefaultThemeGroupIds | AdditionalThemeGroupIds\n >\n | CreateConfigSubsequent,\n ...createConfig: CreateConfigSubsequent[]\n) =>\n typeof configExtension === 'function'\n ? createTailwindMerge(getDefaultConfig, configExtension, ...createConfig)\n : createTailwindMerge(\n () => mergeConfigs(getDefaultConfig(), configExtension),\n ...createConfig,\n )\n", "import { createTailwindMerge } from './create-tailwind-merge'\nimport { getDefaultConfig } from './default-config'\n\nexport const twMerge = createTailwindMerge(getDefaultConfig)\n", "import { type ClassValue, clsx } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nexport function cn(...inputs: ClassValue[]) {\n return twMerge(clsx(inputs));\n}\n", "import { wait } from \"./promises\";\nimport { deindent, nicify } from \"./strings\";\n\nexport type Result<T, E = unknown> =\n | {\n status: \"ok\",\n data: T,\n }\n | {\n status: \"error\",\n error: E,\n };\n\nexport type AsyncResult<T, E = unknown, P = void> =\n | Result<T, E>\n | (\n & {\n status: \"pending\",\n }\n & {\n progress: P,\n }\n );\n\n\nexport const Result = {\n fromThrowing,\n fromThrowingAsync,\n fromPromise: promiseToResult,\n ok<T>(data: T): Result<T, never> & { status: \"ok\" } {\n return {\n status: \"ok\",\n data,\n };\n },\n error<E>(error: E): Result<never, E> & { status: \"error\" } {\n return {\n status: \"error\",\n error,\n };\n },\n map: mapResult,\n or: <T, E, U>(result: Result<T, E>, fallback: U): T | U => {\n return result.status === \"ok\" ? result.data : fallback;\n },\n orThrow: <T, E>(result: Result<T, E>): T => {\n if (result.status === \"error\") {\n throw result.error;\n }\n return result.data;\n },\n orThrowAsync: async <T, E>(result: Promise<Result<T, E>>): Promise<T> => {\n return Result.orThrow(await result);\n },\n retry,\n};\nimport.meta.vitest?.test(\"Result.ok and Result.error\", ({ expect }) => {\n // Test Result.ok\n const okResult = Result.ok(42);\n expect(okResult.status).toBe(\"ok\");\n expect(okResult.data).toBe(42);\n\n // Test Result.error\n const error = new Error(\"Test error\");\n const errorResult = Result.error(error);\n expect(errorResult.status).toBe(\"error\");\n expect(errorResult.error).toBe(error);\n});\n\nimport.meta.vitest?.test(\"Result.or\", ({ expect }) => {\n // Test with ok result\n const okResult: Result<number, string> = { status: \"ok\", data: 42 };\n expect(Result.or(okResult, 0)).toBe(42);\n\n // Test with error result\n const errorResult: Result<number, string> = { status: \"error\", error: \"error message\" };\n expect(Result.or(errorResult, 0)).toBe(0);\n});\n\nimport.meta.vitest?.test(\"Result.orThrow\", ({ expect }) => {\n // Test with ok result\n const okResult: Result<number, Error> = { status: \"ok\", data: 42 };\n expect(Result.orThrow(okResult)).toBe(42);\n\n // Test with error result\n const error = new Error(\"Test error\");\n const errorResult: Result<number, Error> = { status: \"error\", error };\n expect(() => Result.orThrow(errorResult)).toThrow(error);\n});\n\nimport.meta.vitest?.test(\"Result.orThrowAsync\", async ({ expect }) => {\n // Test with ok result\n const okPromise = Promise.resolve({ status: \"ok\", data: 42 } as Result<number, Error>);\n expect(await Result.orThrowAsync(okPromise)).toBe(42);\n\n // Test with error result\n const error = new Error(\"Test error\");\n const errorPromise = Promise.resolve({ status: \"error\", error } as Result<number, Error>);\n await expect(Result.orThrowAsync(errorPromise)).rejects.toThrow(error);\n});\n\nexport const AsyncResult = {\n fromThrowing,\n fromPromise: promiseToResult,\n ok: Result.ok,\n error: Result.error,\n pending,\n map: mapResult,\n or: <T, E, P, U>(result: AsyncResult<T, E, P>, fallback: U): T | U => {\n if (result.status === \"pending\") {\n return fallback;\n }\n return Result.or(result, fallback);\n },\n orThrow: <T, E, P>(result: AsyncResult<T, E, P>): T => {\n if (result.status === \"pending\") {\n throw new Error(\"Result still pending\");\n }\n return Result.orThrow(result);\n },\n retry,\n};\nimport.meta.vitest?.test(\"AsyncResult.or\", ({ expect }) => {\n // Test with ok result\n const okResult: AsyncResult<number, string> = { status: \"ok\", data: 42 };\n expect(AsyncResult.or(okResult, 0)).toBe(42);\n\n // Test with error result\n const errorResult: AsyncResult<number, string> = { status: \"error\", error: \"error message\" };\n expect(AsyncResult.or(errorResult, 0)).toBe(0);\n\n // Test with pending result\n const pendingResult: AsyncResult<number, string> = { status: \"pending\", progress: undefined };\n expect(AsyncResult.or(pendingResult, 0)).toBe(0);\n});\n\nimport.meta.vitest?.test(\"AsyncResult.orThrow\", ({ expect }) => {\n // Test with ok result\n const okResult: AsyncResult<number, Error> = { status: \"ok\", data: 42 };\n expect(AsyncResult.orThrow(okResult)).toBe(42);\n\n // Test with error result\n const error = new Error(\"Test error\");\n const errorResult: AsyncResult<number, Error> = { status: \"error\", error };\n expect(() => AsyncResult.orThrow(errorResult)).toThrow(error);\n\n // Test with pending result\n const pendingResult: AsyncResult<number, Error> = { status: \"pending\", progress: undefined };\n expect(() => AsyncResult.orThrow(pendingResult)).toThrow(\"Result still pending\");\n});\n\nfunction pending(): AsyncResult<never, never, void> & { status: \"pending\" };\nfunction pending<P>(progress: P): AsyncResult<never, never, P> & { status: \"pending\" };\nfunction pending<P>(progress?: P): AsyncResult<never, never, P> & { status: \"pending\" } {\n return {\n status: \"pending\",\n progress: progress!,\n };\n}\nimport.meta.vitest?.test(\"pending\", ({ expect }) => {\n // Test without progress\n const pendingResult = pending();\n expect(pendingResult.status).toBe(\"pending\");\n expect(pendingResult.progress).toBe(undefined);\n\n // Test with progress\n const progressValue = { loaded: 50, total: 100 };\n const pendingWithProgress = pending(progressValue);\n expect(pendingWithProgress.status).toBe(\"pending\");\n expect(pendingWithProgress.progress).toBe(progressValue);\n});\n\nasync function promiseToResult<T>(promise: Promise<T>): Promise<Result<T>> {\n try {\n const value = await promise;\n return Result.ok(value);\n } catch (error) {\n return Result.error(error);\n }\n}\nimport.meta.vitest?.test(\"promiseToResult\", async ({ expect }) => {\n // Test with resolved promise\n const resolvedPromise = Promise.resolve(42);\n const resolvedResult = await promiseToResult(resolvedPromise);\n expect(resolvedResult.status).toBe(\"ok\");\n if (resolvedResult.status === \"ok\") {\n expect(resolvedResult.data).toBe(42);\n }\n\n // Test with rejected promise\n const error = new Error(\"Test error\");\n const rejectedPromise = Promise.reject(error);\n const rejectedResult = await promiseToResult(rejectedPromise);\n expect(rejectedResult.status).toBe(\"error\");\n if (rejectedResult.status === \"error\") {\n expect(rejectedResult.error).toBe(error);\n }\n});\n\nfunction fromThrowing<T>(fn: () => T): Result<T, unknown> {\n try {\n return Result.ok(fn());\n } catch (error) {\n return Result.error(error);\n }\n}\nimport.meta.vitest?.test(\"fromThrowing\", ({ expect }) => {\n // Test with function that succeeds\n const successFn = () => 42;\n const successResult = fromThrowing(successFn);\n expect(successResult.status).toBe(\"ok\");\n if (successResult.status === \"ok\") {\n expect(successResult.data).toBe(42);\n }\n\n // Test with function that throws\n const error = new Error(\"Test error\");\n const errorFn = () => {\n throw error;\n };\n const errorResult = fromThrowing(errorFn);\n expect(errorResult.status).toBe(\"error\");\n if (errorResult.status === \"error\") {\n expect(errorResult.error).toBe(error);\n }\n});\n\nasync function fromThrowingAsync<T>(fn: () => Promise<T>): Promise<Result<T, unknown>> {\n try {\n return Result.ok(await fn());\n } catch (error) {\n return Result.error(error);\n }\n}\nimport.meta.vitest?.test(\"fromThrowingAsync\", async ({ expect }) => {\n // Test with async function that succeeds\n const successFn = async () => 42;\n const successResult = await fromThrowingAsync(successFn);\n expect(successResult.status).toBe(\"ok\");\n if (successResult.status === \"ok\") {\n expect(successResult.data).toBe(42);\n }\n\n // Test with async function that throws\n const error = new Error(\"Test error\");\n const errorFn = async () => {\n throw error;\n };\n const errorResult = await fromThrowingAsync(errorFn);\n expect(errorResult.status).toBe(\"error\");\n if (errorResult.status === \"error\") {\n expect(errorResult.error).toBe(error);\n }\n});\n\nfunction mapResult<T, U, E = unknown, P = unknown>(result: Result<T, E>, fn: (data: T) => U): Result<U, E>;\nfunction mapResult<T, U, E = unknown, P = unknown>(result: AsyncResult<T, E, P>, fn: (data: T) => U): AsyncResult<U, E, P>;\nfunction mapResult<T, U, E = unknown, P = unknown>(result: AsyncResult<T, E, P>, fn: (data: T) => U): AsyncResult<U, E, P> {\n if (result.status === \"error\") return {\n status: \"error\",\n error: result.error,\n };\n if (result.status === \"pending\") return {\n status: \"pending\",\n ...\"progress\" in result ? { progress: result.progress } : {},\n } as any;\n\n return Result.ok(fn(result.data));\n}\nimport.meta.vitest?.test(\"mapResult\", ({ expect }) => {\n // Test with ok result\n const okResult: Result<number, string> = { status: \"ok\", data: 42 };\n const mappedOk = mapResult(okResult, (n: number) => n * 2);\n expect(mappedOk.status).toBe(\"ok\");\n if (mappedOk.status === \"ok\") {\n expect(mappedOk.data).toBe(84);\n }\n\n // Test with error result\n const errorResult: Result<number, string> = { status: \"error\", error: \"error message\" };\n const mappedError = mapResult(errorResult, (n: number) => n * 2);\n expect(mappedError.status).toBe(\"error\");\n if (mappedError.status === \"error\") {\n expect(mappedError.error).toBe(\"error message\");\n }\n\n // Test with pending result (no progress)\n const pendingResult: AsyncResult<number, string, void> = { status: \"pending\", progress: undefined };\n const mappedPending = mapResult(pendingResult, (n: number) => n * 2);\n expect(mappedPending.status).toBe(\"pending\");\n\n // Test with pending result (with progress)\n const progressValue = { loaded: 50, total: 100 };\n const pendingWithProgress: AsyncResult<number, string, typeof progressValue> = {\n status: \"pending\",\n progress: progressValue\n };\n const mappedPendingWithProgress = mapResult(pendingWithProgress, (n: number) => n * 2);\n expect(mappedPendingWithProgress.status).toBe(\"pending\");\n if (mappedPendingWithProgress.status === \"pending\") {\n expect(mappedPendingWithProgress.progress).toBe(progressValue);\n }\n});\n\n\nclass RetryError<E = unknown> extends AggregateError {\n constructor(public readonly errors: E[]) {\n const strings = errors.map(e => nicify(e));\n const isAllSame = strings.length > 1 && strings.every(s => s === strings[0]);\n super(\n errors,\n deindent`\n Error after ${errors.length} attempts.\n \n ${isAllSame ? deindent`\n Attempts 1-${errors.length}:\n ${strings[0]}\n ` : strings.map((s, i) => deindent`\n Attempt ${i + 1}:\n ${s}\n `).join(\"\\n\\n\")}\n `,\n { cause: errors[errors.length - 1] }\n );\n this.name = \"RetryError\";\n }\n\n get attempts() {\n return this.errors.length;\n }\n}\nRetryError.prototype.name = \"RetryError\";\n\nimport.meta.vitest?.test(\"RetryError\", ({ expect }) => {\n // Test with single error\n const singleError = new Error(\"Single error\");\n const retryErrorSingle = new RetryError([singleError]);\n expect(retryErrorSingle.name).toBe(\"RetryError\");\n expect(retryErrorSingle.errors).toEqual([singleError]);\n expect(retryErrorSingle.attempts).toBe(1);\n expect(retryErrorSingle.cause).toBe(singleError);\n expect(retryErrorSingle.message).toContain(\"Error after 1 attempts\");\n\n // Test with multiple different errors\n const error1 = new Error(\"Error 1\");\n const error2 = new Error(\"Error 2\");\n const retryErrorMultiple = new RetryError([error1, error2]);\n expect(retryErrorMultiple.name).toBe(\"RetryError\");\n expect(retryErrorMultiple.errors).toEqual([error1, error2]);\n expect(retryErrorMultiple.attempts).toBe(2);\n expect(retryErrorMultiple.cause).toBe(error2);\n expect(retryErrorMultiple.message).toContain(\"Error after 2 attempts\");\n expect(retryErrorMultiple.message).toContain(\"Attempt 1\");\n expect(retryErrorMultiple.message).toContain(\"Attempt 2\");\n\n // Test with multiple identical errors\n const sameError = new Error(\"Same error\");\n const retryErrorSame = new RetryError([sameError, sameError]);\n expect(retryErrorSame.name).toBe(\"RetryError\");\n expect(retryErrorSame.errors).toEqual([sameError, sameError]);\n expect(retryErrorSame.attempts).toBe(2);\n expect(retryErrorSame.cause).toBe(sameError);\n expect(retryErrorSame.message).toContain(\"Error after 2 attempts\");\n expect(retryErrorSame.message).toContain(\"Attempts 1-2\");\n});\n\nasync function retry<T, E>(\n fn: (attemptIndex: number) => Result<T, E> | Promise<Result<T, E>>,\n totalAttempts: number,\n { exponentialDelayBase = 1000 } = {},\n): Promise<Result<T, RetryError<E>> & { attempts: number }> {\n const errors: E[] = [];\n for (let i = 0; i < totalAttempts; i++) {\n const res = await fn(i);\n if (res.status === \"ok\") {\n return Object.assign(Result.ok(res.data), { attempts: i + 1 });\n } else {\n errors.push(res.error);\n if (i < totalAttempts - 1) {\n await wait((Math.random() + 0.5) * exponentialDelayBase * (2 ** i));\n }\n }\n }\n return Object.assign(Result.error(new RetryError(errors)), { attempts: totalAttempts });\n}\nimport.meta.vitest?.test(\"retry\", async ({ expect }) => {\n // Test successful on first attempt\n const successFn = async () => Result.ok(\"success\");\n const successResult = await retry(successFn, 3, { exponentialDelayBase: 0 });\n expect(successResult).toEqual({ status: \"ok\", data: \"success\", attempts: 1 });\n\n // Test successful after failures\n let attemptCount = 0;\n const eventualSuccessFn = async () => {\n return ++attemptCount < 2 ? Result.error(new Error(`Attempt ${attemptCount} failed`))\n : Result.ok(\"eventual success\");\n };\n const eventualSuccessResult = await retry(eventualSuccessFn, 3, { exponentialDelayBase: 0 });\n expect(eventualSuccessResult).toEqual({ status: \"ok\", data: \"eventual success\", attempts: 2 });\n\n // Test all attempts fail\n const errors = [new Error(\"Error 1\"), new Error(\"Error 2\"), new Error(\"Error 3\")];\n const allFailFn = async (attempt: number) => {\n return Result.error(errors[attempt]);\n };\n const allFailResult = await retry(allFailFn, 3, { exponentialDelayBase: 0 });\n expect(allFailResult).toEqual({ status: \"error\", error: expect.any(RetryError), attempts: 3 });\n const retryError = (allFailResult as any).error as RetryError;\n expect(retryError.errors).toEqual(errors);\n expect(retryError.attempts).toBe(3);\n});\n", "import { StackAssertionError, StatusError, throwErr } from \"./utils/errors\";\nimport { identityArgs } from \"./utils/functions\";\nimport { Json } from \"./utils/json\";\nimport { deindent } from \"./utils/strings\";\n\nexport type KnownErrorJson = {\n code: string,\n message: string,\n details?: Json,\n};\n\nexport type AbstractKnownErrorConstructor<Args extends any[]> =\n & (abstract new (...args: Args) => KnownError)\n & {\n constructorArgsFromJson: (json: KnownErrorJson) => Args,\n };\n\nexport type KnownErrorConstructor<SuperInstance extends KnownError, Args extends any[]> = {\n new(...args: Args): SuperInstance & { constructorArgs: Args },\n errorCode: string,\n constructorArgsFromJson: (json: KnownErrorJson) => Args,\n isInstance: (error: unknown) => error is SuperInstance & { constructorArgs: Args },\n};\n\nexport abstract class KnownError extends StatusError {\n private readonly __stackKnownErrorBrand = \"stack-known-error-brand-sentinel\" as const;\n public name = \"KnownError\";\n\n constructor(\n public readonly statusCode: number,\n public readonly humanReadableMessage: string,\n public readonly details?: Json,\n ) {\n super(\n statusCode,\n humanReadableMessage\n );\n }\n\n public static isKnownError(error: unknown): error is KnownError {\n // like instanceof, but also works for errors thrown in other realms or by different versions of the same package\n return typeof error === \"object\" && error !== null && \"__stackKnownErrorBrand\" in error && error.__stackKnownErrorBrand === \"stack-known-error-brand-sentinel\";\n }\n\n public override getBody(): Uint8Array {\n return new TextEncoder().encode(JSON.stringify(this.toDescriptiveJson(), undefined, 2));\n }\n\n public override getHeaders(): Record<string, string[]> {\n return {\n \"Content-Type\": [\"application/json; charset=utf-8\"],\n \"X-Stack-Known-Error\": [this.errorCode],\n };\n }\n\n public override toDescriptiveJson(): Json {\n return {\n code: this.errorCode,\n ...this.details ? { details: this.details } : {},\n error: this.humanReadableMessage,\n };\n }\n\n get errorCode(): string {\n return (this.constructor as any).errorCode ?? throwErr(`Can't find error code for this KnownError. Is its constructor a KnownErrorConstructor? ${this}`);\n }\n\n public static constructorArgsFromJson(json: KnownErrorJson): ConstructorParameters<typeof KnownError> {\n return [\n 400,\n json.message,\n json,\n ];\n }\n\n public static fromJson(json: KnownErrorJson): KnownError {\n for (const [_, KnownErrorType] of Object.entries(KnownErrors)) {\n if (json.code === KnownErrorType.prototype.errorCode) {\n const constructorArgs = KnownErrorType.constructorArgsFromJson(json);\n return new KnownErrorType(\n // @ts-ignore-next-line\n ...constructorArgs,\n );\n }\n }\n\n throw new Error(`An error occurred. Please update your version of the Stack Auth SDK. ${json.code}: ${json.message}`);\n }\n}\n\nconst knownErrorConstructorErrorCodeSentinel = Symbol(\"knownErrorConstructorErrorCodeSentinel\");\n/**\n * Exists solely so that known errors are nominative types (ie. two KnownErrors with the same interface are not the same type)\n */\ntype KnownErrorBrand<ErrorCode extends string> = {\n /**\n * Does not exist at runtime\n *\n * Must be an object because it may be true for multiple error codes (it's true for all parents)\n */\n [knownErrorConstructorErrorCodeSentinel]: {\n [K in ErrorCode]: true\n },\n};\n\nfunction createKnownErrorConstructor<ErrorCode extends string, Super extends AbstractKnownErrorConstructor<any>, Args extends any[]>(\n SuperClass: Super,\n errorCode: ErrorCode,\n create: ((...args: Args) => Readonly<ConstructorParameters<Super>>),\n constructorArgsFromJson: ((jsonDetails: any) => NoInfer<Args>),\n): KnownErrorConstructor<InstanceType<Super> & KnownErrorBrand<ErrorCode>, Args> & { errorCode: ErrorCode };\nfunction createKnownErrorConstructor<ErrorCode extends string, Super extends AbstractKnownErrorConstructor<any>>(\n SuperClass: Super,\n errorCode: ErrorCode,\n create: \"inherit\",\n constructorArgsFromJson: \"inherit\",\n): KnownErrorConstructor<InstanceType<Super> & KnownErrorBrand<ErrorCode>, ConstructorParameters<Super>> & { errorCode: ErrorCode };\nfunction createKnownErrorConstructor<ErrorCode extends string, Super extends AbstractKnownErrorConstructor<any>, Args extends any[]>(\n SuperClass: Super,\n errorCode: ErrorCode,\n create: \"inherit\" | ((...args: Args) => Readonly<ConstructorParameters<Super>>),\n constructorArgsFromJson: \"inherit\" | ((jsonDetails: any) => NoInfer<Args>),\n): KnownErrorConstructor<InstanceType<Super> & KnownErrorBrand<ErrorCode>, Args> & { errorCode: ErrorCode } {\n const createFn = create === \"inherit\" ? identityArgs<Args> as never : create;\n const constructorArgsFromJsonFn = constructorArgsFromJson === \"inherit\" ? SuperClass.constructorArgsFromJson as never : constructorArgsFromJson;\n\n // @ts-expect-error this is not a mixin, but TS detects it as one\n class KnownErrorImpl extends SuperClass {\n public static readonly errorCode = errorCode;\n public name = `KnownError<${errorCode}>`;\n public readonly constructorArgs: Args;\n\n constructor(...args: Args) {\n // @ts-ignore legendary comment, may never be removed https://x.com/konstiwohlwend/status/1998543556567617780\n super(...createFn(...args));\n this.constructorArgs = args;\n }\n\n static constructorArgsFromJson(json: KnownErrorJson): Args {\n return constructorArgsFromJsonFn(json.details);\n }\n\n static isInstance(error: unknown): error is InstanceType<Super> & { constructorArgs: Args } {\n if (!KnownError.isKnownError(error)) return false;\n let current: unknown = error;\n while (true) {\n current = Object.getPrototypeOf(current);\n if (!current) break;\n if (\"errorCode\" in current.constructor && current.constructor.errorCode === errorCode) return true;\n }\n return false;\n }\n };\n\n // @ts-expect-error\n return KnownErrorImpl;\n}\nimport.meta.vitest?.test(\"KnownError.isInstance\", ({ expect }) => {\n expect(KnownErrors.InvalidProjectAuthentication.isInstance(undefined)).toBe(false);\n expect(KnownErrors.InvalidProjectAuthentication.isInstance(new Error())).toBe(false);\n\n const error = new KnownErrors.ProjectKeyWithoutAccessType();\n expect(KnownErrors.ProjectKeyWithoutAccessType.isInstance(error)).toBe(true);\n expect(KnownErrors.InvalidProjectAuthentication.isInstance(error)).toBe(true);\n expect(KnownErrors.InvalidAccessType.isInstance(error)).toBe(false);\n});\n\nconst UnsupportedError = createKnownErrorConstructor(\n KnownError,\n \"UNSUPPORTED_ERROR\",\n (originalErrorCode: string) => [\n 500,\n `An error occurred that is not currently supported (possibly because it was added in a version of Stack that is newer than this client). The original unsupported error code was: ${originalErrorCode}`,\n {\n originalErrorCode,\n },\n ] as const,\n (json) => [\n (json as any)?.originalErrorCode ?? throwErr(\"originalErrorCode not found in UnsupportedError details\"),\n ] as const,\n);\n\nconst BodyParsingError = createKnownErrorConstructor(\n KnownError,\n \"BODY_PARSING_ERROR\",\n (message: string) => [\n 400,\n message,\n ] as const,\n (json) => [json.message] as const,\n);\n\nconst SchemaError = createKnownErrorConstructor(\n KnownError,\n \"SCHEMA_ERROR\",\n (message: string) => [\n 400,\n message || throwErr(\"SchemaError requires a message\"),\n {\n message,\n },\n ] as const,\n (json: any) => [json.message] as const,\n);\n\nconst AllOverloadsFailed = createKnownErrorConstructor(\n KnownError,\n \"ALL_OVERLOADS_FAILED\",\n (overloadErrors: Json[]) => [\n 400,\n deindent`\n This endpoint has multiple overloads, but they all failed to process the request.\n\n ${overloadErrors.map((e, i) => deindent`\n Overload ${i + 1}: ${JSON.stringify(e, undefined, 2)}\n `).join(\"\\n\\n\")}\n `,\n {\n overload_errors: overloadErrors,\n },\n ] as const,\n (json) => [\n (json as any)?.overload_errors ?? throwErr(\"overload_errors not found in AllOverloadsFailed details\"),\n ] as const,\n);\n\nconst ProjectAuthenticationError = createKnownErrorConstructor(\n KnownError,\n \"PROJECT_AUTHENTICATION_ERROR\",\n \"inherit\",\n \"inherit\",\n);\n\nconst InvalidProjectAuthentication = createKnownErrorConstructor(\n ProjectAuthenticationError,\n \"INVALID_PROJECT_AUTHENTICATION\",\n \"inherit\",\n \"inherit\",\n);\n\nconst ProjectKeyWithoutAccessType = createKnownErrorConstructor(\n InvalidProjectAuthentication,\n \"PROJECT_KEY_WITHOUT_ACCESS_TYPE\",\n () => [\n 400,\n \"Either an API key or an admin access token was provided, but the x-stack-access-type header is missing. Set it to 'client', 'server', or 'admin' as appropriate.\",\n ] as const,\n () => [] as const,\n);\n\nconst InvalidAccessType = createKnownErrorConstructor(\n InvalidProjectAuthentication,\n \"INVALID_ACCESS_TYPE\",\n (accessType: string) => [\n 400,\n `The x-stack-access-type header must be 'client', 'server', or 'admin', but was '${accessType}'.`,\n ] as const,\n (json) => [\n (json as any)?.accessType ?? throwErr(\"accessType not found in InvalidAccessType details\"),\n ] as const,\n);\n\nconst AccessTypeWithoutProjectId = createKnownErrorConstructor(\n InvalidProjectAuthentication,\n \"ACCESS_TYPE_WITHOUT_PROJECT_ID\",\n (accessType: \"client\" | \"server\" | \"admin\") => [\n 400,\n deindent`\n The x-stack-access-type header was '${accessType}', but the x-stack-project-id header was not provided.\n \n For more information, see the docs on REST API authentication: https://docs.stack-auth.com/rest-api/overview#authentication\n `,\n {\n request_type: accessType,\n },\n ] as const,\n (json: any) => [json.request_type] as const,\n);\n\nconst AccessTypeRequired = createKnownErrorConstructor(\n InvalidProjectAuthentication,\n \"ACCESS_TYPE_REQUIRED\",\n () => [\n 400,\n deindent`\n You must specify an access level for this Stack project. Make sure project API keys are provided (eg. x-stack-publishable-client-key) and you set the x-stack-access-type header to 'client', 'server', or 'admin'.\n \n For more information, see the docs on REST API authentication: https://docs.stack-auth.com/rest-api/overview#authentication\n `,\n ] as const,\n () => [] as const,\n);\n\nconst InsufficientAccessType = createKnownErrorConstructor(\n InvalidProjectAuthentication,\n \"INSUFFICIENT_ACCESS_TYPE\",\n (actualAccessType: \"client\" | \"server\" | \"admin\", allowedAccessTypes: (\"client\" | \"server\" | \"admin\")[]) => [\n 401,\n `The x-stack-access-type header must be ${allowedAccessTypes.map(s => `'${s}'`).join(\" or \")}, but was '${actualAccessType}'.`,\n {\n actual_access_type: actualAccessType,\n allowed_access_types: allowedAccessTypes,\n },\n ] as const,\n (json: any) => [\n json.actual_access_type,\n json.allowed_access_types,\n ] as const,\n);\n\nconst InvalidPublishableClientKey = createKnownErrorConstructor(\n InvalidProjectAuthentication,\n \"INVALID_PUBLISHABLE_CLIENT_KEY\",\n (projectId: string) => [\n 401,\n `The publishable key is not valid for the project ${JSON.stringify(projectId)}. Does the project and/or the key exist?`,\n {\n project_id: projectId,\n },\n ] as const,\n (json: any) => [json.project_id] as const,\n);\n\nconst InvalidSecretServerKey = createKnownErrorConstructor(\n InvalidProjectAuthentication,\n \"INVALID_SECRET_SERVER_KEY\",\n (projectId: string) => [\n 401,\n `The secret server key is not valid for the project ${JSON.stringify(projectId)}. Does the project and/or the key exist?`,\n {\n project_id: projectId,\n },\n ] as const,\n (json: any) => [json.project_id] as const,\n);\n\nconst InvalidSuperSecretAdminKey = createKnownErrorConstructor(\n InvalidProjectAuthentication,\n \"INVALID_SUPER_SECRET_ADMIN_KEY\",\n (projectId: string) => [\n 401,\n `The super secret admin key is not valid for the project ${JSON.stringify(projectId)}. Does the project and/or the key exist?`,\n {\n project_id: projectId,\n },\n ] as const,\n (json: any) => [json.project_id] as const,\n);\n\nconst InvalidAdminAccessToken = createKnownErrorConstructor(\n InvalidProjectAuthentication,\n \"INVALID_ADMIN_ACCESS_TOKEN\",\n \"inherit\",\n \"inherit\",\n);\n\nconst UnparsableAdminAccessToken = createKnownErrorConstructor(\n InvalidAdminAccessToken,\n \"UNPARSABLE_ADMIN_ACCESS_TOKEN\",\n () => [\n 401,\n \"Admin access token is not parsable.\",\n ] as const,\n () => [] as const,\n);\n\nconst AdminAccessTokenExpired = createKnownErrorConstructor(\n InvalidAdminAccessToken,\n \"ADMIN_ACCESS_TOKEN_EXPIRED\",\n (expiredAt: Date | undefined) => [\n 401,\n `Admin access token has expired. Please refresh it and try again.${expiredAt ? ` (The access token expired at ${expiredAt.toISOString()}.)` : \"\"}`,\n { expired_at_millis: expiredAt?.getTime() ?? null },\n ] as const,\n (json: any) => [json.expired_at_millis ? new Date(json.expired_at_millis) : undefined] as const,\n);\n\nconst InvalidProjectForAdminAccessToken = createKnownErrorConstructor(\n InvalidAdminAccessToken,\n \"INVALID_PROJECT_FOR_ADMIN_ACCESS_TOKEN\",\n () => [\n 401,\n \"Admin access tokens must be created on the internal project.\",\n ] as const,\n () => [] as const,\n);\n\nconst AdminAccessTokenIsNotAdmin = createKnownErrorConstructor(\n InvalidAdminAccessToken,\n \"ADMIN_ACCESS_TOKEN_IS_NOT_ADMIN\",\n () => [\n 401,\n \"Admin access token does not have the required permissions to access this project.\",\n ] as const,\n () => [] as const,\n);\n\n/**\n * @deprecated Use InsufficientAccessType instead\n */\nconst ProjectAuthenticationRequired = createKnownErrorConstructor(\n ProjectAuthenticationError,\n \"PROJECT_AUTHENTICATION_REQUIRED\",\n \"inherit\",\n \"inherit\",\n);\n\n\n/**\n * @deprecated Use InsufficientAccessType instead\n */\nconst ClientAuthenticationRequired = createKnownErrorConstructor(\n ProjectAuthenticationRequired,\n \"CLIENT_AUTHENTICATION_REQUIRED\",\n () => [\n 401,\n \"The publishable client key must be provided.\",\n ] as const,\n () => [] as const,\n);\n\nconst PublishableClientKeyRequiredForProject = createKnownErrorConstructor(\n ProjectAuthenticationRequired,\n \"PUBLISHABLE_CLIENT_KEY_REQUIRED_FOR_PROJECT\",\n (projectId?: string) => [\n 401,\n \"Publishable client keys are required for this project. Create one in Project Keys, or disable this requirement there to allow keyless client access.\",\n {\n project_id: projectId ?? null,\n },\n ] as const,\n (json: any) => [json.project_id ?? undefined] as const,\n);\n\n/**\n * @deprecated Use InsufficientAccessType instead\n */\nconst ServerAuthenticationRequired = createKnownErrorConstructor(\n ProjectAuthenticationRequired,\n \"SERVER_AUTHENTICATION_REQUIRED\",\n () => [\n 401,\n \"The secret server key must be provided.\",\n ] as const,\n () => [] as const,\n);\n\n/**\n * @deprecated Use InsufficientAccessType instead\n */\nconst ClientOrServerAuthenticationRequired = createKnownErrorConstructor(\n ProjectAuthenticationRequired,\n \"CLIENT_OR_SERVER_AUTHENTICATION_REQUIRED\",\n () => [\n 401,\n \"Either the publishable client key or the secret server key must be provided.\",\n ] as const,\n () => [] as const,\n);\n\n/**\n * @deprecated Use InsufficientAccessType instead\n */\nconst ClientOrAdminAuthenticationRequired = createKnownErrorConstructor(\n ProjectAuthenticationRequired,\n \"CLIENT_OR_ADMIN_AUTHENTICATION_REQUIRED\",\n () => [\n 401,\n \"Either the publishable client key or the super secret admin key must be provided.\",\n ] as const,\n () => [] as const,\n);\n\n/**\n * @deprecated Use InsufficientAccessType instead\n */\nconst ClientOrServerOrAdminAuthenticationRequired = createKnownErrorConstructor(\n ProjectAuthenticationRequired,\n \"CLIENT_OR_SERVER_OR_ADMIN_AUTHENTICATION_REQUIRED\",\n () => [\n 401,\n \"Either the publishable client key, the secret server key, or the super secret admin key must be provided.\",\n ] as const,\n () => [] as const,\n);\n\n/**\n * @deprecated Use InsufficientAccessType instead\n */\nconst AdminAuthenticationRequired = createKnownErrorConstructor(\n ProjectAuthenticationRequired,\n \"ADMIN_AUTHENTICATION_REQUIRED\",\n () => [\n 401,\n \"The super secret admin key must be provided.\",\n ] as const,\n () => [] as const,\n);\n\nconst ExpectedInternalProject = createKnownErrorConstructor(\n ProjectAuthenticationError,\n \"EXPECTED_INTERNAL_PROJECT\",\n () => [\n 401,\n \"The project ID is expected to be internal.\",\n ] as const,\n () => [] as const,\n);\n\nconst SessionAuthenticationError = createKnownErrorConstructor(\n KnownError,\n \"SESSION_AUTHENTICATION_ERROR\",\n \"inherit\",\n \"inherit\",\n);\n\nconst InvalidSessionAuthentication = createKnownErrorConstructor(\n SessionAuthenticationError,\n \"INVALID_SESSION_AUTHENTICATION\",\n \"inherit\",\n \"inherit\",\n);\n\nconst InvalidAccessToken = createKnownErrorConstructor(\n InvalidSessionAuthentication,\n \"INVALID_ACCESS_TOKEN\",\n \"inherit\",\n \"inherit\",\n);\n\nconst UnparsableAccessToken = createKnownErrorConstructor(\n InvalidAccessToken,\n \"UNPARSABLE_ACCESS_TOKEN\",\n () => [\n 401,\n \"Access token is not parsable.\",\n ] as const,\n () => [] as const,\n);\n\nconst AccessTokenExpired = createKnownErrorConstructor(\n InvalidAccessToken,\n \"ACCESS_TOKEN_EXPIRED\",\n (expiredAt: Date | undefined, projectId: string | undefined, userId: string | undefined, refreshTokenId: string | undefined) => [\n 401,\n deindent`\n Access token has expired. Please refresh it and try again.${expiredAt ? ` (The access token expired at ${expiredAt.toISOString()}.)` : \"\"}${projectId ? ` Project ID: ${projectId}.` : \"\"}${userId ? ` User ID: ${userId}.` : \"\"}${refreshTokenId ? ` Refresh token ID: ${refreshTokenId}.` : \"\"}\n\n Debug info: Most likely, you fetched the access token before it expired (for example, in a server component, pre-rendered page, or on page load), but then didn't refresh it before it expired. If this is the case, and you're using the SDK, make sure you call getAccessToken() every time you need to use the access token. If you're not using the SDK, make sure you refresh the access token with the refresh endpoint.\n `,\n {\n expired_at_millis: expiredAt?.getTime() ?? null,\n project_id: projectId ?? null,\n user_id: userId ?? null,\n refresh_token_id: refreshTokenId ?? null,\n },\n ] as const,\n (json: any) => [\n json.expired_at_millis ? new Date(json.expired_at_millis) : undefined,\n json.project_id ?? undefined,\n json.user_id ?? undefined,\n json.refresh_token_id ?? undefined,\n ] as const,\n);\n\nconst InvalidProjectForAccessToken = createKnownErrorConstructor(\n InvalidAccessToken,\n \"INVALID_PROJECT_FOR_ACCESS_TOKEN\",\n (expectedProjectId: string, actualProjectId: string) => [\n 401,\n `Access token not valid for this project. Expected project ID ${JSON.stringify(expectedProjectId)}, but the token is for project ID ${JSON.stringify(actualProjectId)}.`,\n {\n expected_project_id: expectedProjectId,\n actual_project_id: actualProjectId,\n },\n ] as const,\n (json: any) => [json.expected_project_id, json.actual_project_id] as const,\n);\n\n\nconst RefreshTokenError = createKnownErrorConstructor(\n KnownError,\n \"REFRESH_TOKEN_ERROR\",\n \"inherit\",\n \"inherit\",\n);\n\nconst RefreshTokenNotFoundOrExpired = createKnownErrorConstructor(\n RefreshTokenError,\n \"REFRESH_TOKEN_NOT_FOUND_OR_EXPIRED\",\n () => [\n 401,\n \"Refresh token not found for this project, or the session has expired/been revoked.\",\n ] as const,\n () => [] as const,\n);\n\nconst CannotDeleteCurrentSession = createKnownErrorConstructor(\n RefreshTokenError,\n \"CANNOT_DELETE_CURRENT_SESSION\",\n () => [\n 400,\n \"Cannot delete the current session.\",\n ] as const,\n () => [] as const,\n);\n\n\nconst ProviderRejected = createKnownErrorConstructor(\n RefreshTokenError,\n \"PROVIDER_REJECTED\",\n () => [\n 401,\n \"The provider refused to refresh their token. This usually means that the provider used to authenticate the user no longer regards this session as valid, and the user must re-authenticate.\",\n ] as const,\n () => [] as const,\n);\n\nconst UserWithEmailAlreadyExists = createKnownErrorConstructor(\n KnownError,\n \"USER_EMAIL_ALREADY_EXISTS\",\n (email: string, wouldWorkIfEmailWasVerified: boolean = false) => [\n 409,\n `A user with email ${JSON.stringify(email)} already exists${wouldWorkIfEmailWasVerified ? \" but the email is not verified. Please login to your existing account with the method you used to sign up, and then verify your email to sign in with this login method.\" : \".\"}`,\n {\n email,\n would_work_if_email_was_verified: wouldWorkIfEmailWasVerified,\n },\n ] as const,\n (json: any) => [json.email, json.would_work_if_email_was_verified ?? false] as const,\n);\n\nconst EmailNotVerified = createKnownErrorConstructor(\n KnownError,\n \"EMAIL_NOT_VERIFIED\",\n () => [\n 400,\n \"The email is not verified.\",\n ] as const,\n () => [] as const,\n);\n\nconst CannotGetOwnUserWithoutUser = createKnownErrorConstructor(\n KnownError,\n \"CANNOT_GET_OWN_USER_WITHOUT_USER\",\n () => [\n 400,\n \"You have specified 'me' as a userId, but did not provide authentication for a user.\",\n ] as const,\n () => [] as const,\n);\n\nconst UserIdDoesNotExist = createKnownErrorConstructor(\n KnownError,\n \"USER_ID_DOES_NOT_EXIST\",\n (userId: string) => [\n 400,\n `The given user with the ID ${userId} does not exist.`,\n {\n user_id: userId,\n },\n ] as const,\n (json: any) => [json.user_id] as const,\n);\n\nconst UserNotFound = createKnownErrorConstructor(\n KnownError,\n \"USER_NOT_FOUND\",\n () => [\n 404,\n \"User not found.\",\n ] as const,\n () => [] as const,\n);\n\nconst RestrictedUserNotAllowed = createKnownErrorConstructor(\n KnownError,\n \"RESTRICTED_USER_NOT_ALLOWED\",\n (restrictedReason: { type: \"anonymous\" | \"email_not_verified\" | \"restricted_by_administrator\" }) => [\n 403,\n `The user in the access token is in restricted state. Reason: ${restrictedReason.type}. Please pass the X-Stack-Allow-Restricted-User header if this is intended.`,\n {\n restricted_reason: restrictedReason,\n },\n ] as const,\n (json: any) => [json.restricted_reason ?? { type: \"anonymous\" }] as const,\n);\n\nconst ProjectNotFound = createKnownErrorConstructor(\n KnownError,\n \"PROJECT_NOT_FOUND\",\n (projectId: string) => {\n if (typeof projectId !== \"string\") throw new StackAssertionError(\"projectId of KnownErrors.ProjectNotFound must be a string\");\n return [\n 404,\n `Project ${projectId} not found or is not accessible with the current user.`,\n {\n project_id: projectId,\n },\n ] as const;\n },\n (json: any) => [json.project_id] as const,\n);\n\nconst CurrentProjectNotFound = createKnownErrorConstructor(\n KnownError,\n \"CURRENT_PROJECT_NOT_FOUND\",\n (projectId: string) => [\n 400,\n `The current project with ID ${projectId} was not found. Please check the value of the x-stack-project-id header.`,\n {\n project_id: projectId,\n },\n ] as const,\n (json: any) => [json.project_id] as const,\n);\n\nconst BranchDoesNotExist = createKnownErrorConstructor(\n KnownError,\n \"BRANCH_DOES_NOT_EXIST\",\n (branchId: string) => [\n 400,\n `The branch with ID ${branchId} does not exist.`,\n {\n branch_id: branchId,\n },\n ] as const,\n (json: any) => [json.branch_id] as const,\n);\n\n\nconst SignUpNotEnabled = createKnownErrorConstructor(\n KnownError,\n \"SIGN_UP_NOT_ENABLED\",\n () => [\n 400,\n \"Creation of new accounts is not enabled for this project. Please ask the project owner to enable it.\",\n ] as const,\n () => [] as const,\n);\n\nconst SignUpRejected = createKnownErrorConstructor(\n KnownError,\n \"SIGN_UP_REJECTED\",\n (message?: string) => [\n 403,\n message ?? \"Your sign up was rejected by an administrator's sign-up rule.\",\n {\n message: message ?? \"Your sign up was rejected by an administrator's sign-up rule.\",\n },\n ] as const,\n (json: any) => [json.message] as const,\n);\n\nconst PasswordAuthenticationNotEnabled = createKnownErrorConstructor(\n KnownError,\n \"PASSWORD_AUTHENTICATION_NOT_ENABLED\",\n () => [\n 400,\n \"Password authentication is not enabled for this project.\",\n ] as const,\n () => [] as const,\n);\n\nconst DataVaultStoreDoesNotExist = createKnownErrorConstructor(\n KnownError,\n \"DATA_VAULT_STORE_DOES_NOT_EXIST\",\n (storeId: string) => [\n 400,\n `Data vault store with ID ${storeId} does not exist.`,\n {\n store_id: storeId,\n },\n ] as const,\n (json: any) => [json.store_id] as const,\n);\n\nconst DataVaultStoreHashedKeyDoesNotExist = createKnownErrorConstructor(\n KnownError,\n \"DATA_VAULT_STORE_HASHED_KEY_DOES_NOT_EXIST\",\n (storeId: string, hashedKey: string) => [\n 400,\n `Data vault store with ID ${storeId} does not contain a key with hash ${hashedKey}.`,\n {\n store_id: storeId,\n hashed_key: hashedKey,\n },\n ] as const,\n (json: any) => [json.store_id, json.hashed_key] as const,\n);\n\nconst PasskeyAuthenticationNotEnabled = createKnownErrorConstructor(\n KnownError,\n \"PASSKEY_AUTHENTICATION_NOT_ENABLED\",\n () => [\n 400,\n \"Passkey authentication is not enabled for this project.\",\n ] as const,\n () => [] as const,\n);\n\nconst AnonymousAccountsNotEnabled = createKnownErrorConstructor(\n KnownError,\n \"ANONYMOUS_ACCOUNTS_NOT_ENABLED\",\n () => [\n 400,\n \"Anonymous accounts are not enabled for this project.\",\n ] as const,\n () => [] as const,\n);\n\nconst AnonymousAuthenticationNotAllowed = createKnownErrorConstructor(\n KnownError,\n \"ANONYMOUS_AUTHENTICATION_NOT_ALLOWED\",\n () => [\n 401,\n \"X-Stack-Access-Token is for an anonymous user, but anonymous users are not enabled. Set the X-Stack-Allow-Anonymous-User header of this request to 'true' to allow anonymous users.\",\n ] as const,\n () => [] as const,\n);\n\n\nconst EmailPasswordMismatch = createKnownErrorConstructor(\n KnownError,\n \"EMAIL_PASSWORD_MISMATCH\",\n () => [\n 400,\n \"Wrong e-mail or password.\",\n ] as const,\n () => [] as const,\n);\n\nconst RedirectUrlNotWhitelisted = createKnownErrorConstructor(\n KnownError,\n \"REDIRECT_URL_NOT_WHITELISTED\",\n () => [\n 400,\n \"Redirect URL not whitelisted. Did you forget to add this domain to the trusted domains list on the Stack Auth dashboard?\",\n ] as const,\n () => [] as const,\n);\n\nconst PasswordRequirementsNotMet = createKnownErrorConstructor(\n KnownError,\n \"PASSWORD_REQUIREMENTS_NOT_MET\",\n \"inherit\",\n \"inherit\",\n);\n\nconst PasswordTooShort = createKnownErrorConstructor(\n PasswordRequirementsNotMet,\n \"PASSWORD_TOO_SHORT\",\n (minLength: number) => [\n 400,\n `Password too short. Minimum length is ${minLength}.`,\n {\n min_length: minLength,\n },\n ] as const,\n (json) => [\n (json as any)?.min_length ?? throwErr(\"min_length not found in PasswordTooShort details\"),\n ] as const,\n);\n\nconst PasswordTooLong = createKnownErrorConstructor(\n PasswordRequirementsNotMet,\n \"PASSWORD_TOO_LONG\",\n (maxLength: number) => [\n 400,\n `Password too long. Maximum length is ${maxLength}.`,\n {\n maxLength,\n },\n ] as const,\n (json) => [\n (json as any)?.maxLength ?? throwErr(\"maxLength not found in PasswordTooLong details\"),\n ] as const,\n);\n\nconst UserDoesNotHavePassword = createKnownErrorConstructor(\n KnownError,\n \"USER_DOES_NOT_HAVE_PASSWORD\",\n () => [\n 400,\n \"This user does not have password authentication enabled.\",\n ] as const,\n () => [] as const,\n);\n\nconst VerificationCodeError = createKnownErrorConstructor(\n KnownError,\n \"VERIFICATION_ERROR\",\n \"inherit\",\n \"inherit\",\n);\n\nconst VerificationCodeNotFound = createKnownErrorConstructor(\n VerificationCodeError,\n \"VERIFICATION_CODE_NOT_FOUND\",\n () => [\n 404,\n \"The verification code does not exist for this project.\",\n ] as const,\n () => [] as const,\n);\n\nconst VerificationCodeExpired = createKnownErrorConstructor(\n VerificationCodeError,\n \"VERIFICATION_CODE_EXPIRED\",\n () => [\n 400,\n \"The verification code has expired.\",\n ] as const,\n () => [] as const,\n);\n\nconst VerificationCodeAlreadyUsed = createKnownErrorConstructor(\n VerificationCodeError,\n \"VERIFICATION_CODE_ALREADY_USED\",\n () => [\n 409,\n \"The verification link has already been used.\",\n ] as const,\n () => [] as const,\n);\n\nconst VerificationCodeMaxAttemptsReached = createKnownErrorConstructor(\n VerificationCodeError,\n \"VERIFICATION_CODE_MAX_ATTEMPTS_REACHED\",\n () => [\n 400,\n \"The verification code nonce has reached the maximum number of attempts. This code is not valid anymore.\",\n ] as const,\n () => [] as const,\n);\n\nconst PasswordConfirmationMismatch = createKnownErrorConstructor(\n KnownError,\n \"PASSWORD_CONFIRMATION_MISMATCH\",\n () => [\n 400,\n \"Passwords do not match.\",\n ] as const,\n () => [] as const,\n);\n\nconst EmailAlreadyVerified = createKnownErrorConstructor(\n KnownError,\n \"EMAIL_ALREADY_VERIFIED\",\n () => [\n 409,\n \"The e-mail is already verified.\",\n ] as const,\n () => [] as const,\n);\n\nconst EmailNotAssociatedWithUser = createKnownErrorConstructor(\n KnownError,\n \"EMAIL_NOT_ASSOCIATED_WITH_USER\",\n () => [\n 400,\n \"The e-mail is not associated with a user that could log in with that e-mail.\",\n ] as const,\n () => [] as const,\n);\n\nconst EmailIsNotPrimaryEmail = createKnownErrorConstructor(\n KnownError,\n \"EMAIL_IS_NOT_PRIMARY_EMAIL\",\n (email: string, primaryEmail: string | null) => [\n 400,\n `The given e-mail (${email}) must equal the user's primary e-mail (${primaryEmail}).`,\n {\n email,\n primary_email: primaryEmail,\n },\n ] as const,\n (json: any) => [json.email, json.primary_email] as const,\n);\n\n\nconst PasskeyRegistrationFailed = createKnownErrorConstructor(\n KnownError,\n \"PASSKEY_REGISTRATION_FAILED\",\n (message: string) => [\n 400,\n message,\n ] as const,\n (json: any) => [json.message] as const,\n);\n\n\nconst PasskeyWebAuthnError = createKnownErrorConstructor(\n KnownError,\n \"PASSKEY_WEBAUTHN_ERROR\",\n (message: string, code: string) => [\n 400,\n message,\n {\n message,\n code,\n },\n ] as const,\n (json: any) => [json.message, json.code] as const,\n);\n\nconst PasskeyAuthenticationFailed = createKnownErrorConstructor(\n KnownError,\n \"PASSKEY_AUTHENTICATION_FAILED\",\n (message: string) => [\n 400,\n message,\n ] as const,\n (json: any) => [json.message] as const,\n);\n\n\nconst PermissionNotFound = createKnownErrorConstructor(\n KnownError,\n \"PERMISSION_NOT_FOUND\",\n (permissionId: string) => [\n 404,\n `Permission \"${permissionId}\" not found. Make sure you created it on the dashboard.`,\n {\n permission_id: permissionId,\n },\n ] as const,\n (json: any) => [json.permission_id] as const,\n);\n\nconst PermissionScopeMismatch = createKnownErrorConstructor(\n KnownError,\n \"WRONG_PERMISSION_SCOPE\",\n (permissionId: string, expectedScope: \"team\" | \"project\", actualScope: \"team\" | \"project\" | null) => [\n 404,\n `Permission ${JSON.stringify(permissionId)} not found. (It was found for a different scope ${JSON.stringify(actualScope)}, but scope ${JSON.stringify(expectedScope)} was expected.)`,\n {\n permission_id: permissionId,\n expected_scope: expectedScope,\n actual_scope: actualScope,\n },\n ] as const,\n (json: any) => [json.permission_id, json.expected_scope, json.actual_scope] as const,\n);\n\nconst ContainedPermissionNotFound = createKnownErrorConstructor(\n KnownError,\n \"CONTAINED_PERMISSION_NOT_FOUND\",\n (permissionId: string) => [\n 400,\n `Contained permission with ID \"${permissionId}\" not found. Make sure you created it on the dashboard.`,\n {\n permission_id: permissionId,\n },\n ] as const,\n (json: any) => [json.permission_id] as const,\n);\n\nconst TeamNotFound = createKnownErrorConstructor(\n KnownError,\n \"TEAM_NOT_FOUND\",\n (teamId: string) => [\n 404,\n `Team ${teamId} not found.`,\n {\n team_id: teamId,\n },\n ] as const,\n (json: any) => [json.team_id] as const,\n);\n\nconst TeamAlreadyExists = createKnownErrorConstructor(\n KnownError,\n \"TEAM_ALREADY_EXISTS\",\n (teamId: string) => [\n 409,\n `Team ${teamId} already exists.`,\n {\n team_id: teamId,\n },\n ] as const,\n (json: any) => [json.team_id] as const,\n);\n\nconst TeamMembershipNotFound = createKnownErrorConstructor(\n KnownError,\n \"TEAM_MEMBERSHIP_NOT_FOUND\",\n (teamId: string, userId: string) => [\n 404,\n `User ${userId} is not found in team ${teamId}.`,\n {\n team_id: teamId,\n user_id: userId,\n },\n ] as const,\n (json: any) => [json.team_id, json.user_id] as const,\n);\n\nconst TeamInvitationRestrictedUserNotAllowed = createKnownErrorConstructor(\n KnownError,\n \"TEAM_INVITATION_RESTRICTED_USER_NOT_ALLOWED\",\n (restrictedReason: { type: \"anonymous\" | \"email_not_verified\" | \"restricted_by_administrator\" }) => [\n 403,\n `Restricted users cannot accept team invitations. Reason: ${restrictedReason.type}. Please complete the onboarding process before accepting team invitations.`,\n {\n restricted_reason: restrictedReason,\n },\n ] as const,\n (json: any) => [json.restricted_reason ?? { type: \"anonymous\" }] as const,\n);\n\n\nconst EmailTemplateAlreadyExists = createKnownErrorConstructor(\n KnownError,\n \"EMAIL_TEMPLATE_ALREADY_EXISTS\",\n () => [\n 409,\n \"Email template already exists.\",\n ] as const,\n () => [] as const,\n);\n\nconst OAuthConnectionNotConnectedToUser = createKnownErrorConstructor(\n KnownError,\n \"OAUTH_CONNECTION_NOT_CONNECTED_TO_USER\",\n () => [\n 400,\n \"The OAuth connection is not connected to any user.\",\n ] as const,\n () => [] as const,\n);\n\nconst OAuthConnectionAlreadyConnectedToAnotherUser = createKnownErrorConstructor(\n KnownError,\n \"OAUTH_CONNECTION_ALREADY_CONNECTED_TO_ANOTHER_USER\",\n () => [\n 409,\n \"The OAuth connection is already connected to another user.\",\n ] as const,\n () => [] as const,\n);\n\nconst OAuthConnectionDoesNotHaveRequiredScope = createKnownErrorConstructor(\n KnownError,\n \"OAUTH_CONNECTION_DOES_NOT_HAVE_REQUIRED_SCOPE\",\n () => [\n 400,\n \"The OAuth connection does not have the required scope.\",\n ] as const,\n () => [] as const,\n);\n\nconst OAuthAccessTokenNotAvailable = createKnownErrorConstructor(\n KnownError,\n \"OAUTH_ACCESS_TOKEN_NOT_AVAILABLE\",\n (provider: string, details: string) => [\n 400,\n `Failed to retrieve an OAuth access token for the connected account (provider: ${provider}). ${details}`,\n {\n provider,\n details,\n } as const,\n ] as const,\n (json: any) => [json.provider, json.details] as const,\n);\n\nconst OAuthExtraScopeNotAvailableWithSharedOAuthKeys = createKnownErrorConstructor(\n KnownError,\n \"OAUTH_EXTRA_SCOPE_NOT_AVAILABLE_WITH_SHARED_OAUTH_KEYS\",\n () => [\n 400,\n \"Extra scopes are not available with shared OAuth keys. Please add your own OAuth keys on the Stack dashboard to use extra scopes.\",\n ] as const,\n () => [] as const,\n);\n\nconst OAuthAccessTokenNotAvailableWithSharedOAuthKeys = createKnownErrorConstructor(\n KnownError,\n \"OAUTH_ACCESS_TOKEN_NOT_AVAILABLE_WITH_SHARED_OAUTH_KEYS\",\n () => [\n 400,\n \"Access tokens are not available with shared OAuth keys. Please add your own OAuth keys on the Stack dashboard to use access tokens.\",\n ] as const,\n () => [] as const,\n);\n\nconst InvalidOAuthClientIdOrSecret = createKnownErrorConstructor(\n KnownError,\n \"INVALID_OAUTH_CLIENT_ID_OR_SECRET\",\n (clientId?: string) => [\n 400,\n \"The OAuth client ID or secret is invalid. The client ID must be equal to the project ID (potentially with a hash and a branch ID), and the client secret must be a publishable client key.\",\n {\n client_id: clientId ?? null,\n },\n ] as const,\n (json: any) => [json.client_id ?? undefined] as const,\n);\n\nconst InvalidScope = createKnownErrorConstructor(\n KnownError,\n \"INVALID_SCOPE\",\n (scope: string) => [\n 400,\n `The scope \"${scope}\" is not a valid OAuth scope for Stack.`,\n ] as const,\n (json: any) => [json.scope] as const,\n);\n\nconst UserAlreadyConnectedToAnotherOAuthConnection = createKnownErrorConstructor(\n KnownError,\n \"USER_ALREADY_CONNECTED_TO_ANOTHER_OAUTH_CONNECTION\",\n () => [\n 409,\n \"The user is already connected to another OAuth account. Did you maybe selected the wrong account?\",\n ] as const,\n () => [] as const,\n);\n\nconst OuterOAuthTimeout = createKnownErrorConstructor(\n KnownError,\n \"OUTER_OAUTH_TIMEOUT\",\n () => [\n 408,\n \"The OAuth flow has timed out. Please sign in again.\",\n ] as const,\n () => [] as const,\n);\n\nconst OAuthProviderNotFoundOrNotEnabled = createKnownErrorConstructor(\n KnownError,\n \"OAUTH_PROVIDER_NOT_FOUND_OR_NOT_ENABLED\",\n () => [\n 400,\n \"The OAuth provider is not found or not enabled.\",\n ] as const,\n () => [] as const,\n);\n\nconst AppleBundleIdNotConfigured = createKnownErrorConstructor(\n KnownError,\n \"APPLE_BUNDLE_ID_NOT_CONFIGURED\",\n () => [\n 400,\n \"Apple Sign In is enabled, but no Bundle IDs are configured. Please add your app's Bundle ID in the Stack Auth dashboard under OAuth Providers > Apple > Apple Bundle IDs.\",\n ] as const,\n () => [] as const,\n);\n\nconst OAuthProviderAccountIdAlreadyUsedForSignIn = createKnownErrorConstructor(\n KnownError,\n \"OAUTH_PROVIDER_ACCOUNT_ID_ALREADY_USED_FOR_SIGN_IN\",\n () => [\n 400,\n `A provider with the same account ID is already used for signing in.`,\n ] as const,\n () => [] as const,\n);\n\nconst MultiFactorAuthenticationRequired = createKnownErrorConstructor(\n KnownError,\n \"MULTI_FACTOR_AUTHENTICATION_REQUIRED\",\n (attemptCode: string) => [\n 400,\n `Multi-factor authentication is required for this user.`,\n {\n attempt_code: attemptCode,\n },\n ] as const,\n (json) => [json.attempt_code] as const,\n);\n\nconst InvalidTotpCode = createKnownErrorConstructor(\n KnownError,\n \"INVALID_TOTP_CODE\",\n () => [\n 400,\n \"The TOTP code is invalid. Please try again.\",\n ] as const,\n () => [] as const,\n);\n\nconst UserAuthenticationRequired = createKnownErrorConstructor(\n KnownError,\n \"USER_AUTHENTICATION_REQUIRED\",\n () => [\n 401,\n \"User authentication required for this endpoint.\",\n ] as const,\n () => [] as const,\n);\n\nconst TeamMembershipAlreadyExists = createKnownErrorConstructor(\n KnownError,\n \"TEAM_MEMBERSHIP_ALREADY_EXISTS\",\n () => [\n 409,\n \"Team membership already exists.\",\n ] as const,\n () => [] as const,\n);\n\nconst ProjectPermissionRequired = createKnownErrorConstructor(\n KnownError,\n \"PROJECT_PERMISSION_REQUIRED\",\n (userId, permissionId) => [\n 401,\n `User ${userId} does not have permission ${permissionId}.`,\n {\n user_id: userId,\n permission_id: permissionId,\n },\n ] as const,\n (json) => [json.user_id, json.permission_id] as const,\n);\n\nconst TeamPermissionRequired = createKnownErrorConstructor(\n KnownError,\n \"TEAM_PERMISSION_REQUIRED\",\n (teamId, userId, permissionId) => [\n 401,\n `User ${userId} does not have permission ${permissionId} in team ${teamId}.`,\n {\n team_id: teamId,\n user_id: userId,\n permission_id: permissionId,\n },\n ] as const,\n (json) => [json.team_id, json.user_id, json.permission_id] as const,\n);\n\nconst TeamPermissionNotFound = createKnownErrorConstructor(\n KnownError,\n \"TEAM_PERMISSION_NOT_FOUND\",\n (teamId, userId, permissionId) => [\n 401,\n `User ${userId} does not have permission ${permissionId} in team ${teamId}.`,\n {\n team_id: teamId,\n user_id: userId,\n permission_id: permissionId,\n },\n ] as const,\n (json) => [json.team_id, json.user_id, json.permission_id] as const,\n);\n\nconst InvalidSharedOAuthProviderId = createKnownErrorConstructor(\n KnownError,\n \"INVALID_SHARED_OAUTH_PROVIDER_ID\",\n (providerId) => [\n 400,\n `The shared OAuth provider with ID ${providerId} is not valid.`,\n {\n provider_id: providerId,\n },\n ] as const,\n (json) => [json.provider_id] as const,\n);\n\nconst InvalidStandardOAuthProviderId = createKnownErrorConstructor(\n KnownError,\n \"INVALID_STANDARD_OAUTH_PROVIDER_ID\",\n (providerId) => [\n 400,\n `The standard OAuth provider with ID ${providerId} is not valid.`,\n {\n provider_id: providerId,\n },\n ] as const,\n (json) => [json.provider_id] as const,\n);\n\nconst InvalidAuthorizationCode = createKnownErrorConstructor(\n KnownError,\n \"INVALID_AUTHORIZATION_CODE\",\n () => [\n 400,\n \"The given authorization code is invalid.\",\n ] as const,\n () => [] as const,\n);\n\nconst InvalidAppleCredentials = createKnownErrorConstructor(\n KnownError,\n \"INVALID_APPLE_CREDENTIALS\",\n () => [\n 400,\n \"The Apple Sign In credentials could not be verified. Please try signing in again.\",\n ] as const,\n () => [] as const,\n);\n\nconst OAuthProviderAccessDenied = createKnownErrorConstructor(\n KnownError,\n \"OAUTH_PROVIDER_ACCESS_DENIED\",\n () => [\n 400,\n \"The OAuth provider denied access to the user.\",\n ] as const,\n () => [] as const,\n);\n\nconst ContactChannelAlreadyUsedForAuthBySomeoneElse = createKnownErrorConstructor(\n KnownError,\n \"CONTACT_CHANNEL_ALREADY_USED_FOR_AUTH_BY_SOMEONE_ELSE\",\n (type: \"email\", contactChannelValue?: string, wouldWorkIfEmailWasVerified: boolean = false) => [\n 409,\n `This ${type} ${contactChannelValue ? `\"(${contactChannelValue})\"` : \"\"} is already used for authentication by another account${wouldWorkIfEmailWasVerified ? \" but the email is not verified. Please login to your existing account with the method you used to sign up, and then verify your email to sign in with this login method.\" : \".\"}`,\n {\n type,\n contact_channel_value: contactChannelValue ?? null,\n would_work_if_email_was_verified: wouldWorkIfEmailWasVerified,\n },\n ] as const,\n (json) => [json.type, json.contact_channel_value, json.would_work_if_email_was_verified ?? false] as const,\n);\n\nconst InvalidPollingCodeError = createKnownErrorConstructor(\n KnownError,\n \"INVALID_POLLING_CODE\",\n (details?: Json) => [\n 400,\n \"The polling code is invalid or does not exist.\",\n details,\n ] as const,\n (json: any) => [json] as const,\n);\n\nconst CliAuthError = createKnownErrorConstructor(\n KnownError,\n \"CLI_AUTH_ERROR\",\n (message: string) => [\n 400,\n message,\n ] as const,\n (json: any) => [json.message] as const,\n);\n\nconst CliAuthExpiredError = createKnownErrorConstructor(\n KnownError,\n \"CLI_AUTH_EXPIRED_ERROR\",\n (message: string = \"CLI authentication request expired. Please try again.\") => [\n 400,\n message,\n ] as const,\n (json: any) => [json.message] as const,\n);\n\nconst CliAuthUsedError = createKnownErrorConstructor(\n KnownError,\n \"CLI_AUTH_USED_ERROR\",\n (message: string = \"This authentication token has already been used.\") => [\n 400,\n message,\n ] as const,\n (json: any) => [json.message] as const,\n);\n\n\nconst ApiKeyNotValid = createKnownErrorConstructor(\n KnownError,\n \"API_KEY_NOT_VALID\",\n \"inherit\",\n \"inherit\",\n);\n\nconst ApiKeyExpired = createKnownErrorConstructor(\n ApiKeyNotValid,\n \"API_KEY_EXPIRED\",\n () => [\n 401,\n \"API key has expired.\",\n ] as const,\n () => [] as const,\n);\n\nconst ApiKeyRevoked = createKnownErrorConstructor(\n ApiKeyNotValid,\n \"API_KEY_REVOKED\",\n () => [\n 401,\n \"API key has been revoked.\",\n ] as const,\n () => [] as const,\n);\n\nconst WrongApiKeyType = createKnownErrorConstructor(\n ApiKeyNotValid,\n \"WRONG_API_KEY_TYPE\",\n (expectedType: string, actualType: string) => [\n 400,\n `This endpoint is for ${expectedType} API keys, but a ${actualType} API key was provided.`,\n { expected_type: expectedType, actual_type: actualType },\n ] as const,\n (json) => [json.expected_type, json.actual_type] as const,\n);\n\nconst ApiKeyNotFound = createKnownErrorConstructor(\n ApiKeyNotValid,\n \"API_KEY_NOT_FOUND\",\n () => [\n 404,\n \"API key not found.\",\n ] as const,\n () => [] as const,\n);\n\nconst PublicApiKeyCannotBeRevoked = createKnownErrorConstructor(\n ApiKeyNotValid,\n \"PUBLIC_API_KEY_CANNOT_BE_REVOKED\",\n () => [\n 400,\n \"Public API keys cannot be revoked by the secretscanner endpoint.\",\n ] as const,\n () => [] as const,\n);\nconst PermissionIdAlreadyExists = createKnownErrorConstructor(\n KnownError,\n \"PERMISSION_ID_ALREADY_EXISTS\",\n (permissionId: string) => [\n 400,\n `Permission with ID \"${permissionId}\" already exists. Choose a different ID.`,\n {\n permission_id: permissionId,\n },\n ] as const,\n (json: any) => [json.permission_id] as const,\n);\n\nconst EmailRenderingError = createKnownErrorConstructor(\n KnownError,\n \"EMAIL_RENDERING_ERROR\",\n (error: string) => [\n 400,\n `Failed to render email with theme: ${error}`,\n { error },\n ] as const,\n (json: any) => [json.error] as const,\n);\n\nconst TemplateSourceRewriteError = createKnownErrorConstructor(\n KnownError,\n \"TEMPLATE_SOURCE_REWRITE_ERROR\",\n (error: string) => [\n 400,\n `Failed to rewrite template source: ${error}`,\n { error },\n ] as const,\n (json: any) => [json.error] as const,\n);\n\nconst RequiresCustomEmailServer = createKnownErrorConstructor(\n KnownError,\n \"REQUIRES_CUSTOM_EMAIL_SERVER\",\n () => [\n 400,\n `This action requires a custom SMTP server. Please edit your email server configuration and try again.`,\n ] as const,\n () => [] as const,\n);\n\nconst EmailCapacityBoostAlreadyActive = createKnownErrorConstructor(\n KnownError,\n \"EMAIL_CAPACITY_BOOST_ALREADY_ACTIVE\",\n (expiresAt: string) => [\n 409,\n `Email capacity boost is already active until ${expiresAt}.`,\n { expires_at: expiresAt },\n ] as const,\n (json: any) => [json.expires_at] as const,\n);\n\nconst EmailNotEditable = createKnownErrorConstructor(\n KnownError,\n \"EMAIL_NOT_EDITABLE\",\n (emailId: string, status: string) => [\n 400,\n `Email with ID \"${emailId}\" cannot be edited because it is in status \"${status}\". Only emails in PAUSED, PREPARING, RENDERING, RENDER_ERROR, SCHEDULED, QUEUED, or SERVER_ERROR status can be edited.`,\n {\n email_id: emailId,\n status,\n },\n ] as const,\n (json: any) => [json.email_id, json.status] as const,\n);\n\nconst ItemNotFound = createKnownErrorConstructor(\n KnownError,\n \"ITEM_NOT_FOUND\",\n (itemId: string) => [\n 404,\n `Item with ID \"${itemId}\" not found.`,\n {\n item_id: itemId,\n },\n ] as const,\n (json) => [json.item_id] as const,\n);\n\nconst ItemCustomerTypeDoesNotMatch = createKnownErrorConstructor(\n KnownError,\n \"ITEM_CUSTOMER_TYPE_DOES_NOT_MATCH\",\n (itemId: string, customerId: string, itemCustomerType: \"user\" | \"team\" | \"custom\" | undefined, actualCustomerType: \"user\" | \"team\" | \"custom\") => [\n 400,\n `The ${actualCustomerType} with ID ${JSON.stringify(customerId)} is not a valid customer for the item with ID ${JSON.stringify(itemId)}. ${itemCustomerType ? `The item is configured to only be available for ${itemCustomerType} customers, but the customer is a ${actualCustomerType}.` : `The item is missing a customer type field. Please make sure it is set up correctly in your project configuration.`}`,\n {\n item_id: itemId,\n customer_id: customerId,\n item_customer_type: itemCustomerType ?? null,\n actual_customer_type: actualCustomerType,\n },\n ] as const,\n (json) => [json.item_id, json.customer_id, json.item_customer_type ?? undefined, json.actual_customer_type] as const,\n);\n\nconst CustomerDoesNotExist = createKnownErrorConstructor(\n KnownError,\n \"CUSTOMER_DOES_NOT_EXIST\",\n (customerId: string) => [\n 400,\n `Customer with ID ${JSON.stringify(customerId)} does not exist.`,\n {\n customer_id: customerId,\n },\n ] as const,\n (json) => [json.customer_id] as const,\n);\n\nconst SubscriptionInvoiceNotFound = createKnownErrorConstructor(\n KnownError,\n \"SUBSCRIPTION_INVOICE_NOT_FOUND\",\n (subscriptionInvoiceId: string) => [\n 404,\n `Subscription invoice with ID ${JSON.stringify(subscriptionInvoiceId)} does not exist.`,\n {\n subscription_invoice_id: subscriptionInvoiceId,\n },\n ] as const,\n (json) => [json.subscription_invoice_id] as const,\n);\n\nconst OneTimePurchaseNotFound = createKnownErrorConstructor(\n KnownError,\n \"ONE_TIME_PURCHASE_NOT_FOUND\",\n (purchaseId: string) => [\n 404,\n `One-time purchase with ID ${JSON.stringify(purchaseId)} does not exist.`,\n {\n one_time_purchase_id: purchaseId,\n },\n ] as const,\n (json) => [json.one_time_purchase_id] as const,\n);\n\nconst SubscriptionAlreadyRefunded = createKnownErrorConstructor(\n KnownError,\n \"SUBSCRIPTION_ALREADY_REFUNDED\",\n (subscriptionId: string) => [\n 400,\n `Subscription with ID ${JSON.stringify(subscriptionId)} was already refunded.`,\n {\n subscription_id: subscriptionId,\n },\n ] as const,\n (json) => [json.subscription_id] as const,\n);\n\nconst OneTimePurchaseAlreadyRefunded = createKnownErrorConstructor(\n KnownError,\n \"ONE_TIME_PURCHASE_ALREADY_REFUNDED\",\n (purchaseId: string) => [\n 400,\n `One-time purchase with ID ${JSON.stringify(purchaseId)} was already refunded.`,\n {\n one_time_purchase_id: purchaseId,\n },\n ] as const,\n (json) => [json.one_time_purchase_id] as const,\n);\n\nconst TestModePurchaseNonRefundable = createKnownErrorConstructor(\n KnownError,\n \"TEST_MODE_PURCHASE_NON_REFUNDABLE\",\n () => [\n 400,\n \"Test mode purchases are not refundable.\",\n ] as const,\n () => [] as const,\n);\n\n\nconst ProductDoesNotExist = createKnownErrorConstructor(\n KnownError,\n \"PRODUCT_DOES_NOT_EXIST\",\n (productId: string, context: \"item_exists\" | \"server_only\" | null) => [\n 400,\n `Product with ID ${JSON.stringify(productId)} ${context === \"server_only\"\n ? \"is marked as server-only and cannot be accessed client side.\"\n : context === \"item_exists\"\n ? \"does not exist, but an item with this ID exists.\"\n : \"does not exist.\"\n }`,\n {\n product_id: productId,\n context,\n } as const,\n ] as const,\n (json) => [json.product_id, json.context] as const,\n);\n\nconst ProductCustomerTypeDoesNotMatch = createKnownErrorConstructor(\n KnownError,\n \"PRODUCT_CUSTOMER_TYPE_DOES_NOT_MATCH\",\n (productId: string | undefined, customerId: string, productCustomerType: \"user\" | \"team\" | \"custom\" | undefined, actualCustomerType: \"user\" | \"team\" | \"custom\") => [\n 400,\n `The ${actualCustomerType} with ID ${JSON.stringify(customerId)} is not a valid customer for the inline product that has been passed in. ${productCustomerType ? `The product is configured to only be available for ${productCustomerType} customers, but the customer is a ${actualCustomerType}.` : `The product is missing a customer type field. Please make sure it is set up correctly in your project configuration.`}`,\n {\n product_id: productId ?? null,\n customer_id: customerId,\n product_customer_type: productCustomerType ?? null,\n actual_customer_type: actualCustomerType,\n },\n ] as const,\n (json) => [json.product_id ?? undefined, json.customer_id, json.product_customer_type ?? undefined, json.actual_customer_type] as const,\n);\n\nconst ProductAlreadyGranted = createKnownErrorConstructor(\n KnownError,\n \"PRODUCT_ALREADY_GRANTED\",\n (productId: string, customerId: string) => [\n 400,\n `Customer with ID ${JSON.stringify(customerId)} already owns product ${JSON.stringify(productId)}.`,\n {\n product_id: productId,\n customer_id: customerId,\n },\n ] as const,\n (json) => [json.product_id, json.customer_id] as const,\n);\n\nconst ItemQuantityInsufficientAmount = createKnownErrorConstructor(\n KnownError,\n \"ITEM_QUANTITY_INSUFFICIENT_AMOUNT\",\n (itemId: string, customerId: string, quantity: number) => [\n 400,\n `The item with ID ${JSON.stringify(itemId)} has an insufficient quantity for the customer with ID ${JSON.stringify(customerId)}. An attempt was made to charge ${quantity} credits.`,\n {\n item_id: itemId,\n customer_id: customerId,\n quantity,\n },\n ] as const,\n (json) => [json.item_id, json.customer_id, json.quantity] as const,\n);\n\nconst StripeAccountInfoNotFound = createKnownErrorConstructor(\n KnownError,\n \"STRIPE_ACCOUNT_INFO_NOT_FOUND\",\n () => [\n 404,\n \"Stripe account information not found. Please make sure the user has onboarded with Stripe.\",\n ] as const,\n () => [] as const,\n);\n\nconst AnalyticsQueryTimeout = createKnownErrorConstructor(\n KnownError,\n \"ANALYTICS_QUERY_TIMEOUT\",\n (timeoutMs: number) => [\n 400,\n `The query timed out. Please try again with a shorter query or increase the timeout. Timeout was ${timeoutMs}ms.`,\n { timeout_ms: timeoutMs },\n ] as const,\n (json) => [json.timeout_ms] as const,\n);\n\nconst AnalyticsQueryError = createKnownErrorConstructor(\n KnownError,\n \"ANALYTICS_QUERY_ERROR\",\n (error: string) => [\n 400,\n `${error}`,\n { error },\n ] as const,\n (json) => [json.error] as const,\n);\n\nconst AnalyticsNotEnabled = createKnownErrorConstructor(\n KnownError,\n \"ANALYTICS_NOT_ENABLED\",\n () => [\n 400,\n \"Analytics is not enabled for this project.\",\n ] as const,\n () => [] as const,\n);\n\nconst DefaultPaymentMethodRequired = createKnownErrorConstructor(\n KnownError,\n \"DEFAULT_PAYMENT_METHOD_REQUIRED\",\n (customerType: \"user\" | \"team\", customerId: string) => [\n 400,\n \"No default payment method is set for this customer.\",\n {\n customer_type: customerType,\n customer_id: customerId,\n },\n ] as const,\n (json) => [json.customer_type, json.customer_id] as const,\n);\n\nconst NewPurchasesBlocked = createKnownErrorConstructor(\n KnownError,\n \"NEW_PURCHASES_BLOCKED\",\n () => [\n 403,\n \"New purchases are currently blocked for this project. Please contact support for more information.\",\n ] as const,\n () => [] as const,\n);\n\nexport type KnownErrors = {\n [K in keyof typeof KnownErrors]: InstanceType<typeof KnownErrors[K]>;\n};\n\nexport const KnownErrors = {\n CannotDeleteCurrentSession,\n UnsupportedError,\n BodyParsingError,\n SchemaError,\n AllOverloadsFailed,\n ProjectAuthenticationError,\n PermissionIdAlreadyExists,\n CliAuthError,\n CliAuthExpiredError,\n CliAuthUsedError,\n InvalidProjectAuthentication,\n ProjectKeyWithoutAccessType,\n InvalidAccessType,\n AccessTypeWithoutProjectId,\n AccessTypeRequired,\n CannotGetOwnUserWithoutUser,\n InsufficientAccessType,\n InvalidPublishableClientKey,\n InvalidSecretServerKey,\n InvalidSuperSecretAdminKey,\n InvalidAdminAccessToken,\n UnparsableAdminAccessToken,\n AdminAccessTokenExpired,\n InvalidProjectForAdminAccessToken,\n AdminAccessTokenIsNotAdmin,\n ProjectAuthenticationRequired,\n ClientAuthenticationRequired,\n PublishableClientKeyRequiredForProject,\n ServerAuthenticationRequired,\n ClientOrServerAuthenticationRequired,\n ClientOrAdminAuthenticationRequired,\n ClientOrServerOrAdminAuthenticationRequired,\n AdminAuthenticationRequired,\n ExpectedInternalProject,\n SessionAuthenticationError,\n InvalidSessionAuthentication,\n InvalidAccessToken,\n UnparsableAccessToken,\n AccessTokenExpired,\n InvalidProjectForAccessToken,\n RefreshTokenError,\n ProviderRejected,\n RefreshTokenNotFoundOrExpired,\n UserWithEmailAlreadyExists,\n EmailNotVerified,\n UserIdDoesNotExist,\n UserNotFound,\n RestrictedUserNotAllowed,\n ApiKeyNotFound,\n PublicApiKeyCannotBeRevoked,\n ProjectNotFound,\n CurrentProjectNotFound,\n BranchDoesNotExist,\n SignUpNotEnabled,\n SignUpRejected,\n PasswordAuthenticationNotEnabled,\n PasskeyAuthenticationNotEnabled,\n AnonymousAccountsNotEnabled,\n AnonymousAuthenticationNotAllowed,\n EmailPasswordMismatch,\n RedirectUrlNotWhitelisted,\n PasswordRequirementsNotMet,\n PasswordTooShort,\n PasswordTooLong,\n UserDoesNotHavePassword,\n VerificationCodeError,\n VerificationCodeNotFound,\n VerificationCodeExpired,\n VerificationCodeAlreadyUsed,\n VerificationCodeMaxAttemptsReached,\n PasswordConfirmationMismatch,\n EmailAlreadyVerified,\n EmailNotAssociatedWithUser,\n EmailIsNotPrimaryEmail,\n PasskeyRegistrationFailed,\n PasskeyWebAuthnError,\n PasskeyAuthenticationFailed,\n PermissionNotFound,\n PermissionScopeMismatch,\n ContainedPermissionNotFound,\n TeamNotFound,\n TeamMembershipNotFound,\n TeamInvitationRestrictedUserNotAllowed,\n EmailTemplateAlreadyExists,\n OAuthConnectionNotConnectedToUser,\n OAuthConnectionAlreadyConnectedToAnotherUser,\n OAuthConnectionDoesNotHaveRequiredScope,\n OAuthAccessTokenNotAvailable,\n OAuthExtraScopeNotAvailableWithSharedOAuthKeys,\n OAuthAccessTokenNotAvailableWithSharedOAuthKeys,\n InvalidOAuthClientIdOrSecret,\n InvalidScope,\n UserAlreadyConnectedToAnotherOAuthConnection,\n OuterOAuthTimeout,\n OAuthProviderNotFoundOrNotEnabled,\n AppleBundleIdNotConfigured,\n OAuthProviderAccountIdAlreadyUsedForSignIn,\n MultiFactorAuthenticationRequired,\n InvalidTotpCode,\n UserAuthenticationRequired,\n TeamMembershipAlreadyExists,\n ProjectPermissionRequired,\n TeamPermissionRequired,\n InvalidSharedOAuthProviderId,\n InvalidStandardOAuthProviderId,\n InvalidAuthorizationCode,\n InvalidAppleCredentials,\n TeamPermissionNotFound,\n OAuthProviderAccessDenied,\n ContactChannelAlreadyUsedForAuthBySomeoneElse,\n InvalidPollingCodeError,\n ApiKeyNotValid,\n ApiKeyExpired,\n ApiKeyRevoked,\n WrongApiKeyType,\n EmailRenderingError,\n TemplateSourceRewriteError,\n RequiresCustomEmailServer,\n EmailCapacityBoostAlreadyActive,\n EmailNotEditable,\n ItemNotFound,\n ItemCustomerTypeDoesNotMatch,\n CustomerDoesNotExist,\n ProductDoesNotExist,\n ProductCustomerTypeDoesNotMatch,\n ProductAlreadyGranted,\n SubscriptionInvoiceNotFound,\n OneTimePurchaseNotFound,\n SubscriptionAlreadyRefunded,\n OneTimePurchaseAlreadyRefunded,\n TestModePurchaseNonRefundable,\n ItemQuantityInsufficientAmount,\n StripeAccountInfoNotFound,\n DefaultPaymentMethodRequired,\n NewPurchasesBlocked,\n DataVaultStoreDoesNotExist,\n DataVaultStoreHashedKeyDoesNotExist,\n AnalyticsQueryTimeout,\n AnalyticsQueryError,\n AnalyticsNotEnabled,\n} satisfies Record<string, KnownErrorConstructor<any, any>>;\n\n\n// ensure that all known error codes are unique\nconst knownErrorCodes = new Set<string>();\nfor (const [_, KnownError] of Object.entries(KnownErrors)) {\n if (knownErrorCodes.has(KnownError.errorCode)) {\n throw new Error(`Duplicate known error code: ${KnownError.errorCode}`);\n }\n knownErrorCodes.add(KnownError.errorCode);\n}\n", "import { StackAssertionError } from \"./errors\";\n\nconst crockfordAlphabet = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\";\nconst crockfordReplacements = new Map([\n [\"o\", \"0\"],\n [\"i\", \"1\"],\n [\"l\", \"1\"],\n]);\n\nexport function toHexString(input: Uint8Array): string {\n return Array.from(input).map(b => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\nimport.meta.vitest?.test(\"toHexString\", ({ expect }) => {\n expect(toHexString(new Uint8Array([]))).toBe(\"\");\n expect(toHexString(new Uint8Array([0]))).toBe(\"00\");\n expect(toHexString(new Uint8Array([15]))).toBe(\"0f\");\n expect(toHexString(new Uint8Array([16]))).toBe(\"10\");\n expect(toHexString(new Uint8Array([255]))).toBe(\"ff\");\n expect(toHexString(new Uint8Array([1, 2, 3]))).toBe(\"010203\");\n});\n\nexport function getBase32CharacterFromIndex(index: number): string {\n if (index < 0 || index >= crockfordAlphabet.length) {\n throw new StackAssertionError(`Invalid base32 index: ${index}`);\n }\n return crockfordAlphabet[index];\n}\nimport.meta.vitest?.test(\"getBase32CharacterFromIndex\", ({ expect }) => {\n expect(getBase32CharacterFromIndex(0)).toBe(\"0\");\n expect(getBase32CharacterFromIndex(15)).toBe(\"F\");\n expect(() => getBase32CharacterFromIndex(32)).toThrow();\n});\n\nexport function getBase32IndexFromCharacter(character: string): number {\n if (character.length !== 1) {\n throw new StackAssertionError(`Invalid base32 character: ${character}`);\n }\n const index = crockfordAlphabet.indexOf(character.toUpperCase());\n if (index === -1) {\n throw new StackAssertionError(`Invalid base32 character: ${character}`);\n }\n return index;\n}\nimport.meta.vitest?.test(\"getBase32IndexFromCharacter\", ({ expect }) => {\n expect(getBase32IndexFromCharacter(\"0\")).toBe(0);\n expect(getBase32IndexFromCharacter(\"F\")).toBe(15);\n expect(() => getBase32IndexFromCharacter(\"_\")).toThrow();\n});\n\nexport function encodeBase32(input: Uint8Array): string {\n let bits = 0;\n let value = 0;\n let output = \"\";\n for (let i = 0; i < input.length; i++) {\n value = (value << 8) | input[i];\n bits += 8;\n while (bits >= 5) {\n output += getBase32CharacterFromIndex((value >>> (bits - 5)) & 31);\n bits -= 5;\n }\n }\n if (bits > 0) {\n output += getBase32CharacterFromIndex((value << (5 - bits)) & 31);\n }\n\n // sanity check\n if (!isBase32(output)) {\n throw new StackAssertionError(\"Invalid base32 output; this should never happen\");\n }\n\n return output;\n}\nimport.meta.vitest?.test(\"encodeBase32\", ({ expect }) => {\n expect(encodeBase32(new Uint8Array([]))).toBe(\"\");\n expect(encodeBase32(new Uint8Array([1]))).toBe(\"04\");\n expect(encodeBase32(new Uint8Array([15]))).toBe(\"1W\");\n expect(encodeBase32(new Uint8Array([16]))).toBe(\"20\");\n expect(encodeBase32(new Uint8Array([255]))).toBe(\"ZW\");\n expect(encodeBase32(new Uint8Array([255,255]))).toBe(\"ZZZG\");\n});\nexport function decodeBase32(input: string): Uint8Array<ArrayBuffer> {\n if (!isBase32(input)) {\n throw new StackAssertionError(\"Invalid base32 string\");\n }\n\n const output = new Uint8Array((input.length * 5 / 8) | 0);\n let bits = 0;\n let value = 0;\n let outputIndex = 0;\n for (let i = 0; i < input.length; i++) {\n let char = input[i].toLowerCase();\n if (char === \" \") continue;\n if (crockfordReplacements.has(char)) {\n char = crockfordReplacements.get(char)!;\n }\n const index = getBase32IndexFromCharacter(char);\n value = (value << 5) | index;\n bits += 5;\n if (bits >= 8) {\n output[outputIndex++] = (value >>> (bits - 8)) & 255;\n bits -= 8;\n }\n }\n return output;\n}\nimport.meta.vitest?.test(\"decodeBase32\", ({ expect }) => {\n expect(decodeBase32(\"\")).toEqual(new Uint8Array([]));\n expect(decodeBase32(\"00\")).toEqual(new Uint8Array([0]));\n expect(decodeBase32(\"1W\")).toEqual(new Uint8Array([15]));\n expect(decodeBase32(\"20\")).toEqual(new Uint8Array([16]));\n expect(decodeBase32(\"ZW\")).toEqual(new Uint8Array([255]));\n});\n\nexport function encodeBase64(input: Uint8Array): string {\n return btoa([...input].map((b) => String.fromCharCode(b)).join(\"\"));\n}\n\nexport function decodeBase64(input: string): Uint8Array<ArrayBuffer> {\n return new Uint8Array(atob(input).split(\"\").map((char) => char.charCodeAt(0)));\n}\nimport.meta.vitest?.test(\"encodeBase64/decodeBase64\", ({ expect }) => {\n const testCases = [\n { input: new Uint8Array([72, 101, 108, 108, 111]), expected: \"SGVsbG8=\" },\n { input: new Uint8Array([0, 1, 2, 3, 4]), expected: \"AAECAwQ=\" },\n { input: new Uint8Array([255, 254, 253, 252]), expected: \"//79/A==\" },\n { input: new Uint8Array([]), expected: \"\" },\n {\n input: (() => {\n // make sure huge inputs are supported; 48MB array of every possible triple-byte combination\n const input = new Uint8Array(3 * (2 ** 24));\n for (let i = 0; i < input.length / 3; i++) {\n input[3 * i] = Math.floor(i / 256 / 256);\n input[3 * i + 1] = Math.floor(i / 256) % 256;\n input[3 * i + 2] = i % 256;\n }\n return input;\n })(),\n expected: (() => {\n const base64Alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n const output = [];\n for (let i = 0; i < 2 ** 24; i++) {\n output.push(\n base64Alphabet[Math.floor(i / 64 / 64 / 64)]\n + base64Alphabet[Math.floor(i / 64 / 64) % 64]\n + base64Alphabet[Math.floor(i / 64) % 64]\n + base64Alphabet[i % 64]\n );\n }\n return output.join(\"\");\n })(),\n },\n ];\n\n for (const [i, { input, expected }] of testCases.entries()) {\n // expect(...) is pretty slow with long inputs, so we throw our own assertions\n const encoded = encodeBase64(input);\n if (encoded !== expected) {\n throw new StackAssertionError(`encodeBase64 test case ${i} failed`);\n }\n const decoded = decodeBase64(encoded);\n if (decoded.some((b, i) => b !== input[i])) {\n throw new StackAssertionError(`decodeBase64 test case ${i} failed`);\n }\n }\n\n // Test invalid input for decodeBase64\n expect(() => decodeBase64(\"invalid!\")).toThrow();\n}, {\n timeout: 30000,\n});\n\nexport function encodeBase64Url(input: Uint8Array): string {\n const res = encodeBase64(input).replace(/=+$/, \"\").replace(/\\+/g, \"-\").replace(/\\//g, \"_\");\n\n // Skip sanity check for test cases\n // This avoids circular dependency with isBase64Url function\n return res;\n}\n\nexport function decodeBase64Url(input: string): Uint8Array<ArrayBuffer> {\n if (!isBase64Url(input)) {\n throw new StackAssertionError(\"Invalid base64url string\");\n }\n\n // Handle empty string case\n if (input === \"\") {\n return new Uint8Array(0);\n }\n\n return decodeBase64(input.replace(/-/g, \"+\").replace(/_/g, \"/\") + \"====\".slice((input.length - 1) % 4 + 1));\n}\nimport.meta.vitest?.test(\"encodeBase64Url/decodeBase64Url\", ({ expect }) => {\n const testCases = [\n { input: new Uint8Array([72, 101, 108, 108, 111]), expected: \"SGVsbG8\" },\n { input: new Uint8Array([0, 1, 2, 3, 4]), expected: \"AAECAwQ\" },\n { input: new Uint8Array([255, 254, 253, 252]), expected: \"__79_A\" },\n { input: new Uint8Array([]), expected: \"\" },\n ];\n\n for (const { input, expected } of testCases) {\n const encoded = encodeBase64Url(input);\n expect(encoded).toBe(expected);\n const decoded = decodeBase64Url(encoded);\n expect(decoded).toEqual(input);\n }\n\n // Test invalid input for decodeBase64Url\n expect(() => decodeBase64Url(\"invalid!\")).toThrow();\n});\n\nexport function decodeBase64OrBase64Url(input: string): Uint8Array<ArrayBuffer> {\n if (isBase64Url(input)) {\n return decodeBase64Url(input);\n } else if (isBase64(input)) {\n return decodeBase64(input);\n } else {\n throw new StackAssertionError(\"Invalid base64 or base64url string\");\n }\n}\nimport.meta.vitest?.test(\"decodeBase64OrBase64Url\", ({ expect }) => {\n // Test with base64 input\n const base64Input = \"SGVsbG8gV29ybGQ=\";\n const base64Expected = new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]);\n expect(decodeBase64OrBase64Url(base64Input)).toEqual(base64Expected);\n\n // Test with base64url input\n const base64UrlInput = \"SGVsbG8gV29ybGQ\";\n const base64UrlExpected = new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]);\n expect(decodeBase64OrBase64Url(base64UrlInput)).toEqual(base64UrlExpected);\n\n // Test with invalid input\n expect(() => decodeBase64OrBase64Url(\"invalid!\")).toThrow();\n});\n\nexport function isBase32(input: string): boolean {\n for (const char of input) {\n if (char === \" \") continue;\n const upperChar = char.toUpperCase();\n // Check if the character is in the Crockford alphabet\n if (!crockfordAlphabet.includes(upperChar)) {\n return false;\n }\n }\n return true;\n}\nimport.meta.vitest?.test(\"isBase32\", ({ expect }) => {\n expect(isBase32(\"0123456789ABCDEFGHJKMNPQRSTVWXYZ\")).toBe(true);\n expect(isBase32(\"0OIJ\")).toBe(false); // O and I are not allowed\n expect(isBase32(\"ABC DEF\")).toBe(true); // Spaces are allowed\n expect(isBase32(\"ABC!\")).toBe(false); // Special characters not allowed\n expect(isBase32(\"\")).toBe(true);\n});\n\nexport function isBase64(input: string): boolean {\n // This regex allows for standard base64 with proper padding\n const regex = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;\n return regex.test(input);\n}\nimport.meta.vitest?.test(\"isBase64\", ({ expect }) => {\n expect(isBase64(\"SGVsbG8gV29ybGQ=\")).toBe(true);\n expect(isBase64(\"SGVsbG8gV29ybGQ\")).toBe(false); // No padding\n expect(isBase64(\"SGVsbG8gV29ybGQ==\")).toBe(false); // Wrong padding\n expect(isBase64(\"SGVsbG8!V29ybGQ=\")).toBe(false); // Invalid character\n expect(isBase64(\"\")).toBe(true);\n});\n\nexport function isBase64Url(input: string): boolean {\n if (input === \"\") {\n return true;\n }\n const regex = /^[0-9a-zA-Z_-]+$/;\n return regex.test(input);\n}\nimport.meta.vitest?.test(\"isBase64Url\", ({ expect }) => {\n expect(isBase64Url(\"SGVsbG8gV2 9ybGQ\")).toBe(false); // Space is not valid\n expect(isBase64Url(\"SGVsbG8_V29ybGQ\")).toBe(true); // _ is a valid character\n expect(isBase64Url(\"SGVsbG8-V29ybGQ\")).toBe(true); // - is valid\n expect(isBase64Url(\"SGVsbG8_V29ybGQ=\")).toBe(false); // = not allowed\n expect(isBase64Url(\"\")).toBe(true); // Empty string is valid\n});\n", "import { generateSecureRandomString } from \"./crypto\";\nimport { templateIdentity } from \"./strings\";\n\nexport function createUrlIfValid(...args: ConstructorParameters<typeof URL>) {\n try {\n return new URL(...args);\n } catch (e) {\n return null;\n }\n}\nimport.meta.vitest?.test(\"createUrlIfValid\", ({ expect }) => {\n // Test with valid URLs\n expect(createUrlIfValid(\"https://example.com\")).toBeInstanceOf(URL);\n expect(createUrlIfValid(\"https://example.com/path?query=value#hash\")).toBeInstanceOf(URL);\n expect(createUrlIfValid(\"/path\", \"https://example.com\")).toBeInstanceOf(URL);\n\n // Test with invalid URLs\n expect(createUrlIfValid(\"\")).toBeNull();\n expect(createUrlIfValid(\"not a url\")).toBeNull();\n expect(createUrlIfValid(\"http://\")).toBeNull();\n});\n\nexport function isValidUrl(url: string) {\n return !!createUrlIfValid(url);\n}\nimport.meta.vitest?.test(\"isValidUrl\", ({ expect }) => {\n // Test with valid URLs\n expect(isValidUrl(\"https://example.com\")).toBe(true);\n expect(isValidUrl(\"http://localhost:3000\")).toBe(true);\n expect(isValidUrl(\"ftp://example.com\")).toBe(true);\n\n // Test with invalid URLs\n expect(isValidUrl(\"\")).toBe(false);\n expect(isValidUrl(\"not a url\")).toBe(false);\n expect(isValidUrl(\"http://\")).toBe(false);\n});\n\nexport function isValidHostname(hostname: string) {\n // Basic validation\n if (!hostname || hostname.startsWith('.') || hostname.endsWith('.') || hostname.includes('..')) {\n return false;\n }\n\n const url = createUrlIfValid(`https://${hostname}`);\n if (!url) return false;\n return url.hostname === hostname;\n}\nimport.meta.vitest?.test(\"isValidHostname\", ({ expect }) => {\n // Test with valid hostnames\n expect(isValidHostname(\"example.com\")).toBe(true);\n expect(isValidHostname(\"localhost\")).toBe(true);\n expect(isValidHostname(\"sub.domain.example.com\")).toBe(true);\n expect(isValidHostname(\"127.0.0.1\")).toBe(true);\n\n // Test with invalid hostnames\n expect(isValidHostname(\"\")).toBe(false);\n expect(isValidHostname(\"example.com/path\")).toBe(false);\n expect(isValidHostname(\"https://example.com\")).toBe(false);\n expect(isValidHostname(\"example com\")).toBe(false);\n});\n\nexport function isValidHostnameWithWildcards(hostname: string) {\n // Empty hostnames are invalid\n if (!hostname) return false;\n\n // Check if it contains wildcards\n const hasWildcard = hostname.includes('*');\n\n if (!hasWildcard) {\n // If no wildcards, validate as a normal hostname\n return isValidHostname(hostname);\n }\n\n // Basic validation checks that apply even with wildcards\n // - Hostname cannot start or end with a dot\n if (hostname.startsWith('.') || hostname.endsWith('.')) {\n return false;\n }\n\n // - No consecutive dots\n if (hostname.includes('..')) {\n return false;\n }\n\n // For wildcard validation, check that non-wildcard parts contain valid characters\n // Replace wildcards with a valid placeholder to check the rest\n const testHostname = hostname.replace(/\\*+/g, 'wildcard');\n\n // Check if the resulting string would be a valid hostname\n if (!/^[a-zA-Z0-9.-]+$/.test(testHostname)) {\n return false;\n }\n\n // Additional check: ensure the pattern makes sense\n // Check each segment between wildcards\n const segments = hostname.split(/\\*+/);\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n if (segment === '') continue; // Empty segments are OK (consecutive wildcards)\n\n // First segment can't start with dot\n if (i === 0 && segment.startsWith('.')) {\n return false;\n }\n\n // Last segment can't end with dot\n if (i === segments.length - 1 && segment.endsWith('.')) {\n return false;\n }\n\n // No segment should have consecutive dots\n if (segment.includes('..')) {\n return false;\n }\n }\n\n return true;\n}\nimport.meta.vitest?.test(\"isValidHostnameWithWildcards\", ({ expect }) => {\n // Test with valid regular hostnames\n expect(isValidHostnameWithWildcards(\"example.com\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"localhost\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"sub.domain.example.com\")).toBe(true);\n\n // Test with valid wildcard hostnames\n expect(isValidHostnameWithWildcards(\"*.example.com\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"a-*.example.com\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"*.*.org\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"**.example.com\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"sub.**.com\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"*-api.*.com\")).toBe(true);\n\n // Test with invalid hostnames\n expect(isValidHostnameWithWildcards(\"\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"example.com/path\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"https://example.com\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"example com\")).toBe(false);\n expect(isValidHostnameWithWildcards(\".example.com\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"example.com.\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"example..com\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"*.example..com\")).toBe(false);\n});\n\nexport function matchHostnamePattern(pattern: string, hostname: string): boolean {\n // If no wildcards, it's an exact match\n if (!pattern.includes('*')) {\n return pattern === hostname;\n }\n\n // Convert the pattern to a regex\n // First, escape all regex special characters except *\n let regexPattern = pattern.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\n // Use a placeholder for ** to handle it separately from single *\n const doubleWildcardPlaceholder = '\\x00DOUBLE_WILDCARD\\x00';\n regexPattern = regexPattern.replace(/\\*\\*/g, doubleWildcardPlaceholder);\n\n // Replace single * with a pattern that matches anything except dots\n regexPattern = regexPattern.replace(/\\*/g, '[^.]*');\n\n // Replace the double wildcard placeholder with a pattern that matches anything including dots\n regexPattern = regexPattern.replace(new RegExp(doubleWildcardPlaceholder, 'g'), '.*');\n\n // Anchor the pattern to match the entire hostname\n regexPattern = '^' + regexPattern + '$';\n\n try {\n const regex = new RegExp(regexPattern);\n return regex.test(hostname);\n } catch {\n return false;\n }\n}\nimport.meta.vitest?.test(\"matchHostnamePattern\", ({ expect }) => {\n // Test exact matches\n expect(matchHostnamePattern(\"example.com\", \"example.com\")).toBe(true);\n expect(matchHostnamePattern(\"example.com\", \"other.com\")).toBe(false);\n\n // Test single wildcard matches\n expect(matchHostnamePattern(\"*.example.com\", \"api.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"*.example.com\", \"www.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"*.example.com\", \"example.com\")).toBe(false);\n expect(matchHostnamePattern(\"*.example.com\", \"api.v2.example.com\")).toBe(false);\n\n // Test double wildcard matches\n expect(matchHostnamePattern(\"**.example.com\", \"api.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"**.example.com\", \"api.v2.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"**.example.com\", \"a.b.c.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"**.example.com\", \"example.com\")).toBe(false);\n\n // Test complex patterns\n expect(matchHostnamePattern(\"api-*.example.com\", \"api-v1.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"api-*.example.com\", \"api-v2.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"api-*.example.com\", \"api.example.com\")).toBe(false);\n expect(matchHostnamePattern(\"*.*.org\", \"mail.example.org\")).toBe(true);\n expect(matchHostnamePattern(\"*.*.org\", \"example.org\")).toBe(false);\n});\n\nexport function isLocalhost(urlOrString: string | URL) {\n const url = createUrlIfValid(urlOrString);\n if (!url) return false;\n if (url.hostname === \"localhost\" || url.hostname.endsWith(\".localhost\")) return true;\n if (url.hostname.match(/^127\\.\\d+\\.\\d+\\.\\d+$/)) return true;\n return false;\n}\nimport.meta.vitest?.test(\"isLocalhost\", ({ expect }) => {\n // Test with localhost URLs\n expect(isLocalhost(\"http://localhost\")).toBe(true);\n expect(isLocalhost(\"https://localhost:8080\")).toBe(true);\n expect(isLocalhost(\"http://sub.localhost\")).toBe(true);\n expect(isLocalhost(\"http://127.0.0.1\")).toBe(true);\n expect(isLocalhost(\"http://127.1.2.3\")).toBe(true);\n\n // Test with non-localhost URLs\n expect(isLocalhost(\"https://example.com\")).toBe(false);\n expect(isLocalhost(\"http://192.168.1.1\")).toBe(false);\n expect(isLocalhost(\"http://10.0.0.1\")).toBe(false);\n\n // Test with URL objects\n expect(isLocalhost(new URL(\"http://localhost\"))).toBe(true);\n expect(isLocalhost(new URL(\"https://example.com\"))).toBe(false);\n\n // Test with invalid URLs\n expect(isLocalhost(\"not a url\")).toBe(false);\n expect(isLocalhost(\"\")).toBe(false);\n});\n\nexport function isRelative(url: string) {\n const randomDomain = `${generateSecureRandomString()}.stack-auth.example.com`;\n const u = createUrlIfValid(url, `https://${randomDomain}`);\n if (!u) return false;\n if (u.host !== randomDomain) return false;\n if (u.protocol !== \"https:\") return false;\n return true;\n}\nimport.meta.vitest?.test(\"isRelative\", ({ expect }) => {\n // We can't easily mock generateSecureRandomString in this context\n // but we can still test the function's behavior\n\n // Test with relative URLs\n expect(isRelative(\"/\")).toBe(true);\n expect(isRelative(\"/path\")).toBe(true);\n expect(isRelative(\"/path?query=value#hash\")).toBe(true);\n\n // Test with absolute URLs\n expect(isRelative(\"https://example.com\")).toBe(false);\n expect(isRelative(\"http://example.com\")).toBe(false);\n expect(isRelative(\"//example.com\")).toBe(false);\n\n // Note: The implementation treats empty strings and invalid URLs as relative\n // This is because they can be resolved against a base URL\n expect(isRelative(\"\")).toBe(true);\n expect(isRelative(\"not a url\")).toBe(true);\n});\n\nexport function getRelativePart(url: URL) {\n return url.pathname + url.search + url.hash;\n}\nimport.meta.vitest?.test(\"getRelativePart\", ({ expect }) => {\n // Test with various URLs\n expect(getRelativePart(new URL(\"https://example.com\"))).toBe(\"/\");\n expect(getRelativePart(new URL(\"https://example.com/path\"))).toBe(\"/path\");\n expect(getRelativePart(new URL(\"https://example.com/path?query=value\"))).toBe(\"/path?query=value\");\n expect(getRelativePart(new URL(\"https://example.com/path#hash\"))).toBe(\"/path#hash\");\n expect(getRelativePart(new URL(\"https://example.com/path?query=value#hash\"))).toBe(\"/path?query=value#hash\");\n\n // Test with different domains but same paths\n const url1 = new URL(\"https://example.com/path?query=value#hash\");\n const url2 = new URL(\"https://different.com/path?query=value#hash\");\n expect(getRelativePart(url1)).toBe(getRelativePart(url2));\n});\n\n/**\n * A template literal tag that returns a URL.\n *\n * Any values passed are encoded.\n */\nexport function url(strings: TemplateStringsArray | readonly string[], ...values: (string | number | boolean)[]): URL {\n return new URL(urlString(strings, ...values));\n}\nimport.meta.vitest?.test(\"url\", ({ expect }) => {\n // Test with no interpolation\n expect(url`https://example.com`).toBeInstanceOf(URL);\n expect(url`https://example.com`.href).toBe(\"https://example.com/\");\n\n // Test with string interpolation\n expect(url`https://example.com/${\"path\"}`).toBeInstanceOf(URL);\n expect(url`https://example.com/${\"path\"}`.pathname).toBe(\"/path\");\n\n // Test with number interpolation\n expect(url`https://example.com/${42}`).toBeInstanceOf(URL);\n expect(url`https://example.com/${42}`.pathname).toBe(\"/42\");\n\n // Test with boolean interpolation\n expect(url`https://example.com/${true}`).toBeInstanceOf(URL);\n expect(url`https://example.com/${true}`.pathname).toBe(\"/true\");\n\n // Test with special characters in interpolation\n expect(url`https://example.com/${\"path with spaces\"}`).toBeInstanceOf(URL);\n expect(url`https://example.com/${\"path with spaces\"}`.pathname).toBe(\"/path%20with%20spaces\");\n\n // Test with multiple interpolations\n expect(url`https://example.com/${\"path\"}?query=${\"value\"}`).toBeInstanceOf(URL);\n expect(url`https://example.com/${\"path\"}?query=${\"value\"}`.pathname).toBe(\"/path\");\n expect(url`https://example.com/${\"path\"}?query=${\"value\"}`.search).toBe(\"?query=value\");\n});\n\n\n/**\n * A template literal tag that returns a URL string.\n *\n * Any values passed are encoded.\n */\nexport function urlString(strings: TemplateStringsArray | readonly string[], ...values: (string | number | boolean)[]): string {\n return templateIdentity(strings, ...values.map(encodeURIComponent));\n}\nimport.meta.vitest?.test(\"urlString\", ({ expect }) => {\n // Test with no interpolation\n expect(urlString`https://example.com`).toBe(\"https://example.com\");\n\n // Test with string interpolation\n expect(urlString`https://example.com/${\"path\"}`).toBe(\"https://example.com/path\");\n\n // Test with number interpolation\n expect(urlString`https://example.com/${42}`).toBe(\"https://example.com/42\");\n\n // Test with boolean interpolation\n expect(urlString`https://example.com/${true}`).toBe(\"https://example.com/true\");\n\n // Test with special characters in interpolation\n expect(urlString`https://example.com/${\"path with spaces\"}`).toBe(\"https://example.com/path%20with%20spaces\");\n expect(urlString`https://example.com/${\"?&=\"}`).toBe(\"https://example.com/%3F%26%3D\");\n\n // Test with multiple interpolations\n expect(urlString`https://example.com/${\"path\"}?query=${\"value\"}`).toBe(\"https://example.com/path?query=value\");\n expect(urlString`https://example.com/${\"path\"}?query=${\"value with spaces\"}`).toBe(\"https://example.com/path?query=value%20with%20spaces\");\n});\n\nexport function isChildUrl(parentUrl: URL, maybeChildUrl: URL) {\n return parentUrl.origin === maybeChildUrl.origin\n && isChildPath(parentUrl.pathname, maybeChildUrl.pathname)\n && [...parentUrl.searchParams].every(([key, value]) => maybeChildUrl.searchParams.get(key) === value)\n && (!parentUrl.hash || parentUrl.hash === maybeChildUrl.hash);\n}\nimport.meta.vitest?.test(\"isChildUrl\", ({ expect }) => {\n // true\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://abc.com/\"))).toBe(true);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://abc.com/path\"))).toBe(true);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://abc.com/path?query=value\"))).toBe(true);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://abc.com/path?query=value#hash\"))).toBe(true);\n\n // false\n expect(isChildUrl(new URL(\"https://abc.com\"), new URL(\"https://example.com\"))).toBe(false);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://example.com/path\"))).toBe(false);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://example.com/path?query=value\"))).toBe(false);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://example.com/path?query=value#hash\"))).toBe(false);\n expect(isChildUrl(new URL(\"https://example.com\"), new URL(\"https://abc.com/path?query=value#hash\"))).toBe(false);\n expect(isChildUrl(new URL(\"https://example.com?query=value123\"), new URL(\"https://example.com/path?query=value#hash\"))).toBe(false);\n});\n\nexport function isChildPath(parentPath: string, maybeChildPath: string) {\n parentPath = parentPath.endsWith(\"/\") ? parentPath : parentPath + \"/\";\n maybeChildPath = maybeChildPath.endsWith(\"/\") ? maybeChildPath : maybeChildPath + \"/\";\n return maybeChildPath.startsWith(parentPath);\n}\nimport.meta.vitest?.test(\"isSubPath\", ({ expect }) => {\n expect(isChildPath(\"/\", \"/\")).toBe(true);\n expect(isChildPath(\"/\", \"/path\")).toBe(true);\n expect(isChildPath(\"/path\", \"/\")).toBe(false);\n expect(isChildPath(\"/path\", \"/path\")).toBe(true);\n expect(isChildPath(\"/path/\", \"/path\")).toBe(true);\n expect(isChildPath(\"/path\", \"/path/\")).toBe(true);\n expect(isChildPath(\"/path/\", \"/path/\")).toBe(true);\n expect(isChildPath(\"/path\", \"/path/abc\")).toBe(true);\n expect(isChildPath(\"/path/\", \"/path/abc\")).toBe(true);\n expect(isChildPath(\"/path\", \"/path-abc\")).toBe(false);\n expect(isChildPath(\"/path\", \"/path-abc/\")).toBe(false);\n expect(isChildPath(\"/path/\", \"/path-abc\")).toBe(false);\n expect(isChildPath(\"/path/\", \"/path-abc/\")).toBe(false);\n});\n", "import { getter, forEach, split, normalizePath, join } from 'property-expr';\nimport { camelCase, snakeCase } from 'tiny-case';\nimport toposort from 'toposort';\n\nconst toString = Object.prototype.toString;\nconst errorToString = Error.prototype.toString;\nconst regExpToString = RegExp.prototype.toString;\nconst symbolToString = typeof Symbol !== 'undefined' ? Symbol.prototype.toString : () => '';\nconst SYMBOL_REGEXP = /^Symbol\\((.*)\\)(.*)$/;\nfunction printNumber(val) {\n if (val != +val) return 'NaN';\n const isNegativeZero = val === 0 && 1 / val < 0;\n return isNegativeZero ? '-0' : '' + val;\n}\nfunction printSimpleValue(val, quoteStrings = false) {\n if (val == null || val === true || val === false) return '' + val;\n const typeOf = typeof val;\n if (typeOf === 'number') return printNumber(val);\n if (typeOf === 'string') return quoteStrings ? `\"${val}\"` : val;\n if (typeOf === 'function') return '[Function ' + (val.name || 'anonymous') + ']';\n if (typeOf === 'symbol') return symbolToString.call(val).replace(SYMBOL_REGEXP, 'Symbol($1)');\n const tag = toString.call(val).slice(8, -1);\n if (tag === 'Date') return isNaN(val.getTime()) ? '' + val : val.toISOString(val);\n if (tag === 'Error' || val instanceof Error) return '[' + errorToString.call(val) + ']';\n if (tag === 'RegExp') return regExpToString.call(val);\n return null;\n}\nfunction printValue(value, quoteStrings) {\n let result = printSimpleValue(value, quoteStrings);\n if (result !== null) return result;\n return JSON.stringify(value, function (key, value) {\n let result = printSimpleValue(this[key], quoteStrings);\n if (result !== null) return result;\n return value;\n }, 2);\n}\n\nfunction toArray(value) {\n return value == null ? [] : [].concat(value);\n}\n\nlet _Symbol$toStringTag, _Symbol$hasInstance, _Symbol$toStringTag2;\nlet strReg = /\\$\\{\\s*(\\w+)\\s*\\}/g;\n_Symbol$toStringTag = Symbol.toStringTag;\nclass ValidationErrorNoStack {\n constructor(errorOrErrors, value, field, type) {\n this.name = void 0;\n this.message = void 0;\n this.value = void 0;\n this.path = void 0;\n this.type = void 0;\n this.params = void 0;\n this.errors = void 0;\n this.inner = void 0;\n this[_Symbol$toStringTag] = 'Error';\n this.name = 'ValidationError';\n this.value = value;\n this.path = field;\n this.type = type;\n this.errors = [];\n this.inner = [];\n toArray(errorOrErrors).forEach(err => {\n if (ValidationError.isError(err)) {\n this.errors.push(...err.errors);\n const innerErrors = err.inner.length ? err.inner : [err];\n this.inner.push(...innerErrors);\n } else {\n this.errors.push(err);\n }\n });\n this.message = this.errors.length > 1 ? `${this.errors.length} errors occurred` : this.errors[0];\n }\n}\n_Symbol$hasInstance = Symbol.hasInstance;\n_Symbol$toStringTag2 = Symbol.toStringTag;\nclass ValidationError extends Error {\n static formatError(message, params) {\n // Attempt to make the path more friendly for error message interpolation.\n const path = params.label || params.path || 'this';\n // Store the original path under `originalPath` so it isn't lost to custom\n // message functions; e.g., ones provided in `setLocale()` calls.\n params = Object.assign({}, params, {\n path,\n originalPath: params.path\n });\n if (typeof message === 'string') return message.replace(strReg, (_, key) => printValue(params[key]));\n if (typeof message === 'function') return message(params);\n return message;\n }\n static isError(err) {\n return err && err.name === 'ValidationError';\n }\n constructor(errorOrErrors, value, field, type, disableStack) {\n const errorNoStack = new ValidationErrorNoStack(errorOrErrors, value, field, type);\n if (disableStack) {\n return errorNoStack;\n }\n super();\n this.value = void 0;\n this.path = void 0;\n this.type = void 0;\n this.params = void 0;\n this.errors = [];\n this.inner = [];\n this[_Symbol$toStringTag2] = 'Error';\n this.name = errorNoStack.name;\n this.message = errorNoStack.message;\n this.type = errorNoStack.type;\n this.value = errorNoStack.value;\n this.path = errorNoStack.path;\n this.errors = errorNoStack.errors;\n this.inner = errorNoStack.inner;\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, ValidationError);\n }\n }\n static [_Symbol$hasInstance](inst) {\n return ValidationErrorNoStack[Symbol.hasInstance](inst) || super[Symbol.hasInstance](inst);\n }\n}\n\nlet mixed = {\n default: '${path} is invalid',\n required: '${path} is a required field',\n defined: '${path} must be defined',\n notNull: '${path} cannot be null',\n oneOf: '${path} must be one of the following values: ${values}',\n notOneOf: '${path} must not be one of the following values: ${values}',\n notType: ({\n path,\n type,\n value,\n originalValue\n }) => {\n const castMsg = originalValue != null && originalValue !== value ? ` (cast from the value \\`${printValue(originalValue, true)}\\`).` : '.';\n return type !== 'mixed' ? `${path} must be a \\`${type}\\` type, ` + `but the final value was: \\`${printValue(value, true)}\\`` + castMsg : `${path} must match the configured type. ` + `The validated value was: \\`${printValue(value, true)}\\`` + castMsg;\n }\n};\nlet string = {\n length: '${path} must be exactly ${length} characters',\n min: '${path} must be at least ${min} characters',\n max: '${path} must be at most ${max} characters',\n matches: '${path} must match the following: \"${regex}\"',\n email: '${path} must be a valid email',\n url: '${path} must be a valid URL',\n uuid: '${path} must be a valid UUID',\n datetime: '${path} must be a valid ISO date-time',\n datetime_precision: '${path} must be a valid ISO date-time with a sub-second precision of exactly ${precision} digits',\n datetime_offset: '${path} must be a valid ISO date-time with UTC \"Z\" timezone',\n trim: '${path} must be a trimmed string',\n lowercase: '${path} must be a lowercase string',\n uppercase: '${path} must be a upper case string'\n};\nlet number = {\n min: '${path} must be greater than or equal to ${min}',\n max: '${path} must be less than or equal to ${max}',\n lessThan: '${path} must be less than ${less}',\n moreThan: '${path} must be greater than ${more}',\n positive: '${path} must be a positive number',\n negative: '${path} must be a negative number',\n integer: '${path} must be an integer'\n};\nlet date = {\n min: '${path} field must be later than ${min}',\n max: '${path} field must be at earlier than ${max}'\n};\nlet boolean = {\n isValue: '${path} field must be ${value}'\n};\nlet object = {\n noUnknown: '${path} field has unspecified keys: ${unknown}',\n exact: '${path} object contains unknown properties: ${properties}'\n};\nlet array = {\n min: '${path} field must have at least ${min} items',\n max: '${path} field must have less than or equal to ${max} items',\n length: '${path} must have ${length} items'\n};\nlet tuple = {\n notType: params => {\n const {\n path,\n value,\n spec\n } = params;\n const typeLen = spec.types.length;\n if (Array.isArray(value)) {\n if (value.length < typeLen) return `${path} tuple value has too few items, expected a length of ${typeLen} but got ${value.length} for value: \\`${printValue(value, true)}\\``;\n if (value.length > typeLen) return `${path} tuple value has too many items, expected a length of ${typeLen} but got ${value.length} for value: \\`${printValue(value, true)}\\``;\n }\n return ValidationError.formatError(mixed.notType, params);\n }\n};\nvar locale = Object.assign(Object.create(null), {\n mixed,\n string,\n number,\n date,\n object,\n array,\n boolean,\n tuple\n});\n\nconst isSchema = obj => obj && obj.__isYupSchema__;\n\nclass Condition {\n static fromOptions(refs, config) {\n if (!config.then && !config.otherwise) throw new TypeError('either `then:` or `otherwise:` is required for `when()` conditions');\n let {\n is,\n then,\n otherwise\n } = config;\n let check = typeof is === 'function' ? is : (...values) => values.every(value => value === is);\n return new Condition(refs, (values, schema) => {\n var _branch;\n let branch = check(...values) ? then : otherwise;\n return (_branch = branch == null ? void 0 : branch(schema)) != null ? _branch : schema;\n });\n }\n constructor(refs, builder) {\n this.fn = void 0;\n this.refs = refs;\n this.refs = refs;\n this.fn = builder;\n }\n resolve(base, options) {\n let values = this.refs.map(ref =>\n // TODO: ? operator here?\n ref.getValue(options == null ? void 0 : options.value, options == null ? void 0 : options.parent, options == null ? void 0 : options.context));\n let schema = this.fn(values, base, options);\n if (schema === undefined ||\n // @ts-ignore this can be base\n schema === base) {\n return base;\n }\n if (!isSchema(schema)) throw new TypeError('conditions must return a schema object');\n return schema.resolve(options);\n }\n}\n\nconst prefixes = {\n context: '$',\n value: '.'\n};\nfunction create$9(key, options) {\n return new Reference(key, options);\n}\nclass Reference {\n constructor(key, options = {}) {\n this.key = void 0;\n this.isContext = void 0;\n this.isValue = void 0;\n this.isSibling = void 0;\n this.path = void 0;\n this.getter = void 0;\n this.map = void 0;\n if (typeof key !== 'string') throw new TypeError('ref must be a string, got: ' + key);\n this.key = key.trim();\n if (key === '') throw new TypeError('ref must be a non-empty string');\n this.isContext = this.key[0] === prefixes.context;\n this.isValue = this.key[0] === prefixes.value;\n this.isSibling = !this.isContext && !this.isValue;\n let prefix = this.isContext ? prefixes.context : this.isValue ? prefixes.value : '';\n this.path = this.key.slice(prefix.length);\n this.getter = this.path && getter(this.path, true);\n this.map = options.map;\n }\n getValue(value, parent, context) {\n let result = this.isContext ? context : this.isValue ? value : parent;\n if (this.getter) result = this.getter(result || {});\n if (this.map) result = this.map(result);\n return result;\n }\n\n /**\n *\n * @param {*} value\n * @param {Object} options\n * @param {Object=} options.context\n * @param {Object=} options.parent\n */\n cast(value, options) {\n return this.getValue(value, options == null ? void 0 : options.parent, options == null ? void 0 : options.context);\n }\n resolve() {\n return this;\n }\n describe() {\n return {\n type: 'ref',\n key: this.key\n };\n }\n toString() {\n return `Ref(${this.key})`;\n }\n static isRef(value) {\n return value && value.__isYupRef;\n }\n}\n\n// @ts-ignore\nReference.prototype.__isYupRef = true;\n\nconst isAbsent = value => value == null;\n\nfunction createValidation(config) {\n function validate({\n value,\n path = '',\n options,\n originalValue,\n schema\n }, panic, next) {\n const {\n name,\n test,\n params,\n message,\n skipAbsent\n } = config;\n let {\n parent,\n context,\n abortEarly = schema.spec.abortEarly,\n disableStackTrace = schema.spec.disableStackTrace\n } = options;\n const resolveOptions = {\n value,\n parent,\n context\n };\n function createError(overrides = {}) {\n const nextParams = resolveParams(Object.assign({\n value,\n originalValue,\n label: schema.spec.label,\n path: overrides.path || path,\n spec: schema.spec,\n disableStackTrace: overrides.disableStackTrace || disableStackTrace\n }, params, overrides.params), resolveOptions);\n const error = new ValidationError(ValidationError.formatError(overrides.message || message, nextParams), value, nextParams.path, overrides.type || name, nextParams.disableStackTrace);\n error.params = nextParams;\n return error;\n }\n const invalid = abortEarly ? panic : next;\n let ctx = {\n path,\n parent,\n type: name,\n from: options.from,\n createError,\n resolve(item) {\n return resolveMaybeRef(item, resolveOptions);\n },\n options,\n originalValue,\n schema\n };\n const handleResult = validOrError => {\n if (ValidationError.isError(validOrError)) invalid(validOrError);else if (!validOrError) invalid(createError());else next(null);\n };\n const handleError = err => {\n if (ValidationError.isError(err)) invalid(err);else panic(err);\n };\n const shouldSkip = skipAbsent && isAbsent(value);\n if (shouldSkip) {\n return handleResult(true);\n }\n let result;\n try {\n var _result;\n result = test.call(ctx, value, ctx);\n if (typeof ((_result = result) == null ? void 0 : _result.then) === 'function') {\n if (options.sync) {\n throw new Error(`Validation test of type: \"${ctx.type}\" returned a Promise during a synchronous validate. ` + `This test will finish after the validate call has returned`);\n }\n return Promise.resolve(result).then(handleResult, handleError);\n }\n } catch (err) {\n handleError(err);\n return;\n }\n handleResult(result);\n }\n validate.OPTIONS = config;\n return validate;\n}\n\n// Warning: mutates the input\nfunction resolveParams(params, options) {\n if (!params) return params;\n for (const key of Object.keys(params)) {\n params[key] = resolveMaybeRef(params[key], options);\n }\n return params;\n}\nfunction resolveMaybeRef(item, options) {\n return Reference.isRef(item) ? item.getValue(options.value, options.parent, options.context) : item;\n}\n\nfunction getIn(schema, path, value, context = value) {\n let parent, lastPart, lastPartDebug;\n\n // root path: ''\n if (!path) return {\n parent,\n parentPath: path,\n schema\n };\n forEach(path, (_part, isBracket, isArray) => {\n let part = isBracket ? _part.slice(1, _part.length - 1) : _part;\n schema = schema.resolve({\n context,\n parent,\n value\n });\n let isTuple = schema.type === 'tuple';\n let idx = isArray ? parseInt(part, 10) : 0;\n if (schema.innerType || isTuple) {\n if (isTuple && !isArray) throw new Error(`Yup.reach cannot implicitly index into a tuple type. the path part \"${lastPartDebug}\" must contain an index to the tuple element, e.g. \"${lastPartDebug}[0]\"`);\n if (value && idx >= value.length) {\n throw new Error(`Yup.reach cannot resolve an array item at index: ${_part}, in the path: ${path}. ` + `because there is no value at that index. `);\n }\n parent = value;\n value = value && value[idx];\n schema = isTuple ? schema.spec.types[idx] : schema.innerType;\n }\n\n // sometimes the array index part of a path doesn't exist: \"nested.arr.child\"\n // in these cases the current part is the next schema and should be processed\n // in this iteration. For cases where the index signature is included this\n // check will fail and we'll handle the `child` part on the next iteration like normal\n if (!isArray) {\n if (!schema.fields || !schema.fields[part]) throw new Error(`The schema does not contain the path: ${path}. ` + `(failed at: ${lastPartDebug} which is a type: \"${schema.type}\")`);\n parent = value;\n value = value && value[part];\n schema = schema.fields[part];\n }\n lastPart = part;\n lastPartDebug = isBracket ? '[' + _part + ']' : '.' + _part;\n });\n return {\n schema,\n parent,\n parentPath: lastPart\n };\n}\nfunction reach(obj, path, value, context) {\n return getIn(obj, path, value, context).schema;\n}\n\nclass ReferenceSet extends Set {\n describe() {\n const description = [];\n for (const item of this.values()) {\n description.push(Reference.isRef(item) ? item.describe() : item);\n }\n return description;\n }\n resolveAll(resolve) {\n let result = [];\n for (const item of this.values()) {\n result.push(resolve(item));\n }\n return result;\n }\n clone() {\n return new ReferenceSet(this.values());\n }\n merge(newItems, removeItems) {\n const next = this.clone();\n newItems.forEach(value => next.add(value));\n removeItems.forEach(value => next.delete(value));\n return next;\n }\n}\n\n// tweaked from https://github.com/Kelin2025/nanoclone/blob/0abeb7635bda9b68ef2277093f76dbe3bf3948e1/src/index.js\nfunction clone(src, seen = new Map()) {\n if (isSchema(src) || !src || typeof src !== 'object') return src;\n if (seen.has(src)) return seen.get(src);\n let copy;\n if (src instanceof Date) {\n // Date\n copy = new Date(src.getTime());\n seen.set(src, copy);\n } else if (src instanceof RegExp) {\n // RegExp\n copy = new RegExp(src);\n seen.set(src, copy);\n } else if (Array.isArray(src)) {\n // Array\n copy = new Array(src.length);\n seen.set(src, copy);\n for (let i = 0; i < src.length; i++) copy[i] = clone(src[i], seen);\n } else if (src instanceof Map) {\n // Map\n copy = new Map();\n seen.set(src, copy);\n for (const [k, v] of src.entries()) copy.set(k, clone(v, seen));\n } else if (src instanceof Set) {\n // Set\n copy = new Set();\n seen.set(src, copy);\n for (const v of src) copy.add(clone(v, seen));\n } else if (src instanceof Object) {\n // Object\n copy = {};\n seen.set(src, copy);\n for (const [k, v] of Object.entries(src)) copy[k] = clone(v, seen);\n } else {\n throw Error(`Unable to clone ${src}`);\n }\n return copy;\n}\n\n/**\n * Copied from @standard-schema/spec to avoid having a dependency on it.\n * https://github.com/standard-schema/standard-schema/blob/main/packages/spec/src/index.ts\n */\n\nfunction createStandardPath(path) {\n if (!(path != null && path.length)) {\n return undefined;\n }\n\n // Array to store the final path segments\n const segments = [];\n // Buffer for building the current segment\n let currentSegment = '';\n // Track if we're inside square brackets (array/property access)\n let inBrackets = false;\n // Track if we're inside quotes (for property names with special chars)\n let inQuotes = false;\n for (let i = 0; i < path.length; i++) {\n const char = path[i];\n if (char === '[' && !inQuotes) {\n // When entering brackets, push any accumulated segment after splitting on dots\n if (currentSegment) {\n segments.push(...currentSegment.split('.').filter(Boolean));\n currentSegment = '';\n }\n inBrackets = true;\n continue;\n }\n if (char === ']' && !inQuotes) {\n if (currentSegment) {\n // Handle numeric indices (e.g. arr[0])\n if (/^\\d+$/.test(currentSegment)) {\n segments.push(currentSegment);\n } else {\n // Handle quoted property names (e.g. obj[\"foo.bar\"])\n segments.push(currentSegment.replace(/^\"|\"$/g, ''));\n }\n currentSegment = '';\n }\n inBrackets = false;\n continue;\n }\n if (char === '\"') {\n // Toggle quote state for handling quoted property names\n inQuotes = !inQuotes;\n continue;\n }\n if (char === '.' && !inBrackets && !inQuotes) {\n // On dots outside brackets/quotes, push current segment\n if (currentSegment) {\n segments.push(currentSegment);\n currentSegment = '';\n }\n continue;\n }\n currentSegment += char;\n }\n\n // Push any remaining segment after splitting on dots\n if (currentSegment) {\n segments.push(...currentSegment.split('.').filter(Boolean));\n }\n return segments;\n}\nfunction createStandardIssues(error, parentPath) {\n const path = parentPath ? `${parentPath}.${error.path}` : error.path;\n return error.errors.map(err => ({\n message: err,\n path: createStandardPath(path)\n }));\n}\nfunction issuesFromValidationError(error, parentPath) {\n var _error$inner;\n if (!((_error$inner = error.inner) != null && _error$inner.length) && error.errors.length) {\n return createStandardIssues(error, parentPath);\n }\n const path = parentPath ? `${parentPath}.${error.path}` : error.path;\n return error.inner.flatMap(err => issuesFromValidationError(err, path));\n}\n\n// If `CustomSchemaMeta` isn't extended with any keys, we'll fall back to a\n// loose Record definition allowing free form usage.\nclass Schema {\n constructor(options) {\n this.type = void 0;\n this.deps = [];\n this.tests = void 0;\n this.transforms = void 0;\n this.conditions = [];\n this._mutate = void 0;\n this.internalTests = {};\n this._whitelist = new ReferenceSet();\n this._blacklist = new ReferenceSet();\n this.exclusiveTests = Object.create(null);\n this._typeCheck = void 0;\n this.spec = void 0;\n this.tests = [];\n this.transforms = [];\n this.withMutation(() => {\n this.typeError(mixed.notType);\n });\n this.type = options.type;\n this._typeCheck = options.check;\n this.spec = Object.assign({\n strip: false,\n strict: false,\n abortEarly: true,\n recursive: true,\n disableStackTrace: false,\n nullable: false,\n optional: true,\n coerce: true\n }, options == null ? void 0 : options.spec);\n this.withMutation(s => {\n s.nonNullable();\n });\n }\n\n // TODO: remove\n get _type() {\n return this.type;\n }\n clone(spec) {\n if (this._mutate) {\n if (spec) Object.assign(this.spec, spec);\n return this;\n }\n\n // if the nested value is a schema we can skip cloning, since\n // they are already immutable\n const next = Object.create(Object.getPrototypeOf(this));\n\n // @ts-expect-error this is readonly\n next.type = this.type;\n next._typeCheck = this._typeCheck;\n next._whitelist = this._whitelist.clone();\n next._blacklist = this._blacklist.clone();\n next.internalTests = Object.assign({}, this.internalTests);\n next.exclusiveTests = Object.assign({}, this.exclusiveTests);\n\n // @ts-expect-error this is readonly\n next.deps = [...this.deps];\n next.conditions = [...this.conditions];\n next.tests = [...this.tests];\n next.transforms = [...this.transforms];\n next.spec = clone(Object.assign({}, this.spec, spec));\n return next;\n }\n label(label) {\n let next = this.clone();\n next.spec.label = label;\n return next;\n }\n meta(...args) {\n if (args.length === 0) return this.spec.meta;\n let next = this.clone();\n next.spec.meta = Object.assign(next.spec.meta || {}, args[0]);\n return next;\n }\n withMutation(fn) {\n let before = this._mutate;\n this._mutate = true;\n let result = fn(this);\n this._mutate = before;\n return result;\n }\n concat(schema) {\n if (!schema || schema === this) return this;\n if (schema.type !== this.type && this.type !== 'mixed') throw new TypeError(`You cannot \\`concat()\\` schema's of different types: ${this.type} and ${schema.type}`);\n let base = this;\n let combined = schema.clone();\n const mergedSpec = Object.assign({}, base.spec, combined.spec);\n combined.spec = mergedSpec;\n combined.internalTests = Object.assign({}, base.internalTests, combined.internalTests);\n\n // manually merge the blacklist/whitelist (the other `schema` takes\n // precedence in case of conflicts)\n combined._whitelist = base._whitelist.merge(schema._whitelist, schema._blacklist);\n combined._blacklist = base._blacklist.merge(schema._blacklist, schema._whitelist);\n\n // start with the current tests\n combined.tests = base.tests;\n combined.exclusiveTests = base.exclusiveTests;\n\n // manually add the new tests to ensure\n // the deduping logic is consistent\n combined.withMutation(next => {\n schema.tests.forEach(fn => {\n next.test(fn.OPTIONS);\n });\n });\n combined.transforms = [...base.transforms, ...combined.transforms];\n return combined;\n }\n isType(v) {\n if (v == null) {\n if (this.spec.nullable && v === null) return true;\n if (this.spec.optional && v === undefined) return true;\n return false;\n }\n return this._typeCheck(v);\n }\n resolve(options) {\n let schema = this;\n if (schema.conditions.length) {\n let conditions = schema.conditions;\n schema = schema.clone();\n schema.conditions = [];\n schema = conditions.reduce((prevSchema, condition) => condition.resolve(prevSchema, options), schema);\n schema = schema.resolve(options);\n }\n return schema;\n }\n resolveOptions(options) {\n var _options$strict, _options$abortEarly, _options$recursive, _options$disableStack;\n return Object.assign({}, options, {\n from: options.from || [],\n strict: (_options$strict = options.strict) != null ? _options$strict : this.spec.strict,\n abortEarly: (_options$abortEarly = options.abortEarly) != null ? _options$abortEarly : this.spec.abortEarly,\n recursive: (_options$recursive = options.recursive) != null ? _options$recursive : this.spec.recursive,\n disableStackTrace: (_options$disableStack = options.disableStackTrace) != null ? _options$disableStack : this.spec.disableStackTrace\n });\n }\n\n /**\n * Run the configured transform pipeline over an input value.\n */\n\n cast(value, options = {}) {\n let resolvedSchema = this.resolve(Object.assign({}, options, {\n value\n // parent: options.parent,\n // context: options.context,\n }));\n\n let allowOptionality = options.assert === 'ignore-optionality';\n let result = resolvedSchema._cast(value, options);\n if (options.assert !== false && !resolvedSchema.isType(result)) {\n if (allowOptionality && isAbsent(result)) {\n return result;\n }\n let formattedValue = printValue(value);\n let formattedResult = printValue(result);\n throw new TypeError(`The value of ${options.path || 'field'} could not be cast to a value ` + `that satisfies the schema type: \"${resolvedSchema.type}\". \\n\\n` + `attempted value: ${formattedValue} \\n` + (formattedResult !== formattedValue ? `result of cast: ${formattedResult}` : ''));\n }\n return result;\n }\n _cast(rawValue, options) {\n let value = rawValue === undefined ? rawValue : this.transforms.reduce((prevValue, fn) => fn.call(this, prevValue, rawValue, this, options), rawValue);\n if (value === undefined) {\n value = this.getDefault(options);\n }\n return value;\n }\n _validate(_value, options = {}, panic, next) {\n let {\n path,\n originalValue = _value,\n strict = this.spec.strict\n } = options;\n let value = _value;\n if (!strict) {\n value = this._cast(value, Object.assign({\n assert: false\n }, options));\n }\n let initialTests = [];\n for (let test of Object.values(this.internalTests)) {\n if (test) initialTests.push(test);\n }\n this.runTests({\n path,\n value,\n originalValue,\n options,\n tests: initialTests\n }, panic, initialErrors => {\n // even if we aren't ending early we can't proceed further if the types aren't correct\n if (initialErrors.length) {\n return next(initialErrors, value);\n }\n this.runTests({\n path,\n value,\n originalValue,\n options,\n tests: this.tests\n }, panic, next);\n });\n }\n\n /**\n * Executes a set of validations, either schema, produced Tests or a nested\n * schema validate result.\n */\n runTests(runOptions, panic, next) {\n let fired = false;\n let {\n tests,\n value,\n originalValue,\n path,\n options\n } = runOptions;\n let panicOnce = arg => {\n if (fired) return;\n fired = true;\n panic(arg, value);\n };\n let nextOnce = arg => {\n if (fired) return;\n fired = true;\n next(arg, value);\n };\n let count = tests.length;\n let nestedErrors = [];\n if (!count) return nextOnce([]);\n let args = {\n value,\n originalValue,\n path,\n options,\n schema: this\n };\n for (let i = 0; i < tests.length; i++) {\n const test = tests[i];\n test(args, panicOnce, function finishTestRun(err) {\n if (err) {\n Array.isArray(err) ? nestedErrors.push(...err) : nestedErrors.push(err);\n }\n if (--count <= 0) {\n nextOnce(nestedErrors);\n }\n });\n }\n }\n asNestedTest({\n key,\n index,\n parent,\n parentPath,\n originalParent,\n options\n }) {\n const k = key != null ? key : index;\n if (k == null) {\n throw TypeError('Must include `key` or `index` for nested validations');\n }\n const isIndex = typeof k === 'number';\n let value = parent[k];\n const testOptions = Object.assign({}, options, {\n // Nested validations fields are always strict:\n // 1. parent isn't strict so the casting will also have cast inner values\n // 2. parent is strict in which case the nested values weren't cast either\n strict: true,\n parent,\n value,\n originalValue: originalParent[k],\n // FIXME: tests depend on `index` being passed around deeply,\n // we should not let the options.key/index bleed through\n key: undefined,\n // index: undefined,\n [isIndex ? 'index' : 'key']: k,\n path: isIndex || k.includes('.') ? `${parentPath || ''}[${isIndex ? k : `\"${k}\"`}]` : (parentPath ? `${parentPath}.` : '') + key\n });\n return (_, panic, next) => this.resolve(testOptions)._validate(value, testOptions, panic, next);\n }\n validate(value, options) {\n var _options$disableStack2;\n let schema = this.resolve(Object.assign({}, options, {\n value\n }));\n let disableStackTrace = (_options$disableStack2 = options == null ? void 0 : options.disableStackTrace) != null ? _options$disableStack2 : schema.spec.disableStackTrace;\n return new Promise((resolve, reject) => schema._validate(value, options, (error, parsed) => {\n if (ValidationError.isError(error)) error.value = parsed;\n reject(error);\n }, (errors, validated) => {\n if (errors.length) reject(new ValidationError(errors, validated, undefined, undefined, disableStackTrace));else resolve(validated);\n }));\n }\n validateSync(value, options) {\n var _options$disableStack3;\n let schema = this.resolve(Object.assign({}, options, {\n value\n }));\n let result;\n let disableStackTrace = (_options$disableStack3 = options == null ? void 0 : options.disableStackTrace) != null ? _options$disableStack3 : schema.spec.disableStackTrace;\n schema._validate(value, Object.assign({}, options, {\n sync: true\n }), (error, parsed) => {\n if (ValidationError.isError(error)) error.value = parsed;\n throw error;\n }, (errors, validated) => {\n if (errors.length) throw new ValidationError(errors, value, undefined, undefined, disableStackTrace);\n result = validated;\n });\n return result;\n }\n isValid(value, options) {\n return this.validate(value, options).then(() => true, err => {\n if (ValidationError.isError(err)) return false;\n throw err;\n });\n }\n isValidSync(value, options) {\n try {\n this.validateSync(value, options);\n return true;\n } catch (err) {\n if (ValidationError.isError(err)) return false;\n throw err;\n }\n }\n _getDefault(options) {\n let defaultValue = this.spec.default;\n if (defaultValue == null) {\n return defaultValue;\n }\n return typeof defaultValue === 'function' ? defaultValue.call(this, options) : clone(defaultValue);\n }\n getDefault(options\n // If schema is defaulted we know it's at least not undefined\n ) {\n let schema = this.resolve(options || {});\n return schema._getDefault(options);\n }\n default(def) {\n if (arguments.length === 0) {\n return this._getDefault();\n }\n let next = this.clone({\n default: def\n });\n return next;\n }\n strict(isStrict = true) {\n return this.clone({\n strict: isStrict\n });\n }\n nullability(nullable, message) {\n const next = this.clone({\n nullable\n });\n next.internalTests.nullable = createValidation({\n message,\n name: 'nullable',\n test(value) {\n return value === null ? this.schema.spec.nullable : true;\n }\n });\n return next;\n }\n optionality(optional, message) {\n const next = this.clone({\n optional\n });\n next.internalTests.optionality = createValidation({\n message,\n name: 'optionality',\n test(value) {\n return value === undefined ? this.schema.spec.optional : true;\n }\n });\n return next;\n }\n optional() {\n return this.optionality(true);\n }\n defined(message = mixed.defined) {\n return this.optionality(false, message);\n }\n nullable() {\n return this.nullability(true);\n }\n nonNullable(message = mixed.notNull) {\n return this.nullability(false, message);\n }\n required(message = mixed.required) {\n return this.clone().withMutation(next => next.nonNullable(message).defined(message));\n }\n notRequired() {\n return this.clone().withMutation(next => next.nullable().optional());\n }\n transform(fn) {\n let next = this.clone();\n next.transforms.push(fn);\n return next;\n }\n\n /**\n * Adds a test function to the schema's queue of tests.\n * tests can be exclusive or non-exclusive.\n *\n * - exclusive tests, will replace any existing tests of the same name.\n * - non-exclusive: can be stacked\n *\n * If a non-exclusive test is added to a schema with an exclusive test of the same name\n * the exclusive test is removed and further tests of the same name will be stacked.\n *\n * If an exclusive test is added to a schema with non-exclusive tests of the same name\n * the previous tests are removed and further tests of the same name will replace each other.\n */\n\n test(...args) {\n let opts;\n if (args.length === 1) {\n if (typeof args[0] === 'function') {\n opts = {\n test: args[0]\n };\n } else {\n opts = args[0];\n }\n } else if (args.length === 2) {\n opts = {\n name: args[0],\n test: args[1]\n };\n } else {\n opts = {\n name: args[0],\n message: args[1],\n test: args[2]\n };\n }\n if (opts.message === undefined) opts.message = mixed.default;\n if (typeof opts.test !== 'function') throw new TypeError('`test` is a required parameters');\n let next = this.clone();\n let validate = createValidation(opts);\n let isExclusive = opts.exclusive || opts.name && next.exclusiveTests[opts.name] === true;\n if (opts.exclusive) {\n if (!opts.name) throw new TypeError('Exclusive tests must provide a unique `name` identifying the test');\n }\n if (opts.name) next.exclusiveTests[opts.name] = !!opts.exclusive;\n next.tests = next.tests.filter(fn => {\n if (fn.OPTIONS.name === opts.name) {\n if (isExclusive) return false;\n if (fn.OPTIONS.test === validate.OPTIONS.test) return false;\n }\n return true;\n });\n next.tests.push(validate);\n return next;\n }\n when(keys, options) {\n if (!Array.isArray(keys) && typeof keys !== 'string') {\n options = keys;\n keys = '.';\n }\n let next = this.clone();\n let deps = toArray(keys).map(key => new Reference(key));\n deps.forEach(dep => {\n // @ts-ignore readonly array\n if (dep.isSibling) next.deps.push(dep.key);\n });\n next.conditions.push(typeof options === 'function' ? new Condition(deps, options) : Condition.fromOptions(deps, options));\n return next;\n }\n typeError(message) {\n let next = this.clone();\n next.internalTests.typeError = createValidation({\n message,\n name: 'typeError',\n skipAbsent: true,\n test(value) {\n if (!this.schema._typeCheck(value)) return this.createError({\n params: {\n type: this.schema.type\n }\n });\n return true;\n }\n });\n return next;\n }\n oneOf(enums, message = mixed.oneOf) {\n let next = this.clone();\n enums.forEach(val => {\n next._whitelist.add(val);\n next._blacklist.delete(val);\n });\n next.internalTests.whiteList = createValidation({\n message,\n name: 'oneOf',\n skipAbsent: true,\n test(value) {\n let valids = this.schema._whitelist;\n let resolved = valids.resolveAll(this.resolve);\n return resolved.includes(value) ? true : this.createError({\n params: {\n values: Array.from(valids).join(', '),\n resolved\n }\n });\n }\n });\n return next;\n }\n notOneOf(enums, message = mixed.notOneOf) {\n let next = this.clone();\n enums.forEach(val => {\n next._blacklist.add(val);\n next._whitelist.delete(val);\n });\n next.internalTests.blacklist = createValidation({\n message,\n name: 'notOneOf',\n test(value) {\n let invalids = this.schema._blacklist;\n let resolved = invalids.resolveAll(this.resolve);\n if (resolved.includes(value)) return this.createError({\n params: {\n values: Array.from(invalids).join(', '),\n resolved\n }\n });\n return true;\n }\n });\n return next;\n }\n strip(strip = true) {\n let next = this.clone();\n next.spec.strip = strip;\n return next;\n }\n\n /**\n * Return a serialized description of the schema including validations, flags, types etc.\n *\n * @param options Provide any needed context for resolving runtime schema alterations (lazy, when conditions, etc).\n */\n describe(options) {\n const next = (options ? this.resolve(options) : this).clone();\n const {\n label,\n meta,\n optional,\n nullable\n } = next.spec;\n const description = {\n meta,\n label,\n optional,\n nullable,\n default: next.getDefault(options),\n type: next.type,\n oneOf: next._whitelist.describe(),\n notOneOf: next._blacklist.describe(),\n tests: next.tests.filter((n, idx, list) => list.findIndex(c => c.OPTIONS.name === n.OPTIONS.name) === idx).map(fn => {\n const params = fn.OPTIONS.params && options ? resolveParams(Object.assign({}, fn.OPTIONS.params), options) : fn.OPTIONS.params;\n return {\n name: fn.OPTIONS.name,\n params\n };\n })\n };\n return description;\n }\n get ['~standard']() {\n const schema = this;\n const standard = {\n version: 1,\n vendor: 'yup',\n async validate(value) {\n try {\n const result = await schema.validate(value, {\n abortEarly: false\n });\n return {\n value: result\n };\n } catch (err) {\n if (err instanceof ValidationError) {\n return {\n issues: issuesFromValidationError(err)\n };\n }\n throw err;\n }\n }\n };\n return standard;\n }\n}\n// @ts-expect-error\nSchema.prototype.__isYupSchema__ = true;\nfor (const method of ['validate', 'validateSync']) Schema.prototype[`${method}At`] = function (path, value, options = {}) {\n const {\n parent,\n parentPath,\n schema\n } = getIn(this, path, value, options.context);\n return schema[method](parent && parent[parentPath], Object.assign({}, options, {\n parent,\n path\n }));\n};\nfor (const alias of ['equals', 'is']) Schema.prototype[alias] = Schema.prototype.oneOf;\nfor (const alias of ['not', 'nope']) Schema.prototype[alias] = Schema.prototype.notOneOf;\n\nconst returnsTrue = () => true;\nfunction create$8(spec) {\n return new MixedSchema(spec);\n}\nclass MixedSchema extends Schema {\n constructor(spec) {\n super(typeof spec === 'function' ? {\n type: 'mixed',\n check: spec\n } : Object.assign({\n type: 'mixed',\n check: returnsTrue\n }, spec));\n }\n}\ncreate$8.prototype = MixedSchema.prototype;\n\nfunction create$7() {\n return new BooleanSchema();\n}\nclass BooleanSchema extends Schema {\n constructor() {\n super({\n type: 'boolean',\n check(v) {\n if (v instanceof Boolean) v = v.valueOf();\n return typeof v === 'boolean';\n }\n });\n this.withMutation(() => {\n this.transform((value, _raw) => {\n if (this.spec.coerce && !this.isType(value)) {\n if (/^(true|1)$/i.test(String(value))) return true;\n if (/^(false|0)$/i.test(String(value))) return false;\n }\n return value;\n });\n });\n }\n isTrue(message = boolean.isValue) {\n return this.test({\n message,\n name: 'is-value',\n exclusive: true,\n params: {\n value: 'true'\n },\n test(value) {\n return isAbsent(value) || value === true;\n }\n });\n }\n isFalse(message = boolean.isValue) {\n return this.test({\n message,\n name: 'is-value',\n exclusive: true,\n params: {\n value: 'false'\n },\n test(value) {\n return isAbsent(value) || value === false;\n }\n });\n }\n default(def) {\n return super.default(def);\n }\n defined(msg) {\n return super.defined(msg);\n }\n optional() {\n return super.optional();\n }\n required(msg) {\n return super.required(msg);\n }\n notRequired() {\n return super.notRequired();\n }\n nullable() {\n return super.nullable();\n }\n nonNullable(msg) {\n return super.nonNullable(msg);\n }\n strip(v) {\n return super.strip(v);\n }\n}\ncreate$7.prototype = BooleanSchema.prototype;\n\n/**\n * This file is a modified version of the file from the following repository:\n * Date.parse with progressive enhancement for ISO 8601 <https://github.com/csnover/js-iso8601>\n * NON-CONFORMANT EDITION.\n * \u00A9 2011 Colin Snover <http://zetafleet.com>\n * Released under MIT license.\n */\n\n// prettier-ignore\n// 1 YYYY 2 MM 3 DD 4 HH 5 mm 6 ss 7 msec 8 Z 9 \u00B1 10 tzHH 11 tzmm\nconst isoReg = /^(\\d{4}|[+-]\\d{6})(?:-?(\\d{2})(?:-?(\\d{2}))?)?(?:[ T]?(\\d{2}):?(\\d{2})(?::?(\\d{2})(?:[,.](\\d{1,}))?)?(?:(Z)|([+-])(\\d{2})(?::?(\\d{2}))?)?)?$/;\nfunction parseIsoDate(date) {\n const struct = parseDateStruct(date);\n if (!struct) return Date.parse ? Date.parse(date) : Number.NaN;\n\n // timestamps without timezone identifiers should be considered local time\n if (struct.z === undefined && struct.plusMinus === undefined) {\n return new Date(struct.year, struct.month, struct.day, struct.hour, struct.minute, struct.second, struct.millisecond).valueOf();\n }\n let totalMinutesOffset = 0;\n if (struct.z !== 'Z' && struct.plusMinus !== undefined) {\n totalMinutesOffset = struct.hourOffset * 60 + struct.minuteOffset;\n if (struct.plusMinus === '+') totalMinutesOffset = 0 - totalMinutesOffset;\n }\n return Date.UTC(struct.year, struct.month, struct.day, struct.hour, struct.minute + totalMinutesOffset, struct.second, struct.millisecond);\n}\nfunction parseDateStruct(date) {\n var _regexResult$7$length, _regexResult$;\n const regexResult = isoReg.exec(date);\n if (!regexResult) return null;\n\n // use of toNumber() avoids NaN timestamps caused by \u201Cundefined\u201D\n // values being passed to Date constructor\n return {\n year: toNumber(regexResult[1]),\n month: toNumber(regexResult[2], 1) - 1,\n day: toNumber(regexResult[3], 1),\n hour: toNumber(regexResult[4]),\n minute: toNumber(regexResult[5]),\n second: toNumber(regexResult[6]),\n millisecond: regexResult[7] ?\n // allow arbitrary sub-second precision beyond milliseconds\n toNumber(regexResult[7].substring(0, 3)) : 0,\n precision: (_regexResult$7$length = (_regexResult$ = regexResult[7]) == null ? void 0 : _regexResult$.length) != null ? _regexResult$7$length : undefined,\n z: regexResult[8] || undefined,\n plusMinus: regexResult[9] || undefined,\n hourOffset: toNumber(regexResult[10]),\n minuteOffset: toNumber(regexResult[11])\n };\n}\nfunction toNumber(str, defaultValue = 0) {\n return Number(str) || defaultValue;\n}\n\n// Taken from HTML spec: https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address\nlet rEmail =\n// eslint-disable-next-line\n/^[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])?)*$/;\nlet rUrl =\n// eslint-disable-next-line\n/^((https?|ftp):)?\\/\\/(((([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&'\\(\\)\\*\\+,;=]|:)*@)?(((\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]))|((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.?)(:\\d*)?)(\\/((([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&'\\(\\)\\*\\+,;=]|:|@)+(\\/(([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&'\\(\\)\\*\\+,;=]|:|@)*)*)?)?(\\?((([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&'\\(\\)\\*\\+,;=]|:|@)|[\\uE000-\\uF8FF]|\\/|\\?)*)?(\\#((([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&'\\(\\)\\*\\+,;=]|:|@)|\\/|\\?)*)?$/i;\n\n// eslint-disable-next-line\nlet rUUID = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;\nlet yearMonthDay = '^\\\\d{4}-\\\\d{2}-\\\\d{2}';\nlet hourMinuteSecond = '\\\\d{2}:\\\\d{2}:\\\\d{2}';\nlet zOrOffset = '(([+-]\\\\d{2}(:?\\\\d{2})?)|Z)';\nlet rIsoDateTime = new RegExp(`${yearMonthDay}T${hourMinuteSecond}(\\\\.\\\\d+)?${zOrOffset}$`);\nlet isTrimmed = value => isAbsent(value) || value === value.trim();\nlet objStringTag = {}.toString();\nfunction create$6() {\n return new StringSchema();\n}\nclass StringSchema extends Schema {\n constructor() {\n super({\n type: 'string',\n check(value) {\n if (value instanceof String) value = value.valueOf();\n return typeof value === 'string';\n }\n });\n this.withMutation(() => {\n this.transform((value, _raw) => {\n if (!this.spec.coerce || this.isType(value)) return value;\n\n // don't ever convert arrays\n if (Array.isArray(value)) return value;\n const strValue = value != null && value.toString ? value.toString() : value;\n\n // no one wants plain objects converted to [Object object]\n if (strValue === objStringTag) return value;\n return strValue;\n });\n });\n }\n required(message) {\n return super.required(message).withMutation(schema => schema.test({\n message: message || mixed.required,\n name: 'required',\n skipAbsent: true,\n test: value => !!value.length\n }));\n }\n notRequired() {\n return super.notRequired().withMutation(schema => {\n schema.tests = schema.tests.filter(t => t.OPTIONS.name !== 'required');\n return schema;\n });\n }\n length(length, message = string.length) {\n return this.test({\n message,\n name: 'length',\n exclusive: true,\n params: {\n length\n },\n skipAbsent: true,\n test(value) {\n return value.length === this.resolve(length);\n }\n });\n }\n min(min, message = string.min) {\n return this.test({\n message,\n name: 'min',\n exclusive: true,\n params: {\n min\n },\n skipAbsent: true,\n test(value) {\n return value.length >= this.resolve(min);\n }\n });\n }\n max(max, message = string.max) {\n return this.test({\n name: 'max',\n exclusive: true,\n message,\n params: {\n max\n },\n skipAbsent: true,\n test(value) {\n return value.length <= this.resolve(max);\n }\n });\n }\n matches(regex, options) {\n let excludeEmptyString = false;\n let message;\n let name;\n if (options) {\n if (typeof options === 'object') {\n ({\n excludeEmptyString = false,\n message,\n name\n } = options);\n } else {\n message = options;\n }\n }\n return this.test({\n name: name || 'matches',\n message: message || string.matches,\n params: {\n regex\n },\n skipAbsent: true,\n test: value => value === '' && excludeEmptyString || value.search(regex) !== -1\n });\n }\n email(message = string.email) {\n return this.matches(rEmail, {\n name: 'email',\n message,\n excludeEmptyString: true\n });\n }\n url(message = string.url) {\n return this.matches(rUrl, {\n name: 'url',\n message,\n excludeEmptyString: true\n });\n }\n uuid(message = string.uuid) {\n return this.matches(rUUID, {\n name: 'uuid',\n message,\n excludeEmptyString: false\n });\n }\n datetime(options) {\n let message = '';\n let allowOffset;\n let precision;\n if (options) {\n if (typeof options === 'object') {\n ({\n message = '',\n allowOffset = false,\n precision = undefined\n } = options);\n } else {\n message = options;\n }\n }\n return this.matches(rIsoDateTime, {\n name: 'datetime',\n message: message || string.datetime,\n excludeEmptyString: true\n }).test({\n name: 'datetime_offset',\n message: message || string.datetime_offset,\n params: {\n allowOffset\n },\n skipAbsent: true,\n test: value => {\n if (!value || allowOffset) return true;\n const struct = parseDateStruct(value);\n if (!struct) return false;\n return !!struct.z;\n }\n }).test({\n name: 'datetime_precision',\n message: message || string.datetime_precision,\n params: {\n precision\n },\n skipAbsent: true,\n test: value => {\n if (!value || precision == undefined) return true;\n const struct = parseDateStruct(value);\n if (!struct) return false;\n return struct.precision === precision;\n }\n });\n }\n\n //-- transforms --\n ensure() {\n return this.default('').transform(val => val === null ? '' : val);\n }\n trim(message = string.trim) {\n return this.transform(val => val != null ? val.trim() : val).test({\n message,\n name: 'trim',\n test: isTrimmed\n });\n }\n lowercase(message = string.lowercase) {\n return this.transform(value => !isAbsent(value) ? value.toLowerCase() : value).test({\n message,\n name: 'string_case',\n exclusive: true,\n skipAbsent: true,\n test: value => isAbsent(value) || value === value.toLowerCase()\n });\n }\n uppercase(message = string.uppercase) {\n return this.transform(value => !isAbsent(value) ? value.toUpperCase() : value).test({\n message,\n name: 'string_case',\n exclusive: true,\n skipAbsent: true,\n test: value => isAbsent(value) || value === value.toUpperCase()\n });\n }\n}\ncreate$6.prototype = StringSchema.prototype;\n\n//\n// String Interfaces\n//\n\nlet isNaN$1 = value => value != +value;\nfunction create$5() {\n return new NumberSchema();\n}\nclass NumberSchema extends Schema {\n constructor() {\n super({\n type: 'number',\n check(value) {\n if (value instanceof Number) value = value.valueOf();\n return typeof value === 'number' && !isNaN$1(value);\n }\n });\n this.withMutation(() => {\n this.transform((value, _raw) => {\n if (!this.spec.coerce) return value;\n let parsed = value;\n if (typeof parsed === 'string') {\n parsed = parsed.replace(/\\s/g, '');\n if (parsed === '') return NaN;\n // don't use parseFloat to avoid positives on alpha-numeric strings\n parsed = +parsed;\n }\n\n // null -> NaN isn't useful; treat all nulls as null and let it fail on\n // nullability check vs TypeErrors\n if (this.isType(parsed) || parsed === null) return parsed;\n return parseFloat(parsed);\n });\n });\n }\n min(min, message = number.min) {\n return this.test({\n message,\n name: 'min',\n exclusive: true,\n params: {\n min\n },\n skipAbsent: true,\n test(value) {\n return value >= this.resolve(min);\n }\n });\n }\n max(max, message = number.max) {\n return this.test({\n message,\n name: 'max',\n exclusive: true,\n params: {\n max\n },\n skipAbsent: true,\n test(value) {\n return value <= this.resolve(max);\n }\n });\n }\n lessThan(less, message = number.lessThan) {\n return this.test({\n message,\n name: 'max',\n exclusive: true,\n params: {\n less\n },\n skipAbsent: true,\n test(value) {\n return value < this.resolve(less);\n }\n });\n }\n moreThan(more, message = number.moreThan) {\n return this.test({\n message,\n name: 'min',\n exclusive: true,\n params: {\n more\n },\n skipAbsent: true,\n test(value) {\n return value > this.resolve(more);\n }\n });\n }\n positive(msg = number.positive) {\n return this.moreThan(0, msg);\n }\n negative(msg = number.negative) {\n return this.lessThan(0, msg);\n }\n integer(message = number.integer) {\n return this.test({\n name: 'integer',\n message,\n skipAbsent: true,\n test: val => Number.isInteger(val)\n });\n }\n truncate() {\n return this.transform(value => !isAbsent(value) ? value | 0 : value);\n }\n round(method) {\n var _method;\n let avail = ['ceil', 'floor', 'round', 'trunc'];\n method = ((_method = method) == null ? void 0 : _method.toLowerCase()) || 'round';\n\n // this exists for symemtry with the new Math.trunc\n if (method === 'trunc') return this.truncate();\n if (avail.indexOf(method.toLowerCase()) === -1) throw new TypeError('Only valid options for round() are: ' + avail.join(', '));\n return this.transform(value => !isAbsent(value) ? Math[method](value) : value);\n }\n}\ncreate$5.prototype = NumberSchema.prototype;\n\n//\n// Number Interfaces\n//\n\nlet invalidDate = new Date('');\nlet isDate = obj => Object.prototype.toString.call(obj) === '[object Date]';\nfunction create$4() {\n return new DateSchema();\n}\nclass DateSchema extends Schema {\n constructor() {\n super({\n type: 'date',\n check(v) {\n return isDate(v) && !isNaN(v.getTime());\n }\n });\n this.withMutation(() => {\n this.transform((value, _raw) => {\n // null -> InvalidDate isn't useful; treat all nulls as null and let it fail on\n // nullability check vs TypeErrors\n if (!this.spec.coerce || this.isType(value) || value === null) return value;\n value = parseIsoDate(value);\n\n // 0 is a valid timestamp equivalent to 1970-01-01T00:00:00Z(unix epoch) or before.\n return !isNaN(value) ? new Date(value) : DateSchema.INVALID_DATE;\n });\n });\n }\n prepareParam(ref, name) {\n let param;\n if (!Reference.isRef(ref)) {\n let cast = this.cast(ref);\n if (!this._typeCheck(cast)) throw new TypeError(`\\`${name}\\` must be a Date or a value that can be \\`cast()\\` to a Date`);\n param = cast;\n } else {\n param = ref;\n }\n return param;\n }\n min(min, message = date.min) {\n let limit = this.prepareParam(min, 'min');\n return this.test({\n message,\n name: 'min',\n exclusive: true,\n params: {\n min\n },\n skipAbsent: true,\n test(value) {\n return value >= this.resolve(limit);\n }\n });\n }\n max(max, message = date.max) {\n let limit = this.prepareParam(max, 'max');\n return this.test({\n message,\n name: 'max',\n exclusive: true,\n params: {\n max\n },\n skipAbsent: true,\n test(value) {\n return value <= this.resolve(limit);\n }\n });\n }\n}\nDateSchema.INVALID_DATE = invalidDate;\ncreate$4.prototype = DateSchema.prototype;\ncreate$4.INVALID_DATE = invalidDate;\n\n// @ts-expect-error\nfunction sortFields(fields, excludedEdges = []) {\n let edges = [];\n let nodes = new Set();\n let excludes = new Set(excludedEdges.map(([a, b]) => `${a}-${b}`));\n function addNode(depPath, key) {\n let node = split(depPath)[0];\n nodes.add(node);\n if (!excludes.has(`${key}-${node}`)) edges.push([key, node]);\n }\n for (const key of Object.keys(fields)) {\n let value = fields[key];\n nodes.add(key);\n if (Reference.isRef(value) && value.isSibling) addNode(value.path, key);else if (isSchema(value) && 'deps' in value) value.deps.forEach(path => addNode(path, key));\n }\n return toposort.array(Array.from(nodes), edges).reverse();\n}\n\nfunction findIndex(arr, err) {\n let idx = Infinity;\n arr.some((key, ii) => {\n var _err$path;\n if ((_err$path = err.path) != null && _err$path.includes(key)) {\n idx = ii;\n return true;\n }\n });\n return idx;\n}\nfunction sortByKeyOrder(keys) {\n return (a, b) => {\n return findIndex(keys, a) - findIndex(keys, b);\n };\n}\n\nconst parseJson = (value, _, schema) => {\n if (typeof value !== 'string') {\n return value;\n }\n let parsed = value;\n try {\n parsed = JSON.parse(value);\n } catch (err) {\n /* */\n }\n return schema.isType(parsed) ? parsed : value;\n};\n\n// @ts-ignore\nfunction deepPartial(schema) {\n if ('fields' in schema) {\n const partial = {};\n for (const [key, fieldSchema] of Object.entries(schema.fields)) {\n partial[key] = deepPartial(fieldSchema);\n }\n return schema.setFields(partial);\n }\n if (schema.type === 'array') {\n const nextArray = schema.optional();\n if (nextArray.innerType) nextArray.innerType = deepPartial(nextArray.innerType);\n return nextArray;\n }\n if (schema.type === 'tuple') {\n return schema.optional().clone({\n types: schema.spec.types.map(deepPartial)\n });\n }\n if ('optional' in schema) {\n return schema.optional();\n }\n return schema;\n}\nconst deepHas = (obj, p) => {\n const path = [...normalizePath(p)];\n if (path.length === 1) return path[0] in obj;\n let last = path.pop();\n let parent = getter(join(path), true)(obj);\n return !!(parent && last in parent);\n};\nlet isObject = obj => Object.prototype.toString.call(obj) === '[object Object]';\nfunction unknown(ctx, value) {\n let known = Object.keys(ctx.fields);\n return Object.keys(value).filter(key => known.indexOf(key) === -1);\n}\nconst defaultSort = sortByKeyOrder([]);\nfunction create$3(spec) {\n return new ObjectSchema(spec);\n}\nclass ObjectSchema extends Schema {\n constructor(spec) {\n super({\n type: 'object',\n check(value) {\n return isObject(value) || typeof value === 'function';\n }\n });\n this.fields = Object.create(null);\n this._sortErrors = defaultSort;\n this._nodes = [];\n this._excludedEdges = [];\n this.withMutation(() => {\n if (spec) {\n this.shape(spec);\n }\n });\n }\n _cast(_value, options = {}) {\n var _options$stripUnknown;\n let value = super._cast(_value, options);\n\n //should ignore nulls here\n if (value === undefined) return this.getDefault(options);\n if (!this._typeCheck(value)) return value;\n let fields = this.fields;\n let strip = (_options$stripUnknown = options.stripUnknown) != null ? _options$stripUnknown : this.spec.noUnknown;\n let props = [].concat(this._nodes, Object.keys(value).filter(v => !this._nodes.includes(v)));\n let intermediateValue = {}; // is filled during the transform below\n let innerOptions = Object.assign({}, options, {\n parent: intermediateValue,\n __validating: options.__validating || false\n });\n let isChanged = false;\n for (const prop of props) {\n let field = fields[prop];\n let exists = (prop in value);\n let inputValue = value[prop];\n if (field) {\n let fieldValue;\n\n // safe to mutate since this is fired in sequence\n innerOptions.path = (options.path ? `${options.path}.` : '') + prop;\n field = field.resolve({\n value: inputValue,\n context: options.context,\n parent: intermediateValue\n });\n let fieldSpec = field instanceof Schema ? field.spec : undefined;\n let strict = fieldSpec == null ? void 0 : fieldSpec.strict;\n if (fieldSpec != null && fieldSpec.strip) {\n isChanged = isChanged || prop in value;\n continue;\n }\n fieldValue = !options.__validating || !strict ? field.cast(inputValue, innerOptions) : inputValue;\n if (fieldValue !== undefined) {\n intermediateValue[prop] = fieldValue;\n }\n } else if (exists && !strip) {\n intermediateValue[prop] = inputValue;\n }\n if (exists !== prop in intermediateValue || intermediateValue[prop] !== inputValue) {\n isChanged = true;\n }\n }\n return isChanged ? intermediateValue : value;\n }\n _validate(_value, options = {}, panic, next) {\n let {\n from = [],\n originalValue = _value,\n recursive = this.spec.recursive\n } = options;\n options.from = [{\n schema: this,\n value: originalValue\n }, ...from];\n // this flag is needed for handling `strict` correctly in the context of\n // validation vs just casting. e.g strict() on a field is only used when validating\n options.__validating = true;\n options.originalValue = originalValue;\n super._validate(_value, options, panic, (objectErrors, value) => {\n if (!recursive || !isObject(value)) {\n next(objectErrors, value);\n return;\n }\n originalValue = originalValue || value;\n let tests = [];\n for (let key of this._nodes) {\n let field = this.fields[key];\n if (!field || Reference.isRef(field)) {\n continue;\n }\n tests.push(field.asNestedTest({\n options,\n key,\n parent: value,\n parentPath: options.path,\n originalParent: originalValue\n }));\n }\n this.runTests({\n tests,\n value,\n originalValue,\n options\n }, panic, fieldErrors => {\n next(fieldErrors.sort(this._sortErrors).concat(objectErrors), value);\n });\n });\n }\n clone(spec) {\n const next = super.clone(spec);\n next.fields = Object.assign({}, this.fields);\n next._nodes = this._nodes;\n next._excludedEdges = this._excludedEdges;\n next._sortErrors = this._sortErrors;\n return next;\n }\n concat(schema) {\n let next = super.concat(schema);\n let nextFields = next.fields;\n for (let [field, schemaOrRef] of Object.entries(this.fields)) {\n const target = nextFields[field];\n nextFields[field] = target === undefined ? schemaOrRef : target;\n }\n return next.withMutation(s =>\n // XXX: excludes here is wrong\n s.setFields(nextFields, [...this._excludedEdges, ...schema._excludedEdges]));\n }\n _getDefault(options) {\n if ('default' in this.spec) {\n return super._getDefault(options);\n }\n\n // if there is no default set invent one\n if (!this._nodes.length) {\n return undefined;\n }\n let dft = {};\n this._nodes.forEach(key => {\n var _innerOptions;\n const field = this.fields[key];\n let innerOptions = options;\n if ((_innerOptions = innerOptions) != null && _innerOptions.value) {\n innerOptions = Object.assign({}, innerOptions, {\n parent: innerOptions.value,\n value: innerOptions.value[key]\n });\n }\n dft[key] = field && 'getDefault' in field ? field.getDefault(innerOptions) : undefined;\n });\n return dft;\n }\n setFields(shape, excludedEdges) {\n let next = this.clone();\n next.fields = shape;\n next._nodes = sortFields(shape, excludedEdges);\n next._sortErrors = sortByKeyOrder(Object.keys(shape));\n // XXX: this carries over edges which may not be what you want\n if (excludedEdges) next._excludedEdges = excludedEdges;\n return next;\n }\n shape(additions, excludes = []) {\n return this.clone().withMutation(next => {\n let edges = next._excludedEdges;\n if (excludes.length) {\n if (!Array.isArray(excludes[0])) excludes = [excludes];\n edges = [...next._excludedEdges, ...excludes];\n }\n\n // XXX: excludes here is wrong\n return next.setFields(Object.assign(next.fields, additions), edges);\n });\n }\n partial() {\n const partial = {};\n for (const [key, schema] of Object.entries(this.fields)) {\n partial[key] = 'optional' in schema && schema.optional instanceof Function ? schema.optional() : schema;\n }\n return this.setFields(partial);\n }\n deepPartial() {\n const next = deepPartial(this);\n return next;\n }\n pick(keys) {\n const picked = {};\n for (const key of keys) {\n if (this.fields[key]) picked[key] = this.fields[key];\n }\n return this.setFields(picked, this._excludedEdges.filter(([a, b]) => keys.includes(a) && keys.includes(b)));\n }\n omit(keys) {\n const remaining = [];\n for (const key of Object.keys(this.fields)) {\n if (keys.includes(key)) continue;\n remaining.push(key);\n }\n return this.pick(remaining);\n }\n from(from, to, alias) {\n let fromGetter = getter(from, true);\n return this.transform(obj => {\n if (!obj) return obj;\n let newObj = obj;\n if (deepHas(obj, from)) {\n newObj = Object.assign({}, obj);\n if (!alias) delete newObj[from];\n newObj[to] = fromGetter(obj);\n }\n return newObj;\n });\n }\n\n /** Parse an input JSON string to an object */\n json() {\n return this.transform(parseJson);\n }\n\n /**\n * Similar to `noUnknown` but only validates that an object is the right shape without stripping the unknown keys\n */\n exact(message) {\n return this.test({\n name: 'exact',\n exclusive: true,\n message: message || object.exact,\n test(value) {\n if (value == null) return true;\n const unknownKeys = unknown(this.schema, value);\n return unknownKeys.length === 0 || this.createError({\n params: {\n properties: unknownKeys.join(', ')\n }\n });\n }\n });\n }\n stripUnknown() {\n return this.clone({\n noUnknown: true\n });\n }\n noUnknown(noAllow = true, message = object.noUnknown) {\n if (typeof noAllow !== 'boolean') {\n message = noAllow;\n noAllow = true;\n }\n let next = this.test({\n name: 'noUnknown',\n exclusive: true,\n message: message,\n test(value) {\n if (value == null) return true;\n const unknownKeys = unknown(this.schema, value);\n return !noAllow || unknownKeys.length === 0 || this.createError({\n params: {\n unknown: unknownKeys.join(', ')\n }\n });\n }\n });\n next.spec.noUnknown = noAllow;\n return next;\n }\n unknown(allow = true, message = object.noUnknown) {\n return this.noUnknown(!allow, message);\n }\n transformKeys(fn) {\n return this.transform(obj => {\n if (!obj) return obj;\n const result = {};\n for (const key of Object.keys(obj)) result[fn(key)] = obj[key];\n return result;\n });\n }\n camelCase() {\n return this.transformKeys(camelCase);\n }\n snakeCase() {\n return this.transformKeys(snakeCase);\n }\n constantCase() {\n return this.transformKeys(key => snakeCase(key).toUpperCase());\n }\n describe(options) {\n const next = (options ? this.resolve(options) : this).clone();\n const base = super.describe(options);\n base.fields = {};\n for (const [key, value] of Object.entries(next.fields)) {\n var _innerOptions2;\n let innerOptions = options;\n if ((_innerOptions2 = innerOptions) != null && _innerOptions2.value) {\n innerOptions = Object.assign({}, innerOptions, {\n parent: innerOptions.value,\n value: innerOptions.value[key]\n });\n }\n base.fields[key] = value.describe(innerOptions);\n }\n return base;\n }\n}\ncreate$3.prototype = ObjectSchema.prototype;\n\nfunction create$2(type) {\n return new ArraySchema(type);\n}\nclass ArraySchema extends Schema {\n constructor(type) {\n super({\n type: 'array',\n spec: {\n types: type\n },\n check(v) {\n return Array.isArray(v);\n }\n });\n\n // `undefined` specifically means uninitialized, as opposed to \"no subtype\"\n this.innerType = void 0;\n this.innerType = type;\n }\n _cast(_value, _opts) {\n const value = super._cast(_value, _opts);\n\n // should ignore nulls here\n if (!this._typeCheck(value) || !this.innerType) {\n return value;\n }\n let isChanged = false;\n const castArray = value.map((v, idx) => {\n const castElement = this.innerType.cast(v, Object.assign({}, _opts, {\n path: `${_opts.path || ''}[${idx}]`,\n parent: value,\n originalValue: v,\n value: v,\n index: idx\n }));\n if (castElement !== v) {\n isChanged = true;\n }\n return castElement;\n });\n return isChanged ? castArray : value;\n }\n _validate(_value, options = {}, panic, next) {\n var _options$recursive;\n // let sync = options.sync;\n // let path = options.path;\n let innerType = this.innerType;\n // let endEarly = options.abortEarly ?? this.spec.abortEarly;\n let recursive = (_options$recursive = options.recursive) != null ? _options$recursive : this.spec.recursive;\n options.originalValue != null ? options.originalValue : _value;\n super._validate(_value, options, panic, (arrayErrors, value) => {\n var _options$originalValu2;\n if (!recursive || !innerType || !this._typeCheck(value)) {\n next(arrayErrors, value);\n return;\n }\n\n // #950 Ensure that sparse array empty slots are validated\n let tests = new Array(value.length);\n for (let index = 0; index < value.length; index++) {\n var _options$originalValu;\n tests[index] = innerType.asNestedTest({\n options,\n index,\n parent: value,\n parentPath: options.path,\n originalParent: (_options$originalValu = options.originalValue) != null ? _options$originalValu : _value\n });\n }\n this.runTests({\n value,\n tests,\n originalValue: (_options$originalValu2 = options.originalValue) != null ? _options$originalValu2 : _value,\n options\n }, panic, innerTypeErrors => next(innerTypeErrors.concat(arrayErrors), value));\n });\n }\n clone(spec) {\n const next = super.clone(spec);\n // @ts-expect-error readonly\n next.innerType = this.innerType;\n return next;\n }\n\n /** Parse an input JSON string to an object */\n json() {\n return this.transform(parseJson);\n }\n concat(schema) {\n let next = super.concat(schema);\n\n // @ts-expect-error readonly\n next.innerType = this.innerType;\n if (schema.innerType)\n // @ts-expect-error readonly\n next.innerType = next.innerType ?\n // @ts-expect-error Lazy doesn't have concat and will break\n next.innerType.concat(schema.innerType) : schema.innerType;\n return next;\n }\n of(schema) {\n // FIXME: this should return a new instance of array without the default to be\n let next = this.clone();\n if (!isSchema(schema)) throw new TypeError('`array.of()` sub-schema must be a valid yup schema not: ' + printValue(schema));\n\n // @ts-expect-error readonly\n next.innerType = schema;\n next.spec = Object.assign({}, next.spec, {\n types: schema\n });\n return next;\n }\n length(length, message = array.length) {\n return this.test({\n message,\n name: 'length',\n exclusive: true,\n params: {\n length\n },\n skipAbsent: true,\n test(value) {\n return value.length === this.resolve(length);\n }\n });\n }\n min(min, message) {\n message = message || array.min;\n return this.test({\n message,\n name: 'min',\n exclusive: true,\n params: {\n min\n },\n skipAbsent: true,\n // FIXME(ts): Array<typeof T>\n test(value) {\n return value.length >= this.resolve(min);\n }\n });\n }\n max(max, message) {\n message = message || array.max;\n return this.test({\n message,\n name: 'max',\n exclusive: true,\n params: {\n max\n },\n skipAbsent: true,\n test(value) {\n return value.length <= this.resolve(max);\n }\n });\n }\n ensure() {\n return this.default(() => []).transform((val, original) => {\n // We don't want to return `null` for nullable schema\n if (this._typeCheck(val)) return val;\n return original == null ? [] : [].concat(original);\n });\n }\n compact(rejector) {\n let reject = !rejector ? v => !!v : (v, i, a) => !rejector(v, i, a);\n return this.transform(values => values != null ? values.filter(reject) : values);\n }\n describe(options) {\n const next = (options ? this.resolve(options) : this).clone();\n const base = super.describe(options);\n if (next.innerType) {\n var _innerOptions;\n let innerOptions = options;\n if ((_innerOptions = innerOptions) != null && _innerOptions.value) {\n innerOptions = Object.assign({}, innerOptions, {\n parent: innerOptions.value,\n value: innerOptions.value[0]\n });\n }\n base.innerType = next.innerType.describe(innerOptions);\n }\n return base;\n }\n}\ncreate$2.prototype = ArraySchema.prototype;\n\n// @ts-ignore\nfunction create$1(schemas) {\n return new TupleSchema(schemas);\n}\nclass TupleSchema extends Schema {\n constructor(schemas) {\n super({\n type: 'tuple',\n spec: {\n types: schemas\n },\n check(v) {\n const types = this.spec.types;\n return Array.isArray(v) && v.length === types.length;\n }\n });\n this.withMutation(() => {\n this.typeError(tuple.notType);\n });\n }\n _cast(inputValue, options) {\n const {\n types\n } = this.spec;\n const value = super._cast(inputValue, options);\n if (!this._typeCheck(value)) {\n return value;\n }\n let isChanged = false;\n const castArray = types.map((type, idx) => {\n const castElement = type.cast(value[idx], Object.assign({}, options, {\n path: `${options.path || ''}[${idx}]`,\n parent: value,\n originalValue: value[idx],\n value: value[idx],\n index: idx\n }));\n if (castElement !== value[idx]) isChanged = true;\n return castElement;\n });\n return isChanged ? castArray : value;\n }\n _validate(_value, options = {}, panic, next) {\n let itemTypes = this.spec.types;\n super._validate(_value, options, panic, (tupleErrors, value) => {\n var _options$originalValu2;\n // intentionally not respecting recursive\n if (!this._typeCheck(value)) {\n next(tupleErrors, value);\n return;\n }\n let tests = [];\n for (let [index, itemSchema] of itemTypes.entries()) {\n var _options$originalValu;\n tests[index] = itemSchema.asNestedTest({\n options,\n index,\n parent: value,\n parentPath: options.path,\n originalParent: (_options$originalValu = options.originalValue) != null ? _options$originalValu : _value\n });\n }\n this.runTests({\n value,\n tests,\n originalValue: (_options$originalValu2 = options.originalValue) != null ? _options$originalValu2 : _value,\n options\n }, panic, innerTypeErrors => next(innerTypeErrors.concat(tupleErrors), value));\n });\n }\n describe(options) {\n const next = (options ? this.resolve(options) : this).clone();\n const base = super.describe(options);\n base.innerType = next.spec.types.map((schema, index) => {\n var _innerOptions;\n let innerOptions = options;\n if ((_innerOptions = innerOptions) != null && _innerOptions.value) {\n innerOptions = Object.assign({}, innerOptions, {\n parent: innerOptions.value,\n value: innerOptions.value[index]\n });\n }\n return schema.describe(innerOptions);\n });\n return base;\n }\n}\ncreate$1.prototype = TupleSchema.prototype;\n\nfunction create(builder) {\n return new Lazy(builder);\n}\nfunction catchValidationError(fn) {\n try {\n return fn();\n } catch (err) {\n if (ValidationError.isError(err)) return Promise.reject(err);\n throw err;\n }\n}\nclass Lazy {\n constructor(builder) {\n this.type = 'lazy';\n this.__isYupSchema__ = true;\n this.spec = void 0;\n this._resolve = (value, options = {}) => {\n let schema = this.builder(value, options);\n if (!isSchema(schema)) throw new TypeError('lazy() functions must return a valid schema');\n if (this.spec.optional) schema = schema.optional();\n return schema.resolve(options);\n };\n this.builder = builder;\n this.spec = {\n meta: undefined,\n optional: false\n };\n }\n clone(spec) {\n const next = new Lazy(this.builder);\n next.spec = Object.assign({}, this.spec, spec);\n return next;\n }\n optionality(optional) {\n const next = this.clone({\n optional\n });\n return next;\n }\n optional() {\n return this.optionality(true);\n }\n resolve(options) {\n return this._resolve(options.value, options);\n }\n cast(value, options) {\n return this._resolve(value, options).cast(value, options);\n }\n asNestedTest(config) {\n let {\n key,\n index,\n parent,\n options\n } = config;\n let value = parent[index != null ? index : key];\n return this._resolve(value, Object.assign({}, options, {\n value,\n parent\n })).asNestedTest(config);\n }\n validate(value, options) {\n return catchValidationError(() => this._resolve(value, options).validate(value, options));\n }\n validateSync(value, options) {\n return this._resolve(value, options).validateSync(value, options);\n }\n validateAt(path, value, options) {\n return catchValidationError(() => this._resolve(value, options).validateAt(path, value, options));\n }\n validateSyncAt(path, value, options) {\n return this._resolve(value, options).validateSyncAt(path, value, options);\n }\n isValid(value, options) {\n try {\n return this._resolve(value, options).isValid(value, options);\n } catch (err) {\n if (ValidationError.isError(err)) {\n return Promise.resolve(false);\n }\n throw err;\n }\n }\n isValidSync(value, options) {\n return this._resolve(value, options).isValidSync(value, options);\n }\n describe(options) {\n return options ? this.resolve(options).describe(options) : {\n type: 'lazy',\n meta: this.spec.meta,\n label: undefined\n };\n }\n meta(...args) {\n if (args.length === 0) return this.spec.meta;\n let next = this.clone();\n next.spec.meta = Object.assign(next.spec.meta || {}, args[0]);\n return next;\n }\n get ['~standard']() {\n const schema = this;\n const standard = {\n version: 1,\n vendor: 'yup',\n async validate(value) {\n try {\n const result = await schema.validate(value, {\n abortEarly: false\n });\n return {\n value: result\n };\n } catch (err) {\n if (ValidationError.isError(err)) {\n return {\n issues: issuesFromValidationError(err)\n };\n }\n throw err;\n }\n }\n };\n return standard;\n }\n}\n\nfunction setLocale(custom) {\n Object.keys(custom).forEach(type => {\n // @ts-ignore\n Object.keys(custom[type]).forEach(method => {\n // @ts-ignore\n locale[type][method] = custom[type][method];\n });\n });\n}\n\nfunction addMethod(schemaType, name, fn) {\n if (!schemaType || !isSchema(schemaType.prototype)) throw new TypeError('You must provide a yup schema constructor function');\n if (typeof name !== 'string') throw new TypeError('A Method name must be provided');\n if (typeof fn !== 'function') throw new TypeError('Method function must be provided');\n schemaType.prototype[name] = fn;\n}\n\nexport { ArraySchema, BooleanSchema, DateSchema, Lazy as LazySchema, MixedSchema, NumberSchema, ObjectSchema, Schema, StringSchema, TupleSchema, ValidationError, addMethod, create$2 as array, create$7 as bool, create$7 as boolean, create$4 as date, locale as defaultLocale, getIn, isSchema, create as lazy, create$8 as mixed, create$5 as number, create$3 as object, printValue, reach, create$9 as ref, setLocale, create$6 as string, create$1 as tuple };\n", "export type MoneyAmount = `${number}` | `${number}.${number}`;\n\nexport type Currency = {\n code: Uppercase<string>,\n decimals: number,\n stripeDecimals: number,\n};\n\nexport const SUPPORTED_CURRENCIES = [\n {\n code: 'USD',\n decimals: 2,\n stripeDecimals: 2,\n },\n {\n code: 'EUR',\n decimals: 2,\n stripeDecimals: 2,\n },\n {\n code: 'GBP',\n decimals: 2,\n stripeDecimals: 2,\n },\n {\n code: 'JPY',\n decimals: 0,\n stripeDecimals: 0,\n },\n {\n code: 'INR',\n decimals: 2,\n stripeDecimals: 2,\n },\n {\n code: 'AUD',\n decimals: 2,\n stripeDecimals: 2,\n },\n {\n code: 'CAD',\n decimals: 2,\n stripeDecimals: 2,\n },\n] as const satisfies Currency[];\n", "import { decodeBase64, encodeBase64, isBase64 } from \"./bytes\";\n\nexport const HTTP_METHODS = {\n \"GET\": {\n safe: true,\n idempotent: true,\n },\n \"POST\": {\n safe: false,\n idempotent: false,\n },\n \"PUT\": {\n safe: false,\n idempotent: true,\n },\n \"DELETE\": {\n safe: false,\n idempotent: true,\n },\n \"PATCH\": {\n safe: false,\n idempotent: false,\n },\n \"OPTIONS\": {\n safe: true,\n idempotent: true,\n },\n \"HEAD\": {\n safe: true,\n idempotent: true,\n },\n \"TRACE\": {\n safe: true,\n idempotent: true,\n },\n \"CONNECT\": {\n safe: false,\n idempotent: false,\n },\n} as const;\nexport type HttpMethod = keyof typeof HTTP_METHODS;\n\nexport function decodeBasicAuthorizationHeader(value: string): [string, string] | null {\n const [type, encoded, ...rest] = value.split(' ');\n if (rest.length > 0) return null;\n if (!encoded) return null;\n if (type !== 'Basic') return null;\n if (!isBase64(encoded)) return null;\n const decoded = new TextDecoder().decode(decodeBase64(encoded));\n const split = decoded.split(':');\n return [split[0], split.slice(1).join(':')];\n}\nimport.meta.vitest?.test(\"decodeBasicAuthorizationHeader\", ({ expect }) => {\n // Test with valid Basic Authorization header\n const username = \"user\";\n const password = \"pass\";\n const encoded = encodeBasicAuthorizationHeader(username, password);\n expect(decodeBasicAuthorizationHeader(encoded)).toEqual([username, password]);\n\n // Test with password containing colons\n const complexPassword = \"pass:with:colons\";\n const encodedComplex = encodeBasicAuthorizationHeader(username, complexPassword);\n expect(decodeBasicAuthorizationHeader(encodedComplex)).toEqual([username, complexPassword]);\n\n // Test with invalid headers\n expect(decodeBasicAuthorizationHeader(\"NotBasic dXNlcjpwYXNz\")).toBe(null); // Wrong type\n expect(decodeBasicAuthorizationHeader(\"Basic\")).toBe(null); // Missing encoded part\n expect(decodeBasicAuthorizationHeader(\"Basic not-base64\")).toBe(null); // Not base64\n expect(decodeBasicAuthorizationHeader(\"Basic dXNlcjpwYXNz extra\")).toBe(null); // Extra parts\n});\n\nexport function encodeBasicAuthorizationHeader(id: string, password: string): string {\n if (id.includes(':')) throw new Error(\"Basic authorization header id cannot contain ':'\");\n return `Basic ${encodeBase64(new TextEncoder().encode(`${id}:${password}`))}`;\n}\nimport.meta.vitest?.test(\"encodeBasicAuthorizationHeader\", ({ expect }) => {\n // Test with simple username and password\n const encoded = encodeBasicAuthorizationHeader(\"user\", \"pass\");\n expect(encoded).toMatch(/^Basic [A-Za-z0-9+/=]+$/); // Should start with \"Basic \" followed by base64\n\n // Test with empty password\n const encodedEmptyPass = encodeBasicAuthorizationHeader(\"user\", \"\");\n expect(encodedEmptyPass).toMatch(/^Basic [A-Za-z0-9+/=]+$/);\n\n // Test with password containing special characters\n const encodedSpecialChars = encodeBasicAuthorizationHeader(\"user\", \"p@ss!w0rd\");\n expect(encodedSpecialChars).toMatch(/^Basic [A-Za-z0-9+/=]+$/);\n\n // Test with username containing colon should throw\n expect(() => encodeBasicAuthorizationHeader(\"user:name\", \"pass\")).toThrow();\n});\n", "export const standardProviders = [\"google\", \"github\", \"microsoft\", \"spotify\", \"facebook\", \"discord\", \"gitlab\", \"bitbucket\", \"linkedin\", \"apple\", \"x\", \"twitch\"] as const;\n// No more shared providers should be added except for special cases\nexport const sharedProviders = [\"google\", \"github\", \"microsoft\", \"spotify\"] as const;\nexport const allProviders = standardProviders;\nexport const publishableClientKeyNotNecessarySentinel = \"__stack_public_client__\";\n\nexport type ProviderType = typeof allProviders[number];\nexport type StandardProviderType = typeof standardProviders[number];\nexport type SharedProviderType = typeof sharedProviders[number];\n", "import { generateRandomValues } from \"./crypto\";\n\nexport function generateUuid() {\n // crypto.randomUuid is not supported in all browsers, so this is a polyfill\n return \"10000000-1000-4000-8000-100000000000\".replace(/[018]/g, c =>\n (+c ^ generateRandomValues(new Uint8Array(1))[0] & 15 >> +c / 4).toString(16)\n );\n}\nimport.meta.vitest?.test(\"generateUuid\", ({ expect }) => {\n // Test that the function returns a valid UUID\n const uuid = generateUuid();\n expect(uuid).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);\n\n // Test that multiple calls generate different UUIDs\n const uuid2 = generateUuid();\n expect(uuid).not.toBe(uuid2);\n\n // Test that the UUID is version 4 (random)\n expect(uuid.charAt(14)).toBe('4');\n\n // Test that the UUID has the correct variant (8, 9, a, or b in position 19)\n expect('89ab').toContain(uuid.charAt(19));\n});\n\nexport function isUuid(str: string) {\n return /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(str);\n}\nimport.meta.vitest?.test(\"isUuid\", ({ expect }) => {\n // Test with valid UUIDs\n expect(isUuid(\"123e4567-e89b-42d3-a456-426614174000\")).toBe(true);\n expect(isUuid(\"123e4567-e89b-42d3-8456-426614174000\")).toBe(true);\n expect(isUuid(\"123e4567-e89b-42d3-9456-426614174000\")).toBe(true);\n expect(isUuid(\"123e4567-e89b-42d3-a456-426614174000\")).toBe(true);\n expect(isUuid(\"123e4567-e89b-42d3-b456-426614174000\")).toBe(true);\n\n // Test with invalid UUIDs\n expect(isUuid(\"\")).toBe(false);\n expect(isUuid(\"not-a-uuid\")).toBe(false);\n expect(isUuid(\"123e4567-e89b-12d3-a456-426614174000\")).toBe(false); // Wrong version (not 4)\n expect(isUuid(\"123e4567-e89b-42d3-c456-426614174000\")).toBe(false); // Wrong variant (not 8, 9, a, or b)\n expect(isUuid(\"123e4567-e89b-42d3-a456-42661417400\")).toBe(false); // Too short\n expect(isUuid(\"123e4567-e89b-42d3-a456-4266141740000\")).toBe(false); // Too long\n expect(isUuid(\"123e4567-e89b-42d3-a456_426614174000\")).toBe(false); // Wrong format (underscore instead of dash)\n\n // Test with uppercase letters (should fail as UUID should be lowercase)\n expect(isUuid(\"123E4567-E89B-42D3-A456-426614174000\")).toBe(false);\n});\n", "import * as yup from \"yup\";\nimport { KnownErrors } from \"./known-errors\";\nimport { isBase64 } from \"./utils/bytes\";\nimport { SUPPORTED_CURRENCIES, type Currency, type MoneyAmount } from \"./utils/currency-constants\";\nimport type { DayInterval, Interval } from \"./utils/dates\";\nimport { StackAssertionError, throwErr } from \"./utils/errors\";\nimport { decodeBasicAuthorizationHeader } from \"./utils/http\";\nimport { allProviders } from \"./utils/oauth\";\nimport { deepPlainClone, omit, typedFromEntries } from \"./utils/objects\";\nimport { deindent } from \"./utils/strings\";\nimport { isValidHostnameWithWildcards, isValidUrl } from \"./utils/urls\";\nimport { isUuid } from \"./utils/uuids\";\n\nconst MAX_IMAGE_SIZE_BASE64_BYTES = 1_000_000; // 1MB\n\ndeclare module \"yup\" {\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface StringSchema<TType, TContext, TDefault, TFlags> {\n nonEmpty(message?: string): StringSchema<TType, TContext, TDefault, TFlags>,\n empty(): StringSchema<TType, TContext, TDefault, TFlags>,\n }\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface Schema<TType, TContext, TDefault, TFlags> {\n hasNested<K extends keyof NonNullable<TType>>(path: K): boolean,\n getNested<K extends keyof NonNullable<TType>>(path: K): yup.Schema<NonNullable<TType>[K], TContext, TDefault, TFlags>,\n\n // the default types for concat kinda suck, so let's fix that\n concat<U extends yup.AnySchema>(schema: U): yup.Schema<Omit<NonNullable<TType>, keyof yup.InferType<U>> & yup.InferType<U> | (TType & (null | undefined)), TContext, Omit<NonNullable<TDefault>, keyof U['__default']> & U['__default'] | (TDefault & (null | undefined)), TFlags>,\n }\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n export interface CustomSchemaMetadata {\n stackSchemaInfo?:\n | {\n type: \"object\" | \"array\" | \"string\" | \"number\" | \"boolean\" | \"date\" | \"mixed\" | \"never\",\n }\n | {\n type: \"tuple\",\n items: yup.AnySchema[],\n }\n | {\n type: \"union\",\n items: yup.AnySchema[],\n }\n | {\n type: \"record\",\n keySchema: yup.StringSchema<any>,\n valueSchema: yup.AnySchema,\n },\n }\n}\n\n// eslint-disable-next-line no-restricted-syntax\nyup.addMethod(yup.string, \"nonEmpty\", function (message?: string) {\n return this.test(\n \"non-empty\",\n message ?? (({ path }) => `${path} must not be empty`),\n (value) => {\n return value !== \"\";\n }\n );\n});\n\nyup.addMethod(yup.Schema, \"hasNested\", function (path: any) {\n if (!path.match(/^[a-zA-Z0-9_$:-]*$/)) throw new StackAssertionError(`yupSchema.hasNested can currently only be used with alphanumeric keys, underscores, dollar signs, colons, and hyphens. Fix this in the future. Provided key: ${JSON.stringify(path)}`);\n const schemaInfo = this.meta()?.stackSchemaInfo as any;\n if (schemaInfo?.type === \"record\") {\n return schemaInfo.keySchema.isValidSync(path);\n } else if (schemaInfo?.type === \"union\") {\n return schemaInfo.items.some((s: any) => s.hasNested(path));\n } else {\n try {\n yup.reach(this, path);\n return true as any;\n } catch (e) {\n if (e instanceof Error && e.message.includes(\"The schema does not contain the path\")) {\n return false as any;\n }\n throw e;\n }\n }\n});\n\nyup.addMethod(yup.Schema, \"getNested\", function (path: any) {\n if (!path.match(/^[a-zA-Z0-9_$:-]*$/)) throw new StackAssertionError(`yupSchema.getNested can currently only be used with alphanumeric keys, underscores, dollar signs, colons, and hyphens. Fix this in the future. Provided key: ${JSON.stringify(path)}`);\n\n if (!this.hasNested(path as never)) throw new StackAssertionError(`Tried to call yupSchema.getNested, but key is not present in the schema. Provided key: ${path}`, { path, schema: this });\n\n const schemaInfo = this.meta()?.stackSchemaInfo;\n if (schemaInfo?.type === \"record\") {\n return schemaInfo.valueSchema;\n } else if (schemaInfo?.type === \"union\") {\n const schemasWithNested = schemaInfo.items.filter((s: any) => s.hasNested(path));\n return yupUnion(...schemasWithNested.map(s => s.getNested(path)));\n } else {\n return yup.reach(this, path) as any;\n }\n});\n\nimport.meta.vitest?.test(\"hasNested\", ({ expect }) => {\n expect(yupObject({ a: yupString() }).hasNested(\"a\")).toBe(true);\n expect(yupObject({}).hasNested(\"a\" as never)).toBe(false);\n expect(yupRecord(yupString(), yupString()).hasNested(\"a\")).toBe(true);\n expect(yupRecord(yupString().oneOf([\"a\"]), yupString()).hasNested(\"b\")).toBe(false);\n expect(yupUnion(yupString(), yupNumber()).hasNested(\"a\" as any)).toBe(false);\n expect(yupUnion(yupString(), yupObject({ b: yupNumber() })).hasNested(\"a\" as never)).toBe(false);\n expect(yupUnion(yupString(), yupObject({ a: yupNumber() })).hasNested(\"a\" as never)).toBe(true);\n});\nimport.meta.vitest?.test(\"getNested\", ({ expect }) => {\n expect(yupObject({ a: yupNumber() }).getNested(\"a\").describe().type).toEqual(\"number\");\n expect(() => yupObject({}).getNested(\"a\" as never)).toThrow();\n expect(() => yupObject({ a: yupObject({ b: yupString() }) }).getNested(\"a.b\" as never)).toThrow();\n expect(yupRecord(yupString().oneOf([\"a\"]), yupNumber()).getNested(\"a\").describe().type).toEqual(\"number\");\n expect(() => yupRecord(yupString().oneOf([\"a\"]), yupString()).getNested(\"b\" as never)).toThrow();\n expect(yupUnion(yupString(), yupObject({ a: yupNumber() })).getNested(\"a\" as never).describe().type).toEqual(\"mixed\");\n expect(yupUnion(yupObject({ a: yupString() }), yupObject({ a: yupNumber() })).getNested(\"a\").describe().type).toEqual(\"mixed\");\n});\n\nexport async function yupValidate<S extends yup.ISchema<any>>(\n schema: S,\n obj: unknown,\n options?: yup.ValidateOptions & { currentUserId?: string | null }\n): Promise<yup.InferType<S>> {\n try {\n return await schema.validate(obj, {\n ...omit(options ?? {}, ['currentUserId']),\n context: {\n ...options?.context,\n stackAllowUserIdMe: options?.currentUserId !== undefined,\n },\n });\n } catch (error) {\n if (error instanceof ReplaceFieldWithOwnUserId) {\n const currentUserId = options?.currentUserId;\n if (!currentUserId) throw new KnownErrors.CannotGetOwnUserWithoutUser();\n\n // parse yup path\n let pathRemaining = error.path;\n const fieldPath = [];\n while (pathRemaining.length > 0) {\n if (pathRemaining.startsWith(\"[\")) {\n const index = pathRemaining.indexOf(\"]\");\n if (index < 0) throw new StackAssertionError(\"Invalid path\");\n fieldPath.push(JSON.parse(pathRemaining.slice(1, index)));\n pathRemaining = pathRemaining.slice(index + 1);\n } else {\n let dotIndex = pathRemaining.indexOf(\".\");\n if (dotIndex === -1) dotIndex = pathRemaining.length;\n fieldPath.push(pathRemaining.slice(0, dotIndex));\n pathRemaining = pathRemaining.slice(dotIndex + 1);\n }\n }\n\n const newObj = deepPlainClone(obj);\n let it = newObj;\n for (const field of fieldPath.slice(0, -1)) {\n if (!Object.prototype.hasOwnProperty.call(it, field)) {\n throw new StackAssertionError(`Segment ${field} of path ${error.path} not found in object`);\n }\n it = (it as any)[field];\n }\n (it as any)[fieldPath[fieldPath.length - 1]] = currentUserId;\n\n return await yupValidate(schema, newObj, options);\n }\n throw error;\n }\n}\n\nconst _idDescription = (identify: string) => `The unique identifier of the ${identify}`;\nconst _displayNameDescription = (identify: string) => `Human-readable ${identify} display name. This is not a unique identifier.`;\nconst _clientMetaDataDescription = (identify: string) => `Client metadata. Used as a data store, accessible from the client side. Do not store information that should not be exposed to the client.`;\nconst _clientReadOnlyMetaDataDescription = (identify: string) => `Client read-only, server-writable metadata. Used as a data store, accessible from the client side. Do not store information that should not be exposed to the client. The client can read this data, but cannot modify it. This is useful for things like subscription status.`;\nconst _profileImageUrlDescription = (identify: string) => `URL of the profile image for ${identify}. Can be a Base64 encoded image. Must be smaller than 100KB. Please compress and crop to a square before passing in.`;\nconst _serverMetaDataDescription = (identify: string) => `Server metadata. Used as a data store, only accessible from the server side. You can store secret information related to the ${identify} here.`;\nconst _atMillisDescription = (identify: string) => `(the number of milliseconds since epoch, January 1, 1970, UTC)`;\nconst _createdAtMillisDescription = (identify: string) => `The time the ${identify} was created ${_atMillisDescription(identify)}`;\nconst _signedUpAtMillisDescription = `The time the user signed up ${_atMillisDescription}`;\nconst _lastActiveAtMillisDescription = `The time the user was last active ${_atMillisDescription}`;\n\n\ndeclare const StackAdaptSentinel: unique symbol;\nexport type StackAdaptSentinel = typeof StackAdaptSentinel;\n\n// Built-in replacements\nexport function yupString<A extends string, B extends yup.Maybe<yup.AnyObject> = yup.AnyObject>(...args: Parameters<typeof yup.string<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.string(...args).meta({ stackSchemaInfo: { type: \"string\" } });\n}\nexport function yupNumber<A extends number, B extends yup.Maybe<yup.AnyObject> = yup.AnyObject>(...args: Parameters<typeof yup.number<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.number(...args).meta({ stackSchemaInfo: { type: \"number\" } });\n}\nexport function yupBoolean<A extends boolean, B extends yup.Maybe<yup.AnyObject> = yup.AnyObject>(...args: Parameters<typeof yup.boolean<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.boolean(...args).meta({ stackSchemaInfo: { type: \"boolean\" } });\n}\n/**\n * @deprecated, use number of milliseconds since epoch instead\n */\nexport function yupDate<A extends Date, B extends yup.Maybe<yup.AnyObject> = yup.AnyObject>(...args: Parameters<typeof yup.date<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.date(...args).meta({ stackSchemaInfo: { type: \"date\" } });\n}\nfunction _yupMixedInternal<A extends {}>(...args: Parameters<typeof yup.mixed<A>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.mixed(...args);\n}\nexport function yupMixed<A extends {}>(...args: Parameters<typeof yup.mixed<A>>) {\n return _yupMixedInternal(...args).meta({ stackSchemaInfo: { type: \"mixed\" } });\n}\nexport function yupArray<A extends yup.Maybe<yup.AnyObject> = yup.AnyObject, B = any>(...args: Parameters<typeof yup.array<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n return yup.array(...args).meta({ stackSchemaInfo: { type: \"array\" } });\n}\nexport function yupTuple<T extends [unknown, ...unknown[]]>(schemas: { [K in keyof T]: yup.Schema<T[K]> }) {\n if (schemas.length === 0) throw new Error('yupTuple must have at least one schema');\n // eslint-disable-next-line no-restricted-syntax\n return yup.tuple<T>(schemas as any).meta({ stackSchemaInfo: { type: \"tuple\", items: schemas } });\n}\nexport function yupObjectWithAutoDefault<A extends yup.Maybe<yup.AnyObject>, B extends yup.ObjectShape>(...args: Parameters<typeof yup.object<A, B>>) {\n // eslint-disable-next-line no-restricted-syntax\n const object = yup.object(...args).test(\n 'no-unknown-object-properties',\n ({ path }) => `${path} contains unknown properties`,\n (value: any, context) => {\n if (context.options.context?.noUnknownPathPrefixes?.some((prefix: string) => context.path.startsWith(prefix))) {\n if (context.schema.spec.noUnknown !== false) {\n const availableKeys = new Set(Object.keys(context.schema.fields));\n const unknownKeys = Object.keys(value ?? {}).filter(key => !availableKeys.has(key));\n if (unknownKeys.length > 0) {\n // TODO \"did you mean XYZ\"\n return context.createError({\n message: `${context.path || \"Object\"} contains unknown properties: ${unknownKeys.join(', ')}`,\n path: context.path,\n params: { unknownKeys, availableKeys },\n });\n }\n }\n }\n return true;\n },\n ).meta({ stackSchemaInfo: { type: \"object\" } });\n return object;\n}\nexport function yupObject<A extends yup.Maybe<yup.AnyObject>, B extends yup.ObjectShape>(...args: Parameters<typeof yup.object<A, B>>) {\n // we don't want to update the type of `object` to have a default flag\n const object = yupObjectWithAutoDefault(...args);\n return object.default(undefined) as any as typeof object;\n}\n\nexport function yupNever(): yup.MixedSchema<never> {\n return _yupMixedInternal().meta({ stackSchemaInfo: { type: \"never\" } }).test('never', 'This value should never be reached', () => false) as any;\n}\n\nexport function yupUnion<T extends yup.AnySchema[]>(...args: T): yup.MixedSchema<yup.InferType<T[number]>> {\n if (args.length === 0) throw new Error('yupUnion must have at least one schema');\n\n return _yupMixedInternal().meta({ stackSchemaInfo: { type: \"union\", items: args } }).test('is-one-of', 'Invalid value', async (value, context) => {\n if (value == null) return true;\n const errors = [];\n for (const schema of args) {\n try {\n await yupValidate(schema, value, context.options);\n return true;\n } catch (e) {\n errors.push(e);\n }\n }\n return context.createError({\n message: deindent`\n ${context.path} is not matched by any of the provided schemas:\n ${errors.map((e: any, i) => deindent`\n Schema ${i}:\n ${e.errors.join('\\n')}\n `).join('\\n')}`,\n path: context.path,\n });\n });\n}\n\nexport function yupRecord<K extends yup.StringSchema, T extends yup.AnySchema>(\n keySchema: K,\n valueSchema: T,\n): yup.MixedSchema<Record<yup.InferType<K> & string, yup.InferType<T>>> {\n return yupObject().meta({ stackSchemaInfo: { type: \"record\", keySchema, valueSchema } }).unknown(true).test(\n 'record',\n '${path} must be a record of valid values',\n async function (value: unknown, context: yup.TestContext) {\n if (value == null) return true;\n const { path, createError } = this as any;\n if (typeof value !== 'object') {\n return createError({ message: `${path} must be an object` });\n }\n\n // Validate each property using the provided valueSchema\n for (const key of Object.keys(value)) {\n // Validate the key\n await yupValidate(keySchema, key, context.options);\n\n // Validate the value\n try {\n await yupValidate(valueSchema, (value as Record<string, unknown>)[key], {\n ...context.options,\n context: {\n ...context.options.context,\n path: path ? `${path}.${key}` : key,\n },\n });\n } catch (e: any) {\n return createError({\n path: path ? `${path}.${key}` : key,\n message: e.message,\n });\n }\n }\n\n return true;\n },\n ) as any;\n}\n\nexport function ensureObjectSchema<T extends yup.AnyObject>(schema: yup.Schema<T>): yup.ObjectSchema<T> & typeof schema {\n if (!(schema instanceof yup.ObjectSchema)) throw new StackAssertionError(`assertObjectSchema: schema is not an ObjectSchema: ${schema.describe().type}`);\n return schema as any;\n}\n\n// Common\nexport const adaptSchema = yupMixed<StackAdaptSentinel>();\n/**\n * Yup's URL schema does not recognize some URLs (including `http://localhost`) as a valid URL. This schema is a workaround for that.\n */\nexport const urlSchema = yupString().test({\n name: 'no-spaces',\n message: (params) => `${params.path} contains spaces`,\n test: (value) => value == null || !value.includes(' ')\n}).test({\n name: 'url',\n message: (params) => `${params.path} is not a valid URL`,\n test: (value) => value == null || isValidUrl(value)\n});\n/**\n * URL schema that supports wildcard patterns in hostnames (e.g., \"https://*.example.com\", \"http://*:8080\")\n */\nexport const wildcardUrlSchema = yupString().test({\n name: 'no-spaces',\n message: (params) => `${params.path} contains spaces`,\n test: (value) => value == null || !value.includes(' ')\n}).test({\n name: 'wildcard-url',\n message: (params) => `${params.path} is not a valid URL or wildcard URL pattern`,\n test: (value) => {\n if (value == null) return true;\n\n // If it doesn't contain wildcards, use the regular URL validation\n if (!value.includes('*')) {\n return isValidUrl(value);\n }\n\n // For wildcard URLs, validate the structure by replacing wildcards with placeholders\n try {\n const PLACEHOLDER = 'wildcard-placeholder';\n // Replace wildcards with valid placeholders for URL parsing\n const normalizedUrl = value.replace(/\\*/g, PLACEHOLDER);\n const url = new URL(normalizedUrl);\n\n // Only allow wildcards in the hostname; reject anywhere else\n if (\n url.username.includes(PLACEHOLDER) ||\n url.password.includes(PLACEHOLDER) ||\n url.pathname.includes(PLACEHOLDER) ||\n url.search.includes(PLACEHOLDER) ||\n url.hash.includes(PLACEHOLDER)\n ) {\n return false;\n }\n\n // Only http/https are acceptable\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n return false;\n }\n\n // Extract original hostname pattern from the input\n const hostPattern = url.hostname.split(PLACEHOLDER).join('*');\n\n // Validate the wildcard hostname pattern using the existing function\n return isValidHostnameWithWildcards(hostPattern);\n } catch (e) {\n return false;\n }\n }\n});\nexport const wildcardProtocolAndDomainSchema = wildcardUrlSchema.test({\n name: 'is-protocol-and-domain',\n message: (params) => `${params.path} must be a protocol and domain (with optional port) without any path, query parameters, or hash`,\n test: (value) => {\n if (value == null) return true;\n try {\n const PLACEHOLDER = 'wildcard-placeholder';\n // Replace wildcards with valid placeholders for URL parsing\n const normalized = value.replace(/\\*/g, PLACEHOLDER);\n const url = new URL(normalized);\n return url.protocol !== '' && url.hostname !== '' && url.pathname === '/' && url.search === '' && url.hash === '';\n } catch (e) {\n return false;\n }\n }\n});\nexport const jsonSchema = yupMixed().nullable().defined().transform((value) => JSON.parse(JSON.stringify(value)));\nexport const jsonStringSchema = yupString().test(\"json\", (params) => `${params.path} is not valid JSON`, (value) => {\n if (value == null) return true;\n try {\n JSON.parse(value);\n return true;\n } catch (error) {\n return false;\n }\n});\nexport const jsonStringOrEmptySchema = yupString().test(\"json\", (params) => `${params.path} is not valid JSON`, (value) => {\n if (!value) return true;\n try {\n JSON.parse(value);\n return true;\n } catch (error) {\n return false;\n }\n});\nexport const base64Schema = yupString().test(\"is-base64\", (params) => `${params.path} is not valid base64`, (value) => {\n if (value == null) return true;\n return isBase64(value);\n});\nexport const passwordSchema = yupString().max(70);\nexport const intervalSchema = yupTuple<Interval>([yupNumber().min(0).integer().defined(), yupString().oneOf(['millisecond', 'second', 'minute', 'hour', 'day', 'week', 'month', 'year']).defined()]);\nexport const dayIntervalSchema = yupTuple<DayInterval>([yupNumber().min(0).integer().defined(), yupString().oneOf(['day', 'week', 'month', 'year']).defined()]);\nexport const intervalOrNeverSchema = yupUnion(intervalSchema.defined(), yupString().oneOf(['never']).defined());\nexport const dayIntervalOrNeverSchema = yupUnion(dayIntervalSchema.defined(), yupString().oneOf(['never']).defined());\n/**\n * This schema is useful for fields where the user can specify the ID, such as price IDs. It is particularly common\n * for IDs in the config schema.\n *\n * Valid IDs:\n * - Must contain only letters, numbers, underscores, and hyphens\n * - Must not start with a hyphen\n * - Maximum length of 63 characters\n */\nexport const USER_SPECIFIED_ID_PATTERN = /^[a-zA-Z0-9_][a-zA-Z0-9_-]*$/;\nexport const USER_SPECIFIED_ID_MAX_LENGTH = 63;\n\n/**\n * Checks if the given string is a valid user-specified ID.\n */\nexport function isValidUserSpecifiedId(id: string): boolean {\n return id.length > 0 && id.length <= USER_SPECIFIED_ID_MAX_LENGTH && USER_SPECIFIED_ID_PATTERN.test(id);\n}\n\n/**\n * Gets the error message for an invalid user-specified ID.\n */\nexport function getUserSpecifiedIdErrorMessage(idName: `${string}Id`): string {\n return `${idName} must contain only letters, numbers, underscores, and hyphens, and not start with a hyphen`;\n}\n\n/**\n * Sanitizes user input to create a valid user-specified ID.\n * Converts to lowercase and replaces invalid characters with hyphens.\n * Strips leading hyphens.\n */\nexport function sanitizeUserSpecifiedId(input: string): string {\n // Convert to lowercase, replace invalid characters with empty string (or hyphen for spaces)\n const sanitized = input\n .replace(/\\s+/g, '-') // Replace spaces with hyphens\n .replace(/[^a-zA-Z0-9_-]/g, ''); // Remove other invalid characters\n\n // Strip leading hyphens\n return sanitized.replace(/^-+/, '');\n}\n\nexport const userSpecifiedIdSchema = (idName: `${string}Id`) => yupString().max(USER_SPECIFIED_ID_MAX_LENGTH).matches(USER_SPECIFIED_ID_PATTERN, getUserSpecifiedIdErrorMessage(idName));\nexport const moneyAmountSchema = (currency: Currency) => yupString<MoneyAmount>().test('money-amount', 'Invalid money amount', (value, context) => {\n if (value == null) return true;\n const regex = /^([0-9]+)(\\.([0-9]+))?$/;\n const match = value.match(regex);\n if (!match) return context.createError({ message: 'Money amount must be in the format of <number> or <number>.<number>' });\n const whole = match[1];\n const decimals = match[3];\n if (decimals && decimals.length > currency.decimals) return context.createError({ message: `Too many decimals; ${currency.code} only has ${currency.decimals} decimals` });\n if (whole !== '0' && whole.startsWith('0')) return context.createError({ message: 'Money amount must not have leading zeros' });\n return true;\n});\n\n\n/**\n * A stricter email schema that does some additional checks for UX input. (Some emails are allowed by the spec, for\n * example `test@localhost` or `abc@gmail`, but almost certainly a user input error.)\n *\n * Note that some users in the DB have an email that doesn't match this regex, so most of the time you should use\n * `emailSchema` instead until we do the DB migration.\n */\n// eslint-disable-next-line no-restricted-syntax\nexport const strictEmailSchema = (message: string | undefined) => yupString().email(message).max(256).matches(/^[^.]+(\\.[^.]+)*@.*\\.[^.][^.]+$/, message);\n// eslint-disable-next-line no-restricted-syntax\nexport const emailSchema = yupString().email();\n\nimport.meta.vitest?.test('strictEmailSchema', ({ expect }) => {\n const validEmails = [\n \"a@example.com\",\n \"abc@example.com\",\n \"a.b@example.com\",\n \"throwaway.mail+token@example.com\",\n \"email-alt-dash@demo-mail.com\",\n \"test-account@weird-domain.net\",\n \"%!~&+{}=|`#@domain.test\",\n \"admin@a.longtldexample\",\n ];\n for (const email of validEmails) {\n expect(strictEmailSchema(undefined).validateSync(email)).toBe(email);\n }\n const invalidEmails = [\n \"test@localhost\",\n \"test@gmail\",\n \"test@gmail.com.a\",\n \"test@gmail.a\",\n \"test.@example.com\",\n \"test..test@example.com\",\n \".test@example.com\",\n ];\n for (const email of invalidEmails) {\n expect(() => strictEmailSchema(undefined).validateSync(email)).toThrow();\n }\n});\n\n// Request auth\nexport const clientOrHigherAuthTypeSchema = yupString().oneOf(['client', 'server', 'admin']).defined();\nexport const serverOrHigherAuthTypeSchema = yupString().oneOf(['server', 'admin']).defined();\nexport const adminAuthTypeSchema = yupString().oneOf(['admin']).defined();\n\n// Projects\nexport const projectIdSchema = yupString().test((v) => v === undefined || v === \"internal\" || isUuid(v)).meta({ openapiField: { description: _idDescription('project'), exampleValue: 'e0b52f4d-dece-408c-af49-d23061bb0f8d' } });\nexport const projectBranchIdSchema = yupString().nonEmpty().max(255).meta({ openapiField: { description: _idDescription('project branch'), exampleValue: 'main' } });\nexport const projectDisplayNameSchema = yupString().meta({ openapiField: { description: _displayNameDescription('project'), exampleValue: 'MyMusic' } });\nexport const projectLogoUrlSchema = urlSchema.max(MAX_IMAGE_SIZE_BASE64_BYTES).meta({ openapiField: { description: 'URL of the logo for the project. This is usually a close to 1:1 image of the company logo.', exampleValue: 'https://example.com/logo.png' } });\nexport const projectLogoFullUrlSchema = urlSchema.max(MAX_IMAGE_SIZE_BASE64_BYTES).meta({ openapiField: { description: 'URL of the full logo for the project. This is usually a vertical image with the logo and the company name.', exampleValue: 'https://example.com/full-logo.png' } });\nexport const projectLogoDarkModeUrlSchema = urlSchema.max(MAX_IMAGE_SIZE_BASE64_BYTES).meta({ openapiField: { description: 'URL of the dark mode logo for the project. This is usually a close to 1:1 image of the company logo optimized for dark backgrounds.', exampleValue: 'https://example.com/logo-dark.png' } });\nexport const projectLogoFullDarkModeUrlSchema = urlSchema.max(MAX_IMAGE_SIZE_BASE64_BYTES).meta({ openapiField: { description: 'URL of the dark mode full logo for the project. This is usually a vertical image with the logo and the company name optimized for dark backgrounds.', exampleValue: 'https://example.com/full-logo-dark.png' } });\nexport const projectDescriptionSchema = yupString().nullable().meta({ openapiField: { description: 'A human readable description of the project', exampleValue: 'A music streaming service' } });\nexport const projectCreatedAtMillisSchema = yupNumber().meta({ openapiField: { description: _createdAtMillisDescription('project'), exampleValue: 1630000000000 } });\nexport const projectIsProductionModeSchema = yupBoolean().meta({ openapiField: { description: 'Whether the project is in production mode', exampleValue: true } });\nexport const projectOnboardingStatusValues = [\n \"config_choice\",\n \"apps_selection\",\n \"auth_setup\",\n \"domain_setup\",\n \"email_theme_setup\",\n \"payments_setup\",\n \"completed\",\n] as const;\nexport type ProjectOnboardingStatus = typeof projectOnboardingStatusValues[number];\nexport const projectOnboardingStatusSchema = yupString().oneOf(projectOnboardingStatusValues).meta({\n openapiField: {\n description: \"The current dashboard onboarding stage for this project.\",\n exampleValue: \"config_choice\",\n },\n});\n// Project config\nexport const projectConfigIdSchema = yupString().meta({ openapiField: { description: _idDescription('project config'), exampleValue: 'd09201f0-54f5-40bd-89ff-6d1815ddad24' } });\nexport const projectAllowLocalhostSchema = yupBoolean().meta({ openapiField: { description: 'Whether localhost is allowed as a domain for this project. Should only be allowed in development mode', exampleValue: true } });\nexport const projectCreateTeamOnSignUpSchema = yupBoolean().meta({ openapiField: { description: 'Whether a team should be created for each user that signs up', exampleValue: true } });\nexport const projectMagicLinkEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether magic link authentication is enabled for this project', exampleValue: true } });\nexport const projectPasskeyEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether passkey authentication is enabled for this project', exampleValue: true } });\nexport const projectClientTeamCreationEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether client users can create teams', exampleValue: true } });\nexport const projectClientUserDeletionEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether client users can delete their own account from the client', exampleValue: true } });\nexport const projectSignUpEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether users can sign up new accounts, or whether they are only allowed to sign in to existing accounts. Regardless of this option, the server API can always create new users with the `POST /users` endpoint.', exampleValue: true } });\nexport const projectCredentialEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether email password authentication is enabled for this project', exampleValue: true } });\n// Project OAuth config\nexport const oauthIdSchema = yupString().oneOf(allProviders).meta({ openapiField: { description: `OAuth provider ID, one of ${allProviders.map(x => `\\`${x}\\``).join(', ')}`, exampleValue: 'google' } });\nexport const oauthEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether the OAuth provider is enabled. If an provider is first enabled, then disabled, it will be shown in the list but with enabled=false', exampleValue: true } });\nexport const oauthTypeSchema = yupString().oneOf(['shared', 'standard']).meta({ openapiField: { description: 'OAuth provider type, one of shared, standard. \"shared\" uses Stack shared OAuth keys and it is only meant for development. \"standard\" uses your own OAuth keys and will show your logo and company name when signing in with the provider.', exampleValue: 'standard' } });\nexport const oauthClientIdSchema = yupString().meta({ openapiField: { description: 'OAuth client ID. Needs to be specified when using type=\"standard\"', exampleValue: 'google-oauth-client-id' } });\nexport const oauthClientSecretSchema = yupString().meta({ openapiField: { description: 'OAuth client secret. Needs to be specified when using type=\"standard\"', exampleValue: 'google-oauth-client-secret' } });\nexport const oauthFacebookConfigIdSchema = yupString().meta({ openapiField: { description: 'The configuration id for Facebook business login (for things like ads and marketing). This is only required if you are using the standard OAuth with Facebook and you are using Facebook business login.' } });\nexport const oauthMicrosoftTenantIdSchema = yupString().meta({ openapiField: { description: 'The Microsoft tenant id for Microsoft directory. This is only required if you are using the standard OAuth with Microsoft and you have an Azure AD tenant.' } });\nexport const oauthAppleBundleIdsSchema = yupArray(yupString().defined()).meta({ openapiField: { description: 'Apple Bundle IDs for native iOS/macOS apps. Required for native Sign In with Apple (in addition to web Apple OAuth which uses the Client ID/Services ID).', exampleValue: ['com.example.ios', 'com.example.macos'] } });\nexport const oauthAppleBundleIdSchema = yupString().defined().meta({ openapiField: { description: 'Apple Bundle ID for native iOS/macOS apps.', exampleValue: 'com.example.ios' } });\nexport const oauthAccountMergeStrategySchema = yupString().oneOf(['link_method', 'raise_error', 'allow_duplicates']).meta({ openapiField: { description: 'Determines how to handle OAuth logins that match an existing user by email. `link_method` adds the OAuth method to the existing user. `raise_error` rejects the login with an error. `allow_duplicates` creates a new user.', exampleValue: 'link_method' } });\n// Project email config\nexport const emailTypeSchema = yupString().oneOf(['shared', 'standard']).meta({ openapiField: { description: 'Email provider type, one of shared, standard. \"shared\" uses Stack shared email provider and it is only meant for development. \"standard\" uses your own email server and will have your email address as the sender.', exampleValue: 'standard' } });\nexport const emailSenderNameSchema = yupString().meta({ openapiField: { description: 'Email sender name. Needs to be specified when using type=\"standard\"', exampleValue: 'Stack' } });\nexport const emailHostSchema = yupString().meta({ openapiField: { description: 'Email host. Needs to be specified when using type=\"standard\"', exampleValue: 'smtp.your-domain.com' } });\nexport const emailPortSchema = yupNumber().min(0).max(65535).meta({ openapiField: { description: 'Email port. Needs to be specified when using type=\"standard\"', exampleValue: 587 } });\nexport const emailUsernameSchema = yupString().meta({ openapiField: { description: 'Email username. Needs to be specified when using type=\"standard\"', exampleValue: 'smtp-email' } });\nexport const emailSenderEmailSchema = emailSchema.meta({ openapiField: { description: 'Email sender email. Needs to be specified when using type=\"standard\"', exampleValue: 'example@your-domain.com' } });\nexport const emailPasswordSchema = passwordSchema.meta({ openapiField: { description: 'Email password. Needs to be specified when using type=\"standard\"', exampleValue: 'your-email-password' } });\n// Project domain config\nexport const handlerPathSchema = yupString().test('is-handler-path', 'Handler path must start with /', (value) => value?.startsWith('/')).meta({ openapiField: { description: 'Handler path. If you did not setup a custom handler path, it should be \"/handler\" by default. It needs to start with /', exampleValue: '/handler' } });\n// Project email theme config\nexport const emailThemeSchema = yupString().meta({ openapiField: { description: 'Email theme id for the project. Determines the visual style of emails sent by the project.' } });\nexport const emailThemeListSchema = yupRecord(\n yupString().uuid(),\n yupObject({\n displayName: yupString().meta({ openapiField: { description: 'Email theme name', exampleValue: 'Default Light' } }).defined(),\n tsxSource: yupString().meta({ openapiField: { description: 'Email theme source code tsx component' } }).defined(),\n })\n).meta({ openapiField: { description: 'Record of email theme IDs to their display name and source code' } });\nexport const templateThemeIdSchema = yupMixed<string | false>().test((v: any) => v === undefined || v === false || v === null || (typeof v === 'string' && isUuid(v))).meta({ openapiField: { description: 'Email theme id for the template' } }).optional();\nexport const emailTemplateListSchema = yupRecord(\n yupString().uuid(),\n yupObject({\n displayName: yupString().meta({ openapiField: { description: 'Email template name', exampleValue: 'Email Verification' } }).defined(),\n tsxSource: yupString().meta({ openapiField: { description: 'Email template source code tsx component' } }).defined(),\n // themeId can be one of three values:\n // 1. A valid theme id\n // 2. false, which means the template uses no theme\n // 3. undefined/not given, which means the template uses the project's active theme\n themeId: templateThemeIdSchema,\n })\n).meta({ openapiField: { description: 'Record of email template IDs to their display name and source code' } });\n\n// Custom dashboards\nexport const customDashboardsSchema = yupRecord(\n yupString().uuid(),\n yupObject({\n displayName: yupString().meta({ openapiField: { description: 'Custom dashboard name', exampleValue: 'User Growth Dashboard' } }).defined(),\n tsxSource: yupString().meta({ openapiField: { description: 'Custom dashboard source code tsx component' } }).defined(),\n })\n).meta({ openapiField: { description: 'Record of custom dashboard IDs to their display name and source code' } });\n\n// Payments\nexport const customerTypeSchema = yupString().oneOf(['user', 'team', 'custom']);\nconst validateHasAtLeastOneSupportedCurrency = (value: Record<string, unknown> | null, context: any) => {\n if (!value) return true;\n const currencies = Object.keys(value).filter(key => SUPPORTED_CURRENCIES.some(c => c.code === key));\n if (currencies.length === 0) {\n return context.createError({ message: \"At least one currency is required\" });\n }\n return true;\n};\nexport const productPriceSchema = yupObject({\n ...typedFromEntries(SUPPORTED_CURRENCIES.map(currency => [currency.code, moneyAmountSchema(currency).optional()])),\n interval: dayIntervalSchema.optional(),\n serverOnly: yupBoolean(),\n freeTrial: dayIntervalSchema.optional(),\n}).test(\"at-least-one-currency\", (value, context) => validateHasAtLeastOneSupportedCurrency(value, context));\nexport const priceOrIncludeByDefaultSchema = yupUnion(\n yupString().oneOf(['include-by-default']).meta({ openapiField: { description: 'Makes this item free and includes it by default for all customers.', exampleValue: 'include-by-default' } }),\n yupRecord(\n userSpecifiedIdSchema(\"priceId\"),\n productPriceSchema,\n ),\n);\nexport const productSchema = yupObject({\n displayName: yupString(),\n productLineId: userSpecifiedIdSchema(\"productLineId\").optional().meta({ openapiField: { description: 'The ID of the product line this product belongs to. Within a product line, all products are mutually exclusive unless they are an add-on to another product in the product line.', exampleValue: 'product-line-id' } }),\n isAddOnTo: yupUnion(\n yupBoolean().isFalse(),\n yupRecord(\n userSpecifiedIdSchema(\"productId\"),\n yupBoolean().isTrue().defined(),\n ),\n ).optional().meta({ openapiField: { description: 'The products that this product is an add-on to. If this is set, the customer must already have one of the products in the record to be able to purchase this product.', exampleValue: { \"product-id\": true } } }),\n customerType: customerTypeSchema.defined(),\n freeTrial: dayIntervalSchema.optional(),\n serverOnly: yupBoolean(),\n stackable: yupBoolean(),\n prices: priceOrIncludeByDefaultSchema.defined(),\n includedItems: yupRecord(\n userSpecifiedIdSchema(\"itemId\"),\n yupObject({\n quantity: yupNumber().defined(),\n repeat: dayIntervalOrNeverSchema.optional(),\n expires: yupString().oneOf(['never', 'when-purchase-expires', 'when-repeated']).optional(),\n }),\n ),\n});\n\nconst productMetadataExample = { featureFlag: true, source: 'marketing-campaign' } as const;\n\nexport const productClientMetadataSchema = jsonSchema.meta({ openapiField: { description: _clientMetaDataDescription('product'), exampleValue: productMetadataExample } });\nexport const productClientReadOnlyMetadataSchema = jsonSchema.meta({ openapiField: { description: _clientReadOnlyMetaDataDescription('product'), exampleValue: productMetadataExample } });\nexport const productServerMetadataSchema = jsonSchema.meta({ openapiField: { description: _serverMetaDataDescription('product'), exampleValue: productMetadataExample } });\n\nexport const productSchemaWithMetadata = productSchema.concat(yupObject({\n clientMetadata: productClientMetadataSchema.optional(),\n clientReadOnlyMetadata: productClientReadOnlyMetadataSchema.optional(),\n serverMetadata: productServerMetadataSchema.optional(),\n}));\n\nexport const inlineProductSchema = yupObject({\n display_name: yupString().defined(),\n customer_type: customerTypeSchema.defined(),\n free_trial: dayIntervalSchema.optional(),\n server_only: yupBoolean().default(true),\n stackable: yupBoolean().default(false),\n prices: yupRecord(\n userSpecifiedIdSchema(\"priceId\"),\n yupObject({\n ...typedFromEntries(SUPPORTED_CURRENCIES.map(currency => [currency.code, moneyAmountSchema(currency).optional()])),\n interval: dayIntervalSchema.optional(),\n free_trial: dayIntervalSchema.optional(),\n }).test(\"at-least-one-currency\", (value, context) => validateHasAtLeastOneSupportedCurrency(value, context)),\n ),\n included_items: yupRecord(\n userSpecifiedIdSchema(\"itemId\"),\n yupObject({\n quantity: yupNumber(),\n repeat: dayIntervalOrNeverSchema.optional(),\n expires: yupString().oneOf(['never', 'when-purchase-expires', 'when-repeated']).optional(),\n }),\n ),\n client_metadata: productClientMetadataSchema.optional(),\n client_read_only_metadata: productClientReadOnlyMetadataSchema.optional(),\n server_metadata: productServerMetadataSchema.optional(),\n});\n\n// Users\nexport class ReplaceFieldWithOwnUserId extends Error {\n constructor(public readonly path: string) {\n super(`This error should be caught by whoever validated the schema, and the field in the path '${path}' should be replaced with the current user's id. This is a workaround to yup not providing access to the context inside the transform function.`);\n }\n}\nconst userIdMeSentinelUuid = \"cad564fd-f81b-43f4-b390-98abf3fcc17e\";\nexport const userIdOrMeSchema = yupString().uuid().transform(v => {\n if (v === \"me\") return userIdMeSentinelUuid;\n else return v;\n}).test((v, context) => {\n if (!(\"stackAllowUserIdMe\" in (context.options.context ?? {}))) throw new StackAssertionError('userIdOrMeSchema is not allowed in this context. Make sure you\\'re using yupValidate from schema-fields.ts to validate, instead of schema.validate(...).');\n if (!context.options.context?.stackAllowUserIdMe) throw new StackAssertionError('userIdOrMeSchema is not allowed in this context. Make sure you\\'re passing in the currentUserId option in yupValidate.');\n if (v === userIdMeSentinelUuid) throw new ReplaceFieldWithOwnUserId(context.path);\n return true;\n}).meta({ openapiField: { description: 'The ID of the user, or the special value `me` for the currently authenticated user', exampleValue: '3241a285-8329-4d69-8f3d-316e08cf140c' } });\nexport const userIdSchema = yupString().uuid().meta({ openapiField: { description: _idDescription('user'), exampleValue: '3241a285-8329-4d69-8f3d-316e08cf140c' } });\nexport const primaryEmailSchema = emailSchema.meta({ openapiField: { description: 'Primary email', exampleValue: 'johndoe@example.com' } });\nexport const primaryEmailAuthEnabledSchema = yupBoolean().meta({ openapiField: { description: 'Whether the primary email is used for authentication. If this is set to `false`, the user will not be able to sign in with the primary email with password or OTP', exampleValue: true } });\nexport const primaryEmailVerifiedSchema = yupBoolean().meta({ openapiField: { description: 'Whether the primary email has been verified to belong to this user', exampleValue: true } });\nexport const userDisplayNameSchema = yupString().nullable().max(256).meta({ openapiField: { description: _displayNameDescription('user'), exampleValue: 'John Doe' } });\nexport const selectedTeamIdSchema = yupString().uuid().meta({ openapiField: { description: 'ID of the team currently selected by the user', exampleValue: 'team-id' } });\nexport const profileImageUrlSchema = urlSchema.max(MAX_IMAGE_SIZE_BASE64_BYTES).meta({ openapiField: { description: _profileImageUrlDescription('user'), exampleValue: 'https://example.com/image.jpg' } });\nexport const signedUpAtMillisSchema = yupNumber().meta({ openapiField: { description: _signedUpAtMillisDescription, exampleValue: 1630000000000 } });\nexport const userClientMetadataSchema = jsonSchema.meta({ openapiField: { description: _clientMetaDataDescription('user'), exampleValue: { key: 'value' } } });\nexport const userClientReadOnlyMetadataSchema = jsonSchema.meta({ openapiField: { description: _clientReadOnlyMetaDataDescription('user'), exampleValue: { key: 'value' } } });\nexport const userServerMetadataSchema = jsonSchema.meta({ openapiField: { description: _serverMetaDataDescription('user'), exampleValue: { key: 'value' } } });\nexport const userOAuthProviderSchema = yupObject({\n id: yupString().defined(),\n type: yupString().oneOf(allProviders).defined(),\n provider_user_id: yupString().defined(),\n});\nexport const userLastActiveAtMillisSchema = yupNumber().nullable().meta({ openapiField: { description: _lastActiveAtMillisDescription, exampleValue: 1630000000000 } });\nexport const userPasskeyAuthEnabledSchema = yupBoolean().meta({ openapiField: { hidden: true, description: 'Whether the user has passkeys enabled', exampleValue: false } });\nexport const userOtpAuthEnabledSchema = yupBoolean().meta({ openapiField: { hidden: true, description: 'Whether the user has OTP/magic link enabled. ', exampleValue: true } });\nexport const userOtpAuthEnabledMutationSchema = yupBoolean().meta({ openapiField: { hidden: true, description: 'Whether the user has OTP/magic link enabled. Note that only accounts with verified emails can sign-in with OTP.', exampleValue: true } });\nexport const userHasPasswordSchema = yupBoolean().meta({ openapiField: { hidden: true, description: 'Whether the user has a password set. If the user does not have a password set, they will not be able to sign in with email/password.', exampleValue: true } });\nexport const userPasswordMutationSchema = passwordSchema.nullable().meta({ openapiField: { description: 'Sets the user\\'s password. Doing so revokes all current sessions.', exampleValue: 'my-new-password' } }).max(70);\nexport const userPasswordHashMutationSchema = yupString()\n .nonEmpty()\n .meta({ openapiField: { description: 'If `password` is not given, sets the user\\'s password hash to the given string in Modular Crypt Format (ex.: `$2a$10$VIhIOofSMqGdGlL4wzE//e.77dAQGqNtF/1dT7bqCrVtQuInWy2qi`). Doing so revokes all current sessions.' } }); // we don't set an exampleValue here because it's exclusive with the password field and having both would break the generated example\nexport const userTotpSecretMutationSchema = base64Schema.nullable().meta({ openapiField: { description: 'Enables 2FA and sets a TOTP secret for the user. Set to null to disable 2FA.', exampleValue: 'dG90cC1zZWNyZXQ=' } });\n\n// Auth\nexport const restrictedReasonTypes = [\"anonymous\", \"email_not_verified\", \"restricted_by_administrator\"] as const;\nexport type RestrictedReasonType = typeof restrictedReasonTypes[number];\nexport const restrictedReasonSchema = yupObject({\n type: yupString().oneOf(restrictedReasonTypes).defined(),\n});\nexport type RestrictedReason = yup.InferType<typeof restrictedReasonSchema>;\n\nexport const accessTokenPayloadSchema = yupObject({\n sub: yupString().defined(),\n exp: yupNumber().optional(),\n iat: yupNumber().defined(),\n iss: yupString().defined(),\n aud: yupString().defined(),\n project_id: yupString().defined(),\n branch_id: yupString().defined(),\n refresh_token_id: yupString().defined(),\n role: yupString().oneOf([\"authenticated\"]).defined(),\n name: yupString().defined().nullable(),\n email: yupString().defined().nullable(),\n email_verified: yupBoolean().defined(),\n selected_team_id: yupString().defined().nullable(),\n is_anonymous: yupBoolean().defined(),\n is_restricted: yupBoolean().defined(),\n restricted_reason: restrictedReasonSchema.defined().nullable(),\n requires_totp_mfa: yupBoolean().defined(),\n});\nexport const signInEmailSchema = strictEmailSchema(undefined).meta({ openapiField: { description: 'The email to sign in with.', exampleValue: 'johndoe@example.com' } });\nexport const emailOtpSignInCallbackUrlSchema = urlSchema.meta({ openapiField: { description: 'The base callback URL to construct the magic link from. A query parameter `code` with the verification code will be appended to it. The page should then make a request to the `/auth/otp/sign-in` endpoint.', exampleValue: 'https://example.com/handler/magic-link-callback' } });\nexport const emailVerificationCallbackUrlSchema = urlSchema.meta({ openapiField: { description: 'The base callback URL to construct a verification link for the verification e-mail. A query parameter `code` with the verification code will be appended to it. The page should then make a request to the `/contact-channels/verify` endpoint.', exampleValue: 'https://example.com/handler/email-verification' } });\nexport const accessTokenResponseSchema = yupString().meta({ openapiField: { description: 'Short-lived access token that can be used to authenticate the user', exampleValue: 'eyJhmMiJB2TO...diI4QT' } });\nexport const refreshTokenResponseSchema = yupString().meta({ openapiField: { description: 'Long-lived refresh token that can be used to obtain a new access token', exampleValue: 'i8ns3aq2...14y' } });\nexport const signInResponseSchema = yupObject({\n refresh_token: refreshTokenResponseSchema.defined(),\n access_token: accessTokenResponseSchema.defined(),\n is_new_user: yupBoolean().meta({ openapiField: { description: 'Whether the user is a new user', exampleValue: true } }).defined(),\n user_id: userIdSchema.defined(),\n});\n\n// Permissions\nexport const teamSystemPermissions = [\n '$update_team',\n '$delete_team',\n '$read_members',\n '$remove_members',\n '$invite_members',\n '$manage_api_keys',\n] as const;\nexport const permissionDefinitionIdSchema = yupString()\n .matches(/^\\$?[a-z0-9_:]+$/, 'Only lowercase letters, numbers, \":\", \"_\" and optional \"$\" at the beginning are allowed')\n .test('is-system-permission', 'System permissions must start with a dollar sign', (value, ctx) => {\n if (!value) return true;\n if (value.startsWith('$') && !teamSystemPermissions.includes(value as any)) {\n return ctx.createError({ message: 'Invalid system permission' });\n }\n return true;\n })\n .meta({ openapiField: { description: `The permission ID used to uniquely identify a permission. Can either be a custom permission with lowercase letters, numbers, \\`:\\`, and \\`_\\` characters, or one of the system permissions: ${teamSystemPermissions.map(x => `\\`${x}\\``).join(', ')}`, exampleValue: 'read_secret_info' } });\nexport const customPermissionDefinitionIdSchema = yupString()\n .matches(/^[a-z0-9_:]+$/, 'Only lowercase letters, numbers, \":\", \"_\" are allowed')\n .meta({ openapiField: { description: 'The permission ID used to uniquely identify a permission. Can only contain lowercase letters, numbers, \":\", and \"_\" characters', exampleValue: 'read_secret_info' } });\nexport const teamPermissionDescriptionSchema = yupString().meta({ openapiField: { description: 'A human-readable description of the permission', exampleValue: 'Read secret information' } });\nexport const containedPermissionIdsSchema = yupArray(permissionDefinitionIdSchema.defined()).meta({ openapiField: { description: 'The IDs of the permissions that are contained in this permission', exampleValue: ['read_public_info'] } });\n\n// Teams\nexport const teamIdSchema = yupString().uuid().meta({ openapiField: { description: _idDescription('team'), exampleValue: 'ad962777-8244-496a-b6a2-e0c6a449c79e' } });\nexport const teamDisplayNameSchema = yupString().meta({ openapiField: { description: _displayNameDescription('team'), exampleValue: 'My Team' } });\nexport const teamProfileImageUrlSchema = urlSchema.max(1000000).meta({ openapiField: { description: _profileImageUrlDescription('team'), exampleValue: 'https://example.com/image.jpg' } });\nexport const teamClientMetadataSchema = jsonSchema.meta({ openapiField: { description: _clientMetaDataDescription('team'), exampleValue: { key: 'value' } } });\nexport const teamClientReadOnlyMetadataSchema = jsonSchema.meta({ openapiField: { description: _clientReadOnlyMetaDataDescription('team'), exampleValue: { key: 'value' } } });\nexport const teamServerMetadataSchema = jsonSchema.meta({ openapiField: { description: _serverMetaDataDescription('team'), exampleValue: { key: 'value' } } });\nexport const teamCreatedAtMillisSchema = yupNumber().meta({ openapiField: { description: _createdAtMillisDescription('team'), exampleValue: 1630000000000 } });\nexport const teamInvitationEmailSchema = emailSchema.meta({ openapiField: { description: 'The email of the user to invite.', exampleValue: 'johndoe@example.com' } });\nexport const teamInvitationCallbackUrlSchema = urlSchema.meta({ openapiField: { description: 'The base callback URL to construct an invite link with. A query parameter `code` with the verification code will be appended to it. The page should then make a request to the `/team-invitations/accept` endpoint.', exampleValue: 'https://example.com/handler/team-invitation' } });\nexport const teamCreatorUserIdSchema = userIdOrMeSchema.meta({ openapiField: { description: 'The ID of the creator of the team. If not specified, the user will not be added to the team. Can be either \"me\" or the ID of the user. Only used on the client side.', exampleValue: 'me' } });\n\n// Team member profiles\nexport const teamMemberDisplayNameSchema = yupString().meta({ openapiField: { description: _displayNameDescription('team member') + ' Note that this is separate from the display_name of the user.', exampleValue: 'John Doe' } });\nexport const teamMemberProfileImageUrlSchema = urlSchema.max(1000000).meta({ openapiField: { description: _profileImageUrlDescription('team member'), exampleValue: 'https://example.com/image.jpg' } });\n\n// Contact channels\nexport const contactChannelIdSchema = yupString().uuid().meta({ openapiField: { description: _idDescription('contact channel'), exampleValue: 'b3d396b8-c574-4c80-97b3-50031675ceb2' } });\nexport const contactChannelTypeSchema = yupString().oneOf(['email']).meta({ openapiField: { description: `The type of the contact channel. Currently only \"email\" is supported.`, exampleValue: 'email' } });\nexport const contactChannelValueSchema = yupString().when('type', {\n is: 'email',\n then: (schema) => schema.email(),\n}).meta({ openapiField: { description: 'The value of the contact channel. For email, this should be a valid email address.', exampleValue: 'johndoe@example.com' } });\nexport const contactChannelUsedForAuthSchema = yupBoolean().meta({ openapiField: { description: 'Whether the contact channel is used for authentication. If this is set to `true`, the user will be able to sign in with the contact channel with password or OTP.', exampleValue: true } });\nexport const contactChannelIsVerifiedSchema = yupBoolean().meta({ openapiField: { description: 'Whether the contact channel has been verified. If this is set to `true`, the contact channel has been verified to belong to the user.', exampleValue: true } });\nexport const contactChannelIsPrimarySchema = yupBoolean().meta({ openapiField: { description: 'Whether the contact channel is the primary contact channel. If this is set to `true`, it will be used for authentication and notifications by default.', exampleValue: true } });\n\n// OAuth providers\nexport const oauthProviderIdSchema = yupString().uuid().meta({ openapiField: { description: _idDescription('OAuth provider'), exampleValue: 'b3d396b8-c574-4c80-97b3-50031675ceb2' } });\nexport const oauthProviderEmailSchema = emailSchema.meta({ openapiField: { description: 'Email of the OAuth provider. This is used to display and identify the OAuth provider in the UI.', exampleValue: 'test@gmail.com' } });\nexport const oauthProviderTypeSchema = yupString().oneOf(allProviders).meta({ openapiField: { description: `OAuth provider type, one of ${allProviders.map(x => `\\`${x}\\``).join(', ')}`, exampleValue: 'google' } });\nexport const oauthProviderAllowSignInSchema = yupBoolean().meta({ openapiField: { description: 'Whether the user can use this OAuth provider to sign in. Only one OAuth provider per type can have this set to `true`.', exampleValue: true } });\nexport const oauthProviderAllowConnectedAccountsSchema = yupBoolean().meta({ openapiField: { description: 'Whether the user can use this OAuth provider as connected account. Multiple OAuth providers per type can have this set to `true`.', exampleValue: true } });\nexport const oauthProviderAccountIdSchema = yupString().meta({ openapiField: { description: 'Account ID of the OAuth provider. This uniquely identifies the account on the provider side.', exampleValue: 'google-account-id-12345' } });\nexport const oauthProviderProviderConfigIdSchema = yupString().meta({ openapiField: { description: 'Provider config ID of the OAuth provider. This uniquely identifies the provider config on config.json file', exampleValue: 'google' } });\n\n// Headers\nexport const basicAuthorizationHeaderSchema = yupString().test('is-basic-authorization-header', 'Authorization header must be in the format \"Basic <base64>\"', (value) => {\n if (!value) return true;\n return decodeBasicAuthorizationHeader(value) !== null;\n});\n\n// Neon integration\nexport const neonAuthorizationHeaderSchema = basicAuthorizationHeaderSchema.test('is-authorization-header', 'Invalid client_id:client_secret values; did you use the correct values for the integration?', (value) => {\n if (!value) return true;\n const [clientId, clientSecret] = decodeBasicAuthorizationHeader(value) ?? throwErr(`Authz header invalid? This should've been validated by basicAuthorizationHeaderSchema: ${value}`);\n for (const neonClientConfig of JSON.parse(process.env.STACK_INTEGRATION_CLIENTS_CONFIG || '[]')) {\n if (clientId === neonClientConfig.client_id && clientSecret === neonClientConfig.client_secret) return true;\n }\n return false;\n});\n\n// Utils\nexport function yupDefinedWhen<S extends yup.AnyObject>(\n schema: S,\n triggers: Record<string, any>,\n): S {\n const entries = Object.entries(triggers);\n return schema.when(entries.map(([key]) => key), {\n is: (...values: any[]) => entries.every(([key, value], index) => value === values[index]),\n then: (schema: S) => schema.defined(),\n otherwise: (schema: S) => schema.optional()\n });\n}\n\nexport function yupDefinedAndNonEmptyWhen<S extends yup.StringSchema>(\n schema: S,\n triggers: Record<string, any>,\n): S {\n const entries = Object.entries(triggers);\n return schema.when(entries.map(([key]) => key), {\n is: (...values: any[]) => entries.every(([key, value], index) => value === values[index]),\n then: (schema: S) => schema.defined().nonEmpty(),\n otherwise: (schema: S) => schema.optional()\n });\n}\n\nexport const branchConfigSourceSchema = yupUnion(\n yupObject({\n type: yupString().oneOf([\"pushed-from-github\"]).defined(),\n owner: yupString().defined(),\n repo: yupString().defined(),\n branch: yupString().defined(),\n commit_hash: yupString().defined(),\n config_file_path: yupString().defined(),\n }),\n yupObject({\n type: yupString().oneOf([\"pushed-from-unknown\"]).defined(),\n }),\n yupObject({\n type: yupString().oneOf([\"unlinked\"]).defined(),\n }),\n);\n", "const E_TIMEOUT = new Error('timeout while waiting for mutex to become available');\nconst E_ALREADY_LOCKED = new Error('mutex already locked');\nconst E_CANCELED = new Error('request for lock canceled');\n\nvar __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nclass Semaphore {\n constructor(_value, _cancelError = E_CANCELED) {\n this._value = _value;\n this._cancelError = _cancelError;\n this._queue = [];\n this._weightedWaiters = [];\n }\n acquire(weight = 1, priority = 0) {\n if (weight <= 0)\n throw new Error(`invalid weight ${weight}: must be positive`);\n return new Promise((resolve, reject) => {\n const task = { resolve, reject, weight, priority };\n const i = findIndexFromEnd(this._queue, (other) => priority <= other.priority);\n if (i === -1 && weight <= this._value) {\n // Needs immediate dispatch, skip the queue\n this._dispatchItem(task);\n }\n else {\n this._queue.splice(i + 1, 0, task);\n }\n });\n }\n runExclusive(callback_1) {\n return __awaiter$2(this, arguments, void 0, function* (callback, weight = 1, priority = 0) {\n const [value, release] = yield this.acquire(weight, priority);\n try {\n return yield callback(value);\n }\n finally {\n release();\n }\n });\n }\n waitForUnlock(weight = 1, priority = 0) {\n if (weight <= 0)\n throw new Error(`invalid weight ${weight}: must be positive`);\n if (this._couldLockImmediately(weight, priority)) {\n return Promise.resolve();\n }\n else {\n return new Promise((resolve) => {\n if (!this._weightedWaiters[weight - 1])\n this._weightedWaiters[weight - 1] = [];\n insertSorted(this._weightedWaiters[weight - 1], { resolve, priority });\n });\n }\n }\n isLocked() {\n return this._value <= 0;\n }\n getValue() {\n return this._value;\n }\n setValue(value) {\n this._value = value;\n this._dispatchQueue();\n }\n release(weight = 1) {\n if (weight <= 0)\n throw new Error(`invalid weight ${weight}: must be positive`);\n this._value += weight;\n this._dispatchQueue();\n }\n cancel() {\n this._queue.forEach((entry) => entry.reject(this._cancelError));\n this._queue = [];\n }\n _dispatchQueue() {\n this._drainUnlockWaiters();\n while (this._queue.length > 0 && this._queue[0].weight <= this._value) {\n this._dispatchItem(this._queue.shift());\n this._drainUnlockWaiters();\n }\n }\n _dispatchItem(item) {\n const previousValue = this._value;\n this._value -= item.weight;\n item.resolve([previousValue, this._newReleaser(item.weight)]);\n }\n _newReleaser(weight) {\n let called = false;\n return () => {\n if (called)\n return;\n called = true;\n this.release(weight);\n };\n }\n _drainUnlockWaiters() {\n if (this._queue.length === 0) {\n for (let weight = this._value; weight > 0; weight--) {\n const waiters = this._weightedWaiters[weight - 1];\n if (!waiters)\n continue;\n waiters.forEach((waiter) => waiter.resolve());\n this._weightedWaiters[weight - 1] = [];\n }\n }\n else {\n const queuedPriority = this._queue[0].priority;\n for (let weight = this._value; weight > 0; weight--) {\n const waiters = this._weightedWaiters[weight - 1];\n if (!waiters)\n continue;\n const i = waiters.findIndex((waiter) => waiter.priority <= queuedPriority);\n (i === -1 ? waiters : waiters.splice(0, i))\n .forEach((waiter => waiter.resolve()));\n }\n }\n }\n _couldLockImmediately(weight, priority) {\n return (this._queue.length === 0 || this._queue[0].priority < priority) &&\n weight <= this._value;\n }\n}\nfunction insertSorted(a, v) {\n const i = findIndexFromEnd(a, (other) => v.priority <= other.priority);\n a.splice(i + 1, 0, v);\n}\nfunction findIndexFromEnd(a, predicate) {\n for (let i = a.length - 1; i >= 0; i--) {\n if (predicate(a[i])) {\n return i;\n }\n }\n return -1;\n}\n\nvar __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nclass Mutex {\n constructor(cancelError) {\n this._semaphore = new Semaphore(1, cancelError);\n }\n acquire() {\n return __awaiter$1(this, arguments, void 0, function* (priority = 0) {\n const [, releaser] = yield this._semaphore.acquire(1, priority);\n return releaser;\n });\n }\n runExclusive(callback, priority = 0) {\n return this._semaphore.runExclusive(() => callback(), 1, priority);\n }\n isLocked() {\n return this._semaphore.isLocked();\n }\n waitForUnlock(priority = 0) {\n return this._semaphore.waitForUnlock(1, priority);\n }\n release() {\n if (this._semaphore.isLocked())\n this._semaphore.release();\n }\n cancel() {\n return this._semaphore.cancel();\n }\n}\n\nvar __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nfunction withTimeout(sync, timeout, timeoutError = E_TIMEOUT) {\n return {\n acquire: (weightOrPriority, priority) => {\n let weight;\n if (isSemaphore(sync)) {\n weight = weightOrPriority;\n }\n else {\n weight = undefined;\n priority = weightOrPriority;\n }\n if (weight !== undefined && weight <= 0) {\n throw new Error(`invalid weight ${weight}: must be positive`);\n }\n return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {\n let isTimeout = false;\n const handle = setTimeout(() => {\n isTimeout = true;\n reject(timeoutError);\n }, timeout);\n try {\n const ticket = yield (isSemaphore(sync)\n ? sync.acquire(weight, priority)\n : sync.acquire(priority));\n if (isTimeout) {\n const release = Array.isArray(ticket) ? ticket[1] : ticket;\n release();\n }\n else {\n clearTimeout(handle);\n resolve(ticket);\n }\n }\n catch (e) {\n if (!isTimeout) {\n clearTimeout(handle);\n reject(e);\n }\n }\n }));\n },\n runExclusive(callback, weight, priority) {\n return __awaiter(this, void 0, void 0, function* () {\n let release = () => undefined;\n try {\n const ticket = yield this.acquire(weight, priority);\n if (Array.isArray(ticket)) {\n release = ticket[1];\n return yield callback(ticket[0]);\n }\n else {\n release = ticket;\n return yield callback();\n }\n }\n finally {\n release();\n }\n });\n },\n release(weight) {\n sync.release(weight);\n },\n cancel() {\n return sync.cancel();\n },\n waitForUnlock: (weightOrPriority, priority) => {\n let weight;\n if (isSemaphore(sync)) {\n weight = weightOrPriority;\n }\n else {\n weight = undefined;\n priority = weightOrPriority;\n }\n if (weight !== undefined && weight <= 0) {\n throw new Error(`invalid weight ${weight}: must be positive`);\n }\n return new Promise((resolve, reject) => {\n const handle = setTimeout(() => reject(timeoutError), timeout);\n (isSemaphore(sync)\n ? sync.waitForUnlock(weight, priority)\n : sync.waitForUnlock(priority)).then(() => {\n clearTimeout(handle);\n resolve();\n });\n });\n },\n isLocked: () => sync.isLocked(),\n getValue: () => sync.getValue(),\n setValue: (value) => sync.setValue(value),\n };\n}\nfunction isSemaphore(sync) {\n return sync.getValue !== undefined;\n}\n\n// eslint-disable-next-lisne @typescript-eslint/explicit-module-boundary-types\nfunction tryAcquire(sync, alreadyAcquiredError = E_ALREADY_LOCKED) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return withTimeout(sync, 0, alreadyAcquiredError);\n}\n\nexport { E_ALREADY_LOCKED, E_CANCELED, E_TIMEOUT, Mutex, Semaphore, tryAcquire, withTimeout };\n", "import { Semaphore } from 'async-mutex';\n\ntype LockCallback<T> = () => Promise<T>;\n\nexport class ReadWriteLock {\n private semaphore: Semaphore;\n private readers: number;\n private readersMutex: Semaphore;\n\n constructor() {\n this.semaphore = new Semaphore(1); // Semaphore with 1 permit\n this.readers = 0; // Track the number of readers\n this.readersMutex = new Semaphore(1); // Protect access to `readers` count\n }\n\n async withReadLock<T>(callback: LockCallback<T>): Promise<T> {\n await this._acquireReadLock();\n try {\n return await callback();\n } finally {\n await this._releaseReadLock();\n }\n }\n\n async withWriteLock<T>(callback: LockCallback<T>): Promise<T> {\n await this._acquireWriteLock();\n try {\n return await callback();\n } finally {\n await this._releaseWriteLock();\n }\n }\n\n private async _acquireReadLock(): Promise<void> {\n // Increment the readers count\n await this.readersMutex.acquire();\n try {\n this.readers += 1;\n // If this is the first reader, block writers\n if (this.readers === 1) {\n await this.semaphore.acquire();\n }\n } finally {\n this.readersMutex.release();\n }\n }\n\n private async _releaseReadLock(): Promise<void> {\n // Decrement the readers count\n await this.readersMutex.acquire();\n try {\n this.readers -= 1;\n // If this was the last reader, release the writer block\n if (this.readers === 0) {\n this.semaphore.release();\n }\n } finally {\n this.readersMutex.release();\n }\n }\n\n private async _acquireWriteLock(): Promise<void> {\n // Writers acquire the main semaphore exclusively\n await this.semaphore.acquire();\n }\n\n private async _releaseWriteLock(): Promise<void> {\n // Writers release the main semaphore\n this.semaphore.release();\n }\n}\n", "import { ReadWriteLock } from \"./locks\";\nimport { ReactPromise, pending, rejected, resolved } from \"./promises\";\nimport { AsyncResult, Result } from \"./results\";\nimport { generateUuid } from \"./uuids\";\n\nexport type ReadonlyStore<T> = {\n get(): T,\n onChange(callback: (value: T, oldValue: T | undefined) => void): { unsubscribe: () => void },\n onceChange(callback: (value: T, oldValue: T | undefined) => void): { unsubscribe: () => void },\n};\n\nexport type AsyncStoreStateChangeCallback<T> = (args: { state: AsyncResult<T>, oldState: AsyncResult<T>, lastOkValue: T | undefined }) => void;\n\nexport type ReadonlyAsyncStore<T> = {\n isAvailable(): boolean,\n get(): AsyncResult<T, unknown, void>,\n getOrWait(): ReactPromise<T>,\n onChange(callback: (value: T, oldValue: T | undefined) => void): { unsubscribe: () => void },\n onceChange(callback: (value: T, oldValue: T | undefined) => void): { unsubscribe: () => void },\n onStateChange(callback: AsyncStoreStateChangeCallback<T>): { unsubscribe: () => void },\n onceStateChange(callback: AsyncStoreStateChangeCallback<T>): { unsubscribe: () => void },\n};\n\nexport class Store<T> implements ReadonlyStore<T> {\n private readonly _callbacks: Map<string, ((value: T, oldValue: T | undefined) => void)> = new Map();\n\n constructor(\n private _value: T\n ) {}\n\n get(): T {\n return this._value;\n }\n\n set(value: T): void {\n const oldValue = this._value;\n this._value = value;\n this._callbacks.forEach((callback) => callback(value, oldValue));\n }\n\n update(updater: (value: T) => T): T {\n const value = updater(this._value);\n this.set(value);\n return value;\n }\n\n onChange(callback: (value: T, oldValue: T | undefined) => void): { unsubscribe: () => void } {\n const uuid = generateUuid();\n this._callbacks.set(uuid, callback);\n return {\n unsubscribe: () => {\n this._callbacks.delete(uuid);\n },\n };\n }\n\n onceChange(callback: (value: T, oldValue: T | undefined) => void): { unsubscribe: () => void } {\n const { unsubscribe } = this.onChange((...args) => {\n unsubscribe();\n callback(...args);\n });\n return { unsubscribe };\n }\n}\n\nexport const storeLock = new ReadWriteLock();\n\n\nexport class AsyncStore<T> implements ReadonlyAsyncStore<T> {\n private _isAvailable: boolean;\n private _mostRecentOkValue: T | undefined = undefined;\n\n private _isRejected = false;\n private _rejectionError: unknown;\n private readonly _waitingRejectFunctions = new Map<string, ((error: unknown) => void)>();\n\n private readonly _callbacks: Map<string, AsyncStoreStateChangeCallback<T>> = new Map();\n\n private _updateCounter = 0;\n private _lastSuccessfulUpdate = -1;\n\n constructor(...args: [] | [T]) {\n if (args.length === 0) {\n this._isAvailable = false;\n } else {\n this._isAvailable = true;\n this._mostRecentOkValue = args[0];\n }\n }\n\n isAvailable(): boolean {\n return this._isAvailable;\n }\n\n isRejected(): boolean {\n return this._isRejected;\n }\n\n get() {\n if (this.isRejected()) {\n return AsyncResult.error(this._rejectionError);\n } else if (this.isAvailable()) {\n return AsyncResult.ok(this._mostRecentOkValue as T);\n } else {\n return AsyncResult.pending();\n }\n }\n\n getOrWait(): ReactPromise<T> {\n const uuid = generateUuid();\n if (this.isRejected()) {\n return rejected(this._rejectionError);\n } else if (this.isAvailable()) {\n return resolved(this._mostRecentOkValue as T);\n }\n const promise = new Promise<T>((resolve, reject) => {\n this.onceChange((value) => {\n resolve(value);\n });\n this._waitingRejectFunctions.set(uuid, reject);\n });\n const withFinally = promise.finally(() => {\n this._waitingRejectFunctions.delete(uuid);\n });\n return pending(withFinally);\n }\n\n _setIfLatest(result: Result<T>, curCounter: number) {\n const oldState = this.get();\n const oldValue = this._mostRecentOkValue;\n if (curCounter > this._lastSuccessfulUpdate) {\n switch (result.status) {\n case \"ok\": {\n if (!this._isAvailable || this._isRejected || this._mostRecentOkValue !== result.data) {\n this._lastSuccessfulUpdate = curCounter;\n this._isAvailable = true;\n this._isRejected = false;\n this._mostRecentOkValue = result.data;\n this._rejectionError = undefined;\n this._callbacks.forEach((callback) => callback({\n state: this.get(),\n oldState,\n lastOkValue: oldValue,\n }));\n return true;\n }\n return false;\n }\n case \"error\": {\n this._lastSuccessfulUpdate = curCounter;\n this._isAvailable = false;\n this._isRejected = true;\n this._rejectionError = result.error;\n this._waitingRejectFunctions.forEach((reject) => reject(result.error));\n this._callbacks.forEach((callback) => callback({\n state: this.get(),\n oldState,\n lastOkValue: oldValue,\n }));\n return true;\n }\n }\n }\n return false;\n }\n\n set(value: T): void {\n this._setIfLatest(Result.ok(value), ++this._updateCounter);\n }\n\n update(updater: (value: T | undefined) => T): T {\n const value = updater(this._mostRecentOkValue);\n this.set(value);\n return value;\n }\n\n async setAsync(promise: Promise<T>): Promise<boolean> {\n return await storeLock.withReadLock(async () => {\n const curCounter = ++this._updateCounter;\n const result = await Result.fromPromise(promise);\n return this._setIfLatest(result, curCounter);\n });\n }\n\n setUnavailable(): void {\n this._lastSuccessfulUpdate = ++this._updateCounter;\n this._mostRecentOkValue = undefined;\n this._isAvailable = false;\n this._isRejected = false;\n this._rejectionError = undefined;\n }\n\n setRejected(error: unknown): void {\n this._setIfLatest(Result.error(error), ++this._updateCounter);\n }\n\n map<U>(mapper: (value: T) => U): AsyncStore<U> {\n const store = new AsyncStore<U>();\n this.onChange((value) => {\n store.set(mapper(value));\n });\n return store;\n }\n\n onChange(callback: (value: T, oldValue: T | undefined) => void): { unsubscribe: () => void } {\n return this.onStateChange(({ state, lastOkValue }) => {\n if (state.status === \"ok\") {\n callback(state.data, lastOkValue);\n }\n });\n }\n\n onStateChange(callback: AsyncStoreStateChangeCallback<T>): { unsubscribe: () => void } {\n const uuid = generateUuid();\n this._callbacks.set(uuid, callback);\n return {\n unsubscribe: () => {\n this._callbacks.delete(uuid);\n },\n };\n }\n\n onceChange(callback: (value: T, oldValue: T | undefined) => void): { unsubscribe: () => void } {\n const { unsubscribe } = this.onChange((...args) => {\n unsubscribe();\n callback(...args);\n });\n return { unsubscribe };\n }\n\n onceStateChange(callback: AsyncStoreStateChangeCallback<T>): { unsubscribe: () => void } {\n const { unsubscribe } = this.onStateChange((...args) => {\n unsubscribe();\n callback(...args);\n });\n return { unsubscribe };\n }\n}\n", "let USER_AGENT;\nif (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) {\n const NAME = 'oauth4webapi';\n const VERSION = 'v3.8.3';\n USER_AGENT = `${NAME}/${VERSION}`;\n}\nfunction looseInstanceOf(input, expected) {\n if (input == null) {\n return false;\n }\n try {\n return (input instanceof expected ||\n Object.getPrototypeOf(input)[Symbol.toStringTag] === expected.prototype[Symbol.toStringTag]);\n }\n catch {\n return false;\n }\n}\nconst ERR_INVALID_ARG_VALUE = 'ERR_INVALID_ARG_VALUE';\nconst ERR_INVALID_ARG_TYPE = 'ERR_INVALID_ARG_TYPE';\nfunction CodedTypeError(message, code, cause) {\n const err = new TypeError(message, { cause });\n Object.assign(err, { code });\n return err;\n}\nexport const allowInsecureRequests = Symbol();\nexport const clockSkew = Symbol();\nexport const clockTolerance = Symbol();\nexport const customFetch = Symbol();\nexport const modifyAssertion = Symbol();\nexport const jweDecrypt = Symbol();\nexport const jwksCache = Symbol();\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\nfunction buf(input) {\n if (typeof input === 'string') {\n return encoder.encode(input);\n }\n return decoder.decode(input);\n}\nlet encodeBase64Url;\nif (Uint8Array.prototype.toBase64) {\n encodeBase64Url = (input) => {\n if (input instanceof ArrayBuffer) {\n input = new Uint8Array(input);\n }\n return input.toBase64({ alphabet: 'base64url', omitPadding: true });\n };\n}\nelse {\n const CHUNK_SIZE = 0x8000;\n encodeBase64Url = (input) => {\n if (input instanceof ArrayBuffer) {\n input = new Uint8Array(input);\n }\n const arr = [];\n for (let i = 0; i < input.byteLength; i += CHUNK_SIZE) {\n arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));\n }\n return btoa(arr.join('')).replace(/=/g, '').replace(/\\+/g, '-').replace(/\\//g, '_');\n };\n}\nlet decodeBase64Url;\nif (Uint8Array.fromBase64) {\n decodeBase64Url = (input) => {\n try {\n return Uint8Array.fromBase64(input, { alphabet: 'base64url' });\n }\n catch (cause) {\n throw CodedTypeError('The input to be decoded is not correctly encoded.', ERR_INVALID_ARG_VALUE, cause);\n }\n };\n}\nelse {\n decodeBase64Url = (input) => {\n try {\n const binary = atob(input.replace(/-/g, '+').replace(/_/g, '/').replace(/\\s/g, ''));\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n }\n catch (cause) {\n throw CodedTypeError('The input to be decoded is not correctly encoded.', ERR_INVALID_ARG_VALUE, cause);\n }\n };\n}\nfunction b64u(input) {\n if (typeof input === 'string') {\n return decodeBase64Url(input);\n }\n return encodeBase64Url(input);\n}\nexport class UnsupportedOperationError extends Error {\n code;\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n this.code = UNSUPPORTED_OPERATION;\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nexport class OperationProcessingError extends Error {\n code;\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n if (options?.code) {\n this.code = options?.code;\n }\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nfunction OPE(message, code, cause) {\n return new OperationProcessingError(message, { code, cause });\n}\nasync function calculateJwkThumbprint(jwk) {\n let components;\n switch (jwk.kty) {\n case 'EC':\n components = {\n crv: jwk.crv,\n kty: jwk.kty,\n x: jwk.x,\n y: jwk.y,\n };\n break;\n case 'OKP':\n components = {\n crv: jwk.crv,\n kty: jwk.kty,\n x: jwk.x,\n };\n break;\n case 'AKP':\n components = {\n alg: jwk.alg,\n kty: jwk.kty,\n pub: jwk.pub,\n };\n break;\n case 'RSA':\n components = {\n e: jwk.e,\n kty: jwk.kty,\n n: jwk.n,\n };\n break;\n default:\n throw new UnsupportedOperationError('unsupported JWK key type', { cause: jwk });\n }\n return b64u(await crypto.subtle.digest('SHA-256', buf(JSON.stringify(components))));\n}\nfunction assertCryptoKey(key, it) {\n if (!(key instanceof CryptoKey)) {\n throw CodedTypeError(`${it} must be a CryptoKey`, ERR_INVALID_ARG_TYPE);\n }\n}\nfunction assertPrivateKey(key, it) {\n assertCryptoKey(key, it);\n if (key.type !== 'private') {\n throw CodedTypeError(`${it} must be a private CryptoKey`, ERR_INVALID_ARG_VALUE);\n }\n}\nfunction assertPublicKey(key, it) {\n assertCryptoKey(key, it);\n if (key.type !== 'public') {\n throw CodedTypeError(`${it} must be a public CryptoKey`, ERR_INVALID_ARG_VALUE);\n }\n}\nfunction normalizeTyp(value) {\n return value.toLowerCase().replace(/^application\\//, '');\n}\nfunction isJsonObject(input) {\n if (input === null || typeof input !== 'object' || Array.isArray(input)) {\n return false;\n }\n return true;\n}\nfunction prepareHeaders(input) {\n if (looseInstanceOf(input, Headers)) {\n input = Object.fromEntries(input.entries());\n }\n const headers = new Headers(input ?? {});\n if (USER_AGENT && !headers.has('user-agent')) {\n headers.set('user-agent', USER_AGENT);\n }\n if (headers.has('authorization')) {\n throw CodedTypeError('\"options.headers\" must not include the \"authorization\" header name', ERR_INVALID_ARG_VALUE);\n }\n return headers;\n}\nfunction signal(url, value) {\n if (value !== undefined) {\n if (typeof value === 'function') {\n value = value(url.href);\n }\n if (!(value instanceof AbortSignal)) {\n throw CodedTypeError('\"options.signal\" must return or be an instance of AbortSignal', ERR_INVALID_ARG_TYPE);\n }\n return value;\n }\n return undefined;\n}\nfunction replaceDoubleSlash(pathname) {\n if (pathname.includes('//')) {\n return pathname.replace('//', '/');\n }\n return pathname;\n}\nfunction prependWellKnown(url, wellKnown, allowTerminatingSlash = false) {\n if (url.pathname === '/') {\n url.pathname = wellKnown;\n }\n else {\n url.pathname = replaceDoubleSlash(`${wellKnown}/${allowTerminatingSlash ? url.pathname : url.pathname.replace(/(\\/)$/, '')}`);\n }\n return url;\n}\nfunction appendWellKnown(url, wellKnown) {\n url.pathname = replaceDoubleSlash(`${url.pathname}/${wellKnown}`);\n return url;\n}\nasync function performDiscovery(input, urlName, transform, options) {\n if (!(input instanceof URL)) {\n throw CodedTypeError(`\"${urlName}\" must be an instance of URL`, ERR_INVALID_ARG_TYPE);\n }\n checkProtocol(input, options?.[allowInsecureRequests] !== true);\n const url = transform(new URL(input.href));\n const headers = prepareHeaders(options?.headers);\n headers.set('accept', 'application/json');\n return (options?.[customFetch] || fetch)(url.href, {\n body: undefined,\n headers: Object.fromEntries(headers.entries()),\n method: 'GET',\n redirect: 'manual',\n signal: signal(url, options?.signal),\n });\n}\nexport async function discoveryRequest(issuerIdentifier, options) {\n return performDiscovery(issuerIdentifier, 'issuerIdentifier', (url) => {\n switch (options?.algorithm) {\n case undefined:\n case 'oidc':\n appendWellKnown(url, '.well-known/openid-configuration');\n break;\n case 'oauth2':\n prependWellKnown(url, '.well-known/oauth-authorization-server');\n break;\n default:\n throw CodedTypeError('\"options.algorithm\" must be \"oidc\" (default), or \"oauth2\"', ERR_INVALID_ARG_VALUE);\n }\n return url;\n }, options);\n}\nfunction assertNumber(input, allow0, it, code, cause) {\n try {\n if (typeof input !== 'number' || !Number.isFinite(input)) {\n throw CodedTypeError(`${it} must be a number`, ERR_INVALID_ARG_TYPE, cause);\n }\n if (input > 0)\n return;\n if (allow0) {\n if (input !== 0) {\n throw CodedTypeError(`${it} must be a non-negative number`, ERR_INVALID_ARG_VALUE, cause);\n }\n return;\n }\n throw CodedTypeError(`${it} must be a positive number`, ERR_INVALID_ARG_VALUE, cause);\n }\n catch (err) {\n if (code) {\n throw OPE(err.message, code, cause);\n }\n throw err;\n }\n}\nfunction assertString(input, it, code, cause) {\n try {\n if (typeof input !== 'string') {\n throw CodedTypeError(`${it} must be a string`, ERR_INVALID_ARG_TYPE, cause);\n }\n if (input.length === 0) {\n throw CodedTypeError(`${it} must not be empty`, ERR_INVALID_ARG_VALUE, cause);\n }\n }\n catch (err) {\n if (code) {\n throw OPE(err.message, code, cause);\n }\n throw err;\n }\n}\nexport async function processDiscoveryResponse(expectedIssuerIdentifier, response) {\n const expected = expectedIssuerIdentifier;\n if (!(expected instanceof URL) && expected !== _nodiscoverycheck) {\n throw CodedTypeError('\"expectedIssuerIdentifier\" must be an instance of URL', ERR_INVALID_ARG_TYPE);\n }\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n if (response.status !== 200) {\n throw OPE('\"response\" is not a conform Authorization Server Metadata response (unexpected HTTP status code)', RESPONSE_IS_NOT_CONFORM, response);\n }\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response);\n assertString(json.issuer, '\"response\" body \"issuer\" property', INVALID_RESPONSE, { body: json });\n if (expected !== _nodiscoverycheck && new URL(json.issuer).href !== expected.href) {\n throw OPE('\"response\" body \"issuer\" property does not match the expected value', JSON_ATTRIBUTE_COMPARISON, { expected: expected.href, body: json, attribute: 'issuer' });\n }\n return json;\n}\nfunction assertApplicationJson(response) {\n assertContentType(response, 'application/json');\n}\nfunction notJson(response, ...types) {\n let msg = '\"response\" content-type must be ';\n if (types.length > 2) {\n const last = types.pop();\n msg += `${types.join(', ')}, or ${last}`;\n }\n else if (types.length === 2) {\n msg += `${types[0]} or ${types[1]}`;\n }\n else {\n msg += types[0];\n }\n return OPE(msg, RESPONSE_IS_NOT_JSON, response);\n}\nfunction assertContentTypes(response, ...types) {\n if (!types.includes(getContentType(response))) {\n throw notJson(response, ...types);\n }\n}\nfunction assertContentType(response, contentType) {\n if (getContentType(response) !== contentType) {\n throw notJson(response, contentType);\n }\n}\nfunction randomBytes() {\n return b64u(crypto.getRandomValues(new Uint8Array(32)));\n}\nexport function generateRandomCodeVerifier() {\n return randomBytes();\n}\nexport function generateRandomState() {\n return randomBytes();\n}\nexport function generateRandomNonce() {\n return randomBytes();\n}\nexport async function calculatePKCECodeChallenge(codeVerifier) {\n assertString(codeVerifier, 'codeVerifier');\n return b64u(await crypto.subtle.digest('SHA-256', buf(codeVerifier)));\n}\nfunction getKeyAndKid(input) {\n if (input instanceof CryptoKey) {\n return { key: input };\n }\n if (!(input?.key instanceof CryptoKey)) {\n return {};\n }\n if (input.kid !== undefined) {\n assertString(input.kid, '\"kid\"');\n }\n return {\n key: input.key,\n kid: input.kid,\n };\n}\nfunction psAlg(key) {\n switch (key.algorithm.hash.name) {\n case 'SHA-256':\n return 'PS256';\n case 'SHA-384':\n return 'PS384';\n case 'SHA-512':\n return 'PS512';\n default:\n throw new UnsupportedOperationError('unsupported RsaHashedKeyAlgorithm hash name', {\n cause: key,\n });\n }\n}\nfunction rsAlg(key) {\n switch (key.algorithm.hash.name) {\n case 'SHA-256':\n return 'RS256';\n case 'SHA-384':\n return 'RS384';\n case 'SHA-512':\n return 'RS512';\n default:\n throw new UnsupportedOperationError('unsupported RsaHashedKeyAlgorithm hash name', {\n cause: key,\n });\n }\n}\nfunction esAlg(key) {\n switch (key.algorithm.namedCurve) {\n case 'P-256':\n return 'ES256';\n case 'P-384':\n return 'ES384';\n case 'P-521':\n return 'ES512';\n default:\n throw new UnsupportedOperationError('unsupported EcKeyAlgorithm namedCurve', { cause: key });\n }\n}\nfunction keyToJws(key) {\n switch (key.algorithm.name) {\n case 'RSA-PSS':\n return psAlg(key);\n case 'RSASSA-PKCS1-v1_5':\n return rsAlg(key);\n case 'ECDSA':\n return esAlg(key);\n case 'Ed25519':\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n return key.algorithm.name;\n case 'EdDSA':\n return 'Ed25519';\n default:\n throw new UnsupportedOperationError('unsupported CryptoKey algorithm name', { cause: key });\n }\n}\nfunction getClockSkew(client) {\n const skew = client?.[clockSkew];\n return typeof skew === 'number' && Number.isFinite(skew) ? skew : 0;\n}\nfunction getClockTolerance(client) {\n const tolerance = client?.[clockTolerance];\n return typeof tolerance === 'number' && Number.isFinite(tolerance) && Math.sign(tolerance) !== -1\n ? tolerance\n : 30;\n}\nfunction epochTime() {\n return Math.floor(Date.now() / 1000);\n}\nfunction assertAs(as) {\n if (typeof as !== 'object' || as === null) {\n throw CodedTypeError('\"as\" must be an object', ERR_INVALID_ARG_TYPE);\n }\n assertString(as.issuer, '\"as.issuer\"');\n}\nfunction assertClient(client) {\n if (typeof client !== 'object' || client === null) {\n throw CodedTypeError('\"client\" must be an object', ERR_INVALID_ARG_TYPE);\n }\n assertString(client.client_id, '\"client.client_id\"');\n}\nfunction formUrlEncode(token) {\n return encodeURIComponent(token).replace(/(?:[-_.!~*'()]|%20)/g, (substring) => {\n switch (substring) {\n case '-':\n case '_':\n case '.':\n case '!':\n case '~':\n case '*':\n case \"'\":\n case '(':\n case ')':\n return `%${substring.charCodeAt(0).toString(16).toUpperCase()}`;\n case '%20':\n return '+';\n default:\n throw new Error();\n }\n });\n}\nexport function ClientSecretPost(clientSecret) {\n assertString(clientSecret, '\"clientSecret\"');\n return (_as, client, body, _headers) => {\n body.set('client_id', client.client_id);\n body.set('client_secret', clientSecret);\n };\n}\nexport function ClientSecretBasic(clientSecret) {\n assertString(clientSecret, '\"clientSecret\"');\n return (_as, client, _body, headers) => {\n const username = formUrlEncode(client.client_id);\n const password = formUrlEncode(clientSecret);\n const credentials = btoa(`${username}:${password}`);\n headers.set('authorization', `Basic ${credentials}`);\n };\n}\nfunction clientAssertionPayload(as, client) {\n const now = epochTime() + getClockSkew(client);\n return {\n jti: randomBytes(),\n aud: as.issuer,\n exp: now + 60,\n iat: now,\n nbf: now,\n iss: client.client_id,\n sub: client.client_id,\n };\n}\nexport function PrivateKeyJwt(clientPrivateKey, options) {\n const { key, kid } = getKeyAndKid(clientPrivateKey);\n assertPrivateKey(key, '\"clientPrivateKey.key\"');\n return async (as, client, body, _headers) => {\n const header = { alg: keyToJws(key), kid };\n const payload = clientAssertionPayload(as, client);\n options?.[modifyAssertion]?.(header, payload);\n body.set('client_id', client.client_id);\n body.set('client_assertion_type', 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer');\n body.set('client_assertion', await signJwt(header, payload, key));\n };\n}\nexport function ClientSecretJwt(clientSecret, options) {\n assertString(clientSecret, '\"clientSecret\"');\n const modify = options?.[modifyAssertion];\n let key;\n return async (as, client, body, _headers) => {\n key ||= await crypto.subtle.importKey('raw', buf(clientSecret), { hash: 'SHA-256', name: 'HMAC' }, false, ['sign']);\n const header = { alg: 'HS256' };\n const payload = clientAssertionPayload(as, client);\n modify?.(header, payload);\n const data = `${b64u(buf(JSON.stringify(header)))}.${b64u(buf(JSON.stringify(payload)))}`;\n const hmac = await crypto.subtle.sign(key.algorithm, key, buf(data));\n body.set('client_id', client.client_id);\n body.set('client_assertion_type', 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer');\n body.set('client_assertion', `${data}.${b64u(new Uint8Array(hmac))}`);\n };\n}\nexport function None() {\n return (_as, client, body, _headers) => {\n body.set('client_id', client.client_id);\n };\n}\nexport function TlsClientAuth() {\n return None();\n}\nasync function signJwt(header, payload, key) {\n if (!key.usages.includes('sign')) {\n throw CodedTypeError('CryptoKey instances used for signing assertions must include \"sign\" in their \"usages\"', ERR_INVALID_ARG_VALUE);\n }\n const input = `${b64u(buf(JSON.stringify(header)))}.${b64u(buf(JSON.stringify(payload)))}`;\n const signature = b64u(await crypto.subtle.sign(keyToSubtle(key), key, buf(input)));\n return `${input}.${signature}`;\n}\nexport async function issueRequestObject(as, client, parameters, privateKey, options) {\n assertAs(as);\n assertClient(client);\n parameters = new URLSearchParams(parameters);\n const { key, kid } = getKeyAndKid(privateKey);\n assertPrivateKey(key, '\"privateKey.key\"');\n parameters.set('client_id', client.client_id);\n const now = epochTime() + getClockSkew(client);\n const claims = {\n ...Object.fromEntries(parameters.entries()),\n jti: randomBytes(),\n aud: as.issuer,\n exp: now + 60,\n iat: now,\n nbf: now,\n iss: client.client_id,\n };\n let resource;\n if (parameters.has('resource') &&\n (resource = parameters.getAll('resource')) &&\n resource.length > 1) {\n claims.resource = resource;\n }\n {\n let value = parameters.get('max_age');\n if (value !== null) {\n claims.max_age = parseInt(value, 10);\n assertNumber(claims.max_age, true, '\"max_age\" parameter');\n }\n }\n {\n let value = parameters.get('claims');\n if (value !== null) {\n try {\n claims.claims = JSON.parse(value);\n }\n catch (cause) {\n throw OPE('failed to parse the \"claims\" parameter as JSON', PARSE_ERROR, cause);\n }\n if (!isJsonObject(claims.claims)) {\n throw CodedTypeError('\"claims\" parameter must be a JSON with a top level object', ERR_INVALID_ARG_VALUE);\n }\n }\n }\n {\n let value = parameters.get('authorization_details');\n if (value !== null) {\n try {\n claims.authorization_details = JSON.parse(value);\n }\n catch (cause) {\n throw OPE('failed to parse the \"authorization_details\" parameter as JSON', PARSE_ERROR, cause);\n }\n if (!Array.isArray(claims.authorization_details)) {\n throw CodedTypeError('\"authorization_details\" parameter must be a JSON with a top level array', ERR_INVALID_ARG_VALUE);\n }\n }\n }\n const header = {\n alg: keyToJws(key),\n typ: 'oauth-authz-req+jwt',\n kid,\n };\n options?.[modifyAssertion]?.(header, claims);\n return signJwt(header, claims, key);\n}\nlet jwkCache;\nasync function getSetPublicJwkCache(key, alg) {\n const { kty, e, n, x, y, crv, pub } = await crypto.subtle.exportKey('jwk', key);\n const jwk = { kty, e, n, x, y, crv, pub };\n if (kty === 'AKP')\n jwk.alg = alg;\n jwkCache.set(key, jwk);\n return jwk;\n}\nasync function publicJwk(key, alg) {\n jwkCache ||= new WeakMap();\n return jwkCache.get(key) || getSetPublicJwkCache(key, alg);\n}\nconst URLParse = URL.parse\n ?\n (url, base) => URL.parse(url, base)\n : (url, base) => {\n try {\n return new URL(url, base);\n }\n catch {\n return null;\n }\n };\nexport function checkProtocol(url, enforceHttps) {\n if (enforceHttps && url.protocol !== 'https:') {\n throw OPE('only requests to HTTPS are allowed', HTTP_REQUEST_FORBIDDEN, url);\n }\n if (url.protocol !== 'https:' && url.protocol !== 'http:') {\n throw OPE('only HTTP and HTTPS requests are allowed', REQUEST_PROTOCOL_FORBIDDEN, url);\n }\n}\nfunction validateEndpoint(value, endpoint, useMtlsAlias, enforceHttps) {\n let url;\n if (typeof value !== 'string' || !(url = URLParse(value))) {\n throw OPE(`authorization server metadata does not contain a valid ${useMtlsAlias ? `\"as.mtls_endpoint_aliases.${endpoint}\"` : `\"as.${endpoint}\"`}`, value === undefined ? MISSING_SERVER_METADATA : INVALID_SERVER_METADATA, { attribute: useMtlsAlias ? `mtls_endpoint_aliases.${endpoint}` : endpoint });\n }\n checkProtocol(url, enforceHttps);\n return url;\n}\nexport function resolveEndpoint(as, endpoint, useMtlsAlias, enforceHttps) {\n if (useMtlsAlias && as.mtls_endpoint_aliases && endpoint in as.mtls_endpoint_aliases) {\n return validateEndpoint(as.mtls_endpoint_aliases[endpoint], endpoint, useMtlsAlias, enforceHttps);\n }\n return validateEndpoint(as[endpoint], endpoint, useMtlsAlias, enforceHttps);\n}\nexport async function pushedAuthorizationRequest(as, client, clientAuthentication, parameters, options) {\n assertAs(as);\n assertClient(client);\n const url = resolveEndpoint(as, 'pushed_authorization_request_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n const body = new URLSearchParams(parameters);\n body.set('client_id', client.client_id);\n const headers = prepareHeaders(options?.headers);\n headers.set('accept', 'application/json');\n if (options?.DPoP !== undefined) {\n assertDPoP(options.DPoP);\n await options.DPoP.addProof(url, headers, 'POST');\n }\n const response = await authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);\n options?.DPoP?.cacheNonce(response, url);\n return response;\n}\nclass DPoPHandler {\n #header;\n #privateKey;\n #publicKey;\n #clockSkew;\n #modifyAssertion;\n #map;\n #jkt;\n constructor(client, keyPair, options) {\n assertPrivateKey(keyPair?.privateKey, '\"DPoP.privateKey\"');\n assertPublicKey(keyPair?.publicKey, '\"DPoP.publicKey\"');\n if (!keyPair.publicKey.extractable) {\n throw CodedTypeError('\"DPoP.publicKey.extractable\" must be true', ERR_INVALID_ARG_VALUE);\n }\n this.#modifyAssertion = options?.[modifyAssertion];\n this.#clockSkew = getClockSkew(client);\n this.#privateKey = keyPair.privateKey;\n this.#publicKey = keyPair.publicKey;\n branded.add(this);\n }\n #get(key) {\n this.#map ||= new Map();\n let item = this.#map.get(key);\n if (item) {\n this.#map.delete(key);\n this.#map.set(key, item);\n }\n return item;\n }\n #set(key, val) {\n this.#map ||= new Map();\n this.#map.delete(key);\n if (this.#map.size === 100) {\n this.#map.delete(this.#map.keys().next().value);\n }\n this.#map.set(key, val);\n }\n async calculateThumbprint() {\n if (!this.#jkt) {\n const jwk = await crypto.subtle.exportKey('jwk', this.#publicKey);\n this.#jkt ||= await calculateJwkThumbprint(jwk);\n }\n return this.#jkt;\n }\n async addProof(url, headers, htm, accessToken) {\n const alg = keyToJws(this.#privateKey);\n this.#header ||= {\n alg,\n typ: 'dpop+jwt',\n jwk: await publicJwk(this.#publicKey, alg),\n };\n const nonce = this.#get(url.origin);\n const now = epochTime() + this.#clockSkew;\n const payload = {\n iat: now,\n jti: randomBytes(),\n htm,\n nonce,\n htu: `${url.origin}${url.pathname}`,\n ath: accessToken\n ? b64u(await crypto.subtle.digest('SHA-256', buf(accessToken)))\n : undefined,\n };\n this.#modifyAssertion?.(this.#header, payload);\n headers.set('dpop', await signJwt(this.#header, payload, this.#privateKey));\n }\n cacheNonce(response, url) {\n try {\n const nonce = response.headers.get('dpop-nonce');\n if (nonce) {\n this.#set(url.origin, nonce);\n }\n }\n catch { }\n }\n}\nexport function isDPoPNonceError(err) {\n if (err instanceof WWWAuthenticateChallengeError) {\n const { 0: challenge, length } = err.cause;\n return (length === 1 && challenge.scheme === 'dpop' && challenge.parameters.error === 'use_dpop_nonce');\n }\n if (err instanceof ResponseBodyError) {\n return err.error === 'use_dpop_nonce';\n }\n return false;\n}\nexport function DPoP(client, keyPair, options) {\n return new DPoPHandler(client, keyPair, options);\n}\nexport class ResponseBodyError extends Error {\n cause;\n code;\n error;\n status;\n error_description;\n response;\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n this.code = RESPONSE_BODY_ERROR;\n this.cause = options.cause;\n this.error = options.cause.error;\n this.status = options.response.status;\n this.error_description = options.cause.error_description;\n Object.defineProperty(this, 'response', { enumerable: false, value: options.response });\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nexport class AuthorizationResponseError extends Error {\n cause;\n code;\n error;\n error_description;\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n this.code = AUTHORIZATION_RESPONSE_ERROR;\n this.cause = options.cause;\n this.error = options.cause.get('error');\n this.error_description = options.cause.get('error_description') ?? undefined;\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nexport class WWWAuthenticateChallengeError extends Error {\n cause;\n code;\n response;\n status;\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n this.code = WWW_AUTHENTICATE_CHALLENGE;\n this.cause = options.cause;\n this.status = options.response.status;\n this.response = options.response;\n Object.defineProperty(this, 'response', { enumerable: false });\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nconst tokenMatch = \"[a-zA-Z0-9!#$%&\\\\'\\\\*\\\\+\\\\-\\\\.\\\\^_`\\\\|~]+\";\nconst token68Match = '[a-zA-Z0-9\\\\-\\\\._\\\\~\\\\+\\\\/]+={0,2}';\nconst quotedMatch = '\"((?:[^\"\\\\\\\\]|\\\\\\\\[\\\\s\\\\S])*)\"';\nconst quotedParamMatcher = '(' + tokenMatch + ')\\\\s*=\\\\s*' + quotedMatch;\nconst paramMatcher = '(' + tokenMatch + ')\\\\s*=\\\\s*(' + tokenMatch + ')';\nconst schemeRE = new RegExp('^[,\\\\s]*(' + tokenMatch + ')');\nconst quotedParamRE = new RegExp('^[,\\\\s]*' + quotedParamMatcher + '[,\\\\s]*(.*)');\nconst unquotedParamRE = new RegExp('^[,\\\\s]*' + paramMatcher + '[,\\\\s]*(.*)');\nconst token68ParamRE = new RegExp('^(' + token68Match + ')(?:$|[,\\\\s])(.*)');\nfunction parseWwwAuthenticateChallenges(response) {\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n const header = response.headers.get('www-authenticate');\n if (header === null) {\n return undefined;\n }\n const challenges = [];\n let rest = header;\n while (rest) {\n let match = rest.match(schemeRE);\n const scheme = match?.['1'].toLowerCase();\n if (!scheme) {\n return undefined;\n }\n const afterScheme = rest.substring(match[0].length);\n if (afterScheme && !afterScheme.match(/^[\\s,]/)) {\n return undefined;\n }\n const spaceMatch = afterScheme.match(/^\\s+(.*)$/);\n const hasParameters = !!spaceMatch;\n rest = spaceMatch ? spaceMatch[1] : undefined;\n const parameters = {};\n let token68;\n if (hasParameters) {\n while (rest) {\n let key;\n let value;\n if ((match = rest.match(quotedParamRE))) {\n ;\n [, key, value, rest] = match;\n if (value.includes('\\\\')) {\n try {\n value = JSON.parse(`\"${value}\"`);\n }\n catch { }\n }\n parameters[key.toLowerCase()] = value;\n continue;\n }\n if ((match = rest.match(unquotedParamRE))) {\n ;\n [, key, value, rest] = match;\n parameters[key.toLowerCase()] = value;\n continue;\n }\n if ((match = rest.match(token68ParamRE))) {\n if (Object.keys(parameters).length) {\n break;\n }\n ;\n [, token68, rest] = match;\n break;\n }\n return undefined;\n }\n }\n else {\n rest = afterScheme || undefined;\n }\n const challenge = { scheme, parameters };\n if (token68) {\n challenge.token68 = token68;\n }\n challenges.push(challenge);\n }\n if (!challenges.length) {\n return undefined;\n }\n return challenges;\n}\nexport async function processPushedAuthorizationResponse(as, client, response) {\n assertAs(as);\n assertClient(client);\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n await checkOAuthBodyError(response, 201, 'Pushed Authorization Request Endpoint');\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response);\n assertString(json.request_uri, '\"response\" body \"request_uri\" property', INVALID_RESPONSE, {\n body: json,\n });\n let expiresIn = typeof json.expires_in !== 'number' ? parseFloat(json.expires_in) : json.expires_in;\n assertNumber(expiresIn, true, '\"response\" body \"expires_in\" property', INVALID_RESPONSE, {\n body: json,\n });\n json.expires_in = expiresIn;\n return json;\n}\nasync function parseOAuthResponseErrorBody(response) {\n if (response.status > 399 && response.status < 500) {\n assertReadableResponse(response);\n assertApplicationJson(response);\n try {\n const json = await response.clone().json();\n if (isJsonObject(json) && typeof json.error === 'string' && json.error.length) {\n return json;\n }\n }\n catch { }\n }\n return undefined;\n}\nasync function checkOAuthBodyError(response, expected, label) {\n if (response.status !== expected) {\n checkAuthenticationChallenges(response);\n let err;\n if ((err = await parseOAuthResponseErrorBody(response))) {\n await response.body?.cancel();\n throw new ResponseBodyError('server responded with an error in the response body', {\n cause: err,\n response,\n });\n }\n throw OPE(`\"response\" is not a conform ${label} response (unexpected HTTP status code)`, RESPONSE_IS_NOT_CONFORM, response);\n }\n}\nfunction assertDPoP(option) {\n if (!branded.has(option)) {\n throw CodedTypeError('\"options.DPoP\" is not a valid DPoPHandle', ERR_INVALID_ARG_VALUE);\n }\n}\nasync function resourceRequest(accessToken, method, url, headers, body, options) {\n assertString(accessToken, '\"accessToken\"');\n if (!(url instanceof URL)) {\n throw CodedTypeError('\"url\" must be an instance of URL', ERR_INVALID_ARG_TYPE);\n }\n checkProtocol(url, options?.[allowInsecureRequests] !== true);\n headers = prepareHeaders(headers);\n if (options?.DPoP) {\n assertDPoP(options.DPoP);\n await options.DPoP.addProof(url, headers, method.toUpperCase(), accessToken);\n }\n headers.set('authorization', `${headers.has('dpop') ? 'DPoP' : 'Bearer'} ${accessToken}`);\n const response = await (options?.[customFetch] || fetch)(url.href, {\n body,\n headers: Object.fromEntries(headers.entries()),\n method,\n redirect: 'manual',\n signal: signal(url, options?.signal),\n });\n options?.DPoP?.cacheNonce(response, url);\n return response;\n}\nexport async function protectedResourceRequest(accessToken, method, url, headers, body, options) {\n const response = await resourceRequest(accessToken, method, url, headers, body, options);\n checkAuthenticationChallenges(response);\n return response;\n}\nexport async function userInfoRequest(as, client, accessToken, options) {\n assertAs(as);\n assertClient(client);\n const url = resolveEndpoint(as, 'userinfo_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n const headers = prepareHeaders(options?.headers);\n if (client.userinfo_signed_response_alg) {\n headers.set('accept', 'application/jwt');\n }\n else {\n headers.set('accept', 'application/json');\n headers.append('accept', 'application/jwt');\n }\n return resourceRequest(accessToken, 'GET', url, headers, null, {\n ...options,\n [clockSkew]: getClockSkew(client),\n });\n}\nlet jwksMap;\nfunction setJwksCache(as, jwks, uat, cache) {\n jwksMap ||= new WeakMap();\n jwksMap.set(as, {\n jwks,\n uat,\n get age() {\n return epochTime() - this.uat;\n },\n });\n if (cache) {\n Object.assign(cache, { jwks: structuredClone(jwks), uat });\n }\n}\nfunction isFreshJwksCache(input) {\n if (typeof input !== 'object' || input === null) {\n return false;\n }\n if (!('uat' in input) || typeof input.uat !== 'number' || epochTime() - input.uat >= 300) {\n return false;\n }\n if (!('jwks' in input) ||\n !isJsonObject(input.jwks) ||\n !Array.isArray(input.jwks.keys) ||\n !Array.prototype.every.call(input.jwks.keys, isJsonObject)) {\n return false;\n }\n return true;\n}\nfunction clearJwksCache(as, cache) {\n jwksMap?.delete(as);\n delete cache?.jwks;\n delete cache?.uat;\n}\nasync function getPublicSigKeyFromIssuerJwksUri(as, options, header) {\n const { alg, kid } = header;\n checkSupportedJwsAlg(header);\n if (!jwksMap?.has(as) && isFreshJwksCache(options?.[jwksCache])) {\n setJwksCache(as, options?.[jwksCache].jwks, options?.[jwksCache].uat);\n }\n let jwks;\n let age;\n if (jwksMap?.has(as)) {\n ;\n ({ jwks, age } = jwksMap.get(as));\n if (age >= 300) {\n clearJwksCache(as, options?.[jwksCache]);\n return getPublicSigKeyFromIssuerJwksUri(as, options, header);\n }\n }\n else {\n jwks = await jwksRequest(as, options).then(processJwksResponse);\n age = 0;\n setJwksCache(as, jwks, epochTime(), options?.[jwksCache]);\n }\n let kty;\n switch (alg.slice(0, 2)) {\n case 'RS':\n case 'PS':\n kty = 'RSA';\n break;\n case 'ES':\n kty = 'EC';\n break;\n case 'Ed':\n kty = 'OKP';\n break;\n case 'ML':\n kty = 'AKP';\n break;\n default:\n throw new UnsupportedOperationError('unsupported JWS algorithm', { cause: { alg } });\n }\n const candidates = jwks.keys.filter((jwk) => {\n if (jwk.kty !== kty) {\n return false;\n }\n if (kid !== undefined && kid !== jwk.kid) {\n return false;\n }\n if (jwk.alg !== undefined && alg !== jwk.alg) {\n return false;\n }\n if (jwk.use !== undefined && jwk.use !== 'sig') {\n return false;\n }\n if (jwk.key_ops?.includes('verify') === false) {\n return false;\n }\n switch (true) {\n case alg === 'ES256' && jwk.crv !== 'P-256':\n case alg === 'ES384' && jwk.crv !== 'P-384':\n case alg === 'ES512' && jwk.crv !== 'P-521':\n case alg === 'Ed25519' && jwk.crv !== 'Ed25519':\n case alg === 'EdDSA' && jwk.crv !== 'Ed25519':\n return false;\n }\n return true;\n });\n const { 0: jwk, length } = candidates;\n if (!length) {\n if (age >= 60) {\n clearJwksCache(as, options?.[jwksCache]);\n return getPublicSigKeyFromIssuerJwksUri(as, options, header);\n }\n throw OPE('error when selecting a JWT verification key, no applicable keys found', KEY_SELECTION, { header, candidates, jwks_uri: new URL(as.jwks_uri) });\n }\n if (length !== 1) {\n throw OPE('error when selecting a JWT verification key, multiple applicable keys found, a \"kid\" JWT Header Parameter is required', KEY_SELECTION, { header, candidates, jwks_uri: new URL(as.jwks_uri) });\n }\n return importJwk(alg, jwk);\n}\nexport const skipSubjectCheck = Symbol();\nexport function getContentType(input) {\n return input.headers.get('content-type')?.split(';')[0];\n}\nexport async function processUserInfoResponse(as, client, expectedSubject, response, options) {\n assertAs(as);\n assertClient(client);\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n checkAuthenticationChallenges(response);\n if (response.status !== 200) {\n throw OPE('\"response\" is not a conform UserInfo Endpoint response (unexpected HTTP status code)', RESPONSE_IS_NOT_CONFORM, response);\n }\n assertReadableResponse(response);\n let json;\n if (getContentType(response) === 'application/jwt') {\n const { claims, jwt } = await validateJwt(await response.text(), checkSigningAlgorithm.bind(undefined, client.userinfo_signed_response_alg, as.userinfo_signing_alg_values_supported, undefined), getClockSkew(client), getClockTolerance(client), options?.[jweDecrypt])\n .then(validateOptionalAudience.bind(undefined, client.client_id))\n .then(validateOptionalIssuer.bind(undefined, as));\n jwtRefs.set(response, jwt);\n json = claims;\n }\n else {\n if (client.userinfo_signed_response_alg) {\n throw OPE('JWT UserInfo Response expected', JWT_USERINFO_EXPECTED, response);\n }\n json = await getResponseJsonBody(response);\n }\n assertString(json.sub, '\"response\" body \"sub\" property', INVALID_RESPONSE, { body: json });\n switch (expectedSubject) {\n case skipSubjectCheck:\n break;\n default:\n assertString(expectedSubject, '\"expectedSubject\"');\n if (json.sub !== expectedSubject) {\n throw OPE('unexpected \"response\" body \"sub\" property value', JSON_ATTRIBUTE_COMPARISON, {\n expected: expectedSubject,\n body: json,\n attribute: 'sub',\n });\n }\n }\n return json;\n}\nasync function authenticatedRequest(as, client, clientAuthentication, url, body, headers, options) {\n await clientAuthentication(as, client, body, headers);\n headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');\n return (options?.[customFetch] || fetch)(url.href, {\n body,\n headers: Object.fromEntries(headers.entries()),\n method: 'POST',\n redirect: 'manual',\n signal: signal(url, options?.signal),\n });\n}\nasync function tokenEndpointRequest(as, client, clientAuthentication, grantType, parameters, options) {\n const url = resolveEndpoint(as, 'token_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n parameters.set('grant_type', grantType);\n const headers = prepareHeaders(options?.headers);\n headers.set('accept', 'application/json');\n if (options?.DPoP !== undefined) {\n assertDPoP(options.DPoP);\n await options.DPoP.addProof(url, headers, 'POST');\n }\n const response = await authenticatedRequest(as, client, clientAuthentication, url, parameters, headers, options);\n options?.DPoP?.cacheNonce(response, url);\n return response;\n}\nexport async function refreshTokenGrantRequest(as, client, clientAuthentication, refreshToken, options) {\n assertAs(as);\n assertClient(client);\n assertString(refreshToken, '\"refreshToken\"');\n const parameters = new URLSearchParams(options?.additionalParameters);\n parameters.set('refresh_token', refreshToken);\n return tokenEndpointRequest(as, client, clientAuthentication, 'refresh_token', parameters, options);\n}\nconst idTokenClaims = new WeakMap();\nconst jwtRefs = new WeakMap();\nexport function getValidatedIdTokenClaims(ref) {\n if (!ref.id_token) {\n return undefined;\n }\n const claims = idTokenClaims.get(ref);\n if (!claims) {\n throw CodedTypeError('\"ref\" was already garbage collected or did not resolve from the proper sources', ERR_INVALID_ARG_VALUE);\n }\n return claims;\n}\nexport async function validateApplicationLevelSignature(as, ref, options) {\n assertAs(as);\n if (!jwtRefs.has(ref)) {\n throw CodedTypeError('\"ref\" does not contain a processed JWT Response to verify the signature of', ERR_INVALID_ARG_VALUE);\n }\n const { 0: protectedHeader, 1: payload, 2: encodedSignature } = jwtRefs.get(ref).split('.');\n const header = JSON.parse(buf(b64u(protectedHeader)));\n if (header.alg.startsWith('HS')) {\n throw new UnsupportedOperationError('unsupported JWS algorithm', { cause: { alg: header.alg } });\n }\n let key;\n key = await getPublicSigKeyFromIssuerJwksUri(as, options, header);\n await validateJwsSignature(protectedHeader, payload, key, b64u(encodedSignature));\n}\nasync function processGenericAccessTokenResponse(as, client, response, additionalRequiredIdTokenClaims, decryptFn, recognizedTokenTypes) {\n assertAs(as);\n assertClient(client);\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n await checkOAuthBodyError(response, 200, 'Token Endpoint');\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response);\n assertString(json.access_token, '\"response\" body \"access_token\" property', INVALID_RESPONSE, {\n body: json,\n });\n assertString(json.token_type, '\"response\" body \"token_type\" property', INVALID_RESPONSE, {\n body: json,\n });\n json.token_type = json.token_type.toLowerCase();\n if (json.expires_in !== undefined) {\n let expiresIn = typeof json.expires_in !== 'number' ? parseFloat(json.expires_in) : json.expires_in;\n assertNumber(expiresIn, true, '\"response\" body \"expires_in\" property', INVALID_RESPONSE, {\n body: json,\n });\n json.expires_in = expiresIn;\n }\n if (json.refresh_token !== undefined) {\n assertString(json.refresh_token, '\"response\" body \"refresh_token\" property', INVALID_RESPONSE, {\n body: json,\n });\n }\n if (json.scope !== undefined && typeof json.scope !== 'string') {\n throw OPE('\"response\" body \"scope\" property must be a string', INVALID_RESPONSE, { body: json });\n }\n if (json.id_token !== undefined) {\n assertString(json.id_token, '\"response\" body \"id_token\" property', INVALID_RESPONSE, {\n body: json,\n });\n const requiredClaims = ['aud', 'exp', 'iat', 'iss', 'sub'];\n if (client.require_auth_time === true) {\n requiredClaims.push('auth_time');\n }\n if (client.default_max_age !== undefined) {\n assertNumber(client.default_max_age, true, '\"client.default_max_age\"');\n requiredClaims.push('auth_time');\n }\n if (additionalRequiredIdTokenClaims?.length) {\n requiredClaims.push(...additionalRequiredIdTokenClaims);\n }\n const { claims, jwt } = await validateJwt(json.id_token, checkSigningAlgorithm.bind(undefined, client.id_token_signed_response_alg, as.id_token_signing_alg_values_supported, 'RS256'), getClockSkew(client), getClockTolerance(client), decryptFn)\n .then(validatePresence.bind(undefined, requiredClaims))\n .then(validateIssuer.bind(undefined, as))\n .then(validateAudience.bind(undefined, client.client_id));\n if (Array.isArray(claims.aud) && claims.aud.length !== 1) {\n if (claims.azp === undefined) {\n throw OPE('ID Token \"aud\" (audience) claim includes additional untrusted audiences', JWT_CLAIM_COMPARISON, { claims, claim: 'aud' });\n }\n if (claims.azp !== client.client_id) {\n throw OPE('unexpected ID Token \"azp\" (authorized party) claim value', JWT_CLAIM_COMPARISON, { expected: client.client_id, claims, claim: 'azp' });\n }\n }\n if (claims.auth_time !== undefined) {\n assertNumber(claims.auth_time, true, 'ID Token \"auth_time\" (authentication time)', INVALID_RESPONSE, { claims });\n }\n jwtRefs.set(response, jwt);\n idTokenClaims.set(json, claims);\n }\n if (recognizedTokenTypes?.[json.token_type] !== undefined) {\n recognizedTokenTypes[json.token_type](response, json);\n }\n else if (json.token_type !== 'dpop' && json.token_type !== 'bearer') {\n throw new UnsupportedOperationError('unsupported `token_type` value', { cause: { body: json } });\n }\n return json;\n}\nfunction checkAuthenticationChallenges(response) {\n let challenges;\n if ((challenges = parseWwwAuthenticateChallenges(response))) {\n throw new WWWAuthenticateChallengeError('server responded with a challenge in the WWW-Authenticate HTTP Header', { cause: challenges, response });\n }\n}\nexport async function processRefreshTokenResponse(as, client, response, options) {\n return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);\n}\nfunction validateOptionalAudience(expected, result) {\n if (result.claims.aud !== undefined) {\n return validateAudience(expected, result);\n }\n return result;\n}\nfunction validateAudience(expected, result) {\n if (Array.isArray(result.claims.aud)) {\n if (!result.claims.aud.includes(expected)) {\n throw OPE('unexpected JWT \"aud\" (audience) claim value', JWT_CLAIM_COMPARISON, {\n expected,\n claims: result.claims,\n claim: 'aud',\n });\n }\n }\n else if (result.claims.aud !== expected) {\n throw OPE('unexpected JWT \"aud\" (audience) claim value', JWT_CLAIM_COMPARISON, {\n expected,\n claims: result.claims,\n claim: 'aud',\n });\n }\n return result;\n}\nfunction validateOptionalIssuer(as, result) {\n if (result.claims.iss !== undefined) {\n return validateIssuer(as, result);\n }\n return result;\n}\nfunction validateIssuer(as, result) {\n const expected = as[_expectedIssuer]?.(result) ?? as.issuer;\n if (result.claims.iss !== expected) {\n throw OPE('unexpected JWT \"iss\" (issuer) claim value', JWT_CLAIM_COMPARISON, {\n expected,\n claims: result.claims,\n claim: 'iss',\n });\n }\n return result;\n}\nconst branded = new WeakSet();\nfunction brand(searchParams) {\n branded.add(searchParams);\n return searchParams;\n}\nexport const nopkce = Symbol();\nexport async function authorizationCodeGrantRequest(as, client, clientAuthentication, callbackParameters, redirectUri, codeVerifier, options) {\n assertAs(as);\n assertClient(client);\n if (!branded.has(callbackParameters)) {\n throw CodedTypeError('\"callbackParameters\" must be an instance of URLSearchParams obtained from \"validateAuthResponse()\", or \"validateJwtAuthResponse()', ERR_INVALID_ARG_VALUE);\n }\n assertString(redirectUri, '\"redirectUri\"');\n const code = getURLSearchParameter(callbackParameters, 'code');\n if (!code) {\n throw OPE('no authorization code in \"callbackParameters\"', INVALID_RESPONSE);\n }\n const parameters = new URLSearchParams(options?.additionalParameters);\n parameters.set('redirect_uri', redirectUri);\n parameters.set('code', code);\n if (codeVerifier !== nopkce) {\n assertString(codeVerifier, '\"codeVerifier\"');\n parameters.set('code_verifier', codeVerifier);\n }\n return tokenEndpointRequest(as, client, clientAuthentication, 'authorization_code', parameters, options);\n}\nconst jwtClaimNames = {\n aud: 'audience',\n c_hash: 'code hash',\n client_id: 'client id',\n exp: 'expiration time',\n iat: 'issued at',\n iss: 'issuer',\n jti: 'jwt id',\n nonce: 'nonce',\n s_hash: 'state hash',\n sub: 'subject',\n ath: 'access token hash',\n htm: 'http method',\n htu: 'http uri',\n cnf: 'confirmation',\n auth_time: 'authentication time',\n};\nfunction validatePresence(required, result) {\n for (const claim of required) {\n if (result.claims[claim] === undefined) {\n throw OPE(`JWT \"${claim}\" (${jwtClaimNames[claim]}) claim missing`, INVALID_RESPONSE, {\n claims: result.claims,\n });\n }\n }\n return result;\n}\nexport const expectNoNonce = Symbol();\nexport const skipAuthTimeCheck = Symbol();\nexport async function processAuthorizationCodeResponse(as, client, response, options) {\n if (typeof options?.expectedNonce === 'string' ||\n typeof options?.maxAge === 'number' ||\n options?.requireIdToken) {\n return processAuthorizationCodeOpenIDResponse(as, client, response, options.expectedNonce, options.maxAge, options[jweDecrypt], options.recognizedTokenTypes);\n }\n return processAuthorizationCodeOAuth2Response(as, client, response, options?.[jweDecrypt], options?.recognizedTokenTypes);\n}\nasync function processAuthorizationCodeOpenIDResponse(as, client, response, expectedNonce, maxAge, decryptFn, recognizedTokenTypes) {\n const additionalRequiredClaims = [];\n switch (expectedNonce) {\n case undefined:\n expectedNonce = expectNoNonce;\n break;\n case expectNoNonce:\n break;\n default:\n assertString(expectedNonce, '\"expectedNonce\" argument');\n additionalRequiredClaims.push('nonce');\n }\n maxAge ??= client.default_max_age;\n switch (maxAge) {\n case undefined:\n maxAge = skipAuthTimeCheck;\n break;\n case skipAuthTimeCheck:\n break;\n default:\n assertNumber(maxAge, true, '\"maxAge\" argument');\n additionalRequiredClaims.push('auth_time');\n }\n const result = await processGenericAccessTokenResponse(as, client, response, additionalRequiredClaims, decryptFn, recognizedTokenTypes);\n assertString(result.id_token, '\"response\" body \"id_token\" property', INVALID_RESPONSE, {\n body: result,\n });\n const claims = getValidatedIdTokenClaims(result);\n if (maxAge !== skipAuthTimeCheck) {\n const now = epochTime() + getClockSkew(client);\n const tolerance = getClockTolerance(client);\n if (claims.auth_time + maxAge < now - tolerance) {\n throw OPE('too much time has elapsed since the last End-User authentication', JWT_TIMESTAMP_CHECK, { claims, now, tolerance, claim: 'auth_time' });\n }\n }\n if (expectedNonce === expectNoNonce) {\n if (claims.nonce !== undefined) {\n throw OPE('unexpected ID Token \"nonce\" claim value', JWT_CLAIM_COMPARISON, {\n expected: undefined,\n claims,\n claim: 'nonce',\n });\n }\n }\n else if (claims.nonce !== expectedNonce) {\n throw OPE('unexpected ID Token \"nonce\" claim value', JWT_CLAIM_COMPARISON, {\n expected: expectedNonce,\n claims,\n claim: 'nonce',\n });\n }\n return result;\n}\nasync function processAuthorizationCodeOAuth2Response(as, client, response, decryptFn, recognizedTokenTypes) {\n const result = await processGenericAccessTokenResponse(as, client, response, undefined, decryptFn, recognizedTokenTypes);\n const claims = getValidatedIdTokenClaims(result);\n if (claims) {\n if (client.default_max_age !== undefined) {\n assertNumber(client.default_max_age, true, '\"client.default_max_age\"');\n const now = epochTime() + getClockSkew(client);\n const tolerance = getClockTolerance(client);\n if (claims.auth_time + client.default_max_age < now - tolerance) {\n throw OPE('too much time has elapsed since the last End-User authentication', JWT_TIMESTAMP_CHECK, { claims, now, tolerance, claim: 'auth_time' });\n }\n }\n if (claims.nonce !== undefined) {\n throw OPE('unexpected ID Token \"nonce\" claim value', JWT_CLAIM_COMPARISON, {\n expected: undefined,\n claims,\n claim: 'nonce',\n });\n }\n }\n return result;\n}\nexport const WWW_AUTHENTICATE_CHALLENGE = 'OAUTH_WWW_AUTHENTICATE_CHALLENGE';\nexport const RESPONSE_BODY_ERROR = 'OAUTH_RESPONSE_BODY_ERROR';\nexport const UNSUPPORTED_OPERATION = 'OAUTH_UNSUPPORTED_OPERATION';\nexport const AUTHORIZATION_RESPONSE_ERROR = 'OAUTH_AUTHORIZATION_RESPONSE_ERROR';\nexport const JWT_USERINFO_EXPECTED = 'OAUTH_JWT_USERINFO_EXPECTED';\nexport const PARSE_ERROR = 'OAUTH_PARSE_ERROR';\nexport const INVALID_RESPONSE = 'OAUTH_INVALID_RESPONSE';\nexport const INVALID_REQUEST = 'OAUTH_INVALID_REQUEST';\nexport const RESPONSE_IS_NOT_JSON = 'OAUTH_RESPONSE_IS_NOT_JSON';\nexport const RESPONSE_IS_NOT_CONFORM = 'OAUTH_RESPONSE_IS_NOT_CONFORM';\nexport const HTTP_REQUEST_FORBIDDEN = 'OAUTH_HTTP_REQUEST_FORBIDDEN';\nexport const REQUEST_PROTOCOL_FORBIDDEN = 'OAUTH_REQUEST_PROTOCOL_FORBIDDEN';\nexport const JWT_TIMESTAMP_CHECK = 'OAUTH_JWT_TIMESTAMP_CHECK_FAILED';\nexport const JWT_CLAIM_COMPARISON = 'OAUTH_JWT_CLAIM_COMPARISON_FAILED';\nexport const JSON_ATTRIBUTE_COMPARISON = 'OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED';\nexport const KEY_SELECTION = 'OAUTH_KEY_SELECTION_FAILED';\nexport const MISSING_SERVER_METADATA = 'OAUTH_MISSING_SERVER_METADATA';\nexport const INVALID_SERVER_METADATA = 'OAUTH_INVALID_SERVER_METADATA';\nfunction checkJwtType(expected, result) {\n if (typeof result.header.typ !== 'string' || normalizeTyp(result.header.typ) !== expected) {\n throw OPE('unexpected JWT \"typ\" header parameter value', INVALID_RESPONSE, {\n header: result.header,\n });\n }\n return result;\n}\nexport async function clientCredentialsGrantRequest(as, client, clientAuthentication, parameters, options) {\n assertAs(as);\n assertClient(client);\n return tokenEndpointRequest(as, client, clientAuthentication, 'client_credentials', new URLSearchParams(parameters), options);\n}\nexport async function genericTokenEndpointRequest(as, client, clientAuthentication, grantType, parameters, options) {\n assertAs(as);\n assertClient(client);\n assertString(grantType, '\"grantType\"');\n return tokenEndpointRequest(as, client, clientAuthentication, grantType, new URLSearchParams(parameters), options);\n}\nexport async function processGenericTokenEndpointResponse(as, client, response, options) {\n return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);\n}\nexport async function processClientCredentialsResponse(as, client, response, options) {\n return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);\n}\nexport async function revocationRequest(as, client, clientAuthentication, token, options) {\n assertAs(as);\n assertClient(client);\n assertString(token, '\"token\"');\n const url = resolveEndpoint(as, 'revocation_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n const body = new URLSearchParams(options?.additionalParameters);\n body.set('token', token);\n const headers = prepareHeaders(options?.headers);\n headers.delete('accept');\n return authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);\n}\nexport async function processRevocationResponse(response) {\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n await checkOAuthBodyError(response, 200, 'Revocation Endpoint');\n return undefined;\n}\nfunction assertReadableResponse(response) {\n if (response.bodyUsed) {\n throw CodedTypeError('\"response\" body has been used already', ERR_INVALID_ARG_VALUE);\n }\n}\nexport async function introspectionRequest(as, client, clientAuthentication, token, options) {\n assertAs(as);\n assertClient(client);\n assertString(token, '\"token\"');\n const url = resolveEndpoint(as, 'introspection_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n const body = new URLSearchParams(options?.additionalParameters);\n body.set('token', token);\n const headers = prepareHeaders(options?.headers);\n if (options?.requestJwtResponse ?? client.introspection_signed_response_alg) {\n headers.set('accept', 'application/token-introspection+jwt');\n }\n else {\n headers.set('accept', 'application/json');\n }\n return authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);\n}\nexport async function processIntrospectionResponse(as, client, response, options) {\n assertAs(as);\n assertClient(client);\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n await checkOAuthBodyError(response, 200, 'Introspection Endpoint');\n let json;\n if (getContentType(response) === 'application/token-introspection+jwt') {\n assertReadableResponse(response);\n const { claims, jwt } = await validateJwt(await response.text(), checkSigningAlgorithm.bind(undefined, client.introspection_signed_response_alg, as.introspection_signing_alg_values_supported, 'RS256'), getClockSkew(client), getClockTolerance(client), options?.[jweDecrypt])\n .then(checkJwtType.bind(undefined, 'token-introspection+jwt'))\n .then(validatePresence.bind(undefined, ['aud', 'iat', 'iss']))\n .then(validateIssuer.bind(undefined, as))\n .then(validateAudience.bind(undefined, client.client_id));\n jwtRefs.set(response, jwt);\n if (!isJsonObject(claims.token_introspection)) {\n throw OPE('JWT \"token_introspection\" claim must be a JSON object', INVALID_RESPONSE, {\n claims,\n });\n }\n json = claims.token_introspection;\n }\n else {\n assertReadableResponse(response);\n json = await getResponseJsonBody(response);\n }\n if (typeof json.active !== 'boolean') {\n throw OPE('\"response\" body \"active\" property must be a boolean', INVALID_RESPONSE, {\n body: json,\n });\n }\n return json;\n}\nasync function jwksRequest(as, options) {\n assertAs(as);\n const url = resolveEndpoint(as, 'jwks_uri', false, options?.[allowInsecureRequests] !== true);\n const headers = prepareHeaders(options?.headers);\n headers.set('accept', 'application/json');\n headers.append('accept', 'application/jwk-set+json');\n return (options?.[customFetch] || fetch)(url.href, {\n body: undefined,\n headers: Object.fromEntries(headers.entries()),\n method: 'GET',\n redirect: 'manual',\n signal: signal(url, options?.signal),\n });\n}\nasync function processJwksResponse(response) {\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n if (response.status !== 200) {\n throw OPE('\"response\" is not a conform JSON Web Key Set response (unexpected HTTP status code)', RESPONSE_IS_NOT_CONFORM, response);\n }\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response, (response) => assertContentTypes(response, 'application/json', 'application/jwk-set+json'));\n if (!Array.isArray(json.keys)) {\n throw OPE('\"response\" body \"keys\" property must be an array', INVALID_RESPONSE, { body: json });\n }\n if (!Array.prototype.every.call(json.keys, isJsonObject)) {\n throw OPE('\"response\" body \"keys\" property members must be JWK formatted objects', INVALID_RESPONSE, { body: json });\n }\n return json;\n}\nfunction supported(alg) {\n switch (alg) {\n case 'PS256':\n case 'ES256':\n case 'RS256':\n case 'PS384':\n case 'ES384':\n case 'RS384':\n case 'PS512':\n case 'ES512':\n case 'RS512':\n case 'Ed25519':\n case 'EdDSA':\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n return true;\n default:\n return false;\n }\n}\nfunction checkSupportedJwsAlg(header) {\n if (!supported(header.alg)) {\n throw new UnsupportedOperationError('unsupported JWS \"alg\" identifier', {\n cause: { alg: header.alg },\n });\n }\n}\nfunction checkRsaKeyAlgorithm(key) {\n const { algorithm } = key;\n if (typeof algorithm.modulusLength !== 'number' || algorithm.modulusLength < 2048) {\n throw new UnsupportedOperationError(`unsupported ${algorithm.name} modulusLength`, {\n cause: key,\n });\n }\n}\nfunction ecdsaHashName(key) {\n const { algorithm } = key;\n switch (algorithm.namedCurve) {\n case 'P-256':\n return 'SHA-256';\n case 'P-384':\n return 'SHA-384';\n case 'P-521':\n return 'SHA-512';\n default:\n throw new UnsupportedOperationError('unsupported ECDSA namedCurve', { cause: key });\n }\n}\nfunction keyToSubtle(key) {\n switch (key.algorithm.name) {\n case 'ECDSA':\n return {\n name: key.algorithm.name,\n hash: ecdsaHashName(key),\n };\n case 'RSA-PSS': {\n checkRsaKeyAlgorithm(key);\n switch (key.algorithm.hash.name) {\n case 'SHA-256':\n case 'SHA-384':\n case 'SHA-512':\n return {\n name: key.algorithm.name,\n saltLength: parseInt(key.algorithm.hash.name.slice(-3), 10) >> 3,\n };\n default:\n throw new UnsupportedOperationError('unsupported RSA-PSS hash name', { cause: key });\n }\n }\n case 'RSASSA-PKCS1-v1_5':\n checkRsaKeyAlgorithm(key);\n return key.algorithm.name;\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n case 'Ed25519':\n return key.algorithm.name;\n }\n throw new UnsupportedOperationError('unsupported CryptoKey algorithm name', { cause: key });\n}\nasync function validateJwsSignature(protectedHeader, payload, key, signature) {\n const data = buf(`${protectedHeader}.${payload}`);\n const algorithm = keyToSubtle(key);\n const verified = await crypto.subtle.verify(algorithm, key, signature, data);\n if (!verified) {\n throw OPE('JWT signature verification failed', INVALID_RESPONSE, {\n key,\n data,\n signature,\n algorithm,\n });\n }\n}\nasync function validateJwt(jws, checkAlg, clockSkew, clockTolerance, decryptJwt) {\n let { 0: protectedHeader, 1: payload, length } = jws.split('.');\n if (length === 5) {\n if (decryptJwt !== undefined) {\n jws = await decryptJwt(jws);\n ({ 0: protectedHeader, 1: payload, length } = jws.split('.'));\n }\n else {\n throw new UnsupportedOperationError('JWE decryption is not configured', { cause: jws });\n }\n }\n if (length !== 3) {\n throw OPE('Invalid JWT', INVALID_RESPONSE, jws);\n }\n let header;\n try {\n header = JSON.parse(buf(b64u(protectedHeader)));\n }\n catch (cause) {\n throw OPE('failed to parse JWT Header body as base64url encoded JSON', PARSE_ERROR, cause);\n }\n if (!isJsonObject(header)) {\n throw OPE('JWT Header must be a top level object', INVALID_RESPONSE, jws);\n }\n checkAlg(header);\n if (header.crit !== undefined) {\n throw new UnsupportedOperationError('no JWT \"crit\" header parameter extensions are supported', {\n cause: { header },\n });\n }\n let claims;\n try {\n claims = JSON.parse(buf(b64u(payload)));\n }\n catch (cause) {\n throw OPE('failed to parse JWT Payload body as base64url encoded JSON', PARSE_ERROR, cause);\n }\n if (!isJsonObject(claims)) {\n throw OPE('JWT Payload must be a top level object', INVALID_RESPONSE, jws);\n }\n const now = epochTime() + clockSkew;\n if (claims.exp !== undefined) {\n if (typeof claims.exp !== 'number') {\n throw OPE('unexpected JWT \"exp\" (expiration time) claim type', INVALID_RESPONSE, { claims });\n }\n if (claims.exp <= now - clockTolerance) {\n throw OPE('unexpected JWT \"exp\" (expiration time) claim value, expiration is past current timestamp', JWT_TIMESTAMP_CHECK, { claims, now, tolerance: clockTolerance, claim: 'exp' });\n }\n }\n if (claims.iat !== undefined) {\n if (typeof claims.iat !== 'number') {\n throw OPE('unexpected JWT \"iat\" (issued at) claim type', INVALID_RESPONSE, { claims });\n }\n }\n if (claims.iss !== undefined) {\n if (typeof claims.iss !== 'string') {\n throw OPE('unexpected JWT \"iss\" (issuer) claim type', INVALID_RESPONSE, { claims });\n }\n }\n if (claims.nbf !== undefined) {\n if (typeof claims.nbf !== 'number') {\n throw OPE('unexpected JWT \"nbf\" (not before) claim type', INVALID_RESPONSE, { claims });\n }\n if (claims.nbf > now + clockTolerance) {\n throw OPE('unexpected JWT \"nbf\" (not before) claim value', JWT_TIMESTAMP_CHECK, {\n claims,\n now,\n tolerance: clockTolerance,\n claim: 'nbf',\n });\n }\n }\n if (claims.aud !== undefined) {\n if (typeof claims.aud !== 'string' && !Array.isArray(claims.aud)) {\n throw OPE('unexpected JWT \"aud\" (audience) claim type', INVALID_RESPONSE, { claims });\n }\n }\n return { header, claims, jwt: jws };\n}\nexport async function validateJwtAuthResponse(as, client, parameters, expectedState, options) {\n assertAs(as);\n assertClient(client);\n if (parameters instanceof URL) {\n parameters = parameters.searchParams;\n }\n if (!(parameters instanceof URLSearchParams)) {\n throw CodedTypeError('\"parameters\" must be an instance of URLSearchParams, or URL', ERR_INVALID_ARG_TYPE);\n }\n const response = getURLSearchParameter(parameters, 'response');\n if (!response) {\n throw OPE('\"parameters\" does not contain a JARM response', INVALID_RESPONSE);\n }\n const { claims, header, jwt } = await validateJwt(response, checkSigningAlgorithm.bind(undefined, client.authorization_signed_response_alg, as.authorization_signing_alg_values_supported, 'RS256'), getClockSkew(client), getClockTolerance(client), options?.[jweDecrypt])\n .then(validatePresence.bind(undefined, ['aud', 'exp', 'iss']))\n .then(validateIssuer.bind(undefined, as))\n .then(validateAudience.bind(undefined, client.client_id));\n const { 0: protectedHeader, 1: payload, 2: encodedSignature } = jwt.split('.');\n const signature = b64u(encodedSignature);\n const key = await getPublicSigKeyFromIssuerJwksUri(as, options, header);\n await validateJwsSignature(protectedHeader, payload, key, signature);\n const result = new URLSearchParams();\n for (const [key, value] of Object.entries(claims)) {\n if (typeof value === 'string' && key !== 'aud') {\n result.set(key, value);\n }\n }\n return validateAuthResponse(as, client, result, expectedState);\n}\nasync function idTokenHash(data, header, claimName) {\n let algorithm;\n switch (header.alg) {\n case 'RS256':\n case 'PS256':\n case 'ES256':\n algorithm = 'SHA-256';\n break;\n case 'RS384':\n case 'PS384':\n case 'ES384':\n algorithm = 'SHA-384';\n break;\n case 'RS512':\n case 'PS512':\n case 'ES512':\n case 'Ed25519':\n case 'EdDSA':\n algorithm = 'SHA-512';\n break;\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n algorithm = { name: 'cSHAKE256', length: 512 };\n break;\n default:\n throw new UnsupportedOperationError(`unsupported JWS algorithm for ${claimName} calculation`, { cause: { alg: header.alg } });\n }\n const digest = await crypto.subtle.digest(algorithm, buf(data));\n return b64u(digest.slice(0, digest.byteLength / 2));\n}\nasync function idTokenHashMatches(data, actual, header, claimName) {\n const expected = await idTokenHash(data, header, claimName);\n return actual === expected;\n}\nexport async function validateDetachedSignatureResponse(as, client, parameters, expectedNonce, expectedState, maxAge, options) {\n return validateHybridResponse(as, client, parameters, expectedNonce, expectedState, maxAge, options, true);\n}\nexport async function validateCodeIdTokenResponse(as, client, parameters, expectedNonce, expectedState, maxAge, options) {\n return validateHybridResponse(as, client, parameters, expectedNonce, expectedState, maxAge, options, false);\n}\nasync function consumeStream(request) {\n if (request.bodyUsed) {\n throw CodedTypeError('form_post Request instances must contain a readable body', ERR_INVALID_ARG_VALUE, { cause: request });\n }\n return request.text();\n}\nexport async function formPostResponse(request) {\n if (request.method !== 'POST') {\n throw CodedTypeError('form_post responses are expected to use the POST method', ERR_INVALID_ARG_VALUE, { cause: request });\n }\n if (getContentType(request) !== 'application/x-www-form-urlencoded') {\n throw CodedTypeError('form_post responses are expected to use the application/x-www-form-urlencoded content-type', ERR_INVALID_ARG_VALUE, { cause: request });\n }\n return consumeStream(request);\n}\nasync function validateHybridResponse(as, client, parameters, expectedNonce, expectedState, maxAge, options, fapi) {\n assertAs(as);\n assertClient(client);\n if (parameters instanceof URL) {\n if (!parameters.hash.length) {\n throw CodedTypeError('\"parameters\" as an instance of URL must contain a hash (fragment) with the Authorization Response parameters', ERR_INVALID_ARG_VALUE);\n }\n parameters = new URLSearchParams(parameters.hash.slice(1));\n }\n else if (looseInstanceOf(parameters, Request)) {\n parameters = new URLSearchParams(await formPostResponse(parameters));\n }\n else if (parameters instanceof URLSearchParams) {\n parameters = new URLSearchParams(parameters);\n }\n else {\n throw CodedTypeError('\"parameters\" must be an instance of URLSearchParams, URL, or Response', ERR_INVALID_ARG_TYPE);\n }\n const id_token = getURLSearchParameter(parameters, 'id_token');\n parameters.delete('id_token');\n switch (expectedState) {\n case undefined:\n case expectNoState:\n break;\n default:\n assertString(expectedState, '\"expectedState\" argument');\n }\n const result = validateAuthResponse({\n ...as,\n authorization_response_iss_parameter_supported: false,\n }, client, parameters, expectedState);\n if (!id_token) {\n throw OPE('\"parameters\" does not contain an ID Token', INVALID_RESPONSE);\n }\n const code = getURLSearchParameter(parameters, 'code');\n if (!code) {\n throw OPE('\"parameters\" does not contain an Authorization Code', INVALID_RESPONSE);\n }\n const requiredClaims = [\n 'aud',\n 'exp',\n 'iat',\n 'iss',\n 'sub',\n 'nonce',\n 'c_hash',\n ];\n const state = parameters.get('state');\n if (fapi && (typeof expectedState === 'string' || state !== null)) {\n requiredClaims.push('s_hash');\n }\n if (maxAge !== undefined) {\n assertNumber(maxAge, true, '\"maxAge\" argument');\n }\n else if (client.default_max_age !== undefined) {\n assertNumber(client.default_max_age, true, '\"client.default_max_age\"');\n }\n maxAge ??= client.default_max_age ?? skipAuthTimeCheck;\n if (client.require_auth_time || maxAge !== skipAuthTimeCheck) {\n requiredClaims.push('auth_time');\n }\n const { claims, header, jwt } = await validateJwt(id_token, checkSigningAlgorithm.bind(undefined, client.id_token_signed_response_alg, as.id_token_signing_alg_values_supported, 'RS256'), getClockSkew(client), getClockTolerance(client), options?.[jweDecrypt])\n .then(validatePresence.bind(undefined, requiredClaims))\n .then(validateIssuer.bind(undefined, as))\n .then(validateAudience.bind(undefined, client.client_id));\n const clockSkew = getClockSkew(client);\n const now = epochTime() + clockSkew;\n if (claims.iat < now - 3600) {\n throw OPE('unexpected JWT \"iat\" (issued at) claim value, it is too far in the past', JWT_TIMESTAMP_CHECK, { now, claims, claim: 'iat' });\n }\n assertString(claims.c_hash, 'ID Token \"c_hash\" (code hash) claim value', INVALID_RESPONSE, {\n claims,\n });\n if (claims.auth_time !== undefined) {\n assertNumber(claims.auth_time, true, 'ID Token \"auth_time\" (authentication time)', INVALID_RESPONSE, { claims });\n }\n if (maxAge !== skipAuthTimeCheck) {\n const now = epochTime() + getClockSkew(client);\n const tolerance = getClockTolerance(client);\n if (claims.auth_time + maxAge < now - tolerance) {\n throw OPE('too much time has elapsed since the last End-User authentication', JWT_TIMESTAMP_CHECK, { claims, now, tolerance, claim: 'auth_time' });\n }\n }\n assertString(expectedNonce, '\"expectedNonce\" argument');\n if (claims.nonce !== expectedNonce) {\n throw OPE('unexpected ID Token \"nonce\" claim value', JWT_CLAIM_COMPARISON, {\n expected: expectedNonce,\n claims,\n claim: 'nonce',\n });\n }\n if (Array.isArray(claims.aud) && claims.aud.length !== 1) {\n if (claims.azp === undefined) {\n throw OPE('ID Token \"aud\" (audience) claim includes additional untrusted audiences', JWT_CLAIM_COMPARISON, { claims, claim: 'aud' });\n }\n if (claims.azp !== client.client_id) {\n throw OPE('unexpected ID Token \"azp\" (authorized party) claim value', JWT_CLAIM_COMPARISON, {\n expected: client.client_id,\n claims,\n claim: 'azp',\n });\n }\n }\n const { 0: protectedHeader, 1: payload, 2: encodedSignature } = jwt.split('.');\n const signature = b64u(encodedSignature);\n const key = await getPublicSigKeyFromIssuerJwksUri(as, options, header);\n await validateJwsSignature(protectedHeader, payload, key, signature);\n if ((await idTokenHashMatches(code, claims.c_hash, header, 'c_hash')) !== true) {\n throw OPE('invalid ID Token \"c_hash\" (code hash) claim value', JWT_CLAIM_COMPARISON, {\n code,\n alg: header.alg,\n claim: 'c_hash',\n claims,\n });\n }\n if ((fapi && state !== null) || claims.s_hash !== undefined) {\n assertString(claims.s_hash, 'ID Token \"s_hash\" (state hash) claim value', INVALID_RESPONSE, {\n claims,\n });\n assertString(state, '\"state\" response parameter', INVALID_RESPONSE, { parameters });\n if ((await idTokenHashMatches(state, claims.s_hash, header, 's_hash')) !== true) {\n throw OPE('invalid ID Token \"s_hash\" (state hash) claim value', JWT_CLAIM_COMPARISON, {\n state,\n alg: header.alg,\n claim: 's_hash',\n claims,\n });\n }\n }\n return result;\n}\nfunction checkSigningAlgorithm(client, issuer, fallback, header) {\n if (client !== undefined) {\n if (typeof client === 'string' ? header.alg !== client : !client.includes(header.alg)) {\n throw OPE('unexpected JWT \"alg\" header parameter', INVALID_RESPONSE, {\n header,\n expected: client,\n reason: 'client configuration',\n });\n }\n return;\n }\n if (Array.isArray(issuer)) {\n if (!issuer.includes(header.alg)) {\n throw OPE('unexpected JWT \"alg\" header parameter', INVALID_RESPONSE, {\n header,\n expected: issuer,\n reason: 'authorization server metadata',\n });\n }\n return;\n }\n if (fallback !== undefined) {\n if (typeof fallback === 'string'\n ? header.alg !== fallback\n : typeof fallback === 'function'\n ? !fallback(header.alg)\n : !fallback.includes(header.alg)) {\n throw OPE('unexpected JWT \"alg\" header parameter', INVALID_RESPONSE, {\n header,\n expected: fallback,\n reason: 'default value',\n });\n }\n return;\n }\n throw OPE('missing client or server configuration to verify used JWT \"alg\" header parameter', undefined, { client, issuer, fallback });\n}\nfunction getURLSearchParameter(parameters, name) {\n const { 0: value, length } = parameters.getAll(name);\n if (length > 1) {\n throw OPE(`\"${name}\" parameter must be provided only once`, INVALID_RESPONSE);\n }\n return value;\n}\nexport const skipStateCheck = Symbol();\nexport const expectNoState = Symbol();\nexport function validateAuthResponse(as, client, parameters, expectedState) {\n assertAs(as);\n assertClient(client);\n if (parameters instanceof URL) {\n parameters = parameters.searchParams;\n }\n if (!(parameters instanceof URLSearchParams)) {\n throw CodedTypeError('\"parameters\" must be an instance of URLSearchParams, or URL', ERR_INVALID_ARG_TYPE);\n }\n if (getURLSearchParameter(parameters, 'response')) {\n throw OPE('\"parameters\" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()', INVALID_RESPONSE, { parameters });\n }\n const iss = getURLSearchParameter(parameters, 'iss');\n const state = getURLSearchParameter(parameters, 'state');\n if (!iss && as.authorization_response_iss_parameter_supported) {\n throw OPE('response parameter \"iss\" (issuer) missing', INVALID_RESPONSE, { parameters });\n }\n if (iss && iss !== as.issuer) {\n throw OPE('unexpected \"iss\" (issuer) response parameter value', INVALID_RESPONSE, {\n expected: as.issuer,\n parameters,\n });\n }\n switch (expectedState) {\n case undefined:\n case expectNoState:\n if (state !== undefined) {\n throw OPE('unexpected \"state\" response parameter encountered', INVALID_RESPONSE, {\n expected: undefined,\n parameters,\n });\n }\n break;\n case skipStateCheck:\n break;\n default:\n assertString(expectedState, '\"expectedState\" argument');\n if (state !== expectedState) {\n throw OPE(state === undefined\n ? 'response parameter \"state\" missing'\n : 'unexpected \"state\" response parameter value', INVALID_RESPONSE, { expected: expectedState, parameters });\n }\n }\n const error = getURLSearchParameter(parameters, 'error');\n if (error) {\n throw new AuthorizationResponseError('authorization response from the server is an error', {\n cause: parameters,\n });\n }\n const id_token = getURLSearchParameter(parameters, 'id_token');\n const token = getURLSearchParameter(parameters, 'token');\n if (id_token !== undefined || token !== undefined) {\n throw new UnsupportedOperationError('implicit and hybrid flows are not supported');\n }\n return brand(new URLSearchParams(parameters));\n}\nfunction algToSubtle(alg) {\n switch (alg) {\n case 'PS256':\n case 'PS384':\n case 'PS512':\n return { name: 'RSA-PSS', hash: `SHA-${alg.slice(-3)}` };\n case 'RS256':\n case 'RS384':\n case 'RS512':\n return { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${alg.slice(-3)}` };\n case 'ES256':\n case 'ES384':\n return { name: 'ECDSA', namedCurve: `P-${alg.slice(-3)}` };\n case 'ES512':\n return { name: 'ECDSA', namedCurve: 'P-521' };\n case 'EdDSA':\n return 'Ed25519';\n case 'Ed25519':\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n return alg;\n default:\n throw new UnsupportedOperationError('unsupported JWS algorithm', { cause: { alg } });\n }\n}\nasync function importJwk(alg, jwk) {\n const { ext, key_ops, use, ...key } = jwk;\n return crypto.subtle.importKey('jwk', key, algToSubtle(alg), true, ['verify']);\n}\nexport async function deviceAuthorizationRequest(as, client, clientAuthentication, parameters, options) {\n assertAs(as);\n assertClient(client);\n const url = resolveEndpoint(as, 'device_authorization_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n const body = new URLSearchParams(parameters);\n body.set('client_id', client.client_id);\n const headers = prepareHeaders(options?.headers);\n headers.set('accept', 'application/json');\n return authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);\n}\nexport async function processDeviceAuthorizationResponse(as, client, response) {\n assertAs(as);\n assertClient(client);\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n await checkOAuthBodyError(response, 200, 'Device Authorization Endpoint');\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response);\n assertString(json.device_code, '\"response\" body \"device_code\" property', INVALID_RESPONSE, {\n body: json,\n });\n assertString(json.user_code, '\"response\" body \"user_code\" property', INVALID_RESPONSE, {\n body: json,\n });\n assertString(json.verification_uri, '\"response\" body \"verification_uri\" property', INVALID_RESPONSE, { body: json });\n let expiresIn = typeof json.expires_in !== 'number' ? parseFloat(json.expires_in) : json.expires_in;\n assertNumber(expiresIn, true, '\"response\" body \"expires_in\" property', INVALID_RESPONSE, {\n body: json,\n });\n json.expires_in = expiresIn;\n if (json.verification_uri_complete !== undefined) {\n assertString(json.verification_uri_complete, '\"response\" body \"verification_uri_complete\" property', INVALID_RESPONSE, { body: json });\n }\n if (json.interval !== undefined) {\n assertNumber(json.interval, false, '\"response\" body \"interval\" property', INVALID_RESPONSE, {\n body: json,\n });\n }\n return json;\n}\nexport async function deviceCodeGrantRequest(as, client, clientAuthentication, deviceCode, options) {\n assertAs(as);\n assertClient(client);\n assertString(deviceCode, '\"deviceCode\"');\n const parameters = new URLSearchParams(options?.additionalParameters);\n parameters.set('device_code', deviceCode);\n return tokenEndpointRequest(as, client, clientAuthentication, 'urn:ietf:params:oauth:grant-type:device_code', parameters, options);\n}\nexport async function processDeviceCodeResponse(as, client, response, options) {\n return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);\n}\nexport async function generateKeyPair(alg, options) {\n assertString(alg, '\"alg\"');\n const algorithm = algToSubtle(alg);\n if (alg.startsWith('PS') || alg.startsWith('RS')) {\n Object.assign(algorithm, {\n modulusLength: options?.modulusLength ?? 2048,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n });\n }\n return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, [\n 'sign',\n 'verify',\n ]);\n}\nfunction normalizeHtu(htu) {\n const url = new URL(htu);\n url.search = '';\n url.hash = '';\n return url.href;\n}\nasync function validateDPoP(request, accessToken, accessTokenClaims, options) {\n const headerValue = request.headers.get('dpop');\n if (headerValue === null) {\n throw OPE('operation indicated DPoP use but the request has no DPoP HTTP Header', INVALID_REQUEST, { headers: request.headers });\n }\n if (request.headers.get('authorization')?.toLowerCase().startsWith('dpop ') === false) {\n throw OPE(`operation indicated DPoP use but the request's Authorization HTTP Header scheme is not DPoP`, INVALID_REQUEST, { headers: request.headers });\n }\n if (typeof accessTokenClaims.cnf?.jkt !== 'string') {\n throw OPE('operation indicated DPoP use but the JWT Access Token has no jkt confirmation claim', INVALID_REQUEST, { claims: accessTokenClaims });\n }\n const clockSkew = getClockSkew(options);\n const proof = await validateJwt(headerValue, checkSigningAlgorithm.bind(undefined, options?.signingAlgorithms, undefined, supported), clockSkew, getClockTolerance(options), undefined)\n .then(checkJwtType.bind(undefined, 'dpop+jwt'))\n .then(validatePresence.bind(undefined, ['iat', 'jti', 'ath', 'htm', 'htu']));\n const now = epochTime() + clockSkew;\n const diff = Math.abs(now - proof.claims.iat);\n if (diff > 300) {\n throw OPE('DPoP Proof iat is not recent enough', JWT_TIMESTAMP_CHECK, {\n now,\n claims: proof.claims,\n claim: 'iat',\n });\n }\n if (proof.claims.htm !== request.method) {\n throw OPE('DPoP Proof htm mismatch', JWT_CLAIM_COMPARISON, {\n expected: request.method,\n claims: proof.claims,\n claim: 'htm',\n });\n }\n if (typeof proof.claims.htu !== 'string' ||\n normalizeHtu(proof.claims.htu) !== normalizeHtu(request.url)) {\n throw OPE('DPoP Proof htu mismatch', JWT_CLAIM_COMPARISON, {\n expected: normalizeHtu(request.url),\n claims: proof.claims,\n claim: 'htu',\n });\n }\n {\n const expected = b64u(await crypto.subtle.digest('SHA-256', buf(accessToken)));\n if (proof.claims.ath !== expected) {\n throw OPE('DPoP Proof ath mismatch', JWT_CLAIM_COMPARISON, {\n expected,\n claims: proof.claims,\n claim: 'ath',\n });\n }\n }\n {\n const expected = await calculateJwkThumbprint(proof.header.jwk);\n if (accessTokenClaims.cnf.jkt !== expected) {\n throw OPE('JWT Access Token confirmation mismatch', JWT_CLAIM_COMPARISON, {\n expected,\n claims: accessTokenClaims,\n claim: 'cnf.jkt',\n });\n }\n }\n const { 0: protectedHeader, 1: payload, 2: encodedSignature } = headerValue.split('.');\n const signature = b64u(encodedSignature);\n const { jwk, alg } = proof.header;\n if (!jwk) {\n throw OPE('DPoP Proof is missing the jwk header parameter', INVALID_REQUEST, {\n header: proof.header,\n });\n }\n const key = await importJwk(alg, jwk);\n if (key.type !== 'public') {\n throw OPE('DPoP Proof jwk header parameter must contain a public key', INVALID_REQUEST, {\n header: proof.header,\n });\n }\n await validateJwsSignature(protectedHeader, payload, key, signature);\n}\nexport async function validateJwtAccessToken(as, request, expectedAudience, options) {\n assertAs(as);\n if (!looseInstanceOf(request, Request)) {\n throw CodedTypeError('\"request\" must be an instance of Request', ERR_INVALID_ARG_TYPE);\n }\n assertString(expectedAudience, '\"expectedAudience\"');\n const authorization = request.headers.get('authorization');\n if (authorization === null) {\n throw OPE('\"request\" is missing an Authorization HTTP Header', INVALID_REQUEST, {\n headers: request.headers,\n });\n }\n let { 0: scheme, 1: accessToken, length } = authorization.split(' ');\n scheme = scheme.toLowerCase();\n switch (scheme) {\n case 'dpop':\n case 'bearer':\n break;\n default:\n throw new UnsupportedOperationError('unsupported Authorization HTTP Header scheme', {\n cause: { headers: request.headers },\n });\n }\n if (length !== 2) {\n throw OPE('invalid Authorization HTTP Header format', INVALID_REQUEST, {\n headers: request.headers,\n });\n }\n const requiredClaims = [\n 'iss',\n 'exp',\n 'aud',\n 'sub',\n 'iat',\n 'jti',\n 'client_id',\n ];\n if (options?.requireDPoP || scheme === 'dpop' || request.headers.has('dpop')) {\n requiredClaims.push('cnf');\n }\n const { claims, header } = await validateJwt(accessToken, checkSigningAlgorithm.bind(undefined, options?.signingAlgorithms, undefined, supported), getClockSkew(options), getClockTolerance(options), undefined)\n .then(checkJwtType.bind(undefined, 'at+jwt'))\n .then(validatePresence.bind(undefined, requiredClaims))\n .then(validateIssuer.bind(undefined, as))\n .then(validateAudience.bind(undefined, expectedAudience))\n .catch(reassignRSCode);\n for (const claim of ['client_id', 'jti', 'sub']) {\n if (typeof claims[claim] !== 'string') {\n throw OPE(`unexpected JWT \"${claim}\" claim type`, INVALID_REQUEST, { claims });\n }\n }\n if ('cnf' in claims) {\n if (!isJsonObject(claims.cnf)) {\n throw OPE('unexpected JWT \"cnf\" (confirmation) claim value', INVALID_REQUEST, { claims });\n }\n const { 0: cnf, length } = Object.keys(claims.cnf);\n if (length) {\n if (length !== 1) {\n throw new UnsupportedOperationError('multiple confirmation claims are not supported', {\n cause: { claims },\n });\n }\n if (cnf !== 'jkt') {\n throw new UnsupportedOperationError('unsupported JWT Confirmation method', {\n cause: { claims },\n });\n }\n }\n }\n const { 0: protectedHeader, 1: payload, 2: encodedSignature } = accessToken.split('.');\n const signature = b64u(encodedSignature);\n const key = await getPublicSigKeyFromIssuerJwksUri(as, options, header);\n await validateJwsSignature(protectedHeader, payload, key, signature);\n if (options?.requireDPoP ||\n scheme === 'dpop' ||\n claims.cnf?.jkt !== undefined ||\n request.headers.has('dpop')) {\n await validateDPoP(request, accessToken, claims, options).catch(reassignRSCode);\n }\n return claims;\n}\nfunction reassignRSCode(err) {\n if (err instanceof OperationProcessingError && err?.code === INVALID_REQUEST) {\n err.code = INVALID_RESPONSE;\n }\n throw err;\n}\nexport async function backchannelAuthenticationRequest(as, client, clientAuthentication, parameters, options) {\n assertAs(as);\n assertClient(client);\n const url = resolveEndpoint(as, 'backchannel_authentication_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n const body = new URLSearchParams(parameters);\n body.set('client_id', client.client_id);\n const headers = prepareHeaders(options?.headers);\n headers.set('accept', 'application/json');\n return authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);\n}\nexport async function processBackchannelAuthenticationResponse(as, client, response) {\n assertAs(as);\n assertClient(client);\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n await checkOAuthBodyError(response, 200, 'Backchannel Authentication Endpoint');\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response);\n assertString(json.auth_req_id, '\"response\" body \"auth_req_id\" property', INVALID_RESPONSE, {\n body: json,\n });\n let expiresIn = typeof json.expires_in !== 'number' ? parseFloat(json.expires_in) : json.expires_in;\n assertNumber(expiresIn, true, '\"response\" body \"expires_in\" property', INVALID_RESPONSE, {\n body: json,\n });\n json.expires_in = expiresIn;\n if (json.interval !== undefined) {\n assertNumber(json.interval, false, '\"response\" body \"interval\" property', INVALID_RESPONSE, {\n body: json,\n });\n }\n return json;\n}\nexport async function backchannelAuthenticationGrantRequest(as, client, clientAuthentication, authReqId, options) {\n assertAs(as);\n assertClient(client);\n assertString(authReqId, '\"authReqId\"');\n const parameters = new URLSearchParams(options?.additionalParameters);\n parameters.set('auth_req_id', authReqId);\n return tokenEndpointRequest(as, client, clientAuthentication, 'urn:openid:params:grant-type:ciba', parameters, options);\n}\nexport async function processBackchannelAuthenticationGrantResponse(as, client, response, options) {\n return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);\n}\nexport async function dynamicClientRegistrationRequest(as, metadata, options) {\n assertAs(as);\n const url = resolveEndpoint(as, 'registration_endpoint', metadata.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n const headers = prepareHeaders(options?.headers);\n headers.set('accept', 'application/json');\n headers.set('content-type', 'application/json');\n const method = 'POST';\n if (options?.DPoP) {\n assertDPoP(options.DPoP);\n await options.DPoP.addProof(url, headers, method, options.initialAccessToken);\n }\n if (options?.initialAccessToken) {\n headers.set('authorization', `${headers.has('dpop') ? 'DPoP' : 'Bearer'} ${options.initialAccessToken}`);\n }\n const response = await (options?.[customFetch] || fetch)(url.href, {\n body: JSON.stringify(metadata),\n headers: Object.fromEntries(headers.entries()),\n method,\n redirect: 'manual',\n signal: signal(url, options?.signal),\n });\n options?.DPoP?.cacheNonce(response, url);\n return response;\n}\nexport async function processDynamicClientRegistrationResponse(response) {\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n await checkOAuthBodyError(response, 201, 'Dynamic Client Registration Endpoint');\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response);\n assertString(json.client_id, '\"response\" body \"client_id\" property', INVALID_RESPONSE, {\n body: json,\n });\n if (json.client_secret !== undefined) {\n assertString(json.client_secret, '\"response\" body \"client_secret\" property', INVALID_RESPONSE, {\n body: json,\n });\n }\n if (json.client_secret) {\n assertNumber(json.client_secret_expires_at, true, '\"response\" body \"client_secret_expires_at\" property', INVALID_RESPONSE, {\n body: json,\n });\n }\n return json;\n}\nexport async function resourceDiscoveryRequest(resourceIdentifier, options) {\n return performDiscovery(resourceIdentifier, 'resourceIdentifier', (url) => {\n prependWellKnown(url, '.well-known/oauth-protected-resource', true);\n return url;\n }, options);\n}\nexport async function processResourceDiscoveryResponse(expectedResourceIdentifier, response) {\n const expected = expectedResourceIdentifier;\n if (!(expected instanceof URL) && expected !== _nodiscoverycheck) {\n throw CodedTypeError('\"expectedResourceIdentifier\" must be an instance of URL', ERR_INVALID_ARG_TYPE);\n }\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n if (response.status !== 200) {\n throw OPE('\"response\" is not a conform Resource Server Metadata response (unexpected HTTP status code)', RESPONSE_IS_NOT_CONFORM, response);\n }\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response);\n assertString(json.resource, '\"response\" body \"resource\" property', INVALID_RESPONSE, {\n body: json,\n });\n if (expected !== _nodiscoverycheck && new URL(json.resource).href !== expected.href) {\n throw OPE('\"response\" body \"resource\" property does not match the expected value', JSON_ATTRIBUTE_COMPARISON, { expected: expected.href, body: json, attribute: 'resource' });\n }\n return json;\n}\nasync function getResponseJsonBody(response, check = assertApplicationJson) {\n let json;\n try {\n json = await response.json();\n }\n catch (cause) {\n check(response);\n throw OPE('failed to parse \"response\" body as JSON', PARSE_ERROR, cause);\n }\n if (!isJsonObject(json)) {\n throw OPE('\"response\" body must be a top level object', INVALID_RESPONSE, { body: json });\n }\n return json;\n}\nexport const _nopkce = nopkce;\nexport const _nodiscoverycheck = Symbol();\nexport const _expectedIssuer = Symbol();\n//# sourceMappingURL=index.js.map", "import * as oauth from 'oauth4webapi';\n\nimport * as yup from 'yup';\nimport { KnownError, KnownErrors } from '../known-errors';\nimport { inlineProductSchema } from '../schema-fields';\nimport { AccessToken, InternalSession, RefreshToken } from '../sessions';\nimport { generateSecureRandomString } from '../utils/crypto';\nimport { StackAssertionError, throwErr } from '../utils/errors';\nimport { globalVar } from '../utils/globals';\nimport { HTTP_METHODS, HttpMethod } from '../utils/http';\nimport { ReadonlyJson } from '../utils/json';\nimport { publishableClientKeyNotNecessarySentinel } from '../utils/oauth';\nimport { filterUndefined, filterUndefinedOrNull } from '../utils/objects';\nimport { AuthenticationResponseJSON, PublicKeyCredentialCreationOptionsJSON, PublicKeyCredentialRequestOptionsJSON, RegistrationResponseJSON } from '../utils/passkey';\nimport { wait } from '../utils/promises';\nimport { Result } from \"../utils/results\";\nimport { deindent } from '../utils/strings';\nimport { urlString } from '../utils/urls';\nimport { ConnectedAccountAccessTokenCrud, ConnectedAccountCrud } from './crud/connected-accounts';\nimport { ContactChannelsCrud } from './crud/contact-channels';\nimport { CurrentUserCrud } from './crud/current-user';\nimport { CustomerInvoicesListResponse, ListCustomerInvoicesOptions } from './crud/invoices';\nimport { ItemCrud } from './crud/items';\nimport { NotificationPreferenceCrud } from './crud/notification-preferences';\nimport { OAuthProviderCrud } from './crud/oauth-providers';\nimport { CustomerProductsListResponse, ListCustomerProductsOptions } from './crud/products';\nimport { TeamApiKeysCrud, UserApiKeysCrud, teamApiKeysCreateInputSchema, teamApiKeysCreateOutputSchema, userApiKeysCreateInputSchema, userApiKeysCreateOutputSchema } from './crud/project-api-keys';\nimport { ProjectPermissionsCrud } from './crud/project-permissions';\nimport { AdminUserProjectsCrud, ClientProjectsCrud } from './crud/projects';\nimport { SessionsCrud } from './crud/sessions';\nimport { TeamInvitationCrud } from './crud/team-invitation';\nimport { TeamMemberProfilesCrud } from './crud/team-member-profiles';\nimport { TeamPermissionsCrud } from './crud/team-permissions';\nimport { TeamsCrud } from './crud/teams';\n\nexport type ClientInterfaceOptions = {\n clientVersion: string,\n // This is a function instead of a string because it might be different based on the environment (for example client vs server)\n getBaseUrl: () => string,\n getAnalyticsBaseUrl?: () => string,\n extraRequestHeaders: Record<string, string>,\n projectId: string,\n prepareRequest?: () => Promise<void>,\n} & ({\n publishableClientKey?: string,\n} | {\n projectOwnerSession: InternalSession | (() => Promise<string | null>),\n});\n\nexport class StackClientInterface {\n private pendingNetworkDiagnostics?: ReturnType<StackClientInterface[\"_runNetworkDiagnosticsInner\"]>;\n\n constructor(public readonly options: ClientInterfaceOptions) {\n // nothing here\n }\n\n get projectId() {\n return this.options.projectId;\n }\n\n getApiUrl() {\n return this.options.getBaseUrl() + \"/api/v1\";\n }\n\n getAnalyticsApiUrl() {\n return (this.options.getAnalyticsBaseUrl ?? this.options.getBaseUrl)() + \"/api/v1\";\n }\n\n public async runNetworkDiagnostics(session?: InternalSession | null, requestType?: \"client\" | \"server\" | \"admin\") {\n if (this.pendingNetworkDiagnostics) {\n return await this.pendingNetworkDiagnostics;\n }\n\n this.pendingNetworkDiagnostics = this._runNetworkDiagnosticsInner(session, requestType);\n try {\n return await this.pendingNetworkDiagnostics;\n } finally {\n this.pendingNetworkDiagnostics = undefined;\n }\n }\n\n private async _runNetworkDiagnosticsInner(session?: InternalSession | null, requestType?: \"client\" | \"server\" | \"admin\") {\n const tryRequest = async (cb: () => Promise<void>) => {\n try {\n await cb();\n return \"OK\";\n } catch (e) {\n return `${e}`;\n }\n };\n const cfTrace = await tryRequest(async () => {\n const res = await fetch(\"https://1.1.1.1/cdn-cgi/trace\");\n if (!res.ok) {\n throw new Error(`${res.status} ${res.statusText}: ${await res.text()}`);\n }\n });\n const baseUrlBackend = await tryRequest(async () => {\n const res = await fetch(new URL(\"/health\", this.getApiUrl()));\n if (!res.ok) {\n throw new Error(`${res.status} ${res.statusText}: ${await res.text()}`);\n }\n });\n const prodDashboard = await tryRequest(async () => {\n const res = await fetch(\"https://app.stack-auth.com/health\");\n if (!res.ok) {\n throw new Error(`${res.status} ${res.statusText}: ${await res.text()}`);\n }\n });\n const prodBackend = await tryRequest(async () => {\n const res = await fetch(\"https://api.stack-auth.com/health\");\n if (!res.ok) {\n throw new Error(`${res.status} ${res.statusText}: ${await res.text()}`);\n }\n });\n return {\n \"navigator?.onLine\": globalVar.navigator?.onLine,\n cfTrace,\n baseUrlBackend,\n prodDashboard,\n prodBackend,\n };\n }\n\n protected async _createNetworkError(cause: Error, session?: InternalSession | null, requestType?: \"client\" | \"server\" | \"admin\") {\n return new Error(deindent`\n Stack Auth is unable to connect to the server. Please check your internet connection and try again.\n\n If the problem persists, please contact support and provide a screenshot of your entire browser console.\n\n ${cause}\n\n ${JSON.stringify(await this.runNetworkDiagnostics(session, requestType), null, 2)}\n `, { cause: cause });\n }\n\n protected async _networkRetry<T>(cb: () => Promise<Result<T, any>>, session?: InternalSession | null, requestType?: \"client\" | \"server\" | \"admin\"): Promise<T> {\n const retriedResult = await Result.retry(\n cb,\n 5,\n { exponentialDelayBase: 1000 },\n );\n\n // try to diagnose the error for the user\n if (retriedResult.status === \"error\") {\n if (globalVar.navigator && globalVar.navigator.onLine === false) {\n throw new Error(\"You are offline. Please check your internet connection and try again. (window.navigator.onLine is false)\", { cause: retriedResult.error });\n }\n throw await this._createNetworkError(retriedResult.error, session, requestType);\n }\n return retriedResult.data;\n }\n\n protected async _networkRetryException<T>(cb: () => Promise<T>, session?: InternalSession | null, requestType?: \"client\" | \"server\" | \"admin\"): Promise<T> {\n return await this._networkRetry(async () => await Result.fromThrowingAsync(cb), session, requestType);\n }\n\n public async fetchNewAccessToken(refreshToken: RefreshToken) {\n if (\"projectOwnerSession\" in this.options) {\n // TODO support it\n throw new Error(\"Admin session token is currently not supported for fetching new access token. Did you try to log in on a StackApp initiated with the admin session?\");\n }\n\n const clientSecret = this.options.publishableClientKey ?? publishableClientKeyNotNecessarySentinel;\n const tokenEndpoint = this.getApiUrl() + '/auth/oauth/token';\n const as = {\n issuer: this.options.getBaseUrl(),\n algorithm: 'oauth2',\n token_endpoint: tokenEndpoint,\n };\n const client: oauth.Client = {\n client_id: this.projectId,\n client_secret: clientSecret,\n };\n\n const clientAuthentication = oauth.ClientSecretPost(clientSecret);\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const allowInsecure = tokenEndpoint.startsWith('http://');\n\n const response = await this._networkRetryException(async () => {\n const rawResponse = await oauth.refreshTokenGrantRequest(\n as,\n client,\n clientAuthentication,\n refreshToken.token,\n allowInsecure ? { [oauth.allowInsecureRequests]: true } : undefined,\n );\n\n const response = await this._processResponse(rawResponse);\n\n if (response.status === \"error\") {\n const error = response.error;\n if (KnownErrors.RefreshTokenError.isInstance(error)) {\n return null;\n }\n throw error;\n }\n\n if (!response.data.ok) {\n const body = await response.data.text();\n throw new Error(`Failed to send refresh token request: ${response.status} ${body}`);\n }\n\n return response.data;\n });\n if (!response) return null;\n\n let result: oauth.TokenEndpointResponse;\n try {\n result = await oauth.processRefreshTokenResponse(as, client, response);\n } catch (e){\n if (e instanceof oauth.ResponseBodyError) {\n throw new StackAssertionError(\"ResponseBodyError when processing refresh token response\", {\n cause: e.cause,\n code: e.code,\n error: e.error,\n });\n }\n throw new StackAssertionError(\"Unexpected error when processing refresh token response\", { cause: e });\n }\n\n if (!result.access_token) {\n throw new StackAssertionError(\"Access token not found in token endpoint response, this is weird!\");\n }\n\n return AccessToken.createIfValid(result.access_token) ?? throwErr(\"Access token in fetchNewAccessToken is invalid, looks like the backend is returning an invalid token!\", { result });\n\n }\n\n public async sendClientRequest(\n path: string,\n requestOptions: RequestInit,\n session: InternalSession | null,\n requestType: \"client\" | \"server\" | \"admin\" = \"client\",\n apiUrlOverride?: string,\n ) {\n session ??= this.createSession({\n refreshToken: null,\n });\n\n return await this._networkRetry(\n () => this.sendClientRequestInner(path, requestOptions, session!, requestType, apiUrlOverride),\n session,\n requestType,\n );\n }\n\n public createSession(options: Omit<ConstructorParameters<typeof InternalSession>[0], \"refreshAccessTokenCallback\">): InternalSession {\n const session = new InternalSession({\n refreshAccessTokenCallback: async (refreshToken) => await this.fetchNewAccessToken(refreshToken),\n ...options,\n });\n return session;\n }\n\n async sendSessionReplayBatch(\n body: string,\n session: InternalSession | null,\n options: { keepalive: boolean },\n ): Promise<Result<Response, Error>> {\n try {\n const response = await this.sendClientRequest(\n \"/session-replays/batch\",\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body,\n keepalive: options.keepalive,\n },\n session,\n \"client\",\n this.getAnalyticsApiUrl(),\n );\n return Result.ok(response);\n } catch (e) {\n return Result.error(e instanceof Error ? e : new Error(String(e)));\n }\n }\n\n async sendAnalyticsEventBatch(\n body: string,\n session: InternalSession | null,\n options: { keepalive: boolean },\n ): Promise<Result<Response, Error>> {\n try {\n const response = await this.sendClientRequest(\n \"/analytics/events/batch\",\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body,\n keepalive: options.keepalive,\n },\n session,\n \"client\",\n this.getAnalyticsApiUrl(),\n );\n return Result.ok(response);\n } catch (e) {\n return Result.error(e instanceof Error ? e : new Error(String(e)));\n }\n }\n\n protected async sendClientRequestAndCatchKnownError<E extends typeof KnownErrors[keyof KnownErrors]>(\n path: string,\n requestOptions: RequestInit,\n tokenStoreOrNull: InternalSession | null,\n errorsToCatch: readonly E[],\n ): Promise<Result<\n Response & {\n usedTokens: {\n accessToken: AccessToken,\n refreshToken: RefreshToken | null,\n } | null,\n },\n InstanceType<E>\n >> {\n try {\n return Result.ok(await this.sendClientRequest(path, requestOptions, tokenStoreOrNull));\n } catch (e) {\n for (const errorType of errorsToCatch) {\n if (errorType.isInstance(e)) {\n return Result.error(e as InstanceType<E>);\n }\n }\n throw e;\n }\n }\n\n private async sendClientRequestInner(\n path: string,\n options: RequestInit,\n session: InternalSession,\n requestType: \"client\" | \"server\" | \"admin\",\n apiUrlOverride?: string,\n ): Promise<Result<Response & {\n usedTokens: {\n accessToken: AccessToken,\n refreshToken: RefreshToken | null,\n } | null,\n }>> {\n /**\n * `tokenObj === null` means the session is invalid/not logged in\n */\n let tokenObj = await session.getOrFetchLikelyValidTokens(20_000, null);\n\n let adminSession: InternalSession | null = null;\n let adminTokenObj: { accessToken: AccessToken, refreshToken: RefreshToken | null } | null = null;\n\n if (\"projectOwnerSession\" in this.options) {\n const projectOwnerSession = this.options.projectOwnerSession;\n\n if (typeof projectOwnerSession === 'function') {\n const accessTokenString = await projectOwnerSession();\n if (accessTokenString) {\n const accessToken = AccessToken.createIfValid(accessTokenString);\n if (accessToken) {\n adminTokenObj = { accessToken, refreshToken: null };\n }\n }\n } else {\n adminSession = projectOwnerSession;\n adminTokenObj = await projectOwnerSession.getOrFetchLikelyValidTokens(20_000, null);\n }\n }\n\n // all requests should be dynamic to prevent Next.js caching\n await this.options.prepareRequest?.();\n\n let url = (apiUrlOverride ?? this.getApiUrl()) + path;\n if (url.endsWith(\"/\")) {\n url = url.slice(0, -1);\n }\n const params: RequestInit = {\n /**\n * This fetch may be cross-origin, in which case we don't want to send cookies of the\n * original origin (this is the default behavior of `credentials`).\n *\n * To help debugging, also omit cookies on same-origin, so we don't accidentally\n * implement reliance on cookies anywhere.\n *\n * However, Cloudflare Workers don't actually support `credentials`, so we only set it\n * if Cloudflare-exclusive globals are not detected. https://github.com/cloudflare/workers-sdk/issues/2514\n */\n ...(\"WebSocketPair\" in globalVar ? {} : {\n credentials: \"omit\",\n }),\n ...options,\n headers: {\n \"X-Stack-Override-Error-Status\": \"true\",\n \"X-Stack-Project-Id\": this.projectId,\n \"X-Stack-Access-Type\": requestType,\n \"X-Stack-Client-Version\": this.options.clientVersion,\n ...(tokenObj ? {\n \"X-Stack-Access-Token\": tokenObj.accessToken.token,\n } : {}),\n ...(tokenObj?.refreshToken ? {\n \"X-Stack-Refresh-Token\": tokenObj.refreshToken.token,\n } : {}),\n \"X-Stack-Allow-Anonymous-User\": \"true\",\n ...(\"publishableClientKey\" in this.options && this.options.publishableClientKey ? {\n \"X-Stack-Publishable-Client-Key\": this.options.publishableClientKey,\n } : {}),\n ...(adminTokenObj ? {\n \"X-Stack-Admin-Access-Token\": adminTokenObj.accessToken.token,\n } : {}),\n /**\n * Next.js until v15 would cache fetch requests by default, and forcefully disabling it was nearly impossible.\n *\n * This header is used to change the cache key and hence always disable it, because we do our own caching.\n *\n * When we drop support for Next.js <15, we may be able to remove this header, but please make sure that this is\n * the case (I haven't actually tested.)\n */\n \"X-Stack-Random-Nonce\": generateSecureRandomString(),\n // don't show a warning when proxying the API through ngrok (only relevant if the API url is an ngrok site)\n 'ngrok-skip-browser-warning': 'true',\n ...this.options.extraRequestHeaders,\n ...options.headers,\n },\n /**\n * Cloudflare Workers does not support cache, so don't pass it there\n */\n ...(\"WebSocketPair\" in globalVar ? {} : {\n cache: \"no-store\",\n }),\n };\n\n let rawRes;\n try {\n rawRes = await fetch(url, params);\n } catch (e) {\n if (e instanceof TypeError) {\n // Likely to be a network error. Retry if the request is idempotent, throw network error otherwise.\n if (HTTP_METHODS[(params.method ?? \"GET\") as HttpMethod].idempotent) {\n return Result.error(e);\n } else {\n throw await this._createNetworkError(e, session, requestType);\n }\n }\n throw e;\n }\n\n const processedRes = await this._processResponse(rawRes);\n if (processedRes.status === \"error\") {\n // If the access token is invalid, reset it and retry\n if (KnownErrors.InvalidAccessToken.isInstance(processedRes.error)) {\n if (!tokenObj) {\n throw new StackAssertionError(\"Received invalid access token, but session is not logged in\", { tokenObj, processedRes });\n }\n session.markAccessTokenExpired(tokenObj.accessToken);\n return Result.error(processedRes.error);\n }\n\n // Same for the admin access token\n // TODO HACK: Some of the backend hasn't been ported to use the new error codes, so if we have project owner tokens we need to check for ApiKeyNotFound too. Once the migration to smartRouteHandlers is complete, we can check for InvalidAdminAccessToken only.\n if (adminSession && (KnownErrors.InvalidAdminAccessToken.isInstance(processedRes.error) || KnownErrors.ApiKeyNotFound.isInstance(processedRes.error))) {\n if (!adminTokenObj) {\n throw new StackAssertionError(\"Received invalid admin access token, but admin session is not logged in\", { adminTokenObj, processedRes });\n }\n adminSession.markAccessTokenExpired(adminTokenObj.accessToken);\n return Result.error(processedRes.error);\n }\n\n // Known errors are client side errors, so except for the ones above they should not be retried\n // Hence, throw instead of returning an error\n throw processedRes.error;\n }\n\n\n const res = Object.assign(processedRes.data, {\n usedTokens: tokenObj,\n });\n if (res.ok) {\n return Result.ok(res);\n } else if (res.status === 429) {\n // Rate limited, so retry if we can\n const retryAfter = res.headers.get(\"Retry-After\");\n if (retryAfter !== null) {\n console.log(`Rate limited while sending request to ${url}. Will retry after ${retryAfter} seconds...`);\n await wait(Number(retryAfter) * 1000);\n return Result.error(new Error(`Rate limited, retrying after ${retryAfter} seconds`));\n }\n console.log(`Rate limited while sending request to ${url}, no retry-after header received. Retrying...`);\n return Result.error(new Error(\"Rate limited, no retry-after header received\"));\n } else {\n const error = await res.text();\n\n const errorObj = new StackAssertionError(`Failed to send request to ${url}: ${res.status} ${error}`, { request: params, res, path });\n\n if (res.status === 508 && error.includes(\"INFINITE_LOOP_DETECTED\")) {\n // Some Vercel deployments seem to have an odd infinite loop bug. In that case, retry.\n // See: https://github.com/stack-auth/stack-auth/issues/319\n return Result.error(errorObj);\n }\n\n // Do not retry, throw error instead of returning one\n throw errorObj;\n }\n }\n\n private async _processResponse(rawRes: Response): Promise<Result<Response, KnownError>> {\n let res = rawRes;\n if (rawRes.headers.has(\"x-stack-actual-status\")) {\n const actualStatus = Number(rawRes.headers.get(\"x-stack-actual-status\"));\n res = new Response(rawRes.body, {\n status: actualStatus,\n statusText: rawRes.statusText,\n headers: rawRes.headers,\n });\n }\n\n // Handle known errors\n if (res.headers.has(\"x-stack-known-error\")) {\n const errorJson = await res.json();\n if (res.headers.get(\"x-stack-known-error\") !== errorJson.code) {\n throw new StackAssertionError(\"Mismatch between x-stack-known-error header and error code in body; the server's response is invalid\");\n }\n const error = KnownError.fromJson(errorJson);\n return Result.error(error);\n }\n\n return Result.ok(res);\n }\n\n public async checkFeatureSupport(options: { featureName?: string } & ReadonlyJson): Promise<never> {\n const res = await this.sendClientRequest(\"/check-feature-support\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(options),\n }, null);\n\n throw new StackAssertionError(await res.text());\n }\n\n async sendForgotPasswordEmail(\n email: string,\n callbackUrl: string,\n ): Promise<Result<undefined, KnownErrors[\"UserNotFound\"]>> {\n const res = await this.sendClientRequestAndCatchKnownError(\n \"/auth/password/send-reset-code\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({\n email,\n callback_url: callbackUrl,\n }),\n },\n null,\n [KnownErrors.UserNotFound],\n );\n\n if (res.status === \"error\") {\n return Result.error(res.error);\n } else {\n return Result.ok(undefined);\n }\n }\n\n async sendVerificationEmail(\n email: string,\n callbackUrl: string,\n session: InternalSession\n ): Promise<KnownErrors[\"EmailAlreadyVerified\"] | undefined> {\n const res = await this.sendClientRequestAndCatchKnownError(\n \"/contact-channels/send-verification-code\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({\n email,\n callback_url: callbackUrl,\n }),\n },\n session,\n [KnownErrors.EmailAlreadyVerified]\n );\n\n if (res.status === \"error\") {\n return res.error;\n }\n }\n\n async sendMagicLinkEmail(\n email: string,\n callbackUrl: string,\n ): Promise<Result<{ nonce: string }, KnownErrors[\"RedirectUrlNotWhitelisted\"]>> {\n const res = await this.sendClientRequestAndCatchKnownError(\n \"/auth/otp/send-sign-in-code\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({\n email,\n callback_url: callbackUrl,\n }),\n },\n null,\n [KnownErrors.RedirectUrlNotWhitelisted]\n );\n\n if (res.status === \"error\") {\n return Result.error(res.error);\n } else {\n return Result.ok(await res.data.json());\n }\n }\n\n async resetPassword(\n options: { code: string } & ({ password: string } | { onlyVerifyCode: true })\n ): Promise<Result<undefined, KnownErrors[\"VerificationCodeError\"]>> {\n const res = await this.sendClientRequestAndCatchKnownError(\n \"onlyVerifyCode\" in options ? \"/auth/password/reset/check-code\" : \"/auth/password/reset\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({\n code: options.code,\n ...(\"password\" in options ? { password: options.password } : {}),\n }),\n },\n null,\n [KnownErrors.VerificationCodeError]\n );\n\n if (res.status === \"error\") {\n return Result.error(res.error);\n } else {\n return Result.ok(undefined);\n }\n }\n\n async updatePassword(\n options: { oldPassword: string, newPassword: string },\n session: InternalSession\n ): Promise<KnownErrors[\"PasswordConfirmationMismatch\"] | KnownErrors[\"PasswordRequirementsNotMet\"] | undefined> {\n const res = await this.sendClientRequestAndCatchKnownError(\n \"/auth/password/update\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({\n old_password: options.oldPassword,\n new_password: options.newPassword,\n }),\n },\n session,\n [KnownErrors.PasswordConfirmationMismatch, KnownErrors.PasswordRequirementsNotMet]\n );\n\n if (res.status === \"error\") {\n return res.error;\n }\n }\n\n async setPassword(\n options: { password: string },\n session: InternalSession\n ): Promise<KnownErrors[\"PasswordRequirementsNotMet\"] | undefined> {\n const res = await this.sendClientRequestAndCatchKnownError(\n \"/auth/password/set\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify(options),\n },\n session,\n [KnownErrors.PasswordRequirementsNotMet]\n );\n\n if (res.status === \"error\") {\n return res.error;\n }\n }\n\n async verifyPasswordResetCode(code: string): Promise<Result<undefined, KnownErrors[\"VerificationCodeError\"]>> {\n const res = await this.resetPassword({ code, onlyVerifyCode: true });\n if (res.status === \"error\") {\n return Result.error(res.error);\n } else {\n return Result.ok(undefined);\n }\n }\n\n async verifyEmail(code: string): Promise<Result<undefined, KnownErrors[\"VerificationCodeError\"]>> {\n const res = await this.sendClientRequestAndCatchKnownError(\n \"/contact-channels/verify\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({\n code,\n }),\n },\n null,\n [KnownErrors.VerificationCodeError]\n );\n\n if (res.status === \"error\") {\n return Result.error(res.error);\n } else {\n return Result.ok(undefined);\n }\n }\n\n async initiatePasskeyRegistration(\n options: {},\n session: InternalSession\n ): Promise<Result<{ options_json: PublicKeyCredentialCreationOptionsJSON, code: string }, KnownErrors[]>> {\n const res = await this.sendClientRequestAndCatchKnownError(\n \"/auth/passkey/initiate-passkey-registration\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify(options),\n },\n session,\n []\n );\n\n if (res.status === \"error\") {\n return Result.error(res.error);\n }\n\n return Result.ok(await res.data.json());\n }\n\n async registerPasskey(\n options: { credential: RegistrationResponseJSON, code: string },\n session: InternalSession\n ): Promise<Result<undefined, KnownErrors[\"PasskeyRegistrationFailed\"]>> {\n const res = await this.sendClientRequestAndCatchKnownError(\n \"/auth/passkey/register\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify(options),\n },\n session,\n [KnownErrors.PasskeyRegistrationFailed]\n );\n if (res.status === \"error\") {\n return Result.error(res.error);\n }\n return Result.ok(undefined);\n }\n\n async initiatePasskeyAuthentication(\n options: {\n },\n session: InternalSession\n ): Promise<Result<{ options_json: PublicKeyCredentialRequestOptionsJSON, code: string }, KnownErrors[]>> {\n const res = await this.sendClientRequestAndCatchKnownError(\n \"/auth/passkey/initiate-passkey-authentication\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify(options),\n },\n session,\n []\n );\n\n if (res.status === \"error\") {\n return Result.error(res.error);\n }\n\n return Result.ok(await res.data.json());\n }\n\n async sendTeamInvitation(options: {\n email: string,\n teamId: string,\n callbackUrl: string,\n session: InternalSession,\n }): Promise<void> {\n await this.sendClientRequest(\n \"/team-invitations/send-code\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({\n email: options.email,\n team_id: options.teamId,\n callback_url: options.callbackUrl,\n }),\n },\n options.session,\n );\n }\n\n async acceptTeamInvitation<T extends 'use' | 'details' | 'check'>(options: {\n code: string,\n session: InternalSession,\n type: T,\n }): Promise<Result<T extends 'details' ? { team_display_name: string } : undefined, KnownErrors[\"VerificationCodeError\"]>> {\n const res = await this.sendClientRequestAndCatchKnownError(\n options.type === 'check' ?\n \"/team-invitations/accept/check-code\" :\n options.type === 'details' ?\n \"/team-invitations/accept/details\" :\n \"/team-invitations/accept\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({\n code: options.code,\n }),\n },\n options.session,\n [KnownErrors.VerificationCodeError]\n );\n\n if (res.status === \"error\") {\n return Result.error(res.error);\n } else {\n return Result.ok(await res.data.json());\n }\n }\n\n async totpMfa(\n attemptCode: string,\n totp: string,\n session: InternalSession\n ) {\n const res = await this.sendClientRequest(\"/auth/mfa/sign-in\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({\n code: attemptCode,\n type: \"totp\",\n totp: totp,\n }),\n }, session);\n\n const result = await res.json();\n return {\n accessToken: result.access_token,\n refreshToken: result.refresh_token,\n newUser: result.is_new_user,\n };\n }\n\n async signInWithCredential(\n email: string,\n password: string,\n session: InternalSession\n ): Promise<Result<{ accessToken: string, refreshToken: string }, KnownErrors[\"EmailPasswordMismatch\"]>> {\n const res = await this.sendClientRequestAndCatchKnownError(\n \"/auth/password/sign-in\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({\n email,\n password,\n }),\n },\n session,\n [KnownErrors.EmailPasswordMismatch]\n );\n\n if (res.status === \"error\") {\n return Result.error(res.error);\n }\n\n const result = await res.data.json();\n return Result.ok({\n accessToken: result.access_token,\n refreshToken: result.refresh_token,\n });\n }\n\n async signUpWithCredential(\n email: string,\n password: string,\n emailVerificationRedirectUrl: string | undefined,\n session: InternalSession,\n ): Promise<Result<{ accessToken: string, refreshToken: string }, KnownErrors[\"UserWithEmailAlreadyExists\"] | KnownErrors[\"PasswordRequirementsNotMet\"]>> {\n const res = await this.sendClientRequestAndCatchKnownError(\n \"/auth/password/sign-up\",\n {\n headers: {\n \"Content-Type\": \"application/json\"\n },\n method: \"POST\",\n body: JSON.stringify({\n email,\n password,\n verification_callback_url: emailVerificationRedirectUrl,\n }),\n },\n session,\n [KnownErrors.UserWithEmailAlreadyExists, KnownErrors.PasswordRequirementsNotMet]\n );\n\n if (res.status === \"error\") {\n return Result.error(res.error);\n }\n\n const result = await res.data.json();\n return Result.ok({\n accessToken: result.access_token,\n refreshToken: result.refresh_token,\n });\n }\n\n async signUpAnonymously(session: InternalSession): Promise<Result<{ accessToken: string, refreshToken: string }, never>> {\n const res = await this.sendClientRequestAndCatchKnownError(\n \"/auth/anonymous/sign-up\",\n {\n method: \"POST\",\n },\n session,\n [],\n );\n\n if (res.status === \"error\") {\n return Result.error(res.error);\n }\n\n const result = await res.data.json();\n return Result.ok({\n accessToken: result.access_token,\n refreshToken: result.refresh_token,\n });\n }\n\n async signInWithMagicLink(code: string, session: InternalSession): Promise<Result<{ newUser: boolean, accessToken: string, refreshToken: string }, KnownErrors[\"VerificationCodeError\"]>> {\n const res = await this.sendClientRequestAndCatchKnownError(\n \"/auth/otp/sign-in\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({\n code,\n }),\n },\n session,\n [KnownErrors.VerificationCodeError]\n );\n\n if (res.status === \"error\") {\n return Result.error(res.error);\n }\n\n const result = await res.data.json();\n return Result.ok({\n accessToken: result.access_token,\n refreshToken: result.refresh_token,\n newUser: result.is_new_user,\n });\n }\n\n async signInWithMfa(totp: string, code: string, session: InternalSession): Promise<Result<{ newUser: boolean, accessToken: string, refreshToken: string }, KnownErrors[\"VerificationCodeError\"]>> {\n const res = await this.sendClientRequestAndCatchKnownError(\n \"/auth/mfa/sign-in\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({\n type: \"totp\",\n totp,\n code,\n }),\n },\n session,\n [KnownErrors.VerificationCodeError]\n );\n\n if (res.status === \"error\") {\n return Result.error(res.error);\n }\n\n const result = await res.data.json();\n return Result.ok({\n accessToken: result.access_token,\n refreshToken: result.refresh_token,\n newUser: result.is_new_user,\n });\n }\n\n async signInWithPasskey(body: { authentication_response: AuthenticationResponseJSON, code: string }, session: InternalSession): Promise<Result<{accessToken: string, refreshToken: string }, KnownErrors[\"PasskeyAuthenticationFailed\"]>> {\n const res = await this.sendClientRequestAndCatchKnownError(\n \"/auth/passkey/sign-in\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify(body),\n },\n session,\n [KnownErrors.PasskeyAuthenticationFailed]\n );\n\n if (res.status === \"error\") {\n return Result.error(res.error);\n }\n\n const result = await res.data.json();\n return Result.ok({\n accessToken: result.access_token,\n refreshToken: result.refresh_token,\n });\n }\n\n async getOAuthUrl(\n options: {\n provider: string,\n redirectUrl: string,\n errorRedirectUrl: string,\n afterCallbackRedirectUrl?: string,\n codeChallenge: string,\n state: string,\n type: \"authenticate\" | \"link\",\n providerScope?: string,\n session: InternalSession,\n }\n ): Promise<string> {\n const updatedRedirectUrl = new URL(options.redirectUrl);\n for (const key of [\"code\", \"state\"]) {\n if (updatedRedirectUrl.searchParams.has(key)) {\n console.warn(\"Redirect URL already contains \" + key + \" parameter, removing it as it will be overwritten by the OAuth callback\");\n }\n updatedRedirectUrl.searchParams.delete(key);\n }\n\n if (\"projectOwnerSession\" in this.options) {\n // TODO fix\n throw new Error(\"Admin session token is currently not supported for OAuth\");\n }\n const clientSecret = this.options.publishableClientKey ?? publishableClientKeyNotNecessarySentinel;\n const url = new URL(this.getApiUrl() + \"/auth/oauth/authorize/\" + options.provider.toLowerCase());\n url.searchParams.set(\"client_id\", this.projectId);\n url.searchParams.set(\"client_secret\", clientSecret);\n url.searchParams.set(\"redirect_uri\", updatedRedirectUrl.toString());\n url.searchParams.set(\"scope\", \"legacy\");\n url.searchParams.set(\"state\", options.state);\n url.searchParams.set(\"grant_type\", \"authorization_code\");\n url.searchParams.set(\"code_challenge\", options.codeChallenge);\n url.searchParams.set(\"code_challenge_method\", \"S256\");\n url.searchParams.set(\"response_type\", \"code\");\n url.searchParams.set(\"type\", options.type);\n url.searchParams.set(\"error_redirect_url\", options.errorRedirectUrl);\n\n // TODO: This token will expire after 45s if the token lifetime is 60s, which may be shorter than the OAuth flow.\n // We should probably find a way to request a longer-lived token here.\n const tokens = await options.session.getOrFetchLikelyValidTokens(45_000, 60_000);\n if (tokens) {\n url.searchParams.set(\"token\", tokens.accessToken.token);\n }\n\n if (options.afterCallbackRedirectUrl) {\n url.searchParams.set(\"after_callback_redirect_url\", options.afterCallbackRedirectUrl);\n }\n if (options.providerScope) {\n url.searchParams.set(\"provider_scope\", options.providerScope);\n }\n\n return url.toString();\n }\n\n async callOAuthCallback(options: {\n oauthParams: URLSearchParams,\n redirectUri: string,\n codeVerifier: string,\n state: string,\n }): Promise<{ newUser: boolean, afterCallbackRedirectUrl?: string, accessToken: string, refreshToken: string }> {\n if (\"projectOwnerSession\" in this.options) {\n // TODO fix\n throw new Error(\"Admin session token is currently not supported for OAuth\");\n }\n const clientSecret = this.options.publishableClientKey ?? publishableClientKeyNotNecessarySentinel;\n const tokenEndpoint = this.getApiUrl() + '/auth/oauth/token';\n const as = {\n issuer: this.options.getBaseUrl(),\n algorithm: 'oauth2',\n token_endpoint: tokenEndpoint,\n };\n const client: oauth.Client = {\n client_id: this.projectId,\n client_secret: clientSecret,\n };\n const clientAuthentication = oauth.ClientSecretPost(clientSecret);\n // Allow insecure HTTP requests only in test environment (for localhost testing)\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const allowInsecure = tokenEndpoint.startsWith('http://');\n\n let params: URLSearchParams;\n try {\n params = oauth.validateAuthResponse(as, client, options.oauthParams, options.state);\n } catch (e) {\n if (e instanceof oauth.AuthorizationResponseError) {\n throw new StackAssertionError(\"Authorization response error when validating outer OAuth response\", {\n //cause is a URLSearchParams object for this error, so we need to serialize it better\n cause: Object.fromEntries(e.cause),\n code: e.code,\n error: e.error,\n });\n }\n throw new StackAssertionError(\"Unexpected error when validating outer OAuth response\", { cause: e });\n }\n const response = await oauth.authorizationCodeGrantRequest(\n as,\n client,\n clientAuthentication,\n params,\n options.redirectUri,\n options.codeVerifier,\n allowInsecure ? { [oauth.allowInsecureRequests]: true } : undefined,\n );\n\n let result;\n try {\n result = await oauth.processAuthorizationCodeResponse(as, client, response);\n } catch (e) {\n if (e instanceof oauth.ResponseBodyError) {\n if ((e.cause as any).code === \"MULTI_FACTOR_AUTHENTICATION_REQUIRED\") {\n throw new KnownErrors.MultiFactorAuthenticationRequired((e.cause as any).details.attempt_code);\n }\n // TODO Handle OAuth 2.0 response body error\n throw new StackAssertionError(\"Outer OAuth error during authorization code response\", {\n cause: e.cause,\n code: e.code,\n error: e.error,\n });\n }\n throw new StackAssertionError(\"Unexpected error when processing authorization code response\", { cause: e });\n }\n return {\n newUser: result.is_new_user as boolean,\n afterCallbackRedirectUrl: result.after_callback_redirect_url as string | undefined,\n accessToken: result.access_token,\n refreshToken: result.refresh_token ?? throwErr(\"Refresh token not found in outer OAuth response\"),\n };\n }\n\n async signOut(session: InternalSession): Promise<void> {\n const tokenObj = await session.getOrFetchLikelyValidTokens(20_000, null);\n if (tokenObj) {\n const resOrError = await this.sendClientRequestAndCatchKnownError(\n \"/auth/sessions/current\",\n {\n method: \"DELETE\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({}),\n },\n session,\n [KnownErrors.RefreshTokenError]\n );\n if (resOrError.status === \"error\") {\n if (KnownErrors.RefreshTokenError.isInstance(resOrError.error)) {\n // refresh token was already invalid, just continue like nothing happened\n } else {\n // this should never happen\n throw new StackAssertionError(\"Unexpected error\", { error: resOrError.error });\n }\n } else {\n // user was signed out successfully, all good\n }\n }\n session.markInvalid();\n }\n\n async getClientUserByToken(session: InternalSession): Promise<CurrentUserCrud[\"Client\"][\"Read\"] | null> {\n const responseOrError = await this.sendClientRequestAndCatchKnownError(\n \"/users/me\",\n {},\n session,\n [KnownErrors.CannotGetOwnUserWithoutUser],\n );\n if (responseOrError.status === \"error\") {\n if (KnownErrors.CannotGetOwnUserWithoutUser.isInstance(responseOrError.error)) {\n return null;\n } else {\n throw new StackAssertionError(\"Unexpected uncaught error\", { cause: responseOrError.error });\n }\n }\n const response = responseOrError.data;\n const user: CurrentUserCrud[\"Client\"][\"Read\"] = await response.json();\n if (!(user as any)) throw new StackAssertionError(\"User endpoint returned null; this should never happen\");\n return user;\n }\n\n async listTeamInvitations(\n options: {\n teamId: string,\n },\n session: InternalSession,\n ): Promise<TeamInvitationCrud['Client']['Read'][]> {\n const response = await this.sendClientRequest(\n \"/team-invitations?\" + new URLSearchParams({ team_id: options.teamId }),\n {},\n session,\n );\n const result = await response.json() as TeamInvitationCrud['Client']['List'];\n return result.items;\n }\n\n async listCurrentUserTeamInvitations(\n session: InternalSession,\n ): Promise<TeamInvitationCrud['Client']['Read'][]> {\n const response = await this.sendClientRequest(\n \"/team-invitations?\" + new URLSearchParams({ user_id: 'me' }),\n {},\n session,\n );\n const result = await response.json() as TeamInvitationCrud['Client']['List'];\n return result.items;\n }\n\n async acceptTeamInvitationById(\n invitationId: string,\n session: InternalSession,\n ) {\n await this.sendClientRequest(\n urlString`/team-invitations/${invitationId}/accept` + \"?\" + new URLSearchParams({ user_id: 'me' }),\n { method: \"POST\" },\n session,\n );\n }\n\n async revokeTeamInvitation(\n invitationId: string,\n teamId: string,\n session: InternalSession,\n ) {\n await this.sendClientRequest(\n `/team-invitations/${invitationId}?team_id=${teamId}`,\n { method: \"DELETE\" },\n session,\n );\n }\n\n async listTeamMemberProfiles(\n options: {\n teamId?: string,\n userId?: string,\n },\n session: InternalSession,\n ): Promise<TeamMemberProfilesCrud['Client']['Read'][]> {\n const response = await this.sendClientRequest(\n \"/team-member-profiles?\" + new URLSearchParams(filterUndefined({\n team_id: options.teamId,\n user_id: options.userId,\n })),\n {},\n session,\n );\n const result = await response.json() as TeamMemberProfilesCrud['Client']['List'];\n return result.items;\n }\n\n async getTeamMemberProfile(\n options: {\n teamId: string,\n userId: string,\n },\n session: InternalSession,\n ): Promise<TeamMemberProfilesCrud['Client']['Read']> {\n const response = await this.sendClientRequest(\n `/team-member-profiles/${options.teamId}/${options.userId}`,\n {},\n session,\n );\n return await response.json();\n }\n\n async leaveTeam(\n teamId: string,\n session: InternalSession,\n ) {\n await this.sendClientRequest(\n `/team-memberships/${teamId}/me`,\n {\n method: \"DELETE\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({}),\n },\n session,\n );\n }\n\n async updateTeamMemberProfile(\n options: {\n teamId: string,\n userId: string,\n profile: TeamMemberProfilesCrud['Client']['Update'],\n },\n session: InternalSession,\n ) {\n await this.sendClientRequest(\n `/team-member-profiles/${options.teamId}/${options.userId}`,\n {\n method: \"PATCH\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify(options.profile),\n },\n session,\n );\n }\n\n async updateTeam(\n options: {\n teamId: string,\n data: TeamsCrud['Client']['Update'],\n },\n session: InternalSession,\n ) {\n await this.sendClientRequest(\n `/teams/${options.teamId}`,\n {\n method: \"PATCH\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify(options.data),\n },\n session,\n );\n }\n\n async listCurrentUserTeamPermissions(\n options: {\n teamId: string,\n recursive: boolean,\n },\n session: InternalSession\n ): Promise<TeamPermissionsCrud['Client']['Read'][]> {\n const response = await this.sendClientRequest(\n `/team-permissions?team_id=${options.teamId}&user_id=me&recursive=${options.recursive}`,\n {},\n session,\n );\n const result = await response.json() as TeamPermissionsCrud['Client']['List'];\n return result.items;\n }\n\n async listCurrentUserProjectPermissions(\n options: {\n recursive: boolean,\n },\n session: InternalSession\n ): Promise<ProjectPermissionsCrud['Client']['Read'][]> {\n const response = await this.sendClientRequest(\n `/project-permissions?user_id=me&recursive=${options.recursive}`,\n {},\n session,\n );\n const result = await response.json() as ProjectPermissionsCrud['Client']['List'];\n return result.items;\n }\n\n async listCurrentUserTeams(session: InternalSession): Promise<TeamsCrud[\"Client\"][\"Read\"][]> {\n const response = await this.sendClientRequest(\n \"/teams?user_id=me\",\n {},\n session,\n );\n const result = await response.json() as TeamsCrud[\"Client\"][\"List\"];\n return result.items;\n }\n\n async getClientProject(): Promise<Result<ClientProjectsCrud['Client']['Read'], KnownErrors[\"ProjectNotFound\"]>> {\n const responseOrError = await this.sendClientRequestAndCatchKnownError(\"/projects/current\", {}, null, [KnownErrors.ProjectNotFound]);\n if (responseOrError.status === \"error\") {\n return Result.error(responseOrError.error);\n }\n const response = responseOrError.data;\n const project: ClientProjectsCrud['Client']['Read'] = await response.json();\n return Result.ok(project);\n }\n\n async updateClientUser(update: CurrentUserCrud[\"Client\"][\"Update\"], session: InternalSession) {\n await this.sendClientRequest(\n \"/users/me\",\n {\n method: \"PATCH\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify(update),\n },\n session,\n );\n }\n\n async listProjects(session: InternalSession): Promise<AdminUserProjectsCrud['Client']['Read'][]> {\n const response = await this.sendClientRequest(\"/internal/projects\", {}, session);\n if (!response.ok) {\n throw new Error(\"Failed to list projects: \" + response.status + \" \" + (await response.text()));\n }\n\n const json = await response.json() as AdminUserProjectsCrud['Client']['List'];\n return json.items;\n }\n\n async createProject(\n project: AdminUserProjectsCrud['Client']['Create'],\n session: InternalSession,\n ): Promise<AdminUserProjectsCrud['Client']['Read']> {\n const fetchResponse = await this.sendClientRequest(\n \"/internal/projects\",\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify(project),\n },\n session,\n );\n if (!fetchResponse.ok) {\n throw new Error(\"Failed to create project: \" + fetchResponse.status + \" \" + (await fetchResponse.text()));\n }\n\n const json = await fetchResponse.json();\n return json;\n }\n\n async createProviderAccessToken(\n provider: string,\n scope: string,\n session: InternalSession,\n ): Promise<ConnectedAccountAccessTokenCrud['Client']['Read']> {\n const response = await this.sendClientRequest(\n `/connected-accounts/me/${provider}/access-token`,\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({ scope }),\n },\n session,\n );\n return await response.json();\n }\n\n /**\n * Get access token for a specific connected account by provider ID and provider account ID.\n * This is the preferred method when dealing with multiple accounts of the same provider.\n */\n async createProviderAccessTokenByAccount(\n providerId: string,\n providerAccountId: string,\n scope: string,\n session: InternalSession,\n ): Promise<ConnectedAccountAccessTokenCrud['Client']['Read']> {\n const response = await this.sendClientRequest(\n `/connected-accounts/me/${encodeURIComponent(providerId)}/${encodeURIComponent(providerAccountId)}/access-token`,\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({ scope }),\n },\n session,\n );\n return await response.json();\n }\n\n /**\n * List all connected accounts for the current user.\n */\n async listConnectedAccounts(\n session: InternalSession,\n ): Promise<ConnectedAccountCrud['Client']['List']> {\n const response = await this.sendClientRequest(\n `/connected-accounts/me`,\n { method: \"GET\" },\n session,\n );\n return await response.json();\n }\n\n async createClientTeam(\n data: TeamsCrud['Client']['Create'],\n session: InternalSession,\n ): Promise<TeamsCrud['Client']['Read']> {\n const response = await this.sendClientRequest(\n \"/teams\",\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify(data),\n },\n session,\n );\n return await response.json();\n }\n\n async deleteTeam(\n teamId: string,\n session: InternalSession,\n ) {\n await this.sendClientRequest(\n `/teams/${teamId}`,\n {\n method: \"DELETE\",\n },\n session,\n );\n }\n\n async deleteCurrentUser(session: InternalSession) {\n await this.sendClientRequest(\n \"/users/me\",\n {\n method: \"DELETE\",\n },\n session,\n );\n }\n\n async createClientContactChannel(\n data: ContactChannelsCrud['Client']['Create'],\n session: InternalSession,\n ): Promise<ContactChannelsCrud['Client']['Read']> {\n const response = await this.sendClientRequest(\n \"/contact-channels\",\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify(data),\n },\n session,\n );\n return await response.json();\n }\n\n async updateClientContactChannel(\n id: string,\n data: ContactChannelsCrud['Client']['Update'],\n session: InternalSession,\n ): Promise<ContactChannelsCrud['Client']['Read']> {\n const response = await this.sendClientRequest(\n `/contact-channels/me/${id}`,\n {\n method: \"PATCH\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify(data),\n },\n session,\n );\n return await response.json();\n }\n\n async deleteClientContactChannel(\n id: string,\n session: InternalSession,\n ): Promise<void> {\n await this.sendClientRequest(\n `/contact-channels/me/${id}`,\n {\n method: \"DELETE\",\n },\n session,\n );\n }\n\n async deleteSession(\n sessionId: string,\n session: InternalSession,\n ): Promise<void> {\n await this.sendClientRequest(\n `/auth/sessions/${sessionId}?user_id=me`,\n {\n method: \"DELETE\",\n },\n session,\n );\n }\n\n async listSessions(\n session: InternalSession,\n ): Promise<SessionsCrud['Client']['List']> {\n const response = await this.sendClientRequest(\n \"/auth/sessions?user_id=me\",\n {\n method: \"GET\",\n },\n session,\n );\n return await response.json();\n }\n\n\n async listClientContactChannels(\n session: InternalSession,\n ): Promise<ContactChannelsCrud['Client']['Read'][]> {\n const response = await this.sendClientRequest(\n \"/contact-channels?user_id=me\",\n {\n method: \"GET\",\n },\n session,\n );\n const json = await response.json() as ContactChannelsCrud['Client']['List'];\n return json.items;\n }\n\n async sendCurrentUserContactChannelVerificationEmail(\n contactChannelId: string,\n callbackUrl: string,\n session: InternalSession,\n ): Promise<Result<undefined, KnownErrors[\"EmailAlreadyVerified\"]>> {\n const responseOrError = await this.sendClientRequestAndCatchKnownError(\n `/contact-channels/me/${contactChannelId}/send-verification-code`,\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({ callback_url: callbackUrl }),\n },\n session,\n [KnownErrors.EmailAlreadyVerified]\n );\n\n if (responseOrError.status === \"error\") {\n return Result.error(responseOrError.error);\n }\n return Result.ok(undefined);\n }\n\n async cliLogin(\n loginCode: string,\n refreshToken: string,\n session: InternalSession\n ): Promise<Result<undefined, KnownErrors[\"SchemaError\"]>> {\n const responseOrError = await this.sendClientRequestAndCatchKnownError(\n \"/auth/cli/complete\",\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({\n login_code: loginCode,\n refresh_token: refreshToken,\n }),\n },\n session,\n [KnownErrors.SchemaError]\n );\n\n if (responseOrError.status === \"error\") {\n return Result.error(responseOrError.error);\n }\n return Result.ok(undefined);\n }\n\n private async _getApiKeyRequestInfo(options: { user_id: string | null } | { team_id: string }) {\n if (\"user_id\" in options && \"team_id\" in options) {\n throw new StackAssertionError(\"Cannot specify both user_id and team_id in _getApiKeyRequestInfo\");\n }\n\n return {\n endpoint: \"team_id\" in options ? \"/team-api-keys\" : \"/user-api-keys\",\n queryParams: new URLSearchParams(filterUndefinedOrNull(options)),\n };\n }\n\n // API Keys CRUD operations\n listProjectApiKeys(options: { user_id: string }, session: InternalSession | null, requestType: \"client\" | \"server\" | \"admin\"): Promise<UserApiKeysCrud['Client']['Read'][]>;\n listProjectApiKeys(options: { team_id: string }, session: InternalSession | null, requestType: \"client\" | \"server\" | \"admin\"): Promise<TeamApiKeysCrud['Client']['Read'][]>;\n listProjectApiKeys(options: { user_id: string } | { team_id: string }, session: InternalSession | null, requestType: \"client\" | \"server\" | \"admin\"): Promise<(UserApiKeysCrud['Client']['Read'] | TeamApiKeysCrud['Client']['Read'])[]>;\n async listProjectApiKeys(\n options: { user_id: string } | { team_id: string },\n session: InternalSession | null,\n requestType: \"client\" | \"server\" | \"admin\",\n ): Promise<(UserApiKeysCrud['Client']['Read'] | TeamApiKeysCrud['Client']['Read'])[]> {\n const sendRequest = (requestType === \"client\" ? this.sendClientRequest : (this as any).sendServerRequest as never).bind(this);\n const { endpoint, queryParams } = await this._getApiKeyRequestInfo(options);\n\n const response = await sendRequest(\n `${endpoint}?${queryParams.toString()}`,\n {\n method: \"GET\",\n },\n session,\n requestType,\n );\n const json = await response.json();\n return json.items;\n }\n\n createProjectApiKey(data: yup.InferType<typeof userApiKeysCreateInputSchema>, session: InternalSession | null, requestType: \"client\" | \"server\" | \"admin\"): Promise<yup.InferType<typeof userApiKeysCreateOutputSchema>>;\n createProjectApiKey(data: yup.InferType<typeof teamApiKeysCreateInputSchema>, session: InternalSession | null, requestType: \"client\" | \"server\" | \"admin\"): Promise<yup.InferType<typeof teamApiKeysCreateOutputSchema>>;\n createProjectApiKey(data: yup.InferType<typeof userApiKeysCreateInputSchema> | yup.InferType<typeof teamApiKeysCreateInputSchema>, session: InternalSession | null, requestType: \"client\" | \"server\" | \"admin\"): Promise<yup.InferType<typeof userApiKeysCreateOutputSchema> | yup.InferType<typeof teamApiKeysCreateOutputSchema>>;\n async createProjectApiKey(\n data: yup.InferType<typeof userApiKeysCreateInputSchema> | yup.InferType<typeof teamApiKeysCreateInputSchema>,\n session: InternalSession | null,\n requestType: \"client\" | \"server\" | \"admin\",\n ): Promise<yup.InferType<typeof userApiKeysCreateOutputSchema> | yup.InferType<typeof teamApiKeysCreateOutputSchema>> {\n const sendRequest = (requestType === \"client\" ? this.sendClientRequest : (this as any).sendServerRequest as never).bind(this);\n const { endpoint } = await this._getApiKeyRequestInfo(data);\n\n const response = await sendRequest(\n `${endpoint}`,\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify(data),\n },\n session,\n requestType,\n );\n return await response.json();\n }\n\n getProjectApiKey(options: { user_id: string | null }, keyId: string, session: InternalSession | null, requestType: \"client\" | \"server\" | \"admin\"): Promise<UserApiKeysCrud['Client']['Read']>;\n getProjectApiKey(options: { team_id: string }, keyId: string, session: InternalSession | null, requestType: \"client\" | \"server\" | \"admin\"): Promise<TeamApiKeysCrud['Client']['Read']>;\n getProjectApiKey(options: { user_id: string | null } | { team_id: string }, keyId: string, session: InternalSession | null, requestType: \"client\" | \"server\" | \"admin\"): Promise<UserApiKeysCrud['Client']['Read'] | TeamApiKeysCrud['Client']['Read']>;\n async getProjectApiKey(\n options: { user_id: string | null } | { team_id: string },\n keyId: string,\n session: InternalSession | null,\n requestType: \"client\" | \"server\" | \"admin\",\n ): Promise<UserApiKeysCrud['Client']['Read'] | TeamApiKeysCrud['Client']['Read']> {\n const sendRequest = (requestType === \"client\" ? this.sendClientRequest : (this as any).sendServerRequest as never).bind(this);\n const { endpoint, queryParams } = await this._getApiKeyRequestInfo(options);\n\n const response = await sendRequest(\n `${endpoint}/${keyId}?${queryParams.toString()}`,\n {\n method: \"GET\",\n },\n session,\n requestType,\n );\n return await response.json();\n }\n\n updateProjectApiKey(options: { user_id: string }, keyId: string, data: UserApiKeysCrud['Client']['Update'], session: InternalSession | null, requestType: \"client\" | \"server\" | \"admin\"): Promise<UserApiKeysCrud['Client']['Read']>;\n updateProjectApiKey(options: { team_id: string }, keyId: string, data: TeamApiKeysCrud['Client']['Update'], session: InternalSession | null, requestType: \"client\" | \"server\" | \"admin\"): Promise<TeamApiKeysCrud['Client']['Read']>;\n updateProjectApiKey(options: { user_id: string } | { team_id: string }, keyId: string, data: UserApiKeysCrud['Client']['Update'] | TeamApiKeysCrud['Client']['Update'], session: InternalSession | null, requestType: \"client\" | \"server\" | \"admin\"): Promise<UserApiKeysCrud['Client']['Read'] | TeamApiKeysCrud['Client']['Read']>;\n async updateProjectApiKey(\n options: { user_id: string } | { team_id: string },\n keyId: string,\n data: UserApiKeysCrud['Client']['Update'] | TeamApiKeysCrud['Client']['Update'],\n session: InternalSession | null,\n requestType: \"client\" | \"server\" | \"admin\",\n ): Promise<UserApiKeysCrud['Client']['Read'] | TeamApiKeysCrud['Client']['Read']> {\n const sendRequest = (requestType === \"client\" ? this.sendClientRequest : (this as any).sendServerRequest as never).bind(this);\n const { endpoint, queryParams } = await this._getApiKeyRequestInfo(options);\n\n const response = await sendRequest(\n `${endpoint}/${keyId}?${queryParams.toString()}`,\n {\n method: \"PATCH\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify(data),\n },\n session,\n requestType,\n );\n return await response.json();\n }\n\n checkProjectApiKey(type: \"user\", apiKey: string, session: InternalSession | null, requestType: \"client\" | \"server\" | \"admin\"): Promise<UserApiKeysCrud['Client']['Read'] | null>;\n checkProjectApiKey(type: \"team\", apiKey: string, session: InternalSession | null, requestType: \"client\" | \"server\" | \"admin\"): Promise<TeamApiKeysCrud['Client']['Read'] | null>;\n checkProjectApiKey(type: \"user\" | \"team\", apiKey: string, session: InternalSession | null, requestType: \"client\" | \"server\" | \"admin\"): Promise<UserApiKeysCrud['Client']['Read'] | TeamApiKeysCrud['Client']['Read'] | null>;\n async checkProjectApiKey(type: \"user\" | \"team\", apiKey: string, session: InternalSession | null, requestType: \"client\" | \"server\" | \"admin\"): Promise<UserApiKeysCrud['Client']['Read'] | TeamApiKeysCrud['Client']['Read'] | null> {\n const sendRequest = (requestType === \"client\" ? this.sendClientRequestAndCatchKnownError : (this as any).sendServerRequestAndCatchKnownError as never).bind(this);\n const result = await sendRequest(\n `/${type}-api-keys/check`,\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({ api_key: apiKey }),\n },\n session,\n [KnownErrors.ApiKeyNotValid]\n );\n if (result.status === \"error\") {\n return null;\n }\n return await result.data.json();\n }\n\n async listNotificationCategories(\n session: InternalSession,\n ): Promise<NotificationPreferenceCrud['Client']['Read'][]> {\n const response = await this.sendClientRequest(\n `/emails/notification-preference/me`,\n {},\n session,\n );\n const result = await response.json() as NotificationPreferenceCrud['Client']['List'];\n return result.items;\n }\n\n async setNotificationsEnabled(\n notificationCategoryId: string,\n enabled: boolean,\n session: InternalSession,\n ): Promise<void> {\n await this.sendClientRequest(\n `/emails/notification-preference/me/${notificationCategoryId}`,\n {\n method: \"PATCH\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({\n enabled,\n }),\n },\n session,\n );\n }\n\n async getOAuthProvider(\n userId: string,\n providerId: string,\n session: InternalSession,\n ): Promise<OAuthProviderCrud['Client']['Read']> {\n const response = await this.sendClientRequest(\n `/oauth-providers/${userId}/${providerId}`,\n {\n method: \"GET\",\n },\n session,\n );\n return await response.json();\n }\n\n async updateOAuthProvider(\n userId: string,\n providerId: string,\n data: OAuthProviderCrud['Client']['Update'],\n session: InternalSession,\n ): Promise<OAuthProviderCrud['Client']['Read']> {\n const response = await this.sendClientRequest(\n `/oauth-providers/${userId}/${providerId}`,\n {\n method: \"PATCH\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify(data),\n },\n session,\n );\n return await response.json();\n }\n\n async listOAuthProviders(\n options: {\n user_id?: string,\n } = {},\n session: InternalSession,\n ): Promise<OAuthProviderCrud['Client']['Read'][]> {\n const queryParams = new URLSearchParams(filterUndefined(options));\n const response = await this.sendClientRequest(\n `/oauth-providers${queryParams.toString() ? `?${queryParams.toString()}` : ''}`,\n {\n method: \"GET\",\n },\n session,\n );\n const result = await response.json();\n return result.items;\n }\n\n async deleteOAuthProvider(\n userId: string,\n providerId: string,\n session: InternalSession,\n ): Promise<void> {\n const response = await this.sendClientRequest(\n `/oauth-providers/${userId}/${providerId}`,\n {\n method: \"DELETE\",\n },\n session,\n );\n return await response.json();\n }\n\n async getItem(\n options: (\n { itemId: string, userId: string } |\n { itemId: string, teamId: string } |\n { itemId: string, customCustomerId: string }\n ),\n session: InternalSession | null,\n requestType: \"client\" | \"server\" | \"admin\" = \"client\",\n ): Promise<ItemCrud['Client']['Read']> {\n let customerType: \"user\" | \"team\" | \"custom\";\n let customerId: string;\n if (\"userId\" in options) {\n customerType = \"user\";\n customerId = options.userId;\n } else if (\"teamId\" in options) {\n customerType = \"team\";\n customerId = options.teamId;\n } else if (\"customCustomerId\" in options) {\n customerType = \"custom\";\n customerId = options.customCustomerId;\n } else {\n throw new StackAssertionError(\"getItem requires one of userId, teamId, or customCustomerId\");\n }\n\n const sendRequest = (requestType === \"client\" ? this.sendClientRequest : (this as any).sendServerRequest as never).bind(this);\n const response = await sendRequest(\n urlString`/payments/items/${customerType}/${customerId}/${options.itemId}`,\n {},\n session,\n requestType,\n );\n return await response.json();\n }\n\n async listProducts(\n options: ListCustomerProductsOptions,\n session: InternalSession | null,\n requestType: \"client\" | \"server\" | \"admin\" = \"client\",\n ): Promise<CustomerProductsListResponse> {\n const queryParams = new URLSearchParams(filterUndefined({\n cursor: options.cursor,\n limit: options.limit !== undefined ? options.limit.toString() : undefined,\n }));\n const path = urlString`/payments/products/${options.customer_type}/${options.customer_id}`;\n const sendRequest = (requestType === \"client\" ? this.sendClientRequest : (this as any).sendServerRequest as never).bind(this);\n const response = await sendRequest(\n `${path}${queryParams.toString() ? `?${queryParams.toString()}` : ''}`,\n {},\n session,\n requestType,\n );\n return await response.json();\n }\n\n async listInvoices(\n options: ListCustomerInvoicesOptions,\n session: InternalSession | null,\n ): Promise<CustomerInvoicesListResponse> {\n const queryParams = new URLSearchParams(filterUndefined({\n cursor: options.cursor,\n limit: options.limit !== undefined ? options.limit.toString() : undefined,\n }));\n const path = urlString`/payments/invoices/${options.customer_type}/${options.customer_id}`;\n const response = await this.sendClientRequest(\n `${path}${queryParams.toString() ? `?${queryParams.toString()}` : ''}`,\n {},\n session,\n );\n return await response.json();\n }\n\n async cancelSubscription(\n options: {\n customer_type: \"user\" | \"team\" | \"custom\",\n customer_id: string,\n product_id: string,\n subscription_id?: string,\n },\n session: InternalSession | null,\n ): Promise<void> {\n const queryParams = new URLSearchParams(filterUndefined({\n subscription_id: options.subscription_id,\n }));\n const path = urlString`/payments/products/${options.customer_type}/${options.customer_id}/${options.product_id}`;\n await this.sendClientRequest(\n `${path}${queryParams.toString() ? `?${queryParams.toString()}` : ''}`,\n {\n method: \"DELETE\",\n },\n session,\n );\n }\n\n async switchSubscription(\n options: {\n customer_type: \"user\" | \"team\",\n customer_id: string,\n from_product_id: string,\n to_product_id: string,\n price_id?: string,\n quantity?: number,\n },\n session: InternalSession | null,\n ): Promise<void> {\n await this.sendClientRequest(\n urlString`/payments/products/${options.customer_type}/${options.customer_id}/switch`,\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({\n from_product_id: options.from_product_id,\n to_product_id: options.to_product_id,\n price_id: options.price_id,\n quantity: options.quantity,\n }),\n },\n session,\n );\n }\n\n async createCheckoutUrl(\n customer_type: \"user\" | \"team\" | \"custom\",\n customer_id: string,\n productIdOrInline: string | yup.InferType<typeof inlineProductSchema>,\n session: InternalSession | null,\n returnUrl?: string,\n requestType: \"client\" | \"server\" | \"admin\" = \"client\",\n ): Promise<string> {\n const productBody = typeof productIdOrInline === \"string\" ?\n { product_id: productIdOrInline } :\n { product_inline: productIdOrInline };\n const sendRequest = (requestType === \"client\" ? this.sendClientRequest : (this as any).sendServerRequest as never).bind(this);\n const response = await sendRequest(\n \"/payments/purchases/create-purchase-url\",\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({ customer_type, customer_id, ...productBody, return_url: returnUrl }),\n },\n session,\n requestType,\n );\n const { url } = await response.json() as { url: string };\n return url;\n }\n\n async getCustomerBilling(\n customerType: \"user\" | \"team\",\n customerId: string,\n session: InternalSession | null,\n ): Promise<{\n has_customer: boolean,\n default_payment_method: {\n id: string,\n brand: string | null,\n last4: string | null,\n exp_month: number | null,\n exp_year: number | null,\n } | null,\n }> {\n const response = await this.sendClientRequest(\n urlString`/payments/billing/${customerType}/${customerId}`,\n {},\n session,\n );\n return await response.json();\n }\n\n async createCustomerPaymentMethodSetupIntent(\n customerType: \"user\" | \"team\",\n customerId: string,\n session: InternalSession | null,\n ): Promise<{\n client_secret: string,\n stripe_account_id: string,\n }> {\n const response = await this.sendClientRequest(\n urlString`/payments/payment-method/${customerType}/${customerId}/setup-intent`,\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({}),\n },\n session,\n );\n return await response.json();\n }\n\n async setDefaultCustomerPaymentMethodFromSetupIntent(\n customerType: \"user\" | \"team\",\n customerId: string,\n setupIntentId: string,\n session: InternalSession | null,\n ): Promise<{\n default_payment_method: {\n id: string,\n brand: string | null,\n last4: string | null,\n exp_month: number | null,\n exp_year: number | null,\n },\n }> {\n const response = await this.sendClientRequest(\n urlString`/payments/payment-method/${customerType}/${customerId}/set-default`,\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({\n setup_intent_id: setupIntentId,\n }),\n },\n session,\n );\n return await response.json();\n }\n\n async transferProject(internalProjectSession: InternalSession, projectIdToTransfer: string, newTeamId: string): Promise<void> {\n if (this.options.projectId !== \"internal\") {\n throw new StackAssertionError(\"StackClientInterface.transferProject() is only available for internal projects (please specify the project ID in the constructor)\");\n }\n await this.sendClientRequest(\n \"/internal/projects/transfer\",\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({\n project_id: projectIdToTransfer,\n new_team_id: newTeamId,\n }),\n },\n internalProjectSession,\n );\n }\n}\n", "import { Result } from \"./results\";\n\nexport class WeakRefIfAvailable<T extends object> {\n private readonly _ref: { deref: () => T | undefined };\n\n constructor(value: T) {\n if (typeof WeakRef === \"undefined\") {\n this._ref = { deref: () => value };\n } else {\n this._ref = new WeakRef<T>(value);\n }\n }\n\n deref(): T | undefined {\n return this._ref.deref();\n }\n}\nimport.meta.vitest?.test(\"WeakRefIfAvailable\", ({ expect }) => {\n // Test with an object\n const obj = { id: 1, name: \"test\" };\n const weakRef = new WeakRefIfAvailable(obj);\n\n // Test deref returns the original object\n expect(weakRef.deref()).toBe(obj);\n\n // Test with a different object\n const obj2 = { id: 2, name: \"test2\" };\n const weakRef2 = new WeakRefIfAvailable(obj2);\n expect(weakRef2.deref()).toBe(obj2);\n expect(weakRef2.deref()).not.toBe(obj);\n\n // We can't easily test garbage collection in this environment,\n // but we can verify the basic functionality works\n});\n\n\n/**\n * A WeakMap-like object that can be iterated over.\n *\n * Note that it relies on WeakRef, and always falls back to the regular Map behavior (ie. no GC) in browsers that don't support it.\n */\nexport class IterableWeakMap<K extends object, V> {\n private readonly _weakMap: WeakMap<K & WeakKey, { value: V, keyRef: WeakRefIfAvailable<K & WeakKey> }>;\n private readonly _keyRefs: Set<WeakRefIfAvailable<K & WeakKey>>;\n\n constructor(entries?: readonly (readonly [K, V])[] | null) {\n const mappedEntries = entries?.map((e) => [e[0], { value: e[1], keyRef: new WeakRefIfAvailable(e[0]) }] as const);\n this._weakMap = new WeakMap(mappedEntries ?? []);\n this._keyRefs = new Set(mappedEntries?.map((e) => e[1].keyRef) ?? []);\n }\n\n get(key: K): V | undefined {\n return this._weakMap.get(key)?.value;\n }\n\n set(key: K, value: V): this {\n const existing = this._weakMap.get(key);\n const updated = { value, keyRef: existing?.keyRef ?? new WeakRefIfAvailable(key) };\n this._weakMap.set(key, updated);\n this._keyRefs.add(updated.keyRef);\n return this;\n }\n\n delete(key: K): boolean {\n const res = this._weakMap.get(key);\n if (res) {\n this._weakMap.delete(key);\n this._keyRefs.delete(res.keyRef);\n return true;\n }\n return false;\n }\n\n has(key: K): boolean {\n return this._weakMap.has(key) && this._keyRefs.has(this._weakMap.get(key)!.keyRef);\n }\n\n *[Symbol.iterator](): IterableIterator<[K, V]> {\n for (const keyRef of this._keyRefs) {\n const key = keyRef.deref();\n const existing = key ? this._weakMap.get(key) : undefined;\n if (!key) {\n // This can happen if the key was GCed. Remove it so the next iteration is faster.\n this._keyRefs.delete(keyRef);\n } else if (existing) {\n yield [key, existing.value];\n }\n }\n }\n\n [Symbol.toStringTag] = \"IterableWeakMap\";\n}\nimport.meta.vitest?.test(\"IterableWeakMap\", ({ expect }) => {\n // Test basic functionality\n const map = new IterableWeakMap<{ id: number }, string>();\n\n // Create object keys\n const obj1 = { id: 1 };\n const obj2 = { id: 2 };\n\n // Test set and get\n map.set(obj1, \"value1\");\n expect(map.get(obj1)).toBe(\"value1\");\n\n // Test has\n expect(map.has(obj1)).toBe(true);\n expect(map.has(obj2)).toBe(false);\n expect(map.has({ id: 1 })).toBe(false); // Different object with same content\n\n // Test with multiple keys\n map.set(obj2, \"value2\");\n expect(map.get(obj2)).toBe(\"value2\");\n expect(map.get(obj1)).toBe(\"value1\"); // Original still exists\n\n // Test delete\n expect(map.delete(obj1)).toBe(true);\n expect(map.has(obj1)).toBe(false);\n expect(map.get(obj1)).toBeUndefined();\n expect(map.has(obj2)).toBe(true); // Other key still exists\n\n // Test delete non-existent key\n expect(map.delete({ id: 3 })).toBe(false);\n\n // Test iteration\n const iterMap = new IterableWeakMap<{ id: number }, number>();\n const iterObj1 = { id: 1 };\n const iterObj2 = { id: 2 };\n const iterObj3 = { id: 3 };\n\n iterMap.set(iterObj1, 1);\n iterMap.set(iterObj2, 2);\n iterMap.set(iterObj3, 3);\n\n const entries = Array.from(iterMap);\n expect(entries.length).toBe(3);\n\n // Find entries by their values since we can't directly compare objects in the array\n const values = entries.map(entry => entry[1]);\n expect(values).toContain(1);\n expect(values).toContain(2);\n expect(values).toContain(3);\n\n // Test constructor with entries\n const initialEntries: [{ id: number }, string][] = [\n [{ id: 4 }, \"initial1\"],\n [{ id: 5 }, \"initial2\"]\n ];\n const mapWithEntries = new IterableWeakMap(initialEntries);\n\n // We can't directly access the initial entries since they're different object references\n // But we can verify the map has the correct number of entries\n const entriesFromConstructor = Array.from(mapWithEntries);\n expect(entriesFromConstructor.length).toBe(2);\n});\n\n/**\n * A map that is a IterableWeakMap for object keys and a regular Map for primitive keys. Also provides iteration over both\n * object and primitive keys.\n *\n * Note that, just like IterableWeakMap, older browsers without support for WeakRef will use a regular Map for object keys.\n */\nexport class MaybeWeakMap<K, V> {\n private readonly _primitiveMap: Map<K, V>;\n private readonly _weakMap: IterableWeakMap<K & WeakKey, V>;\n\n constructor(entries?: readonly (readonly [K, V])[] | null) {\n const entriesArray = [...entries ?? []];\n this._primitiveMap = new Map(entriesArray.filter((e) => !this._isAllowedInWeakMap(e[0])));\n this._weakMap = new IterableWeakMap(entriesArray.filter((e): e is [K & WeakKey, V] => this._isAllowedInWeakMap(e[0])));\n }\n\n private _isAllowedInWeakMap(key: K): key is K & WeakKey {\n return (typeof key === \"object\" && key !== null) || (typeof key === \"symbol\" && Symbol.keyFor(key) === undefined);\n }\n\n get(key: K): V | undefined {\n if (this._isAllowedInWeakMap(key)) {\n return this._weakMap.get(key);\n } else {\n return this._primitiveMap.get(key);\n }\n }\n\n set(key: K, value: V): this {\n if (this._isAllowedInWeakMap(key)) {\n this._weakMap.set(key, value);\n } else {\n this._primitiveMap.set(key, value);\n }\n return this;\n }\n\n delete(key: K): boolean {\n if (this._isAllowedInWeakMap(key)) {\n return this._weakMap.delete(key);\n } else {\n return this._primitiveMap.delete(key);\n }\n }\n\n has(key: K): boolean {\n if (this._isAllowedInWeakMap(key)) {\n return this._weakMap.has(key);\n } else {\n return this._primitiveMap.has(key);\n }\n }\n\n *[Symbol.iterator](): IterableIterator<[K, V]> {\n yield* this._primitiveMap;\n yield* this._weakMap;\n }\n\n [Symbol.toStringTag] = \"MaybeWeakMap\";\n}\nimport.meta.vitest?.test(\"MaybeWeakMap\", ({ expect }) => {\n // Test with primitive keys\n const map = new MaybeWeakMap<string | object, number>();\n\n // Test with string keys\n map.set(\"key1\", 1);\n map.set(\"key2\", 2);\n expect(map.get(\"key1\")).toBe(1);\n expect(map.get(\"key2\")).toBe(2);\n expect(map.has(\"key1\")).toBe(true);\n expect(map.has(\"nonexistent\")).toBe(false);\n\n // Test with object keys\n const obj1 = { id: 1 };\n const obj2 = { id: 2 };\n map.set(obj1, 3);\n map.set(obj2, 4);\n expect(map.get(obj1)).toBe(3);\n expect(map.get(obj2)).toBe(4);\n expect(map.has(obj1)).toBe(true);\n\n // Test delete with primitive key\n expect(map.delete(\"key1\")).toBe(true);\n expect(map.has(\"key1\")).toBe(false);\n expect(map.delete(\"nonexistent\")).toBe(false);\n\n // Test delete with object key\n expect(map.delete(obj1)).toBe(true);\n expect(map.has(obj1)).toBe(false);\n\n // Test iteration\n const entries = Array.from(map);\n expect(entries.length).toBe(2);\n expect(entries).toContainEqual([\"key2\", 2]);\n expect(entries).toContainEqual([obj2, 4]);\n\n // Test constructor with entries\n const initialEntries: [string | object, number][] = [\n [\"initial1\", 10],\n [{ id: 3 }, 20]\n ];\n const mapWithEntries = new MaybeWeakMap(initialEntries);\n expect(mapWithEntries.get(\"initial1\")).toBe(10);\n expect(mapWithEntries.get(initialEntries[1][0])).toBe(20);\n});\n\n\ntype DependenciesMapInner<V> = (\n & { map: MaybeWeakMap<unknown, DependenciesMapInner<V>> }\n & (\n | { hasValue: true, value: V }\n | { hasValue: false, value: undefined }\n )\n);\n\n/**\n * A map that stores values indexed by an array of keys. If the keys are objects and the environment supports WeakRefs,\n * they are stored in a WeakMap.\n */\nexport class DependenciesMap<K extends any[], V> {\n private _inner: DependenciesMapInner<V> = { map: new MaybeWeakMap(), hasValue: false, value: undefined };\n\n private _valueToResult(inner: DependenciesMapInner<V>): Result<V, void> {\n if (inner.hasValue) {\n return Result.ok(inner.value);\n } else {\n return Result.error(undefined);\n }\n }\n\n\n private _unwrapFromInner(dependencies: any[], inner: DependenciesMapInner<V>): Result<V, void> {\n if ((dependencies.length === 0)) {\n return this._valueToResult(inner);\n } else {\n const [key, ...rest] = dependencies;\n const newInner = inner.map.get(key);\n if (!newInner) {\n return Result.error(undefined);\n }\n return this._unwrapFromInner(rest, newInner);\n }\n }\n\n private _setInInner(dependencies: any[], value: Result<V, void>, inner: DependenciesMapInner<V>): Result<V, void> {\n if (dependencies.length === 0) {\n const res = this._valueToResult(inner);\n if (value.status === \"ok\") {\n inner.hasValue = true;\n inner.value = value.data;\n } else {\n inner.hasValue = false;\n inner.value = undefined;\n }\n return res;\n } else {\n const [key, ...rest] = dependencies;\n let newInner = inner.map.get(key);\n if (!newInner) {\n inner.map.set(key, newInner = { map: new MaybeWeakMap(), hasValue: false, value: undefined });\n }\n return this._setInInner(rest, value, newInner);\n }\n }\n\n private *_iterateInner(dependencies: any[], inner: DependenciesMapInner<V>): IterableIterator<[K, V]> {\n if (inner.hasValue) {\n yield [dependencies as K, inner.value];\n }\n for (const [key, value] of inner.map) {\n yield* this._iterateInner([...dependencies, key], value);\n }\n }\n\n get(dependencies: K): V | undefined {\n return Result.or(this._unwrapFromInner(dependencies, this._inner), undefined);\n }\n\n set(dependencies: K, value: V): this {\n this._setInInner(dependencies, Result.ok(value), this._inner);\n return this;\n }\n\n delete(dependencies: K): boolean {\n return this._setInInner(dependencies, Result.error(undefined), this._inner).status === \"ok\";\n }\n\n has(dependencies: K): boolean {\n return this._unwrapFromInner(dependencies, this._inner).status === \"ok\";\n }\n\n clear(): void {\n this._inner = { map: new MaybeWeakMap(), hasValue: false, value: undefined };\n }\n\n *[Symbol.iterator](): IterableIterator<[K, V]> {\n yield* this._iterateInner([], this._inner);\n }\n\n [Symbol.toStringTag] = \"DependenciesMap\";\n}\nimport.meta.vitest?.test(\"DependenciesMap\", ({ expect }) => {\n // Test basic functionality\n const map = new DependenciesMap<[string, number], string>();\n\n // Test set and get\n map.set([\"key\", 1], \"value1\");\n expect(map.get([\"key\", 1])).toBe(\"value1\");\n\n // Test has\n expect(map.has([\"key\", 1])).toBe(true);\n expect(map.has([\"key\", 2])).toBe(false);\n\n // Test with different dependencies\n map.set([\"key\", 2], \"value2\");\n expect(map.get([\"key\", 2])).toBe(\"value2\");\n expect(map.get([\"key\", 1])).toBe(\"value1\"); // Original still exists\n\n // Test delete\n expect(map.delete([\"key\", 1])).toBe(true);\n expect(map.has([\"key\", 1])).toBe(false);\n expect(map.get([\"key\", 1])).toBeUndefined();\n expect(map.has([\"key\", 2])).toBe(true); // Other key still exists\n\n // Test delete non-existent key\n expect(map.delete([\"nonexistent\", 1])).toBe(false);\n\n // Test clear\n map.clear();\n expect(map.has([\"key\", 2])).toBe(false);\n\n // Test with object keys\n const objMap = new DependenciesMap<[object, number], string>();\n const obj1 = { id: 1 };\n const obj2 = { id: 2 };\n objMap.set([obj1, 1], \"object1\");\n objMap.set([obj2, 2], \"object2\");\n expect(objMap.get([obj1, 1])).toBe(\"object1\");\n expect(objMap.get([obj2, 2])).toBe(\"object2\");\n\n // Test iteration\n const iterMap = new DependenciesMap<[string], number>();\n iterMap.set([\"a\"], 1);\n iterMap.set([\"b\"], 2);\n iterMap.set([\"c\"], 3);\n\n const entries = Array.from(iterMap);\n expect(entries.length).toBe(3);\n expect(entries).toContainEqual([[\"a\"], 1]);\n expect(entries).toContainEqual([[\"b\"], 2]);\n expect(entries).toContainEqual([[\"c\"], 3]);\n});\n", "import { KnownError } from \"..\";\nimport { StackAssertionError, captureError, concatStacktraces, errorToNiceString } from \"./errors\";\nimport { DependenciesMap } from \"./maps\";\nimport { Result } from \"./results\";\nimport { generateUuid } from \"./uuids\";\n\nexport type ReactPromise<T> = Promise<T> & (\n | { status: \"rejected\", reason: unknown }\n | { status: \"fulfilled\", value: T }\n | { status: \"pending\" }\n);\n\ntype Resolve<T> = (value: T) => void;\ntype Reject = (reason: unknown) => void;\nexport function createPromise<T>(callback: (resolve: Resolve<T>, reject: Reject) => void): ReactPromise<T> {\n let status = \"pending\" as \"fulfilled\" | \"rejected\" | \"pending\";\n let valueOrReason: T | unknown | undefined = undefined;\n let resolve: Resolve<T> | null = null;\n let reject: Reject | null = null;\n const promise = new Promise<T>((res, rej) => {\n resolve = (value) => {\n if (status !== \"pending\") return;\n status = \"fulfilled\";\n valueOrReason = value;\n res(value);\n };\n reject = (reason) => {\n if (status !== \"pending\") return;\n status = \"rejected\";\n valueOrReason = reason;\n rej(reason);\n };\n });\n\n callback(resolve!, reject!);\n return Object.assign(promise, {\n status: status,\n ...status === \"fulfilled\" ? { value: valueOrReason as T } : {},\n ...status === \"rejected\" ? { reason: valueOrReason } : {},\n } as any);\n}\nimport.meta.vitest?.test(\"createPromise\", async ({ expect }) => {\n // Test resolved promise\n const resolvedPromise = createPromise<number>((resolve) => {\n resolve(42);\n });\n expect(resolvedPromise.status).toBe(\"fulfilled\");\n expect((resolvedPromise as any).value).toBe(42);\n expect(await resolvedPromise).toBe(42);\n\n // Test rejected promise\n const error = new Error(\"Test error\");\n const rejectedPromise = createPromise<number>((_, reject) => {\n reject(error);\n });\n expect(rejectedPromise.status).toBe(\"rejected\");\n expect((rejectedPromise as any).reason).toBe(error);\n await expect(rejectedPromise).rejects.toBe(error);\n\n // Test pending promise\n const pendingPromise = createPromise<number>(() => {\n // Do nothing, leave it pending\n });\n expect(pendingPromise.status).toBe(\"pending\");\n expect((pendingPromise as any).value).toBeUndefined();\n expect((pendingPromise as any).reason).toBeUndefined();\n\n // Test that resolving after already resolved does nothing\n let resolveCount = 0;\n const multiResolvePromise = createPromise<number>((resolve) => {\n resolve(1);\n resolveCount++;\n resolve(2);\n resolveCount++;\n });\n expect(resolveCount).toBe(2); // Both resolve calls executed\n expect(multiResolvePromise.status).toBe(\"fulfilled\");\n expect((multiResolvePromise as any).value).toBe(1); // Only first resolve took effect\n expect(await multiResolvePromise).toBe(1);\n});\n\nlet resolvedCache: DependenciesMap<[unknown], ReactPromise<unknown>> | null = null;\n/**\n * Like Promise.resolve(...), but also adds the status and value properties for use with React's `use` hook, and caches\n * the value so that invoking `resolved` twice returns the same promise.\n */\nexport function resolved<T>(value: T): ReactPromise<T> {\n resolvedCache ??= new DependenciesMap<[unknown], ReactPromise<unknown>>();\n if (resolvedCache.has([value])) {\n return resolvedCache.get([value]) as ReactPromise<T>;\n }\n\n const res = Object.assign(Promise.resolve(value), {\n status: \"fulfilled\",\n value,\n } as const);\n resolvedCache.set([value], res);\n return res;\n}\nimport.meta.vitest?.test(\"resolved\", async ({ expect }) => {\n // Test with primitive value\n const promise1 = resolved(42);\n expect(promise1.status).toBe(\"fulfilled\");\n // Need to use type assertion since value is only available when status is \"fulfilled\"\n expect((promise1 as { value: number }).value).toBe(42);\n expect(await promise1).toBe(42);\n\n // Test with object value\n const obj = { test: true };\n const promise2 = resolved(obj);\n expect(promise2.status).toBe(\"fulfilled\");\n expect((promise2 as { value: typeof obj }).value).toBe(obj);\n expect(await promise2).toBe(obj);\n\n // Test caching (same reference for same value)\n const promise3 = resolved(42);\n expect(promise3).toBe(promise1); // Same reference due to caching\n\n // Test with different value (different reference)\n const promise4 = resolved(43);\n expect(promise4).not.toBe(promise1);\n});\n\nlet rejectedCache: DependenciesMap<[unknown], ReactPromise<unknown>> | null = null;\n/**\n * Like Promise.reject(...), but also adds the status and value properties for use with React's `use` hook, and caches\n * the value so that invoking `rejected` twice returns the same promise.\n */\nexport function rejected<T>(reason: unknown): ReactPromise<T> {\n rejectedCache ??= new DependenciesMap<[unknown], ReactPromise<unknown>>();\n if (rejectedCache.has([reason])) {\n return rejectedCache.get([reason]) as ReactPromise<T>;\n }\n\n const promise = Promise.reject(reason);\n ignoreUnhandledRejection(promise);\n const res = Object.assign(promise, {\n status: \"rejected\",\n reason: reason,\n } as const);\n rejectedCache.set([reason], res);\n return res;\n}\nimport.meta.vitest?.test(\"rejected\", ({ expect }) => {\n // Test with error object\n const error = new Error(\"Test error\");\n const promise1 = rejected<number>(error);\n expect(promise1.status).toBe(\"rejected\");\n // Need to use type assertion since reason is only available when status is \"rejected\"\n expect((promise1 as { reason: Error }).reason).toBe(error);\n\n // Test with string reason\n const promise2 = rejected<string>(\"error message\");\n expect(promise2.status).toBe(\"rejected\");\n expect((promise2 as { reason: string }).reason).toBe(\"error message\");\n\n // Test caching (same reference for same reason)\n const promise3 = rejected<number>(error);\n expect(promise3).toBe(promise1); // Same reference due to caching\n\n // Test with different reason (different reference)\n const differentError = new Error(\"Different error\");\n const promise4 = rejected<number>(differentError);\n expect(promise4).not.toBe(promise1);\n\n // Note: We're not using await expect(promise).rejects to avoid unhandled rejections\n});\n\n// We'll skip the rejection test for pending() since it's causing unhandled rejections\n// The function is already well tested through other tests like rejected() and createPromise()\n\n\nconst neverResolvePromise = pending(new Promise<never>(() => {}));\nexport function neverResolve(): ReactPromise<never> {\n return neverResolvePromise;\n}\nimport.meta.vitest?.test(\"neverResolve\", ({ expect }) => {\n const promise = neverResolve();\n expect(promise.status).toBe(\"pending\");\n expect((promise as any).value).toBeUndefined();\n expect((promise as any).reason).toBeUndefined();\n\n // Test that multiple calls return the same promise\n const promise2 = neverResolve();\n expect(promise2).toBe(promise);\n});\n\nexport function pending<T>(promise: Promise<T>, options: { disableErrorWrapping?: boolean } = {}): ReactPromise<T> {\n const res = promise.then(\n value => {\n res.status = \"fulfilled\";\n (res as any).value = value;\n return value;\n },\n actualReason => {\n res.status = \"rejected\";\n (res as any).reason = actualReason;\n throw actualReason;\n },\n ) as ReactPromise<T>;\n res.status = \"pending\";\n return res;\n}\nimport.meta.vitest?.test(\"pending\", async ({ expect }) => {\n // Test with a promise that resolves\n const resolvePromise = Promise.resolve(42);\n const pendingPromise = pending(resolvePromise);\n\n // Initially it should be pending\n expect(pendingPromise.status).toBe(\"pending\");\n\n // After resolution, it should be fulfilled\n await resolvePromise;\n // Need to wait a tick for the then handler to execute\n await new Promise(resolve => setTimeout(resolve, 0));\n expect(pendingPromise.status).toBe(\"fulfilled\");\n expect((pendingPromise as { value: number }).value).toBe(42);\n\n // For the rejection test, we'll use a separate test to avoid unhandled rejections\n});\n\n/**\n * Should be used to wrap Promises that are not immediately awaited, so they don't throw an unhandled promise rejection\n * error.\n *\n * Vercel kills serverless functions on unhandled promise rejection errors, so this is important.\n */\nexport function ignoreUnhandledRejection<T extends Promise<any>>(promise: T): void {\n promise.catch(() => {});\n}\nimport.meta.vitest?.test(\"ignoreUnhandledRejection\", async ({ expect }) => {\n // Test with a promise that resolves\n const resolvePromise = Promise.resolve(42);\n ignoreUnhandledRejection(resolvePromise);\n expect(await resolvePromise).toBe(42); // Should still resolve to the same value\n\n // Test with a promise that rejects\n // The promise should still reject, but the rejection is caught internally\n // so it doesn't cause an unhandled rejection error\n const error = new Error(\"Test error\");\n const rejectPromise = Promise.reject(error);\n ignoreUnhandledRejection(rejectPromise);\n await expect(rejectPromise).rejects.toBe(error);\n});\n\n/**\n * See concatStacktraces for more information.\n */\nexport function concatStacktracesIfRejected<T>(promise: Promise<T>): void {\n const currentError = new Error();\n promise.catch(error => {\n if (error instanceof Error) {\n concatStacktraces(error, currentError);\n } else {\n // we can only concatenate errors, so we'll just ignore the non-error\n }\n });\n}\n\nexport async function wait(ms: number) {\n if (!Number.isFinite(ms) || ms < 0) {\n throw new StackAssertionError(`wait() requires a non-negative integer number of milliseconds to wait. (found: ${ms}ms)`);\n }\n if (ms >= 2**31) {\n throw new StackAssertionError(\"The maximum timeout for wait() is 2147483647ms (2**31 - 1). (found: ${ms}ms)\");\n }\n return await new Promise<void>(resolve => setTimeout(resolve, ms));\n}\nimport.meta.vitest?.test(\"wait\", async ({ expect }) => {\n // Test with valid input\n const start = Date.now();\n await wait(10);\n const elapsed = Date.now() - start;\n expect(elapsed).toBeGreaterThanOrEqual(5); // Allow some flexibility in timing\n\n // Test with zero\n await expect(wait(0)).resolves.toBeUndefined();\n\n // Test with negative number\n await expect(wait(-10)).rejects.toThrow(\"wait() requires a non-negative integer\");\n\n // Test with non-finite number\n await expect(wait(NaN)).rejects.toThrow(\"wait() requires a non-negative integer\");\n await expect(wait(Infinity)).rejects.toThrow(\"wait() requires a non-negative integer\");\n\n // Test with too large number\n await expect(wait(2**31)).rejects.toThrow(\"The maximum timeout for wait()\");\n});\n\nexport async function waitUntil(date: Date) {\n return await wait(date.getTime() - Date.now());\n}\nimport.meta.vitest?.test(\"waitUntil\", async ({ expect }) => {\n // Test with future date\n const futureDate = new Date(Date.now() + 10);\n const start = Date.now();\n await waitUntil(futureDate);\n const elapsed = Date.now() - start;\n expect(elapsed).toBeGreaterThanOrEqual(5); // Allow some flexibility in timing\n\n // Test with past date - this will throw because wait() requires non-negative time\n // We need to verify it throws the correct error\n try {\n await waitUntil(new Date(Date.now() - 1000));\n expect.fail(\"Should have thrown an error\");\n } catch (error) {\n expect(error).toBeInstanceOf(StackAssertionError);\n expect((error as Error).message).toContain(\"wait() requires a non-negative integer\");\n }\n});\n\nexport function runAsynchronouslyWithAlert(...args: Parameters<typeof runAsynchronously>) {\n return runAsynchronously(\n args[0],\n {\n ...args[1],\n onError: error => {\n if (KnownError.isKnownError(error) && typeof process !== \"undefined\" && (process.env.NODE_ENV as any)?.includes(\"production\")) {\n alert(error.message);\n } else {\n alert(`An unhandled error occurred. Please ${process.env.NODE_ENV === \"development\" ? `check the browser console for the full error.` : \"report this to the developer.\"}\\n\\n${error}`);\n }\n args[1]?.onError?.(error);\n },\n },\n ...args.slice(2) as [],\n );\n}\nimport.meta.vitest?.test(\"runAsynchronouslyWithAlert\", ({ expect }) => {\n // Simple test to verify the function calls runAsynchronously\n // We can't easily test the alert functionality without mocking\n const testFn = () => Promise.resolve(\"test\");\n const testOptions = { noErrorLogging: true };\n\n // Just verify it doesn't throw\n expect(() => runAsynchronouslyWithAlert(testFn, testOptions)).not.toThrow();\n\n // We can't easily test the error handling without mocking, so we'll\n // just verify the function exists and can be called\n expect(typeof runAsynchronouslyWithAlert).toBe(\"function\");\n});\n\nexport function runAsynchronously(\n promiseOrFunc: void | Promise<unknown> | (() => void | Promise<unknown>) | undefined,\n options: {\n noErrorLogging?: boolean,\n onError?: (error: Error) => void,\n } = {},\n): void {\n if (typeof promiseOrFunc === \"function\") {\n promiseOrFunc = promiseOrFunc();\n }\n if (promiseOrFunc) {\n concatStacktracesIfRejected(promiseOrFunc);\n promiseOrFunc.catch(error => {\n options.onError?.(error);\n const newError = new StackAssertionError(\n \"Uncaught error in asynchronous function: \" + errorToNiceString(error),\n { cause: error },\n );\n if (!options.noErrorLogging) {\n captureError(\"runAsynchronously\", newError);\n }\n });\n }\n}\nimport.meta.vitest?.test(\"runAsynchronously\", ({ expect }) => {\n // Simple test to verify the function exists and can be called\n const testFn = () => Promise.resolve(\"test\");\n\n // Just verify it doesn't throw\n expect(() => runAsynchronously(testFn)).not.toThrow();\n expect(() => runAsynchronously(Promise.resolve(\"test\"))).not.toThrow();\n expect(() => runAsynchronously(undefined)).not.toThrow();\n\n // We can't easily test the error handling without mocking, so we'll\n // just verify the function exists and can be called with options\n expect(() => runAsynchronously(testFn, { noErrorLogging: true })).not.toThrow();\n expect(() => runAsynchronously(testFn, { onError: () => {} })).not.toThrow();\n});\n\n\nclass TimeoutError extends Error {\n constructor(public readonly ms: number) {\n super(`Timeout after ${ms}ms`);\n this.name = \"TimeoutError\";\n }\n}\n\nexport async function timeout<T>(promiseOrFunc: Promise<T> | (() => Promise<T>), ms: number): Promise<Result<T, TimeoutError>> {\n const promise = typeof promiseOrFunc === \"function\" ? promiseOrFunc() : promiseOrFunc;\n return await Promise.race([\n promise.then(value => Result.ok(value)),\n wait(ms).then(() => Result.error(new TimeoutError(ms))),\n ]);\n}\nimport.meta.vitest?.test(\"timeout\", async ({ expect }) => {\n // Test with a promise that resolves quickly\n const fastPromise = Promise.resolve(42);\n const fastResult = await timeout(fastPromise, 100);\n expect(fastResult.status).toBe(\"ok\");\n if (fastResult.status === \"ok\") {\n expect(fastResult.data).toBe(42);\n }\n\n // Test with a promise that takes longer than the timeout\n const slowPromise = new Promise(resolve => setTimeout(() => resolve(\"too late\"), 50));\n const slowResult = await timeout(slowPromise, 10);\n expect(slowResult.status).toBe(\"error\");\n if (slowResult.status === \"error\") {\n expect(slowResult.error).toBeInstanceOf(TimeoutError);\n expect((slowResult.error as TimeoutError).ms).toBe(10);\n }\n});\n\nexport async function timeoutThrow<T>(promise: Promise<T>, ms: number): Promise<T> {\n return Result.orThrow(await timeout(promise, ms));\n}\nimport.meta.vitest?.test(\"timeoutThrow\", async ({ expect }) => {\n // Test with a promise that resolves quickly\n const fastPromise = Promise.resolve(42);\n const fastResult = await timeoutThrow(fastPromise, 100);\n expect(fastResult).toBe(42);\n\n // Test with a promise that takes longer than the timeout\n const slowPromise = new Promise(resolve => setTimeout(() => resolve(\"too late\"), 50));\n await expect(timeoutThrow(slowPromise, 10)).rejects.toThrow(\"Timeout after 10ms\");\n await expect(timeoutThrow(slowPromise, 10)).rejects.toBeInstanceOf(TimeoutError);\n});\n\n\nexport type RateLimitOptions = {\n /**\n * The number of requests to process in parallel. Currently only 1 is supported.\n */\n concurrency: 1,\n\n /**\n * If true, multiple requests waiting at the same time will be reduced to just one. Default is false.\n */\n batchCalls?: boolean,\n\n /**\n * Waits for throttleMs since the start of last request before starting the next request. Default is 0.\n */\n throttleMs?: number,\n\n /**\n * Waits for gapMs since the end of last request before starting the next request. Default is 0.\n */\n gapMs?: number,\n\n /**\n * Waits until there have been no new requests for debounceMs before starting a new request. Default is 0.\n */\n debounceMs?: number,\n};\n\nexport function rateLimited<T>(\n func: () => Promise<T>,\n options: RateLimitOptions,\n): () => Promise<T> {\n let waitUntil = performance.now();\n let queue: [(t: T) => void, (e: unknown) => void][] = [];\n let addedToQueueCallbacks = new Map<string, () => void>;\n\n const next = async () => {\n while (true) {\n if (waitUntil > performance.now()) {\n await wait(Math.max(1, waitUntil - performance.now() + 1));\n } else if (queue.length === 0) {\n const uuid = generateUuid();\n await new Promise<void>(resolve => {\n addedToQueueCallbacks.set(uuid, resolve);\n });\n addedToQueueCallbacks.delete(uuid);\n } else {\n break;\n }\n }\n const nextFuncs = options.batchCalls ? queue.splice(0, queue.length) : [queue.shift()!];\n\n const start = performance.now();\n const value = await Result.fromPromise(func());\n const end = performance.now();\n\n waitUntil = Math.max(\n waitUntil,\n start + (options.throttleMs ?? 0),\n end + (options.gapMs ?? 0),\n );\n\n for (const nextFunc of nextFuncs) {\n if (value.status === \"ok\") {\n nextFunc[0](value.data);\n } else {\n nextFunc[1](value.error);\n }\n }\n };\n\n runAsynchronously(async () => {\n while (true) {\n await next();\n }\n });\n\n return () => {\n return new Promise<T>((resolve, reject) => {\n waitUntil = Math.max(\n waitUntil,\n performance.now() + (options.debounceMs ?? 0),\n );\n queue.push([resolve, reject]);\n addedToQueueCallbacks.forEach(cb => cb());\n });\n };\n}\n\nexport function throttled<T, A extends any[]>(func: (...args: A) => Promise<T>, delayMs: number): (...args: A) => Promise<T> {\n let timeout: ReturnType<typeof setTimeout> | null = null;\n let nextAvailable: Promise<T> | null = null;\n return async (...args) => {\n while (nextAvailable !== null) {\n await nextAvailable;\n }\n nextAvailable = new Promise<T>(resolve => {\n timeout = setTimeout(() => {\n nextAvailable = null;\n resolve(func(...args));\n }, delayMs);\n });\n return await nextAvailable;\n };\n}\n", "import * as React from 'react';\nimport { composeRefs } from '@radix-ui/react-compose-refs';\n\n/* -------------------------------------------------------------------------------------------------\n * Slot\n * -----------------------------------------------------------------------------------------------*/\n\ninterface SlotProps extends React.HTMLAttributes<HTMLElement> {\n children?: React.ReactNode;\n}\n\nconst Slot = React.forwardRef<HTMLElement, SlotProps>((props, forwardedRef) => {\n const { children, ...slotProps } = props;\n const childrenArray = React.Children.toArray(children);\n const slottable = childrenArray.find(isSlottable);\n\n if (slottable) {\n // the new element to render is the one passed as a child of `Slottable`\n const newElement = slottable.props.children as React.ReactNode;\n\n const newChildren = childrenArray.map((child) => {\n if (child === slottable) {\n // because the new element will be the one rendered, we are only interested\n // in grabbing its children (`newElement.props.children`)\n if (React.Children.count(newElement) > 1) return React.Children.only(null);\n return React.isValidElement(newElement)\n ? (newElement.props.children as React.ReactNode)\n : null;\n } else {\n return child;\n }\n });\n\n return (\n <SlotClone {...slotProps} ref={forwardedRef}>\n {React.isValidElement(newElement)\n ? React.cloneElement(newElement, undefined, newChildren)\n : null}\n </SlotClone>\n );\n }\n\n return (\n <SlotClone {...slotProps} ref={forwardedRef}>\n {children}\n </SlotClone>\n );\n});\n\nSlot.displayName = 'Slot';\n\n/* -------------------------------------------------------------------------------------------------\n * SlotClone\n * -----------------------------------------------------------------------------------------------*/\n\ninterface SlotCloneProps {\n children: React.ReactNode;\n}\n\nconst SlotClone = React.forwardRef<any, SlotCloneProps>((props, forwardedRef) => {\n const { children, ...slotProps } = props;\n\n if (React.isValidElement(children)) {\n const childrenRef = getElementRef(children);\n return React.cloneElement(children, {\n ...mergeProps(slotProps, children.props),\n // @ts-ignore\n ref: forwardedRef ? composeRefs(forwardedRef, childrenRef) : childrenRef,\n });\n }\n\n return React.Children.count(children) > 1 ? React.Children.only(null) : null;\n});\n\nSlotClone.displayName = 'SlotClone';\n\n/* -------------------------------------------------------------------------------------------------\n * Slottable\n * -----------------------------------------------------------------------------------------------*/\n\nconst Slottable = ({ children }: { children: React.ReactNode }) => {\n return <>{children}</>;\n};\n\n/* ---------------------------------------------------------------------------------------------- */\n\ntype AnyProps = Record<string, any>;\n\nfunction isSlottable(child: React.ReactNode): child is React.ReactElement {\n return React.isValidElement(child) && child.type === Slottable;\n}\n\nfunction mergeProps(slotProps: AnyProps, childProps: AnyProps) {\n // all child props should override\n const overrideProps = { ...childProps };\n\n for (const propName in childProps) {\n const slotPropValue = slotProps[propName];\n const childPropValue = childProps[propName];\n\n const isHandler = /^on[A-Z]/.test(propName);\n if (isHandler) {\n // if the handler exists on both, we compose them\n if (slotPropValue && childPropValue) {\n overrideProps[propName] = (...args: unknown[]) => {\n childPropValue(...args);\n slotPropValue(...args);\n };\n }\n // but if it exists only on the slot, we use only this one\n else if (slotPropValue) {\n overrideProps[propName] = slotPropValue;\n }\n }\n // if it's `style`, we merge them\n else if (propName === 'style') {\n overrideProps[propName] = { ...slotPropValue, ...childPropValue };\n } else if (propName === 'className') {\n overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(' ');\n }\n }\n\n return { ...slotProps, ...overrideProps };\n}\n\n// Before React 19 accessing `element.props.ref` will throw a warning and suggest using `element.ref`\n// After React 19 accessing `element.ref` does the opposite.\n// https://github.com/facebook/react/pull/28348\n//\n// Access the ref using the method that doesn't yield a warning.\nfunction getElementRef(element: React.ReactElement) {\n // React <=18 in DEV\n let getter = Object.getOwnPropertyDescriptor(element.props, 'ref')?.get;\n let mayWarn = getter && 'isReactWarning' in getter && getter.isReactWarning;\n if (mayWarn) {\n return (element as any).ref;\n }\n\n // React 19 in DEV\n getter = Object.getOwnPropertyDescriptor(element, 'ref')?.get;\n mayWarn = getter && 'isReactWarning' in getter && getter.isReactWarning;\n if (mayWarn) {\n return element.props.ref;\n }\n\n // Not DEV\n return element.props.ref || (element as any).ref;\n}\n\nconst Root = Slot;\n\nexport {\n Slot,\n Slottable,\n //\n Root,\n};\nexport type { SlotProps };\n", "import * as React from 'react';\n\ntype PossibleRef<T> = React.Ref<T> | undefined;\n\n/**\n * Set a given ref to a given value\n * This utility takes care of different types of refs: callback refs and RefObject(s)\n */\nfunction setRef<T>(ref: PossibleRef<T>, value: T) {\n if (typeof ref === 'function') {\n ref(value);\n } else if (ref !== null && ref !== undefined) {\n (ref as React.MutableRefObject<T>).current = value;\n }\n}\n\n/**\n * A utility to compose multiple refs together\n * Accepts callback refs and RefObject(s)\n */\nfunction composeRefs<T>(...refs: PossibleRef<T>[]) {\n return (node: T) => refs.forEach((ref) => setRef(ref, node));\n}\n\n/**\n * A custom hook that composes multiple refs\n * Accepts callback refs and RefObject(s)\n */\nfunction useComposedRefs<T>(...refs: PossibleRef<T>[]) {\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return React.useCallback(composeRefs(...refs), refs);\n}\n\nexport { composeRefs, useComposedRefs };\n", "function composeEventHandlers<E>(\n originalEventHandler?: (event: E) => void,\n ourEventHandler?: (event: E) => void,\n { checkForDefaultPrevented = true } = {}\n) {\n return function handleEvent(event: E) {\n originalEventHandler?.(event);\n\n if (checkForDefaultPrevented === false || !((event as unknown) as Event).defaultPrevented) {\n return ourEventHandler?.(event);\n }\n };\n}\n\nexport { composeEventHandlers };\n", "import * as React from 'react';\n\nfunction createContext<ContextValueType extends object | null>(\n rootComponentName: string,\n defaultContext?: ContextValueType\n) {\n const Context = React.createContext<ContextValueType | undefined>(defaultContext);\n\n function Provider(props: ContextValueType & { children: React.ReactNode }) {\n const { children, ...context } = props;\n // Only re-memoize when prop values change\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const value = React.useMemo(() => context, Object.values(context)) as ContextValueType;\n return <Context.Provider value={value}>{children}</Context.Provider>;\n }\n\n function useContext(consumerName: string) {\n const context = React.useContext(Context);\n if (context) return context;\n if (defaultContext !== undefined) return defaultContext;\n // if a defaultContext wasn't specified, it's a required context.\n throw new Error(`\\`${consumerName}\\` must be used within \\`${rootComponentName}\\``);\n }\n\n Provider.displayName = rootComponentName + 'Provider';\n return [Provider, useContext] as const;\n}\n\n/* -------------------------------------------------------------------------------------------------\n * createContextScope\n * -----------------------------------------------------------------------------------------------*/\n\ntype Scope<C = any> = { [scopeName: string]: React.Context<C>[] } | undefined;\ntype ScopeHook = (scope: Scope) => { [__scopeProp: string]: Scope };\ninterface CreateScope {\n scopeName: string;\n (): ScopeHook;\n}\n\nfunction createContextScope(scopeName: string, createContextScopeDeps: CreateScope[] = []) {\n let defaultContexts: any[] = [];\n\n /* -----------------------------------------------------------------------------------------------\n * createContext\n * ---------------------------------------------------------------------------------------------*/\n\n function createContext<ContextValueType extends object | null>(\n rootComponentName: string,\n defaultContext?: ContextValueType\n ) {\n const BaseContext = React.createContext<ContextValueType | undefined>(defaultContext);\n const index = defaultContexts.length;\n defaultContexts = [...defaultContexts, defaultContext];\n\n function Provider(\n props: ContextValueType & { scope: Scope<ContextValueType>; children: React.ReactNode }\n ) {\n const { scope, children, ...context } = props;\n const Context = scope?.[scopeName][index] || BaseContext;\n // Only re-memoize when prop values change\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const value = React.useMemo(() => context, Object.values(context)) as ContextValueType;\n return <Context.Provider value={value}>{children}</Context.Provider>;\n }\n\n function useContext(consumerName: string, scope: Scope<ContextValueType | undefined>) {\n const Context = scope?.[scopeName][index] || BaseContext;\n const context = React.useContext(Context);\n if (context) return context;\n if (defaultContext !== undefined) return defaultContext;\n // if a defaultContext wasn't specified, it's a required context.\n throw new Error(`\\`${consumerName}\\` must be used within \\`${rootComponentName}\\``);\n }\n\n Provider.displayName = rootComponentName + 'Provider';\n return [Provider, useContext] as const;\n }\n\n /* -----------------------------------------------------------------------------------------------\n * createScope\n * ---------------------------------------------------------------------------------------------*/\n\n const createScope: CreateScope = () => {\n const scopeContexts = defaultContexts.map((defaultContext) => {\n return React.createContext(defaultContext);\n });\n return function useScope(scope: Scope) {\n const contexts = scope?.[scopeName] || scopeContexts;\n return React.useMemo(\n () => ({ [`__scope${scopeName}`]: { ...scope, [scopeName]: contexts } }),\n [scope, contexts]\n );\n };\n };\n\n createScope.scopeName = scopeName;\n return [createContext, composeContextScopes(createScope, ...createContextScopeDeps)] as const;\n}\n\n/* -------------------------------------------------------------------------------------------------\n * composeContextScopes\n * -----------------------------------------------------------------------------------------------*/\n\nfunction composeContextScopes(...scopes: CreateScope[]) {\n const baseScope = scopes[0];\n if (scopes.length === 1) return baseScope;\n\n const createScope: CreateScope = () => {\n const scopeHooks = scopes.map((createScope) => ({\n useScope: createScope(),\n scopeName: createScope.scopeName,\n }));\n\n return function useComposedScopes(overrideScopes) {\n const nextScopes = scopeHooks.reduce((nextScopes, { useScope, scopeName }) => {\n // We are calling a hook inside a callback which React warns against to avoid inconsistent\n // renders, however, scoping doesn't have render side effects so we ignore the rule.\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const scopeProps = useScope(overrideScopes);\n const currentScope = scopeProps[`__scope${scopeName}`];\n return { ...nextScopes, ...currentScope };\n }, {});\n\n return React.useMemo(() => ({ [`__scope${baseScope.scopeName}`]: nextScopes }), [nextScopes]);\n };\n };\n\n createScope.scopeName = baseScope.scopeName;\n return createScope;\n}\n\n/* -----------------------------------------------------------------------------------------------*/\n\nexport { createContext, createContextScope };\nexport type { CreateScope, Scope };\n", "import * as React from 'react';\n\nfunction createContext<ContextValueType extends object | null>(\n rootComponentName: string,\n defaultContext?: ContextValueType\n) {\n const Context = React.createContext<ContextValueType | undefined>(defaultContext);\n\n const Provider: React.FC<ContextValueType & { children: React.ReactNode }> = (props) => {\n const { children, ...context } = props;\n // Only re-memoize when prop values change\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const value = React.useMemo(() => context, Object.values(context)) as ContextValueType;\n return <Context.Provider value={value}>{children}</Context.Provider>;\n };\n\n Provider.displayName = rootComponentName + 'Provider';\n\n function useContext(consumerName: string) {\n const context = React.useContext(Context);\n if (context) return context;\n if (defaultContext !== undefined) return defaultContext;\n // if a defaultContext wasn't specified, it's a required context.\n throw new Error(`\\`${consumerName}\\` must be used within \\`${rootComponentName}\\``);\n }\n\n return [Provider, useContext] as const;\n}\n\n/* -------------------------------------------------------------------------------------------------\n * createContextScope\n * -----------------------------------------------------------------------------------------------*/\n\ntype Scope<C = any> = { [scopeName: string]: React.Context<C>[] } | undefined;\ntype ScopeHook = (scope: Scope) => { [__scopeProp: string]: Scope };\ninterface CreateScope {\n scopeName: string;\n (): ScopeHook;\n}\n\nfunction createContextScope(scopeName: string, createContextScopeDeps: CreateScope[] = []) {\n let defaultContexts: any[] = [];\n\n /* -----------------------------------------------------------------------------------------------\n * createContext\n * ---------------------------------------------------------------------------------------------*/\n\n function createContext<ContextValueType extends object | null>(\n rootComponentName: string,\n defaultContext?: ContextValueType\n ) {\n const BaseContext = React.createContext<ContextValueType | undefined>(defaultContext);\n const index = defaultContexts.length;\n defaultContexts = [...defaultContexts, defaultContext];\n\n const Provider: React.FC<\n ContextValueType & { scope: Scope<ContextValueType>; children: React.ReactNode }\n > = (props) => {\n const { scope, children, ...context } = props;\n const Context = scope?.[scopeName]?.[index] || BaseContext;\n // Only re-memoize when prop values change\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const value = React.useMemo(() => context, Object.values(context)) as ContextValueType;\n return <Context.Provider value={value}>{children}</Context.Provider>;\n };\n\n Provider.displayName = rootComponentName + 'Provider';\n\n function useContext(consumerName: string, scope: Scope<ContextValueType | undefined>) {\n const Context = scope?.[scopeName]?.[index] || BaseContext;\n const context = React.useContext(Context);\n if (context) return context;\n if (defaultContext !== undefined) return defaultContext;\n // if a defaultContext wasn't specified, it's a required context.\n throw new Error(`\\`${consumerName}\\` must be used within \\`${rootComponentName}\\``);\n }\n\n return [Provider, useContext] as const;\n }\n\n /* -----------------------------------------------------------------------------------------------\n * createScope\n * ---------------------------------------------------------------------------------------------*/\n\n const createScope: CreateScope = () => {\n const scopeContexts = defaultContexts.map((defaultContext) => {\n return React.createContext(defaultContext);\n });\n return function useScope(scope: Scope) {\n const contexts = scope?.[scopeName] || scopeContexts;\n return React.useMemo(\n () => ({ [`__scope${scopeName}`]: { ...scope, [scopeName]: contexts } }),\n [scope, contexts]\n );\n };\n };\n\n createScope.scopeName = scopeName;\n return [createContext, composeContextScopes(createScope, ...createContextScopeDeps)] as const;\n}\n\n/* -------------------------------------------------------------------------------------------------\n * composeContextScopes\n * -----------------------------------------------------------------------------------------------*/\n\nfunction composeContextScopes(...scopes: CreateScope[]) {\n const baseScope = scopes[0];\n if (scopes.length === 1) return baseScope;\n\n const createScope: CreateScope = () => {\n const scopeHooks = scopes.map((createScope) => ({\n useScope: createScope(),\n scopeName: createScope.scopeName,\n }));\n\n return function useComposedScopes(overrideScopes) {\n const nextScopes = scopeHooks.reduce((nextScopes, { useScope, scopeName }) => {\n // We are calling a hook inside a callback which React warns against to avoid inconsistent\n // renders, however, scoping doesn't have render side effects so we ignore the rule.\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const scopeProps = useScope(overrideScopes);\n const currentScope = scopeProps[`__scope${scopeName}`];\n return { ...nextScopes, ...currentScope };\n }, {});\n\n return React.useMemo(() => ({ [`__scope${baseScope.scopeName}`]: nextScopes }), [nextScopes]);\n };\n };\n\n createScope.scopeName = baseScope.scopeName;\n return createScope;\n}\n\n/* -----------------------------------------------------------------------------------------------*/\n\nexport { createContext, createContextScope };\nexport type { CreateScope, Scope };\n", "import * as React from 'react';\nimport { composeEventHandlers } from '@radix-ui/primitive';\nimport { Primitive, dispatchDiscreteCustomEvent } from '@radix-ui/react-primitive';\nimport { useComposedRefs } from '@radix-ui/react-compose-refs';\nimport { useCallbackRef } from '@radix-ui/react-use-callback-ref';\nimport { useEscapeKeydown } from '@radix-ui/react-use-escape-keydown';\n\n/* -------------------------------------------------------------------------------------------------\n * DismissableLayer\n * -----------------------------------------------------------------------------------------------*/\n\nconst DISMISSABLE_LAYER_NAME = 'DismissableLayer';\nconst CONTEXT_UPDATE = 'dismissableLayer.update';\nconst POINTER_DOWN_OUTSIDE = 'dismissableLayer.pointerDownOutside';\nconst FOCUS_OUTSIDE = 'dismissableLayer.focusOutside';\n\nlet originalBodyPointerEvents: string;\n\nconst DismissableLayerContext = React.createContext({\n layers: new Set<DismissableLayerElement>(),\n layersWithOutsidePointerEventsDisabled: new Set<DismissableLayerElement>(),\n branches: new Set<DismissableLayerBranchElement>(),\n});\n\ntype DismissableLayerElement = React.ElementRef<typeof Primitive.div>;\ntype PrimitiveDivProps = React.ComponentPropsWithoutRef<typeof Primitive.div>;\ninterface DismissableLayerProps extends PrimitiveDivProps {\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 * Event handler called when the escape key is down.\n * Can be prevented.\n */\n onEscapeKeyDown?: (event: KeyboardEvent) => void;\n /**\n * Event handler called when the a `pointerdown` event happens outside of the `DismissableLayer`.\n * Can be prevented.\n */\n onPointerDownOutside?: (event: PointerDownOutsideEvent) => void;\n /**\n * Event handler called when the focus moves outside of the `DismissableLayer`.\n * Can be prevented.\n */\n onFocusOutside?: (event: FocusOutsideEvent) => void;\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 onInteractOutside?: (event: PointerDownOutsideEvent | FocusOutsideEvent) => void;\n /**\n * Handler called when the `DismissableLayer` should be dismissed\n */\n onDismiss?: () => void;\n}\n\nconst DismissableLayer = React.forwardRef<DismissableLayerElement, DismissableLayerProps>(\n (props, forwardedRef) => {\n const {\n disableOutsidePointerEvents = false,\n onEscapeKeyDown,\n onPointerDownOutside,\n onFocusOutside,\n onInteractOutside,\n onDismiss,\n ...layerProps\n } = props;\n const context = React.useContext(DismissableLayerContext);\n const [node, setNode] = React.useState<DismissableLayerElement | null>(null);\n const ownerDocument = node?.ownerDocument ?? globalThis?.document;\n const [, force] = React.useState({});\n const composedRefs = useComposedRefs(forwardedRef, (node) => setNode(node));\n const layers = Array.from(context.layers);\n const [highestLayerWithOutsidePointerEventsDisabled] = [...context.layersWithOutsidePointerEventsDisabled].slice(-1); // prettier-ignore\n const highestLayerWithOutsidePointerEventsDisabledIndex = layers.indexOf(highestLayerWithOutsidePointerEventsDisabled); // prettier-ignore\n const index = node ? layers.indexOf(node) : -1;\n const isBodyPointerEventsDisabled = context.layersWithOutsidePointerEventsDisabled.size > 0;\n const isPointerEventsEnabled = index >= highestLayerWithOutsidePointerEventsDisabledIndex;\n\n const pointerDownOutside = usePointerDownOutside((event) => {\n const target = event.target as HTMLElement;\n const isPointerDownOnBranch = [...context.branches].some((branch) => branch.contains(target));\n if (!isPointerEventsEnabled || isPointerDownOnBranch) return;\n onPointerDownOutside?.(event);\n onInteractOutside?.(event);\n if (!event.defaultPrevented) onDismiss?.();\n }, ownerDocument);\n\n const focusOutside = useFocusOutside((event) => {\n const target = event.target as HTMLElement;\n const isFocusInBranch = [...context.branches].some((branch) => branch.contains(target));\n if (isFocusInBranch) return;\n onFocusOutside?.(event);\n onInteractOutside?.(event);\n if (!event.defaultPrevented) onDismiss?.();\n }, ownerDocument);\n\n useEscapeKeydown((event) => {\n const isHighestLayer = index === context.layers.size - 1;\n if (!isHighestLayer) return;\n onEscapeKeyDown?.(event);\n if (!event.defaultPrevented && onDismiss) {\n event.preventDefault();\n onDismiss();\n }\n }, ownerDocument);\n\n React.useEffect(() => {\n if (!node) return;\n if (disableOutsidePointerEvents) {\n if (context.layersWithOutsidePointerEventsDisabled.size === 0) {\n originalBodyPointerEvents = ownerDocument.body.style.pointerEvents;\n ownerDocument.body.style.pointerEvents = 'none';\n }\n context.layersWithOutsidePointerEventsDisabled.add(node);\n }\n context.layers.add(node);\n dispatchUpdate();\n return () => {\n if (\n disableOutsidePointerEvents &&\n context.layersWithOutsidePointerEventsDisabled.size === 1\n ) {\n ownerDocument.body.style.pointerEvents = originalBodyPointerEvents;\n }\n };\n }, [node, ownerDocument, disableOutsidePointerEvents, context]);\n\n /**\n * We purposefully prevent combining this effect with the `disableOutsidePointerEvents` effect\n * because a change to `disableOutsidePointerEvents` would remove this layer from the stack\n * and add it to the end again so the layering order wouldn't be _creation order_.\n * We only want them to be removed from context stacks when unmounted.\n */\n React.useEffect(() => {\n return () => {\n if (!node) return;\n context.layers.delete(node);\n context.layersWithOutsidePointerEventsDisabled.delete(node);\n dispatchUpdate();\n };\n }, [node, context]);\n\n React.useEffect(() => {\n const handleUpdate = () => force({});\n document.addEventListener(CONTEXT_UPDATE, handleUpdate);\n return () => document.removeEventListener(CONTEXT_UPDATE, handleUpdate);\n }, []);\n\n return (\n <Primitive.div\n {...layerProps}\n ref={composedRefs}\n style={{\n pointerEvents: isBodyPointerEventsDisabled\n ? isPointerEventsEnabled\n ? 'auto'\n : 'none'\n : undefined,\n ...props.style,\n }}\n onFocusCapture={composeEventHandlers(props.onFocusCapture, focusOutside.onFocusCapture)}\n onBlurCapture={composeEventHandlers(props.onBlurCapture, focusOutside.onBlurCapture)}\n onPointerDownCapture={composeEventHandlers(\n props.onPointerDownCapture,\n pointerDownOutside.onPointerDownCapture\n )}\n />\n );\n }\n);\n\nDismissableLayer.displayName = DISMISSABLE_LAYER_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * DismissableLayerBranch\n * -----------------------------------------------------------------------------------------------*/\n\nconst BRANCH_NAME = 'DismissableLayerBranch';\n\ntype DismissableLayerBranchElement = React.ElementRef<typeof Primitive.div>;\ninterface DismissableLayerBranchProps extends PrimitiveDivProps {}\n\nconst DismissableLayerBranch = React.forwardRef<\n DismissableLayerBranchElement,\n DismissableLayerBranchProps\n>((props, forwardedRef) => {\n const context = React.useContext(DismissableLayerContext);\n const ref = React.useRef<DismissableLayerBranchElement>(null);\n const composedRefs = useComposedRefs(forwardedRef, ref);\n\n React.useEffect(() => {\n const node = ref.current;\n if (node) {\n context.branches.add(node);\n return () => {\n context.branches.delete(node);\n };\n }\n }, [context.branches]);\n\n return <Primitive.div {...props} ref={composedRefs} />;\n});\n\nDismissableLayerBranch.displayName = BRANCH_NAME;\n\n/* -----------------------------------------------------------------------------------------------*/\n\ntype PointerDownOutsideEvent = CustomEvent<{ originalEvent: PointerEvent }>;\ntype FocusOutsideEvent = CustomEvent<{ originalEvent: FocusEvent }>;\n\n/**\n * Listens for `pointerdown` outside a react 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 */\nfunction usePointerDownOutside(\n onPointerDownOutside?: (event: PointerDownOutsideEvent) => void,\n ownerDocument: Document = globalThis?.document\n) {\n const handlePointerDownOutside = useCallbackRef(onPointerDownOutside) as EventListener;\n const isPointerInsideReactTreeRef = React.useRef(false);\n const handleClickRef = React.useRef(() => {});\n\n React.useEffect(() => {\n const handlePointerDown = (event: PointerEvent) => {\n if (event.target && !isPointerInsideReactTreeRef.current) {\n const eventDetail = { originalEvent: event };\n\n function handleAndDispatchPointerDownOutsideEvent() {\n handleAndDispatchCustomEvent(\n POINTER_DOWN_OUTSIDE,\n handlePointerDownOutside,\n eventDetail,\n { discrete: true }\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 executres 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.current);\n handleClickRef.current = handleAndDispatchPointerDownOutsideEvent;\n ownerDocument.addEventListener('click', handleClickRef.current, { once: true });\n } else {\n handleAndDispatchPointerDownOutsideEvent();\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.current);\n }\n isPointerInsideReactTreeRef.current = 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 not React specific, but rather 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 return () => {\n window.clearTimeout(timerId);\n ownerDocument.removeEventListener('pointerdown', handlePointerDown);\n ownerDocument.removeEventListener('click', handleClickRef.current);\n };\n }, [ownerDocument, handlePointerDownOutside]);\n\n return {\n // ensures we check React component tree (not just DOM tree)\n onPointerDownCapture: () => (isPointerInsideReactTreeRef.current = true),\n };\n}\n\n/**\n * Listens for when focus happens outside a react subtree.\n * Returns props to pass to the root (node) of the subtree we want to check.\n */\nfunction useFocusOutside(\n onFocusOutside?: (event: FocusOutsideEvent) => void,\n ownerDocument: Document = globalThis?.document\n) {\n const handleFocusOutside = useCallbackRef(onFocusOutside) as EventListener;\n const isFocusInsideReactTreeRef = React.useRef(false);\n\n React.useEffect(() => {\n const handleFocus = (event: FocusEvent) => {\n if (event.target && !isFocusInsideReactTreeRef.current) {\n const eventDetail = { originalEvent: event };\n handleAndDispatchCustomEvent(FOCUS_OUTSIDE, handleFocusOutside, eventDetail, {\n discrete: false,\n });\n }\n };\n ownerDocument.addEventListener('focusin', handleFocus);\n return () => ownerDocument.removeEventListener('focusin', handleFocus);\n }, [ownerDocument, handleFocusOutside]);\n\n return {\n onFocusCapture: () => (isFocusInsideReactTreeRef.current = true),\n onBlurCapture: () => (isFocusInsideReactTreeRef.current = false),\n };\n}\n\nfunction dispatchUpdate() {\n const event = new CustomEvent(CONTEXT_UPDATE);\n document.dispatchEvent(event);\n}\n\nfunction handleAndDispatchCustomEvent<E extends CustomEvent, OriginalEvent extends Event>(\n name: string,\n handler: ((event: E) => void) | undefined,\n detail: { originalEvent: OriginalEvent } & (E extends CustomEvent<infer D> ? D : never),\n { discrete }: { discrete: boolean }\n) {\n const target = detail.originalEvent.target;\n const event = new CustomEvent(name, { bubbles: false, cancelable: true, detail });\n if (handler) target.addEventListener(name, handler as EventListener, { once: true });\n\n if (discrete) {\n dispatchDiscreteCustomEvent(target, event);\n } else {\n target.dispatchEvent(event);\n }\n}\n\nconst Root = DismissableLayer;\nconst Branch = DismissableLayerBranch;\n\nexport {\n DismissableLayer,\n DismissableLayerBranch,\n //\n Root,\n Branch,\n};\nexport type { DismissableLayerProps };\n", "import * as React from 'react';\nimport * as ReactDOM from 'react-dom';\nimport { Slot } from '@radix-ui/react-slot';\n\nconst NODES = [\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] as const;\n\ntype Primitives = { [E in (typeof NODES)[number]]: PrimitiveForwardRefComponent<E> };\ntype PrimitivePropsWithRef<E extends React.ElementType> = React.ComponentPropsWithRef<E> & {\n asChild?: boolean;\n};\n\ninterface PrimitiveForwardRefComponent<E extends React.ElementType>\n extends React.ForwardRefExoticComponent<PrimitivePropsWithRef<E>> {}\n\n/* -------------------------------------------------------------------------------------------------\n * Primitive\n * -----------------------------------------------------------------------------------------------*/\n\nconst Primitive = NODES.reduce((primitive, node) => {\n const Node = React.forwardRef((props: PrimitivePropsWithRef<typeof node>, forwardedRef: any) => {\n const { asChild, ...primitiveProps } = props;\n const Comp: any = asChild ? Slot : node;\n\n if (typeof window !== 'undefined') {\n (window as any)[Symbol.for('radix-ui')] = true;\n }\n\n return <Comp {...primitiveProps} ref={forwardedRef} />;\n });\n\n Node.displayName = `Primitive.${node}`;\n\n return { ...primitive, [node]: Node };\n}, {} as Primitives);\n\n/* -------------------------------------------------------------------------------------------------\n * Utils\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * Flush custom event dispatch\n * https://github.com/radix-ui/primitives/pull/1378\n *\n * React batches *all* event handlers since version 18, this introduces certain considerations when using custom event types.\n *\n * Internally, React prioritises events in the following order:\n * - discrete\n * - continuous\n * - default\n *\n * https://github.com/facebook/react/blob/a8a4742f1c54493df00da648a3f9d26e3db9c8b5/packages/react-dom/src/events/ReactDOMEventListener.js#L294-L350\n *\n * `discrete` is an important distinction as updates within these events are applied immediately.\n * React however, is not able to infer the priority of custom event types due to how they are detected internally.\n * Because of this, it's possible for updates from custom events to be unexpectedly batched when\n * dispatched by another `discrete` event.\n *\n * In order to ensure that updates from custom events are applied predictably, we need to manually flush the batch.\n * This utility should be used when dispatching a custom event from within another `discrete` event, this utility\n * is not nessesary when dispatching known event types, or if dispatching a custom type inside a non-discrete event.\n * For example:\n *\n * dispatching a known click \uD83D\uDC4E\n * target.dispatchEvent(new Event(\u2018click\u2019))\n *\n * dispatching a custom type within a non-discrete event \uD83D\uDC4E\n * onScroll={(event) => event.target.dispatchEvent(new CustomEvent(\u2018customType\u2019))}\n *\n * dispatching a custom type within a `discrete` event \uD83D\uDC4D\n * onPointerDown={(event) => dispatchDiscreteCustomEvent(event.target, new CustomEvent(\u2018customType\u2019))}\n *\n * Note: though React classifies `focus`, `focusin` and `focusout` events as `discrete`, it's not recommended to use\n * this utility with them. This is because it's possible for those handlers to be called implicitly during render\n * e.g. when focus is within a component as it is unmounted, or when managing focus on mount.\n */\n\nfunction dispatchDiscreteCustomEvent<E extends CustomEvent>(target: E['target'], event: E) {\n if (target) ReactDOM.flushSync(() => target.dispatchEvent(event));\n}\n\n/* -----------------------------------------------------------------------------------------------*/\n\nconst Root = Primitive;\n\nexport {\n Primitive,\n //\n Root,\n //\n dispatchDiscreteCustomEvent,\n};\nexport type { PrimitivePropsWithRef };\n", "import * as React from 'react';\n\n/**\n * A custom hook that converts a callback to a ref to avoid triggering re-renders when passed as a\n * prop or avoid re-executing effects when passed as a dependency\n */\nfunction useCallbackRef<T extends (...args: any[]) => any>(callback: T | undefined): T {\n const callbackRef = React.useRef(callback);\n\n React.useEffect(() => {\n callbackRef.current = callback;\n });\n\n // https://github.com/facebook/react/issues/19240\n return React.useMemo(() => ((...args) => callbackRef.current?.(...args)) as T, []);\n}\n\nexport { useCallbackRef };\n", "import * as React from 'react';\nimport { useCallbackRef } from '@radix-ui/react-use-callback-ref';\n\n/**\n * Listens for when the escape key is down\n */\nfunction useEscapeKeydown(\n onEscapeKeyDownProp?: (event: KeyboardEvent) => void,\n ownerDocument: Document = globalThis?.document\n) {\n const onEscapeKeyDown = useCallbackRef(onEscapeKeyDownProp);\n\n React.useEffect(() => {\n const handleKeyDown = (event: KeyboardEvent) => {\n if (event.key === 'Escape') {\n onEscapeKeyDown(event);\n }\n };\n ownerDocument.addEventListener('keydown', handleKeyDown, { capture: true });\n return () => ownerDocument.removeEventListener('keydown', handleKeyDown, { capture: true });\n }, [onEscapeKeyDown, ownerDocument]);\n}\n\nexport { useEscapeKeydown };\n", "import * as React from 'react';\nimport { useLayoutEffect } from '@radix-ui/react-use-layout-effect';\n\n// We `toString()` to prevent bundlers from trying to `import { useId } from 'react';`\nconst useReactId = (React as any)['useId'.toString()] || (() => undefined);\nlet count = 0;\n\nfunction useId(deterministicId?: string): string {\n const [id, setId] = React.useState<string | undefined>(useReactId());\n // React versions older than 18 will have client-side ids only.\n useLayoutEffect(() => {\n if (!deterministicId) setId((reactId) => reactId ?? String(count++));\n }, [deterministicId]);\n return deterministicId || (id ? `radix-${id}` : '');\n}\n\nexport { useId };\n", "import * as React from 'react';\n\n/**\n * On the server, React emits a warning when calling `useLayoutEffect`.\n * This is because neither `useLayoutEffect` nor `useEffect` run on the server.\n * We use this safe version which suppresses the warning by replacing it with a noop on the server.\n *\n * See: https://reactjs.org/docs/hooks-reference.html#uselayouteffect\n */\nconst useLayoutEffect = Boolean(globalThis?.document) ? React.useLayoutEffect : () => {};\n\nexport { useLayoutEffect };\n", "import * as React from 'react';\nimport {\n useFloating,\n autoUpdate,\n offset,\n shift,\n limitShift,\n hide,\n arrow as floatingUIarrow,\n flip,\n size,\n} from '@floating-ui/react-dom';\nimport * as ArrowPrimitive from '@radix-ui/react-arrow';\nimport { useComposedRefs } from '@radix-ui/react-compose-refs';\nimport { createContextScope } from '@radix-ui/react-context';\nimport { Primitive } from '@radix-ui/react-primitive';\nimport { useCallbackRef } from '@radix-ui/react-use-callback-ref';\nimport { useLayoutEffect } from '@radix-ui/react-use-layout-effect';\nimport { useSize } from '@radix-ui/react-use-size';\n\nimport type { Placement, Middleware } from '@floating-ui/react-dom';\nimport type { Scope } from '@radix-ui/react-context';\nimport type { Measurable } from '@radix-ui/rect';\n\nconst SIDE_OPTIONS = ['top', 'right', 'bottom', 'left'] as const;\nconst ALIGN_OPTIONS = ['start', 'center', 'end'] as const;\n\ntype Side = (typeof SIDE_OPTIONS)[number];\ntype Align = (typeof ALIGN_OPTIONS)[number];\n\n/* -------------------------------------------------------------------------------------------------\n * Popper\n * -----------------------------------------------------------------------------------------------*/\n\nconst POPPER_NAME = 'Popper';\n\ntype ScopedProps<P> = P & { __scopePopper?: Scope };\nconst [createPopperContext, createPopperScope] = createContextScope(POPPER_NAME);\n\ntype PopperContextValue = {\n anchor: Measurable | null;\n onAnchorChange(anchor: Measurable | null): void;\n};\nconst [PopperProvider, usePopperContext] = createPopperContext<PopperContextValue>(POPPER_NAME);\n\ninterface PopperProps {\n children?: React.ReactNode;\n}\nconst Popper: React.FC<PopperProps> = (props: ScopedProps<PopperProps>) => {\n const { __scopePopper, children } = props;\n const [anchor, setAnchor] = React.useState<Measurable | null>(null);\n return (\n <PopperProvider scope={__scopePopper} anchor={anchor} onAnchorChange={setAnchor}>\n {children}\n </PopperProvider>\n );\n};\n\nPopper.displayName = POPPER_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * PopperAnchor\n * -----------------------------------------------------------------------------------------------*/\n\nconst ANCHOR_NAME = 'PopperAnchor';\n\ntype PopperAnchorElement = React.ElementRef<typeof Primitive.div>;\ntype PrimitiveDivProps = React.ComponentPropsWithoutRef<typeof Primitive.div>;\ninterface PopperAnchorProps extends PrimitiveDivProps {\n virtualRef?: React.RefObject<Measurable>;\n}\n\nconst PopperAnchor = React.forwardRef<PopperAnchorElement, PopperAnchorProps>(\n (props: ScopedProps<PopperAnchorProps>, forwardedRef) => {\n const { __scopePopper, virtualRef, ...anchorProps } = props;\n const context = usePopperContext(ANCHOR_NAME, __scopePopper);\n const ref = React.useRef<PopperAnchorElement>(null);\n const composedRefs = useComposedRefs(forwardedRef, ref);\n\n React.useEffect(() => {\n // Consumer can anchor the popper to something that isn't\n // a DOM node e.g. pointer position, so we override the\n // `anchorRef` with their virtual ref in this case.\n context.onAnchorChange(virtualRef?.current || ref.current);\n });\n\n return virtualRef ? null : <Primitive.div {...anchorProps} ref={composedRefs} />;\n }\n);\n\nPopperAnchor.displayName = ANCHOR_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * PopperContent\n * -----------------------------------------------------------------------------------------------*/\n\nconst CONTENT_NAME = 'PopperContent';\n\ntype PopperContentContextValue = {\n placedSide: Side;\n onArrowChange(arrow: HTMLSpanElement | null): void;\n arrowX?: number;\n arrowY?: number;\n shouldHideArrow: boolean;\n};\n\nconst [PopperContentProvider, useContentContext] =\n createPopperContext<PopperContentContextValue>(CONTENT_NAME);\n\ntype Boundary = Element | null;\n\ntype PopperContentElement = React.ElementRef<typeof Primitive.div>;\ninterface PopperContentProps extends PrimitiveDivProps {\n side?: Side;\n sideOffset?: number;\n align?: Align;\n alignOffset?: number;\n arrowPadding?: number;\n avoidCollisions?: boolean;\n collisionBoundary?: Boundary | Boundary[];\n collisionPadding?: number | Partial<Record<Side, number>>;\n sticky?: 'partial' | 'always';\n hideWhenDetached?: boolean;\n updatePositionStrategy?: 'optimized' | 'always';\n onPlaced?: () => void;\n}\n\nconst PopperContent = React.forwardRef<PopperContentElement, PopperContentProps>(\n (props: ScopedProps<PopperContentProps>, forwardedRef) => {\n const {\n __scopePopper,\n side = 'bottom',\n sideOffset = 0,\n align = 'center',\n alignOffset = 0,\n arrowPadding = 0,\n avoidCollisions = true,\n collisionBoundary = [],\n collisionPadding: collisionPaddingProp = 0,\n sticky = 'partial',\n hideWhenDetached = false,\n updatePositionStrategy = 'optimized',\n onPlaced,\n ...contentProps\n } = props;\n\n const context = usePopperContext(CONTENT_NAME, __scopePopper);\n\n const [content, setContent] = React.useState<HTMLDivElement | null>(null);\n const composedRefs = useComposedRefs(forwardedRef, (node) => setContent(node));\n\n const [arrow, setArrow] = React.useState<HTMLSpanElement | null>(null);\n const arrowSize = useSize(arrow);\n const arrowWidth = arrowSize?.width ?? 0;\n const arrowHeight = arrowSize?.height ?? 0;\n\n const desiredPlacement = (side + (align !== 'center' ? '-' + align : '')) as Placement;\n\n const collisionPadding =\n typeof collisionPaddingProp === 'number'\n ? collisionPaddingProp\n : { top: 0, right: 0, bottom: 0, left: 0, ...collisionPaddingProp };\n\n const boundary = Array.isArray(collisionBoundary) ? collisionBoundary : [collisionBoundary];\n const hasExplicitBoundaries = boundary.length > 0;\n\n const detectOverflowOptions = {\n padding: collisionPadding,\n boundary: boundary.filter(isNotNull),\n // with `strategy: 'fixed'`, this is the only way to get it to respect boundaries\n altBoundary: hasExplicitBoundaries,\n };\n\n const { refs, floatingStyles, placement, isPositioned, middlewareData } = useFloating({\n // default to `fixed` strategy so users don't have to pick and we also avoid focus scroll issues\n strategy: 'fixed',\n placement: desiredPlacement,\n whileElementsMounted: (...args) => {\n const cleanup = autoUpdate(...args, {\n animationFrame: updatePositionStrategy === 'always',\n });\n return cleanup;\n },\n elements: {\n reference: context.anchor,\n },\n middleware: [\n offset({ mainAxis: sideOffset + arrowHeight, alignmentAxis: alignOffset }),\n avoidCollisions &&\n shift({\n mainAxis: true,\n crossAxis: false,\n limiter: sticky === 'partial' ? limitShift() : undefined,\n ...detectOverflowOptions,\n }),\n avoidCollisions && flip({ ...detectOverflowOptions }),\n size({\n ...detectOverflowOptions,\n apply: ({ elements, rects, availableWidth, availableHeight }) => {\n const { width: anchorWidth, height: anchorHeight } = rects.reference;\n const contentStyle = elements.floating.style;\n contentStyle.setProperty('--radix-popper-available-width', `${availableWidth}px`);\n contentStyle.setProperty('--radix-popper-available-height', `${availableHeight}px`);\n contentStyle.setProperty('--radix-popper-anchor-width', `${anchorWidth}px`);\n contentStyle.setProperty('--radix-popper-anchor-height', `${anchorHeight}px`);\n },\n }),\n arrow && floatingUIarrow({ element: arrow, padding: arrowPadding }),\n transformOrigin({ arrowWidth, arrowHeight }),\n hideWhenDetached && hide({ strategy: 'referenceHidden', ...detectOverflowOptions }),\n ],\n });\n\n const [placedSide, placedAlign] = getSideAndAlignFromPlacement(placement);\n\n const handlePlaced = useCallbackRef(onPlaced);\n useLayoutEffect(() => {\n if (isPositioned) {\n handlePlaced?.();\n }\n }, [isPositioned, handlePlaced]);\n\n const arrowX = middlewareData.arrow?.x;\n const arrowY = middlewareData.arrow?.y;\n const cannotCenterArrow = middlewareData.arrow?.centerOffset !== 0;\n\n const [contentZIndex, setContentZIndex] = React.useState<string>();\n useLayoutEffect(() => {\n if (content) setContentZIndex(window.getComputedStyle(content).zIndex);\n }, [content]);\n\n return (\n <div\n ref={refs.setFloating}\n data-radix-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 ['--radix-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 // Floating UI interally calculates logical alignment based the `dir` attribute on\n // the reference/floating node, we must add this attribute here to ensure\n // this is calculated when portalled as well as inline.\n dir={props.dir}\n >\n <PopperContentProvider\n scope={__scopePopper}\n placedSide={placedSide}\n onArrowChange={setArrow}\n arrowX={arrowX}\n arrowY={arrowY}\n shouldHideArrow={cannotCenterArrow}\n >\n <Primitive.div\n data-side={placedSide}\n data-align={placedAlign}\n {...contentProps}\n ref={composedRefs}\n style={{\n ...contentProps.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 </PopperContentProvider>\n </div>\n );\n }\n);\n\nPopperContent.displayName = CONTENT_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * PopperArrow\n * -----------------------------------------------------------------------------------------------*/\n\nconst ARROW_NAME = 'PopperArrow';\n\nconst OPPOSITE_SIDE: Record<Side, Side> = {\n top: 'bottom',\n right: 'left',\n bottom: 'top',\n left: 'right',\n};\n\ntype PopperArrowElement = React.ElementRef<typeof ArrowPrimitive.Root>;\ntype ArrowProps = React.ComponentPropsWithoutRef<typeof ArrowPrimitive.Root>;\ninterface PopperArrowProps extends ArrowProps {}\n\nconst PopperArrow = React.forwardRef<PopperArrowElement, PopperArrowProps>(function PopperArrow(\n props: ScopedProps<PopperArrowProps>,\n forwardedRef\n) {\n const { __scopePopper, ...arrowProps } = props;\n const contentContext = useContentContext(ARROW_NAME, __scopePopper);\n const baseSide = OPPOSITE_SIDE[contentContext.placedSide];\n\n return (\n // we have to use an extra wrapper because `ResizeObserver` (used by `useSize`)\n // doesn't report size as we'd expect on SVG elements.\n // it reports their bounding box which is effectively the largest path inside the SVG.\n <span\n ref={contentContext.onArrowChange}\n style={{\n position: 'absolute',\n left: contentContext.arrowX,\n top: contentContext.arrowY,\n [baseSide]: 0,\n transformOrigin: {\n top: '',\n right: '0 0',\n bottom: 'center 0',\n left: '100% 0',\n }[contentContext.placedSide],\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],\n visibility: contentContext.shouldHideArrow ? 'hidden' : undefined,\n }}\n >\n <ArrowPrimitive.Root\n {...arrowProps}\n ref={forwardedRef}\n style={{\n ...arrowProps.style,\n // ensures the element can be measured correctly (mostly for if SVG)\n display: 'block',\n }}\n />\n </span>\n );\n});\n\nPopperArrow.displayName = ARROW_NAME;\n\n/* -----------------------------------------------------------------------------------------------*/\n\nfunction isNotNull<T>(value: T | null): value is T {\n return value !== null;\n}\n\nconst transformOrigin = (options: { arrowWidth: number; arrowHeight: number }): Middleware => ({\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%' }[placedAlign];\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 } else if (placedSide === 'top') {\n x = isArrowHidden ? noArrowAlign : `${arrowXCenter}px`;\n y = `${rects.floating.height + arrowHeight}px`;\n } else if (placedSide === 'right') {\n x = `${-arrowHeight}px`;\n y = isArrowHidden ? noArrowAlign : `${arrowYCenter}px`;\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\nfunction getSideAndAlignFromPlacement(placement: Placement) {\n const [side, align = 'center'] = placement.split('-');\n return [side as Side, align as Align] as const;\n}\n\nconst Root = Popper;\nconst Anchor = PopperAnchor;\nconst Content = PopperContent;\nconst Arrow = PopperArrow;\n\nexport {\n createPopperScope,\n //\n Popper,\n PopperAnchor,\n PopperContent,\n PopperArrow,\n //\n Root,\n Anchor,\n Content,\n Arrow,\n //\n SIDE_OPTIONS,\n ALIGN_OPTIONS,\n};\nexport type { PopperProps, PopperAnchorProps, PopperContentProps, PopperArrowProps };\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};\nconst oppositeAlignmentMap = {\n start: 'end',\n end: 'start'\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 return ['top', 'bottom'].includes(getSide(placement)) ? '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.replace(/start|end/g, alignment => oppositeAlignmentMap[alignment]);\n}\nfunction getSideList(side, isStart, rtl) {\n const lr = ['left', 'right'];\n const rl = ['right', 'left'];\n const tb = ['top', 'bottom'];\n const bt = ['bottom', 'top'];\n switch (side) {\n case 'top':\n case 'bottom':\n if (rtl) return isStart ? rl : lr;\n return isStart ? lr : rl;\n case 'left':\n case 'right':\n return isStart ? tb : bt;\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 return placement.replace(/left|right|bottom|top/g, side => oppositeSideMap[side]);\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 * 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 validMiddleware = middleware.filter(Boolean);\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 middlewareData = {};\n let resetCount = 0;\n for (let i = 0; i < validMiddleware.length; i++) {\n const {\n name,\n fn\n } = validMiddleware[i];\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,\n elements: {\n reference,\n floating\n }\n });\n x = nextX != null ? nextX : x;\n y = nextY != null ? nextY : y;\n middlewareData = {\n ...middlewareData,\n [name]: {\n ...middlewareData[name],\n ...data\n }\n };\n if (reset && resetCount <= 50) {\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 * 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/**\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 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 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 // 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 // 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 } = state;\n const {\n strategy = 'referenceHidden',\n ...detectOverflowOptions\n } = evaluate(options, state);\n switch (strategy) {\n case 'referenceHidden':\n {\n const overflow = await 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 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\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 = ['left', 'top'].includes(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 } = 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 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 = ['top', 'left'].includes(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 \u2014\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 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) && !['inline', 'contents'].includes(display);\n}\nfunction isTableElement(element) {\n return ['table', 'td', 'th'].includes(getNodeName(element));\n}\nfunction isTopLayer(element) {\n return [':popover-open', ':modal'].some(selector => {\n try {\n return element.matches(selector);\n } catch (e) {\n return false;\n }\n });\n}\nfunction isContainingBlock(elementOrCss) {\n const webkit = isWebKit();\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 return css.transform !== 'none' || css.perspective !== 'none' || (css.containerType ? css.containerType !== 'normal' : false) || !webkit && (css.backdropFilter ? css.backdropFilter !== 'none' : false) || !webkit && (css.filter ? css.filter !== 'none' : false) || ['transform', 'perspective', 'filter'].some(value => (css.willChange || '').includes(value)) || ['paint', 'layout', 'strict', 'content'].some(value => (css.contain || '').includes(value));\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 (typeof CSS === 'undefined' || !CSS.supports) return false;\n return CSS.supports('-webkit-backdrop-filter', 'none');\n}\nfunction isLastTraversableNode(node) {\n return ['html', 'body', '#document'].includes(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 }\n return list.concat(scrollableAncestor, getOverflowAncestors(scrollableAncestor, [], traverseIframes));\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, detectOverflow as detectOverflow$1, offset as offset$1, autoPlacement as autoPlacement$1, shift as shift$1, flip as flip$1, size as size$1, hide as hide$1, arrow as arrow$1, inline as inline$1, limitShift as limitShift$1, computePosition as computePosition$1 } from '@floating-ui/core';\nimport { round, createCoords, max, min, floor } from '@floating-ui/utils';\nimport { getComputedStyle, 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(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(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, ignoreScrollbarX) {\n if (ignoreScrollbarX === void 0) {\n ignoreScrollbarX = false;\n }\n const htmlRect = documentElement.getBoundingClientRect();\n const x = htmlRect.left + scroll.scrollLeft - (ignoreScrollbarX ? 0 :\n // RTL <body> scrollbar.\n 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 (isHTMLElement(offsetParent)) {\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, true) : 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(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\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 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(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(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(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 && ['absolute', 'fixed'].includes(currentContainingBlockComputedStyle.position) || 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 firstClippingAncestor = clippingAncestors[0];\n const clippingRect = clippingAncestors.reduce((accRect, clippingAncestor) => {\n const rect = getClientRectFromClippingAncestor(element, clippingAncestor, strategy);\n accRect.top = max(rect.top, accRect.top);\n accRect.right = min(rect.right, accRect.right);\n accRect.bottom = min(rect.bottom, accRect.bottom);\n accRect.left = max(rect.left, accRect.left);\n return accRect;\n }, getClientRectFromClippingAncestor(element, firstClippingAncestor, strategy));\n return {\n width: clippingRect.right - clippingRect.left,\n height: clippingRect.bottom - clippingRect.top,\n x: clippingRect.left,\n y: clippingRect.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 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 // 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 offsets.x = getWindowScrollBarX(documentElement);\n }\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(element).position === 'static';\n}\n\nfunction getTrueOffsetParent(element, polyfill) {\n if (!isHTMLElement(element) || getComputedStyle(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(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\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 {\n left,\n top,\n width,\n height\n } = element.getBoundingClientRect();\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 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) : []), ...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) {\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 resizeObserver.observe(floating);\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 && (nextRefRect.x !== prevRefRect.x || nextRefRect.y !== prevRefRect.y || nextRefRect.width !== prevRefRect.width || nextRefRect.height !== prevRefRect.height)) {\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 \u2014\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", "import { computePosition, arrow as arrow$2, offset as offset$1, shift as shift$1, limitShift as limitShift$1, flip as flip$1, size as size$1, autoPlacement as autoPlacement$1, hide as hide$1, inline as inline$1 } from '@floating-ui/dom';\nexport { autoUpdate, computePosition, detectOverflow, getOverflowAncestors, platform } from '@floating-ui/dom';\nimport * as React from 'react';\nimport { useLayoutEffect, useEffect } from 'react';\nimport * as ReactDOM from 'react-dom';\n\nvar index = typeof document !== 'undefined' ? useLayoutEffect : useEffect;\n\n// Fork of `fast-deep-equal` that only does the comparisons we need and compares\n// functions\nfunction deepEqual(a, b) {\n if (a === b) {\n return true;\n }\n if (typeof a !== typeof b) {\n return false;\n }\n if (typeof a === 'function' && a.toString() === b.toString()) {\n return true;\n }\n let length;\n let i;\n let keys;\n if (a && b && typeof a === 'object') {\n if (Array.isArray(a)) {\n length = a.length;\n if (length !== b.length) return false;\n for (i = length; i-- !== 0;) {\n if (!deepEqual(a[i], b[i])) {\n return false;\n }\n }\n return true;\n }\n keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length) {\n return false;\n }\n for (i = length; i-- !== 0;) {\n if (!{}.hasOwnProperty.call(b, keys[i])) {\n return false;\n }\n }\n for (i = length; i-- !== 0;) {\n const key = keys[i];\n if (key === '_owner' && a.$$typeof) {\n continue;\n }\n if (!deepEqual(a[key], b[key])) {\n return false;\n }\n }\n return true;\n }\n return a !== a && b !== b;\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\nfunction useLatestRef(value) {\n const ref = React.useRef(value);\n index(() => {\n ref.current = value;\n });\n return ref;\n}\n\n/**\n * Provides data to position a floating element.\n * @see https://floating-ui.com/docs/useFloating\n */\nfunction useFloating(options) {\n if (options === void 0) {\n options = {};\n }\n const {\n placement = 'bottom',\n strategy = 'absolute',\n middleware = [],\n platform,\n elements: {\n reference: externalReference,\n floating: externalFloating\n } = {},\n transform = true,\n whileElementsMounted,\n open\n } = options;\n const [data, setData] = React.useState({\n x: 0,\n y: 0,\n strategy,\n placement,\n middlewareData: {},\n isPositioned: false\n });\n const [latestMiddleware, setLatestMiddleware] = React.useState(middleware);\n if (!deepEqual(latestMiddleware, middleware)) {\n setLatestMiddleware(middleware);\n }\n const [_reference, _setReference] = React.useState(null);\n const [_floating, _setFloating] = React.useState(null);\n const setReference = React.useCallback(node => {\n if (node !== referenceRef.current) {\n referenceRef.current = node;\n _setReference(node);\n }\n }, []);\n const setFloating = React.useCallback(node => {\n if (node !== floatingRef.current) {\n floatingRef.current = node;\n _setFloating(node);\n }\n }, []);\n const referenceEl = externalReference || _reference;\n const floatingEl = externalFloating || _floating;\n const referenceRef = React.useRef(null);\n const floatingRef = React.useRef(null);\n const dataRef = React.useRef(data);\n const hasWhileElementsMounted = whileElementsMounted != null;\n const whileElementsMountedRef = useLatestRef(whileElementsMounted);\n const platformRef = useLatestRef(platform);\n const openRef = useLatestRef(open);\n const update = React.useCallback(() => {\n if (!referenceRef.current || !floatingRef.current) {\n return;\n }\n const config = {\n placement,\n strategy,\n middleware: latestMiddleware\n };\n if (platformRef.current) {\n config.platform = platformRef.current;\n }\n computePosition(referenceRef.current, floatingRef.current, config).then(data => {\n const fullData = {\n ...data,\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 isPositioned: openRef.current !== false\n };\n if (isMountedRef.current && !deepEqual(dataRef.current, fullData)) {\n dataRef.current = fullData;\n ReactDOM.flushSync(() => {\n setData(fullData);\n });\n }\n });\n }, [latestMiddleware, placement, strategy, platformRef, openRef]);\n index(() => {\n if (open === false && dataRef.current.isPositioned) {\n dataRef.current.isPositioned = false;\n setData(data => ({\n ...data,\n isPositioned: false\n }));\n }\n }, [open]);\n const isMountedRef = React.useRef(false);\n index(() => {\n isMountedRef.current = true;\n return () => {\n isMountedRef.current = false;\n };\n }, []);\n index(() => {\n if (referenceEl) referenceRef.current = referenceEl;\n if (floatingEl) floatingRef.current = floatingEl;\n if (referenceEl && floatingEl) {\n if (whileElementsMountedRef.current) {\n return whileElementsMountedRef.current(referenceEl, floatingEl, update);\n }\n update();\n }\n }, [referenceEl, floatingEl, update, whileElementsMountedRef, hasWhileElementsMounted]);\n const refs = React.useMemo(() => ({\n reference: referenceRef,\n floating: floatingRef,\n setReference,\n setFloating\n }), [setReference, setFloating]);\n const elements = React.useMemo(() => ({\n reference: referenceEl,\n floating: floatingEl\n }), [referenceEl, floatingEl]);\n const floatingStyles = React.useMemo(() => {\n const initialStyles = {\n position: strategy,\n left: 0,\n top: 0\n };\n if (!elements.floating) {\n return initialStyles;\n }\n const x = roundByDPR(elements.floating, data.x);\n const y = roundByDPR(elements.floating, data.y);\n if (transform) {\n return {\n ...initialStyles,\n transform: \"translate(\" + x + \"px, \" + y + \"px)\",\n ...(getDPR(elements.floating) >= 1.5 && {\n willChange: 'transform'\n })\n };\n }\n return {\n position: strategy,\n left: x,\n top: y\n };\n }, [strategy, transform, elements.floating, data.x, data.y]);\n return React.useMemo(() => ({\n ...data,\n update,\n refs,\n elements,\n floatingStyles\n }), [data, update, refs, elements, floatingStyles]);\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 * This wraps the core `arrow` middleware to allow React refs as the element.\n * @see https://floating-ui.com/docs/arrow\n */\nconst arrow$1 = options => {\n function isRef(value) {\n return {}.hasOwnProperty.call(value, 'current');\n }\n return {\n name: 'arrow',\n options,\n fn(state) {\n const {\n element,\n padding\n } = typeof options === 'function' ? options(state) : options;\n if (element && isRef(element)) {\n if (element.current != null) {\n return arrow$2({\n element: element.current,\n padding\n }).fn(state);\n }\n return {};\n }\n if (element) {\n return arrow$2({\n element,\n padding\n }).fn(state);\n }\n return {};\n }\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 = (options, deps) => ({\n ...offset$1(options),\n options: [options, deps]\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 = (options, deps) => ({\n ...shift$1(options),\n options: [options, deps]\n});\n\n/**\n * Built-in `limiter` that will stop `shift()` at a certain point.\n */\nconst limitShift = (options, deps) => ({\n ...limitShift$1(options),\n options: [options, deps]\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 = (options, deps) => ({\n ...flip$1(options),\n options: [options, deps]\n});\n\n/**\n * Provides data that allows you to change the size of the floating element \u2014\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 = (options, deps) => ({\n ...size$1(options),\n options: [options, deps]\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 = (options, deps) => ({\n ...autoPlacement$1(options),\n options: [options, deps]\n});\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 = (options, deps) => ({\n ...hide$1(options),\n options: [options, deps]\n});\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 = (options, deps) => ({\n ...inline$1(options),\n options: [options, deps]\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 * This wraps the core `arrow` middleware to allow React refs as the element.\n * @see https://floating-ui.com/docs/arrow\n */\nconst arrow = (options, deps) => ({\n ...arrow$1(options),\n options: [options, deps]\n});\n\nexport { arrow, autoPlacement, flip, hide, inline, limitShift, offset, shift, size, useFloating };\n", "import * as React from 'react';\nimport { Primitive } from '@radix-ui/react-primitive';\n\n/* -------------------------------------------------------------------------------------------------\n * Arrow\n * -----------------------------------------------------------------------------------------------*/\n\nconst NAME = 'Arrow';\n\ntype ArrowElement = React.ElementRef<typeof Primitive.svg>;\ntype PrimitiveSvgProps = React.ComponentPropsWithoutRef<typeof Primitive.svg>;\ninterface ArrowProps extends PrimitiveSvgProps {}\n\nconst Arrow = React.forwardRef<ArrowElement, ArrowProps>((props, forwardedRef) => {\n const { children, width = 10, height = 5, ...arrowProps } = props;\n return (\n <Primitive.svg\n {...arrowProps}\n ref={forwardedRef}\n width={width}\n height={height}\n viewBox=\"0 0 30 10\"\n preserveAspectRatio=\"none\"\n >\n {/* We use their children if they're slotting to replace the whole svg */}\n {props.asChild ? children : <polygon points=\"0,0 30,0 15,10\" />}\n </Primitive.svg>\n );\n});\n\nArrow.displayName = NAME;\n\n/* -----------------------------------------------------------------------------------------------*/\n\nconst Root = Arrow;\n\nexport {\n Arrow,\n //\n Root,\n};\nexport type { ArrowProps };\n", "/// <reference types=\"resize-observer-browser\" />\n\nimport * as React from 'react';\nimport { useLayoutEffect } from '@radix-ui/react-use-layout-effect';\n\nfunction useSize(element: HTMLElement | null) {\n const [size, setSize] = React.useState<{ width: number; height: number } | undefined>(undefined);\n\n useLayoutEffect(() => {\n if (element) {\n // provide size as early as possible\n setSize({ width: element.offsetWidth, height: element.offsetHeight });\n\n const resizeObserver = new ResizeObserver((entries) => {\n if (!Array.isArray(entries)) {\n return;\n }\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\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) ? borderSizeEntry[0] : borderSizeEntry;\n width = borderSize['inlineSize'];\n height = borderSize['blockSize'];\n } else {\n // for browsers that don't support `borderBoxSize`\n // we calculate it ourselves to get the correct border box.\n width = element.offsetWidth;\n height = element.offsetHeight;\n }\n\n setSize({ width, height });\n });\n\n resizeObserver.observe(element, { box: 'border-box' });\n\n return () => resizeObserver.unobserve(element);\n } else {\n // We only want to reset to `undefined` when the element becomes `null`,\n // not if it changes to another element.\n setSize(undefined);\n }\n }, [element]);\n\n return size;\n}\n\nexport { useSize };\n", "import * as React from 'react';\nimport ReactDOM from 'react-dom';\nimport { Primitive } from '@radix-ui/react-primitive';\nimport { useLayoutEffect } from '@radix-ui/react-use-layout-effect';\n\n/* -------------------------------------------------------------------------------------------------\n * Portal\n * -----------------------------------------------------------------------------------------------*/\n\nconst PORTAL_NAME = 'Portal';\n\ntype PortalElement = React.ElementRef<typeof Primitive.div>;\ntype PrimitiveDivProps = React.ComponentPropsWithoutRef<typeof Primitive.div>;\ninterface PortalProps extends PrimitiveDivProps {\n /**\n * An optional container where the portaled content should be appended.\n */\n container?: Element | DocumentFragment | null;\n}\n\nconst Portal = React.forwardRef<PortalElement, PortalProps>((props, forwardedRef) => {\n const { container: containerProp, ...portalProps } = props;\n const [mounted, setMounted] = React.useState(false);\n useLayoutEffect(() => setMounted(true), []);\n const container = containerProp || (mounted && globalThis?.document?.body);\n return container\n ? ReactDOM.createPortal(<Primitive.div {...portalProps} ref={forwardedRef} />, container)\n : null;\n});\n\nPortal.displayName = PORTAL_NAME;\n\n/* -----------------------------------------------------------------------------------------------*/\n\nconst Root = Portal;\n\nexport {\n Portal,\n //\n Root,\n};\nexport type { PortalProps };\n", "import * as React from 'react';\nimport { useCallbackRef } from '@radix-ui/react-use-callback-ref';\n\ntype UseControllableStateParams<T> = {\n prop?: T | undefined;\n defaultProp?: T | undefined;\n onChange?: (state: T) => void;\n};\n\ntype SetStateFn<T> = (prevState?: T) => T;\n\nfunction useControllableState<T>({\n prop,\n defaultProp,\n onChange = () => {},\n}: UseControllableStateParams<T>) {\n const [uncontrolledProp, setUncontrolledProp] = useUncontrolledState({ defaultProp, onChange });\n const isControlled = prop !== undefined;\n const value = isControlled ? prop : uncontrolledProp;\n const handleChange = useCallbackRef(onChange);\n\n const setValue: React.Dispatch<React.SetStateAction<T | undefined>> = React.useCallback(\n (nextValue) => {\n if (isControlled) {\n const setter = nextValue as SetStateFn<T>;\n const value = typeof nextValue === 'function' ? setter(prop) : nextValue;\n if (value !== prop) handleChange(value as T);\n } else {\n setUncontrolledProp(nextValue);\n }\n },\n [isControlled, prop, setUncontrolledProp, handleChange]\n );\n\n return [value, setValue] as const;\n}\n\nfunction useUncontrolledState<T>({\n defaultProp,\n onChange,\n}: Omit<UseControllableStateParams<T>, 'prop'>) {\n const uncontrolledState = React.useState<T | undefined>(defaultProp);\n const [value] = uncontrolledState;\n const prevValueRef = React.useRef(value);\n const handleChange = useCallbackRef(onChange);\n\n React.useEffect(() => {\n if (prevValueRef.current !== value) {\n handleChange(value as T);\n prevValueRef.current = value;\n }\n }, [value, prevValueRef, handleChange]);\n\n return uncontrolledState;\n}\n\nexport { useControllableState };\n", "import * as React from 'react';\nimport { Primitive } from '@radix-ui/react-primitive';\n\n/* -------------------------------------------------------------------------------------------------\n * VisuallyHidden\n * -----------------------------------------------------------------------------------------------*/\n\nconst NAME = 'VisuallyHidden';\n\ntype VisuallyHiddenElement = React.ElementRef<typeof Primitive.span>;\ntype PrimitiveSpanProps = React.ComponentPropsWithoutRef<typeof Primitive.span>;\ninterface VisuallyHiddenProps extends PrimitiveSpanProps {}\n\nconst VisuallyHidden = React.forwardRef<VisuallyHiddenElement, VisuallyHiddenProps>(\n (props, forwardedRef) => {\n return (\n <Primitive.span\n {...props}\n ref={forwardedRef}\n style={{\n // See: https://github.com/twbs/bootstrap/blob/master/scss/mixins/_screen-reader.scss\n position: 'absolute',\n border: 0,\n width: 1,\n height: 1,\n padding: 0,\n margin: -1,\n overflow: 'hidden',\n clip: 'rect(0, 0, 0, 0)',\n whiteSpace: 'nowrap',\n wordWrap: 'normal',\n ...props.style,\n }}\n />\n );\n }\n);\n\nVisuallyHidden.displayName = NAME;\n\n/* -----------------------------------------------------------------------------------------------*/\n\nconst Root = VisuallyHidden;\n\nexport {\n VisuallyHidden,\n //\n Root,\n};\nexport type { VisuallyHiddenProps };\n", "import * as React from 'react';\nimport { useComposedRefs } from '@radix-ui/react-compose-refs';\nimport { useLayoutEffect } from '@radix-ui/react-use-layout-effect';\nimport { useStateMachine } from './useStateMachine';\n\ninterface PresenceProps {\n children: React.ReactElement | ((props: { present: boolean }) => React.ReactElement);\n present: boolean;\n}\n\nconst Presence: React.FC<PresenceProps> = (props) => {\n const { present, children } = props;\n const presence = usePresence(present);\n\n const child = (\n typeof children === 'function'\n ? children({ present: presence.isPresent })\n : React.Children.only(children)\n ) as React.ReactElement;\n\n const ref = useComposedRefs(presence.ref, getElementRef(child));\n const forceMount = typeof children === 'function';\n return forceMount || presence.isPresent ? React.cloneElement(child, { ref }) : null;\n};\n\nPresence.displayName = 'Presence';\n\n/* -------------------------------------------------------------------------------------------------\n * usePresence\n * -----------------------------------------------------------------------------------------------*/\n\nfunction usePresence(present: boolean) {\n const [node, setNode] = React.useState<HTMLElement>();\n const stylesRef = React.useRef<CSSStyleDeclaration>({} as any);\n const prevPresentRef = React.useRef(present);\n const prevAnimationNameRef = React.useRef<string>('none');\n const initialState = present ? 'mounted' : 'unmounted';\n const [state, send] = 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 React.useEffect(() => {\n const currentAnimationName = getAnimationName(stylesRef.current);\n prevAnimationNameRef.current = state === 'mounted' ? currentAnimationName : 'none';\n }, [state]);\n\n useLayoutEffect(() => {\n const styles = stylesRef.current;\n const wasPresent = prevPresentRef.current;\n const hasPresentChanged = wasPresent !== present;\n\n if (hasPresentChanged) {\n const prevAnimationName = prevAnimationNameRef.current;\n const currentAnimationName = getAnimationName(styles);\n\n if (present) {\n send('MOUNT');\n } else if (currentAnimationName === 'none' || styles?.display === 'none') {\n // If there is no exit animation or the element is hidden, animations won't run\n // so we unmount instantly\n send('UNMOUNT');\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\n if (wasPresent && isAnimating) {\n send('ANIMATION_OUT');\n } else {\n send('UNMOUNT');\n }\n }\n\n prevPresentRef.current = present;\n }\n }, [present, send]);\n\n useLayoutEffect(() => {\n if (node) {\n let timeoutId: number;\n const ownerWindow = node.ownerDocument.defaultView ?? window;\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(stylesRef.current);\n const isCurrentAnimation = currentAnimationName.includes(event.animationName);\n if (event.target === node && isCurrentAnimation) {\n // With React 18 concurrency this update is applied a frame after the\n // animation ends, creating a flash of visible content. By setting the\n // animation fill mode to \"forwards\", we force the node to keep the\n // styles of the last keyframe, removing the flash.\n //\n // Previously we flushed the update via ReactDom.flushSync, but with\n // exit animations this resulted in the node being removed from the\n // DOM before the synthetic animationEnd event was dispatched, meaning\n // user-provided event handlers would not be called.\n // https://github.com/radix-ui/primitives/pull/1849\n send('ANIMATION_END');\n if (!prevPresentRef.current) {\n const currentFillMode = node.style.animationFillMode;\n node.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.style.animationFillMode === 'forwards') {\n node.style.animationFillMode = currentFillMode;\n }\n });\n }\n }\n };\n const handleAnimationStart = (event: AnimationEvent) => {\n if (event.target === node) {\n // if animation occurred, store its name as the previous animation.\n prevAnimationNameRef.current = getAnimationName(stylesRef.current);\n }\n };\n node.addEventListener('animationstart', handleAnimationStart);\n node.addEventListener('animationcancel', handleAnimationEnd);\n node.addEventListener('animationend', handleAnimationEnd);\n return () => {\n ownerWindow.clearTimeout(timeoutId);\n node.removeEventListener('animationstart', handleAnimationStart);\n node.removeEventListener('animationcancel', handleAnimationEnd);\n node.removeEventListener('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 send('ANIMATION_END');\n }\n }, [node, send]);\n\n return {\n isPresent: ['mounted', 'unmountSuspended'].includes(state),\n ref: React.useCallback((node: HTMLElement) => {\n if (node) stylesRef.current = getComputedStyle(node);\n setNode(node);\n }, []),\n };\n}\n\n/* -----------------------------------------------------------------------------------------------*/\n\nfunction getAnimationName(styles?: CSSStyleDeclaration) {\n return styles?.animationName || 'none';\n}\n\n// Before React 19 accessing `element.props.ref` will throw a warning and suggest using `element.ref`\n// After React 19 accessing `element.ref` does the opposite.\n// https://github.com/facebook/react/pull/28348\n//\n// Access the ref using the method that doesn't yield a warning.\nfunction getElementRef(element: React.ReactElement) {\n // React <=18 in DEV\n let getter = Object.getOwnPropertyDescriptor(element.props, 'ref')?.get;\n let mayWarn = getter && 'isReactWarning' in getter && getter.isReactWarning;\n if (mayWarn) {\n return (element as any).ref;\n }\n\n // React 19 in DEV\n getter = Object.getOwnPropertyDescriptor(element, 'ref')?.get;\n mayWarn = getter && 'isReactWarning' in getter && getter.isReactWarning;\n if (mayWarn) {\n return element.props.ref;\n }\n\n // Not DEV\n return element.props.ref || (element as any).ref;\n}\n\nexport { Presence };\nexport type { PresenceProps };\n", "import * as React from 'react';\n\ntype Machine<S> = { [k: string]: { [k: string]: S } };\ntype MachineState<T> = keyof T;\ntype MachineEvent<T> = keyof UnionToIntersection<T[keyof T]>;\n\n// \uD83E\uDD2F https://fettblog.eu/typescript-union-to-intersection/\ntype UnionToIntersection<T> = (T extends any ? (x: T) => any : never) extends (x: infer R) => any\n ? R\n : never;\n\nexport function useStateMachine<M>(\n initialState: MachineState<M>,\n machine: M & Machine<MachineState<M>>\n) {\n return React.useReducer((state: MachineState<M>, event: MachineEvent<M>): MachineState<M> => {\n const nextState = (machine[state] as any)[event];\n return nextState ?? state;\n }, initialState);\n}\n", "/* eslint-disable no-restricted-properties */\n\n/* eslint-disable no-restricted-globals */\nexport const canUseDOM = !!(\n typeof window !== 'undefined' &&\n window.document &&\n window.document.createElement\n);\n/* eslint-enable no-restricted-globals */\n\nexport function composeEventHandlers<E extends { defaultPrevented: boolean }>(\n originalEventHandler?: (event: E) => void,\n ourEventHandler?: (event: E) => void,\n { checkForDefaultPrevented = true } = {}\n) {\n return function handleEvent(event: E) {\n originalEventHandler?.(event);\n\n if (checkForDefaultPrevented === false || !event.defaultPrevented) {\n return ourEventHandler?.(event);\n }\n };\n}\n\nexport function getOwnerWindow(element: Node | null | undefined) {\n if (!canUseDOM) {\n throw new Error('Cannot access window outside of the DOM');\n }\n // eslint-disable-next-line no-restricted-globals\n return element?.ownerDocument?.defaultView ?? window;\n}\n\nexport function getOwnerDocument(element: Node | null | undefined) {\n if (!canUseDOM) {\n throw new Error('Cannot access document outside of the DOM');\n }\n // eslint-disable-next-line no-restricted-globals\n return element?.ownerDocument ?? document;\n}\n\n/**\n * Lifted from https://github.com/ariakit/ariakit/blob/main/packages/ariakit-core/src/utils/dom.ts#L37\n * MIT License, Copyright (c) AriaKit.\n */\nexport function getActiveElement(\n node: Node | null | undefined,\n activeDescendant = false\n): HTMLElement | null {\n const { activeElement } = getOwnerDocument(node);\n if (!activeElement?.nodeName) {\n // `activeElement` might be an empty object if we're interacting with elements\n // inside of an iframe.\n return null;\n }\n\n if (isFrame(activeElement) && activeElement.contentDocument) {\n return getActiveElement(activeElement.contentDocument.body, activeDescendant);\n }\n\n if (activeDescendant) {\n const id = activeElement.getAttribute('aria-activedescendant');\n if (id) {\n const element = getOwnerDocument(activeElement).getElementById(id);\n if (element) {\n return element;\n }\n }\n }\n\n return activeElement as HTMLElement | null;\n}\n\nexport function isFrame(element: Element): element is HTMLIFrameElement {\n return element.tagName === 'IFRAME';\n}\n", "import * as React from 'react';\nimport { composeEventHandlers } from '@radix-ui/primitive';\nimport { useComposedRefs } from '@radix-ui/react-compose-refs';\nimport { createContextScope } from '@radix-ui/react-context';\nimport { DismissableLayer } from '@radix-ui/react-dismissable-layer';\nimport { useId } from '@radix-ui/react-id';\nimport * as PopperPrimitive from '@radix-ui/react-popper';\nimport { createPopperScope } from '@radix-ui/react-popper';\nimport { Portal as PortalPrimitive } from '@radix-ui/react-portal';\nimport { Presence } from '@radix-ui/react-presence';\nimport { Primitive } from '@radix-ui/react-primitive';\nimport { Slottable } from '@radix-ui/react-slot';\nimport { useControllableState } from '@radix-ui/react-use-controllable-state';\nimport * as VisuallyHiddenPrimitive from '@radix-ui/react-visually-hidden';\n\nimport type { Scope } from '@radix-ui/react-context';\n\ntype ScopedProps<P = {}> = P & { __scopeTooltip?: Scope };\nconst [createTooltipContext, createTooltipScope] = createContextScope('Tooltip', [\n createPopperScope,\n]);\nconst usePopperScope = createPopperScope();\n\n/* -------------------------------------------------------------------------------------------------\n * TooltipProvider\n * -----------------------------------------------------------------------------------------------*/\n\nconst PROVIDER_NAME = 'TooltipProvider';\nconst DEFAULT_DELAY_DURATION = 700;\nconst TOOLTIP_OPEN = 'tooltip.open';\n\ntype TooltipProviderContextValue = {\n isOpenDelayed: boolean;\n delayDuration: number;\n onOpen(): void;\n onClose(): void;\n onPointerInTransitChange(inTransit: boolean): void;\n isPointerInTransitRef: React.MutableRefObject<boolean>;\n disableHoverableContent: boolean;\n};\n\nconst [TooltipProviderContextProvider, useTooltipProviderContext] =\n createTooltipContext<TooltipProviderContextValue>(PROVIDER_NAME);\n\ninterface TooltipProviderProps {\n children: React.ReactNode;\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\nconst TooltipProvider: React.FC<TooltipProviderProps> = (\n props: ScopedProps<TooltipProviderProps>\n) => {\n const {\n __scopeTooltip,\n delayDuration = DEFAULT_DELAY_DURATION,\n skipDelayDuration = 300,\n disableHoverableContent = false,\n children,\n } = props;\n const [isOpenDelayed, setIsOpenDelayed] = React.useState(true);\n const isPointerInTransitRef = React.useRef(false);\n const skipDelayTimerRef = React.useRef(0);\n\n React.useEffect(() => {\n const skipDelayTimer = skipDelayTimerRef.current;\n return () => window.clearTimeout(skipDelayTimer);\n }, []);\n\n return (\n <TooltipProviderContextProvider\n scope={__scopeTooltip}\n isOpenDelayed={isOpenDelayed}\n delayDuration={delayDuration}\n onOpen={React.useCallback(() => {\n window.clearTimeout(skipDelayTimerRef.current);\n setIsOpenDelayed(false);\n }, [])}\n onClose={React.useCallback(() => {\n window.clearTimeout(skipDelayTimerRef.current);\n skipDelayTimerRef.current = window.setTimeout(\n () => setIsOpenDelayed(true),\n skipDelayDuration\n );\n }, [skipDelayDuration])}\n isPointerInTransitRef={isPointerInTransitRef}\n onPointerInTransitChange={React.useCallback((inTransit: boolean) => {\n isPointerInTransitRef.current = inTransit;\n }, [])}\n disableHoverableContent={disableHoverableContent}\n >\n {children}\n </TooltipProviderContextProvider>\n );\n};\n\nTooltipProvider.displayName = PROVIDER_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * Tooltip\n * -----------------------------------------------------------------------------------------------*/\n\nconst TOOLTIP_NAME = 'Tooltip';\n\ntype TooltipContextValue = {\n contentId: string;\n open: boolean;\n stateAttribute: 'closed' | 'delayed-open' | 'instant-open';\n trigger: TooltipTriggerElement | null;\n onTriggerChange(trigger: TooltipTriggerElement | null): void;\n onTriggerEnter(): void;\n onTriggerLeave(): void;\n onOpen(): void;\n onClose(): void;\n disableHoverableContent: boolean;\n};\n\nconst [TooltipContextProvider, useTooltipContext] =\n createTooltipContext<TooltipContextValue>(TOOLTIP_NAME);\n\ninterface TooltipProps {\n children?: React.ReactNode;\n open?: boolean;\n defaultOpen?: boolean;\n onOpenChange?: (open: boolean) => void;\n /**\n * The duration from when the pointer enters the trigger until the tooltip gets opened. This will\n * override the prop with the same name passed to Provider.\n * @defaultValue 700\n */\n delayDuration?: 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\nconst Tooltip: React.FC<TooltipProps> = (props: ScopedProps<TooltipProps>) => {\n const {\n __scopeTooltip,\n children,\n open: openProp,\n defaultOpen = false,\n onOpenChange,\n disableHoverableContent: disableHoverableContentProp,\n delayDuration: delayDurationProp,\n } = props;\n const providerContext = useTooltipProviderContext(TOOLTIP_NAME, props.__scopeTooltip);\n const popperScope = usePopperScope(__scopeTooltip);\n const [trigger, setTrigger] = React.useState<HTMLButtonElement | null>(null);\n const contentId = useId();\n const openTimerRef = React.useRef(0);\n const disableHoverableContent =\n disableHoverableContentProp ?? providerContext.disableHoverableContent;\n const delayDuration = delayDurationProp ?? providerContext.delayDuration;\n const wasOpenDelayedRef = React.useRef(false);\n const [open = false, setOpen] = useControllableState({\n prop: openProp,\n defaultProp: defaultOpen,\n onChange: (open) => {\n if (open) {\n providerContext.onOpen();\n\n // as `onChange` is called within a lifecycle method we\n // avoid dispatching via `dispatchDiscreteCustomEvent`.\n document.dispatchEvent(new CustomEvent(TOOLTIP_OPEN));\n } else {\n providerContext.onClose();\n }\n onOpenChange?.(open);\n },\n });\n const stateAttribute = React.useMemo(() => {\n return open ? (wasOpenDelayedRef.current ? 'delayed-open' : 'instant-open') : 'closed';\n }, [open]);\n\n const handleOpen = React.useCallback(() => {\n window.clearTimeout(openTimerRef.current);\n wasOpenDelayedRef.current = false;\n setOpen(true);\n }, [setOpen]);\n\n const handleClose = React.useCallback(() => {\n window.clearTimeout(openTimerRef.current);\n setOpen(false);\n }, [setOpen]);\n\n const handleDelayedOpen = React.useCallback(() => {\n window.clearTimeout(openTimerRef.current);\n openTimerRef.current = window.setTimeout(() => {\n wasOpenDelayedRef.current = true;\n setOpen(true);\n }, delayDuration);\n }, [delayDuration, setOpen]);\n\n React.useEffect(() => {\n return () => window.clearTimeout(openTimerRef.current);\n }, []);\n\n return (\n <PopperPrimitive.Root {...popperScope}>\n <TooltipContextProvider\n scope={__scopeTooltip}\n contentId={contentId}\n open={open}\n stateAttribute={stateAttribute}\n trigger={trigger}\n onTriggerChange={setTrigger}\n onTriggerEnter={React.useCallback(() => {\n if (providerContext.isOpenDelayed) handleDelayedOpen();\n else handleOpen();\n }, [providerContext.isOpenDelayed, handleDelayedOpen, handleOpen])}\n onTriggerLeave={React.useCallback(() => {\n if (disableHoverableContent) {\n handleClose();\n } else {\n // Clear the timer in case the pointer leaves the trigger before the tooltip is opened.\n window.clearTimeout(openTimerRef.current);\n }\n }, [handleClose, disableHoverableContent])}\n onOpen={handleOpen}\n onClose={handleClose}\n disableHoverableContent={disableHoverableContent}\n >\n {children}\n </TooltipContextProvider>\n </PopperPrimitive.Root>\n );\n};\n\nTooltip.displayName = TOOLTIP_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * TooltipTrigger\n * -----------------------------------------------------------------------------------------------*/\n\nconst TRIGGER_NAME = 'TooltipTrigger';\n\ntype TooltipTriggerElement = React.ElementRef<typeof Primitive.button>;\ntype PrimitiveButtonProps = React.ComponentPropsWithoutRef<typeof Primitive.button>;\ninterface TooltipTriggerProps extends PrimitiveButtonProps {}\n\nconst TooltipTrigger = React.forwardRef<TooltipTriggerElement, TooltipTriggerProps>(\n (props: ScopedProps<TooltipTriggerProps>, forwardedRef) => {\n const { __scopeTooltip, ...triggerProps } = props;\n const context = useTooltipContext(TRIGGER_NAME, __scopeTooltip);\n const providerContext = useTooltipProviderContext(TRIGGER_NAME, __scopeTooltip);\n const popperScope = usePopperScope(__scopeTooltip);\n const ref = React.useRef<TooltipTriggerElement>(null);\n const composedRefs = useComposedRefs(forwardedRef, ref, context.onTriggerChange);\n const isPointerDownRef = React.useRef(false);\n const hasPointerMoveOpenedRef = React.useRef(false);\n const handlePointerUp = React.useCallback(() => (isPointerDownRef.current = false), []);\n\n React.useEffect(() => {\n return () => document.removeEventListener('pointerup', handlePointerUp);\n }, [handlePointerUp]);\n\n return (\n <PopperPrimitive.Anchor asChild {...popperScope}>\n <Primitive.button\n // We purposefully avoid adding `type=button` here because tooltip triggers are also\n // commonly anchors and the anchor `type` attribute signifies MIME type.\n aria-describedby={context.open ? context.contentId : undefined}\n data-state={context.stateAttribute}\n {...triggerProps}\n ref={composedRefs}\n onPointerMove={composeEventHandlers(props.onPointerMove, (event) => {\n if (event.pointerType === 'touch') return;\n if (\n !hasPointerMoveOpenedRef.current &&\n !providerContext.isPointerInTransitRef.current\n ) {\n context.onTriggerEnter();\n hasPointerMoveOpenedRef.current = true;\n }\n })}\n onPointerLeave={composeEventHandlers(props.onPointerLeave, () => {\n context.onTriggerLeave();\n hasPointerMoveOpenedRef.current = false;\n })}\n onPointerDown={composeEventHandlers(props.onPointerDown, () => {\n isPointerDownRef.current = true;\n document.addEventListener('pointerup', handlePointerUp, { once: true });\n })}\n onFocus={composeEventHandlers(props.onFocus, () => {\n if (!isPointerDownRef.current) context.onOpen();\n })}\n onBlur={composeEventHandlers(props.onBlur, context.onClose)}\n onClick={composeEventHandlers(props.onClick, context.onClose)}\n />\n </PopperPrimitive.Anchor>\n );\n }\n);\n\nTooltipTrigger.displayName = TRIGGER_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * TooltipPortal\n * -----------------------------------------------------------------------------------------------*/\n\nconst PORTAL_NAME = 'TooltipPortal';\n\ntype PortalContextValue = { forceMount?: true };\nconst [PortalProvider, usePortalContext] = createTooltipContext<PortalContextValue>(PORTAL_NAME, {\n forceMount: undefined,\n});\n\ntype PortalProps = React.ComponentPropsWithoutRef<typeof PortalPrimitive>;\ninterface TooltipPortalProps {\n children?: React.ReactNode;\n /**\n * Specify a container element to portal the content into.\n */\n container?: PortalProps['container'];\n /**\n * Used to force mounting when more control is needed. Useful when\n * controlling animation with React animation libraries.\n */\n forceMount?: true;\n}\n\nconst TooltipPortal: React.FC<TooltipPortalProps> = (props: ScopedProps<TooltipPortalProps>) => {\n const { __scopeTooltip, forceMount, children, container } = props;\n const context = useTooltipContext(PORTAL_NAME, __scopeTooltip);\n return (\n <PortalProvider scope={__scopeTooltip} forceMount={forceMount}>\n <Presence present={forceMount || context.open}>\n <PortalPrimitive asChild container={container}>\n {children}\n </PortalPrimitive>\n </Presence>\n </PortalProvider>\n );\n};\n\nTooltipPortal.displayName = PORTAL_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * TooltipContent\n * -----------------------------------------------------------------------------------------------*/\n\nconst CONTENT_NAME = 'TooltipContent';\n\ntype TooltipContentElement = TooltipContentImplElement;\ninterface TooltipContentProps extends TooltipContentImplProps {\n /**\n * Used to force mounting when more control is needed. Useful when\n * controlling animation with React animation libraries.\n */\n forceMount?: true;\n}\n\nconst TooltipContent = React.forwardRef<TooltipContentElement, TooltipContentProps>(\n (props: ScopedProps<TooltipContentProps>, forwardedRef) => {\n const portalContext = usePortalContext(CONTENT_NAME, props.__scopeTooltip);\n const { forceMount = portalContext.forceMount, side = 'top', ...contentProps } = props;\n const context = useTooltipContext(CONTENT_NAME, props.__scopeTooltip);\n\n return (\n <Presence present={forceMount || context.open}>\n {context.disableHoverableContent ? (\n <TooltipContentImpl side={side} {...contentProps} ref={forwardedRef} />\n ) : (\n <TooltipContentHoverable side={side} {...contentProps} ref={forwardedRef} />\n )}\n </Presence>\n );\n }\n);\n\ntype Point = { x: number; y: number };\ntype Polygon = Point[];\n\ntype TooltipContentHoverableElement = TooltipContentImplElement;\ninterface TooltipContentHoverableProps extends TooltipContentImplProps {}\n\nconst TooltipContentHoverable = React.forwardRef<\n TooltipContentHoverableElement,\n TooltipContentHoverableProps\n>((props: ScopedProps<TooltipContentHoverableProps>, forwardedRef) => {\n const context = useTooltipContext(CONTENT_NAME, props.__scopeTooltip);\n const providerContext = useTooltipProviderContext(CONTENT_NAME, props.__scopeTooltip);\n const ref = React.useRef<TooltipContentHoverableElement>(null);\n const composedRefs = useComposedRefs(forwardedRef, ref);\n const [pointerGraceArea, setPointerGraceArea] = React.useState<Polygon | null>(null);\n\n const { trigger, onClose } = context;\n const content = ref.current;\n\n const { onPointerInTransitChange } = providerContext;\n\n const handleRemoveGraceArea = React.useCallback(() => {\n setPointerGraceArea(null);\n onPointerInTransitChange(false);\n }, [onPointerInTransitChange]);\n\n const handleCreateGraceArea = React.useCallback(\n (event: PointerEvent, hoverTarget: HTMLElement) => {\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);\n const hoverTargetPoints = getPointsFromRect(hoverTarget.getBoundingClientRect());\n const graceArea = getHull([...paddedExitPoints, ...hoverTargetPoints]);\n setPointerGraceArea(graceArea);\n onPointerInTransitChange(true);\n },\n [onPointerInTransitChange]\n );\n\n React.useEffect(() => {\n return () => handleRemoveGraceArea();\n }, [handleRemoveGraceArea]);\n\n React.useEffect(() => {\n if (trigger && content) {\n const handleTriggerLeave = (event: PointerEvent) => handleCreateGraceArea(event, content);\n const handleContentLeave = (event: PointerEvent) => handleCreateGraceArea(event, trigger);\n\n trigger.addEventListener('pointerleave', handleTriggerLeave);\n content.addEventListener('pointerleave', handleContentLeave);\n return () => {\n trigger.removeEventListener('pointerleave', handleTriggerLeave);\n content.removeEventListener('pointerleave', handleContentLeave);\n };\n }\n }, [trigger, content, handleCreateGraceArea, handleRemoveGraceArea]);\n\n React.useEffect(() => {\n if (pointerGraceArea) {\n const handleTrackPointerGrace = (event: PointerEvent) => {\n const target = event.target as HTMLElement;\n const pointerPosition = { x: event.clientX, y: event.clientY };\n const hasEnteredTarget = trigger?.contains(target) || content?.contains(target);\n const isPointerOutsideGraceArea = !isPointInPolygon(pointerPosition, pointerGraceArea);\n\n if (hasEnteredTarget) {\n handleRemoveGraceArea();\n } else if (isPointerOutsideGraceArea) {\n handleRemoveGraceArea();\n onClose();\n }\n };\n document.addEventListener('pointermove', handleTrackPointerGrace);\n return () => document.removeEventListener('pointermove', handleTrackPointerGrace);\n }\n }, [trigger, content, pointerGraceArea, onClose, handleRemoveGraceArea]);\n\n return <TooltipContentImpl {...props} ref={composedRefs} />;\n});\n\nconst [VisuallyHiddenContentContextProvider, useVisuallyHiddenContentContext] =\n createTooltipContext(TOOLTIP_NAME, { isInside: false });\n\ntype TooltipContentImplElement = React.ElementRef<typeof PopperPrimitive.Content>;\ntype DismissableLayerProps = React.ComponentPropsWithoutRef<typeof DismissableLayer>;\ntype PopperContentProps = React.ComponentPropsWithoutRef<typeof PopperPrimitive.Content>;\ninterface TooltipContentImplProps extends Omit<PopperContentProps, 'onPlaced'> {\n /**\n * A more descriptive label for accessibility purpose\n */\n 'aria-label'?: string;\n\n /**\n * Event handler called when the escape key is down.\n * Can be prevented.\n */\n onEscapeKeyDown?: DismissableLayerProps['onEscapeKeyDown'];\n /**\n * Event handler called when the a `pointerdown` event happens outside of the `Tooltip`.\n * Can be prevented.\n */\n onPointerDownOutside?: DismissableLayerProps['onPointerDownOutside'];\n}\n\nconst TooltipContentImpl = React.forwardRef<TooltipContentImplElement, TooltipContentImplProps>(\n (props: ScopedProps<TooltipContentImplProps>, forwardedRef) => {\n const {\n __scopeTooltip,\n children,\n 'aria-label': ariaLabel,\n onEscapeKeyDown,\n onPointerDownOutside,\n ...contentProps\n } = props;\n const context = useTooltipContext(CONTENT_NAME, __scopeTooltip);\n const popperScope = usePopperScope(__scopeTooltip);\n const { onClose } = context;\n\n // Close this tooltip if another one opens\n React.useEffect(() => {\n document.addEventListener(TOOLTIP_OPEN, onClose);\n return () => document.removeEventListener(TOOLTIP_OPEN, onClose);\n }, [onClose]);\n\n // Close the tooltip if the trigger is scrolled\n React.useEffect(() => {\n if (context.trigger) {\n const handleScroll = (event: Event) => {\n const target = event.target as HTMLElement;\n if (target?.contains(context.trigger)) onClose();\n };\n window.addEventListener('scroll', handleScroll, { capture: true });\n return () => window.removeEventListener('scroll', handleScroll, { capture: true });\n }\n }, [context.trigger, onClose]);\n\n return (\n <DismissableLayer\n asChild\n disableOutsidePointerEvents={false}\n onEscapeKeyDown={onEscapeKeyDown}\n onPointerDownOutside={onPointerDownOutside}\n onFocusOutside={(event) => event.preventDefault()}\n onDismiss={onClose}\n >\n <PopperPrimitive.Content\n data-state={context.stateAttribute}\n {...popperScope}\n {...contentProps}\n ref={forwardedRef}\n style={{\n ...contentProps.style,\n // re-namespace exposed content custom properties\n ...{\n '--radix-tooltip-content-transform-origin': 'var(--radix-popper-transform-origin)',\n '--radix-tooltip-content-available-width': 'var(--radix-popper-available-width)',\n '--radix-tooltip-content-available-height': 'var(--radix-popper-available-height)',\n '--radix-tooltip-trigger-width': 'var(--radix-popper-anchor-width)',\n '--radix-tooltip-trigger-height': 'var(--radix-popper-anchor-height)',\n },\n }}\n >\n <Slottable>{children}</Slottable>\n <VisuallyHiddenContentContextProvider scope={__scopeTooltip} isInside={true}>\n <VisuallyHiddenPrimitive.Root id={context.contentId} role=\"tooltip\">\n {ariaLabel || children}\n </VisuallyHiddenPrimitive.Root>\n </VisuallyHiddenContentContextProvider>\n </PopperPrimitive.Content>\n </DismissableLayer>\n );\n }\n);\n\nTooltipContent.displayName = CONTENT_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * TooltipArrow\n * -----------------------------------------------------------------------------------------------*/\n\nconst ARROW_NAME = 'TooltipArrow';\n\ntype TooltipArrowElement = React.ElementRef<typeof PopperPrimitive.Arrow>;\ntype PopperArrowProps = React.ComponentPropsWithoutRef<typeof PopperPrimitive.Arrow>;\ninterface TooltipArrowProps extends PopperArrowProps {}\n\nconst TooltipArrow = React.forwardRef<TooltipArrowElement, TooltipArrowProps>(\n (props: ScopedProps<TooltipArrowProps>, forwardedRef) => {\n const { __scopeTooltip, ...arrowProps } = props;\n const popperScope = usePopperScope(__scopeTooltip);\n const visuallyHiddenContentContext = useVisuallyHiddenContentContext(\n ARROW_NAME,\n __scopeTooltip\n );\n // if the arrow is inside the `VisuallyHidden`, we don't want to render it all to\n // prevent issues in positioning the arrow due to the duplicate\n return visuallyHiddenContentContext.isInside ? null : (\n <PopperPrimitive.Arrow {...popperScope} {...arrowProps} ref={forwardedRef} />\n );\n }\n);\n\nTooltipArrow.displayName = ARROW_NAME;\n\n/* -----------------------------------------------------------------------------------------------*/\n\ntype Side = NonNullable<TooltipContentProps['side']>;\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) 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) return -1;\n else if (a.x > b.x) return +1;\n else if (a.y < b.y) return -1;\n else if (a.y > b.y) 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) 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[upperHull.length - 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)) 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[lowerHull.length - 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)) 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 } else {\n return upperHull.concat(lowerHull);\n }\n}\n\nconst Provider = TooltipProvider;\nconst Root = Tooltip;\nconst Trigger = TooltipTrigger;\nconst Portal = TooltipPortal;\nconst Content = TooltipContent;\nconst Arrow = TooltipArrow;\n\nexport {\n createTooltipScope,\n //\n TooltipProvider,\n Tooltip,\n TooltipTrigger,\n TooltipPortal,\n TooltipContent,\n TooltipArrow,\n //\n Provider,\n Root,\n Trigger,\n Portal,\n Content,\n Arrow,\n};\nexport type {\n TooltipProviderProps,\n TooltipProps,\n TooltipTriggerProps,\n TooltipPortalProps,\n TooltipContentProps,\n TooltipArrowProps,\n};\n", "import { forwardRefIfNeeded } from \"@stackframe/stack-shared/dist/utils/react\";\n\nimport { cn } from \"../../lib/utils\";\n\nconst Card = forwardRefIfNeeded<\n HTMLDivElement,\n React.HTMLAttributes<HTMLDivElement>\n>(({ className, ...props }, ref) => (\n <div\n ref={ref}\n className={cn(\n \"rounded-xl border bg-card text-card-foreground shadow-sm\",\n className\n )}\n {...props}\n />\n));\nCard.displayName = \"Card\";\n\nconst CardHeader = forwardRefIfNeeded<\n HTMLDivElement,\n React.HTMLAttributes<HTMLDivElement>\n>(({ className, ...props }, ref) => (\n <div\n ref={ref}\n className={cn(\"flex flex-col space-y-1.5 p-6 pb-0\", className)}\n {...props}\n />\n));\nCardHeader.displayName = \"CardHeader\";\n\nconst CardTitle = forwardRefIfNeeded<\n HTMLParagraphElement,\n React.HTMLAttributes<HTMLHeadingElement>\n>(({ className, ...props }, ref) => (\n <h3\n ref={ref}\n className={cn(\"font-semibold leading-none tracking-tight capitalize\", className)}\n {...props}\n />\n));\nCardTitle.displayName = \"CardTitle\";\n\nconst CardDescription = forwardRefIfNeeded<\n HTMLParagraphElement,\n React.HTMLAttributes<HTMLParagraphElement>\n>(({ className, ...props }, ref) => (\n <p\n ref={ref}\n className={cn(\"text-sm text-muted-foreground\", className)}\n {...props}\n />\n));\nCardDescription.displayName = \"CardDescription\";\n\nconst CardContent = forwardRefIfNeeded<\n HTMLDivElement,\n React.HTMLAttributes<HTMLDivElement>\n>(({ className, ...props }, ref) => (\n <div ref={ref} className={cn(\"p-6\", className)} {...props} />\n));\nCardContent.displayName = \"CardContent\";\n\nconst CardSubtitle = forwardRefIfNeeded<\n HTMLParagraphElement,\n React.HTMLAttributes<HTMLParagraphElement>\n>(({ className, ...props }, ref) => (\n <h4\n ref={ref}\n className={cn(\"text-sm text-muted-foreground font-bold\", className)}\n {...props}\n />\n));\n\nconst CardFooter = forwardRefIfNeeded<\n HTMLDivElement,\n React.HTMLAttributes<HTMLDivElement>\n>(({ className, ...props }, ref) => (\n <div\n ref={ref}\n className={cn(\"flex items-center p-6 pt-0\", className)}\n {...props}\n />\n));\nCardFooter.displayName = \"CardFooter\";\n\nexport { Card, CardContent, CardDescription, CardFooter, CardHeader, CardSubtitle, CardTitle };\n\n", "\"use client\";\n\nimport { CheckCircle, Info, WarningCircle, XCircle } from \"@phosphor-icons/react\";\nimport { cn } from \"@stackframe/stack-ui\";\n\ntype DesignAlertVariant = \"default\" | \"success\" | \"error\" | \"warning\" | \"info\";\n\nconst variantIconMap = new Map<DesignAlertVariant, React.ElementType>([\n [\"default\", Info],\n [\"success\", CheckCircle],\n [\"error\", XCircle],\n [\"warning\", WarningCircle],\n [\"info\", Info],\n]);\n\ntype VariantStyles = {\n container: string,\n icon: string,\n title: string,\n};\n\nconst variantStyles = new Map<DesignAlertVariant, VariantStyles>([\n [\n \"default\",\n {\n container: \"bg-background border-border\",\n icon: \"text-foreground\",\n title: \"text-foreground\",\n },\n ],\n [\n \"success\",\n {\n container: \"bg-green-500/[0.06] border-green-500/30\",\n icon: \"text-green-500\",\n title: \"text-green-600 dark:text-green-400\",\n },\n ],\n [\n \"error\",\n {\n container: \"bg-red-500/[0.06] border-red-500/30\",\n icon: \"text-red-500\",\n title: \"text-red-600 dark:text-red-400\",\n },\n ],\n [\n \"warning\",\n {\n container: \"bg-amber-500/[0.08] border-amber-500/40\",\n icon: \"text-amber-600 dark:text-amber-400\",\n title: \"text-amber-700 dark:text-amber-300\",\n },\n ],\n [\n \"info\",\n {\n container: \"bg-blue-500/[0.06] border-blue-500/30\",\n icon: \"text-blue-500\",\n title: \"text-blue-600 dark:text-blue-400\",\n },\n ],\n]);\n\nfunction getMapValueOrThrow<TKey, TValue>(map: Map<TKey, TValue>, key: TKey, mapName: string) {\n const value = map.get(key);\n if (!value) {\n throw new Error(`Missing ${mapName} entry for key \"${String(key)}\"`);\n }\n return value;\n}\n\nexport type DesignAlertProps = React.HTMLAttributes<HTMLDivElement> & {\n variant?: DesignAlertVariant,\n title?: React.ReactNode,\n description?: React.ReactNode,\n glassmorphic?: boolean,\n};\n\nexport function DesignAlert({\n variant = \"default\",\n title,\n description,\n glassmorphic = false,\n className,\n children,\n ...props\n}: DesignAlertProps) {\n const styles = getMapValueOrThrow(variantStyles, variant, \"variantStyles\");\n const Icon = getMapValueOrThrow(variantIconMap, variant, \"variantIconMap\");\n\n return (\n <div\n role=\"alert\"\n className={cn(\n \"relative w-full rounded-2xl border p-4 text-sm\",\n \"flex gap-3 items-start\",\n styles.container,\n glassmorphic && \"backdrop-blur-xl\",\n className\n )}\n {...props}\n >\n <Icon className={cn(\"h-4 w-4 mt-0.5 flex-shrink-0\", styles.icon)} />\n <div className=\"min-w-0\">\n {title && (\n <h5 className={cn(\"mb-1 font-medium leading-none tracking-tight\", styles.title)}>\n {title}\n </h5>\n )}\n {description && (\n <div className=\"text-sm text-foreground/80 dark:text-muted-foreground [&_p]:leading-relaxed\">\n {description}\n </div>\n )}\n {children}\n </div>\n </div>\n );\n}\n", "\"use client\";\n\nimport { cn } from \"@stackframe/stack-ui\";\n\nexport type DesignBadgeColor = \"blue\" | \"cyan\" | \"purple\" | \"green\" | \"orange\" | \"red\";\nexport type DesignBadgeSize = \"sm\" | \"md\";\n\nconst badgeStyles = new Map<DesignBadgeColor, string>([\n [\"blue\", \"text-blue-700 dark:text-blue-400 bg-blue-500/20 dark:bg-blue-500/10 ring-1 ring-blue-500/30 dark:ring-blue-500/20\"],\n [\"cyan\", \"text-cyan-700 dark:text-cyan-400 bg-cyan-500/20 dark:bg-cyan-500/10 ring-1 ring-cyan-500/30 dark:ring-cyan-500/20\"],\n [\"purple\", \"text-purple-700 dark:text-purple-400 bg-purple-500/20 dark:bg-purple-500/10 ring-1 ring-purple-500/30 dark:ring-purple-500/20\"],\n [\"green\", \"text-emerald-700 dark:text-emerald-400 bg-emerald-500/20 dark:bg-emerald-500/10 ring-1 ring-emerald-500/30 dark:ring-emerald-500/20\"],\n [\"orange\", \"text-amber-700 dark:text-amber-300 bg-amber-500/20 dark:bg-amber-500/10 ring-1 ring-amber-500/30 dark:ring-amber-500/20\"],\n [\"red\", \"text-red-700 dark:text-red-400 bg-red-500/20 dark:bg-red-500/10 ring-1 ring-red-500/30 dark:ring-red-500/20\"],\n]);\n\nfunction getMapValueOrThrow<TKey, TValue>(map: Map<TKey, TValue>, key: TKey, mapName: string) {\n const value = map.get(key);\n if (!value) {\n throw new Error(`Missing ${mapName} entry for key \"${String(key)}\"`);\n }\n return value;\n}\n\n/** At least one of showLabel or showIcon must be true. */\nexport type DesignBadgeContentMode = \"both\" | \"text\" | \"icon\";\n\nexport type DesignBadgeProps = {\n label: string,\n color: DesignBadgeColor,\n icon?: React.ElementType,\n size?: DesignBadgeSize,\n /** What to display: \"both\" (default), \"text\" (label only), or \"icon\" (icon only; requires icon prop). */\n contentMode?: DesignBadgeContentMode,\n};\n\nfunction getShowLabelShowIcon(\n contentMode: DesignBadgeContentMode,\n hasIcon: boolean,\n): { showLabel: boolean, showIcon: boolean } {\n switch (contentMode) {\n case \"both\": {\n return { showLabel: true, showIcon: hasIcon };\n }\n case \"text\": {\n return { showLabel: true, showIcon: false };\n }\n case \"icon\": {\n if (!hasIcon) {\n throw new Error(\"DesignBadge contentMode 'icon' requires the icon prop to be provided.\");\n }\n return { showLabel: false, showIcon: true };\n }\n default: {\n const _exhaustive: never = contentMode;\n throw new Error(`Unknown contentMode: ${String(_exhaustive)}`);\n }\n }\n}\n\nexport function DesignBadge({\n label,\n color,\n icon,\n size = \"md\",\n contentMode = \"both\",\n}: DesignBadgeProps) {\n const Icon = icon;\n const { showLabel, showIcon } = getShowLabelShowIcon(contentMode, !!Icon);\n if (!showLabel && !showIcon) {\n throw new Error(\"DesignBadge must show at least label or icon.\");\n }\n const sizeClasses = size === \"sm\"\n ? \"px-2 py-0.5 text-[10px]\"\n : \"px-2.5 py-1 text-[11px]\";\n const colorClasses = getMapValueOrThrow(badgeStyles, color, \"badgeStyles\");\n\n return (\n <div\n className={cn(\n \"inline-flex items-center gap-1.5 rounded-full font-medium\",\n colorClasses,\n sizeClasses\n )}\n title={!showLabel ? label : undefined}\n aria-label={label}\n >\n {showIcon && Icon && <Icon className=\"h-3 w-3\" />}\n {showLabel ? label : null}\n </div>\n );\n}\n", "import * as React from 'react';\nimport { composeRefs } from '@radix-ui/react-compose-refs';\n\ndeclare module 'react' {\n interface ReactElement {\n $$typeof?: symbol | string;\n }\n}\n\nconst REACT_LAZY_TYPE = Symbol.for('react.lazy');\n\ninterface LazyReactElement extends React.ReactElement {\n $$typeof: typeof REACT_LAZY_TYPE;\n _payload: PromiseLike<Exclude<React.ReactNode, PromiseLike<any>>>;\n}\n\n/* -------------------------------------------------------------------------------------------------\n * Slot\n * -----------------------------------------------------------------------------------------------*/\n\nexport type Usable<T> = PromiseLike<T> | React.Context<T>;\nconst use: typeof React.use | undefined = (React as any)[' use '.trim().toString()];\n\ninterface SlotProps extends React.HTMLAttributes<HTMLElement> {\n children?: React.ReactNode;\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return typeof value === 'object' && value !== null && 'then' in value;\n}\n\nfunction isLazyComponent(element: React.ReactNode): element is LazyReactElement {\n return (\n element != null &&\n typeof element === 'object' &&\n '$$typeof' in element &&\n element.$$typeof === REACT_LAZY_TYPE &&\n '_payload' in element &&\n isPromiseLike(element._payload)\n );\n}\n\n/* @__NO_SIDE_EFFECTS__ */ export function createSlot(ownerName: string) {\n const SlotClone = createSlotClone(ownerName);\n const Slot = React.forwardRef<HTMLElement, SlotProps>((props, forwardedRef) => {\n let { children, ...slotProps } = props;\n if (isLazyComponent(children) && typeof use === 'function') {\n children = use(children._payload);\n }\n const childrenArray = React.Children.toArray(children);\n const slottable = childrenArray.find(isSlottable);\n\n if (slottable) {\n // the new element to render is the one passed as a child of `Slottable`\n const newElement = slottable.props.children;\n\n const newChildren = childrenArray.map((child) => {\n if (child === slottable) {\n // because the new element will be the one rendered, we are only interested\n // in grabbing its children (`newElement.props.children`)\n if (React.Children.count(newElement) > 1) return React.Children.only(null);\n return React.isValidElement(newElement)\n ? (newElement.props as { children: React.ReactNode }).children\n : null;\n } else {\n return child;\n }\n });\n\n return (\n <SlotClone {...slotProps} ref={forwardedRef}>\n {React.isValidElement(newElement)\n ? React.cloneElement(newElement, undefined, newChildren)\n : null}\n </SlotClone>\n );\n }\n\n return (\n <SlotClone {...slotProps} ref={forwardedRef}>\n {children}\n </SlotClone>\n );\n });\n\n Slot.displayName = `${ownerName}.Slot`;\n return Slot;\n}\n\nconst Slot = createSlot('Slot');\n\n/* -------------------------------------------------------------------------------------------------\n * SlotClone\n * -----------------------------------------------------------------------------------------------*/\n\ninterface SlotCloneProps {\n children: React.ReactNode;\n}\n\n/* @__NO_SIDE_EFFECTS__ */ function createSlotClone(ownerName: string) {\n const SlotClone = React.forwardRef<any, SlotCloneProps>((props, forwardedRef) => {\n let { children, ...slotProps } = props;\n if (isLazyComponent(children) && typeof use === 'function') {\n children = use(children._payload);\n }\n\n if (React.isValidElement(children)) {\n const childrenRef = getElementRef(children);\n const props = mergeProps(slotProps, children.props as AnyProps);\n // do not pass ref to React.Fragment for React 19 compatibility\n if (children.type !== React.Fragment) {\n props.ref = forwardedRef ? composeRefs(forwardedRef, childrenRef) : childrenRef;\n }\n return React.cloneElement(children, props);\n }\n\n return React.Children.count(children) > 1 ? React.Children.only(null) : null;\n });\n\n SlotClone.displayName = `${ownerName}.SlotClone`;\n return SlotClone;\n}\n\n/* -------------------------------------------------------------------------------------------------\n * Slottable\n * -----------------------------------------------------------------------------------------------*/\n\nconst SLOTTABLE_IDENTIFIER = Symbol('radix.slottable');\n\ninterface SlottableProps {\n children: React.ReactNode;\n}\n\ninterface SlottableComponent extends React.FC<SlottableProps> {\n __radixId: symbol;\n}\n\n/* @__NO_SIDE_EFFECTS__ */ export function createSlottable(ownerName: string) {\n const Slottable: SlottableComponent = ({ children }) => {\n return <>{children}</>;\n };\n Slottable.displayName = `${ownerName}.Slottable`;\n Slottable.__radixId = SLOTTABLE_IDENTIFIER;\n return Slottable;\n}\n\nconst Slottable = createSlottable('Slottable');\n\n/* ---------------------------------------------------------------------------------------------- */\n\ntype AnyProps = Record<string, any>;\n\nfunction isSlottable(\n child: React.ReactNode,\n): child is React.ReactElement<SlottableProps, typeof Slottable> {\n return (\n React.isValidElement(child) &&\n typeof child.type === 'function' &&\n '__radixId' in child.type &&\n child.type.__radixId === SLOTTABLE_IDENTIFIER\n );\n}\n\nfunction mergeProps(slotProps: AnyProps, childProps: AnyProps) {\n // all child props should override\n const overrideProps = { ...childProps };\n\n for (const propName in childProps) {\n const slotPropValue = slotProps[propName];\n const childPropValue = childProps[propName];\n\n const isHandler = /^on[A-Z]/.test(propName);\n if (isHandler) {\n // if the handler exists on both, we compose them\n if (slotPropValue && childPropValue) {\n overrideProps[propName] = (...args: unknown[]) => {\n const result = childPropValue(...args);\n slotPropValue(...args);\n return result;\n };\n }\n // but if it exists only on the slot, we use only this one\n else if (slotPropValue) {\n overrideProps[propName] = slotPropValue;\n }\n }\n // if it's `style`, we merge them\n else if (propName === 'style') {\n overrideProps[propName] = { ...slotPropValue, ...childPropValue };\n } else if (propName === 'className') {\n overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(' ');\n }\n }\n\n return { ...slotProps, ...overrideProps };\n}\n\n// Before React 19 accessing `element.props.ref` will throw a warning and suggest using `element.ref`\n// After React 19 accessing `element.ref` does the opposite.\n// https://github.com/facebook/react/pull/28348\n//\n// Access the ref using the method that doesn't yield a warning.\nfunction getElementRef(element: React.ReactElement) {\n // React <=18 in DEV\n let getter = Object.getOwnPropertyDescriptor(element.props, 'ref')?.get;\n let mayWarn = getter && 'isReactWarning' in getter && getter.isReactWarning;\n if (mayWarn) {\n return (element as any).ref;\n }\n\n // React 19 in DEV\n getter = Object.getOwnPropertyDescriptor(element, 'ref')?.get;\n mayWarn = getter && 'isReactWarning' in getter && getter.isReactWarning;\n if (mayWarn) {\n return (element.props as { ref?: React.Ref<unknown> }).ref;\n }\n\n // Not DEV\n return (element.props as { ref?: React.Ref<unknown> }).ref || (element as any).ref;\n}\n\nexport {\n Slot,\n Slottable,\n //\n Slot as Root,\n};\nexport type { SlotProps };\n", "import * as React from 'react';\n\ntype PossibleRef<T> = React.Ref<T> | undefined;\n\n/**\n * Set a given ref to a given value\n * This utility takes care of different types of refs: callback refs and RefObject(s)\n */\nfunction setRef<T>(ref: PossibleRef<T>, value: T) {\n if (typeof ref === 'function') {\n return ref(value);\n } else if (ref !== null && ref !== undefined) {\n ref.current = value;\n }\n}\n\n/**\n * A utility to compose multiple refs together\n * Accepts callback refs and RefObject(s)\n */\nfunction composeRefs<T>(...refs: PossibleRef<T>[]): React.RefCallback<T> {\n return (node) => {\n let hasCleanup = false;\n const cleanups = refs.map((ref) => {\n const cleanup = setRef(ref, node);\n if (!hasCleanup && typeof cleanup == 'function') {\n hasCleanup = true;\n }\n return cleanup;\n });\n\n // React <19 will log an error to the console if a callback ref returns a\n // value. We don't use ref cleanups internally so this will only happen if a\n // user's ref callback returns a value, which we only expect if they are\n // using the cleanup functionality added in React 19.\n if (hasCleanup) {\n return () => {\n for (let i = 0; i < cleanups.length; i++) {\n const cleanup = cleanups[i];\n if (typeof cleanup == 'function') {\n cleanup();\n } else {\n setRef(refs[i], null);\n }\n }\n };\n }\n };\n}\n\n/**\n * A custom hook that composes multiple refs\n * Accepts callback refs and RefObject(s)\n */\nfunction useComposedRefs<T>(...refs: PossibleRef<T>[]): React.RefCallback<T> {\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return React.useCallback(composeRefs(...refs), refs);\n}\n\nexport { composeRefs, useComposedRefs };\n", "/**\n * Copyright 2022 Joe Bell. All rights reserved.\n *\n * This file is licensed to you under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with the\n * License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n */ import { clsx } from \"clsx\";\nconst falsyToString = (value)=>typeof value === \"boolean\" ? `${value}` : value === 0 ? \"0\" : value;\nexport const cx = clsx;\nexport const cva = (base, config)=>(props)=>{\n var _config_compoundVariants;\n if ((config === null || config === void 0 ? void 0 : config.variants) == null) return cx(base, props === null || props === void 0 ? void 0 : props.class, props === null || props === void 0 ? void 0 : props.className);\n const { variants, defaultVariants } = config;\n const getVariantClassNames = Object.keys(variants).map((variant)=>{\n const variantProp = props === null || props === void 0 ? void 0 : props[variant];\n const defaultVariantProp = defaultVariants === null || defaultVariants === void 0 ? void 0 : defaultVariants[variant];\n if (variantProp === null) return null;\n const variantKey = falsyToString(variantProp) || falsyToString(defaultVariantProp);\n return variants[variant][variantKey];\n });\n const propsWithoutUndefined = props && Object.entries(props).reduce((acc, param)=>{\n let [key, value] = param;\n if (value === undefined) {\n return acc;\n }\n acc[key] = value;\n return acc;\n }, {});\n const getCompoundVariantClassNames = config === null || config === void 0 ? void 0 : (_config_compoundVariants = config.compoundVariants) === null || _config_compoundVariants === void 0 ? void 0 : _config_compoundVariants.reduce((acc, param)=>{\n let { class: cvClass, className: cvClassName, ...compoundVariantOptions } = param;\n return Object.entries(compoundVariantOptions).every((param)=>{\n let [key, value] = param;\n return Array.isArray(value) ? value.includes({\n ...defaultVariants,\n ...propsWithoutUndefined\n }[key]) : ({\n ...defaultVariants,\n ...propsWithoutUndefined\n })[key] === value;\n }) ? [\n ...acc,\n cvClass,\n cvClassName\n ] : acc;\n }, []);\n return cx(base, getVariantClassNames, getCompoundVariantClassNames, props === null || props === void 0 ? void 0 : props.class, props === null || props === void 0 ? void 0 : props.className);\n };\n\n", "import { Slot, Slottable } from \"@radix-ui/react-slot\";\nimport { forwardRefIfNeeded } from \"@stackframe/stack-shared/dist/utils/react\";\nimport { cva, type VariantProps } from \"class-variance-authority\";\nimport React from \"react\";\n\nimport { cn, Spinner } from \"@stackframe/stack-ui\";\nimport { useAsyncCallback } from \"@stackframe/stack-shared/dist/hooks/use-async-callback\";\nimport { runAsynchronouslyWithAlert } from \"@stackframe/stack-shared/dist/utils/promises\";\n\nconst designButtonVariants = cva(\n \"stack-scope inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50\",\n {\n variants: {\n variant: {\n default:\n \"bg-primary text-primary-foreground hover:bg-primary/90\",\n destructive:\n \"bg-destructive text-destructive-foreground hover:bg-destructive/90\",\n outline:\n \"border border-input bg-white/85 dark:bg-background hover:bg-white dark:hover:bg-accent hover:text-accent-foreground\",\n secondary:\n \"bg-secondary text-secondary-foreground hover:bg-secondary/80\",\n ghost: \"hover:bg-accent hover:text-accent-foreground\",\n link: \"text-primary underline-offset-4 hover:underline\",\n plain: \"\",\n },\n size: {\n default: \"h-9 px-4 py-2\",\n sm: \"h-8 rounded-md px-3 text-xs\",\n lg: \"h-10 rounded-md px-8\",\n icon: \"h-9 w-9\",\n },\n },\n defaultVariants: {\n variant: \"default\",\n size: \"default\",\n },\n }\n);\n\nexport type DesignOriginalButtonProps = {\n asChild?: boolean,\n} & React.ButtonHTMLAttributes<HTMLButtonElement> & VariantProps<typeof designButtonVariants>;\n\nconst DesignOriginalButton = forwardRefIfNeeded<HTMLButtonElement, DesignOriginalButtonProps>(\n ({ className, variant, size, asChild = false, ...props }, ref) => {\n const Comp = asChild ? Slot : \"button\";\n return (\n <Comp\n className={cn(designButtonVariants({ variant, size, className }))}\n ref={ref}\n {...props}\n />\n );\n }\n);\nDesignOriginalButton.displayName = \"DesignButton\";\n\nexport type DesignButtonProps = {\n onClick?: (e: React.MouseEvent<HTMLButtonElement>) => void | Promise<void>,\n loading?: boolean,\n loadingStyle?: \"spinner\" | \"disabled\",\n} & DesignOriginalButtonProps;\n\nexport const DesignButton = forwardRefIfNeeded<HTMLButtonElement, DesignButtonProps>(\n ({ onClick, loading: loadingProp, loadingStyle = \"spinner\", children, size, ...props }, ref) => {\n const [handleClick, isLoading] = useAsyncCallback(async (e: React.MouseEvent<HTMLButtonElement>) => {\n await onClick?.(e);\n }, [onClick]);\n\n const loading = loadingProp || isLoading;\n\n return (\n <DesignOriginalButton\n {...props}\n ref={ref}\n disabled={props.disabled || loading}\n onClick={(e) => runAsynchronouslyWithAlert(handleClick(e))}\n size={size}\n className={cn(\"relative\", loading && \"[&>:not(.stack-button-do-not-hide-when-siblings-are)]:invisible\", props.className)}\n >\n {loadingStyle === \"spinner\" && <Spinner className={cn(\"absolute inset-0 flex items-center justify-center stack-button-do-not-hide-when-siblings-are\", !loading && \"invisible\")} />}\n <Slottable>\n {typeof children === \"string\" ? <span>{children}</span> : children}\n </Slottable>\n </DesignOriginalButton>\n );\n }\n);\nDesignButton.displayName = \"DesignButton\";\n", "\"use client\";\n\nimport { Card } from \"@stackframe/stack-ui\";\nimport { cn } from \"@stackframe/stack-ui\";\nimport React from \"react\";\n\n// \u2500\u2500\u2500 Card nesting context \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Components with a `glassmorphic` prop use this to auto-detect whether they\n// sit inside a DesignCard. When they do, glassmorphic defaults to `true`;\n// when they don't, it defaults to `false`.\n\nconst DesignCardNestingContext = React.createContext(false);\n\n/**\n * Returns `true` when the calling component is rendered inside a DesignCard.\n * Useful for deriving a glassmorphic default.\n */\nexport function useInsideDesignCard(): boolean {\n return React.useContext(DesignCardNestingContext);\n}\n\n/**\n * Resolve the effective glassmorphic value.\n * - If the caller passed an explicit boolean \u2192 honour it.\n * - Otherwise \u2192 fall back to whether we're inside a DesignCard.\n */\nexport function useGlassmorphicDefault(explicit: boolean | undefined): boolean {\n const insideCard = useInsideDesignCard();\n return explicit ?? insideCard;\n}\n\ntype DesignCardGradient = \"blue\" | \"cyan\" | \"purple\" | \"green\" | \"orange\" | \"default\";\n\nconst hoverTintClasses = new Map<DesignCardGradient, string>([\n [\"blue\", \"group-hover:bg-blue-500/[0.03]\"],\n [\"purple\", \"group-hover:bg-purple-500/[0.03]\"],\n [\"green\", \"group-hover:bg-emerald-500/[0.03]\"],\n [\"orange\", \"group-hover:bg-orange-500/[0.03]\"],\n [\"default\", \"group-hover:bg-slate-500/[0.02]\"],\n [\"cyan\", \"group-hover:bg-cyan-500/[0.03]\"],\n]);\n\nconst demoTintClasses = new Map<DesignCardGradient, string>([\n [\"blue\", \"group-hover/tint:bg-blue-500/[0.02]\"],\n [\"purple\", \"group-hover/tint:bg-purple-500/[0.02]\"],\n [\"green\", \"group-hover/tint:bg-emerald-500/[0.02]\"],\n [\"orange\", \"group-hover/tint:bg-orange-500/[0.02]\"],\n [\"default\", \"group-hover/tint:bg-slate-500/[0.015]\"],\n [\"cyan\", \"group-hover/tint:bg-cyan-500/[0.02]\"],\n]);\n\nconst bodyPaddingClass = \"p-5\";\n\n// \u2500\u2500\u2500 Discriminated props \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// - If title is given, icon is required.\n// - The layout is derived automatically:\n// title + subtitle \u2192 \"header\" (full header block with subtitle)\n// title only \u2192 \"compact\" (slim bar with border-b)\n// no title \u2192 \"bodyOnly\" (just the body)\n\ntype DesignCardBaseProps = {\n glassmorphic?: boolean,\n gradient?: DesignCardGradient,\n contentClassName?: string,\n} & Omit<React.ComponentProps<typeof Card>, \"title\">;\n\ntype WithTitleProps = {\n title: React.ReactNode,\n subtitle?: React.ReactNode,\n icon: React.ElementType,\n actions?: React.ReactNode,\n};\n\ntype WithoutTitleProps = {\n title?: never,\n subtitle?: never,\n icon?: never,\n actions?: never,\n};\n\nexport type DesignCardProps = DesignCardBaseProps & (WithTitleProps | WithoutTitleProps);\n\nexport function DesignCard({\n title,\n subtitle,\n icon: Icon,\n actions,\n glassmorphic: glassmorphicProp,\n gradient = \"default\",\n children,\n className,\n contentClassName,\n ...props\n}: DesignCardProps) {\n const glassmorphic = glassmorphicProp ?? true;\n const hoverTintClass = hoverTintClasses.get(gradient) ?? \"group-hover:bg-slate-500/[0.02]\";\n const hasContent = React.Children.count(children) > 0;\n\n // Derive layout from which props were provided\n const variant = title != null\n ? (subtitle != null ? \"header\" : \"compact\")\n : \"bodyOnly\";\n\n return (\n <DesignCardNestingContext.Provider value={true}>\n <Card\n className={cn(\n \"group relative rounded-2xl overflow-hidden\",\n glassmorphic && [\n \"bg-white/90 dark:bg-background/60 dark:backdrop-blur-xl border-0 transition-all duration-150 hover:transition-none\",\n \"ring-1 ring-black/[0.06] hover:ring-black/[0.1] dark:ring-white/[0.06] dark:hover:ring-white/[0.1]\",\n \"shadow-none\",\n ],\n glassmorphic && variant === \"bodyOnly\" && \"dark:bg-transparent dark:ring-0 dark:shadow-none\",\n className\n )}\n {...props}\n >\n {glassmorphic && (\n <>\n <div className={cn(\n \"absolute inset-0 bg-gradient-to-br from-foreground/[0.04] dark:from-foreground/[0.02] to-transparent pointer-events-none rounded-2xl\",\n variant === \"bodyOnly\" && \"dark:hidden\"\n )} />\n {variant !== \"bodyOnly\" && (\n <div\n className={cn(\n \"absolute inset-0 transition-colors duration-150 group-hover:transition-none pointer-events-none rounded-2xl\",\n hoverTintClass\n )}\n />\n )}\n </>\n )}\n <div className=\"relative\">\n {variant === \"header\" && (\n <div className={bodyPaddingClass}>\n <div className=\"flex items-start justify-between gap-4\">\n <div className=\"flex-1 min-w-0\">\n <div className=\"flex items-center gap-2\">\n {Icon && (\n <div className=\"p-1.5 rounded-lg bg-foreground/[0.06] dark:bg-foreground/[0.04]\">\n <Icon className=\"h-3.5 w-3.5 text-foreground/70 dark:text-muted-foreground\" />\n </div>\n )}\n <span className=\"text-xs font-semibold text-foreground uppercase tracking-wider\">\n {title}\n </span>\n </div>\n {subtitle && (\n <p className=\"text-sm text-muted-foreground mt-1\">\n {subtitle}\n </p>\n )}\n </div>\n {actions && (\n <div className=\"flex-shrink-0\">\n {actions}\n </div>\n )}\n </div>\n </div>\n )}\n {variant === \"compact\" && (\n <div className=\"p-5 flex items-center justify-between gap-4 border-b border-black/[0.12] dark:border-white/[0.06]\">\n <div className=\"flex items-center gap-2 min-w-0\">\n {Icon && (\n <div className=\"p-1.5 rounded-lg bg-foreground/[0.04]\">\n <Icon className=\"h-3.5 w-3.5 text-muted-foreground\" />\n </div>\n )}\n <span className=\"text-xs font-semibold text-foreground uppercase tracking-wider\">\n {title}\n </span>\n </div>\n {actions && (\n <div className=\"flex-shrink-0\">\n {actions}\n </div>\n )}\n </div>\n )}\n {hasContent && (\n <div\n className={cn(\n variant === \"header\" ? \"border-t border-black/[0.12] dark:border-white/[0.06]\" : \"\",\n variant === \"compact\" ? \"px-5 py-4\" : \"\",\n variant === \"bodyOnly\" || variant === \"header\" ? bodyPaddingClass : \"\",\n contentClassName\n )}\n >\n {children}\n </div>\n )}\n </div>\n </Card>\n </DesignCardNestingContext.Provider>\n );\n}\n\nexport type DesignCardTintProps = {\n gradient: DesignCardGradient,\n} & React.ComponentProps<\"div\">\n\nexport function DesignCardTint({\n gradient,\n className,\n children,\n ...props\n}: DesignCardTintProps) {\n const tintClass = demoTintClasses.get(gradient) ?? \"group-hover/tint:bg-slate-500/[0.015]\";\n\n return (\n <div\n className={cn(\n \"group/tint relative rounded-2xl bg-white/90 dark:bg-background/60 dark:backdrop-blur-xl transition-all duration-150 hover:transition-none\",\n \"ring-1 ring-black/[0.06] hover:ring-black/[0.1] dark:ring-white/[0.06] dark:hover:ring-white/[0.1]\",\n \"shadow-none overflow-hidden\",\n className\n )}\n {...props}\n >\n <div className=\"absolute inset-0 bg-gradient-to-br from-foreground/[0.04] dark:from-foreground/[0.02] to-transparent pointer-events-none rounded-2xl\" />\n <div\n className={cn(\n \"absolute inset-0 transition-colors duration-150 group-hover/tint:transition-none pointer-events-none rounded-2xl\",\n tintClass\n )}\n />\n <div className=\"relative\">\n {children}\n </div>\n </div>\n );\n}\n", "\"use client\";\n\nimport { useEffect, useRef, useState } from \"react\";\nimport { createPortal } from \"react-dom\";\n\ntype Blast = {\n id: number,\n x: number,\n y: number,\n size: number,\n hue: number,\n};\n\nconst DEFAULT_BLAST_LIFETIME_MS = 720;\nconst DEFAULT_MAX_ACTIVE_BLASTS = 18;\n\n/** Minimum rapid clicks in the time window to count as a rage click */\nconst DEFAULT_RAGE_CLICK_THRESHOLD = 3;\n/** Time window (ms) in which clicks must occur to be considered rage clicking */\nconst DEFAULT_RAGE_CLICK_WINDOW_MS = 600;\n/** Max distance (px) between clicks to still count as same-spot rage clicking */\nconst DEFAULT_RAGE_CLICK_RADIUS_PX = 60;\n\ntype RecentClick = {\n time: number,\n x: number,\n y: number,\n};\n\nexport type CursorBlastEffectProps = {\n /** Lifetime of each blast animation in ms. Default: 720 */\n blastLifetimeMs?: number,\n /** Maximum number of concurrent active blasts. Default: 18 */\n maxActiveBlasts?: number,\n /** Minimum rapid clicks in the time window to trigger a blast. Default: 3 */\n rageClickThreshold?: number,\n /** Time window (ms) for counting rage clicks. Default: 600 */\n rageClickWindowMs?: number,\n /** Max distance (px) between clicks to count as same-spot rage clicking. Default: 60 */\n rageClickRadiusPx?: number,\n /**\n * When provided, the blast effect is scoped to this container element.\n * Clicks are only detected within the container and blasts are positioned\n * relative to the container rather than the viewport.\n */\n containerRef?: React.RefObject<HTMLElement | null>,\n};\n\nexport function CursorBlastEffect({\n blastLifetimeMs = DEFAULT_BLAST_LIFETIME_MS,\n maxActiveBlasts = DEFAULT_MAX_ACTIVE_BLASTS,\n rageClickThreshold = DEFAULT_RAGE_CLICK_THRESHOLD,\n rageClickWindowMs = DEFAULT_RAGE_CLICK_WINDOW_MS,\n rageClickRadiusPx = DEFAULT_RAGE_CLICK_RADIUS_PX,\n containerRef,\n}: CursorBlastEffectProps = {}) {\n const [blasts, setBlasts] = useState<Blast[]>([]);\n const [mounted, setMounted] = useState(false);\n const idCounterRef = useRef(0);\n const timeoutIdsRef = useRef<Map<number, number>>(new Map());\n const recentClicksRef = useRef<RecentClick[]>([]);\n\n // Store latest config in refs so the effect callback always reads current values\n const configRef = useRef({\n blastLifetimeMs,\n maxActiveBlasts,\n rageClickThreshold,\n rageClickWindowMs,\n rageClickRadiusPx,\n });\n configRef.current = {\n blastLifetimeMs,\n maxActiveBlasts,\n rageClickThreshold,\n rageClickWindowMs,\n rageClickRadiusPx,\n };\n\n useEffect(() => {\n setMounted(true);\n }, []);\n\n useEffect(() => {\n const removeBlast = (id: number) => {\n setBlasts((prev) => prev.filter((blast) => blast.id !== id));\n const timeoutId = timeoutIdsRef.current.get(id);\n if (timeoutId !== undefined) {\n window.clearTimeout(timeoutId);\n timeoutIdsRef.current.delete(id);\n }\n };\n\n const spawnBlast = (x: number, y: number) => {\n const cfg = configRef.current;\n const nextId = idCounterRef.current;\n idCounterRef.current += 1;\n\n const nextBlast: Blast = {\n id: nextId,\n x,\n y,\n size: 44 + Math.random() * 20,\n hue: 185 + Math.random() * 35,\n };\n\n setBlasts((prev) => {\n const next = [...prev, nextBlast];\n if (next.length <= cfg.maxActiveBlasts) {\n return next;\n }\n return next.slice(next.length - cfg.maxActiveBlasts);\n });\n\n const timeoutId = window.setTimeout(() => removeBlast(nextId), cfg.blastLifetimeMs);\n timeoutIdsRef.current.set(nextId, timeoutId);\n };\n\n const onClick = (event: MouseEvent) => {\n const cfg = configRef.current;\n const now = performance.now();\n\n let x: number;\n let y: number;\n\n if (containerRef?.current) {\n const rect = containerRef.current.getBoundingClientRect();\n x = event.clientX - rect.left;\n y = event.clientY - rect.top;\n } else {\n x = event.clientX;\n y = event.clientY;\n }\n\n // Prune clicks outside the time window\n recentClicksRef.current = recentClicksRef.current.filter(\n (click) => now - click.time < cfg.rageClickWindowMs,\n );\n\n recentClicksRef.current.push({ time: now, x, y });\n\n // Count how many recent clicks are within the radius of the current click\n const nearbyCount = recentClicksRef.current.filter((click) => {\n const dx = click.x - x;\n const dy = click.y - y;\n return Math.sqrt(dx * dx + dy * dy) <= cfg.rageClickRadiusPx;\n }).length;\n\n if (nearbyCount >= cfg.rageClickThreshold) {\n spawnBlast(x, y);\n }\n };\n\n const target = containerRef?.current ?? window;\n const timeoutIds = timeoutIdsRef.current;\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- EventTarget union requires cast\n (target as EventTarget).addEventListener(\"click\", onClick as EventListener);\n return () => {\n (target as EventTarget).removeEventListener(\"click\", onClick as EventListener);\n for (const timeoutId of timeoutIds.values()) {\n window.clearTimeout(timeoutId);\n }\n timeoutIds.clear();\n };\n }, [containerRef]);\n\n if (!mounted) {\n return null;\n }\n\n const blastElements = (\n <>\n {blasts.map((blast) => (\n <div\n key={blast.id}\n style={{\n position: \"absolute\",\n left: blast.x,\n top: blast.y,\n width: blast.size,\n height: blast.size,\n transform: \"translate(-50%, -50%)\",\n willChange: \"transform, opacity\",\n filter: `hue-rotate(${blast.hue}deg)`,\n }}\n >\n <span className=\"cursor-blast-ring\" />\n <span className=\"cursor-blast-core\" />\n {Array.from({ length: 10 }).map((_, index) => {\n const angle = (360 / 10) * index;\n return (\n <span\n key={`${blast.id}-${index}`}\n className=\"cursor-blast-shard-wrap\"\n style={{\n transform: `translate(-50%, -50%) rotate(${angle}deg)`,\n animationDelay: `${index * 16}ms`,\n }}\n >\n <span className=\"cursor-blast-shard\" />\n </span>\n );\n })}\n </div>\n ))}\n <style dangerouslySetInnerHTML={{ __html: `\n .cursor-blast-ring {\n position: absolute;\n inset: 0;\n border-radius: 999px;\n border: 2px solid hsl(197 98% 67% / 0.9);\n box-shadow:\n 0 0 22px hsl(191 100% 72% / 0.6),\n inset 0 0 12px hsl(204 100% 77% / 0.65);\n animation: blast-ring 560ms cubic-bezier(0.16, 1, 0.3, 1) forwards;\n }\n\n .cursor-blast-core {\n position: absolute;\n left: 50%;\n top: 50%;\n width: 10px;\n height: 10px;\n border-radius: 999px;\n transform: translate(-50%, -50%);\n background: hsl(196 100% 85%);\n box-shadow:\n 0 0 26px hsl(193 100% 72% / 0.9),\n 0 0 10px hsl(201 100% 85% / 0.9);\n animation: blast-core 420ms ease-out forwards;\n }\n\n .cursor-blast-shard-wrap {\n position: absolute;\n left: 50%;\n top: 50%;\n width: 0;\n height: 0;\n }\n\n .cursor-blast-shard {\n position: absolute;\n left: 0;\n top: -1.5px;\n width: 12px;\n height: 3px;\n border-radius: 999px;\n background: linear-gradient(90deg, hsl(190 100% 84%), hsl(197 98% 67%));\n box-shadow: 0 0 12px hsl(195 100% 70% / 0.8);\n animation: blast-shard 680ms cubic-bezier(0.22, 1, 0.36, 1) forwards;\n }\n\n @keyframes blast-ring {\n 0% {\n transform: scale(0.2);\n opacity: 0.95;\n }\n 100% {\n transform: scale(1.6);\n opacity: 0;\n }\n }\n\n @keyframes blast-core {\n 0% {\n transform: translate(-50%, -50%) scale(0.5);\n opacity: 1;\n }\n 100% {\n transform: translate(-50%, -50%) scale(2.2);\n opacity: 0;\n }\n }\n\n @keyframes blast-shard {\n 0% {\n transform: translateX(0) scaleX(0.7);\n opacity: 1;\n }\n 100% {\n transform: translateX(46px) scaleX(1.1);\n opacity: 0;\n }\n }\n\n @media (prefers-reduced-motion: reduce) {\n .cursor-blast-ring,\n .cursor-blast-core,\n .cursor-blast-shard {\n animation-duration: 1ms;\n }\n }\n ` }} />\n </>\n );\n\n // When scoped to a container, render inline (the container must have position: relative)\n if (containerRef) {\n return (\n <div\n aria-hidden\n style={{\n position: \"absolute\",\n inset: 0,\n zIndex: 2147483647,\n pointerEvents: \"none\",\n overflow: \"hidden\",\n borderRadius: \"inherit\",\n }}\n >\n {blastElements}\n </div>\n );\n }\n\n // Default: portal to body with fixed positioning (original behaviour)\n return createPortal(\n <div\n aria-hidden\n style={{\n position: \"fixed\",\n inset: 0,\n zIndex: 2147483647,\n pointerEvents: \"none\",\n }}\n >\n {blastElements}\n </div>,\n document.body,\n );\n}\n", "\"use client\";\n\nimport { createContext, useContext } from \"react\";\n\nconst DesignEditModeContext = createContext(false);\n\nexport function DesignEditMode({ children }: { children: React.ReactNode }) {\n return (\n <DesignEditModeContext.Provider value={true}>\n {children}\n </DesignEditModeContext.Provider>\n );\n}\n\nexport function useDesignEditMode(): boolean {\n return useContext(DesignEditModeContext);\n}\n", "\"use client\";\n\nimport { forwardRefIfNeeded } from \"@stackframe/stack-shared/dist/utils/react\";\nimport React from \"react\";\n\nimport { cn } from \"@stackframe/stack-ui\";\n\nexport type DesignInputProps = {\n prefixItem?: React.ReactNode,\n leadingIcon?: React.ReactNode,\n size?: \"sm\" | \"md\" | \"lg\",\n} & Omit<React.InputHTMLAttributes<HTMLInputElement>, \"size\">;\n\nexport const DesignInput = forwardRefIfNeeded<HTMLInputElement, DesignInputProps>(\n ({ className, type, prefixItem, leadingIcon, size = \"md\", ...props }, ref) => {\n const sizeClasses = size === \"sm\"\n ? \"h-7 px-2 text-xs\"\n : size === \"lg\"\n ? \"h-10 px-4 text-sm\"\n : \"h-9 px-3 text-sm\";\n const baseClasses = cn(\n \"stack-scope flex w-full rounded-xl border border-black/[0.08] dark:border-white/[0.06] bg-white/80 dark:bg-foreground/[0.03] shadow-sm ring-1 ring-black/[0.08] dark:ring-white/[0.06]\",\n \"file:border-0 file:bg-transparent file:text-sm file:font-medium\",\n \"placeholder:text-muted-foreground/50 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-foreground/[0.1]\",\n \"disabled:cursor-not-allowed disabled:opacity-50\",\n \"transition-all duration-150 hover:transition-none hover:bg-white dark:hover:bg-foreground/[0.06]\",\n sizeClasses\n );\n\n if (prefixItem) {\n return (\n <div className=\"flex flex-row items-center flex-1 rounded-xl border border-black/[0.08] dark:border-white/[0.06] bg-white/80 dark:bg-foreground/[0.03] shadow-sm ring-1 ring-black/[0.08] dark:ring-white/[0.06] overflow-hidden transition-all duration-150 hover:transition-none hover:bg-white dark:hover:bg-foreground/[0.06] focus-within:ring-1 focus-within:ring-foreground/[0.1]\">\n <div className={cn(\n \"flex self-stretch items-center justify-center select-none text-muted-foreground/70 border-r border-black/[0.06] dark:border-white/[0.06] bg-black/[0.03] dark:bg-white/[0.02]\",\n size === \"sm\" ? \"px-2.5 text-xs\" : size === \"lg\" ? \"px-3.5 text-sm\" : \"px-3 text-sm\"\n )}>\n {prefixItem}\n </div>\n <input\n type={type}\n className={cn(\n \"stack-scope flex w-full bg-transparent\",\n \"file:border-0 file:bg-transparent file:text-sm file:font-medium\",\n \"placeholder:text-muted-foreground/50 focus-visible:outline-none\",\n \"disabled:cursor-not-allowed disabled:opacity-50\",\n sizeClasses,\n \"rounded-none border-0 shadow-none ring-0 focus-visible:ring-0\",\n className\n )}\n ref={ref}\n {...props}\n />\n </div>\n );\n }\n\n if (leadingIcon) {\n return (\n <div className=\"relative flex flex-row items-center flex-1\">\n <div className=\"pointer-events-none absolute left-2.5 flex items-center text-muted-foreground\">\n {leadingIcon}\n </div>\n <input\n type={type}\n className={cn(baseClasses, \"pl-8\", className)}\n ref={ref}\n {...props}\n />\n </div>\n );\n }\n\n return (\n <div className=\"flex flex-row items-center flex-1\">\n <input\n type={type}\n className={cn(baseClasses, className)}\n ref={ref}\n {...props}\n />\n </div>\n );\n }\n);\nDesignInput.displayName = \"DesignInput\";\n", "\"use client\";\n\nimport { useState } from \"react\";\nimport { cn, Spinner, Tooltip, TooltipContent, TooltipTrigger } from \"@stackframe/stack-ui\";\nimport { TooltipPortal } from \"@radix-ui/react-tooltip\";\nimport { runAsynchronouslyWithAlert } from \"@stackframe/stack-shared/dist/utils/promises\";\nimport { useGlassmorphicDefault } from \"./card\";\n\ntype DesignPillToggleSize = \"sm\" | \"md\" | \"lg\";\ntype DesignPillToggleGradient = \"blue\" | \"cyan\" | \"purple\" | \"green\" | \"orange\" | \"default\";\n\nexport type DesignPillToggleOption = {\n id: string,\n label: string,\n icon?: React.ElementType,\n};\n\nexport type DesignPillToggleProps = {\n options: DesignPillToggleOption[],\n selected: string,\n onSelect: (id: string) => void | Promise<void>,\n size?: DesignPillToggleSize,\n glassmorphic?: boolean,\n gradient?: DesignPillToggleGradient,\n /** When false, hides labels and shows a tooltip on hover instead. Defaults to true. */\n showLabels?: boolean,\n className?: string,\n};\n\ntype SizeClass = {\n button: string,\n icon: string,\n};\n\nconst sizeClasses = new Map<DesignPillToggleSize, SizeClass>([\n [\"sm\", { button: \"px-3 py-1.5 text-xs\", icon: \"h-3.5 w-3.5\" }],\n [\"md\", { button: \"px-4 py-2 text-sm\", icon: \"h-4 w-4\" }],\n [\"lg\", { button: \"px-5 py-2.5 text-sm\", icon: \"h-4 w-4\" }],\n]);\n\nconst gradientClasses = new Map<DesignPillToggleGradient, string>([\n [\"blue\", \"ring-blue-500/20 dark:ring-blue-400/20\"],\n [\"cyan\", \"ring-cyan-500/20 dark:ring-cyan-400/20\"],\n [\"purple\", \"ring-purple-500/20 dark:ring-purple-400/20\"],\n [\"green\", \"ring-emerald-500/20 dark:ring-emerald-400/20\"],\n [\"orange\", \"ring-amber-500/20 dark:ring-amber-400/20\"],\n [\"default\", \"ring-black/[0.12] dark:ring-white/[0.06]\"],\n]);\n\nfunction getMapValueOrThrow<TKey, TValue>(map: Map<TKey, TValue>, key: TKey, mapName: string) {\n const value = map.get(key);\n if (!value) {\n throw new Error(`Missing ${mapName} entry for key \"${String(key)}\"`);\n }\n return value;\n}\n\nexport function DesignPillToggle({\n options,\n selected,\n onSelect,\n size = \"md\",\n glassmorphic: glassmorphicProp,\n gradient = \"default\",\n showLabels = true,\n className,\n}: DesignPillToggleProps) {\n const glassmorphic = useGlassmorphicDefault(glassmorphicProp);\n const sizeClass = getMapValueOrThrow(sizeClasses, size, \"sizeClasses\");\n const activeRingClass = getMapValueOrThrow(gradientClasses, gradient, \"gradientClasses\");\n\n const [loadingOptionId, setLoadingOptionId] = useState<string | null>(null);\n\n const handleClick = (optionId: string) => {\n const result = onSelect(optionId);\n if (result && typeof (result as Promise<void>).then === \"function\") {\n setLoadingOptionId(optionId);\n runAsynchronouslyWithAlert(\n Promise.resolve(result).finally(() => setLoadingOptionId(null))\n );\n }\n };\n\n return (\n <div\n className={cn(\n \"inline-flex items-center gap-1 p-1 rounded-xl\",\n glassmorphic\n ? \"bg-foreground/[0.04] backdrop-blur-sm\"\n : \"bg-black/[0.08] dark:bg-white/[0.04]\",\n className\n )}\n >\n {options.map((option) => {\n const isActive = selected === option.id;\n const Icon = option.icon;\n\n const pill = (\n <button\n key={option.id}\n onClick={() => handleClick(option.id)}\n disabled={loadingOptionId !== null}\n className={cn(\n \"relative flex items-center gap-2 font-medium rounded-lg transition-all duration-150 hover:transition-none\",\n sizeClass.button,\n isActive\n ? cn(\n \"bg-background text-foreground shadow-sm ring-1\",\n glassmorphic\n ? \"ring-foreground/[0.06] dark:bg-[hsl(240,71%,70%)]/10 dark:text-[hsl(240,71%,90%)] dark:ring-[hsl(240,71%,70%)]/20\"\n : activeRingClass\n )\n : cn(\n \"text-muted-foreground hover:text-foreground\",\n glassmorphic\n ? \"hover:bg-background/50\"\n : \"hover:bg-black/[0.06] dark:hover:bg-white/[0.04]\"\n )\n )}\n >\n {loadingOptionId === option.id && (\n <Spinner\n size={12}\n className=\"absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 pointer-events-none\"\n />\n )}\n <span className={cn(\n \"flex items-center gap-2\",\n loadingOptionId === option.id && \"invisible\"\n )}>\n {Icon && <Icon className={sizeClass.icon} />}\n {showLabels && option.label}\n </span>\n </button>\n );\n\n if (!showLabels) {\n return (\n <Tooltip key={option.id} delayDuration={0}>\n <TooltipTrigger asChild>\n {pill}\n </TooltipTrigger>\n <TooltipPortal>\n <TooltipContent side=\"top\">\n {option.label}\n </TooltipContent>\n </TooltipPortal>\n </Tooltip>\n );\n }\n\n return pill;\n })}\n </div>\n );\n}\n", "import * as React from 'react';\nimport { composeEventHandlers } from '@radix-ui/primitive';\nimport { useComposedRefs } from '@radix-ui/react-compose-refs';\nimport { createContextScope } from '@radix-ui/react-context';\nimport { DismissableLayer } from '@radix-ui/react-dismissable-layer';\nimport { useId } from '@radix-ui/react-id';\nimport * as PopperPrimitive from '@radix-ui/react-popper';\nimport { createPopperScope } from '@radix-ui/react-popper';\nimport { Portal as PortalPrimitive } from '@radix-ui/react-portal';\nimport { Presence } from '@radix-ui/react-presence';\nimport { Primitive } from '@radix-ui/react-primitive';\nimport { createSlottable } from '@radix-ui/react-slot';\nimport { useControllableState } from '@radix-ui/react-use-controllable-state';\nimport * as VisuallyHiddenPrimitive from '@radix-ui/react-visually-hidden';\n\nimport type { Scope } from '@radix-ui/react-context';\n\ntype ScopedProps<P = {}> = P & { __scopeTooltip?: Scope };\nconst [createTooltipContext, createTooltipScope] = createContextScope('Tooltip', [\n createPopperScope,\n]);\nconst usePopperScope = createPopperScope();\n\n/* -------------------------------------------------------------------------------------------------\n * TooltipProvider\n * -----------------------------------------------------------------------------------------------*/\n\nconst PROVIDER_NAME = 'TooltipProvider';\nconst DEFAULT_DELAY_DURATION = 700;\nconst TOOLTIP_OPEN = 'tooltip.open';\n\ntype TooltipProviderContextValue = {\n isOpenDelayedRef: React.MutableRefObject<boolean>;\n delayDuration: number;\n onOpen(): void;\n onClose(): void;\n onPointerInTransitChange(inTransit: boolean): void;\n isPointerInTransitRef: React.MutableRefObject<boolean>;\n disableHoverableContent: boolean;\n};\n\nconst [TooltipProviderContextProvider, useTooltipProviderContext] =\n createTooltipContext<TooltipProviderContextValue>(PROVIDER_NAME);\n\ninterface TooltipProviderProps {\n children: React.ReactNode;\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\nconst TooltipProvider: React.FC<TooltipProviderProps> = (\n props: ScopedProps<TooltipProviderProps>\n) => {\n const {\n __scopeTooltip,\n delayDuration = DEFAULT_DELAY_DURATION,\n skipDelayDuration = 300,\n disableHoverableContent = false,\n children,\n } = props;\n const isOpenDelayedRef = React.useRef(true);\n const isPointerInTransitRef = React.useRef(false);\n const skipDelayTimerRef = React.useRef(0);\n\n React.useEffect(() => {\n const skipDelayTimer = skipDelayTimerRef.current;\n return () => window.clearTimeout(skipDelayTimer);\n }, []);\n\n return (\n <TooltipProviderContextProvider\n scope={__scopeTooltip}\n isOpenDelayedRef={isOpenDelayedRef}\n delayDuration={delayDuration}\n onOpen={React.useCallback(() => {\n window.clearTimeout(skipDelayTimerRef.current);\n isOpenDelayedRef.current = false;\n }, [])}\n onClose={React.useCallback(() => {\n window.clearTimeout(skipDelayTimerRef.current);\n skipDelayTimerRef.current = window.setTimeout(\n () => (isOpenDelayedRef.current = true),\n skipDelayDuration\n );\n }, [skipDelayDuration])}\n isPointerInTransitRef={isPointerInTransitRef}\n onPointerInTransitChange={React.useCallback((inTransit: boolean) => {\n isPointerInTransitRef.current = inTransit;\n }, [])}\n disableHoverableContent={disableHoverableContent}\n >\n {children}\n </TooltipProviderContextProvider>\n );\n};\n\nTooltipProvider.displayName = PROVIDER_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * Tooltip\n * -----------------------------------------------------------------------------------------------*/\n\nconst TOOLTIP_NAME = 'Tooltip';\n\ntype TooltipContextValue = {\n contentId: string;\n open: boolean;\n stateAttribute: 'closed' | 'delayed-open' | 'instant-open';\n trigger: TooltipTriggerElement | null;\n onTriggerChange(trigger: TooltipTriggerElement | null): void;\n onTriggerEnter(): void;\n onTriggerLeave(): void;\n onOpen(): void;\n onClose(): void;\n disableHoverableContent: boolean;\n};\n\nconst [TooltipContextProvider, useTooltipContext] =\n createTooltipContext<TooltipContextValue>(TOOLTIP_NAME);\n\ninterface TooltipProps {\n children?: React.ReactNode;\n open?: boolean;\n defaultOpen?: boolean;\n onOpenChange?: (open: boolean) => void;\n /**\n * The duration from when the pointer enters the trigger until the tooltip gets opened. This will\n * override the prop with the same name passed to Provider.\n * @defaultValue 700\n */\n delayDuration?: 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\nconst Tooltip: React.FC<TooltipProps> = (props: ScopedProps<TooltipProps>) => {\n const {\n __scopeTooltip,\n children,\n open: openProp,\n defaultOpen,\n onOpenChange,\n disableHoverableContent: disableHoverableContentProp,\n delayDuration: delayDurationProp,\n } = props;\n const providerContext = useTooltipProviderContext(TOOLTIP_NAME, props.__scopeTooltip);\n const popperScope = usePopperScope(__scopeTooltip);\n const [trigger, setTrigger] = React.useState<HTMLButtonElement | null>(null);\n const contentId = useId();\n const openTimerRef = React.useRef(0);\n const disableHoverableContent =\n disableHoverableContentProp ?? providerContext.disableHoverableContent;\n const delayDuration = delayDurationProp ?? providerContext.delayDuration;\n const wasOpenDelayedRef = React.useRef(false);\n const [open, setOpen] = useControllableState({\n prop: openProp,\n defaultProp: defaultOpen ?? false,\n onChange: (open) => {\n if (open) {\n providerContext.onOpen();\n\n // as `onChange` is called within a lifecycle method we\n // avoid dispatching via `dispatchDiscreteCustomEvent`.\n document.dispatchEvent(new CustomEvent(TOOLTIP_OPEN));\n } else {\n providerContext.onClose();\n }\n onOpenChange?.(open);\n },\n caller: TOOLTIP_NAME,\n });\n const stateAttribute = React.useMemo(() => {\n return open ? (wasOpenDelayedRef.current ? 'delayed-open' : 'instant-open') : 'closed';\n }, [open]);\n\n const handleOpen = React.useCallback(() => {\n window.clearTimeout(openTimerRef.current);\n openTimerRef.current = 0;\n wasOpenDelayedRef.current = false;\n setOpen(true);\n }, [setOpen]);\n\n const handleClose = React.useCallback(() => {\n window.clearTimeout(openTimerRef.current);\n openTimerRef.current = 0;\n setOpen(false);\n }, [setOpen]);\n\n const handleDelayedOpen = React.useCallback(() => {\n window.clearTimeout(openTimerRef.current);\n openTimerRef.current = window.setTimeout(() => {\n wasOpenDelayedRef.current = true;\n setOpen(true);\n openTimerRef.current = 0;\n }, delayDuration);\n }, [delayDuration, setOpen]);\n\n React.useEffect(() => {\n return () => {\n if (openTimerRef.current) {\n window.clearTimeout(openTimerRef.current);\n openTimerRef.current = 0;\n }\n };\n }, []);\n\n return (\n <PopperPrimitive.Root {...popperScope}>\n <TooltipContextProvider\n scope={__scopeTooltip}\n contentId={contentId}\n open={open}\n stateAttribute={stateAttribute}\n trigger={trigger}\n onTriggerChange={setTrigger}\n onTriggerEnter={React.useCallback(() => {\n if (providerContext.isOpenDelayedRef.current) handleDelayedOpen();\n else handleOpen();\n }, [providerContext.isOpenDelayedRef, handleDelayedOpen, handleOpen])}\n onTriggerLeave={React.useCallback(() => {\n if (disableHoverableContent) {\n handleClose();\n } else {\n // Clear the timer in case the pointer leaves the trigger before the tooltip is opened.\n window.clearTimeout(openTimerRef.current);\n openTimerRef.current = 0;\n }\n }, [handleClose, disableHoverableContent])}\n onOpen={handleOpen}\n onClose={handleClose}\n disableHoverableContent={disableHoverableContent}\n >\n {children}\n </TooltipContextProvider>\n </PopperPrimitive.Root>\n );\n};\n\nTooltip.displayName = TOOLTIP_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * TooltipTrigger\n * -----------------------------------------------------------------------------------------------*/\n\nconst TRIGGER_NAME = 'TooltipTrigger';\n\ntype TooltipTriggerElement = React.ComponentRef<typeof Primitive.button>;\ntype PrimitiveButtonProps = React.ComponentPropsWithoutRef<typeof Primitive.button>;\ninterface TooltipTriggerProps extends PrimitiveButtonProps {}\n\nconst TooltipTrigger = React.forwardRef<TooltipTriggerElement, TooltipTriggerProps>(\n (props: ScopedProps<TooltipTriggerProps>, forwardedRef) => {\n const { __scopeTooltip, ...triggerProps } = props;\n const context = useTooltipContext(TRIGGER_NAME, __scopeTooltip);\n const providerContext = useTooltipProviderContext(TRIGGER_NAME, __scopeTooltip);\n const popperScope = usePopperScope(__scopeTooltip);\n const ref = React.useRef<TooltipTriggerElement>(null);\n const composedRefs = useComposedRefs(forwardedRef, ref, context.onTriggerChange);\n const isPointerDownRef = React.useRef(false);\n const hasPointerMoveOpenedRef = React.useRef(false);\n const handlePointerUp = React.useCallback(() => (isPointerDownRef.current = false), []);\n\n React.useEffect(() => {\n return () => document.removeEventListener('pointerup', handlePointerUp);\n }, [handlePointerUp]);\n\n return (\n <PopperPrimitive.Anchor asChild {...popperScope}>\n <Primitive.button\n // We purposefully avoid adding `type=button` here because tooltip triggers are also\n // commonly anchors and the anchor `type` attribute signifies MIME type.\n aria-describedby={context.open ? context.contentId : undefined}\n data-state={context.stateAttribute}\n {...triggerProps}\n ref={composedRefs}\n onPointerMove={composeEventHandlers(props.onPointerMove, (event) => {\n if (event.pointerType === 'touch') return;\n if (\n !hasPointerMoveOpenedRef.current &&\n !providerContext.isPointerInTransitRef.current\n ) {\n context.onTriggerEnter();\n hasPointerMoveOpenedRef.current = true;\n }\n })}\n onPointerLeave={composeEventHandlers(props.onPointerLeave, () => {\n context.onTriggerLeave();\n hasPointerMoveOpenedRef.current = false;\n })}\n onPointerDown={composeEventHandlers(props.onPointerDown, () => {\n if (context.open) {\n context.onClose();\n }\n isPointerDownRef.current = true;\n document.addEventListener('pointerup', handlePointerUp, { once: true });\n })}\n onFocus={composeEventHandlers(props.onFocus, () => {\n if (!isPointerDownRef.current) context.onOpen();\n })}\n onBlur={composeEventHandlers(props.onBlur, context.onClose)}\n onClick={composeEventHandlers(props.onClick, context.onClose)}\n />\n </PopperPrimitive.Anchor>\n );\n }\n);\n\nTooltipTrigger.displayName = TRIGGER_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * TooltipPortal\n * -----------------------------------------------------------------------------------------------*/\n\nconst PORTAL_NAME = 'TooltipPortal';\n\ntype PortalContextValue = { forceMount?: true };\nconst [PortalProvider, usePortalContext] = createTooltipContext<PortalContextValue>(PORTAL_NAME, {\n forceMount: undefined,\n});\n\ntype PortalProps = React.ComponentPropsWithoutRef<typeof PortalPrimitive>;\ninterface TooltipPortalProps {\n children?: React.ReactNode;\n /**\n * Specify a container element to portal the content into.\n */\n container?: PortalProps['container'];\n /**\n * Used to force mounting when more control is needed. Useful when\n * controlling animation with React animation libraries.\n */\n forceMount?: true;\n}\n\nconst TooltipPortal: React.FC<TooltipPortalProps> = (props: ScopedProps<TooltipPortalProps>) => {\n const { __scopeTooltip, forceMount, children, container } = props;\n const context = useTooltipContext(PORTAL_NAME, __scopeTooltip);\n return (\n <PortalProvider scope={__scopeTooltip} forceMount={forceMount}>\n <Presence present={forceMount || context.open}>\n <PortalPrimitive asChild container={container}>\n {children}\n </PortalPrimitive>\n </Presence>\n </PortalProvider>\n );\n};\n\nTooltipPortal.displayName = PORTAL_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * TooltipContent\n * -----------------------------------------------------------------------------------------------*/\n\nconst CONTENT_NAME = 'TooltipContent';\n\ntype TooltipContentElement = TooltipContentImplElement;\ninterface TooltipContentProps extends TooltipContentImplProps {\n /**\n * Used to force mounting when more control is needed. Useful when\n * controlling animation with React animation libraries.\n */\n forceMount?: true;\n}\n\nconst TooltipContent = React.forwardRef<TooltipContentElement, TooltipContentProps>(\n (props: ScopedProps<TooltipContentProps>, forwardedRef) => {\n const portalContext = usePortalContext(CONTENT_NAME, props.__scopeTooltip);\n const { forceMount = portalContext.forceMount, side = 'top', ...contentProps } = props;\n const context = useTooltipContext(CONTENT_NAME, props.__scopeTooltip);\n\n return (\n <Presence present={forceMount || context.open}>\n {context.disableHoverableContent ? (\n <TooltipContentImpl side={side} {...contentProps} ref={forwardedRef} />\n ) : (\n <TooltipContentHoverable side={side} {...contentProps} ref={forwardedRef} />\n )}\n </Presence>\n );\n }\n);\n\ntype Point = { x: number; y: number };\ntype Polygon = Point[];\n\ntype TooltipContentHoverableElement = TooltipContentImplElement;\ninterface TooltipContentHoverableProps extends TooltipContentImplProps {}\n\nconst TooltipContentHoverable = React.forwardRef<\n TooltipContentHoverableElement,\n TooltipContentHoverableProps\n>((props: ScopedProps<TooltipContentHoverableProps>, forwardedRef) => {\n const context = useTooltipContext(CONTENT_NAME, props.__scopeTooltip);\n const providerContext = useTooltipProviderContext(CONTENT_NAME, props.__scopeTooltip);\n const ref = React.useRef<TooltipContentHoverableElement>(null);\n const composedRefs = useComposedRefs(forwardedRef, ref);\n const [pointerGraceArea, setPointerGraceArea] = React.useState<Polygon | null>(null);\n\n const { trigger, onClose } = context;\n const content = ref.current;\n\n const { onPointerInTransitChange } = providerContext;\n\n const handleRemoveGraceArea = React.useCallback(() => {\n setPointerGraceArea(null);\n onPointerInTransitChange(false);\n }, [onPointerInTransitChange]);\n\n const handleCreateGraceArea = React.useCallback(\n (event: PointerEvent, hoverTarget: HTMLElement) => {\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);\n const hoverTargetPoints = getPointsFromRect(hoverTarget.getBoundingClientRect());\n const graceArea = getHull([...paddedExitPoints, ...hoverTargetPoints]);\n setPointerGraceArea(graceArea);\n onPointerInTransitChange(true);\n },\n [onPointerInTransitChange]\n );\n\n React.useEffect(() => {\n return () => handleRemoveGraceArea();\n }, [handleRemoveGraceArea]);\n\n React.useEffect(() => {\n if (trigger && content) {\n const handleTriggerLeave = (event: PointerEvent) => handleCreateGraceArea(event, content);\n const handleContentLeave = (event: PointerEvent) => handleCreateGraceArea(event, trigger);\n\n trigger.addEventListener('pointerleave', handleTriggerLeave);\n content.addEventListener('pointerleave', handleContentLeave);\n return () => {\n trigger.removeEventListener('pointerleave', handleTriggerLeave);\n content.removeEventListener('pointerleave', handleContentLeave);\n };\n }\n }, [trigger, content, handleCreateGraceArea, handleRemoveGraceArea]);\n\n React.useEffect(() => {\n if (pointerGraceArea) {\n const handleTrackPointerGrace = (event: PointerEvent) => {\n const target = event.target as HTMLElement;\n const pointerPosition = { x: event.clientX, y: event.clientY };\n const hasEnteredTarget = trigger?.contains(target) || content?.contains(target);\n const isPointerOutsideGraceArea = !isPointInPolygon(pointerPosition, pointerGraceArea);\n\n if (hasEnteredTarget) {\n handleRemoveGraceArea();\n } else if (isPointerOutsideGraceArea) {\n handleRemoveGraceArea();\n onClose();\n }\n };\n document.addEventListener('pointermove', handleTrackPointerGrace);\n return () => document.removeEventListener('pointermove', handleTrackPointerGrace);\n }\n }, [trigger, content, pointerGraceArea, onClose, handleRemoveGraceArea]);\n\n return <TooltipContentImpl {...props} ref={composedRefs} />;\n});\n\nconst [VisuallyHiddenContentContextProvider, useVisuallyHiddenContentContext] =\n createTooltipContext(TOOLTIP_NAME, { isInside: false });\n\ntype TooltipContentImplElement = React.ComponentRef<typeof PopperPrimitive.Content>;\ntype DismissableLayerProps = React.ComponentPropsWithoutRef<typeof DismissableLayer>;\ntype PopperContentProps = React.ComponentPropsWithoutRef<typeof PopperPrimitive.Content>;\ninterface TooltipContentImplProps extends Omit<PopperContentProps, 'onPlaced'> {\n /**\n * A more descriptive label for accessibility purpose\n */\n 'aria-label'?: string;\n\n /**\n * Event handler called when the escape key is down.\n * Can be prevented.\n */\n onEscapeKeyDown?: DismissableLayerProps['onEscapeKeyDown'];\n /**\n * Event handler called when the a `pointerdown` event happens outside of the `Tooltip`.\n * Can be prevented.\n */\n onPointerDownOutside?: DismissableLayerProps['onPointerDownOutside'];\n}\n\nconst Slottable = createSlottable('TooltipContent');\n\nconst TooltipContentImpl = React.forwardRef<TooltipContentImplElement, TooltipContentImplProps>(\n (props: ScopedProps<TooltipContentImplProps>, forwardedRef) => {\n const {\n __scopeTooltip,\n children,\n 'aria-label': ariaLabel,\n onEscapeKeyDown,\n onPointerDownOutside,\n ...contentProps\n } = props;\n const context = useTooltipContext(CONTENT_NAME, __scopeTooltip);\n const popperScope = usePopperScope(__scopeTooltip);\n const { onClose } = context;\n\n // Close this tooltip if another one opens\n React.useEffect(() => {\n document.addEventListener(TOOLTIP_OPEN, onClose);\n return () => document.removeEventListener(TOOLTIP_OPEN, onClose);\n }, [onClose]);\n\n // Close the tooltip if the trigger is scrolled\n React.useEffect(() => {\n if (context.trigger) {\n const handleScroll = (event: Event) => {\n const target = event.target as HTMLElement;\n if (target?.contains(context.trigger)) onClose();\n };\n window.addEventListener('scroll', handleScroll, { capture: true });\n return () => window.removeEventListener('scroll', handleScroll, { capture: true });\n }\n }, [context.trigger, onClose]);\n\n return (\n <DismissableLayer\n asChild\n disableOutsidePointerEvents={false}\n onEscapeKeyDown={onEscapeKeyDown}\n onPointerDownOutside={onPointerDownOutside}\n onFocusOutside={(event) => event.preventDefault()}\n onDismiss={onClose}\n >\n <PopperPrimitive.Content\n data-state={context.stateAttribute}\n {...popperScope}\n {...contentProps}\n ref={forwardedRef}\n style={{\n ...contentProps.style,\n // re-namespace exposed content custom properties\n ...{\n '--radix-tooltip-content-transform-origin': 'var(--radix-popper-transform-origin)',\n '--radix-tooltip-content-available-width': 'var(--radix-popper-available-width)',\n '--radix-tooltip-content-available-height': 'var(--radix-popper-available-height)',\n '--radix-tooltip-trigger-width': 'var(--radix-popper-anchor-width)',\n '--radix-tooltip-trigger-height': 'var(--radix-popper-anchor-height)',\n },\n }}\n >\n <Slottable>{children}</Slottable>\n <VisuallyHiddenContentContextProvider scope={__scopeTooltip} isInside={true}>\n <VisuallyHiddenPrimitive.Root id={context.contentId} role=\"tooltip\">\n {ariaLabel || children}\n </VisuallyHiddenPrimitive.Root>\n </VisuallyHiddenContentContextProvider>\n </PopperPrimitive.Content>\n </DismissableLayer>\n );\n }\n);\n\nTooltipContent.displayName = CONTENT_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * TooltipArrow\n * -----------------------------------------------------------------------------------------------*/\n\nconst ARROW_NAME = 'TooltipArrow';\n\ntype TooltipArrowElement = React.ComponentRef<typeof PopperPrimitive.Arrow>;\ntype PopperArrowProps = React.ComponentPropsWithoutRef<typeof PopperPrimitive.Arrow>;\ninterface TooltipArrowProps extends PopperArrowProps {}\n\nconst TooltipArrow = React.forwardRef<TooltipArrowElement, TooltipArrowProps>(\n (props: ScopedProps<TooltipArrowProps>, forwardedRef) => {\n const { __scopeTooltip, ...arrowProps } = props;\n const popperScope = usePopperScope(__scopeTooltip);\n const visuallyHiddenContentContext = useVisuallyHiddenContentContext(\n ARROW_NAME,\n __scopeTooltip\n );\n // if the arrow is inside the `VisuallyHidden`, we don't want to render it all to\n // prevent issues in positioning the arrow due to the duplicate\n return visuallyHiddenContentContext.isInside ? null : (\n <PopperPrimitive.Arrow {...popperScope} {...arrowProps} ref={forwardedRef} />\n );\n }\n);\n\nTooltipArrow.displayName = ARROW_NAME;\n\n/* -----------------------------------------------------------------------------------------------*/\n\ntype Side = NonNullable<TooltipContentProps['side']>;\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 ii = polygon[i]!;\n const jj = polygon[j]!;\n const xi = ii.x;\n const yi = ii.y;\n const xj = jj.x;\n const yj = jj.y;\n\n // prettier-ignore\n const intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);\n if (intersect) 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) return -1;\n else if (a.x > b.x) return +1;\n else if (a.y < b.y) return -1;\n else if (a.y > b.y) 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) 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[upperHull.length - 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)) 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[lowerHull.length - 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)) 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 } else {\n return upperHull.concat(lowerHull);\n }\n}\n\nconst Provider = TooltipProvider;\nconst Root = Tooltip;\nconst Trigger = TooltipTrigger;\nconst Portal = TooltipPortal;\nconst Content = TooltipContent;\nconst Arrow = TooltipArrow;\n\nexport {\n createTooltipScope,\n //\n TooltipProvider,\n Tooltip,\n TooltipTrigger,\n TooltipPortal,\n TooltipContent,\n TooltipArrow,\n //\n Provider,\n Root,\n Trigger,\n Portal,\n Content,\n Arrow,\n};\nexport type {\n TooltipProviderProps,\n TooltipProps,\n TooltipTriggerProps,\n TooltipPortalProps,\n TooltipContentProps,\n TooltipArrowProps,\n};\n", "import * as React from 'react';\n\nfunction createContext<ContextValueType extends object | null>(\n rootComponentName: string,\n defaultContext?: ContextValueType\n) {\n const Context = React.createContext<ContextValueType | undefined>(defaultContext);\n\n const Provider: React.FC<ContextValueType & { children: React.ReactNode }> = (props) => {\n const { children, ...context } = props;\n // Only re-memoize when prop values change\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const value = React.useMemo(() => context, Object.values(context)) as ContextValueType;\n return <Context.Provider value={value}>{children}</Context.Provider>;\n };\n\n Provider.displayName = rootComponentName + 'Provider';\n\n function useContext(consumerName: string) {\n const context = React.useContext(Context);\n if (context) return context;\n if (defaultContext !== undefined) return defaultContext;\n // if a defaultContext wasn't specified, it's a required context.\n throw new Error(`\\`${consumerName}\\` must be used within \\`${rootComponentName}\\``);\n }\n\n return [Provider, useContext] as const;\n}\n\n/* -------------------------------------------------------------------------------------------------\n * createContextScope\n * -----------------------------------------------------------------------------------------------*/\n\ntype Scope<C = any> = { [scopeName: string]: React.Context<C>[] } | undefined;\ntype ScopeHook = (scope: Scope) => { [__scopeProp: string]: Scope };\ninterface CreateScope {\n scopeName: string;\n (): ScopeHook;\n}\n\nfunction createContextScope(scopeName: string, createContextScopeDeps: CreateScope[] = []) {\n let defaultContexts: any[] = [];\n\n /* -----------------------------------------------------------------------------------------------\n * createContext\n * ---------------------------------------------------------------------------------------------*/\n\n function createContext<ContextValueType extends object | null>(\n rootComponentName: string,\n defaultContext?: ContextValueType\n ) {\n const BaseContext = React.createContext<ContextValueType | undefined>(defaultContext);\n const index = defaultContexts.length;\n defaultContexts = [...defaultContexts, defaultContext];\n\n const Provider: React.FC<\n ContextValueType & { scope: Scope<ContextValueType>; children: React.ReactNode }\n > = (props) => {\n const { scope, children, ...context } = props;\n const Context = scope?.[scopeName]?.[index] || BaseContext;\n // Only re-memoize when prop values change\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const value = React.useMemo(() => context, Object.values(context)) as ContextValueType;\n return <Context.Provider value={value}>{children}</Context.Provider>;\n };\n\n Provider.displayName = rootComponentName + 'Provider';\n\n function useContext(consumerName: string, scope: Scope<ContextValueType | undefined>) {\n const Context = scope?.[scopeName]?.[index] || BaseContext;\n const context = React.useContext(Context);\n if (context) return context;\n if (defaultContext !== undefined) return defaultContext;\n // if a defaultContext wasn't specified, it's a required context.\n throw new Error(`\\`${consumerName}\\` must be used within \\`${rootComponentName}\\``);\n }\n\n return [Provider, useContext] as const;\n }\n\n /* -----------------------------------------------------------------------------------------------\n * createScope\n * ---------------------------------------------------------------------------------------------*/\n\n const createScope: CreateScope = () => {\n const scopeContexts = defaultContexts.map((defaultContext) => {\n return React.createContext(defaultContext);\n });\n return function useScope(scope: Scope) {\n const contexts = scope?.[scopeName] || scopeContexts;\n return React.useMemo(\n () => ({ [`__scope${scopeName}`]: { ...scope, [scopeName]: contexts } }),\n [scope, contexts]\n );\n };\n };\n\n createScope.scopeName = scopeName;\n return [createContext, composeContextScopes(createScope, ...createContextScopeDeps)] as const;\n}\n\n/* -------------------------------------------------------------------------------------------------\n * composeContextScopes\n * -----------------------------------------------------------------------------------------------*/\n\nfunction composeContextScopes(...scopes: CreateScope[]) {\n const baseScope = scopes[0];\n if (scopes.length === 1) return baseScope;\n\n const createScope: CreateScope = () => {\n const scopeHooks = scopes.map((createScope) => ({\n useScope: createScope(),\n scopeName: createScope.scopeName,\n }));\n\n return function useComposedScopes(overrideScopes) {\n const nextScopes = scopeHooks.reduce((nextScopes, { useScope, scopeName }) => {\n // We are calling a hook inside a callback which React warns against to avoid inconsistent\n // renders, however, scoping doesn't have render side effects so we ignore the rule.\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const scopeProps = useScope(overrideScopes);\n const currentScope = scopeProps[`__scope${scopeName}`];\n return { ...nextScopes, ...currentScope };\n }, {});\n\n return React.useMemo(() => ({ [`__scope${baseScope.scopeName}`]: nextScopes }), [nextScopes]);\n };\n };\n\n createScope.scopeName = baseScope.scopeName;\n return createScope;\n}\n\n/* -----------------------------------------------------------------------------------------------*/\n\nexport { createContext, createContextScope };\nexport type { CreateScope, Scope };\n", "import * as React from 'react';\nimport { composeEventHandlers } from '@radix-ui/primitive';\nimport { Primitive, dispatchDiscreteCustomEvent } from '@radix-ui/react-primitive';\nimport { useComposedRefs } from '@radix-ui/react-compose-refs';\nimport { useCallbackRef } from '@radix-ui/react-use-callback-ref';\nimport { useEscapeKeydown } from '@radix-ui/react-use-escape-keydown';\n\n/* -------------------------------------------------------------------------------------------------\n * DismissableLayer\n * -----------------------------------------------------------------------------------------------*/\n\nconst DISMISSABLE_LAYER_NAME = 'DismissableLayer';\nconst CONTEXT_UPDATE = 'dismissableLayer.update';\nconst POINTER_DOWN_OUTSIDE = 'dismissableLayer.pointerDownOutside';\nconst FOCUS_OUTSIDE = 'dismissableLayer.focusOutside';\n\nlet originalBodyPointerEvents: string;\n\nconst DismissableLayerContext = React.createContext({\n layers: new Set<DismissableLayerElement>(),\n layersWithOutsidePointerEventsDisabled: new Set<DismissableLayerElement>(),\n branches: new Set<DismissableLayerBranchElement>(),\n});\n\ntype DismissableLayerElement = React.ComponentRef<typeof Primitive.div>;\ntype PrimitiveDivProps = React.ComponentPropsWithoutRef<typeof Primitive.div>;\ninterface DismissableLayerProps extends PrimitiveDivProps {\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 * Event handler called when the escape key is down.\n * Can be prevented.\n */\n onEscapeKeyDown?: (event: KeyboardEvent) => void;\n /**\n * Event handler called when the a `pointerdown` event happens outside of the `DismissableLayer`.\n * Can be prevented.\n */\n onPointerDownOutside?: (event: PointerDownOutsideEvent) => void;\n /**\n * Event handler called when the focus moves outside of the `DismissableLayer`.\n * Can be prevented.\n */\n onFocusOutside?: (event: FocusOutsideEvent) => void;\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 onInteractOutside?: (event: PointerDownOutsideEvent | FocusOutsideEvent) => void;\n /**\n * Handler called when the `DismissableLayer` should be dismissed\n */\n onDismiss?: () => void;\n}\n\nconst DismissableLayer = React.forwardRef<DismissableLayerElement, DismissableLayerProps>(\n (props, forwardedRef) => {\n const {\n disableOutsidePointerEvents = false,\n onEscapeKeyDown,\n onPointerDownOutside,\n onFocusOutside,\n onInteractOutside,\n onDismiss,\n ...layerProps\n } = props;\n const context = React.useContext(DismissableLayerContext);\n const [node, setNode] = React.useState<DismissableLayerElement | null>(null);\n const ownerDocument = node?.ownerDocument ?? globalThis?.document;\n const [, force] = React.useState({});\n const composedRefs = useComposedRefs(forwardedRef, (node) => setNode(node));\n const layers = Array.from(context.layers);\n const [highestLayerWithOutsidePointerEventsDisabled] = [...context.layersWithOutsidePointerEventsDisabled].slice(-1); // prettier-ignore\n const highestLayerWithOutsidePointerEventsDisabledIndex = layers.indexOf(highestLayerWithOutsidePointerEventsDisabled!); // prettier-ignore\n const index = node ? layers.indexOf(node) : -1;\n const isBodyPointerEventsDisabled = context.layersWithOutsidePointerEventsDisabled.size > 0;\n const isPointerEventsEnabled = index >= highestLayerWithOutsidePointerEventsDisabledIndex;\n\n const pointerDownOutside = usePointerDownOutside((event) => {\n const target = event.target as HTMLElement;\n const isPointerDownOnBranch = [...context.branches].some((branch) => branch.contains(target));\n if (!isPointerEventsEnabled || isPointerDownOnBranch) return;\n onPointerDownOutside?.(event);\n onInteractOutside?.(event);\n if (!event.defaultPrevented) onDismiss?.();\n }, ownerDocument);\n\n const focusOutside = useFocusOutside((event) => {\n const target = event.target as HTMLElement;\n const isFocusInBranch = [...context.branches].some((branch) => branch.contains(target));\n if (isFocusInBranch) return;\n onFocusOutside?.(event);\n onInteractOutside?.(event);\n if (!event.defaultPrevented) onDismiss?.();\n }, ownerDocument);\n\n useEscapeKeydown((event) => {\n const isHighestLayer = index === context.layers.size - 1;\n if (!isHighestLayer) return;\n onEscapeKeyDown?.(event);\n if (!event.defaultPrevented && onDismiss) {\n event.preventDefault();\n onDismiss();\n }\n }, ownerDocument);\n\n React.useEffect(() => {\n if (!node) return;\n if (disableOutsidePointerEvents) {\n if (context.layersWithOutsidePointerEventsDisabled.size === 0) {\n originalBodyPointerEvents = ownerDocument.body.style.pointerEvents;\n ownerDocument.body.style.pointerEvents = 'none';\n }\n context.layersWithOutsidePointerEventsDisabled.add(node);\n }\n context.layers.add(node);\n dispatchUpdate();\n return () => {\n if (\n disableOutsidePointerEvents &&\n context.layersWithOutsidePointerEventsDisabled.size === 1\n ) {\n ownerDocument.body.style.pointerEvents = originalBodyPointerEvents;\n }\n };\n }, [node, ownerDocument, disableOutsidePointerEvents, context]);\n\n /**\n * We purposefully prevent combining this effect with the `disableOutsidePointerEvents` effect\n * because a change to `disableOutsidePointerEvents` would remove this layer from the stack\n * and add it to the end again so the layering order wouldn't be _creation order_.\n * We only want them to be removed from context stacks when unmounted.\n */\n React.useEffect(() => {\n return () => {\n if (!node) return;\n context.layers.delete(node);\n context.layersWithOutsidePointerEventsDisabled.delete(node);\n dispatchUpdate();\n };\n }, [node, context]);\n\n React.useEffect(() => {\n const handleUpdate = () => force({});\n document.addEventListener(CONTEXT_UPDATE, handleUpdate);\n return () => document.removeEventListener(CONTEXT_UPDATE, handleUpdate);\n }, []);\n\n return (\n <Primitive.div\n {...layerProps}\n ref={composedRefs}\n style={{\n pointerEvents: isBodyPointerEventsDisabled\n ? isPointerEventsEnabled\n ? 'auto'\n : 'none'\n : undefined,\n ...props.style,\n }}\n onFocusCapture={composeEventHandlers(props.onFocusCapture, focusOutside.onFocusCapture)}\n onBlurCapture={composeEventHandlers(props.onBlurCapture, focusOutside.onBlurCapture)}\n onPointerDownCapture={composeEventHandlers(\n props.onPointerDownCapture,\n pointerDownOutside.onPointerDownCapture\n )}\n />\n );\n }\n);\n\nDismissableLayer.displayName = DISMISSABLE_LAYER_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * DismissableLayerBranch\n * -----------------------------------------------------------------------------------------------*/\n\nconst BRANCH_NAME = 'DismissableLayerBranch';\n\ntype DismissableLayerBranchElement = React.ComponentRef<typeof Primitive.div>;\ninterface DismissableLayerBranchProps extends PrimitiveDivProps {}\n\nconst DismissableLayerBranch = React.forwardRef<\n DismissableLayerBranchElement,\n DismissableLayerBranchProps\n>((props, forwardedRef) => {\n const context = React.useContext(DismissableLayerContext);\n const ref = React.useRef<DismissableLayerBranchElement>(null);\n const composedRefs = useComposedRefs(forwardedRef, ref);\n\n React.useEffect(() => {\n const node = ref.current;\n if (node) {\n context.branches.add(node);\n return () => {\n context.branches.delete(node);\n };\n }\n }, [context.branches]);\n\n return <Primitive.div {...props} ref={composedRefs} />;\n});\n\nDismissableLayerBranch.displayName = BRANCH_NAME;\n\n/* -----------------------------------------------------------------------------------------------*/\n\ntype PointerDownOutsideEvent = CustomEvent<{ originalEvent: PointerEvent }>;\ntype FocusOutsideEvent = CustomEvent<{ originalEvent: FocusEvent }>;\n\n/**\n * Listens for `pointerdown` outside a react 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 */\nfunction usePointerDownOutside(\n onPointerDownOutside?: (event: PointerDownOutsideEvent) => void,\n ownerDocument: Document = globalThis?.document\n) {\n const handlePointerDownOutside = useCallbackRef(onPointerDownOutside) as EventListener;\n const isPointerInsideReactTreeRef = React.useRef(false);\n const handleClickRef = React.useRef(() => {});\n\n React.useEffect(() => {\n const handlePointerDown = (event: PointerEvent) => {\n if (event.target && !isPointerInsideReactTreeRef.current) {\n const eventDetail = { originalEvent: event };\n\n function handleAndDispatchPointerDownOutsideEvent() {\n handleAndDispatchCustomEvent(\n POINTER_DOWN_OUTSIDE,\n handlePointerDownOutside,\n eventDetail,\n { discrete: true }\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 executres 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.current);\n handleClickRef.current = handleAndDispatchPointerDownOutsideEvent;\n ownerDocument.addEventListener('click', handleClickRef.current, { once: true });\n } else {\n handleAndDispatchPointerDownOutsideEvent();\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.current);\n }\n isPointerInsideReactTreeRef.current = 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 not React specific, but rather 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 return () => {\n window.clearTimeout(timerId);\n ownerDocument.removeEventListener('pointerdown', handlePointerDown);\n ownerDocument.removeEventListener('click', handleClickRef.current);\n };\n }, [ownerDocument, handlePointerDownOutside]);\n\n return {\n // ensures we check React component tree (not just DOM tree)\n onPointerDownCapture: () => (isPointerInsideReactTreeRef.current = true),\n };\n}\n\n/**\n * Listens for when focus happens outside a react subtree.\n * Returns props to pass to the root (node) of the subtree we want to check.\n */\nfunction useFocusOutside(\n onFocusOutside?: (event: FocusOutsideEvent) => void,\n ownerDocument: Document = globalThis?.document\n) {\n const handleFocusOutside = useCallbackRef(onFocusOutside) as EventListener;\n const isFocusInsideReactTreeRef = React.useRef(false);\n\n React.useEffect(() => {\n const handleFocus = (event: FocusEvent) => {\n if (event.target && !isFocusInsideReactTreeRef.current) {\n const eventDetail = { originalEvent: event };\n handleAndDispatchCustomEvent(FOCUS_OUTSIDE, handleFocusOutside, eventDetail, {\n discrete: false,\n });\n }\n };\n ownerDocument.addEventListener('focusin', handleFocus);\n return () => ownerDocument.removeEventListener('focusin', handleFocus);\n }, [ownerDocument, handleFocusOutside]);\n\n return {\n onFocusCapture: () => (isFocusInsideReactTreeRef.current = true),\n onBlurCapture: () => (isFocusInsideReactTreeRef.current = false),\n };\n}\n\nfunction dispatchUpdate() {\n const event = new CustomEvent(CONTEXT_UPDATE);\n document.dispatchEvent(event);\n}\n\nfunction handleAndDispatchCustomEvent<E extends CustomEvent, OriginalEvent extends Event>(\n name: string,\n handler: ((event: E) => void) | undefined,\n detail: { originalEvent: OriginalEvent } & (E extends CustomEvent<infer D> ? D : never),\n { discrete }: { discrete: boolean }\n) {\n const target = detail.originalEvent.target;\n const event = new CustomEvent(name, { bubbles: false, cancelable: true, detail });\n if (handler) target.addEventListener(name, handler as EventListener, { once: true });\n\n if (discrete) {\n dispatchDiscreteCustomEvent(target, event);\n } else {\n target.dispatchEvent(event);\n }\n}\n\nconst Root = DismissableLayer;\nconst Branch = DismissableLayerBranch;\n\nexport {\n DismissableLayer,\n DismissableLayerBranch,\n //\n Root,\n Branch,\n};\nexport type { DismissableLayerProps };\n", "import * as React from 'react';\nimport * as ReactDOM from 'react-dom';\nimport { createSlot } from '@radix-ui/react-slot';\n\nconst NODES = [\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 'select',\n 'span',\n 'svg',\n 'ul',\n] as const;\n\ntype Primitives = { [E in (typeof NODES)[number]]: PrimitiveForwardRefComponent<E> };\ntype PrimitivePropsWithRef<E extends React.ElementType> = React.ComponentPropsWithRef<E> & {\n asChild?: boolean;\n};\n\ninterface PrimitiveForwardRefComponent<E extends React.ElementType>\n extends React.ForwardRefExoticComponent<PrimitivePropsWithRef<E>> {}\n\n/* -------------------------------------------------------------------------------------------------\n * Primitive\n * -----------------------------------------------------------------------------------------------*/\n\nconst Primitive = NODES.reduce((primitive, node) => {\n const Slot = createSlot(`Primitive.${node}`);\n const Node = React.forwardRef((props: PrimitivePropsWithRef<typeof node>, forwardedRef: any) => {\n const { asChild, ...primitiveProps } = props;\n const Comp: any = asChild ? Slot : node;\n\n if (typeof window !== 'undefined') {\n (window as any)[Symbol.for('radix-ui')] = true;\n }\n\n return <Comp {...primitiveProps} ref={forwardedRef} />;\n });\n\n Node.displayName = `Primitive.${node}`;\n\n return { ...primitive, [node]: Node };\n}, {} as Primitives);\n\n/* -------------------------------------------------------------------------------------------------\n * Utils\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * Flush custom event dispatch\n * https://github.com/radix-ui/primitives/pull/1378\n *\n * React batches *all* event handlers since version 18, this introduces certain considerations when using custom event types.\n *\n * Internally, React prioritises events in the following order:\n * - discrete\n * - continuous\n * - default\n *\n * https://github.com/facebook/react/blob/a8a4742f1c54493df00da648a3f9d26e3db9c8b5/packages/react-dom/src/events/ReactDOMEventListener.js#L294-L350\n *\n * `discrete` is an important distinction as updates within these events are applied immediately.\n * React however, is not able to infer the priority of custom event types due to how they are detected internally.\n * Because of this, it's possible for updates from custom events to be unexpectedly batched when\n * dispatched by another `discrete` event.\n *\n * In order to ensure that updates from custom events are applied predictably, we need to manually flush the batch.\n * This utility should be used when dispatching a custom event from within another `discrete` event, this utility\n * is not necessary when dispatching known event types, or if dispatching a custom type inside a non-discrete event.\n * For example:\n *\n * dispatching a known click \uD83D\uDC4E\n * target.dispatchEvent(new Event(\u2018click\u2019))\n *\n * dispatching a custom type within a non-discrete event \uD83D\uDC4E\n * onScroll={(event) => event.target.dispatchEvent(new CustomEvent(\u2018customType\u2019))}\n *\n * dispatching a custom type within a `discrete` event \uD83D\uDC4D\n * onPointerDown={(event) => dispatchDiscreteCustomEvent(event.target, new CustomEvent(\u2018customType\u2019))}\n *\n * Note: though React classifies `focus`, `focusin` and `focusout` events as `discrete`, it's not recommended to use\n * this utility with them. This is because it's possible for those handlers to be called implicitly during render\n * e.g. when focus is within a component as it is unmounted, or when managing focus on mount.\n */\n\nfunction dispatchDiscreteCustomEvent<E extends CustomEvent>(target: E['target'], event: E) {\n if (target) ReactDOM.flushSync(() => target.dispatchEvent(event));\n}\n\n/* -----------------------------------------------------------------------------------------------*/\n\nconst Root = Primitive;\n\nexport {\n Primitive,\n //\n Root,\n //\n dispatchDiscreteCustomEvent,\n};\nexport type { PrimitivePropsWithRef };\n", "import * as React from 'react';\nimport { composeRefs } from '@radix-ui/react-compose-refs';\n\n/* -------------------------------------------------------------------------------------------------\n * Slot\n * -----------------------------------------------------------------------------------------------*/\n\ninterface SlotProps extends React.HTMLAttributes<HTMLElement> {\n children?: React.ReactNode;\n}\n\n/* @__NO_SIDE_EFFECTS__ */ export function createSlot(ownerName: string) {\n const SlotClone = createSlotClone(ownerName);\n const Slot = React.forwardRef<HTMLElement, SlotProps>((props, forwardedRef) => {\n const { children, ...slotProps } = props;\n const childrenArray = React.Children.toArray(children);\n const slottable = childrenArray.find(isSlottable);\n\n if (slottable) {\n // the new element to render is the one passed as a child of `Slottable`\n const newElement = slottable.props.children;\n\n const newChildren = childrenArray.map((child) => {\n if (child === slottable) {\n // because the new element will be the one rendered, we are only interested\n // in grabbing its children (`newElement.props.children`)\n if (React.Children.count(newElement) > 1) return React.Children.only(null);\n return React.isValidElement(newElement)\n ? (newElement.props as { children: React.ReactNode }).children\n : null;\n } else {\n return child;\n }\n });\n\n return (\n <SlotClone {...slotProps} ref={forwardedRef}>\n {React.isValidElement(newElement)\n ? React.cloneElement(newElement, undefined, newChildren)\n : null}\n </SlotClone>\n );\n }\n\n return (\n <SlotClone {...slotProps} ref={forwardedRef}>\n {children}\n </SlotClone>\n );\n });\n\n Slot.displayName = `${ownerName}.Slot`;\n return Slot;\n}\n\nconst Slot = createSlot('Slot');\n\n/* -------------------------------------------------------------------------------------------------\n * SlotClone\n * -----------------------------------------------------------------------------------------------*/\n\ninterface SlotCloneProps {\n children: React.ReactNode;\n}\n\n/* @__NO_SIDE_EFFECTS__ */ function createSlotClone(ownerName: string) {\n const SlotClone = React.forwardRef<any, SlotCloneProps>((props, forwardedRef) => {\n const { children, ...slotProps } = props;\n\n if (React.isValidElement(children)) {\n const childrenRef = getElementRef(children);\n const props = mergeProps(slotProps, children.props as AnyProps);\n // do not pass ref to React.Fragment for React 19 compatibility\n if (children.type !== React.Fragment) {\n props.ref = forwardedRef ? composeRefs(forwardedRef, childrenRef) : childrenRef;\n }\n return React.cloneElement(children, props);\n }\n\n return React.Children.count(children) > 1 ? React.Children.only(null) : null;\n });\n\n SlotClone.displayName = `${ownerName}.SlotClone`;\n return SlotClone;\n}\n\n/* -------------------------------------------------------------------------------------------------\n * Slottable\n * -----------------------------------------------------------------------------------------------*/\n\nconst SLOTTABLE_IDENTIFIER = Symbol('radix.slottable');\n\ninterface SlottableProps {\n children: React.ReactNode;\n}\n\ninterface SlottableComponent extends React.FC<SlottableProps> {\n __radixId: symbol;\n}\n\n/* @__NO_SIDE_EFFECTS__ */ export function createSlottable(ownerName: string) {\n const Slottable: SlottableComponent = ({ children }) => {\n return <>{children}</>;\n };\n Slottable.displayName = `${ownerName}.Slottable`;\n Slottable.__radixId = SLOTTABLE_IDENTIFIER;\n return Slottable;\n}\n\nconst Slottable = createSlottable('Slottable');\n\n/* ---------------------------------------------------------------------------------------------- */\n\ntype AnyProps = Record<string, any>;\n\nfunction isSlottable(\n child: React.ReactNode\n): child is React.ReactElement<SlottableProps, typeof Slottable> {\n return (\n React.isValidElement(child) &&\n typeof child.type === 'function' &&\n '__radixId' in child.type &&\n child.type.__radixId === SLOTTABLE_IDENTIFIER\n );\n}\n\nfunction mergeProps(slotProps: AnyProps, childProps: AnyProps) {\n // all child props should override\n const overrideProps = { ...childProps };\n\n for (const propName in childProps) {\n const slotPropValue = slotProps[propName];\n const childPropValue = childProps[propName];\n\n const isHandler = /^on[A-Z]/.test(propName);\n if (isHandler) {\n // if the handler exists on both, we compose them\n if (slotPropValue && childPropValue) {\n overrideProps[propName] = (...args: unknown[]) => {\n const result = childPropValue(...args);\n slotPropValue(...args);\n return result;\n };\n }\n // but if it exists only on the slot, we use only this one\n else if (slotPropValue) {\n overrideProps[propName] = slotPropValue;\n }\n }\n // if it's `style`, we merge them\n else if (propName === 'style') {\n overrideProps[propName] = { ...slotPropValue, ...childPropValue };\n } else if (propName === 'className') {\n overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(' ');\n }\n }\n\n return { ...slotProps, ...overrideProps };\n}\n\n// Before React 19 accessing `element.props.ref` will throw a warning and suggest using `element.ref`\n// After React 19 accessing `element.ref` does the opposite.\n// https://github.com/facebook/react/pull/28348\n//\n// Access the ref using the method that doesn't yield a warning.\nfunction getElementRef(element: React.ReactElement) {\n // React <=18 in DEV\n let getter = Object.getOwnPropertyDescriptor(element.props, 'ref')?.get;\n let mayWarn = getter && 'isReactWarning' in getter && getter.isReactWarning;\n if (mayWarn) {\n return (element as any).ref;\n }\n\n // React 19 in DEV\n getter = Object.getOwnPropertyDescriptor(element, 'ref')?.get;\n mayWarn = getter && 'isReactWarning' in getter && getter.isReactWarning;\n if (mayWarn) {\n return (element.props as { ref?: React.Ref<unknown> }).ref;\n }\n\n // Not DEV\n return (element.props as { ref?: React.Ref<unknown> }).ref || (element as any).ref;\n}\n\nexport {\n Slot,\n Slottable,\n //\n Slot as Root,\n};\nexport type { SlotProps };\n", "import * as React from 'react';\n\n/**\n * A custom hook that converts a callback to a ref to avoid triggering re-renders when passed as a\n * prop or avoid re-executing effects when passed as a dependency\n */\nfunction useCallbackRef<T extends (...args: any[]) => any>(callback: T | undefined): T {\n const callbackRef = React.useRef(callback);\n\n React.useEffect(() => {\n callbackRef.current = callback;\n });\n\n // https://github.com/facebook/react/issues/19240\n return React.useMemo(() => ((...args) => callbackRef.current?.(...args)) as T, []);\n}\n\nexport { useCallbackRef };\n", "import * as React from 'react';\nimport { useCallbackRef } from '@radix-ui/react-use-callback-ref';\n\n/**\n * Listens for when the escape key is down\n */\nfunction useEscapeKeydown(\n onEscapeKeyDownProp?: (event: KeyboardEvent) => void,\n ownerDocument: Document = globalThis?.document\n) {\n const onEscapeKeyDown = useCallbackRef(onEscapeKeyDownProp);\n\n React.useEffect(() => {\n const handleKeyDown = (event: KeyboardEvent) => {\n if (event.key === 'Escape') {\n onEscapeKeyDown(event);\n }\n };\n ownerDocument.addEventListener('keydown', handleKeyDown, { capture: true });\n return () => ownerDocument.removeEventListener('keydown', handleKeyDown, { capture: true });\n }, [onEscapeKeyDown, ownerDocument]);\n}\n\nexport { useEscapeKeydown };\n", "import * as React from 'react';\nimport { useLayoutEffect } from '@radix-ui/react-use-layout-effect';\n\n// We spaces with `.trim().toString()` to prevent bundlers from trying to `import { useId } from 'react';`\nconst useReactId = (React as any)[' useId '.trim().toString()] || (() => undefined);\nlet count = 0;\n\nfunction useId(deterministicId?: string): string {\n const [id, setId] = React.useState<string | undefined>(useReactId());\n // React versions older than 18 will have client-side ids only.\n useLayoutEffect(() => {\n if (!deterministicId) setId((reactId) => reactId ?? String(count++));\n }, [deterministicId]);\n return deterministicId || (id ? `radix-${id}` : '');\n}\n\nexport { useId };\n", "import * as React from 'react';\n\n/**\n * On the server, React emits a warning when calling `useLayoutEffect`.\n * This is because neither `useLayoutEffect` nor `useEffect` run on the server.\n * We use this safe version which suppresses the warning by replacing it with a noop on the server.\n *\n * See: https://reactjs.org/docs/hooks-reference.html#uselayouteffect\n */\nconst useLayoutEffect = globalThis?.document ? React.useLayoutEffect : () => {};\n\nexport { useLayoutEffect };\n", "import * as React from 'react';\nimport {\n useFloating,\n autoUpdate,\n offset,\n shift,\n limitShift,\n hide,\n arrow as floatingUIarrow,\n flip,\n size,\n} from '@floating-ui/react-dom';\nimport * as ArrowPrimitive from '@radix-ui/react-arrow';\nimport { useComposedRefs } from '@radix-ui/react-compose-refs';\nimport { createContextScope } from '@radix-ui/react-context';\nimport { Primitive } from '@radix-ui/react-primitive';\nimport { useCallbackRef } from '@radix-ui/react-use-callback-ref';\nimport { useLayoutEffect } from '@radix-ui/react-use-layout-effect';\nimport { useSize } from '@radix-ui/react-use-size';\n\nimport type { Placement, Middleware } from '@floating-ui/react-dom';\nimport type { Scope } from '@radix-ui/react-context';\nimport type { Measurable } from '@radix-ui/rect';\n\nconst SIDE_OPTIONS = ['top', 'right', 'bottom', 'left'] as const;\nconst ALIGN_OPTIONS = ['start', 'center', 'end'] as const;\n\ntype Side = (typeof SIDE_OPTIONS)[number];\ntype Align = (typeof ALIGN_OPTIONS)[number];\n\n/* -------------------------------------------------------------------------------------------------\n * Popper\n * -----------------------------------------------------------------------------------------------*/\n\nconst POPPER_NAME = 'Popper';\n\ntype ScopedProps<P> = P & { __scopePopper?: Scope };\nconst [createPopperContext, createPopperScope] = createContextScope(POPPER_NAME);\n\ntype PopperContextValue = {\n anchor: Measurable | null;\n onAnchorChange(anchor: Measurable | null): void;\n};\nconst [PopperProvider, usePopperContext] = createPopperContext<PopperContextValue>(POPPER_NAME);\n\ninterface PopperProps {\n children?: React.ReactNode;\n}\nconst Popper: React.FC<PopperProps> = (props: ScopedProps<PopperProps>) => {\n const { __scopePopper, children } = props;\n const [anchor, setAnchor] = React.useState<Measurable | null>(null);\n return (\n <PopperProvider scope={__scopePopper} anchor={anchor} onAnchorChange={setAnchor}>\n {children}\n </PopperProvider>\n );\n};\n\nPopper.displayName = POPPER_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * PopperAnchor\n * -----------------------------------------------------------------------------------------------*/\n\nconst ANCHOR_NAME = 'PopperAnchor';\n\ntype PopperAnchorElement = React.ComponentRef<typeof Primitive.div>;\ntype PrimitiveDivProps = React.ComponentPropsWithoutRef<typeof Primitive.div>;\ninterface PopperAnchorProps extends PrimitiveDivProps {\n virtualRef?: React.RefObject<Measurable>;\n}\n\nconst PopperAnchor = React.forwardRef<PopperAnchorElement, PopperAnchorProps>(\n (props: ScopedProps<PopperAnchorProps>, forwardedRef) => {\n const { __scopePopper, virtualRef, ...anchorProps } = props;\n const context = usePopperContext(ANCHOR_NAME, __scopePopper);\n const ref = React.useRef<PopperAnchorElement>(null);\n const composedRefs = useComposedRefs(forwardedRef, ref);\n\n const anchorRef = React.useRef<Measurable | null>(null);\n React.useEffect(() => {\n const previousAnchor = anchorRef.current;\n anchorRef.current = virtualRef?.current || ref.current;\n if (previousAnchor !== anchorRef.current) {\n // Consumer can anchor the popper to something that isn't\n // a DOM node e.g. pointer position, so we override the\n // `anchorRef` with their virtual ref in this case.\n context.onAnchorChange(anchorRef.current);\n }\n });\n\n return virtualRef ? null : <Primitive.div {...anchorProps} ref={composedRefs} />;\n }\n);\n\nPopperAnchor.displayName = ANCHOR_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * PopperContent\n * -----------------------------------------------------------------------------------------------*/\n\nconst CONTENT_NAME = 'PopperContent';\n\ntype PopperContentContextValue = {\n placedSide: Side;\n onArrowChange(arrow: HTMLSpanElement | null): void;\n arrowX?: number;\n arrowY?: number;\n shouldHideArrow: boolean;\n};\n\nconst [PopperContentProvider, useContentContext] =\n createPopperContext<PopperContentContextValue>(CONTENT_NAME);\n\ntype Boundary = Element | null;\n\ntype PopperContentElement = React.ComponentRef<typeof Primitive.div>;\ninterface PopperContentProps extends PrimitiveDivProps {\n side?: Side;\n sideOffset?: number;\n align?: Align;\n alignOffset?: number;\n arrowPadding?: number;\n avoidCollisions?: boolean;\n collisionBoundary?: Boundary | Boundary[];\n collisionPadding?: number | Partial<Record<Side, number>>;\n sticky?: 'partial' | 'always';\n hideWhenDetached?: boolean;\n updatePositionStrategy?: 'optimized' | 'always';\n onPlaced?: () => void;\n}\n\nconst PopperContent = React.forwardRef<PopperContentElement, PopperContentProps>(\n (props: ScopedProps<PopperContentProps>, forwardedRef) => {\n const {\n __scopePopper,\n side = 'bottom',\n sideOffset = 0,\n align = 'center',\n alignOffset = 0,\n arrowPadding = 0,\n avoidCollisions = true,\n collisionBoundary = [],\n collisionPadding: collisionPaddingProp = 0,\n sticky = 'partial',\n hideWhenDetached = false,\n updatePositionStrategy = 'optimized',\n onPlaced,\n ...contentProps\n } = props;\n\n const context = usePopperContext(CONTENT_NAME, __scopePopper);\n\n const [content, setContent] = React.useState<HTMLDivElement | null>(null);\n const composedRefs = useComposedRefs(forwardedRef, (node) => setContent(node));\n\n const [arrow, setArrow] = React.useState<HTMLSpanElement | null>(null);\n const arrowSize = useSize(arrow);\n const arrowWidth = arrowSize?.width ?? 0;\n const arrowHeight = arrowSize?.height ?? 0;\n\n const desiredPlacement = (side + (align !== 'center' ? '-' + align : '')) as Placement;\n\n const collisionPadding =\n typeof collisionPaddingProp === 'number'\n ? collisionPaddingProp\n : { top: 0, right: 0, bottom: 0, left: 0, ...collisionPaddingProp };\n\n const boundary = Array.isArray(collisionBoundary) ? collisionBoundary : [collisionBoundary];\n const hasExplicitBoundaries = boundary.length > 0;\n\n const detectOverflowOptions = {\n padding: collisionPadding,\n boundary: boundary.filter(isNotNull),\n // with `strategy: 'fixed'`, this is the only way to get it to respect boundaries\n altBoundary: hasExplicitBoundaries,\n };\n\n const { refs, floatingStyles, placement, isPositioned, middlewareData } = useFloating({\n // default to `fixed` strategy so users don't have to pick and we also avoid focus scroll issues\n strategy: 'fixed',\n placement: desiredPlacement,\n whileElementsMounted: (...args) => {\n const cleanup = autoUpdate(...args, {\n animationFrame: updatePositionStrategy === 'always',\n });\n return cleanup;\n },\n elements: {\n reference: context.anchor,\n },\n middleware: [\n offset({ mainAxis: sideOffset + arrowHeight, alignmentAxis: alignOffset }),\n avoidCollisions &&\n shift({\n mainAxis: true,\n crossAxis: false,\n limiter: sticky === 'partial' ? limitShift() : undefined,\n ...detectOverflowOptions,\n }),\n avoidCollisions && flip({ ...detectOverflowOptions }),\n size({\n ...detectOverflowOptions,\n apply: ({ elements, rects, availableWidth, availableHeight }) => {\n const { width: anchorWidth, height: anchorHeight } = rects.reference;\n const contentStyle = elements.floating.style;\n contentStyle.setProperty('--radix-popper-available-width', `${availableWidth}px`);\n contentStyle.setProperty('--radix-popper-available-height', `${availableHeight}px`);\n contentStyle.setProperty('--radix-popper-anchor-width', `${anchorWidth}px`);\n contentStyle.setProperty('--radix-popper-anchor-height', `${anchorHeight}px`);\n },\n }),\n arrow && floatingUIarrow({ element: arrow, padding: arrowPadding }),\n transformOrigin({ arrowWidth, arrowHeight }),\n hideWhenDetached && hide({ strategy: 'referenceHidden', ...detectOverflowOptions }),\n ],\n });\n\n const [placedSide, placedAlign] = getSideAndAlignFromPlacement(placement);\n\n const handlePlaced = useCallbackRef(onPlaced);\n useLayoutEffect(() => {\n if (isPositioned) {\n handlePlaced?.();\n }\n }, [isPositioned, handlePlaced]);\n\n const arrowX = middlewareData.arrow?.x;\n const arrowY = middlewareData.arrow?.y;\n const cannotCenterArrow = middlewareData.arrow?.centerOffset !== 0;\n\n const [contentZIndex, setContentZIndex] = React.useState<string>();\n useLayoutEffect(() => {\n if (content) setContentZIndex(window.getComputedStyle(content).zIndex);\n }, [content]);\n\n return (\n <div\n ref={refs.setFloating}\n data-radix-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 ['--radix-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 // Floating UI interally calculates logical alignment based the `dir` attribute on\n // the reference/floating node, we must add this attribute here to ensure\n // this is calculated when portalled as well as inline.\n dir={props.dir}\n >\n <PopperContentProvider\n scope={__scopePopper}\n placedSide={placedSide}\n onArrowChange={setArrow}\n arrowX={arrowX}\n arrowY={arrowY}\n shouldHideArrow={cannotCenterArrow}\n >\n <Primitive.div\n data-side={placedSide}\n data-align={placedAlign}\n {...contentProps}\n ref={composedRefs}\n style={{\n ...contentProps.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 </PopperContentProvider>\n </div>\n );\n }\n);\n\nPopperContent.displayName = CONTENT_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * PopperArrow\n * -----------------------------------------------------------------------------------------------*/\n\nconst ARROW_NAME = 'PopperArrow';\n\nconst OPPOSITE_SIDE: Record<Side, Side> = {\n top: 'bottom',\n right: 'left',\n bottom: 'top',\n left: 'right',\n};\n\ntype PopperArrowElement = React.ComponentRef<typeof ArrowPrimitive.Root>;\ntype ArrowProps = React.ComponentPropsWithoutRef<typeof ArrowPrimitive.Root>;\ninterface PopperArrowProps extends ArrowProps {}\n\nconst PopperArrow = React.forwardRef<PopperArrowElement, PopperArrowProps>(function PopperArrow(\n props: ScopedProps<PopperArrowProps>,\n forwardedRef\n) {\n const { __scopePopper, ...arrowProps } = props;\n const contentContext = useContentContext(ARROW_NAME, __scopePopper);\n const baseSide = OPPOSITE_SIDE[contentContext.placedSide];\n\n return (\n // we have to use an extra wrapper because `ResizeObserver` (used by `useSize`)\n // doesn't report size as we'd expect on SVG elements.\n // it reports their bounding box which is effectively the largest path inside the SVG.\n <span\n ref={contentContext.onArrowChange}\n style={{\n position: 'absolute',\n left: contentContext.arrowX,\n top: contentContext.arrowY,\n [baseSide]: 0,\n transformOrigin: {\n top: '',\n right: '0 0',\n bottom: 'center 0',\n left: '100% 0',\n }[contentContext.placedSide],\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],\n visibility: contentContext.shouldHideArrow ? 'hidden' : undefined,\n }}\n >\n <ArrowPrimitive.Root\n {...arrowProps}\n ref={forwardedRef}\n style={{\n ...arrowProps.style,\n // ensures the element can be measured correctly (mostly for if SVG)\n display: 'block',\n }}\n />\n </span>\n );\n});\n\nPopperArrow.displayName = ARROW_NAME;\n\n/* -----------------------------------------------------------------------------------------------*/\n\nfunction isNotNull<T>(value: T | null): value is T {\n return value !== null;\n}\n\nconst transformOrigin = (options: { arrowWidth: number; arrowHeight: number }): Middleware => ({\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%' }[placedAlign];\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 } else if (placedSide === 'top') {\n x = isArrowHidden ? noArrowAlign : `${arrowXCenter}px`;\n y = `${rects.floating.height + arrowHeight}px`;\n } else if (placedSide === 'right') {\n x = `${-arrowHeight}px`;\n y = isArrowHidden ? noArrowAlign : `${arrowYCenter}px`;\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\nfunction getSideAndAlignFromPlacement(placement: Placement) {\n const [side, align = 'center'] = placement.split('-');\n return [side as Side, align as Align] as const;\n}\n\nconst Root = Popper;\nconst Anchor = PopperAnchor;\nconst Content = PopperContent;\nconst Arrow = PopperArrow;\n\nexport {\n createPopperScope,\n //\n Popper,\n PopperAnchor,\n PopperContent,\n PopperArrow,\n //\n Root,\n Anchor,\n Content,\n Arrow,\n //\n SIDE_OPTIONS,\n ALIGN_OPTIONS,\n};\nexport type { PopperProps, PopperAnchorProps, PopperContentProps, PopperArrowProps };\n", "import { computePosition, arrow as arrow$2, offset as offset$1, shift as shift$1, limitShift as limitShift$1, flip as flip$1, size as size$1, autoPlacement as autoPlacement$1, hide as hide$1, inline as inline$1 } from '@floating-ui/dom';\nexport { autoUpdate, computePosition, detectOverflow, getOverflowAncestors, platform } from '@floating-ui/dom';\nimport * as React from 'react';\nimport { useLayoutEffect, useEffect } from 'react';\nimport * as ReactDOM from 'react-dom';\n\nvar index = typeof document !== 'undefined' ? useLayoutEffect : useEffect;\n\n// Fork of `fast-deep-equal` that only does the comparisons we need and compares\n// functions\nfunction deepEqual(a, b) {\n if (a === b) {\n return true;\n }\n if (typeof a !== typeof b) {\n return false;\n }\n if (typeof a === 'function' && a.toString() === b.toString()) {\n return true;\n }\n let length;\n let i;\n let keys;\n if (a && b && typeof a === 'object') {\n if (Array.isArray(a)) {\n length = a.length;\n if (length !== b.length) return false;\n for (i = length; i-- !== 0;) {\n if (!deepEqual(a[i], b[i])) {\n return false;\n }\n }\n return true;\n }\n keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length) {\n return false;\n }\n for (i = length; i-- !== 0;) {\n if (!{}.hasOwnProperty.call(b, keys[i])) {\n return false;\n }\n }\n for (i = length; i-- !== 0;) {\n const key = keys[i];\n if (key === '_owner' && a.$$typeof) {\n continue;\n }\n if (!deepEqual(a[key], b[key])) {\n return false;\n }\n }\n return true;\n }\n return a !== a && b !== b;\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\nfunction useLatestRef(value) {\n const ref = React.useRef(value);\n index(() => {\n ref.current = value;\n });\n return ref;\n}\n\n/**\n * Provides data to position a floating element.\n * @see https://floating-ui.com/docs/useFloating\n */\nfunction useFloating(options) {\n if (options === void 0) {\n options = {};\n }\n const {\n placement = 'bottom',\n strategy = 'absolute',\n middleware = [],\n platform,\n elements: {\n reference: externalReference,\n floating: externalFloating\n } = {},\n transform = true,\n whileElementsMounted,\n open\n } = options;\n const [data, setData] = React.useState({\n x: 0,\n y: 0,\n strategy,\n placement,\n middlewareData: {},\n isPositioned: false\n });\n const [latestMiddleware, setLatestMiddleware] = React.useState(middleware);\n if (!deepEqual(latestMiddleware, middleware)) {\n setLatestMiddleware(middleware);\n }\n const [_reference, _setReference] = React.useState(null);\n const [_floating, _setFloating] = React.useState(null);\n const setReference = React.useCallback(node => {\n if (node !== referenceRef.current) {\n referenceRef.current = node;\n _setReference(node);\n }\n }, []);\n const setFloating = React.useCallback(node => {\n if (node !== floatingRef.current) {\n floatingRef.current = node;\n _setFloating(node);\n }\n }, []);\n const referenceEl = externalReference || _reference;\n const floatingEl = externalFloating || _floating;\n const referenceRef = React.useRef(null);\n const floatingRef = React.useRef(null);\n const dataRef = React.useRef(data);\n const hasWhileElementsMounted = whileElementsMounted != null;\n const whileElementsMountedRef = useLatestRef(whileElementsMounted);\n const platformRef = useLatestRef(platform);\n const openRef = useLatestRef(open);\n const update = React.useCallback(() => {\n if (!referenceRef.current || !floatingRef.current) {\n return;\n }\n const config = {\n placement,\n strategy,\n middleware: latestMiddleware\n };\n if (platformRef.current) {\n config.platform = platformRef.current;\n }\n computePosition(referenceRef.current, floatingRef.current, config).then(data => {\n const fullData = {\n ...data,\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 isPositioned: openRef.current !== false\n };\n if (isMountedRef.current && !deepEqual(dataRef.current, fullData)) {\n dataRef.current = fullData;\n ReactDOM.flushSync(() => {\n setData(fullData);\n });\n }\n });\n }, [latestMiddleware, placement, strategy, platformRef, openRef]);\n index(() => {\n if (open === false && dataRef.current.isPositioned) {\n dataRef.current.isPositioned = false;\n setData(data => ({\n ...data,\n isPositioned: false\n }));\n }\n }, [open]);\n const isMountedRef = React.useRef(false);\n index(() => {\n isMountedRef.current = true;\n return () => {\n isMountedRef.current = false;\n };\n }, []);\n index(() => {\n if (referenceEl) referenceRef.current = referenceEl;\n if (floatingEl) floatingRef.current = floatingEl;\n if (referenceEl && floatingEl) {\n if (whileElementsMountedRef.current) {\n return whileElementsMountedRef.current(referenceEl, floatingEl, update);\n }\n update();\n }\n }, [referenceEl, floatingEl, update, whileElementsMountedRef, hasWhileElementsMounted]);\n const refs = React.useMemo(() => ({\n reference: referenceRef,\n floating: floatingRef,\n setReference,\n setFloating\n }), [setReference, setFloating]);\n const elements = React.useMemo(() => ({\n reference: referenceEl,\n floating: floatingEl\n }), [referenceEl, floatingEl]);\n const floatingStyles = React.useMemo(() => {\n const initialStyles = {\n position: strategy,\n left: 0,\n top: 0\n };\n if (!elements.floating) {\n return initialStyles;\n }\n const x = roundByDPR(elements.floating, data.x);\n const y = roundByDPR(elements.floating, data.y);\n if (transform) {\n return {\n ...initialStyles,\n transform: \"translate(\" + x + \"px, \" + y + \"px)\",\n ...(getDPR(elements.floating) >= 1.5 && {\n willChange: 'transform'\n })\n };\n }\n return {\n position: strategy,\n left: x,\n top: y\n };\n }, [strategy, transform, elements.floating, data.x, data.y]);\n return React.useMemo(() => ({\n ...data,\n update,\n refs,\n elements,\n floatingStyles\n }), [data, update, refs, elements, floatingStyles]);\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 * This wraps the core `arrow` middleware to allow React refs as the element.\n * @see https://floating-ui.com/docs/arrow\n */\nconst arrow$1 = options => {\n function isRef(value) {\n return {}.hasOwnProperty.call(value, 'current');\n }\n return {\n name: 'arrow',\n options,\n fn(state) {\n const {\n element,\n padding\n } = typeof options === 'function' ? options(state) : options;\n if (element && isRef(element)) {\n if (element.current != null) {\n return arrow$2({\n element: element.current,\n padding\n }).fn(state);\n }\n return {};\n }\n if (element) {\n return arrow$2({\n element,\n padding\n }).fn(state);\n }\n return {};\n }\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 = (options, deps) => ({\n ...offset$1(options),\n options: [options, deps]\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 = (options, deps) => ({\n ...shift$1(options),\n options: [options, deps]\n});\n\n/**\n * Built-in `limiter` that will stop `shift()` at a certain point.\n */\nconst limitShift = (options, deps) => ({\n ...limitShift$1(options),\n options: [options, deps]\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 = (options, deps) => ({\n ...flip$1(options),\n options: [options, deps]\n});\n\n/**\n * Provides data that allows you to change the size of the floating element \u2014\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 = (options, deps) => ({\n ...size$1(options),\n options: [options, deps]\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 = (options, deps) => ({\n ...autoPlacement$1(options),\n options: [options, deps]\n});\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 = (options, deps) => ({\n ...hide$1(options),\n options: [options, deps]\n});\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 = (options, deps) => ({\n ...inline$1(options),\n options: [options, deps]\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 * This wraps the core `arrow` middleware to allow React refs as the element.\n * @see https://floating-ui.com/docs/arrow\n */\nconst arrow = (options, deps) => ({\n ...arrow$1(options),\n options: [options, deps]\n});\n\nexport { arrow, autoPlacement, flip, hide, inline, limitShift, offset, shift, size, useFloating };\n", "import * as React from 'react';\nimport { Primitive } from '@radix-ui/react-primitive';\n\n/* -------------------------------------------------------------------------------------------------\n * Arrow\n * -----------------------------------------------------------------------------------------------*/\n\nconst NAME = 'Arrow';\n\ntype ArrowElement = React.ComponentRef<typeof Primitive.svg>;\ntype PrimitiveSvgProps = React.ComponentPropsWithoutRef<typeof Primitive.svg>;\ninterface ArrowProps extends PrimitiveSvgProps {}\n\nconst Arrow = React.forwardRef<ArrowElement, ArrowProps>((props, forwardedRef) => {\n const { children, width = 10, height = 5, ...arrowProps } = props;\n return (\n <Primitive.svg\n {...arrowProps}\n ref={forwardedRef}\n width={width}\n height={height}\n viewBox=\"0 0 30 10\"\n preserveAspectRatio=\"none\"\n >\n {/* We use their children if they're slotting to replace the whole svg */}\n {props.asChild ? children : <polygon points=\"0,0 30,0 15,10\" />}\n </Primitive.svg>\n );\n});\n\nArrow.displayName = NAME;\n\n/* -----------------------------------------------------------------------------------------------*/\n\nconst Root = Arrow;\n\nexport {\n Arrow,\n //\n Root,\n};\nexport type { ArrowProps };\n", "/// <reference types=\"resize-observer-browser\" />\n\nimport * as React from 'react';\nimport { useLayoutEffect } from '@radix-ui/react-use-layout-effect';\n\nfunction useSize(element: HTMLElement | null) {\n const [size, setSize] = React.useState<{ width: number; height: number } | undefined>(undefined);\n\n useLayoutEffect(() => {\n if (element) {\n // provide size as early as possible\n setSize({ width: element.offsetWidth, height: element.offsetHeight });\n\n const resizeObserver = new ResizeObserver((entries) => {\n if (!Array.isArray(entries)) {\n return;\n }\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\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) ? borderSizeEntry[0] : borderSizeEntry;\n width = borderSize['inlineSize'];\n height = borderSize['blockSize'];\n } else {\n // for browsers that don't support `borderBoxSize`\n // we calculate it ourselves to get the correct border box.\n width = element.offsetWidth;\n height = element.offsetHeight;\n }\n\n setSize({ width, height });\n });\n\n resizeObserver.observe(element, { box: 'border-box' });\n\n return () => resizeObserver.unobserve(element);\n } else {\n // We only want to reset to `undefined` when the element becomes `null`,\n // not if it changes to another element.\n setSize(undefined);\n }\n }, [element]);\n\n return size;\n}\n\nexport { useSize };\n", "import * as React from 'react';\nimport ReactDOM from 'react-dom';\nimport { Primitive } from '@radix-ui/react-primitive';\nimport { useLayoutEffect } from '@radix-ui/react-use-layout-effect';\n\n/* -------------------------------------------------------------------------------------------------\n * Portal\n * -----------------------------------------------------------------------------------------------*/\n\nconst PORTAL_NAME = 'Portal';\n\ntype PortalElement = React.ComponentRef<typeof Primitive.div>;\ntype PrimitiveDivProps = React.ComponentPropsWithoutRef<typeof Primitive.div>;\ninterface PortalProps extends PrimitiveDivProps {\n /**\n * An optional container where the portaled content should be appended.\n */\n container?: Element | DocumentFragment | null;\n}\n\nconst Portal = React.forwardRef<PortalElement, PortalProps>((props, forwardedRef) => {\n const { container: containerProp, ...portalProps } = props;\n const [mounted, setMounted] = React.useState(false);\n useLayoutEffect(() => setMounted(true), []);\n const container = containerProp || (mounted && globalThis?.document?.body);\n return container\n ? ReactDOM.createPortal(<Primitive.div {...portalProps} ref={forwardedRef} />, container)\n : null;\n});\n\nPortal.displayName = PORTAL_NAME;\n\n/* -----------------------------------------------------------------------------------------------*/\n\nconst Root = Portal;\n\nexport {\n Portal,\n //\n Root,\n};\nexport type { PortalProps };\n", "import * as React from 'react';\nimport { useComposedRefs } from '@radix-ui/react-compose-refs';\nimport { useLayoutEffect } from '@radix-ui/react-use-layout-effect';\nimport { useStateMachine } from './use-state-machine';\n\ninterface PresenceProps {\n children: React.ReactElement | ((props: { present: boolean }) => React.ReactElement);\n present: boolean;\n}\n\nconst Presence: React.FC<PresenceProps> = (props) => {\n const { present, children } = props;\n const presence = usePresence(present);\n\n const child = (\n typeof children === 'function'\n ? children({ present: presence.isPresent })\n : React.Children.only(children)\n ) as React.ReactElement<{ ref?: React.Ref<HTMLElement> }>;\n\n const ref = useComposedRefs(presence.ref, getElementRef(child));\n const forceMount = typeof children === 'function';\n return forceMount || presence.isPresent ? React.cloneElement(child, { ref }) : null;\n};\n\nPresence.displayName = 'Presence';\n\n/* -------------------------------------------------------------------------------------------------\n * usePresence\n * -----------------------------------------------------------------------------------------------*/\n\nfunction usePresence(present: boolean) {\n const [node, setNode] = React.useState<HTMLElement>();\n const stylesRef = React.useRef<CSSStyleDeclaration | null>(null);\n const prevPresentRef = React.useRef(present);\n const prevAnimationNameRef = React.useRef<string>('none');\n const initialState = present ? 'mounted' : 'unmounted';\n const [state, send] = 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 React.useEffect(() => {\n const currentAnimationName = getAnimationName(stylesRef.current);\n prevAnimationNameRef.current = state === 'mounted' ? currentAnimationName : 'none';\n }, [state]);\n\n useLayoutEffect(() => {\n const styles = stylesRef.current;\n const wasPresent = prevPresentRef.current;\n const hasPresentChanged = wasPresent !== present;\n\n if (hasPresentChanged) {\n const prevAnimationName = prevAnimationNameRef.current;\n const currentAnimationName = getAnimationName(styles);\n\n if (present) {\n send('MOUNT');\n } else if (currentAnimationName === 'none' || styles?.display === 'none') {\n // If there is no exit animation or the element is hidden, animations won't run\n // so we unmount instantly\n send('UNMOUNT');\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\n if (wasPresent && isAnimating) {\n send('ANIMATION_OUT');\n } else {\n send('UNMOUNT');\n }\n }\n\n prevPresentRef.current = present;\n }\n }, [present, send]);\n\n useLayoutEffect(() => {\n if (node) {\n let timeoutId: number;\n const ownerWindow = node.ownerDocument.defaultView ?? window;\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(stylesRef.current);\n // The event.animationName is unescaped for CSS syntax,\n // so we need to escape it to compare with the animationName computed from the style.\n const isCurrentAnimation = currentAnimationName.includes(CSS.escape(event.animationName));\n if (event.target === node && isCurrentAnimation) {\n // With React 18 concurrency this update is applied a frame after the\n // animation ends, creating a flash of visible content. By setting the\n // animation fill mode to \"forwards\", we force the node to keep the\n // styles of the last keyframe, removing the flash.\n //\n // Previously we flushed the update via ReactDom.flushSync, but with\n // exit animations this resulted in the node being removed from the\n // DOM before the synthetic animationEnd event was dispatched, meaning\n // user-provided event handlers would not be called.\n // https://github.com/radix-ui/primitives/pull/1849\n send('ANIMATION_END');\n if (!prevPresentRef.current) {\n const currentFillMode = node.style.animationFillMode;\n node.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.style.animationFillMode === 'forwards') {\n node.style.animationFillMode = currentFillMode;\n }\n });\n }\n }\n };\n const handleAnimationStart = (event: AnimationEvent) => {\n if (event.target === node) {\n // if animation occurred, store its name as the previous animation.\n prevAnimationNameRef.current = getAnimationName(stylesRef.current);\n }\n };\n node.addEventListener('animationstart', handleAnimationStart);\n node.addEventListener('animationcancel', handleAnimationEnd);\n node.addEventListener('animationend', handleAnimationEnd);\n return () => {\n ownerWindow.clearTimeout(timeoutId);\n node.removeEventListener('animationstart', handleAnimationStart);\n node.removeEventListener('animationcancel', handleAnimationEnd);\n node.removeEventListener('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 send('ANIMATION_END');\n }\n }, [node, send]);\n\n return {\n isPresent: ['mounted', 'unmountSuspended'].includes(state),\n ref: React.useCallback((node: HTMLElement) => {\n stylesRef.current = node ? getComputedStyle(node) : null;\n setNode(node);\n }, []),\n };\n}\n\n/* -----------------------------------------------------------------------------------------------*/\n\nfunction getAnimationName(styles: CSSStyleDeclaration | null) {\n return styles?.animationName || 'none';\n}\n\n// Before React 19 accessing `element.props.ref` will throw a warning and suggest using `element.ref`\n// After React 19 accessing `element.ref` does the opposite.\n// https://github.com/facebook/react/pull/28348\n//\n// Access the ref using the method that doesn't yield a warning.\nfunction getElementRef(element: React.ReactElement<{ ref?: React.Ref<unknown> }>) {\n // React <=18 in DEV\n let getter = Object.getOwnPropertyDescriptor(element.props, 'ref')?.get;\n let mayWarn = getter && 'isReactWarning' in getter && getter.isReactWarning;\n if (mayWarn) {\n return (element as any).ref;\n }\n\n // React 19 in DEV\n getter = Object.getOwnPropertyDescriptor(element, 'ref')?.get;\n mayWarn = getter && 'isReactWarning' in getter && getter.isReactWarning;\n if (mayWarn) {\n return element.props.ref;\n }\n\n // Not DEV\n return element.props.ref || (element as any).ref;\n}\n\nconst Root = Presence;\n\nexport {\n Presence,\n //\n Root,\n};\nexport type { PresenceProps };\n", "import * as React from 'react';\n\ntype Machine<S> = { [k: string]: { [k: string]: S } };\ntype MachineState<T> = keyof T;\ntype MachineEvent<T> = keyof UnionToIntersection<T[keyof T]>;\n\n// \uD83E\uDD2F https://fettblog.eu/typescript-union-to-intersection/\ntype UnionToIntersection<T> = (T extends any ? (x: T) => any : never) extends (x: infer R) => any\n ? R\n : never;\n\nexport function useStateMachine<M>(\n initialState: MachineState<M>,\n machine: M & Machine<MachineState<M>>\n) {\n return React.useReducer((state: MachineState<M>, event: MachineEvent<M>): MachineState<M> => {\n const nextState = (machine[state] as any)[event];\n return nextState ?? state;\n }, initialState);\n}\n", "import * as React from 'react';\nimport { useLayoutEffect } from '@radix-ui/react-use-layout-effect';\n\n// Prevent bundlers from trying to optimize the import\nconst useInsertionEffect: typeof useLayoutEffect =\n (React as any)[' useInsertionEffect '.trim().toString()] || useLayoutEffect;\n\ntype ChangeHandler<T> = (state: T) => void;\ntype SetStateFn<T> = React.Dispatch<React.SetStateAction<T>>;\n\ninterface UseControllableStateParams<T> {\n prop?: T | undefined;\n defaultProp: T;\n onChange?: ChangeHandler<T>;\n caller?: string;\n}\n\nexport function useControllableState<T>({\n prop,\n defaultProp,\n onChange = () => {},\n caller,\n}: UseControllableStateParams<T>): [T, SetStateFn<T>] {\n const [uncontrolledProp, setUncontrolledProp, onChangeRef] = useUncontrolledState({\n defaultProp,\n onChange,\n });\n const isControlled = prop !== undefined;\n const value = isControlled ? prop : uncontrolledProp;\n\n // OK to disable conditionally calling hooks here because they will always run\n // consistently in the same environment. Bundlers should be able to remove the\n // code block entirely in production.\n /* eslint-disable react-hooks/rules-of-hooks */\n if (process.env.NODE_ENV !== 'production') {\n const isControlledRef = React.useRef(prop !== undefined);\n React.useEffect(() => {\n const wasControlled = isControlledRef.current;\n if (wasControlled !== isControlled) {\n const from = wasControlled ? 'controlled' : 'uncontrolled';\n const to = isControlled ? 'controlled' : 'uncontrolled';\n console.warn(\n `${caller} is changing from ${from} to ${to}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`\n );\n }\n isControlledRef.current = isControlled;\n }, [isControlled, caller]);\n }\n /* eslint-enable react-hooks/rules-of-hooks */\n\n const setValue = React.useCallback<SetStateFn<T>>(\n (nextValue) => {\n if (isControlled) {\n const value = isFunction(nextValue) ? nextValue(prop) : nextValue;\n if (value !== prop) {\n onChangeRef.current?.(value);\n }\n } else {\n setUncontrolledProp(nextValue);\n }\n },\n [isControlled, prop, setUncontrolledProp, onChangeRef]\n );\n\n return [value, setValue];\n}\n\nfunction useUncontrolledState<T>({\n defaultProp,\n onChange,\n}: Omit<UseControllableStateParams<T>, 'prop'>): [\n Value: T,\n setValue: React.Dispatch<React.SetStateAction<T>>,\n OnChangeRef: React.RefObject<ChangeHandler<T> | undefined>,\n] {\n const [value, setValue] = React.useState(defaultProp);\n const prevValueRef = React.useRef(value);\n\n const onChangeRef = React.useRef(onChange);\n useInsertionEffect(() => {\n onChangeRef.current = onChange;\n }, [onChange]);\n\n React.useEffect(() => {\n if (prevValueRef.current !== value) {\n onChangeRef.current?.(value);\n prevValueRef.current = value;\n }\n }, [value, prevValueRef]);\n\n return [value, setValue, onChangeRef];\n}\n\nfunction isFunction(value: unknown): value is (...args: any[]) => any {\n return typeof value === 'function';\n}\n", "import * as React from 'react';\nimport { useEffectEvent } from '@radix-ui/react-use-effect-event';\n\ntype ChangeHandler<T> = (state: T) => void;\n\ninterface UseControllableStateParams<T> {\n prop: T | undefined;\n defaultProp: T;\n onChange: ChangeHandler<T> | undefined;\n caller: string;\n}\n\ninterface AnyAction {\n type: string;\n}\n\nconst SYNC_STATE = Symbol('RADIX:SYNC_STATE');\n\ninterface SyncStateAction<T> {\n type: typeof SYNC_STATE;\n state: T;\n}\n\nexport function useControllableStateReducer<T, S extends {}, A extends AnyAction>(\n reducer: (prevState: S & { state: T }, action: A) => S & { state: T },\n userArgs: UseControllableStateParams<T>,\n initialState: S\n): [S & { state: T }, React.Dispatch<A>];\n\nexport function useControllableStateReducer<T, S extends {}, I, A extends AnyAction>(\n reducer: (prevState: S & { state: T }, action: A) => S & { state: T },\n userArgs: UseControllableStateParams<T>,\n initialArg: I,\n init: (i: I & { state: T }) => S\n): [S & { state: T }, React.Dispatch<A>];\n\nexport function useControllableStateReducer<T, S extends {}, A extends AnyAction>(\n reducer: (prevState: S & { state: T }, action: A) => S & { state: T },\n userArgs: UseControllableStateParams<T>,\n initialArg: any,\n init?: (i: any) => Omit<S, 'state'>\n): [S & { state: T }, React.Dispatch<A>] {\n const { prop: controlledState, defaultProp, onChange: onChangeProp, caller } = userArgs;\n const isControlled = controlledState !== undefined;\n\n const onChange = useEffectEvent(onChangeProp);\n\n // OK to disable conditionally calling hooks here because they will always run\n // consistently in the same environment. Bundlers should be able to remove the\n // code block entirely in production.\n /* eslint-disable react-hooks/rules-of-hooks */\n if (process.env.NODE_ENV !== 'production') {\n const isControlledRef = React.useRef(controlledState !== undefined);\n React.useEffect(() => {\n const wasControlled = isControlledRef.current;\n if (wasControlled !== isControlled) {\n const from = wasControlled ? 'controlled' : 'uncontrolled';\n const to = isControlled ? 'controlled' : 'uncontrolled';\n console.warn(\n `${caller} is changing from ${from} to ${to}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`\n );\n }\n isControlledRef.current = isControlled;\n }, [isControlled, caller]);\n }\n /* eslint-enable react-hooks/rules-of-hooks */\n\n type InternalState = S & { state: T };\n const args: [InternalState] = [{ ...initialArg, state: defaultProp }];\n if (init) {\n // @ts-expect-error\n args.push(init);\n }\n\n const [internalState, dispatch] = React.useReducer(\n (state: InternalState, action: A | SyncStateAction<T>): InternalState => {\n if (action.type === SYNC_STATE) {\n return { ...state, state: action.state };\n }\n\n const next = reducer(state, action);\n if (isControlled && !Object.is(next.state, state.state)) {\n onChange(next.state);\n }\n return next;\n },\n ...args\n );\n\n const uncontrolledState = internalState.state;\n const prevValueRef = React.useRef(uncontrolledState);\n React.useEffect(() => {\n if (prevValueRef.current !== uncontrolledState) {\n prevValueRef.current = uncontrolledState;\n if (!isControlled) {\n onChange(uncontrolledState);\n }\n }\n }, [onChange, uncontrolledState, prevValueRef, isControlled]);\n\n const state = React.useMemo(() => {\n const isControlled = controlledState !== undefined;\n if (isControlled) {\n return { ...internalState, state: controlledState };\n }\n\n return internalState;\n }, [internalState, controlledState]);\n\n React.useEffect(() => {\n // Sync internal state for controlled components so that reducer is called\n // with the correct state values\n if (isControlled && !Object.is(controlledState, internalState.state)) {\n dispatch({ type: SYNC_STATE, state: controlledState });\n }\n }, [controlledState, internalState.state, isControlled]);\n\n return [state, dispatch as React.Dispatch<A>];\n}\n", "import * as React from 'react';\nimport { Primitive } from '@radix-ui/react-primitive';\n\n/* -------------------------------------------------------------------------------------------------\n * VisuallyHidden\n * -----------------------------------------------------------------------------------------------*/\n\nconst VISUALLY_HIDDEN_STYLES = Object.freeze({\n // See: https://github.com/twbs/bootstrap/blob/main/scss/mixins/_visually-hidden.scss\n position: 'absolute',\n border: 0,\n width: 1,\n height: 1,\n padding: 0,\n margin: -1,\n overflow: 'hidden',\n clip: 'rect(0, 0, 0, 0)',\n whiteSpace: 'nowrap',\n wordWrap: 'normal',\n}) satisfies React.CSSProperties;\n\nconst NAME = 'VisuallyHidden';\n\ntype VisuallyHiddenElement = React.ComponentRef<typeof Primitive.span>;\ntype PrimitiveSpanProps = React.ComponentPropsWithoutRef<typeof Primitive.span>;\ninterface VisuallyHiddenProps extends PrimitiveSpanProps {}\n\nconst VisuallyHidden = React.forwardRef<VisuallyHiddenElement, VisuallyHiddenProps>(\n (props, forwardedRef) => {\n return (\n <Primitive.span\n {...props}\n ref={forwardedRef}\n style={{ ...VISUALLY_HIDDEN_STYLES, ...props.style }}\n />\n );\n }\n);\n\nVisuallyHidden.displayName = NAME;\n\n/* -----------------------------------------------------------------------------------------------*/\n\nconst Root = VisuallyHidden;\n\nexport {\n VisuallyHidden,\n //\n Root,\n //\n VISUALLY_HIDDEN_STYLES,\n};\nexport type { VisuallyHiddenProps };\n", "\"use client\";\n\nimport { cn } from \"@stackframe/stack-ui\";\n\nexport type DesignSeparatorProps = {\n orientation?: \"horizontal\" | \"vertical\",\n} & React.HTMLAttributes<HTMLDivElement>;\n\nexport function DesignSeparator({\n orientation = \"horizontal\",\n className,\n ...props\n}: DesignSeparatorProps) {\n return (\n <div\n role=\"separator\"\n aria-orientation={orientation}\n className={cn(\n orientation === \"horizontal\"\n ? \"h-[1px] w-full bg-black/[0.08] dark:bg-white/[0.06]\"\n : \"w-[1px] h-full bg-black/[0.08] dark:bg-white/[0.06]\",\n className\n )}\n {...props}\n />\n );\n}\n", "\"use client\";\n\nimport { cn } from \"@stackframe/stack-ui\";\nimport type React from \"react\";\n\nexport type DesignSkeletonProps = React.HTMLAttributes<HTMLDivElement>;\n\nexport function DesignSkeleton({ className, ...props }: DesignSkeletonProps) {\n return (\n <div\n className={cn(\n \"animate-pulse rounded-md bg-black/[0.06] dark:bg-white/[0.06]\",\n className\n )}\n {...props}\n />\n );\n}\n", "\"use client\";\n\nimport { forwardRefIfNeeded } from \"@stackframe/stack-shared/dist/utils/react\";\nimport { cn } from \"@stackframe/stack-ui\";\nimport React from \"react\";\n\nexport const DesignTable = forwardRefIfNeeded<\n HTMLTableElement,\n React.HTMLAttributes<HTMLTableElement>\n>(({ className, ...props }, ref) => (\n <div className=\"relative w-full overflow-auto\">\n <table\n ref={ref}\n className={cn(\"w-full caption-bottom text-sm\", className)}\n {...props}\n />\n </div>\n));\nDesignTable.displayName = \"DesignTable\";\n\nexport const DesignTableHeader = forwardRefIfNeeded<\n HTMLTableSectionElement,\n React.HTMLAttributes<HTMLTableSectionElement>\n>(({ className, ...props }, ref) => (\n <thead\n ref={ref}\n className={cn(\"bg-foreground/[0.02] [&_tr]:border-b [&_tr]:border-black/[0.06] dark:[&_tr]:border-white/[0.06]\", className)}\n {...props}\n />\n));\nDesignTableHeader.displayName = \"DesignTableHeader\";\n\nexport const DesignTableBody = forwardRefIfNeeded<\n HTMLTableSectionElement,\n React.HTMLAttributes<HTMLTableSectionElement>\n>(({ className, ...props }, ref) => (\n <tbody\n ref={ref}\n className={cn(\"[&_tr:last-child]:border-0\", className)}\n {...props}\n />\n));\nDesignTableBody.displayName = \"DesignTableBody\";\n\nexport const DesignTableRow = forwardRefIfNeeded<\n HTMLTableRowElement,\n React.HTMLAttributes<HTMLTableRowElement>\n>(({ className, ...props }, ref) => (\n <tr\n ref={ref}\n className={cn(\n \"border-b border-black/[0.06] dark:border-white/[0.06] transition-colors duration-150 hover:transition-none hover:bg-foreground/[0.04] data-[state=selected]:bg-foreground/[0.06]\",\n className\n )}\n {...props}\n />\n));\nDesignTableRow.displayName = \"DesignTableRow\";\n\nexport const DesignTableHead = forwardRefIfNeeded<\n HTMLTableCellElement,\n React.ThHTMLAttributes<HTMLTableCellElement>\n>(({ className, ...props }, ref) => (\n <th\n ref={ref}\n className={cn(\n \"h-10 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]\",\n className\n )}\n {...props}\n />\n));\nDesignTableHead.displayName = \"DesignTableHead\";\n\nexport const DesignTableCell = forwardRefIfNeeded<\n HTMLTableCellElement,\n React.TdHTMLAttributes<HTMLTableCellElement>\n>(({ className, ...props }, ref) => (\n <td\n ref={ref}\n className={cn(\n \"p-4 align-middle [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]\",\n className\n )}\n {...props}\n />\n));\nDesignTableCell.displayName = \"DesignTableCell\";\n", "\"use client\";\n\nimport { useState } from \"react\";\nimport { cn, Spinner } from \"@stackframe/stack-ui\";\nimport { runAsynchronouslyWithAlert } from \"@stackframe/stack-shared/dist/utils/promises\";\nimport { useGlassmorphicDefault } from \"./card\";\n\ntype DesignTabsSize = \"sm\" | \"md\";\ntype DesignTabsGradient = \"blue\" | \"cyan\" | \"purple\" | \"green\" | \"orange\" | \"default\";\n\nexport type DesignCategoryTabItem = {\n id: string,\n label: string,\n count?: number,\n badgeCount?: number,\n};\n\nexport type DesignCategoryTabsProps = Omit<React.ComponentProps<\"div\">, \"onSelect\"> & {\n categories: DesignCategoryTabItem[],\n selectedCategory: string,\n onSelect: (id: string) => void | Promise<void>,\n showBadge?: boolean,\n size?: DesignTabsSize,\n glassmorphic?: boolean,\n gradient?: DesignTabsGradient,\n};\n\ntype TabSizeClass = {\n button: string,\n badge: string,\n};\n\ntype GradientClass = {\n activeText: string,\n activeBadge: string,\n underline: string,\n};\n\nconst tabSizeClasses = new Map<DesignTabsSize, TabSizeClass>([\n [\"sm\", { button: \"px-3 py-2 text-xs\", badge: \"text-[10px] px-1.5 py-0.5\" }],\n [\"md\", { button: \"px-4 py-3 text-sm\", badge: \"text-xs px-1.5 py-0.5\" }],\n]);\n\nconst gradientClasses = new Map<DesignTabsGradient, GradientClass>([\n [\n \"blue\",\n {\n activeText: \"text-blue-700 dark:text-blue-400\",\n activeBadge: \"bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400\",\n underline: \"bg-blue-700 dark:bg-blue-400\",\n },\n ],\n [\n \"cyan\",\n {\n activeText: \"text-cyan-700 dark:text-cyan-300\",\n activeBadge: \"bg-cyan-100 dark:bg-cyan-900/30 text-cyan-700 dark:text-cyan-300\",\n underline: \"bg-cyan-600 dark:bg-cyan-400\",\n },\n ],\n [\n \"purple\",\n {\n activeText: \"text-purple-700 dark:text-purple-300\",\n activeBadge: \"bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300\",\n underline: \"bg-purple-600 dark:bg-purple-400\",\n },\n ],\n [\n \"green\",\n {\n activeText: \"text-emerald-700 dark:text-emerald-300\",\n activeBadge: \"bg-emerald-100 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-300\",\n underline: \"bg-emerald-600 dark:bg-emerald-400\",\n },\n ],\n [\n \"orange\",\n {\n activeText: \"text-amber-700 dark:text-amber-300\",\n activeBadge: \"bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-300\",\n underline: \"bg-amber-600 dark:bg-amber-400\",\n },\n ],\n [\n \"default\",\n {\n activeText: \"text-foreground\",\n activeBadge: \"bg-foreground/10 text-foreground\",\n underline: \"bg-foreground/80\",\n },\n ],\n]);\n\nfunction getMapValueOrThrow<TKey, TValue>(map: Map<TKey, TValue>, key: TKey, mapName: string) {\n const value = map.get(key);\n if (!value) {\n throw new Error(`Missing ${mapName} entry for key \"${String(key)}\"`);\n }\n return value;\n}\n\nexport function DesignCategoryTabs({\n categories,\n selectedCategory,\n onSelect,\n showBadge = true,\n size = \"sm\",\n glassmorphic: glassmorphicProp,\n gradient = \"blue\",\n className,\n ...props\n}: DesignCategoryTabsProps) {\n const glassmorphic = useGlassmorphicDefault(glassmorphicProp);\n const sizeClass = getMapValueOrThrow(tabSizeClasses, size, \"tabSizeClasses\");\n const gradientClass = getMapValueOrThrow(gradientClasses, gradient, \"gradientClasses\");\n const [loadingCategoryId, setLoadingCategoryId] = useState<string | null>(null);\n\n const handleSelect = (categoryId: string) => {\n const result = onSelect(categoryId);\n if (result && typeof (result as Promise<void>).then === \"function\") {\n setLoadingCategoryId(categoryId);\n runAsynchronouslyWithAlert(\n Promise.resolve(result).finally(() => setLoadingCategoryId(null))\n );\n }\n };\n\n return (\n <div\n className={cn(\n \"flex items-center gap-1 overflow-x-auto flex-nowrap [&::-webkit-scrollbar]:hidden\",\n glassmorphic\n ? \"rounded-xl bg-black/[0.08] dark:bg-white/[0.04] p-1 backdrop-blur-sm\"\n : \"border-b border-gray-300 dark:border-gray-800\",\n className\n )}\n {...props}\n >\n {categories.map((category) => {\n const isActive = selectedCategory === category.id;\n const badgeValue = category.badgeCount ?? category.count;\n const shouldShowBadge = showBadge && badgeValue !== undefined;\n\n return (\n <button\n key={category.id}\n onClick={() => handleSelect(category.id)}\n disabled={loadingCategoryId !== null}\n className={cn(\n \"font-medium transition-all duration-150 hover:transition-none relative flex flex-shrink-0 items-center justify-center gap-2 whitespace-nowrap\",\n \"hover:text-gray-900 dark:hover:text-gray-100\",\n sizeClass.button,\n glassmorphic ? \"rounded-lg\" : \"\",\n isActive\n ? cn(\n gradientClass.activeText,\n glassmorphic && \"bg-background shadow-sm ring-1 ring-black/[0.12] dark:ring-white/[0.06]\"\n )\n : \"text-gray-700 dark:text-gray-400\"\n )}\n >\n {loadingCategoryId === category.id && (\n <Spinner\n size={12}\n className=\"absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 pointer-events-none\"\n />\n )}\n <span className={cn(\n \"flex items-center gap-2\",\n loadingCategoryId === category.id && \"invisible\"\n )}>\n {category.label}\n {shouldShowBadge && (\n <span\n className={cn(\n \"rounded-full\",\n sizeClass.badge,\n isActive\n ? gradientClass.activeBadge\n : \"bg-gray-200 dark:bg-gray-800 text-gray-600 dark:text-gray-400\"\n )}\n >\n {badgeValue}\n </span>\n )}\n </span>\n {!glassmorphic && isActive && (\n <div className={cn(\"absolute bottom-0 left-0 right-0 h-0.5\", gradientClass.underline)} />\n )}\n </button>\n );\n })}\n </div>\n );\n}\n", "\"use client\";\n\nexport type DesignChartColorEntry = {\n light: string,\n dark: string,\n};\n\n/**\n * Design-system-consistent chart colors that work in light and dark mode.\n * Maps to the gradient system used across the dashboard design components.\n */\nexport const DESIGN_CHART_COLORS: readonly DesignChartColorEntry[] = [\n { light: \"hsl(221, 83%, 53%)\", dark: \"hsl(217, 91%, 60%)\" }, // blue\n { light: \"hsl(192, 91%, 36%)\", dark: \"hsl(188, 94%, 43%)\" }, // cyan\n { light: \"hsl(271, 91%, 65%)\", dark: \"hsl(270, 95%, 75%)\" }, // purple\n { light: \"hsl(160, 84%, 39%)\", dark: \"hsl(160, 84%, 45%)\" }, // emerald/green\n { light: \"hsl(38, 92%, 50%)\", dark: \"hsl(38, 92%, 50%)\" }, // amber/orange\n { light: \"hsl(0, 84%, 60%)\", dark: \"hsl(0, 84%, 65%)\" }, // red\n] as const;\n\nexport type DesignChartColorName = \"blue\" | \"cyan\" | \"purple\" | \"green\" | \"orange\" | \"red\";\n\nconst colorNameIndexMap = new Map<DesignChartColorName, number>([\n [\"blue\", 0],\n [\"cyan\", 1],\n [\"purple\", 2],\n [\"green\", 3],\n [\"orange\", 4],\n [\"red\", 5],\n]);\n\n/**\n * Get a chart color by index (wraps around) or by name.\n */\nexport function getDesignChartColor(\n indexOrName: number | DesignChartColorName,\n mode: \"light\" | \"dark\" = \"dark\",\n): string {\n const index = typeof indexOrName === \"string\"\n ? colorNameIndexMap.get(indexOrName) ?? 0\n : indexOrName % DESIGN_CHART_COLORS.length;\n return DESIGN_CHART_COLORS[index][mode];\n}\n\n/**\n * Recharts-compatible grid/axis styling constants that match the design system.\n */\nexport const DESIGN_CHART_GRID_COLOR = \"hsl(0 0% 50% / 0.12)\";\nexport const DESIGN_CHART_AXIS_TICK_STYLE = {\n fill: \"hsl(0 0% 50% / 0.5)\",\n fontSize: 11,\n} as const;\n", "\"use client\";\n\nimport * as React from \"react\";\nimport * as RechartsPrimitive from \"recharts\";\nimport { cn } from \"@stackframe/stack-ui\";\n\nconst THEMES = { light: \"\", dark: \".dark\" } as const;\n\nexport type DesignChartConfig = {\n [k in string]: {\n label?: React.ReactNode,\n icon?: React.ComponentType,\n } & (\n | { color?: string, theme?: never }\n | { color?: never, theme: Record<keyof typeof THEMES, string> }\n )\n};\n\ntype ChartContextProps = {\n config: DesignChartConfig,\n};\n\nconst ChartContext = React.createContext<ChartContextProps | null>(null);\n\nexport function useDesignChart() {\n const context = React.useContext(ChartContext);\n if (!context) {\n throw new Error(\"useDesignChart must be used within a <DesignChartContainer />\");\n }\n return context;\n}\n\nexport function DesignChartStyle({ id, config }: { id: string, config: DesignChartConfig }) {\n const colorConfig = Object.entries(config).filter(\n ([_, cfg]) => cfg.theme || cfg.color\n );\n\n if (!colorConfig.length) {\n return null;\n }\n\n return (\n <style\n dangerouslySetInnerHTML={{\n __html: Object.entries(THEMES)\n .map(\n ([theme, prefix]) => `\n${prefix} [data-chart=${id}] {\n${colorConfig\n .map(([key, itemConfig]) => {\n const color =\n itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ||\n itemConfig.color;\n return color ? ` --color-${key}: ${color};` : null;\n })\n .join(\"\\n\")}\n}\n`\n )\n .join(\"\\n\"),\n }}\n />\n );\n}\n\nexport const DesignChartContainer = React.forwardRef<\n HTMLDivElement,\n React.ComponentProps<\"div\"> & {\n maxHeight?: number,\n config: DesignChartConfig,\n children: React.ComponentProps<\n typeof RechartsPrimitive.ResponsiveContainer\n >[\"children\"],\n }\n>(({ id, className, children, config, maxHeight, ...props }, ref) => {\n const uniqueId = React.useId();\n const chartId = `chart-${id || uniqueId.replace(/:/g, \"\")}`;\n\n return (\n <ChartContext.Provider value={{ config }}>\n <div\n data-chart={chartId}\n ref={ref}\n className={cn(\n \"flex aspect-video justify-center text-xs\",\n \"[&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground\",\n \"[&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-black/[0.06] dark:[&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-white/[0.06]\",\n \"[&_.recharts-curve.recharts-tooltip-cursor]:stroke-black/[0.12] dark:[&_.recharts-curve.recharts-tooltip-cursor]:stroke-white/[0.12]\",\n \"[&_.recharts-dot[stroke='#fff']]:stroke-transparent\",\n \"[&_.recharts-layer]:outline-none\",\n \"[&_.recharts-polar-grid_[stroke='#ccc']]:stroke-black/[0.06] dark:[&_.recharts-polar-grid_[stroke='#ccc']]:stroke-white/[0.06]\",\n \"[&_.recharts-radial-bar-background-sector]:fill-black/[0.04] dark:[&_.recharts-radial-bar-background-sector]:fill-white/[0.04]\",\n \"[&_.recharts-rectangle.recharts-tooltip-cursor]:fill-black/[0.04] dark:[&_.recharts-rectangle.recharts-tooltip-cursor]:fill-white/[0.04]\",\n \"[&_.recharts-reference-line_[stroke='#ccc']]:stroke-black/[0.06] dark:[&_.recharts-reference-line_[stroke='#ccc']]:stroke-white/[0.06]\",\n \"[&_.recharts-sector[stroke='#fff']]:stroke-transparent\",\n \"[&_.recharts-sector]:outline-none\",\n \"[&_.recharts-surface]:outline-none\",\n className\n )}\n {...props}\n style={{\n ...props.style,\n maxHeight,\n }}\n >\n <DesignChartStyle id={chartId} config={config} />\n <RechartsPrimitive.ResponsiveContainer maxHeight={maxHeight}>\n {children}\n </RechartsPrimitive.ResponsiveContainer>\n </div>\n </ChartContext.Provider>\n );\n});\nDesignChartContainer.displayName = \"DesignChartContainer\";\n\n/**\n * Helper to extract item config from a Recharts payload object.\n */\nexport function getPayloadConfigFromPayload(\n config: DesignChartConfig,\n payload: unknown,\n key: string,\n) {\n if (typeof payload !== \"object\" || payload === null) {\n return undefined;\n }\n\n const payloadPayload =\n \"payload\" in payload &&\n typeof payload.payload === \"object\" &&\n payload.payload !== null\n ? payload.payload\n : undefined;\n\n let configLabelKey: string = key;\n\n if (\n key in payload &&\n typeof payload[key as keyof typeof payload] === \"string\"\n ) {\n configLabelKey = payload[key as keyof typeof payload] as string;\n } else if (\n payloadPayload &&\n key in payloadPayload &&\n typeof payloadPayload[key as keyof typeof payloadPayload] === \"string\"\n ) {\n configLabelKey = payloadPayload[\n key as keyof typeof payloadPayload\n ] as string;\n }\n\n return configLabelKey in config\n ? config[configLabelKey]\n : config[key as keyof typeof config];\n}\n", "\"use client\";\n\nimport * as React from \"react\";\nimport * as RechartsPrimitive from \"recharts\";\nimport { cn } from \"@stackframe/stack-ui\";\nimport { useDesignChart, getPayloadConfigFromPayload } from \"./chart-container\";\n\nexport const DesignChartTooltip = RechartsPrimitive.Tooltip;\n\nexport const DesignChartTooltipContent = React.forwardRef<\n HTMLDivElement,\n React.ComponentProps<typeof RechartsPrimitive.Tooltip> &\n React.ComponentProps<\"div\"> & {\n hideLabel?: boolean,\n hideIndicator?: boolean,\n indicator?: \"line\" | \"dot\" | \"dashed\",\n nameKey?: string,\n labelKey?: string,\n }\n>(\n (\n {\n active,\n payload,\n className,\n indicator = \"dot\",\n hideLabel = false,\n hideIndicator = false,\n label,\n labelFormatter,\n labelClassName,\n formatter,\n color,\n nameKey,\n labelKey,\n },\n ref\n ) => {\n const { config } = useDesignChart();\n\n const tooltipLabel = React.useMemo(() => {\n if (hideLabel || !payload?.length) {\n return null;\n }\n\n const [item] = payload;\n const key = `${labelKey || item.dataKey || item.name || \"value\"}`;\n const itemConfig = getPayloadConfigFromPayload(config, item, key);\n const configEntry = typeof label === \"string\" ? config[label as keyof typeof config] : undefined;\n const value =\n !labelKey && typeof label === \"string\"\n ? configEntry?.label ?? label\n : itemConfig?.label;\n\n if (labelFormatter) {\n return (\n <div className={cn(\"font-medium text-muted-foreground tracking-wide\", labelClassName)}>\n {labelFormatter(value, payload)}\n </div>\n );\n }\n\n if (!value) {\n return null;\n }\n\n return <div className={cn(\"font-medium text-muted-foreground tracking-wide\", labelClassName)}>{value}</div>;\n }, [\n label,\n labelFormatter,\n payload,\n hideLabel,\n labelClassName,\n config,\n labelKey,\n ]);\n\n if (!active || !payload?.length) {\n return null;\n }\n\n const nestLabel = payload.length === 1 && indicator !== \"dot\";\n\n return (\n <div\n ref={ref}\n className={cn(\n \"grid min-w-[8rem] items-start gap-1.5 rounded-xl bg-background/95 px-3.5 py-2.5 text-xs shadow-lg backdrop-blur-xl ring-1 ring-foreground/[0.08]\",\n className\n )}\n style={{ zIndex: 9999 }}\n >\n {!nestLabel ? tooltipLabel : null}\n <div className=\"grid gap-1.5\">\n {payload.map((item, index) => {\n const key = `${nameKey || item.name || item.dataKey || \"value\"}`;\n const itemConfig = getPayloadConfigFromPayload(config, item, key);\n const indicatorColor = color || item.payload.fill || item.color;\n\n return (\n <div\n key={item.dataKey}\n className={cn(\n \"flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground\",\n indicator === \"dot\" && \"items-center\"\n )}\n >\n {formatter && item.value !== undefined && item.name ? (\n formatter(item.value, item.name, item, index, item.payload)\n ) : (\n <>\n {itemConfig?.icon ? (\n <itemConfig.icon />\n ) : (\n !hideIndicator && (\n <div\n className={cn(\n \"shrink-0 rounded-full\",\n {\n \"h-2 w-2 ring-2 ring-white/20\": indicator === \"dot\",\n \"w-1 rounded-[2px]\": indicator === \"line\",\n \"w-0 border-[1.5px] border-dashed bg-transparent rounded-[2px]\":\n indicator === \"dashed\",\n \"my-0.5\": nestLabel && indicator === \"dashed\",\n }\n )}\n style={\n {\n \"--color-bg\": indicatorColor,\n \"--color-border\": indicatorColor,\n backgroundColor: indicator === \"dot\" ? indicatorColor : undefined,\n } as React.CSSProperties\n }\n />\n )\n )}\n <div\n className={cn(\n \"flex flex-1 justify-between leading-none\",\n nestLabel ? \"items-end\" : \"items-center\"\n )}\n >\n <div className=\"grid gap-1.5\">\n {nestLabel ? tooltipLabel : null}\n <span className=\"text-[11px] text-muted-foreground\">\n {itemConfig?.label || item.name}\n </span>\n </div>\n {item.value != null && (\n <span className=\"ml-auto font-mono text-xs font-semibold tabular-nums text-foreground\">\n {typeof item.value === \"number\" ? item.value.toLocaleString() : item.value}\n </span>\n )}\n </div>\n </>\n )}\n </div>\n );\n })}\n </div>\n </div>\n );\n }\n);\nDesignChartTooltipContent.displayName = \"DesignChartTooltipContent\";\n", "\"use client\";\n\nimport * as React from \"react\";\nimport * as RechartsPrimitive from \"recharts\";\nimport { cn } from \"@stackframe/stack-ui\";\nimport { useDesignChart, getPayloadConfigFromPayload } from \"./chart-container\";\n\nexport const DesignChartLegend = RechartsPrimitive.Legend;\n\nexport const DesignChartLegendContent = React.forwardRef<\n HTMLDivElement,\n React.ComponentProps<\"div\"> &\n Pick<RechartsPrimitive.LegendProps, \"payload\" | \"verticalAlign\"> & {\n hideIcon?: boolean,\n nameKey?: string,\n }\n>(\n (\n { className, hideIcon = false, payload, verticalAlign = \"bottom\", nameKey },\n ref\n ) => {\n const { config } = useDesignChart();\n\n if (!payload?.length) {\n return null;\n }\n\n return (\n <div\n ref={ref}\n className={cn(\n \"flex flex-wrap items-center justify-center gap-2\",\n verticalAlign === \"top\" ? \"pb-3\" : \"pt-3\",\n className\n )}\n >\n {payload.map((item) => {\n const key = `${nameKey || item.dataKey || \"value\"}`;\n const itemConfig = getPayloadConfigFromPayload(config, item, key);\n\n return (\n <div\n key={item.value}\n className={cn(\n \"flex items-center gap-1.5 rounded-full bg-foreground/[0.03] ring-1 ring-foreground/[0.06] px-3 py-1.5 text-xs\",\n \"transition-colors duration-150 hover:transition-none hover:bg-foreground/[0.05]\"\n )}\n >\n {itemConfig?.icon && !hideIcon ? (\n <itemConfig.icon />\n ) : (\n <span\n className=\"h-2 w-2 shrink-0 rounded-full\"\n style={{ backgroundColor: item.color }}\n />\n )}\n <span className=\"font-medium text-foreground\">\n {itemConfig?.label || item.value}\n </span>\n </div>\n );\n })}\n </div>\n );\n }\n);\nDesignChartLegendContent.displayName = \"DesignChartLegendContent\";\n", "\"use client\";\n\nimport { cn } from \"@stackframe/stack-ui\";\nimport React from \"react\";\n\ntype DesignChartCardGradient = \"blue\" | \"cyan\" | \"purple\" | \"green\" | \"orange\" | \"default\";\n\nconst hoverTintClasses = new Map<DesignChartCardGradient, string>([\n [\"blue\", \"group-hover:bg-blue-500/[0.03]\"],\n [\"cyan\", \"group-hover:bg-cyan-500/[0.03]\"],\n [\"purple\", \"group-hover:bg-purple-500/[0.03]\"],\n [\"green\", \"group-hover:bg-emerald-500/[0.03]\"],\n [\"orange\", \"group-hover:bg-orange-500/[0.03]\"],\n [\"default\", \"group-hover:bg-slate-500/[0.02]\"],\n]);\n\nexport type DesignChartCardProps = {\n gradient?: DesignChartCardGradient,\n title?: React.ReactNode,\n description?: React.ReactNode,\n} & Omit<React.ComponentProps<\"div\">, \"title\">;\n\nexport function DesignChartCard({\n gradient = \"default\",\n title,\n description,\n className,\n children,\n ...props\n}: DesignChartCardProps) {\n const hoverTintClass = hoverTintClasses.get(gradient) ?? \"group-hover:bg-slate-500/[0.02]\";\n\n return (\n <>\n <style dangerouslySetInnerHTML={{ __html: `\n .design-chart-card-tooltip-escape .recharts-tooltip-wrapper {\n z-index: 9999 !important;\n overflow: visible !important;\n }\n .design-chart-card-tooltip-escape .recharts-tooltip-wrapper > * {\n overflow: visible !important;\n }\n ` }} />\n <div\n className={cn(\n \"group relative rounded-2xl bg-white/90 dark:bg-background/60 backdrop-blur-xl transition-all duration-150 hover:transition-none design-chart-card-tooltip-escape\",\n \"ring-1 ring-black/[0.06] hover:ring-black/[0.1] dark:ring-white/[0.06] dark:hover:ring-white/[0.1]\",\n \"shadow-sm hover:shadow-md hover:z-10\",\n className\n )}\n {...props}\n >\n <div className=\"absolute inset-0 bg-gradient-to-br from-foreground/[0.04] dark:from-foreground/[0.02] to-transparent pointer-events-none rounded-2xl overflow-hidden\" />\n <div\n className={cn(\n \"absolute inset-0 transition-colors duration-150 group-hover:transition-none pointer-events-none rounded-2xl overflow-hidden\",\n hoverTintClass\n )}\n />\n <div className=\"relative h-full flex flex-col p-4\">\n {(title || description) && (\n <div className=\"mb-3\">\n {title && <h3 className=\"text-sm font-semibold text-foreground\">{title}</h3>}\n {description && <p className=\"text-xs text-muted-foreground mt-0.5\">{description}</p>}\n </div>\n )}\n {children}\n </div>\n </div>\n </>\n );\n}\n", "\"use client\";\n\nimport { cn } from \"@stackframe/stack-ui\";\nimport React from \"react\";\n\ntype DesignMetricCardGradient = \"blue\" | \"cyan\" | \"purple\" | \"green\" | \"orange\" | \"default\";\n\nconst hoverTintClasses = new Map<DesignMetricCardGradient, string>([\n [\"blue\", \"group-hover:bg-blue-500/[0.03]\"],\n [\"cyan\", \"group-hover:bg-cyan-500/[0.03]\"],\n [\"purple\", \"group-hover:bg-purple-500/[0.03]\"],\n [\"green\", \"group-hover:bg-emerald-500/[0.03]\"],\n [\"orange\", \"group-hover:bg-orange-500/[0.03]\"],\n [\"default\", \"group-hover:bg-slate-500/[0.02]\"],\n]);\n\nexport type DesignMetricCardTrend = {\n value: number,\n direction: \"up\" | \"down\",\n label?: string,\n};\n\nexport type DesignMetricCardProps = {\n label: string,\n value: string | number,\n description?: string,\n trend?: DesignMetricCardTrend,\n icon?: React.ElementType,\n gradient?: DesignMetricCardGradient,\n} & Omit<React.ComponentProps<\"div\">, \"children\">;\n\nexport function DesignMetricCard({\n label,\n value,\n description,\n trend,\n icon: Icon,\n gradient = \"default\",\n className,\n ...props\n}: DesignMetricCardProps) {\n const hoverTintClass = hoverTintClasses.get(gradient) ?? \"group-hover:bg-slate-500/[0.02]\";\n\n return (\n <div\n className={cn(\n \"group relative rounded-2xl bg-white/90 dark:bg-background/60 backdrop-blur-xl transition-all duration-150 hover:transition-none overflow-hidden\",\n \"ring-1 ring-black/[0.06] hover:ring-black/[0.1] dark:ring-white/[0.06] dark:hover:ring-white/[0.1]\",\n \"shadow-sm hover:shadow-md\",\n className\n )}\n {...props}\n >\n <div className=\"absolute inset-0 bg-gradient-to-br from-foreground/[0.04] dark:from-foreground/[0.02] to-transparent pointer-events-none rounded-2xl\" />\n <div\n className={cn(\n \"absolute inset-0 transition-colors duration-150 group-hover:transition-none pointer-events-none rounded-2xl\",\n hoverTintClass\n )}\n />\n <div className=\"relative p-5\">\n <div className=\"flex items-start justify-between gap-3\">\n <div className=\"flex-1 min-w-0\">\n <div className=\"flex items-center gap-2\">\n {Icon && (\n <div className=\"p-1.5 rounded-lg bg-foreground/[0.06] dark:bg-foreground/[0.04]\">\n <Icon className=\"h-3.5 w-3.5 text-foreground/70 dark:text-muted-foreground\" />\n </div>\n )}\n <span className=\"text-xs font-semibold text-muted-foreground uppercase tracking-wider\">\n {label}\n </span>\n </div>\n <div className=\"mt-3 flex items-baseline gap-2\">\n <span className=\"text-3xl font-bold tabular-nums text-foreground\">\n {typeof value === \"number\" ? value.toLocaleString() : value}\n </span>\n {trend && (\n <span\n className={cn(\n \"inline-flex items-center gap-0.5 text-xs font-medium\",\n trend.direction === \"up\"\n ? \"text-emerald-600 dark:text-emerald-400\"\n : \"text-red-600 dark:text-red-400\"\n )}\n >\n <svg\n className={cn(\"h-3 w-3\", trend.direction === \"down\" && \"rotate-180\")}\n viewBox=\"0 0 12 12\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path\n d=\"M6 2.5V9.5M6 2.5L3 5.5M6 2.5L9 5.5\"\n stroke=\"currentColor\"\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n </svg>\n {trend.value}%\n {trend.label && (\n <span className=\"text-muted-foreground ml-0.5\">{trend.label}</span>\n )}\n </span>\n )}\n </div>\n {description && (\n <p className=\"mt-1 text-xs text-muted-foreground\">\n {description}\n </p>\n )}\n </div>\n </div>\n </div>\n </div>\n );\n}\n", "\"use client\";\n\nimport { cn } from \"@stackframe/stack-ui\";\n\ntype DesignProgressBarGradient = \"blue\" | \"cyan\" | \"purple\" | \"green\" | \"orange\" | \"default\";\n\nconst fillClasses = new Map<DesignProgressBarGradient, string>([\n [\"blue\", \"bg-blue-500 dark:bg-blue-400\"],\n [\"cyan\", \"bg-cyan-500 dark:bg-cyan-400\"],\n [\"purple\", \"bg-purple-500 dark:bg-purple-400\"],\n [\"green\", \"bg-emerald-500 dark:bg-emerald-400\"],\n [\"orange\", \"bg-amber-500 dark:bg-amber-400\"],\n [\"default\", \"bg-foreground/60\"],\n]);\n\nexport type DesignProgressBarProps = {\n value: number,\n max?: number,\n gradient?: DesignProgressBarGradient,\n label?: string,\n showPercentage?: boolean,\n size?: \"sm\" | \"md\" | \"lg\",\n className?: string,\n};\n\nexport function DesignProgressBar({\n value,\n max = 100,\n gradient = \"default\",\n label,\n showPercentage = false,\n size = \"md\",\n className,\n}: DesignProgressBarProps) {\n const percentage = max > 0 ? Math.min(Math.max((value / max) * 100, 0), 100) : 0;\n const fillClass = fillClasses.get(gradient) ?? \"bg-foreground/60\";\n\n const trackHeight = size === \"sm\" ? \"h-1.5\" : size === \"lg\" ? \"h-3\" : \"h-2\";\n\n return (\n <div className={cn(\"w-full\", className)}>\n {(label || showPercentage) && (\n <div className=\"flex items-center justify-between mb-2\">\n {label && (\n <span className=\"text-xs font-medium text-muted-foreground\">\n {label}\n </span>\n )}\n {showPercentage && (\n <span className=\"text-xs font-medium tabular-nums text-foreground\">\n {Math.round(percentage)}%\n </span>\n )}\n </div>\n )}\n <div\n className={cn(\n \"w-full rounded-full bg-black/[0.06] dark:bg-white/[0.06] overflow-hidden\",\n trackHeight\n )}\n >\n <div\n className={cn(\n \"h-full rounded-full transition-all duration-300 ease-out\",\n fillClass\n )}\n style={{ width: `${percentage}%` }}\n />\n </div>\n </div>\n );\n}\n", "\"use client\";\n\nimport { cn } from \"@stackframe/stack-ui\";\nimport React from \"react\";\n\nexport type DesignEmptyStateProps = {\n icon?: React.ElementType,\n title?: string,\n description?: string,\n children?: React.ReactNode,\n className?: string,\n};\n\nexport function DesignEmptyState({\n icon: Icon,\n title = \"No data available\",\n description,\n children,\n className,\n}: DesignEmptyStateProps) {\n return (\n <div\n className={cn(\n \"flex flex-col items-center justify-center py-12 px-6 text-center\",\n className\n )}\n >\n {Icon && (\n <div className=\"mb-4\">\n <Icon className=\"h-10 w-10 text-muted-foreground/30\" />\n </div>\n )}\n <h3 className=\"text-sm font-medium text-foreground\">\n {title}\n </h3>\n {description && (\n <p className=\"mt-1 text-xs text-muted-foreground max-w-[280px]\">\n {description}\n </p>\n )}\n {children && (\n <div className=\"mt-4\">\n {children}\n </div>\n )}\n </div>\n );\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA,aAAO,UAAU,WAAW;AAAA;AAAA;;;ACA5B;AAAA;AAAA;AAKA,eAAS,MAAM,SAAS;AACtB,aAAK,WAAW;AAChB,aAAK,MAAM;AAAA,MACb;AACA,YAAM,UAAU,QAAQ,WAAY;AAClC,aAAK,QAAQ;AACb,aAAK,UAAU,uBAAO,OAAO,IAAI;AAAA,MACnC;AACA,YAAM,UAAU,MAAM,SAAU,KAAK;AACnC,eAAO,KAAK,QAAQ,GAAG;AAAA,MACzB;AACA,YAAM,UAAU,MAAM,SAAU,KAAK,OAAO;AAC1C,aAAK,SAAS,KAAK,YAAY,KAAK,MAAM;AAC1C,YAAI,EAAE,OAAO,KAAK,SAAU,MAAK;A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CAAA,CAAE;AAGV,MAAM,wBAAwB,4BAC5B,YACA,2BAAA,CACC,cAAsB;IACrB;IACA,mGAAmG,SAAA;IACnG,EAAE,YAAY,UAAA;KACf,CACA,SAAS,CAAC,KAAK,UAAA,CAAW;AAG7B,MAAM,sBAAsB,4BAC1B,YACA,yBAAA,CACC,UAAkB;IACjB;IACA,GAAG,KAAA;IACH,EAAE,MAAA;KACH,CACA,SAAS,CAAC,KAAK,KAAA,CAAM;AAGxB,MAAM,sBAAsB,4BAC1B,YACA,yBAAA,MACM,CACJ,KACA,4CAAA,GACD,MACK,CAAA,CAAE;AAGV,MAAM,+BAA+B,4BACnC,YACA,mCAAA,CACC,cAA+B,eAAuB;IACrD;IACA;IACA;MACE,eAAe;MACf,aAAa;;KAEhB,CACA,SAAS,CAAC,KAAK,eAAe,KAAK,WAAA,CAAY;AAGlD,MAAM,sBAAsB,4BAC1B,YACA,yBAAA,MACM,CACJ,KACA,oGAAA,GACD,MACK,CAAA,CAAE;AAOV,MAAa,cAAc;IACzB;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA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ACX,iBACH;AAAA,UACC,eACC,oBAAC,OAAE,WAAU,oDACV,uBACH;AAAA,UAED,YACC,oBAAC,SAAI,WAAU,QACZ,UACH;AAAA;AAAA;AAAA,IAEJ;AAAA,EAEJ;",
6
+ "names": ["split", "normalizePath", "index", "getter", "forEach", "join", "camelCase", "snakeCase", "toposort", "i", "e", "e", "a", "e", "a", "e", "a", "e", "r", "s", "a", "r", "o", "c", "m", "e", "o", "r", "o", "e", "r", "a", "c", "r", "e", "o", "a", "e", "o", "r", "c", "a", "s", "import_react", "React", "Fragment", "React", "a", "b", "s", "s", "min", "string", "s", "options", "extraLines", "resValueLength", "resValues", "toString", "value", "a", "r", "e", "o", "CLASS_PART_SEPARATOR", "createClassGroupUtils", "config", "classMap", "createClassMap", "conflictingClassGroups", "conflictingClassGroupModifiers", "getClassGroupId", "className", "classParts", "split", "length", "shift", "getGroupRecursive", "getGroupIdForArbitraryProperty", "getConflictingClassGroupIds", "classGroupId", "hasPostfixModifier", "conflicts", "classPartObject", "currentClassPart", "nextClassPartObject", "nextPart", "get", "classGroupFromNextClassPart", "slice", "undefined", "validators", "classRest", "join", "find", "validator", "arbitraryPropertyRegex", "test", "arbitraryPropertyClassName", "exec", "property", "substring", "indexOf", "theme", "prefix", "Map", "prefixedClassGroupEntries", "getPrefixedClassGroupEntries", "Object", "entries", "classGroups", "forEach", "classGroup", "processClassesRecursively", "classDefinition", "classPartObjectToEdit", "getPart", "isThemeGetter", "push", "key", "path", "currentClassPartObject", "pathPart", "has", "set", "func", "classGroupEntries", "map", "prefixedClassGroup", "fromEntries", "value", "createLruCache", "maxCacheSize", "cacheSize", "cache", "previousCache", "update", "IMPORTANT_MODIFIER", "createParseClassName", "separator", "experimentalParseClassName", "isSeparatorSingleCharacter", "firstSeparatorCharacter", "separatorLength", "parseClassName", "modifiers", "bracketDepth", "modifierStart", "postfixModifierPosition", "index", "currentCharacter", "baseClassNameWithImportantModifier", "hasImportantModifier", "startsWith", "baseClassName", "maybePostfixModifierPosition", "sortModifiers", "sortedModifiers", "unsortedModifiers", "modifier", "isArbitraryVariant", "sort", "createConfigUtils", "SPLIT_CLASSES_REGEX", "mergeClassList", "classList", "configUtils", "classGroupsInConflict", "classNames", "trim", "result", "originalClassName", "Boolean", "variantModifier", "modifierId", "classId", "includes", "conflictGroups", "i", "group", "twJoin", "argument", "resolvedValue", "string", "arguments", "toValue", "mix", "k", "createTailwindMerge", "createConfigFirst", "createConfigRest", "cacheGet", "cacheSet", "functionToCall", "initTailwindMerge", "reduce", "previousConfig", "createConfigCurrent", "tailwindMerge", "cachedResult", "callTailwindMerge", "apply", "fromTheme", "themeGetter", "arbitraryValueRegex", "fractionRegex", "stringLengths", "Set", "tshirtUnitRegex", "lengthUnitRegex", "colorFunctionRegex", "shadowRegex", "imageRegex", "isLength", "isNumber", "isArbitraryLength", "getIsArbitraryValue", "isLengthOnly", "Number", "isNaN", "isArbitraryNumber", "isInteger", "isPercent", "endsWith", "isArbitraryValue", "isTshirtSize", "sizeLabels", "isArbitrarySize", "isNever", "isArbitraryPosition", "imageLabels", "isArbitraryImage", "isImage", "isArbitraryShadow", "isShadow", "isAny", "label", "testValue", "getDefaultConfig", "colors", "fromTheme", "spacing", "blur", "brightness", "borderColor", "borderRadius", "borderSpacing", "borderWidth", "contrast", "grayscale", "hueRotate", "invert", "gap", "gradientColorStops", "gradientColorStopPositions", "inset", "margin", "opacity", "padding", "saturate", "scale", "sepia", "skew", "space", "translate", "getOverscroll", "getOverflow", "getSpacingWithAutoAndArbitrary", "isArbitraryValue", "getSpacingWithArbitrary", "getLengthWithEmptyAndArbitrary", "isLength", "isArbitraryLength", "getNumberWithAutoAndArbitrary", "isNumber", "getPositions", "getLineStyles", "getBlendModes", "getAlign", "getZeroAndEmpty", "getBreaks", "getNumberAndArbitrary", "cacheSize", "separator", "theme", "isAny", "isTshirtSize", "isPercent", "classGroups", "aspect", "container", "columns", "box", "display", "float", "clear", "isolation", "object", "overflow", "overscroll", "position", "start", "end", "top", "right", "bottom", "left", "visibility", "z", "isInteger", "basis", "flex", "grow", "shrink", "order", "col", "span", "row", "justify", "content", "items", "self", "p", "px", "py", "ps", "pe", "pt", "pr", "pb", "pl", "m", "mx", "my", "ms", "me", "mt", "mr", "mb", "ml", "w", "screen", "h", "size", "text", "font", "isArbitraryNumber", "tracking", "leading", "list", "placeholder", "decoration", "indent", "align", "whitespace", "break", "hyphens", "bg", "isArbitraryPosition", "repeat", "isArbitrarySize", "isArbitraryImage", "from", "via", "to", "rounded", "border", "divide", "outline", "ring", "shadow", "isArbitraryShadow", "filter", "table", "caption", "transition", "duration", "ease", "delay", "animate", "transform", "rotate", "origin", "accent", "appearance", "cursor", "caret", "resize", "scroll", "snap", "touch", "select", "fill", "stroke", "sr", "conflictingClassGroups", "conflictingClassGroupModifiers", "twMerge", "createTailwindMerge", "getDefaultConfig", "e", "s", "e", "s", "KnownError", "e", "value", "result", "s", "count", "index", "resolved", "c", "date", "min", "max", "a", "toposort", "p", "split", "s", "e", "index", "e", "e", "c", "e", "rejected", "a", "_a", "e", "React", "ReloadIcon", "React", "forwardedRef", "color", "props", "width", "height", "viewBox", "fill", "xmlns", "ref", "d", "fillRule", "clipRule", "React", "React", "Fragment", "getter", "React", "c", "e", "size", "React", "createContext", "index", "Provider", "useContext", "createScope", "nextScopes", "React", "createContextScope", "createContext", "index", "Provider", "useContext", "composeContextScopes", "createScope", "nextScopes", "React", "React", "Node", "React", "React", "node", "index", "handleAndDispatchPointerDownOutsideEvent", "React", "React", "useLayoutEffect", "React", "React", "platform", "max", "offset", "platform", "placements", "sides", "side", "a", "placement", "overflow", "platform", "x", "y", "min", "max", "offset", "getComputedStyle", "e", "getComputedStyle", "e", "offset", "shift", "flip", "size", "hide", "arrow", "limitShift", "computePosition", "React", "import_react", "ReactDOM", "a", "platform", "computePosition", "data", "arrow", "offset", "shift", "limitShift", "flip", "size", "hide", "arrow", "React", "React", "size", "arrow", "offset", "shift", "limitShift", "flip", "size", "hide", "PopperArrow", "Root", "Arrow", "React", "import_react_dom", "ReactDOM", "React", "value", "React", "NAME", "Root", "React2", "React", "getElementRef", "node", "getter", "composeEventHandlers", "React", "createContextScope", "open", "PORTAL_NAME", "CONTENT_NAME", "Root", "ARROW_NAME", "Arrow", "a", "p", "r", "Content", "TooltipProvider", "Tooltip", "Root3", "TooltipTrigger", "TooltipContent", "c", "s", "getMapValueOrThrow", "size", "sizeClasses", "React", "React", "setRef", "composeRefs", "useComposedRefs", "React", "SlotClone", "Slot", "isSlottable", "getElementRef", "props", "mergeProps", "composeRefs", "Slottable", "Fragment", "getter", "param", "size", "Slot", "e", "Slottable", "import_react", "React", "Fragment", "import_react", "import_react_dom", "Fragment", "index", "import_react", "size", "sizeClasses", "import_react", "React", "React", "createContextScope", "createContext", "index", "Provider", "useContext", "composeContextScopes", "createScope", "nextScopes", "React", "React", "ReactDOM", "React", "createSlot", "SlotClone", "createSlotClone", "Slot", "isSlottable", "createSlotClone", "SlotClone", "getElementRef", "props", "mergeProps", "composeRefs", "SLOTTABLE_IDENTIFIER", "createSlottable", "Slottable", "Fragment", "isSlottable", "SLOTTABLE_IDENTIFIER", "mergeProps", "getElementRef", "getter", "NODES", "Primitive", "Slot", "createSlot", "Node", "dispatchDiscreteCustomEvent", "React", "useCallbackRef", "React", "useEscapeKeydown", "useCallbackRef", "DISMISSABLE_LAYER_NAME", "CONTEXT_UPDATE", "POINTER_DOWN_OUTSIDE", "FOCUS_OUTSIDE", "originalBodyPointerEvents", "DismissableLayerContext", "DismissableLayer", "useComposedRefs", "node", "index", "usePointerDownOutside", "useFocusOutside", "useEscapeKeydown", "dispatchUpdate", "Primitive", "composeEventHandlers", "BRANCH_NAME", "DismissableLayerBranch", "useCallbackRef", "handleAndDispatchPointerDownOutsideEvent", "handleAndDispatchCustomEvent", "dispatchDiscreteCustomEvent", "React", "React", "useLayoutEffect", "useReactId", "React", "count", "useId", "useLayoutEffect2", "React", "React", "import_react", "ReactDOM", "index", "deepEqual", "a", "getDPR", "roundByDPR", "useLatestRef", "useFloating", "platform", "computePosition", "data", "arrow$1", "arrow", "offset", "shift", "limitShift", "flip", "size", "hide", "arrow", "arrow$1", "React", "NAME", "Arrow", "Primitive", "Root", "React", "useSize", "size", "useLayoutEffect2", "POPPER_NAME", "createPopperContext", "createPopperScope", "createContextScope", "PopperProvider", "usePopperContext", "Popper", "ANCHOR_NAME", "PopperAnchor", "useComposedRefs", "Primitive", "CONTENT_NAME", "PopperContentProvider", "useContentContext", "PopperContent", "arrow", "useSize", "isNotNull", "useFloating", "offset", "shift", "limitShift", "flip", "size", "transformOrigin", "hide", "getSideAndAlignFromPlacement", "useCallbackRef", "useLayoutEffect2", "ARROW_NAME", "OPPOSITE_SIDE", "PopperArrow", "Root", "Anchor", "Content", "Arrow", "React", "import_react_dom", "PORTAL_NAME", "Portal", "useLayoutEffect2", "ReactDOM", "Primitive", "React2", "React", "useStateMachine", "Presence", "usePresence", "useComposedRefs", "getElementRef", "getAnimationName", "useLayoutEffect2", "node", "getter", "React", "React2", "React", "useLayoutEffect2", "useControllableState", "useUncontrolledState", "value", "React", "NAME", "VisuallyHidden", "Primitive", "Root", "createTooltipContext", "createTooltipScope", "createContextScope", "createPopperScope", "usePopperScope", "PROVIDER_NAME", "DEFAULT_DELAY_DURATION", "TOOLTIP_OPEN", "TooltipProviderContextProvider", "useTooltipProviderContext", "TooltipProvider", "TOOLTIP_NAME", "TooltipContextProvider", "useTooltipContext", "Tooltip", "useId", "useControllableState", "open", "Root2", "TRIGGER_NAME", "TooltipTrigger", "useComposedRefs", "Anchor", "Primitive", "composeEventHandlers", "PORTAL_NAME", "PortalProvider", "usePortalContext", "TooltipPortal", "Presence", "Portal", "CONTENT_NAME", "TooltipContent", "TooltipContentImpl", "TooltipContentHoverable", "getExitSideFromRect", "getPaddedExitPoints", "getPointsFromRect", "getHull", "isPointInPolygon", "VisuallyHiddenContentContextProvider", "useVisuallyHiddenContentContext", "Slottable", "createSlottable", "DismissableLayer", "Content", "Root", "ARROW_NAME", "TooltipArrow", "Arrow", "a", "getHullPresorted", "p", "r", "getMapValueOrThrow", "size", "Tooltip", "TooltipTrigger", "TooltipPortal", "TooltipContent", "import_react", "gradientClasses", "getMapValueOrThrow", "size", "index", "React", "React", "RechartsPrimitive", "index", "Fragment", "React", "RechartsPrimitive", "hoverTintClasses", "Fragment", "hoverTintClasses", "max", "size"]
7
+ }