@theholocron/datapad 5.0.0-alpha.25 → 5.0.0-alpha.250

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