@theholocron/datapad 5.0.0-alpha.37 → 5.0.0-alpha.371

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.
Files changed (4) hide show
  1. package/README.md +101 -17
  2. package/dist/index.d.mts +242 -55
  3. package/dist/index.mjs +314 -124
  4. package/package.json +22 -19
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,64 @@ 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
+ ### `loadConfigDir<T>({ cwd, dir, areas, extensions? })`
91
+
92
+ Loads the area files of a config directory (`.holocron/notifications.ts`,
93
+ `.holocron/repo.json`, ...) the way `loadConfigFile` loads a config. For each
94
+ name in the closed list `areas`, the first of `<cwd>/<dir>/<area>.{ts,js,mjs,cjs,json}`
95
+ that exists is loaded (`.ts` wins over `.json` when both are there). Returns
96
+ `{ area, path, extension, filepath, value }[]`, one entry per area that has a
97
+ file; a missing directory returns `[]`. A file that cannot be loaded throws
98
+ `ConfigFileError`. Files not named in `areas` are never read. The directory name
99
+ and the area names are parameters: datapad does not know what an area means, and
100
+ an area file may `import` a sibling in the directory.
101
+
102
+ ### `readConfigDirSource({ dir, areas, fetch, extensions? })`
103
+
104
+ `loadConfigDir`'s probe for a directory that lives somewhere other than the local
105
+ disk. Asks `fetch("<dir>/<area>.<ext>")` in extension-priority order for each
106
+ area and returns `{ area, path, extension, content }[]` for the areas found.
107
+ It reads only the named areas; a caller that lists the whole directory and
108
+ fetches every file passes that tree to `writeConfigDir` instead.
109
+
110
+ ### `writeConfigDir({ dir, files })`
111
+
112
+ The sandbox writer: writes a tree of fetched files (`{ path, content }`, `path`
113
+ relative to `dir`, e.g. `.holocron/notifications.ts` or `.holocron/lib/x.ts`)
114
+ into the sandbox beside the config, creating sub-directories and keeping the
115
+ relative paths, so `loadConfigDir({ cwd: dir, ... })` finds them and an area that
116
+ imports a sibling resolves it. Returns the absolute paths written. A path that is
117
+ absolute or leaves `dir` throws `ConfigFileError` before anything is written.
118
+
119
+ ```ts
120
+ await withConfigSandbox({ nodeModules }, async (dir) => {
121
+ const { extension, content } = (await readConfigSource({ name: "holocron", fetch }))!;
122
+ await loadConfigFromContent({ dir, name: "holocron", extension, content });
123
+ await writeConfigDir({ dir, files: [{ path: ".holocron/notifications.ts", content: "export default {}" }] });
124
+ const areas = await loadConfigDir({ cwd: dir, dir: ".holocron", areas: ["notifications", "repo"] });
125
+ });
126
+ ```
127
+
128
+ ### `withConfigSandbox({ nodeModules, root?, prefix? }, run)`
129
+
130
+ Runs `run(dir)` with a throwaway directory ready to be
131
+ `loadConfigFromContent`'s `dir`: `node_modules` symlinked to
132
+ `options.nodeModules` (so the config's package imports resolve) and a
133
+ `{"type":"module"}` `package.json` (so `tsx` doesn't default the files to
134
+ CommonJS and `require()` a pure-ESM dependency). Created under the OS temp dir
135
+ by default — read-only deployments can't write inside a package — and removed
136
+ afterwards, also when `run` throws.
137
+
138
+ ### `loadLayered<T>({ cwd, name, fallback?, extensions?, walkUp?, coerce? })`
71
139
 
72
140
  `<name>.config.*` layered over the `[fallback.key]` of
73
141
  `<fallback.file>.config.*`. Either, both, or neither may be present; the
@@ -75,11 +143,27 @@ dedicated file wins on conflict (`vitest`-over-`vite`). Returns
75
143
  `{ config, filepath, sources } | null` — `sources` lists the absolute
76
144
  paths actually merged, lowest priority first.
77
145
 
146
+ - `fallback.preloaded` — the `<fallback.file>.config.*` the caller has
147
+ already loaded (`null`: looked for, not there), used as is instead of loading
148
+ it again.
149
+ - `coerce(raw)` — turns each layer's raw value into the shape being merged
150
+ before the merge (a bare array standing for `{ tasks: [...] }`, say);
151
+ returning `undefined` treats the layer as absent.
152
+
153
+ ### `mergeLayers<T>(layers)`
154
+
155
+ The merge `loadLayered` uses, for layers loaded some other way: deep-merges
156
+ `layers` lowest priority first, skipping `undefined`, and returns a copy — or
157
+ `undefined` when there is nothing to merge.
158
+
78
159
  ### `mergeConfig<T>(base, override)`
79
160
 
80
161
  Deep-merge, `vite`-style: plain objects merge recursively, arrays
81
162
  concatenate (`base` first), `undefined` in `override` is skipped, every
82
- other `override` value replaces `base`. Neither input is mutated.
163
+ other `override` value replaces `base`. Neither input is mutated. A
164
+ re-export of `@theholocron/object-utils`'s `deepMerge` under this
165
+ package's established name — the merge logic itself has no awareness of
166
+ configs at all, so it lives there instead of being duplicated here.
83
167
 
84
168
  ### `createDefineConfig<T>()`
85
169
 
@@ -100,12 +184,12 @@ reads a dedicated file _and_ a parent file), so the persistent
100
184
 
101
185
  ## Development
102
186
 
