{"version":3,"file":"index.cjs","names":["ISLAND_STRATEGIES","CLIENT_STRATEGY_METADATA_ATTRIBUTE","CLIENT_EVENT_METADATA_ATTRIBUTE","DEFAULT_INTERACTION_EVENT_TYPE","CLIENT_ACTIONS_METADATA_ATTRIBUTE","ISLAND_METADATA_ATTRIBUTE","ISLAND_VALUE_METADATA_ATTRIBUTE","HYDRATE_ISLANDS_STATUS","CLIENT_TARGET_METADATA_ATTRIBUTE","canUseComponentDOMRuntime","renderDSD","getCssText","getStoreFromHost","#islandHydrationAccepted","#clientActionCleanup","HYDRATE_ISLANDS_HOOK","peekStoreFromHost","#storeRetryScheduled","#dispose"],"sources":["../src/defineComponent/implementation.ts"],"sourcesContent":["/**\n * defineComponent - High-level API for defining Web Components.\n *\n * Automates: Shadow DOM setup, createRoot lifecycle, DSD hydration detection,\n * adoptedStyleSheets, and props reflection with reactive signals and type coercion.\n * @module\n */\nimport {\n  connectGlobalStyles,\n  disconnectGlobalStyles,\n  getCssText,\n} from \"@/css/implementation\";\nimport {\n  bindCurrentStoreToSubtree,\n  canUseComponentDOMRuntime,\n  captureCurrentStore,\n  getStoreFromHost,\n  peekStoreFromHost,\n} from \"@/defineComponent/internal\";\nimport { registerComponent } from \"@/registry/implementation\";\nimport { ensureComponentRenderer, renderDSD } from \"@/ssr/implementation\";\nimport type { RootDispose, Signal } from \"@dathra/reactivity\";\nimport { createRoot, signal, templateEffect } from \"@dathra/reactivity\";\nimport {\n  cancelScheduledIslandHydration,\n  hydrateWithPlan,\n  type GenericHydrationPlan,\n  HYDRATE_ISLANDS_HOOK,\n  HYDRATE_ISLANDS_STATUS,\n} from \"@dathra/runtime/hydration\";\nimport { fromMarkup, getClientAction, insert, setAttr } from \"@dathra/runtime\";\nimport {\n  CLIENT_ACTIONS_METADATA_ATTRIBUTE,\n  CLIENT_EVENT_METADATA_ATTRIBUTE,\n  CLIENT_STRATEGY_METADATA_ATTRIBUTE,\n  CLIENT_TARGET_METADATA_ATTRIBUTE,\n  DEFAULT_INTERACTION_EVENT_TYPE,\n  ISLAND_METADATA_ATTRIBUTE,\n  ISLAND_STRATEGIES,\n  ISLAND_VALUE_METADATA_ATTRIBUTE,\n  isIslandStrategyName,\n  type ColocatedClientStrategyName,\n  type IslandStrategyName,\n} from \"@dathra/shared\";\nimport type { AtomStore } from \"@dathra/store\";\n\n// ── Type definitions ────────────────────────────────────────────────\n\n/** Supported prop type constructors or custom coercion functions. */\ntype PropType =\n  | StringConstructor\n  | NumberConstructor\n  | BooleanConstructor\n  | ((value: string | null) => unknown);\n\n/** Definition for a single prop (type, default, attribute mapping). */\ninterface PropDefinition {\n  /** Constructor or coercion function for attribute→value conversion. */\n  type: PropType;\n  /** Default value when attribute is absent. Falls back to type default. */\n  default?: unknown;\n  /** Attribute name override, or `false` to disable attribute observation. */\n  attribute?: string | false;\n}\n\n/** Schema mapping prop names to their definitions. */\ntype PropsSchema = Record<string, PropDefinition>;\ntype EmptyPropsSchema = Record<never, never>;\n\nfunction buildComponentContent(content: Node | string): Node {\n  if (typeof content === \"string\") {\n    const fragment = fromMarkup(content)();\n    bindCurrentStoreToSubtree(fragment);\n    return fragment;\n  }\n\n  return content;\n}\n\n/** Infer the runtime type from a PropDefinition's type field. */\ntype InferPropType<D extends PropDefinition> = D extends {\n  type: StringConstructor;\n}\n  ? string\n  : D extends { type: NumberConstructor }\n    ? number\n    : D extends { type: BooleanConstructor }\n      ? boolean\n      : D extends { type: (v: string | null) => infer R }\n        ? R\n        : unknown;\n\n/** Map a PropsSchema to an object of reactive signals. */\ntype InferProps<S extends PropsSchema> = {\n  readonly [K in keyof S]: Signal<InferPropType<S[K]>>;\n};\n\n/**\n * Function component that receives reactive props as signals.\n * Props can be accessed via .value and will reactively update when attributes change.\n */\ntype FunctionComponent<S extends PropsSchema = PropsSchema> = (\n  ctx: ComponentContext<S>,\n) => Node | DocumentFragment | string;\n\n/** Internal setup function with host and context. @internal */\ntype SetupFunction<S extends PropsSchema = PropsSchema> = (\n  host: HTMLElement,\n  ctx: ComponentContext<S>,\n) => Node | DocumentFragment | string;\n\n/** Context passed to setup and hydrate functions. */\ninterface ComponentContext<S extends PropsSchema = PropsSchema> {\n  readonly host: HTMLElement;\n  readonly props: Readonly<InferProps<S>>;\n  readonly client: ComponentClientContext;\n  readonly store: AtomStore;\n  readonly children: unknown;\n}\n\ninterface ComponentClientContext {\n  readonly strategy: IslandStrategyName | null;\n  readonly value: string | null;\n  readonly hydrated: boolean;\n}\n\ninterface JSXReactiveValue<T> {\n  readonly value: T;\n}\n\ntype JSXPropValue<T> = T | JSXReactiveValue<T>;\n\ninterface IslandsDirectiveJSXProps {\n  readonly \"client:load\"?: true | \"\";\n  readonly \"client:visible\"?: true | \"\";\n  readonly \"client:idle\"?: true | \"\";\n  readonly \"client:interaction\"?: true | string;\n  readonly \"client:media\"?: string;\n}\n\nconst KNOWN_ISLAND_STRATEGIES = new Set(ISLAND_STRATEGIES);\n\ninterface IslandHydrationTrigger {\n  readonly strategy: ColocatedClientStrategyName;\n  readonly eventType?: string;\n  readonly replayTargetId?: string | null;\n  readonly replayEvent?: ReplayEventSnapshot;\n}\n\ninterface ReplayEventSnapshot {\n  readonly kind: \"event\" | \"mouse\" | \"keyboard\" | \"focus\" | \"input\" | \"pointer\";\n  readonly init:\n    | EventInit\n    | MouseEventInit\n    | KeyboardEventInit\n    | FocusEventInit\n    | InputEventInit\n    | PointerEventInit;\n}\n\n/** Props accepted by the JSX helper component returned from defineComponent. */\ntype JSXComponentProps<S extends PropsSchema = EmptyPropsSchema> = {\n  readonly [K in keyof S]?: JSXPropValue<InferPropType<S[K]>>;\n} & {\n  readonly children?: unknown;\n} & IslandsDirectiveJSXProps;\n\n/** Options for defineComponent. */\ninterface ComponentOptions<S extends PropsSchema = PropsSchema> {\n  /** CSS styles to apply via adoptedStyleSheets. */\n  styles?: readonly (CSSStyleSheet | string)[];\n  /** Props schema defining observed attributes with type coercion. */\n  props?: S;\n  /** Hydration setup function for Declarative Shadow DOM. */\n  hydrate?: HydrateSetupFunction<S>;\n}\n\n/** Component class with tag name and schema metadata. */\ninterface ComponentMetadata<S extends PropsSchema = PropsSchema> {\n  readonly __tagName__: string;\n  readonly __propsSchema__?: S;\n  readonly __hydrationMetadata__?: ComponentHydrationMetadata;\n}\n\ntype HydrationPlanFactory = (\n  host: HTMLElement,\n  ctx: ComponentContext<PropsSchema>,\n) => GenericHydrationPlan;\n\ninterface ComponentHydrationMetadata {\n  readonly kind: \"generic-plan\";\n  readonly planFactory?: HydrationPlanFactory | null;\n  readonly unsupportedReason?: string;\n}\n\n/** Component class with tag name and schema metadata. */\ninterface ComponentClass<S extends PropsSchema = PropsSchema>\n  extends Function, ComponentMetadata<S> {}\n\n/** Constructor type returned by defineComponent. */\ntype ComponentConstructor<S extends PropsSchema = PropsSchema> = {\n  new (): HTMLElement & { [K in keyof S]: InferPropType<S[K]> };\n  readonly prototype: HTMLElement;\n} & ComponentClass<S>;\n\n/** JSX helper component returned by defineComponent. */\ntype JSXComponent<S extends PropsSchema = EmptyPropsSchema> = (\n  props: JSXComponentProps<S> | null,\n) => Node;\n\n/** Public object returned by defineComponent. */\ninterface DefinedComponent<\n  S extends PropsSchema = EmptyPropsSchema,\n> extends ComponentMetadata<S> {\n  (props: JSXComponentProps<S> | null): Node;\n  readonly webComponent: ComponentConstructor<S>;\n  readonly jsx: JSXComponent<S>;\n}\n\n/** TSX helper: derive element attribute types from a ComponentClass. */\ntype ComponentElement<C> =\n  C extends ComponentMetadata<infer S>\n    ? JSXComponentProps<S>\n    : Record<string, unknown>;\n\n/** Function that hydrates existing DSD content without creating new DOM. */\ntype HydrateSetupFunction<S extends PropsSchema = PropsSchema> = (\n  ctx: ComponentContext<S>,\n) => void;\n\n// ── Internal helpers ────────────────────────────────────────────────\n\n/**\n * Get the default value for a PropDefinition.\n * @internal\n */\nfunction getDefaultValue(def: PropDefinition): unknown {\n  if (def.default !== undefined) return def.default;\n  if (def.type === String) return \"\";\n  if (def.type === Number) return 0;\n  if (def.type === Boolean) return false;\n  return undefined;\n}\n\n/**\n * Coerce an attribute string (or null) to the typed value.\n * @internal\n */\nfunction coerceValue(def: PropDefinition, attrValue: string | null): unknown {\n  if (def.type === Boolean) {\n    // Boolean attributes: presence = true, absence (null) = false\n    return attrValue !== null;\n  }\n  if (def.type === Number) {\n    // Per SPEC: null → default value (Number(null) = 0 would hide the real default)\n    if (attrValue === null) return getDefaultValue(def);\n    return Number(attrValue);\n  }\n  if (def.type === String) {\n    // Per SPEC: null → default value\n    if (attrValue === null) return getDefaultValue(def);\n    return attrValue;\n  }\n  // Custom coercion function - pass null through as per SPEC\n  if (typeof def.type === \"function\") {\n    return def.type(attrValue);\n  }\n  // Fallback for null with no custom function\n  if (attrValue === null) {\n    return getDefaultValue(def);\n  }\n  return attrValue;\n}\n\n/**\n * Derive the attribute name for a prop.\n * Returns null if `attribute: false` (property-only prop).\n * @internal\n */\nfunction attrNameForProp(propName: string, def: PropDefinition): string | null {\n  if (def.attribute === false) return null;\n  return typeof def.attribute === \"string\" ? def.attribute : propName;\n}\n\ninterface ReactiveValue<T = unknown> {\n  readonly value: T;\n}\n\nfunction isReactiveValue(value: unknown): value is ReactiveValue {\n  const isNode = typeof Node !== \"undefined\" && value instanceof Node;\n  return (\n    typeof value === \"object\" &&\n    value !== null &&\n    \"value\" in value &&\n    typeof (value as Record<string, unknown>).value !== \"undefined\" &&\n    !isNode\n  );\n}\n\nfunction isEventHandlerKey(key: string): boolean {\n  return (\n    key.startsWith(\"on\") && key.length > 2 && key[2] === key[2].toUpperCase()\n  );\n}\n\nfunction getEventType(key: string): string {\n  return key.slice(2).toLowerCase();\n}\n\nfunction isIslandsDirectiveProp(\n  key: string,\n): key is keyof IslandsDirectiveJSXProps {\n  return (\n    key === \"client:load\" ||\n    key === \"client:visible\" ||\n    key === \"client:idle\" ||\n    key === \"client:interaction\" ||\n    key === \"client:media\"\n  );\n}\n\nfunction isKnownIslandStrategy(value: string | null): boolean {\n  return isIslandStrategyName(value) && KNOWN_ISLAND_STRATEGIES.has(value);\n}\n\nfunction getNormalizedIslandStrategy(\n  value: string | null,\n): IslandStrategyName | null {\n  return isIslandStrategyName(value) ? value : null;\n}\n\nfunction getColocatedClientStrategyFromShadowRoot(\n  shadowRoot: ShadowRoot,\n): { strategy: ColocatedClientStrategyName; value: string | null } | null {\n  const targets = Array.from(\n    shadowRoot.querySelectorAll<HTMLElement>(\n      `[${CLIENT_STRATEGY_METADATA_ATTRIBUTE}]`,\n    ),\n  );\n\n  if (targets.length === 0) {\n    return null;\n  }\n\n  let strategy: ColocatedClientStrategyName | null = null;\n  let interactionEventType: string | null = null;\n\n  for (const target of targets) {\n    const nextStrategy = target.getAttribute(\n      CLIENT_STRATEGY_METADATA_ATTRIBUTE,\n    );\n    if (!isIslandStrategyName(nextStrategy) || nextStrategy === \"media\") {\n      continue;\n    }\n\n    if (strategy === null) {\n      strategy = nextStrategy;\n    } else if (strategy !== nextStrategy) {\n      throw new Error(\n        \"[dathra] Mixed colocated client strategies are not supported in one component shadow root\",\n      );\n    }\n\n    if (nextStrategy !== \"interaction\") {\n      continue;\n    }\n\n    const nextEventType =\n      target.getAttribute(CLIENT_EVENT_METADATA_ATTRIBUTE) ??\n      DEFAULT_INTERACTION_EVENT_TYPE;\n    if (interactionEventType === null) {\n      interactionEventType = nextEventType;\n      continue;\n    }\n\n    if (interactionEventType !== nextEventType) {\n      throw new Error(\n        \"[dathra] Mixed colocated interaction event types are not supported in one component shadow root\",\n      );\n    }\n  }\n\n  const normalizedStrategy = getNormalizedIslandStrategy(strategy);\n  if (normalizedStrategy === null || normalizedStrategy === \"media\") {\n    return null;\n  }\n\n  return {\n    strategy: normalizedStrategy,\n    value:\n      normalizedStrategy === \"interaction\"\n        ? (interactionEventType ?? DEFAULT_INTERACTION_EVENT_TYPE)\n        : null,\n  };\n}\n\nfunction createReplayEvent(\n  eventType: string,\n  replayEvent: ReplayEventSnapshot | undefined,\n): Event {\n  const baseInit = replayEvent?.init ?? {\n    bubbles: true,\n    cancelable: true,\n    composed: true,\n  };\n\n  switch (replayEvent?.kind) {\n    case \"pointer\":\n      if (typeof PointerEvent === \"function\") {\n        return new PointerEvent(eventType, baseInit as PointerEventInit);\n      }\n      break;\n    case \"mouse\":\n      if (typeof MouseEvent === \"function\") {\n        return new MouseEvent(eventType, baseInit as MouseEventInit);\n      }\n      break;\n    case \"keyboard\":\n      if (typeof KeyboardEvent === \"function\") {\n        return new KeyboardEvent(eventType, baseInit as KeyboardEventInit);\n      }\n      break;\n    case \"focus\":\n      if (typeof FocusEvent === \"function\") {\n        return new FocusEvent(eventType, baseInit as FocusEventInit);\n      }\n      break;\n    case \"input\":\n      if (typeof InputEvent === \"function\") {\n        return new InputEvent(eventType, baseInit as InputEventInit);\n      }\n      break;\n  }\n\n  return new Event(eventType, baseInit);\n}\n\nfunction getHostClientActionBindings(\n  host: HTMLElement,\n): Record<string, { id: string; payload: Record<string, unknown> }> {\n  const raw = host.getAttribute(CLIENT_ACTIONS_METADATA_ATTRIBUTE);\n  if (raw === null) {\n    return {};\n  }\n\n  try {\n    const parsed = JSON.parse(raw) as Record<string, unknown>;\n    const entries = Object.entries(parsed).flatMap(([eventType, binding]) => {\n      if (\n        typeof eventType !== \"string\" ||\n        typeof binding !== \"object\" ||\n        binding === null\n      ) {\n        return [];\n      }\n\n      const actionId = (binding as { id?: unknown }).id;\n      if (typeof actionId !== \"string\") {\n        return [];\n      }\n\n      const payload = (binding as { payload?: unknown }).payload;\n      return [\n        [\n          eventType,\n          {\n            id: actionId,\n            payload:\n              typeof payload === \"object\" && payload !== null\n                ? (payload as Record<string, unknown>)\n                : {},\n          },\n        ] as const,\n      ];\n    });\n\n    return Object.fromEntries(entries) as Record<\n      string,\n      { id: string; payload: Record<string, unknown> }\n    >;\n  } catch {\n    console.error(\n      `[dathra] Invalid ${CLIENT_ACTIONS_METADATA_ATTRIBUTE} metadata on component host`,\n    );\n    return {};\n  }\n}\n\nfunction bindHostClientActions(host: HTMLElement): () => void {\n  const bindings = getHostClientActionBindings(host);\n  const cleanups: Array<() => void> = [];\n\n  for (const [eventType, binding] of Object.entries(bindings)) {\n    const factory = getClientAction(binding.id) as\n      | ((payload: Record<string, unknown>, host: HTMLElement) => EventListener)\n      | undefined;\n    if (factory === undefined) {\n      console.warn(\n        `[dathra] Missing client action artifact for id ${binding.id}`,\n      );\n      continue;\n    }\n\n    const handler = factory(binding.payload, host);\n    host.addEventListener(eventType, handler);\n    cleanups.push(() => {\n      host.removeEventListener(eventType, handler);\n    });\n  }\n\n  return () => {\n    for (const cleanup of cleanups) {\n      cleanup();\n    }\n  };\n}\n\nfunction replayHostClientAction(\n  host: HTMLElement,\n  trigger: IslandHydrationTrigger | undefined,\n): void {\n  if (trigger?.eventType == null || trigger.replayTargetId != null) {\n    return;\n  }\n\n  const bindings = getHostClientActionBindings(host);\n  if (!(trigger.eventType in bindings)) {\n    return;\n  }\n\n  host.dispatchEvent(createReplayEvent(trigger.eventType, trigger.replayEvent));\n}\n\nfunction createClientContext(host: HTMLElement): ComponentClientContext {\n  const strategy = host.getAttribute(ISLAND_METADATA_ATTRIBUTE);\n  const normalizedStrategy = getNormalizedIslandStrategy(strategy);\n  const value =\n    normalizedStrategy === null\n      ? null\n      : normalizedStrategy === \"interaction\"\n        ? (host.getAttribute(ISLAND_VALUE_METADATA_ATTRIBUTE) ??\n          DEFAULT_INTERACTION_EVENT_TYPE)\n        : host.getAttribute(ISLAND_VALUE_METADATA_ATTRIBUTE);\n  return {\n    strategy: normalizedStrategy,\n    value,\n    hydrated: Reflect.get(host, HYDRATE_ISLANDS_STATUS) === \"hydrated\",\n  };\n}\n\nfunction replayHydrationTrigger(\n  shadowRoot: ShadowRoot,\n  trigger: IslandHydrationTrigger | undefined,\n): void {\n  if (trigger?.eventType == null || trigger.replayTargetId == null) {\n    return;\n  }\n\n  const target = shadowRoot.querySelector<HTMLElement>(\n    `[${CLIENT_TARGET_METADATA_ATTRIBUTE}=\"${trigger.replayTargetId}\"]`,\n  );\n\n  if (target === null) {\n    return;\n  }\n\n  target.dispatchEvent(\n    createReplayEvent(trigger.eventType, trigger.replayEvent),\n  );\n}\n\nfunction isIterableValue(value: unknown): value is Iterable<unknown> {\n  const isNode = typeof Node !== \"undefined\" && value instanceof Node;\n  return (\n    typeof value === \"object\" &&\n    value !== null &&\n    Symbol.iterator in value &&\n    !isNode\n  );\n}\n\nfunction hasDynamicJSXChildren(value: unknown): boolean {\n  if (typeof value === \"function\" || isReactiveValue(value)) {\n    return true;\n  }\n\n  if (Array.isArray(value)) {\n    return value.some((item) => hasDynamicJSXChildren(item));\n  }\n\n  if (isIterableValue(value)) {\n    for (const item of value) {\n      if (hasDynamicJSXChildren(item)) {\n        return true;\n      }\n    }\n  }\n\n  return false;\n}\n\nfunction resolveJSXChildren(value: unknown): unknown {\n  if (typeof value === \"function\") {\n    return resolveJSXChildren((value as () => unknown)());\n  }\n\n  if (isReactiveValue(value)) {\n    return resolveJSXChildren(value.value);\n  }\n\n  if (Array.isArray(value)) {\n    return value.map((item) => resolveJSXChildren(item));\n  }\n\n  if (isIterableValue(value)) {\n    return Array.from(value, (item) => resolveJSXChildren(item));\n  }\n\n  return value;\n}\n\nfunction applyJSXValue<S extends PropsSchema>(\n  element: HTMLElement,\n  key: string,\n  value: unknown,\n  propsSchema?: S,\n): void {\n  if (propsSchema && key in propsSchema) {\n    (element as unknown as Record<string, unknown>)[key] = value;\n    return;\n  }\n\n  const attrKey = key === \"className\" ? \"class\" : key;\n  setAttr(element, attrKey, value);\n}\n\nfunction propsToSSRAttributes<S extends PropsSchema>(\n  props: JSXComponentProps<S>,\n  propsSchema?: S,\n): Record<string, unknown> {\n  const attrs: Record<string, unknown> = {};\n\n  for (const [key, rawValue] of Object.entries(props)) {\n    if (isEventHandlerKey(key) || isIslandsDirectiveProp(key)) {\n      continue;\n    }\n\n    const value = isReactiveValue(rawValue) ? rawValue.value : rawValue;\n    if (value === null || value === undefined || value === false) {\n      continue;\n    }\n\n    if (propsSchema && key in propsSchema) {\n      const def = propsSchema[key]!;\n      const attrName = attrNameForProp(key, def);\n      if (attrName === null) {\n        continue;\n      }\n      if (def.type === Boolean) {\n        if (value) {\n          attrs[attrName] = true;\n        }\n        continue;\n      }\n      attrs[attrName] = value;\n      continue;\n    }\n\n    const attrKey = key === \"className\" ? \"class\" : key;\n    attrs[attrKey] = value;\n  }\n\n  return attrs;\n}\n\nfunction createBrowserJSXElement<S extends PropsSchema>(\n  tagName: string,\n  props: JSXComponentProps<S>,\n  propsSchema?: S,\n): HTMLElement {\n  const element = document.createElement(tagName) as HTMLElement;\n\n  for (const [key, value] of Object.entries(props)) {\n    if (key === \"children\" || isIslandsDirectiveProp(key)) {\n      continue;\n    }\n\n    if (isEventHandlerKey(key) && typeof value === \"function\") {\n      element.addEventListener(getEventType(key), value as EventListener);\n      continue;\n    }\n\n    if (isReactiveValue(value)) {\n      templateEffect(() => {\n        applyJSXValue(element, key, value.value, propsSchema);\n      });\n      continue;\n    }\n\n    applyJSXValue(element, key, value, propsSchema);\n  }\n\n  const children = props.children;\n  if (children !== undefined) {\n    if (hasDynamicJSXChildren(children)) {\n      const anchor = document.createComment(\"component-children\");\n      element.append(anchor);\n      templateEffect(() => {\n        insert(element, resolveJSXChildren(children), anchor);\n        bindCurrentStoreToSubtree(element);\n      });\n    } else {\n      insert(element, children, null);\n      bindCurrentStoreToSubtree(element);\n    }\n  }\n\n  bindCurrentStoreToSubtree(element);\n\n  return element;\n}\n\nfunction createJSXComponent<S extends PropsSchema>(\n  tagName: string,\n  propsSchema?: S,\n  useBrowserRuntime = canUseComponentDOMRuntime(),\n): JSXComponent<S> {\n  return (props: JSXComponentProps<S> | null) => {\n    const safeProps = props ?? ({} as JSXComponentProps<S>);\n\n    if (!useBrowserRuntime) {\n      return renderDSD(\n        tagName,\n        propsToSSRAttributes(safeProps, propsSchema),\n      ) as unknown as Node;\n    }\n\n    return createBrowserJSXElement(tagName, safeProps, propsSchema);\n  };\n}\n\nfunction createDefinedComponent<S extends PropsSchema>(\n  webComponent: ComponentConstructor<S>,\n  jsx: JSXComponent<S>,\n  propsSchema: S | undefined,\n  tagName: string,\n  hydrationMetadata?: ComponentHydrationMetadata,\n): DefinedComponent<S> {\n  const definedComponent = jsx as DefinedComponent<S>;\n  Object.defineProperties(definedComponent, {\n    webComponent: {\n      value: webComponent,\n      enumerable: true,\n    },\n    jsx: {\n      value: jsx,\n      enumerable: true,\n    },\n    __tagName__: {\n      value: tagName,\n      enumerable: true,\n    },\n    __propsSchema__: {\n      value: propsSchema,\n      enumerable: true,\n    },\n    __hydrationMetadata__: {\n      value: hydrationMetadata,\n      enumerable: true,\n    },\n  });\n  return definedComponent;\n}\n\n// ── Main API ────────────────────────────────────────────────────────\n\n/**\n * Wrap a function component into a SetupFunction.\n * Passes reactive signal props directly to the function component.\n * @internal\n */\nfunction wrapFunctionComponent<S extends PropsSchema>(\n  fc: FunctionComponent<S>,\n  _propsSchema: S | undefined,\n): SetupFunction<S> {\n  return (_host: HTMLElement, ctx: ComponentContext<S>) => {\n    return fc(ctx);\n  };\n}\n\nfunction collectServerCssTexts(\n  styles?: readonly (CSSStyleSheet | string)[],\n): string[] {\n  const cssTexts: string[] = [];\n\n  if (styles?.length) {\n    for (const style of styles) {\n      const text = getCssText(style);\n      if (text) {\n        cssTexts.push(text);\n      }\n    }\n  }\n\n  return cssTexts;\n}\n\nfunction createSSRPlaceholderClass<S extends PropsSchema>(\n  tagName: string,\n  propsSchema: S | undefined,\n  hydrationMetadata?: ComponentHydrationMetadata,\n): ComponentConstructor<S> {\n  const SSRClass = class {} as ComponentConstructor<S> & {\n    __tagName__?: string;\n    __propsSchema__?: S;\n    __hydrationMetadata__?: ComponentHydrationMetadata;\n  };\n\n  SSRClass.__tagName__ = tagName;\n  SSRClass.__propsSchema__ = propsSchema;\n  SSRClass.__hydrationMetadata__ = hydrationMetadata;\n\n  return SSRClass;\n}\n\nfunction createServerDefinedComponent<S extends PropsSchema>(\n  tagName: string,\n  resolvedSetup: SetupFunction<S>,\n  options: ComponentOptions<S>,\n  jsx: JSXComponent<S>,\n  hydrationMetadata?: ComponentHydrationMetadata,\n): DefinedComponent<S> {\n  registerComponent(\n    tagName,\n    resolvedSetup as SetupFunction,\n    collectServerCssTexts(options.styles),\n    options.props as PropsSchema | undefined,\n    hydrationMetadata,\n  );\n  ensureComponentRenderer();\n\n  return createDefinedComponent(\n    createSSRPlaceholderClass(tagName, options.props, hydrationMetadata),\n    jsx,\n    options.props,\n    tagName,\n    hydrationMetadata,\n  );\n}\n\nfunction createClientDefinedComponent<S extends PropsSchema>(\n  tagName: string,\n  resolvedSetup: SetupFunction<S>,\n  options: ComponentOptions<S>,\n  jsx: JSXComponent<S>,\n  hydrationMetadata?: ComponentHydrationMetadata,\n): DefinedComponent<S> {\n  const { styles, props: propsSchema, hydrate: hydrateSetup } = options;\n\n  if (typeof __DEV__ !== \"undefined\" && __DEV__) {\n    if (!tagName.includes(\"-\")) {\n      console.warn(\n        `[dathra] Custom element tag name \"${tagName}\" must contain a hyphen.`,\n      );\n    }\n  }\n\n  let sheets: CSSStyleSheet[] | undefined;\n  if (styles?.length) {\n    sheets = styles.map((style) => {\n      if (typeof style === \"string\") {\n        const sheet = new CSSStyleSheet();\n        sheet.replaceSync(style);\n        return sheet;\n      }\n      return style;\n    });\n  }\n\n  const attrToProp = new Map<string, string>();\n  const observedAttrNames: string[] = [];\n  if (propsSchema) {\n    for (const propName of Object.keys(propsSchema)) {\n      const attrName = attrNameForProp(propName, propsSchema[propName]!);\n      if (attrName !== null) {\n        attrToProp.set(attrName, propName);\n        observedAttrNames.push(attrName);\n      }\n    }\n  }\n\n  const propSignalMap = new WeakMap<\n    HTMLElement,\n    Record<string, Signal<unknown>>\n  >();\n\n  class Component extends HTMLElement {\n    static observedAttributes = observedAttrNames;\n    #dispose: RootDispose | undefined;\n    #clientActionCleanup: (() => void) | undefined;\n    #islandHydrationAccepted = false;\n    #storeRetryScheduled = false;\n\n    constructor() {\n      super();\n      captureCurrentStore(this);\n\n      if (!this.shadowRoot) {\n        const template = this.querySelector(\n          \":scope > template[shadowrootmode]\",\n        ) as HTMLTemplateElement | null;\n        if (template) {\n          const shadow = this.attachShadow({ mode: \"open\" });\n          shadow.appendChild(template.content);\n          template.remove();\n        } else {\n          this.attachShadow({ mode: \"open\" });\n        }\n      }\n\n      if (propsSchema) {\n        const signals: Record<string, Signal<unknown>> = {};\n        for (const propName of Object.keys(propsSchema)) {\n          const def = propsSchema[propName]!;\n          const attrName = attrNameForProp(propName, def);\n          const rawAttr =\n            attrName !== null ? this.getAttribute(attrName) : null;\n          const initialValue =\n            attrName !== null\n              ? coerceValue(def, rawAttr)\n              : getDefaultValue(def);\n          signals[propName] = signal(initialValue);\n        }\n        propSignalMap.set(this, signals);\n      }\n    }\n\n    connectedCallback(): void {\n      const propSignals = propSignalMap.get(this) ?? {};\n      const shadowRoot = this.shadowRoot!;\n      const hasDSD = shadowRoot.childNodes.length > 0;\n      let colocatedStrategy = hasDSD\n        ? getColocatedClientStrategyFromShadowRoot(shadowRoot)\n        : null;\n\n      const hasHostIslandMetadata =\n        this.getAttribute(ISLAND_METADATA_ATTRIBUTE) !== null;\n      const hasHostClientActions =\n        this.getAttribute(CLIENT_ACTIONS_METADATA_ATTRIBUTE) !== null;\n\n      if (colocatedStrategy !== null && hydrateSetup !== undefined) {\n        console.error(\n          \"[dathra] colocated load:on* / interaction:on* / idle:on* / visible:on* cannot be combined with a hydrate option in the same component\",\n        );\n        colocatedStrategy = null;\n      }\n\n      if (colocatedStrategy !== null && hasHostIslandMetadata) {\n        console.error(\n          \"[dathra] host-level client:* directives or data-dh-island metadata cannot be combined with colocated client directives in the same component render subtree\",\n        );\n        colocatedStrategy = null;\n      }\n\n      if (\n        colocatedStrategy !== null &&\n        this.getAttribute(ISLAND_METADATA_ATTRIBUTE) === null\n      ) {\n        this.setAttribute(\n          ISLAND_METADATA_ATTRIBUTE,\n          colocatedStrategy.strategy,\n        );\n        if (colocatedStrategy.value !== null) {\n          this.setAttribute(\n            ISLAND_VALUE_METADATA_ATTRIBUTE,\n            colocatedStrategy.value,\n          );\n        }\n      }\n\n      const rawChildren = this.getAttribute(\"data-dh-children\");\n      let children: unknown;\n      if (rawChildren !== null) {\n        try {\n          children = JSON.parse(rawChildren) as unknown;\n        } catch {\n          children = rawChildren;\n        }\n      } else if (this.childNodes.length > 0) {\n        const parts: string[] = [];\n        for (let i = 0; i < this.childNodes.length; i++) {\n          const node = this.childNodes[i]!;\n          if (\n            node.nodeType === Node.TEXT_NODE ||\n            node.nodeType === Node.ELEMENT_NODE\n          ) {\n            const text = node.textContent;\n            if (text !== null && text.length > 0) parts.push(text);\n          }\n        }\n        if (parts.length > 0) children = parts.join(\"\");\n      }\n\n      const ctx = {\n        host: this,\n        props: propSignals,\n        children,\n        get client() {\n          return createClientContext(this.host);\n        },\n        get store() {\n          return getStoreFromHost(this.host);\n        },\n      } as ComponentContext<S>;\n      const islandStrategy = this.getAttribute(ISLAND_METADATA_ATTRIBUTE);\n      const planFactory =\n        hydrationMetadata?.unsupportedReason === undefined &&\n        typeof hydrationMetadata?.planFactory === \"function\"\n          ? hydrationMetadata.planFactory\n          : null;\n      const shouldDeferIslandHydration =\n        hasDSD &&\n        (hydrateSetup !== undefined ||\n          planFactory !== null ||\n          colocatedStrategy !== null ||\n          hasHostClientActions) &&\n        isKnownIslandStrategy(islandStrategy);\n\n      this.#islandHydrationAccepted = false;\n      this.#clientActionCleanup?.();\n      this.#clientActionCleanup = undefined;\n      (this as Record<PropertyKey, unknown>)[HYDRATE_ISLANDS_HOOK] = undefined;\n      (this as Record<PropertyKey, unknown>)[HYDRATE_ISLANDS_STATUS] =\n        undefined;\n      connectGlobalStyles(shadowRoot, sheets ?? []);\n\n      const retryIfStoreEventuallyBinds = (run: () => void): boolean => {\n        if (\n          peekStoreFromHost(this) !== undefined ||\n          this.#storeRetryScheduled\n        ) {\n          return false;\n        }\n\n        this.#storeRetryScheduled = true;\n        queueMicrotask(() => {\n          this.#storeRetryScheduled = false;\n          if (!this.isConnected || peekStoreFromHost(this) === undefined) {\n            return;\n          }\n\n          run();\n        });\n        return true;\n      };\n\n      const isMissingStoreError = (error: unknown): boolean => {\n        return (\n          error instanceof Error &&\n          error.message === \"[dathra] No store bound to component host\"\n        );\n      };\n\n      const finalizeHostClientActions = (\n        trigger?: IslandHydrationTrigger,\n      ): void => {\n        this.#clientActionCleanup?.();\n        this.#clientActionCleanup = bindHostClientActions(this);\n        replayHostClientAction(this, trigger);\n      };\n\n      const runHydrate = (trigger?: IslandHydrationTrigger): boolean => {\n        try {\n          this.#dispose = createRoot(() => {\n            hydrateSetup!(ctx);\n          });\n          finalizeHostClientActions(trigger);\n          this.#islandHydrationAccepted = true;\n          if (\n            isKnownIslandStrategy(this.getAttribute(ISLAND_METADATA_ATTRIBUTE))\n          ) {\n            (this as Record<PropertyKey, unknown>)[HYDRATE_ISLANDS_STATUS] =\n              \"hydrated\";\n          }\n          return true;\n        } catch (error) {\n          if (\n            isMissingStoreError(error) &&\n            retryIfStoreEventuallyBinds(() => {\n              runHydrate(trigger);\n            })\n          ) {\n            return false;\n          }\n          console.error(\"[dathra] Error in component hydrate:\", error);\n          return false;\n        }\n      };\n\n      const runHydrateWithPlan = (\n        trigger?: IslandHydrationTrigger,\n      ): boolean => {\n        if (planFactory === null) {\n          return false;\n        }\n\n        try {\n          const plan = planFactory(this, ctx) as GenericHydrationPlan;\n          const dispose = hydrateWithPlan(shadowRoot, plan, {\n            store: peekStoreFromHost(this),\n          });\n          if (dispose === null) {\n            return false;\n          }\n          this.#dispose = dispose;\n          this.#islandHydrationAccepted = true;\n          if (\n            isKnownIslandStrategy(this.getAttribute(ISLAND_METADATA_ATTRIBUTE))\n          ) {\n            (this as Record<PropertyKey, unknown>)[HYDRATE_ISLANDS_STATUS] =\n              \"hydrated\";\n          }\n          finalizeHostClientActions(trigger);\n          replayHydrationTrigger(shadowRoot, trigger);\n          return true;\n        } catch (error) {\n          if (\n            isMissingStoreError(error) &&\n            retryIfStoreEventuallyBinds(() => {\n              runHydrateWithPlan(trigger);\n            })\n          ) {\n            return false;\n          }\n          console.error(\n            \"[dathra] Error in compiler-generated hydration plan:\",\n            error,\n          );\n          return false;\n        }\n      };\n\n      const logUnsupportedHydrationReason = (): void => {\n        if (hydrationMetadata?.unsupportedReason === undefined) {\n          return;\n        }\n\n        console.warn(\n          `[dathra] Falling back to setup rerender for <${tagName}> because compiler-generated hydration is unsupported: ${hydrationMetadata.unsupportedReason}`,\n        );\n      };\n\n      const runSetup = (trigger?: IslandHydrationTrigger): boolean => {\n        try {\n          this.#dispose = createRoot(() => {\n            if (hasDSD) {\n              shadowRoot.innerHTML = \"\";\n            }\n            const content = resolvedSetup(this, ctx);\n            shadowRoot.append(buildComponentContent(content as string | Node));\n            finalizeHostClientActions(trigger);\n            replayHydrationTrigger(shadowRoot, trigger);\n          });\n          this.#islandHydrationAccepted = true;\n          if (\n            isKnownIslandStrategy(this.getAttribute(ISLAND_METADATA_ATTRIBUTE))\n          ) {\n            (this as Record<PropertyKey, unknown>)[HYDRATE_ISLANDS_STATUS] =\n              \"hydrated\";\n          }\n          return true;\n        } catch (error) {\n          if (\n            isMissingStoreError(error) &&\n            retryIfStoreEventuallyBinds(() => {\n              runSetup(trigger);\n            })\n          ) {\n            return false;\n          }\n          console.error(\"[dathra] Error in component setup:\", error);\n          return false;\n        }\n      };\n\n      if (hasDSD) {\n        if (this.shadowRoot!.adoptedStyleSheets.length > 0) {\n          const dsdStyles = shadowRoot.querySelectorAll(\"style\");\n          for (const style of dsdStyles) {\n            style.remove();\n          }\n        }\n\n        if (shouldDeferIslandHydration) {\n          (this as Record<PropertyKey, unknown>)[HYDRATE_ISLANDS_STATUS] =\n            \"idle\";\n          (this as Record<PropertyKey, unknown>)[HYDRATE_ISLANDS_HOOK] = (\n            trigger?: IslandHydrationTrigger,\n          ) => {\n            if (!this.isConnected || this.#islandHydrationAccepted) {\n              return false;\n            }\n\n            (this as Record<PropertyKey, unknown>)[HYDRATE_ISLANDS_STATUS] =\n              \"hydrated\";\n            const didHydrate =\n              hydrateSetup !== undefined\n                ? runHydrate(trigger)\n                : planFactory !== null\n                  ? runHydrateWithPlan(trigger)\n                  : runSetup(trigger);\n            if (didHydrate) {\n              (this as Record<PropertyKey, unknown>)[HYDRATE_ISLANDS_STATUS] =\n                \"hydrated\";\n            } else {\n              (this as Record<PropertyKey, unknown>)[HYDRATE_ISLANDS_STATUS] =\n                \"idle\";\n            }\n            return didHydrate;\n          };\n        } else if (hydrateSetup) {\n          runHydrate();\n        } else if (planFactory !== null) {\n          runHydrateWithPlan();\n        } else {\n          logUnsupportedHydrationReason();\n          runSetup();\n        }\n      } else {\n        runSetup();\n      }\n    }\n\n    disconnectedCallback(): void {\n      cancelScheduledIslandHydration(this);\n      this.#dispose?.();\n      this.#dispose = undefined;\n      this.#clientActionCleanup?.();\n      this.#clientActionCleanup = undefined;\n      this.#islandHydrationAccepted = false;\n      (this as Record<PropertyKey, unknown>)[HYDRATE_ISLANDS_HOOK] = undefined;\n      (this as Record<PropertyKey, unknown>)[HYDRATE_ISLANDS_STATUS] =\n        undefined;\n      disconnectGlobalStyles(this.shadowRoot!);\n    }\n\n    attributeChangedCallback(\n      name: string,\n      _oldValue: string | null,\n      newValue: string | null,\n    ): void {\n      const propName = attrToProp.get(name);\n      if (!propName || !propsSchema) return;\n      const def = propsSchema[propName]!;\n      const propSignals = propSignalMap.get(this);\n      const signalValue = propSignals?.[propName];\n      if (signalValue) {\n        try {\n          signalValue.set(coerceValue(def, newValue) as never);\n        } catch (error) {\n          console.error(\"[dathra] Error updating prop signal:\", error);\n        }\n      }\n    }\n  }\n\n  if (propsSchema) {\n    for (const propName of Object.keys(propsSchema)) {\n      Object.defineProperty(Component.prototype, propName, {\n        get(this: HTMLElement) {\n          return propSignalMap.get(this)?.[propName]?.value;\n        },\n        set(this: HTMLElement, newValue: unknown) {\n          propSignalMap.get(this)?.[propName]?.set(newValue as never);\n        },\n        enumerable: true,\n        configurable: true,\n      });\n    }\n  }\n\n  customElements.define(tagName, Component);\n\n  const componentMetadata = Component as typeof Component & {\n    __tagName__?: string;\n    __propsSchema__?: S;\n    __hydrationMetadata__?: ComponentHydrationMetadata;\n  };\n\n  componentMetadata.__tagName__ = tagName;\n  componentMetadata.__propsSchema__ = propsSchema;\n  componentMetadata.__hydrationMetadata__ = hydrationMetadata;\n\n  return createDefinedComponent(\n    Component as unknown as ComponentConstructor<S>,\n    jsx,\n    propsSchema,\n    tagName,\n    hydrationMetadata,\n  );\n}\n\n/**\n * Define a custom element with automatic Shadow DOM, reactive props with\n * type coercion, adoptedStyleSheets, and lifecycle management.\n * Accepts a FunctionComponent that receives reactive prop signals.\n * @param tagName - Custom element tag name (must contain a hyphen).\n * @param component - Function component that creates the component's DOM content.\n * @param options - Optional configuration for styles, props, and hydration.\n * @returns A component definition object containing the custom element class and JSX helper.\n */\nfunction defineComponent<const S extends PropsSchema = EmptyPropsSchema>(\n  tagName: string,\n  component: FunctionComponent<S>,\n  options: ComponentOptions<S> = {},\n): DefinedComponent<S> {\n  const useBrowserRuntime = canUseComponentDOMRuntime();\n  const jsx = createJSXComponent(tagName, options.props, useBrowserRuntime);\n  const hydrationMetadata = (component as unknown as ComponentMetadata<S>)\n    .__hydrationMetadata__;\n  const resolvedSetup: SetupFunction<S> = wrapFunctionComponent(\n    component,\n    options.props,\n  );\n\n  if (!useBrowserRuntime) {\n    return createServerDefinedComponent(\n      tagName,\n      resolvedSetup,\n      options,\n      jsx,\n      hydrationMetadata,\n    );\n  }\n\n  return createClientDefinedComponent(\n    tagName,\n    resolvedSetup,\n    options,\n    jsx,\n    hydrationMetadata,\n  );\n}\n\nexport { defineComponent };\nexport type {\n  ComponentClass,\n  ComponentClientContext,\n  ComponentConstructor,\n  ComponentContext,\n  ComponentElement,\n  ComponentMetadata,\n  ComponentOptions,\n  ComponentHydrationMetadata,\n  DefinedComponent,\n  FunctionComponent,\n  HydrateSetupFunction,\n  InferProps,\n  InferPropType,\n  JSXComponent,\n  JSXComponentProps,\n  JSXProp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