Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: generic types support #64

Merged
merged 2 commits into from
Mar 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
{
"extends": [
"eslint-config-unjs"
],
"extends": ["eslint-config-unjs"],
"rules": {
"unicorn/prevent-abbreviations": 0
"unicorn/prevent-abbreviations": 0,
"@typescript-eslint/no-non-null-assertion": 0
}
}
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,6 @@ jobs:
- run: pnpm install
- run: pnpm lint
- run: pnpm build
- run: pnpm test:types
- run: pnpm vitest --coverage
- uses: codecov/codecov-action@v3
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@
"lint:fix": "eslint --ext .ts,.js,.mjs,.cjs . --fix && prettier -w src test",
"prepack": "unbuild",
"release": "changelogen --release && npm publish && git push --follow-tags",
"test": "vitest run --coverage"
"test": "vitest run --coverage && pnpm test:types",
"test:types": "tsc --noEmit"
},
"dependencies": {
"defu": "^6.1.2",
Expand All @@ -43,6 +44,7 @@
"changelogen": "^0.5.1",
"eslint": "^8.36.0",
"eslint-config-unjs": "^0.1.0",
"expect-type": "^0.15.0",
"prettier": "^2.8.4",
"typescript": "^4.9.5",
"unbuild": "^1.1.2",
Expand Down
6 changes: 6 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 6 additions & 6 deletions src/dotenv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,15 +65,15 @@ export async function setupDotenv(options: DotenvOptions): Promise<Env> {
export async function loadDotenv(options: DotenvOptions): Promise<Env> {
const environment = Object.create(null);

const dotenvFile = resolve(options.cwd, options.fileName);
const dotenvFile = resolve(options.cwd, options.fileName!);

if (existsSync(dotenvFile)) {
const parsed = dotenv.parse(await fsp.readFile(dotenvFile, "utf8"));
Object.assign(environment, parsed);
}

// Apply process.env
if (!options.env._applied) {
if (!options.env?._applied) {
Object.assign(environment, options.env);
environment._applied = true;
}
Expand All @@ -97,25 +97,25 @@ function interpolate(
return source[key] !== undefined ? source[key] : target[key];
}

function interpolate(value: unknown, parents: string[] = []) {
function interpolate(value: unknown, parents: string[] = []): any {
if (typeof value !== "string") {
return value;
}
const matches: string[] = value.match(/(.?\${?(?:[\w:]+)?}?)/g) || [];
return parse(
// eslint-disable-next-line unicorn/no-array-reduce
matches.reduce((newValue, match) => {
const parts = /(.?)\${?([\w:]+)?}?/g.exec(match);
const parts = /(.?)\${?([\w:]+)?}?/g.exec(match) || [];
const prefix = parts[1];

let value, replacePart: string;

if (prefix === "\\") {
replacePart = parts[0];
replacePart = parts[0] || "";
value = replacePart.replace("\\$", "$");
} else {
const key = parts[2];
replacePart = parts[0].slice(prefix.length);
replacePart = (parts[0] || "").slice(prefix.length);

// Avoid recursion
if (parents.includes(key)) {
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from "./dotenv";
export * from "./loader";
export * from "./types";
162 changes: 54 additions & 108 deletions src/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,92 +2,26 @@ import { existsSync } from "node:fs";
import { rmdir } from "node:fs/promises";
import { homedir } from "node:os";
import { resolve, extname, dirname } from "pathe";
import createJiti, { JITI } from "jiti";
import createJiti from "jiti";
import * as rc9 from "rc9";
import { defu } from "defu";
import { findWorkspaceDir, readPackageJSON } from "pkg-types";
import type { JITIOptions } from "jiti/dist/types";
import { DotenvOptions, setupDotenv } from "./dotenv";

export type UserInputConfig = Record<string, any>;

export interface ConfigLayerMeta {
name?: string;
[key: string]: any;
}

export interface C12InputConfig {
$test?: UserInputConfig;
$development?: UserInputConfig;
$production?: UserInputConfig;
$env?: Record<string, UserInputConfig>;
$meta?: ConfigLayerMeta;
}

export interface InputConfig extends C12InputConfig, UserInputConfig {}

export interface SourceOptions {
meta?: ConfigLayerMeta;
overrides?: UserInputConfig;
[key: string]: any;
}

export interface ConfigLayer<T extends InputConfig = InputConfig> {
config: T | null;
source?: string;
sourceOptions?: SourceOptions;
meta?: ConfigLayerMeta;
cwd?: string;
configFile?: string;
}

export interface ResolvedConfig<T extends InputConfig = InputConfig>
extends ConfigLayer<T> {
layers?: ConfigLayer<T>[];
cwd?: string;
}

export interface ResolveConfigOptions {
cwd: string;
}

export interface LoadConfigOptions<T extends InputConfig = InputConfig> {
name?: string;
cwd?: string;

configFile?: string;

rcFile?: false | string;
globalRc?: boolean;

dotenv?: boolean | DotenvOptions;

envName?: string | false;

packageJson?: boolean | string | string[];

defaults?: T;
defaultConfig?: T;
overrides?: T;

resolve?: (
id: string,
options: LoadConfigOptions
) => null | ResolvedConfig | Promise<ResolvedConfig | null>;

jiti?: JITI;
jitiOptions?: JITIOptions;

extend?:
| false
| {
extendKey?: string | string[];
};
}

export async function loadConfig<T extends InputConfig = InputConfig>(
options: LoadConfigOptions<T>
): Promise<ResolvedConfig<T>> {
import { setupDotenv } from "./dotenv";

import type {
UserInputConfig,
ConfigLayerMeta,
LoadConfigOptions,
ResolvedConfig,
ConfigLayer,
SourceOptions,
InputConfig,
} from "./types";

export async function loadConfig<
T extends UserInputConfig = UserInputConfig,
MT extends ConfigLayerMeta = ConfigLayerMeta
>(options: LoadConfigOptions<T, MT>): Promise<ResolvedConfig<T, MT>> {
// Normalize options
options.cwd = resolve(process.cwd(), options.cwd || ".");
options.name = options.name || "config";
Expand All @@ -106,15 +40,15 @@ export async function loadConfig<T extends InputConfig = InputConfig>(
// Create jiti instance
options.jiti =
options.jiti ||
createJiti(undefined, {
createJiti(undefined as unknown as string, {
interopDefault: true,
requireCache: false,
esmResolve: true,
...options.jitiOptions,
});

// Create context
const r: ResolvedConfig<T> = {
const r: ResolvedConfig<T, MT> = {
config: {} as any,
cwd: options.cwd,
configFile: resolve(options.cwd, options.configFile),
Expand Down Expand Up @@ -188,7 +122,7 @@ export async function loadConfig<T extends InputConfig = InputConfig>(
await extendConfig(r.config, options);
r.layers = r.config._layers;
delete r.config._layers;
r.config = defu(r.config, ...r.layers.map((e) => e.config)) as T;
r.config = defu(r.config, ...r.layers!.map((e) => e.config)) as T;
}

// Preserve unmerged sources as layers
Expand All @@ -201,8 +135,9 @@ export async function loadConfig<T extends InputConfig = InputConfig>(
{ config, configFile: options.configFile, cwd: options.cwd },
options.rcFile && { config: configRC, configFile: options.rcFile },
options.packageJson && { config: pkgJson, configFile: "package.json" },
].filter((l) => l && l.config) as ConfigLayer<T>[];
r.layers = [...baseLayers, ...r.layers];
].filter((l) => l && l.config) as ConfigLayer<T, MT>[];

r.layers = [...baseLayers, ...r.layers!];

// Apply defaults
if (options.defaults) {
Expand All @@ -213,8 +148,11 @@ export async function loadConfig<T extends InputConfig = InputConfig>(
return r;
}

async function extendConfig(config, options: LoadConfigOptions) {
config._layers = config._layers || [];
async function extendConfig<
T extends UserInputConfig = UserInputConfig,
MT extends ConfigLayerMeta = ConfigLayerMeta
>(config: InputConfig<T, MT>, options: LoadConfigOptions<T, MT>) {
(config as any)._layers = config._layers || [];
if (!options.extend) {
return;
}
Expand All @@ -223,7 +161,7 @@ async function extendConfig(config, options: LoadConfigOptions) {
keys = [keys];
}
const extendSources = [];
for (const key of keys) {
for (const key of keys as string[]) {
extendSources.push(
...(Array.isArray(config[key]) ? config[key] : [config[key]]).filter(
Boolean
Expand Down Expand Up @@ -276,11 +214,14 @@ const GIT_PREFIXES = ["github:", "gitlab:", "bitbucket:", "https://"];
const NPM_PACKAGE_RE =
/^(@[\da-z~-][\d._a-z~-]*\/)?[\da-z~-][\d._a-z~-]*($|\/.*)/;

async function resolveConfig(
async function resolveConfig<
T extends UserInputConfig = UserInputConfig,
MT extends ConfigLayerMeta = ConfigLayerMeta
>(
source: string,
options: LoadConfigOptions,
sourceOptions: SourceOptions = {}
): Promise<ResolvedConfig> {
options: LoadConfigOptions<T, MT>,
sourceOptions: SourceOptions<T, MT> = {}
): Promise<ResolvedConfig<T, MT>> {
// Custom user resolver
if (options.resolve) {
const res = await options.resolve(source, options);
Expand Down Expand Up @@ -309,48 +250,53 @@ async function resolveConfig(
// Try resolving as npm package
if (NPM_PACKAGE_RE.test(source)) {
try {
source = options.jiti.resolve(source, { paths: [options.cwd] });
source = options.jiti!.resolve(source, { paths: [options.cwd!] });
} catch {}
}

// Import from local fs
const isDir = !extname(source);
const cwd = resolve(options.cwd, isDir ? source : dirname(source));
const cwd = resolve(options.cwd!, isDir ? source : dirname(source));
if (isDir) {
source = options.configFile;
source = options.configFile!;
}
const res: ResolvedConfig = { config: undefined, cwd, source, sourceOptions };
const res: ResolvedConfig<T, MT> = {
config: undefined as unknown as T,
cwd,
source,
sourceOptions,
};
try {
res.configFile = options.jiti.resolve(resolve(cwd, source), {
res.configFile = options.jiti!.resolve(resolve(cwd, source), {
paths: [cwd],
});
} catch {}
if (!existsSync(res.configFile)) {
if (!existsSync(res.configFile!)) {
return res;
}
res.config = options.jiti(res.configFile);
res.config = options.jiti!(res.configFile!);
if (res.config instanceof Function) {
res.config = await res.config();
}

// Extend env specific config
if (options.envName) {
const envConfig = {
...res.config["$" + options.envName],
...res.config.$env?.[options.envName],
...res.config!["$" + options.envName],
...res.config!.$env?.[options.envName],
};
if (Object.keys(envConfig).length > 0) {
res.config = defu(envConfig, res.config);
}
}

// Meta
res.meta = defu(res.sourceOptions.meta, res.config.$meta);
delete res.config.$meta;
res.meta = defu(res.sourceOptions!.meta, res.config!.$meta) as MT;
delete res.config!.$meta;

// Overrides
if (res.sourceOptions.overrides) {
res.config = defu(res.sourceOptions.overrides, res.config);
if (res.sourceOptions!.overrides) {
res.config = defu(res.sourceOptions!.overrides, res.config) as T;
}

return res;
Expand Down
Loading