<commit_before>import {ApolloClient, HttpLink, InMemoryCache} from "@apollo/client"

import fetch from "isomorphic-fetch"

/**
 * @typedef {import("@apollo/client").NormalizedCacheObject} NormalizedCacheObject
 */

/**
 * @type {ApolloClient<NormalizedCacheObject>}
 */
let cachedClient = null

const createApollo = () => new ApolloClient({
  ssrMode: process.browser === false || typeof window === "undefined",
  link: new HttpLink({
    uri: process.env.NEXT_PUBLIC_GRAPHQL,
    credentials: "same-origin",
    fetch
  }),
  cache: new InMemoryCache()
})

/**
 * @param {Object.<string, any>} initialState
 */
function initializeApollo(initialState = null) {
  /**
   * @type {ApolloClient<NormalizedCacheObject>}
   */
  const client = cachedClient ?? createApollo()

  if (initialState) {
    const oldCache = client.extract()

    client.cache.restore({...oldCache, ...initialState})
  }

  // Always return a new client for SSR
  if (process.browser === false) {
    return client
  }

  if (cachedClient) {
    cachedClient = client
  }

  return client
}

export default initializeApollo<commit_msg>Fix Apollo Client instance caching on client-side<commit_after>import {ApolloClient, HttpLink, InMemoryCache} from "@apollo/client"

import fetch from "isomorphic-fetch"

/**
 * @typedef {import("@apollo/client").NormalizedCacheObject} NormalizedCacheObject
 */

/**
 * @type {ApolloClient<NormalizedCacheObject>}
 */
let cachedClient = null

const createApollo = () => new ApolloClient({
  ssrMode: process.browser === false || typeof window === "undefined",
  link: new HttpLink({
    uri: process.env.NEXT_PUBLIC_GRAPHQL,
    credentials: "same-origin",
    fetch
  }),
  cache: new InMemoryCache()
})

/**
 * @param {Object.<string, any>} initialState
 */
function initializeApollo(initialState = null) {
  /**
   * @type {ApolloClient<NormalizedCacheObject>}
   */
  const client = cachedClient ?? createApollo()

  if (initialState) {
    const oldCache = client.extract()

    client.cache.restore({...oldCache, ...initialState})
  }

  // Always return a new client for SSR
  if (process.browser === false) {
    return client
  }

  // Cache client if it wasn't cached before
  if (!cachedClient) {
    cachedClient = client
  }

  return client
}

export default initializeApollo
{'fraction_non_alphanumeric': 0.13458188153310105, 'fraction_numerical': 0.0, 'mean_word_length': 3.929184549356223, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6631298', 'n_tokens_mistral': 730, 'n_tokens_neox': 689, 'n_words': 172}