@theholocron/datapad 5.0.0-alpha.113 → 5.0.0-alpha.115

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -43,13 +43,23 @@ export const defineConfig = createDefineConfig<TasksConfig>();
43
43
 
44
44
  ## API
45
45
 
46
- ### `loadConfigFile<T>({ cwd, name, extensions? })`
47
-
48
- Loads the first `<name>.config.<ext>` found in `cwd`. Probe order is
49
- **TS-first** — `.ts` → `.js` → `.mjs` → `.cjs` → `.json` — overridable via
50
- `extensions`. Returns `{ config, filepath } | null`. `null` means "no such
51
- file"; a file that exists but cannot be parsed / loaded / has no default
52
- export throws `ConfigFileError`.
46
+ ### `loadConfigFile<T>({ cwd, name, extensions?, walkUp? })`
47
+
48
+ Loads the first `<name>.config.<ext>` found starting at `cwd`. Probe order
49
+ is **TS-first** — `.ts` → `.js` → `.mjs` → `.cjs` → `.json` — overridable
50
+ via `extensions`. Returns `{ config, filepath } | null`. `null` means "no
51
+ such file anywhere searched"; a file that exists but cannot be parsed /
52
+ loaded / has no default export throws `ConfigFileError`.
53
+
54
+ `walkUp: true` (off by default) adds the "nearest config" search
55
+ `cosmiconfig`/`postcss`/`stylelint`/ESLint's flat config all do: when `cwd`
56
+ has no match, check its parent, then its parent's parent, and so on —
57
+ stopping at the first directory containing a `.git` entry (that directory
58
+ is still searched before stopping) or the filesystem root. Never wanders
59
+ past a repo boundary into an unrelated enclosing directory. `loadLayered`
60
+ passes its own `walkUp` through to both the dedicated-file and
61
+ fallback-file lookups. Built on `@theholocron/fs-utils`'s generic
62
+ `findUpward`/`hasGitEntry` — not reimplemented here.
53
63
 
54
64
  ### `loadConfigFromContent<T>({ dir, content, name, extension })`
55
65
 
@@ -67,7 +77,7 @@ Built for `@theholocron/sentinel`'s `validateConfig()` — it fetches a
67
77
  repo's `holocron.config.*` from GitHub's API, not a local checkout, but
68
78
  still needs the fetched content to execute as a real module.
69
79
 
70
- ### `loadLayered<T>({ cwd, name, fallback?, extensions? })`
80
+ ### `loadLayered<T>({ cwd, name, fallback?, extensions?, walkUp? })`
71
81
 
72
82
  `<name>.config.*` layered over the `[fallback.key]` of
73
83
  `<fallback.file>.config.*`. Either, both, or neither may be present; the
@@ -79,7 +89,10 @@ paths actually merged, lowest priority first.
79
89
 
80
90
  Deep-merge, `vite`-style: plain objects merge recursively, arrays
81
91
  concatenate (`base` first), `undefined` in `override` is skipped, every
82
- other `override` value replaces `base`. Neither input is mutated.
92
+ other `override` value replaces `base`. Neither input is mutated. A
93
+ re-export of `@theholocron/object-utils`'s `deepMerge` under this
94
+ package's established name — the merge logic itself has no awareness of
95
+ configs at all, so it lives there instead of being duplicated here.
83
96
 
84
97
  ### `createDefineConfig<T>()`
85
98
 
package/dist/index.d.mts CHANGED
@@ -1,3 +1,4 @@
1
+ import { deepMerge as mergeConfig } from "@theholocron/object-utils";
1
2
  //#region src/define.d.ts
2
3
  /**
3
4
  * Build a typed identity `defineConfig` for a specific config shape.
@@ -39,16 +40,35 @@ declare class ConfigFileError extends Error {
39
40
  * Probe order is **TS-first**: `.ts` → `.js` → `.mjs` → `.cjs` → `.json`.
40
41
  * TS is loaded through `tsx`'s `tsImport` (a runtime dependency) so a
41
42
  * typed `defineConfig` file works with no build step.
43
+ *
44
+ * `walkUp` (off by default) adds the "nearest config" search
45
+ * cosmiconfig/postcss/stylelint/ESLint's flat config all do: when `cwd`
46
+ * itself has no match, check its parent, then its parent's parent, and so
47
+ * on — stopping at the first directory containing a `.git` entry (checked
48
+ * after that directory's own config probe, so the project root itself is
49
+ * still searched) or the filesystem root. Never wanders past a repo
50
+ * boundary into an unrelated enclosing directory. Built on
51
+ * `@theholocron/fs-utils`'s `findUpward`/`hasGitEntry` — the same
52
+ * upward-walk shape `@theholocron/sentinel`'s own `findPackageRoot` needs,
53
+ * only with a different predicate.
42
54
  */