103
- | Script | Description |
104
- | --------------------------------------- | ------------------------------------------- |
105
- | `pnpm run delivery.build` | Bundle with tsdown |
106
- | `pnpm run verification.unitTests` | Run the vitest suite (always with coverage) |
107
- | `pnpm run verification.typeSafety` | `tsc --noEmit` |
108
- | `pnpm run sourceQuality.staticAnalysis` | ESLint |
187
+ | Script | Description |
188
+ | -------------------- | ------------------------------------------- |
189
+ | `pnpm run build` | Bundle with tsdown |
190
+ | `pnpm run test:unit` | Run the vitest suite (always with coverage) |
191
+ | `pnpm run typecheck` | `tsc --noEmit` |
192
+ | `pnpm run lint:code` | ESLint |
109
193
 
110
194
  ## Releases
111
195
 
@@ -113,4 +197,4 @@ Automated via semantic-release. See [CHANGELOG.md](../../CHANGELOG.md).
113
197
 
114
198
  ## Documentation
115
199
 
116
- <https://theholocron.github.io/holocron/>
200
+ <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,160 @@
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
32
+ /** One area file loaded from a config directory. */
33
+ interface ConfigDirArea<T = unknown> {
34
+ /** The area's name, as passed in `areas`. */
35
+ area: string;
36
+ /** The file path relative to `cwd`, with `/` separators: `.holocron/notifications.ts`. */
37
+ path: string;
38
+ /** Which extension matched. */
39
+ extension: string;
40
+ /** Absolute path of the file. */
41
+ filepath: string;
42
+ /** The file's default export (`.ts`, `.js`, `.mjs`, `.cjs`) or its parsed content (`.json`). */
43
+ value: T;
44
+ /**
45
+ * The same area read from the repository root's directory, when this one is the config's own and the root has a
46
+ * file for it too. Only areas named in `shared` are looked up there. Absent when the root has no such file.
47
+ */
48
+ root?: ConfigDirArea<T>;
49
+ }
50
+ /** Options for loading the area files of a config directory from disk. */
51
+ interface LoadConfigDirOptions {
52
+ /** The directory holding `dir` — normally the one the config file was found in. */
53
+ cwd: string;
54
+ /** The directory the areas live in, relative to `cwd`: `".holocron"`. */
55
+ dir: string;
56
+ /** The closed list of area names to look for. Files not named here are never read. */
57
+ areas: readonly string[];
58
+ /**
59
+ * Area names that are also read from the repository root's `dir` (the nearest ancestor of `cwd` with a `.git`
60
+ * entry, `cwd` itself first). A shared area with a file in both places comes back as the one in `cwd` with the
61
+ * root's as `root`; one that only the root has comes back as the root's file, its `path` relative to `cwd`. The
62
+ * caller decides how the two combine. When `cwd` is the root there is nothing to inherit.
63
+ */
64
+ shared?: readonly string[];
65
+ /** Override the extension probe order. */
66
+ extensions?: readonly string[];
67
+ }
33
68
  /**
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.
69
+ * Load the area files of a config directory: for each name in `options.areas`, the first of
70
+ * `<cwd>/<dir>/<area>.{ts,js,mjs,cjs,json}` that exists, loaded the way {@link loadConfigFile} loads a config. Areas
71
+ * with no file are left out, so a missing directory returns `[]`. When one area has files in two formats, the
72
+ * extension priority picks one (`.ts` over `.json`). Throws {@link ConfigFileError} when a file exists but cannot be
73
+ * loaded. Holocron-agnostic: the directory and the area names are parameters, and what an area means is the caller's.
38
74
  *
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.
75
+ * Areas named in `options.shared` are also looked up in the repository root's directory (see
76
+ * {@link LoadConfigDirOptions.shared}), so a config in a subdirectory can inherit what the repo declares once.
42
77
  */
43
- /** Default extension probe order, highest priority first. */
44
- declare const DEFAULT_EXTENSIONS: readonly ["ts", "js", "mjs", "cjs", "json"];
78
+ export declare function loadConfigDir<T = unknown>(options: LoadConfigDirOptions): Promise<ConfigDirArea<T>[]>;
79
+ /** Options for finding and loading a config file from disk. */
45
80
  interface LoadConfigFileOptions {
46
- /** Directory to look in. */
81
+ /** Directory to start looking in. */
47
82
  cwd: string;
48
83
  /** Base name — `"holocron"` resolves `holocron.config.{ts,js,mjs,cjs,json}`. */
49
84
  name: string;
50
85
  /** Override the extension probe order. */
51
86
  extensions?: readonly string[];
87
+ /**
88
+ * Walk upward through ancestor directories when `cwd` itself has no
89
+ * match, stopping at the first directory containing a `.git` entry (that
90
+ * directory is still searched before stopping) or the filesystem root.
91
+ * Off by default — exact-`cwd`-only, unchanged behavior for any existing
92
+ * caller that doesn't pass this.
93
+ */
94
+ walkUp?: boolean;
52
95
  }
96
+ /** A config value together with the file it was loaded from. */
53
97
  interface Loaded<T> {
98
+ /** The loaded config value. */
54
99
  config: T;
55
100
  /** Absolute path of the file the value came from. */
56
101
  filepath: string;
57
102
  }
58
103
  /**
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.
104
+ * Load the first `<name>.config.<ext>` found starting at `cwd` — just
105
+ * `cwd` itself by default, or walking up through ancestor directories when
106
+ * `walkUp` is set (see the module doc comment for the stop conditions).
107
+ * Returns `null` when none is present anywhere searched; throws
108
+ * {@link ConfigFileError} when a file exists but cannot be loaded.
62
109
  */
