@intlayer/core
Version:
Includes core Intlayer functions like translation, dictionary, and utility functions shared across multiple packages.
1 lines • 2.89 kB
Source Map (JSON)
{"version":3,"file":"getLocaleFromPath.cjs","names":["resolveRoutingConfig","checkIsURLAbsolute"],"sources":["../../../src/localization/getLocaleFromPath.ts"],"sourcesContent":["import type { Locale } from '@intlayer/types/allLocales';\nimport { checkIsURLAbsolute } from '../utils/checkIsURLAbsolute';\nimport { type RoutingOptions, resolveRoutingConfig } from './getPrefix';\n\n/**\n * Extracts the locale segment from the given URL or pathname based on the routing mode.\n *\n * Mode Behaviors:\n * - 'prefix-no-default': Checks path prefix. If no prefix found, assumes default locale.\n * - 'prefix-all': Checks path prefix.\n * - 'search-params': Checks for 'locale' query parameter.\n * - 'no-prefix': Returns the default locale.\n *\n * @param inputUrl - The complete URL string or pathname to process.\n * @returns The detected locale, default locale (if fallback/implicit), or undefined.\n */\nexport const getLocaleFromPath = (\n inputUrl: string = '/',\n options?: RoutingOptions\n): Locale | undefined => {\n const { defaultLocale, locales, mode } = resolveRoutingConfig(options);\n\n if (!defaultLocale || !locales) {\n return defaultLocale as Locale | undefined;\n }\n\n const isAbsoluteUrl = checkIsURLAbsolute(inputUrl);\n const fixedInputUrl =\n inputUrl?.endsWith('/') && inputUrl.length > 1\n ? inputUrl.slice(0, -1)\n : inputUrl;\n\n const url = isAbsoluteUrl\n ? new URL(fixedInputUrl)\n : new URL(fixedInputUrl, 'http://example.com');\n\n // Handle 'search-params' mode — locale is in query string\n if (mode === 'search-params') {\n const localeParam = url.searchParams.get('locale');\n if (localeParam && locales.includes(localeParam)) {\n return localeParam as Locale;\n }\n return defaultLocale as Locale;\n }\n\n // Handle 'no-prefix' mode — locale is not in the URL\n if (mode === 'no-prefix') {\n return defaultLocale as Locale;\n }\n\n // Handle prefix modes ('prefix-all' | 'prefix-no-default')\n const firstSegment = url.pathname.split('/')[1];\n if (firstSegment && locales.includes(firstSegment)) {\n return firstSegment as Locale;\n }\n\n // In 'prefix-no-default', no prefix implies the default locale\n if (mode === 'prefix-no-default') {\n return defaultLocale as Locale;\n }\n\n return undefined;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AAgBA,MAAa,qBACX,WAAmB,KACnB,YACuB;CACvB,MAAM,EAAE,eAAe,SAAS,SAASA,oDAAqB,QAAQ;AAEtE,KAAI,CAAC,iBAAiB,CAAC,QACrB,QAAO;CAGT,MAAM,gBAAgBC,oDAAmB,SAAS;CAClD,MAAM,gBACJ,UAAU,SAAS,IAAI,IAAI,SAAS,SAAS,IACzC,SAAS,MAAM,GAAG,GAAG,GACrB;CAEN,MAAM,MAAM,gBACR,IAAI,IAAI,cAAc,GACtB,IAAI,IAAI,eAAe,qBAAqB;AAGhD,KAAI,SAAS,iBAAiB;EAC5B,MAAM,cAAc,IAAI,aAAa,IAAI,SAAS;AAClD,MAAI,eAAe,QAAQ,SAAS,YAAY,CAC9C,QAAO;AAET,SAAO;;AAIT,KAAI,SAAS,YACX,QAAO;CAIT,MAAM,eAAe,IAAI,SAAS,MAAM,IAAI,CAAC;AAC7C,KAAI,gBAAgB,QAAQ,SAAS,aAAa,CAChD,QAAO;AAIT,KAAI,SAAS,oBACX,QAAO"}