{"version":3,"file":"index.mjs","sources":["webpack://@tarko/config-loader/./src/index.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n/*\n * Copyright (c) 2025 Bytedance, Inc. and its affiliates.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { pathToFileURL } from 'node:url';\n\n/**\n * Checks if a value is a plain object (not an array, function, or other object type)\n */\nexport const isObject = (obj: unknown): obj is Record<string, any> => {\n  return obj !== null && typeof obj === 'object' && Object.getPrototypeOf(obj) === Object.prototype;\n};\n\nexport type ConfigLoader = 'jiti' | 'native';\n\nexport type LoadConfigOptions = {\n  /**\n   * The root path to resolve the config file.\n   * @default process.cwd()\n   */\n  cwd?: string;\n  /**\n   * The path to the config file, can be a relative or absolute path.\n   * If not provided, the function will search for the config file in the `cwd`.\n   */\n  path?: string;\n  /**\n   * A custom meta object to be passed into the config function.\n   */\n  meta?: Record<string, unknown>;\n  /**\n   * The environment mode to be passed into the config function.\n   * @default process.env.NODE_ENV\n   */\n  envMode?: string;\n  /**\n   * Specify the config loader, can be `jiti` or `native`.\n   * - 'jiti': Use `jiti` as loader, which supports TypeScript and ESM out of the box\n   * - 'native': Use native Node.js loader, requires TypeScript support in Node.js >= 22.6\n   * @default 'jiti'\n   */\n  loader?: ConfigLoader;\n  /**\n   * The list of config file names to search for.\n   * For example: ['app.config.ts', 'app.config.js']\n   * @default []\n   */\n  configFiles?: string[];\n};\n\nexport type LoadConfigResult<T extends Record<string, any> = Record<string, any>> = {\n  /**\n   * The loaded configuration object with specified type.\n   */\n  content: T;\n  /**\n   * The path to the loaded configuration file.\n   * Return `null` if the configuration file is not found.\n   */\n  filePath: string | null;\n};\n\n/**\n * Resolves the path to the config file.\n */\nexport const resolveConfigPath = (root: string, configFiles: string[], customConfig?: string) => {\n  if (customConfig) {\n    const customConfigPath = path.isAbsolute(customConfig)\n      ? customConfig\n      : path.join(root, customConfig);\n    if (fs.existsSync(customConfigPath)) {\n      return customConfigPath;\n    }\n  }\n\n  if (configFiles.length === 0) {\n    return null;\n  }\n\n  for (const file of configFiles) {\n    const configFile = path.join(root, file);\n    if (fs.existsSync(configFile)) {\n      return configFile;\n    }\n  }\n\n  return null;\n};\n\n/**\n * Loads configuration from a file with generic type support.\n */\nexport async function loadConfig<T extends Record<string, any> = Record<string, any>>({\n  cwd = process.cwd(),\n  path: configPath,\n  meta = {},\n  envMode,\n  loader = 'jiti',\n  configFiles = [],\n}: LoadConfigOptions = {}): Promise<LoadConfigResult<T>> {\n  const configFilePath = resolveConfigPath(cwd, configFiles, configPath);\n\n  if (!configFilePath) {\n    return {\n      content: {} as T,\n      filePath: configFilePath,\n    };\n  }\n\n  let configExport: any;\n\n  // Handle JSON files\n  if (/\\.json$/.test(configFilePath)) {\n    try {\n      const content = await fs.promises.readFile(configFilePath, 'utf-8');\n      configExport = JSON.parse(content);\n    } catch (err) {\n      console.error(`Failed to load JSON file: ${configFilePath}`);\n      throw err;\n    }\n  }\n  // Handle YAML files\n  else if (/\\.ya?ml$/.test(configFilePath)) {\n    try {\n      const { default: yaml } = await import('js-yaml');\n      const content = await fs.promises.readFile(configFilePath, 'utf-8');\n      configExport = yaml.load(content);\n    } catch (err) {\n      console.error(`Failed to load YAML file: ${configFilePath}`);\n      throw err;\n    }\n  }\n  // Handle JavaScript files or when using native loader\n  else if (loader === 'native' || /\\.(?:js|mjs|cjs)$/.test(configFilePath)) {\n    try {\n      const configFileURL = pathToFileURL(configFilePath).href;\n      const exportModule = await import(`${configFileURL}?t=${Date.now()}`);\n      configExport = exportModule.default ? exportModule.default : exportModule;\n    } catch (err) {\n      if (loader === 'native') {\n        console.error(`Failed to load file with native loader: ${configFilePath}`);\n        throw err;\n      }\n      console.debug(`Failed to load file with dynamic import: ${configFilePath}`);\n    }\n  }\n\n  // Handle TypeScript files with jiti\n  try {\n    if (configExport === undefined) {\n      const { createJiti } = await import('jiti');\n      const jiti = createJiti(__filename, {\n        // disable require cache to support restart and read the new config\n        moduleCache: false,\n        interopDefault: true,\n      });\n\n      configExport = await jiti.import(configFilePath, {\n        default: true,\n      });\n    }\n  } catch (err) {\n    console.error(`Failed to load file with jiti: ${configFilePath}`);\n    throw err;\n  }\n\n  // Handle function export\n  if (typeof configExport === 'function') {\n    const nodeEnv = process.env.NODE_ENV || 'development';\n    const configParams = {\n      env: nodeEnv,\n      envMode: envMode || nodeEnv,\n      meta,\n    };\n\n    const result = await configExport(configParams);\n\n    if (result === undefined) {\n      throw new Error('[loadConfig] The config function must return a config object.');\n    }\n\n    return {\n      content: result as T,\n      filePath: configFilePath,\n    };\n  }\n\n  if (!isObject(configExport)) {\n    throw new Error(\n      `[loadConfig] The config must be an object or a function that returns an object, got ${configExport}`,\n    );\n  }\n\n  return {\n    content: configExport as T,\n    filePath: configFilePath,\n  };\n}\n"],"names":["isObject","obj","Object","resolveConfigPath","root","configFiles","customConfig","customConfigPath","path","fs","file","configFile","loadConfig","cwd","process","configPath","meta","envMode","loader","configFilePath","configExport","content","JSON","err","console","yaml","configFileURL","pathToFileURL","exportModule","Date","undefined","createJiti","jiti","__filename","nodeEnv","configParams","result","Error"],"mappings":";;;;;;;AAYO,MAAMA,WAAW,CAACC,MAChBA,AAAQ,SAARA,OAAgB,AAAe,YAAf,OAAOA,OAAoBC,OAAO,cAAc,CAACD,SAASC,OAAO,SAAS;AAuD5F,MAAMC,oBAAoB,CAACC,MAAcC,aAAuBC;IACrE,IAAIA,cAAc;QAChB,MAAMC,mBAAmBC,UAAAA,UAAe,CAACF,gBACrCA,eACAE,UAAAA,IAAS,CAACJ,MAAME;QACpB,IAAIG,QAAAA,UAAa,CAACF,mBAChB,OAAOA;IAEX;IAEA,IAAIF,AAAuB,MAAvBA,YAAY,MAAM,EACpB,OAAO;IAGT,KAAK,MAAMK,QAAQL,YAAa;QAC9B,MAAMM,aAAaH,UAAAA,IAAS,CAACJ,MAAMM;QACnC,IAAID,QAAAA,UAAa,CAACE,aAChB,OAAOA;IAEX;IAEA,OAAO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