63
- declare function loadConfigFile<T>(opts: LoadConfigFileOptions): Promise<Loaded<T> | null>;
64
- interface LoadLayeredOptions extends LoadConfigFileOptions {
110
+ export declare function loadConfigFile<T>(opts: LoadConfigFileOptions): Promise<Loaded<T> | null>;
111
+ /** Options for loading a config from raw content rather than a file already on disk. */
112
+ interface LoadConfigFromContentOptions {
113
+ /**
114
+ * Directory to write `<name>.config.<extension>` into before loading —
115
+ * this is what upward `node_modules` resolution sees, so a config that
116
+ * does `import { defineConfig } from "@theholocron/cli"` only resolves
117
+ * if `dir` sits under a tree where that package is a real dependency.
118
+ * Callers own creating and cleaning up `dir` — this function only
119
+ * writes the one file into it.
120
+ */
121
+ dir: string;
122
+ /** Raw file content — not necessarily sourced from a local file at all (a network fetch, a git blob, …). */
123
+ content: string;
124
+ /** Base name — `"holocron"` writes `holocron.config.<extension>`. */
125
+ name: string;
126
+ /** Which of `DEFAULT_EXTENSIONS` `content` is — determines how it's interpreted (ts/js/mjs/cjs parsed as a module, json as `JSON.parse`). */
127
+ extension: string;
128
+ }
129
+ /**
130
+ * Load config from content that didn't come from a file already on disk —
131
+ * writes it to `<dir>/<name>.config.<extension>` first, then loads it
132
+ * through the exact same path {@link loadConfigFile} uses for a file it
133
+ * discovered itself. Exists because sourcing config content from somewhere
134
+ * other than the local filesystem (a GitHub API fetch, for one — see
135
+ * `@theholocron/sentinel`) doesn't change what loading it correctly means:
136
+ * a `.ts` config still needs real module resolution, `defineConfig` import
137
+ * included, not a re-implemented parser.
138
+ */
139
+ export declare function loadConfigFromContent<T>(opts: LoadConfigFromContentOptions): Promise<Loaded<T>>;
140
+ /** Options for loading a dedicated config file layered over a fallback file's key. */
141
+ interface LoadLayeredOptions<T = unknown> extends LoadConfigFileOptions {
65
142
  /**
66
143
  * When no dedicated `<name>.config.*` exists — or in addition to it —
67
144
  * read `<file>.config.*` and take its `[key]`. The dedicated file (if
68
145
  * any) is merged on top.
69
146
  */
70
147
  fallback?: {
148
+ /** Base name of the fallback file, read as `<file>.config.*`. */
71
149
  file: string;
150
+ /** The key in the fallback file whose value is taken. */
72
151
  key: string;
152
+ /**
153
+ * The `<file>.config.*` already loaded by the caller (`null`: it was
154
+ * looked for and isn't there). Used as is instead of loading it again;
155
+ * leave it `undefined` to have `loadLayered` find and load it.
156
+ */
157
+ preloaded?: Loaded<object> | null;
73
158
  };
159
+ /**
160
+ * Turns each layer's raw value — the dedicated file's default export, and
161
+ * the fallback's `[key]` — into the shape being merged, before the merge.
162
+ * Return `undefined` to treat the layer as absent. For configs that accept
163
+ * shorthand (a bare array standing for `{ tasks: [...] }`).
164
+ */
165
+ coerce?: (raw: unknown) => T | undefined;
74
166
  }
167
+ /** The merged config from `loadLayered`, with where it came from. */
75
168
  interface LayeredResult<T> {
169
+ /** The merged config value. */
76
170
  config: T;
77
171
  /** The dedicated file path if present, else the fallback file path, else `null`. */
78
172
  filepath: string | null;
@@ -85,47 +179,140 @@ interface LayeredResult<T> {
85
179
  * the dedicated file wins on conflict (vitest-over-vite). Returns `null`
86
180
  * when neither source resolves.
87
181
  */
88
- declare function loadLayered<T>(opts: LoadLayeredOptions): Promise<LayeredResult<T> | null>;
89
- interface LoadConfigFromContentOptions {
182
+ export declare function loadLayered<T>(opts: LoadLayeredOptions<T>): Promise<LayeredResult<T> | null>;
183
+ /**
184
+ * Deep-merges config layers, lowest priority first (a later layer wins on
185
+ * scalars; arrays concatenate; nested objects merge). `undefined` layers are
186
+ * skipped. Returns `undefined` when there is no layer to merge. The result is
187
+ * a copy for object layers — it never aliases a layer.
188
+ *
189
+ * The one merge `loadLayered` and every caller layering configs it loaded
190
+ * some other way (content from an API, say) use, so layering means the same
191
+ * thing everywhere.
192
+ */
193
+ export declare function mergeLayers<T>(layers: readonly (T | undefined)[]): T | undefined;
194
+ /** One area file's content fetched from somewhere other than the local disk. */
195
+ interface ConfigDirSource {
196
+ /** The area's name, as passed in `areas` — `"notifications"` for `.holocron/notifications.ts`. */
197
+ area: string;
198
+ /** The file path probed, relative as `fetch` was asked for it, e.g. `.holocron/notifications.ts`. */
199
+ path: string;
200
+ /** Which extension matched. */
201
+ extension: string;
202
+ /** The raw file content. */
203
+ content: string;
204
+ }
205
+ /** Options for fetching the area files of a config directory from a remote source. */
206
+ interface ReadConfigDirSourceOptions {
207
+ /** The directory the areas live in, relative to the config: `".holocron"`. */
208
+ dir: string;
209
+ /** The closed list of area names to look for: `["notifications", "repo"]` probes `<dir>/notifications.*` and `<dir>/repo.*`. */
210
+ areas: readonly string[];
90
211
  /**
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.
212
+ * Fetches one file by relative path (`.holocron/notifications.ts`): its content, or `undefined` when it doesn't
213
+ * exist. Throw for anything else (a network failure, a permission error) — that propagates rather than reading
214
+ * as "absent".
97
215
  */
98
- dir: string;
99
- /** Raw file content — not necessarily sourced from a local file at all (a network fetch, a git blob, …). */
216
+ fetch: (path: string) => Promise<string | undefined>;
217
+ /** Override the extension probe order. */
218
+ extensions?: readonly string[];
219
+ }
220
+ /**
221
+ * {@link readConfigSource} for the area files of a config directory (`.holocron/<area>.<ext>`) that live somewhere
222
+ * other than the local disk: for each name in `options.areas`, probes the extensions in priority order through
223
+ * `options.fetch` and keeps the first file that exists. Areas with no file are left out, so a repo with no
224
+ * directory returns `[]`. Write the result with {@link writeConfigDir} and read it back with {@link loadConfigDir}.
225
+ *
226
+ * This reads only the named areas. A caller that lists the whole directory (and so also gets the files an area
227
+ * imports) passes that tree to {@link writeConfigDir} directly.
228
+ */
229
+ export declare function readConfigDirSource(options: ReadConfigDirSourceOptions): Promise<ConfigDirSource[]>;
230
+ /** A config file's content fetched from somewhere other than the local disk. */
231
+ interface ConfigSource {
232
+ /** The file name probed, e.g. `holocron.config.ts` — relative, as `fetch` was asked for it. */
233
+ path: string;
234
+ /** Which extension matched — what {@link loadConfigFromContent} needs as `extension`. */
235
+ extension: string;
236
+ /** The raw file content. */
100
237
  content: string;
101
- /** Base name — `"holocron"` writes `holocron.config.<extension>`. */
238
+ }
239
+ /** Options for fetching a config file's content from a remote source. */
240
+ interface ReadConfigSourceOptions {
241
+ /** Base name — `"holocron"` probes `holocron.config.{ts,js,mjs,cjs,json}`. */
102
242
  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;
243
+ /**
244
+ * Fetches one file by relative path (`holocron.config.ts`): its content, or
245
+ * `undefined` when it doesn't exist. Throw for anything else (a network
246
+ * failure, a permission error) — that propagates rather than reading as "absent".
247
+ */
248
+ fetch: (path: string) => Promise<string | undefined>;
249
+ /** Override the extension probe order. */
250
+ extensions?: readonly string[];
105
251
  }
106
252
  /**
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.
253
+ * {@link probeExtensions} for a config that lives somewhere other than the
254
+ * local disk (a GitHub API, a git blob): probes `<name>.config.<ext>` in
255
+ * extension-priority order through `options.fetch`, returning the first file
256
+ * that exists, or `undefined` when none does. Pass the result to
257
+ * `loadConfigFromContent` to execute it exactly as a local file would be.
115
258
  */
116
- declare function loadConfigFromContent<T>(opts: LoadConfigFromContentOptions): Promise<Loaded<T>>;
117
- //#endregion
118
- //#region src/merge.d.ts
259
+ export declare function readConfigSource(options: ReadConfigSourceOptions): Promise<ConfigSource | undefined>;
260
+ /** Options for the temporary directory a config is loaded in. */
261
+ interface ConfigSandboxOptions {
262
+ /**
263
+ * A real `node_modules` directory to make visible from the sandbox. A config
264
+ * that does `import { defineConfig } from "@theholocron/cli"` only resolves
265
+ * if the directory it sits in has that package reachable by Node's upward
266
+ * `node_modules` search, so the sandbox gets a symlink to this one (not a
267
+ * copy — nothing is duplicated).
268
+ */
269
+ nodeModules: string;
270
+ /** Where to create the sandbox. Defaults to the OS temp dir. */
271
+ root?: string;
272
+ /** Prefix for the sandbox directory's name. */
273
+ prefix?: string;
274
+ }
119
275
  /**
120
- * Deep-merge two config objects, `vite`-style:
276
+ * Runs `run` with a throwaway directory prepared for
277
+ * {@link loadConfigFromContent}'s `dir`, and removes it afterwards (also when
278
+ * `run` throws).
279
+ *
280
+ * The directory is made for a TS/JS config that imports packages:
121
281
  *
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`
282
+ * - `node_modules` is a symlink to `options.nodeModules`, so those imports
283
+ * resolve as if the config sat next to that directory.
284
+ * - A `package.json` of `{"type":"module"}` is written into it. Node decides
285
+ * whether a `.ts`/`.js` file is ESM or CommonJS from the nearest ancestor
286
+ * `package.json`'s `type`, defaulting to CommonJS — and `tsx`'s loader,
287
+ * correctly honouring that, would then `require()` a pure-ESM dependency
288
+ * such as `@theholocron/cli`'s `dist/index.mjs`, which Node rejects outright
289
+ * ("require() of ES Module … not supported").
126
290
  *
127
- * Neither input is mutated.
291
+ * The directory lives under the OS temp dir by default rather than inside any
292
+ * package: read-only deployments (Vercel's Node.js Functions ship the bundle
293
+ * read-only under `/var/task`) can't create a directory there.
294
+ */
295
+ export declare function withConfigSandbox<R>(options: ConfigSandboxOptions, run: (dir: string) => Promise<R>): Promise<R>;
296
+ /** One file of a config directory's tree, as fetched from a remote source. */
297
+ interface ConfigDirFile {
298
+ /** Path relative to the sandbox directory, e.g. `.holocron/notifications.ts` or `.holocron/lib/channels.ts`. */
299
+ path: string;
300
+ /** The raw file content. */
301
+ content: string;
302
+ }
303
+ /** Options for writing a fetched config directory beside a config. */
304
+ interface WriteConfigDirOptions {
305
+ /** The sandbox directory (the `dir` given to {@link loadConfigFromContent}); `files` are written under it. */
306
+ dir: string;
307
+ /** The files to write; their relative paths (and so the sub-directories) are kept. */
308
+ files: readonly ConfigDirFile[];
309
+ }
310
+ /**
311
+ * Write the files fetched from a config directory (`.holocron/…`) into the sandbox beside the config, keeping each
312
+ * relative path, so {@link loadConfigDir} finds them and an area file that imports a sibling resolves it. Creates the
313
+ * sub-directories as needed and returns the absolute paths written. Throws {@link ConfigFileError} for a path that is
314
+ * absolute or leaves `dir`, because the paths come from a remote tree and must never write outside the sandbox; it
315
+ * checks every path before it writes any.
128
316
  */
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 };
317
+ export declare function writeConfigDir(options: WriteConfigDirOptions): Promise<string[]>;
318
+ export { type ConfigDirArea, type ConfigDirFile, type ConfigDirSource, type ConfigSandboxOptions, type ConfigSource, type LayeredResult, type LoadConfigDirOptions, type LoadConfigFileOptions, type LoadConfigFromContentOptions, type LoadLayeredOptions, type Loaded, type ReadConfigDirSourceOptions, type ReadConfigSourceOptions, type WriteConfigDirOptions, mergeConfig };
package/dist/index.mjs CHANGED
@@ -1,7 +1,20 @@
1
- import { readFile, stat, writeFile } from "node:fs/promises";
2
- import { join } from "node:path";
1
+ import { findRoot, findUpward, hasGitEntry } from "@theholocron/fs-utils";
2
+ import { dirname, isAbsolute, join, relative, resolve, sep } 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,43 +39,150 @@ 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
58
+ /**
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.
66
+ */
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);
77
+ }
78
+ }
79
+ let tsRegistered;
80
+ async function registerTsx() {
81
+ const { register } = await import("tsx/esm/api");
82
+ register();
83
+ }
84
+ /**
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.
90
+ */
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
+ }
102
+ /**
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.
107
+ */
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/load-config-dir-area/load-config-dir-area.ts
38
115
  /**
39
- * Deep-merge two config objects, `vite`-style:
116
+ * Load one area of a config directory: the first of `<root>/<dir>/<area>.{ts,js,mjs,cjs,json}` that exists, or
117
+ * `undefined` when there is none. `path` on the result is relative to `base` (the directory the caller treats as
118
+ * its own), with `/` separators, so an area read from an ancestor directory comes back as `../../.holocron/org.ts`.
119
+ * Throws {@link ConfigFileError} when the file exists but cannot be loaded.
40
120
  *
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`
121
+ * @param root - The directory holding `dir`.
122
+ * @param base - The directory `path` is relative to; the same as `root` for the caller's own directory.
123
+ * @param dir - The directory the area lives in, relative to `root`: `".holocron"`.
124
+ * @param area - The area's name.
125
+ * @param extensions - The extension probe order. Default {@link DEFAULT_EXTENSIONS}.
126
+ */
127
+ async function loadConfigDirArea(root, base, dir, area, extensions = DEFAULT_EXTENSIONS) {
128
+ for (const extension of extensions) {
129
+ const filepath = join(root, dir, `${area}.${extension}`);
130
+ if (!await isFile(filepath)) continue;
131
+ return {
132
+ area,
133
+ path: relative(base, filepath).split(sep).join("/"),
134
+ extension,
135
+ filepath,
136
+ value: await loadFile(filepath, extension)
137
+ };
138
+ }
139
+ }
140
+ // src/load-config-dir/load-config-dir.ts
141
+ /**
142
+ * Load the area files of a config directory: for each name in `options.areas`, the first of
143
+ * `<cwd>/<dir>/<area>.{ts,js,mjs,cjs,json}` that exists, loaded the way {@link loadConfigFile} loads a config. Areas
144
+ * with no file are left out, so a missing directory returns `[]`. When one area has files in two formats, the
145
+ * extension priority picks one (`.ts` over `.json`). Throws {@link ConfigFileError} when a file exists but cannot be
146
+ * loaded. Holocron-agnostic: the directory and the area names are parameters, and what an area means is the caller's.
45
147
  *
46
- * Neither input is mutated.
47
- */
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;
148
+ * Areas named in `options.shared` are also looked up in the repository root's directory (see
149
+ * {@link LoadConfigDirOptions.shared}), so a config in a subdirectory can inherit what the repo declares once.
150
+ */
151
+ async function loadConfigDir(options) {
152
+ const shared = options.shared ?? [];
153
+ const root = shared.length > 0 ? await findRoot(options.cwd, ".git") : void 0;
154
+ const inheritFrom = root !== void 0 && root !== options.cwd ? root : void 0;
155
+ const areas = [];
156
+ for (const area of options.areas) {
157
+ const own = await loadConfigDirArea(options.cwd, options.cwd, options.dir, area, options.extensions);
158
+ const inherited = inheritFrom !== void 0 && shared.includes(area) ? await loadConfigDirArea(inheritFrom, options.cwd, options.dir, area, options.extensions) : void 0;
159
+ const found = own && inherited ? {
160
+ ...own,
161
+ root: inherited
162
+ } : own ?? inherited;
163
+ if (found) areas.push(found);
57
164
  }
58
- return out;
165
+ return areas;
59
166
  }
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;
167
+ // src/probe-extensions/probe-extensions.ts
168
+ /**
169
+ * Probe `dir` for `<name>.config.<ext>` in extension-priority order,
170
+ * loading and returning the first match. The one piece of per-directory
171
+ * orchestration `loadConfigFile` needs on both its non-walking and
172
+ * walking paths — pulled out so it can be unit-tested directly instead of
173
+ * only through `loadConfigFile`'s full probe/walk behavior.
174
+ */
175
+ async function probeExtensions(dir, name, extensions) {
176
+ for (const ext of extensions) {
177
+ const filepath = join(dir, `${name}.config.${ext}`);
178
+ if (!await isFile(filepath)) continue;
179
+ return {
180
+ config: await loadFile(filepath, ext),
181
+ filepath
182
+ };
183
+ }
64
184
  }
