{"version":3,"sources":["../../src/client/lifecycle.ts","../../src/client/runtime-error-overlay.ts","../../src/client/plugin.ts"],"sourcesContent":["\"use client\";\n\nexport { defineClient } from \"./plugin\";\nexport type {\n  FarmClientNavigationAction,\n  FarmClientNavigationErrorEvent,\n  FarmClientNavigationEvent,\n  FarmClientNavigationLoadedEvent,\n  FarmClientNavigationResolvedEvent,\n  FarmClientNavigationSession,\n  FarmClientPlugin,\n  FarmClientPluginCloseEvent,\n  FarmClientPluginRouter,\n  FarmClientPluginSetupEvent,\n  FarmClientPluginStateEvent,\n} from \"./plugin\";\n","\"use client\";\n\nimport {\n  originalPositionFor,\n  sourceContentFor,\n  TraceMap,\n  type SourceMapInput,\n} from \"@jridgewell/trace-mapping\";\nimport { DEFAULT_ERROR_STYLES } from \"../components/error-styles\";\nimport { FARM_VERSION } from \"../version\";\nimport { isChunkLoadError } from \"./chunk-recovery\";\n\nexport interface FarmRuntimeErrorLocation {\n  href: string;\n  pathname: string;\n  search: string;\n  hash: string;\n}\n\nexport interface FarmRuntimeErrorOverlayContext {\n  phase: string;\n  location: FarmRuntimeErrorLocation;\n  sourceEvent?: Event;\n}\n\nexport interface FarmRuntimeErrorOverlayOptions {\n  window: Window;\n  farmVersion?: string;\n  reload?: () => void;\n  fetch?: typeof fetch;\n}\n\nexport interface FarmRuntimeErrorOverlay {\n  show(error: unknown, context: FarmRuntimeErrorOverlayContext): void;\n  dismiss(): void;\n  destroy(): void;\n}\n\ninterface NormalizedRuntimeError {\n  name: string;\n  message: string;\n  stack?: string;\n}\n\ninterface BrowserSourceLocation {\n  url: string;\n  displayPath: string;\n  line: number;\n  column: number;\n  stackLine?: string;\n}\n\ninterface BrowserSourceLine {\n  number?: number;\n  content: string;\n  highlight?: boolean;\n}\n\ninterface BrowserSourceFrame {\n  path: string;\n  line?: number;\n  column?: number;\n  lines: BrowserSourceLine[];\n  unavailable?: boolean;\n}\n\ninterface RuntimeErrorRecord {\n  error: NormalizedRuntimeError;\n  context: FarmRuntimeErrorOverlayContext;\n  fingerprint: string;\n  occurrences: number;\n  sourceLocation?: BrowserSourceLocation;\n  sourceFrame: BrowserSourceFrame;\n}\n\nconst OVERLAY_STYLES = `\n:host {\n  position: fixed;\n  inset: 0;\n  z-index: 2147483647;\n  display: block;\n  width: 100%;\n  height: 100%;\n  /* Owned by the overlay: the default error page's source marker is a neutral\n     accent, but the overlay uses this to mark the expression that threw. */\n  --farm-runtime-error-inline-code: #f87171;\n}\n\n@media (prefers-color-scheme: light) {\n  :host {\n    --farm-runtime-error-inline-code: #b91c1c;\n  }\n}\n\n:host([hidden]) {\n  display: none;\n}\n\n.farm-runtime-error__viewport {\n  width: 100%;\n  height: 100%;\n  overflow: auto;\n  overscroll-behavior: contain;\n}\n\n.farm-runtime-error__viewport .farm-default-error {\n  min-height: 100%;\n  padding: clamp(22px, 4vh, 36px) 24px;\n}\n\n.farm-runtime-error__viewport .farm-default-error__code {\n  font-size: clamp(96px, 10vw, 120px);\n  line-height: 0.92;\n}\n\n.farm-runtime-error__viewport .farm-default-error__eyebrow {\n  margin-top: 22px;\n  margin-bottom: 18px;\n}\n\n.farm-runtime-error__viewport .farm-default-error__summary {\n  margin-bottom: 20px;\n}\n\n.farm-runtime-error__viewport .farm-default-error__row {\n  min-height: 48px;\n}\n\n.farm-runtime-error__viewport .farm-default-error__details {\n  padding-top: 16px;\n  padding-bottom: 14px;\n}\n\n.farm-runtime-error__viewport .farm-default-error__details-header {\n  margin-bottom: 8px;\n}\n\n.farm-runtime-error__viewport .farm-default-error__source-path {\n  padding-top: 9px;\n  padding-bottom: 9px;\n}\n\n.farm-runtime-error__viewport .farm-default-error__source-code {\n  padding-top: 6px;\n  padding-bottom: 6px;\n}\n\n.farm-runtime-error__viewport .farm-default-error__meta {\n  margin-top: 10px;\n}\n\n.farm-runtime-error__viewport .farm-default-error__actions {\n  margin-top: 20px;\n}\n\n.farm-runtime-error__occurrences {\n  display: inline-flex;\n  align-items: center;\n  min-height: 24px;\n  margin-right: auto;\n  padding: 0 8px;\n  border: 1px solid var(--farm-error-line);\n  color: var(--farm-error-muted);\n  font-family: var(--farm-error-font-mono);\n  font-size: 10px;\n  font-weight: 600;\n  letter-spacing: 0.08em;\n  text-transform: uppercase;\n}\n\n.farm-runtime-error__occurrences[hidden],\n.farm-runtime-error__action[hidden] {\n  display: none;\n}\n\n.farm-runtime-error__copy {\n  min-width: 166px;\n}\n\n.farm-runtime-error__action:focus {\n  outline: 1px solid var(--farm-error-fg);\n  outline-offset: 2px;\n}\n\n.farm-runtime-error__viewport .farm-default-error__panel {\n  border: 0;\n  box-shadow: inset 0 0 0 0.5px var(--farm-error-line-strong);\n}\n\n.farm-runtime-error__github-icon {\n  display: block;\n  width: 18px;\n  height: 18px;\n  flex: 0 0 auto;\n  margin-right: 10px;\n  color: currentColor;\n}\n\n.farm-runtime-error__message-value {\n  font-family: var(--farm-error-font-sans);\n}\n\n.farm-runtime-error__inline-code {\n  color: var(--farm-runtime-error-inline-code);\n  font-family: var(--farm-error-font-mono);\n  font-size: 0.94em;\n  font-weight: 600;\n  line-height: inherit;\n  overflow-wrap: anywhere;\n}\n\n@media (max-width: 620px) {\n  .farm-runtime-error__occurrences {\n    margin-right: 0;\n  }\n\n  .farm-runtime-error__viewport .farm-default-error__content,\n  .farm-runtime-error__viewport .farm-default-error__panel,\n  .farm-runtime-error__viewport .farm-default-error__details,\n  .farm-runtime-error__viewport .farm-default-error__source,\n  .farm-runtime-error__viewport .farm-default-error__actions {\n    min-width: 0;\n    max-width: 100%;\n  }\n\n  .farm-runtime-error__viewport .farm-default-error__actions {\n    width: 100%;\n  }\n\n  .farm-runtime-error__viewport .farm-default-error__action {\n    min-width: 0;\n  }\n\n  .farm-runtime-error__viewport .farm-default-error__code {\n    font-size: 80px;\n  }\n}\n\n@media (max-height: 760px) {\n  .farm-runtime-error__viewport .farm-default-error {\n    place-items: start center;\n    padding-top: 12px;\n    padding-bottom: 12px;\n  }\n\n  .farm-runtime-error__viewport .farm-default-error__code {\n    font-size: 88px;\n  }\n\n  .farm-runtime-error__viewport .farm-default-error__eyebrow {\n    margin-top: 14px;\n    margin-bottom: 12px;\n  }\n\n  .farm-runtime-error__viewport .farm-default-error__summary {\n    margin-bottom: 14px;\n  }\n\n  .farm-runtime-error__viewport .farm-default-error__row {\n    min-height: 42px;\n  }\n\n  .farm-runtime-error__viewport .farm-default-error__details {\n    padding-top: 12px;\n    padding-bottom: 10px;\n  }\n\n  .farm-runtime-error__viewport .farm-default-error__actions {\n    /* The redesigned page is taller than a short window. Rather than shrink it\n       until it is unreadable, keep the recovery controls pinned to the bottom\n       so they stay reachable while the rest of the report scrolls under them. */\n    position: sticky;\n    bottom: 0;\n    z-index: 1;\n    margin-top: 10px;\n    padding: 10px 0;\n    background: var(--farm-error-bg);\n  }\n}\n`;\n\nconst OVERLAY_MARKUP = `\n<div class=\"farm-runtime-error__viewport\" data-farm-runtime-error-viewport>\n  <main class=\"farm-default-error\" data-farm-runtime-error role=\"alertdialog\" aria-modal=\"true\" aria-labelledby=\"farm-runtime-error-title\" aria-describedby=\"farm-runtime-error-description\">\n    <div class=\"farm-default-error__content\">\n      <p class=\"farm-default-error__code\" aria-hidden=\"true\">500</p>\n      <p class=\"farm-default-error__eyebrow\">Runtime error</p>\n      <header class=\"farm-default-error__summary\">\n        <h1 id=\"farm-runtime-error-title\" class=\"farm-default-error__title\">Application failed in the browser</h1>\n      </header>\n      <section class=\"farm-default-error__panel\" aria-label=\"Error information\">\n        <div class=\"farm-default-error__row\">\n          <span class=\"farm-default-error__label\">Error type</span>\n          <span class=\"farm-default-error__value\" data-farm-runtime-error-type></span>\n        </div>\n        <div class=\"farm-default-error__row\">\n          <span class=\"farm-default-error__label\">Error message</span>\n          <span id=\"farm-runtime-error-description\" class=\"farm-default-error__value farm-runtime-error__message-value\" data-farm-runtime-error-message></span>\n        </div>\n        <div class=\"farm-default-error__row\">\n          <span class=\"farm-default-error__label\">Location</span>\n          <span class=\"farm-default-error__value\" data-farm-runtime-error-location></span>\n        </div>\n        <section class=\"farm-default-error__details\" aria-labelledby=\"farm-runtime-error-details-title\">\n          <div class=\"farm-default-error__details-header\">\n            <h2 id=\"farm-runtime-error-details-title\" class=\"farm-default-error__details-title\">Details</h2>\n            <span class=\"farm-runtime-error__occurrences\" data-farm-runtime-error-occurrences hidden></span>\n            <button class=\"farm-default-error__copy farm-runtime-error__copy\" type=\"button\" data-farm-runtime-error-copy>\n              <span data-farm-runtime-error-copy-label>Copy debug report</span>\n              <span class=\"farm-default-error__sr-only\" aria-live=\"polite\" data-farm-runtime-error-copy-status></span>\n            </button>\n          </div>\n          <div data-farm-runtime-error-source></div>\n          <p class=\"farm-default-error__meta\" data-farm-runtime-error-meta></p>\n        </section>\n      </section>\n      <div class=\"farm-default-error__actions\">\n        <a class=\"farm-default-error__action farm-default-error__action--primary farm-runtime-error__action\" data-farm-runtime-error-issue target=\"_blank\" rel=\"noopener noreferrer\"><svg class=\"farm-runtime-error__github-icon\" viewBox=\"0 0 24 24\" fill=\"currentColor\" aria-hidden=\"true\" focusable=\"false\"><path d=\"M12 .7a11.5 11.5 0 0 0-3.64 22.41c.58.1.79-.25.79-.56v-2.23c-3.22.7-3.9-1.37-3.9-1.37-.52-1.34-1.28-1.69-1.28-1.69-1.05-.72.08-.7.08-.7 1.16.08 1.77 1.19 1.77 1.19 1.03 1.77 2.7 1.26 3.36.96.1-.75.4-1.26.73-1.55-2.57-.29-5.27-1.29-5.27-5.68 0-1.26.45-2.28 1.18-3.09-.12-.29-.51-1.47.11-3.05 0 0 .96-.31 3.16 1.18A10.95 10.95 0 0 1 12 6.1c.98 0 1.95.13 2.87.39 2.2-1.49 3.16-1.18 3.16-1.18.62 1.58.23 2.76.11 3.05.74.81 1.18 1.83 1.18 3.09 0 4.4-2.71 5.38-5.29 5.67.42.36.79 1.07.79 2.16v3.27c0 .31.21.67.8.56A11.5 11.5 0 0 0 12 .7Z\" /></svg><span>Open GitHub issue</span></a>\n        <button class=\"farm-default-error__action farm-runtime-error__action\" type=\"button\" data-farm-runtime-error-reload>Reload page</button>\n        <button class=\"farm-default-error__action farm-runtime-error__action\" type=\"button\" data-farm-runtime-error-dismiss>Dismiss</button>\n      </div>\n    </div>\n  </main>\n</div>\n`;\n\nclass DefaultFarmRuntimeErrorOverlay implements FarmRuntimeErrorOverlay {\n  private readonly options: FarmRuntimeErrorOverlayOptions;\n  private readonly document: Document;\n  private readonly host: HTMLDivElement;\n  private readonly shadow: ShadowRoot;\n  private readonly dismissedFingerprints = new Set<string>();\n  private readonly themeObserver: MutationObserver;\n  private readonly colorSchemeQuery?: MediaQueryList;\n  private current?: RuntimeErrorRecord;\n  private previousFocus?: Element | null;\n  private renderSequence = 0;\n  private copyResetTimer?: number;\n  private destroyed = false;\n\n  constructor(options: FarmRuntimeErrorOverlayOptions) {\n    this.options = options;\n    this.document = options.window.document;\n    this.host = this.document.createElement(\"div\");\n    this.host.dataset.farmRuntimeErrorOverlay = \"\";\n    this.host.hidden = true;\n    this.shadow = this.host.attachShadow({ mode: \"open\" });\n    this.shadow.innerHTML = `<style>${DEFAULT_ERROR_STYLES}${OVERLAY_STYLES}</style>${OVERLAY_MARKUP}`;\n\n    this.getElement<HTMLButtonElement>(\"[data-farm-runtime-error-reload]\").addEventListener(\n      \"click\",\n      this.handleReload,\n    );\n    this.getElement<HTMLButtonElement>(\"[data-farm-runtime-error-dismiss]\").addEventListener(\n      \"click\",\n      this.handleDismiss,\n    );\n    this.getElement<HTMLButtonElement>(\"[data-farm-runtime-error-copy]\").addEventListener(\n      \"click\",\n      this.handleCopy,\n    );\n    this.shadow.addEventListener(\"keydown\", this.handleKeyDown);\n\n    this.themeObserver = new MutationObserver(this.updateTheme);\n    this.themeObserver.observe(this.document.documentElement, {\n      attributes: true,\n      attributeFilter: [\"class\", \"data-theme\", \"data-color-scheme\", \"style\"],\n    });\n    if (this.document.body) {\n      this.themeObserver.observe(this.document.body, {\n        attributes: true,\n        attributeFilter: [\"class\", \"data-theme\", \"data-color-scheme\", \"style\"],\n      });\n    }\n\n    this.colorSchemeQuery = options.window.matchMedia?.(\"(prefers-color-scheme: dark)\");\n    this.colorSchemeQuery?.addEventListener?.(\"change\", this.updateTheme);\n    this.updateTheme();\n  }\n\n  show(errorLike: unknown, context: FarmRuntimeErrorOverlayContext): void {\n    if (this.destroyed || isChunkLoadError(errorLike) || isChunkLoadError(context.sourceEvent)) {\n      return;\n    }\n\n    const error = normalizeRuntimeError(errorLike);\n    const sourceLocation = resolveBrowserSourceLocation(\n      error,\n      context.sourceEvent,\n      this.options.window,\n    );\n    if (sourceLocation && isBrowserExtensionUrl(sourceLocation.url)) return;\n    if (isRecoverableReactHydrationError(error, context, sourceLocation)) return;\n\n    const fingerprint = createErrorFingerprint(error, context, sourceLocation);\n    if (this.dismissedFingerprints.has(fingerprint)) return;\n\n    if (this.current?.fingerprint === fingerprint) {\n      this.current.occurrences += 1;\n      this.renderOccurrences(this.current.occurrences);\n      return;\n    }\n\n    const record: RuntimeErrorRecord = {\n      error,\n      context,\n      fingerprint,\n      occurrences: 1,\n      sourceLocation,\n      sourceFrame: createFallbackSourceFrame(error, sourceLocation),\n    };\n    this.current = record;\n    const sequence = ++this.renderSequence;\n    this.render(record);\n    this.mount();\n\n    if (sourceLocation) {\n      void loadBrowserSourceFrame(sourceLocation, this.options)\n        .then((sourceFrame) => {\n          if (\n            !sourceFrame ||\n            this.destroyed ||\n            sequence !== this.renderSequence ||\n            this.current !== record\n          ) {\n            return;\n          }\n          record.sourceFrame = sourceFrame;\n          this.renderSourceFrame(sourceFrame);\n          this.renderIssueLink(record);\n        })\n        .catch(() => {});\n    }\n  }\n\n  dismiss(): void {\n    if (this.destroyed || this.host.hidden) return;\n    if (this.current) this.dismissedFingerprints.add(this.current.fingerprint);\n    this.host.hidden = true;\n    this.renderSequence += 1;\n    if (this.previousFocus instanceof HTMLElement && this.previousFocus.isConnected) {\n      this.previousFocus.focus();\n    }\n    this.previousFocus = undefined;\n  }\n\n  destroy(): void {\n    if (this.destroyed) return;\n    this.destroyed = true;\n    this.renderSequence += 1;\n    this.themeObserver.disconnect();\n    this.colorSchemeQuery?.removeEventListener?.(\"change\", this.updateTheme);\n    this.shadow.removeEventListener(\"keydown\", this.handleKeyDown);\n    if (this.copyResetTimer !== undefined) {\n      this.options.window.clearTimeout(this.copyResetTimer);\n    }\n    this.host.remove();\n    this.current = undefined;\n  }\n\n  private mount(): void {\n    if (!this.host.isConnected) {\n      (this.document.body || this.document.documentElement).appendChild(this.host);\n    }\n    const wasHidden = this.host.hidden;\n    this.host.hidden = false;\n    if (wasHidden) {\n      this.previousFocus = this.document.activeElement;\n      this.options.window.setTimeout(() => {\n        if (!this.host.hidden && !this.destroyed) {\n          this.getElement<HTMLAnchorElement>(\"[data-farm-runtime-error-issue]\").focus({\n            preventScroll: true,\n          });\n        }\n      }, 0);\n    }\n  }\n\n  private render(record: RuntimeErrorRecord): void {\n    this.getElement(\"[data-farm-runtime-error-type]\").textContent = formatErrorType(\n      record.error,\n      record.context.phase,\n    );\n    renderErrorMessage(\n      this.getElement(\"[data-farm-runtime-error-message]\"),\n      record.error.message,\n      this.document,\n    );\n    this.getElement(\"[data-farm-runtime-error-location]\").textContent =\n      `${record.context.location.pathname}${record.context.location.search}` || \"/\";\n    this.getElement(\"[data-farm-runtime-error-meta]\").textContent =\n      `Farm.js v${this.options.farmVersion || FARM_VERSION} · development · browser`;\n    this.renderIssueLink(record);\n    this.renderOccurrences(record.occurrences);\n    this.renderSourceFrame(record.sourceFrame);\n    this.resetCopyStatus();\n  }\n\n  private renderOccurrences(occurrences: number): void {\n    const badge = this.getElement<HTMLElement>(\"[data-farm-runtime-error-occurrences]\");\n    badge.hidden = occurrences < 2;\n    badge.textContent = occurrences < 2 ? \"\" : `Repeated ×${occurrences}`;\n  }\n\n  private renderIssueLink(record: RuntimeErrorRecord): void {\n    this.getElement<HTMLAnchorElement>(\"[data-farm-runtime-error-issue]\").href =\n      createGithubIssueUrl(record, this.options.window, this.options.farmVersion || FARM_VERSION);\n  }\n\n  private renderSourceFrame(sourceFrame: BrowserSourceFrame): void {\n    const container = this.getElement<HTMLElement>(\"[data-farm-runtime-error-source]\");\n    container.replaceChildren();\n\n    const source = this.document.createElement(\"div\");\n    source.className = \"farm-default-error__source\";\n\n    const path = this.document.createElement(\"p\");\n    path.className = \"farm-default-error__source-path\";\n    path.textContent = formatSourcePath(sourceFrame);\n    source.appendChild(path);\n\n    const pre = this.document.createElement(\"pre\");\n    pre.className = \"farm-default-error__source-code\";\n    pre.tabIndex = 0;\n    const code = this.document.createElement(\"code\");\n    for (const line of sourceFrame.lines) {\n      const row = this.document.createElement(\"span\");\n      row.className = `farm-default-error__source-line${line.highlight ? \" farm-default-error__source-line--active\" : \"\"}`;\n\n      const gutter = this.document.createElement(\"span\");\n      gutter.className = \"farm-default-error__source-gutter\";\n      gutter.textContent = `${line.highlight ? \">\" : \" \"} ${line.number ?? \"\"}`;\n\n      const text = this.document.createElement(\"span\");\n      text.className = \"farm-default-error__source-text\";\n      text.textContent = line.content || \" \";\n\n      row.append(gutter, text);\n      code.appendChild(row);\n    }\n    pre.appendChild(code);\n    source.appendChild(pre);\n    container.appendChild(source);\n  }\n\n  private readonly handleReload = () => {\n    (this.options.reload || (() => this.options.window.location.reload()))();\n  };\n\n  private readonly handleDismiss = () => {\n    this.dismiss();\n  };\n\n  private readonly handleCopy = async () => {\n    if (!this.current) return;\n    const report = createFarmRuntimeErrorDebugReport(\n      this.current,\n      this.options.window,\n      this.options.farmVersion || FARM_VERSION,\n    );\n    const label = this.getElement<HTMLElement>(\"[data-farm-runtime-error-copy-label]\");\n    const status = this.getElement<HTMLElement>(\"[data-farm-runtime-error-copy-status]\");\n\n    try {\n      await copyText(report, this.options.window, this.document);\n      label.textContent = \"Copied\";\n      status.textContent = \"Debug report copied\";\n      if (this.copyResetTimer !== undefined) {\n        this.options.window.clearTimeout(this.copyResetTimer);\n      }\n      this.copyResetTimer = this.options.window.setTimeout(() => this.resetCopyStatus(), 1800);\n    } catch {\n      status.textContent = \"Unable to copy the debug report\";\n    }\n  };\n\n  private readonly handleKeyDown = (event: Event) => {\n    const keyboardEvent = event as KeyboardEvent;\n    if (keyboardEvent.key === \"Escape\") {\n      keyboardEvent.preventDefault();\n      this.dismiss();\n      return;\n    }\n    if (keyboardEvent.key !== \"Tab\") return;\n\n    const controls = Array.from(\n      this.shadow.querySelectorAll<HTMLElement>(\"a[href], button:not([hidden]):not([disabled])\"),\n    );\n    if (controls.length === 0) return;\n    const first = controls[0];\n    const last = controls[controls.length - 1];\n    const active = this.shadow.activeElement;\n\n    if (keyboardEvent.shiftKey && active === first) {\n      keyboardEvent.preventDefault();\n      last.focus();\n    } else if (!keyboardEvent.shiftKey && active === last) {\n      keyboardEvent.preventDefault();\n      first.focus();\n    }\n  };\n\n  private readonly updateTheme = () => {\n    this.getElement<HTMLElement>(\"[data-farm-runtime-error-viewport]\").dataset.theme =\n      resolveDocumentTheme(this.document, this.options.window);\n  };\n\n  private resetCopyStatus(): void {\n    this.getElement(\"[data-farm-runtime-error-copy-label]\").textContent = \"Copy debug report\";\n    this.getElement(\"[data-farm-runtime-error-copy-status]\").textContent = \"\";\n  }\n\n  private getElement<T extends Element = HTMLElement>(selector: string): T {\n    const element = this.shadow.querySelector<T>(selector);\n    if (!element) throw new Error(`Farm runtime error overlay is missing ${selector}`);\n    return element;\n  }\n}\n\nexport function createFarmRuntimeErrorOverlay(\n  options: FarmRuntimeErrorOverlayOptions,\n): FarmRuntimeErrorOverlay {\n  return new DefaultFarmRuntimeErrorOverlay(options);\n}\n\nfunction normalizeRuntimeError(errorLike: unknown): NormalizedRuntimeError {\n  if (errorLike instanceof Error) {\n    return {\n      name: errorLike.name || \"Error\",\n      message: errorLike.message || \"An unknown browser error occurred.\",\n      stack: errorLike.stack,\n    };\n  }\n\n  if (errorLike && typeof errorLike === \"object\") {\n    const error = errorLike as Record<string, unknown>;\n    const name = typeof error.name === \"string\" && error.name ? error.name : \"Error\";\n    const message =\n      typeof error.message === \"string\" && error.message\n        ? error.message\n        : typeof error.reason === \"string\" && error.reason\n          ? error.reason\n          : stringifyUnknown(errorLike);\n    return {\n      name,\n      message: message || \"An unknown browser error occurred.\",\n      stack: typeof error.stack === \"string\" ? error.stack : undefined,\n    };\n  }\n\n  return {\n    name: \"Error\",\n    message: stringifyUnknown(errorLike) || \"An unknown browser error occurred.\",\n  };\n}\n\nfunction stringifyUnknown(value: unknown): string {\n  if (typeof value === \"string\") return value;\n  if (value == null) return \"\";\n  try {\n    return JSON.stringify(value);\n  } catch {\n    return String(value);\n  }\n}\n\nfunction resolveBrowserSourceLocation(\n  error: NormalizedRuntimeError,\n  sourceEvent: Event | undefined,\n  clientWindow: Window,\n): BrowserSourceLocation | undefined {\n  if (sourceEvent && \"filename\" in sourceEvent) {\n    const event = sourceEvent as ErrorEvent;\n    if (event.filename && event.lineno) {\n      return createSourceLocation(event.filename, event.lineno, event.colno || 1, clientWindow);\n    }\n  }\n\n  if (!error.stack) return undefined;\n  for (const stackLine of error.stack.split(\"\\n\").slice(1)) {\n    const match = stackLine\n      .trim()\n      .match(/\\(?((?:[a-z][a-z\\d+.-]*):\\/\\/[^)\\s]+|\\/[^)\\s]+):(\\d+):(\\d+)\\)?$/i);\n    if (!match) continue;\n    return {\n      ...createSourceLocation(match[1], Number(match[2]), Number(match[3]), clientWindow),\n      stackLine: stackLine.trim(),\n    };\n  }\n  return undefined;\n}\n\nfunction createSourceLocation(\n  url: string,\n  line: number,\n  column: number,\n  clientWindow: Window,\n): BrowserSourceLocation {\n  let displayPath = url;\n  try {\n    const parsed = new URL(url, clientWindow.location.href);\n    displayPath = parsed.origin === clientWindow.location.origin ? parsed.pathname : parsed.href;\n  } catch {}\n\n  return { url, displayPath, line, column };\n}\n\nfunction createFallbackSourceFrame(\n  error: NormalizedRuntimeError,\n  location?: BrowserSourceLocation,\n): BrowserSourceFrame {\n  const firstStackLine =\n    location?.stackLine || error.stack?.split(\"\\n\").find((line) => line.trim().startsWith(\"at \"));\n  return {\n    path: location?.displayPath || \"Browser stack\",\n    line: location?.line,\n    column: location?.column,\n    unavailable: true,\n    lines: [\n      {\n        number: location?.line,\n        content: firstStackLine?.trim() || error.message,\n        highlight: true,\n      },\n    ],\n  };\n}\n\nasync function loadBrowserSourceFrame(\n  location: BrowserSourceLocation,\n  options: FarmRuntimeErrorOverlayOptions,\n): Promise<BrowserSourceFrame | undefined> {\n  const request = options.fetch || options.window.fetch?.bind(options.window);\n  if (!request) return undefined;\n\n  let sourceUrl: URL;\n  try {\n    sourceUrl = new URL(location.url, options.window.location.href);\n  } catch {\n    return undefined;\n  }\n  if (\n    sourceUrl.origin !== options.window.location.origin ||\n    (sourceUrl.protocol !== \"http:\" && sourceUrl.protocol !== \"https:\")\n  ) {\n    return undefined;\n  }\n\n  try {\n    const response = await request(sourceUrl.href, {\n      headers: { Accept: \"text/plain, application/javascript\" },\n    });\n    if (!response.ok) return undefined;\n    const source = await response.text();\n    if (source.length > 1_000_000) return undefined;\n\n    const mappedFrame = await createMappedSourceFrame(\n      source,\n      sourceUrl,\n      location,\n      request,\n      options.window,\n    );\n    if (mappedFrame) return mappedFrame;\n\n    return createSourceFrame(source, location.displayPath, location.line, location.column);\n  } catch {\n    return undefined;\n  }\n}\n\nasync function createMappedSourceFrame(\n  generatedSource: string,\n  generatedUrl: URL,\n  location: BrowserSourceLocation,\n  request: typeof fetch,\n  clientWindow: Window,\n): Promise<BrowserSourceFrame | undefined> {\n  const traceMap = await loadTraceMap(generatedSource, generatedUrl, request, clientWindow);\n  if (!traceMap) return undefined;\n\n  const original = originalPositionFor(traceMap, {\n    line: location.line,\n    column: Math.max(0, location.column - 1),\n  });\n  if (!original.source || original.line == null) return undefined;\n\n  const originalSource = sourceContentFor(traceMap, original.source);\n  if (originalSource == null) return undefined;\n\n  const originalLines = originalSource.split(/\\r?\\n/);\n  const generatedLine = generatedSource.split(/\\r?\\n/)[location.line - 1] || \"\";\n  const line = refineOriginalLine(generatedLine, originalLines, original.line);\n  const lineContent = originalLines[line - 1] || \"\";\n  const trimmedGeneratedLine = generatedLine.trim();\n  const column =\n    line !== original.line && trimmedGeneratedLine && lineContent.includes(trimmedGeneratedLine)\n      ? lineContent.indexOf(trimmedGeneratedLine) + 1\n      : (original.column ?? 0) + 1;\n\n  return createSourceFrame(\n    originalSource,\n    formatDisplaySourceUrl(original.source, clientWindow),\n    line,\n    column,\n  );\n}\n\nasync function loadTraceMap(\n  generatedSource: string,\n  generatedUrl: URL,\n  request: typeof fetch,\n  clientWindow: Window,\n): Promise<TraceMap | undefined> {\n  const matches = Array.from(generatedSource.matchAll(/\\/\\/[#@]\\s*sourceMappingURL=([^\\s]+)/g));\n  const reference = matches[matches.length - 1]?.[1];\n  if (!reference) return undefined;\n\n  let sourceMapJson: string;\n  if (reference.startsWith(\"data:\")) {\n    sourceMapJson = decodeSourceMapDataUrl(reference, clientWindow);\n  } else {\n    const sourceMapUrl = new URL(reference, generatedUrl);\n    if (sourceMapUrl.origin !== clientWindow.location.origin) return undefined;\n    const response = await request(sourceMapUrl.href, {\n      headers: { Accept: \"application/json, text/plain\" },\n    });\n    if (!response.ok) return undefined;\n    sourceMapJson = await response.text();\n    if (sourceMapJson.length > 2_000_000) return undefined;\n  }\n\n  return new TraceMap(JSON.parse(sourceMapJson) as SourceMapInput, generatedUrl.href);\n}\n\nfunction decodeSourceMapDataUrl(value: string, clientWindow: Window): string {\n  const separator = value.indexOf(\",\");\n  if (separator < 0) throw new Error(\"Invalid inline source map\");\n  const metadata = value.slice(0, separator);\n  const payload = value.slice(separator + 1);\n  if (!metadata.includes(\";base64\")) return decodeURIComponent(payload);\n\n  const binary = clientWindow.atob(payload);\n  const bytes = new Uint8Array(binary.length);\n  for (let index = 0; index < binary.length; index += 1) {\n    bytes[index] = binary.charCodeAt(index);\n  }\n  return new TextDecoder().decode(bytes);\n}\n\nfunction refineOriginalLine(\n  generatedLine: string,\n  originalLines: string[],\n  mappedLine: number,\n): number {\n  const normalizedGeneratedLine = normalizeSourceLine(generatedLine);\n  if (normalizedGeneratedLine.length < 8) return mappedLine;\n\n  let bestMatch = mappedLine;\n  let bestDistance = Number.POSITIVE_INFINITY;\n  for (let index = 0; index < originalLines.length; index += 1) {\n    if (normalizeSourceLine(originalLines[index]) !== normalizedGeneratedLine) continue;\n    const line = index + 1;\n    const distance = Math.abs(line - mappedLine);\n    if (distance < bestDistance) {\n      bestMatch = line;\n      bestDistance = distance;\n    }\n  }\n  return bestMatch;\n}\n\nfunction normalizeSourceLine(value: string): string {\n  return value.trim().replace(/\\s+/g, \" \");\n}\n\nfunction createSourceFrame(\n  source: string,\n  path: string,\n  line: number,\n  column: number,\n): BrowserSourceFrame | undefined {\n  const lines = source.split(/\\r?\\n/);\n  if (line < 1 || line > lines.length) return undefined;\n  const start = Math.max(1, line - 2);\n  const end = Math.min(lines.length, line + 2);\n  const frameLines: BrowserSourceLine[] = [];\n  for (let number = start; number <= end; number += 1) {\n    frameLines.push({\n      number,\n      content: lines[number - 1] || \" \",\n      highlight: number === line,\n    });\n  }\n\n  return { path, line, column, lines: frameLines };\n}\n\nfunction formatDisplaySourceUrl(url: string, clientWindow: Window): string {\n  try {\n    const parsed = new URL(url, clientWindow.location.href);\n    return parsed.origin === clientWindow.location.origin ? parsed.pathname : parsed.href;\n  } catch {\n    return url.replace(/[?#].*$/, \"\");\n  }\n}\n\nfunction isBrowserExtensionUrl(url: string): boolean {\n  try {\n    return [\n      \"chrome-extension:\",\n      \"moz-extension:\",\n      \"safari-web-extension:\",\n      \"ms-browser-extension:\",\n    ].includes(new URL(url).protocol);\n  } catch {\n    return /^(?:chrome|moz|safari-web|ms-browser)-extension:\\/\\//i.test(url);\n  }\n}\n\nfunction isRecoverableReactHydrationError(\n  error: NormalizedRuntimeError,\n  context: FarmRuntimeErrorOverlayContext,\n  location?: BrowserSourceLocation,\n): boolean {\n  if (context.phase !== \"window\") return false;\n\n  const isKnownRecoverableMessage = [\n    /^Hydration failed because the server rendered (?:text|HTML) didn't match the client\\b/i,\n    /^Text content does not match server-rendered HTML\\b/i,\n    /^There was an error while hydrating but React was able to recover\\b/i,\n  ].some((pattern) => pattern.test(error.message));\n  if (!isKnownRecoverableMessage) return false;\n\n  return /(?:react-dom(?:_client)?(?:\\.development)?\\.js|react-dom\\/|throwOnHydrationMismatch|onRecoverableError)/i.test(\n    `${location?.url || \"\"}\\n${error.stack || \"\"}`,\n  );\n}\n\nfunction renderErrorMessage(container: Element, message: string, document: Document): void {\n  const fragments: Node[] = [];\n  const codePattern = /`([^`\\n]+)`|\\b[A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*){2,}\\b/g;\n  let offset = 0;\n\n  for (const match of message.matchAll(codePattern)) {\n    const index = match.index ?? 0;\n    if (index > offset) fragments.push(document.createTextNode(message.slice(offset, index)));\n\n    const code = document.createElement(\"code\");\n    code.className = \"farm-runtime-error__inline-code\";\n    code.textContent = match[1] || match[0];\n    fragments.push(code);\n    offset = index + match[0].length;\n  }\n\n  if (offset < message.length) fragments.push(document.createTextNode(message.slice(offset)));\n  container.replaceChildren(...fragments);\n}\n\nfunction createErrorFingerprint(\n  error: NormalizedRuntimeError,\n  context: FarmRuntimeErrorOverlayContext,\n  location?: BrowserSourceLocation,\n): string {\n  return [\n    context.phase,\n    context.location.pathname,\n    error.name,\n    error.message,\n    location?.displayPath || \"\",\n    location?.line || \"\",\n    error.stack?.split(\"\\n\")[1]?.trim() || \"\",\n  ].join(\"\\u0000\");\n}\n\nfunction formatPhase(phase: string): string {\n  return phase\n    .replace(/^plugin:/, \"Plugin · \")\n    .replace(/-/g, \" \")\n    .replace(/\\b\\w/g, (character) => character.toUpperCase());\n}\n\nfunction formatErrorType(error: NormalizedRuntimeError, phase: string): string {\n  const category =\n    phase === \"hydration\"\n      ? \"Hydration\"\n      : phase === \"navigation\"\n        ? \"Navigation\"\n        : phase === \"setup\" || phase.startsWith(\"plugin:\")\n          ? \"Plugin\"\n          : phase === \"performance\"\n            ? \"Performance\"\n            : \"Runtime\";\n  const name = error.name.trim() || \"Error\";\n  return `${category} ${name}`;\n}\n\nfunction formatSourcePath(sourceFrame: BrowserSourceFrame): string {\n  if (!sourceFrame.line) return sourceFrame.path;\n  return `${sourceFrame.path}:${sourceFrame.line}:${sourceFrame.column || 1}${\n    sourceFrame.unavailable ? \" · source preview unavailable\" : \"\"\n  }`;\n}\n\nfunction resolveDocumentTheme(document: Document, clientWindow: Window): \"light\" | \"dark\" {\n  for (const element of [document.documentElement, document.body]) {\n    if (!element) continue;\n    const explicit =\n      element.getAttribute(\"data-theme\") || element.getAttribute(\"data-color-scheme\");\n    if (explicit === \"dark\" || element.classList.contains(\"dark\")) return \"dark\";\n    if (explicit === \"light\" || element.classList.contains(\"light\")) return \"light\";\n  }\n\n  const colorScheme = clientWindow.getComputedStyle?.(document.documentElement).colorScheme;\n  if (colorScheme?.includes(\"dark\") && !colorScheme.includes(\"light\")) return \"dark\";\n  return clientWindow.matchMedia?.(\"(prefers-color-scheme: dark)\").matches ? \"dark\" : \"light\";\n}\n\nfunction createFarmRuntimeErrorDebugReport(\n  record: RuntimeErrorRecord,\n  clientWindow: Window,\n  farmVersion: string,\n): string {\n  const source = record.sourceFrame.lines\n    .map(\n      (line) =>\n        `${line.highlight ? \">\" : \" \"} ${line.number ? String(line.number).padStart(4, \" \") : \"    \"} | ${line.content}`,\n    )\n    .join(\"\\n\");\n  const viewport = `${clientWindow.innerWidth}×${clientWindow.innerHeight}`;\n\n  return [\n    \"# Farm.js client runtime debug report\",\n    \"\",\n    \"## Error\",\n    `- Type: ${formatErrorType(record.error, record.context.phase)}`,\n    `- Message: ${record.error.message}`,\n    `- Phase: ${formatPhase(record.context.phase)}`,\n    `- Page: ${record.context.location.href}`,\n    `- Occurrences: ${record.occurrences}`,\n    \"\",\n    \"## Browser runtime\",\n    `- Farm.js: ${farmVersion}`,\n    `- User agent: ${clientWindow.navigator.userAgent}`,\n    `- Viewport: ${viewport}`,\n    `- Online: ${clientWindow.navigator.onLine === false ? \"no\" : \"yes\"}`,\n    \"\",\n    \"## Source\",\n    `\\`${formatSourcePath(record.sourceFrame)}\\``,\n    \"\",\n    \"```text\",\n    source,\n    \"```\",\n    \"\",\n    \"## Stack trace\",\n    \"```text\",\n    record.error.stack || \"Stack trace unavailable.\",\n    \"```\",\n    \"\",\n    \"## Diagnostic request\",\n    \"Identify the most likely root cause from the message, source frame, and stack trace. Explain the smallest safe fix and how to verify it.\",\n  ].join(\"\\n\");\n}\n\nfunction createGithubIssueUrl(\n  record: RuntimeErrorRecord,\n  clientWindow: Window,\n  farmVersion: string,\n): string {\n  const source = record.sourceFrame.lines\n    .map(\n      (line) =>\n        `${line.highlight ? \">\" : \" \"} ${line.number ? String(line.number).padStart(4, \" \") : \"    \"} | ${line.content}`,\n    )\n    .join(\"\\n\");\n  const body = truncateText(\n    [\n      \"## Runtime error report\",\n      \"\",\n      \"> This report was prefilled by the Farm.js development error overlay. Review it and remove sensitive information before submitting.\",\n      \"\",\n      \"### Error\",\n      `- Type: ${formatErrorType(record.error, record.context.phase)}`,\n      `- Message: ${record.error.message}`,\n      `- Phase: ${formatPhase(record.context.phase)}`,\n      `- Page path: ${record.context.location.pathname}`,\n      `- Occurrences: ${record.occurrences}`,\n      `- Farm.js: ${farmVersion}`,\n      `- Browser: ${clientWindow.navigator.userAgent}`,\n      `- Viewport: ${clientWindow.innerWidth}×${clientWindow.innerHeight}`,\n      `- Online: ${clientWindow.navigator.onLine === false ? \"no\" : \"yes\"}`,\n      \"\",\n      \"### Source\",\n      `\\`${formatSourcePath(record.sourceFrame)}\\``,\n      \"\",\n      \"```text\",\n      source,\n      \"```\",\n      \"\",\n      \"### Stack trace\",\n      \"```text\",\n      record.error.stack || \"Stack trace unavailable.\",\n      \"```\",\n      \"\",\n      \"### Expected behavior\",\n      \"Describe what you expected to happen and the steps needed to reproduce the failure.\",\n      \"\",\n      \"### Diagnostic request\",\n      \"Identify the most likely root cause from the message, source frame, and stack trace. Explain the smallest safe fix and how to verify it.\",\n    ].join(\"\\n\"),\n    6_000,\n  );\n  const issueUrl = new URL(\"https://github.com/farming-labs/farm.js/issues/new\");\n  issueUrl.searchParams.set(\"title\", truncateText(`[runtime error] ${record.error.message}`, 120));\n  issueUrl.searchParams.set(\"body\", body);\n  return issueUrl.href;\n}\n\nfunction truncateText(value: string, maxLength: number): string {\n  if (value.length <= maxLength) return value;\n  return `${value.slice(0, maxLength - 24)}\\n\\n[report truncated]`;\n}\n\nasync function copyText(value: string, clientWindow: Window, document: Document): Promise<void> {\n  if (clientWindow.navigator.clipboard && clientWindow.isSecureContext) {\n    await clientWindow.navigator.clipboard.writeText(value);\n    return;\n  }\n\n  const area = document.createElement(\"textarea\");\n  area.value = value;\n  area.readOnly = true;\n  area.style.position = \"fixed\";\n  area.style.opacity = \"0\";\n  document.body.appendChild(area);\n  area.select();\n  const copied = document.execCommand(\"copy\");\n  area.remove();\n  if (!copied) throw new Error(\"Copy command was rejected\");\n}\n","\"use client\";\n\nimport {\n  createFarmRuntimeErrorOverlay,\n  type FarmRuntimeErrorOverlay,\n} from \"./runtime-error-overlay\";\n\ntype MaybePromise<T> = T | Promise<T>;\n\nexport type FarmClientPluginEnforce = \"pre\" | \"post\";\nexport type FarmClientNavigationAction = \"push\" | \"replace\" | \"pop\";\nexport type FarmClientHydrationMode = \"hydrate\" | \"render\";\n\nexport interface FarmClientLocation {\n  href: string;\n  pathname: string;\n  search: string;\n  hash: string;\n}\n\nexport interface FarmClientPluginRouter {\n  navigate(href: string, options?: Record<string, unknown>): MaybePromise<void>;\n  /** Re-render the current URL from fresh server data without replacing the document shell. */\n  refresh?(options?: Record<string, unknown>): MaybePromise<void>;\n  prefetch?(href: string): MaybePromise<void>;\n  clearCache?(): void;\n  getNavigationState?(): unknown;\n}\n\nexport interface FarmClientPluginMetadata {\n  name: string;\n  version?: string;\n}\n\nexport interface FarmClientPluginSetupEvent<TPublic = undefined> {\n  plugin: FarmClientPluginMetadata;\n  public: Readonly<TPublic>;\n  router: FarmClientPluginRouter;\n  isDev: boolean;\n  isProd: boolean;\n  deploymentId?: string;\n}\n\nexport interface FarmClientPluginStateEvent<\n  TState = unknown,\n  TPublic = undefined,\n> extends FarmClientPluginSetupEvent<TPublic> {\n  state: TState;\n}\n\nexport interface FarmClientHydrationSession {\n  container: Element;\n  location: FarmClientLocation;\n  mode: FarmClientHydrationMode;\n  startedAt: number;\n}\n\nexport interface FarmClientHydrationEvent<TState = unknown, TPublic = undefined>\n  extends FarmClientPluginStateEvent<TState, TPublic>, FarmClientHydrationSession {}\n\nexport interface FarmClientHydrationCompleteEvent<\n  TState = unknown,\n  TPublic = undefined,\n> extends FarmClientHydrationEvent<TState, TPublic> {\n  durationMs: number;\n  recovered: boolean;\n}\n\nexport interface FarmClientNavigationSession {\n  id: string;\n  from: FarmClientLocation | null;\n  to: FarmClientLocation;\n  action: FarmClientNavigationAction;\n  signal: AbortSignal;\n  startedAt: number;\n  route?: {\n    pattern?: string | null;\n    params?: Record<string, string>;\n  };\n}\n\nexport interface FarmClientNavigationEvent<TState = unknown, TPublic = undefined>\n  extends FarmClientPluginStateEvent<TState, TPublic>, FarmClientNavigationSession {}\n\nexport interface FarmClientNavigationLoadedEvent<\n  TState = unknown,\n  TPublic = undefined,\n> extends FarmClientNavigationEvent<TState, TPublic> {\n  durationMs: number;\n  data?: unknown;\n}\n\nexport interface FarmClientNavigationResolvedEvent<\n  TState = unknown,\n  TPublic = undefined,\n> extends FarmClientNavigationEvent<TState, TPublic> {\n  durationMs: number;\n}\n\nexport interface FarmClientNavigationErrorEvent<\n  TState = unknown,\n  TPublic = undefined,\n> extends FarmClientNavigationResolvedEvent<TState, TPublic> {\n  error: unknown;\n}\n\nexport type FarmClientPluginErrorPhase =\n  | \"setup\"\n  | \"hydration\"\n  | \"navigation\"\n  | \"window\"\n  | \"unhandled-rejection\"\n  | \"performance\"\n  | `plugin:${string}`\n  | (string & {});\n\nexport interface FarmClientPluginErrorEvent<\n  TState = unknown,\n  TPublic = undefined,\n> extends FarmClientPluginStateEvent<TState, TPublic> {\n  error: unknown;\n  phase: FarmClientPluginErrorPhase;\n  location: FarmClientLocation;\n  navigation?: FarmClientNavigationSession;\n}\n\nexport interface FarmClientPerformanceEvent<\n  TState = unknown,\n  TPublic = undefined,\n> extends FarmClientPluginStateEvent<TState, TPublic> {\n  entry: PerformanceEntry;\n  location: FarmClientLocation;\n}\n\nexport interface FarmClientPluginCloseEvent<\n  TState = unknown,\n  TPublic = undefined,\n> extends FarmClientPluginStateEvent<TState, TPublic> {\n  reason: \"pagehide\" | \"hmr\" | \"manual\" | (string & {});\n}\n\nexport interface FarmClientPlugin<TState = unknown, TPublic = undefined> {\n  setup?(event: FarmClientPluginSetupEvent<TPublic>): MaybePromise<TState>;\n  hydration?: {\n    before?(event: FarmClientHydrationEvent<TState, TPublic>): MaybePromise<void>;\n    after?(event: FarmClientHydrationCompleteEvent<TState, TPublic>): MaybePromise<void>;\n  };\n  navigation?: {\n    before?(event: FarmClientNavigationEvent<TState, TPublic>): MaybePromise<void>;\n    loaded?(event: FarmClientNavigationLoadedEvent<TState, TPublic>): MaybePromise<void>;\n    resolved?(event: FarmClientNavigationResolvedEvent<TState, TPublic>): MaybePromise<void>;\n    rendered?(event: FarmClientNavigationResolvedEvent<TState, TPublic>): MaybePromise<void>;\n    error?(event: FarmClientNavigationErrorEvent<TState, TPublic>): MaybePromise<void>;\n  };\n  error?(event: FarmClientPluginErrorEvent<TState, TPublic>): MaybePromise<void>;\n  performance?(event: FarmClientPerformanceEvent<TState, TPublic>): MaybePromise<void>;\n  close?(event: FarmClientPluginCloseEvent<TState, TPublic>): MaybePromise<void>;\n}\n\nexport interface FarmClientPluginRegistration<TPublic = undefined> {\n  name: string;\n  version?: string;\n  enforce?: FarmClientPluginEnforce;\n  definition: FarmClientPlugin<any, TPublic>;\n  public?: TPublic;\n}\n\n/**\n * Define the lifecycle for an application's auto-discovered `src/client.ts`\n * entry. The identity helper preserves state inference while keeping the\n * module entirely in the browser bundle.\n */\nexport function defineClient<TState = unknown, TPublic = undefined>(\n  definition: FarmClientPlugin<TState, TPublic>,\n): FarmClientPlugin<TState, TPublic> {\n  return definition;\n}\n\nexport interface FarmClientPluginManagerOptions {\n  router: FarmClientPluginRouter;\n  isDev?: boolean;\n  isProd?: boolean;\n  deploymentId?: string;\n  window?: Window;\n}\n\ninterface FarmClientPluginInstance {\n  registration: FarmClientPluginRegistration<any>;\n  plugin: FarmClientPlugin<any, any>;\n  state: unknown;\n}\n\nconst PERFORMANCE_ENTRY_TYPES = [\n  \"navigation\",\n  \"paint\",\n  \"largest-contentful-paint\",\n  \"layout-shift\",\n  \"event\",\n];\n\nexport class FarmClientPluginManager {\n  private readonly registrations: FarmClientPluginRegistration[];\n  private readonly options: FarmClientPluginManagerOptions;\n  private readonly instances: FarmClientPluginInstance[] = [];\n  private readonly performanceObservers: PerformanceObserver[] = [];\n  private startPromise?: Promise<void>;\n  private closePromise?: Promise<void>;\n  private currentNavigation?: {\n    controller: AbortController;\n    session: FarmClientNavigationSession;\n  };\n  private navigationSequence = 0;\n  private starting = false;\n  private started = false;\n  private closed = false;\n  private readonly reportedErrors = new WeakSet<object>();\n  private readonly runtimeErrorOverlay?: FarmRuntimeErrorOverlay;\n\n  private readonly handleWindowError = (event: ErrorEvent) => {\n    const error = event.error ?? new Error(event.message || \"Unknown browser error\");\n    void this.reportError(error, \"window\", undefined, this.getLocation(), event);\n  };\n\n  private readonly handleUnhandledRejection = (event: PromiseRejectionEvent) => {\n    void this.reportError(\n      event.reason,\n      \"unhandled-rejection\",\n      undefined,\n      this.getLocation(),\n      event,\n    );\n  };\n\n  private readonly handlePageHide = (event: PageTransitionEvent) => {\n    // A persisted pagehide means the page is entering the back/forward cache and\n    // may be restored. close() is terminal — start() refuses to run again once\n    // closed — so tearing down here would hand the restored page dead scripts,\n    // PWA, and observability plugins with nothing able to revive them.\n    if (event.persisted) return;\n    void this.close(\"pagehide\");\n  };\n\n  constructor(\n    registrations: readonly FarmClientPluginRegistration[],\n    options: FarmClientPluginManagerOptions,\n  ) {\n    this.registrations = sortRegistrations(registrations);\n    this.options = {\n      ...options,\n      isDev: options.isDev ?? false,\n      isProd: options.isProd ?? !options.isDev,\n      window: options.window ?? (typeof window !== \"undefined\" ? window : undefined),\n    };\n    if (this.options.isDev && this.options.window) {\n      this.runtimeErrorOverlay = createFarmRuntimeErrorOverlay({\n        window: this.options.window,\n      });\n    }\n  }\n\n  start(): Promise<void> {\n    if (this.startPromise) return this.startPromise;\n\n    this.startPromise = Promise.resolve().then(() => this.startInternal());\n    return this.startPromise;\n  }\n\n  async beginHydration(input: {\n    container: Element;\n    mode: FarmClientHydrationMode;\n  }): Promise<FarmClientHydrationSession> {\n    await this.start();\n    const session: FarmClientHydrationSession = {\n      ...input,\n      location: this.getLocation(),\n      startedAt: now(),\n    };\n\n    await this.runHook(\"hydration.before\", (instance) =>\n      instance.plugin.hydration?.before?.({\n        ...this.createStateEvent(instance),\n        ...session,\n      }),\n    );\n\n    return session;\n  }\n\n  async completeHydration(\n    session: FarmClientHydrationSession,\n    options: { recovered?: boolean } = {},\n  ): Promise<void> {\n    await this.runHook(\"hydration.after\", (instance) =>\n      instance.plugin.hydration?.after?.({\n        ...this.createStateEvent(instance),\n        ...session,\n        durationMs: now() - session.startedAt,\n        recovered: options.recovered ?? false,\n      }),\n    );\n  }\n\n  async failHydration(session: FarmClientHydrationSession, error: unknown): Promise<void> {\n    await this.reportError(error, \"hydration\", undefined, session.location);\n  }\n\n  async beginNavigation(input: {\n    from?: string | URL | FarmClientLocation | null;\n    to: string | URL | FarmClientLocation;\n    action: FarmClientNavigationAction;\n    route?: FarmClientNavigationSession[\"route\"];\n  }): Promise<FarmClientNavigationSession> {\n    await this.start();\n    this.currentNavigation?.controller.abort(\"superseded\");\n\n    const controller = new AbortController();\n    const session: FarmClientNavigationSession = {\n      id: `navigation:${++this.navigationSequence}`,\n      from:\n        input.from === null\n          ? null\n          : toClientLocation(input.from ?? this.getLocation().href, this.getBaseUrl()),\n      to: toClientLocation(input.to, this.getBaseUrl()),\n      action: input.action,\n      signal: controller.signal,\n      startedAt: now(),\n      route: input.route,\n    };\n\n    this.currentNavigation = { controller, session };\n    await this.runHook(\"navigation.before\", (instance) =>\n      instance.plugin.navigation?.before?.({\n        ...this.createStateEvent(instance),\n        ...session,\n      }),\n    );\n\n    return session;\n  }\n\n  async markNavigationLoaded(session: FarmClientNavigationSession, data?: unknown): Promise<void> {\n    if (session.signal.aborted) return;\n    await this.runHook(\"navigation.loaded\", (instance) =>\n      instance.plugin.navigation?.loaded?.({\n        ...this.createStateEvent(instance),\n        ...session,\n        data,\n        durationMs: now() - session.startedAt,\n      }),\n    );\n  }\n\n  cancelNavigation(session?: FarmClientNavigationSession, reason: unknown = \"canceled\"): void {\n    const current = this.currentNavigation;\n    if (!current || (session && current.session !== session)) return;\n    current.controller.abort(reason);\n    this.currentNavigation = undefined;\n  }\n\n  async resolveNavigation(session: FarmClientNavigationSession): Promise<void> {\n    if (session.signal.aborted) return;\n    await this.runHook(\"navigation.resolved\", (instance) =>\n      instance.plugin.navigation?.resolved?.({\n        ...this.createStateEvent(instance),\n        ...session,\n        durationMs: now() - session.startedAt,\n      }),\n    );\n  }\n\n  scheduleNavigationRendered(session: FarmClientNavigationSession): Promise<void> {\n    if (session.signal.aborted) return Promise.resolve();\n    const clientWindow = this.options.window;\n    const schedule = clientWindow?.requestAnimationFrame\n      ? (callback: () => void) =>\n          clientWindow.requestAnimationFrame(() => clientWindow.requestAnimationFrame(callback))\n      : (callback: () => void) => setTimeout(callback, 0);\n\n    return new Promise((resolve) => {\n      schedule(() => {\n        if (session.signal.aborted || this.closed) {\n          resolve();\n          return;\n        }\n        void this.runHook(\"navigation.rendered\", (instance) =>\n          instance.plugin.navigation?.rendered?.({\n            ...this.createStateEvent(instance),\n            ...session,\n            durationMs: now() - session.startedAt,\n          }),\n        ).finally(() => {\n          if (this.currentNavigation?.session === session) {\n            this.currentNavigation = undefined;\n          }\n          resolve();\n        });\n      });\n    });\n  }\n\n  async failNavigation(session: FarmClientNavigationSession, error: unknown): Promise<void> {\n    if (!session.signal.aborted) {\n      await this.runHook(\"navigation.error\", (instance) =>\n        instance.plugin.navigation?.error?.({\n          ...this.createStateEvent(instance),\n          ...session,\n          durationMs: now() - session.startedAt,\n          error,\n        }),\n      );\n      await this.reportError(error, \"navigation\", session, session.to);\n    }\n\n    if (this.currentNavigation?.session === session) {\n      this.currentNavigation = undefined;\n    }\n  }\n\n  async reportError(\n    error: unknown,\n    phase: FarmClientPluginErrorPhase,\n    navigation?: FarmClientNavigationSession,\n    location = this.getLocation(),\n    sourceEvent?: Event,\n  ): Promise<void> {\n    if (this.closed) return;\n    if (isObject(error)) {\n      if (this.reportedErrors.has(error)) return;\n      this.reportedErrors.add(error);\n    }\n\n    if (!this.started && !this.starting) await this.start();\n    await this.runErrorHooks({ error, phase, navigation, location }, undefined, sourceEvent);\n  }\n\n  close(reason: FarmClientPluginCloseEvent[\"reason\"] = \"manual\"): Promise<void> {\n    if (this.closePromise) return this.closePromise;\n    this.closePromise = this.closeInternal(reason);\n    return this.closePromise;\n  }\n\n  getPlugins(): readonly FarmClientPluginMetadata[] {\n    return this.instances.map(({ registration }) => ({\n      name: registration.name,\n      version: registration.version,\n    }));\n  }\n\n  private async startInternal(): Promise<void> {\n    if (this.started || this.closed) return;\n    this.starting = true;\n\n    try {\n      for (const registration of this.registrations) {\n        try {\n          const definition = registration.definition;\n          if (!definition || typeof definition !== \"object\") {\n            throw new TypeError(\n              `Client plugin \"${registration.name}\" does not define a lifecycle object`,\n            );\n          }\n\n          const instance: FarmClientPluginInstance = {\n            registration,\n            plugin: definition,\n            state: undefined,\n          };\n          instance.state = await definition.setup?.(this.createSetupEvent(instance));\n          this.instances.push(instance);\n        } catch (error) {\n          this.logHookError(registration.name, \"setup\", error);\n          await this.runErrorHooks({\n            error,\n            phase: \"setup\",\n            location: this.getLocation(),\n          });\n        }\n      }\n\n      this.started = true;\n      this.installBrowserListeners();\n      this.installPerformanceObservers();\n    } finally {\n      this.starting = false;\n    }\n  }\n\n  private installBrowserListeners(): void {\n    const clientWindow = this.options.window;\n    if (!clientWindow) return;\n\n    if (this.runtimeErrorOverlay || this.instances.some(({ plugin }) => plugin.error)) {\n      clientWindow.addEventListener(\"error\", this.handleWindowError);\n      clientWindow.addEventListener(\"unhandledrejection\", this.handleUnhandledRejection);\n    }\n    // Not `once`: a persisted pagehide is ignored above, and the page can be\n    // restored and then genuinely unloaded later. close() is idempotent, so\n    // keeping the listener costs nothing and never disposes twice.\n    clientWindow.addEventListener(\"pagehide\", this.handlePageHide);\n  }\n\n  private installPerformanceObservers(): void {\n    if (!this.instances.some(({ plugin }) => plugin.performance)) return;\n    const Observer = typeof PerformanceObserver !== \"undefined\" ? PerformanceObserver : undefined;\n    if (!Observer) return;\n\n    const supported = new Set(Observer.supportedEntryTypes || []);\n    for (const type of PERFORMANCE_ENTRY_TYPES) {\n      if (!supported.has(type)) continue;\n      try {\n        const observer = new Observer((list: PerformanceObserverEntryList) => {\n          for (const entry of list.getEntries()) {\n            void this.runHook(\"performance\", (instance) =>\n              instance.plugin.performance?.({\n                ...this.createStateEvent(instance),\n                entry,\n                location: this.getLocation(),\n              }),\n            );\n          }\n        });\n        observer.observe({ type, buffered: true });\n        this.performanceObservers.push(observer);\n      } catch (error) {\n        void this.reportError(error, \"performance\");\n      }\n    }\n  }\n\n  private async closeInternal(reason: FarmClientPluginCloseEvent[\"reason\"]): Promise<void> {\n    if (this.closed) return;\n    if (this.startPromise) await this.startPromise;\n    this.closed = true;\n    this.currentNavigation?.controller.abort(reason);\n    this.currentNavigation = undefined;\n\n    const clientWindow = this.options.window;\n    clientWindow?.removeEventListener(\"error\", this.handleWindowError);\n    clientWindow?.removeEventListener(\"unhandledrejection\", this.handleUnhandledRejection);\n    clientWindow?.removeEventListener(\"pagehide\", this.handlePageHide);\n    for (const observer of this.performanceObservers) observer.disconnect();\n    this.performanceObservers.length = 0;\n    this.runtimeErrorOverlay?.destroy();\n\n    for (const instance of [...this.instances].reverse()) {\n      try {\n        await instance.plugin.close?.({\n          ...this.createStateEvent(instance),\n          reason,\n        });\n      } catch (error) {\n        this.logHookError(instance.registration.name, \"close\", error);\n      }\n    }\n  }\n\n  private async runHook(\n    hook: string,\n    invoke: (instance: FarmClientPluginInstance) => MaybePromise<void> | undefined,\n  ): Promise<void> {\n    for (const instance of this.instances) {\n      try {\n        await invoke(instance);\n      } catch (error) {\n        this.logHookError(instance.registration.name, hook, error);\n        await this.runErrorHooks(\n          {\n            error,\n            phase: `plugin:${hook}`,\n            location: this.getLocation(),\n          },\n          instance,\n        );\n      }\n    }\n  }\n\n  private async runErrorHooks(\n    event: Pick<FarmClientPluginErrorEvent, \"error\" | \"phase\" | \"location\" | \"navigation\">,\n    excluded?: FarmClientPluginInstance,\n    sourceEvent?: Event,\n  ): Promise<void> {\n    this.runtimeErrorOverlay?.show(event.error, {\n      phase: event.phase,\n      location: event.location,\n      sourceEvent,\n    });\n    for (const instance of this.instances) {\n      if (instance === excluded || !instance.plugin.error) continue;\n      try {\n        await instance.plugin.error({\n          ...this.createStateEvent(instance),\n          ...event,\n        });\n      } catch (error) {\n        this.logHookError(instance.registration.name, \"error\", error);\n      }\n    }\n  }\n\n  private createSetupEvent(\n    instance: Pick<FarmClientPluginInstance, \"registration\">,\n  ): FarmClientPluginSetupEvent<any> {\n    return {\n      plugin: {\n        name: instance.registration.name,\n        version: instance.registration.version,\n      },\n      public: readonlyPublicData(instance.registration.public),\n      router: this.options.router,\n      isDev: Boolean(this.options.isDev),\n      isProd: Boolean(this.options.isProd),\n      deploymentId: this.options.deploymentId,\n    };\n  }\n\n  private createStateEvent(\n    instance: FarmClientPluginInstance,\n  ): FarmClientPluginStateEvent<any, any> {\n    return {\n      ...this.createSetupEvent(instance),\n      state: instance.state,\n    };\n  }\n\n  private getLocation(): FarmClientLocation {\n    const href = this.options.window?.location.href ?? \"http://localhost/\";\n    return toClientLocation(href, href);\n  }\n\n  private getBaseUrl(): string {\n    return this.options.window?.location.href ?? \"http://localhost/\";\n  }\n\n  private logHookError(name: string, hook: string, error: unknown): void {\n    console.error(`[Farm.js] Client plugin \"${name}\" failed in ${hook}:`, error);\n  }\n}\n\nexport function createClientPluginManager(\n  registrations: readonly FarmClientPluginRegistration[],\n  options: FarmClientPluginManagerOptions,\n): FarmClientPluginManager {\n  return new FarmClientPluginManager(registrations, options);\n}\n\nfunction sortRegistrations(\n  registrations: readonly FarmClientPluginRegistration[],\n): FarmClientPluginRegistration[] {\n  const rank = (enforce?: FarmClientPluginEnforce) =>\n    enforce === \"pre\" ? 0 : enforce === \"post\" ? 2 : 1;\n  return registrations\n    .map((registration, index) => ({ registration, index }))\n    .sort(\n      (left, right) =>\n        rank(left.registration.enforce) - rank(right.registration.enforce) ||\n        left.index - right.index,\n    )\n    .map(({ registration }) => registration);\n}\n\nfunction toClientLocation(\n  input: string | URL | FarmClientLocation,\n  base: string,\n): FarmClientLocation {\n  if (typeof input === \"object\" && \"href\" in input && \"pathname\" in input) {\n    return {\n      href: input.href,\n      pathname: input.pathname,\n      search: input.search,\n      hash: input.hash,\n    };\n  }\n\n  const url = new URL(input, base);\n  return {\n    href: url.href,\n    pathname: url.pathname,\n    search: url.search,\n    hash: url.hash,\n  };\n}\n\nfunction readonlyPublicData<T>(value: T | undefined): Readonly<T> {\n  if (value && typeof value === \"object\") {\n    return Object.freeze(value);\n  }\n  return value as Readonly<T>;\n}\n\nfunction now(): number {\n  return typeof performance !== \"undefined\" ? performance.now() : Date.now();\n}\n\nfunction isObject(value: unknown): value is object {\n  return (typeof value === \"object\" && value !== null) || typeof value === \"function\";\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEA,2BAKO;;;ACqKA,SAAS,aACd,YACmC;AACnC,SAAO;AACT;AAJgB;","names":[]}