@unterberg/nivel 0.0.3 → 0.0.5

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/mdx/code-blocks/ChoiceGroup.tsx","../src/mdx/code-blocks/CodeBlockHeaderMeta.tsx","../src/mdx/code-blocks/CopyButton.tsx","../src/mdx/code-blocks/context.tsx","../src/mdx/code-blocks/useRestoreScroll.ts","../src/mdx/code-blocks/useSelectedChoice.ts","../src/mdx/code-blocks/CodeBlockTransformer.tsx","../src/mdx/code-blocks/FileState.tsx","../src/mdx/code-blocks/Pre.tsx","../src/mdx/components/Alert.tsx","../src/mdx/components/Link.tsx","../src/mdx/components/Overview.tsx","../src/mdx/components/RepoLink.tsx","../src/mdx/components/Table.tsx"],"sourcesContent":["export { ChoiceGroup }\n\nimport { Children, isValidElement, type ReactElement, type ReactNode, useRef } from 'react'\nimport { CodeBlockHeaderMeta } from './CodeBlockHeaderMeta.js'\nimport { CodeBlockCopyButton, trimTrailingWhitespace } from './CopyButton.js'\nimport { CodeBlockGroupProvider } from './context.js'\nimport { useRestoreScroll } from './useRestoreScroll.js'\nimport { useSelectedChoice } from './useSelectedChoice.js'\n\ntype ChoiceGroupDescriptor = {\n default: string\n disabled: string[]\n name: string\n choices: string[]\n}\n\ntype ChoiceElementProps = {\n children?: ReactNode\n 'data-choice-value'?: string\n}\n\nconst isChoiceElement = (node: ReactNode): node is ReactElement<ChoiceElementProps> => {\n return isValidElement<ChoiceElementProps>(node) && typeof node.props?.['data-choice-value'] === 'string'\n}\n\nconst asTrimmedString = (value: unknown) => {\n return typeof value === 'string' && value.trim() ? value.trim() : null\n}\n\nconst getActiveCodeBlockMeta = (node: ReactNode): { env: string | null; hideCopy: boolean; title: string | null } => {\n for (const child of Children.toArray(node)) {\n if (!isValidElement(child)) {\n continue\n }\n\n const props = child.props as {\n children?: ReactNode\n 'data-code-env'?: string\n 'data-code-title'?: string\n 'hide-menu'?: string\n }\n const env = asTrimmedString(props['data-code-env'])\n const title = asTrimmedString(props['data-code-title'])\n const hideCopy = props['hide-menu'] === 'true'\n\n if (title || env || hideCopy) {\n return { env, hideCopy, title }\n }\n\n const nestedMeta = getActiveCodeBlockMeta(props.children)\n if (nestedMeta.title || nestedMeta.env || nestedMeta.hideCopy) {\n return nestedMeta\n }\n }\n\n return { env: null, hideCopy: false, title: null }\n}\n\nconst ChoiceGroup = ({\n children,\n choiceGroup,\n hide = false,\n}: {\n children: ReactNode\n choiceGroup: ChoiceGroupDescriptor\n hide?: boolean\n lvl?: number\n}) => {\n const [selectedChoice, setSelectedChoice] = useSelectedChoice(choiceGroup.name, choiceGroup.default)\n const bodyRef = useRef<HTMLDivElement>(null)\n const previousPositionRef = useRestoreScroll([selectedChoice])\n const choiceElements = Children.toArray(children).filter(isChoiceElement)\n const activeChoiceElement =\n choiceElements.find((choiceElement) => choiceElement.props['data-choice-value'] === selectedChoice) ??\n choiceElements[0]\n\n if (!activeChoiceElement) {\n return <>{children}</>\n }\n\n const activeCodeBlockMeta = getActiveCodeBlockMeta(activeChoiceElement.props.children)\n const headerLabel = activeCodeBlockMeta.title ?? activeChoiceElement.props['data-choice-value'] ?? ''\n\n if (hide) {\n return <>{activeChoiceElement.props.children}</>\n }\n\n return (\n <div\n data-choice-group-outer\n className=\"mt-5 mb-5 flex h-full flex-col overflow-hidden rounded-box border border-base-muted-light\"\n >\n <div\n className=\"not-prose flex min-h-10 items-center relative justify-between gap-3 border-b border-base-muted-light bg-base-muted-superlight px-4\"\n data-choice-group-header\n >\n <CodeBlockHeaderMeta label={headerLabel} env={activeCodeBlockMeta.env} />\n <div className=\"flex items-center gap-1\">\n <label className=\"select select-xs min-w-28 w-fit\">\n <select\n name={`choicesFor-${choiceGroup.name}`}\n value={activeChoiceElement.props['data-choice-value']}\n onChange={(event) => {\n previousPositionRef.current = {\n top: event.currentTarget.getBoundingClientRect().top,\n element: event.currentTarget,\n }\n setSelectedChoice(event.currentTarget.value)\n }}\n >\n {choiceGroup.choices.map((choice) => (\n <option key={choice} value={choice} disabled={choiceGroup.disabled.includes(choice)}>\n {choice}\n </option>\n ))}\n </select>\n </label>\n {!activeCodeBlockMeta.hideCopy && (\n <CodeBlockCopyButton\n onCopy={async () => {\n const text = trimTrailingWhitespace(bodyRef.current?.textContent ?? '')\n\n try {\n await navigator.clipboard.writeText(text)\n return true\n } catch {\n return false\n }\n }}\n />\n )}\n </div>\n </div>\n <div ref={bodyRef} className=\"h-full flex-1 bg-base-200! [&>*:first-child]:mt-0 [&>*:last-child]:mb-0\">\n <CodeBlockGroupProvider value={true}>{activeChoiceElement.props.children}</CodeBlockGroupProvider>\n </div>\n </div>\n )\n}\n","import cm from '@classmatejs/react'\n\nexport { CodeBlockHeaderMeta }\n\nconst CodeBlockHeaderMeta = ({ env, label }: { env?: string | null; label: string }) => {\n const effectiveEnv = env === 'server' || env === 'client' ? env : undefined\n\n return (\n <div className=\"flex min-w-0 items-center gap-2\">\n {env && <StyledDivider $env={env === 'server' || env === 'client' ? env : undefined} />}\n {env && <StyledBgShade $env={env === 'server' || env === 'client' ? env : undefined} />}\n <div className=\"font-mono text-xs font-semibold text-base-muted\">{label}</div>\n {env && <StyledBadge $env={effectiveEnv}>{env}</StyledBadge>}\n </div>\n )\n}\n\nconst StyledDivider = cm.div.variants<{ $env?: 'server' | 'client' }>({\n base: 'absolute h-1 -bottom-px left-0 w-full pointer-events-none',\n variants: {\n $env: {\n server: 'border-info/50 border-b ',\n client: 'border-success/50 border-b',\n },\n },\n defaultVariants: { $env: 'server' },\n})\n\nconst StyledBadge = cm.div.variants<{ $env?: 'server' | 'client' }>({\n base: 'shrink-0 badge badge-sm rounded-field badge-soft border pointer-events-none',\n variants: {\n $env: {\n server: 'badge-info border-info',\n client: 'badge-success border-success',\n },\n },\n defaultVariants: { $env: 'server' },\n})\n\nconst StyledBgShade = cm.div.variants<{ $env?: 'server' | 'client' }>({\n base: 'absolute inset-0 opacity-5 bg-linear-to-t via-40% via-transparent pointer-events-none',\n variants: {\n $env: {\n server: 'from-info',\n client: 'from-success',\n },\n },\n defaultVariants: { $env: 'server' },\n})\n","export { CodeBlockCopyButton, trimTrailingWhitespace }\n\nimport { cmMerge } from '@classmatejs/react'\nimport { Check, Copy } from 'lucide-react'\nimport { useState } from 'react'\n\nconst trimTrailingWhitespace = (text: string) => {\n return text\n .split('\\n')\n .map((line) => line.trimEnd())\n .join('\\n')\n}\n\nconst CodeBlockCopyButton = ({\n onCopy,\n className = '',\n}: {\n onCopy: () => Promise<boolean> | boolean\n className?: string\n}) => {\n const [copyState, setCopyState] = useState<'idle' | 'success' | 'error'>('idle')\n\n return (\n <button\n type=\"button\"\n className={cmMerge('btn btn-ghost btn-xs h-8 min-h-8 px-2 text-base-muted hover:text-base-content', className)}\n onClick={async () => {\n const success = await onCopy()\n setCopyState(success ? 'success' : 'error')\n window.setTimeout(() => setCopyState('idle'), 900)\n }}\n aria-label={copyState === 'idle' ? 'Copy to clipboard' : copyState === 'success' ? 'Copied' : 'Copy failed'}\n >\n {copyState === 'success' ? <Check size={14} /> : <Copy size={14} />}\n </button>\n )\n}\n","import { createContext, useContext } from 'react'\n\nconst CodeBlockGroupContext = createContext(false)\n\nexport const CodeBlockGroupProvider = CodeBlockGroupContext.Provider\n\nexport const useIsInCodeBlockGroup = () => useContext(CodeBlockGroupContext)\n","import { useEffect, useRef } from 'react'\n\ntype ScrollPosition = {\n top: number\n element: Element\n}\n\nexport const useRestoreScroll = (deps: ReadonlyArray<unknown>) => {\n const previousPositionRef = useRef<ScrollPosition | null>(null)\n\n useEffect(() => {\n if (!previousPositionRef.current) {\n return\n }\n\n const { top, element } = previousPositionRef.current\n const delta = element.getBoundingClientRect().top - top\n\n if (delta !== 0) {\n window.scrollBy(0, delta)\n }\n\n previousPositionRef.current = null\n // biome-ignore lint/correctness/useExhaustiveDependencies: restore only when the tracked value changes\n }, deps)\n\n return previousPositionRef\n}\n","import { useEffect, useState, useSyncExternalStore } from 'react'\nimport { useUniversalMdxRuntime } from '../components/UniversalMdxProvider.js'\n\nconst subscribeNoop = () => () => {}\nconst getServerSnapshot = () => null\n\nexport const useSelectedChoice = (choiceGroupName: string, defaultValue: string) => {\n const runtime = useUniversalMdxRuntime()\n const choiceStore = runtime?.codeBlockChoices\n const storedChoice = useSyncExternalStore(\n choiceStore?.subscribe ?? subscribeNoop,\n () => choiceStore?.getChoice(choiceGroupName) ?? null,\n getServerSnapshot,\n )\n const [localChoice, setLocalChoice] = useState(defaultValue)\n\n useEffect(() => {\n if (!choiceStore || storedChoice) {\n return\n }\n\n const legacyChoice = choiceStore.getLegacyChoice?.(choiceGroupName)\n if (legacyChoice) {\n choiceStore.setChoice(choiceGroupName, legacyChoice)\n }\n }, [choiceGroupName, choiceStore, storedChoice])\n\n if (choiceStore) {\n return [storedChoice ?? defaultValue, (value: string) => choiceStore.setChoice(choiceGroupName, value)] as const\n }\n\n return [localChoice, setLocalChoice] as const\n}\n","export { CodeBlockTransformer }\nexport type { LineBreak }\n\nimport type { ReactNode } from 'react'\n\ntype LineBreak = 'white-space' | 'break-word'\n\nconst CodeBlockTransformer = ({ children, lineBreak }: { children: ReactNode; lineBreak: LineBreak }) => {\n const className = `with-line-break_${lineBreak}` as const\n return <div className={className}>{children}</div>\n}\n","export { FileAdded, FileRemoved }\n\nimport type { ReactNode } from 'react'\n\nconst FileAdded = ({ children }: { children: ReactNode }) => {\n return <div className=\"doc-code-file-state doc-code-file-added\">{children}</div>\n}\n\nconst FileRemoved = ({ children }: { children: ReactNode }) => {\n return <div className=\"doc-code-file-state doc-code-file-removed\">{children}</div>\n}\n","export { Pre }\n\nimport { cmMerge } from '@classmatejs/react'\nimport {\n Children,\n type ComponentPropsWithoutRef,\n isValidElement,\n type ReactElement,\n type ReactNode,\n useRef,\n} from 'react'\nimport { CodeBlockHeaderMeta } from './CodeBlockHeaderMeta.js'\nimport { CodeBlockCopyButton, trimTrailingWhitespace } from './CopyButton.js'\nimport { useIsInCodeBlockGroup } from './context.js'\n\ntype PreProps = ComponentPropsWithoutRef<'pre'> & {\n 'data-code-env'?: string\n 'data-code-title'?: string\n 'data-language'?: string\n 'data-language-label'?: string\n 'file-added'?: string\n 'file-removed'?: string\n 'hide-menu'?: string\n}\n\nconst asTrimmedString = (value: unknown) => {\n return typeof value === 'string' && value.trim() ? value.trim() : null\n}\n\nconst getLanguageFromChildren = (children: ReactNode) => {\n const firstChild = Children.toArray(children)[0]\n if (!isValidElement(firstChild)) {\n return null\n }\n\n const props = (firstChild as ReactElement<{ className?: string; 'data-language'?: string }>).props\n const explicitLanguage = asTrimmedString(props['data-language'])\n if (explicitLanguage) {\n return explicitLanguage\n }\n\n const classNames = typeof props.className === 'string' ? props.className.split(/\\s+/) : []\n const languageClassName = classNames.find((className) => className.startsWith('language-'))\n return languageClassName ? languageClassName.slice('language-'.length) : null\n}\n\nconst getLanguageLabel = (props: PreProps) => {\n const explicitLabel = asTrimmedString(props['data-language-label'])\n if (explicitLabel) {\n return explicitLabel\n }\n\n const explicitLanguage = asTrimmedString(props['data-language']) ?? getLanguageFromChildren(props.children)\n return explicitLanguage ? explicitLanguage.toUpperCase() : 'CODE'\n}\n\nconst Pre = ({ children, className, ...props }: PreProps) => {\n const preRef = useRef<HTMLPreElement>(null)\n const isInChoiceGroup = useIsInCodeBlockGroup()\n const label = asTrimmedString(props['data-code-title']) ?? getLanguageLabel(props)\n const env = asTrimmedString(props['data-code-env'])\n const fileState = props['file-added'] ? 'added' : props['file-removed'] ? 'removed' : null\n const hideMenu = props['hide-menu'] === 'true'\n\n const copyButton =\n hideMenu || isInChoiceGroup ? null : (\n <CodeBlockCopyButton\n onCopy={async () => {\n const text = trimTrailingWhitespace(preRef.current?.textContent ?? '')\n\n try {\n await navigator.clipboard.writeText(text)\n return true\n } catch {\n return false\n }\n }}\n />\n )\n\n return (\n <div\n className={cmMerge(\n 'group relative h-full not-prose overflow-hidden',\n isInChoiceGroup ? '' : 'mb-6 rounded-box border border-base-muted-light',\n className,\n )}\n data-code-block-frame=\"\"\n data-file-state={fileState ?? undefined}\n >\n {!isInChoiceGroup && (\n <div\n className=\"flex min-h-10 relative items-center justify-between gap-3 border-b border-base-muted-light bg-base-muted-superlight! px-4\"\n data-code-block-header=\"\"\n >\n <CodeBlockHeaderMeta label={label} env={env} />\n {copyButton}\n </div>\n )}\n <pre\n {...props}\n ref={preRef}\n className={cmMerge('doc-code-pre m-0 h-full overflow-x-auto bg-base-200! p-4 text-sm', className)}\n data-code-block-content=\"\"\n >\n {children}\n </pre>\n </div>\n )\n}\n","import cm, { cmMerge } from '@classmatejs/react'\nimport { Check, CircleX, Info, TriangleAlert } from 'lucide-react'\nimport type { ReactNode } from 'react'\n\nexport type AlertVariant = 'info' | 'warning' | 'error' | 'success'\n\nconst alertIconMap = {\n info: Info,\n warning: TriangleAlert,\n error: CircleX,\n success: Check,\n}\n\nexport const Alert = ({\n type = 'info',\n heading,\n children,\n icon = true,\n}: {\n type?: AlertVariant\n heading?: ReactNode\n children: ReactNode\n icon?: boolean | ReactNode\n}) => {\n const AlertIcon = icon === true ? alertIconMap[type] : typeof icon === 'object' ? () => <>{icon}</> : null\n\n const alertIconTextColorClass = {\n info: 'text-info',\n warning: 'text-warning',\n error: 'text-error',\n success: 'text-success',\n }[type]\n\n return (\n <AlertOuter $variant={type}>\n {!!heading && AlertIcon && (\n <div className=\"mb-3 flex items-center gap-2\">\n <AlertIcon className={cmMerge(alertIconTextColorClass, 'float-left h-5 w-5')} />\n <AlertHeading>{heading}</AlertHeading>\n </div>\n )}\n {!(!!heading && AlertIcon) && !!heading && <AlertHeading>{heading}</AlertHeading>}\n {!(!!heading && AlertIcon) && AlertIcon && (\n <div className={cmMerge(alertIconTextColorClass, 'float-left mr-2')}>\n <AlertIcon className=\"mt-1 h-5 w-5\" />\n </div>\n )}\n {children}\n </AlertOuter>\n )\n}\n\nconst AlertOuter = cm.section.variants<{ $variant: AlertVariant }>({\n base: `\n p-4\n mt-5\n mb-5\n border\n rounded-lg\n prose-p:last:mb-0\n prose-p:mt-0\n prose-headings:first:mt-0\n prose-headings:last:mb-0\n prose-ul:first:mt-0\n prose-ul:last:mb-0\n text-sm\n `,\n variants: {\n $variant: {\n info: 'bg-info/10 border-info/30',\n warning: 'bg-warning/10 border-warning/30',\n error: 'bg-error/10 border-error/25',\n success: 'bg-success/10 border-success/35',\n },\n },\n defaultVariants: {\n $variant: 'info',\n },\n})\n\nconst AlertHeading = cm.header`\n font-bold\n text-base\n`\n","import { cmMerge } from '@classmatejs/react'\nimport type { ComponentPropsWithoutRef, ReactNode } from 'react'\nimport { withSiteBaseUrl } from '../../shared/assets.js'\nimport { useUniversalMdxRuntime } from './UniversalMdxProvider.js'\n\nexport type LinkProps = ComponentPropsWithoutRef<'a'> & {\n href?: string\n text?: string | ReactNode\n noBreadcrumb?: boolean\n doNotInferSectionTitle?: boolean\n noWarning?: boolean\n}\n\nfunction assertUsage(condition: unknown, message: string): asserts condition {\n if (!condition) {\n throw new Error(`[UniversalMdxMods][Wrong Usage] ${message}`)\n }\n}\n\nconst assertWarning = (condition: unknown, message: string) => {\n const isDev = (import.meta as ImportMeta & { env?: { DEV?: boolean } }).env?.DEV === true\n\n if (condition || !isDev) {\n return\n }\n\n console.warn(`[UniversalMdxMods][Warning] ${message}`)\n}\n\nconst parseMarkdownMini = (markdown: string) => {\n type Part = { content: string; nodeType: 'code' | 'text' }\n const parts: Part[] = []\n let current: Part | undefined\n\n for (const letter of markdown.split('')) {\n if (letter === '`') {\n if (current?.nodeType === 'code') {\n parts.push(current)\n current = undefined\n } else {\n if (current) {\n parts.push(current)\n }\n current = { nodeType: 'code', content: '' }\n }\n continue\n }\n\n current ??= { nodeType: 'text', content: '' }\n current.content += letter\n }\n\n if (current) {\n parts.push(current)\n }\n\n return (\n <>\n {parts.map((part, index) =>\n part.nodeType === 'code' ? <code key={index}>{part.content}</code> : <span key={index}>{part.content}</span>,\n )}\n </>\n )\n}\n\nconst determineSectionTitle = (href: string) => {\n const hash = href.split('#')[1]\n\n if (!hash) {\n return null\n }\n\n return hash\n .split(':~:text')[0]\n ?.split('-')\n .map((word, index) => (index === 0 ? `${word[0]?.toUpperCase() ?? ''}${word.slice(1)}` : word))\n .join(' ')\n}\n\nconst isExternalHref = (href: string) => {\n return /^(?:[a-z]+:)?\\/\\//i.test(href) || href.startsWith('mailto:') || href.startsWith('tel:')\n}\n\nconst renderLabelPart = (value: ReactNode) => {\n return typeof value === 'string' ? parseMarkdownMini(value) : value\n}\n\nconst getLinkText = ({\n isCurrentPage,\n breadcrumb,\n noBreadcrumb,\n sectionTitle,\n title,\n}: {\n isCurrentPage?: boolean\n breadcrumb?: ReactNode[]\n noBreadcrumb?: boolean\n sectionTitle?: ReactNode\n title?: ReactNode\n}) => {\n const breadcrumbParts: ReactNode[] = []\n\n if (breadcrumb) {\n breadcrumbParts.push(...breadcrumb.map((item) => renderLabelPart(item)))\n }\n\n if (title) {\n breadcrumbParts.push(renderLabelPart(title))\n }\n\n if (sectionTitle) {\n breadcrumbParts.push(renderLabelPart(sectionTitle))\n }\n\n if (noBreadcrumb || isCurrentPage) {\n return breadcrumbParts[breadcrumbParts.length - 1] ?? null\n }\n\n return (\n <>\n {breadcrumbParts.map((part, index) => (\n <span key={index}>\n {index > 0 ? ' > ' : null}\n {part}\n </span>\n ))}\n </>\n )\n}\n\nexport const Link = ({\n href,\n text,\n noBreadcrumb,\n doNotInferSectionTitle,\n noWarning,\n children,\n className,\n ...props\n}: LinkProps) => {\n const runtime = useUniversalMdxRuntime()\n\n if (typeof href !== 'string' || href === '') {\n assertWarning(false, '<Link /> is missing `href`.')\n\n return (\n <a className={cmMerge(className, 'inline-flex gap-1 items-center')} {...props}>\n {text ?? children ?? 'LINK-TARGET-NOT-FOUND'}\n </a>\n )\n }\n\n assertUsage(\n href.startsWith('/') || href.startsWith('#') || isExternalHref(href),\n `<Link href /> prop \\`href==='${href}'\\` but should be external or start with '/' or '#'`,\n )\n assertUsage(!text || !children, 'Cannot use both `text` or `children`')\n\n const content = text ?? children\n const resolvedDocLink = runtime?.resolveDocLink?.({\n href,\n doNotInferSectionTitle,\n noWarning,\n })\n const localizedHref = resolvedDocLink?.href ?? runtime?.localizeHref?.(href) ?? withSiteBaseUrl(href)\n const inferredSectionTitle =\n resolvedDocLink?.sectionTitle ?? (!doNotInferSectionTitle ? determineSectionTitle(href) : null)\n const inferredText =\n content ??\n (resolvedDocLink\n ? getLinkText({\n breadcrumb: resolvedDocLink.breadcrumb,\n isCurrentPage: resolvedDocLink.isCurrentPage,\n noBreadcrumb,\n sectionTitle: inferredSectionTitle ?? undefined,\n title: resolvedDocLink.title,\n })\n : isExternalHref(href)\n ? href\n : (inferredSectionTitle ?? 'LINK-TARGET-NOT-FOUND'))\n\n return (\n <a href={localizedHref} className={cmMerge(className, '')} {...props}>\n {inferredText}\n </a>\n )\n}\n","import type { ReactNode } from 'react'\nimport { withSiteBaseUrl } from '../../shared/assets.js'\nimport { renderInlineMarkdown } from '../../shared/renderInlineMarkdown.js'\nimport type { UniversalResolvedOverviewItem } from './types.js'\nimport { useUniversalMdxRuntime } from './UniversalMdxProvider.js'\n\ntype OverviewLinkItem = {\n title: ReactNode\n href: string\n excerpt?: ReactNode | null\n}\n\ntype OverviewDividerItem = {\n dividerText: ReactNode\n}\n\nexport type OverviewItem = OverviewLinkItem | OverviewDividerItem\n\ninterface OverviewProps {\n items: Array<string | OverviewItem>\n}\n\nconst isOverviewDividerItem = (item: string | OverviewItem): item is OverviewDividerItem =>\n typeof item === 'object' && item !== null && 'dividerText' in item\n\nfunction assertUsage(condition: unknown, message: string): asserts condition {\n if (!condition) {\n throw new Error(`[UniversalMdxMods][Wrong Usage] ${message}`)\n }\n}\n\nconst groupOverviewItems = (items: OverviewItem[]) => {\n const groups: { dividerText?: ReactNode; items: OverviewLinkItem[] }[] = []\n let currentGroup: { dividerText?: ReactNode; items: OverviewLinkItem[] } = {\n items: [],\n }\n\n const commitCurrentGroup = () => {\n if (currentGroup.items.length > 0) {\n groups.push(currentGroup)\n }\n }\n\n for (const item of items) {\n if (isOverviewDividerItem(item)) {\n commitCurrentGroup()\n currentGroup = {\n dividerText: item.dividerText,\n items: [],\n }\n continue\n }\n\n currentGroup.items.push(item)\n }\n\n commitCurrentGroup()\n\n return groups\n}\n\nconst OverviewCard = ({ excerpt, href, title }: OverviewLinkItem) => {\n return (\n <a\n href={withSiteBaseUrl(href)}\n className=\"group flex h-full flex-col gap-3 rounded-box border border-base-muted-light bg-base-muted-superlight p-5 no-underline hover:border-primary-muted-medium hover:bg-base-muted-superlight/50\"\n >\n <h3 className=\"text-lg font-semibold text-base-content\">{renderInlineMarkdown(title)}</h3>\n {excerpt ? <p className=\"text-sm leading-relaxed text-base-muted\">{renderInlineMarkdown(excerpt)}</p> : null}\n </a>\n )\n}\n\nconst normalizeOverviewItems = (\n items: Array<string | OverviewItem>,\n resolveOverviewItem?: (key: string) => UniversalResolvedOverviewItem | null,\n): OverviewItem[] => {\n return items.map((item) => {\n if (typeof item !== 'string') {\n return item\n }\n\n const resolvedItem = resolveOverviewItem?.(item)\n\n assertUsage(\n resolvedItem,\n `Overview item \"${item}\" requires runtime.resolveOverviewItem(). Pass { title, href, excerpt } manually when no resolver is available.`,\n )\n\n return resolvedItem\n })\n}\n\nexport const Overview = ({ items }: OverviewProps) => {\n const runtime = useUniversalMdxRuntime()\n const groups = groupOverviewItems(normalizeOverviewItems(items, runtime?.resolveOverviewItem))\n\n if (groups.length === 0) {\n return null\n }\n\n return (\n <div className=\"prose-headings:my-0 prose-p:my-0 my-5 flex flex-col gap-8\">\n {groups.map((group, groupIndex) => (\n <section className=\"flex flex-col gap-4\" key={groupIndex}>\n {group.dividerText ? (\n <p className=\"text-sm font-semibold uppercase tracking-wide\">{renderInlineMarkdown(group.dividerText)}</p>\n ) : null}\n <div className=\"grid gap-4 sm:grid-cols-2\">\n {group.items.map((item, itemIndex) => (\n <OverviewCard {...item} key={item.href || itemIndex} />\n ))}\n </div>\n </section>\n ))}\n </div>\n )\n}\n","type Repo = `${string}/${string}`\ntype TimestampType = `${number}.${number}`\n\nexport const RepoLink = ({ repo, timestamp }: { repo: Repo; timestamp: TimestampType }) => {\n if (!repo || repo.split('/').length !== 2) {\n throw new Error('Invalid repo')\n }\n\n return (\n <span className=\"inline-flex items-center gap-1\">\n <span className=\"bg-white font-mono font-bold h-fit px-1 text-sm!\">{timestamp}</span>\n <a href={`https://github.com/${repo}`} target=\"_blank\" rel=\"noopener\">\n GitHub &gt; <code>{repo}</code>\n </a>\n </span>\n )\n}\n","import cm from '@classmatejs/react'\n\nexport interface TableData {\n headers: string[]\n rows: string[][]\n}\n\nexport interface TableProps {\n size?: 'sm' | 'md' | 'lg'\n data: TableData\n}\n\nexport const Table = ({ size = 'md', data }: TableProps) => {\n return (\n <StyledTable $size={size}>\n <thead className=\"overflow-hidden rounded-t-box bg-base-200\">\n <tr>\n {data.headers.map((header, index) => (\n <th key={index}>{header}</th>\n ))}\n </tr>\n </thead>\n <tbody>\n {data.rows.map((row, rowIndex) => (\n <tr key={rowIndex}>\n {row.map((cell, cellIndex) => (\n <td key={cellIndex}>{cell}</td>\n ))}\n </tr>\n ))}\n </tbody>\n </StyledTable>\n )\n}\n\nconst StyledTable = cm.table.variants<{ $size: TableProps['size'] }>({\n base: `\n not-prose\n table\n w-full\n table-zebra\n mb-6\n `,\n variants: {\n $size: {\n sm: 'table-sm',\n md: 'table-md',\n lg: 'table-lg',\n },\n },\n defaultVariants: {\n $size: 'md',\n },\n})\n"],"mappings":";;;;;;;;;AAEA,SAAS,UAAU,gBAAmD,UAAAA,eAAc;;;ACFpF,OAAO,QAAQ;AAQX,SACU,KADV;AAJJ,IAAM,sBAAsB,CAAC,EAAE,KAAK,MAAM,MAA8C;AACtF,QAAM,eAAe,QAAQ,YAAY,QAAQ,WAAW,MAAM;AAElE,SACE,qBAAC,SAAI,WAAU,mCACZ;AAAA,WAAO,oBAAC,iBAAc,MAAM,QAAQ,YAAY,QAAQ,WAAW,MAAM,QAAW;AAAA,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WAAU,kCACd;AAAA,oBAAAD,MAAC,UAAK,WAAU,oDAAoD,qBAAU;AAAA,IAC9E,gBAAAC,MAAC,OAAE,MAAM,sBAAsB,IAAI,IAAI,QAAO,UAAS,KAAI,YAAW;AAAA;AAAA,MACxD,gBAAAD,MAAC,UAAM,gBAAK;AAAA,OAC1B;AAAA,KACF;AAEJ;;;AChBA,OAAOE,SAAQ;AAcX,SAIQ,OAAAC,OAJR,QAAAC,aAAA;AAFG,IAAM,QAAQ,CAAC,EAAE,OAAO,MAAM,KAAK,MAAkB;AAC1D,SACE,gBAAAA,MAAC,eAAY,OAAO,MAClB;AAAA,oBAAAD,MAAC,WAAM,WAAU,6CACf,0BAAAA,MAAC,QACE,eAAK,QAAQ,IAAI,CAAC,QAAQ,UACzB,gBAAAA,MAAC,QAAgB,oBAAR,KAAe,CACzB,GACH,GACF;AAAA,IACA,gBAAAA,MAAC,WACE,eAAK,KAAK,IAAI,CAAC,KAAK,aACnB,gBAAAA,MAAC,QACE,cAAI,IAAI,CAAC,MAAM,cACd,gBAAAA,MAAC,QAAoB,kBAAZ,SAAiB,CAC3B,KAHM,QAIT,CACD,GACH;AAAA,KACF;AAEJ;AAEA,IAAM,cAAcD,IAAG,MAAM,SAAwC;AAAA,EACnE,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAON,UAAU;AAAA,IACR,OAAO;AAAA,MACL,IAAI;AAAA,MACJ,IAAI;AAAA,MACJ,IAAI;AAAA,IACN;AAAA,EACF;AAAA,EACA,iBAAiB;AAAA,IACf,OAAO;AAAA,EACT;AACF,CAAC;","names":["useRef","jsx","jsx","useEffect","useState","useState","useEffect","jsx","jsxs","useRef","jsx","jsxs","jsx","jsx","jsx","jsx","cmMerge","Children","isValidElement","useRef","jsx","jsxs","asTrimmedString","Children","isValidElement","useRef","jsx","jsxs","cmMerge","cm","cmMerge","Check","Fragment","jsx","jsxs","cmMerge","Fragment","jsx","jsxs","cmMerge","jsx","jsxs","assertUsage","jsx","jsxs","cm","jsx","jsxs"]}
@@ -2,7 +2,7 @@ import {
2
2
  isDocsSourcePath,
3
3
  loadDocsConfig,
4
4
  syncGeneratedDocsPages
5
- } from "./chunk-DNCQR5NH.js";
5
+ } from "./chunk-UMMK73OW.js";
6
6
  import {
7
7
  nivelPublicRoute
8
8
  } from "./chunk-PYYPYIBD.js";