65
- //#endregion
66
- //#region src/load.ts
185
+ // src/load-config-file/load-config-file.ts
67
186
  /**
68
187
  * Discover and load `<name>.config.*` files, or load one from content that
69
188
  * didn't come from a file at all ({@link loadConfigFromContent}).
@@ -73,32 +192,67 @@ function isPlainObject(value) {
73
192
  * Probe order is **TS-first**: `.ts` → `.js` → `.mjs` → `.cjs` → `.json`.
74
193
  * TS is loaded through `tsx`'s `tsImport` (a runtime dependency) so a
75
194
  * typed `defineConfig` file works with no build step.
195
+ *
196
+ * `walkUp` (off by default) adds the "nearest config" search
197
+ * cosmiconfig/postcss/stylelint/ESLint's flat config all do: when `cwd`
198
+ * itself has no match, check its parent, then its parent's parent, and so
199
+ * on — stopping at the first directory containing a `.git` entry (checked
200
+ * after that directory's own config probe, so the project root itself is
201
+ * still searched) or the filesystem root. Never wanders past a repo
202
+ * boundary into an unrelated enclosing directory. Built on
203
+ * `@theholocron/fs-utils`'s `findUpward`/`hasGitEntry` — the same
204
+ * upward-walk shape `@theholocron/sentinel`'s own `findPackageRoot` needs,
205
+ * only with a different predicate.
76
206
  */
