@theholocron/datapad 5.0.0-alpha.28 → 5.0.0-alpha.281

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
 
@@ -59,7 +69,8 @@ the exact same internals `loadConfigFile` uses for a file it discovered
59
69
  itself. `dir` matters: it's what upward `node_modules` resolution sees, so
60
70
  content that does `import { defineConfig } from "@theholocron/cli"` only
61
71
  resolves if `dir` sits under a tree where that package is a real
62
- dependency. Callers own creating and cleaning up `dir`. Returns
72
+ dependency — [`withConfigSandbox`](#withconfigsandbox-nodemodules-root-prefix--run) prepares
73
+ one. Callers own creating and cleaning up `dir`. Returns
63
74
  `{ config, filepath }`; throws `ConfigFileError` the same way
64
75
  `loadConfigFile` does on a parse/load failure.
65
76
 
@@ -67,7 +78,26 @@ Built for `@theholocron/sentinel`'s `validateConfig()` — it fetches a
67
78
  repo's `holocron.config.*` from GitHub's API, not a local checkout, but
68
79
  still needs the fetched content to execute as a real module.
69
80
 
70
- ### `loadLayered<T>({ cwd, name, fallback?, extensions? })`
81
+ ### `readConfigSource({ name, fetch, extensions? })`
82
+
83
+ `loadConfigFile`'s extension probe for a config that lives somewhere other
84
+ than the local disk. Asks `fetch(path)` for `<name>.config.<ext>` in
85
+ extension-priority order (`fetch` returns the content, or `undefined` when
86
+ the file isn't there, and throws for any other failure) and returns the first
87
+ hit as `{ path, extension, content }`, or `undefined`. Hand the result to
88
+ `loadConfigFromContent`.
89
+
90
+ ### `withConfigSandbox({ nodeModules, root?, prefix? }, run)`
91
+
92
+ Runs `run(dir)` with a throwaway directory ready to be
93
+ `loadConfigFromContent`'s `dir`: `node_modules` symlinked to
94
+ `options.nodeModules` (so the config's package imports resolve) and a
95
+ `{"type":"module"}` `package.json` (so `tsx` doesn't default the files to
96
+ CommonJS and `require()` a pure-ESM dependency). Created under the OS temp dir
97
+ by default — read-only deployments can't write inside a package — and removed
98
+ afterwards, also when `run` throws.
99
+
100
+ ### `loadLayered<T>({ cwd, name, fallback?, extensions?, walkUp?, coerce? })`
71
101
 
72
102
  `<name>.config.*` layered over the `[fallback.key]` of
73
103
  `<fallback.file>.config.*`. Either, both, or neither may be present; the
@@ -75,11 +105,27 @@ dedicated file wins on conflict (`vitest`-over-`vite`). Returns
75
105
  `{ config, filepath, sources } | null` — `sources` lists the absolute
76
106
  paths actually merged, lowest priority first.
77
107
 
108
+ - `fallback.preloaded` — the `<fallback.file>.config.*` the caller has
109
+ already loaded (`null`: looked for, not there), used as is instead of loading
110
+ it again.
111
+ - `coerce(raw)` — turns each layer's raw value into the shape being merged
112
+ before the merge (a bare array standing for `{ tasks: [...] }`, say);
113
+ returning `undefined` treats the layer as absent.
114
+
115
+ ### `mergeLayers<T>(layers)`
116
+
117
+ The merge `loadLayered` uses, for layers loaded some other way: deep-merges
118
+ `layers` lowest priority first, skipping `undefined`, and returns a copy — or
119
+ `undefined` when there is nothing to merge.
120
+
78
121
  ### `mergeConfig<T>(base, override)`
79
122
 
80
123
  Deep-merge, `vite`-style: plain objects merge recursively, arrays
81
124
  concatenate (`base` first), `undefined` in `override` is skipped, every
82
- other `override` value replaces `base`. Neither input is mutated.
125
+ other `override` value replaces `base`. Neither input is mutated. A
126
+ re-export of `@theholocron/object-utils`'s `deepMerge` under this
127
+ package's established name — the merge logic itself has no awareness of
128
+ configs at all, so it lives there instead of being duplicated here.
83
129
 
84
130
  ### `createDefineConfig<T>()`
85
131
 
@@ -113,4 +159,4 @@ Automated via semantic-release. See [CHANGELOG.md](../../CHANGELOG.md).
113
159
 
114
160
  ## Documentation
115
161
 
116
- <https://theholocron.github.io/holocron/>
162
+ <https://docs.theholocron.dev/holocron/>
package/dist/index.d.mts CHANGED
@@ -1,4 +1,6 @@
1
- //#region src/define.d.ts
1
+ import { deepMerge as mergeConfig } from "@theholocron/object-utils";
2
+ /** Default extension probe order, highest priority first. */
3
+ export declare const DEFAULT_EXTENSIONS: readonly ["ts", "js", "mjs", "cjs", "json"];
2
4
  /**
3
5
  * Build a typed identity `defineConfig` for a specific config shape.
4
6
  *
@@ -11,68 +13,113 @@
11
13
  * export const defineConfig = createDefineConfig<TasksConfig>();
12
14
  * ```
13
15
  */
14
- declare function createDefineConfig<T>(): <C extends T>(config: C) => C;
15
- //#endregion
16
- //#region src/errors.d.ts
16
+ export declare function createDefineConfig<T>(): <C extends T>(config: C) => C;
17
17
  /**
18
18
  * Thrown when a config file is found but cannot be loaded — malformed
19
19
  * JSON, a syntax error in a `.ts` / `.js` module, or no usable default
20
20
  * export. "Not found" is never an error: {@link loadConfigFile} returns
21
21
  * `null` for that.
22
22
  */
23
- declare class ConfigFileError extends Error {
23
+ export declare class ConfigFileError extends Error {
24
24
  /** Absolute path of the offending file, when known. */
25
25
  readonly filepath?: string | undefined;
26
+ /** The error's name, `"ConfigFileError"`. */
26
27
  name: string;
27
28
  constructor(message: string,
28
29
  /** Absolute path of the offending file, when known. */
29
30
  filepath?: string | undefined);
30
31
  }
31
- //#endregion
32
- //#region src/load.d.ts
33
- /**
34
- * Discover and load `<name>.config.*` files, or load one from content that
35
- * didn't come from a file at all ({@link loadConfigFromContent}).
36
- * Holocron-agnostic — no schema, no validation, no defaults. Consumers
37
- * layer those on top.
38
- *
39
- * Probe order is **TS-first**: `.ts` → `.js` → `.mjs` → `.cjs` → `.json`.
40
- * TS is loaded through `tsx`'s `tsImport` (a runtime dependency) so a
41
- * typed `defineConfig` file works with no build step.
42
- */
43
- /** Default extension probe order, highest priority first. */
44
- declare const DEFAULT_EXTENSIONS: readonly ["ts", "js", "mjs", "cjs", "json"];
32
+ /** Options for finding and loading a config file from disk. */
45
33
  interface LoadConfigFileOptions {
46
- /** Directory to look in. */
34
+ /** Directory to start looking in. */
47
35
  cwd: string;
48
36
  /** Base name — `"holocron"` resolves `holocron.config.{ts,js,mjs,cjs,json}`. */
49
37
  name: string;
50
38
  /** Override the extension probe order. */
51
39
  extensions?: readonly string[];
40
+ /**
41
+ * Walk upward through ancestor directories when `cwd` itself has no
42
+ * match, stopping at the first directory containing a `.git` entry (that
43
+ * directory is still searched before stopping) or the filesystem root.
44
+ * Off by default — exact-`cwd`-only, unchanged behavior for any existing
45
+ * caller that doesn't pass this.
46
+ */
47
+ walkUp?: boolean;
52
48
  }
49
+ /** A config value together with the file it was loaded from. */
53
50
  interface Loaded<T> {
51
+ /** The loaded config value. */
54
52
  config: T;
55
53
  /** Absolute path of the file the value came from. */
56
54
  filepath: string;
57
55
  }
58
56
  /**
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.
57
+ * Load the first `<name>.config.<ext>` found starting at `cwd` — just
58
+ * `cwd` itself by default, or walking up through ancestor directories when
59
+ * `walkUp` is set (see the module doc comment for the stop conditions).
60
+ * Returns `null` when none is present anywhere searched; throws
61
+ * {@link ConfigFileError} when a file exists but cannot be loaded.
62
+ */
63
+ export declare function loadConfigFile<T>(opts: LoadConfigFileOptions): Promise<Loaded<T> | null>;
64
+ /** Options for loading a config from raw content rather than a file already on disk. */
65
+ interface LoadConfigFromContentOptions {
66
+ /**
67
+ * Directory to write `<name>.config.<extension>` into before loading —
68
+ * this is what upward `node_modules` resolution sees, so a config that
69
+ * does `import { defineConfig } from "@theholocron/cli"` only resolves
70
+ * if `dir` sits under a tree where that package is a real dependency.
71
+ * Callers own creating and cleaning up `dir` — this function only
72
+ * writes the one file into it.
73
+ */
74
+ dir: string;
75
+ /** Raw file content — not necessarily sourced from a local file at all (a network fetch, a git blob, …). */
76
+ content: string;
77
+ /** Base name — `"holocron"` writes `holocron.config.<extension>`. */
78
+ name: string;
79
+ /** Which of `DEFAULT_EXTENSIONS` `content` is — determines how it's interpreted (ts/js/mjs/cjs parsed as a module, json as `JSON.parse`). */
80
+ extension: string;
81
+ }
82
+ /**
83
+ * Load config from content that didn't come from a file already on disk —
84
+ * writes it to `<dir>/<name>.config.<extension>` first, then loads it
85
+ * through the exact same path {@link loadConfigFile} uses for a file it
86
+ * discovered itself. Exists because sourcing config content from somewhere
87
+ * other than the local filesystem (a GitHub API fetch, for one — see
88
+ * `@theholocron/sentinel`) doesn't change what loading it correctly means:
89
+ * a `.ts` config still needs real module resolution, `defineConfig` import
90
+ * included, not a re-implemented parser.
62
91
  */
63
- declare function loadConfigFile<T>(opts: LoadConfigFileOptions): Promise<Loaded<T> | null>;
64
- interface LoadLayeredOptions extends LoadConfigFileOptions {
92
+ export declare function loadConfigFromContent<T>(opts: LoadConfigFromContentOptions): Promise<Loaded<T>>;
93
+ /** Options for loading a dedicated config file layered over a fallback file's key. */
94
+ interface LoadLayeredOptions<T = unknown> extends LoadConfigFileOptions {
65
95
  /**
66
96
  * When no dedicated `<name>.config.*` exists — or in addition to it —
67
97
  * read `<file>.config.*` and take its `[key]`. The dedicated file (if
68
98
  * any) is merged on top.
69
99
  */
70
100
  fallback?: {
101
+ /** Base name of the fallback file, read as `<file>.config.*`. */
71
102
  file: string;
103
+ /** The key in the fallback file whose value is taken. */
72
104
  key: string;
105
+ /**
106
+ * The `<file>.config.*` already loaded by the caller (`null`: it was
107
+ * looked for and isn't there). Used as is instead of loading it again;
108
+ * leave it `undefined` to have `loadLayered` find and load it.
109
+ */
110
+ preloaded?: Loaded<object> | null;
73
111
  };
112
+ /**
113
+ * Turns each layer's raw value — the dedicated file's default export, and
114
+ * the fallback's `[key]` — into the shape being merged, before the merge.
115
+ * Return `undefined` to treat the layer as absent. For configs that accept
116
+ * shorthand (a bare array standing for `{ tasks: [...] }`).
117
+ */
118
+ coerce?: (raw: unknown) => T | undefined;
74
119
  }
120
+ /** The merged config from `loadLayered`, with where it came from. */
75
121
  interface LayeredResult<T> {
122
+ /** The merged config value. */
76
123
  config: T;
77
124
  /** The dedicated file path if present, else the fallback file path, else `null`. */
78
125
  filepath: string | null;
@@ -85,47 +132,82 @@ interface LayeredResult<T> {
85
132
  * the dedicated file wins on conflict (vitest-over-vite). Returns `null`
86
133
  * when neither source resolves.
87
134
  */
88
- declare function loadLayered<T>(opts: LoadLayeredOptions): Promise<LayeredResult<T> | null>;
89
- interface LoadConfigFromContentOptions {
90
- /**
91
- * Directory to write `<name>.config.<extension>` into before loading —
92
- * this is what upward `node_modules` resolution sees, so a config that
93
- * does `import { defineConfig } from "@theholocron/cli"` only resolves
94
- * if `dir` sits under a tree where that package is a real dependency.
95
- * Callers own creating and cleaning up `dir` — this function only
96
- * writes the one file into it.
97
- */
98
- dir: string;
99
- /** Raw file content — not necessarily sourced from a local file at all (a network fetch, a git blob, …). */
135
+ export declare function loadLayered<T>(opts: LoadLayeredOptions<T>): Promise<LayeredResult<T> | null>;
136
+ /**
137
+ * Deep-merges config layers, lowest priority first (a later layer wins on
138
+ * scalars; arrays concatenate; nested objects merge). `undefined` layers are
139
+ * skipped. Returns `undefined` when there is no layer to merge. The result is
140
+ * a copy for object layers — it never aliases a layer.
141
+ *
142
+ * The one merge `loadLayered` and every caller layering configs it loaded
143
+ * some other way (content from an API, say) use, so layering means the same
144
+ * thing everywhere.
145
+ */
146
+ export declare function mergeLayers<T>(layers: readonly (T | undefined)[]): T | undefined;
147
+ /** A config file's content fetched from somewhere other than the local disk. */
148
+ interface ConfigSource {
149
+ /** The file name probed, e.g. `holocron.config.ts` — relative, as `fetch` was asked for it. */
150
+ path: string;
151
+ /** Which extension matched — what {@link loadConfigFromContent} needs as `extension`. */
152
+ extension: string;
153
+ /** The raw file content. */
100
154
  content: string;
101
- /** Base name — `"holocron"` writes `holocron.config.<extension>`. */
155
+ }
156
+ /** Options for fetching a config file's content from a remote source. */
157
+ interface ReadConfigSourceOptions {
158
+ /** Base name — `"holocron"` probes `holocron.config.{ts,js,mjs,cjs,json}`. */
102
159
  name: string;
103
- /** Which of `DEFAULT_EXTENSIONS` `content` is — determines how it's interpreted (ts/js/mjs/cjs parsed as a module, json as `JSON.parse`). */
104
- extension: string;
160
+ /**
161
+ * Fetches one file by relative path (`holocron.config.ts`): its content, or
162
+ * `undefined` when it doesn't exist. Throw for anything else (a network
163
+ * failure, a permission error) — that propagates rather than reading as "absent".
164
+ */
165
+ fetch: (path: string) => Promise<string | undefined>;
166
+ /** Override the extension probe order. */
167
+ extensions?: readonly string[];
105
168
  }
106
169
  /**
107
- * Load config from content that didn't come from a file already on disk —
108
- * writes it to `<dir>/<name>.config.<extension>` first, then loads it
109
- * through the exact same path {@link loadConfigFile} uses for a file it
110
- * discovered itself. Exists because sourcing config content from somewhere
111
- * other than the local filesystem (a GitHub API fetch, for one — see
112
- * `@theholocron/sentinel`) doesn't change what loading it correctly means:
113
- * a `.ts` config still needs real module resolution, `defineConfig` import
114
- * included, not a re-implemented parser.
170
+ * {@link probeExtensions} for a config that lives somewhere other than the
171
+ * local disk (a GitHub API, a git blob): probes `<name>.config.<ext>` in
172
+ * extension-priority order through `options.fetch`, returning the first file
173
+ * that exists, or `undefined` when none does. Pass the result to
174
+ * `loadConfigFromContent` to execute it exactly as a local file would be.
115
175
  */
116
- declare function loadConfigFromContent<T>(opts: LoadConfigFromContentOptions): Promise<Loaded<T>>;
117
- //#endregion
118
- //#region src/merge.d.ts
176
+ export declare function readConfigSource(options: ReadConfigSourceOptions): Promise<ConfigSource | undefined>;
177
+ /** Options for the temporary directory a config is loaded in. */
178
+ interface ConfigSandboxOptions {
179
+ /**
180
+ * A real `node_modules` directory to make visible from the sandbox. A config
181
+ * that does `import { defineConfig } from "@theholocron/cli"` only resolves
182
+ * if the directory it sits in has that package reachable by Node's upward
183
+ * `node_modules` search, so the sandbox gets a symlink to this one (not a
184
+ * copy — nothing is duplicated).
185
+ */
186
+ nodeModules: string;
187
+ /** Where to create the sandbox. Defaults to the OS temp dir. */
188
+ root?: string;
189
+ /** Prefix for the sandbox directory's name. */
190
+ prefix?: string;
191
+ }
119
192
  /**
120
- * Deep-merge two config objects, `vite`-style:
193
+ * Runs `run` with a throwaway directory prepared for
194
+ * {@link loadConfigFromContent}'s `dir`, and removes it afterwards (also when
195
+ * `run` throws).
196
+ *
197
+ * The directory is made for a TS/JS config that imports packages:
121
198
  *
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`
199
+ * - `node_modules` is a symlink to `options.nodeModules`, so those imports
200
+ * resolve as if the config sat next to that directory.
201
+ * - A `package.json` of `{"type":"module"}` is written into it. Node decides
202
+ * whether a `.ts`/`.js` file is ESM or CommonJS from the nearest ancestor
203
+ * `package.json`'s `type`, defaulting to CommonJS — and `tsx`'s loader,
204
+ * correctly honouring that, would then `require()` a pure-ESM dependency
205
+ * such as `@theholocron/cli`'s `dist/index.mjs`, which Node rejects outright
206
+ * ("require() of ES Module … not supported").
126
207
  *
127
- * Neither input is mutated.
208
+ * The directory lives under the OS temp dir by default rather than inside any
209
+ * package: read-only deployments (Vercel's Node.js Functions ship the bundle
210
+ * read-only under `/var/task`) can't create a directory there.
128
211
  */
129
- declare function mergeConfig<T>(base: T, override: unknown): T;
130
- //#endregion
131
- export { ConfigFileError, DEFAULT_EXTENSIONS, type LayeredResult, type LoadConfigFileOptions, type LoadConfigFromContentOptions, type LoadLayeredOptions, type Loaded, createDefineConfig, loadConfigFile, loadConfigFromContent, loadLayered, mergeConfig };
212
+ export declare function withConfigSandbox<R>(options: ConfigSandboxOptions, run: (dir: string) => Promise<R>): Promise<R>;
213
+ export { type ConfigSandboxOptions, type ConfigSource, type LayeredResult, type LoadConfigFileOptions, type LoadConfigFromContentOptions, type LoadLayeredOptions, type Loaded, type ReadConfigSourceOptions, mergeConfig };
package/dist/index.mjs CHANGED
@@ -1,7 +1,20 @@
1
- import { readFile, stat, writeFile } from "node:fs/promises";
1
+ import { findUpward, hasGitEntry } from "@theholocron/fs-utils";
2
2
  import { join } from "node:path";
3
+ import { mkdir, mkdtemp, readFile, rm, stat, symlink, writeFile } from "node:fs/promises";
3
4
  import { pathToFileURL } from "node:url";
4
- //#region src/define.ts
5
+ import { errorMessage } from "@theholocron/misc-utils";
6
+ import { deepMerge, deepMerge as mergeConfig } from "@theholocron/object-utils";
7
+ import { tmpdir } from "node:os";
8
+ // src/default-extensions/default-extensions.ts
9
+ /** Default extension probe order, highest priority first. */
10
+ const DEFAULT_EXTENSIONS = [
11
+ "ts",
12
+ "js",
13
+ "mjs",
14
+ "cjs",
15
+ "json"
16
+ ];
17
+ // src/define/define.ts
5
18
  /**
6
19
  * Build a typed identity `defineConfig` for a specific config shape.
7
20
  *
@@ -17,8 +30,7 @@ import { pathToFileURL } from "node:url";
17
30
  function createDefineConfig() {
18
31
  return (config) => config;
19
32
  }
20
- //#endregion
21
- //#region src/errors.ts
33
+ // src/errors/errors.ts
22
34
  /**
23
35
  * Thrown when a config file is found but cannot be loaded — malformed
24
36
  * JSON, a syntax error in a `.ts` / `.js` module, or no usable default
@@ -27,108 +39,132 @@ function createDefineConfig() {
27
39
  */
28
40
  var ConfigFileError = class extends Error {
29
41
  filepath;
42
+ /** The error's name, `"ConfigFileError"`. */
30
43
  name = "ConfigFileError";
31
44
  constructor(message, filepath) {
32
45
  super(message);
33
46
  this.filepath = filepath;
34
47
  }
35
48
  };
36
- //#endregion
37
- //#region src/merge.ts
49
+ // src/is-file/is-file.ts
50
+ async function isFile(path) {
51
+ try {
52
+ return (await stat(path)).isFile();
53
+ } catch {
54
+ return false;
55
+ }
56
+ }
57
+ // src/load-file/load-file.ts
38
58
  /**
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.
59
+ * The actual file-loading mechanics `load.ts`'s exported functions share:
60
+ * JSON parsing, dynamic `import()` (TS via `tsx`'s persistent ESM loader,
61
+ * JS/MJS/CJS natively), and unwrapping the CJS/ESM default-export
62
+ * double-wrap `tsx`'s transform produces. Kept separate from `load.ts`'s
63
+ * own orchestration (which directory, which extension order, upward
64
+ * search) — this file only knows "given one exact filepath and
65
+ * extension, load it," always throwing {@link ConfigFileError} on failure.
47
66
  */
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;
67
+ async function loadFile(filepath, ext) {
68
+ if (ext === "json") return loadJson(filepath);
69
+ return extractDefault(filepath, await importModule(filepath, ext));
70
+ }
71
+ async function loadJson(filepath) {
72
+ const text = await readFile(filepath, "utf8");
73
+ try {
74
+ return JSON.parse(text);
75
+ } catch (err) {
76
+ throw new ConfigFileError(`${filepath} is not valid JSON: ${errorMessage(err)}`, filepath);
57
77
  }
58
- return out;
59
78
  }
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;
79
+ let tsRegistered;
80
+ async function registerTsx() {
81
+ const { register } = await import("tsx/esm/api");
82
+ register();
64
83
  }
65
- //#endregion
66
- //#region src/load.ts
67
84
  /**
68
- * Discover and load `<name>.config.*` files, or load one from content that
69
- * didn't come from a file at all ({@link loadConfigFromContent}).
70
- * Holocron-agnostic — no schema, no validation, no defaults. Consumers
71
- * layer those on top.
72
- *
73
- * Probe order is **TS-first**: `.ts` → `.js` → `.mjs` → `.cjs` → `.json`.
74
- * TS is loaded through `tsx`'s `tsImport` (a runtime dependency) so a
75
- * typed `defineConfig` file works with no build step.
85
+ * Import `filepath`. For `.ts`, `tsx`'s ESM loader is registered first, once
86
+ * per process (lazily — only when a `.ts` file is actually loaded).
87
+ * `register()` is used over `tsImport()` because a single run may load
88
+ * several TS files (`loadLayered` reads a dedicated file *and* a parent
89
+ * file) and `tsImport`'s one-off register/unregister cycle is not reentrant.
76
90
  */
77
- /** Default extension probe order, highest priority first. */
78
- const DEFAULT_EXTENSIONS = [
79
- "ts",
80
- "js",
81
- "mjs",
82
- "cjs",
83
- "json"
84
- ];
91
+ async function importModule(filepath, ext) {
92
+ if (ext === "ts") {
93
+ tsRegistered ??= registerTsx();
94
+ await tsRegistered;
95
+ }
96
+ try {
97
+ return await import(pathToFileURL(filepath).href);
98
+ } catch (err) {
99
+ throw new ConfigFileError(`could not load ${filepath}: ${errorMessage(err)}`, filepath);
100
+ }
101
+ }
85
102
  /**
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.
103
+ * Unwrap `export default`. `tsx` CJS-transforms `export default x` into
104
+ * `exports.default = x`, which dynamic import wraps as
105
+ * `{ default: { __esModule: true, default: x } }` — strip the extra layer
106
+ * when present so ESM and CJS outputs both resolve.
89
107
  */
90
- async function loadConfigFile(opts) {
91
- const extensions = opts.extensions ?? DEFAULT_EXTENSIONS;
108
+ function extractDefault(filepath, mod) {
109
+ const outer = mod.default;
110
+ const raw = outer?.__esModule === true ? outer.default : outer;
111
+ if (raw === void 0 || raw === null) throw new ConfigFileError(`${filepath} must have a default export (use \`export default defineConfig({…})\`)`, filepath);
112
+ return raw;
113
+ }
114
+ // src/probe-extensions/probe-extensions.ts
115
+ /**
116
+ * Probe `dir` for `<name>.config.<ext>` in extension-priority order,
117
+ * loading and returning the first match. The one piece of per-directory
118
+ * orchestration `loadConfigFile` needs on both its non-walking and
119
+ * walking paths — pulled out so it can be unit-tested directly instead of
120
+ * only through `loadConfigFile`'s full probe/walk behavior.
121
+ */
122
+ async function probeExtensions(dir, name, extensions) {
92
123
  for (const ext of extensions) {
93
- const filepath = join(opts.cwd, `${opts.name}.config.${ext}`);
124
+ const filepath = join(dir, `${name}.config.${ext}`);
94
125
  if (!await isFile(filepath)) continue;
95
126
  return {
96
127
  config: await loadFile(filepath, ext),
97
128
  filepath
98
129
  };
99
130
  }
100
- return null;
101
131
  }
132
+ // src/load-config-file/load-config-file.ts
102
133
  /**
103
- * `<name>.config.*` layered over the `[fallback.key]` of
104
- * `<fallback.file>.config.*`. Either, both, or neither may be present;
105
- * the dedicated file wins on conflict (vitest-over-vite). Returns `null`
106
- * when neither source resolves.
134
+ * Discover and load `<name>.config.*` files, or load one from content that
135
+ * didn't come from a file at all ({@link loadConfigFromContent}).
136
+ * Holocron-agnostic — no schema, no validation, no defaults. Consumers
137
+ * layer those on top.
138
+ *
139
+ * Probe order is **TS-first**: `.ts` → `.js` → `.mjs` → `.cjs` → `.json`.
140
+ * TS is loaded through `tsx`'s `tsImport` (a runtime dependency) so a
141
+ * typed `defineConfig` file works with no build step.
142
+ *
143
+ * `walkUp` (off by default) adds the "nearest config" search
144
+ * cosmiconfig/postcss/stylelint/ESLint's flat config all do: when `cwd`
145
+ * itself has no match, check its parent, then its parent's parent, and so
146
+ * on — stopping at the first directory containing a `.git` entry (checked
147
+ * after that directory's own config probe, so the project root itself is
148
+ * still searched) or the filesystem root. Never wanders past a repo
149
+ * boundary into an unrelated enclosing directory. Built on
150
+ * `@theholocron/fs-utils`'s `findUpward`/`hasGitEntry` — the same
151
+ * upward-walk shape `@theholocron/sentinel`'s own `findPackageRoot` needs,
152
+ * only with a different predicate.
107
153
  */
108
- async function loadLayered(opts) {
109
- const dedicated = await loadConfigFile(opts);
110
- let base;
111
- let baseFile = null;
112
- if (opts.fallback) {
113
- const parent = await loadConfigFile({
114
- cwd: opts.cwd,
115
- name: opts.fallback.file,
116
- extensions: opts.extensions
117
- });
118
- if (parent && parent.config[opts.fallback.key] !== void 0) {
119
- base = parent.config[opts.fallback.key];
120
- baseFile = parent.filepath;
121
- }
122
- }
123
- if (!dedicated && base === void 0) return null;
124
- const config = mergeConfig(base, dedicated?.config);
125
- const sources = [baseFile, dedicated?.filepath ?? null].filter((s) => s !== null);
126
- return {
127
- config,
128
- filepath: dedicated?.filepath ?? baseFile,
129
- sources
130
- };
154
+ /**
155
+ * Load the first `<name>.config.<ext>` found starting at `cwd` — just
156
+ * `cwd` itself by default, or walking up through ancestor directories when
157
+ * `walkUp` is set (see the module doc comment for the stop conditions).
158
+ * Returns `null` when none is present anywhere searched; throws
159
+ * {@link ConfigFileError} when a file exists but cannot be loaded.
160
+ */
161
+ async function loadConfigFile(opts) {
162
+ const extensions = opts.extensions ?? DEFAULT_EXTENSIONS;
163
+ const checkDir = (dir) => probeExtensions(dir, opts.name, extensions);
164
+ if (!opts.walkUp) return await checkDir(opts.cwd) ?? null;
165
+ return await findUpward(opts.cwd, checkDir, hasGitEntry) ?? null;
131
166
  }
167
+ // src/load-config-from-content/load-config-from-content.ts
132
168
  /**
133
169
  * Load config from content that didn't come from a file already on disk —
134
170
  * writes it to `<dir>/<name>.config.<extension>` first, then loads it
@@ -147,65 +183,115 @@ async function loadConfigFromContent(opts) {
147
183
  filepath
148
184
  };
149
185
  }
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));
186
+ // src/merge-layers/merge-layers.ts
187
+ /**
188
+ * Deep-merges config layers, lowest priority first (a later layer wins on
189
+ * scalars; arrays concatenate; nested objects merge). `undefined` layers are
190
+ * skipped. Returns `undefined` when there is no layer to merge. The result is
191
+ * a copy for object layers — it never aliases a layer.
192
+ *
193
+ * The one merge `loadLayered` and every caller layering configs it loaded
194
+ * some other way (content from an API, say) use, so layering means the same
195
+ * thing everywhere.
196
+ */
197
+ function mergeLayers(layers) {
198
+ const present = layers.filter((layer) => layer !== void 0);
199
+ if (present.length === 0) return void 0;
200
+ return present.reduce((acc, layer) => deepMerge(acc, layer), {});
153
201
  }
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);
202
+ // src/load-layered/load-layered.ts
203
+ /**
204
+ * `<name>.config.*` layered over the `[fallback.key]` of
205
+ * `<fallback.file>.config.*`. Either, both, or neither may be present;
206
+ * the dedicated file wins on conflict (vitest-over-vite). Returns `null`
207
+ * when neither source resolves.
208
+ */
209
+ async function loadLayered(opts) {
210
+ const coerce = opts.coerce ?? ((raw) => raw);
211
+ const dedicated = await loadConfigFile(opts);
212
+ let top;
213
+ let topFile = null;
214
+ if (dedicated) {
215
+ top = coerce(dedicated.config);
216
+ if (top !== void 0) topFile = dedicated.filepath;
160
217
  }
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);
218
+ let base;
219
+ let baseFile = null;
220
+ if (opts.fallback) {
221
+ const parent = opts.fallback.preloaded !== void 0 ? opts.fallback.preloaded : await loadConfigFile({
222
+ cwd: opts.cwd,
223
+ name: opts.fallback.file,
224
+ extensions: opts.extensions,
225
+ walkUp: opts.walkUp
226
+ });
227
+ const raw = (parent?.config)?.[opts.fallback.key];
228
+ if (parent && raw !== void 0) {
229
+ base = coerce(raw);
230
+ if (base !== void 0) baseFile = parent.filepath;
231
+ }
167
232
  }
233
+ const config = mergeLayers([base, top]);
234
+ if (config === void 0) return null;
235
+ const sources = [baseFile, topFile].filter((s) => s !== null);
236
+ return {
237
+ config,
238
+ filepath: topFile ?? baseFile,
239
+ sources
240
+ };
168
241
  }
169
- let tsRegistered;
170
- async function registerTsx() {
171
- const { register } = await import("tsx/esm/api");
172
- register();
173
- }
242
+ // src/read-config-source/read-config-source.ts
174
243
  /**
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.
244
+ * {@link probeExtensions} for a config that lives somewhere other than the
245
+ * local disk (a GitHub API, a git blob): probes `<name>.config.<ext>` in
246
+ * extension-priority order through `options.fetch`, returning the first file
247
+ * that exists, or `undefined` when none does. Pass the result to
248
+ * `loadConfigFromContent` to execute it exactly as a local file would be.
180
249
  */
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);
250
+ async function readConfigSource(options) {
251
+ for (const extension of options.extensions ?? DEFAULT_EXTENSIONS) {
252
+ const path = `${options.name}.config.${extension}`;
253
+ const content = await options.fetch(path);
254
+ if (content !== void 0) return {
255
+ path,
256
+ extension,
257
+ content
258
+ };
188
259
  }
189
260
  }
261
+ // src/with-config-sandbox/with-config-sandbox.ts
190
262
  /**
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.
263
+ * Runs `run` with a throwaway directory prepared for
264
+ * {@link loadConfigFromContent}'s `dir`, and removes it afterwards (also when
265
+ * `run` throws).
266
+ *
267
+ * The directory is made for a TS/JS config that imports packages:
268
+ *
269
+ * - `node_modules` is a symlink to `options.nodeModules`, so those imports
270
+ * resolve as if the config sat next to that directory.
271
+ * - A `package.json` of `{"type":"module"}` is written into it. Node decides
272
+ * whether a `.ts`/`.js` file is ESM or CommonJS from the nearest ancestor
273
+ * `package.json`'s `type`, defaulting to CommonJS — and `tsx`'s loader,
274
+ * correctly honouring that, would then `require()` a pure-ESM dependency
275
+ * such as `@theholocron/cli`'s `dist/index.mjs`, which Node rejects outright
276
+ * ("require() of ES Module … not supported").
277
+ *
278
+ * The directory lives under the OS temp dir by default rather than inside any
279
+ * package: read-only deployments (Vercel's Node.js Functions ship the bundle
280
+ * read-only under `/var/task`) can't create a directory there.
195
281
  */
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) {
282
+ async function withConfigSandbox(options, run) {
283
+ const root = options.root ?? tmpdir();
284
+ await mkdir(root, { recursive: true });
285
+ const dir = await mkdtemp(join(root, options.prefix ?? "datapad-"));
203
286
  try {
204
- return (await stat(path)).isFile();
205
- } catch {
206
- return false;
287
+ await symlink(options.nodeModules, join(dir, "node_modules"), "dir");
288
+ await writeFile(join(dir, "package.json"), JSON.stringify({ type: "module" }), "utf8");
289
+ return await run(dir);
290
+ } finally {
291
+ await rm(dir, {
292
+ recursive: true,
293
+ force: true
294
+ });
207
295
  }
208
296
  }
209
- const message = (err) => err instanceof Error ? err.message : String(err);
210
- //#endregion
211
- export { ConfigFileError, DEFAULT_EXTENSIONS, createDefineConfig, loadConfigFile, loadConfigFromContent, loadLayered, mergeConfig };
297
+ export { ConfigFileError, DEFAULT_EXTENSIONS, createDefineConfig, loadConfigFile, loadConfigFromContent, loadLayered, mergeConfig, mergeLayers, readConfigSource, withConfigSandbox };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theholocron/datapad",
3
- "version": "5.0.0-alpha.28",
3
+ "version": "5.0.0-alpha.281",
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",
@@ -10,12 +10,12 @@
10
10
  "theholocron",
11
11
  "typescript"
12
12
  ],
13
- "homepage": "https://github.com/theholocron/holocron/tree/main/packages/datapad#readme",
13
+ "homepage": "https://docs.theholocron.dev/holocron/datapad/",
14
14
  "bugs": "https://github.com/theholocron/holocron/issues",
15
15
  "repository": {
16
16
  "type": "git",
17
17
  "url": "git+https://github.com/theholocron/holocron.git",
18
- "directory": "packages/datapad"
18
+ "directory": "cli/datapad"
19
19
  },
20
20
  "license": "MIT",
21
21
  "author": "Newton Koumantzelis",
@@ -32,22 +32,25 @@
32
32
  "dist"
33
33
  ],
34
34
  "dependencies": {
35
- "tsx": "4.23.12"
35
+ "tsx": "4.23.15",
36
+ "@theholocron/misc-utils": "^1.16.1-alpha.3",
37
+ "@theholocron/fs-utils": "^1.16.1-alpha.3",
38
+ "@theholocron/object-utils": "^1.16.1-alpha.3"
36
39
  },
37
40
  "devDependencies": {
38
- "@theholocron/eslint-config": "^8.0.0",
39
- "@theholocron/tsconfig": "^8.0.0",
40
- "@theholocron/tsdown-config": "^8.0.0",
41
- "@theholocron/vitest-config": "^8.0.0",
42
41
  "@types/node": "^26",
43
- "@vitest/coverage-v8": "^4.1.11",
42
+ "@vitest/coverage-v8": "^5.0.5",
44
43
  "@vitest/eslint-plugin": "^1.6.27",
45
44
  "eslint": "^10.8.1",
46
45
  "eslint-plugin-n": "^18.3.0",
47
46
  "globals": "^17.11.0",
48
- "tsdown": "^0.22.14",
47
+ "tsdown": "^0.23.3",
49
48
  "typescript": "^5.9.3",
50
- "vitest": "^4.1.11"
49
+ "vitest": "^5.0.5",
50
+ "@theholocron/eslint-config": "^8.9.0-alpha.5",
51
+ "@theholocron/tsconfig": "^8.9.0-alpha.5",
52
+ "@theholocron/tsdown-config": "^8.9.0-alpha.5",
53
+ "@theholocron/vitest-config": "^8.9.0-alpha.5"
51
54
  },
52
55
  "engines": {
53
56
  "node": ">=22"