"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateTrpcClient = generateTrpcClient;
const generator_1 = require("@postxl/generator");
/**
 * Utility component that generates the definition of the React context for a given model.
 */
function generateTrpcClient(context) {
    const imports = generator_1.ImportGenerator
        //
        .from(context.trpcClient.location)
        .addType(context.trpcRouter.appRoutes.type);
    return /* ts */ `
import { createTRPCClient, httpLink } from '@trpc/client'
import { createTRPCContext } from '@trpc/tanstack-react-query'
${imports.generate()}

import SuperJSON from 'superjson'

import { getAuthHeaders } from '@context-providers/auth-context-provider'

export const { TRPCProvider, useTRPC, useTRPCClient } = createTRPCContext<AppRoutes>()

export const createTrpcClient = ({ apiUrl }: { apiUrl: string }) => {
  return createTRPCClient<AppRoutes>({
    links: [
      httpLink({
        url: getTRPCUrl(apiUrl),
        fetch: createFetch(),
        transformer: SuperJSON,
      }),
    ],
  })
}

const createFetch = () => (url: URL | RequestInfo, options?: RequestInit) => {
  const headers = getAuthHeaders(options)

  return fetch(url, { ...options, headers, signal: undefined, credentials: 'include' })
}

/**
 * Makes sure that the URL always ends with a slash.
 */
export const normalizeUrl = (url: string): string => {
  return url.endsWith('/') ? url : \`\${url}/\`
}

function getTRPCUrl(apiUrl: string) {
  const url = new URL(apiUrl)

  // This is a fix for the TRPC client to work in E2E tests when we run
  // the server outside of the Docker container and the client inside
  // the Docker container.
  if (globalThis.window === undefined && url.hostname === 'host.docker.internal') {
    url.hostname = 'localhost'
  }

  url.pathname = normalizeUrl(url.pathname) + 'trpc'

  return url.toString()
}`;
}
//# sourceMappingURL=trpc-client.generator.js.map