77
- /** Default extension probe order, highest priority first. */
78
- const DEFAULT_EXTENSIONS = [
79
- "ts",
80
- "js",
81
- "mjs",
82
- "cjs",
83
- "json"
84
- ];
85
207
  /**
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.
208
+ * Load the first `<name>.config.<ext>` found starting at `cwd` — just
209
+ * `cwd` itself by default, or walking up through ancestor directories when
210
+ * `walkUp` is set (see the module doc comment for the stop conditions).
211
+ * Returns `null` when none is present anywhere searched; throws
212
+ * {@link ConfigFileError} when a file exists but cannot be loaded.
89
213
  */
90
214
  async function loadConfigFile(opts) {
91
215
  const extensions = opts.extensions ?? DEFAULT_EXTENSIONS;
92
- for (const ext of extensions) {
93
- const filepath = join(opts.cwd, `${opts.name}.config.${ext}`);
94
- if (!await isFile(filepath)) continue;
95
- return {
96
- config: await loadFile(filepath, ext),
97
- filepath
98
- };
99
- }
100
- return null;
216
+ const checkDir = (dir) => probeExtensions(dir, opts.name, extensions);
217
+ if (!opts.walkUp) return await checkDir(opts.cwd) ?? null;
218
+ return await findUpward(opts.cwd, checkDir, hasGitEntry) ?? null;
219
+ }
220
+ // src/load-config-from-content/load-config-from-content.ts
221
+ /**
222
+ * Load config from content that didn't come from a file already on disk —
223
+ * writes it to `<dir>/<name>.config.<extension>` first, then loads it
224
+ * through the exact same path {@link loadConfigFile} uses for a file it
225
+ * discovered itself. Exists because sourcing config content from somewhere
226
+ * other than the local filesystem (a GitHub API fetch, for one — see
227
+ * `@theholocron/sentinel`) doesn't change what loading it correctly means:
228
+ * a `.ts` config still needs real module resolution, `defineConfig` import
229
+ * included, not a re-implemented parser.
230
+ */
231
+ async function loadConfigFromContent(opts) {
232
+ const filepath = join(opts.dir, `${opts.name}.config.${opts.extension}`);
233
+ await writeFile(filepath, opts.content, "utf8");
234
+ return {
235
+ config: await loadFile(filepath, opts.extension),
236
+ filepath
237
+ };
238
+ }
239
+ // src/merge-layers/merge-layers.ts
240
+ /**
241
+ * Deep-merges config layers, lowest priority first (a later layer wins on
242
+ * scalars; arrays concatenate; nested objects merge). `undefined` layers are
243
+ * skipped. Returns `undefined` when there is no layer to merge. The result is
244
+ * a copy for object layers — it never aliases a layer.
245
+ *
246
+ * The one merge `loadLayered` and every caller layering configs it loaded
247
+ * some other way (content from an API, say) use, so layering means the same
248
+ * thing everywhere.
249
+ */
250
+ function mergeLayers(layers) {
251
+ const present = layers.filter((layer) => layer !== void 0);
252
+ if (present.length === 0) return void 0;
253
+ return present.reduce((acc, layer) => deepMerge(acc, layer), {});
101
254
  }
