{"version":3,"file":"ScreenRenderer-DQ7DQNH1.cjs","names":["useDataSourceRegistryConfig","useShellTranslationOptional","SHAREABLE_TO_RESOURCE_TYPE"],"sources":["../../core/src/data-source-api-context.ts","../../widgets/src/contexts/RegistryContext.tsx","../../widgets/src/contexts/ScreenRendererContext.tsx","../../widgets/src/contexts/WidgetNodeContext.tsx","../../core/src/types/widget-schema.ts","../../core/src/data-sources/presets.ts","../../core/src/data-sources/source-key.ts","../../react/src/data-sources/use-widget-data.ts","../../react/src/data-sources/ErrorState.tsx","../../react/src/data-sources/DataAwareWidget.tsx","../../widgets/src/core/ScreenRenderer.tsx"],"sourcesContent":["import { createContext, use } from \"react\";\nimport type { DataSourceApi } from \"./data-source-api\";\n\nconst DataSourceApiContext = createContext<DataSourceApi | null>(null);\n\nexport const DataSourceApiProvider = DataSourceApiContext.Provider;\n\n/**\n * Access the DataSourceApi adapter.\n * Throws if no DataSourceApiProvider ancestor exists.\n */\nexport function useDataSourceApi(): DataSourceApi {\n  const api = use(DataSourceApiContext);\n  if (!api) {\n    throw new Error(\n      \"useDataSourceApi must be used within a DataSourceApiProvider\",\n    );\n  }\n  return api;\n}\n\n/**\n * Access the DataSourceApi adapter without throwing.\n * Returns null when no DataSourceApiProvider ancestor exists.\n * Use in isolated rendering contexts (Storybook, unit tests) where the\n * full provider stack may not be wired.\n */\nexport function useDataSourceApiOptional(): DataSourceApi | null {\n  return use(DataSourceApiContext);\n}\n","import React, {\n  createContext,\n  useContext,\n  type ComponentType,\n  type ReactNode,\n} from \"react\";\nimport type { WidgetSchema } from \"@fluid-app/portal-core/types\";\n\n/**\n * Base props interface for widget components.\n * All widgets receive at least these props from the ScreenRenderer.\n */\nexport interface WidgetBaseProps {\n  readonly widget: WidgetSchema;\n  readonly path?: readonly number[];\n}\n\n/**\n * Generic widget component type.\n * Widgets receive WidgetBaseProps and may have additional props.\n */\nexport type WidgetComponent<P extends WidgetBaseProps = WidgetBaseProps> =\n  ComponentType<P>;\n\n/**\n * Registry mapping widget type names to their components.\n * The keys are widget type strings (e.g., \"TextWidget\", \"ButtonWidget\").\n * Using WidgetComponent for the value type provides better type safety than `any`.\n */\nexport type WidgetRegistry = Readonly<\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Widget props vary by type\n  Record<string, WidgetComponent<any>>\n>;\n\n/**\n * Context for providing the widget registry to all components in the tree.\n * This eliminates prop drilling and makes the registry accessible anywhere.\n *\n * Default to undefined - registry must be provided by a RegistryProvider.\n */\nexport const RegistryContext: React.Context<WidgetRegistry | undefined> =\n  createContext<WidgetRegistry | undefined>(undefined);\n\nexport interface RegistryProviderProps {\n  registry?: WidgetRegistry;\n  children: ReactNode;\n}\n\n/**\n * Provider component that makes the widget registry available to all descendants.\n * A registry must be provided either via props or by nesting within another RegistryProvider.\n */\nexport function RegistryProvider({\n  registry,\n  children,\n}: RegistryProviderProps): React.JSX.Element {\n  // If no registry provided, inherit from parent provider\n  const parentRegistry = useContext(RegistryContext);\n  const contextValue = registry ?? parentRegistry;\n\n  if (!contextValue) {\n    throw new Error(\n      \"RegistryProvider requires a registry prop or must be nested within another RegistryProvider.\",\n    );\n  }\n\n  return (\n    <RegistryContext.Provider value={contextValue}>\n      {children}\n    </RegistryContext.Provider>\n  );\n}\n\n/**\n * Hook to access the widget registry from anywhere in the component tree.\n * Must be used within a RegistryProvider that has a registry prop.\n */\nexport function useRegistry(): WidgetRegistry {\n  const registry = useContext(RegistryContext);\n\n  if (!registry) {\n    throw new Error(\n      \"useRegistry must be used within a RegistryProvider with a registry prop.\",\n    );\n  }\n\n  return registry;\n}\n","import React, { createContext, useContext, type ComponentType } from \"react\";\nimport type { WidgetSchema } from \"@fluid-app/portal-core/types\";\nimport type { WidgetRegistry } from \"./RegistryContext\";\n\n/**\n * Props that any ScreenRenderer must accept.\n * This is the minimal interface used by container widgets (e.g. LayoutWidget)\n * to render their children.\n */\nexport interface ScreenRendererComponentProps {\n  screen: WidgetSchema[];\n  registry?: WidgetRegistry;\n  className?: string;\n}\n\n/**\n * Context for providing an alternative ScreenRenderer component.\n *\n * This allows packages like portal-builder to inject their own ScreenRenderer\n * (with edit mode, drag-and-drop, etc.) so that container widgets in portal-widgets\n * use the richer renderer instead of the basic view-only one.\n *\n * Default is undefined — container widgets fall back to the local ScreenRenderer import.\n */\nexport const ScreenRendererContext: React.Context<\n  ComponentType<ScreenRendererComponentProps> | undefined\n> = createContext<ComponentType<ScreenRendererComponentProps> | undefined>(\n  undefined,\n);\n\n/**\n * Hook to get the ScreenRenderer component from context.\n * Returns undefined if no override has been provided.\n */\nexport function useScreenRenderer():\n  | ComponentType<ScreenRendererComponentProps>\n  | undefined {\n  return useContext(ScreenRendererContext);\n}\n","import { createContext, useContext, type ReactNode } from \"react\";\nimport type { WidgetSchema } from \"@fluid-app/portal-core/types\";\n\nconst WidgetNodeContext = createContext<WidgetSchema | undefined>(undefined);\n\nexport function WidgetNodeProvider({\n  children,\n  widget,\n}: {\n  readonly children?: ReactNode;\n  readonly widget: WidgetSchema;\n}): React.JSX.Element {\n  return (\n    <WidgetNodeContext.Provider value={widget}>\n      {children}\n    </WidgetNodeContext.Provider>\n  );\n}\n\nexport function useOptionalWidgetNode(): WidgetSchema | undefined {\n  return useContext(WidgetNodeContext);\n}\n","import type { DataSourceConfig } from \"../data-sources/types\";\nimport type { RemoteWidgetCapabilityGrants } from \"../remote-widget-capability-grants\";\n\n/**\n * Generic component type — avoids React dependency in core.\n * Accepts both function components and class component constructors.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyComponent = ((props: any) => any) | (new (props: any) => any);\n\n/**\n * Widget type names as a const object.\n * This serves as the single source of truth for widget discriminants.\n * Use `as const` for literal type inference (safety-as-const-deep-readonly rule).\n */\nexport const WIDGET_TYPE_NAMES = {\n  Alert: \"AlertWidget\",\n  Announcement: \"AnnouncementWidget\",\n  BulletList: \"BulletListWidget\",\n  Calendar: \"CalendarWidget\",\n  Card: \"CardWidget\",\n  Carousel: \"CarouselWidget\",\n  CatchUp: \"CatchUpWidget\",\n  Chart: \"ChartWidget\",\n  Container: \"ContainerWidget\",\n  Embed: \"EmbedWidget\",\n  Image: \"ImageWidget\",\n  Layout: \"LayoutWidget\",\n  Link: \"LinkWidget\",\n  List: \"ListWidget\",\n  MySite: \"MySiteWidget\",\n  Nested: \"NestedWidget\",\n  Points: \"PointsWidget\",\n  Quote: \"QuoteWidget\",\n  QuickLinks: \"QuickLinksWidget\",\n  QuickShare: \"QuickShareWidget\",\n  RecentActivity: \"RecentActivityWidget\",\n  Separator: \"SeparatorWidget\",\n  Shop: \"ShopWidget\",\n  Spacer: \"SpacerWidget\",\n  Table: \"TableWidget\",\n  Text: \"TextWidget\",\n  ToDo: \"ToDoWidget\",\n  Video: \"VideoWidget\",\n} as const;\n\n/**\n * Union of all known widget type names.\n * Derived from WIDGET_TYPE_NAMES to avoid duplication (deriving-typeof-for-object-keys rule).\n */\nexport type WidgetTypeName =\n  (typeof WIDGET_TYPE_NAMES)[keyof typeof WIDGET_TYPE_NAMES];\n\n/**\n * Legacy alias for backwards compatibility.\n * Prefer using WidgetTypeName for new code when you need the union type.\n */\nexport type WidgetType = string;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type WidgetRegistry = Record<WidgetType, AnyComponent>;\n\n/**\n * Base widget schema with loose typing for runtime data.\n * Use TypedWidgetSchema<T> when you have a known registry for better type safety.\n */\nexport type WidgetSchema = {\n  readonly type: WidgetType;\n  readonly props: Readonly<Record<string, unknown>>;\n  readonly id?: string; // Optional unique identifier for drag-and-drop\n  /** Optional data source configuration for data-bound widgets */\n  readonly dataSource?: DataSourceConfig | undefined;\n  /** Column index for masonry layouts (0-indexed) */\n  readonly columnIndex?: number;\n  /** Host-approved capabilities for a specific remote widget package version. */\n  readonly capabilityGrants?: RemoteWidgetCapabilityGrants;\n};\n\n/**\n * Type-safe widget schema based on registry.\n * Uses discriminated unions - the `type` field serves as discriminant.\n * When narrowed (e.g., `if (widget.type === \"AlertWidget\")`),\n * TypeScript automatically knows the correct props type.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type TypedWidgetSchema<T extends Record<string, AnyComponent>> = {\n  [K in keyof T]: {\n    readonly type: K;\n    readonly props: Readonly<\n      T[K] extends (props: infer P) => any\n        ? P\n        : T[K] extends new (props: infer P) => any\n          ? P\n          : never\n    >;\n    readonly id?: string;\n    readonly dataSource?: DataSourceConfig | undefined;\n    /** Column index for masonry layouts (0-indexed) */\n    readonly columnIndex?: number;\n    readonly capabilityGrants?: RemoteWidgetCapabilityGrants;\n  };\n}[keyof T];\n\n/**\n * Widget path in the tree - array of indices.\n * Readonly tuple to prevent accidental mutation.\n */\nexport type WidgetPath = readonly number[];\n\n// ============================================================================\n// Type Guards and Assertion Functions\n// ============================================================================\n\n/**\n * Type predicate to check if a string is a known widget type name.\n * Use for runtime validation of widget types.\n *\n * @example\n * if (isWidgetTypeName(widget.type)) {\n *   // TypeScript knows widget.type is WidgetTypeName\n * }\n */\nexport function isWidgetTypeName(type: string): type is WidgetTypeName {\n  // Type assertion required in type guard: Object.values() returns string[], but we\n  // need to check against WidgetTypeName values. The assertion is safe because we're\n  // checking membership, and the return type predicate ensures correct narrowing.\n  return Object.values(WIDGET_TYPE_NAMES).includes(type as WidgetTypeName);\n}\n\n/**\n * Type predicate to check if a widget has a specific type.\n * Enables type-safe widget narrowing without `as` assertions.\n *\n * @example\n * if (isWidgetType(widget, \"LayoutWidget\")) {\n *   // TypeScript knows widget.type === \"LayoutWidget\"\n *   // and widget.props is LayoutWidget props\n * }\n */\nexport function isWidgetType<T extends WidgetTypeName>(\n  widget: WidgetSchema | null | undefined,\n  typeName: T,\n): widget is WidgetSchema & { readonly type: T } {\n  return widget != null && widget.type === typeName;\n}\n\n/**\n * Helper for exhaustive switch statements on widget types.\n * Use in the default case to ensure all widget types are handled.\n *\n * @example\n * switch (widget.type) {\n *   case \"AlertWidget\": return handleAlert();\n *   case \"TextWidget\": return handleText();\n *   // ... all other widget types\n *   default: return assertNever(widget.type, \"widget type\");\n * }\n */\nexport function assertNever(value: never, context?: string): never {\n  const message = context\n    ? `Unexpected ${context}: ${String(value)}`\n    : `Unexpected value: ${String(value)}`;\n  throw new Error(message);\n}\n\n/**\n * Assertion function that throws if value is undefined.\n * Narrows the type to exclude undefined.\n *\n * @example\n * const widget = screen[0];\n * assertDefined(widget, \"widget at index 0\");\n * // TypeScript knows widget is defined here\n */\nexport function assertDefined<T>(\n  value: T | undefined | null,\n  name?: string,\n): asserts value is T {\n  if (value == null) {\n    throw new Error(name ? `${name} is required` : \"Value is required\");\n  }\n}\n","/**\n * Data Source Presets Registry\n *\n * Configurable presets that allow users to select options via sub-menus\n * and fine-tune parameters in a detail panel.\n */\n\nimport type {\n  SelectFieldSchema,\n  NumberFieldSchema,\n} from \"../registries/property-schema-types\";\nimport type { DataSource } from \"./types\";\n\n/** Widget types that can use data sources */\nexport type DataSourceCompatibleWidget =\n  | \"CarouselWidget\"\n  | \"ChartWidget\"\n  | \"EmbedWidget\"\n  | \"ImageWidget\"\n  | \"ListWidget\"\n  | \"NestedWidget\"\n  | \"ShopWidget\"\n  | \"TableWidget\"\n  | \"VideoWidget\";\n\n/** Field types supported in preset config panels */\nexport type PresetConfigField = SelectFieldSchema<string> | NumberFieldSchema;\n\n/** A preset data source configuration */\nexport interface DataSourcePreset {\n  /** Unique identifier for the preset */\n  id: string;\n  /** Human-readable name for display */\n  name: string;\n  /** Description of what data this endpoint provides */\n  description: string;\n  /** The API endpoint path (can include {variable} placeholders) */\n  endpoint: string;\n  /** Transformer name to apply to the data */\n  transform?: string;\n  /** Optional path to extract data from response (e.g., \"data.items\") */\n  resultPath?: string;\n  /** Which widgets this preset is compatible with */\n  compatibleWidgets: DataSourceCompatibleWidget[];\n  /** Optional select field shown as a sub-menu. The field's key becomes a variable in the endpoint URL. */\n  menuField?: SelectFieldSchema<string>;\n  /** Optional config fields rendered in the detail panel below the popover. Each field's key becomes a variable. */\n  configFields?: PresetConfigField[];\n  /**\n   * Per-widget locked field values. When the consuming widget is listed here,\n   * the named keys are forced to the given values: the menu/config UI for\n   * those keys is suppressed and the values are injected into the resolved\n   * variables. Used to scope a generic preset (e.g. one with a content-type\n   * picker) to a specific widget that only handles one content type.\n   */\n  widgetVariables?: Partial<\n    Record<DataSourceCompatibleWidget, Record<string, string>>\n  >;\n}\n\n/**\n * Pre-configured data source presets\n */\nexport const DATA_SOURCE_PRESETS: DataSourcePreset[] = [\n  {\n    id: \"rep-most-shared\",\n    name: \"Most Shared Visits\",\n    description: \"Content with the most share-link click-throughs\",\n    endpoint:\n      \"/v2025-06/reps/{rep_id}/most_shared?shareable_type={shareable_type}&limit={limit}&period={period}&language_iso={language_iso}\",\n    resultPath: \"resources\",\n    compatibleWidgets: [\n      \"CarouselWidget\",\n      \"ListWidget\",\n      \"NestedWidget\",\n      \"ShopWidget\",\n    ],\n    widgetVariables: {\n      ShopWidget: { shareable_type: \"products\" },\n    },\n    menuField: {\n      key: \"shareable_type\",\n      label: \"Content Type\",\n      type: \"select\",\n      options: [\n        { label: \"Products\", value: \"products\" },\n        { label: \"Media\", value: \"media\" },\n        { label: \"Pages\", value: \"pages\" },\n        { label: \"Libraries\", value: \"libraries\" },\n        { label: \"Enrollment Packs\", value: \"enrollment_packs\" },\n      ],\n      defaultValue: \"products\",\n    },\n    configFields: [\n      {\n        key: \"limit\",\n        label: \"Limit\",\n        type: \"number\",\n        defaultValue: 10,\n        min: 1,\n        max: 20,\n        description: \"Maximum number of items to show\",\n      },\n      {\n        key: \"period\",\n        label: \"Time Range\",\n        type: \"select\",\n        options: [\n          { label: \"7 days\", value: \"7d\" },\n          { label: \"30 days\", value: \"30d\" },\n          { label: \"90 days\", value: \"90d\" },\n          { label: \"1 year\", value: \"1y\" },\n          { label: \"All time\", value: \"all\" },\n        ],\n        defaultValue: \"all\",\n      },\n    ],\n  },\n  {\n    id: \"rep-most-viewed\",\n    name: \"Most Viewed\",\n    description: \"Most viewed content\",\n    endpoint:\n      \"/v2025-06/reps/{rep_id}/most_viewed?shareable_type={shareable_type}&limit={limit}&period={period}&language_iso={language_iso}\",\n    resultPath: \"resources\",\n    compatibleWidgets: [\n      \"CarouselWidget\",\n      \"ListWidget\",\n      \"NestedWidget\",\n      \"ShopWidget\",\n    ],\n    widgetVariables: {\n      ShopWidget: { shareable_type: \"products\" },\n    },\n    menuField: {\n      key: \"shareable_type\",\n      label: \"Content Type\",\n      type: \"select\",\n      options: [\n        { label: \"Products\", value: \"products\" },\n        { label: \"Media\", value: \"media\" },\n        { label: \"Pages\", value: \"pages\" },\n        { label: \"Libraries\", value: \"libraries\" },\n        { label: \"Enrollment Packs\", value: \"enrollment_packs\" },\n      ],\n      defaultValue: \"products\",\n    },\n    configFields: [\n      {\n        key: \"limit\",\n        label: \"Limit\",\n        type: \"number\",\n        defaultValue: 10,\n        min: 1,\n        max: 20,\n        description: \"Maximum number of items to show\",\n      },\n      {\n        key: \"period\",\n        label: \"Time Range\",\n        type: \"select\",\n        options: [\n          { label: \"7 days\", value: \"7d\" },\n          { label: \"30 days\", value: \"30d\" },\n          { label: \"90 days\", value: \"90d\" },\n          { label: \"1 year\", value: \"1y\" },\n          { label: \"All time\", value: \"all\" },\n        ],\n        defaultValue: \"all\",\n      },\n    ],\n  },\n  {\n    id: \"customer-orders\",\n    name: \"Orders\",\n    description: \"Customer order history\",\n    endpoint:\n      \"/v202506/orders?customer_id={customer_id}&page[limit]={limit}&status={status}\",\n    resultPath: \"orders\",\n    transform: \"toOrderTableProps\",\n    compatibleWidgets: [\"TableWidget\"],\n    configFields: [\n      {\n        key: \"limit\",\n        label: \"Limit\",\n        type: \"number\",\n        defaultValue: 10,\n        min: 1,\n        max: 50,\n        description: \"Maximum number of orders to show\",\n      },\n      {\n        key: \"status\",\n        label: \"Status\",\n        type: \"select\",\n        options: [\n          { label: \"All\", value: \"all\" },\n          { label: \"Paid\", value: \"paid\" },\n          { label: \"Unpaid\", value: \"unpaid\" },\n          { label: \"Refunded\", value: \"refunded\" },\n        ],\n        defaultValue: \"all\",\n      },\n    ],\n  },\n  {\n    id: \"customer-subscriptions\",\n    name: \"Subscriptions\",\n    description: \"Customer subscriptions\",\n    // Subscriptions endpoint is unversioned (legacy API), orders uses v202506\n    endpoint:\n      \"/subscriptions?customer_id={customer_id}&per_page={limit}&status={status}\",\n    resultPath: \"subscriptions\",\n    transform: \"toSubscriptionTableProps\",\n    compatibleWidgets: [\"TableWidget\"],\n    configFields: [\n      {\n        key: \"limit\",\n        label: \"Limit\",\n        type: \"number\",\n        defaultValue: 10,\n        min: 1,\n        max: 50,\n        description: \"Maximum number of subscriptions to show\",\n      },\n      {\n        key: \"status\",\n        label: \"Status\",\n        type: \"select\",\n        options: [\n          { label: \"All\", value: \"all\" },\n          { label: \"Active\", value: \"active\" },\n          { label: \"Paused\", value: \"paused\" },\n          { label: \"Cancelled\", value: \"cancelled\" },\n        ],\n        defaultValue: \"all\",\n      },\n    ],\n  },\n];\n\n/** Lookup map for O(1) preset resolution */\nconst PRESET_MAP = new Map<string, DataSourcePreset>(\n  DATA_SOURCE_PRESETS.map((p) => [p.id, p]),\n);\n\n/**\n * Resolves a preset by ID, returning the current preset definition.\n * Returns undefined if the preset ID is not recognized.\n */\nexport function resolvePreset(presetId: string): DataSourcePreset | undefined {\n  return PRESET_MAP.get(presetId);\n}\n\n/**\n * If the source is an API source with a presetId, returns a copy with\n * endpoint, resultPath, and transform resolved from the current preset.\n * Falls back to stored values if the preset is unknown.\n * Non-API sources are returned as-is.\n */\nexport function resolveSource<T extends DataSource>(source: T): T {\n  if (source.type !== \"api\" || !source.presetId) return source;\n\n  const preset = resolvePreset(source.presetId);\n  if (!preset) {\n    console.warn(\n      `[DataSource] Unknown preset \"${source.presetId}\", falling back to stored values`,\n    );\n    return source;\n  }\n\n  return {\n    ...source,\n    endpoint: preset.endpoint,\n    resultPath: preset.resultPath,\n    transform: preset.transform ?? source.transform,\n  } as T;\n}\n","import type { DataSource } from \"./types\";\n\n/**\n * Stable React Query cache key for the raw data fetch of a single source.\n *\n * Transforms and targetProps are intentionally excluded — they are applied\n * per-widget after reading from the shared cache, so two widgets that share\n * the same source can share a single fetch even when they consume the data\n * differently. The builder's data-source preview reuses this key so the\n * field's preview and the runtime widget hit the cache the same way.\n */\nexport function getSourceKey(source: DataSource): string {\n  if (source.type === \"api\") {\n    const varsKey = source.variables\n      ? `:${JSON.stringify(source.variables)}`\n      : \"\";\n    const identity = source.presetId ?? source.endpoint;\n    return `${identity}${varsKey}`;\n  }\n  if (source.type === \"custom\") {\n    const itemKeys =\n      source.selectedItems?.map((item) => `${item.shareableType}:${item.id}`) ??\n      [];\n    return `custom:${itemKeys.join(\",\")}`;\n  }\n  if (source.type === \"static\") {\n    return `static:${source.staticType}:${source.selectedId}`;\n  }\n  return \"unknown\";\n}\n","import { useQueries } from \"@tanstack/react-query\";\nimport { useCallback, useMemo, useRef } from \"react\";\nimport type { WidgetSchema } from \"@fluid-app/portal-core/types\";\nimport type {\n  DataSourceRegistry,\n  WidgetDataResult,\n  DataSourceContext,\n  DataSource,\n} from \"@fluid-app/portal-core/data-sources/types\";\nimport { resolveSource } from \"@fluid-app/portal-core/data-sources/presets\";\nimport { getSourceKey } from \"@fluid-app/portal-core/data-sources/source-key\";\nimport { useDataSourceApiOptional } from \"@fluid-app/portal-core/data-source-api-context\";\nimport { useShellTranslationOptional } from \"@fluid-app/portal-core/shell-translation-api-context\";\nimport { SHAREABLE_TO_RESOURCE_TYPE } from \"@fluid-app/portal-core/data-sources/fetchers/custom\";\nimport { useDataSourceRegistryConfig } from \"./registry-context\";\n\ninterface UseWidgetDataOptions {\n  /** Override the default registry from context */\n  registry?: DataSourceRegistry | undefined;\n  /** Base URL for API calls (e.g., \"https://api.fluid.app/api\") */\n  baseUrl?: string | undefined;\n}\n\n/**\n * Resolves cached raw data into widget props by applying each widget's own\n * transforms and targetProps mapping.\n */\nfunction resolvePropsFromQueries<T>(\n  queryResults: ReadonlyArray<{\n    data?: unknown;\n    isLoading: boolean;\n    error: Error | null;\n  }>,\n  sources: DataSource[],\n  registry: DataSourceRegistry,\n  errorConfig?: { fallback?: unknown },\n  transformerContext?: Pick<DataSourceContext, \"t\">,\n): T | undefined {\n  if (sources.length === 0) return undefined;\n  if (queryResults.some((q) => q.isLoading && !q.data)) return undefined;\n\n  const failedQuery = queryResults.find((q) => q.error);\n  const hasError = !!failedQuery?.error;\n\n  if (hasError && errorConfig?.fallback) {\n    return errorConfig.fallback as T;\n  }\n\n  if (hasError) {\n    return undefined;\n  }\n\n  const resolvedProps: Record<string, unknown> = {};\n\n  for (let i = 0; i < queryResults.length; i++) {\n    const query = queryResults[i];\n    const source = sources[i];\n    if (!query?.data || !source) continue;\n\n    // Sentry fix: FLUID-ADMIN-1DH — source or targetProps can be undefined from malformed widget config\n    if (!source.targetProps) continue;\n\n    // Apply this widget's transform to the cached raw data\n    let result: unknown = query.data;\n    if (source.transform) {\n      const transformer = registry.transformers[source.transform];\n      if (transformer) {\n        result = transformer(result, source, transformerContext);\n      } else {\n        console.warn(`Transform \"${source.transform}\" not found in registry`);\n      }\n    }\n\n    // Map to this widget's targetProps\n    if (\n      result !== null &&\n      typeof result === \"object\" &&\n      !Array.isArray(result) &&\n      source.targetProps.length > 1\n    ) {\n      const resultObj = result as Record<string, unknown>;\n      for (const prop of source.targetProps) {\n        if (prop in resultObj) {\n          resolvedProps[prop] = resultObj[prop];\n        }\n      }\n    } else {\n      for (const prop of source.targetProps) {\n        resolvedProps[prop] = result;\n      }\n    }\n  }\n\n  return resolvedProps as T;\n}\n\ntype FlatEntry =\n  | { kind: \"regular\"; sourceIndex: number }\n  | { kind: \"custom-item\"; sourceIndex: number };\n\n/**\n * A 404 means the item isn't available to this viewer — most commonly a product\n * not priced in the rep's market (portal products are market-scoped by design).\n * We treat it as a soft per-item miss rather than a widget-level failure.\n */\nfunction isNotFoundError(error: Error): boolean {\n  return (\n    \"status\" in error && (error as Error & { status: number }).status === 404\n  );\n}\n\n/**\n * Hook that fetches and resolves data sources for a widget using React Query.\n *\n * Raw API data is cached and shared across widgets with the same data source.\n * Transforms and targetProps mapping are applied per-widget after cache reads,\n * so multiple widgets can share one fetch but resolve data independently.\n *\n * Custom data sources expand to per-item queries so that the same resource\n * (e.g. Medium #42) is fetched only once even when referenced by multiple\n * widgets on the same page, eliminating N+1 API calls.\n */\nexport function useWidgetData<T = Record<string, unknown>>(\n  widget: WidgetSchema,\n  options?: UseWidgetDataOptions,\n): WidgetDataResult<T> {\n  const config = useDataSourceRegistryConfig();\n  const registry = options?.registry ?? config.registry;\n  const baseUrl = options?.baseUrl ?? config.baseUrl;\n  const getApiHeaders = config.getApiHeaders;\n  const variables = config.variables;\n  // useDataSourceApiOptional returns null outside a DataSourceApiProvider.\n  // This allows widgets with zero data sources to render in isolation\n  // (Storybook, unit tests). Fetchers that require api will throw at call\n  // time if it's missing — not at render time for every widget.\n  const api = useDataSourceApiOptional() ?? undefined;\n  // Shell translation for transformer labels (columns, alt text).\n  // Optional so widgets still work outside a ShellTranslationProvider.\n  const shellTranslation = useShellTranslationOptional();\n\n  // Resolve preset-backed sources to their current endpoint/resultPath/transform\n  const sources = useMemo(\n    () => (widget.dataSource?.sources ?? []).map(resolveSource),\n    [widget.dataSource?.sources],\n  );\n  const errorConfig = widget.dataSource?.error;\n  const widgetId = widget.id ?? \"unknown\";\n  const widgetType = widget.type;\n\n  const queryResultsRef = useRef<Array<{ refetch: () => void }>>([]);\n\n  // Build a flat query list. Custom sources expand to one query per selected\n  // item so that the React Query cache is keyed per resource (not per widget),\n  // letting multiple widgets share a single fetch for the same resource.\n  const { flatEntries, flatQueries } = useMemo(() => {\n    const entries: FlatEntry[] = [];\n    const qs = sources.flatMap((source, sourceIndex) => {\n      if (source.type === \"custom\" && source.selectedItems?.length) {\n        return source.selectedItems.map((item) => {\n          entries.push({ kind: \"custom-item\", sourceIndex });\n          const languageIso = variables?.language_iso;\n          return {\n            queryKey: [\n              \"portal-widget-item\",\n              item.shareableType,\n              item.id,\n              baseUrl,\n              languageIso,\n            ],\n            queryFn: async ({\n              signal,\n            }: {\n              signal: AbortSignal;\n            }): Promise<unknown> => {\n              if (!api) {\n                throw new Error(\n                  \"DataSourceApiProvider required for custom data sources\",\n                );\n              }\n              const resourceType =\n                SHAREABLE_TO_RESOURCE_TYPE[item.shareableType];\n              if (!resourceType) {\n                throw new Error(\n                  `Unknown shareable type: ${item.shareableType} for item #${item.id}`,\n                );\n              }\n              return api.fetchResource(\n                resourceType,\n                item.id,\n                signal,\n                languageIso,\n              );\n            },\n            enabled: sources.length > 0 && !!api,\n            retry: errorConfig?.retryCount ?? 0,\n            retryDelay: errorConfig?.retryDelay ?? 1000,\n            refetchInterval: source.refreshInterval ?? (false as false),\n          };\n        });\n      }\n      entries.push({ kind: \"regular\", sourceIndex });\n      return [\n        {\n          queryKey: [\n            \"portal-widget-data\",\n            getSourceKey(source),\n            baseUrl,\n            variables ? JSON.stringify(variables) : undefined,\n          ],\n          queryFn: async ({\n            signal,\n          }: {\n            signal: AbortSignal;\n          }): Promise<unknown> => {\n            const context: DataSourceContext = {\n              widgetId,\n              widgetType,\n              signal,\n              baseUrl,\n              getApiHeaders,\n              variables,\n              api,\n            };\n\n            const fetcher = registry.fetchers[source.type];\n            if (!fetcher) {\n              throw new Error(\n                `No fetcher registered for source type: ${source.type}`,\n              );\n            }\n\n            return fetcher(source, context);\n          },\n          enabled: sources.length > 0,\n          retry: errorConfig?.retryCount ?? 0,\n          retryDelay: errorConfig?.retryDelay ?? 1000,\n          refetchInterval: source.refreshInterval ?? (false as false),\n        },\n      ];\n    });\n    return { flatEntries: entries, flatQueries: qs };\n  }, [\n    sources,\n    baseUrl,\n    variables,\n    widgetId,\n    widgetType,\n    api,\n    registry,\n    errorConfig,\n    getApiHeaders,\n  ]);\n\n  // Cache only raw fetched data — no transforms or source objects stored\n  const rawResults = useQueries({ queries: flatQueries });\n\n  // Update ref for refetch callback (covers all flat queries)\n  queryResultsRef.current = rawResults;\n\n  // Re-aggregate per-item flat results back into one result per source so that\n  // resolvePropsFromQueries sees the same shape it always has.\n  const results = useMemo(() => {\n    const indicesBySource = new Map<number, number[]>();\n    flatEntries.forEach((e, i) => {\n      const existing = indicesBySource.get(e.sourceIndex) ?? [];\n      existing.push(i);\n      indicesBySource.set(e.sourceIndex, existing);\n    });\n\n    return sources.map((_, sourceIndex) => {\n      const indices = indicesBySource.get(sourceIndex) ?? [];\n      const firstEntry = flatEntries[indices[0] ?? -1];\n\n      if (firstEntry?.kind === \"custom-item\") {\n        const anyLoading = indices.some(\n          (i) => rawResults[i]?.isLoading ?? false,\n        );\n        // Hold back undefined until all items have settled — prevents partial\n        // renders that would cause a second paint once remaining items arrive.\n        const items = anyLoading\n          ? undefined\n          : indices\n              .map((i) => rawResults[i]?.data)\n              .filter((d): d is NonNullable<typeof d> => d !== undefined);\n\n        let aggError: Error | null = null;\n        if (!anyLoading && items !== undefined) {\n          const failures = indices.filter((i) => rawResults[i]?.error);\n          const failureErrors = failures.map((i) => rawResults[i]?.error);\n          if (failures.length > 0) {\n            console.error(\n              `[CustomFetcher] ${failures.length}/${indices.length} items failed to fetch`,\n              failureErrors,\n            );\n          }\n          // Surface an error only when a *hard* failure occurred. A 404 means\n          // the item isn't available to this viewer (e.g. a product not priced\n          // in their market), an expected per-item miss — not a widget failure.\n          // When every failure is a 404, render empty instead of the system\n          // error state so a page whose picked items are simply out-of-market\n          // degrades gracefully.\n          if (items.length === 0 && indices.length > 0) {\n            // Normalize first so a non-Error rejection still counts as a hard\n            // failure (a converted Error has no status, so it's never a 404).\n            const hardFailure = failureErrors\n              .map((e) => (e instanceof Error ? e : new Error(String(e))))\n              .find((e) => !isNotFoundError(e));\n            if (hardFailure) aggError = hardFailure;\n          }\n        }\n\n        return {\n          data: items as unknown[] | undefined,\n          isLoading: anyLoading,\n          error: aggError,\n        };\n      }\n\n      const idx = indices[0];\n      if (idx === undefined)\n        return {\n          data: undefined,\n          isLoading: false,\n          error: null as Error | null,\n        };\n      const raw = rawResults[idx];\n      if (!raw)\n        return {\n          data: undefined,\n          isLoading: false,\n          error: null as Error | null,\n        };\n      return {\n        data: raw.data,\n        isLoading: raw.isLoading,\n        error:\n          raw.error instanceof Error\n            ? raw.error\n            : raw.error\n              ? new Error(String(raw.error))\n              : null,\n      };\n    });\n  }, [rawResults, flatEntries, sources]);\n\n  // Aggregate loading state across all flat queries\n  const isLoading = rawResults.some((q) => q.isLoading);\n\n  // Expose the first error across all sources. Regular source errors come from\n  // rawResults directly. Custom source all-failure errors come from the\n  // per-source re-aggregation above (stored in results[].error).\n  const error = (() => {\n    for (let i = 0; i < rawResults.length; i++) {\n      const entry = flatEntries[i];\n      const result = rawResults[i];\n      if (entry?.kind === \"regular\" && result?.error) {\n        return result.error instanceof Error\n          ? result.error\n          : new Error(String(result.error));\n      }\n    }\n    for (const r of results) {\n      if (r.error) return r.error;\n    }\n    return null;\n  })();\n\n  // Stable fingerprint that changes only when query data or loading states change\n  const queryFingerprint = rawResults\n    .map((r) => `${r.dataUpdatedAt}:${r.isLoading}`)\n    .join(\",\");\n\n  // Resolve data: apply per-widget transforms and map to targetProps\n  const resultsRef = useRef(results);\n  resultsRef.current = results;\n\n  const transformerContext = useMemo(\n    () =>\n      shellTranslation\n        ? { t: (key: string) => shellTranslation.t(key as never) }\n        : undefined,\n    [shellTranslation],\n  );\n\n  const data = useMemo(() => {\n    const querySnapshots = resultsRef.current.map((q) => ({\n      data: q.data,\n      isLoading: q.isLoading,\n      error: q.error,\n    }));\n    return resolvePropsFromQueries<T>(\n      querySnapshots,\n      sources,\n      registry,\n      errorConfig,\n      transformerContext,\n    );\n  }, [queryFingerprint, sources, registry, errorConfig, transformerContext]);\n\n  // Stable refetch callback using ref\n  const refetch = useCallback(() => {\n    queryResultsRef.current.forEach((q) => q.refetch());\n  }, []);\n\n  return {\n    data,\n    isLoading,\n    error,\n    refetch,\n  };\n}\n","import type React from \"react\";\n\nexport function ErrorState(): React.JSX.Element {\n  return (\n    <div className=\"flex min-h-[120px] flex-col items-center justify-center p-6 text-center\">\n      <p className=\"text-lg font-semibold\">Something Went Wrong</p>\n      <p className=\"text-muted-foreground text-sm\">\n        Please contact a company admin for help\n      </p>\n    </div>\n  );\n}\n","import type React from \"react\";\nimport { memo, useMemo, type ComponentType, type ReactNode } from \"react\";\nimport type { WidgetSchema } from \"@fluid-app/portal-core/types\";\nimport { useWidgetData } from \"./use-widget-data\";\nimport { ErrorState } from \"./ErrorState\";\n\nexport interface DataAwareWidgetProps {\n  widget: WidgetSchema;\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  Component: ComponentType<any>;\n  /** Additional props to pass through (e.g., edit mode callbacks) */\n  additionalProps?: Record<string, unknown>;\n  /** Custom loading component */\n  loadingComponent?: ReactNode;\n  /** Custom error component */\n  errorComponent?: (error: Error) => ReactNode;\n  /** Base URL for API calls (e.g., \"https://api.fluid.app/api\") */\n  baseUrl?: string | undefined;\n}\n\n// Empty object constant to avoid creating new references\nconst EMPTY_OBJECT: Record<string, unknown> = {};\n\n/**\n * Wrapper component that resolves data sources before rendering the widget.\n * Merges resolved data with static props.\n */\nfunction DataAwareWidgetImpl({\n  widget,\n  Component,\n  additionalProps,\n  loadingComponent,\n  errorComponent,\n  baseUrl,\n}: DataAwareWidgetProps): React.JSX.Element | null {\n  // Use stable empty object if no additionalProps provided\n  const stableAdditionalProps = additionalProps ?? EMPTY_OBJECT;\n  const { data, isLoading, error } = useWidgetData(widget, { baseUrl });\n\n  // Merge static props with resolved data\n  // Data takes precedence (allows overriding defaults)\n  // Memoized to prevent unnecessary child re-renders\n  // Note: Must be called before any early returns to satisfy Rules of Hooks\n  const mergedProps = useMemo(\n    () => ({\n      ...widget.props,\n      ...data,\n      ...stableAdditionalProps,\n    }),\n    [widget.props, data, stableAdditionalProps],\n  );\n\n  // Show loading state\n  if (isLoading && widget.dataSource?.loading?.showSkeleton !== false) {\n    if (loadingComponent) {\n      return <>{loadingComponent}</>;\n    }\n    // Default skeleton - can be customized\n    return (\n      <div\n        className=\"bg-muted animate-pulse rounded-md\"\n        style={{ minHeight: 100 }}\n      >\n        <span className=\"sr-only\">Loading…</span>\n      </div>\n    );\n  }\n\n  // Show error state (if no fallback was applied)\n  if (error && !data) {\n    if (errorComponent) {\n      return <>{errorComponent(error)}</>;\n    }\n    // Default error display\n    return <ErrorState />;\n  }\n\n  return <Component {...mergedProps} />;\n}\n\n/**\n * Memoized wrapper component that resolves data sources before rendering the widget.\n * Prevents re-renders when parent re-renders but props haven't changed.\n */\nexport const DataAwareWidget: React.NamedExoticComponent<DataAwareWidgetProps> =\n  memo(DataAwareWidgetImpl);\n","import type { ComponentType } from \"react\";\nimport { useCallback } from \"react\";\nimport type React from \"react\";\nimport type {\n  WidgetSchema,\n  TypedWidgetSchema,\n  WidgetPath,\n} from \"@fluid-app/portal-core/types\";\nimport { WIDGET_TYPE_NAMES } from \"@fluid-app/portal-core/types\";\nimport { DataAwareWidget } from \"@fluid-app/portal-react/data-sources/DataAwareWidget\";\nimport { RegistryProvider, useRegistry } from \"../contexts/RegistryContext\";\nimport { WidgetNodeProvider } from \"../contexts/WidgetNodeContext\";\n\nexport interface ScreenRendererProps<\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  T extends Record<string, ComponentType<any>>,\n> {\n  /** Array of widget schemas to render */\n  screen: TypedWidgetSchema<T>[] | WidgetSchema[];\n  /** Widget registry mapping type names to components */\n  registry?: T;\n  /** Container widgets (like LayoutWidget) receive these additional props */\n  containerWidgetTypes?: string[];\n  /** Additional CSS classes for the wrapper div */\n  className?: string;\n}\n\ninterface ScreenRendererContentProps {\n  screen: WidgetSchema[];\n  containerWidgetTypes: string[];\n  className?: string | undefined;\n}\n\n/**\n * Internal component that uses the registry from context.\n * This allows us to avoid prop drilling the registry.\n */\nfunction ScreenRendererContent({\n  screen,\n  containerWidgetTypes,\n  className,\n}: ScreenRendererContentProps) {\n  const registry = useRegistry();\n\n  // Check if a widget type is a container\n  const isContainerWidget = useCallback(\n    (widgetType: string) => containerWidgetTypes.includes(widgetType),\n    [containerWidgetTypes],\n  );\n\n  // Render widgets recursively with path tracking\n  const renderWidget = useCallback(\n    (widget: WidgetSchema, index: number, currentPath: WidgetPath) => {\n      const Component = registry[widget.type];\n      if (!Component) {\n        console.warn(\n          `Widget type \"${String(widget.type)}\" not found in registry`,\n        );\n        return null;\n      }\n\n      const widgetPath = [...currentPath, index];\n\n      // Build additional props for container widgets\n      const additionalProps = isContainerWidget(widget.type)\n        ? {\n            widgetId: widget.id,\n            widgetPath,\n          }\n        : {};\n\n      const props = {\n        ...widget.props,\n        ...additionalProps,\n      };\n\n      // Wrap data-bound widgets with DataAwareWidget to resolve data sources\n      if (widget.dataSource) {\n        return (\n          <div\n            key={widget.id || index}\n            className=\"h-full w-full overflow-x-hidden\"\n          >\n            <WidgetNodeProvider widget={widget}>\n              <DataAwareWidget widget={widget} Component={Component} />\n            </WidgetNodeProvider>\n          </div>\n        );\n      }\n\n      return (\n        <div\n          key={widget.id || index}\n          className=\"h-full w-full overflow-x-hidden\"\n        >\n          <WidgetNodeProvider widget={widget}>\n            <Component {...props} />\n          </WidgetNodeProvider>\n        </div>\n      );\n    },\n    [registry, isContainerWidget],\n  );\n\n  return (\n    <div className={className || \"h-full w-full\"}>\n      {screen?.map((item, index) => {\n        // Skip null items (empty grid cells)\n        if (!item) return null;\n        return renderWidget(item, index, []);\n      })}\n    </div>\n  );\n}\n\n/**\n * ScreenRenderer - View-only component for rendering widget screens.\n *\n * This is a simplified version designed for the SDK that only handles\n * rendering widgets without edit mode or drag-and-drop functionality.\n *\n * Features:\n * - Static rendering of widgets\n * - Registry context: No prop drilling for widget registry\n * - Container widget support with path tracking\n *\n * Usage:\n * ```tsx\n * <ScreenRenderer\n *   screen={widgets}\n *   registry={WIDGET_REGISTRY}\n * />\n * ```\n */\nexport function ScreenRenderer<\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  T extends Record<string, ComponentType<any>>,\n>(props: ScreenRendererProps<T>): React.JSX.Element {\n  const {\n    screen,\n    registry,\n    containerWidgetTypes = [\n      WIDGET_TYPE_NAMES.Layout,\n      WIDGET_TYPE_NAMES.Container,\n    ],\n    className,\n  } = props;\n\n  // Conditionally pass registry prop to satisfy exactOptionalPropertyTypes\n  // When registry is undefined, we omit it entirely and let RegistryProvider inherit from parent\n  const registryProviderProps = registry !== undefined ? { registry } : {};\n\n  return (\n    <RegistryProvider {...registryProviderProps}>\n      {/* Type assertion required: TypedWidgetSchema<T>[] is a subtype of WidgetSchema[]\n          when T's components accept props compatible with WidgetSchema props.\n          This enables type-safe widget rendering with custom registries while allowing\n          the internal renderer to work with the base WidgetSchema type. */}\n      <ScreenRendererContent\n        screen={screen as WidgetSchema[]}\n        containerWidgetTypes={containerWidgetTypes}\n        className={className}\n      />\n    </RegistryProvider>\n  );\n}\n"],"mappings":";;;;;;;;AAGA,MAAM,wBAAA,GAAA,MAAA,eAA2D,KAAK;AAEtE,MAAa,wBAAwB,qBAAqB;;;;;;;AAsB1D,SAAgB,2BAAiD;AAC/D,SAAA,GAAA,MAAA,KAAW,qBAAqB;;;;;;;;;;ACYlC,MAAa,mBAAA,GAAA,MAAA,eAC+B,KAAA,EAAU;;;;;AAWtD,SAAgB,iBAAiB,EAC/B,UACA,YAC2C;CAE3C,MAAM,kBAAA,GAAA,MAAA,YAA4B,gBAAgB;CAClD,MAAM,eAAe,YAAY;AAEjC,KAAI,CAAC,aACH,OAAM,IAAI,MACR,+FACD;AAGH,QACE,iBAAA,GAAA,kBAAA,KAAC,gBAAgB,UAAjB;EAA0B,OAAO;EAC9B;EACwB,CAAA;;;;;;AAQ/B,SAAgB,cAA8B;CAC5C,MAAM,YAAA,GAAA,MAAA,YAAsB,gBAAgB;AAE5C,KAAI,CAAC,SACH,OAAM,IAAI,MACR,2EACD;AAGH,QAAO;;;;;;;;;;;;;AC9DT,MAAa,yBAAA,GAAA,MAAA,eAGX,KAAA,EACD;;;;;AAMD,SAAgB,oBAEF;AACZ,SAAA,GAAA,MAAA,YAAkB,sBAAsB;;;;AClC1C,MAAM,qB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