43
55
  /** Default extension probe order, highest priority first. */
44
56
  declare const DEFAULT_EXTENSIONS: readonly ["ts", "js", "mjs", "cjs", "json"];
45
57
  interface LoadConfigFileOptions {
46
- /** Directory to look in. */
58
+ /** Directory to start looking in. */
47
59
  cwd: string;
48
60
  /** Base name — `"holocron"` resolves `holocron.config.{ts,js,mjs,cjs,json}`. */
49
61
  name: string;
50
62
  /** Override the extension probe order. */
51
63
  extensions?: readonly string[];
64
+ /**
65
+ * Walk upward through ancestor directories when `cwd` itself has no
66
+ * match, stopping at the first directory containing a `.git` entry (that
67
+ * directory is still searched before stopping) or the filesystem root.
68
+ * Off by default — exact-`cwd`-only, unchanged behavior for any existing
69
+ * caller that doesn't pass this.
70
+ */
71
+ walkUp?: boolean;
52
72
  }
53
73
  interface Loaded<T> {
54
74
  config: T;
@@ -56,9 +76,11 @@ interface Loaded<T> {
56
76
  filepath: string;
57
77
  }
58
78
  /**
59
- * Load the first `<name>.config.<ext>` that exists in `cwd`. Returns
60
- * `null` when none is present; throws {@link ConfigFileError} when a file
61
- * exists but cannot be loaded.
79
+ * Load the first `<name>.config.<ext>` found starting at `cwd` — just
80
+ * `cwd` itself by default, or walking up through ancestor directories when
81
+ * `walkUp` is set (see the module doc comment for the stop conditions).
82
+ * Returns `null` when none is present anywhere searched; throws
83
+ * {@link ConfigFileError} when a file exists but cannot be loaded.
62
84
  */
63
85
  declare function loadConfigFile<T>(opts: LoadConfigFileOptions): Promise<Loaded<T> | null>;
64
86
  interface LoadLayeredOptions extends LoadConfigFileOptions {
@@ -115,17 +137,4 @@ interface LoadConfigFromContentOptions {
115
137
  */
116
138
  declare function loadConfigFromContent<T>(opts: LoadConfigFromContentOptions): Promise<Loaded<T>>;
117
139
  //#endregion
118
- //#region src/merge.d.ts
119
- /**
120
- * Deep-merge two config objects, `vite`-style:
121
- *
122
- * - plain objects merge recursively
123
- * - arrays concatenate (`base` first, then `override`)
124
- * - an `undefined` value in `override` is skipped (keeps `base`)
125
- * - every other `override` value replaces `base`
126
- *
127
- * Neither input is mutated.
128
- */
129
- declare function mergeConfig<T>(base: T, override: unknown): T;
130
- //#endregion
131
140
  export { ConfigFileError, DEFAULT_EXTENSIONS, type LayeredResult, type LoadConfigFileOptions, type LoadConfigFromContentOptions, type LoadLayeredOptions, type Loaded, createDefineConfig, loadConfigFile, loadConfigFromContent, loadLayered, mergeConfig };
package/dist/index.mjs CHANGED
@@ -1,6 +1,9 @@
1
1
  import { readFile, stat, writeFile } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
+ import { findUpward, hasGitEntry } from "@theholocron/fs-utils";
4
+ import { deepMerge, deepMerge as mergeConfig } from "@theholocron/object-utils";
3
5
  import { pathToFileURL } from "node:url";
6
+ import { errorMessage } from "@theholocron/misc-utils";
4
7
  //#region src/define.ts
5
8
  /**
6
9
  * Build a typed identity `defineConfig` for a specific config shape.
@@ -34,33 +37,74 @@ var ConfigFileError = class extends Error {
34
37
  }
35
38
  };
36
39
  //#endregion
37
- //#region src/merge.ts
40
+ //#region src/utils.ts
38
41
  /**
39
- * Deep-merge two config objects, `vite`-style:
40
- *
41
- * - plain objects merge recursively
42
- * - arrays concatenate (`base` first, then `override`)
43
- * - an `undefined` value in `override` is skipped (keeps `base`)
44
- * - every other `override` value replaces `base`
45
- *
46
- * Neither input is mutated.
42
+ * The actual file-loading mechanics `load.ts`'s exported functions share:
43
+ * JSON parsing, dynamic `import()` (TS via `tsx`'s persistent ESM loader,
44
+ * JS/MJS/CJS natively), and unwrapping the CJS/ESM default-export
45
+ * double-wrap `tsx`'s transform produces. Kept separate from `load.ts`'s
46
+ * own orchestration (which directory, which extension order, upward
47
+ * search) — this file only knows "given one exact filepath and
48
+ * extension, load it," always throwing {@link ConfigFileError} on failure.
47
49
  */
48
- function mergeConfig(base, override) {
49
- if (!isPlainObject(base) || !isPlainObject(override)) return override === void 0 ? base : override;
50
- const out = { ...base };
51
- for (const [key, value] of Object.entries(override)) {
52
- if (value === void 0) continue;
53
- const prev = out[key];
54
- if (Array.isArray(prev) && Array.isArray(value)) out[key] = [...prev, ...value];
55
- else if (isPlainObject(prev) && isPlainObject(value)) out[key] = mergeConfig(prev, value);
56
- else out[key] = value;
50
+ async function loadFile(filepath, ext) {
51
+ if (ext === "json") return loadJson(filepath);
52
+ return extractDefault(filepath, ext === "ts" ? await importTs(filepath) : await importModule(filepath));
53
+ }
54
+ async function loadJson(filepath) {
55
+ const text = await readFile(filepath, "utf8");
56
+ try {
57
+ return JSON.parse(text);
58
+ } catch (err) {
59
+ throw new ConfigFileError(`${filepath} is not valid JSON: ${errorMessage(err)}`, filepath);
57
60
  }
58
- return out;
59
61
  }
60
- function isPlainObject(value) {
61
- if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
62
- const proto = Object.getPrototypeOf(value);
63
- return proto === Object.prototype || proto === null;
62
+ async function importModule(filepath) {
63
+ try {
64
+ return await import(pathToFileURL(filepath).href);
65
+ } catch (err) {
66
+ throw new ConfigFileError(`could not load ${filepath}: ${errorMessage(err)}`, filepath);
67
+ }
68
+ }
69
+ let tsRegistered;
70
+ async function registerTsx() {
71
+ const { register } = await import("tsx/esm/api");
72
+ register();
73
+ }
74
+ /**
75
+ * Load a `.ts` file. `tsx`'s ESM loader is registered once per process
76
+ * (lazily — only when a `.ts` file is actually loaded). `register()` is
77
+ * used over `tsImport()` because a single run may load several TS files
78
+ * (`loadLayered` reads a dedicated file *and* a parent file) and
79
+ * `tsImport`'s one-off register/unregister cycle is not reentrant.
80
+ */
81
+ async function importTs(filepath) {
82
+ tsRegistered ??= registerTsx();
83
+ await tsRegistered;
84
+ try {
85
+ return await import(pathToFileURL(filepath).href);
86
+ } catch (err) {
87
+ throw new ConfigFileError(`could not load ${filepath}: ${errorMessage(err)}`, filepath);
88
+ }
89
+ }
90
+ /**
91
+ * Unwrap `export default`. `tsx` CJS-transforms `export default x` into
92
+ * `exports.default = x`, which dynamic import wraps as
93
+ * `{ default: { __esModule: true, default: x } }` — strip the extra layer
94
+ * when present so ESM and CJS outputs both resolve.
95
+ */
96
+ function extractDefault(filepath, mod) {
97
+ const outer = mod.default;
98
+ const raw = outer?.__esModule === true ? outer.default : outer;
99
+ if (raw === void 0 || raw === null) throw new ConfigFileError(`${filepath} must have a default export (use \`export default defineConfig({…})\`)`, filepath);
100
+ return raw;
101
+ }
102
+ async function isFile(path) {
103
+ try {
104
+ return (await stat(path)).isFile();
105
+ } catch {
106
+ return false;
107
+ }
64
108
  }
65
109
  //#endregion
66
110
  //#region src/load.ts
@@ -73,6 +117,17 @@ function isPlainObject(value) {
73
117
  * Probe order is **TS-first**: `.ts` → `.js` → `.mjs` → `.cjs` → `.json`.
74
118
  * TS is loaded through `tsx`'s `tsImport` (a runtime dependency) so a
75
119
  * typed `defineConfig` file works with no build step.
120
+ *
121
+ * `walkUp` (off by default) adds the "nearest config" search
122
+ * cosmiconfig/postcss/stylelint/ESLint's flat config all do: when `cwd`
123
+ * itself has no match, check its parent, then its parent's parent, and so
124
+ * on — stopping at the first directory containing a `.git` entry (checked
125
+ * after that directory's own config probe, so the project root itself is
126
+ * still searched) or the filesystem root. Never wanders past a repo
127
+ * boundary into an unrelated enclosing directory. Built on
128
+ * `@theholocron/fs-utils`'s `findUpward`/`hasGitEntry` — the same
129
+ * upward-walk shape `@theholocron/sentinel`'s own `findPackageRoot` needs,
130
+ * only with a different predicate.
76
131
  */
77
132
  /** Default extension probe order, highest priority first. */
78
133
  const DEFAULT_EXTENSIONS = [
@@ -83,21 +138,34 @@ const DEFAULT_EXTENSIONS = [
83
138
  "json"
84
139
  ];
85
140
  /**
86
- * Load the first `<name>.config.<ext>` that exists in `cwd`. Returns
87
- * `null` when none is present; throws {@link ConfigFileError} when a file
88
- * exists but cannot be loaded.
141
+ * Probe `dir` for `<name>.config.<ext>` in extension-priority order,
142
+ * loading and returning the first match. The one piece of per-directory
143
+ * orchestration `loadConfigFile` needs on both its non-walking and
144
+ * walking paths — pulled out so it can be unit-tested directly instead of
145
+ * only through `loadConfigFile`'s full probe/walk behavior.
89
146
  */
90
- async function loadConfigFile(opts) {
91
- const extensions = opts.extensions ?? DEFAULT_EXTENSIONS;
147
+ async function probeExtensions(dir, name, extensions) {
92
148
  for (const ext of extensions) {
93
- const filepath = join(opts.cwd, `${opts.name}.config.${ext}`);
149
+ const filepath = join(dir, `${name}.config.${ext}`);
94
150
  if (!await isFile(filepath)) continue;
95
151
  return {
96
152
  config: await loadFile(filepath, ext),
97
153
  filepath
98
154
  };
99
155
  }
100
- return null;
156
+ }
157
+ /**
158
+ * Load the first `<name>.config.<ext>` found starting at `cwd` — just
159
+ * `cwd` itself by default, or walking up through ancestor directories when
160
+ * `walkUp` is set (see the module doc comment for the stop conditions).
161
+ * Returns `null` when none is present anywhere searched; throws
162
+ * {@link ConfigFileError} when a file exists but cannot be loaded.
163
+ */
164
+ async function loadConfigFile(opts) {
165
+ const extensions = opts.extensions ?? DEFAULT_EXTENSIONS;
166
+ const checkDir = (dir) => probeExtensions(dir, opts.name, extensions);
167
+ if (!opts.walkUp) return await checkDir(opts.cwd) ?? null;
168
+ return await findUpward(opts.cwd, checkDir, hasGitEntry) ?? null;
101
169
  }
102
170
  /**
103
171
  * `<name>.config.*` layered over the `[fallback.key]` of
@@ -113,7 +181,8 @@ async function loadLayered(opts) {
113
181
  const parent = await loadConfigFile({
114
182
  cwd: opts.cwd,
115
183
  name: opts.fallback.file,
116
- extensions: opts.extensions
184
+ extensions: opts.extensions,
185
+ walkUp: opts.walkUp
117
186
  });
118
187
  if (parent && parent.config[opts.fallback.key] !== void 0) {
119
188
  base = parent.config[opts.fallback.key];
@@ -121,7 +190,7 @@ async function loadLayered(opts) {
121
190
  }
122
191
  }
123
192
  if (!dedicated && base === void 0) return null;
124
- const config = mergeConfig(base, dedicated?.config);
193
+ const config = deepMerge(base, dedicated?.config);
125
194
  const sources = [baseFile, dedicated?.filepath ?? null].filter((s) => s !== null);
126
195
  return {
127
196
  config,
@@ -147,65 +216,5 @@ async function loadConfigFromContent(opts) {
147
216
  filepath
148
217
  };
149
218
  }
150
- async function loadFile(filepath, ext) {
151
- if (ext === "json") return loadJson(filepath);
152
- return extractDefault(filepath, ext === "ts" ? await importTs(filepath) : await importModule(filepath));
153
- }
154
- async function loadJson(filepath) {
155
- const text = await readFile(filepath, "utf8");
156
- try {
157
- return JSON.parse(text);
158
- } catch (err) {
159
- throw new ConfigFileError(`${filepath} is not valid JSON: ${message(err)}`, filepath);
160
- }
161
- }
162
- async function importModule(filepath) {
163
- try {
164
- return await import(pathToFileURL(filepath).href);
165
- } catch (err) {
166
- throw new ConfigFileError(`could not load ${filepath}: ${message(err)}`, filepath);
167
- }
168
- }
169
- let tsRegistered;
170
- async function registerTsx() {
171
- const { register } = await import("tsx/esm/api");
172
- register();
173
- }
174
- /**
175
- * Load a `.ts` config. `tsx`'s ESM loader is registered once per process
176
- * (lazily — only when a `.ts` config is actually loaded). `register()` is
177
- * used over `tsImport()` because a single run may load several TS configs
178
- * (`loadLayered` reads a dedicated file *and* a parent file) and
179
- * `tsImport`'s one-off register/unregister cycle is not reentrant.
180
- */
181
- async function importTs(filepath) {
182
- tsRegistered ??= registerTsx();
183
- await tsRegistered;
184
- try {
185
- return await import(pathToFileURL(filepath).href);
186
- } catch (err) {
187
- throw new ConfigFileError(`could not load ${filepath}: ${message(err)}`, filepath);
188
- }
189
- }
190
- /**
191
- * Unwrap `export default`. `tsx` CJS-transforms `export default x` into
192
- * `exports.default = x`, which dynamic import wraps as
193
- * `{ default: { __esModule: true, default: x } }` — strip the extra layer
194
- * when present so ESM and CJS outputs both resolve.
195
- */
196
- function extractDefault(filepath, mod) {
197
- const outer = mod.default;
198
- const raw = outer?.__esModule === true ? outer.default : outer;
199
- if (raw === void 0 || raw === null) throw new ConfigFileError(`${filepath} must have a default export (use \`export default defineConfig({…})\`)`, filepath);
200
- return raw;
201
- }
202
- async function isFile(path) {
203
- try {
204
- return (await stat(path)).isFile();
205
- } catch {
206
- return false;
207
- }
208
- }
209
- const message = (err) => err instanceof Error ? err.message : String(err);
210
219
  //#endregion
211
220
  export { ConfigFileError, DEFAULT_EXTENSIONS, createDefineConfig, loadConfigFile, loadConfigFromContent, loadLayered, mergeConfig };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theholocron/datapad",
3
- "version": "5.0.0-alpha.113",
3
+ "version": "5.0.0-alpha.115",
4
4
  "description": "Generic config-file loading for Holocron — discover, load (JSON/JS/TS/ESM/CJS), and merge <name>.config.* files with a typed defineConfig.",
5
5
  "keywords": [
6
6
  "config",
@@ -32,13 +32,16 @@
32
32
  "dist"
33
33
  ],
34
34
  "dependencies": {
35
+ "@theholocron/fs-utils": "^1.9.2",
36
+ "@theholocron/misc-utils": "^1.9.2",
37
+ "@theholocron/object-utils": "^1.9.2",
35
38
  "tsx": "4.23.12"
36
39
  },
37
40
  "devDependencies": {
38
- "@theholocron/eslint-config": "^8.6.0",
39
- "@theholocron/tsconfig": "^8.4.5",
40
- "@theholocron/tsdown-config": "^8.4.5",
41
- "@theholocron/vitest-config": "^8.4.5",
41
+ "@theholocron/eslint-config": "^8.7.0",
42
+ "@theholocron/tsconfig": "^8.7.0",
43
+ "@theholocron/tsdown-config": "^8.7.0",
44
+ "@theholocron/vitest-config": "^8.7.0",
42
45
  "@types/node": "^26",
43
46
  "@vitest/coverage-v8": "^4.1.11",
44
47
  "@vitest/eslint-plugin": "^1.6.27",