255
+ // src/load-layered/load-layered.ts
102
256
  /**
103
257
  * `<name>.config.*` layered over the `[fallback.key]` of
104
258
  * `<fallback.file>.config.*`. Either, both, or neither may be present;
@@ -106,106 +260,142 @@ async function loadConfigFile(opts) {
106
260
  * when neither source resolves.
107
261
  */
108
262
  async function loadLayered(opts) {
263
+ const coerce = opts.coerce ?? ((raw) => raw);
109
264
  const dedicated = await loadConfigFile(opts);
265
+ let top;
266
+ let topFile = null;
267
+ if (dedicated) {
268
+ top = coerce(dedicated.config);
269
+ if (top !== void 0) topFile = dedicated.filepath;
270
+ }
110
271
  let base;
111
272
  let baseFile = null;
112
273
  if (opts.fallback) {
113
- const parent = await loadConfigFile({
274
+ const parent = opts.fallback.preloaded !== void 0 ? opts.fallback.preloaded : await loadConfigFile({
114
275
  cwd: opts.cwd,
115
276
  name: opts.fallback.file,
116
- extensions: opts.extensions
277
+ extensions: opts.extensions,
278
+ walkUp: opts.walkUp
117
279
  });
118
- if (parent && parent.config[opts.fallback.key] !== void 0) {
119
- base = parent.config[opts.fallback.key];
120
- baseFile = parent.filepath;
280
+ const raw = (parent?.config)?.[opts.fallback.key];
281
+ if (parent && raw !== void 0) {
282
+ base = coerce(raw);
283
+ if (base !== void 0) baseFile = parent.filepath;
121
284
  }
122
285
  }
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);
286
+ const config = mergeLayers([base, top]);
287
+ if (config === void 0) return null;
288
+ const sources = [baseFile, topFile].filter((s) => s !== null);
126
289
  return {
127
290
  config,
128
- filepath: dedicated?.filepath ?? baseFile,
291
+ filepath: topFile ?? baseFile,
129
292
  sources
130
293
  };
131
294
  }
295
+ // src/read-config-dir-source/read-config-dir-source.ts
132
296
  /**
133
- * Load config from content that didn't come from a file already on disk —
134
- * writes it to `<dir>/<name>.config.<extension>` first, then loads it
135
- * through the exact same path {@link loadConfigFile} uses for a file it
136
- * discovered itself. Exists because sourcing config content from somewhere
137
- * other than the local filesystem (a GitHub API fetch, for one — see
138
- * `@theholocron/sentinel`) doesn't change what loading it correctly means:
139
- * a `.ts` config still needs real module resolution, `defineConfig` import
140
- * included, not a re-implemented parser.
297
+ * {@link readConfigSource} for the area files of a config directory (`.holocron/<area>.<ext>`) that live somewhere
298
+ * other than the local disk: for each name in `options.areas`, probes the extensions in priority order through
299
+ * `options.fetch` and keeps the first file that exists. Areas with no file are left out, so a repo with no
300
+ * directory returns `[]`. Write the result with {@link writeConfigDir} and read it back with {@link loadConfigDir}.
301
+ *
302
+ * This reads only the named areas. A caller that lists the whole directory (and so also gets the files an area
303
+ * imports) passes that tree to {@link writeConfigDir} directly.
141
304
  */
142
- async function loadConfigFromContent(opts) {
143
- const filepath = join(opts.dir, `${opts.name}.config.${opts.extension}`);
144
- await writeFile(filepath, opts.content, "utf8");
145
- return {
146
- config: await loadFile(filepath, opts.extension),
147
- filepath
148
- };
149
- }
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);
305
+ async function readConfigDirSource(options) {
306
+ const sources = [];
307
+ for (const area of options.areas) for (const extension of options.extensions ?? DEFAULT_EXTENSIONS) {
308
+ const path = `${options.dir}/${area}.${extension}`;
309
+ const content = await options.fetch(path);
310
+ if (content === void 0) continue;
311
+ sources.push({
312
+ area,
313
+ path,
314
+ extension,
315
+ content
316
+ });
317
+ break;
160
318
  }
319
+ return sources;
161
320
  }
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);
321
+ // src/read-config-source/read-config-source.ts
322
+ /**
323
+ * {@link probeExtensions} for a config that lives somewhere other than the
324
+ * local disk (a GitHub API, a git blob): probes `<name>.config.<ext>` in
325
+ * extension-priority order through `options.fetch`, returning the first file
326
+ * that exists, or `undefined` when none does. Pass the result to
327
+ * `loadConfigFromContent` to execute it exactly as a local file would be.
328
+ */
329
+ async function readConfigSource(options) {
330
+ for (const extension of options.extensions ?? DEFAULT_EXTENSIONS) {
331
+ const path = `${options.name}.config.${extension}`;
332
+ const content = await options.fetch(path);
333
+ if (content !== void 0) return {
334
+ path,
335
+ extension,
336
+ content
337
+ };
167
338
  }
168
339
  }