@@ -195,4 +195,4 @@ var nivelPagesPlugin = () => {
195
195
  export {
196
196
  nivelPagesPlugin
197
197
  };
198
- //# sourceMappingURL=chunk-K5ZYRA3G.js.map
198
+ //# sourceMappingURL=chunk-D35PFSSY.js.map
@@ -0,0 +1,9 @@
1
+ // src/docs/defineDocs.ts
2
+ var defineDocsConfig = (config) => config;
3
+ var defineDocsGraph = (graph) => graph;
4
+
5
+ export {
6
+ defineDocsConfig,
7
+ defineDocsGraph
8
+ };
9
+ //# sourceMappingURL=chunk-JSZZPQEP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/docs/defineDocs.ts"],"sourcesContent":["import type { DocsConfig, DocsGraph } from './types.js'\n\nexport const defineDocsConfig = (config: DocsConfig) => config\n\nexport const defineDocsGraph = (graph: DocsGraph) => graph\n"],"mappings":";AAEO,IAAM,mBAAmB,CAAC,WAAuB;AAEjD,IAAM,kBAAkB,CAAC,UAAqB;","names":[]}
@@ -0,0 +1,493 @@
1
+ import {
2
+ extractDocHeadings,
3
+ getResolvedPageById,
4
+ resolveDocsConfig
5
+ } from "./chunk-D7IAGT53.js";
6
+
7
+ // src/runtime/node/codegen.ts
8
+ import fs from "fs";
9
+ import path from "path";
10
+ var GENERATED_DIRNAME = "(nivel-generated)";
11
+ var writeFileIfChanged = (filePath, source) => {
12
+ const current = fs.existsSync(filePath) ? fs.readFileSync(filePath, "utf8") : null;
13
+ if (current === source) {
14
+ return;
15
+ }
16
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
17
+ fs.writeFileSync(filePath, source);
18
+ };
19
+ var toPosix = (value) => value.split(path.sep).join(path.posix.sep);
20
+ var getRelativeImportPath = (fromDirectory, toFile) => {
21
+ const relativePath = toPosix(path.relative(fromDirectory, toFile));
22
+ if (relativePath.startsWith(".")) {
23
+ return relativePath;
24
+ }
25
+ return `./${relativePath}`;
26
+ };
27
+ var serializeData = (data) => JSON.stringify(data, null, 2);
28
+ var collectFiles = (directoryPath) => {
29
+ if (!fs.existsSync(directoryPath)) {
30
+ return [];
31
+ }
32
+ const entries = fs.readdirSync(directoryPath, { withFileTypes: true });
33
+ return entries.flatMap((entry) => {
34
+ const entryPath = path.join(directoryPath, entry.name);
35
+ return entry.isDirectory() ? collectFiles(entryPath) : [entryPath];
36
+ });
37
+ };
38
+ var removeEmptyDirectories = (directoryPath, rootPath) => {
39
+ if (!fs.existsSync(directoryPath)) {
40
+ return;
41
+ }
42
+ for (const entry of fs.readdirSync(directoryPath, { withFileTypes: true })) {
43
+ if (!entry.isDirectory()) {
44
+ continue;
45
+ }
46
+ removeEmptyDirectories(path.join(directoryPath, entry.name), rootPath);
47
+ }
48
+ if (directoryPath === rootPath) {
49
+ return;
50
+ }
51
+ if (fs.readdirSync(directoryPath).length === 0) {
52
+ fs.rmdirSync(directoryPath);
53
+ }
54
+ };
55
+ var getGeneratedPageSource = (contentImportPath) => {
56
+ return [
57
+ "import { DocsPage } from '@unterberg/nivel/client'",
58
+ `import Content from ${JSON.stringify(contentImportPath)}`,
59
+ "",
60
+ "const Page = () => {",
61
+ " return <DocsPage Content={Content} />",
62
+ "}",
63
+ "",
64
+ "export default Page",
65
+ ""
66
+ ].join("\n");
67
+ };
68
+ var getGeneratedDataSource = (data) => {
69
+ return [
70
+ "import type { DocPageData } from '@unterberg/nivel'",
71
+ "",
72
+ `const data: DocPageData = ${serializeData(data)}`,
73
+ "",
74
+ "const pageData = () => {",
75
+ " return data",
76
+ "}",
77
+ "",
78
+ "export default pageData",
79
+ ""
80
+ ].join("\n");
81
+ };
82
+ var getGeneratedGlobalContextSource = (data) => {
83
+ return [
84
+ "import type { DocsGlobalContextData } from '@unterberg/nivel'",
85
+ "",
86
+ `const docsGlobalContextData: DocsGlobalContextData = ${serializeData(data)}`,
87
+ "",
88
+ "export { docsGlobalContextData }",
89
+ ""
90
+ ].join("\n");
91
+ };
92
+ var getRouteString = (href) => {
93
+ if (href === "/") {
94
+ return href;
95
+ }
96
+ return href.replace(/\/+$/g, "");
97
+ };
98
+ var getGeneratedRouteSource = (href) => {
99
+ return [`export default ${JSON.stringify(getRouteString(href))}`, ""].join("\n");
100
+ };
101
+ var getGeneratedTextExport = (value) => {
102
+ return [`export default ${JSON.stringify(value)}`, ""].join("\n");
103
+ };
104
+ var toDocPageLinkData = (page) => {
105
+ if (!page) {
106
+ return null;
107
+ }
108
+ return {
109
+ id: page.id,
110
+ title: page.title,
111
+ href: page.href,
112
+ documentTitle: page.documentTitle
113
+ };
114
+ };
115
+ var getGeneratedPagesRoot = (rootDir) => path.join(rootDir, "pages", GENERATED_DIRNAME);
116
+ var syncGeneratedDocsPages = (options) => {
117
+ const { rootDir, docsConfig } = options;
118
+ const resolved = resolveDocsConfig(docsConfig);
119
+ const generatedPagesRoot = getGeneratedPagesRoot(rootDir);
120
+ const docsRoot = path.join(rootDir, "docs");
121
+ const expectedFiles = /* @__PURE__ */ new Set();
122
+ const globalContextFilePath = path.join(generatedPagesRoot, "_docsGlobalContext.ts");
123
+ fs.mkdirSync(generatedPagesRoot, { recursive: true });
124
+ const globalContextData = {
125
+ siteTitle: resolved.siteTitle,
126
+ basePath: resolved.basePath,
127
+ theme: resolved.theme,
128
+ footer: resolved.footer,
129
+ brand: resolved.brand,
130
+ head: resolved.head,
131
+ partners: resolved.partners,
132
+ algolia: resolved.algolia,
133
+ pages: resolved.pages,
134
+ navbarItems: resolved.navbarItems,
135
+ sidebarSections: resolved.sections
136
+ };
137
+ writeFileIfChanged(globalContextFilePath, getGeneratedGlobalContextSource(globalContextData));
138
+ expectedFiles.add(globalContextFilePath);
139
+ for (const [pageIndex, page] of resolved.pages.entries()) {
140
+ const contentFilePath = path.join(docsRoot, page.source);
141
+ if (!fs.existsSync(contentFilePath)) {
142
+ throw new Error(`Docs page "${page.id}" points to missing source file: ${contentFilePath}`);
143
+ }
144
+ const pageSource = fs.readFileSync(contentFilePath, "utf8");
145
+ const data = {
146
+ page: getResolvedPageById(resolved, page.id),
147
+ headings: extractDocHeadings(pageSource),
148
+ previousPage: toDocPageLinkData(resolved.pages[pageIndex - 1]),
149
+ nextPage: toDocPageLinkData(resolved.pages[pageIndex + 1])
150
+ };
151
+ for (const routeHref of [page.href, ...page.aliasHrefs]) {
152
+ const routeSlug = routeHref.replace(/^\/docs\//, "").replace(/\/+$/g, "");
153
+ const pageDir = path.join(generatedPagesRoot, ...routeSlug.split("/"));
154
+ const contentImportPath = getRelativeImportPath(pageDir, contentFilePath);
155
+ const pageFilePath = path.join(pageDir, "+Page.tsx");
156
+ const dataFilePath = path.join(pageDir, "+data.ts");
157
+ const routeFilePath = path.join(pageDir, "+route.ts");
158
+ const titleFilePath = path.join(pageDir, "+title.ts");
159
+ writeFileIfChanged(pageFilePath, getGeneratedPageSource(contentImportPath));
160
+ writeFileIfChanged(dataFilePath, getGeneratedDataSource(data));
161
+ writeFileIfChanged(routeFilePath, getGeneratedRouteSource(routeHref));
162
+ writeFileIfChanged(titleFilePath, getGeneratedTextExport(page.documentTitle));
163
+ expectedFiles.add(pageFilePath);
164
+ expectedFiles.add(dataFilePath);
165
+ expectedFiles.add(routeFilePath);
166
+ expectedFiles.add(titleFilePath);
167
+ if (page.description) {
168
+ const descriptionFilePath = path.join(pageDir, "+description.ts");
169
+ writeFileIfChanged(descriptionFilePath, getGeneratedTextExport(page.description));
170
+ expectedFiles.add(descriptionFilePath);
171
+ }
172
+ }
173
+ }
174
+ for (const filePath of collectFiles(generatedPagesRoot)) {
175
+ if (expectedFiles.has(filePath)) {
176
+ continue;
177
+ }
178
+ fs.rmSync(filePath, { force: true });
179
+ }
180
+ removeEmptyDirectories(generatedPagesRoot, generatedPagesRoot);
181
+ };
182
+ var isDocsSourcePath = (filePath, rootDir) => {
183
+ const normalized = toPosix(filePath);
184
+ const docsRoot = toPosix(path.join(rootDir, "docs"));
185
+ const docsConfigPath = toPosix(path.join(rootDir, "pages", "+docs.ts"));
186
+ const generatedRoot = toPosix(getGeneratedPagesRoot(rootDir));
187
+ if (normalized.startsWith(generatedRoot)) {
188
+ return false;
189
+ }
190
+ return normalized === docsConfigPath || normalized.startsWith(`${docsRoot}/`);
191
+ };
192
+
193
+ // src/runtime/node/loadDocsConfig.ts
194
+ import path2 from "path";
195
+ var getDocsConfigModulePath = (rootDir) => {
196
+ return path2.join(rootDir, "pages", "+docs.ts");
197
+ };
198
+ var getDocsConfigFromLoadedModule = (loaded, modulePath) => {
199
+ const docsConfig = loaded.default;
200
+ if (!docsConfig) {
201
+ throw new Error(`Expected default export from ${modulePath}`);
202
+ }
203
+ return docsConfig;
204
+ };
205
+ var loadDocsConfig = async (options) => {
206
+ const modulePath = getDocsConfigModulePath(options.rootDir);
207
+ const loaded = await options.loadModule(modulePath);
208
+ return getDocsConfigFromLoadedModule(loaded, modulePath);
209
+ };
210
+
211
+ // src/runtime/node/scaffold.ts
212
+ import fs2 from "fs";
213
+ import path3 from "path";
214
+ var MANAGED_SCRIPT_NAMES = ["generate:docs", "predev", "prebuild", "pretypecheck"];
215
+ var REQUIRED_DEPENDENCIES = ["@unterberg/nivel", "react", "react-dom", "vike", "vike-react"];
216
+ var REQUIRED_DEV_DEPENDENCIES = ["vite", "typescript", "@types/react", "@types/react-dom"];
217
+ var getDocsConfigTemplate = () => {
218
+ return [
219
+ "import { defineDocsConfig } from '@unterberg/nivel/config'",
220
+ "import { docsGraph } from '../docs/docs.graph'",
221
+ "",
222
+ "const docsConfig = defineDocsConfig({",
223
+ " graph: docsGraph,",
224
+ " siteTitle: 'My Docs',",
225
+ " siteDescription: 'Documentation site powered by @unterberg/nivel.',",
226
+ " basePath: '/docs',",
227
+ "})",
228
+ "",
229
+ "export default docsConfig",
230
+ ""
231
+ ].join("\n");
232
+ };
233
+ var getDocsGraphTemplate = () => {
234
+ return [
235
+ "import { defineDocsGraph } from '@unterberg/nivel/config'",
236
+ "",
237
+ "export const docsGraph = defineDocsGraph({",
238
+ " items: [",
239
+ " {",
240
+ " kind: 'section',",
241
+ " id: 'docs',",
242
+ " title: 'Docs',",
243
+ " items: [",
244
+ " {",
245
+ " kind: 'page',",
246
+ " id: 'gettingStarted',",
247
+ " title: 'Getting Started',",
248
+ " slug: 'getting-started',",
249
+ " source: 'content/getting-started/content.mdx',",
250
+ " description: 'Getting started with @unterberg/nivel.',",
251
+ " },",
252
+ " ],",
253
+ " },",
254
+ " ],",
255
+ "})",
256
+ ""
257
+ ].join("\n");
258
+ };
259
+ var getConfigTemplate = () => {
260
+ return [
261
+ "import nivel from '@unterberg/nivel/vike'",
262
+ "import type { Config } from 'vike/types'",
263
+ "import vikeReact from 'vike-react/config'",
264
+ "import docsConfig from './+docs'",
265
+ "",
266
+ "export { config }",
267
+ "",
268
+ "const themePreference = docsConfig.theme?.defaultPreference ?? 'light'",
269
+ "const dataTheme =",
270
+ " themePreference === 'dark'",
271
+ " ? (docsConfig.theme?.dark ?? 'consumer-dark')",
272
+ " : (docsConfig.theme?.light ?? 'consumer-light')",
273
+ "",
274
+ "const config: Config = {",
275
+ " ...nivel,",
276
+ " extends: [vikeReact],",
277
+ " title: docsConfig.siteTitle,",
278
+ " description: docsConfig.siteDescription ?? `${docsConfig.siteTitle} documentation`,",
279
+ " htmlAttributes: { 'data-theme': dataTheme },",
280
+ " passToClient: ['docs'],",
281
+ "",
282
+ " // User-facing Vike levers stay visible in +config.ts.",
283
+ " prerender: true,",
284
+ " // ssr: true,",
285
+ " // prefetchStaticAssets: 'viewport',",
286
+ "}",
287
+ ""
288
+ ].join("\n");
289
+ };
290
+ var getHeadTemplate = () => {
291
+ return [
292
+ "import { MetaHead } from '@unterberg/nivel/client'",
293
+ "",
294
+ "export const Head = () => {",
295
+ " return <MetaHead />",
296
+ "}",
297
+ ""
298
+ ].join("\n");
299
+ };
300
+ var getLayoutTemplate = () => {
301
+ return [
302
+ "import { AppLayout } from '@unterberg/nivel/client'",
303
+ "import type { ReactNode } from 'react'",
304
+ "",
305
+ "const Layout = ({ children }: { children: ReactNode }) => {",
306
+ " return <AppLayout>{children}</AppLayout>",
307
+ "}",
308
+ "",
309
+ "export default Layout",
310
+ ""
311
+ ].join("\n");
312
+ };
313
+ var getGlobalContextTemplate = () => {
314
+ return [
315
+ "import { docsGlobalContextData } from './(nivel-generated)/_docsGlobalContext'",
316
+ "",
317
+ "export const onCreateGlobalContext = (globalContext: { docs?: typeof docsGlobalContextData }) => {",
318
+ " globalContext.docs = docsGlobalContextData",
319
+ "}",
320
+ ""
321
+ ].join("\n");
322
+ };
323
+ var getWrapperTemplate = () => {
324
+ return [
325
+ "import type { ReactNode } from 'react'",
326
+ "",
327
+ "const Wrapper = ({ children }: { children: ReactNode }) => {",
328
+ " return <>{children}</>",
329
+ "}",
330
+ "",
331
+ "export default Wrapper",
332
+ ""
333
+ ].join("\n");
334
+ };
335
+ var getGlobalTypesTemplate = () => {
336
+ return [
337
+ "declare module '*.mdx' {",
338
+ " import type { ComponentType } from 'react'",
339
+ "",
340
+ " const MdxComponent: ComponentType",
341
+ " export default MdxComponent",
342
+ "}",
343
+ "",
344
+ "declare module '*.css'",
345
+ "",
346
+ "declare global {",
347
+ " namespace Vike {",
348
+ " interface GlobalContext {",
349
+ " docs: import('@unterberg/nivel').DocsGlobalContextData",
350
+ " }",
351
+ " }",
352
+ "}",
353
+ ""
354
+ ].join("\n");
355
+ };
356
+ var getManagedFileEntries = () => {
357
+ return [
358
+ ["pages/+docs.ts", getDocsConfigTemplate()],
359
+ ["docs/docs.graph.ts", getDocsGraphTemplate()],
360
+ ["pages/+config.ts", getConfigTemplate()],
361
+ ["pages/+Head.tsx", getHeadTemplate()],
362
+ ["pages/+Layout.tsx", getLayoutTemplate()],
363
+ ["pages/+onCreateGlobalContext.ts", getGlobalContextTemplate()],
364
+ ["pages/+Wrapper.tsx", getWrapperTemplate()],
365
+ ["global.d.ts", getGlobalTypesTemplate()]
366
+ ];
367
+ };
368
+ var getGenerateDocsRunner = (packageJson) => {
369
+ const packageManager = packageJson.packageManager?.trim() ?? "";
370
+ if (packageManager.startsWith("pnpm@")) {
371
+ return "pnpm generate:docs";
372
+ }
373
+ if (packageManager.startsWith("npm@")) {
374
+ return "npm run generate:docs";
375
+ }
376
+ return "npm run generate:docs";
377
+ };
378
+ var getManagedScripts = (packageJson) => {
379
+ const generateDocsRunner = getGenerateDocsRunner(packageJson);
380
+ return {
381
+ "generate:docs": "nivel prepare",
382
+ predev: generateDocsRunner,
383
+ prebuild: generateDocsRunner,
384
+ pretypecheck: generateDocsRunner
385
+ };
386
+ };
387
+ var writeFile = (filePath, source) => {
388
+ fs2.mkdirSync(path3.dirname(filePath), { recursive: true });
389
+ fs2.writeFileSync(filePath, source);
390
+ };
391
+ var writeManagedFile = (rootDir, relativeFilePath, source, force, result) => {
392
+ const filePath = path3.join(rootDir, relativeFilePath);
393
+ const exists = fs2.existsSync(filePath);
394
+ if (exists && !force) {
395
+ result.skippedFiles.push(relativeFilePath);
396
+ return;
397
+ }
398
+ writeFile(filePath, source);
399
+ if (exists) {
400
+ result.overwrittenFiles.push(relativeFilePath);
401
+ return;
402
+ }
403
+ result.createdFiles.push(relativeFilePath);
404
+ };
405
+ var readPackageJson = (rootDir) => {
406
+ const packageJsonPath = path3.join(rootDir, "package.json");
407
+ if (!fs2.existsSync(packageJsonPath)) {
408
+ throw new Error(`Expected package.json in ${rootDir}`);
409
+ }
410
+ return {
411
+ packageJson: JSON.parse(fs2.readFileSync(packageJsonPath, "utf8")),
412
+ packageJsonPath
413
+ };
414
+ };
415
+ var patchPackageScripts = (packageJson, packageJsonPath, result) => {
416
+ const scripts = { ...packageJson.scripts ?? {} };
417
+ const managedScripts = getManagedScripts(packageJson);
418
+ for (const scriptName of MANAGED_SCRIPT_NAMES) {
419
+ if (scripts[scriptName] === managedScripts[scriptName]) {
420
+ continue;
421
+ }
422
+ scripts[scriptName] = managedScripts[scriptName];
423
+ result.updatedScripts.push(scriptName);
424
+ }
425
+ const nextPackageJson = {
426
+ ...packageJson,
427
+ scripts
428
+ };
429
+ fs2.writeFileSync(packageJsonPath, `${JSON.stringify(nextPackageJson, null, 2)}
430
+ `);
431
+ };
432
+ var getMissingDependencies = (packageJson) => {
433
+ const installed = /* @__PURE__ */ new Set([
434
+ ...Object.keys(packageJson.dependencies ?? {}),
435
+ ...Object.keys(packageJson.devDependencies ?? {})
436
+ ]);
437
+ return [...REQUIRED_DEPENDENCIES, ...REQUIRED_DEV_DEPENDENCIES].filter((packageName) => !installed.has(packageName));
438
+ };
439
+ var getInitSummary = (result) => {
440
+ const lines = ["Initialized nivel consumer scaffolding."];
441
+ if (result.createdFiles.length > 0) {
442
+ lines.push(`Created files: ${result.createdFiles.join(", ")}`);
443
+ }
444
+ if (result.overwrittenFiles.length > 0) {
445
+ lines.push(`Overwritten files: ${result.overwrittenFiles.join(", ")}`);
446
+ }
447
+ if (result.skippedFiles.length > 0) {
448
+ lines.push(`Skipped existing files: ${result.skippedFiles.join(", ")}`);
449
+ }
450
+ if (result.updatedScripts.length > 0) {
451
+ lines.push(`Updated package.json scripts: ${result.updatedScripts.join(", ")}`);
452
+ }
453
+ if (result.missingDependencies.length > 0) {
454
+ lines.push(`Missing dependencies: ${result.missingDependencies.join(", ")}`);
455
+ lines.push(
456
+ "Consumer CSS stays hand-authored. Add your stylesheet import manually, for example in pages/+Wrapper.tsx."
457
+ );
458
+ } else if (!result.allDependenciesPresent) {
459
+ lines.push("Dependency validation completed with warnings.");
460
+ } else {
461
+ lines.push("All required dependencies are already present.");
462
+ }
463
+ return `${lines.join("\n")}
464
+ `;
465
+ };
466
+ var initConsumer = (options) => {
467
+ const result = {
468
+ allDependenciesPresent: true,
469
+ createdFiles: [],
470
+ missingDependencies: [],
471
+ overwrittenFiles: [],
472
+ skippedFiles: [],
473
+ updatedScripts: []
474
+ };
475
+ const { packageJson, packageJsonPath } = readPackageJson(options.rootDir);
476
+ for (const [relativeFilePath, source] of getManagedFileEntries()) {
477
+ writeManagedFile(options.rootDir, relativeFilePath, source, options.force, result);
478
+ }
479
+ patchPackageScripts(packageJson, packageJsonPath, result);
480
+ result.missingDependencies = getMissingDependencies(packageJson);
481
+ result.allDependenciesPresent = result.missingDependencies.length === 0;
482
+ return result;
483
+ };
484
+
485
+ export {
486
+ getGeneratedPagesRoot,
487
+ syncGeneratedDocsPages,
488
+ isDocsSourcePath,
489
+ loadDocsConfig,
490
+ getInitSummary,
491
+ initConsumer
492
+ };
493
+ //# sourceMappingURL=chunk-UMMK73OW.js.map