@preprio/prepr-nextjs 1.3.2 → 2.0.0-alpha.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/LICENSE +2 -2
  2. package/README.md +752 -111
  3. package/dist/chunk-E7ATRJ2F.js +2 -0
  4. package/dist/chunk-E7ATRJ2F.js.map +1 -0
  5. package/dist/chunk-LVXDK2EY.js +2 -0
  6. package/dist/chunk-LVXDK2EY.js.map +1 -0
  7. package/dist/index.css +1 -0
  8. package/dist/metafile-cjs.json +1 -0
  9. package/dist/metafile-esm.json +1 -0
  10. package/dist/middleware/index.cjs +2 -0
  11. package/dist/middleware/index.cjs.map +1 -0
  12. package/dist/middleware/index.d.cts +26 -0
  13. package/dist/middleware/index.d.ts +26 -0
  14. package/dist/middleware/index.js +2 -0
  15. package/dist/middleware/index.js.map +1 -0
  16. package/dist/react/index.cjs +11 -0
  17. package/dist/react/index.cjs.map +1 -0
  18. package/dist/react/index.d.cts +80 -0
  19. package/dist/react/index.d.ts +80 -0
  20. package/dist/react/index.js +11 -0
  21. package/dist/react/index.js.map +1 -0
  22. package/dist/server/index.cjs +7 -0
  23. package/dist/server/index.cjs.map +1 -0
  24. package/dist/server/index.d.cts +73 -0
  25. package/dist/server/index.d.ts +73 -0
  26. package/dist/server/index.js +7 -0
  27. package/dist/server/index.js.map +1 -0
  28. package/dist/types/index.cjs +2 -0
  29. package/dist/types/index.cjs.map +1 -0
  30. package/dist/types/index.d.cts +34 -0
  31. package/dist/types/index.d.ts +34 -0
  32. package/dist/types/index.js +2 -0
  33. package/dist/types/index.js.map +1 -0
  34. package/dist/utils/index.cjs +2 -0
  35. package/dist/utils/index.cjs.map +1 -0
  36. package/dist/utils/index.d.cts +164 -0
  37. package/dist/utils/index.d.ts +164 -0
  38. package/dist/utils/index.js +2 -0
  39. package/dist/utils/index.js.map +1 -0
  40. package/package.json +104 -59
  41. package/dist/chunk-IQXHJV5O.mjs +0 -25
  42. package/dist/chunk-IQXHJV5O.mjs.map +0 -1
  43. package/dist/components.css +0 -430
  44. package/dist/components.css.map +0 -1
  45. package/dist/components.d.mts +0 -10
  46. package/dist/components.d.ts +0 -10
  47. package/dist/components.js +0 -415
  48. package/dist/components.js.map +0 -1
  49. package/dist/components.mjs +0 -388
  50. package/dist/components.mjs.map +0 -1
  51. package/dist/index.d.mts +0 -45
  52. package/dist/index.d.ts +0 -45
  53. package/dist/index.js +0 -325
  54. package/dist/index.js.map +0 -1
  55. package/dist/index.mjs +0 -279
  56. package/dist/index.mjs.map +0 -1
  57. package/dist/types-DmITW6Tn.d.mts +0 -6
  58. package/dist/types-DmITW6Tn.d.ts +0 -6
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/react/components/toolbar/toolbar-provider.tsx","../../src/react/contexts/segment-context.tsx","../../src/utils/errors.ts","../../src/react/contexts/variant-context.tsx","../../src/react/contexts/edit-mode-context.tsx","../../src/react/components/error-boundary.tsx","../../src/utils/debug.ts","../../src/react/components/toolbar/prepr-toolbar.tsx","../../src/react/hooks/use-stega-scan.tsx","../../src/utils/dom.ts","../../src/utils/performance.ts","../../src/react/hooks/use-stega-overlay.tsx","../../src/react/hooks/use-stega-proximity.tsx","../../src/react/hooks/use-stega-elements.tsx","../../src/react/components/toolbar/toolbar-wrapper.tsx","../../src/react/components/toolbar/toolbar.tsx","../../src/utils/index.ts","../../src/react/hooks/use-modal.ts","../../src/react/components/toolbar/toolbar-content.tsx","../../src/react/components/ui/status-indicator-pill.tsx","../../src/react/components/icons/xmark.tsx","../../src/react/components/ui/close-edit-mode-pill.tsx","../../src/react/components/ui/reset-button.tsx","../../src/react/components/icons/rotate.tsx","../../src/react/components/ui/icon.tsx","../../src/react/components/ui/logo.tsx","../../src/react/components/ui/prepr-tracking-pixel.tsx","../../src/react/components/selectors/segment-selector.tsx","../../src/react/components/icons/sort-down.tsx","../../src/react/components/selectors/variant-selector.tsx","../../src/react/components/selectors/radio-selector.tsx","../../src/react/components/selectors/edit-mode-selector.tsx","../../src/react/components/toolbar/toolbar-button.tsx","../../src/react/components/toolbar/toolbar-indicator-wrapper.tsx"],"sourcesContent":["'use client';\n\nimport React, { ReactNode, useEffect, useCallback, useMemo } from 'react';\nimport { PreprToolbarOptions, PreprToolbarProps } from '../../../types';\nimport {\n SegmentProvider,\n VariantProvider,\n EditModeProvider,\n useSegmentContext,\n useVariantContext,\n useEditModeContext,\n} from '../../contexts';\nimport { StegaErrorBoundary } from '../error-boundary';\nimport { initDebugLogger } from '../../../utils/debug';\n\ninterface PreprToolbarProviderProps {\n children: ReactNode;\n props: PreprToolbarProps;\n options?: PreprToolbarOptions;\n}\n\nexport const PreprToolbarProvider: React.FC<PreprToolbarProviderProps> = ({\n children,\n props,\n options,\n}) => {\n const { activeSegment, activeVariant, data } = props;\n\n // Initialize debug logger with options\n useEffect(() => {\n const debugEnabled = options?.debug ?? false;\n initDebugLogger(debugEnabled);\n }, [options?.debug]);\n\n return (\n <StegaErrorBoundary>\n <SegmentProvider initialSegments={data} activeSegment={activeSegment}>\n <VariantProvider activeVariant={activeVariant}>\n <EditModeProvider>{children}</EditModeProvider>\n </VariantProvider>\n </SegmentProvider>\n </StegaErrorBoundary>\n );\n};\n\n// Legacy hook for backward compatibility\nexport const usePreprToolbar = () => {\n // This will be deprecated in favor of specific context hooks\n // but kept for backward compatibility\n const segmentContext = useSegmentContext();\n const variantContext = useVariantContext();\n const editModeContext = useEditModeContext();\n\n const resetPersonalization = useCallback(() => {\n segmentContext.setSelectedSegment(segmentContext.emptySegment);\n variantContext.setSelectedVariant(variantContext.emptyVariant);\n }, [segmentContext, variantContext]);\n\n const resetAll = useCallback(() => {\n segmentContext.setSelectedSegment(segmentContext.emptySegment);\n variantContext.setSelectedVariant(variantContext.emptyVariant);\n editModeContext.setEditMode(false);\n }, [segmentContext, variantContext, editModeContext]);\n\n return useMemo(\n () => ({\n isPreviewMode: false,\n activeSegment: segmentContext.selectedSegment._id,\n activeVariant: variantContext.selectedVariant,\n data: segmentContext.segments,\n emptySegment: segmentContext.emptySegment,\n segmentList: segmentContext.segments,\n selectedSegment: segmentContext.selectedSegment,\n setSelectedSegment: segmentContext.setSelectedSegment,\n emptyVariant: variantContext.emptyVariant,\n selectedVariant: variantContext.selectedVariant,\n setSelectedVariant: variantContext.setSelectedVariant,\n editMode: editModeContext.editMode,\n setEditMode: editModeContext.setEditMode,\n isIframe: editModeContext.isIframe,\n resetPersonalization,\n resetAll,\n }),\n [\n segmentContext.selectedSegment,\n segmentContext.segments,\n segmentContext.emptySegment,\n segmentContext.setSelectedSegment,\n variantContext.selectedVariant,\n variantContext.emptyVariant,\n variantContext.setSelectedVariant,\n editModeContext.editMode,\n editModeContext.setEditMode,\n editModeContext.isIframe,\n resetPersonalization,\n resetAll,\n ]\n );\n};\n","'use client';\n\nimport React, { createContext, useContext, useState, ReactNode } from 'react';\nimport { PreprSegment } from '../../types';\nimport { handleContextError } from '../../utils/errors';\n\ninterface SegmentContextValue {\n segments: PreprSegment[];\n selectedSegment: PreprSegment;\n setSelectedSegment: (segment: PreprSegment) => void;\n emptySegment: PreprSegment;\n}\n\nconst SegmentContext = createContext<SegmentContextValue | undefined>(\n undefined\n);\n\ninterface SegmentProviderProps {\n children: ReactNode;\n initialSegments: readonly PreprSegment[];\n activeSegment?: string | null;\n}\n\nexport function SegmentProvider({\n children,\n initialSegments,\n activeSegment,\n}: SegmentProviderProps) {\n const segmentList: PreprSegment[] = [\n {\n _id: 'all_other_users',\n name: 'All other users',\n },\n ...initialSegments,\n ];\n\n const emptySegment: PreprSegment = {\n name: 'Choose segment',\n _id: 'null',\n };\n\n const [selectedSegment, setSelectedSegment] = useState<PreprSegment>(\n (segmentList &&\n segmentList.filter(\n (segmentData: PreprSegment) => segmentData._id === activeSegment\n )[0]) ||\n emptySegment\n );\n\n const value: SegmentContextValue = {\n segments: segmentList,\n selectedSegment,\n setSelectedSegment,\n emptySegment,\n };\n\n return (\n <SegmentContext.Provider value={value}>{children}</SegmentContext.Provider>\n );\n}\n\nexport function useSegmentContext(): SegmentContextValue {\n const context = useContext(SegmentContext);\n if (!context) {\n handleContextError('useSegmentContext');\n }\n return context!;\n}\n","export const StegaError = {\n DECODE_FAILED: 'STEGA_DECODE_FAILED',\n INVALID_FORMAT: 'STEGA_INVALID_FORMAT',\n DOM_MANIPULATION_FAILED: 'DOM_MANIPULATION_FAILED',\n CONTEXT_NOT_FOUND: 'CONTEXT_NOT_FOUND',\n} as const;\n\nexport type StegaErrorType = (typeof StegaError)[keyof typeof StegaError];\n\n// Define specific types for error additional data\nexport interface ErrorAdditionalData {\n input?: string;\n element?: HTMLElement;\n context?: string;\n [key: string]: string | HTMLElement | undefined;\n}\n\nexport interface ErrorInfo {\n type: StegaErrorType;\n context: string;\n message: string;\n timestamp: string;\n stack?: string;\n additionalData?: ErrorAdditionalData;\n}\n\nexport function createErrorInfo(\n type: StegaErrorType,\n context: string,\n error: Error,\n additionalData?: ErrorAdditionalData\n): ErrorInfo {\n return {\n type,\n context,\n message: error.message,\n timestamp: new Date().toISOString(),\n stack: error.stack,\n additionalData,\n };\n}\n\nexport function handleStegaError(\n error: Error,\n context: string,\n additionalData?: ErrorAdditionalData\n) {\n const errorInfo = createErrorInfo(\n StegaError.DECODE_FAILED,\n context,\n error,\n additionalData\n );\n\n console.error('Stega Error:', errorInfo);\n\n // In production, you might want to send this to an error tracking service\n if (process.env.NODE_ENV === 'production') {\n // sendToErrorTrackingService(errorInfo);\n }\n\n return errorInfo;\n}\n\nexport function handleDOMError(error: Error, context: string) {\n const errorInfo = createErrorInfo(\n StegaError.DOM_MANIPULATION_FAILED,\n context,\n error\n );\n\n console.error('DOM Error:', errorInfo);\n return errorInfo;\n}\n\nexport function handleContextError(contextName: string) {\n const error = new Error(`${contextName} must be used within its provider`);\n const errorInfo = createErrorInfo(\n StegaError.CONTEXT_NOT_FOUND,\n contextName,\n error\n );\n\n console.error('Context Error:', errorInfo);\n throw error;\n}\n","'use client';\n\nimport React, { createContext, useContext, useState, ReactNode } from 'react';\nimport { handleContextError } from '../../utils/errors';\n\ninterface VariantContextValue {\n selectedVariant: string | null;\n setSelectedVariant: (variant: string | null) => void;\n emptyVariant: string;\n}\n\nconst VariantContext = createContext<VariantContextValue | undefined>(\n undefined\n);\n\ninterface VariantProviderProps {\n children: ReactNode;\n activeVariant?: string | null;\n}\n\nexport function VariantProvider({\n children,\n activeVariant,\n}: VariantProviderProps) {\n const emptyVariant = 'null';\n\n const [selectedVariant, setSelectedVariant] = useState<string | null>(\n activeVariant || 'null'\n );\n\n const value: VariantContextValue = {\n selectedVariant,\n setSelectedVariant,\n emptyVariant,\n };\n\n return (\n <VariantContext.Provider value={value}>{children}</VariantContext.Provider>\n );\n}\n\nexport function useVariantContext(): VariantContextValue {\n const context = useContext(VariantContext);\n if (!context) {\n handleContextError('useVariantContext');\n }\n return context!;\n}\n","'use client';\n\nimport React, {\n createContext,\n useContext,\n useState,\n useEffect,\n ReactNode,\n} from 'react';\nimport { handleContextError } from '../../utils/errors';\n\ninterface EditModeContextValue {\n editMode: boolean;\n setEditMode: (mode: boolean) => void;\n isIframe: boolean;\n}\n\nconst EditModeContext = createContext<EditModeContextValue | undefined>(\n undefined\n);\n\ninterface EditModeProviderProps {\n children: ReactNode;\n}\n\nexport function EditModeProvider({ children }: EditModeProviderProps) {\n const [editMode, setEditMode] = useState(false);\n const [isIframe, setIsIframe] = useState(false);\n\n useEffect(() => {\n if (window.parent !== self) {\n setIsIframe(true);\n }\n }, []);\n\n // Handle escape key to turn off edit mode\n useEffect(() => {\n const handleEscapeKey = (event: KeyboardEvent) => {\n if (event.key === 'Escape' && editMode) {\n setEditMode(false);\n }\n };\n\n if (editMode) {\n document.addEventListener('keydown', handleEscapeKey);\n }\n\n return () => {\n document.removeEventListener('keydown', handleEscapeKey);\n };\n }, [editMode]);\n\n const value: EditModeContextValue = {\n editMode,\n setEditMode,\n isIframe,\n };\n\n return (\n <EditModeContext.Provider value={value}>\n {children}\n </EditModeContext.Provider>\n );\n}\n\nexport function useEditModeContext(): EditModeContextValue {\n const context = useContext(EditModeContext);\n if (!context) {\n handleContextError('useEditModeContext');\n }\n return context!;\n}\n","'use client';\n\nimport React, { Component, ReactNode } from 'react';\n\ninterface Props {\n children: ReactNode;\n fallback?: ReactNode;\n}\n\ninterface State {\n hasError: boolean;\n error: Error | null;\n}\n\nexport class StegaErrorBoundary extends Component<Props, State> {\n constructor(props: Props) {\n super(props);\n this.state = { hasError: false, error: null };\n }\n\n static getDerivedStateFromError(error: Error): State {\n return { hasError: true, error };\n }\n\n componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {\n console.error('Stega Error Boundary caught an error:', error, errorInfo);\n\n // In production, you might want to send this to an error tracking service\n if (process.env.NODE_ENV === 'production') {\n // sendToErrorTrackingService({ error, errorInfo });\n }\n }\n\n render() {\n if (this.state.hasError) {\n if (this.props.fallback) {\n return this.props.fallback;\n }\n\n return (\n <div className=\"p-rounded-lg p-border p-border-red-200 p-bg-red-50 p-p-4 p-text-sm p-text-red-800\">\n <div className=\"p-mb-2 p-font-semibold\">Preview mode unavailable</div>\n <div className=\"p-text-red-600\">\n {this.state.error?.message || 'An unexpected error occurred'}\n </div>\n </div>\n );\n }\n\n return this.props.children;\n }\n}\n","/**\n * Debug utility for Prepr Next.js package\n * Provides centralized debug logging with performance optimizations\n */\n\n// Define specific types for debug arguments\nexport type DebugArg = string | number | boolean | null | undefined | object;\n\ninterface DebugOptions {\n enabled: boolean;\n prefix?: string;\n}\n\nclass DebugLogger {\n private options: DebugOptions;\n\n constructor(options: DebugOptions) {\n this.options = {\n prefix: '[Prepr]',\n ...options,\n };\n }\n\n /**\n * Log a debug message if debug is enabled\n */\n log(message: string, ...args: DebugArg[]): void {\n if (!this.options.enabled) return;\n\n const prefix = this.options.prefix;\n console.log(`${prefix} ${message}`, ...args);\n }\n\n /**\n * Log a debug warning if debug is enabled\n */\n warn(message: string, ...args: DebugArg[]): void {\n if (!this.options.enabled) return;\n\n const prefix = this.options.prefix;\n console.warn(`${prefix} ${message}`, ...args);\n }\n\n /**\n * Log a debug error if debug is enabled\n */\n error(message: string, ...args: DebugArg[]): void {\n if (!this.options.enabled) return;\n\n const prefix = this.options.prefix;\n console.error(`${prefix} ${message}`, ...args);\n }\n\n /**\n * Create a scoped logger with additional context\n */\n scope(scopeName: string): DebugLogger {\n return new DebugLogger({\n ...this.options,\n prefix: `${this.options.prefix}[${scopeName}]`,\n });\n }\n}\n\n// Global debug instance\nlet globalDebugLogger: DebugLogger | null = null;\n\n/**\n * Initialize the debug logger\n */\nexport function initDebugLogger(enabled: boolean = false): void {\n globalDebugLogger = new DebugLogger({ enabled });\n}\n\n/**\n * Get the debug logger instance\n */\nexport function getDebugLogger(): DebugLogger {\n if (!globalDebugLogger) {\n // Fallback to disabled logger if not initialized\n globalDebugLogger = new DebugLogger({ enabled: false });\n }\n return globalDebugLogger;\n}\n\n/**\n * Convenience function for logging\n */\nexport function debugLog(message: string, ...args: DebugArg[]): void {\n getDebugLogger().log(message, ...args);\n}\n\n/**\n * Convenience function for warning\n */\nexport function debugWarn(message: string, ...args: DebugArg[]): void {\n getDebugLogger().warn(message, ...args);\n}\n\n/**\n * Convenience function for errors\n */\nexport function debugError(message: string, ...args: DebugArg[]): void {\n getDebugLogger().error(message, ...args);\n}\n\n/**\n * Create a scoped debug logger\n */\nexport function createScopedLogger(scopeName: string): DebugLogger {\n return getDebugLogger().scope(scopeName);\n}\n","'use client';\n\nimport React from 'react';\nimport { useEditModeContext } from '../../contexts';\nimport useStegaScan from '../../hooks/use-stega-scan';\nimport ToolbarWrapper from './toolbar-wrapper';\nimport ToolbarIndicatorWrapper from './toolbar-indicator-wrapper';\n\nexport default function PreprToolbar() {\n const { editMode } = useEditModeContext();\n\n useStegaScan(editMode);\n\n return (\n <>\n <ToolbarWrapper />\n <ToolbarIndicatorWrapper />\n </>\n );\n}\n","import { useEffect, useRef, useCallback, useMemo } from 'react';\nimport { DOMService } from '../../utils/dom';\nimport { createScopedLogger } from '../../utils/debug';\nimport { throttle } from '../../utils/performance';\nimport { useStegaOverlay } from './use-stega-overlay';\nimport { useStegaProximity } from './use-stega-proximity';\nimport { useStegaElements } from './use-stega-elements';\n\nexport default function useStegaScan(editMode: boolean): void {\n const debug = createScopedLogger('useStegaScan');\n const isInitializedRef = useRef(false);\n\n const {\n currentElementRef,\n hideTimeoutRef,\n createOverlay,\n showOverlay,\n hideOverlay,\n cleanup: cleanupOverlay,\n decode,\n } = useStegaOverlay();\n\n const { updateElementGradients, clearAllHighlights } = useStegaProximity();\n\n const {\n getElements,\n scanDocument,\n setupMutationObserver,\n cleanup: cleanupElements,\n } = useStegaElements();\n\n // Memoize the throttled mouse move handler\n const throttledMouseMove = useMemo(\n () =>\n throttle((e: Event) => {\n const mouseEvent = e as MouseEvent;\n const target = mouseEvent.target as HTMLElement;\n // Early return if hovering over tooltip\n if (target.closest('.prepr-tooltip')) {\n return;\n }\n updateElementGradients(mouseEvent.clientX, mouseEvent.clientY);\n const encodedElement = target.closest('[data-prepr-encoded]');\n if (encodedElement) {\n showOverlay(encodedElement as HTMLElement);\n } else {\n hideOverlay();\n }\n }, 16),\n [updateElementGradients, showOverlay, hideOverlay]\n );\n\n // Memoize tooltip handlers\n const handleTooltipMouseEnter = useCallback(() => {\n if (hideTimeoutRef.current) {\n clearTimeout(hideTimeoutRef.current);\n hideTimeoutRef.current = null;\n }\n }, [hideTimeoutRef]);\n\n const handleTooltipMouseLeave = useCallback(() => {\n if (!currentElementRef.current) {\n hideOverlay();\n }\n }, [currentElementRef, hideOverlay]);\n\n useEffect(() => {\n debug.log('editMode changed to', editMode);\n if (!editMode) {\n debug.log('editMode is false, cleaning up');\n if (isInitializedRef.current) {\n DOMService.removeEventListener(\n document,\n 'mousemove',\n throttledMouseMove\n );\n cleanupOverlay();\n clearAllHighlights();\n cleanupElements();\n isInitializedRef.current = false;\n }\n return;\n }\n if (isInitializedRef.current) {\n debug.log('already initialized, skipping setup');\n return;\n }\n debug.log('editMode is true, setting up scanning');\n // Create overlay and tooltip elements\n const { tooltip } = createOverlay();\n debug.log('created overlay and tooltip');\n DOMService.addEventListener(tooltip, 'mouseenter', handleTooltipMouseEnter);\n DOMService.addEventListener(tooltip, 'mouseleave', handleTooltipMouseLeave);\n debug.log('starting document scan');\n scanDocument(decode);\n const elements = getElements();\n debug.log('found', elements.length, 'encoded elements after scan');\n setupMutationObserver(decode);\n debug.log('set up mutation observer');\n DOMService.addEventListener(document, 'mousemove', throttledMouseMove);\n debug.log('added throttled mousemove handler');\n isInitializedRef.current = true;\n return () => {\n debug.log('cleaning up');\n DOMService.removeEventListener(document, 'mousemove', throttledMouseMove);\n DOMService.removeEventListener(\n tooltip,\n 'mouseenter',\n handleTooltipMouseEnter\n );\n DOMService.removeEventListener(\n tooltip,\n 'mouseleave',\n handleTooltipMouseLeave\n );\n if (hideTimeoutRef.current) {\n clearTimeout(hideTimeoutRef.current);\n }\n cleanupOverlay();\n clearAllHighlights();\n cleanupElements();\n isInitializedRef.current = false;\n };\n }, [editMode]);\n}\n","import { handleDOMError } from './errors';\n\nexport class DOMService {\n /**\n * Creates an HTML element with specified tag and class name\n */\n static createElement(tag: string, className: string): HTMLElement {\n try {\n const element = document.createElement(tag);\n element.className = className;\n return element;\n } catch (error) {\n handleDOMError(error as Error, 'createElement');\n throw error;\n }\n }\n\n /**\n * Appends an element to the document body\n */\n static appendToBody(element: HTMLElement): void {\n try {\n document.body.appendChild(element);\n } catch (error) {\n handleDOMError(error as Error, 'appendToBody');\n throw error;\n }\n }\n\n /**\n * Removes an element from the document body\n */\n static removeFromBody(element: HTMLElement): void {\n try {\n if (element.parentNode) {\n element.parentNode.removeChild(element);\n }\n } catch (error) {\n handleDOMError(error as Error, 'removeFromBody');\n throw error;\n }\n }\n\n /**\n * Sets multiple CSS properties on an element\n */\n static setElementStyles(\n element: HTMLElement,\n styles: Record<string, string>\n ): void {\n try {\n Object.entries(styles).forEach(([property, value]) => {\n element.style.setProperty(property, value);\n });\n } catch (error) {\n handleDOMError(error as Error, 'setElementStyles');\n throw error;\n }\n }\n\n /**\n * Gets the bounding rectangle of an element\n */\n static getElementRect(element: HTMLElement): DOMRect {\n try {\n return element.getBoundingClientRect();\n } catch (error) {\n handleDOMError(error as Error, 'getElementRect');\n throw error;\n }\n }\n\n /**\n * Checks if an element is in the viewport\n */\n static isElementInViewport(element: HTMLElement): boolean {\n try {\n const rect = this.getElementRect(element);\n return (\n rect.top >= 0 &&\n rect.left >= 0 &&\n rect.bottom <=\n (window.innerHeight || document.documentElement.clientHeight) &&\n rect.right <=\n (window.innerWidth || document.documentElement.clientWidth)\n );\n } catch (error) {\n handleDOMError(error as Error, 'isElementInViewport');\n return false;\n }\n }\n\n /**\n * Calculates distance between two points\n */\n static calculateDistance(\n x1: number,\n y1: number,\n x2: number,\n y2: number\n ): number {\n return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));\n }\n\n /**\n * Finds the closest element to a point from a list of elements\n */\n static findClosestElement(\n pointX: number,\n pointY: number,\n elements: NodeListOf<Element>\n ): HTMLElement | null {\n try {\n let closestElement: HTMLElement | null = null;\n let minDistance = Infinity;\n\n elements.forEach(element => {\n const rect = this.getElementRect(element as HTMLElement);\n const distance = this.calculateDistance(\n pointX,\n pointY,\n rect.left + rect.width / 2,\n rect.top + rect.height / 2\n );\n\n if (distance < minDistance) {\n minDistance = distance;\n closestElement = element as HTMLElement;\n }\n });\n\n return closestElement;\n } catch (error) {\n handleDOMError(error as Error, 'findClosestElement');\n return null;\n }\n }\n\n /**\n * Safely adds event listeners\n */\n static addEventListener(\n element: EventTarget,\n event: string,\n handler: EventListener,\n options?: AddEventListenerOptions\n ): void {\n try {\n element.addEventListener(event, handler, options);\n } catch (error) {\n handleDOMError(error as Error, 'addEventListener');\n throw error;\n }\n }\n\n /**\n * Safely removes event listeners\n */\n static removeEventListener(\n element: EventTarget,\n event: string,\n handler: EventListener,\n options?: EventListenerOptions\n ): void {\n try {\n element.removeEventListener(event, handler, options);\n } catch (error) {\n handleDOMError(error as Error, 'removeEventListener');\n throw error;\n }\n }\n}\n","// Performance utilities\n\n/**\n * Throttled function with cancellation support\n */\nexport interface ThrottledFunction<T extends (...args: any[]) => any> {\n (...args: Parameters<T>): void;\n cancel(): void;\n}\n\n/**\n * Improved throttle function with better memory management and cancellation\n * @param func - The function to throttle\n * @param delay - The delay in milliseconds\n * @returns Throttled function with cancel method\n */\nexport function throttle<T extends (...args: any[]) => any>(\n func: T,\n delay: number\n): ThrottledFunction<T> {\n let timeoutId: NodeJS.Timeout | null = null;\n let lastExecTime = 0;\n\n const throttledFunc = ((...args: Parameters<T>) => {\n const currentTime = Date.now();\n const timeSinceLastExec = currentTime - lastExecTime;\n\n if (timeSinceLastExec >= delay) {\n func(...args);\n lastExecTime = currentTime;\n } else {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n timeoutId = setTimeout(() => {\n func(...args);\n lastExecTime = Date.now();\n timeoutId = null;\n }, delay - timeSinceLastExec);\n }\n }) as ThrottledFunction<T>;\n\n throttledFunc.cancel = () => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n };\n\n return throttledFunc;\n}\n\n/**\n * Debounce function with cancellation support\n * @param func - The function to debounce\n * @param delay - The delay in milliseconds\n * @returns Debounced function with cancel method\n */\nexport function debounce<T extends (...args: any[]) => any>(\n func: T,\n delay: number\n): ThrottledFunction<T> {\n let timeoutId: NodeJS.Timeout | null = null;\n\n const debouncedFunc = ((...args: Parameters<T>) => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n timeoutId = setTimeout(() => {\n func(...args);\n timeoutId = null;\n }, delay);\n }) as ThrottledFunction<T>;\n\n debouncedFunc.cancel = () => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n };\n\n return debouncedFunc;\n}\n\n// Simple DOM element cache for querySelectorAll\nexport function createElementCache<T extends Element = Element>(\n query: string,\n ttl: number = 1000\n) {\n let cache: NodeListOf<T> | null = null;\n let lastCacheTime = 0;\n return () => {\n const now = Date.now();\n if (!cache || now - lastCacheTime > ttl) {\n cache = document.querySelectorAll<T>(query);\n lastCacheTime = now;\n }\n return cache;\n };\n}\n","import { useRef, useCallback } from 'react';\nimport { DOMService } from '../../utils/dom';\nimport { handleStegaError } from '../../utils/errors';\nimport { createScopedLogger } from '../../utils/debug';\nimport { vercelStegaDecode } from '@vercel/stega';\n\ninterface DecodedData {\n origin: string;\n href: string;\n}\n\nfunction decode(str: string | null): DecodedData | null {\n if (!str) return null;\n\n const debug = createScopedLogger('decode');\n\n try {\n // First, try to decode the string directly\n debug.log('attempting to decode stega data');\n\n const decoded = vercelStegaDecode(str) as DecodedData;\n debug.log('vercelStegaDecode result:', decoded);\n\n if (decoded?.href) {\n debug.log('successfully decoded', decoded);\n return decoded;\n }\n } catch (e) {\n debug.log('error decoding stega data:', e as Error);\n // If it fails, it might be because of trailing characters.\n // Regex to find the JSON string\n const regex = /{\"origin.*?}/;\n const match = str.match(regex);\n\n if (match) {\n try {\n // Now, try to decode the matched JSON string\n const decodedMatch = vercelStegaDecode(match[0]) as DecodedData;\n if (decodedMatch?.href) {\n debug.log('successfully decoded with regex match', decodedMatch);\n return decodedMatch;\n }\n } catch (e) {\n handleStegaError(e as Error, 'decode', { input: str });\n }\n }\n }\n\n return null;\n}\n\nexport function useStegaOverlay() {\n const debug = createScopedLogger('useStegaOverlay');\n const overlayRef = useRef<HTMLDivElement | null>(null);\n const tooltipRef = useRef<HTMLDivElement | null>(null);\n const hideTimeoutRef = useRef<NodeJS.Timeout | null>(null);\n const currentElementRef = useRef<HTMLElement | null>(null);\n\n const createOverlay = useCallback(() => {\n const overlay = DOMService.createElement(\n 'div',\n 'prepr-overlay'\n ) as HTMLDivElement;\n overlay.style.display = 'none';\n\n const tooltip = DOMService.createElement(\n 'div',\n 'prepr-tooltip'\n ) as HTMLDivElement;\n tooltip.style.display = 'none';\n\n DOMService.appendToBody(overlay);\n DOMService.appendToBody(tooltip);\n\n overlayRef.current = overlay;\n tooltipRef.current = tooltip;\n\n debug.log('created overlay and tooltip elements');\n\n return { overlay, tooltip };\n }, [debug]);\n\n const showOverlay = useCallback(\n (element: HTMLElement) => {\n if (!overlayRef.current || !tooltipRef.current) return;\n\n if (hideTimeoutRef.current) {\n clearTimeout(hideTimeoutRef.current);\n hideTimeoutRef.current = null;\n }\n\n const rect = DOMService.getElementRect(element);\n const href = element.getAttribute('data-prepr-href');\n const origin = element.getAttribute('data-prepr-origin');\n\n debug.log('showing overlay for element:', { href, origin, rect });\n\n // Position overlay\n const overlay = overlayRef.current;\n overlay.style.display = 'block';\n overlay.style.top = `${rect.top + window.scrollY - 2}px`;\n overlay.style.left = `${rect.left + window.scrollX - 4}px`;\n overlay.style.width = `${rect.width + 8}px`;\n overlay.style.height = `${rect.height + 4}px`;\n\n // Position and show tooltip\n const tooltip = tooltipRef.current;\n if (tooltip && href && origin) {\n const MIN_WIDTH_FOR_TEXT = 80;\n const isCompact = rect.width < MIN_WIDTH_FOR_TEXT;\n tooltip.textContent = isCompact ? '↗' : `${origin} ↗`;\n tooltip.style.display = 'block';\n\n // Remove min-width constraint for compact tooltips\n if (isCompact) {\n tooltip.style.minWidth = 'auto';\n } else {\n tooltip.style.minWidth = '80px';\n }\n\n // Use requestAnimationFrame to ensure the DOM has updated before calculating position\n requestAnimationFrame(() => {\n if (tooltip) {\n tooltip.style.top = `${rect.top + window.scrollY - tooltip.clientHeight - 2}px`;\n tooltip.style.left = `${rect.right + 4 - tooltip.clientWidth}px`;\n }\n });\n\n tooltip.onclick = () =>\n window.open(href, '_blank', 'noopener,noreferrer');\n }\n\n currentElementRef.current = element;\n },\n [debug]\n );\n\n const hideOverlay = useCallback(() => {\n if (!overlayRef.current || !tooltipRef.current) return;\n\n if (hideTimeoutRef.current) {\n clearTimeout(hideTimeoutRef.current);\n }\n\n hideTimeoutRef.current = setTimeout(() => {\n if (overlayRef.current) overlayRef.current.style.display = 'none';\n if (tooltipRef.current) tooltipRef.current.style.display = 'none';\n currentElementRef.current = null;\n debug.log('hidden overlay and tooltip');\n }, 100);\n }, [debug]);\n\n const cleanup = useCallback(() => {\n if (hideTimeoutRef.current) {\n clearTimeout(hideTimeoutRef.current);\n }\n\n if (overlayRef.current) {\n DOMService.removeFromBody(overlayRef.current);\n }\n if (tooltipRef.current) {\n DOMService.removeFromBody(tooltipRef.current);\n }\n\n debug.log('cleaned up overlay and tooltip');\n }, [debug]);\n\n return {\n overlayRef,\n tooltipRef,\n currentElementRef,\n hideTimeoutRef,\n createOverlay,\n showOverlay,\n hideOverlay,\n cleanup,\n decode,\n };\n}\n","import { useRef, useCallback } from 'react';\nimport { createScopedLogger } from '../../utils/debug';\nimport { createElementCache } from '../../utils/performance';\n\nexport function useStegaProximity() {\n const debug = createScopedLogger('useStegaProximity');\n const highlightedElementsRef = useRef<Set<HTMLElement>>(new Set());\n const getEncodedElements = createElementCache<HTMLElement>(\n '[data-prepr-encoded]',\n 500\n );\n\n const updateElementGradients = useCallback(\n (cursorX: number, cursorY: number) => {\n const encodedElements = getEncodedElements();\n const newHighlightedElements = new Set<HTMLElement>();\n let highlightedCount = 0;\n\n encodedElements.forEach(element => {\n const rect = element.getBoundingClientRect();\n\n // Calculate shortest distance from cursor to element edges\n const distanceLeft = Math.abs(cursorX - rect.left);\n const distanceRight = Math.abs(cursorX - rect.right);\n const distanceTop = Math.abs(cursorY - rect.top);\n const distanceBottom = Math.abs(cursorY - rect.bottom);\n\n // Use minimum distance to any edge\n const distance = Math.min(\n distanceLeft,\n distanceRight,\n distanceTop,\n distanceBottom\n );\n\n const el = element as HTMLElement;\n if (distance < 150) {\n // Calculate relative cursor position within the element\n const relativeX = cursorX - rect.left;\n const relativeY = cursorY - rect.top;\n\n el.style.setProperty('--cursor-x', `${relativeX}px`);\n el.style.setProperty('--cursor-y', `${relativeY}px`);\n\n // Set gradient size based on element dimensions\n // Calculate base gradient size based on element dimensions\n const baseGradientSize = Math.max(\n 150,\n Math.max(rect.width, rect.height) * 1.1\n );\n // Scale gradient size based on distance (400 is max distance, closer = larger gradient)\n const distanceScale = Math.max(0, (400 - distance) / 400);\n const gradientSize = baseGradientSize * distanceScale;\n\n el.style.setProperty('--gradient-size', `${gradientSize}px`);\n el.classList.add('prepr-proximity-highlight');\n newHighlightedElements.add(el);\n highlightedCount++;\n } else {\n el.classList.remove('prepr-proximity-highlight');\n }\n });\n\n // Update the highlighted elements reference\n highlightedElementsRef.current = newHighlightedElements;\n\n if (highlightedCount > 0) {\n debug.log('highlighted', highlightedCount, 'elements near cursor');\n }\n },\n [debug, getEncodedElements]\n );\n\n const clearAllHighlights = useCallback(() => {\n const highlightedElements = highlightedElementsRef.current;\n let clearedCount = 0;\n\n highlightedElements.forEach(element => {\n element.classList.remove('prepr-proximity-highlight');\n clearedCount++;\n });\n\n highlightedElementsRef.current.clear();\n\n if (clearedCount > 0) {\n debug.log('cleared highlights from', clearedCount, 'elements');\n }\n }, [debug]);\n\n return {\n updateElementGradients,\n clearAllHighlights,\n highlightedElementsRef,\n };\n}\n","import { useRef, useCallback } from 'react';\nimport { createScopedLogger } from '../../utils/debug';\n\n// Define the expected structure for decoded data\ninterface DecodedData {\n href: string;\n origin: string;\n}\n\nexport function useStegaElements() {\n const debug = createScopedLogger('useStegaElements');\n const elementsRef = useRef<NodeListOf<Element> | undefined>(undefined);\n const observerRef = useRef<MutationObserver | null>(null);\n\n const getElements = useCallback(() => {\n if (!elementsRef.current) {\n elementsRef.current = document.querySelectorAll('[data-prepr-encoded]');\n }\n return elementsRef.current;\n }, []);\n\n const scanNode = useCallback(\n (node: Node, decode: (str: string | null) => DecodedData | null) => {\n if (node.nodeType === Node.TEXT_NODE) {\n if (!node.textContent?.trim()) return;\n if (node.parentElement?.closest('script, style, noscript')) return;\n const decoded = decode(node.textContent);\n if (decoded?.href) {\n const target = node.parentElement;\n if (target && !target.hasAttribute('data-prepr-encoded')) {\n target.setAttribute('data-prepr-encoded', '');\n target.setAttribute('data-prepr-href', decoded.href);\n target.setAttribute('data-prepr-origin', decoded.origin);\n debug.log('encoded element found:', {\n href: decoded.href,\n origin: decoded.origin,\n });\n }\n }\n } else if (node.nodeType === Node.ELEMENT_NODE) {\n for (let i = 0; i < node.childNodes.length; i++) {\n scanNode(node.childNodes[i], decode);\n }\n }\n },\n [debug]\n );\n\n const scanDocument = useCallback(\n (decode: (str: string | null) => DecodedData | null) => {\n debug.log('starting document scan');\n const walker = document.createTreeWalker(\n document.body,\n NodeFilter.SHOW_TEXT,\n {\n acceptNode: node => {\n if (node.parentElement?.closest('script, style, noscript')) {\n return NodeFilter.FILTER_REJECT;\n }\n if (!node.textContent?.trim()) {\n return NodeFilter.FILTER_REJECT;\n }\n return NodeFilter.FILTER_ACCEPT;\n },\n }\n );\n let textNode;\n let encodedCount = 0;\n while ((textNode = walker.nextNode())) {\n const decoded = decode(textNode.textContent);\n if (decoded?.href) {\n const target = textNode.parentElement;\n if (target && !target.hasAttribute('data-prepr-encoded')) {\n target.setAttribute('data-prepr-encoded', '');\n target.setAttribute('data-prepr-href', decoded.href);\n target.setAttribute('data-prepr-origin', decoded.origin);\n encodedCount++;\n }\n }\n }\n debug.log('document scan complete, encoded', encodedCount, 'elements');\n elementsRef.current = document.querySelectorAll('[data-prepr-encoded]');\n },\n [debug]\n );\n\n const setupMutationObserver = useCallback(\n (decode: (str: string | null) => DecodedData | null) => {\n if (observerRef.current) {\n observerRef.current.disconnect();\n }\n let pendingMutations: MutationRecord[] = [];\n let debounceTimeout: NodeJS.Timeout | null = null;\n const processMutations = () => {\n const allAddedNodes = new Set<Node>();\n pendingMutations.forEach(mutation => {\n mutation.addedNodes.forEach(node => allAddedNodes.add(node));\n });\n allAddedNodes.forEach(node => scanNode(node, decode));\n pendingMutations = [];\n elementsRef.current = document.querySelectorAll('[data-prepr-encoded]');\n };\n observerRef.current = new MutationObserver(mutations => {\n pendingMutations.push(...mutations);\n if (debounceTimeout) clearTimeout(debounceTimeout);\n debounceTimeout = setTimeout(processMutations, 100);\n });\n observerRef.current.observe(document.body, {\n childList: true,\n subtree: true,\n });\n debug.log('mutation observer set up');\n },\n [scanNode, debug]\n );\n\n const cleanup = useCallback(() => {\n if (observerRef.current) {\n observerRef.current.disconnect();\n observerRef.current = null;\n }\n const encodedElements = document.querySelectorAll('[data-prepr-encoded]');\n encodedElements.forEach(element => {\n element.removeAttribute('data-prepr-encoded');\n element.removeAttribute('data-prepr-href');\n element.removeAttribute('data-prepr-origin');\n });\n debug.log('cleaned up', encodedElements.length, 'encoded elements');\n elementsRef.current = undefined;\n }, [debug]);\n\n return {\n getElements,\n scanDocument,\n setupMutationObserver,\n cleanup,\n };\n}\n","import React, { useEffect, useState } from 'react';\nimport { useSearchParams } from 'next/navigation';\nimport Toolbar from './toolbar';\n\nexport default function ToolbarWrapper() {\n const searchParams = useSearchParams();\n const [isIframe, setIsIframe] = useState<boolean>(false);\n\n const handleKeyDown = (event: KeyboardEvent) => {\n const key = event.key.toLowerCase();\n // Check for the blocked shortcuts\n const isSaveShortcut = (event.ctrlKey || event.metaKey) && key === 's';\n const isPrintShortcut = (event.ctrlKey || event.metaKey) && key === 'p';\n const isAddressBarShortcut =\n (event.ctrlKey || event.metaKey) && key === 'l';\n if (isSaveShortcut || isPrintShortcut || isAddressBarShortcut) {\n event.preventDefault(); // Prevent the browser's default action\n }\n };\n\n useEffect(() => {\n const isIframe =\n typeof window !== 'undefined' && window?.parent !== window.self;\n if (isIframe) {\n setIsIframe(true);\n const previewBarMessage = {\n name: 'prepr_preview_bar',\n event: 'loaded',\n };\n window.parent.postMessage(previewBarMessage, '*');\n window.addEventListener('keydown', handleKeyDown);\n }\n return () => {\n if (isIframe) {\n window.removeEventListener('keydown', handleKeyDown);\n }\n };\n }, []);\n\n if (searchParams.get('prepr_hide_bar') === 'true' || isIframe) {\n return null;\n }\n\n return <Toolbar />;\n}\n","import React, { useEffect, useState } from 'react';\nimport { createPortal } from 'react-dom';\nimport { cn } from '../../../utils';\nimport { useEditModeContext } from '../../contexts';\nimport { useModal } from '../../hooks/use-modal';\nimport { ToolbarContent } from './toolbar-content';\nimport { ToolbarButton } from './toolbar-button';\n\ninterface ToolbarProps {\n children?: React.ReactNode;\n}\n\nexport default function Toolbar({ children }: ToolbarProps) {\n const [isMounted, setIsMounted] = useState(false);\n const [isBarVisible, setIsBarVisible] = React.useState(false);\n const { editMode } = useEditModeContext();\n const { contentRef, triggerRef } = useModal({\n isVisible: isBarVisible,\n onClose: () => setIsBarVisible(false),\n });\n\n useEffect(() => {\n setIsMounted(true);\n }, []);\n\n // Ref for the popup box\n const popupBoxRef = React.useRef<HTMLDivElement>(null);\n const [popupTop, setPopupTop] = React.useState<string | number>('');\n\n const updatePopupPosition = React.useCallback(() => {\n if (popupBoxRef.current && triggerRef.current) {\n const popupHeight = popupBoxRef.current.offsetHeight;\n const windowHeight = window.innerHeight;\n const triggerRect = triggerRef.current.getBoundingClientRect();\n // Center popup relative to the icon (trigger)\n const triggerCenter = triggerRect.top + triggerRect.height / 2;\n let top = triggerCenter - popupHeight / 2;\n // Clamp to leave at least 32px top and bottom\n top = Math.max(32, Math.min(top, windowHeight - popupHeight - 32));\n setPopupTop(top);\n }\n }, [triggerRef]);\n\n useEffect(() => {\n if (isBarVisible) {\n updatePopupPosition();\n window.addEventListener('resize', updatePopupPosition);\n return () => window.removeEventListener('resize', updatePopupPosition);\n }\n return undefined;\n }, [isBarVisible, updatePopupPosition]);\n\n const handleClick = () => {\n setIsBarVisible(!isBarVisible);\n };\n\n useEffect(() => {\n if (editMode) {\n setTimeout(() => {\n setIsBarVisible(false);\n }, 150);\n }\n }, [editMode]);\n\n const previewBarContent = (\n <>\n {isBarVisible && <div className=\"preview-bar-backdrop\" />}\n <div className={cn('preview-bar-container')}>\n {/* Button holder*/}\n <div className=\"p-pr-2\" ref={triggerRef}>\n <ToolbarButton onClick={handleClick} />\n </div>\n\n {/* Box holder */}\n <div\n ref={popupBoxRef}\n style={\n popupTop !== ''\n ? { top: popupTop, position: 'fixed', right: 0 }\n : {}\n }\n className={cn(\n 'preview-bar-popup',\n isBarVisible\n ? 'p-pointer-events-auto p-opacity-100'\n : 'p-pointer-events-none p-opacity-0'\n )}\n >\n {children || (\n <ToolbarContent onClose={handleClick} contentRef={contentRef} />\n )}\n </div>\n </div>\n </>\n );\n\n if (!isMounted) return null;\n\n return createPortal(previewBarContent, document.body);\n}\n\n// Compound component pattern\nToolbar.Content = ToolbarContent;\nToolbar.Button = ToolbarButton;\n","import { ClassValue, clsx } from 'clsx';\nimport { twMerge } from 'tailwind-merge';\nimport { PreprEventType } from '../types';\n\nexport function cn(...inputs: ClassValue[]) {\n return twMerge(clsx(inputs));\n}\n\n// Define specific types for Prepr events\nexport interface PreprEventData {\n readonly segment?: string;\n readonly variant?: string;\n readonly editMode?: boolean;\n readonly [key: string]: string | boolean | number | undefined;\n}\n\n/**\n * Sends a Prepr event to the parent window\n * @param event - The event type to send\n * @param data - Optional event data\n */\nexport function sendPreprEvent(\n event: PreprEventType,\n data?: PreprEventData\n): void {\n if (typeof window !== 'undefined' && window.parent) {\n window.parent.postMessage(\n {\n name: 'prepr_preview_bar',\n event,\n ...data,\n },\n '*'\n );\n }\n}\n\n// Export error handling utilities\nexport * from './errors';\n\n// Export DOM service\nexport * from './dom';\n\n// Export debug utilities\nexport * from './debug';\n\n// Export performance utilities\nexport * from './performance';\n","import { useEffect, useRef } from 'react';\n\ninterface UseModalProps {\n isVisible: boolean;\n onClose: () => void;\n}\n\nexport function useModal({ isVisible, onClose }: UseModalProps) {\n const contentRef = useRef<HTMLDivElement>(null);\n const triggerRef = useRef<HTMLDivElement>(null);\n\n useEffect(() => {\n if (isVisible) {\n document.body.style.overflow = 'hidden';\n } else {\n document.body.style.overflow = '';\n }\n return () => {\n document.body.style.overflow = '';\n };\n }, [isVisible]);\n\n useEffect(() => {\n const handleEscapeKey = (event: KeyboardEvent) => {\n if (event.key === 'Escape') {\n onClose();\n }\n };\n\n const handleClickOutside = (event: MouseEvent) => {\n // Check if the click target is part of a dropdown\n const isDropdownItem = (event.target as HTMLElement).closest(\n '[role=\"listbox\"], [role=\"option\"]'\n );\n if (isDropdownItem) {\n return;\n }\n\n if (\n contentRef.current &&\n !contentRef.current.contains(event.target as Node) &&\n triggerRef.current &&\n !triggerRef.current.contains(event.target as Node)\n ) {\n onClose();\n }\n };\n\n if (isVisible) {\n document.addEventListener('keydown', handleEscapeKey);\n document.addEventListener('mousedown', handleClickOutside);\n }\n\n return () => {\n document.removeEventListener('keydown', handleEscapeKey);\n document.removeEventListener('mousedown', handleClickOutside);\n };\n }, [isVisible, onClose]);\n\n return {\n contentRef,\n triggerRef,\n };\n}\n","import React from 'react';\nimport { Logo } from '../ui';\nimport {\n SegmentSelector,\n VariantSelector,\n EditModeSelector,\n} from '../selectors';\nimport { ResetButton } from '../ui';\n\ninterface ToolbarContentProps {\n onClose: () => void;\n contentRef: React.RefObject<HTMLDivElement | null>;\n}\n\nexport function ToolbarContent({ onClose, contentRef }: ToolbarContentProps) {\n return (\n <div\n ref={contentRef}\n className=\"p-box-shadow p-right-0 p-z-[101] p-flex p-w-full p-flex-col p-gap-y-10 p-rounded-lg p-bg-primary-50 p-p-6 sm:p-w-[502px] sm:p-p-10\"\n >\n {/* Header */}\n <div className=\"p-flex p-items-center p-justify-between p-gap-2\">\n <div className=\"p-flex p-items-start p-gap-3\">\n <Logo />\n <div className=\"p-flex p-h-6 p-items-center p-rounded p-bg-primary-100 p-px-3 p-py-1 p-text-sm p-text-primary-700\">\n toolbar\n </div>\n </div>\n <button\n onClick={onClose}\n className=\"p-flex p-h-8 p-w-8 p-cursor-pointer p-items-center p-justify-center p-rounded-md p-bg-primary-100 p-text-gray-700\"\n >\n <svg\n width=\"10\"\n height=\"10\"\n viewBox=\"0 0 10 10\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path\n d=\"M8.17578 1.07031C8.41016 0.816406 8.82031 0.816406 9.05469 1.07031C9.30859 1.30469 9.30859 1.71484 9.05469 1.94922L5.75391 5.25L9.05469 8.57031C9.30859 8.80469 9.30859 9.21484 9.05469 9.44922C8.82031 9.70312 8.41016 9.70312 8.17578 9.44922L4.875 6.14844L1.55469 9.44922C1.32031 9.70312 0.910156 9.70312 0.675781 9.44922C0.421875 9.21484 0.421875 8.80469 0.675781 8.57031L3.97656 5.25L0.675781 1.94922C0.421875 1.71484 0.421875 1.30469 0.675781 1.07031C0.910156 0.816406 1.32031 0.816406 1.55469 1.07031L4.875 4.37109L8.17578 1.07031Z\"\n fill=\"currentColor\"\n />\n </svg>\n </button>\n </div>\n\n {/* Personalized Content */}\n <div className=\"p-space-y-2\">\n <span className=\"p-text-sm p-text-grey-400\">Personalized content</span>\n <div className=\"p-gap p-flex p-flex-wrap p-items-center p-justify-between p-gap-x-6 p-gap-y-2\">\n <h2 className=\"p-text-grey-800 p-font-semibold\">Apply segment</h2>\n <SegmentSelector />\n </div>\n <div className=\"p-gap p-flex p-flex-wrap p-items-center p-justify-between p-gap-x-6 p-gap-y-2\">\n <h2 className=\"p-text-grey-800 p-font-semibold\">Show A/B variant</h2>\n <VariantSelector />\n </div>\n </div>\n\n {/* Collaboration */}\n <div className=\"p-space-y-2\">\n <span className=\"p-text-sm p-text-grey-400\">Collaboration</span>\n <div className=\"p-gap p-flex p-flex-wrap p-items-center p-justify-between p-gap-x-6 p-gap-y-2\">\n <h2 className=\"p-text-grey-800 p-font-semibold\">Edit mode</h2>\n <EditModeSelector />\n </div>\n </div>\n\n <ResetButton />\n </div>\n );\n}\n","import React from 'react';\nimport { usePreprToolbar } from '../toolbar/toolbar-provider';\nimport XMark from '../icons/xmark';\nimport { usePathname, useRouter } from 'next/navigation';\n\nexport default function StatusIndicatorPill() {\n const {\n selectedSegment,\n selectedVariant,\n emptySegment,\n emptyVariant,\n isIframe,\n resetPersonalization,\n } = usePreprToolbar();\n\n // Only show if a segment or variant is applied (not empty/null)\n const show =\n (selectedSegment &&\n selectedSegment._id !== (emptySegment?._id ?? 'null')) ||\n (selectedVariant && selectedVariant !== (emptyVariant ?? 'null'));\n\n const router = useRouter();\n const pathname = usePathname();\n\n const handleReset = () => {\n resetPersonalization();\n // Set preview params to 'null' in the URL, then remove them for a clean URL\n const params = new URLSearchParams();\n params.set('prepr_preview_segment', 'null');\n params.set('prepr_preview_ab', 'null');\n\n // First, push the URL with reset params to trigger any listeners\n router.push(`${pathname}?${params.toString()}`, { scroll: false });\n router.refresh();\n\n // Then, push the clean URL (without the reset params)\n router.push(pathname, { scroll: false });\n router.refresh();\n };\n\n if (isIframe) {\n return null;\n }\n\n return (\n <div className=\"p-z-[998] p-flex p-gap-2\">\n {show && (\n <button\n type=\"button\"\n onClick={handleReset}\n className=\"p-flex p-cursor-pointer p-items-center p-gap-2 p-rounded-full p-bg-primary-700 p-px-4 p-py-2 p-text-xs p-font-medium p-text-white p-shadow-lg p-transition-colors p-duration-150 hover:p-bg-primary-800\"\n >\n <span className=\"p-text-[10px] p-text-white/60\">viewing as</span>\n {selectedSegment &&\n selectedSegment._id !== (emptySegment?._id ?? 'null') && (\n <span className=\"max-w-[120px] p-inline-block p-truncate\">\n {selectedSegment.name}\n </span>\n )}\n {selectedVariant && selectedVariant !== (emptyVariant ?? 'null') && (\n <span className=\"max-w-[80px] p-inline-block p-truncate p-rounded p-bg-white/20 p-px-2\">\n {selectedVariant}\n </span>\n )}\n <XMark className=\"p-h-3 p-w-3 p-text-white\" />\n </button>\n )}\n </div>\n );\n}\n","import React from 'react';\n\nexport default function XMark(props: React.SVGProps<SVGSVGElement>) {\n return (\n <svg\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 16 16\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n {...props}\n >\n <path\n d=\"M4.22 4.22a.75.75 0 0 1 1.06 0L8 6.94l2.72-2.72a.75.75 0 1 1 1.06 1.06L9.06 8l2.72 2.72a.75.75 0 1 1-1.06 1.06L8 9.06l-2.72 2.72a.75.75 0 1 1-1.06-1.06L6.94 8 4.22 5.28a.75.75 0 0 1 0-1.06z\"\n fill=\"currentColor\"\n />\n </svg>\n );\n}\n","import React from 'react';\nimport { usePreprToolbar } from '../toolbar/toolbar-provider';\nimport XMark from '../icons/xmark';\n\nexport default function CloseEditModePill() {\n const { editMode, setEditMode, isIframe } = usePreprToolbar();\n\n if (!editMode || isIframe) {\n return null;\n }\n\n return (\n <div className=\"p-z-[999] p-flex\">\n <button\n type=\"button\"\n onClick={() => setEditMode && setEditMode(false)}\n className=\"p-flex p-items-center p-gap-2 p-rounded-full p-bg-primary-50 p-px-4 p-py-2 p-text-xs p-font-medium p-text-gray-800 p-shadow-lg p-transition-colors p-duration-150 hover:p-bg-primary-100\"\n aria-label=\"Close edit mode\"\n >\n <span>Edit mode</span>\n <XMark className=\"transition-colors duration-150 p-h-4 p-w-4 p-text-gray-500 hover:p-text-gray-700\" />\n </button>\n </div>\n );\n}\n","import React from 'react';\nimport { usePathname, useRouter } from 'next/navigation';\nimport { cn } from '../../../utils';\nimport { usePreprToolbar } from '../toolbar/toolbar-provider';\nimport Rotate from '../icons/rotate';\n\nexport default function ResetButton() {\n const router = useRouter();\n const { resetAll, selectedVariant, selectedSegment, setEditMode, editMode } =\n usePreprToolbar();\n const pathname = usePathname();\n const enabled =\n selectedSegment._id !== 'null' || selectedVariant !== 'null' || editMode;\n\n const handleClick = () => {\n resetAll();\n setEditMode(false);\n\n // Set preview params to 'null' in the URL, then remove them for a clean URL\n const params = new URLSearchParams();\n params.set('prepr_preview_segment', 'null');\n params.set('prepr_preview_ab', 'null');\n\n // First, push the URL with reset params to trigger any listeners\n router.push(`${pathname}?${params.toString()}`, { scroll: false });\n router.refresh();\n\n // Then, push the clean URL (without the reset params)\n router.push(pathname, { scroll: false });\n router.refresh();\n };\n\n const classes = cn(\n 'p-py-2 p-px-3 p-flex p-justify-center p-gap-2 p-items-center p-rounded-md p-regular-text p-h-10 p-w-full md:p-w-[108px]',\n enabled &&\n 'p-bg-secondary-400 hover:p-secondary-500 p-cursor-pointer p-text-white',\n !enabled && 'p-bg-grey-400 p-text-gray-500'\n );\n\n return (\n <button onClick={handleClick} className={classes} disabled={!enabled}>\n <Rotate />\n <span className=\"p-block sm:p-hidden lg:p-block\">Reset</span>\n </button>\n );\n}\n","import React from 'react';\n\nexport default function Rotate() {\n return (\n <svg\n width=\"15\"\n height=\"14\"\n viewBox=\"0 0 15 14\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path\n d=\"M3.37109 5.80078C3.20703 6.26562 2.6875 6.51172 2.25 6.34766C1.78516 6.18359 1.53906 5.69141 1.70312 5.22656C2.00391 4.37891 2.49609 3.58594 3.15234 2.92969C5.55859 0.550781 9.41406 0.550781 11.8203 2.92969L12.2852 3.42188V2C12.2852 1.53516 12.6953 1.125 13.1602 1.125C13.6523 1.125 14.0352 1.53516 14.0352 2V5.5C14.0352 5.99219 13.6523 6.375 13.1602 6.375H9.6875C9.19531 6.375 8.8125 5.99219 8.8125 5.5C8.8125 5.03516 9.19531 4.625 9.6875 4.625H11.0547L10.5898 4.16016C8.86719 2.46484 6.10547 2.46484 4.38281 4.16016C3.91797 4.65234 3.5625 5.19922 3.37109 5.80078ZM1.56641 8.17969C1.59375 8.15234 1.64844 8.15234 1.67578 8.15234C1.73047 8.15234 1.75781 8.125 1.8125 8.125H5.3125C5.77734 8.125 6.1875 8.53516 6.1875 9C6.1875 9.49219 5.77734 9.875 5.3125 9.875H3.91797L4.38281 10.3672C6.10547 12.0625 8.86719 12.0625 10.5898 10.3672C11.0547 9.875 11.4102 9.32812 11.6016 8.72656C11.7656 8.26172 12.2852 8.01562 12.7227 8.17969C13.1875 8.34375 13.4336 8.83594 13.2695 9.30078C12.9688 10.1484 12.4766 10.9141 11.8203 11.5977C9.41406 13.9766 5.55859 13.9766 3.15234 11.5977L2.6875 11.1055V12.5C2.6875 12.9922 2.27734 13.375 1.8125 13.375C1.32031 13.375 0.9375 12.9922 0.9375 12.5V9.02734C0.9375 8.97266 0.9375 8.91797 0.9375 8.89062C0.9375 8.83594 0.9375 8.80859 0.964844 8.78125C0.992188 8.64453 1.07422 8.50781 1.18359 8.39844C1.29297 8.28906 1.42969 8.20703 1.56641 8.17969Z\"\n fill=\"currentColor\"\n />\n </svg>\n );\n}\n","import React from 'react';\n\nconst Icon: React.FC<React.SVGProps<SVGSVGElement>> = props => {\n return (\n <svg\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 16 16\"\n xmlns=\"http://www.w3.org/2000/svg\"\n {...props}\n >\n <path\n d=\"M9.05365 0C5.71033 0 3 2.75516 3 6.15377V15.6309C3 15.8346 3.16248 16 3.36328 16H5.05838C5.25898 16 5.42166 15.8346 5.42166 15.6309V11.0772C6.43342 11.8498 7.69104 12.3077 9.05385 12.3077C12.397 12.3077 15.1077 9.55259 15.1077 6.15397C15.1075 2.75516 12.397 0 9.05365 0ZM9.05365 9.84623C7.04766 9.84623 5.42146 8.19314 5.42146 6.15377C5.42146 4.1146 7.04766 2.46151 9.05365 2.46151C11.0596 2.46151 12.686 4.1146 12.686 6.15377C12.686 8.19293 11.0596 9.84623 9.05365 9.84623Z\"\n fill=\"currentColor\"\n />\n </svg>\n );\n};\n\nexport default Icon;\n","import React from 'react';\n\nconst Logo: React.FC<React.SVGProps<SVGSVGElement>> = props => {\n return (\n <svg\n width=\"102\"\n height=\"28\"\n viewBox=\"0 0 102 28\"\n fill=\"none\"\n {...props}\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path\n d=\"M39.2674 2.19699C39.2757 2.18321 39.2839 2.16943 39.291 2.15528L39.2939 2.15057L39.2935 2.1502C39.3379 2.06208 39.3633 1.96308 39.3633 1.85754C39.3633 1.62109 39.2374 1.41474 39.0507 1.30231C39.0485 1.30014 39.0467 1.29651 39.0446 1.29578C35.1089 -0.88088 29.8537 -0.36627 26.3741 3.2632C24.4207 5.3006 23.4231 7.92116 23.3716 10.5544H23.3684V20.893C23.3684 21.2495 23.6538 21.5389 24.0058 21.5389H26.98C27.332 21.5389 27.6174 21.2495 27.6174 20.893V10.7698H27.6192C27.6192 9.14658 28.2169 7.52187 29.4209 6.26599C31.5699 4.02478 34.7423 3.8565 36.9299 5.03659C36.9367 5.04058 36.9439 5.04384 36.9507 5.04747C36.9557 5.05001 36.9607 5.05254 36.9657 5.05508H36.9664C37.0494 5.09497 37.1417 5.11782 37.2393 5.11782C37.4879 5.11782 37.7032 4.97276 37.808 4.76206L39.2674 2.19699Z\"\n fill=\"#4338CA\"\n />\n <path\n d=\"M10.6216 0.000244141C4.75551 0.000244141 0 4.82177 0 10.7693V27.3543C0 27.7108 0.285079 28.0002 0.637405 28.0002H3.61161C3.96358 28.0002 4.24902 27.7108 4.24902 27.3543V19.3853C6.02424 20.7373 8.23084 21.5388 10.622 21.5388C16.4878 21.5388 21.244 16.7173 21.244 10.7697C21.2437 4.82177 16.4878 0.000244141 10.6216 0.000244141ZM10.6216 17.2311C7.10196 17.2311 4.24866 14.3382 4.24866 10.7693C4.24866 7.20079 7.10196 4.30788 10.6216 4.30788C14.1413 4.30788 16.995 7.20079 16.995 10.7693C16.995 14.3379 14.1413 17.2311 10.6216 17.2311Z\"\n fill=\"#4338CA\"\n />\n <path\n d=\"M73.259 0C67.3932 0 62.6373 4.82152 62.6373 10.7691V27.3541C62.6373 27.7106 62.9228 28 63.2747 28H66.2489C66.6009 28 66.8863 27.7106 66.8863 27.3541V19.3854C68.6616 20.7374 70.8682 21.5389 73.2593 21.5389C79.1251 21.5389 83.8813 16.7174 83.8813 10.7698C83.881 4.82152 79.1248 0 73.259 0ZM73.259 17.2309C69.7393 17.2309 66.886 14.338 66.886 10.7691C66.886 7.20055 69.7393 4.30764 73.259 4.30764C76.7783 4.30764 79.632 7.20055 79.632 10.7691C79.632 14.3376 76.7783 17.2309 73.259 17.2309Z\"\n fill=\"#4338CA\"\n />\n <path\n d=\"M60.439 10.9845C60.439 5.03657 55.6827 0 49.817 0C43.9508 0 39.1953 4.82152 39.1953 10.7691C39.1953 16.7167 43.9508 21.5382 49.817 21.5382C53.1374 21.5382 55.8763 19.9954 57.5939 18.1031C57.5939 18.1031 57.5942 18.1027 57.5946 18.1024C57.596 18.1009 57.5975 18.0995 57.5985 18.098C57.7112 17.9812 57.7806 17.822 57.7806 17.6461C57.7806 17.4601 57.7026 17.2929 57.5785 17.1751V17.1743L57.5696 17.1671C57.5535 17.1522 57.5367 17.1384 57.5188 17.1254L55.2464 15.2501C55.1344 15.1503 54.9877 15.0891 54.8264 15.0891C54.6261 15.0891 54.4476 15.183 54.331 15.3291C53.3216 16.3707 51.7256 17.2309 49.8166 17.2309C46.2969 17.2309 43.4436 14.338 43.4436 10.7691C43.4436 7.20055 46.2969 4.30764 49.8166 4.30764C52.5909 4.30764 54.9505 6.10605 55.8255 8.61527H50.3474C49.9954 8.61527 49.71 8.90467 49.71 9.26152V12.277C49.71 12.6339 49.9954 12.9233 50.3474 12.9233H59.5884C59.6059 12.9233 59.6227 12.9218 59.6399 12.9207C59.6571 12.9222 59.6742 12.9233 59.6914 12.9233C59.9743 12.9233 60.214 12.7361 60.2973 12.4772L60.3045 12.4783C60.308 12.4551 60.3116 12.4326 60.3152 12.4097C60.3199 12.3876 60.3234 12.3655 60.3256 12.3427C60.4003 11.861 60.439 11.5172 60.439 10.9845Z\"\n fill=\"#4338CA\"\n />\n <path\n d=\"M101.928 2.15406L101.931 2.14934L101.93 2.14898C101.974 2.06085 102 1.96185 102 1.85632C102 1.61987 101.874 1.41351 101.687 1.30109C101.685 1.29891 101.683 1.29529 101.681 1.29456C97.7455 -0.882101 92.4903 -0.367491 89.0107 3.26198C87.0573 5.29938 86.0597 7.91993 86.0082 10.5532H86.005V20.8918C86.005 21.2483 86.2904 21.5377 86.6424 21.5377H89.6166C89.9686 21.5377 90.254 21.2483 90.254 20.8918V10.7686H90.2555C90.2555 9.14535 90.8532 7.52065 92.0571 6.26477C94.2062 4.02355 97.3785 3.85528 99.5662 5.03537C99.573 5.03936 99.5801 5.04262 99.5869 5.04624C99.5919 5.04878 99.5969 5.05132 99.6019 5.05386H99.6027C99.6856 5.09375 99.7779 5.11696 99.8756 5.11696C100.124 5.11696 100.339 4.9719 100.444 4.7612L101.905 2.19685C101.913 2.18235 101.92 2.16856 101.928 2.15406Z\"\n fill=\"#4338CA\"\n />\n </svg>\n );\n};\n\nexport default Logo;\n","'use client';\n\nimport React from 'react';\nimport Script from 'next/script';\n\ninterface PreprTrackingPixelProps {\n /**\n * The Prepr access token (without the full GraphQL URL)\n * Extract this from your PREPR_GRAPHQL_URL: https://graphql.prepr.io/YOUR_ACCESS_TOKEN\n */\n accessToken?: string;\n}\n\n/**\n * PreprTrackingPixel component for user tracking\n *\n * This component loads the Prepr tracking script and initializes tracking.\n * It should be included in your application to track user interactions.\n *\n * @param accessToken - Your Prepr access token\n *\n * @example\n * ```tsx\n * // In your layout or page\n * import { PreprTrackingPixel } from '@preprio/prepr-nextjs/react'\n *\n * // Extract token from PREPR_GRAPHQL_URL\n * const accessToken = process.env.PREPR_GRAPHQL_URL?.split('/').pop() || ''\n *\n * export default function Layout({ children }) {\n * return (\n * <html>\n * <head>\n * <PreprTrackingPixel accessToken={accessToken!} />\n * </head>\n * <body>{children}</body>\n * </html>\n * )\n * }\n * ```\n */\nexport default function PreprTrackingPixel({\n accessToken,\n}: PreprTrackingPixelProps) {\n if (!accessToken) {\n console.warn(\n 'PreprTrackingPixel: accessToken is required for tracking to work'\n );\n return null;\n }\n\n return (\n <Script\n id=\"prepr-tracking-pixel\"\n strategy=\"afterInteractive\"\n dangerouslySetInnerHTML={{\n __html: `\n !function(e,t,p,r,n,a,s){\n e[r]||((n=e[r]=function(){\n n.process?n.process.apply(n,arguments):n.queue.push(arguments)\n }).queue=[],n.t=+new Date,(a=t.createElement(p)).async=1,a.src=\"https://cdn.tracking.prepr.io/js/prepr_v2.min.js?t=\"+864e5*Math.ceil(new Date/864e5),(s=t.getElementsByTagName(p)[0]).parentNode.insertBefore(a,s))\n }(window,document,\"script\",\"prepr\");\n prepr(\"init\",\"${accessToken}\");\n prepr(\"event\",\"pageload\");\n `,\n }}\n />\n );\n}\n","import React from 'react';\nimport { PreprSegment } from '../../../types';\nimport { useSegmentContext } from '../../contexts';\nimport { usePathname, useRouter } from 'next/navigation';\nimport {\n Listbox,\n ListboxButton,\n ListboxOption,\n ListboxOptions,\n} from '@headlessui/react';\nimport SortDown from '../icons/sort-down';\nimport { cn } from '../../../utils';\n\nexport default function SegmentSelector() {\n const { segments, setSelectedSegment, selectedSegment } = useSegmentContext();\n\n const pathname = usePathname();\n const router = useRouter();\n\n const updateSelectedSegment = (value: string) => {\n const params = new URLSearchParams(window.location.search);\n const segment = segments.find(segment => segment._id === value);\n\n if (segment) {\n setSelectedSegment(segment);\n params.set('prepr_preview_segment', value);\n\n router.push(`${pathname}?${params.toString()}`, {\n scroll: false,\n });\n router.refresh();\n }\n };\n\n return (\n <Listbox\n value={selectedSegment._id}\n onChange={(value: string) => updateSelectedSegment(value)}\n >\n <ListboxButton\n as=\"button\"\n disabled={!(segments && segments.length > 0)}\n className=\"p-regular-text p-flex p-h-10 p-w-[240px] p-shrink-0 p-flex-nowrap p-items-center p-gap-2 p-overflow-hidden p-text-ellipsis p-text-nowrap p-rounded-lg p-border p-border-gray-300 p-bg-white p-px-2 p-text-gray-500 disabled:p-cursor-not-allowed disabled:p-bg-gray-200 disabled:p-text-gray-400 data-[open]:p-rounded-b-none data-[open]:p-border-b-white md:p-px-4\"\n >\n <div\n style={{\n textWrap: 'nowrap',\n textOverflow: 'ellipsis',\n textAlign: 'left',\n }}\n className=\"p-mr-auto p-w-full p-overflow-hidden\"\n >\n {segments.length > 0 ? selectedSegment.name : 'No segments'}\n </div>\n <div className=\"p-text-gray-800\">\n <SortDown />\n </div>\n </ListboxButton>\n <ListboxOptions\n anchor=\"bottom start\"\n className=\"p-no-scrollbar p-z-[9999] !p-max-h-[300px] p-w-[240px] p-rounded-b-md p-border-x p-border-b p-border-gray-300 p-bg-white p-shadow-xl\"\n >\n {segments?.map((segment: PreprSegment) => (\n <ListboxOption\n key={segment._id}\n value={segment._id}\n className={cn(\n 'p-regular-text p-z-[100] p-flex p-w-full p-items-center p-p-2 p-px-4 hover:p-cursor-pointer',\n segment._id === selectedSegment._id\n ? 'p-bg-indigo-50 p-text-indigo-700'\n : 'p-bg-white p-text-gray-900 hover:p-bg-gray-100'\n )}\n >\n <div\n style={{\n textWrap: 'nowrap',\n textOverflow: 'ellipsis',\n textAlign: 'left',\n }}\n className=\"p-mr-auto p-w-full p-overflow-hidden\"\n >\n {segment.name}\n </div>\n </ListboxOption>\n ))}\n </ListboxOptions>\n </Listbox>\n );\n}\n","import React from 'react';\n\nexport default function SortDown(props: React.SVGProps<SVGSVGElement>) {\n return (\n <svg\n width=\"9\"\n height=\"6\"\n viewBox=\"0 0 9 6\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n {...props}\n >\n <path\n d=\"M5.24274 5.36865C4.91462 5.72412 4.3404 5.72412 4.01227 5.36865L0.512273 1.86865C0.266179 1.62256 0.184148 1.23975 0.320867 0.911621C0.457586 0.583496 0.785711 0.364746 1.14118 0.364746H8.14118C8.46931 0.364746 8.79743 0.583496 8.93415 0.911621C9.07087 1.23975 8.98884 1.62256 8.74274 1.86865L5.24274 5.36865Z\"\n fill=\"currentColor\"\n />\n </svg>\n );\n}\n","import React from 'react';\nimport { useVariantContext } from '../../contexts';\nimport { usePathname, useRouter } from 'next/navigation';\nimport RadioSelector from './radio-selector';\n\nexport default function VariantSelector() {\n const { selectedVariant, setSelectedVariant, emptyVariant } =\n useVariantContext();\n\n const pathname = usePathname();\n const router = useRouter();\n\n const updateSelectedVariant = (value: string | boolean) => {\n const params = new URLSearchParams(window.location.search);\n setSelectedVariant(String(value));\n params.set('prepr_preview_ab', String(value));\n\n router.push(`${pathname}?${params.toString()}`, {\n scroll: false,\n });\n router.refresh();\n };\n\n const options = [\n { value: 'null', label: 'Off', width: 'p-w-[58px]' },\n { value: 'A', label: 'A', width: 'p-w-[82px]' },\n { value: 'B', label: 'B', width: 'p-w-[82px]' },\n ];\n\n return (\n <RadioSelector\n value={selectedVariant || emptyVariant}\n onChange={updateSelectedVariant}\n options={options}\n />\n );\n}\n","import React from 'react';\nimport { Radio, RadioGroup } from '@headlessui/react';\nimport { cn } from '../../../utils';\n\ninterface RadioOption {\n value: string | boolean;\n label: string;\n width?: string;\n}\n\ninterface RadioSelectorProps {\n value: string | boolean;\n onChange: (value: string | boolean) => void;\n options: RadioOption[];\n}\n\nexport default function RadioSelector({\n value,\n onChange,\n options,\n}: RadioSelectorProps) {\n return (\n <RadioGroup\n className=\"p-flex p-h-10 p-items-center p-gap-1 p-rounded-lg p-border p-border-gray-300 p-bg-white p-p-1\"\n value={value}\n onChange={onChange}\n >\n {options.map(option => (\n <Radio\n key={String(option.value)}\n value={option.value}\n className={cn(\n option.width || 'p-w-[58px]',\n 'p-regular-text p-flex p-h-8 p-cursor-pointer p-items-center p-justify-center p-rounded-md p-px-4.5 p-py-2 p-text-center p-text-gray-900 p-transition-all p-duration-200 p-ease-in-out',\n option.value === false ||\n option.value === 'null' ||\n option.value === 'off'\n ? 'data-[checked]:p-bg-gray-800 data-[checked]:p-text-white'\n : 'data-[checked]:p-bg-indigo-600 data-[checked]:p-text-white',\n option.value === value && 'p-drop-shadow-3'\n )}\n >\n {option.label}\n </Radio>\n ))}\n </RadioGroup>\n );\n}\n","import React from 'react';\nimport { useEditModeContext } from '../../contexts';\nimport RadioSelector from './radio-selector';\n\nexport default function EditModeSelector() {\n const { editMode, setEditMode } = useEditModeContext();\n\n const updateEditMode = (value: string | boolean) => {\n setEditMode(value === 'true' || value === true);\n };\n\n const options = [\n { value: 'false', label: 'Off' },\n { value: 'true', label: 'On' },\n ];\n\n return (\n <RadioSelector\n options={options}\n value={editMode.toString()}\n onChange={updateEditMode}\n />\n );\n}\n","import React from 'react';\nimport { cn } from '../../../utils';\nimport { Icon } from '../ui';\n\ninterface ToolbarButtonProps {\n onClick: () => void;\n className?: string;\n}\n\nexport function ToolbarButton({ onClick, className }: ToolbarButtonProps) {\n return (\n <button\n onClick={onClick}\n className={cn(\n 'cursor-pointer p-z-50 p-flex p-size-9 p-items-center p-justify-center p-rounded-full p-bg-primary-700',\n className\n )}\n >\n <Icon className=\"p-text-white\" />\n </button>\n );\n}\n","import React from 'react';\nimport { StatusIndicatorPill, CloseEditModePill } from '../ui';\n\nexport default function ToolbarIndicatorWrapper() {\n return (\n <div className=\"p-fixed p-bottom-6 p-right-6 p-z-[999] p-flex p-gap-3\">\n <StatusIndicatorPill />\n <CloseEditModePill />\n </div>\n );\n}\n"],"mappings":";0cAEA,OAAOA,GAAoB,aAAAC,GAAW,eAAAC,GAAa,WAAAC,OAAe,QCAlE,OAAOC,IAAS,iBAAAC,GAAe,cAAAC,GAAY,YAAAC,OAA2B,QCF/D,IAAMC,GAAa,CACxB,cAAe,sBACf,eAAgB,uBAChB,wBAAyB,0BACzB,kBAAmB,mBACrB,EAqBO,SAASC,GACdC,EACAC,EACAC,EACAC,EACW,CACX,MAAO,CACL,KAAAH,EACA,QAAAC,EACA,QAASC,EAAM,QACf,UAAW,IAAI,KAAK,EAAE,YAAY,EAClC,MAAOA,EAAM,MACb,eAAAC,CACF,CACF,CAEO,SAASC,GACdF,EACAD,EACAE,EACA,CACA,IAAME,EAAYN,GAChBD,GAAW,cACXG,EACAC,EACAC,CACF,EAEA,eAAQ,MAAM,eAAgBE,CAAS,EAGnC,QAAQ,IAAI,SAITA,CACT,CAEO,SAASC,EAAeJ,EAAcD,EAAiB,CAC5D,IAAMI,EAAYN,GAChBD,GAAW,wBACXG,EACAC,CACF,EAEA,eAAQ,MAAM,aAAcG,CAAS,EAC9BA,CACT,CAEO,SAASE,EAAmBC,EAAqB,CACtD,IAAMN,EAAQ,IAAI,MAAM,GAAGM,CAAW,mCAAmC,EACnEH,EAAYN,GAChBD,GAAW,kBACXU,EACAN,CACF,EAEA,cAAQ,MAAM,iBAAkBG,CAAS,EACnCH,CACR,CDxEA,IAAMO,GAAiBC,GACrB,MACF,EAQO,SAASC,GAAgB,CAC9B,SAAAC,EACA,gBAAA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N,MAAO,QACT,EACA,OAAO,OAAO,YAAYA,EAAmB,GAAG,EAChD,OAAO,iBAAiB,UAAWP,CAAa,CAClD,CACA,MAAO,IAAM,CACPH,GACF,OAAO,oBAAoB,UAAWG,CAAa,CAEvD,CACF,EAAG,CAAC,CAAC,EAEDL,EAAa,IAAI,gBAAgB,IAAM,QAAUE,EAC5C,KAGFW,GAAA,cAACC,EAAA,IAAQ,CAClB,CmB5CA,OAAOC,OAAW,QAGH,SAARC,IAA2C,CAChD,OACEC,GAAA,cAAC,OAAI,UAAU,yDACbA,GAAA,cAACC,EAAA,IAAoB,EACrBD,GAAA,cAACE,EAAA,IAAkB,CACrB,CAEJ,C1BFe,SAARC,IAAgC,CACrC,GAAM,CAAE,SAAAC,CAAS,EAAIC,EAAmB,EAExC,OAAAC,GAAaF,CAAQ,EAGnBG,GAAA,cAAAA,GAAA,cACEA,GAAA,cAACC,GAAA,IAAe,EAChBD,GAAA,cAACE,GAAA,IAAwB,CAC3B,CAEJ","names":["React","useEffect","useCallback","useMemo","React","createContext","useContext","useState","StegaError","createErrorInfo","type","context","error","additionalData","handleStegaError","errorInfo","handleDOMError","handleContextError","contextName","SegmentContext","createContext","SegmentProvider","children","initialSegments","activeSegment","segmentList","emptySegment","selectedSegment","setSelectedSegment","useState","segmentData","value","React","useSegmentContext","context","useContext","handleContextError","React","createContext","useContext","useState","VariantContext","createContext","VariantProvider","children","activeVariant","emptyVariant","selectedVariant","setSelectedVariant","useState","value","React","useVariantContext","context","useContext","handleContextError","React","createContext","useContext","useState","useEffect","EditModeContext","createContext","EditModeProvider","children","editMode","setEditMode","useState","isIframe","setIsIframe","useEffect","handleEscapeKey","event","value","React","useEditModeContext","context","useContext","handleContextError","React","Component","StegaErrorBoundary","props","error","errorInfo","_a","DebugLogger","_DebugLogger","options","__spreadValues","message","args","prefix","scopeName","__spreadProps","globalDebugLogger","initDebugLogger","enabled","getDebugLogger","createScopedLogger","scopeName","getDebugLogger","PreprToolbarProvider","children","props","options","activeSegment","activeVariant","data","useEffect","_a","debugEnabled","initDebugLogger","React","StegaErrorBoundary","SegmentProvider","VariantProvider","EditModeProvider","usePreprToolbar","segmentContext","useSegmentContext","variantContext","useVariantContext","editModeContext","useEditModeContext","resetPersonalization","useCallback","resetAll","useMemo","React","useEffect","useRef","useCallback","useMemo","DOMService","tag","className","element","error","handleDOMError","styles","property","value","rect","x1","y1","x2","y2","pointX","pointY","elements","closestElement","minDistance","distance","event","handler","options","throttle","func","delay","timeoutId","lastExecTime","throttledFunc","args","currentTime","timeSinceLastExec","createElementCache","query","ttl","cache","lastCacheTime","now","useRef","useCallback","vercelStegaDecode","decode","str","debug","createScopedLogger","decoded","e","regex","match","decodedMatch","handleStegaError","useStegaOverlay","overlayRef","useRef","tooltipRef","hideTimeoutRef","currentElementRef","createOverlay","useCallback","overlay","DOMService","tooltip","showOverlay","element","rect","href","origin","isCompact","hideOverlay","cleanup","useRef","useCallback","useStegaProximity","debug","createScopedLogger","highlightedElementsRef","useRef","getEncodedElements","createElementCache","updateElementGradients","useCallback","cursorX","cursorY","encodedElements","newHighlightedElements","highlightedCount","element","rect","distanceLeft","distanceRight","distanceTop","distanceBottom","distance","el","relativeX","relativeY","baseGradientSize","distanceScale","gradientSize","clearAllHighlights","highlightedElements","clearedCount","useRef","useCallback","useStegaElements","debug","createScopedLogger","elementsRef","useRef","observerRef","getElements","useCallback","scanNode","node","decode","_a","_b","decoded","target","i","scanDocument","walker","textNode","encodedCount","setupMutationObserver","pendingMutations","debounceTimeout","processMutations","allAddedNodes","mutation","mutations","cleanup","encodedElements","element","useStegaScan","editMode","debug","createScopedLogger","isInitializedRef","useRef","currentElementRef","hideTimeoutRef","createOverlay","showOverlay","hideOverlay","cleanupOverlay","decode","useStegaOverlay","updateElementGradients","clearAllHighlights","useStegaProximity","getElements","scanDocument","setupMutationObserver","cleanupElements","useStegaElements","throttledMouseMove","useMemo","throttle","e","mouseEvent","target","encodedElement","handleTooltipMouseEnter","useCallback","handleTooltipMouseLeave","useEffect","DOMService","tooltip","elements","React","useEffect","useState","useSearchParams","React","useEffect","useState","createPortal","clsx","twMerge","cn","inputs","twMerge","clsx","useEffect","useRef","useModal","isVisible","onClose","contentRef","triggerRef","handleEscapeKey","event","handleClickOutside","React","React","React","XMark","props","React","__spreadValues","usePathname","useRouter","StatusIndicatorPill","_a","_b","selectedSegment","selectedVariant","emptySegment","emptyVariant","isIframe","resetPersonalization","usePreprToolbar","show","router","pathname","handleReset","params","React","XMark","React","CloseEditModePill","editMode","setEditMode","isIframe","usePreprToolbar","React","XMark","React","usePathname","useRouter","React","Rotate","ResetButton","router","useRouter","resetAll","selectedVariant","selectedSegment","setEditMode","editMode","usePreprToolbar","pathname","usePathname","enabled","handleClick","params","classes","cn","React","Rotate","React","Icon","props","React","__spreadValues","icon_default","React","Logo","props","React","__spreadProps","__spreadValues","logo_default","React","Script","PreprTrackingPixel","accessToken","React","usePathname","useRouter","Listbox","ListboxButton","ListboxOption","ListboxOptions","React","SortDown","props","React","__spreadValues","SegmentSelector","segments","setSelectedSegment","selectedSegment","useSegmentContext","pathname","usePathname","router","useRouter","updateSelectedSegment","value","params","segment","React","Listbox","ListboxButton","SortDown","ListboxOptions","ListboxOption","cn","React","usePathname","useRouter","React","Radio","RadioGroup","RadioSelector","value","onChange","options","React","RadioGroup","option","Radio","cn","VariantSelector","selectedVariant","setSelectedVariant","emptyVariant","useVariantContext","pathname","usePathname","router","useRouter","React","RadioSelector","value","params","React","EditModeSelector","editMode","setEditMode","useEditModeContext","updateEditMode","value","React","RadioSelector","ToolbarContent","onClose","contentRef","React","logo_default","SegmentSelector","VariantSelector","EditModeSelector","ResetButton","React","ToolbarButton","onClick","className","React","cn","icon_default","Toolbar","children","isMounted","setIsMounted","useState","isBarVisible","setIsBarVisible","React","editMode","useEditModeContext","contentRef","triggerRef","useModal","useEffect","popupBoxRef","popupTop","setPopupTop","updatePopupPosition","popupHeight","windowHeight","triggerRect","top","handleClick","previewBarContent","cn","ToolbarButton","ToolbarContent","createPortal","ToolbarWrapper","searchParams","useSearchParams","isIframe","setIsIframe","useState","handleKeyDown","event","key","isSaveShortcut","isPrintShortcut","isAddressBarShortcut","useEffect","previewBarMessage","React","Toolbar","React","ToolbarIndicatorWrapper","React","StatusIndicatorPill","CloseEditModePill","PreprToolbar","editMode","useEditModeContext","useStegaScan","React","ToolbarWrapper","ToolbarIndicatorWrapper"]}
@@ -0,0 +1,7 @@
1
+ 'use strict';var headers=require('next/headers'),functions=require('@vercel/functions'),server=require('next/server');var a=(r,s,t)=>new Promise((e,n)=>{var l=i=>{try{c(t.next(i));}catch(d){n(d);}},u=i=>{try{c(t.throw(i));}catch(d){n(d);}},c=i=>i.done?e(i.value):Promise.resolve(i.value).then(l,u);c((t=t.apply(r,s)).next());});var v={version:"2.0.0-alpha.11"};function y(r,s,t){var x,f,h,w;let e,n;s&&"headers"in s?(e=s,n=t):(e=server.NextResponse.next(),n=s),process.env.PREPR_GRAPHQL_URL||console.error("PREPR_GRAPHQL_URL is not set"),r.nextUrl.searchParams.forEach((o,m)=>{switch(m){case "utm_source":e.headers.set("Prepr-Context-utm_source",o);break;case "utm_medium":e.headers.set("Prepr-Context-utm_medium",o);break;case "utm_term":e.headers.set("Prepr-Context-utm_term",o);break;case "utm_content":e.headers.set("Prepr-Context-utm_content",o);break;case "utm_campaign":e.headers.set("Prepr-Context-utm_campaign",o);break}});let l=r.headers.get("referer");l&&e.headers.set("Prepr-Context-initial_referral",l);let u=functions.ipAddress(r);u&&e.headers.set("Prepr-Visitor-IP",u);let c=(x=r.cookies.get("hubspotutk"))==null?void 0:x.value;c&&e.headers.set("Prepr-Hubspot-Id",c);let i=(f=r.cookies.get("__prepr_uid"))==null?void 0:f.value;if(i||(i=crypto.randomUUID(),e.cookies.set("__prepr_uid",i,{maxAge:1*365*24*60}),e.headers.set("Prepr-Customer-Id-Created","true")),e.headers.set("Prepr-Customer-Id",i),!(n!=null&&n.preview)||process.env.PREPR_ENV!=="preview")return e;e.headers.set("Prepr-Preview-Bar","true");let d=(h=r.cookies.get("Prepr-Segments"))==null?void 0:h.value;d&&e.headers.set("Prepr-Segments",d);let P=(w=r.cookies.get("Prepr-ABtesting"))==null?void 0:w.value;return P&&e.headers.set("Prepr-ABtesting",P),r.nextUrl.searchParams.forEach((o,m)=>{m==="prepr_preview_ab"&&(e.headers.set("Prepr-ABtesting",o),e.cookies.set("Prepr-ABtesting",o)),m==="prepr_preview_segment"&&(e.headers.set("Prepr-Segments",o),e.cookies.set("Prepr-Segments",o));}),e}var p=class extends Error{constructor(t,e,n,l){super(t);this.code=e;this.context=n;this.originalError=l;this.name="PreprError";}};function g(r){return a(this,null,function*(){return (yield headers.headers()).get(r)})}function B(){return a(this,null,function*(){return g("prepr-customer-id")})}function b(){return a(this,null,function*(){return g("Prepr-Segments")})}function j(){return a(this,null,function*(){return g("Prepr-ABtesting")})}function D(){return a(this,null,function*(){let r={};return (yield headers.headers()).forEach((t,e)=>{(e.startsWith("prepr")||e.startsWith("Prepr"))&&(r[e]=t);}),r})}function S(r){return r?r.startsWith("https://")?{valid:true}:{valid:false,error:"Token must be a valid HTTPS URL"}:{valid:false,error:"Token is required"}}function N(){return process.env.PREPR_ENV==="preview"}function F(r){if(!r)return null;try{let s=new URL(r);if(s.hostname!=="graphql.prepr.io")return null;let t=s.pathname.split("/"),e=t[t.length-1];return e&&e.length>0?e:null}catch(s){return null}}function T(r){return a(this,null,function*(){let s=S(r);if(!s.valid)throw new p(s.error,"INVALID_TOKEN","getPreprEnvironmentSegments");try{let t=yield fetch(r,{headers:{"User-Agent":`Prepr-Preview-Bar/${A()}`,"Content-Type":"application/json"},method:"POST",body:JSON.stringify({query:`{
2
+ _Segments {
3
+ _id
4
+ name
5
+ }
6
+ }`})});if(!t.ok)throw new p(`HTTP ${t.status}: ${t.statusText}`,"HTTP_ERROR","getPreprEnvironmentSegments");let e=yield t.json();if(!e||!e.data||!e.data._Segments)throw new p("Invalid response format from Prepr API","INVALID_RESPONSE","getPreprEnvironmentSegments");return e.data._Segments}catch(t){throw t instanceof p?t:new p("Failed to fetch segments from Prepr API","FETCH_ERROR","getPreprEnvironmentSegments",t instanceof Error?t:new Error(String(t)))}})}function W(r){return a(this,null,function*(){let s=[],t=null,e=null;if(N())try{s=yield T(r),t=yield b(),e=yield j();}catch(n){console.error("Failed to fetch toolbar props:",n),s=[];}return {activeSegment:t,activeVariant:e,data:s}})}function A(){return v.version}exports.PreprError=p;exports.createPreprMiddleware=y;exports.extractAccessToken=F;exports.getActiveSegment=b;exports.getActiveVariant=j;exports.getPreprEnvironmentSegments=T;exports.getPreprHeaders=D;exports.getPreprUUID=B;exports.getToolbarProps=W;exports.isPreviewMode=N;exports.validatePreprToken=S;//# sourceMappingURL=index.cjs.map
7
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/server/index.ts","../../package.json","../../src/middleware/index.ts"],"names":["package_default","createPreprMiddleware","request","responseOrOptions","options","_a","_b","_c","_d","response","finalOptions","NextResponse","value","key","referrer","ip","ipAddress","hutkCookie","cookie","segmentCookie","abCookie","PreprError","message","code","context","originalError","getPreprHeader","name","__async","headers","getPreprUUID","getActiveSegment","getActiveVariant","getPreprHeaders","preprHeaders","validatePreprToken","token","isPreviewMode","extractAccessToken","graphqlUrl","url","pathParts","e","getPreprEnvironmentSegments","validation","getPackageVersion","json","error","getToolbarProps","data","activeSegment","activeVariant"],"mappings":"sHAAA,IAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,IAAA,OAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,IAAA,CAAA,CAAA,CAAA,EAAA,CAAA,GAAA,CAAA,CAAA,CAAA,CAAA,CAAA,IAAA,CAAA,CAAA,CAAA,EAAA,CAAA,MAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAA,CAAA,GAAA,CAAA,CAAA,CAAA,CAA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AA,CAAO,CACd,MAAIA,CAAAA,YAAiB1B,CAAAA,CACb0B,CAAAA,CAEF,IAAI1B,CAAAA,CACR,yCAAA,CACA,aAAA,CACA,6BAAA,CACA0B,CAAAA,YAAiB,KAAA,CAAQA,EAAQ,IAAI,KAAA,CAAM,MAAA,CAAOA,CAAK,CAAC,CAC1D,CACF,CACF,CAAA,CAAA,CAOA,SAAsBC,CAAAA,CACpBZ,CAAAA,CAC4B,CAAA,OAAAR,CAAAA,CAAA,IAAA,CAAA,IAAA,CAAA,WAAA,CAC5B,IAAIqB,EAAuB,EAAC,CACxBC,CAAAA,CAA+B,IAAA,CAC/BC,CAAAA,CAA+B,IAAA,CAGnC,GAAId,CAAAA,EAAc,CAChB,GAAI,CACFY,CAAAA,CAAO,MAAMN,CAAAA,CAA4BP,CAAK,CAAA,CAC9Cc,EAAgB,MAAMnB,CAAAA,EAAiB,CACvCoB,CAAAA,CAAgB,MAAMnB,CAAAA,GACxB,CAAA,MAASe,CAAAA,CAAO,CAEd,OAAA,CAAQ,KAAA,CAAM,gCAAA,CAAkCA,CAAK,CAAA,CAErDE,CAAAA,CAAO,GACT,CAGF,OAAO,CACL,aAAA,CAAAC,CAAAA,CACA,aAAA,CAAAC,CAAAA,CACA,IAAA,CAAAF,CACF,CACF,CAAA,CAAA,CAEA,SAASJ,CAAAA,EAAoB,CAC3B,OAAO7C,EAAM,OACf","file":"index.cjs","sourcesContent":["import { headers } from 'next/headers';\nimport {\n PreprToolbarProps,\n PreprSegment,\n PreprHeaderName,\n PreprErrorCode,\n} from '../types';\nimport pjson from '../../package.json';\nimport createPreprMiddleware from '../middleware';\n\n/**\n * Custom error class for Prepr-related errors\n */\nexport class PreprError extends Error {\n constructor(\n message: string,\n public readonly code: PreprErrorCode,\n public readonly context?: string,\n public readonly originalError?: Error\n ) {\n super(message);\n this.name = 'PreprError';\n }\n}\n\n/**\n * Internal helper to get a specific Prepr header value\n * @param name - The header name to retrieve\n * @returns The header value or null if not found\n */\nasync function getPreprHeader(name: PreprHeaderName): Promise<string | null> {\n const headersList = await headers();\n return headersList.get(name);\n}\n\n/**\n * Returns the Prepr Customer ID from the headers\n * @returns Prepr Customer ID\n */\nexport async function getPreprUUID(): Promise<string | null> {\n return getPreprHeader('prepr-customer-id');\n}\n\n/**\n * Returns the active segment from the headers\n * @returns Active segment\n */\nexport async function getActiveSegment(): Promise<string | null> {\n return getPreprHeader('Prepr-Segments');\n}\n\n/**\n * Returns the active variant from the headers\n * @returns Active variant\n */\nexport async function getActiveVariant(): Promise<string | null> {\n return getPreprHeader('Prepr-ABtesting');\n}\n\n/**\n * Helper function to retrieve all Prepr headers\n * @returns Object with Prepr headers\n */\nexport async function getPreprHeaders(): Promise<Record<string, string>> {\n const preprHeaders: Record<string, string> = {};\n const headersList = await headers();\n\n headersList.forEach((value, key) => {\n if (key.startsWith('prepr') || key.startsWith('Prepr')) {\n preprHeaders[key] = value;\n }\n });\n\n return preprHeaders;\n}\n\n/**\n * Validates a Prepr GraphQL token\n * @param token - The token to validate\n * @returns Validation result with error details if invalid\n */\nexport function validatePreprToken(token: string): {\n valid: boolean;\n error?: string;\n} {\n if (!token) {\n return { valid: false, error: 'Token is required' };\n }\n if (!token.startsWith('https://')) {\n return { valid: false, error: 'Token must be a valid HTTPS URL' };\n }\n return { valid: true };\n}\n\n/**\n * Checks if the current environment is in preview mode\n * @returns True if in preview mode\n */\nexport function isPreviewMode(): boolean {\n return process.env.PREPR_ENV === 'preview';\n}\n\n/**\n * Extracts the access token from a Prepr GraphQL URL\n * @param graphqlUrl - The full Prepr GraphQL URL\n * @returns The access token or null if invalid\n * @example\n * ```typescript\n * const token = extractAccessToken('https://graphql.prepr.io/abc123')\n * // Returns: 'abc123'\n * ```\n */\nexport function extractAccessToken(graphqlUrl: string): string | null {\n if (!graphqlUrl) return null;\n\n try {\n const url = new URL(graphqlUrl);\n if (url.hostname !== 'graphql.prepr.io') return null;\n\n const pathParts = url.pathname.split('/');\n const token = pathParts[pathParts.length - 1];\n\n return token && token.length > 0 ? token : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Fetches the segments from the Prepr API\n * @param token Prepr GraphQL URL with scope 'segments'\n * @returns Array of PreprSegment\n * @throws PreprError if the request fails\n */\nexport async function getPreprEnvironmentSegments(\n token: string\n): Promise<PreprSegment[]> {\n const validation = validatePreprToken(token);\n if (!validation.valid) {\n throw new PreprError(\n validation.error!,\n 'INVALID_TOKEN',\n 'getPreprEnvironmentSegments'\n );\n }\n\n try {\n const response = await fetch(token, {\n headers: {\n 'User-Agent': `Prepr-Preview-Bar/${getPackageVersion()}`,\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: JSON.stringify({\n query: `{\n _Segments {\n _id\n name\n }\n }`,\n }),\n });\n\n if (!response.ok) {\n throw new PreprError(\n `HTTP ${response.status}: ${response.statusText}`,\n 'HTTP_ERROR',\n 'getPreprEnvironmentSegments'\n );\n }\n\n const json = await response.json();\n\n if (!json || !json.data || !json.data._Segments) {\n throw new PreprError(\n 'Invalid response format from Prepr API',\n 'INVALID_RESPONSE',\n 'getPreprEnvironmentSegments'\n );\n }\n\n return json.data._Segments as PreprSegment[];\n } catch (error) {\n if (error instanceof PreprError) {\n throw error;\n }\n throw new PreprError(\n 'Failed to fetch segments from Prepr API',\n 'FETCH_ERROR',\n 'getPreprEnvironmentSegments',\n error instanceof Error ? error : new Error(String(error))\n );\n }\n}\n\n/**\n * Fetches all the necessary previewbar props\n * @param token Prepr GraphQL URL with scope 'segments'\n * @returns Object with activeSegment, activeVariant and data\n */\nexport async function getToolbarProps(\n token: string\n): Promise<PreprToolbarProps> {\n let data: PreprSegment[] = [];\n let activeSegment: string | null = null;\n let activeVariant: string | null = null;\n\n // Prevent unnecessary function calling in production\n if (isPreviewMode()) {\n try {\n data = await getPreprEnvironmentSegments(token);\n activeSegment = await getActiveSegment();\n activeVariant = await getActiveVariant();\n } catch (error) {\n // In preview mode, we should still return props even if API fails\n console.error('Failed to fetch toolbar props:', error);\n // Return empty data to prevent toolbar from crashing\n data = [];\n }\n }\n\n return {\n activeSegment,\n activeVariant,\n data,\n };\n}\n\nfunction getPackageVersion() {\n return pjson.version;\n}\n\nexport { createPreprMiddleware };\n","{\n \"name\": \"@preprio/prepr-nextjs\",\n \"version\": \"2.0.0-alpha.11\",\n \"description\": \"Next.js package for Prepr CMS preview functionality with advanced debugging and visual editing capabilities\",\n \"main\": \"dist/react/index.cjs\",\n \"types\": \"./dist/react/index.d.ts\",\n \"module\": \"./dist/react/index.js\",\n \"type\": \"module\",\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"dev:css\": \"postcss ./src/globals.css -o ./src/output.css --watch\",\n \"build:css\": \"NODE_ENV=production postcss ./src/globals.css -o ./dist/index.css\",\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\",\n \"clean\": \"rm -rf dist\",\n \"format\": \"prettier --write \\\"src/**/*.{ts,tsx,js,jsx,json,md}\\\"\",\n \"format:check\": \"prettier --check \\\"src/**/*.{ts,tsx,js,jsx,json,md}\\\"\",\n \"release\": \"node scripts/release.js\",\n \"check\": \"npm run type-check && npm run lint:check && npm run format:check\",\n \"type-check\": \"tsc --noEmit\",\n \"lint\": \"eslint src --ext .ts,.tsx --fix\",\n \"lint:check\": \"eslint src --ext .ts,.tsx\",\n \"prepublishOnly\": \"npm run check && npm run build\"\n },\n \"exports\": {\n \"./middleware\": {\n \"import\": \"./dist/middleware/index.js\",\n \"types\": \"./dist/middleware/index.d.ts\",\n \"require\": \"./dist/middleware/index.cjs\"\n },\n \"./server\": {\n \"import\": \"./dist/server/index.js\",\n \"types\": \"./dist/server/index.d.ts\",\n \"require\": \"./dist/server/index.cjs\"\n },\n \"./react\": {\n \"import\": \"./dist/react/index.js\",\n \"types\": \"./dist/react/index.d.ts\",\n \"require\": \"./dist/react/index.cjs\"\n },\n \"./contexts\": {\n \"import\": \"./dist/contexts/index.js\",\n \"types\": \"./dist/contexts/index.d.ts\",\n \"require\": \"./dist/contexts/index.cjs\"\n },\n \"./utils\": {\n \"import\": \"./dist/utils/index.js\",\n \"types\": \"./dist/utils/index.d.ts\",\n \"require\": \"./dist/utils/index.cjs\"\n },\n \"./types\": {\n \"import\": \"./dist/types/index.js\",\n \"types\": \"./dist/types/index.d.ts\",\n \"require\": \"./dist/types/index.cjs\"\n },\n \"./index.css\": {\n \"import\": \"./dist/index.css\",\n \"require\": \"./dist/index.css\"\n }\n },\n \"files\": [\n \"dist\",\n \"package.json\"\n ],\n \"keywords\": [\n \"prepr\",\n \"cms\",\n \"nextjs\",\n \"preview\",\n \"visual-editing\",\n \"headless-cms\",\n \"react\",\n \"typescript\",\n \"debug\",\n \"stega\"\n ],\n \"author\": \"Preprio\",\n \"license\": \"MIT\",\n \"packageManager\": \"pnpm@10.5.2\",\n \"devDependencies\": {\n \"@eslint/js\": \"^9.25.1\",\n \"@types/node\": \"^20.11.5\",\n \"@types/react\": \"19.1.0\",\n \"@types/react-dom\": \"19.1.2\",\n \"@typescript-eslint/eslint-plugin\": \"^8.31.1\",\n \"@typescript-eslint/parser\": \"^8.31.1\",\n \"autoprefixer\": \"^10.4.21\",\n \"cssnano\": \"^7.0.7\",\n \"eslint\": \"^9.25.1\",\n \"eslint-config-prettier\": \"^10.1.2\",\n \"eslint-plugin-prettier\": \"^5.2.6\",\n \"eslint-plugin-react\": \"^7.37.2\",\n \"eslint-plugin-react-hooks\": \"^5.0.0\",\n \"next\": \"15.3.1\",\n \"postcss\": \"^8\",\n \"prettier\": \"^3.5.3\",\n \"prettier-plugin-tailwindcss\": \"^0.5.12\",\n \"react\": \"^19.1.0\",\n \"react-dom\": \"^19.1.0\",\n \"tailwindcss\": \"^3.4.17\",\n \"tsup\": \"^8.5.0\",\n \"typescript\": \"^5.8.3\"\n },\n \"peerDependencies\": {\n \"next\": \"^15.0.0 || ^14.0.0 || ^13.0.0\",\n \"react\": \"^19.0.0 || ^18.0.0 || ^17.0.0 \",\n \"react-dom\": \"^19.0.0 || ^18.0.0 || ^17.0.0\"\n },\n \"dependencies\": {\n \"@headlessui/react\": \"^2.2.0\",\n \"@vercel/functions\": \"^2.0.0\",\n \"@vercel/stega\": \"^0.1.2\",\n \"clsx\": \"^2.1.1\",\n \"postcss-cli\": \"^11.0.1\",\n \"tailwind-merge\": \"^3.0.1\"\n }\n}\n","import { ipAddress } from '@vercel/functions';\nimport { NextRequest, NextResponse } from 'next/server';\n\nexport interface PreprMiddlewareOptions {\n preview?: boolean;\n}\n\n/**\n * Middleware to set Prepr headers for personalization.\n *\n * @overload\n * @param request - NextRequest object\n * @param options - Options object\n * @returns NextResponse with Prepr headers set\n */\nexport default function createPreprMiddleware(\n request: NextRequest,\n options?: PreprMiddlewareOptions\n): NextResponse;\n\n/**\n * Middleware to set Prepr headers for personalization.\n *\n * @overload\n * @param request - NextRequest object\n * @param response - NextResponse object to chain with\n * @param options - Options object\n * @returns NextResponse with Prepr headers set\n */\nexport default function createPreprMiddleware(\n request: NextRequest,\n response: NextResponse,\n options?: PreprMiddlewareOptions\n): NextResponse;\n\n/**\n * Implementation of createPreprMiddleware with function overloads\n */\nexport default function createPreprMiddleware(\n request: NextRequest,\n responseOrOptions?: NextResponse | PreprMiddlewareOptions,\n options?: PreprMiddlewareOptions\n): NextResponse {\n let response: NextResponse;\n let finalOptions: PreprMiddlewareOptions | undefined;\n\n // Handle overloads\n if (responseOrOptions && 'headers' in responseOrOptions) {\n // Second parameter is NextResponse\n response = responseOrOptions;\n finalOptions = options;\n } else {\n // Second parameter is options or undefined\n response = NextResponse.next();\n finalOptions = responseOrOptions as PreprMiddlewareOptions | undefined;\n }\n\n if (!process.env.PREPR_GRAPHQL_URL) {\n console.error('PREPR_GRAPHQL_URL is not set');\n }\n\n // Map over search params and set headers\n request.nextUrl.searchParams.forEach((value, key) => {\n switch (key) {\n case 'utm_source':\n response.headers.set('Prepr-Context-utm_source', value);\n break;\n case 'utm_medium':\n response.headers.set('Prepr-Context-utm_medium', value);\n break;\n case 'utm_term':\n response.headers.set('Prepr-Context-utm_term', value);\n break;\n case 'utm_content':\n response.headers.set('Prepr-Context-utm_content', value);\n break;\n case 'utm_campaign':\n response.headers.set('Prepr-Context-utm_campaign', value);\n break;\n }\n });\n\n // Set initial referral header\n const referrer = request.headers.get('referer');\n if (referrer) {\n response.headers.set('Prepr-Context-initial_referral', referrer);\n }\n\n // Set IP address header\n const ip = ipAddress(request);\n if (ip) {\n response.headers.set('Prepr-Visitor-IP', ip);\n }\n\n // Set HubSpot cookie header\n const hutkCookie = request.cookies.get('hubspotutk')?.value;\n if (hutkCookie) {\n response.headers.set('Prepr-Hubspot-Id', hutkCookie);\n }\n\n // Check for existing Prepr UID cookie or create a new one\n let cookie = request.cookies.get('__prepr_uid')?.value;\n if (!cookie) {\n cookie = crypto.randomUUID();\n response.cookies.set('__prepr_uid', cookie, {\n maxAge: 1 * 365 * 24 * 60, // Set for one year\n });\n response.headers.set('Prepr-Customer-Id-Created', 'true');\n }\n\n // Set the Prepr Customer ID header\n response.headers.set('Prepr-Customer-Id', cookie);\n\n // If preview mode is not enabled, return the response\n if (!finalOptions?.preview || process.env.PREPR_ENV !== 'preview') {\n return response;\n }\n\n // If preview mode is enabled, set additional headers\n response.headers.set('Prepr-Preview-Bar', 'true');\n\n // Set Prepr Preview Segment and AB test cookies\n const segmentCookie = request.cookies.get('Prepr-Segments')?.value;\n if (segmentCookie) {\n response.headers.set('Prepr-Segments', segmentCookie);\n }\n\n const abCookie = request.cookies.get('Prepr-ABtesting')?.value;\n if (abCookie) {\n response.headers.set('Prepr-ABtesting', abCookie);\n }\n\n // Set Prepr Preview Segment and AB test headers from query params\n request.nextUrl.searchParams.forEach((value, key) => {\n if (key === 'prepr_preview_ab') {\n response.headers.set('Prepr-ABtesting', value);\n response.cookies.set('Prepr-ABtesting', value);\n }\n\n if (key === 'prepr_preview_segment') {\n response.headers.set('Prepr-Segments', value);\n response.cookies.set('Prepr-Segments', value);\n }\n });\n\n return response;\n}\n"]}
@@ -0,0 +1,73 @@
1
+ import { PreprErrorCode, PreprSegment, PreprToolbarProps } from '../types/index.cjs';
2
+ export { default as createPreprMiddleware } from '../middleware/index.cjs';
3
+ import 'next/server';
4
+
5
+ /**
6
+ * Custom error class for Prepr-related errors
7
+ */
8
+ declare class PreprError extends Error {
9
+ readonly code: PreprErrorCode;
10
+ readonly context?: string | undefined;
11
+ readonly originalError?: Error | undefined;
12
+ constructor(message: string, code: PreprErrorCode, context?: string | undefined, originalError?: Error | undefined);
13
+ }
14
+ /**
15
+ * Returns the Prepr Customer ID from the headers
16
+ * @returns Prepr Customer ID
17
+ */
18
+ declare function getPreprUUID(): Promise<string | null>;
19
+ /**
20
+ * Returns the active segment from the headers
21
+ * @returns Active segment
22
+ */
23
+ declare function getActiveSegment(): Promise<string | null>;
24
+ /**
25
+ * Returns the active variant from the headers
26
+ * @returns Active variant
27
+ */
28
+ declare function getActiveVariant(): Promise<string | null>;
29
+ /**
30
+ * Helper function to retrieve all Prepr headers
31
+ * @returns Object with Prepr headers
32
+ */
33
+ declare function getPreprHeaders(): Promise<Record<string, string>>;
34
+ /**
35
+ * Validates a Prepr GraphQL token
36
+ * @param token - The token to validate
37
+ * @returns Validation result with error details if invalid
38
+ */
39
+ declare function validatePreprToken(token: string): {
40
+ valid: boolean;
41
+ error?: string;
42
+ };
43
+ /**
44
+ * Checks if the current environment is in preview mode
45
+ * @returns True if in preview mode
46
+ */
47
+ declare function isPreviewMode(): boolean;
48
+ /**
49
+ * Extracts the access token from a Prepr GraphQL URL
50
+ * @param graphqlUrl - The full Prepr GraphQL URL
51
+ * @returns The access token or null if invalid
52
+ * @example
53
+ * ```typescript
54
+ * const token = extractAccessToken('https://graphql.prepr.io/abc123')
55
+ * // Returns: 'abc123'
56
+ * ```
57
+ */
58
+ declare function extractAccessToken(graphqlUrl: string): string | null;
59
+ /**
60
+ * Fetches the segments from the Prepr API
61
+ * @param token Prepr GraphQL URL with scope 'segments'
62
+ * @returns Array of PreprSegment
63
+ * @throws PreprError if the request fails
64
+ */
65
+ declare function getPreprEnvironmentSegments(token: string): Promise<PreprSegment[]>;
66
+ /**
67
+ * Fetches all the necessary previewbar props
68
+ * @param token Prepr GraphQL URL with scope 'segments'
69
+ * @returns Object with activeSegment, activeVariant and data
70
+ */
71
+ declare function getToolbarProps(token: string): Promise<PreprToolbarProps>;
72
+
73
+ export { PreprError, extractAccessToken, getActiveSegment, getActiveVariant, getPreprEnvironmentSegments, getPreprHeaders, getPreprUUID, getToolbarProps, isPreviewMode, validatePreprToken };
@@ -0,0 +1,73 @@
1
+ import { PreprErrorCode, PreprSegment, PreprToolbarProps } from '../types/index.js';
2
+ export { default as createPreprMiddleware } from '../middleware/index.js';
3
+ import 'next/server';
4
+
5
+ /**
6
+ * Custom error class for Prepr-related errors
7
+ */
8
+ declare class PreprError extends Error {
9
+ readonly code: PreprErrorCode;
10
+ readonly context?: string | undefined;
11
+ readonly originalError?: Error | undefined;
12
+ constructor(message: string, code: PreprErrorCode, context?: string | undefined, originalError?: Error | undefined);
13
+ }
14
+ /**
15
+ * Returns the Prepr Customer ID from the headers
16
+ * @returns Prepr Customer ID
17
+ */
18
+ declare function getPreprUUID(): Promise<string | null>;
19
+ /**
20
+ * Returns the active segment from the headers
21
+ * @returns Active segment
22
+ */
23
+ declare function getActiveSegment(): Promise<string | null>;
24
+ /**
25
+ * Returns the active variant from the headers
26
+ * @returns Active variant
27
+ */
28
+ declare function getActiveVariant(): Promise<string | null>;
29
+ /**
30
+ * Helper function to retrieve all Prepr headers
31
+ * @returns Object with Prepr headers
32
+ */
33
+ declare function getPreprHeaders(): Promise<Record<string, string>>;
34
+ /**
35
+ * Validates a Prepr GraphQL token
36
+ * @param token - The token to validate
37
+ * @returns Validation result with error details if invalid
38
+ */
39
+ declare function validatePreprToken(token: string): {
40
+ valid: boolean;
41
+ error?: string;
42
+ };
43
+ /**
44
+ * Checks if the current environment is in preview mode
45
+ * @returns True if in preview mode
46
+ */
47
+ declare function isPreviewMode(): boolean;
48
+ /**
49
+ * Extracts the access token from a Prepr GraphQL URL
50
+ * @param graphqlUrl - The full Prepr GraphQL URL
51
+ * @returns The access token or null if invalid
52
+ * @example
53
+ * ```typescript
54
+ * const token = extractAccessToken('https://graphql.prepr.io/abc123')
55
+ * // Returns: 'abc123'
56
+ * ```
57
+ */
58
+ declare function extractAccessToken(graphqlUrl: string): string | null;
59
+ /**
60
+ * Fetches the segments from the Prepr API
61
+ * @param token Prepr GraphQL URL with scope 'segments'
62
+ * @returns Array of PreprSegment
63
+ * @throws PreprError if the request fails
64
+ */
65
+ declare function getPreprEnvironmentSegments(token: string): Promise<PreprSegment[]>;
66
+ /**
67
+ * Fetches all the necessary previewbar props
68
+ * @param token Prepr GraphQL URL with scope 'segments'
69
+ * @returns Object with activeSegment, activeVariant and data
70
+ */
71
+ declare function getToolbarProps(token: string): Promise<PreprToolbarProps>;
72
+
73
+ export { PreprError, extractAccessToken, getActiveSegment, getActiveVariant, getPreprEnvironmentSegments, getPreprHeaders, getPreprUUID, getToolbarProps, isPreviewMode, validatePreprToken };
@@ -0,0 +1,7 @@
1
+ export{a as createPreprMiddleware}from'../chunk-LVXDK2EY.js';import {c as c$1}from'../chunk-E7ATRJ2F.js';import {headers}from'next/headers';var c={version:"2.0.0-alpha.11"};var n=class extends Error{constructor(e,t,a,h){super(e);this.code=t;this.context=a;this.originalError=h;this.name="PreprError";}};function o(r){return c$1(this,null,function*(){return (yield headers()).get(r)})}function E(){return c$1(this,null,function*(){return o("prepr-customer-id")})}function u(){return c$1(this,null,function*(){return o("Prepr-Segments")})}function m(){return c$1(this,null,function*(){return o("Prepr-ABtesting")})}function S(){return c$1(this,null,function*(){let r={};return (yield headers()).forEach((e,t)=>{(t.startsWith("prepr")||t.startsWith("Prepr"))&&(r[t]=e);}),r})}function g(r){return r?r.startsWith("https://")?{valid:true}:{valid:false,error:"Token must be a valid HTTPS URL"}:{valid:false,error:"Token is required"}}function x(){return process.env.PREPR_ENV==="preview"}function b(r){if(!r)return null;try{let s=new URL(r);if(s.hostname!=="graphql.prepr.io")return null;let e=s.pathname.split("/"),t=e[e.length-1];return t&&t.length>0?t:null}catch(s){return null}}function P(r){return c$1(this,null,function*(){let s=g(r);if(!s.valid)throw new n(s.error,"INVALID_TOKEN","getPreprEnvironmentSegments");try{let e=yield fetch(r,{headers:{"User-Agent":`Prepr-Preview-Bar/${f()}`,"Content-Type":"application/json"},method:"POST",body:JSON.stringify({query:`{
2
+ _Segments {
3
+ _id
4
+ name
5
+ }
6
+ }`})});if(!e.ok)throw new n(`HTTP ${e.status}: ${e.statusText}`,"HTTP_ERROR","getPreprEnvironmentSegments");let t=yield e.json();if(!t||!t.data||!t.data._Segments)throw new n("Invalid response format from Prepr API","INVALID_RESPONSE","getPreprEnvironmentSegments");return t.data._Segments}catch(e){throw e instanceof n?e:new n("Failed to fetch segments from Prepr API","FETCH_ERROR","getPreprEnvironmentSegments",e instanceof Error?e:new Error(String(e)))}})}function T(r){return c$1(this,null,function*(){let s=[],e=null,t=null;if(x())try{s=yield P(r),e=yield u(),t=yield m();}catch(a){console.error("Failed to fetch toolbar props:",a),s=[];}return {activeSegment:e,activeVariant:t,data:s}})}function f(){return c.version}export{n as PreprError,b as extractAccessToken,u as getActiveSegment,m as getActiveVariant,P as getPreprEnvironmentSegments,S as getPreprHeaders,E as getPreprUUID,T as getToolbarProps,x as isPreviewMode,g as validatePreprToken};//# sourceMappingURL=index.js.map
7
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../package.json","../../src/server/index.ts"],"names":["package_default","PreprError","message","code","context","originalError","getPreprHeader","name","__async","headers","getPreprUUID","getActiveSegment","getActiveVariant","getPreprHeaders","preprHeaders","value","key","validatePreprToken","token","isPreviewMode","extractAccessToken","graphqlUrl","url","pathParts","e","getPreprEnvironmentSegments","validation","response","getPackageVersion","json","error","getToolbarProps","data","activeSegment","activeVariant"],"mappings":"4IAAA,IAAAA,CAAAA,CAAA,CAEE,OAAA,CAAW,gBAkHb,CAAA,CCvGO,IAAMC,C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gB,MAAMtB,CAAAA,GACxB,CAAA,MAASkB,CAAAA,CAAO,CAEd,OAAA,CAAQ,KAAA,CAAM,gCAAA,CAAkCA,CAAK,CAAA,CAErDE,CAAAA,CAAO,GACT,CAGF,OAAO,CACL,aAAA,CAAAC,CAAAA,CACA,aAAA,CAAAC,CAAAA,CACA,IAAA,CAAAF,CACF,CACF,CAAA,CAAA,CAEA,SAASJ,CAAAA,EAAoB,CAC3B,OAAO5B,EAAM,OACf","file":"index.js","sourcesContent":["{\n \"name\": \"@preprio/prepr-nextjs\",\n \"version\": \"2.0.0-alpha.11\",\n \"description\": \"Next.js package for Prepr CMS preview functionality with advanced debugging and visual editing capabilities\",\n \"main\": \"dist/react/index.cjs\",\n \"types\": \"./dist/react/index.d.ts\",\n \"module\": \"./dist/react/index.js\",\n \"type\": \"module\",\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"dev:css\": \"postcss ./src/globals.css -o ./src/output.css --watch\",\n \"build:css\": \"NODE_ENV=production postcss ./src/globals.css -o ./dist/index.css\",\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\",\n \"clean\": \"rm -rf dist\",\n \"format\": \"prettier --write \\\"src/**/*.{ts,tsx,js,jsx,json,md}\\\"\",\n \"format:check\": \"prettier --check \\\"src/**/*.{ts,tsx,js,jsx,json,md}\\\"\",\n \"release\": \"node scripts/release.js\",\n \"check\": \"npm run type-check && npm run lint:check && npm run format:check\",\n \"type-check\": \"tsc --noEmit\",\n \"lint\": \"eslint src --ext .ts,.tsx --fix\",\n \"lint:check\": \"eslint src --ext .ts,.tsx\",\n \"prepublishOnly\": \"npm run check && npm run build\"\n },\n \"exports\": {\n \"./middleware\": {\n \"import\": \"./dist/middleware/index.js\",\n \"types\": \"./dist/middleware/index.d.ts\",\n \"require\": \"./dist/middleware/index.cjs\"\n },\n \"./server\": {\n \"import\": \"./dist/server/index.js\",\n \"types\": \"./dist/server/index.d.ts\",\n \"require\": \"./dist/server/index.cjs\"\n },\n \"./react\": {\n \"import\": \"./dist/react/index.js\",\n \"types\": \"./dist/react/index.d.ts\",\n \"require\": \"./dist/react/index.cjs\"\n },\n \"./contexts\": {\n \"import\": \"./dist/contexts/index.js\",\n \"types\": \"./dist/contexts/index.d.ts\",\n \"require\": \"./dist/contexts/index.cjs\"\n },\n \"./utils\": {\n \"import\": \"./dist/utils/index.js\",\n \"types\": \"./dist/utils/index.d.ts\",\n \"require\": \"./dist/utils/index.cjs\"\n },\n \"./types\": {\n \"import\": \"./dist/types/index.js\",\n \"types\": \"./dist/types/index.d.ts\",\n \"require\": \"./dist/types/index.cjs\"\n },\n \"./index.css\": {\n \"import\": \"./dist/index.css\",\n \"require\": \"./dist/index.css\"\n }\n },\n \"files\": [\n \"dist\",\n \"package.json\"\n ],\n \"keywords\": [\n \"prepr\",\n \"cms\",\n \"nextjs\",\n \"preview\",\n \"visual-editing\",\n \"headless-cms\",\n \"react\",\n \"typescript\",\n \"debug\",\n \"stega\"\n ],\n \"author\": \"Preprio\",\n \"license\": \"MIT\",\n \"packageManager\": \"pnpm@10.5.2\",\n \"devDependencies\": {\n \"@eslint/js\": \"^9.25.1\",\n \"@types/node\": \"^20.11.5\",\n \"@types/react\": \"19.1.0\",\n \"@types/react-dom\": \"19.1.2\",\n \"@typescript-eslint/eslint-plugin\": \"^8.31.1\",\n \"@typescript-eslint/parser\": \"^8.31.1\",\n \"autoprefixer\": \"^10.4.21\",\n \"cssnano\": \"^7.0.7\",\n \"eslint\": \"^9.25.1\",\n \"eslint-config-prettier\": \"^10.1.2\",\n \"eslint-plugin-prettier\": \"^5.2.6\",\n \"eslint-plugin-react\": \"^7.37.2\",\n \"eslint-plugin-react-hooks\": \"^5.0.0\",\n \"next\": \"15.3.1\",\n \"postcss\": \"^8\",\n \"prettier\": \"^3.5.3\",\n \"prettier-plugin-tailwindcss\": \"^0.5.12\",\n \"react\": \"^19.1.0\",\n \"react-dom\": \"^19.1.0\",\n \"tailwindcss\": \"^3.4.17\",\n \"tsup\": \"^8.5.0\",\n \"typescript\": \"^5.8.3\"\n },\n \"peerDependencies\": {\n \"next\": \"^15.0.0 || ^14.0.0 || ^13.0.0\",\n \"react\": \"^19.0.0 || ^18.0.0 || ^17.0.0 \",\n \"react-dom\": \"^19.0.0 || ^18.0.0 || ^17.0.0\"\n },\n \"dependencies\": {\n \"@headlessui/react\": \"^2.2.0\",\n \"@vercel/functions\": \"^2.0.0\",\n \"@vercel/stega\": \"^0.1.2\",\n \"clsx\": \"^2.1.1\",\n \"postcss-cli\": \"^11.0.1\",\n \"tailwind-merge\": \"^3.0.1\"\n }\n}\n","import { headers } from 'next/headers';\nimport {\n PreprToolbarProps,\n PreprSegment,\n PreprHeaderName,\n PreprErrorCode,\n} from '../types';\nimport pjson from '../../package.json';\nimport createPreprMiddleware from '../middleware';\n\n/**\n * Custom error class for Prepr-related errors\n */\nexport class PreprError extends Error {\n constructor(\n message: string,\n public readonly code: PreprErrorCode,\n public readonly context?: string,\n public readonly originalError?: Error\n ) {\n super(message);\n this.name = 'PreprError';\n }\n}\n\n/**\n * Internal helper to get a specific Prepr header value\n * @param name - The header name to retrieve\n * @returns The header value or null if not found\n */\nasync function getPreprHeader(name: PreprHeaderName): Promise<string | null> {\n const headersList = await headers();\n return headersList.get(name);\n}\n\n/**\n * Returns the Prepr Customer ID from the headers\n * @returns Prepr Customer ID\n */\nexport async function getPreprUUID(): Promise<string | null> {\n return getPreprHeader('prepr-customer-id');\n}\n\n/**\n * Returns the active segment from the headers\n * @returns Active segment\n */\nexport async function getActiveSegment(): Promise<string | null> {\n return getPreprHeader('Prepr-Segments');\n}\n\n/**\n * Returns the active variant from the headers\n * @returns Active variant\n */\nexport async function getActiveVariant(): Promise<string | null> {\n return getPreprHeader('Prepr-ABtesting');\n}\n\n/**\n * Helper function to retrieve all Prepr headers\n * @returns Object with Prepr headers\n */\nexport async function getPreprHeaders(): Promise<Record<string, string>> {\n const preprHeaders: Record<string, string> = {};\n const headersList = await headers();\n\n headersList.forEach((value, key) => {\n if (key.startsWith('prepr') || key.startsWith('Prepr')) {\n preprHeaders[key] = value;\n }\n });\n\n return preprHeaders;\n}\n\n/**\n * Validates a Prepr GraphQL token\n * @param token - The token to validate\n * @returns Validation result with error details if invalid\n */\nexport function validatePreprToken(token: string): {\n valid: boolean;\n error?: string;\n} {\n if (!token) {\n return { valid: false, error: 'Token is required' };\n }\n if (!token.startsWith('https://')) {\n return { valid: false, error: 'Token must be a valid HTTPS URL' };\n }\n return { valid: true };\n}\n\n/**\n * Checks if the current environment is in preview mode\n * @returns True if in preview mode\n */\nexport function isPreviewMode(): boolean {\n return process.env.PREPR_ENV === 'preview';\n}\n\n/**\n * Extracts the access token from a Prepr GraphQL URL\n * @param graphqlUrl - The full Prepr GraphQL URL\n * @returns The access token or null if invalid\n * @example\n * ```typescript\n * const token = extractAccessToken('https://graphql.prepr.io/abc123')\n * // Returns: 'abc123'\n * ```\n */\nexport function extractAccessToken(graphqlUrl: string): string | null {\n if (!graphqlUrl) return null;\n\n try {\n const url = new URL(graphqlUrl);\n if (url.hostname !== 'graphql.prepr.io') return null;\n\n const pathParts = url.pathname.split('/');\n const token = pathParts[pathParts.length - 1];\n\n return token && token.length > 0 ? token : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Fetches the segments from the Prepr API\n * @param token Prepr GraphQL URL with scope 'segments'\n * @returns Array of PreprSegment\n * @throws PreprError if the request fails\n */\nexport async function getPreprEnvironmentSegments(\n token: string\n): Promise<PreprSegment[]> {\n const validation = validatePreprToken(token);\n if (!validation.valid) {\n throw new PreprError(\n validation.error!,\n 'INVALID_TOKEN',\n 'getPreprEnvironmentSegments'\n );\n }\n\n try {\n const response = await fetch(token, {\n headers: {\n 'User-Agent': `Prepr-Preview-Bar/${getPackageVersion()}`,\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: JSON.stringify({\n query: `{\n _Segments {\n _id\n name\n }\n }`,\n }),\n });\n\n if (!response.ok) {\n throw new PreprError(\n `HTTP ${response.status}: ${response.statusText}`,\n 'HTTP_ERROR',\n 'getPreprEnvironmentSegments'\n );\n }\n\n const json = await response.json();\n\n if (!json || !json.data || !json.data._Segments) {\n throw new PreprError(\n 'Invalid response format from Prepr API',\n 'INVALID_RESPONSE',\n 'getPreprEnvironmentSegments'\n );\n }\n\n return json.data._Segments as PreprSegment[];\n } catch (error) {\n if (error instanceof PreprError) {\n throw error;\n }\n throw new PreprError(\n 'Failed to fetch segments from Prepr API',\n 'FETCH_ERROR',\n 'getPreprEnvironmentSegments',\n error instanceof Error ? error : new Error(String(error))\n );\n }\n}\n\n/**\n * Fetches all the necessary previewbar props\n * @param token Prepr GraphQL URL with scope 'segments'\n * @returns Object with activeSegment, activeVariant and data\n */\nexport async function getToolbarProps(\n token: string\n): Promise<PreprToolbarProps> {\n let data: PreprSegment[] = [];\n let activeSegment: string | null = null;\n let activeVariant: string | null = null;\n\n // Prevent unnecessary function calling in production\n if (isPreviewMode()) {\n try {\n data = await getPreprEnvironmentSegments(token);\n activeSegment = await getActiveSegment();\n activeVariant = await getActiveVariant();\n } catch (error) {\n // In preview mode, we should still return props even if API fails\n console.error('Failed to fetch toolbar props:', error);\n // Return empty data to prevent toolbar from crashing\n data = [];\n }\n }\n\n return {\n activeSegment,\n activeVariant,\n data,\n };\n}\n\nfunction getPackageVersion() {\n return pjson.version;\n}\n\nexport { createPreprMiddleware };\n"]}
@@ -0,0 +1,2 @@
1
+ 'use strict';//# sourceMappingURL=index.cjs.map
2
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"index.cjs"}
@@ -0,0 +1,34 @@
1
+ interface PreprSegment {
2
+ readonly _id: string;
3
+ readonly name: string;
4
+ }
5
+ interface PreprToolbarOptions {
6
+ readonly debug?: boolean;
7
+ }
8
+ interface PreprToolbarProps {
9
+ readonly activeSegment: string | null;
10
+ readonly activeVariant: string | null;
11
+ readonly data: readonly PreprSegment[];
12
+ }
13
+ type PreprHeaderName = 'prepr-customer-id' | 'Prepr-Segments' | 'Prepr-ABtesting';
14
+ type PreprVariant = 'A' | 'B';
15
+ type PreprEnvironment = 'preview' | 'production';
16
+ type PreprEventType = 'segment_changed' | 'variant_changed' | 'edit_mode_toggled' | 'personalization_reset' | 'getScrollPosition' | 'loaded';
17
+ interface PreprHeaders {
18
+ readonly 'prepr-customer-id'?: string;
19
+ readonly 'Prepr-Segments'?: string;
20
+ readonly 'Prepr-ABtesting'?: PreprVariant;
21
+ readonly 'Prepr-Preview-Bar'?: 'true';
22
+ readonly 'Prepr-Context-utm_source'?: string;
23
+ readonly 'Prepr-Context-utm_medium'?: string;
24
+ readonly 'Prepr-Context-utm_term'?: string;
25
+ readonly 'Prepr-Context-utm_content'?: string;
26
+ readonly 'Prepr-Context-utm_campaign'?: string;
27
+ readonly 'Prepr-Context-initial_referral'?: string;
28
+ readonly 'Prepr-Visitor-IP'?: string;
29
+ readonly 'Prepr-Hubspot-Id'?: string;
30
+ readonly 'Prepr-Customer-Id-Created'?: 'true';
31
+ }
32
+ type PreprErrorCode = 'INVALID_TOKEN' | 'MISSING_TOKEN' | 'HTTP_ERROR' | 'FETCH_ERROR' | 'INVALID_RESPONSE' | 'CONTEXT_ERROR';
33
+
34
+ export type { PreprEnvironment, PreprErrorCode, PreprEventType, PreprHeaderName, PreprHeaders, PreprSegment, PreprToolbarOptions, PreprToolbarProps, PreprVariant };