169
- let tsRegistered;
170
- async function registerTsx() {
171
- const { register } = await import("tsx/esm/api");
172
- register();
173
- }
340
+ // src/with-config-sandbox/with-config-sandbox.ts
174
341
  /**
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.
342
+ * Runs `run` with a throwaway directory prepared for
343
+ * {@link loadConfigFromContent}'s `dir`, and removes it afterwards (also when
344
+ * `run` throws).
345
+ *
346
+ * The directory is made for a TS/JS config that imports packages:
347
+ *
348
+ * - `node_modules` is a symlink to `options.nodeModules`, so those imports
349
+ * resolve as if the config sat next to that directory.
350
+ * - A `package.json` of `{"type":"module"}` is written into it. Node decides
351
+ * whether a `.ts`/`.js` file is ESM or CommonJS from the nearest ancestor
352
+ * `package.json`'s `type`, defaulting to CommonJS — and `tsx`'s loader,
353
+ * correctly honouring that, would then `require()` a pure-ESM dependency
354
+ * such as `@theholocron/cli`'s `dist/index.mjs`, which Node rejects outright
355
+ * ("require() of ES Module … not supported").
356
+ *
357
+ * The directory lives under the OS temp dir by default rather than inside any
358
+ * package: read-only deployments (Vercel's Node.js Functions ship the bundle
359
+ * read-only under `/var/task`) can't create a directory there.
180
360
  */
