@wow-two-beta/fe 0.0.26 → 0.0.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -3
- package/dist/chunks/{AppSwitcherMenu.vue_vue_type_script_setup_true_lang-DVqdOOst.js → AccountMenu.vue_vue_type_script_setup_true_lang-CWsiHHiy.js} +700 -283
- package/dist/chunks/AccountMenu.vue_vue_type_script_setup_true_lang-CWsiHHiy.js.map +1 -0
- package/dist/chunks/Avatar.vue_vue_type_script_setup_true_lang-BIoaOjCh.js +267 -0
- package/dist/chunks/Avatar.vue_vue_type_script_setup_true_lang-BIoaOjCh.js.map +1 -0
- package/dist/chunks/{BackToTopButton.vue_vue_type_script_setup_true_lang-CNMcUYtR.js → BackToTopButton.vue_vue_type_script_setup_true_lang-6tfkqsrZ.js} +2 -2
- package/dist/chunks/{BackToTopButton.vue_vue_type_script_setup_true_lang-CNMcUYtR.js.map → BackToTopButton.vue_vue_type_script_setup_true_lang-6tfkqsrZ.js.map} +1 -1
- package/dist/chunks/{Button.vue_vue_type_script_setup_true_lang-BrgCAsgC.js → Button.vue_vue_type_script_setup_true_lang-Cw0QS_Mm.js} +2 -3
- package/dist/chunks/{Button.vue_vue_type_script_setup_true_lang-BrgCAsgC.js.map → Button.vue_vue_type_script_setup_true_lang-Cw0QS_Mm.js.map} +1 -1
- package/dist/chunks/{DrawerContent.vue_vue_type_script_setup_true_lang-CZQnfNGk.js → DrawerContent.vue_vue_type_script_setup_true_lang-BA-au7LC.js} +2 -2
- package/dist/chunks/{DrawerContent.vue_vue_type_script_setup_true_lang-CZQnfNGk.js.map → DrawerContent.vue_vue_type_script_setup_true_lang-BA-au7LC.js.map} +1 -1
- package/dist/chunks/{ErrorBoundary.vue_vue_type_script_setup_true_lang-LRQbVAiW.js → ErrorBoundary.vue_vue_type_script_setup_true_lang-DzqE0ZF8.js} +4 -4
- package/dist/chunks/{ErrorBoundary.vue_vue_type_script_setup_true_lang-LRQbVAiW.js.map → ErrorBoundary.vue_vue_type_script_setup_true_lang-DzqE0ZF8.js.map} +1 -1
- package/dist/chunks/{FieldHelperText.vue_vue_type_script_setup_true_lang-eqG5AyoV.js → FieldHelperText.vue_vue_type_script_setup_true_lang-DuMcXUch.js} +2 -2
- package/dist/chunks/{FieldHelperText.vue_vue_type_script_setup_true_lang-eqG5AyoV.js.map → FieldHelperText.vue_vue_type_script_setup_true_lang-DuMcXUch.js.map} +1 -1
- package/dist/chunks/{KanbanCard.vue_vue_type_script_setup_true_lang-BCnquIre.js → KanbanCard.vue_vue_type_script_setup_true_lang-CyXb4ZZw.js} +169 -427
- package/dist/chunks/KanbanCard.vue_vue_type_script_setup_true_lang-CyXb4ZZw.js.map +1 -0
- package/dist/chunks/{LightboxModal.vue_vue_type_script_setup_true_lang-Dm79L1eK.js → LightboxModal.vue_vue_type_script_setup_true_lang-BxdSYLYf.js} +6 -6
- package/dist/chunks/{LightboxModal.vue_vue_type_script_setup_true_lang-Dm79L1eK.js.map → LightboxModal.vue_vue_type_script_setup_true_lang-BxdSYLYf.js.map} +1 -1
- package/dist/chunks/{MasonryLayout.vue_vue_type_script_setup_true_lang-TuNWahLw.js → MasonryLayout.vue_vue_type_script_setup_true_lang-DD_jRzkM.js} +22 -7
- package/dist/chunks/MasonryLayout.vue_vue_type_script_setup_true_lang-DD_jRzkM.js.map +1 -0
- package/dist/chunks/{MentionInput.vue_vue_type_script_setup_true_lang-DdT24dkW.js → MentionInput.vue_vue_type_script_setup_true_lang-hYD3uP3P.js} +6 -6
- package/dist/chunks/{MentionInput.vue_vue_type_script_setup_true_lang-DdT24dkW.js.map → MentionInput.vue_vue_type_script_setup_true_lang-hYD3uP3P.js.map} +1 -1
- package/dist/chunks/{OverlayCloseButton.vue_vue_type_script_setup_true_lang-D01KYAAn.js → OverlayCloseButton.vue_vue_type_script_setup_true_lang-Df9raD_m.js} +2 -2
- package/dist/chunks/{OverlayCloseButton.vue_vue_type_script_setup_true_lang-D01KYAAn.js.map → OverlayCloseButton.vue_vue_type_script_setup_true_lang-Df9raD_m.js.map} +1 -1
- package/dist/chunks/{PopoverContent.vue_vue_type_script_setup_true_lang-BIHYpwzT.js → PopoverContent.vue_vue_type_script_setup_true_lang-C6YKEo3H.js} +2 -2
- package/dist/chunks/{PopoverContent.vue_vue_type_script_setup_true_lang-BIHYpwzT.js.map → PopoverContent.vue_vue_type_script_setup_true_lang-C6YKEo3H.js.map} +1 -1
- package/dist/chunks/{ReportAction.vue_vue_type_script_setup_true_lang-l4DjtcpM.js → ReportAction.vue_vue_type_script_setup_true_lang-DCnPCczd.js} +2 -2
- package/dist/chunks/{ReportAction.vue_vue_type_script_setup_true_lang-l4DjtcpM.js.map → ReportAction.vue_vue_type_script_setup_true_lang-DCnPCczd.js.map} +1 -1
- package/dist/chunks/{SurfaceStyles-B8KNkFsm.js → SurfaceStyles-BYvRlsWe.js} +2 -2
- package/dist/chunks/{SurfaceStyles-B8KNkFsm.js.map → SurfaceStyles-BYvRlsWe.js.map} +1 -1
- package/dist/chunks/{ToastHost.vue_vue_type_script_setup_true_lang-p0bfXJ9l.js → ToastHost.vue_vue_type_script_setup_true_lang-J1ZPZXn3.js} +3 -3
- package/dist/chunks/{ToastHost.vue_vue_type_script_setup_true_lang-p0bfXJ9l.js.map → ToastHost.vue_vue_type_script_setup_true_lang-J1ZPZXn3.js.map} +1 -1
- package/dist/chunks/{Tones-CQu-OvAk.js → Tones-Bcz8dIo3.js} +159 -1
- package/dist/chunks/Tones-Bcz8dIo3.js.map +1 -0
- package/dist/chunks/UseScrollActivity-D8MC5xgH.js +37 -0
- package/dist/chunks/UseScrollActivity-D8MC5xgH.js.map +1 -0
- package/dist/chunks/{index-C-r59Hob.js → index-CGIXFfl9.js} +3 -4
- package/dist/chunks/{index-C-r59Hob.js.map → index-CGIXFfl9.js.map} +1 -1
- package/dist/chunks/{index-rh4HVTr5.js → index-COgbQxBT.js} +5 -1
- package/dist/chunks/{index-rh4HVTr5.js.map → index-COgbQxBT.js.map} +1 -1
- package/dist/chunks/{index-CuiXILXc.js → index-Dp6L9sX7.js} +6 -2
- package/dist/chunks/index-Dp6L9sX7.js.map +1 -0
- package/dist/foundation/config/ConfigSource.d.ts +12 -5
- package/dist/foundation/config/DefineConfig.d.ts +9 -4
- package/dist/foundation/config/index.d.ts +1 -1
- package/dist/foundation/config/index.js +12 -9
- package/dist/foundation/config/index.js.map +1 -1
- package/dist/foundation/dom/hooks/UseScrollActivity.d.ts +15 -0
- package/dist/foundation/dom/index.d.ts +1 -0
- package/dist/foundation/dom/index.js +7 -3
- package/dist/foundation/dom/index.js.map +1 -1
- package/dist/foundation/primitives/index.js +1 -1
- package/dist/foundation/primitives/scrollViewport/ScrollViewport.vue.d.ts +9 -0
- package/dist/foundation/styles/index.js +9 -10
- package/dist/foundation/styles/index.js.map +1 -1
- package/dist/index.css +83 -36
- package/dist/index.js +467 -465
- package/dist/index.js.map +1 -1
- package/dist/presentation/actions/index.js +2 -2
- package/dist/presentation/display/index.js +178 -177
- package/dist/presentation/display/index.js.map +1 -1
- package/dist/presentation/feedback/index.js +3 -3
- package/dist/presentation/feedback/toastHost/index.js +1 -1
- package/dist/presentation/forms/index.js +2 -2
- package/dist/presentation/layout/appShell/AppShellMain.vue.d.ts +14 -5
- package/dist/presentation/layout/index.js +1 -1
- package/dist/presentation/layout/scrollArea/ScrollArea.vue.d.ts +7 -0
- package/dist/presentation/layout/virtualScrollArea/VirtualScrollArea.vue.d.ts +6 -0
- package/dist/presentation/nav/accountMenu/AccountMenu.vue.d.ts +131 -0
- package/dist/presentation/nav/accountMenu/index.d.ts +1 -0
- package/dist/presentation/nav/index.d.ts +1 -0
- package/dist/presentation/nav/index.js +72 -71
- package/dist/presentation/overlays/index.js +4 -4
- package/package.json +1 -1
- package/dist/chunks/AppSwitcherMenu.vue_vue_type_script_setup_true_lang-DVqdOOst.js.map +0 -1
- package/dist/chunks/CssExtensions-ctGVlfYU.js +0 -161
- package/dist/chunks/CssExtensions-ctGVlfYU.js.map +0 -1
- package/dist/chunks/KanbanCard.vue_vue_type_script_setup_true_lang-BCnquIre.js.map +0 -1
- package/dist/chunks/MasonryLayout.vue_vue_type_script_setup_true_lang-TuNWahLw.js.map +0 -1
- package/dist/chunks/Tones-CQu-OvAk.js.map +0 -1
- package/dist/chunks/index-CuiXILXc.js.map +0 -1
|
@@ -11,6 +11,7 @@ import { _ as _sfc_main$9 } from "./OverlayArrow.vue_vue_type_script_setup_true_
|
|
|
11
11
|
import { _ as _sfc_main$a } from "./Portal.vue_vue_type_script_setup_true_lang-C2_xSIMy.js";
|
|
12
12
|
import { _ as _sfc_main$c } from "./ScrollLockProvider.vue_vue_type_script_setup_true_lang-C6WDtqT0.js";
|
|
13
13
|
import { c as cn } from "./Cn-C7De6POU.js";
|
|
14
|
+
import { u as useScrollActivity } from "./UseScrollActivity-D8MC5xgH.js";
|
|
14
15
|
import { A as AriaAttribute } from "./AriaAttribute-CmUjjXjp.js";
|
|
15
16
|
import { r as renderableChildren, S as Slottable, m as mergeProps$1, a as renderSlotClone } from "./Slot-BGJ_Mr_j.js";
|
|
16
17
|
import { F as FormControlKey, u as useFormControl, a as useFormControlChrome } from "./FormControlContext-B71MFW26.js";
|
|
@@ -106,13 +107,15 @@ const _sfc_main$1 = /* @__PURE__ */ defineComponent({
|
|
|
106
107
|
height: {},
|
|
107
108
|
maxHeight: {},
|
|
108
109
|
isAnimated: { type: Boolean, default: void 0 },
|
|
109
|
-
animate: { type: Boolean, default: void 0 }
|
|
110
|
+
animate: { type: Boolean, default: void 0 },
|
|
111
|
+
hasAutoHideScrollbar: { type: Boolean, default: false }
|
|
110
112
|
},
|
|
111
113
|
setup(__props, { expose: __expose }) {
|
|
112
114
|
const props = __props;
|
|
113
115
|
const attrs = useAttrs();
|
|
114
116
|
const el = useTemplateRef("el");
|
|
115
117
|
const reducedMotion = useReducedMotion();
|
|
118
|
+
useScrollActivity(el, () => props.hasAutoHideScrollbar);
|
|
116
119
|
const transitionsOn = computed(() => (props.isAnimated ?? props.animate ?? false) && !reducedMotion.value);
|
|
117
120
|
const sizeStyle = computed(
|
|
118
121
|
() => normalizeStyle([
|
|
@@ -127,6 +130,7 @@ const _sfc_main$1 = /* @__PURE__ */ defineComponent({
|
|
|
127
130
|
const classes = computed(
|
|
128
131
|
() => cn(
|
|
129
132
|
"overflow-y-auto overflow-x-hidden",
|
|
133
|
+
props.hasAutoHideScrollbar && "scrollbar-auto-hide",
|
|
130
134
|
transitionsOn.value && "transition-[height,opacity] duration-200 ease-out",
|
|
131
135
|
attrs.class
|
|
132
136
|
)
|
|
@@ -318,4 +322,4 @@ export {
|
|
|
318
322
|
createCollection as e,
|
|
319
323
|
index as i
|
|
320
324
|
};
|
|
321
|
-
//# sourceMappingURL=index-
|
|
325
|
+
//# sourceMappingURL=index-Dp6L9sX7.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index-Dp6L9sX7.js","sources":["../../src/foundation/primitives/visuallyHidden/VisuallyHidden.vue","../../src/foundation/primitives/directionProvider/DirectionProvider.vue","../../src/foundation/primitives/accessibleIcon/AccessibleIcon.ts","../../src/foundation/primitives/collection/Collection.ts","../../src/foundation/primitives/scrollViewport/ScrollViewport.vue","../../src/foundation/primitives/colorModeProvider/ColorModeScript.ts","../../src/foundation/primitives/colorModeProvider/ColorModeProvider.vue"],"sourcesContent":["<script lang=\"ts\">\nimport type { HTMLAttributes } from 'vue';\n\nexport type VisuallyHiddenProps = HTMLAttributes;\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, useAttrs } from 'vue';\nimport { cn } from '../../styles/Cn';\n\n/**\n * Renders the slot in a visually hidden span — content removed from the visual\n * layout but still announced to screen readers. Use for accessible labels on\n * icon-only affordances and live-region announcements.\n *\n * `inheritAttrs: false` so a caller's `class` goes through `cn` (tailwind-merge\n * resolves the conflict) instead of being blindly concatenated by Vue's\n * automatic class fallthrough — a caller's `p-2` must be able to beat `p-0`.\n */\ndefineOptions({ name: 'VisuallyHidden', inheritAttrs: false });\n\ndefineSlots<{\n /** The content announced to screen readers but hidden from view. */\n default(): unknown;\n}>();\n\nconst attrs = useAttrs();\n\nconst classes = computed(() =>\n cn(\n 'absolute h-px w-px overflow-hidden whitespace-nowrap border-0 p-0',\n 'm-[-1px] [clip:rect(0_0_0_0)] [clip-path:inset(50%)]',\n attrs.class as string | undefined,\n ),\n);\n\n/** Everything but `class`, which is re-applied through `cn` above. */\nconst rest = computed(() => {\n const { class: _class, ...others } = attrs;\n return others;\n});\n</script>\n\n<template>\n <span v-bind=\"rest\" :class=\"classes\"><slot /></span>\n</template>\n","<script lang=\"ts\">\nimport type { Direction } from './DirectionContext';\n\nexport interface DirectionProviderProps {\n readonly dir: Direction;\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { provideDirection } from './DirectionContext';\n\n/**\n * Renders no element of its own — the slot passes straight through — while providing reading direction to\n * descendants. Components that mirror in RTL (Tabs arrow keys, Slider, Carousel, etc.) read this via\n * `useDirection()`.\n */\ndefineOptions({ name: 'DirectionProvider' });\n\nconst props = defineProps<DirectionProviderProps>();\n\ndefineSlots<{\n /** The subtree that reads the provided reading direction. */\n default(): unknown;\n}>();\n\nprovideDirection(() => props.dir);\n</script>\n\n<template>\n <slot />\n</template>\n","import { Fragment, cloneVNode, defineComponent, h } from 'vue';\nimport { AriaAttribute } from '../../dom/enums/AriaAttribute';\nimport { renderableChildren } from '../slot/Slot';\nimport VisuallyHidden from '../visuallyHidden/VisuallyHidden.vue';\n\nexport interface AccessibleIconProps {\n /** The accessible label for the icon. */\n readonly label: string;\n}\n\n/**\n * Wrap an icon-only element with an accessible label. The icon is hidden\n * from assistive tech and a `VisuallyHidden` sibling provides the label.\n *\n * A render function rather than an SFC: the `aria-hidden` / `focusable` pair\n * has to land on the *consumer's* icon vnode, and only a render function can\n * rebuild someone else's vnode. `cloneVNode`'s prop merge is safe here — these\n * two attributes collide with neither class, style, nor a handler.\n */\nexport const AccessibleIcon = defineComponent({\n name: 'AccessibleIcon',\n props: {\n label: { type: String, required: true },\n },\n setup(props, { slots }) {\n return () => {\n const children = renderableChildren(slots.default?.());\n const target = children[0];\n const icon = target ? cloneVNode(target, { [AriaAttribute.Hidden]: 'true', focusable: 'false' }) : children;\n return h(Fragment, [icon, h(VisuallyHidden, null, { default: () => props.label })]);\n };\n },\n});\n","import { defineComponent, inject, provide, shallowRef, type Component, type InjectionKey } from 'vue';\n\nexport interface CollectionContextValue<T> {\n /** The registered items, in registration order. A live getter — read it, never destructure it. */\n readonly items: ReadonlyArray<T>;\n register: (item: T) => void;\n unregister: (item: T) => void;\n}\n\n/**\n * Factory for a typed children-registry context. Compound components\n * (Menu, Tabs, Listbox) use this so the parent can iterate ordered children\n * without prop-drilling.\n *\n * The registration model is unchanged from React — items call `register()` on\n * mount and `unregister()` on unmount. That already matched what Vue needs:\n * slots are functions, so there is no children array to walk.\n *\n * `Context` becomes `injectionKey` — Vue's `provide`/`inject` are keyed by\n * symbol rather than by a context object.\n */\nexport function createCollection<T>(): {\n Provider: Component;\n useCollection: () => CollectionContextValue<T>;\n injectionKey: InjectionKey<CollectionContextValue<T>>;\n} {\n const injectionKey: InjectionKey<CollectionContextValue<T>> = Symbol('wow-two.collection');\n\n const Provider = defineComponent({\n name: 'CollectionProvider',\n setup(_props, { slots }) {\n const items = shallowRef<ReadonlyArray<T>>([]);\n\n // Replaced wholesale rather than mutated: a `shallowRef` only notifies on\n // identity change, which is also what kept React's `useState` updates cheap.\n const register = (item: T): void => {\n if (!items.value.includes(item)) items.value = [...items.value, item];\n };\n const unregister = (item: T): void => {\n items.value = items.value.filter((existing) => existing !== item);\n };\n\n // A getter rather than `reactive()` — it keeps `T` intact (reactive would\n // deep-unwrap it) while still tracking as a dependency on read.\n const context: CollectionContextValue<T> = {\n get items() {\n return items.value;\n },\n register,\n unregister,\n };\n provide(injectionKey, context);\n\n return () => slots.default?.() ?? null;\n },\n });\n\n function useCollection(): CollectionContextValue<T> {\n const context = inject(injectionKey, null);\n if (!context) {\n throw new Error('useCollection must be used inside its Provider');\n }\n return context;\n }\n\n return { Provider, useCollection, injectionKey };\n}\n","<script lang=\"ts\">\nimport type { HTMLAttributes } from 'vue';\n\nexport interface ScrollViewportProps extends /* @vue-ignore */ HTMLAttributes {\n /**\n * The fixed viewport height. Number → pixels; string → any CSS length\n * (`'20rem'`, `'50vh'`). Content beyond this scrolls; the box does not grow.\n * Omit to let the container size to its context (still clips + scrolls via `maxHeight`).\n */\n readonly height?: number | string;\n\n /**\n * The height ceiling — grows with content up to this cap without pinning it,\n * then scrolls. Number → pixels; string → any CSS length.\n */\n readonly maxHeight?: number | string;\n\n /**\n * The height/opacity transition flag (a content swap, an expand). Respects\n * `prefers-reduced-motion` — the transition is dropped when the user opts out.\n * @default false\n */\n readonly isAnimated?: boolean;\n /** @deprecated Use `isAnimated`; this alias is removed next release. */\n readonly animate?: boolean;\n\n /**\n * Fades the scrollbar thumb while the area is idle and brings it back on hover and while it scrolls. The track\n * keeps its space, so the layout never shifts.\n * @default false\n */\n readonly hasAutoHideScrollbar?: boolean;\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, normalizeStyle, useAttrs, useTemplateRef } from 'vue';\nimport { cn } from '../../styles/Cn';\nimport { useReducedMotion } from '../../device/hooks/UseReducedMotion';\nimport { useScrollActivity } from '../../dom/hooks/UseScrollActivity';\n\n/**\n * Renders the slot inside a headless fixed-height scroll container. A drop-in for\n * inline `h-[…] overflow-y-auto` viewport styling with two stability guarantees:\n *\n * - `scrollbar-gutter: stable` — reserves the scrollbar's track so content\n * doesn't shift horizontally when the bar appears/disappears (an overflow-y\n * toggle that would otherwise reflow the row).\n * - optional height/opacity transition (`isAnimated`) that short-circuits under\n * `prefers-reduced-motion`, so motion-sensitive users get an instant swap.\n *\n * No visual styling beyond layout — border/padding/rounding stay with the\n * consumer. The scrollable node is exposed as `el` so callers can drive\n * `scrollTop` (scroll-to-top on filter, virtualization measurements, etc.) —\n * the Vue stand-in for the original's `forwardRef`.\n */\ndefineOptions({ name: 'ScrollViewport', inheritAttrs: false });\n\nconst props = withDefaults(\n defineProps<{\n height?: number | string;\n maxHeight?: number | string;\n isAnimated?: boolean;\n animate?: boolean;\n hasAutoHideScrollbar?: boolean;\n }>(),\n { isAnimated: undefined, animate: undefined, hasAutoHideScrollbar: false },\n);\n\ndefineSlots<{\n /** The scrollable content inside the viewport. */\n default(): unknown;\n}>();\n\nconst attrs = useAttrs();\nconst el = useTemplateRef<HTMLDivElement>('el');\nconst reducedMotion = useReducedMotion();\nuseScrollActivity(el, () => props.hasAutoHideScrollbar);\n\nconst transitionsOn = computed(() => (props.isAnimated ?? props.animate ?? false) && !reducedMotion.value);\n\nconst sizeStyle = computed(() =>\n normalizeStyle([\n {\n height: typeof props.height === 'number' ? `${props.height}px` : props.height,\n maxHeight: typeof props.maxHeight === 'number' ? `${props.maxHeight}px` : props.maxHeight,\n scrollbarGutter: 'stable',\n },\n attrs.style,\n ]),\n);\n\nconst classes = computed(() =>\n cn(\n 'overflow-y-auto overflow-x-hidden',\n props.hasAutoHideScrollbar && 'scrollbar-auto-hide',\n transitionsOn.value && 'transition-[height,opacity] duration-200 ease-out',\n attrs.class as string | undefined,\n ),\n);\n\nconst rest = computed(() => {\n const { class: _class, style: _style, ...others } = attrs;\n return others;\n});\n\ndefineExpose({ el });\n</script>\n\n<template>\n <div ref=\"el\" v-bind=\"rest\" :class=\"classes\" :style=\"sizeStyle\"><slot /></div>\n</template>\n","import type { ColorMode } from './ColorModeContext';\n\n/** The `localStorage` key `ColorModeProvider` persists to by default. */\nexport const ColorModeStorageKey = 'wow-color-mode';\n\n/** Options for `colorModeScript` — pass the same values the app gives `ColorModeProvider`. */\nexport interface ColorModeScriptOptions {\n /** The provider's `storageKey`. Default `ColorModeStorageKey`. */\n readonly storageKey?: string;\n\n /** The provider's `defaultMode`. Default `'system'`. */\n readonly defaultMode?: ColorMode | 'system';\n}\n\n/* JSON is valid JavaScript; escaping `<` keeps a value from closing an inline `<script>` element. */\nfunction literal(value: string): string {\n return JSON.stringify(value).replace(/</g, '\\\\u003c');\n}\n\n/**\n * Returns the source of a pre-paint script that applies the remembered colour mode before the first frame, so a\n * dark app never flashes light. It reads the provider's storage key with the provider's rules: a stored `light` or\n * `dark` wins; a stored `system`, or nothing with a `system` default, follows the OS; otherwise the default mode.\n * It toggles `dark` and sets `color-scheme` on `<html>`, exactly as the provider will on mount.\n *\n * Inline it as a classic `<script>` in `index.html`'s `<head>` (a strict CSP needs its hash), or write it to a static\n * file served from the same origin. Storage failures leave the page to the provider.\n */\nexport function colorModeScript(options: ColorModeScriptOptions = {}): string {\n const key = literal(options.storageKey ?? ColorModeStorageKey);\n const fallback = literal(options.defaultMode ?? 'system');\n return (\n '(function(){try{' +\n `var s=localStorage.getItem(${key}),d=${fallback},m;` +\n \"if(s==='light'||s==='dark')m=s;\" +\n \"else if(s==='system'||d==='system')m=matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light';\" +\n 'else m=d;' +\n \"var r=document.documentElement;r.classList.toggle('dark',m==='dark');r.style.colorScheme=m;\" +\n '}catch(e){}})();'\n );\n}\n","<script lang=\"ts\">\nimport type { InjectionKey } from 'vue';\n\ninterface ColorModeOwner {\n readonly parent: ColorModeOwner | null;\n readonly mode: () => ColorMode;\n}\ninterface RootColorModes {\n readonly owners: ColorModeOwner[];\n readonly dark: boolean;\n readonly colorScheme: string;\n readonly priority: string;\n}\nconst ColorModeOwnerKey: InjectionKey<ColorModeOwner> = Symbol('wow-two.colorModeOwner');\nconst RootOwners = new WeakMap<HTMLElement, RootColorModes>();\n\nfunction isDescendant(owner: ColorModeOwner, ancestor: ColorModeOwner): boolean {\n for (let entry: ColorModeOwner | null = owner; entry; entry = entry.parent) {\n if (entry === ancestor) return true;\n }\n return false;\n}\n\nfunction applyRootMode(root: HTMLElement): void {\n const state = RootOwners.get(root);\n if (!state) return;\n const owner = state.owners.at(-1);\n if (owner) {\n const mode = owner.mode();\n root.classList.toggle('dark', mode === 'dark');\n root.style.setProperty('color-scheme', mode);\n } else {\n root.classList.toggle('dark', state.dark);\n if (state.colorScheme) root.style.setProperty('color-scheme', state.colorScheme, state.priority);\n else root.style.removeProperty('color-scheme');\n RootOwners.delete(root);\n }\n}\n// `ColorMode` is imported as a value by `<script setup>` below; both blocks\n// share one module scope, so re-importing the type here would duplicate it.\nexport interface ColorModeProviderProps {\n /** The mode used when nothing is persisted. `'system'` follows the OS preference. Default `'system'`. */\n readonly defaultMode?: ColorMode | 'system';\n\n /** The `localStorage` key for persistence; pass `null` to disable. Default `'wow-color-mode'`. */\n readonly storageKey?: string | null;\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { inject, onMounted, onScopeDispose, provide, shallowRef, watch } from 'vue';\nimport { useMediaQuery } from '../../device';\nimport { ColorMode, ColorModeKey, ColorModeSystemValue, type ColorModeContextValue } from './ColorModeContext';\nimport { ColorModeStorageKey } from './ColorModeScript';\n\n/**\n * Renders no element of its own — the slot passes straight through — while owning the app's light/dark mode:\n * toggles the `dark` class on `<html>` (which flips every semantic token) + sets `color-scheme`, persists the\n * choice, and falls back to the OS preference. Wrap the app once; read via `useColorMode()`. This is the\n * canonical `.dark` mechanism for the design tokens.\n */\ndefineOptions({ name: 'ColorModeProvider' });\n\nconst props = withDefaults(defineProps<ColorModeProviderProps>(), {\n defaultMode: 'system',\n storageKey: ColorModeStorageKey,\n});\n\ndefineSlots<{\n /** The subtree that reads the active color mode. */\n default(): unknown;\n}>();\n\n/** Explicit defaults are shared by SSR and the first client render. */\nconst mode = shallowRef<ColorMode>(props.defaultMode === 'system' ? ColorMode.Light : props.defaultMode);\nlet root: HTMLElement | undefined;\nconst owner: ColorModeOwner = { parent: inject(ColorModeOwnerKey, null), mode: () => mode.value };\nprovide(ColorModeOwnerKey, owner);\nconst followsSystem = shallowRef(false);\nconst prefersDark = useMediaQuery('(prefers-color-scheme: dark)');\n\nonMounted(() => {\n let stored: string | null = null;\n try {\n stored = props.storageKey ? window.localStorage.getItem(props.storageKey) : null;\n } catch {\n // Storage denial must not disable the in-memory theme control.\n }\n // A stored `system` choice follows the OS even when the default names a fixed mode.\n followsSystem.value =\n stored === ColorModeSystemValue ||\n (stored !== ColorMode.Light && stored !== ColorMode.Dark && props.defaultMode === 'system');\n mode.value =\n stored === ColorMode.Light || stored === ColorMode.Dark\n ? stored\n : followsSystem.value\n ? prefersDark.value\n ? ColorMode.Dark\n : ColorMode.Light\n : mode.value;\n root = document.documentElement;\n const state: RootColorModes = RootOwners.get(root) ?? {\n owners: [],\n dark: root.classList.contains('dark'),\n colorScheme: root.style.getPropertyValue('color-scheme'),\n priority: root.style.getPropertyPriority('color-scheme'),\n };\n RootOwners.set(root, state);\n const descendant = state.owners.findIndex((candidate) => isDescendant(candidate, owner));\n if (descendant < 0) state.owners.push(owner);\n else state.owners.splice(descendant, 0, owner);\n applyRootMode(root);\n});\n\nonScopeDispose(() => {\n if (!root) return;\n const state = RootOwners.get(root);\n const index = state?.owners.indexOf(owner) ?? -1;\n if (state && index >= 0) state.owners.splice(index, 1);\n applyRootMode(root);\n root = undefined;\n});\n\nwatch(prefersDark, (dark) => {\n if (followsSystem.value) mode.value = dark ? ColorMode.Dark : ColorMode.Light;\n});\n\nwatch(mode, () => {\n if (root) applyRootMode(root);\n});\n\nfunction setMode(next: ColorMode): void {\n followsSystem.value = false;\n mode.value = next;\n if (!props.storageKey || typeof window === 'undefined') return;\n try {\n window.localStorage.setItem(props.storageKey, next);\n } catch {\n // Storage may be disabled or full; the chosen mode remains active.\n }\n}\n\nfunction followSystem(): void {\n followsSystem.value = true;\n mode.value = prefersDark.value ? ColorMode.Dark : ColorMode.Light;\n if (!props.storageKey || typeof window === 'undefined') return;\n try {\n window.localStorage.setItem(props.storageKey, ColorModeSystemValue);\n } catch {\n // Storage may be disabled or full; following the OS stays active for this session.\n }\n}\n\n// A getter, so consumers read `ctx.mode` as a plain value exactly like the\n// React context object — and tracking still happens on access.\nconst context: ColorModeContextValue = {\n get mode() {\n return mode.value;\n },\n get followsSystem() {\n return followsSystem.value;\n },\n setMode,\n followSystem,\n toggle: () => setMode(mode.value === ColorMode.Dark ? ColorMode.Light : ColorMode.Dark),\n};\n\nprovide(ColorModeKey, context);\n</script>\n\n<template>\n <slot />\n</template>\n"],"names":["_openBlock","_createElementBlock","_mergeProps","_renderSlot","VisuallyHidden","index"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA0BA,UAAM,QAAQ,SAAA;AAEd,UAAM,UAAU;AAAA,MAAS,MACvB;AAAA,QACE;AAAA,QACA;AAAA,QACA,MAAM;AAAA,MAAA;AAAA,IACR;AAIF,UAAM,OAAO,SAAS,MAAM;AAC1B,YAAM,EAAE,OAAO,QAAQ,GAAG,WAAW;AACrC,aAAO;AAAA,IACT,CAAC;;AAIC,aAAAA,UAAA,GAAAC,mBAAoD,QAApDC,WAAoD,YAAlC,EAAG,OAAO,QAAA,MAAA,CAAO,GAAA;AAAA,QAAEC,WAAQ,KAAA,QAAA,SAAA;AAAA,MAAA;;;;;;;;;;;AC1B/C,UAAM,QAAQ;AAOd,qBAAiB,MAAM,MAAM,GAAG;;aAI9BA,WAAQ,KAAA,QAAA,SAAA;AAAA;;;ACVH,MAAM,iBAAiB,gBAAgB;AAAA,EAC5C,MAAM;AAAA,EACN,OAAO;AAAA,IACL,OAAO,EAAE,MAAM,QAAQ,UAAU,KAAA;AAAA,EAAK;AAAA,EAExC,MAAM,OAAO,EAAE,SAAS;AACtB,WAAO,MAAM;AACX,YAAM,WAAW,mBAAmB,MAAM,UAAA,CAAW;AACrD,YAAM,SAAS,SAAS,CAAC;AACzB,YAAM,OAAO,SAAS,WAAW,QAAQ,EAAE,CAAC,cAAc,MAAM,GAAG,QAAQ,WAAW,QAAA,CAAS,IAAI;AACnG,aAAO,EAAE,UAAU,CAAC,MAAM,EAAEC,aAAgB,MAAM,EAAE,SAAS,MAAM,MAAM,MAAA,CAAO,CAAC,CAAC;AAAA,IACpF;AAAA,EACF;AACF,CAAC;ACXM,SAAS,mBAId;AACA,QAAM,eAAwD,O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I;AAAA,IAAA;AAGxF,YAAQ,cAAc,OAAO;;aAI3BF,WAAQ,KAAA,QAAA,SAAA;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
@@ -2,11 +2,15 @@
|
|
|
2
2
|
export type ConfigSource = Readonly<Record<string, string | undefined>>;
|
|
3
3
|
/** The default runtime-config global — `window.__APP_CONFIG__`, injected per-environment ahead of build-time env. */
|
|
4
4
|
export declare const DefaultRuntimeConfigKey = "__APP_CONFIG__";
|
|
5
|
+
/** A build-time env record as a bundler exposes it — Vite's `import.meta.env`, with string and boolean values. */
|
|
6
|
+
export type ConfigEnv = Readonly<Record<string, unknown>>;
|
|
5
7
|
/**
|
|
6
|
-
* The build-time source
|
|
7
|
-
*
|
|
8
|
+
* The build-time source over the app's own env — call it as `importMetaEnvSource(import.meta.env)` from an app
|
|
9
|
+
* module, where the bundler inlines `import.meta.env`. Copies every string, number, boolean and bigint value as a
|
|
10
|
+
* string (`DEV: true` → `'true'`) into a frozen snapshot and drops anything else. A missing or non-object `env`
|
|
11
|
+
* yields `{}`.
|
|
8
12
|
*/
|
|
9
|
-
export declare function importMetaEnvSource(): ConfigSource;
|
|
13
|
+
export declare function importMetaEnvSource(env: ConfigEnv | undefined): ConfigSource;
|
|
10
14
|
/**
|
|
11
15
|
* The runtime source — a global object (default `window.__APP_CONFIG__`) a deployment injects before the app
|
|
12
16
|
* boots. Returns `{}` when there is no `window` (SSR / Node) or the global is absent or not an object.
|
|
@@ -14,8 +18,11 @@ export declare function importMetaEnvSource(): ConfigSource;
|
|
|
14
18
|
export declare function windowConfigSource(globalKey?: string): ConfigSource;
|
|
15
19
|
/** An explicit source over a plain record — the injection seam for tests and for values resolved elsewhere. */
|
|
16
20
|
export declare function staticSource(values: Record<string, string | undefined>): ConfigSource;
|
|
17
|
-
/**
|
|
18
|
-
|
|
21
|
+
/**
|
|
22
|
+
* The default source order: runtime `window.__APP_CONFIG__` layered ahead of the app's build-time env. Pass the
|
|
23
|
+
* app's `import.meta.env` as `env`; without it only the runtime source is read.
|
|
24
|
+
*/
|
|
25
|
+
export declare function defaultSources(env?: ConfigEnv): ReadonlyArray<ConfigSource>;
|
|
19
26
|
/**
|
|
20
27
|
* Resolves `key` across an ordered source list, first non-empty match wins (earlier source = higher priority).
|
|
21
28
|
* A non-string hit (e.g. `import.meta.env.DEV` is a boolean) is coerced to its string form; an empty string is
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { AnyConfigField, ConfigField } from './ConfigField';
|
|
2
|
-
import { ConfigSource } from './ConfigSource';
|
|
2
|
+
import { ConfigEnv, ConfigSource } from './ConfigSource';
|
|
3
3
|
/** A schema: a map from output key to its field spec. */
|
|
4
4
|
export type ConfigSchema = Readonly<Record<string, AnyConfigField>>;
|
|
5
5
|
/** Widens an optional field's output to include `undefined`; a required / defaulted field stays `T`. */
|
|
@@ -10,8 +10,13 @@ export type InferConfig<S extends ConfigSchema> = {
|
|
|
10
10
|
};
|
|
11
11
|
/** Tunes where `defineConfig` reads from and how keys are namespaced. */
|
|
12
12
|
export interface DefineConfigOptions {
|
|
13
|
-
/** The ordered source list; earlier wins. Defaults to `
|
|
13
|
+
/** The ordered source list; earlier wins. Defaults to `defaultSources(env)`. */
|
|
14
14
|
readonly sources?: ReadonlyArray<ConfigSource>;
|
|
15
|
+
/**
|
|
16
|
+
* The app's build-time env — pass `import.meta.env` from the app's own module. Read after the runtime
|
|
17
|
+
* `window.__APP_CONFIG__` when `sources` is omitted; ignored when `sources` is given.
|
|
18
|
+
*/
|
|
19
|
+
readonly env?: ConfigEnv;
|
|
15
20
|
/** A prefix prepended to every schema key on lookup (e.g. `'VITE_'` → key `API_URL` reads `VITE_API_URL`). */
|
|
16
21
|
readonly prefix?: string;
|
|
17
22
|
}
|
|
@@ -36,8 +41,8 @@ export declare class ConfigError extends Error {
|
|
|
36
41
|
* Resolves a typed configuration object from `schema`. Each key is looked up across the source list (prefix
|
|
37
42
|
* applied), parsed through its field, and defaulted when absent. Empty strings count as absent. All missing /
|
|
38
43
|
* invalid problems are aggregated and thrown together as a single {@link ConfigError}; on success the returned
|
|
39
|
-
* object is frozen. Pass an explicit `sources` (e.g.
|
|
40
|
-
* in tests.
|
|
44
|
+
* object is frozen. Pass the app's `env: import.meta.env`, or an explicit `sources` (e.g.
|
|
45
|
+
* `[staticSource({...})]`) to make resolution deterministic in tests.
|
|
41
46
|
*/
|
|
42
47
|
export declare function defineConfig<const S extends ConfigSchema>(schema: S, options?: DefineConfigOptions): InferConfig<S>;
|
|
43
48
|
export {};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
export { type ConfigField, type ConfigJsonDecoder, type ConfigFieldOptions, type AnyConfigField, type ListFieldOptions, str, num, bool, oneOf, url, port, json, list, } from './ConfigField';
|
|
2
|
-
export { type ConfigSource, DefaultRuntimeConfigKey, importMetaEnvSource, windowConfigSource, staticSource, defaultSources, resolveRaw, } from './ConfigSource';
|
|
2
|
+
export { type ConfigEnv, type ConfigSource, DefaultRuntimeConfigKey, importMetaEnvSource, windowConfigSource, staticSource, defaultSources, resolveRaw, } from './ConfigSource';
|
|
3
3
|
export { type ConfigSchema, type InferConfig, type DefineConfigOptions, type ConfigIssue, ConfigError, defineConfig, } from './DefineConfig';
|
|
4
4
|
export { Environment, IsDevelopment, IsProduction } from './Environment';
|
|
@@ -108,13 +108,16 @@ function list(options) {
|
|
|
108
108
|
);
|
|
109
109
|
}
|
|
110
110
|
const DefaultRuntimeConfigKey = "__APP_CONFIG__";
|
|
111
|
-
function importMetaEnvSource() {
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
111
|
+
function importMetaEnvSource(env) {
|
|
112
|
+
const values = /* @__PURE__ */ Object.create(null);
|
|
113
|
+
if (env === null || typeof env !== "object") return Object.freeze(values);
|
|
114
|
+
for (const key of Object.keys(env)) {
|
|
115
|
+
const value = env[key];
|
|
116
|
+
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
|
|
117
|
+
values[key] = String(value);
|
|
118
|
+
}
|
|
117
119
|
}
|
|
120
|
+
return Object.freeze(values);
|
|
118
121
|
}
|
|
119
122
|
function windowConfigSource(globalKey = DefaultRuntimeConfigKey) {
|
|
120
123
|
if (typeof window === "undefined") return {};
|
|
@@ -125,8 +128,8 @@ function windowConfigSource(globalKey = DefaultRuntimeConfigKey) {
|
|
|
125
128
|
function staticSource(values) {
|
|
126
129
|
return values;
|
|
127
130
|
}
|
|
128
|
-
function defaultSources() {
|
|
129
|
-
return [windowConfigSource(), importMetaEnvSource()];
|
|
131
|
+
function defaultSources(env) {
|
|
132
|
+
return env === void 0 ? [windowConfigSource()] : [windowConfigSource(), importMetaEnvSource(env)];
|
|
130
133
|
}
|
|
131
134
|
function resolveRaw(sources, key) {
|
|
132
135
|
for (const source of sources) {
|
|
@@ -152,7 +155,7 @@ ${lines}`);
|
|
|
152
155
|
}
|
|
153
156
|
}
|
|
154
157
|
function defineConfig(schema, options) {
|
|
155
|
-
const sources = options?.sources ?? defaultSources();
|
|
158
|
+
const sources = options?.sources ?? defaultSources(options?.env);
|
|
156
159
|
const prefix = options?.prefix ?? "";
|
|
157
160
|
const resolved = /* @__PURE__ */ Object.create(null);
|
|
158
161
|
const issues = [];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../src/foundation/config/ConfigField.ts","../../../src/foundation/config/ConfigSource.ts","../../../src/foundation/config/DefineConfig.ts"],"sourcesContent":["import { LosslessJson } from '../json';\nimport { ResultExtensions, type Result } from '../results';\n\n// Typed-env field specs. A `ConfigField<T>` describes how one configuration key is parsed from its raw\n// string form, whether it is required, and its fallback — the atoms `defineConfig` reads a source through.\n// Each builder (`str`, `num`, `bool`, `oneOf`, `url`, `port`, `json`, `list`) returns a field whose `parse`\n// handles only a *present* raw string and throws a human-readable message on an invalid value; the engine\n// owns the missing / default / required decision centrally, so a field never re-implements that policy.\n\n/** Tunes one field's presence policy and fallback. A `default` (or `required: false`) makes the field optional. */\nexport interface ConfigFieldOptions<T> {\n /** Marks the field required. Defaults to `true` unless a `default` is supplied. */\n readonly required?: boolean;\n\n /** The value used when the key is absent or empty. Supplying it makes the field optional. */\n readonly default?: T;\n\n /** Creates an independent fallback for each resolution; use for mutable values. */\n readonly defaultFactory?: () => T;\n\n /** Redacts the raw value from `ConfigError` messages — set for tokens, keys, and passwords. */\n readonly secret?: boolean;\n}\n\n/**\n * Describes a single configuration key: its scalar type, presence policy, and how to parse a present raw\n * string into `T`. `Optional` is a phantom flag the schema inference reads to widen the output to `T | undefined`\n * for a field that is `required: false` with no `default`.\n */\nexport interface ConfigField<T, Optional extends boolean = false> {\n /** The human-facing type name used in error messages (`string`, `number`, `one of [...]`, …). */\n readonly typeName: string;\n\n /** Whether a missing key is an error. `false` when a `default` is present or `required: false`. */\n readonly required: boolean;\n\n /** Whether an explicit `default` was supplied. */\n readonly hasDefault: boolean;\n\n /** The configured fallback, meaningful only when `hasDefault` is `true`. */\n readonly defaultValue?: T;\n\n /** Builds an independent fallback when configured. */\n readonly createDefault?: () => T;\n\n /** Whether the raw value is redacted from error output. */\n readonly secret: boolean;\n\n /** Phantom marker: `true` widens the inferred output type to `T | undefined`. Never read at runtime. */\n readonly __optional?: Optional;\n\n /** Parses a present, non-empty raw string into `T`; throws a `string` message describing the failure. */\n parse(raw: string): T;\n}\n\n/** Computes a field's phantom optionality from its options — optional iff no `default` and `required: false`. */\ntype Optionality<O> = O extends { default: unknown } | { defaultFactory: unknown }\n ? false\n : O extends { required: false }\n ? true\n : false;\n\n/** The upper bound for a field of unknown scalar type — every concrete `ConfigField<T, …>` is assignable to it. */\nexport type AnyConfigField = ConfigField<unknown, boolean>;\n\n/** Shared field constructor — folds the options into the runtime presence policy around a scalar `parse`. */\nfunction createField<T>(\n typeName: string,\n parse: (raw: string) => T,\n options: ConfigFieldOptions<T> | undefined,\n): ConfigField<T, boolean> {\n const hasValue = options !== undefined && Object.hasOwn(options, 'default');\n const hasFactory = options !== undefined && Object.hasOwn(options, 'defaultFactory');\n if (hasValue && hasFactory) throw new TypeError('Choose default or defaultFactory, not both.');\n if (\n hasValue &&\n (options.default === undefined ||\n (typeof options.default === 'object' && options.default !== null) ||\n typeof options.default === 'function')\n ) {\n throw new TypeError('Use defaultFactory for mutable config defaults; undefined is not a default.');\n }\n if (hasFactory && typeof options.defaultFactory !== 'function')\n throw new TypeError('defaultFactory must be a function.');\n const hasDefault = hasValue || hasFactory;\n return Object.freeze({\n typeName,\n parse,\n hasDefault,\n defaultValue: hasValue ? options.default : undefined,\n createDefault: hasFactory ? options.defaultFactory : undefined,\n // A field is required unless it carries a default or is explicitly opted out.\n required: hasDefault ? false : (options?.required ?? true),\n secret: options?.secret ?? false,\n });\n}\n\n/** A string field — preserves the raw value; empty strings are handled as missing by resolution. */\nexport function str<const O extends ConfigFieldOptions<string> = ConfigFieldOptions<string>>(\n options?: O,\n): ConfigField<string, Optionality<O>> {\n return createField('string', (raw) => raw, options) as ConfigField<string, Optionality<O>>;\n}\n\n/** A finite-number field — rejects any raw string that does not parse to a finite JS number. */\nexport function num<const O extends ConfigFieldOptions<number> = ConfigFieldOptions<number>>(\n options?: O,\n): ConfigField<number, Optionality<O>> {\n return createField(\n 'number',\n (raw) => {\n const value = Number(raw);\n if (!Number.isFinite(value)) throw `expected a number, got \"${raw}\"`;\n return value;\n },\n options,\n ) as ConfigField<number, Optionality<O>>;\n}\n\n/** The raw spellings each boolean side accepts, case-insensitively. */\nconst TrueTokens = new Set(['true', '1', 'yes', 'on']);\nconst FalseTokens = new Set(['false', '0', 'no', 'off']);\n\n/** A boolean field — accepts `true/1/yes/on` and `false/0/no/off` (case-insensitive); rejects anything else. */\nexport function bool<const O extends ConfigFieldOptions<boolean> = ConfigFieldOptions<boolean>>(\n options?: O,\n): ConfigField<boolean, Optionality<O>> {\n return createField(\n 'boolean',\n (raw) => {\n const token = raw.trim().toLowerCase();\n if (TrueTokens.has(token)) return true;\n if (FalseTokens.has(token)) return false;\n throw `expected a boolean (true/false/1/0/yes/no/on/off), got \"${raw}\"`;\n },\n options,\n ) as ConfigField<boolean, Optionality<O>>;\n}\n\n/** An enum field — the value must be one of `values`; the output type narrows to that literal union. */\nexport function oneOf<\n const V extends readonly string[],\n const O extends ConfigFieldOptions<V[number]> = ConfigFieldOptions<V[number]>,\n>(values: V, options?: O): ConfigField<V[number], Optionality<O>> {\n return createField(\n `one of [${values.join(', ')}]`,\n (raw) => {\n if ((values as readonly string[]).includes(raw)) return raw as V[number];\n throw `expected one of [${values.join(', ')}], got \"${raw}\"`;\n },\n options,\n ) as ConfigField<V[number], Optionality<O>>;\n}\n\n/** A URL field — validated with the `URL` constructor; the parsed string is returned unchanged. */\nexport function url<const O extends ConfigFieldOptions<string> = ConfigFieldOptions<string>>(\n options?: O,\n): ConfigField<string, Optionality<O>> {\n return createField(\n 'url',\n (raw) => {\n try {\n // Construct-and-discard: `URL` throws on a malformed value; we keep the caller's original string.\n void new URL(raw);\n return raw;\n } catch {\n throw `expected a valid URL, got \"${raw}\"`;\n }\n },\n options,\n ) as ConfigField<string, Optionality<O>>;\n}\n\n/** A TCP-port field — a finite integer in `1..65535`. */\nexport function port<const O extends ConfigFieldOptions<number> = ConfigFieldOptions<number>>(\n options?: O,\n): ConfigField<number, Optionality<O>> {\n return createField(\n 'port',\n (raw) => {\n const value = Number(raw);\n if (!Number.isInteger(value) || value < 1 || value > 65535) throw `expected a port in 1..65535, got \"${raw}\"`;\n return value;\n },\n options,\n ) as ConfigField<number, Optionality<O>>;\n}\n\n/** Validates a parsed JSON value; expected failures carry the decoder's own failure data. */\nexport type ConfigJsonDecoder<T> = (value: unknown) => Result<T, unknown>;\n\n/** Reads JSON without claiming a decoded application shape. Numeric tokens remain ExactNumber values. */\nexport function json<const O extends ConfigFieldOptions<unknown> = ConfigFieldOptions<unknown>>(\n options?: O,\n): ConfigField<unknown, Optionality<O>>;\n/** Decodes a lossless JSON value into a validated application shape; decoder failures reject the field. */\nexport function json<T, const O extends ConfigFieldOptions<T> = ConfigFieldOptions<T>>(\n decode: ConfigJsonDecoder<T>,\n options?: O,\n): ConfigField<T, Optionality<O>>;\nexport function json(\n decodeOrOptions?: ConfigJsonDecoder<unknown> | ConfigFieldOptions<unknown>,\n options?: ConfigFieldOptions<unknown>,\n): ConfigField<unknown, boolean> {\n const decode =\n typeof decodeOrOptions === 'function' ? decodeOrOptions : (value: unknown) => ResultExtensions.ok(value);\n return createField(\n 'json',\n (raw) => {\n const parsed = LosslessJson.parse(raw);\n if (!parsed.ok) throw 'expected valid JSON';\n const decoded = decode(parsed.value);\n if (!decoded.ok) throw 'JSON value failed its decoder';\n return decoded.value;\n },\n typeof decodeOrOptions === 'function' ? options : decodeOrOptions,\n );\n}\n\n/** Tunes how a `list` field splits its raw value. */\nexport interface ListFieldOptions extends ConfigFieldOptions<readonly string[]> {\n /** The item separator. Defaults to a comma. */\n readonly separator?: string;\n}\n\n/** A string-list field — splits on `separator` (default `,`), trims each item, and drops empty items. */\nexport function list<const O extends ListFieldOptions = ListFieldOptions>(\n options?: O,\n): ConfigField<ReadonlyArray<string>, Optionality<O>> {\n const separator = options?.separator ?? ',';\n return createField<readonly string[]>(\n 'list',\n (raw) =>\n raw\n .split(separator)\n .map((item) => item.trim())\n .filter((item) => item.length > 0),\n options,\n ) as ConfigField<readonly string[], Optionality<O>>;\n}\n","// Configuration sources — the raw key/value stores `defineConfig` reads through. Two ship by default: the\n// build-time `import.meta.env` (Vite inlines it at build) and the runtime `window.__APP_CONFIG__` global an ops\n// team can inject per-environment without a rebuild (12-factor runtime config). A source is a flat record of\n// string values; `defineConfig` merges an ordered list where the *earlier* source wins, so runtime config is\n// layered ahead of build-time env by default. Reading a source never throws — an unavailable one yields `{}`.\n\n/** A flat, read-only key/value store of raw configuration strings. */\nexport type ConfigSource = Readonly<Record<string, string | undefined>>;\n\n/** The default runtime-config global — `window.__APP_CONFIG__`, injected per-environment ahead of build-time env. */\nexport const DefaultRuntimeConfigKey = '__APP_CONFIG__';\n\n/**\n * The build-time source — Vite's `import.meta.env`, inlined at build. Returns `{}` outside a bundler context\n * (e.g. a plain Node test) where `import.meta.env` is absent, so it is always safe to include.\n */\nexport function importMetaEnvSource(): ConfigSource {\n try {\n const meta = import.meta as unknown as { env?: Record<string, string | undefined> };\n return meta.env ?? {};\n } catch {\n return {};\n }\n}\n\n/**\n * The runtime source — a global object (default `window.__APP_CONFIG__`) a deployment injects before the app\n * boots. Returns `{}` when there is no `window` (SSR / Node) or the global is absent or not an object.\n */\nexport function windowConfigSource(globalKey: string = DefaultRuntimeConfigKey): ConfigSource {\n if (typeof window === 'undefined') return {};\n if (!Object.hasOwn(window, globalKey)) return {};\n const raw = (window as unknown as Record<string, unknown>)[globalKey];\n return raw !== null && typeof raw === 'object' && !Array.isArray(raw) ? (raw as ConfigSource) : {};\n}\n\n/** An explicit source over a plain record — the injection seam for tests and for values resolved elsewhere. */\nexport function staticSource(values: Record<string, string | undefined>): ConfigSource {\n return values;\n}\n\n/** The default source order: runtime `window.__APP_CONFIG__` layered ahead of build-time `import.meta.env`. */\nexport function defaultSources(): ReadonlyArray<ConfigSource> {\n return [windowConfigSource(), importMetaEnvSource()];\n}\n\n/**\n * Resolves `key` across an ordered source list, first non-empty match wins (earlier source = higher priority).\n * A non-string hit (e.g. `import.meta.env.DEV` is a boolean) is coerced to its string form; an empty string is\n * treated as absent so an unset-but-declared env var falls through to the next source or the field default.\n */\nexport function resolveRaw(sources: ReadonlyArray<ConfigSource>, key: string): string | undefined {\n for (const source of sources) {\n if (!Object.hasOwn(source, key)) continue;\n const hit = (source as Record<string, unknown>)[key];\n if (hit === undefined || hit === null) continue;\n const asString = typeof hit === 'string' ? hit : String(hit);\n if (asString.length === 0) continue;\n return asString;\n }\n return undefined;\n}\n","// The typed-env engine. `defineConfig(schema, options)` reads each declared key from an ordered source list,\n// parses it through its `ConfigField`, applies defaults, and returns a frozen, fully-typed config object. Unlike\n// storage (which degrades silently), config fails LOUD: every missing-required and invalid-value problem is\n// collected across the whole schema and thrown together as one `ConfigError` at startup — so a misconfigured\n// deploy surfaces all its problems at once, not one boot-crash at a time.\n\nimport type { AnyConfigField, ConfigField } from './ConfigField';\nimport { defaultSources, resolveRaw, type ConfigSource } from './ConfigSource';\n\n/** A schema: a map from output key to its field spec. */\nexport type ConfigSchema = Readonly<Record<string, AnyConfigField>>;\n\n/** Widens an optional field's output to include `undefined`; a required / defaulted field stays `T`. */\ntype InferField<F> =\n F extends ConfigField<infer T, infer Optional> ? (Optional extends true ? T | undefined : T) : never;\n\n/** The resolved, typed config object inferred from a schema. */\nexport type InferConfig<S extends ConfigSchema> = { readonly [K in keyof S]: InferField<S[K]> };\n\n/** Tunes where `defineConfig` reads from and how keys are namespaced. */\nexport interface DefineConfigOptions {\n /** The ordered source list; earlier wins. Defaults to `[window.__APP_CONFIG__, import.meta.env]`. */\n readonly sources?: ReadonlyArray<ConfigSource>;\n\n /** A prefix prepended to every schema key on lookup (e.g. `'VITE_'` → key `API_URL` reads `VITE_API_URL`). */\n readonly prefix?: string;\n}\n\n/** One resolution failure — a missing required key or a value that failed its field's `parse`. */\nexport interface ConfigIssue {\n /** The schema key (output name, without the lookup prefix). */\n readonly key: string;\n\n /** The full source key looked up (with prefix). */\n readonly lookupKey: string;\n\n /** Why it failed. */\n readonly reason: 'missing' | 'invalid';\n\n /** A human-readable description; a `secret` field's raw value is never included. */\n readonly message: string;\n}\n\n/** Thrown by `defineConfig` when one or more keys are missing or invalid — aggregates every issue found. */\nexport class ConfigError extends Error {\n /** Every resolution failure across the schema. */\n readonly issues: ReadonlyArray<ConfigIssue>;\n\n constructor(issues: ReadonlyArray<ConfigIssue>) {\n const lines = issues.map((issue) => ` - ${issue.lookupKey}: ${issue.message}`).join('\\n');\n super(`Invalid configuration (${issues.length} ${issues.length === 1 ? 'issue' : 'issues'}):\\n${lines}`);\n this.name = 'ConfigError';\n this.issues = Object.freeze(issues.map((issue) => Object.freeze({ ...issue })));\n // Restore the prototype chain across the ES5 `Error` transpilation target so `instanceof` holds.\n Object.setPrototypeOf(this, ConfigError.prototype);\n }\n}\n\n/**\n * Resolves a typed configuration object from `schema`. Each key is looked up across the source list (prefix\n * applied), parsed through its field, and defaulted when absent. Empty strings count as absent. All missing /\n * invalid problems are aggregated and thrown together as a single {@link ConfigError}; on success the returned\n * object is frozen. Pass an explicit `sources` (e.g. `[staticSource({...})]`) to make resolution deterministic\n * in tests.\n */\nexport function defineConfig<const S extends ConfigSchema>(schema: S, options?: DefineConfigOptions): InferConfig<S> {\n const sources = options?.sources ?? defaultSources();\n const prefix = options?.prefix ?? '';\n\n const resolved: Record<string, unknown> = Object.create(null);\n const issues: ConfigIssue[] = [];\n\n for (const [key, field] of Object.entries(schema) as [string, AnyConfigField][]) {\n const lookupKey = `${prefix}${key}`;\n const raw = resolveRaw(sources, lookupKey);\n\n if (raw === undefined) {\n if (field.hasDefault) {\n try {\n const value = field.createDefault ? field.createDefault() : field.defaultValue;\n if (value === undefined) throw new TypeError('Config defaults cannot be undefined.');\n resolved[key] = value;\n } catch {\n issues.push({ key, lookupKey, reason: 'invalid', message: `invalid ${field.typeName} default` });\n }\n } else if (!field.required) {\n resolved[key] = undefined;\n } else {\n issues.push({ key, lookupKey, reason: 'missing', message: `missing required ${field.typeName}` });\n }\n continue;\n }\n\n try {\n resolved[key] = field.parse(raw);\n } catch (error) {\n // A field's `parse` throws a `string` describing the failure; anything else is coerced defensively.\n const detail = typeof error === 'string' ? error : `invalid ${field.typeName}`;\n // Never leak a secret's raw value — the field's own message may quote it, so replace it wholesale.\n const message = field.secret ? `invalid ${field.typeName} (value redacted)` : detail;\n issues.push({ key, lookupKey, reason: 'invalid', message });\n }\n }\n\n if (issues.length > 0) throw new ConfigError(issues);\n\n return Object.freeze(resolved) as InferConfig<S>;\n}\n"],"names":[],"mappings":";;;AAkEA,SAAS,YACP,UACA,OACA,SACyB;AACzB,QAAM,WAAW,YAAY,UAAa,OAAO,OAAO,SAAS,SAAS;AA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AAW,QAAQ,WAAW,SAAS;AAAA,IAC5D;AAAA,EACF;AAEA,MAAI,OAAO,SAAS,EAAG,OAAM,IAAI,YAAY,MAAM;AAEnD,SAAO,OAAO,OAAO,QAAQ;AAC/B;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../src/foundation/config/ConfigField.ts","../../../src/foundation/config/ConfigSource.ts","../../../src/foundation/config/DefineConfig.ts"],"sourcesContent":["import { LosslessJson } from '../json';\nimport { ResultExtensions, type Result } from '../results';\n\n// Typed-env field specs. A `ConfigField<T>` describes how one configuration key is parsed from its raw\n// string form, whether it is required, and its fallback — the atoms `defineConfig` reads a source through.\n// Each builder (`str`, `num`, `bool`, `oneOf`, `url`, `port`, `json`, `list`) returns a field whose `parse`\n// handles only a *present* raw string and throws a human-readable message on an invalid value; the engine\n// owns the missing / default / required decision centrally, so a field never re-implements that policy.\n\n/** Tunes one field's presence policy and fallback. A `default` (or `required: false`) makes the field optional. */\nexport interface ConfigFieldOptions<T> {\n /** Marks the field required. Defaults to `true` unless a `default` is supplied. */\n readonly required?: boolean;\n\n /** The value used when the key is absent or empty. Supplying it makes the field optional. */\n readonly default?: T;\n\n /** Creates an independent fallback for each resolution; use for mutable values. */\n readonly defaultFactory?: () => T;\n\n /** Redacts the raw value from `ConfigError` messages — set for tokens, keys, and passwords. */\n readonly secret?: boolean;\n}\n\n/**\n * Describes a single configuration key: its scalar type, presence policy, and how to parse a present raw\n * string into `T`. `Optional` is a phantom flag the schema inference reads to widen the output to `T | undefined`\n * for a field that is `required: false` with no `default`.\n */\nexport interface ConfigField<T, Optional extends boolean = false> {\n /** The human-facing type name used in error messages (`string`, `number`, `one of [...]`, …). */\n readonly typeName: string;\n\n /** Whether a missing key is an error. `false` when a `default` is present or `required: false`. */\n readonly required: boolean;\n\n /** Whether an explicit `default` was supplied. */\n readonly hasDefault: boolean;\n\n /** The configured fallback, meaningful only when `hasDefault` is `true`. */\n readonly defaultValue?: T;\n\n /** Builds an independent fallback when configured. */\n readonly createDefault?: () => T;\n\n /** Whether the raw value is redacted from error output. */\n readonly secret: boolean;\n\n /** Phantom marker: `true` widens the inferred output type to `T | undefined`. Never read at runtime. */\n readonly __optional?: Optional;\n\n /** Parses a present, non-empty raw string into `T`; throws a `string` message describing the failure. */\n parse(raw: string): T;\n}\n\n/** Computes a field's phantom optionality from its options — optional iff no `default` and `required: false`. */\ntype Optionality<O> = O extends { default: unknown } | { defaultFactory: unknown }\n ? false\n : O extends { required: false }\n ? true\n : false;\n\n/** The upper bound for a field of unknown scalar type — every concrete `ConfigField<T, …>` is assignable to it. */\nexport type AnyConfigField = ConfigField<unknown, boolean>;\n\n/** Shared field constructor — folds the options into the runtime presence policy around a scalar `parse`. */\nfunction createField<T>(\n typeName: string,\n parse: (raw: string) => T,\n options: ConfigFieldOptions<T> | undefined,\n): ConfigField<T, boolean> {\n const hasValue = options !== undefined && Object.hasOwn(options, 'default');\n const hasFactory = options !== undefined && Object.hasOwn(options, 'defaultFactory');\n if (hasValue && hasFactory) throw new TypeError('Choose default or defaultFactory, not both.');\n if (\n hasValue &&\n (options.default === undefined ||\n (typeof options.default === 'object' && options.default !== null) ||\n typeof options.default === 'function')\n ) {\n throw new TypeError('Use defaultFactory for mutable config defaults; undefined is not a default.');\n }\n if (hasFactory && typeof options.defaultFactory !== 'function')\n throw new TypeError('defaultFactory must be a function.');\n const hasDefault = hasValue || hasFactory;\n return Object.freeze({\n typeName,\n parse,\n hasDefault,\n defaultValue: hasValue ? options.default : undefined,\n createDefault: hasFactory ? options.defaultFactory : undefined,\n // A field is required unless it carries a default or is explicitly opted out.\n required: hasDefault ? false : (options?.required ?? true),\n secret: options?.secret ?? false,\n });\n}\n\n/** A string field — preserves the raw value; empty strings are handled as missing by resolution. */\nexport function str<const O extends ConfigFieldOptions<string> = ConfigFieldOptions<string>>(\n options?: O,\n): ConfigField<string, Optionality<O>> {\n return createField('string', (raw) => raw, options) as ConfigField<string, Optionality<O>>;\n}\n\n/** A finite-number field — rejects any raw string that does not parse to a finite JS number. */\nexport function num<const O extends ConfigFieldOptions<number> = ConfigFieldOptions<number>>(\n options?: O,\n): ConfigField<number, Optionality<O>> {\n return createField(\n 'number',\n (raw) => {\n const value = Number(raw);\n if (!Number.isFinite(value)) throw `expected a number, got \"${raw}\"`;\n return value;\n },\n options,\n ) as ConfigField<number, Optionality<O>>;\n}\n\n/** The raw spellings each boolean side accepts, case-insensitively. */\nconst TrueTokens = new Set(['true', '1', 'yes', 'on']);\nconst FalseTokens = new Set(['false', '0', 'no', 'off']);\n\n/** A boolean field — accepts `true/1/yes/on` and `false/0/no/off` (case-insensitive); rejects anything else. */\nexport function bool<const O extends ConfigFieldOptions<boolean> = ConfigFieldOptions<boolean>>(\n options?: O,\n): ConfigField<boolean, Optionality<O>> {\n return createField(\n 'boolean',\n (raw) => {\n const token = raw.trim().toLowerCase();\n if (TrueTokens.has(token)) return true;\n if (FalseTokens.has(token)) return false;\n throw `expected a boolean (true/false/1/0/yes/no/on/off), got \"${raw}\"`;\n },\n options,\n ) as ConfigField<boolean, Optionality<O>>;\n}\n\n/** An enum field — the value must be one of `values`; the output type narrows to that literal union. */\nexport function oneOf<\n const V extends readonly string[],\n const O extends ConfigFieldOptions<V[number]> = ConfigFieldOptions<V[number]>,\n>(values: V, options?: O): ConfigField<V[number], Optionality<O>> {\n return createField(\n `one of [${values.join(', ')}]`,\n (raw) => {\n if ((values as readonly string[]).includes(raw)) return raw as V[number];\n throw `expected one of [${values.join(', ')}], got \"${raw}\"`;\n },\n options,\n ) as ConfigField<V[number], Optionality<O>>;\n}\n\n/** A URL field — validated with the `URL` constructor; the parsed string is returned unchanged. */\nexport function url<const O extends ConfigFieldOptions<string> = ConfigFieldOptions<string>>(\n options?: O,\n): ConfigField<string, Optionality<O>> {\n return createField(\n 'url',\n (raw) => {\n try {\n // Construct-and-discard: `URL` throws on a malformed value; we keep the caller's original string.\n void new URL(raw);\n return raw;\n } catch {\n throw `expected a valid URL, got \"${raw}\"`;\n }\n },\n options,\n ) as ConfigField<string, Optionality<O>>;\n}\n\n/** A TCP-port field — a finite integer in `1..65535`. */\nexport function port<const O extends ConfigFieldOptions<number> = ConfigFieldOptions<number>>(\n options?: O,\n): ConfigField<number, Optionality<O>> {\n return createField(\n 'port',\n (raw) => {\n const value = Number(raw);\n if (!Number.isInteger(value) || value < 1 || value > 65535) throw `expected a port in 1..65535, got \"${raw}\"`;\n return value;\n },\n options,\n ) as ConfigField<number, Optionality<O>>;\n}\n\n/** Validates a parsed JSON value; expected failures carry the decoder's own failure data. */\nexport type ConfigJsonDecoder<T> = (value: unknown) => Result<T, unknown>;\n\n/** Reads JSON without claiming a decoded application shape. Numeric tokens remain ExactNumber values. */\nexport function json<const O extends ConfigFieldOptions<unknown> = ConfigFieldOptions<unknown>>(\n options?: O,\n): ConfigField<unknown, Optionality<O>>;\n/** Decodes a lossless JSON value into a validated application shape; decoder failures reject the field. */\nexport function json<T, const O extends ConfigFieldOptions<T> = ConfigFieldOptions<T>>(\n decode: ConfigJsonDecoder<T>,\n options?: O,\n): ConfigField<T, Optionality<O>>;\nexport function json(\n decodeOrOptions?: ConfigJsonDecoder<unknown> | ConfigFieldOptions<unknown>,\n options?: ConfigFieldOptions<unknown>,\n): ConfigField<unknown, boolean> {\n const decode =\n typeof decodeOrOptions === 'function' ? decodeOrOptions : (value: unknown) => ResultExtensions.ok(value);\n return createField(\n 'json',\n (raw) => {\n const parsed = LosslessJson.parse(raw);\n if (!parsed.ok) throw 'expected valid JSON';\n const decoded = decode(parsed.value);\n if (!decoded.ok) throw 'JSON value failed its decoder';\n return decoded.value;\n },\n typeof decodeOrOptions === 'function' ? options : decodeOrOptions,\n );\n}\n\n/** Tunes how a `list` field splits its raw value. */\nexport interface ListFieldOptions extends ConfigFieldOptions<readonly string[]> {\n /** The item separator. Defaults to a comma. */\n readonly separator?: string;\n}\n\n/** A string-list field — splits on `separator` (default `,`), trims each item, and drops empty items. */\nexport function list<const O extends ListFieldOptions = ListFieldOptions>(\n options?: O,\n): ConfigField<ReadonlyArray<string>, Optionality<O>> {\n const separator = options?.separator ?? ',';\n return createField<readonly string[]>(\n 'list',\n (raw) =>\n raw\n .split(separator)\n .map((item) => item.trim())\n .filter((item) => item.length > 0),\n options,\n ) as ConfigField<readonly string[], Optionality<O>>;\n}\n","// Configuration sources — the raw key/value stores `defineConfig` reads through. Two ship by default: the\n// runtime `window.__APP_CONFIG__` global an ops team can inject per-environment without a rebuild (12-factor\n// runtime config), and the app's build-time `import.meta.env`, which the app passes in from its own module. A\n// source is a flat record of string values; `defineConfig` merges an ordered list where the *earlier* source\n// wins, so runtime config is layered ahead of build-time env. Reading a source never throws — an unavailable\n// one yields `{}`.\n//\n// The package cannot read the app's env itself: a bundler replaces `import.meta.env` only in the app's own\n// modules, never inside this prebuilt package, so the app hands over its `import.meta.env` object.\n\n/** A flat, read-only key/value store of raw configuration strings. */\nexport type ConfigSource = Readonly<Record<string, string | undefined>>;\n\n/** The default runtime-config global — `window.__APP_CONFIG__`, injected per-environment ahead of build-time env. */\nexport const DefaultRuntimeConfigKey = '__APP_CONFIG__';\n\n/** A build-time env record as a bundler exposes it — Vite's `import.meta.env`, with string and boolean values. */\nexport type ConfigEnv = Readonly<Record<string, unknown>>;\n\n/**\n * The build-time source over the app's own env — call it as `importMetaEnvSource(import.meta.env)` from an app\n * module, where the bundler inlines `import.meta.env`. Copies every string, number, boolean and bigint value as a\n * string (`DEV: true` → `'true'`) into a frozen snapshot and drops anything else. A missing or non-object `env`\n * yields `{}`.\n */\nexport function importMetaEnvSource(env: ConfigEnv | undefined): ConfigSource {\n const values: Record<string, string> = Object.create(null);\n if (env === null || typeof env !== 'object') return Object.freeze(values);\n for (const key of Object.keys(env)) {\n const value = env[key];\n if (\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean' ||\n typeof value === 'bigint'\n ) {\n values[key] = String(value);\n }\n }\n return Object.freeze(values);\n}\n\n/**\n * The runtime source — a global object (default `window.__APP_CONFIG__`) a deployment injects before the app\n * boots. Returns `{}` when there is no `window` (SSR / Node) or the global is absent or not an object.\n */\nexport function windowConfigSource(globalKey: string = DefaultRuntimeConfigKey): ConfigSource {\n if (typeof window === 'undefined') return {};\n if (!Object.hasOwn(window, globalKey)) return {};\n const raw = (window as unknown as Record<string, unknown>)[globalKey];\n return raw !== null && typeof raw === 'object' && !Array.isArray(raw) ? (raw as ConfigSource) : {};\n}\n\n/** An explicit source over a plain record — the injection seam for tests and for values resolved elsewhere. */\nexport function staticSource(values: Record<string, string | undefined>): ConfigSource {\n return values;\n}\n\n/**\n * The default source order: runtime `window.__APP_CONFIG__` layered ahead of the app's build-time env. Pass the\n * app's `import.meta.env` as `env`; without it only the runtime source is read.\n */\nexport function defaultSources(env?: ConfigEnv): ReadonlyArray<ConfigSource> {\n return env === undefined ? [windowConfigSource()] : [windowConfigSource(), importMetaEnvSource(env)];\n}\n\n/**\n * Resolves `key` across an ordered source list, first non-empty match wins (earlier source = higher priority).\n * A non-string hit (e.g. `import.meta.env.DEV` is a boolean) is coerced to its string form; an empty string is\n * treated as absent so an unset-but-declared env var falls through to the next source or the field default.\n */\nexport function resolveRaw(sources: ReadonlyArray<ConfigSource>, key: string): string | undefined {\n for (const source of sources) {\n if (!Object.hasOwn(source, key)) continue;\n const hit = (source as Record<string, unknown>)[key];\n if (hit === undefined || hit === null) continue;\n const asString = typeof hit === 'string' ? hit : String(hit);\n if (asString.length === 0) continue;\n return asString;\n }\n return undefined;\n}\n","// The typed-env engine. `defineConfig(schema, options)` reads each declared key from an ordered source list,\n// parses it through its `ConfigField`, applies defaults, and returns a frozen, fully-typed config object. Unlike\n// storage (which degrades silently), config fails LOUD: every missing-required and invalid-value problem is\n// collected across the whole schema and thrown together as one `ConfigError` at startup — so a misconfigured\n// deploy surfaces all its problems at once, not one boot-crash at a time.\n\nimport type { AnyConfigField, ConfigField } from './ConfigField';\nimport { defaultSources, resolveRaw, type ConfigEnv, type ConfigSource } from './ConfigSource';\n\n/** A schema: a map from output key to its field spec. */\nexport type ConfigSchema = Readonly<Record<string, AnyConfigField>>;\n\n/** Widens an optional field's output to include `undefined`; a required / defaulted field stays `T`. */\ntype InferField<F> =\n F extends ConfigField<infer T, infer Optional> ? (Optional extends true ? T | undefined : T) : never;\n\n/** The resolved, typed config object inferred from a schema. */\nexport type InferConfig<S extends ConfigSchema> = { readonly [K in keyof S]: InferField<S[K]> };\n\n/** Tunes where `defineConfig` reads from and how keys are namespaced. */\nexport interface DefineConfigOptions {\n /** The ordered source list; earlier wins. Defaults to `defaultSources(env)`. */\n readonly sources?: ReadonlyArray<ConfigSource>;\n\n /**\n * The app's build-time env — pass `import.meta.env` from the app's own module. Read after the runtime\n * `window.__APP_CONFIG__` when `sources` is omitted; ignored when `sources` is given.\n */\n readonly env?: ConfigEnv;\n\n /** A prefix prepended to every schema key on lookup (e.g. `'VITE_'` → key `API_URL` reads `VITE_API_URL`). */\n readonly prefix?: string;\n}\n\n/** One resolution failure — a missing required key or a value that failed its field's `parse`. */\nexport interface ConfigIssue {\n /** The schema key (output name, without the lookup prefix). */\n readonly key: string;\n\n /** The full source key looked up (with prefix). */\n readonly lookupKey: string;\n\n /** Why it failed. */\n readonly reason: 'missing' | 'invalid';\n\n /** A human-readable description; a `secret` field's raw value is never included. */\n readonly message: string;\n}\n\n/** Thrown by `defineConfig` when one or more keys are missing or invalid — aggregates every issue found. */\nexport class ConfigError extends Error {\n /** Every resolution failure across the schema. */\n readonly issues: ReadonlyArray<ConfigIssue>;\n\n constructor(issues: ReadonlyArray<ConfigIssue>) {\n const lines = issues.map((issue) => ` - ${issue.lookupKey}: ${issue.message}`).join('\\n');\n super(`Invalid configuration (${issues.length} ${issues.length === 1 ? 'issue' : 'issues'}):\\n${lines}`);\n this.name = 'ConfigError';\n this.issues = Object.freeze(issues.map((issue) => Object.freeze({ ...issue })));\n // Restore the prototype chain across the ES5 `Error` transpilation target so `instanceof` holds.\n Object.setPrototypeOf(this, ConfigError.prototype);\n }\n}\n\n/**\n * Resolves a typed configuration object from `schema`. Each key is looked up across the source list (prefix\n * applied), parsed through its field, and defaulted when absent. Empty strings count as absent. All missing /\n * invalid problems are aggregated and thrown together as a single {@link ConfigError}; on success the returned\n * object is frozen. Pass the app's `env: import.meta.env`, or an explicit `sources` (e.g.\n * `[staticSource({...})]`) to make resolution deterministic in tests.\n */\nexport function defineConfig<const S extends ConfigSchema>(schema: S, options?: DefineConfigOptions): InferConfig<S> {\n const sources = options?.sources ?? defaultSources(options?.env);\n const prefix = options?.prefix ?? '';\n\n const resolved: Record<string, unknown> = Object.create(null);\n const issues: ConfigIssue[] = [];\n\n for (const [key, field] of Object.entries(schema) as [string, AnyConfigField][]) {\n const lookupKey = `${prefix}${key}`;\n const raw = resolveRaw(sources, lookupKey);\n\n if (raw === undefined) {\n if (field.hasDefault) {\n try {\n const value = field.createDefault ? field.createDefault() : field.defaultValue;\n if (value === undefined) throw new TypeError('Config defaults cannot be undefined.');\n resolved[key] = value;\n } catch {\n issues.push({ key, lookupKey, reason: 'invalid', message: `invalid ${field.typeName} default` });\n }\n } else if (!field.required) {\n resolved[key] = undefined;\n } else {\n issues.push({ key, lookupKey, reason: 'missing', message: `missing required ${field.typeName}` });\n }\n continue;\n }\n\n try {\n resolved[key] = field.parse(raw);\n } catch (error) {\n // A field's `parse` throws a `string` describing the failure; anything else is coerced defensively.\n const detail = typeof error === 'string' ? error : `invalid ${field.typeName}`;\n // Never leak a secret's raw value — the field's own message may quote it, so replace it wholesale.\n const message = field.secret ? `invalid ${field.typeName} (value redacted)` : detail;\n issues.push({ key, lookupKey, reason: 'invalid', message });\n }\n }\n\n if (issues.length > 0) throw new ConfigError(issues);\n\n return Object.freeze(resolved) as InferConfig<S>;\n}\n"],"names":[],"mappings":";;;AAkEA,SAAS,YACP,UACA,OACA,SACyB;AACzB,QAAM,WAAW,YAAY,UAAa,OAAO,OAAO,SAAS,SAAS;AAC1E,QAAM,aAAa,YAAY,UAAa,OAAO,OAAO,SAAS,gBAAgB;AACnF,MAAI,YAAY,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I;AAAA,MAClG;AACA;AAAA,IACF;AAEA,QAAI;AACF,eAAS,GAAG,IAAI,MAAM,MAAM,GAAG;AAAA,IACjC,SAAS,OAAO;AAEd,YAAM,SAAS,OAAO,UAAU,WAAW,QAAQ,WAAW,MAAM,QAAQ;AAE5E,YAAM,UAAU,MAAM,SAAS,WAAW,MAAM,QAAQ,sBAAsB;AAC9E,aAAO,KAAK,EAAE,KAAK,WAAW,QAAQ,WAAW,SAAS;AAAA,IAC5D;AAAA,EACF;AAEA,MAAI,OAAO,SAAS,EAAG,OAAM,IAAI,YAAY,MAAM;AAEnD,SAAO,OAAO,OAAO,QAAQ;AAC/B;"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { MaybeRefOrGetter } from 'vue';
|
|
2
|
+
/** The attribute that marks an element while its content scrolls; the `scrollbar-auto-hide` styles read it. */
|
|
3
|
+
export declare const ScrollingAttribute = "data-scrolling";
|
|
4
|
+
/** The pause after the last scroll event before an element counts as idle again, in milliseconds. */
|
|
5
|
+
export declare const ScrollIdleDelay = 800;
|
|
6
|
+
type Target = HTMLElement | null | undefined;
|
|
7
|
+
/**
|
|
8
|
+
* Marks `target` with `data-scrolling` while it scrolls and removes the mark `ScrollIdleDelay` after the last
|
|
9
|
+
* scroll event — the signal a `scrollbar-auto-hide` element needs to show its thumb on touch devices, where no
|
|
10
|
+
* pointer hovers it. The attribute is written on the element itself, so a scroll never re-renders the component
|
|
11
|
+
* that owns it. `isEnabled` gates the whole behaviour: while it is `false` nothing is marked, and turning it off
|
|
12
|
+
* clears a mark already set.
|
|
13
|
+
*/
|
|
14
|
+
export declare function useScrollActivity(target: MaybeRefOrGetter<Target>, isEnabled?: MaybeRefOrGetter<boolean>): void;
|
|
15
|
+
export {};
|
|
@@ -13,6 +13,7 @@ export * from './hooks/UseEventListener';
|
|
|
13
13
|
export * from './hooks/UseOutsideClick';
|
|
14
14
|
export * from './hooks/UseFocusTrap';
|
|
15
15
|
export * from './hooks/UseScrollLock';
|
|
16
|
+
export * from './hooks/UseScrollActivity';
|
|
16
17
|
export { DomOrderExtensions } from './DomOrderExtensions';
|
|
17
18
|
export { resolveElement } from './ResolveElement';
|
|
18
19
|
export { ScrollRegionAttribute, findScrollRegions } from './ScrollRegion';
|
|
@@ -3,15 +3,16 @@ import { d } from "../../chunks/DataAttr-7BR67dTj.js";
|
|
|
3
3
|
import { P } from "../../chunks/PressExtensions-DXqhjlR2.js";
|
|
4
4
|
import { B, H } from "../../chunks/HtmlValues-jlKY5f9C.js";
|
|
5
5
|
import { K } from "../../chunks/Key-CQlkK53D.js";
|
|
6
|
-
import { E, u } from "../../chunks/index-
|
|
6
|
+
import { E, u } from "../../chunks/index-COgbQxBT.js";
|
|
7
7
|
import { A } from "../../chunks/AriaAttribute-CmUjjXjp.js";
|
|
8
8
|
import { A as A2, D, u as u2 } from "../../chunks/UseOutsideClick-8TTSb9x6.js";
|
|
9
9
|
import { U } from "../../chunks/UrlExtensions-DqgLm0KY.js";
|
|
10
10
|
import { u as u3 } from "../../chunks/UseEventListener-C1WgWGoT.js";
|
|
11
11
|
import { u as u4 } from "../../chunks/UseScrollLock-BAu79cm4.js";
|
|
12
|
+
import { S, a, u as u5 } from "../../chunks/UseScrollActivity-D8MC5xgH.js";
|
|
12
13
|
import { D as D2 } from "../../chunks/DomOrderExtensions-Czsyvn6e.js";
|
|
13
14
|
import { r } from "../../chunks/ResolveElement-CyRfM82x.js";
|
|
14
|
-
import { S, f } from "../../chunks/ScrollRegion-CO8KnKUY.js";
|
|
15
|
+
import { S as S2, f } from "../../chunks/ScrollRegion-CO8KnKUY.js";
|
|
15
16
|
export {
|
|
16
17
|
A as AriaAttribute,
|
|
17
18
|
A2 as AttributeValue,
|
|
@@ -22,7 +23,9 @@ export {
|
|
|
22
23
|
H as HtmlElement,
|
|
23
24
|
K as Key,
|
|
24
25
|
P as PressExtensions,
|
|
25
|
-
S as
|
|
26
|
+
S as ScrollIdleDelay,
|
|
27
|
+
S2 as ScrollRegionAttribute,
|
|
28
|
+
a as ScrollingAttribute,
|
|
26
29
|
U as UrlExtensions,
|
|
27
30
|
c as composeEventHandlers,
|
|
28
31
|
d as dataAttr,
|
|
@@ -31,6 +34,7 @@ export {
|
|
|
31
34
|
u3 as useEventListener,
|
|
32
35
|
u as useFocusTrap,
|
|
33
36
|
u2 as useOutsideClick,
|
|
37
|
+
u5 as useScrollActivity,
|
|
34
38
|
u4 as useScrollLock
|
|
35
39
|
};
|
|
36
40
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { _ } from "../../chunks/AnchoredPositioner.vue_vue_type_script_setup_true_lang-BpBVI2Cu.js";
|
|
2
2
|
import { _ as _2, P } from "../../chunks/Announce.vue_vue_type_script_setup_true_lang-DbqODft3.js";
|
|
3
|
-
import { A, _ as _3, C, a, b, c, d, e } from "../../chunks/index-
|
|
3
|
+
import { A, _ as _3, C, a, b, c, d, e } from "../../chunks/index-Dp6L9sX7.js";
|
|
4
4
|
import { _ as _4 } from "../../chunks/DismissableLayer.vue_vue_type_script_setup_true_lang-B8hZrhek.js";
|
|
5
5
|
import { _ as _5 } from "../../chunks/FocusScope.vue_vue_type_script_setup_true_lang-C4XeQoxg.js";
|
|
6
6
|
import { _ as _6 } from "../../chunks/FormControlProvider.vue_vue_type_script_setup_true_lang-D_yikT2o.js";
|
|
@@ -19,12 +19,19 @@ export interface ScrollViewportProps extends /* @vue-ignore */ HTMLAttributes {
|
|
|
19
19
|
readonly isAnimated?: boolean;
|
|
20
20
|
/** @deprecated Use `isAnimated`; this alias is removed next release. */
|
|
21
21
|
readonly animate?: boolean;
|
|
22
|
+
/**
|
|
23
|
+
* Fades the scrollbar thumb while the area is idle and brings it back on hover and while it scrolls. The track
|
|
24
|
+
* keeps its space, so the layout never shifts.
|
|
25
|
+
* @default false
|
|
26
|
+
*/
|
|
27
|
+
readonly hasAutoHideScrollbar?: boolean;
|
|
22
28
|
}
|
|
23
29
|
declare const _default: __VLS_WithSlots<import('vue').DefineComponent<{
|
|
24
30
|
height?: number | string;
|
|
25
31
|
maxHeight?: number | string;
|
|
26
32
|
isAnimated?: boolean;
|
|
27
33
|
animate?: boolean;
|
|
34
|
+
hasAutoHideScrollbar?: boolean;
|
|
28
35
|
}, {
|
|
29
36
|
el: Readonly<import('vue').ShallowRef<HTMLDivElement | null>>;
|
|
30
37
|
}, {}, {}, {}, import('vue').ComponentOptionsMixin, import('vue').ComponentOptionsMixin, {}, string, import('vue').PublicProps, Readonly<{
|
|
@@ -32,9 +39,11 @@ declare const _default: __VLS_WithSlots<import('vue').DefineComponent<{
|
|
|
32
39
|
maxHeight?: number | string;
|
|
33
40
|
isAnimated?: boolean;
|
|
34
41
|
animate?: boolean;
|
|
42
|
+
hasAutoHideScrollbar?: boolean;
|
|
35
43
|
}> & Readonly<{}>, {
|
|
36
44
|
animate: boolean;
|
|
37
45
|
isAnimated: boolean;
|
|
46
|
+
hasAutoHideScrollbar: boolean;
|
|
38
47
|
}, {}, {}, {}, string, import('vue').ComponentProvideOptions, false, {}, any>, {
|
|
39
48
|
/** The scrollable content inside the viewport. */
|
|
40
49
|
default(): unknown;
|
|
@@ -1,10 +1,9 @@
|
|
|
1
1
|
import { c } from "../../chunks/Cn-C7De6POU.js";
|
|
2
|
-
import { A, C, R, S } from "../../chunks/
|
|
3
|
-
import { C as C2, a } from "../../chunks/ColorExtensions-DiCSaVbJ.js";
|
|
4
|
-
import { S as S2, s } from "../../chunks/SurfaceStyles-
|
|
5
|
-
import { D, L, l } from "../../chunks/index-
|
|
6
|
-
import { P, R as R2, S as S3, T } from "../../chunks/StyleTokens-Bkz7Dm5L.js";
|
|
7
|
-
import { a as a2, T as T2 } from "../../chunks/Tones-CQu-OvAk.js";
|
|
2
|
+
import { A, C, R, S, a, T } from "../../chunks/Tones-Bcz8dIo3.js";
|
|
3
|
+
import { C as C2, a as a2 } from "../../chunks/ColorExtensions-DiCSaVbJ.js";
|
|
4
|
+
import { S as S2, s } from "../../chunks/SurfaceStyles-BYvRlsWe.js";
|
|
5
|
+
import { D, L, l } from "../../chunks/index-CGIXFfl9.js";
|
|
6
|
+
import { P, R as R2, S as S3, T as T2 } from "../../chunks/StyleTokens-Bkz7Dm5L.js";
|
|
8
7
|
import { S as S4 } from "../../chunks/Severity-D0C5oAt-.js";
|
|
9
8
|
import { O } from "../../chunks/Orientation-u-sYunuG.js";
|
|
10
9
|
import { A as A2 } from "../../chunks/Align-DqFtCY3a.js";
|
|
@@ -18,7 +17,7 @@ export {
|
|
|
18
17
|
A as AbsolutePositionPreset,
|
|
19
18
|
A2 as Align,
|
|
20
19
|
C2 as ColorExtensions,
|
|
21
|
-
|
|
20
|
+
a2 as ColorTone,
|
|
22
21
|
C3 as CornerPosition,
|
|
23
22
|
C as CssExtensions,
|
|
24
23
|
D as Density,
|
|
@@ -35,9 +34,9 @@ export {
|
|
|
35
34
|
S as SizePreset,
|
|
36
35
|
S6 as StatusTone,
|
|
37
36
|
S2 as SurfaceVariant,
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
37
|
+
T2 as Tone,
|
|
38
|
+
a as ToneFamily,
|
|
39
|
+
T as Tones,
|
|
41
40
|
c as cn,
|
|
42
41
|
l as layerStyle,
|
|
43
42
|
s as surfaceVariants,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;"}
|