{"version":3,"sources":["../src/client-headers.ts","../src/client-cancellation.ts","../src/integration-client.ts","../src/api/client-routes.ts","../src/api/client.ts"],"sourcesContent":["/** Instance defaults, resolved once per call before cache lookup or dispatch. */\nexport type ClientHeaders =\n  | Record<string, string>\n  | (() => Record<string, string> | Promise<Record<string, string>>);\n\n/** Snapshot synchronous defaults immediately; keep async resolvers local to the call. */\nexport function resolveClientHeaders(source?: ClientHeaders): Headers | Promise<Headers> {\n  const value = typeof source === \"function\" ? source() : source;\n  if (value && typeof (value as Promise<Record<string, string>>).then === \"function\") {\n    return Promise.resolve(value).then((headers) => new Headers(headers));\n  }\n  return new Headers(value as Record<string, string> | undefined);\n}\n","/** One call budget, shared by header resolution, dispatch, decoding, and retry waits. */\nexport function createClientCancellation(\n  signal?: AbortSignal,\n  timeoutMs = 0,\n  parent?: AbortSignal,\n) {\n  let timer: ReturnType<typeof setTimeout> | undefined;\n  let invalid: Error | undefined;\n  let timeoutReason: DOMException | undefined;\n  const signals = [signal, parent].filter((value): value is AbortSignal => !!value);\n  if (!Number.isInteger(timeoutMs) || timeoutMs < 0 || timeoutMs > 2_147_483_647) {\n    invalid = new RangeError(\n      \"timeoutMs must be an integer between 0 and 2147483647 (0 disables the deadline).\",\n    );\n  } else if (timeoutMs > 0) {\n    const controller = new AbortController();\n    signals.push(controller.signal);\n    timer = setTimeout(() => {\n      timeoutReason = new DOMException(\"Client request timed out\", \"TimeoutError\");\n      controller.abort(timeoutReason);\n    }, timeoutMs);\n  }\n  const combined = signals.length > 1 ? AbortSignal.any(signals) : signals[0];\n  let active = 0;\n  let closed = false;\n  const cleanup = () => {\n    if (closed && active === 0 && timer !== undefined) {\n      clearTimeout(timer);\n      timer = undefined;\n    }\n  };\n  const check = () => {\n    if (invalid) throw invalid;\n    combined?.throwIfAborted();\n  };\n  return {\n    signal: combined,\n    get timedOut() {\n      return timeoutReason !== undefined && combined?.reason === timeoutReason;\n    },\n    check,\n    hold() {\n      active++;\n      return () => {\n        active--;\n        cleanup();\n      };\n    },\n    // A race also bounds cooperative local dispatch and custom HTTP implementations.\n    // Late completion is consumed, but cannot turn a cancelled result into success.\n    async run<T>(work: () => T | PromiseLike<T>): Promise<T> {\n      check();\n      active++;\n      let abort: (() => void) | undefined;\n      try {\n        if (!combined) return await work();\n        return await new Promise<T>((resolve, reject) => {\n          abort = () => reject(combined.reason);\n          combined.addEventListener(\"abort\", abort, { once: true });\n          Promise.resolve()\n            .then(() => {\n              check();\n              return work();\n            })\n            .then(resolve, reject);\n        });\n      } finally {\n        if (abort) combined?.removeEventListener(\"abort\", abort);\n        active--;\n        cleanup();\n      }\n    },\n    async delay(ms: number) {\n      let retryTimer: ReturnType<typeof setTimeout> | undefined;\n      try {\n        await this.run(\n          () =>\n            new Promise<void>((resolve) => {\n              retryTimer = setTimeout(resolve, ms);\n            }),\n        );\n      } finally {\n        if (retryTimer !== undefined) clearTimeout(retryTimer);\n      }\n    },\n    dispose() {\n      closed = true;\n      cleanup();\n    },\n  };\n}\n","import type {\n  FarmIntegrationAPI,\n  FarmIntegrationAPIBodyFormat,\n  FarmIntegrationAPIOperation,\n} from \"./integration-api\";\nimport type { FarmIntegration as FarmIntegrationDefinition } from \"./integrations\";\nimport { resolveFarmAPIRequestURL } from \"./api/config\";\nimport { resolveClientHeaders, type ClientHeaders } from \"./client-headers\";\nimport { createClientCancellation } from \"./client-cancellation\";\nimport {\n  notifyClientObserver,\n  type ClientLifecycleHooks,\n  type ClientRequestEvent,\n  type ClientResponseEvent,\n} from \"./client-observers\";\n\n/**\n * Small per-call integration metadata. When sent from a browser, values are\n * client-controlled and should be validated before authorization decisions.\n */\nexport type IntegrationClientData = Record<string, unknown>;\n\nexport type IntegrationClientOptions = ClientLifecycleHooks & {\n  baseURL?: string;\n  headers?: ClientHeaders;\n  credentials?: RequestCredentials;\n  /** Whole-call deadline in milliseconds; 0 disables it. */\n  timeoutMs?: number;\n  /** HTTP transport, including server fallback; never replaces local dispatch. */\n  fetch?: typeof globalThis.fetch;\n  data?: IntegrationClientData;\n  isServer?: false | undefined;\n};\n\ntype IntegrationRequestOptionsBase<TData = unknown> = ClientLifecycleHooks<TData> & {\n  headers?: Record<string, string>;\n  signal?: AbortSignal;\n  timeoutMs?: number;\n  credentials?: RequestCredentials;\n  data?: IntegrationClientData;\n};\n\nexport type IntegrationClientRequestOptions<TData = unknown> = IntegrationRequestOptionsBase<TData>;\n\nexport type IntegrationServerRequestLike =\n  | Request\n  | {\n      url?: string;\n      headers?: HeadersInit;\n    };\n\nexport type IntegrationServerClientOptions = Omit<IntegrationClientOptions, \"isServer\"> & {\n  isServer: true;\n  request?: IntegrationServerRequestLike;\n  forwardHeaders?: boolean | readonly string[];\n};\n\nexport type IntegrationServerClientRequestOptions<TData = unknown> =\n  IntegrationRequestOptionsBase<TData> & {\n    baseURL?: string;\n    request?: IntegrationServerRequestLike;\n    forwardHeaders?: boolean | readonly string[];\n  };\n\nexport class IntegrationClientError<TData = unknown> extends Error {\n  readonly status: number;\n  readonly response: Response;\n  readonly data: TData | undefined;\n\n  constructor(message: string, response: Response, data?: TData) {\n    super(message);\n    this.name = \"IntegrationClientError\";\n    this.status = response.status;\n    this.response = response;\n    this.data = data;\n  }\n}\n\nexport type IntegrationOperationResult<\n  TData = unknown,\n  TError = IntegrationClientError<unknown> | Error,\n> = {\n  data: TData | null;\n  error: TError | null;\n};\n\ntype ExtractOperationBody<T> = T extends {\n  __types?: { body: infer TBody };\n}\n  ? TBody\n  : never;\n\ntype ExtractOperationQuery<T> = T extends {\n  __types?: { query: infer TQuery };\n}\n  ? TQuery\n  : never;\n\ntype ExtractOperationResponse<T> = T extends {\n  __types?: { response: infer TResponse };\n}\n  ? TResponse\n  : unknown;\n\nexport type InferIntegrationOperationBody<T> = ExtractOperationBody<T>;\nexport type InferIntegrationOperationQuery<T> = ExtractOperationQuery<T>;\nexport type InferIntegrationOperationResponse<T> = ExtractOperationResponse<T>;\n\ntype IsNever<T> = [T] extends [never] ? true : false;\n\ntype OperationInput<T> =\n  IsNever<ExtractOperationBody<T>> extends true\n    ? IsNever<ExtractOperationQuery<T>> extends true\n      ? {}\n      : { query?: ExtractOperationQuery<T> }\n    : IsNever<ExtractOperationQuery<T>> extends true\n      ? { body: ExtractOperationBody<T> }\n      : { body: ExtractOperationBody<T>; query?: ExtractOperationQuery<T> };\n\ntype ClientOperation<T> = (\n  options?: OperationInput<T>,\n  requestOptions?: IntegrationClientRequestOptions<ExtractOperationResponse<T>>,\n) => Promise<IntegrationOperationResult<ExtractOperationResponse<T>>>;\n\ntype ServerOperation<T> = (\n  options?: OperationInput<T>,\n  requestOptions?: IntegrationServerClientRequestOptions<ExtractOperationResponse<T>>,\n) => Promise<IntegrationOperationResult<ExtractOperationResponse<T>>>;\n\ntype IsUnion<T, U = T> = T extends any ? ([U] extends [T] ? false : true) : never;\n\ntype SingleKey<T> = [T] extends [never] ? never : IsUnion<T> extends true ? never : T;\n\ntype ExtractAPIFromSource<TSource> = TSource extends { api?: infer TAPI }\n  ? NonNullable<TAPI> extends FarmIntegrationAPI\n    ? NonNullable<TAPI>\n    : never\n  : TSource extends FarmIntegrationAPI\n    ? TSource\n    : never;\n\ntype SourceKeysWithAPI<TSources extends Record<string, any>> = {\n  [K in keyof TSources]: [ExtractAPIFromSource<TSources[K]>] extends [never] ? never : K;\n}[keyof TSources];\n\ntype IsServerRegisteredOperation<T> = T extends { isServer: true } ? true : false;\n\ntype ClientOperationKeys<TAPI> = {\n  [K in keyof TAPI]: TAPI[K] extends FarmIntegrationAPIOperation<any, any, any, any>\n    ? IsServerRegisteredOperation<TAPI[K]> extends true\n      ? never\n      : K\n    : never;\n}[keyof TAPI];\n\ntype ClientNamespaceShape<TAPI> = {\n  [K in keyof TAPI as TAPI[K] extends FarmIntegrationAPIOperation<any, any, any, any>\n    ? IsServerRegisteredOperation<TAPI[K]> extends true\n      ? never\n      : K\n    : K]: TAPI[K] extends FarmIntegrationAPIOperation<any, any, any, any>\n    ? ClientOperation<TAPI[K]>\n    : TAPI[K] extends Record<string, any>\n      ? IntegrationAPIToClient<TAPI[K]>\n      : never;\n};\n\ntype SingleClientOperationKey<TAPI> =\n  Exclude<keyof TAPI, ClientOperationKeys<TAPI>> extends never\n    ? SingleKey<ClientOperationKeys<TAPI>>\n    : never;\n\ntype IntegrationAPIToClient<TAPI> =\n  TAPI extends FarmIntegrationAPIOperation<any, any, any, any>\n    ? ClientOperation<TAPI>\n    : TAPI extends Record<string, any>\n      ? [SingleClientOperationKey<TAPI>] extends [never]\n        ? ClientNamespaceShape<TAPI>\n        : SingleClientOperationKey<TAPI> extends keyof TAPI\n          ? ClientOperation<TAPI[SingleClientOperationKey<TAPI>]> & ClientNamespaceShape<TAPI>\n          : ClientNamespaceShape<TAPI>\n      : never;\n\nexport type IntegrationClient<TSources extends Record<string, any>> = {\n  [K in SourceKeysWithAPI<TSources>]: IntegrationAPIToClient<ExtractAPIFromSource<TSources[K]>>;\n};\n\nexport type IntegrationClientRoot<TSources extends Record<string, any>> = {\n  integrations: IntegrationClient<TSources>;\n};\n\ntype ServerOperationKeys<TAPI> = {\n  [K in keyof TAPI]: TAPI[K] extends FarmIntegrationAPIOperation<any, any, any> ? K : never;\n}[keyof TAPI];\n\ntype ServerNamespaceShape<TAPI> = {\n  [K in keyof TAPI]: TAPI[K] extends FarmIntegrationAPIOperation<any, any, any>\n    ? ServerOperation<TAPI[K]>\n    : TAPI[K] extends Record<string, any>\n      ? IntegrationAPIToServerClient<TAPI[K]>\n      : never;\n};\n\ntype SingleServerOperationKey<TAPI> =\n  Exclude<keyof TAPI, ServerOperationKeys<TAPI>> extends never\n    ? SingleKey<ServerOperationKeys<TAPI>>\n    : never;\n\ntype IntegrationAPIToServerClient<TAPI> =\n  TAPI extends FarmIntegrationAPIOperation<any, any, any>\n    ? ServerOperation<TAPI>\n    : TAPI extends Record<string, any>\n      ? [SingleServerOperationKey<TAPI>] extends [never]\n        ? ServerNamespaceShape<TAPI>\n        : SingleServerOperationKey<TAPI> extends keyof TAPI\n          ? ServerOperation<TAPI[SingleServerOperationKey<TAPI>]> & ServerNamespaceShape<TAPI>\n          : ServerNamespaceShape<TAPI>\n      : never;\n\nexport type IntegrationServerClient<TSources extends Record<string, any>> = {\n  [K in SourceKeysWithAPI<TSources>]: IntegrationAPIToServerClient<\n    ExtractAPIFromSource<TSources[K]>\n  >;\n};\n\nexport type IntegrationServerClientRoot<TSources extends Record<string, any>> = {\n  integrations: IntegrationServerClient<TSources>;\n};\n\nexport type IntegrationClientAliases<TSources extends Record<string, any>> =\n  IntegrationClient<TSources> & {\n    integrations: IntegrationClient<TSources>;\n  };\n\nexport type IntegrationServerClientAliases<TSources extends Record<string, any>> =\n  IntegrationServerClient<TSources> & {\n    integrations: IntegrationServerClient<TSources>;\n  };\n\nexport type IntegrationAPI<TSources extends Record<string, any>> =\n  IntegrationClientAliases<TSources> & {\n    server: (\n      options: Omit<IntegrationServerClientOptions, \"isServer\">,\n    ) => IntegrationServerClientAliases<TSources>;\n  };\n\nexport type IntegrationClients<TSources extends Record<string, any>> = {\n  api: IntegrationServerClientAliases<TSources>;\n  apiClient: IntegrationClientAliases<TSources>;\n};\n\ntype ResolvedIntegrationNamespace = readonly [\n  string,\n  FarmIntegrationAPI,\n  FarmIntegrationDefinition | FarmIntegrationAPI,\n];\n\ntype RegisteredIntegrationRuntime = {\n  integration: FarmIntegrationDefinition;\n  config: unknown;\n  isDev: boolean;\n  isProd: boolean;\n};\n\nconst INTEGRATION_RUNTIME_REGISTRY_KEY = Symbol.for(\"farm.integrationRuntimeRegistry\");\nconst CURRENT_REQUEST_RESOLVER_KEY = Symbol.for(\"farm.currentRequestResolver\");\nconst INTEGRATION_REQUEST_DISPATCHER_KEY = Symbol.for(\"farm.integrationRequestDispatcher\");\n\ntype IntegrationRequestDispatcher = (\n  runtime: RegisteredIntegrationRuntime,\n  request: Request,\n  options?: { currentRequest?: Request; data?: IntegrationClientData; internal?: boolean },\n) => Promise<Response | null>;\n\ntype GlobalWithIntegrationRuntimeRegistry = typeof globalThis & {\n  [INTEGRATION_RUNTIME_REGISTRY_KEY]?: Map<string, RegisteredIntegrationRuntime>;\n  [CURRENT_REQUEST_RESOLVER_KEY]?: () => Request | undefined;\n  [INTEGRATION_REQUEST_DISPATCHER_KEY]?: IntegrationRequestDispatcher;\n};\n\ntype GlobalWithIntegrationAPIManifest = typeof globalThis & {\n  __FARM_INTEGRATION_API_MANIFEST__?: Record<string, FarmIntegrationAPI>;\n  window?: {\n    __FARM_INTEGRATION_API_MANIFEST__?: Record<string, FarmIntegrationAPI>;\n  };\n};\n\nfunction isOperation(value: unknown): value is FarmIntegrationAPIOperation<any, any, any, any> {\n  return (\n    !!value &&\n    typeof value === \"object\" &&\n    (value as FarmIntegrationAPIOperation<any, any, any, any>).kind ===\n      \"farm-integration-api-operation\"\n  );\n}\n\nfunction resolveSourceAPI(\n  source: FarmIntegrationDefinition | FarmIntegrationAPI,\n): FarmIntegrationAPI {\n  if (\"kind\" in source && source.kind === \"farm-integration\") {\n    if (!source.api) {\n      throw new Error(`Integration \"${source.type}\" does not expose a client API definition.`);\n    }\n\n    return source.api as FarmIntegrationAPI;\n  }\n\n  return source as FarmIntegrationAPI;\n}\n\nfunction tryResolveSourceAPI(\n  source: FarmIntegrationDefinition | FarmIntegrationAPI,\n): FarmIntegrationAPI | null {\n  if (\"kind\" in source && source.kind === \"farm-integration\") {\n    if (!source.api) {\n      return null;\n    }\n\n    return source.api as FarmIntegrationAPI;\n  }\n\n  return source as FarmIntegrationAPI;\n}\n\nfunction getIntegrationRuntimeRegistry() {\n  const globalState = globalThis as GlobalWithIntegrationRuntimeRegistry;\n  return (\n    globalState[INTEGRATION_RUNTIME_REGISTRY_KEY] || new Map<string, RegisteredIntegrationRuntime>()\n  );\n}\n\nfunction getRegisteredIntegrationRuntimeLocal(\n  key: string,\n): RegisteredIntegrationRuntime | undefined {\n  return getIntegrationRuntimeRegistry().get(key);\n}\n\nfunction getRegisteredIntegrationsLocal(): Record<string, FarmIntegrationDefinition> {\n  return Object.fromEntries(\n    Array.from(getIntegrationRuntimeRegistry().entries()).map(([key, runtime]) => [\n      key,\n      runtime.integration,\n    ]),\n  );\n}\n\nfunction resolveCurrentRequestLocal(): Request | undefined {\n  const globalState = globalThis as GlobalWithIntegrationRuntimeRegistry;\n  return globalState[CURRENT_REQUEST_RESOLVER_KEY]?.();\n}\n\nfunction resolveIntegrationRequestDispatcherLocal(): IntegrationRequestDispatcher | undefined {\n  const globalState = globalThis as GlobalWithIntegrationRuntimeRegistry;\n  return globalState[INTEGRATION_REQUEST_DISPATCHER_KEY];\n}\n\nconst INTEGRATION_DATA_HEADER = \"x-farm-integration-data\";\nconst INTEGRATION_DATA_HEADER_MAX_LENGTH = 16 * 1024;\nconst BLOCKED_INTEGRATION_DATA_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nfunction isIntegrationClientData(value: unknown): value is IntegrationClientData {\n  return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction isPlainIntegrationDataObject(value: unknown): value is Record<string, unknown> {\n  if (!isIntegrationClientData(value)) {\n    return false;\n  }\n\n  const prototype = Object.getPrototypeOf(value);\n  return prototype === Object.prototype || prototype === null;\n}\n\nfunction sanitizeIntegrationClientDataValue(value: unknown): unknown {\n  if (Array.isArray(value)) {\n    return value.map((item) => sanitizeIntegrationClientDataValue(item));\n  }\n\n  if (!isPlainIntegrationDataObject(value)) {\n    return value;\n  }\n\n  const sanitized: Record<string, unknown> = {};\n  for (const [key, item] of Object.entries(value)) {\n    if (BLOCKED_INTEGRATION_DATA_KEYS.has(key)) {\n      continue;\n    }\n\n    sanitized[key] = sanitizeIntegrationClientDataValue(item);\n  }\n\n  return sanitized;\n}\n\nfunction normalizeIntegrationClientData(\n  value: IntegrationClientData | undefined,\n): IntegrationClientData | undefined {\n  if (!isIntegrationClientData(value)) {\n    return undefined;\n  }\n\n  const sanitized = sanitizeIntegrationClientDataValue(value);\n  return isIntegrationClientData(sanitized) && Object.keys(sanitized).length > 0\n    ? sanitized\n    : undefined;\n}\n\nfunction getIntegrationDataHeaderByteLength(value: string): number {\n  return new TextEncoder().encode(value).byteLength;\n}\n\nfunction mergeIntegrationClientData(\n  ...values: Array<IntegrationClientData | undefined>\n): IntegrationClientData | undefined {\n  let merged: IntegrationClientData | undefined;\n\n  for (const value of values) {\n    const data = normalizeIntegrationClientData(value);\n    if (!data) {\n      continue;\n    }\n\n    merged = {\n      ...merged,\n      ...data,\n    };\n  }\n\n  return merged && Object.keys(merged).length > 0 ? merged : undefined;\n}\n\nfunction serializeIntegrationClientData(data: IntegrationClientData): string {\n  const serialized = JSON.stringify(data);\n  if (getIntegrationDataHeaderByteLength(serialized) > INTEGRATION_DATA_HEADER_MAX_LENGTH) {\n    throw new Error(\n      `Integration client data must be smaller than ${INTEGRATION_DATA_HEADER_MAX_LENGTH} bytes when sent over HTTP headers.`,\n    );\n  }\n\n  return serialized;\n}\n\nfunction appendIntegrationClientDataHeader(\n  headers: Headers,\n  data: IntegrationClientData | undefined,\n) {\n  if (!data) {\n    return;\n  }\n\n  headers.set(INTEGRATION_DATA_HEADER, serializeIntegrationClientData(data));\n}\n\nfunction resolveAutomaticClientNamespaces(): ResolvedIntegrationNamespace[] {\n  const globalState = globalThis as GlobalWithIntegrationAPIManifest;\n  const manifest =\n    globalState.window?.__FARM_INTEGRATION_API_MANIFEST__ ||\n    globalState.__FARM_INTEGRATION_API_MANIFEST__ ||\n    {};\n\n  return Object.entries(manifest).map(([key, api]) => [key, api, api] as const);\n}\n\nfunction resolveAutomaticServerNamespaces(): ResolvedIntegrationNamespace[] {\n  return Object.entries(getRegisteredIntegrationsLocal()).flatMap(([key, source]) => {\n    const api = tryResolveSourceAPI(source);\n    return api ? [[key, api, source] as ResolvedIntegrationNamespace] : [];\n  });\n}\n\nfunction appendQuery(url: URL, query: Record<string, unknown> | undefined) {\n  if (!query) {\n    return;\n  }\n\n  for (const [key, value] of Object.entries(query)) {\n    if (value == null) {\n      continue;\n    }\n\n    if (Array.isArray(value)) {\n      for (const item of value) {\n        if (item != null) {\n          url.searchParams.append(key, String(item));\n        }\n      }\n      continue;\n    }\n\n    url.searchParams.set(key, String(value));\n  }\n}\n\nfunction appendHeaders(target: Headers, source: HeadersInit | undefined) {\n  if (!source) {\n    return;\n  }\n\n  const headers = new Headers(source);\n  headers.forEach((value, key) => {\n    target.set(key, value);\n  });\n}\n\nconst DEFAULT_FORWARDED_HEADERS = [\n  \"authorization\",\n  \"cookie\",\n  \"x-client-ip\",\n  \"x-forwarded-for\",\n  \"x-forwarded-host\",\n  \"x-forwarded-proto\",\n  \"x-real-ip\",\n] as const;\n\nfunction resolveRequestLike(request: IntegrationServerRequestLike | undefined) {\n  if (!request) {\n    return undefined;\n  }\n\n  if (request instanceof Request) {\n    return {\n      url: request.url,\n      headers: request.headers,\n    };\n  }\n\n  return {\n    url: request.url,\n    headers: request.headers ? new Headers(request.headers) : undefined,\n  };\n}\n\nfunction resolveServerBaseURL(\n  explicitBaseURL: string | undefined,\n  request: ReturnType<typeof resolveRequestLike>,\n) {\n  if (explicitBaseURL) {\n    return explicitBaseURL;\n  }\n\n  if (request?.url) {\n    try {\n      return new URL(request.url).origin;\n    } catch {\n      // Fall back to forwarded headers below.\n    }\n  }\n\n  const headers = request?.headers;\n  const host = headers?.get(\"x-forwarded-host\") || headers?.get(\"host\");\n  if (host) {\n    const proto = headers?.get(\"x-forwarded-proto\") || \"http\";\n    return `${proto}://${host}`;\n  }\n\n  return \"http://localhost:3000\";\n}\n\nfunction resolveForwardHeaders(\n  request: ReturnType<typeof resolveRequestLike>,\n  forwardHeaders: boolean | readonly string[] | undefined,\n) {\n  if (!request?.headers || forwardHeaders === false) {\n    return new Headers();\n  }\n\n  const allowed =\n    Array.isArray(forwardHeaders) && forwardHeaders.length > 0\n      ? new Set(forwardHeaders.map((item) => item.toLowerCase()))\n      : new Set<string>(DEFAULT_FORWARDED_HEADERS);\n\n  const headers = new Headers();\n  request.headers.forEach((value, key) => {\n    if (allowed.has(key.toLowerCase())) {\n      headers.set(key, value);\n    }\n  });\n\n  return headers;\n}\n\nfunction createBody(\n  format: FarmIntegrationAPIBodyFormat | undefined,\n  body: unknown,\n  headers: Headers,\n): BodyInit | undefined {\n  if (body == null || format === \"none\") {\n    return undefined;\n  }\n\n  if (format === \"form\") {\n    if (body instanceof FormData || body instanceof URLSearchParams) {\n      return body;\n    }\n\n    const form = new URLSearchParams();\n    for (const [key, value] of Object.entries(body as Record<string, unknown>)) {\n      if (value == null) {\n        continue;\n      }\n\n      if (Array.isArray(value)) {\n        for (const item of value) {\n          if (item != null) {\n            form.append(key, String(item));\n          }\n        }\n        continue;\n      }\n\n      form.set(key, String(value));\n    }\n\n    headers.set(\"content-type\", \"application/x-www-form-urlencoded;charset=UTF-8\");\n    return form;\n  }\n\n  headers.set(\"content-type\", \"application/json\");\n  return JSON.stringify(body);\n}\n\nfunction createOperationBody(\n  operation: Pick<FarmIntegrationAPIOperation<any, any, any>, \"bodyFormat\" | \"method\">,\n  body: unknown,\n  headers: Headers,\n): BodyInit | undefined {\n  const requestBody = createBody(operation.bodyFormat, body, headers);\n\n  if (operation.method === \"QUERY\" && requestBody === undefined && !headers.has(\"content-type\")) {\n    headers.set(\n      \"content-type\",\n      operation.bodyFormat === \"form\"\n        ? \"application/x-www-form-urlencoded;charset=UTF-8\"\n        : \"application/json\",\n    );\n  }\n\n  return requestBody;\n}\n\nasync function parseResponseData(response: Response): Promise<unknown> {\n  if (response.status === 204 || response.status === 205) {\n    return undefined;\n  }\n\n  const contentType = response.headers.get(\"content-type\") || \"\";\n\n  if (isJSONMediaType(contentType)) {\n    return await response.json();\n  }\n\n  return await response.text();\n}\n\nfunction isJSONMediaType(contentType: string): boolean {\n  const mediaType = contentType.split(\";\", 1)[0].trim().toLowerCase();\n  return mediaType === \"application/json\" || mediaType.endsWith(\"+json\");\n}\n\nasync function safeParseResponseData(response: Response): Promise<unknown> {\n  try {\n    return await parseResponseData(response);\n  } catch {\n    return undefined;\n  }\n}\n\nfunction createResponseError(response: Response, errorData: unknown) {\n  const message =\n    typeof errorData === \"string\"\n      ? errorData\n      : typeof errorData === \"object\" && errorData\n        ? String(\n            (errorData as { error?: string; message?: string }).error ||\n              (errorData as { error?: string; message?: string }).message ||\n              response.statusText,\n          )\n        : response.statusText || \"Integration request failed.\";\n\n  return new IntegrationClientError(message, response, errorData);\n}\n\nfunction normalizeExecutionError(error: unknown): Error {\n  if (error instanceof Error) {\n    return error;\n  }\n\n  if (typeof error === \"string\" && error.length > 0) {\n    return new Error(error);\n  }\n\n  return new Error(\"Integration request failed.\");\n}\n\nasync function finalizeOperationResponse(\n  operation: FarmIntegrationAPIOperation<any, any, any>,\n  response: Response,\n) {\n  if (!response.ok) {\n    const errorData = await safeParseResponseData(response);\n    return {\n      data: null,\n      error: createResponseError(response, errorData),\n    };\n  }\n\n  if (operation.responseFormat === \"response\") {\n    return {\n      data: response,\n      error: null,\n    };\n  }\n\n  return {\n    data: (await parseResponseData(response)) as unknown,\n    error: null,\n  };\n}\n\nlet integrationRequestCounter = 0;\nconst noIntegrationObservers = {\n  response(_response: Response) {},\n  finish<T extends IntegrationOperationResult>(result: T): T {\n    return result;\n  },\n};\n\nfunction createIntegrationObservers(\n  operation: FarmIntegrationAPIOperation<any, any, any>,\n  options: ClientLifecycleHooks,\n  requestOptions?: ClientLifecycleHooks,\n) {\n  if (\n    !options.onRequest &&\n    !options.onResponse &&\n    !options.onError &&\n    !requestOptions?.onRequest &&\n    !requestOptions?.onResponse &&\n    !requestOptions?.onError\n  ) {\n    return noIntegrationObservers;\n  }\n  const requestEvent: ClientRequestEvent = {\n    requestId: `integration-${Date.now()}-${++integrationRequestCounter}`,\n    method: operation.method,\n    path: operation.path ?? \"\",\n    attempt: 0,\n    timestamp: Date.now(),\n  };\n  let response: Response | undefined;\n  notifyClientObserver(options.onRequest, [requestEvent]);\n  notifyClientObserver(requestOptions?.onRequest, [requestEvent]);\n  return {\n    response(value: Response) {\n      response = value;\n    },\n    finish<T extends IntegrationOperationResult>(result: T): T {\n      const data = result.error ? undefined : result.data;\n      const event: ClientResponseEvent = {\n        ...requestEvent,\n        timestamp: Date.now(),\n        response,\n        data,\n        error: result.error ?? undefined,\n        ok: !result.error,\n        status: response?.status,\n      };\n      notifyClientObserver(options.onResponse, [data, result.error, event]);\n      notifyClientObserver(requestOptions?.onResponse, [data, result.error, event]);\n      if (result.error) {\n        notifyClientObserver(options.onError, [result.error]);\n        notifyClientObserver(requestOptions?.onError, [result.error]);\n      }\n      return result;\n    },\n  };\n}\n\nasync function executeClientOperation(\n  operation: FarmIntegrationAPIOperation<any, any, any>,\n  input: Record<string, unknown>,\n  options: IntegrationClientOptions,\n  requestOptions?: IntegrationClientRequestOptions,\n) {\n  const cancellation = createClientCancellation(\n    requestOptions?.signal,\n    requestOptions?.timeoutMs ?? options.timeoutMs,\n  );\n  const observers = createIntegrationObservers(operation, options, requestOptions);\n  try {\n    const result = await cancellation.run(async () => {\n      if (!operation.path) {\n        return {\n          data: null,\n          error: new Error(\n            \"Integration API operation path is missing. Pass a path to api.get/post/... or wrap pathless methods with api.route(path, { ... }).\",\n          ),\n        };\n      }\n\n      const baseURL =\n        options.baseURL ||\n        (typeof window !== \"undefined\" ? window.location.origin : \"http://localhost:3000\");\n      const url = resolveFarmAPIRequestURL(operation.path, baseURL);\n      appendQuery(url, input.query as Record<string, unknown> | undefined);\n\n      const resolved = resolveClientHeaders(options.headers);\n      const headers = resolved instanceof Headers ? resolved : await resolved;\n      cancellation.check();\n      appendHeaders(headers, operation.headers);\n      appendHeaders(headers, requestOptions?.headers);\n      headers.set(\"x-farm-integration-client\", \"1\");\n\n      if (operation.responseFormat !== \"response\") {\n        headers.set(\"accept\", \"application/json\");\n      }\n\n      appendIntegrationClientDataHeader(\n        headers,\n        mergeIntegrationClientData(options.data, requestOptions?.data),\n      );\n\n      const body = createOperationBody(operation, input.body, headers);\n      const response = await (options.fetch ?? fetch)(url.toString(), {\n        method: operation.method,\n        headers,\n        body,\n        credentials:\n          requestOptions?.credentials ?? operation.credentials ?? options.credentials ?? \"include\",\n        signal: cancellation.signal,\n      });\n      cancellation.check();\n\n      observers.response(response);\n      if (!response.ok) {\n        const errorData = await safeParseResponseData(response);\n        return {\n          data: null,\n          error: createResponseError(response, errorData),\n        };\n      }\n\n      if (operation.responseFormat === \"response\") {\n        return {\n          data: response,\n          error: null,\n        };\n      }\n\n      return {\n        data: (await parseResponseData(response)) as unknown,\n        error: null,\n      };\n    });\n    return observers.finish(result);\n  } catch (error) {\n    return observers.finish({\n      data: null,\n      error: normalizeExecutionError(error),\n    });\n  } finally {\n    cancellation.dispose();\n  }\n}\n\nasync function executeServerOperation(\n  operation: FarmIntegrationAPIOperation<any, any, any>,\n  input: Record<string, unknown>,\n  options: Omit<IntegrationServerClientOptions, \"isServer\">,\n  requestOptions?: IntegrationServerClientRequestOptions,\n  integrationKey?: string,\n  source?: FarmIntegrationDefinition | FarmIntegrationAPI,\n) {\n  // Capture the request before any asynchronous work (including header resolvers).\n  const currentRequest =\n    requestOptions?.request instanceof Request\n      ? requestOptions.request\n      : options.request instanceof Request\n        ? options.request\n        : resolveCurrentRequestLocal();\n  const cancellation = createClientCancellation(\n    requestOptions?.signal,\n    requestOptions?.timeoutMs ?? options.timeoutMs,\n    currentRequest?.signal,\n  );\n  const observers = createIntegrationObservers(operation, options, requestOptions);\n  try {\n    const result = await cancellation.run(async () => {\n      if (!operation.path) {\n        return {\n          data: null,\n          error: new Error(\n            \"Integration API operation path is missing. Pass a path to api.get/post/... or wrap pathless methods with api.route(path, { ... }).\",\n          ),\n        };\n      }\n\n      const serverRequestOptions =\n        requestOptions &&\n        (\"request\" in requestOptions ||\n          \"baseURL\" in requestOptions ||\n          \"forwardHeaders\" in requestOptions)\n          ? requestOptions\n          : undefined;\n      const request = resolveRequestLike(\n        serverRequestOptions?.request ?? options.request ?? currentRequest,\n      );\n      const baseURL = resolveServerBaseURL(\n        serverRequestOptions?.baseURL ?? options.baseURL,\n        request,\n      );\n      const origin = resolveServerBaseURL(undefined, request);\n      // Registered handlers use their canonical path, not an HTTP gateway prefix.\n      const url = new URL(operation.path, new URL(baseURL, origin));\n      appendQuery(url, input.query as Record<string, unknown> | undefined);\n\n      const headers = new Headers();\n      appendHeaders(\n        headers,\n        resolveForwardHeaders(\n          request,\n          serverRequestOptions?.forwardHeaders ?? options.forwardHeaders,\n        ),\n      );\n      const resolved = resolveClientHeaders(options.headers);\n      appendHeaders(headers, resolved instanceof Headers ? resolved : await resolved);\n      cancellation.check();\n      appendHeaders(headers, operation.headers);\n      appendHeaders(headers, requestOptions?.headers);\n      headers.set(\"x-farm-integration-client\", \"1\");\n\n      if (operation.responseFormat !== \"response\") {\n        headers.set(\"accept\", \"application/json\");\n      }\n\n      const data = mergeIntegrationClientData(options.data, requestOptions?.data);\n\n      if (integrationKey) {\n        const runtime =\n          \"kind\" in (source || {}) &&\n          (source as FarmIntegrationDefinition).kind === \"farm-integration\"\n            ? getRegisteredIntegrationRuntimeLocal(integrationKey) || {\n                integration: source as FarmIntegrationDefinition,\n                config: {},\n                isDev: process.env.NODE_ENV !== \"production\",\n                isProd: process.env.NODE_ENV === \"production\",\n              }\n            : getRegisteredIntegrationRuntimeLocal(integrationKey);\n\n        if (runtime) {\n          const dispatchIntegrationRequest = resolveIntegrationRequestDispatcherLocal();\n          const body = createOperationBody(operation, input.body, headers);\n          const directResponse = dispatchIntegrationRequest\n            ? await dispatchIntegrationRequest(\n                runtime,\n                new Request(url.toString(), {\n                  method: operation.method,\n                  headers,\n                  body,\n                  signal: cancellation.signal,\n                }),\n                {\n                  currentRequest,\n                  data,\n                  internal: true,\n                },\n              )\n            : null;\n\n          cancellation.check();\n\n          if (directResponse) {\n            observers.response(directResponse);\n            return await finalizeOperationResponse(operation, directResponse);\n          }\n        }\n      }\n\n      appendIntegrationClientDataHeader(headers, data);\n\n      const body = createOperationBody(operation, input.body, headers);\n      const httpURL = resolveFarmAPIRequestURL(operation.path, baseURL, origin);\n      appendQuery(httpURL, input.query as Record<string, unknown> | undefined);\n      const response = await (options.fetch ?? fetch)(httpURL.toString(), {\n        method: operation.method,\n        headers,\n        body,\n        credentials:\n          requestOptions?.credentials ?? operation.credentials ?? options.credentials ?? \"include\",\n        signal: cancellation.signal,\n      });\n      cancellation.check();\n\n      observers.response(response);\n      return await finalizeOperationResponse(operation, response);\n    });\n    return observers.finish(result);\n  } catch (error) {\n    return observers.finish({\n      data: null,\n      error: normalizeExecutionError(error),\n    });\n  } finally {\n    cancellation.dispose();\n  }\n}\n\nexport function createIntegrationClient<TSources extends Record<string, any>>(\n  sources: { integrations: TSources },\n  options: IntegrationServerClientOptions,\n): IntegrationServerClientAliases<TSources>;\nexport function createIntegrationClient<TSources extends Record<string, any>>(\n  sources: { integrations: TSources },\n  options?: IntegrationClientOptions,\n): IntegrationClientAliases<TSources>;\nexport function createIntegrationClient<TSources extends Record<string, any>>(\n  sources: TSources,\n  options: IntegrationServerClientOptions,\n): IntegrationServerClient<TSources>;\nexport function createIntegrationClient<TSources extends Record<string, any>>(\n  sources: TSources,\n  options?: IntegrationClientOptions,\n): IntegrationClient<TSources>;\nexport function createIntegrationClient<TSources extends Record<string, any>>(\n  sources: TSources | { integrations: TSources },\n  options: IntegrationClientOptions | IntegrationServerClientOptions = {},\n):\n  | IntegrationClient<TSources>\n  | IntegrationClientAliases<TSources>\n  | IntegrationServerClient<TSources>\n  | IntegrationServerClientAliases<TSources> {\n  const rawSources = \"integrations\" in sources ? sources.integrations : sources;\n  const isServer = options.isServer === true;\n\n  const namespaces = Object.entries(rawSources)\n    .map(([key, source]) => {\n      const api = tryResolveSourceAPI(source as FarmIntegrationDefinition | FarmIntegrationAPI);\n      if (!api) {\n        return null;\n      }\n      return [key, api, source as FarmIntegrationDefinition | FarmIntegrationAPI] as const;\n    })\n    .filter(\n      (\n        value,\n      ): value is readonly [\n        string,\n        FarmIntegrationAPI,\n        FarmIntegrationDefinition | FarmIntegrationAPI,\n      ] => value !== null,\n    );\n\n  const cache = new Map<string, any>();\n\n  const integrationNamespaces = new Proxy(\n    {},\n    {\n      get(target, property) {\n        if (typeof property !== \"string\") {\n          return undefined;\n        }\n\n        if (Reflect.has(target, property)) {\n          return Reflect.get(target, property);\n        }\n\n        if (cache.has(property)) {\n          return cache.get(property);\n        }\n\n        const match = namespaces.find(([key]) => key === property);\n        if (!match) {\n          return undefined;\n        }\n\n        const namespace = isServer\n          ? createServerNamespaceProxy(\n              match[0],\n              match[2],\n              match[1],\n              options as IntegrationServerClientOptions,\n            )\n          : createNamespaceProxy(match[1], options);\n        cache.set(property, namespace);\n        return namespace;\n      },\n    },\n  ) as\n    | IntegrationClient<TSources>\n    | IntegrationClientAliases<TSources>\n    | IntegrationServerClient<TSources>\n    | IntegrationServerClientAliases<TSources>;\n\n  if (\"integrations\" in sources) {\n    Object.defineProperty(integrationNamespaces, \"integrations\", {\n      value: integrationNamespaces,\n      enumerable: false,\n      configurable: false,\n      writable: false,\n    });\n\n    return integrationNamespaces as\n      | IntegrationClientAliases<TSources>\n      | IntegrationServerClientAliases<TSources>;\n  }\n\n  return integrationNamespaces as IntegrationClient<TSources> | IntegrationServerClient<TSources>;\n}\n\nfunction createAutomaticIntegrationAliases<TSources extends Record<string, any>>(\n  isServer: boolean,\n  options: IntegrationClientOptions | IntegrationServerClientOptions = {},\n): IntegrationClientAliases<TSources> | IntegrationServerClientAliases<TSources> {\n  const cache = isServer ? new Map<string, any>() : null;\n\n  const integrationNamespaces = new Proxy(\n    {},\n    {\n      get(_target, property) {\n        if (typeof property !== \"string\") {\n          return undefined;\n        }\n\n        if (property === \"integrations\") {\n          return integrationNamespaces;\n        }\n\n        if (cache?.has(property)) {\n          return cache.get(property);\n        }\n\n        const namespaces = isServer\n          ? resolveAutomaticServerNamespaces()\n          : resolveAutomaticClientNamespaces();\n        const match = namespaces.find(([key]) => key === property);\n        if (!match) {\n          return undefined;\n        }\n\n        const namespace = isServer\n          ? createServerNamespaceProxy(\n              match[0],\n              match[2],\n              match[1],\n              options as IntegrationServerClientOptions,\n            )\n          : createNamespaceProxy(match[1], options as IntegrationClientOptions);\n\n        cache?.set(property, namespace);\n        return namespace;\n      },\n    },\n  ) as IntegrationClientAliases<TSources> | IntegrationServerClientAliases<TSources>;\n\n  Object.defineProperty(integrationNamespaces, \"integrations\", {\n    value: integrationNamespaces,\n    enumerable: false,\n    configurable: false,\n    writable: false,\n  });\n\n  return integrationNamespaces;\n}\n\nexport function integrationsClient<\n  TSources extends Record<string, any>,\n>(): IntegrationClientAliases<TSources>;\nexport function integrationsClient<TSources extends Record<string, any>>(\n  options: IntegrationClientOptions,\n): IntegrationClientAliases<TSources>;\nexport function integrationsClient<TSources extends Record<string, any>>(\n  options: IntegrationClientOptions = {},\n): IntegrationClientAliases<TSources> {\n  return createAutomaticIntegrationAliases<TSources>(\n    false,\n    options,\n  ) as IntegrationClientAliases<TSources>;\n}\n\nexport function integrationsServer<\n  TSources extends Record<string, any>,\n>(): IntegrationServerClientAliases<TSources>;\nexport function integrationsServer<TSources extends Record<string, any>>(\n  options: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationServerClientAliases<TSources>;\nexport function integrationsServer<TSources extends Record<string, any>>(\n  options: Omit<IntegrationServerClientOptions, \"isServer\"> = {},\n): IntegrationServerClientAliases<TSources> {\n  return createAutomaticIntegrationAliases<TSources>(true, {\n    ...options,\n    isServer: true,\n  }) as IntegrationServerClientAliases<TSources>;\n}\n\nexport function createIntegrationServerClient<TSources extends Record<string, any>>(sources: {\n  integrations: TSources;\n}): IntegrationServerClientAliases<TSources>;\nexport function createIntegrationServerClient<TSources extends Record<string, any>>(\n  sources: TSources,\n): IntegrationServerClient<TSources>;\nexport function createIntegrationServerClient<TSources extends Record<string, any>>(\n  sources: { integrations: TSources },\n  options: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationServerClientAliases<TSources>;\nexport function createIntegrationServerClient<TSources extends Record<string, any>>(\n  sources: TSources,\n  options: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationServerClient<TSources>;\nexport function createIntegrationServerClient<TSources extends Record<string, any>>(\n  sources: TSources | { integrations: TSources },\n  options: Omit<IntegrationServerClientOptions, \"isServer\"> = {},\n): IntegrationServerClient<TSources> | IntegrationServerClientAliases<TSources> {\n  return createIntegrationClient(sources, {\n    ...options,\n    isServer: true,\n  }) as IntegrationServerClient<TSources> | IntegrationServerClientAliases<TSources>;\n}\n\nexport function createIntegrationApi<TSources extends Record<string, any>>(\n  sources: { integrations: TSources },\n  options: IntegrationClientOptions = {},\n): IntegrationAPI<TSources> {\n  const client = createIntegrationClient(sources, options);\n\n  return {\n    ...client,\n    server(serverOptions = {}) {\n      return createIntegrationServerClient(sources, {\n        ...options,\n        ...serverOptions,\n      });\n    },\n  };\n}\n\nfunction isIntegrationClientOptionsInput(value: unknown): value is IntegrationClientOptions {\n  return (\n    !!value &&\n    typeof value === \"object\" &&\n    !Array.isArray(value) &&\n    (\"baseURL\" in value ||\n      \"headers\" in value ||\n      \"credentials\" in value ||\n      \"timeoutMs\" in value ||\n      \"fetch\" in value ||\n      \"onRequest\" in value ||\n      \"onResponse\" in value ||\n      \"onError\" in value ||\n      \"data\" in value ||\n      \"isServer\" in value)\n  );\n}\n\nfunction resolveIntegrationServerOptions(\n  clientOptions: IntegrationClientOptions = {},\n  serverOptions: Omit<IntegrationServerClientOptions, \"isServer\"> = {},\n): Omit<IntegrationServerClientOptions, \"isServer\"> {\n  const data = mergeIntegrationClientData(clientOptions.data, serverOptions.data);\n\n  return {\n    baseURL: clientOptions.baseURL,\n    headers: clientOptions.headers,\n    credentials: clientOptions.credentials,\n    timeoutMs: clientOptions.timeoutMs,\n    fetch: clientOptions.fetch,\n    onRequest: clientOptions.onRequest,\n    onResponse: clientOptions.onResponse,\n    onError: clientOptions.onError,\n    ...serverOptions,\n    ...(data ? { data } : {}),\n  };\n}\n\nexport function createIntegrationClients<TSources extends Record<string, any>>(\n  clientOptions?: IntegrationClientOptions,\n  serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources>;\nexport function createIntegrationClients<TSources extends Record<string, any>>(\n  sources: TSources,\n  clientOptions?: IntegrationClientOptions,\n  serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources>;\nexport function createIntegrationClients<TSources extends Record<string, any>>(\n  sources: { integrations: TSources },\n  clientOptions?: IntegrationClientOptions,\n  serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources>;\nexport function createIntegrationClients<TSources extends Record<string, any>>(\n  sources?: TSources | { integrations: TSources },\n  clientOptions?: IntegrationClientOptions,\n  serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources> {\n  if (arguments.length === 0 || isIntegrationClientOptionsInput(sources)) {\n    const automaticClientOptions = isIntegrationClientOptionsInput(sources) ? sources : {};\n    const automaticServerOptions = arguments.length > 1 ? clientOptions : undefined;\n\n    return {\n      api: integrationsServer<TSources>(\n        resolveIntegrationServerOptions(\n          automaticClientOptions,\n          automaticServerOptions as Omit<IntegrationServerClientOptions, \"isServer\"> | undefined,\n        ),\n      ),\n      apiClient: integrationsClient<TSources>(automaticClientOptions),\n    };\n  }\n\n  const explicitSources =\n    sources && \"integrations\" in sources ? sources.integrations : (sources as TSources);\n\n  return {\n    api: createIntegrationServerClient(\n      {\n        integrations: explicitSources,\n      },\n      resolveIntegrationServerOptions(clientOptions, serverOptions),\n    ) as IntegrationServerClientAliases<TSources>,\n    apiClient: createIntegrationClient(\n      {\n        integrations: explicitSources,\n      },\n      clientOptions,\n    ) as IntegrationClientAliases<TSources>,\n  };\n}\n\nexport function createIntegrations<TSources extends Record<string, any>>(\n  clientOptions?: IntegrationClientOptions,\n  serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources>;\nexport function createIntegrations<TSources extends Record<string, any>>(\n  sources: TSources,\n  clientOptions?: IntegrationClientOptions,\n  serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources>;\nexport function createIntegrations<TSources extends Record<string, any>>(\n  sources: { integrations: TSources },\n  clientOptions?: IntegrationClientOptions,\n  serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources>;\nexport function createIntegrations<TSources extends Record<string, any>>(\n  sources?: TSources | { integrations: TSources } | IntegrationClientOptions,\n  clientOptions?: IntegrationClientOptions,\n  serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources> {\n  if (arguments.length === 0) {\n    return createIntegrationClients<TSources>();\n  }\n\n  return createIntegrationClients<TSources>(\n    sources as TSources,\n    clientOptions,\n    serverOptions,\n  ) as IntegrationClients<TSources>;\n}\n\nfunction createClientSafeIntegrationAPI(\n  api: FarmIntegrationAPI | undefined,\n): FarmIntegrationAPI | undefined {\n  if (!api) {\n    return undefined;\n  }\n\n  const entries = Object.entries(api as Record<string, unknown>).map(([key, value]) => {\n    if (isOperation(value)) {\n      return [\n        key,\n        {\n          kind: value.kind,\n          path: value.path,\n          method: value.method,\n          bodyFormat: value.bodyFormat,\n          responseFormat: value.responseFormat,\n          credentials: value.credentials,\n          isServer: value.isServer,\n          __pathless: value.__pathless,\n        },\n      ];\n    }\n\n    if (value && typeof value === \"object\") {\n      return [key, createClientSafeIntegrationAPI(value as FarmIntegrationAPI)];\n    }\n\n    return [key, value];\n  });\n\n  return Object.fromEntries(entries) as FarmIntegrationAPI;\n}\n\nexport function getIntegrationAPIManifest(): Record<string, FarmIntegrationAPI> {\n  const manifestEntries = Object.entries(getRegisteredIntegrationsLocal())\n    .map(([key, integration]) => {\n      const api = createClientSafeIntegrationAPI(integration.api);\n      return api ? ([key, api] as const) : null;\n    })\n    .filter((value): value is readonly [string, FarmIntegrationAPI] => value !== null);\n\n  return Object.fromEntries(manifestEntries);\n}\n\nexport function integrationClients<TSources extends Record<string, any>>(\n  clientOptions?: IntegrationClientOptions,\n  serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources>;\nexport function integrationClients<TSources extends Record<string, any>>(\n  sources: TSources,\n  clientOptions?: IntegrationClientOptions,\n  serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources>;\nexport function integrationClients<TSources extends Record<string, any>>(\n  sources: { integrations: TSources },\n  clientOptions?: IntegrationClientOptions,\n  serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources>;\nexport function integrationClients<TSources extends Record<string, any>>(\n  sources?: TSources | { integrations: TSources },\n  clientOptions?: IntegrationClientOptions,\n  serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources> {\n  if (arguments.length === 0) {\n    return createIntegrationClients<TSources>();\n  }\n\n  return createIntegrationClients<TSources>(\n    sources as TSources,\n    clientOptions,\n    serverOptions,\n  ) as IntegrationClients<TSources>;\n}\n\nfunction resolveSingleNamespaceOperation(api: FarmIntegrationAPI) {\n  const entries = Object.entries(api as Record<string, unknown>);\n  if (entries.length !== 1) {\n    return null;\n  }\n\n  const [, value] = entries[0]!;\n  return isOperation(value) ? value : null;\n}\n\nfunction createClientOperationCaller(\n  operation: FarmIntegrationAPIOperation<any, any, any, any>,\n  property: string,\n  options: IntegrationClientOptions,\n) {\n  if (operation.isServer === true) {\n    return async () => {\n      throw new Error(\n        `Integration method \"${property}\" is registered with isServer: true and is only available from a server integration client.`,\n      );\n    };\n  }\n\n  return async (\n    input: Record<string, unknown> = {},\n    requestOptions?: IntegrationClientRequestOptions,\n  ) => {\n    if (typeof window === \"undefined\") {\n      throw new Error(\n        \"Client integration API cannot be called on the server. Pass { isServer: true } to createIntegrationClient(...) during server rendering, or provide { isServer: true, request } outside it.\",\n      );\n    }\n\n    return executeClientOperation(operation, input, options, requestOptions);\n  };\n}\n\nfunction createServerOperationCaller(\n  operation: FarmIntegrationAPIOperation<any, any, any, any>,\n  options: IntegrationServerClientOptions,\n  integrationKey: string,\n  source: FarmIntegrationDefinition | FarmIntegrationAPI,\n) {\n  return async (\n    input: Record<string, unknown> = {},\n    requestOptions?: IntegrationServerClientRequestOptions,\n  ) => {\n    if (typeof window !== \"undefined\") {\n      throw new Error(\n        \"Server integration API cannot be called in the browser. Remove { isServer: true } and create a client integration API instead.\",\n      );\n    }\n\n    return executeServerOperation(\n      operation,\n      input,\n      options,\n      requestOptions,\n      integrationKey,\n      source,\n    );\n  };\n}\n\nfunction createNamespaceProxy(api: FarmIntegrationAPI, options: IntegrationClientOptions) {\n  const cache = new Map<string, any>();\n  const directOperation = resolveSingleNamespaceOperation(api);\n  const target = directOperation\n    ? createClientOperationCaller(directOperation, directOperation.method.toLowerCase(), options)\n    : {};\n\n  return new Proxy(target, {\n    get(targetObject, property, receiver) {\n      if (typeof property !== \"string\") {\n        return Reflect.get(targetObject, property, receiver);\n      }\n\n      if (cache.has(property)) {\n        return cache.get(property);\n      }\n\n      const value = (api as Record<string, unknown>)[property];\n      if (!value) {\n        return Reflect.get(targetObject, property, receiver);\n      }\n\n      if (isOperation(value)) {\n        const caller = createClientOperationCaller(value, property, options);\n        cache.set(property, caller);\n        return caller;\n      }\n\n      const namespace = createNamespaceProxy(value as FarmIntegrationAPI, options);\n      cache.set(property, namespace);\n      return namespace;\n    },\n  });\n}\n\nfunction createServerNamespaceProxy(\n  integrationKey: string,\n  source: FarmIntegrationDefinition | FarmIntegrationAPI,\n  api: FarmIntegrationAPI,\n  options: IntegrationServerClientOptions,\n) {\n  const cache = new Map<string, any>();\n  const directOperation = resolveSingleNamespaceOperation(api);\n  const target = directOperation\n    ? createServerOperationCaller(directOperation, options, integrationKey, source)\n    : {};\n\n  return new Proxy(target, {\n    get(targetObject, property, receiver) {\n      if (typeof property !== \"string\") {\n        return Reflect.get(targetObject, property, receiver);\n      }\n\n      if (cache.has(property)) {\n        return cache.get(property);\n      }\n\n      const value = (api as Record<string, unknown>)[property];\n      if (!value) {\n        return Reflect.get(targetObject, property, receiver);\n      }\n\n      if (isOperation(value)) {\n        const caller = createServerOperationCaller(value, options, integrationKey, source);\n        cache.set(property, caller);\n        return caller;\n      }\n\n      const namespace = createServerNamespaceProxy(\n        integrationKey,\n        source,\n        value as FarmIntegrationAPI,\n        options,\n      );\n      cache.set(property, namespace);\n      return namespace;\n    },\n  });\n}\n","import { matchAPIRoute, parseDynamicSegment } from \"./route-pattern\";\n\nexport type APIRouteManifest = readonly {\n  readonly path: string;\n  readonly methods: readonly string[];\n}[];\nexport type BoundRouteParams = Readonly<Record<string, string | readonly string[]>>;\n\n/** A schema-free lookup shared by every immutable scope of one API client. */\nexport class ClientRouteManifest {\n  readonly routes: Map<string, APIRouteManifest[number]>;\n  constructor(routes: APIRouteManifest) {\n    this.routes = new Map(\n      routes.map((route) => [\n        route.path.replace(/\\/$/, \"\"),\n        {\n          path: route.path.replace(/\\/$/, \"\"),\n          methods: [...route.methods],\n        },\n      ]),\n    );\n  }\n\n  bind(path: string, input: unknown): { segment: string; params: BoundRouteParams } {\n    const params = readParams(input);\n    const prefix = `${path.replace(/\\/$/, \"\")}/`;\n    const candidates = new Set(\n      [...this.routes.keys()]\n        .filter((route) => route.startsWith(prefix))\n        .map((route) => route.slice(prefix.length).split(\"/\")[0])\n        .filter((segment) => {\n          const dynamic = parseDynamicSegment(segment);\n          return (\n            dynamic &&\n            Object.keys(params).every((key) => key === dynamic.name) &&\n            (Object.prototype.hasOwnProperty.call(params, dynamic.name) || dynamic.optional)\n          );\n        }),\n    );\n    if (candidates.size !== 1)\n      throw new TypeError(\n        `Cannot bind route params at ${path}: supply exactly the next dynamic segment's parameter.`,\n      );\n    const segment = [...candidates][0]!;\n    const dynamic = parseDynamicSegment(segment)!;\n    encodeParameter(dynamic, params[dynamic.name]);\n    return {\n      segment,\n      params: Object.freeze(\n        Object.fromEntries(\n          Object.entries(params).map(([key, value]) => [\n            key,\n            Array.isArray(value) ? Object.freeze([...value]) : value,\n          ]),\n        ),\n      ),\n    };\n  }\n\n  resolve(\n    path: string,\n    method: string,\n    bound: BoundRouteParams,\n    input?: { params?: unknown },\n  ): string {\n    const normalized = path.replace(/\\/$/, \"\");\n    const supplied = readParams(input?.params);\n    const candidates = [...this.routes.values()].filter((route) => {\n      if (route.path === normalized) return true;\n      if (!route.path.startsWith(`${normalized}/`)) return false;\n      const tail = route.path.slice(normalized.length + 1);\n      return (\n        !tail.includes(\"/\") && Boolean(parseDynamicSegment(tail)) && input?.params !== undefined\n      );\n    });\n    const selected = candidates.filter((route) => {\n      const unbound = route.path\n        .split(\"/\")\n        .map(parseDynamicSegment)\n        .filter((part) => part && !Object.prototype.hasOwnProperty.call(bound, part.name));\n      return (\n        Object.keys(supplied).every((key) => unbound.some((part) => part!.name === key)) &&\n        unbound.every(\n          (part) => part!.optional || Object.prototype.hasOwnProperty.call(supplied, part!.name),\n        )\n      );\n    });\n    if (selected.length !== 1)\n      throw new TypeError(\n        `Cannot resolve ${method} ${normalized}: missing, unexpected, or ambiguous route params.`,\n      );\n    const route = selected[0]!;\n    if (!route.methods.includes(method) && !(method === \"HEAD\" && route.methods.includes(\"GET\"))) {\n      throw new TypeError(`${method} is not registered for ${route.path}.`);\n    }\n    const params = { ...bound, ...supplied };\n    const resolved = route.path\n      .split(\"/\")\n      .map((segment) => {\n        const dynamic = parseDynamicSegment(segment);\n        return dynamic ? encodeParameter(dynamic, params[dynamic.name]) : segment;\n      })\n      .filter(Boolean)\n      .join(\"/\");\n    const pathname = `/${resolved}`;\n    const winner = matchAPIRoute(this.routes, pathname);\n    if (winner?.route.path !== route.path) {\n      throw new TypeError(\n        `Route ${route.path} resolves to ${pathname}, which is shadowed by ${winner?.route.path ?? \"another route\"}.`,\n      );\n    }\n    return pathname;\n  }\n}\n\nfunction readParams(input: unknown): Record<string, string | readonly string[]> {\n  if (input === undefined) return {};\n  if (\n    !input ||\n    typeof input !== \"object\" ||\n    Array.isArray(input) ||\n    ![Object.prototype, null].includes(Object.getPrototypeOf(input))\n  ) {\n    throw new TypeError(\"Route params must be a plain object.\");\n  }\n  for (const key of Object.keys(input)) {\n    if ([\"__proto__\", \"constructor\", \"prototype\"].includes(key))\n      throw new TypeError(`Unsafe route parameter ${key}.`);\n  }\n  return input as Record<string, string | readonly string[]>;\n}\n\nfunction encodeParameter(\n  parameter: { name: string; catchAll: boolean; optional: boolean },\n  value: unknown,\n): string {\n  if (parameter.optional && value === undefined) return \"\";\n  const parts = parameter.catchAll ? value : [value];\n  if (!Array.isArray(parts) || (!parts.length && !parameter.optional)) {\n    throw new TypeError(\n      `Route parameter ${parameter.name} must be ${parameter.catchAll ? \"a non-empty array of strings\" : \"a string\"}.`,\n    );\n  }\n  return Array.from(parts, (part) => {\n    if (\n      typeof part !== \"string\" ||\n      !part ||\n      part === \".\" ||\n      part === \"..\" ||\n      Array.from(part).some(\n        (character) =>\n          character.charCodeAt(0) <= 31 ||\n          (character.charCodeAt(0) >= 127 && character.charCodeAt(0) <= 159),\n      )\n    ) {\n      throw new TypeError(`Invalid value for route parameter ${parameter.name}.`);\n    }\n    return encodeURIComponent(part);\n  }).join(\"/\");\n}\n","import {\n  integrationsClient,\n  integrationsServer,\n  type IntegrationClientOptions,\n  type IntegrationClientRoot,\n  type IntegrationServerClientOptions,\n  type IntegrationServerClientRoot,\n} from \"../integration-client\";\nimport {\n  FarmClientDataCache,\n  getFarmClientDataCache,\n  normalizeFarmClientCacheKey,\n  type FarmClientCacheEntry,\n  type FarmClientCacheKey,\n} from \"../client-cache\";\nimport {\n  applyFarmCacheInvalidations,\n  decodeFarmCacheInvalidations,\n  FARM_CACHE_INVALIDATION_HEADER,\n} from \"../cache-invalidation\";\nimport type { DefinedCacheKey, InferCacheKeyData, RouteDataCacheKey } from \"../cache\";\nimport { getFarmAPIBaseURL, resolveFarmAPIRequestURL } from \"./config\";\nimport { ClientRouteManifest, type APIRouteManifest, type BoundRouteParams } from \"./client-routes\";\nimport type { RoutePathParams } from \"./route\";\nimport { _resolveCurrentRequest } from \"../server/request-bridge\";\nimport { resolveClientHeaders, type ClientHeaders } from \"../client-headers\";\nimport { createClientCancellation } from \"../client-cancellation\";\nimport { notifyClientObserver, type ClientLifecycleHooks } from \"../client-observers\";\nimport { resolveAPIRequestRuntime, type APIRequestRuntime } from \"./server-client-bridge\";\nexport type { APIRouteManifest } from \"./client-routes\";\nimport {\n  isFarmAPIStream,\n  isJSONStreamResponse,\n  readJSONStream,\n  type FarmAPIStream,\n} from \"./transport\";\n\nexport const FARM_API_ROUTE_REF_SYMBOL: unique symbol = Symbol.for(\"farm.api.route-ref\") as any;\nexport const FARM_API_ROUTE_META_SYMBOL: unique symbol = Symbol.for(\"farm.api.route-meta\") as any;\n\nexport type APIRouteRefMetadata = {\n  path: string;\n  method: string;\n  baseURL: string;\n  sameOrigin: boolean;\n};\n\nexport type APIClientOptions = ClientLifecycleHooks & {\n  /** Generated path/method metadata required for dynamic shorthand and $params scopes. */\n  routes?: APIRouteManifest;\n  baseURL?: string;\n  headers?: ClientHeaders;\n  credentials?: RequestCredentials;\n  /** Whole-call deadline in milliseconds. 0 (default) disables it. */\n  timeoutMs?: number;\n  /** HTTP transport only; local server dispatch does not use it. */\n  fetch?: typeof globalThis.fetch;\n  cacheDefaults?: CacheOptions;\n  integrations?: IntegrationClientOptions;\n};\n\nexport type APIClientWithoutIntegrationsOptions = Omit<APIClientOptions, \"integrations\"> & {\n  integrations: false;\n};\n\nexport type ServerAPIClientOptions = {\n  integrations?: Omit<IntegrationServerClientOptions, \"isServer\">;\n};\n\nexport type ServerAPIClientWithoutIntegrationsOptions = Omit<\n  ServerAPIClientOptions,\n  \"integrations\"\n> & {\n  integrations: false;\n};\n\nexport type StatusPhase = \"idle\" | \"pending\" | \"success\" | \"error\" | \"revalidating\" | \"invalidated\";\n\nexport type StatusEvent<TData = unknown, TError = unknown> = {\n  phase: StatusPhase;\n  requestId: string;\n  method: \"GET\" | \"HEAD\" | \"QUERY\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\" | \"OPTIONS\";\n  key: string;\n  input?: unknown;\n  data?: TData;\n  error?: TError;\n  isBackground?: boolean;\n  timestamp: number;\n};\n\nexport type CacheKey<TData = unknown> = string & {\n  readonly __farmCacheData?: TData;\n};\n\nexport type APIResult<TData = unknown, TError = Error> = {\n  data: TData | undefined;\n  error: TError | null;\n  key: CacheKey<TData>;\n};\n\nexport class APIClientError<\n  TCode extends string = string,\n  TData = unknown,\n  TStatus extends number = number,\n> extends Error {\n  readonly code: TCode;\n  readonly data: TData;\n  readonly status: TStatus;\n  readonly response?: Response;\n\n  constructor(\n    code: TCode,\n    data: TData,\n    options: {\n      status: TStatus;\n      message: string;\n      response?: Response;\n    },\n  ) {\n    super(options.message);\n    this.name = \"APIClientError\";\n    this.code = code;\n    this.data = data;\n    this.status = options.status;\n    this.response = options.response;\n  }\n}\n\nexport type APIClientSystemError =\n  | APIClientError<\"http_error\", unknown, number>\n  | APIClientError<\"aborted\" | \"timeout\", unknown, 0>\n  | APIClientError<\"network_error\", unknown, 0>;\n\nexport type RequestEvent = {\n  requestId: string;\n  method: StatusEvent[\"method\"];\n  key: string;\n  path: string;\n  input?: unknown;\n  attempt: number;\n  timestamp: number;\n};\n\nexport type ResponseEvent<TData = unknown, TError = Error> = {\n  requestId: string;\n  method: StatusEvent[\"method\"];\n  key: string;\n  path: string;\n  input?: unknown;\n  attempt: number;\n  timestamp: number;\n  response?: Response;\n  data?: TData;\n  error?: TError;\n  ok?: boolean;\n  status?: number;\n};\n\nexport type CachePolicy = \"cache-first\" | \"network-only\" | \"stale-while-revalidate\";\nexport type CacheScope = \"client\" | \"shared\";\n\nexport type CacheOptions = {\n  key?: FarmClientCacheKey;\n  policy?: CachePolicy;\n  /** Select client-local or public shared storage. Identity-carrying requests always stay local. */\n  scope?: CacheScope;\n  staleTime?: number;\n  gcTime?: number;\n  dedupeMs?: number;\n  /** Allow the configured client cache persistence adapter to store this read. */\n  persist?: boolean;\n};\n\nexport type RetryAttemptContext = {\n  /** Zero-based index of the attempt that just failed. */\n  attempt: number;\n  /** Upper-case HTTP method of the request. */\n  method: string;\n  /** Response status, or undefined when the request never produced a response. */\n  status?: number;\n  error: Error;\n};\n\nexport type RetryOptions = {\n  count?: number;\n  delay?: number | ((attempt: number) => number);\n  /**\n   * Decide whether a failed attempt should be retried.\n   *\n   * Defaults to transient failures of idempotent requests only: replaying a\n   * POST or PATCH whose response was lost duplicates the write it performed.\n   * Supply this to opt a specific call in or out.\n   */\n  shouldRetry?: (context: RetryAttemptContext) => boolean;\n};\n\n/**\n * Methods whose replay has the same effect as a single call, so a retry cannot\n * duplicate work: the idempotent set from RFC 9110, plus QUERY, which Farm\n * supports as a read that carries a body.\n */\nconst FARM_IDEMPOTENT_METHODS = new Set([\"GET\", \"HEAD\", \"OPTIONS\", \"PUT\", \"DELETE\", \"QUERY\"]);\n\n/** Statuses that represent a transient condition worth another attempt. */\nconst FARM_RETRYABLE_STATUSES = new Set([408, 425, 429]);\n\nfunction isFarmRetryableFailure(context: RetryAttemptContext): boolean {\n  // A non-idempotent request may already have been applied by the server even\n  // when the client never saw the response, so it is never retried by default.\n  if (!FARM_IDEMPOTENT_METHODS.has(context.method)) return false;\n  // No response at all: a transport failure, which is the transient case retries\n  // exist for.\n  if (context.status === undefined) return true;\n  return context.status >= 500 || FARM_RETRYABLE_STATUSES.has(context.status);\n}\n\nexport type InvalidateTarget =\n  | FarmClientCacheKey\n  | {\n      key: FarmClientCacheKey;\n    }\n  | {\n      path: string;\n      method?: \"GET\" | \"HEAD\" | \"QUERY\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\" | \"OPTIONS\";\n      input?: unknown;\n    }\n  | [CallableRouteRef<any>, unknown?];\n\nexport type InvalidateOptions =\n  | InvalidateTarget[]\n  | {\n      targets: InvalidateTarget[];\n      refetch?: boolean;\n    };\n\nexport type OptimisticUpdate =\n  | [CallableRouteRef<any>, unknown, (prev: any) => any]\n  | [CacheKey<any> | DefinedCacheKey<any> | string, (prev: any) => any];\n\nexport type OptimisticOptions<TUpdates extends readonly unknown[] = readonly OptimisticUpdate[]> = {\n  update: TUpdates & NormalizeOptimisticUpdates<TUpdates>;\n  rollbackOnError?: boolean;\n};\n\nexport type ClientOptions<\n  TData = unknown,\n  TError = unknown,\n  TUpdates extends readonly unknown[] = readonly OptimisticUpdate[],\n> = {\n  key?: CacheKey<TData> | FarmClientCacheKey;\n  signal?: AbortSignal;\n  /** Override the instance deadline; 0 disables it for this call. */\n  timeoutMs?: number;\n  cache?: CacheOptions;\n  retry?: RetryOptions;\n  invalidate?: InvalidateOptions;\n  optimistic?: OptimisticOptions<TUpdates>;\n  onRequest?: (event: RequestEvent) => void;\n  onResponse?: (\n    data: TData | undefined,\n    error: TError | null,\n    event: ResponseEvent<TData, TError>,\n  ) => void;\n  onSuccess?: (data: TData) => void;\n  onError?: (err: TError) => void;\n  onSettled?: (data?: TData, err?: TError | null) => void;\n  onStatus?: (event: StatusEvent<TData, TError>) => void;\n};\n\ntype AnyRouteRef = (...args: any[]) => any;\ntype RouteRef<TData = any, TInput = any> = {\n  readonly __farmRouteInput: TInput;\n  readonly __farmRouteData: TData;\n};\ntype CallableRouteRef<TData = any, TInput = any> = AnyRouteRef & RouteRef<TData, TInput>;\n\ntype InferRouteInput<TRoute> = TRoute extends { readonly __farmRouteInput: infer TInput }\n  ? TInput\n  : never;\ntype InferRouteData<TRoute> = TRoute extends { readonly __farmRouteData: infer TData }\n  ? TData\n  : never;\n\ntype NormalizeOptimisticUpdate<TUpdate> = TUpdate extends readonly [\n  infer TRoute,\n  unknown,\n  (prev: any) => any,\n]\n  ? TRoute extends RouteRef<any, any>\n    ? [\n        TRoute,\n        InferRouteInput<TRoute> | undefined,\n        (prev: InferRouteData<TRoute> | undefined) => InferRouteData<TRoute>,\n      ]\n    : never\n  : TUpdate extends readonly [infer TKey, (prev: any) => any]\n    ? TKey extends DefinedCacheKey<any, RouteDataCacheKey>\n      ? [TKey, (prev: InferCacheKeyData<TKey> | undefined) => InferCacheKeyData<TKey>]\n      : TKey extends CacheKey<infer TData>\n        ? [TKey, (prev: TData | undefined) => TData]\n        : TKey extends string\n          ? [TKey, (prev: unknown) => unknown]\n          : never\n    : never;\n\ntype NormalizeOptimisticUpdates<TUpdates extends readonly unknown[]> = {\n  [K in keyof TUpdates]: NormalizeOptimisticUpdate<TUpdates[K]>;\n};\n\ntype TypedEndpointLike = {\n  __types: {\n    body: any;\n    query: any;\n    response: any;\n    errors?: any;\n  };\n};\n\ntype Simplify<T> = {\n  [K in keyof T]: T[K];\n} & {};\n\ntype IsNever<T> = [T] extends [never] ? true : false;\ntype IsAny<T> = 0 extends 1 & T ? true : false;\ntype RequiredKeys<T> = T extends object\n  ? {\n      [K in keyof T]-?: {} extends Pick<T, K> ? never : K;\n    }[keyof T]\n  : never;\n\ntype BodyInputProp<TValue> =\n  IsNever<TValue> extends true\n    ? {}\n    : IsAny<TValue> extends true\n      ? { body?: TValue }\n      : undefined extends TValue\n        ? { body?: TValue }\n        : { body: TValue };\n\ntype QueryInputProp<TValue> =\n  IsNever<TValue> extends true\n    ? {}\n    : IsAny<TValue> extends true\n      ? { query?: TValue }\n      : undefined extends TValue\n        ? { query?: TValue }\n        : RequiredKeys<TValue> extends never\n          ? { query?: TValue }\n          : { query: TValue };\n\ntype HasRequiredKeys<T> = RequiredKeys<T> extends never ? false : true;\n\n// Type utilities to extract endpoint input/output types from TypedEndpoint\ntype InferEndpointBody<T> = T extends {\n  __types: {\n    inputBody: infer TInputBody;\n  };\n}\n  ? TInputBody\n  : T extends {\n        __types: {\n          body: infer TBody;\n        };\n      }\n    ? TBody\n    : never;\n\ntype InferEndpointInput<T> = T extends {\n  __types: {\n    query: infer TQuery;\n  };\n}\n  ? Simplify<\n      BodyInputProp<InferEndpointBody<T>> &\n        QueryInputProp<T extends { __types: { inputQuery: infer I } } ? I : TQuery> &\n        (T extends { __routeParams: infer P }\n          ? keyof P extends never\n            ? { params?: never }\n            : { params: P }\n          : {}) &\n        (T extends { __types: { inputHeaders: infer H } }\n          ? IsNever<H> extends true\n            ? {}\n            : RequiredKeys<H> extends never\n              ? { headers?: H }\n              : { headers: H }\n          : {})\n    >\n  : T extends { __routeParams: infer P }\n    ? keyof P extends never\n      ? { params?: never }\n      : { params: P }\n    : {};\n\ntype InferEndpointOutput<T> = T extends {\n  __types: {\n    response: infer R;\n  };\n}\n  ? R extends { readonly __farmStreamItem: infer TItem }\n    ? FarmAPIStream<TItem>\n    : R\n  : any;\n\ntype InferEndpointError<T> = T extends {\n  __types: {\n    errors: infer TErrors;\n  };\n}\n  ? keyof TErrors extends never\n    ? Error\n    :\n        | {\n            [TCode in keyof TErrors]: TErrors[TCode] extends {\n              data: infer TData;\n              status: infer TStatus extends number;\n            }\n              ? APIClientError<TCode & string, TData, TStatus>\n              : never;\n          }[keyof TErrors]\n        | APIClientSystemError\n  : Error;\n\n// Type for a single endpoint method\ntype EndpointCall<T = any> = <TUpdates extends readonly unknown[] = readonly OptimisticUpdate[]>(\n  ...args: HasRequiredKeys<InferEndpointInput<T>> extends true\n    ? [\n        options: InferEndpointInput<T>,\n        clientOptions?: ClientOptions<InferEndpointOutput<T>, InferEndpointError<T>, TUpdates>,\n      ]\n    : [\n        options?: InferEndpointInput<T>,\n        clientOptions?: ClientOptions<InferEndpointOutput<T>, InferEndpointError<T>, TUpdates>,\n      ]\n) => Promise<APIResult<InferEndpointOutput<T>, InferEndpointError<T>>>;\ntype EndpointMethod<T = any> = EndpointCall<T> &\n  RouteRef<InferEndpointOutput<T>, InferEndpointInput<T>>;\n\ntype DynamicKeys<T> = Extract<keyof T, `[${string}]`>;\ntype MethodKeys = \"get\" | \"head\" | \"query\" | \"post\" | \"put\" | \"patch\" | \"delete\" | \"options\";\ntype OwnMethodKeys<T> = {\n  [K in Extract<keyof T, MethodKeys>]: T[K] extends TypedEndpointLike | ((...args: any[]) => any)\n    ? K\n    : never;\n}[Extract<keyof T, MethodKeys>];\ntype WithRouteParams<T, P> = T & { __routeParams: P };\ntype UnionToIntersection<U> = (U extends unknown ? (v: U) => void : never) extends (\n  v: infer I,\n) => void\n  ? I\n  : never;\ntype ChildMethods<T> = { [K in DynamicKeys<T>]: OwnMethodKeys<T[K]> }[DynamicKeys<T>];\ntype MethodEndpoints<T, M extends PropertyKey, P> =\n  | (M extends OwnMethodKeys<T> ? WithRouteParams<T[M], P> : never)\n  | {\n      [K in DynamicKeys<T>]: M extends keyof T[K]\n        ? WithRouteParams<T[K][M], P & RoutePathParams<K>>\n        : never;\n    }[DynamicKeys<T>];\ntype DistributedCall<T> = T extends unknown ? EndpointCall<T> : never;\ntype ScopedMethod<T> = UnionToIntersection<DistributedCall<T>> &\n  EndpointCall<T> &\n  RouteRef<InferEndpointOutput<T>, InferEndpointInput<T>>;\n\n// Keep bracket access for compatibility; explicit binding preserves intermediate segments.\ntype RouterToClient<T, P = {}> = {\n  [K in Exclude<keyof T, OwnMethodKeys<T>>]: T[K] extends TypedEndpointLike\n    ? EndpointMethod<WithRouteParams<T[K], P>>\n    : T[K] extends Record<string, any>\n      ? RouterToClient<T[K], P & (K extends string ? RoutePathParams<K> : {})>\n      : EndpointMethod<WithRouteParams<T[K], P>>;\n} & {\n  [M in OwnMethodKeys<T> | ChildMethods<T>]: M extends ChildMethods<T>\n    ? ScopedMethod<MethodEndpoints<T, M, P>>\n    : M extends keyof T\n      ? EndpointMethod<WithRouteParams<T[M], P>>\n      : never;\n} & ([DynamicKeys<T>] extends [never]\n    ? {}\n    : {\n        $params: UnionToIntersection<\n          {\n            [K in DynamicKeys<T>]: (params: RoutePathParams<K>) => RouterToClient<T[K], P>;\n          }[DynamicKeys<T>]\n        >;\n      });\n\nexport type RouteAPIClient<TRouter extends Record<string, any>> = RouterToClient<TRouter>;\n\nexport type APIClient<\n  TRouter extends Record<string, any>,\n  TIntegrations extends Record<string, any> = {},\n> = RouteAPIClient<TRouter> & IntegrationClientRoot<TIntegrations>;\n\nexport type ServerAPIClient<\n  TEndpoints extends Record<string, any>,\n  TIntegrations extends Record<string, any> = {},\n> = TEndpoints & IntegrationServerClientRoot<TIntegrations>;\n\nexport type ApiClients<\n  TRouter extends Record<string, any>,\n  TIntegrations extends Record<string, any> = {},\n> = {\n  api: RouteAPIClient<TRouter> & IntegrationServerClientRoot<TIntegrations>;\n  apiClient: APIClient<TRouter, TIntegrations>;\n};\n\n/**\n * Define one shared pair of typed callers. Import only generated route metadata\n * here, not endpoint modules. `api` dispatches locally during a Farm request;\n * `apiClient` uses HTTP. Both return the same app-route APIResult shape.\n */\nexport function createApiClients<TRouter extends Record<string, any>>(\n  options: APIClientWithoutIntegrationsOptions,\n): { api: RouteAPIClient<TRouter>; apiClient: RouteAPIClient<TRouter> };\nexport function createApiClients<\n  TRouter extends Record<string, any>,\n  TIntegrations extends Record<string, any> = {},\n>(options?: APIClientOptions): ApiClients<TRouter, TIntegrations>;\nexport function createApiClients<\n  TRouter extends Record<string, any>,\n  TIntegrations extends Record<string, any> = {},\n>(\n  options: APIClientOptions | APIClientWithoutIntegrationsOptions = {},\n): ApiClients<TRouter, TIntegrations> {\n  // A module-level pair is safe across requests. No cache, credentials, or\n  // dispatcher from one request is retained by another request's caller.\n  const localScopes = new WeakMap<APIRequestRuntime, WeakMap<Request, { request: APICall }>>();\n  const routeMeta = new WeakMap<AnyRouteRef, RouteMeta>();\n  const api = createNestedProxy(\n    [],\n    async (path: string, method: string, input: any, clientOptions?: ClientOptions<any, any>) => {\n      if (typeof window !== \"undefined\") {\n        throw new Error(\n          \"api is server-only. Use apiClient from createApiClients() in the browser.\",\n        );\n      }\n      const currentRequest = _resolveCurrentRequest();\n      const runtime = resolveAPIRequestRuntime();\n      if (!currentRequest || !runtime) {\n        throw new Error(\n          \"api requires an active Farm server request. Call it from a server page, query, action, or API handler; use apiClient with an absolute baseURL for standalone HTTP calls.\",\n        );\n      }\n      let localClients = localScopes.get(runtime);\n      if (!localClients) {\n        localClients = new WeakMap();\n        localScopes.set(runtime, localClients);\n      }\n      let local = localClients.get(currentRequest);\n      if (!local) {\n        const origin = new URL(currentRequest.url).origin;\n        const headers = new Headers();\n        // Only identity/content negotiation headers are inherited. In\n        // particular, never copy the outer request's body or hop-by-hop fields.\n        for (const name of [\"cookie\", \"authorization\", \"accept-language\"]) {\n          const value = currentRequest.headers.get(name);\n          if (value !== null) headers.set(name, value);\n        }\n        local = createAPIClientRuntime(\n          {\n            ...options,\n            integrations: false,\n            baseURL: new URL(runtime.basePath, origin).toString(),\n          },\n          {\n            headers,\n            signal: currentRequest.signal,\n            cache: new FarmClientDataCache({ subscribeToInvalidation: false }),\n            routeMeta,\n            fetch: (url, init) => {\n              if (new URL(url).origin !== origin) {\n                throw new Error(\n                  \"api can only dispatch to this Farm app. Use apiClient for HTTP calls.\",\n                );\n              }\n              currentRequest.signal.throwIfAborted();\n              return runtime.dispatch(new Request(url, init));\n            },\n          },\n        );\n        localClients.set(currentRequest, local);\n      }\n      return local.request(path, method, input, clientOptions);\n    },\n    routeMeta,\n    \"/api\",\n    true,\n    options.integrations === false\n      ? undefined\n      : {\n          integrations: integrationsServer<TIntegrations>({\n            baseURL: options.baseURL,\n            headers: options.headers,\n            credentials: options.credentials,\n            timeoutMs: options.timeoutMs,\n            fetch: options.fetch,\n            onRequest: options.onRequest,\n            onResponse: options.onResponse,\n            onError: options.onError,\n            ...options.integrations,\n          }),\n        },\n    options.routes ? new ClientRouteManifest(options.routes) : undefined,\n  );\n  return {\n    api: api as ApiClients<TRouter, TIntegrations>[\"api\"],\n    apiClient: createAPIClient<TRouter, TIntegrations>(options as APIClientOptions),\n  };\n}\n\n/**\n * Create a typed RPC client for Farm.js API routes\n *\n * Returns a nested proxy that supports:\n * - api.hello.get({ query: { name: 'World' } })\n * - api['auth/login'].post({ body: { email: '...', password: '...' } })\n * - api.users.get({ query: { limit: '10' } })\n * - api.integrations.billing.checkout({ body: { priceId: 'price_...' } })\n *\n * @example\n * ```typescript\n * import { createAPIClient } from 'farm/client';\n * import type { APIRouter } from '@/api';\n * import type { AppIntegrations } from '@/lib/integrations';\n *\n * export const api = createAPIClient<APIRouter, AppIntegrations>();\n *\n * // Use it (nested property access)\n * const result = await api.hello.get({ query: { name: 'World' } });\n * if (result.error) console.error(result.error);\n * else console.log(result.data);\n *\n * // Or with string keys for nested paths\n * const result = await api['auth/login'].post({\n *   body: { email: 'test@example.com', password: 'pass123' }\n * });\n *\n * // Integration APIs live under a reserved namespace.\n * const checkout = await api.integrations.billing.checkout({\n *   body: { priceId: 'price_123' }\n * });\n * ```\n */\nexport function createAPIClient<TRouter extends Record<string, any>>(\n  options: APIClientWithoutIntegrationsOptions,\n): RouteAPIClient<TRouter>;\nexport function createAPIClient<\n  TRouter extends Record<string, any>,\n  TIntegrations extends Record<string, any> = {},\n>(options?: APIClientOptions): APIClient<TRouter, TIntegrations>;\nexport function createAPIClient<\n  TRouter extends Record<string, any>,\n  TIntegrations extends Record<string, any> = {},\n>(\n  options: APIClientOptions | APIClientWithoutIntegrationsOptions = {},\n): RouteAPIClient<TRouter> | APIClient<TRouter, TIntegrations> {\n  return createAPIClientRuntime<TRouter, TIntegrations>(options).client;\n}\n\ntype APICall = (\n  path: string,\n  method: string,\n  input?: any,\n  options?: ClientOptions<any, any>,\n) => Promise<APIResult<any, Error>>;\n\nfunction createAPIClientRuntime<\n  TRouter extends Record<string, any>,\n  TIntegrations extends Record<string, any> = {},\n>(\n  options: APIClientOptions | APIClientWithoutIntegrationsOptions = {},\n  transport?: {\n    headers?: HeadersInit;\n    signal?: AbortSignal;\n    fetch(url: string, init: RequestInit): Promise<Response>;\n    cache: FarmClientDataCache;\n    routeMeta: WeakMap<AnyRouteRef, RouteMeta>;\n  },\n): { client: APIClient<TRouter, TIntegrations>; request: APICall } {\n  options ??= {};\n  const baseURL = options.baseURL || getFarmAPIBaseURL();\n  const httpFetch = options.fetch;\n  const integrationOptions =\n    options.integrations === false\n      ? false\n      : {\n          baseURL: options.baseURL,\n          headers: options.headers,\n          credentials: options.credentials,\n          timeoutMs: options.timeoutMs,\n          fetch: httpFetch,\n          onRequest: options.onRequest,\n          onResponse: options.onResponse,\n          onError: options.onError,\n          ...(typeof options.integrations === \"object\" ? options.integrations : {}),\n        };\n  const rootAliases =\n    integrationOptions === false\n      ? undefined\n      : {\n          integrations: integrationsClient<TIntegrations>(integrationOptions),\n        };\n\n  const sharedCacheState = transport?.cache ?? getFarmClientDataCache();\n  const localCaches = transport ? new Set([sharedCacheState]) : undefined;\n  const sharedInflightState = new Map<string, InflightEntry>();\n  let scopedRequestState: ScopedRequestState | undefined;\n  const routeMeta = transport?.routeMeta ?? new WeakMap<AnyRouteRef, RouteMeta>();\n  let requestCounter = 0;\n\n  // Create a simple fetch-based client (browser compatible)\n  const fetchClient = async (\n    path: string,\n    requestOptions: any,\n    defaultHeaders: Headers,\n    cancellation: ReturnType<typeof createClientCancellation>,\n  ) => {\n    const url = resolveFarmAPIRequestURL(path, baseURL);\n    const method = String(requestOptions.method || \"GET\").toUpperCase();\n\n    // Handle query parameters\n    if (requestOptions.query) {\n      Object.entries(requestOptions.query).forEach(([key, value]) => {\n        if (value === undefined || value === null) return;\n        url.searchParams.delete(key);\n        const values = Array.isArray(value) ? value : [value];\n        for (const item of values) {\n          if (item !== undefined && item !== null) url.searchParams.append(key, String(item));\n        }\n      });\n    }\n\n    // Prepare fetch options\n    const headers = new Headers(defaultHeaders);\n    new Headers(requestOptions.headers).forEach((value, key) => headers.set(key, value));\n    const fetchOptions: RequestInit = {\n      method,\n      headers,\n      credentials: options.credentials,\n      signal: cancellation.signal,\n    };\n    if (method === \"QUERY\" && !headers.has(\"content-type\")) {\n      headers.set(\"content-type\", \"application/json\");\n    }\n\n    // Handle body\n    if (requestOptions.body !== undefined) {\n      if (isFormData(requestOptions.body)) {\n        headers.delete(\"content-type\");\n        fetchOptions.body = requestOptions.body;\n      } else {\n        if (!headers.has(\"content-type\")) headers.set(\"content-type\", \"application/json\");\n        fetchOptions.body = JSON.stringify(requestOptions.body);\n      }\n    }\n\n    cancellation.check();\n    const response = await (transport?.fetch ?? httpFetch ?? fetch)(url.toString(), fetchOptions);\n    cancellation.check();\n    const invalidations = decodeFarmCacheInvalidations(\n      response.headers?.get?.(FARM_CACHE_INVALIDATION_HEADER),\n    );\n    if (transport) {\n      for (const cache of localCaches!) {\n        for (const key of invalidations) cache.invalidate(key);\n      }\n    } else {\n      applyFarmCacheInvalidations(invalidations);\n    }\n    let data: unknown;\n    try {\n      data = await readAPIResponseData(response, method);\n      cancellation.check();\n    } catch (decodeError) {\n      if (!(decodeError instanceof APIResponseDecodeError)) throw decodeError;\n      if (response.ok) throw decodeError.cause;\n      return { response, data: undefined, decodeError: decodeError.cause };\n    }\n\n    return { response, data };\n  };\n\n  const request = async (\n    path: string,\n    method: string,\n    input: any = {},\n    clientOptions?: ClientOptions<any, any>,\n  ): Promise<APIResult<any, Error>> => {\n    const cancellation = createClientCancellation(\n      clientOptions?.signal,\n      clientOptions?.timeoutMs ?? options.timeoutMs,\n      transport?.signal,\n    );\n    const normalizeCallError = (error: unknown): Error => {\n      if (!cancellation.signal?.aborted) return normalizeError(error);\n      const normalized = new APIClientError(\n        cancellation.timedOut ? \"timeout\" : \"aborted\",\n        undefined,\n        {\n          status: 0,\n          message: cancellation.timedOut ? \"Client request timed out\" : \"Client request aborted\",\n        },\n      );\n      (normalized as Error & { cause?: unknown }).cause = cancellation.signal.reason;\n      return normalized;\n    };\n    try {\n      const methodUpper = method.toUpperCase() as StatusEvent[\"method\"];\n      const requestId = `${Date.now()}-${++requestCounter}`;\n      const defaultHeaders = new Headers(transport?.headers);\n      let requestContextError: Error | undefined;\n      try {\n        cancellation.check();\n        const resolved = resolveClientHeaders(options.headers);\n        const headers =\n          resolved instanceof Headers ? resolved : await cancellation.run(() => resolved);\n        cancellation.check();\n        headers.forEach((value, name) => defaultHeaders.set(name, value));\n      } catch (error) {\n        requestContextError = normalizeCallError(error);\n      }\n      const cacheOptions = clientOptions?.cache\n        ? {\n            ...options.cacheDefaults,\n            ...clientOptions.cache,\n          }\n        : undefined;\n      const configuredCacheKey = clientOptions?.key ?? cacheOptions?.key;\n      const cacheKey = normalizeFarmClientCacheKey(\n        configuredCacheKey ?? buildCacheKey(methodUpper, path, input, baseURL, defaultHeaders),\n      ) as CacheKey<any>;\n      const now = Date.now();\n\n      const emitStatus = (phase: StatusPhase, payload?: Partial<StatusEvent>) => {\n        clientOptions?.onStatus?.({\n          phase,\n          requestId,\n          method: methodUpper,\n          key: cacheKey,\n          input,\n          timestamp: Date.now(),\n          ...payload,\n        });\n      };\n\n      const policy = cacheOptions?.policy ?? (cacheOptions ? \"cache-first\" : \"network-only\");\n      const staleTime = cacheOptions?.staleTime ?? 0;\n      const hasReliableDefaultCacheKey =\n        methodUpper !== \"QUERY\" || !isFormData(input?.body) || configuredCacheKey !== undefined;\n      const isCacheEnabled =\n        Boolean(cacheOptions) &&\n        (methodUpper === \"GET\" || methodUpper === \"QUERY\") &&\n        hasReliableDefaultCacheKey;\n      const needsCacheState =\n        isCacheEnabled ||\n        Boolean(clientOptions?.optimistic?.update?.length) ||\n        Boolean(clientOptions?.invalidate);\n      let requestCacheContext: string | undefined = undefined;\n      if (needsCacheState && !requestContextError) {\n        try {\n          requestCacheContext = getRequestCacheContext(\n            { headers: defaultHeaders, credentials: options.credentials },\n            input,\n            // Custom transports can inject an identity outside visible headers.\n            // Never share their cached data with other client instances.\n            httpFetch ? \"client\" : cacheOptions?.scope,\n          );\n        } catch (error) {\n          requestContextError = normalizeError(error);\n        }\n      }\n\n      let cacheState = sharedCacheState;\n      let inflightState = sharedInflightState;\n      let requestScopedState: ScopedRequestState | undefined;\n      if (requestCacheContext !== undefined) {\n        if (scopedRequestState && scopedRequestState.context !== requestCacheContext) {\n          scopedRequestState.retired = true;\n          if (scopedRequestState.inflight.size === 0) scopedRequestState.cache.dispose();\n          scopedRequestState = undefined;\n        }\n        scopedRequestState ??= {\n          context: requestCacheContext,\n          cache: new FarmClientDataCache({ subscribeToInvalidation: !transport }),\n          inflight: new Map(),\n          retired: false,\n        };\n        requestScopedState = scopedRequestState;\n        cacheState = requestScopedState.cache;\n        localCaches?.add(cacheState);\n        inflightState = requestScopedState.inflight;\n      }\n      const optimisticState = getOptimisticState(cacheState);\n\n      const entry = getValidCacheEntry(cacheState, cacheKey, now);\n      const isStale = entry ? isEntryStale(entry, now) : true;\n\n      const applyOptimisticUpdates = () => {\n        if (!clientOptions?.optimistic?.update?.length) return [] as OptimisticSnapshot[];\n\n        const snapshots = new Map<string, OptimisticSnapshot>();\n        for (const update of clientOptions.optimistic.update) {\n          const [target, targetInput, updater] =\n            update.length === 2\n              ? [update[0], undefined, update[1]]\n              : [update[0], update[1], update[2]];\n          const targetKey = resolveTargetKey(\n            routeMeta,\n            target,\n            targetInput,\n            baseURL,\n            defaultHeaders,\n            transport ? baseURL : undefined,\n          );\n          if (!targetKey) continue;\n\n          const targetEntry = getValidCacheEntry(cacheState, targetKey, now);\n          const currentEntry = cacheState.get(targetKey);\n          let stack = optimisticState.get(targetKey);\n          if (stack && !reconcileOptimisticInvalidation(cacheState, targetKey, stack)) {\n            stack = undefined;\n          }\n          if (!stack) {\n            stack = {\n              entry: targetEntry ? { ...targetEntry } : undefined,\n              layers: [],\n              renderedEntry: currentEntry,\n            };\n            optimisticState.set(targetKey, stack);\n          }\n\n          let snapshot = snapshots.get(targetKey);\n          if (!snapshot) {\n            const previousEntry = stack.layers.length === 0 ? stack.entry : stack.renderedEntry;\n            const layer: OptimisticLayer = {\n              updaters: [],\n              updatedAt: now,\n              staleAt:\n                targetEntry?.staleAt ??\n                now + (cacheOptions?.staleTime ?? options.cacheDefaults?.staleTime ?? 0),\n              gcAt:\n                targetEntry?.gcAt ??\n                getGcAt(now, cacheOptions?.gcTime ?? options.cacheDefaults?.gcTime),\n            };\n            stack.layers.push(layer);\n            snapshot = {\n              key: targetKey,\n              stack,\n              layer,\n            };\n            snapshots.set(targetKey, snapshot);\n            snapshot.layer.updaters.push(updater);\n            const nextEntry = applyOptimisticLayer(previousEntry, {\n              ...snapshot.layer,\n              updaters: [updater],\n            });\n            storeOptimisticEntry(cacheState, targetKey, stack, nextEntry);\n            continue;\n          }\n          snapshot.layer.updaters.push(updater);\n          const nextEntry = applyOptimisticLayer(stack.renderedEntry, {\n            ...snapshot.layer,\n            updaters: [updater],\n          });\n          storeOptimisticEntry(cacheState, targetKey, stack, nextEntry);\n        }\n\n        return Array.from(snapshots.values());\n      };\n\n      const rollbackOptimisticUpdates = (snapshots: OptimisticSnapshot[]) => {\n        if (!clientOptions?.optimistic?.rollbackOnError) return;\n        settleOptimisticUpdates(cacheState, optimisticState, snapshots, \"rollback\");\n      };\n\n      const invalidateUncommittedOptimisticUpdates = (snapshots: OptimisticSnapshot[]) => {\n        if (clientOptions?.optimistic?.rollbackOnError) return;\n        for (const key of settleOptimisticUpdates(\n          cacheState,\n          optimisticState,\n          snapshots,\n          \"invalidate\",\n        )) {\n          emitStatus(\"invalidated\", { key });\n        }\n      };\n\n      const executeNetwork = async (opts?: { isBackground?: boolean; callCallbacks?: boolean }) => {\n        const release = cancellation.hold();\n        let unsubscribeInvalidation: (() => void) | undefined;\n        let readOwners: Map<string, object> | undefined;\n        let readOwner: object | undefined;\n        const resolvedCacheKey = cacheState.resolveKey(cacheKey);\n        try {\n          const dedupeMs = cacheOptions?.dedupeMs ?? 0;\n          const inflight = inflightState.get(cacheKey);\n          const allowDedupe =\n            isCacheEnabled && dedupeMs > 0 && !cancellation.signal && !requestContextError;\n\n          if (\n            allowDedupe &&\n            inflight &&\n            !inflight.cancellable &&\n            now - inflight.startedAt < dedupeMs\n          ) {\n            emitStatus(\"pending\", { isBackground: opts?.isBackground, data: entry?.data });\n            const result = await inflight.promise;\n\n            if (result.error) {\n              emitStatus(\"error\", { error: result.error, isBackground: opts?.isBackground });\n              notifyClientObserver(options.onError, [result.error]);\n              if (opts?.callCallbacks !== false) {\n                clientOptions?.onError?.(result.error);\n              }\n            } else {\n              emitStatus(\"success\", { data: result.data, isBackground: opts?.isBackground });\n              if (opts?.callCallbacks !== false) {\n                clientOptions?.onSuccess?.(result.data as any);\n              }\n            }\n\n            return result;\n          }\n\n          // Observe ordering, not wall-clock timestamps: invalidation can happen in the\n          // same millisecond, or be cleared by another client's newer cache write.\n          let invalidatedDuringRequest = false;\n          if (isCacheEnabled) {\n            // Transport deduplication is caller-local, but cache ownership must\n            // span every caller writing to the same cache instance.\n            readOwners = getCacheReadOwners(cacheState);\n            readOwner = {};\n            readOwners.set(resolvedCacheKey, readOwner);\n            unsubscribeInvalidation = cacheState.subscribe(cacheKey, (event) => {\n              if (event === \"invalidate\") invalidatedDuringRequest = true;\n            });\n          }\n          emitStatus(opts?.isBackground ? \"revalidating\" : \"pending\", {\n            isBackground: opts?.isBackground,\n          });\n\n          const promise = (async () => {\n            const maxRetries = Math.max(0, clientOptions?.retry?.count ?? 0);\n            const shouldRetryFailure = clientOptions?.retry?.shouldRetry ?? isFarmRetryableFailure;\n            let attempt = 0;\n\n            // eslint-disable-next-line no-constant-condition\n            while (true) {\n              if (options.onRequest || clientOptions?.onRequest) {\n                const requestEvent: RequestEvent = {\n                  requestId,\n                  method: methodUpper,\n                  key: cacheKey,\n                  path,\n                  input,\n                  attempt,\n                  timestamp: Date.now(),\n                };\n                notifyClientObserver(options.onRequest, [requestEvent]);\n                clientOptions?.onRequest?.(requestEvent);\n              }\n\n              try {\n                if (requestContextError) throw requestContextError;\n                const { response, data, decodeError } = await cancellation.run(() =>\n                  fetchClient(\n                    path,\n                    {\n                      ...input,\n                      method: methodUpper,\n                    },\n                    defaultHeaders,\n                    cancellation,\n                  ),\n                );\n\n                const error = response.ok ? null : createResponseError(response, data, decodeError);\n\n                const responseEvent: ResponseEvent<any, Error> = {\n                  requestId,\n                  method: methodUpper,\n                  key: cacheKey,\n                  path,\n                  input,\n                  attempt,\n                  timestamp: Date.now(),\n                  response,\n                  data: response.ok ? data : undefined,\n                  error: error ?? undefined,\n                  ok: response.ok,\n                  status: response.status,\n                };\n\n                notifyClientObserver(options.onResponse, [\n                  response.ok ? data : undefined,\n                  error,\n                  responseEvent,\n                ]);\n                notifyResponseObserver(\n                  clientOptions?.onResponse,\n                  response.ok ? data : undefined,\n                  error,\n                  responseEvent,\n                );\n\n                if (!error) {\n                  return { data, error: null, key: cacheKey } as APIResult<any, Error>;\n                }\n\n                if (\n                  attempt >= maxRetries ||\n                  !shouldRetryFailure({\n                    attempt,\n                    method: methodUpper,\n                    status: response.status,\n                    error,\n                  })\n                ) {\n                  return { data: undefined, error, key: cacheKey } as APIResult<any, Error>;\n                }\n              } catch (err: any) {\n                const error = normalizeCallError(err);\n                const responseEvent: ResponseEvent<any, Error> = {\n                  requestId,\n                  method: methodUpper,\n                  key: cacheKey,\n                  path,\n                  input,\n                  attempt,\n                  timestamp: Date.now(),\n                  error,\n                  ok: false,\n                };\n\n                notifyClientObserver(options.onResponse, [undefined, error, responseEvent]);\n                notifyResponseObserver(clientOptions?.onResponse, undefined, error, responseEvent);\n\n                if (\n                  attempt >= maxRetries ||\n                  requestContextError ||\n                  cancellation.signal?.aborted ||\n                  !shouldRetryFailure({ attempt, method: methodUpper, error })\n                ) {\n                  return { data: undefined, error, key: cacheKey } as APIResult<any, Error>;\n                }\n              }\n\n              attempt += 1;\n              const delay =\n                typeof clientOptions?.retry?.delay === \"function\"\n                  ? clientOptions.retry.delay(attempt)\n                  : (clientOptions?.retry?.delay ?? 0);\n\n              if (delay > 0) {\n                try {\n                  await cancellation.delay(delay);\n                } catch (error) {\n                  return { data: undefined, error: normalizeCallError(error), key: cacheKey };\n                }\n              }\n            }\n          })();\n\n          const inflightEntry = {\n            promise,\n            startedAt: now,\n            cancellable: !!cancellation.signal || !!requestContextError,\n          };\n          inflightState.set(cacheKey, inflightEntry);\n\n          try {\n            const result = await promise;\n\n            if (\n              inflightState.get(cacheKey) === inflightEntry &&\n              readOwners?.get(resolvedCacheKey) === readOwner &&\n              !invalidatedDuringRequest &&\n              !result.error &&\n              isCacheEnabled &&\n              !isFarmAPIStream(result.data)\n            ) {\n              const updatedAt = Date.now();\n              const cached: CacheEntry = {\n                data: result.data,\n                updatedAt,\n                staleAt: updatedAt + staleTime,\n                gcAt: getGcAt(updatedAt, cacheOptions?.gcTime),\n                invalidatedAt: undefined,\n                persist: cacheOptions?.persist === true ? true : undefined,\n                [API_CACHE_REFETCH]: createCacheRefetch(\n                  request,\n                  path,\n                  method,\n                  input,\n                  cacheKey,\n                  cacheOptions!,\n                  clientOptions,\n                  options.onError,\n                ),\n              };\n              cacheState.set(cacheKey, cached);\n            }\n\n            if (result.error) {\n              emitStatus(\"error\", { error: result.error, isBackground: opts?.isBackground });\n              notifyClientObserver(options.onError, [result.error]);\n              if (opts?.callCallbacks !== false) {\n                clientOptions?.onError?.(result.error);\n              }\n            } else {\n              emitStatus(\"success\", { data: result.data, isBackground: opts?.isBackground });\n              if (opts?.callCallbacks !== false) {\n                clientOptions?.onSuccess?.(result.data as any);\n              }\n            }\n\n            return result;\n          } finally {\n            if (inflightState.get(cacheKey) === inflightEntry) {\n              inflightState.delete(cacheKey);\n            }\n            if (requestContextError && requestScopedState) {\n              requestScopedState.retired = true;\n              if (scopedRequestState === requestScopedState) scopedRequestState = undefined;\n            }\n            if (requestScopedState?.retired && requestScopedState.inflight.size === 0) {\n              requestScopedState.cache.dispose();\n            }\n          }\n        } finally {\n          if (readOwner && readOwners?.get(resolvedCacheKey) === readOwner) {\n            readOwners.delete(resolvedCacheKey);\n          }\n          unsubscribeInvalidation?.();\n          release();\n        }\n      };\n\n      const invalidateTargets = async () => {\n        if (!clientOptions?.invalidate) return;\n\n        const invalidateOptions = Array.isArray(clientOptions.invalidate)\n          ? { targets: clientOptions.invalidate, refetch: false }\n          : {\n              targets: clientOptions.invalidate.targets,\n              refetch: clientOptions.invalidate.refetch ?? false,\n            };\n\n        const refetches = new Set<() => void>();\n        for (const target of invalidateOptions.targets) {\n          const targetKey = resolveTargetKey(\n            routeMeta,\n            target,\n            undefined,\n            baseURL,\n            defaultHeaders,\n            transport ? baseURL : undefined,\n          );\n          if (!targetKey) continue;\n\n          const existing = cacheState.get(targetKey);\n          const invalidatedAt = Date.now();\n          // The first read may still be in flight with no stored entry yet.\n          // Notify its invalidation listener before it can cache an old result.\n          cacheState.invalidate(targetKey, invalidatedAt);\n          if (existing) {\n            const stack = optimisticState.get(targetKey);\n            if (stack?.renderedEntry === existing) {\n              stack.invalidatedAt = invalidatedAt;\n              stack.renderedEntry = cacheState.get(targetKey);\n            }\n          }\n\n          emitStatus(\"invalidated\", { key: targetKey });\n\n          const refetch = (existing as CacheEntry | undefined)?.[API_CACHE_REFETCH];\n          if (invalidateOptions.refetch && refetch) {\n            refetches.add(refetch);\n          }\n        }\n        // Invalidate every alias before starting work; never replay this mutation.\n        for (const refetch of refetches) refetch();\n      };\n\n      const optimisticSnapshots = requestContextError ? [] : applyOptimisticUpdates();\n\n      if (isCacheEnabled && !requestContextError && !cancellation.signal?.aborted) {\n        if (entry && !isStale && policy !== \"network-only\") {\n          emitStatus(\"success\", { data: entry.data });\n          clientOptions?.onSuccess?.(entry.data);\n          clientOptions?.onSettled?.(entry.data, null);\n          return { data: entry.data, error: null, key: cacheKey };\n        }\n\n        if (entry && isStale && policy === \"stale-while-revalidate\") {\n          emitStatus(\"success\", { data: entry.data });\n          clientOptions?.onSuccess?.(entry.data);\n          clientOptions?.onSettled?.(entry.data, null);\n\n          void executeNetwork({ isBackground: true, callCallbacks: false });\n          return { data: entry.data, error: null, key: cacheKey };\n        }\n      }\n\n      const result = await executeNetwork();\n      if (result.error) {\n        if (cancellation.signal?.aborted) {\n          settleOptimisticUpdates(cacheState, optimisticState, optimisticSnapshots, \"rollback\");\n        } else {\n          rollbackOptimisticUpdates(optimisticSnapshots);\n          invalidateUncommittedOptimisticUpdates(optimisticSnapshots);\n        }\n      } else {\n        settleOptimisticUpdates(cacheState, optimisticState, optimisticSnapshots, \"commit\");\n        await invalidateTargets();\n      }\n      clientOptions?.onSettled?.(result.data, result.error);\n      return result;\n    } finally {\n      cancellation.dispose();\n    }\n  };\n\n  // Return nested proxy (starts with empty path, user adds to it)\n  const client = createNestedProxy(\n    [],\n    request,\n    routeMeta,\n    baseURL,\n    isSameOriginAPIBaseURL(baseURL),\n    rootAliases,\n    options.routes ? new ClientRouteManifest(options.routes) : undefined,\n  ) as APIClient<TRouter, TIntegrations>;\n  return { client, request };\n}\n\nasync function readAPIResponseData(response: Response, method: string): Promise<unknown> {\n  if (\n    method === \"HEAD\" ||\n    response.status === 204 ||\n    response.status === 205 ||\n    response.status === 304\n  ) {\n    return undefined;\n  }\n\n  // Keep lightweight fetch-compatible adapters working when they expose the\n  // traditional json() contract without a complete Web Response implementation.\n  if (!response.headers?.get && typeof response.json === \"function\") {\n    return readResponseJSON(response);\n  }\n\n  if (response.body === null) return undefined;\n\n  if (isJSONStreamResponse(response)) {\n    return readJSONStream(response);\n  }\n\n  const contentType = response.headers.get(\"content-type\")?.split(\";\", 1)[0]?.trim().toLowerCase();\n  if (typeof response.arrayBuffer === \"function\") {\n    const data = await response.arrayBuffer();\n    if (data.byteLength === 0) return undefined;\n\n    if (!contentType || contentType === \"application/json\" || contentType.endsWith(\"+json\")) {\n      return parseResponseJSON(new TextDecoder().decode(data));\n    }\n\n    if (\n      contentType.startsWith(\"text/\") ||\n      contentType === \"application/xml\" ||\n      contentType === \"application/xhtml+xml\" ||\n      contentType === \"application/graphql\"\n    ) {\n      return new TextDecoder().decode(data);\n    }\n\n    return data;\n  }\n\n  if (\n    (!contentType || contentType === \"application/json\" || contentType.endsWith(\"+json\")) &&\n    typeof response.json === \"function\"\n  ) {\n    return readResponseJSON(response);\n  }\n\n  if (\n    (contentType?.startsWith(\"text/\") ||\n      contentType === \"application/xml\" ||\n      contentType === \"application/xhtml+xml\" ||\n      contentType === \"application/graphql\") &&\n    typeof response.text === \"function\"\n  ) {\n    return response.text();\n  }\n\n  // Some fetch-compatible adapters expose headers but still only implement\n  // the traditional json() reader.\n  if (typeof response.json === \"function\") {\n    return readResponseJSON(response);\n  }\n\n  return undefined;\n}\n\nclass APIResponseDecodeError extends Error {\n  readonly cause: unknown;\n\n  constructor(cause: unknown) {\n    super(cause instanceof Error ? cause.message : \"Failed to decode JSON response\");\n    this.name = \"APIResponseDecodeError\";\n    this.cause = cause;\n  }\n}\n\nfunction parseResponseJSON(value: string): unknown {\n  try {\n    return JSON.parse(value);\n  } catch (error) {\n    throw new APIResponseDecodeError(error);\n  }\n}\n\nasync function readResponseJSON(response: Pick<Response, \"json\">): Promise<unknown> {\n  try {\n    return await response.json();\n  } catch (error) {\n    if (error instanceof SyntaxError) throw new APIResponseDecodeError(error);\n    throw error;\n  }\n}\n\n/**\n * Create a nested proxy that builds up the path\n *\n * Flow:\n * 1. api.hello       -> Proxy(['hello'])\n * 2. api.hello.get   -> Proxy(['hello', 'get'])\n * 3. api.hello.get({ query: {...} })\n *    -> fetch('/api/hello', { method: 'GET', ... })\n *\n * For routes with single method:\n * 1. api.hello       -> Proxy(['hello'])\n * 2. api.hello({ query: {...} })\n *    -> fetch('/api/hello', ...)\n */\nfunction createNestedProxy(\n  path: string[],\n  client: any,\n  routeMeta: WeakMap<AnyRouteRef, RouteMeta>,\n  baseURL: string,\n  sameOrigin: boolean,\n  rootAliases?: Record<string, unknown>,\n  manifest?: ClientRouteManifest,\n  bound: BoundRouteParams = {},\n): any {\n  const target = () => {};\n  const proxy = new Proxy(target, {\n    // When accessing a property (api.hello)\n    get(_target, prop: string | symbol) {\n      if (prop === \"$params\") {\n        return (params: unknown) => {\n          if (!manifest)\n            throw new TypeError(\n              \"$params requires createAPIClient({ routes: apiRoutes }) from the generated API manifest.\",\n            );\n          const scope = manifest.bind(buildProxyRoutePath(path), params);\n          return createNestedProxy(\n            [...path, scope.segment],\n            client,\n            routeMeta,\n            baseURL,\n            sameOrigin,\n            rootAliases,\n            manifest,\n            Object.freeze({ ...bound, ...scope.params }),\n          );\n        };\n      }\n      if (prop === FARM_API_ROUTE_REF_SYMBOL) {\n        return path.length > 0;\n      }\n      if (prop === FARM_API_ROUTE_META_SYMBOL) {\n        let metadata;\n        try {\n          metadata = resolveRouteMeta({ path, baseURL, manifest, bound });\n        } catch {\n          return null;\n        } // An unbound/overloaded route has no single URL yet.\n        const requestURL = resolveFarmAPIRequestURL(metadata.routePath, baseURL);\n        return Object.freeze({\n          path: `${requestURL.pathname}${requestURL.search}${requestURL.hash}`,\n          method: metadata.method,\n          baseURL: requestURL.origin,\n          sameOrigin,\n        });\n      }\n\n      if (path.length === 0 && typeof prop === \"string\" && rootAliases && prop in rootAliases) {\n        return rootAliases[prop];\n      }\n\n      if (typeof prop !== \"string\") {\n        return Reflect.get(_target, prop);\n      }\n\n      // Add prop to path and return new proxy\n      return createNestedProxy(\n        [...path, prop],\n        client,\n        routeMeta,\n        baseURL,\n        sameOrigin,\n        rootAliases,\n        manifest,\n        bound,\n      );\n    },\n\n    // When calling as a function\n    apply(_target, _thisArg, args) {\n      // Check if the last part is an HTTP method\n      const lastPart = path[path.length - 1];\n      const httpMethods = [\"get\", \"head\", \"query\", \"post\", \"put\", \"delete\", \"patch\", \"options\"];\n\n      if (httpMethods.includes(lastPart)) {\n        // Method is explicitly called: api.users.get() or api['auth/login'].post()\n        // Remove the method from path and use it as the HTTP method\n        const routePath = buildProxyRoutePath(path.slice(0, -1));\n        const method = lastPart.toUpperCase();\n\n        // Extract options from arguments\n        const [options, clientOptions] = args;\n\n        // Call fetch client with explicit method\n        const resolved = manifest ? manifest.resolve(routePath, method, bound, options) : routePath;\n        if (!manifest && options?.params)\n          throw new TypeError(\"Dynamic params require the generated routes manifest.\");\n        return client(resolved, method, options, clientOptions);\n      } else {\n        // Direct call without method: api.hello()\n        // Use the full path and let the server determine the method (usually GET)\n        const routePath = buildProxyRoutePath(path);\n\n        // Extract options from arguments\n        const [options, clientOptions] = args;\n\n        // Call fetch client (default method will be GET)\n        const method = options?.method || \"GET\";\n        const resolved = manifest ? manifest.resolve(routePath, method, bound, options) : routePath;\n        return client(resolved, method, options, clientOptions);\n      }\n    },\n  });\n\n  routeMeta.set(proxy, { path: [...path], baseURL, manifest, bound });\n  return proxy;\n}\n\nfunction buildProxyRoutePath(path: string[]): string {\n  return \"/api/\" + path.join(\"/\").replace(/^\\/+/, \"\");\n}\n\nexport function isAPIRouteRef(value: unknown): value is CallableRouteRef {\n  return (\n    typeof value === \"function\" &&\n    (value as { [FARM_API_ROUTE_REF_SYMBOL]?: unknown })[FARM_API_ROUTE_REF_SYMBOL] === true\n  );\n}\n\nexport function getAPIRouteRefMetadata(value: unknown): APIRouteRefMetadata | null {\n  if (!isAPIRouteRef(value)) return null;\n  const metadata = (value as { [FARM_API_ROUTE_META_SYMBOL]?: unknown })[\n    FARM_API_ROUTE_META_SYMBOL\n  ];\n  if (!metadata || typeof metadata !== \"object\") return null;\n\n  const candidate = metadata as Partial<APIRouteRefMetadata>;\n  if (\n    typeof candidate.path !== \"string\" ||\n    typeof candidate.method !== \"string\" ||\n    typeof candidate.baseURL !== \"string\" ||\n    typeof candidate.sameOrigin !== \"boolean\"\n  ) {\n    return null;\n  }\n\n  return {\n    path: candidate.path,\n    method: candidate.method,\n    baseURL: candidate.baseURL,\n    sameOrigin: candidate.sameOrigin,\n  };\n}\n\n/**\n * Server-side API client that calls endpoints directly as functions\n * No HTTP overhead for app endpoints, and registered integration routes can be exposed at\n * api.integrations.* where Farm can dispatch them directly to the integration handler.\n *\n * @example\n * ```typescript\n * import { createServerAPIClient } from 'farm/client';\n * import type { AppIntegrations } from '@/lib/integrations';\n *\n * export const api = createServerAPIClient<{}, AppIntegrations>({});\n *\n * const result = await api.integrations.billing.status();\n * ```\n */\nexport function createServerAPIClient<TEndpoints extends Record<string, any>>(\n  endpoints: TEndpoints,\n): TEndpoints;\nexport function createServerAPIClient<TEndpoints extends Record<string, any>>(\n  endpoints: TEndpoints,\n  options: ServerAPIClientWithoutIntegrationsOptions,\n): TEndpoints;\nexport function createServerAPIClient<\n  TEndpoints extends Record<string, any>,\n  TIntegrations extends Record<string, any> = {},\n>(\n  endpoints: TEndpoints,\n  options?: ServerAPIClientOptions,\n): ServerAPIClient<TEndpoints, TIntegrations>;\nexport function createServerAPIClient<\n  TEndpoints extends Record<string, any>,\n  TIntegrations extends Record<string, any> = {},\n>(\n  endpoints: TEndpoints,\n  options: ServerAPIClientOptions | ServerAPIClientWithoutIntegrationsOptions = {},\n): TEndpoints | ServerAPIClient<TEndpoints, TIntegrations> {\n  if (\n    options.integrations === false ||\n    Object.prototype.hasOwnProperty.call(endpoints, \"integrations\")\n  ) {\n    return endpoints;\n  }\n\n  Object.defineProperty(endpoints, \"integrations\", {\n    get() {\n      return integrationsServer<TIntegrations>(\n        typeof options.integrations === \"object\" ? options.integrations : {},\n      );\n    },\n    enumerable: false,\n    configurable: true,\n  });\n\n  return endpoints as ServerAPIClient<TEndpoints, TIntegrations>;\n}\n\nconst API_CACHE_REFETCH = Symbol.for(\"farm.api.cache-refetch\");\ntype CacheEntry = FarmClientCacheEntry<any> & {\n  [API_CACHE_REFETCH]?: () => void;\n};\n\n// Keep the read recipe on its cache entry, so deletion/GC also releases it.\n// This separate closure must not retain the original request's entry or signal.\nfunction createCacheRefetch(\n  request: APICall,\n  path: string,\n  method: string,\n  input: unknown,\n  key: string,\n  cache: CacheOptions,\n  options: ClientOptions<any, any> | undefined,\n  onError: APIClientOptions[\"onError\"],\n): () => void {\n  const readOptions: ClientOptions<any, any> = {\n    cache: { ...cache, key, policy: \"network-only\", dedupeMs: 0 },\n    retry: options?.retry,\n    timeoutMs: options?.timeoutMs,\n  };\n  return () => {\n    // A new call resolves current defaults and owns a fresh deadline. Do not\n    // retain prior signals, mutation options, or per-call completion callbacks.\n    void request(path, method, input, readOptions).catch((error) => {\n      notifyClientObserver(onError, [normalizeError(error)]);\n    });\n  };\n}\n\ntype InflightEntry = {\n  cancellable?: boolean;\n  promise: Promise<APIResult<any, Error>>;\n  startedAt: number;\n};\n\ntype ScopedRequestState = {\n  context: string;\n  cache: FarmClientDataCache;\n  inflight: Map<string, InflightEntry>;\n  retired: boolean;\n};\n\ntype RouteMeta = {\n  path: string[];\n  baseURL: string;\n  manifest?: ClientRouteManifest;\n  bound?: BoundRouteParams;\n};\n\ntype OptimisticSnapshot = {\n  key: string;\n  stack: OptimisticStack;\n  layer: OptimisticLayer;\n};\n\ntype OptimisticStack = {\n  entry?: CacheEntry;\n  layers: OptimisticLayer[];\n  renderedEntry?: CacheEntry;\n  invalidatedAt?: number;\n};\n\ntype OptimisticLayer = {\n  updaters: Array<(prev: any) => any>;\n  updatedAt: number;\n  staleAt: number;\n  gcAt?: number;\n  committed?: boolean;\n};\n\nconst optimisticStates = new WeakMap<FarmClientDataCache, Map<string, OptimisticStack>>();\nconst cacheReadOwners = new WeakMap<FarmClientDataCache, Map<string, object>>();\n\nfunction getCacheReadOwners(cache: FarmClientDataCache): Map<string, object> {\n  let owners = cacheReadOwners.get(cache);\n  if (!owners) {\n    owners = new Map();\n    cacheReadOwners.set(cache, owners);\n  }\n  return owners;\n}\n\nfunction getOptimisticState(cache: FarmClientDataCache): Map<string, OptimisticStack> {\n  let state = optimisticStates.get(cache);\n  if (!state) {\n    state = new Map();\n    optimisticStates.set(cache, state);\n  }\n  return state;\n}\n\nfunction applyOptimisticLayer(entry: CacheEntry | undefined, layer: OptimisticLayer): CacheEntry {\n  let data = entry?.data;\n  for (const updater of layer.updaters) data = updater(data);\n\n  return {\n    data,\n    updatedAt: layer.updatedAt,\n    staleAt: entry?.staleAt ?? layer.staleAt,\n    gcAt: entry?.gcAt ?? layer.gcAt,\n    invalidatedAt: entry?.invalidatedAt,\n    [API_CACHE_REFETCH]: entry?.[API_CACHE_REFETCH],\n  };\n}\n\nfunction storeOptimisticEntry(\n  cacheState: FarmClientDataCache,\n  key: string,\n  stack: OptimisticStack,\n  entry: CacheEntry | undefined,\n): void {\n  if (!entry) {\n    cacheState.delete(key);\n    stack.renderedEntry = undefined;\n    return;\n  }\n\n  cacheState.set(key, entry);\n  if (stack.invalidatedAt !== undefined) {\n    cacheState.invalidate(key, stack.invalidatedAt);\n  }\n  stack.renderedEntry = cacheState.get(key);\n}\n\nfunction reconcileOptimisticInvalidation(\n  cacheState: FarmClientDataCache,\n  key: string,\n  stack: OptimisticStack,\n): boolean {\n  const current = cacheState.get(key);\n  const rendered = stack.renderedEntry;\n  if (current === rendered) return true;\n  if (\n    !current ||\n    !rendered ||\n    current.data !== rendered.data ||\n    current.updatedAt !== rendered.updatedAt ||\n    current.gcAt !== rendered.gcAt ||\n    current.status !== rendered.status ||\n    current.error !== rendered.error ||\n    current.fetching !== rendered.fetching ||\n    current.staleAt !== 0 ||\n    current.invalidatedAt === undefined\n  ) {\n    return false;\n  }\n\n  stack.invalidatedAt = current.invalidatedAt;\n  stack.renderedEntry = current;\n  return true;\n}\n\nfunction renderOptimisticStack(\n  cacheState: FarmClientDataCache,\n  key: string,\n  stack: OptimisticStack,\n): void {\n  let entry = stack.entry ? { ...stack.entry } : undefined;\n  for (const layer of stack.layers) entry = applyOptimisticLayer(entry, layer);\n  storeOptimisticEntry(cacheState, key, stack, entry);\n}\n\nfunction settleOptimisticUpdates(\n  cacheState: FarmClientDataCache,\n  optimisticState: Map<string, OptimisticStack>,\n  snapshots: OptimisticSnapshot[],\n  outcome: \"commit\" | \"rollback\" | \"invalidate\",\n): string[] {\n  const settledKeys: string[] = [];\n  for (const snapshot of snapshots) {\n    const stack = optimisticState.get(snapshot.key);\n    if (stack !== snapshot.stack) continue;\n    if (!reconcileOptimisticInvalidation(cacheState, snapshot.key, stack)) {\n      optimisticState.delete(snapshot.key);\n      continue;\n    }\n\n    if (outcome === \"rollback\") {\n      stack.layers = stack.layers.filter((layer) => layer !== snapshot.layer);\n    } else {\n      snapshot.layer.committed = true;\n      if (outcome === \"invalidate\") stack.invalidatedAt = Date.now();\n    }\n\n    while (stack.layers[0]?.committed) {\n      stack.entry = applyOptimisticLayer(stack.entry, stack.layers.shift()!);\n    }\n\n    renderOptimisticStack(cacheState, snapshot.key, stack);\n    if (stack.layers.length === 0) optimisticState.delete(snapshot.key);\n    settledKeys.push(snapshot.key);\n  }\n  return settledKeys;\n}\n\n/**\n * @internal Apply key-targeted optimistic updates to the shared client cache\n * for a server-function mutation. Route-reference update tuples need an API\n * caller's route metadata and are skipped here; use structured cache keys.\n */\nexport function applyServerFnOptimisticUpdates(\n  updates: readonly OptimisticUpdate[],\n  now = Date.now(),\n): OptimisticSnapshot[] {\n  const cacheState = getFarmClientDataCache();\n  const optimisticState = getOptimisticState(cacheState);\n  const snapshots = new Map<string, OptimisticSnapshot>();\n\n  for (const update of updates) {\n    if (update.length !== 2) continue;\n    const [target, updater] = update;\n    if (typeof updater !== \"function\") continue;\n    const targetKey =\n      typeof target === \"string\" || Array.isArray(target)\n        ? normalizeFarmClientCacheKey(target as FarmClientCacheKey)\n        : null;\n    if (!targetKey) continue;\n\n    const targetEntry = getValidCacheEntry(cacheState, targetKey, now);\n    const currentEntry = cacheState.get(targetKey);\n    let stack = optimisticState.get(targetKey);\n    if (stack && !reconcileOptimisticInvalidation(cacheState, targetKey, stack)) {\n      stack = undefined;\n    }\n    if (!stack) {\n      stack = {\n        entry: targetEntry ? { ...targetEntry } : undefined,\n        layers: [],\n        renderedEntry: currentEntry,\n      };\n      optimisticState.set(targetKey, stack);\n    }\n\n    let snapshot = snapshots.get(targetKey);\n    if (!snapshot) {\n      const previousEntry = stack.layers.length === 0 ? stack.entry : stack.renderedEntry;\n      const layer: OptimisticLayer = {\n        updaters: [],\n        updatedAt: now,\n        // A server function has no cache policy of its own; preserve the\n        // target read's freshness metadata when it exists.\n        staleAt: targetEntry?.staleAt ?? now,\n        gcAt: targetEntry?.gcAt,\n      };\n      stack.layers.push(layer);\n      snapshot = { key: targetKey, stack, layer };\n      snapshots.set(targetKey, snapshot);\n      snapshot.layer.updaters.push(updater);\n      const nextEntry = applyOptimisticLayer(previousEntry, {\n        ...snapshot.layer,\n        updaters: [updater],\n      });\n      storeOptimisticEntry(cacheState, targetKey, stack, nextEntry);\n      continue;\n    }\n    snapshot.layer.updaters.push(updater);\n    const nextEntry = applyOptimisticLayer(stack.renderedEntry, {\n      ...snapshot.layer,\n      updaters: [updater],\n    });\n    storeOptimisticEntry(cacheState, targetKey, stack, nextEntry);\n  }\n\n  return Array.from(snapshots.values());\n}\n\n/**\n * @internal Settle a server-function mutation's optimistic snapshots with the\n * API client's semantics: commit on success, rollback on failure with\n * `rollbackOnError`, and mark-stale on failure without it.\n */\nexport function settleServerFnOptimisticUpdates(\n  snapshots: OptimisticSnapshot[],\n  outcome: \"commit\" | \"rollback\" | \"invalidate\",\n): void {\n  if (snapshots.length === 0) return;\n  const cacheState = getFarmClientDataCache();\n  settleOptimisticUpdates(cacheState, getOptimisticState(cacheState), snapshots, outcome);\n}\n\n/**\n * @internal Resolve a server-function mutation's invalidate targets to cache\n * keys. Route-reference and path targets need an API caller's identity and are\n * skipped; use structured cache keys. Keys are applied through the shared\n * invalidation bus, matching server-declared `invalidates`.\n */\nexport function resolveServerFnInvalidateTargets(invalidate: InvalidateOptions): string[] {\n  const targets = Array.isArray(invalidate) ? invalidate : invalidate.targets;\n  const keys: string[] = [];\n  for (const target of targets) {\n    if (typeof target === \"string\" || Array.isArray(target)) {\n      if (Array.isArray(target) && typeof target[0] === \"function\") continue;\n      keys.push(normalizeFarmClientCacheKey(target as FarmClientCacheKey));\n    } else if (target && typeof target === \"object\" && \"key\" in target) {\n      keys.push(normalizeFarmClientCacheKey(target.key));\n    }\n  }\n  return keys;\n}\n\nfunction buildCacheKey(\n  method: string,\n  path: string,\n  input: any,\n  baseURL: string,\n  defaultHeaders?: HeadersInit,\n): string {\n  const keyInput =\n    input && typeof input === \"object\"\n      ? {\n          query: input.query,\n          body: input.body,\n          ...(method === \"QUERY\"\n            ? {\n                contentType:\n                  getHeader(input.headers, \"content-type\") ??\n                  getHeader(defaultHeaders, \"content-type\") ??\n                  \"application/json\",\n                contentEncoding:\n                  getHeader(input.headers, \"content-encoding\") ??\n                  getHeader(defaultHeaders, \"content-encoding\"),\n              }\n            : {}),\n        }\n      : input;\n  const url = resolveFarmAPIRequestURL(path, baseURL);\n  return `${method}:${url.origin}${url.pathname}:${stableStringify(keyInput ?? {})}`;\n}\n\nfunction isSameOriginAPIBaseURL(baseURL: string): boolean {\n  if (typeof window === \"undefined\") return baseURL.startsWith(\"/\");\n  return resolveFarmAPIRequestURL(\"/api\", baseURL).origin === window.location.origin;\n}\n\nfunction stableStringify(value: any): string {\n  if (value === null || value === undefined) return String(value);\n  if (value instanceof Date) return value.toISOString();\n  if (typeof value !== \"object\") return JSON.stringify(value);\n  if (Array.isArray(value)) {\n    return `[${value.map((item) => stableStringify(item)).join(\",\")}]`;\n  }\n\n  const keys = Object.keys(value).sort();\n  const entries = keys.map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`);\n  return `{${entries.join(\",\")}}`;\n}\n\nfunction getHeader(headers: unknown, name: string): string | undefined {\n  if (!headers || typeof headers !== \"object\") return undefined;\n\n  if (typeof Headers !== \"undefined\" && headers instanceof Headers) {\n    return headers.get(name) ?? undefined;\n  }\n\n  const entry = Object.entries(headers).find(([key]) => key.toLowerCase() === name);\n  return entry?.[1] === undefined ? undefined : String(entry[1]);\n}\n\nfunction getRequestCacheContext(\n  options: { headers?: HeadersInit; credentials?: RequestCredentials },\n  input: unknown,\n  scope: CacheScope | undefined,\n): string | undefined {\n  const credentials = options.credentials ?? \"same-origin\";\n  const headers = new Headers(options.headers);\n  const requestHeaders =\n    input && typeof input === \"object\" && \"headers\" in input ? input.headers : undefined;\n\n  if (requestHeaders) {\n    new Headers(requestHeaders as HeadersInit).forEach((value, key) => headers.set(key, value));\n  }\n\n  const carriesBrowserIdentity = credentials !== \"omit\" || [...headers].length > 0;\n  if (scope !== \"client\" && !carriesBrowserIdentity) return undefined;\n\n  return stableStringify({\n    credentials,\n    headers: [...headers].sort(([left], [right]) => left.localeCompare(right)),\n  });\n}\n\nfunction getGcAt(now: number, gcTime?: number): number | undefined {\n  if (gcTime === undefined) return undefined;\n  if (!Number.isFinite(gcTime) || gcTime <= 0) return now;\n  return now + gcTime;\n}\n\nfunction getValidCacheEntry(\n  cacheState: FarmClientDataCache,\n  key: string,\n  now: number,\n): CacheEntry | undefined {\n  const entry = cacheState.get(key);\n  if (!entry) return undefined;\n\n  if (entry.gcAt !== undefined && now >= entry.gcAt) {\n    cacheState.delete(key);\n    return undefined;\n  }\n\n  return entry;\n}\n\nfunction isEntryStale(entry: CacheEntry, now: number): boolean {\n  if (entry.invalidatedAt !== undefined) return true;\n  return now >= entry.staleAt;\n}\n\nfunction resolveTargetKey(\n  routeMeta: WeakMap<AnyRouteRef, RouteMeta>,\n  target: InvalidateTarget | AnyRouteRef,\n  input?: unknown,\n  baseURL = \"http://localhost:3000\",\n  defaultHeaders?: HeadersInit,\n  localBaseURL?: string,\n): string | null {\n  if (!target) return null;\n\n  if (typeof target === \"string\") return target;\n\n  if (typeof target === \"function\") {\n    const meta = routeMeta.get(target);\n    if (!meta) return null;\n\n    const { method, routePath } = resolveRouteMeta(meta, input);\n    return buildCacheKey(\n      method,\n      routePath,\n      input ?? {},\n      localBaseURL ?? meta.baseURL,\n      defaultHeaders,\n    );\n  }\n\n  if (Array.isArray(target)) {\n    const [route, routeInput] = target;\n    if (typeof route === \"function\") {\n      return resolveTargetKey(routeMeta, route, routeInput, baseURL, defaultHeaders, localBaseURL);\n    }\n    return normalizeFarmClientCacheKey(target);\n  }\n\n  if (\"key\" in target) return normalizeFarmClientCacheKey(target.key);\n\n  if (\"path\" in target) {\n    const method = target.method ?? \"GET\";\n    return buildCacheKey(method, target.path, target.input ?? {}, baseURL, defaultHeaders);\n  }\n\n  return null;\n}\n\nfunction resolveRouteMeta(meta: RouteMeta, input?: any): { routePath: string; method: string } {\n  const httpMethods = [\"get\", \"head\", \"query\", \"post\", \"put\", \"delete\", \"patch\", \"options\"];\n  const lastPart = meta.path[meta.path.length - 1];\n  if (lastPart && httpMethods.includes(lastPart)) {\n    return {\n      routePath: meta.manifest\n        ? meta.manifest.resolve(\n            buildProxyRoutePath(meta.path.slice(0, -1)),\n            lastPart.toUpperCase(),\n            meta.bound ?? {},\n            input,\n          )\n        : buildProxyRoutePath(meta.path.slice(0, -1)),\n      method: lastPart.toUpperCase(),\n    };\n  }\n\n  return {\n    routePath: meta.manifest\n      ? meta.manifest.resolve(buildProxyRoutePath(meta.path), \"GET\", meta.bound ?? {}, input)\n      : buildProxyRoutePath(meta.path),\n    method: \"GET\",\n  };\n}\n\nfunction normalizeError(error: unknown): Error {\n  if (error instanceof APIClientError) return error;\n\n  const normalized = new APIClientError(\"network_error\", undefined, {\n    status: 0,\n    message:\n      error instanceof Error\n        ? error.message\n        : typeof error === \"string\"\n          ? error\n          : \"Network request failed\",\n  });\n  (normalized as Error & { cause?: unknown }).cause = error;\n  return normalized;\n}\n\nfunction notifyResponseObserver(\n  observer: ClientOptions<any, any>[\"onResponse\"],\n  data: unknown,\n  error: unknown,\n  event: ResponseEvent<any, any>,\n): void {\n  notifyClientObserver(observer, [data, error, event], \"API client onResponse\");\n}\n\nfunction isFormData(value: unknown): value is FormData {\n  return (\n    typeof value === \"object\" &&\n    value !== null &&\n    ((typeof FormData !== \"undefined\" && value instanceof FormData) ||\n      (Object.prototype.toString.call(value) === \"[object FormData]\" &&\n        typeof (value as { entries?: unknown }).entries === \"function\"))\n  );\n}\n\nfunction createResponseError(response: Response, data: any, cause?: unknown): Error {\n  const expected = readEndpointErrorEnvelope(data);\n  if (expected) {\n    return new APIClientError(expected.code, expected.data, {\n      status: response.status,\n      message: expected.message,\n      response,\n    });\n  }\n\n  const error = new APIClientError(\"http_error\", data, {\n    status: response.status,\n    message: `HTTP ${response.status}: ${response.statusText}`,\n    response,\n  });\n  if (cause !== undefined) (error as Error & { cause?: unknown }).cause = cause;\n  return error;\n}\n\nfunction readEndpointErrorEnvelope(data: unknown): {\n  code: string;\n  message: string;\n  data: unknown;\n} | null {\n  if (!data || typeof data !== \"object\") return null;\n  const error = (data as { error?: unknown }).error;\n  if (!error || typeof error !== \"object\") return null;\n\n  const code = (error as { code?: unknown }).code;\n  const message = (error as { message?: unknown }).message;\n  if (typeof code !== \"string\" || typeof message !== \"string\") return null;\n\n  return {\n    code,\n    message,\n    data: (error as { data?: unknown }).data,\n  };\n}\n"],"mappings":";;;;;;;;;;;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