181
- async function importTs(filepath) {
182
- tsRegistered ??= registerTsx();
183
- await tsRegistered;
361
+ async function withConfigSandbox(options, run) {
362
+ const root = options.root ?? tmpdir();
363
+ await mkdir(root, { recursive: true });
364
+ const dir = await mkdtemp(join(root, options.prefix ?? "datapad-"));
184
365
  try {
185
- return await import(pathToFileURL(filepath).href);
186
- } catch (err) {
187
- throw new ConfigFileError(`could not load ${filepath}: ${message(err)}`, filepath);
366
+ await symlink(options.nodeModules, join(dir, "node_modules"), "dir");
367
+ await writeFile(join(dir, "package.json"), JSON.stringify({ type: "module" }), "utf8");
368
+ return await run(dir);
369
+ } finally {
370
+ await rm(dir, {
371
+ recursive: true,
372
+ force: true
373
+ });
188
374
  }
189
375
  }
376
+ // src/write-config-dir/write-config-dir.ts
190
377
  /**
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.
378
+ * Write the files fetched from a config directory (`.holocron/…`) into the sandbox beside the config, keeping each
379
+ * relative path, so {@link loadConfigDir} finds them and an area file that imports a sibling resolves it. Creates the
380
+ * sub-directories as needed and returns the absolute paths written. Throws {@link ConfigFileError} for a path that is
381
+ * absolute or leaves `dir`, because the paths come from a remote tree and must never write outside the sandbox; it
382
+ * checks every path before it writes any.
195
383
  */
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;
384
+ async function writeConfigDir(options) {
385
+ const root = resolve(options.dir);
386
+ const targets = options.files.map((file) => {
387
+ const target = resolve(root, file.path);
388
+ const rel = relative(root, target);
389
+ if (isAbsolute(file.path) || rel === "" || rel.startsWith("..") || isAbsolute(rel)) throw new ConfigFileError(`refusing to write ${file.path}: it is not inside ${options.dir}`, target);
390
+ return {
391
+ target,
392
+ content: file.content
393
+ };
394
+ });
395
+ for (const { target, content } of targets) {
396
+ await mkdir(dirname(target), { recursive: true });
397
+ await writeFile(target, content, "utf8");
207
398
  }
399
+ return targets.map(({ target }) => target);
208
400
  }
209
- const message = (err) => err instanceof Error ? err.message : String(err);
210
- //#endregion
211
- export { ConfigFileError, DEFAULT_EXTENSIONS, createDefineConfig, loadConfigFile, loadConfigFromContent, loadLayered, mergeConfig };
401
+ export { ConfigFileError, DEFAULT_EXTENSIONS, createDefineConfig, loadConfigDir, loadConfigFile, loadConfigFromContent, loadLayered, mergeConfig, mergeLayers, readConfigDirSource, readConfigSource, withConfigSandbox, writeConfigDir };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theholocron/datapad",
3
- "version": "5.0.0-alpha.37",
3
+ "version": "5.0.0-alpha.371",
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/fs-utils": "^1.17.0-alpha.2",
37
+ "@theholocron/misc-utils": "^1.17.0-alpha.2",
38
+ "@theholocron/object-utils": "^1.17.0-alpha.2"
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",
44
- "@vitest/eslint-plugin": "^1.6.27",
45
- "eslint": "^10.8.1",
46
- "eslint-plugin-n": "^18.3.0",
47
- "globals": "^17.11.0",
48
- "tsdown": "^0.22.14",
42
+ "@vitest/coverage-v8": "^5.1.0",
43
+ "@vitest/eslint-plugin": "^1.6.28",
44
+ "eslint": "^10.14.0",
45
+ "eslint-plugin-n": "^18.5.0",
46
+ "globals": "^17.14.0",
47
+ "tsdown": "^0.23.5",
49
48
  "typescript": "^5.9.3",
50
- "vitest": "^4.1.11"
49
+ "vitest": "^5.1.0",
50
+ "@theholocron/eslint-config": "^8.9.0-alpha.11",
51
+ "@theholocron/tsconfig": "^8.9.0-alpha.11",
52
+ "@theholocron/vitest-config": "^8.9.0-alpha.11",
53
+ "@theholocron/tsdown-config": "^8.9.0-alpha.11"
51
54
  },
52
55
  "engines": {
53
56
  "node": ">=22"
@@ -56,10 +59,10 @@
56
59
  "access": "public"
57
60
  },
58
61
  "scripts": {
59
- "delivery.build": "tsdown",
60
- "sourceQuality.staticAnalysis": "eslint .",
62
+ "build": "tsdown",
63
+ "lint:code": "eslint .",
64
+ "test:unit": "vitest run --coverage",
61
65
  "test:watch": "vitest",
62
- "verification.typeSafety": "tsc --noEmit",
63
- "verification.unitTests": "vitest run"
66
+ "typecheck": "tsc --noEmit"
64
67
  }
65
68
  }