{"version":3,"sources":["../../../src/shared/lib/utils.ts"],"sourcesContent":["import type { HtmlProps } from './html-context.shared-runtime'\nimport type { ComponentType, JSX } from 'react'\nimport type { DomainLocale } from '../../server/config'\nimport type { Env } from '@next/env'\nimport type { IncomingMessage, ServerResponse } from 'http'\nimport type { NextRouter } from './router/router'\nimport type { ParsedUrlQuery } from 'querystring'\nimport type { PreviewData } from '../../types'\nimport type { COMPILER_NAMES } from './constants'\nimport type fs from 'fs'\n\nexport type NextComponentType<\n  Context extends BaseContext = NextPageContext,\n  InitialProps = {},\n  Props = {},\n> = ComponentType<Props> & {\n  /**\n   * Used for initial page load data population. Data returned from `getInitialProps` is serialized when server rendered.\n   * Make sure to return plain `Object` without using `Date`, `Map`, `Set`.\n   * @param context Context of `page`\n   */\n  getInitialProps?(context: Context): InitialProps | Promise<InitialProps>\n}\n\nexport type DocumentType = NextComponentType<\n  DocumentContext,\n  DocumentInitialProps,\n  DocumentProps\n>\n\nexport type AppType<P = {}> = NextComponentType<\n  AppContextType,\n  P,\n  AppPropsType<any, P>\n>\n\nexport type AppTreeType = ComponentType<\n  AppInitialProps & { [name: string]: any }\n>\n\n/**\n * Web vitals provided to _app.reportWebVitals by Core Web Vitals plugin developed by Google Chrome team.\n * https://nextjs.org/blog/next-9-4#integrated-web-vitals-reporting\n */\nexport const WEB_VITALS = ['CLS', 'FCP', 'FID', 'INP', 'LCP', 'TTFB'] as const\nexport type NextWebVitalsMetric = {\n  id: string\n  startTime: number\n  value: number\n  attribution?: { [key: string]: unknown }\n} & (\n  | {\n      label: 'web-vital'\n      name: (typeof WEB_VITALS)[number]\n    }\n  | {\n      label: 'custom'\n      name:\n        | 'Next.js-hydration'\n        | 'Next.js-route-change-to-render'\n        | 'Next.js-render'\n    }\n)\n\nexport type Enhancer<C> = (Component: C) => C\n\nexport type ComponentsEnhancer =\n  | {\n      enhanceApp?: Enhancer<AppType>\n      enhanceComponent?: Enhancer<NextComponentType>\n    }\n  | Enhancer<NextComponentType>\n\nexport type RenderPageResult = {\n  html: string\n  head?: Array<JSX.Element | null>\n}\n\nexport type RenderPage = (\n  options?: ComponentsEnhancer\n) => DocumentInitialProps | Promise<DocumentInitialProps>\n\nexport type BaseContext = {\n  res?: ServerResponse\n  [k: string]: any\n}\n\nexport type NEXT_DATA = {\n  props: Record<string, any>\n  page: string\n  query: ParsedUrlQuery\n  buildId: string\n  assetPrefix?: string\n  runtimeConfig?: { [key: string]: any }\n  nextExport?: boolean\n  autoExport?: boolean\n  isFallback?: boolean\n  isExperimentalCompile?: boolean\n  dynamicIds?: (string | number)[]\n  err?: Error & {\n    statusCode?: number\n    source?: typeof COMPILER_NAMES.server | typeof COMPILER_NAMES.edgeServer\n  }\n  gsp?: boolean\n  gssp?: boolean\n  customServer?: boolean\n  gip?: boolean\n  appGip?: boolean\n  locale?: string\n  locales?: readonly string[]\n  defaultLocale?: string\n  domainLocales?: readonly DomainLocale[]\n  scriptLoader?: any[]\n  isPreview?: boolean\n  notFoundSrcPage?: string\n}\n\n/**\n * `Next` context\n */\nexport interface NextPageContext {\n  /**\n   * Error object if encountered during rendering\n   */\n  err?: (Error & { statusCode?: number }) | null\n  /**\n   * `HTTP` request object.\n   */\n  req?: IncomingMessage\n  /**\n   * `HTTP` response object.\n   */\n  res?: ServerResponse\n  /**\n   * Path section of `URL`.\n   */\n  pathname: string\n  /**\n   * Query string section of `URL` parsed as an object.\n   */\n  query: ParsedUrlQuery\n  /**\n   * `String` of the actual path including query.\n   */\n  asPath?: string\n  /**\n   * The currently active locale\n   */\n  locale?: string\n  /**\n   * All configured locales\n   */\n  locales?: readonly string[]\n  /**\n   * The configured default locale\n   */\n  defaultLocale?: string\n  /**\n   * `Component` the tree of the App to use if needing to render separately\n   */\n  AppTree: AppTreeType\n}\n\nexport type AppContextType<Router extends NextRouter = NextRouter> = {\n  Component: NextComponentType<NextPageContext>\n  AppTree: AppTreeType\n  ctx: NextPageContext\n  router: Router\n}\n\nexport type AppInitialProps<PageProps = any> = {\n  pageProps: PageProps\n}\n\nexport type AppPropsType<\n  Router extends NextRouter = NextRouter,\n  PageProps = {},\n> = AppInitialProps<PageProps> & {\n  Component: NextComponentType<NextPageContext, any, any>\n  router: Router\n  __N_SSG?: boolean\n  __N_SSP?: boolean\n}\n\nexport type DocumentContext = NextPageContext & {\n  renderPage: RenderPage\n  defaultGetInitialProps(\n    ctx: DocumentContext,\n    options?: { nonce?: string }\n  ): Promise<DocumentInitialProps>\n}\n\nexport type DocumentInitialProps = RenderPageResult & {\n  styles?: React.ReactElement[] | Iterable<React.ReactNode> | JSX.Element\n}\n\nexport type DocumentProps = DocumentInitialProps & HtmlProps\n\n/**\n * Next `API` route request\n */\nexport interface NextApiRequest extends IncomingMessage {\n  /**\n   * Object of `query` values from url\n   */\n  query: Partial<{\n    [key: string]: string | string[]\n  }>\n  /**\n   * Object of `cookies` from header\n   */\n  cookies: Partial<{\n    [key: string]: string\n  }>\n\n  body: any\n\n  env: Env\n\n  draftMode?: boolean\n\n  preview?: boolean\n  /**\n   * Preview data set on the request, if any\n   * */\n  previewData?: PreviewData\n}\n\n/**\n * Send body of response\n */\ntype Send<T> = (body: T) => void\n\n/**\n * Next `API` route response\n */\nexport type NextApiResponse<Data = any> = ServerResponse & {\n  /**\n   * Send data `any` data in response\n   */\n  send: Send<Data>\n  /**\n   * Send data `json` data in response\n   */\n  json: Send<Data>\n  status: (statusCode: number) => NextApiResponse<Data>\n  redirect(url: string): NextApiResponse<Data>\n  redirect(status: number, url: string): NextApiResponse<Data>\n\n  /**\n   * Set draft mode\n   */\n  setDraftMode: (options: { enable: boolean }) => NextApiResponse<Data>\n\n  /**\n   * Set preview data for Next.js' prerender mode\n   */\n  setPreviewData: (\n    data: object | string,\n    options?: {\n      /**\n       * Specifies the number (in seconds) for the preview session to last for.\n       * The given number will be converted to an integer by rounding down.\n       * By default, no maximum age is set and the preview session finishes\n       * when the client shuts down (browser is closed).\n       */\n      maxAge?: number\n      /**\n       * Specifies the path for the preview session to work under. By default,\n       * the path is considered the \"default path\", i.e., any pages under \"/\".\n       */\n      path?: string\n    }\n  ) => NextApiResponse<Data>\n\n  /**\n   * Clear preview data for Next.js' prerender mode\n   */\n  clearPreviewData: (options?: { path?: string }) => NextApiResponse<Data>\n\n  /**\n   * Revalidate a specific page and regenerate it using On-Demand Incremental\n   * Static Regeneration.\n   * The path should be an actual path, not a rewritten path. E.g. for\n   * \"/blog/[slug]\" this should be \"/blog/post-1\".\n   * @link https://nextjs.org/docs/app/building-your-application/data-fetching/incremental-static-regeneration#on-demand-revalidation-with-revalidatepath\n   */\n  revalidate: (\n    urlPath: string,\n    opts?: {\n      unstable_onlyGenerated?: boolean\n    }\n  ) => Promise<void>\n}\n\n/**\n * Next `API` route handler\n */\nexport type NextApiHandler<T = any> = (\n  req: NextApiRequest,\n  res: NextApiResponse<T>\n) => unknown | Promise<unknown>\n\n/**\n * Utils\n */\nexport function execOnce<T extends (...args: any[]) => ReturnType<T>>(\n  fn: T\n): T {\n  let used = false\n  let result: ReturnType<T>\n\n  return ((...args: any[]) => {\n    if (!used) {\n      used = true\n      result = fn(...args)\n    }\n    return result\n  }) as T\n}\n\n// Scheme: https://tools.ietf.org/html/rfc3986#section-3.1\n// Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3\nconst ABSOLUTE_URL_REGEX = /^[a-zA-Z][a-zA-Z\\d+\\-.]*?:/\nexport const isAbsoluteUrl = (url: string) => ABSOLUTE_URL_REGEX.test(url)\n\nexport function getLocationOrigin() {\n  const { protocol, hostname, port } = window.location\n  return `${protocol}//${hostname}${port ? ':' + port : ''}`\n}\n\nexport function getURL() {\n  const { href } = window.location\n  const origin = getLocationOrigin()\n  return href.substring(origin.length)\n}\n\nexport function getDisplayName<P>(Component: ComponentType<P>) {\n  return typeof Component === 'string'\n    ? Component\n    : Component.displayName || Component.name || 'Unknown'\n}\n\nexport function isResSent(res: ServerResponse) {\n  return res.finished || res.headersSent\n}\n\nexport function normalizeRepeatedSlashes(url: string) {\n  const urlParts = url.split('?')\n  const urlNoQuery = urlParts[0]\n\n  return (\n    urlNoQuery\n      // first we replace any non-encoded backslashes with forward\n      // then normalize repeated forward slashes\n      .replace(/\\\\/g, '/')\n      .replace(/\\/\\/+/g, '/') +\n    (urlParts[1] ? `?${urlParts.slice(1).join('?')}` : '')\n  )\n}\n\nexport async function loadGetInitialProps<\n  C extends BaseContext,\n  IP = {},\n  P = {},\n>(App: NextComponentType<C, IP, P>, ctx: C): Promise<IP> {\n  if (process.env.NODE_ENV !== 'production') {\n    if (App.prototype?.getInitialProps) {\n      const message = `\"${getDisplayName(\n        App\n      )}.getInitialProps()\" is defined as an instance method - visit https://nextjs.org/docs/messages/get-initial-props-as-an-instance-method for more information.`\n      throw new Error(message)\n    }\n  }\n  // when called from _app `ctx` is nested in `ctx`\n  const res = ctx.res || (ctx.ctx && ctx.ctx.res)\n\n  if (!App.getInitialProps) {\n    if (ctx.ctx && ctx.Component) {\n      // @ts-ignore pageProps default\n      return {\n        pageProps: await loadGetInitialProps(ctx.Component, ctx.ctx),\n      }\n    }\n    return {} as IP\n  }\n\n  const props = await App.getInitialProps(ctx)\n\n  if (res && isResSent(res)) {\n    return props\n  }\n\n  if (!props) {\n    const message = `\"${getDisplayName(\n      App\n    )}.getInitialProps()\" should resolve to an object. But found \"${props}\" instead.`\n    throw new Error(message)\n  }\n\n  if (process.env.NODE_ENV !== 'production') {\n    if (Object.keys(props).length === 0 && !ctx.ctx) {\n      console.warn(\n        `${getDisplayName(\n          App\n        )} returned an empty object from \\`getInitialProps\\`. This de-optimizes and prevents automatic static optimization. https://nextjs.org/docs/messages/empty-object-getInitialProps`\n      )\n    }\n  }\n\n  return props\n}\n\nexport const SP = typeof performance !== 'undefined'\nexport const ST =\n  SP &&\n  (['mark', 'measure', 'getEntriesByName'] as const).every(\n    (method) => typeof performance[method] === 'function'\n  )\n\nexport class DecodeError extends Error {}\nexport class NormalizeError extends Error {}\nexport class PageNotFoundError extends Error {\n  code: string\n\n  constructor(page: string) {\n    super()\n    this.code = 'ENOENT'\n    this.name = 'PageNotFoundError'\n    this.message = `Cannot find module for page: ${page}`\n  }\n}\n\nexport class MissingStaticPage extends Error {\n  constructor(page: string, message: string) {\n    super()\n    this.message = `Failed to load static file for page: ${page} ${message}`\n  }\n}\n\nexport class MiddlewareNotFoundError extends Error {\n  code: string\n  constructor() {\n    super()\n    this.code = 'ENOENT'\n    this.message = `Cannot find the middleware module`\n  }\n}\n\nexport interface CacheFs {\n  existsSync: typeof fs.existsSync\n  readFile: typeof fs.promises.readFile\n  readFileSync: typeof fs.readFileSync\n  writeFile(f: string, d: any): Promise<void>\n  mkdir(dir: string): Promise<void | string>\n  stat(f: string): Promise<{ mtime: Date }>\n}\n\nexport function stringifyError(error: Error) {\n  return JSON.stringify({ message: error.message, stack: error.stack })\n}\n"],"names":["DecodeError","MiddlewareNotFoundError","MissingStaticPage","NormalizeError","PageNotFoundError","SP","ST","WEB_VITALS","execOnce","getDisplayName","getLocationOrigin","getURL","isAbsoluteUrl","isResSent","loadGetInitialProps","normalizeRepeatedSlashes","stringifyError","fn","used","result","args","ABSOLUTE_URL_REGEX","url","test","protocol","hostname","port","window","location","href","origin","substring","length","Component","displayName","name","res","finished","headersSent","urlParts","split","urlNoQuery","replace","slice","join","App","ctx","process","env","NODE_ENV","prototype","getInitialProps","message","Error","pageProps","props","Object","keys","console","warn","performance","every","method","constructor","page","code","error","JSON","stringify","stack"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAoaaA,WAAW;eAAXA;;IAoBAC,uBAAuB;eAAvBA;;IAPAC,iBAAiB;eAAjBA;;IAZAC,cAAc;eAAdA;;IACAC,iBAAiB;eAAjBA;;IATAC,EAAE;eAAFA;;IACAC,EAAE;eAAFA;;IAlXAC,UAAU;eAAVA;;IAsQGC,QAAQ;eAARA;;IA+BAC,cAAc;eAAdA;;IAXAC,iBAAiB;eAAjBA;;IAKAC,MAAM;eAANA;;IAPHC,aAAa;eAAbA;;IAmBGC,SAAS;eAATA;;I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