@theholocron/datapad 5.0.0-alpha.35 → 5.0.0-alpha.351

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