@wtf/project-config 0.0.0-stage → 1.0.0

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 (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +76 -2
  3. package/dist/define.d.ts +26 -0
  4. package/dist/define.js +7 -0
  5. package/dist/define.js.map +1 -0
  6. package/dist/env.d.ts +40 -0
  7. package/dist/env.js +160 -0
  8. package/dist/env.js.map +1 -0
  9. package/dist/errors.d.ts +151 -0
  10. package/dist/errors.js +175 -0
  11. package/dist/errors.js.map +1 -0
  12. package/dist/files.d.ts +51 -0
  13. package/dist/files.js +120 -0
  14. package/dist/files.js.map +1 -0
  15. package/dist/index.d.ts +196 -0
  16. package/dist/index.js +2 -0
  17. package/dist/index.js.map +1 -0
  18. package/dist/load.d.ts +82 -0
  19. package/dist/load.js +140 -0
  20. package/dist/load.js.map +1 -0
  21. package/dist/locate.d.ts +71 -0
  22. package/dist/locate.js +121 -0
  23. package/dist/locate.js.map +1 -0
  24. package/dist/merge.d.ts +10 -0
  25. package/dist/merge.js +33 -0
  26. package/dist/merge.js.map +1 -0
  27. package/dist/node.d.ts +20 -0
  28. package/dist/node.js +90 -0
  29. package/dist/node.js.map +1 -0
  30. package/dist/path.d.ts +14 -0
  31. package/dist/path.js +40 -0
  32. package/dist/path.js.map +1 -0
  33. package/dist/placeholder.d.ts +37 -0
  34. package/dist/placeholder.js +47 -0
  35. package/dist/placeholder.js.map +1 -0
  36. package/dist/schema.d.ts +23 -0
  37. package/dist/schema.js +56 -0
  38. package/dist/schema.js.map +1 -0
  39. package/dist/section.d.ts +39 -0
  40. package/dist/section.js +169 -0
  41. package/dist/section.js.map +1 -0
  42. package/dist/text.d.ts +3 -0
  43. package/dist/text.js +3 -0
  44. package/dist/text.js.map +1 -0
  45. package/dist/write.d.ts +35 -0
  46. package/dist/write.js +209 -0
  47. package/dist/write.js.map +1 -0
  48. package/package.json +89 -4
@@ -0,0 +1 @@
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EAAE,CAAC,MAAM,EAAE,EAAE;YAChB,IAAI,CAAC;gBACH,gEAAgE;gBAChE,OAAO,IAAI,GAAG,CACZ,WAAW,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE;oBAClC,IAAI,CAAC;wBACH,OAAO,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC,MAAM,EAAE,CAAA;oBAC9C,CAAC;oBAAC,MAAM,CAAC;wBACP,OAAO,KAAK,CAAA;oBACd,CAAC;gBACH,CAAC,CAAC,CACH,CAAA;YACH,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,IAAI,SAAS,CAAC,KAAK,CAAC;oBAAE,OAAO,IAAI,GAAG,EAAU,CAAA;gBAC9C,MAAM,KAAK,CAAA;YACb,CAAC;QACH,CAAC;KACF;CACF,CAAC,CAAA;AAEF;;;;GAIG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,CACxB,SAAiB,OAAO,CAAC,GAAG,EAAE,EAC9B,UAAgC,EAAE,EACT,EAAE,CAC3B,QAAQ,CAAC,MAAM,EAAE;IACf,WAAW,EAAE,OAAO,CAAC,GAAG;IACxB,GAAG,OAAO;IACV,QAAQ,EAAE,OAAO,CAAC,QAAQ,IAAI,kBAAkB,EAAE;CACnD,CAAC,CAAA;AAEJ;;;;GAIG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,CAC5B,SAAiB,OAAO,CAAC,GAAG,EAAE,EAC9B,UAAoC,EAAE,EACtB,EAAE,CAClB,YAAY,CAAC,MAAM,EAAE;IACnB,WAAW,EAAE,OAAO,CAAC,GAAG;IACxB,GAAG,OAAO;IACV,QAAQ,EAAE,OAAO,CAAC,QAAQ,IAAI,gBAAgB,EAAE;CACjD,CAAC,CAAA","sourcesContent":["/**\n * Node's platform and loads of the configuration: {@link nodeConfigPlatform}, the disk as handles\n * of the File System Standard, by `nodeStorage()` of `@wtf/platform-fs-node/storage`, and the paths\n * of `nodePath()` of `@wtf/platform-node/path`; {@link nodeSyncPlatform}, the disk read\n * synchronously, by `node:fs`; and {@link loadConfig} and {@link loadConfigSync}, those of ./load,\n * of the process's working folder, its environment and Node's platform by default. A repo loads its\n * config by them, and spreads a section into a preset's options:\n *\n * ```ts\n * import { loadConfig } from '@wtf/project-config/node'\n * import { sectionOf } from '@wtf/project-config/section'\n * import { rootConfig } from '@wtf/project-vitest/config'\n * import { vitestSchema } from '@wtf/project-vitest/schema'\n *\n * const config = await loadConfig()\n * export default rootConfig({ ...(await sectionOf(config, 'vitest', vitestSchema)) })\n * ```\n *\n * @packageDocumentation\n */\nimport { readdirSync, readFileSync, statSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport { nodeStorage } from '@wtf/platform-fs-node/storage'\nimport { nodePath } from '@wtf/platform-node/path'\n\nimport type { ConfigPlatform, ConfigSyncPlatform, ResolvedConfig } from './index.ts'\nimport {\n loadConfig as loadWith,\n loadConfigSync as loadSyncWith,\n type LoadOptions,\n type LoadSyncOptions\n} from './load.ts'\n\n/** Node's platform the configuration is read and written by: the disk from its root, its paths,\n * and the process's working folder. */\nexport const nodeConfigPlatform = (): ConfigPlatform => ({\n navigator: { storage: nodeStorage() },\n path: nodePath(),\n dirs: { cwd: process.cwd() }\n})\n\n/** Whether `error` is Node's of a file or a folder not there, or of the other kind. */\nconst isMissing = (error: unknown): boolean =>\n ['ENOENT', 'ENOTDIR', 'EISDIR'].includes((error as NodeJS.ErrnoException | undefined)?.code ?? '')\n\n/** Node's platform the configuration is read by synchronously: the disk by `node:fs`, and its\n * paths. */\nexport const nodeSyncPlatform = (): ConfigSyncPlatform => ({\n path: nodePath(),\n files: {\n text: (path) => {\n try {\n return readFileSync(path, 'utf8')\n } catch (error) {\n if (isMissing(error)) return undefined\n throw error\n }\n },\n files: (folder) => {\n try {\n // A link is what it links to, as a handle of the disk reads it.\n return new Set(\n readdirSync(folder).filter((name) => {\n try {\n return statSync(join(folder, name)).isFile()\n } catch {\n return false\n }\n })\n )\n } catch (error) {\n if (isMissing(error)) return new Set<string>()\n throw error\n }\n }\n }\n})\n\n/**\n * The configuration of the project in `folder`, the process's working folder by default, as\n * `loadConfig` of ./load reads it: the namespace `wtf` by default, of Node's platform and the\n * process's environment, unless `options` gives others.\n */\nexport const loadConfig = (\n folder: string = process.cwd(),\n options: Partial<LoadOptions> = {}\n): Promise<ResolvedConfig> =>\n loadWith(folder, {\n environment: process.env,\n ...options,\n platform: options.platform ?? nodeConfigPlatform()\n })\n\n/**\n * The configuration of the project in `folder`, the process's working folder by default, as\n * `loadConfigSync` of ./load reads it, of a JSON file or package.json alone: of Node's platform\n * and the process's environment, unless `options` gives others.\n */\nexport const loadConfigSync = (\n folder: string = process.cwd(),\n options: Partial<LoadSyncOptions> = {}\n): ResolvedConfig =>\n loadSyncWith(folder, {\n environment: process.env,\n ...options,\n platform: options.platform ?? nodeSyncPlatform()\n })\n"]}
package/dist/path.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ import type { ConfigPath } from './index.ts';
2
+ /**
3
+ * The keys of `text`, a path as a person writes it: its keys, joined by `.`, as `vite.compress`; a
4
+ * key of digits is an index of a list, `doctor.skip.0`, and `[0]` is the same, `doctor.skip[0]`.
5
+ * An empty path, or one with an empty key, as `vite..compress`, is a {@link ConfigPathError}.
6
+ */
7
+ export declare function configPathOf(text: string): ConfigPath;
8
+ /** `path` as a person reads it: its keys joined by `.`, and an index of a list in `[]`. */
9
+ export declare const textOfConfigPath: (path: ConfigPath) => string;
10
+ /**
11
+ * The value at `path` of `value`, by each key in turn: of an object, its own key; of a list, its
12
+ * index. `undefined` when one is not there, or when a value on the way is no object or list.
13
+ */
14
+ export declare function valueAt(value: unknown, path: ConfigPath): unknown;
package/dist/path.js ADDED
@@ -0,0 +1,40 @@
1
+ /**
2
+ * A path in the configuration: {@link configPathOf}, the keys of a path as a person writes it,
3
+ * `vite.compress`; {@link textOfConfigPath}, the other way; and {@link valueAt}, the value at a
4
+ * path of an object, if one is there.
5
+ *
6
+ * @packageDocumentation
7
+ */
8
+ import { ConfigPathError } from "./errors.js";
9
+ import { textOfPath } from "./text.js";
10
+ /**
11
+ * The keys of `text`, a path as a person writes it: its keys, joined by `.`, as `vite.compress`; a
12
+ * key of digits is an index of a list, `doctor.skip.0`, and `[0]` is the same, `doctor.skip[0]`.
13
+ * An empty path, or one with an empty key, as `vite..compress`, is a {@link ConfigPathError}.
14
+ */
15
+ export function configPathOf(text) {
16
+ const keys = text.replaceAll(/\[(\d+)\]/g, '.$1').split('.');
17
+ if (text === '' || keys.some((key) => key === ''))
18
+ throw new ConfigPathError(text, 'is no path: give its keys, joined by ".", as vite.compress.');
19
+ return keys;
20
+ }
21
+ /** `path` as a person reads it: its keys joined by `.`, and an index of a list in `[]`. */
22
+ export const textOfConfigPath = (path) => textOfPath(path);
23
+ const isIndex = (key) => /^\d+$/.test(key);
24
+ /**
25
+ * The value at `path` of `value`, by each key in turn: of an object, its own key; of a list, its
26
+ * index. `undefined` when one is not there, or when a value on the way is no object or list.
27
+ */
28
+ export function valueAt(value, path) {
29
+ let at = value;
30
+ for (const key of path) {
31
+ if (Array.isArray(at) && isIndex(key))
32
+ at = at[Number(key)];
33
+ else if (typeof at === 'object' && at !== null && !Array.isArray(at) && Object.hasOwn(at, key))
34
+ at = at[key];
35
+ else
36
+ return undefined;
37
+ }
38
+ return at;
39
+ }
40
+ //# sourceMappingURL=path.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"path.js","sourceRoot":"","sources":["../src/path.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAE7C,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAA;AAEtC;;;;GAIG;AACH,MAAM,UAAU,YAAY,CAAC,IAAY;IACvC,MAAM,IAAI,GAAG,IAAI,CAAC,UAAU,CAAC,YAAY,EAAE,KAAK,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;IAC5D,IAAI,IAAI,KAAK,EAAE,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,KAAK,EAAE,CAAC;QAC/C,MAAM,IAAI,eAAe,CAAC,IAAI,EAAE,6DAA6D,CAAC,CAAA;IAChG,OAAO,IAAI,CAAA;AACb,CAAC;AAED,2FAA2F;AAC3F,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,IAAgB,EAAU,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,CAAA;AAE9E,MAAM,OAAO,GAAG,CAAC,GAAW,EAAW,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;AAE3D;;;GAGG;AACH,MAAM,UAAU,OAAO,CAAC,KAAc,EAAE,IAAgB;IACtD,IAAI,EAAE,GAAY,KAAK,CAAA;IACvB,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE,CAAC;QACvB,IAAI,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC,IAAI,OAAO,CAAC,GAAG,CAAC;YAAE,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAA;aACtD,IAAI,OAAO,EAAE,KAAK,QAAQ,IAAI,EAAE,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC,IAAI,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,GAAG,CAAC;YAC5F,EAAE,GAAI,EAA8B,CAAC,GAAG,CAAC,CAAA;;YACtC,OAAO,SAAS,CAAA;IACvB,CAAC;IACD,OAAO,EAAE,CAAA;AACX,CAAC","sourcesContent":["/**\n * A path in the configuration: {@link configPathOf}, the keys of a path as a person writes it,\n * `vite.compress`; {@link textOfConfigPath}, the other way; and {@link valueAt}, the value at a\n * path of an object, if one is there.\n *\n * @packageDocumentation\n */\nimport { ConfigPathError } from './errors.ts'\nimport type { ConfigPath } from './index.ts'\nimport { textOfPath } from './text.ts'\n\n/**\n * The keys of `text`, a path as a person writes it: its keys, joined by `.`, as `vite.compress`; a\n * key of digits is an index of a list, `doctor.skip.0`, and `[0]` is the same, `doctor.skip[0]`.\n * An empty path, or one with an empty key, as `vite..compress`, is a {@link ConfigPathError}.\n */\nexport function configPathOf(text: string): ConfigPath {\n const keys = text.replaceAll(/\\[(\\d+)\\]/g, '.$1').split('.')\n if (text === '' || keys.some((key) => key === ''))\n throw new ConfigPathError(text, 'is no path: give its keys, joined by \".\", as vite.compress.')\n return keys\n}\n\n/** `path` as a person reads it: its keys joined by `.`, and an index of a list in `[]`. */\nexport const textOfConfigPath = (path: ConfigPath): string => textOfPath(path)\n\nconst isIndex = (key: string): boolean => /^\\d+$/.test(key)\n\n/**\n * The value at `path` of `value`, by each key in turn: of an object, its own key; of a list, its\n * index. `undefined` when one is not there, or when a value on the way is no object or list.\n */\nexport function valueAt(value: unknown, path: ConfigPath): unknown {\n let at: unknown = value\n for (const key of path) {\n if (Array.isArray(at) && isIndex(key)) at = at[Number(key)]\n else if (typeof at === 'object' && at !== null && !Array.isArray(at) && Object.hasOwn(at, key))\n at = (at as Record<string, unknown>)[key]\n else return undefined\n }\n return at\n}\n"]}
@@ -0,0 +1,37 @@
1
+ /**
2
+ * A value of the configuration that points at the environment: a placeholder `${env:NAME}` in a
3
+ * string, as `"clientSecret": "${env:CLIENT_SECRET}"`, or in a longer one,
4
+ * `"https://${env:HOST}/api"`. {@link expandPlaceholders} gives a value, and {@link expandString}
5
+ * a string, with each placeholder taken for the variable of the environment it names, of the
6
+ * environment the caller gives; `sectionOf` of ./section does it as a tool reads its section,
7
+ * before the schema checks it. Only that form is one, with `NAME` of letters, digits and `_`, not
8
+ * starting with a digit: `${version}`, `${foo}` and every other `$` or `{` stay as they are.
9
+ * `$${env:NAME}` is the text `${env:NAME}`. A variable that is not set, or is empty, is an
10
+ * {@link EnvPlaceholderUnsetError}, which names the path of the value and the variable, and no
11
+ * value. Nothing here reads the environment of a process.
12
+ *
13
+ * ```ts
14
+ * expandString('https://${env:HOST}/api', ['wtf', 'astro', 'url'], { HOST: 'a.example' })
15
+ * // 'https://a.example/api'
16
+ * ```
17
+ *
18
+ * @packageDocumentation
19
+ */
20
+ import type { Environment } from './env.ts';
21
+ import type { ConfigPath } from './index.ts';
22
+ /**
23
+ * `text` with each placeholder `${env:NAME}` taken for the variable `NAME` of `environment`, and
24
+ * each `$${env:NAME}` for the text `${env:NAME}`; the rest as it is. What a variable holds is not
25
+ * read again, so a value with a placeholder in it stays one. A variable that is not set or is
26
+ * empty is an {@link EnvPlaceholderUnsetError} of `path`, the path of the value `text` is, from
27
+ * the key that names the configuration, as `['wtf', 'astro', 'url']`.
28
+ */
29
+ export declare function expandString(text: string, path: ConfigPath, environment: Environment): string;
30
+ /**
31
+ * `value` with {@link expandString} of every string in it, at any depth, in the objects and lists:
32
+ * the values of an object, and not its keys; a number, a boolean, `null`, and anything that is no
33
+ * plain object or list, as it is. `path` is where `value` is, which a refusal names, as
34
+ * `['wtf', 'astro']`; each key goes after it. `value` is not changed: it is copied where a
35
+ * string in it is not as it was written.
36
+ */
37
+ export declare function expandPlaceholders(value: unknown, path: ConfigPath, environment: Environment): unknown;
@@ -0,0 +1,47 @@
1
+ import { EnvPlaceholderUnsetError } from "./errors.js";
2
+ /** A placeholder, or its escape: `$$` before it is the text of it, as it is. */
3
+ const PLACEHOLDER = /(\$\$|\$)\{env:([A-Za-z_][A-Za-z0-9_]*)\}/g;
4
+ /**
5
+ * `text` with each placeholder `${env:NAME}` taken for the variable `NAME` of `environment`, and
6
+ * each `$${env:NAME}` for the text `${env:NAME}`; the rest as it is. What a variable holds is not
7
+ * read again, so a value with a placeholder in it stays one. A variable that is not set or is
8
+ * empty is an {@link EnvPlaceholderUnsetError} of `path`, the path of the value `text` is, from
9
+ * the key that names the configuration, as `['wtf', 'astro', 'url']`.
10
+ */
11
+ export function expandString(text, path, environment) {
12
+ return text.replaceAll(PLACEHOLDER, (match, dollars, name) => {
13
+ if (dollars === '$$')
14
+ return match.slice(1);
15
+ const value = environment[name];
16
+ if (value === undefined || value === '')
17
+ throw new EnvPlaceholderUnsetError(path, name);
18
+ return value;
19
+ });
20
+ }
21
+ /** Whether `value` is an object of keys, as JSON's: no list, and no instance of a class. */
22
+ const isPlain = (value) => {
23
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
24
+ return false;
25
+ const prototype = Object.getPrototypeOf(value);
26
+ return prototype === Object.prototype || prototype === null;
27
+ };
28
+ /**
29
+ * `value` with {@link expandString} of every string in it, at any depth, in the objects and lists:
30
+ * the values of an object, and not its keys; a number, a boolean, `null`, and anything that is no
31
+ * plain object or list, as it is. `path` is where `value` is, which a refusal names, as
32
+ * `['wtf', 'astro']`; each key goes after it. `value` is not changed: it is copied where a
33
+ * string in it is not as it was written.
34
+ */
35
+ export function expandPlaceholders(value, path, environment) {
36
+ if (typeof value === 'string')
37
+ return expandString(value, path, environment);
38
+ if (Array.isArray(value))
39
+ return value.map((item, index) => expandPlaceholders(item, [...path, String(index)], environment));
40
+ if (!isPlain(value))
41
+ return value;
42
+ const expanded = {};
43
+ for (const [key, item] of Object.entries(value))
44
+ expanded[key] = expandPlaceholders(item, [...path, key], environment);
45
+ return expanded;
46
+ }
47
+ //# sourceMappingURL=placeholder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"placeholder.js","sourceRoot":"","sources":["../src/placeholder.ts"],"names":[],"mappings":"AAoBA,OAAO,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAA;AAGtD,gFAAgF;AAChF,MAAM,WAAW,GAAG,4CAA4C,CAAA;AAEhE;;;;;;GAMG;AACH,MAAM,UAAU,YAAY,CAAC,IAAY,EAAE,IAAgB,EAAE,WAAwB;IACnF,OAAO,IAAI,CAAC,UAAU,CAAC,WAAW,EAAE,CAAC,KAAK,EAAE,OAAe,EAAE,IAAY,EAAE,EAAE;QAC3E,IAAI,OAAO,KAAK,IAAI;YAAE,OAAO,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;QAC3C,MAAM,K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AAC,IAAI,EAAE,CAAC,GAAG,IAAI,EAAE,GAAG,CAAC,EAAE,WAAW,CAAC,CAAA;IACvE,OAAO,QAAQ,CAAA;AACjB,CAAC","sourcesContent":["/**\n * A value of the configuration that points at the environment: a placeholder `${env:NAME}` in a\n * string, as `\"clientSecret\": \"${env:CLIENT_SECRET}\"`, or in a longer one,\n * `\"https://${env:HOST}/api\"`. {@link expandPlaceholders} gives a value, and {@link expandString}\n * a string, with each placeholder taken for the variable of the environment it names, of the\n * environment the caller gives; `sectionOf` of ./section does it as a tool reads its section,\n * before the schema checks it. Only that form is one, with `NAME` of letters, digits and `_`, not\n * starting with a digit: `${version}`, `${foo}` and every other `$` or `{` stay as they are.\n * `$${env:NAME}` is the text `${env:NAME}`. A variable that is not set, or is empty, is an\n * {@link EnvPlaceholderUnsetError}, which names the path of the value and the variable, and no\n * value. Nothing here reads the environment of a process.\n *\n * ```ts\n * expandString('https://${env:HOST}/api', ['wtf', 'astro', 'url'], { HOST: 'a.example' })\n * // 'https://a.example/api'\n * ```\n *\n * @packageDocumentation\n */\nimport type { Environment } from './env.ts'\nimport { EnvPlaceholderUnsetError } from './errors.ts'\nimport type { ConfigPath } from './index.ts'\n\n/** A placeholder, or its escape: `$$` before it is the text of it, as it is. */\nconst PLACEHOLDER = /(\\$\\$|\\$)\\{env:([A-Za-z_][A-Za-z0-9_]*)\\}/g\n\n/**\n * `text` with each placeholder `${env:NAME}` taken for the variable `NAME` of `environment`, and\n * each `$${env:NAME}` for the text `${env:NAME}`; the rest as it is. What a variable holds is not\n * read again, so a value with a placeholder in it stays one. A variable that is not set or is\n * empty is an {@link EnvPlaceholderUnsetError} of `path`, the path of the value `text` is, from\n * the key that names the configuration, as `['wtf', 'astro', 'url']`.\n */\nexport function expandString(text: string, path: ConfigPath, environment: Environment): string {\n return text.replaceAll(PLACEHOLDER, (match, dollars: string, name: string) => {\n if (dollars === '$$') return match.slice(1)\n const value = environment[name]\n if (value === undefined || value === '') throw new EnvPlaceholderUnsetError(path, name)\n return value\n })\n}\n\n/** Whether `value` is an object of keys, as JSON's: no list, and no instance of a class. */\nconst isPlain = (value: unknown): value is Readonly<Record<string, unknown>> => {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false\n const prototype: unknown = Object.getPrototypeOf(value)\n return prototype === Object.prototype || prototype === null\n}\n\n/**\n * `value` with {@link expandString} of every string in it, at any depth, in the objects and lists:\n * the values of an object, and not its keys; a number, a boolean, `null`, and anything that is no\n * plain object or list, as it is. `path` is where `value` is, which a refusal names, as\n * `['wtf', 'astro']`; each key goes after it. `value` is not changed: it is copied where a\n * string in it is not as it was written.\n */\nexport function expandPlaceholders(\n value: unknown,\n path: ConfigPath,\n environment: Environment\n): unknown {\n if (typeof value === 'string') return expandString(value, path, environment)\n if (Array.isArray(value))\n return value.map((item: unknown, index) =>\n expandPlaceholders(item, [...path, String(index)], environment)\n )\n if (!isPlain(value)) return value\n const expanded: Record<string, unknown> = {}\n for (const [key, item] of Object.entries(value))\n expanded[key] = expandPlaceholders(item, [...path, key], environment)\n return expanded\n}\n"]}
@@ -0,0 +1,23 @@
1
+ import type { SectionSchema } from './index.ts';
2
+ /** The draft of the JSON Schema {@link namespaceSchema} gives, and a section's is read as. */
3
+ export declare const JSON_SCHEMA_DRAFT = "https://json-schema.org/draft/2020-12/schema";
4
+ /**
5
+ * The `$id` of a section's schema that has none: a `$ref` in it, as `#/$defs/x`, is then of the
6
+ * section's own schema, and not of the whole.
7
+ */
8
+ export declare const sectionIdOf: (namespace: string, name: string) => string;
9
+ /** What the schema of the whole says of itself. */
10
+ export type NamespaceSchemaOptions = {
11
+ readonly title?: string;
12
+ readonly description?: string;
13
+ };
14
+ /**
15
+ * The JSON Schema of the configuration of `namespace`, of draft 2020-12, of `sections`, the schema
16
+ * of each section by its name: a JSON Schema, or a Standard Schema that gives one, as zod's and
17
+ * the presets' do, of its input. It is an object with each section at its property, checked by its
18
+ * schema; the `$schema` key, by which a file names its schema; and any other key as it is. A
19
+ * schema that gives no JSON Schema, as a function, takes any value.
20
+ */
21
+ export declare function namespaceSchema(namespace: string, sections: Readonly<Record<string, SectionSchema>>, { title, description }?: NamespaceSchemaOptions): {
22
+ readonly [keyword: string]: unknown;
23
+ };
package/dist/schema.js ADDED
@@ -0,0 +1,56 @@
1
+ /**
2
+ * The JSON Schema of a namespace's configuration, of the schemas of the sections of the tools a
3
+ * project uses: {@link namespaceSchema}. Each tool's package exports the schema of its options, as
4
+ * `viteSchema` of `@wtf/project-vite/schema`, a Standard Schema that gives its JSON Schema; the
5
+ * schema of the whole has each at the property of its section, and takes any other section as it
6
+ * is. An editor completes `wtf.config.json` by it.
7
+ *
8
+ * ```ts
9
+ * import { namespaceSchema } from '@wtf/project-config/schema'
10
+ * import { viteSchema } from '@wtf/project-vite/schema'
11
+ *
12
+ * const schema = namespaceSchema('wtf', { vite: viteSchema })
13
+ * ```
14
+ *
15
+ * @packageDocumentation
16
+ */
17
+ import { jsonSchemaOf } from "./env.js";
18
+ /** The draft of the JSON Schema {@link namespaceSchema} gives, and a section's is read as. */
19
+ export const JSON_SCHEMA_DRAFT = 'https://json-schema.org/draft/2020-12/schema';
20
+ /**
21
+ * The `$id` of a section's schema that has none: a `$ref` in it, as `#/$defs/x`, is then of the
22
+ * section's own schema, and not of the whole.
23
+ */
24
+ export const sectionIdOf = (namespace, name) => `urn:${namespace}:${name}`;
25
+ /** A section's JSON Schema, with an `$id` of its own when it has none, and with no `$schema`; any
26
+ * value, of a schema that gives no JSON Schema, as a function. */
27
+ function sectionSchema(namespace, name, schema) {
28
+ const json = jsonSchemaOf(schema);
29
+ if (json === undefined || typeof json === 'boolean')
30
+ return json ?? true;
31
+ const { $schema: _draft, ...rest } = json;
32
+ return typeof rest['$id'] === 'string' ? rest : { $id: sectionIdOf(namespace, name), ...rest };
33
+ }
34
+ /**
35
+ * The JSON Schema of the configuration of `namespace`, of draft 2020-12, of `sections`, the schema
36
+ * of each section by its name: a JSON Schema, or a Standard Schema that gives one, as zod's and
37
+ * the presets' do, of its input. It is an object with each section at its property, checked by its
38
+ * schema; the `$schema` key, by which a file names its schema; and any other key as it is. A
39
+ * schema that gives no JSON Schema, as a function, takes any value.
40
+ */
41
+ export function namespaceSchema(namespace, sections, { title = `The ${namespace} configuration`, description = 'The configuration of the tools of a project: a section of each tool, by its name.' } = {}) {
42
+ return {
43
+ $schema: JSON_SCHEMA_DRAFT,
44
+ title,
45
+ description,
46
+ type: 'object',
47
+ properties: {
48
+ $schema: { description: 'The JSON Schema of this file.', type: 'string' },
49
+ ...Object.fromEntries(Object.entries(sections).map(([name, schema]) => [
50
+ name,
51
+ sectionSchema(namespace, name, schema)
52
+ ]))
53
+ }
54
+ };
55
+ }
56
+ //# sourceMappingURL=schema.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.js","sourceRoot":"","sources":["../src/schema.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAA;AAGvC,8FAA8F;AAC9F,MAAM,CAAC,MAAM,iBAAiB,GAAG,8CAA8C,CAAA;AAE/E;;;GAGG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,SAAiB,EAAE,IAAY,EAAU,EAAE,CAAC,OAAO,SAAS,IAAI,IAAI,EAAE,CAAA;AAQlG;kEACkE;AAClE,SAAS,aAAa,CAAC,SAAiB,EAAE,IAAY,EAAE,MAAqB;IAC3E,MAAM,IAAI,GAAG,YAAY,CAAC,MAAM,CAAC,CAAA;IACjC,IAAI,IAAI,KAAK,SAAS,IAAI,OAAO,IAAI,KAAK,SAAS;QAAE,OAAO,IAAI,IAAI,IAAI,CAAA;IACxE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,IAAI,CAAA;IACzC,OAAO,OAAO,IAAI,CAAC,KAAK,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,WAAW,CAAC,SAAS,EAAE,IAAI,CAAC,EAAE,GAAG,IAAI,EAAE,CAAA;AAChG,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,eAAe,CAC7B,SAAiB,EACjB,QAAiD,EACjD,EACE,KAAK,GAAG,OAAO,SAAS,gBAAgB,EACxC,WAAW,GAAG,mFAAmF,KACvE,EAAE;IAE9B,OAAO;QACL,OAAO,EAAE,iBAAiB;QAC1B,KAAK;QACL,WAAW;QACX,IAAI,EAAE,QAAQ;QACd,UAAU,EAAE;YACV,OAAO,EAAE,EAAE,WAAW,EAAE,+BAA+B,EAAE,IAAI,EAAE,QAAQ,EAAE;YACzE,GAAG,MAAM,CAAC,WAAW,CACnB,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,MAAM,CAAC,EAAE,EAAE,CAAC;gBAC/C,IAAI;gBACJ,aAAa,CAAC,SAAS,EAAE,IAAI,EAAE,MAAM,CAAC;aACvC,CAAC,CACH;SACF;KACF,CAAA;AACH,CAAC","sourcesContent":["/**\n * The JSON Schema of a namespace's configuration, of the schemas of the sections of the tools a\n * project uses: {@link namespaceSchema}. Each tool's package exports the schema of its options, as\n * `viteSchema` of `@wtf/project-vite/schema`, a Standard Schema that gives its JSON Schema; the\n * schema of the whole has each at the property of its section, and takes any other section as it\n * is. An editor completes `wtf.config.json` by it.\n *\n * ```ts\n * import { namespaceSchema } from '@wtf/project-config/schema'\n * import { viteSchema } from '@wtf/project-vite/schema'\n *\n * const schema = namespaceSchema('wtf', { vite: viteSchema })\n * ```\n *\n * @packageDocumentation\n */\nimport { jsonSchemaOf } from './env.ts'\nimport type { JsonSchema, SectionSchema } from './index.ts'\n\n/** The draft of the JSON Schema {@link namespaceSchema} gives, and a section's is read as. */\nexport const JSON_SCHEMA_DRAFT = 'https://json-schema.org/draft/2020-12/schema'\n\n/**\n * The `$id` of a section's schema that has none: a `$ref` in it, as `#/$defs/x`, is then of the\n * section's own schema, and not of the whole.\n */\nexport const sectionIdOf = (namespace: string, name: string): string => `urn:${namespace}:${name}`\n\n/** What the schema of the whole says of itself. */\nexport type NamespaceSchemaOptions = {\n readonly title?: string\n readonly description?: string\n}\n\n/** A section's JSON Schema, with an `$id` of its own when it has none, and with no `$schema`; any\n * value, of a schema that gives no JSON Schema, as a function. */\nfunction sectionSchema(namespace: string, name: string, schema: SectionSchema): JsonSchema {\n const json = jsonSchemaOf(schema)\n if (json === undefined || typeof json === 'boolean') return json ?? true\n const { $schema: _draft, ...rest } = json\n return typeof rest['$id'] === 'string' ? rest : { $id: sectionIdOf(namespace, name), ...rest }\n}\n\n/**\n * The JSON Schema of the configuration of `namespace`, of draft 2020-12, of `sections`, the schema\n * of each section by its name: a JSON Schema, or a Standard Schema that gives one, as zod's and\n * the presets' do, of its input. It is an object with each section at its property, checked by its\n * schema; the `$schema` key, by which a file names its schema; and any other key as it is. A\n * schema that gives no JSON Schema, as a function, takes any value.\n */\nexport function namespaceSchema(\n namespace: string,\n sections: Readonly<Record<string, SectionSchema>>,\n {\n title = `The ${namespace} configuration`,\n description = 'The configuration of the tools of a project: a section of each tool, by its name.'\n }: NamespaceSchemaOptions = {}\n): { readonly [keyword: string]: unknown } {\n return {\n $schema: JSON_SCHEMA_DRAFT,\n title,\n description,\n type: 'object',\n properties: {\n $schema: { description: 'The JSON Schema of this file.', type: 'string' },\n ...Object.fromEntries(\n Object.entries(sections).map(([name, schema]) => [\n name,\n sectionSchema(namespace, name, schema)\n ])\n )\n }\n }\n}\n"]}
@@ -0,0 +1,39 @@
1
+ import type { ConfigIssue, ResolvedConfig, SectionSchema } from './index.ts';
2
+ export { mergeSection } from './merge.ts';
3
+ /** What a schema found of a value: what is wrong with it, none when it is valid, and the value as
4
+ * the schema reads it. */
5
+ export type Checked<T> = {
6
+ readonly issues: readonly ConfigIssue[];
7
+ readonly value: T;
8
+ };
9
+ /**
10
+ * What `schema` finds wrong with `value`, none when it is valid, and the value as it reads it: a
11
+ * Standard Schema's output, or `value` itself. A Standard Schema that validates is asked; a JSON
12
+ * Schema, or a Standard JSON Schema of none, is checked by ajv; a function is called.
13
+ */
14
+ export declare function issuesOf<T>(value: unknown, schema: SectionSchema<T>): Promise<Checked<T>>;
15
+ /**
16
+ * What `schema` finds wrong with `value`, as {@link issuesOf} checks it, checked synchronously: a
17
+ * schema that answers with a promise is a {@link SyncSchemaError} of the section `section`.
18
+ */
19
+ export declare function issuesOfSync<T>(value: unknown, schema: SectionSchema<T>, section?: string): Checked<T>;
20
+ /**
21
+ * The section `name` of the configuration, as its tool reads it: the project's, merged over the
22
+ * section of the `defaults` of the tool's package when it gives some ({@link mergeSection}), with
23
+ * the environment's variables the tool gave `loadConfig` over both, each that names a key of the
24
+ * section or of its schema, as `WTF_VITE_COMPRESS` (`withEnvironment` of ./env); `undefined` when
25
+ * none has one, which the tool takes as its own defaults. Each string in it is then read for
26
+ * placeholders `${env:NAME}`, taken from the whole environment the tool gave (`expandPlaceholders`
27
+ * of ./placeholder); a variable not set, or of no environment given, is an
28
+ * `EnvPlaceholderUnsetError`. Only this, and {@link sectionOfSync}, expand them, so what shows or
29
+ * writes the configuration never holds a secret it points at. With a `schema` it is checked, and
30
+ * what is wrong is an {@link InvalidSectionError}, which names where the value came from and the
31
+ * path of each value, as `wtf.vite.compress`.
32
+ */
33
+ export declare function sectionOf<T = unknown>(resolved: ResolvedConfig, name: string, schema?: SectionSchema<T>): Promise<T | undefined>;
34
+ /**
35
+ * The section `name` of the configuration, as {@link sectionOf} reads it, checked synchronously,
36
+ * as a tool that reads its config synchronously reads it with `loadConfigSync` of ./load. A schema
37
+ * that checks asynchronously is a {@link SyncSchemaError}.
38
+ */
39
+ export declare function sectionOfSync<T = unknown>(resolved: ResolvedConfig, name: string, schema?: SectionSchema<T>): T | undefined;
@@ -0,0 +1,169 @@
1
+ import { Ajv2020 } from 'ajv/dist/2020.js';
2
+ import { envNameOf, jsonSchemaOf, withEnvironment } from "./env.js";
3
+ import { InvalidSectionError, SyncSchemaError } from "./errors.js";
4
+ import { mergeSection } from "./merge.js";
5
+ import { expandPlaceholders } from "./placeholder.js";
6
+ export { mergeSection } from "./merge.js";
7
+ const isNode = (value) => typeof value === 'object' && value !== null;
8
+ /** Whether `schema` is a Standard Schema that validates: its `~standard` has `validate`. */
9
+ const validatorOf = (schema) => {
10
+ if (!isNode(schema) || !('~standard' in schema))
11
+ return undefined;
12
+ const standard = schema['~standard'];
13
+ return isNode(standard) && typeof standard['validate'] === 'function'
14
+ ? standard
15
+ : undefined;
16
+ };
17
+ /**
18
+ * The JSON Schemas compiled, by ajv, for draft 2020-12: every fault and not the first, no check
19
+ * of a `format`, and the keywords of an editor's own, as `markdownDescription`, taken.
20
+ */
21
+ let ajv;
22
+ const compiled = new WeakMap();
23
+ const compile = (schema) => {
24
+ ajv ??= new Ajv2020({ allErrors: true, strict: false, validateFormats: false, logger: false });
25
+ if (typeof schema === 'boolean')
26
+ return ajv.compile(schema);
27
+ let validate = compiled.get(schema);
28
+ if (validate === undefined) {
29
+ validate = ajv.compile(schema);
30
+ compiled.set(schema, validate);
31
+ }
32
+ return validate;
33
+ };
34
+ /** The keys of a JSON Pointer, as ajv gives the place of a value: `/compress/threshold`. */
35
+ const keysOfPointer = (pointer) => pointer === ''
36
+ ? []
37
+ : pointer
38
+ .slice(1)
39
+ .split('/')
40
+ .map((key) => key.replaceAll('~1', '/').replaceAll('~0', '~'));
41
+ /** What ajv found wrong, as an issue: a key the schema does not take at its own path. */
42
+ const issueOfAjv = ({ instancePath, keyword, params, message }) => {
43
+ const path = keysOfPointer(instancePath);
44
+ const extra = keyword === 'additionalProperties' ? params['additionalProperty'] : undefined;
45
+ return typeof extra === 'string'
46
+ ? { path: [...path, extra], message: 'is no key that the section takes' }
47
+ : { path, message: message ?? keyword };
48
+ };
49
+ /** The keys of a Standard Schema's path, each as text. */
50
+ const pathOfStandard = (path) => (path ?? []).map((segment) => String(typeof segment === 'object' && segment !== null ? segment.key : segment));
51
+ /** What a Standard Schema's result says, as issues. */
52
+ const checkedOfResult = (result, value) => result.issues === undefined
53
+ ? { issues: [], value: result.value }
54
+ : {
55
+ issues: result.issues.map(({ path, message }) => ({ path: pathOfStandard(path), message })),
56
+ value: value
57
+ };
58
+ /** What ajv finds wrong with `value` by the JSON Schema of `schema`; nothing of a schema that gives
59
+ * none. */
60
+ const checkedOfJson = (value, schema) => {
61
+ const json = jsonSchemaOf(schema);
62
+ if (json === undefined)
63
+ return { issues: [], value: value };
64
+ const validate = compile(json);
65
+ validate(value);
66
+ return { issues: (validate.errors ?? []).map(issueOfAjv), value: value };
67
+ };
68
+ /**
69
+ * What `schema` finds wrong with `value`, none when it is valid, and the value as it reads it: a
70
+ * Standard Schema's output, or `value` itself. A Standard Schema that validates is asked; a JSON
71
+ * Schema, or a Standard JSON Schema of none, is checked by ajv; a function is called.
72
+ */
73
+ export async function issuesOf(value, schema) {
74
+ if (typeof schema === 'function')
75
+ return { issues: await schema(value), value: value };
76
+ const standard = validatorOf(schema);
77
+ if (standard !== undefined)
78
+ return checkedOfResult((await standard.validate(value)), value);
79
+ return checkedOfJson(value, schema);
80
+ }
81
+ /**
82
+ * What `schema` finds wrong with `value`, as {@link issuesOf} checks it, checked synchronously: a
83
+ * schema that answers with a promise is a {@link SyncSchemaError} of the section `section`.
84
+ */
85
+ export function issuesOfSync(value, schema, section = 'configuration') {
86
+ if (typeof schema === 'function') {
87
+ const issues = schema(value);
88
+ if (issues instanceof Promise)
89
+ throw new SyncSchemaError(section);
90
+ return { issues, value: value };
91
+ }
92
+ const standard = validatorOf(schema);
93
+ if (standard !== undefined) {
94
+ const result = standard.validate(value);
95
+ if (result instanceof Promise)
96
+ throw new SyncSchemaError(section);
97
+ return checkedOfResult(result, value);
98
+ }
99
+ return checkedOfJson(value, schema);
100
+ }
101
+ /** Whether `path` is `under` or a path under it. */
102
+ const isUnder = (path, under) => under.every((key, index) => path[index] === key);
103
+ /** The section `name` of the layers of `resolved`, read for placeholders, before it is checked. */
104
+ function layeredOf(resolved, name, schema) {
105
+ const own = Object.hasOwn(resolved.config, name);
106
+ const defaults = resolved.defaults?.config;
107
+ const layered = defaults !== undefined && Object.hasOwn(defaults, name);
108
+ const filed = mergeSection(layered ? defaults[name] : undefined, resolved.config[name]);
109
+ const environment = resolved.environment === undefined
110
+ ? { value: filed, set: [] }
111
+ : withEnvironment(filed, resolved.environment.variables, `${resolved.environment.prefix}${envNameOf(name)}_`, jsonSchemaOf(schema));
112
+ const given = own || layered || environment.set.length > 0;
113
+ // No environment given is one of no variable: each placeholder is refused, never left as text.
114
+ const section = given
115
+ ? expandPlaceholders(environment.value, [resolved.key, name], resolved.environment?.values ?? {})
116
+ : undefined;
117
+ return { section, given, own, environment };
118
+ }
119
+ /** The error of what a schema found wrong with a section: of the variables that set a value it
120
+ * refuses, else of the project's file, or the defaults', of a section the project gives none of. */
121
+ function invalidOf(resolved, name, { own, environment }, issues) {
122
+ const variables = environment.set.filter(({ path }) => issues.some((issue) => isUnder(issue.path, path)));
123
+ if (variables.length > 0)
124
+ return new InvalidSectionError(variables.map(({ variable }) => variable).join(', '), resolved.namespace, name, issues.filter((issue) => variables.some(({ path }) => isUnder(issue.path, path))), resolved.key);
125
+ return own || resolved.defaults === undefined
126
+ ? new InvalidSectionError(resolved.source?.path ?? resolved.root, resolved.namespace, name, issues, resolved.key)
127
+ : new InvalidSectionError(resolved.defaults.path, resolved.namespace, name, issues);
128
+ }
129
+ /**
130
+ * The section `name` of the configuration, as its tool reads it: the project's, merged over the
131
+ * section of the `defaults` of the tool's package when it gives some ({@link mergeSection}), with
132
+ * the environment's variables the tool gave `loadConfig` over both, each that names a key of the
133
+ * section or of its schema, as `WTF_VITE_COMPRESS` (`withEnvironment` of ./env); `undefined` when
134
+ * none has one, which the tool takes as its own defaults. Each string in it is then read for
135
+ * placeholders `${env:NAME}`, taken from the whole environment the tool gave (`expandPlaceholders`
136
+ * of ./placeholder); a variable not set, or of no environment given, is an
137
+ * `EnvPlaceholderUnsetError`. Only this, and {@link sectionOfSync}, expand them, so what shows or
138
+ * writes the configuration never holds a secret it points at. With a `schema` it is checked, and
139
+ * what is wrong is an {@link InvalidSectionError}, which names where the value came from and the
140
+ * path of each value, as `wtf.vite.compress`.
141
+ */
142
+ export async function sectionOf(resolved, name, schema) {
143
+ const layered = layeredOf(resolved, name, schema);
144
+ if (!layered.given)
145
+ return undefined;
146
+ if (schema === undefined)
147
+ return layered.section;
148
+ const { issues, value } = await issuesOf(layered.section, schema);
149
+ if (issues.length === 0)
150
+ return value;
151
+ throw invalidOf(resolved, name, layered, issues);
152
+ }
153
+ /**
154
+ * The section `name` of the configuration, as {@link sectionOf} reads it, checked synchronously,
155
+ * as a tool that reads its config synchronously reads it with `loadConfigSync` of ./load. A schema
156
+ * that checks asynchronously is a {@link SyncSchemaError}.
157
+ */
158
+ export function sectionOfSync(resolved, name, schema) {
159
+ const layered = layeredOf(resolved, name, schema);
160
+ if (!layered.given)
161
+ return undefined;
162
+ if (schema === undefined)
163
+ return layered.section;
164
+ const { issues, value } = issuesOfSync(layered.section, schema, name);
165
+ if (issues.length === 0)
166
+ return value;
167
+ throw invalidOf(resolved, name, layered, issues);
168
+ }
169
+ //# sourceMappingURL=section.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"section.js","sourceRoot":"","sources":["../src/section.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAE,OAAO,EAA2C,MAAM,kBAAkB,CAAA;AAEnF,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,eAAe,EAAwB,MAAM,UAAU,CAAA;AACzF,OAAO,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AASlE,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AACzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAA;AAErD,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAMzC,MAAM,MAAM,GAAG,CAAC,KAAc,EAAoC,EAAE,CAClE,OAAO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KAAK,CAAC;QAAE,OAAO,KAAK,CAAA;IACrC,MAAM,SAAS,CAAC,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,CAAC,CAAA;AAClD,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,aAAa,CAC3B,QAAwB,EACxB,IAAY,EACZ,MAAyB;IAEzB,MAAM,OAAO,GAAG,SAAS,CAAC,QAAQ,EAAE,IAAI,EAAE,MAAM,CAAC,CAAA;IACjD,IAAI,CAAC,OAAO,CAAC,KAAK;QAAE,OAAO,SAAS,CAAA;IACpC,IAAI,MAAM,KAAK,SAAS;QAAE,OAAO,OAAO,CAAC,OAAY,CAAA;IACrD,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,YAAY,CAAC,OAAO,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,CAAA;IACrE,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,KAAK,CAAA;IACrC,MAAM,SAAS,CAAC,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,CAAC,CAAA;AAClD,CAAC","sourcesContent":["/**\n * A tool's section of the configuration: {@link sectionOf}, the section of a name, the project's\n * merged over the defaults of the tool's package ({@link mergeSection}), with the environment's\n * variables the tool gives over both, each placeholder `${env:NAME}` in it replaced by the variable\n * it names, and checked by the schema the tool gives; {@link sectionOfSync}, the same, checked\n * synchronously; and {@link issuesOf} and {@link issuesOfSync}, what a schema finds wrong with a\n * value. A schema is a Standard Schema, as each preset's `./schema` exports one, a JSON Schema or a\n * Standard JSON Schema, which ajv checks, or a function. What is wrong is an\n * `InvalidSectionError` of ./errors, which names the file and the path of each value.\n *\n * ```ts\n * import { loadConfig } from '@wtf/project-config/node'\n * import { sectionOf } from '@wtf/project-config/section'\n * import { baseConfig } from '@wtf/project-vite/config'\n * import { viteSchema } from '@wtf/project-vite/schema'\n *\n * const config = await loadConfig(process.cwd())\n * export default baseConfig({ ...(await sectionOf(config, 'vite', viteSchema)) })\n * ```\n *\n * @packageDocumentation\n */\nimport type { StandardSchemaV1 } from '@standard-schema/spec'\nimport { Ajv2020, type ErrorObject, type ValidateFunction } from 'ajv/dist/2020.js'\n\nimport { envNameOf, jsonSchemaOf, withEnvironment, type WithEnvironment } from './env.ts'\nimport { InvalidSectionError, SyncSchemaError } from './errors.ts'\nimport type {\n ConfigIssue,\n ConfigPath,\n JsonSchema,\n ResolvedConfig,\n SectionSchema,\n ValidateSection\n} from './index.ts'\nimport { mergeSection } from './merge.ts'\nimport { expandPlaceholders } from './placeholder.ts'\n\nexport { mergeSection } from './merge.ts'\n\n/** What a schema found of a value: what is wrong with it, none when it is valid, and the value as\n * the schema reads it. */\nexport type Checked<T> = { readonly issues: readonly ConfigIssue[]; readonly value: T }\n\nconst isNode = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null\n\n/** Whether `schema` is a Standard Schema that validates: its `~standard` has `validate`. */\nconst validatorOf = (schema: unknown): StandardSchemaV1['~standard'] | undefined => {\n if (!isNode(schema) || !('~standard' in schema)) return undefined\n const standard = schema['~standard']\n return isNode(standard) && typeof standard['validate'] === 'function'\n ? (standard as unknown as StandardSchemaV1['~standard'])\n : undefined\n}\n\n/**\n * The JSON Schemas compiled, by ajv, for draft 2020-12: every fault and not the first, no check\n * of a `format`, and the keywords of an editor's own, as `markdownDescription`, taken.\n */\nlet ajv: Ajv2020 | undefined\nconst compiled = new WeakMap<object, ValidateFunction>()\n\nconst compile = (schema: JsonSchema): ValidateFunction => {\n ajv ??= new Ajv2020({ allErrors: true, strict: false, validateFormats: false, logger: false })\n if (typeof schema === 'boolean') return ajv.compile(schema)\n let validate = compiled.get(schema)\n if (validate === undefined) {\n validate = ajv.compile(schema)\n compiled.set(schema, validate)\n }\n return validate\n}\n\n/** The keys of a JSON Pointer, as ajv gives the place of a value: `/compress/threshold`. */\nconst keysOfPointer = (pointer: string): string[] =>\n pointer === ''\n ? []\n : pointer\n .slice(1)\n .split('/')\n .map((key) => key.replaceAll('~1', '/').replaceAll('~0', '~'))\n\n/** What ajv found wrong, as an issue: a key the schema does not take at its own path. */\nconst issueOfAjv = ({ instancePath, keyword, params, message }: ErrorObject): ConfigIssue => {\n const path = keysOfPointer(instancePath)\n const extra: unknown =\n keyword === 'additionalProperties' ? params['additionalProperty'] : undefined\n return typeof extra === 'string'\n ? { path: [...path, extra], message: 'is no key that the section takes' }\n : { path, message: message ?? keyword }\n}\n\n/** The keys of a Standard Schema's path, each as text. */\nconst pathOfStandard = (path: StandardSchemaV1.Issue['path']): ConfigPath =>\n (path ?? []).map((segment) =>\n String(typeof segment === 'object' && segment !== null ? segment.key : segment)\n )\n\n/** What a Standard Schema's result says, as issues. */\nconst checkedOfResult = <T>(result: StandardSchemaV1.Result<T>, value: unknown): Checked<T> =>\n result.issues === undefined\n ? { issues: [], value: result.value }\n : {\n issues: result.issues.map(({ path, message }) => ({ path: pathOfStandard(path), message })),\n value: value as T\n }\n\n/** What ajv finds wrong with `value` by the JSON Schema of `schema`; nothing of a schema that gives\n * none. */\nconst checkedOfJson = <T>(value: unknown, schema: unknown): Checked<T> => {\n const json = jsonSchemaOf(schema)\n if (json === undefined) return { issues: [], value: value as T }\n const validate = compile(json)\n validate(value)\n return { issues: (validate.errors ?? []).map(issueOfAjv), value: value as T }\n}\n\n/**\n * What `schema` finds wrong with `value`, none when it is valid, and the value as it reads it: a\n * Standard Schema's output, or `value` itself. A Standard Schema that validates is asked; a JSON\n * Schema, or a Standard JSON Schema of none, is checked by ajv; a function is called.\n */\nexport async function issuesOf<T>(value: unknown, schema: SectionSchema<T>): Promise<Checked<T>> {\n if (typeof schema === 'function')\n return { issues: await (schema as ValidateSection)(value), value: value as T }\n const standard = validatorOf(schema)\n if (standard !== undefined)\n return checkedOfResult((await standard.validate(value)) as StandardSchemaV1.Result<T>, value)\n return checkedOfJson(value, schema)\n}\n\n/**\n * What `schema` finds wrong with `value`, as {@link issuesOf} checks it, checked synchronously: a\n * schema that answers with a promise is a {@link SyncSchemaError} of the section `section`.\n */\nexport function issuesOfSync<T>(\n value: unknown,\n schema: SectionSchema<T>,\n section: string = 'configuration'\n): Checked<T> {\n if (typeof schema === 'function') {\n const issues = (schema as ValidateSection)(value)\n if (issues instanceof Promise) throw new SyncSchemaError(section)\n return { issues, value: value as T }\n }\n const standard = validatorOf(schema)\n if (standard !== undefined) {\n const result = standard.validate(value)\n if (result instanceof Promise) throw new SyncSchemaError(section)\n return checkedOfResult(result as StandardSchemaV1.Result<T>, value)\n }\n return checkedOfJson(value, schema)\n}\n\n/** Whether `path` is `under` or a path under it. */\nconst isUnder = (path: ConfigPath, under: ConfigPath): boolean =>\n under.every((key, index) => path[index] === key)\n\n/** The section of `name` as the layers give it, before it is checked, and whether any gave one. */\ntype Layered = {\n readonly section: unknown\n readonly given: boolean\n readonly own: boolean\n readonly environment: WithEnvironment\n}\n\n/** The section `name` of the layers of `resolved`, read for placeholders, before it is checked. */\nfunction layeredOf(resolved: ResolvedConfig, name: string, schema: unknown): Layered {\n const own = Object.hasOwn(resolved.config, name)\n const defaults = resolved.defaults?.config\n const layered = defaults !== undefined && Object.hasOwn(defaults, name)\n const filed = mergeSection(layered ? defaults[name] : undefined, resolved.config[name])\n const environment =\n resolved.environment === undefined\n ? { value: filed, set: [] }\n : withEnvironment(\n filed,\n resolved.environment.variables,\n `${resolved.environment.prefix}${envNameOf(name)}_`,\n jsonSchemaOf(schema)\n )\n const given = own || layered || environment.set.length > 0\n // No environment given is one of no variable: each placeholder is refused, never left as text.\n const section = given\n ? expandPlaceholders(\n environment.value,\n [resolved.key, name],\n resolved.environment?.values ?? {}\n )\n : undefined\n return { section, given, own, environment }\n}\n\n/** The error of what a schema found wrong with a section: of the variables that set a value it\n * refuses, else of the project's file, or the defaults', of a section the project gives none of. */\nfunction invalidOf(\n resolved: ResolvedConfig,\n name: string,\n { own, environment }: Layered,\n issues: readonly ConfigIssue[]\n): InvalidSectionError {\n const variables = environment.set.filter(({ path }) =>\n issues.some((issue) => isUnder(issue.path, path))\n )\n if (variables.length > 0)\n return new InvalidSectionError(\n variables.map(({ variable }) => variable).join(', '),\n resolved.namespace,\n name,\n issues.filter((issue) => variables.some(({ path }) => isUnder(issue.path, path))),\n resolved.key\n )\n return own || resolved.defaults === undefined\n ? new InvalidSectionError(\n resolved.source?.path ?? resolved.root,\n resolved.namespace,\n name,\n issues,\n resolved.key\n )\n : new InvalidSectionError(resolved.defaults.path, resolved.namespace, name, issues)\n}\n\n/**\n * The section `name` of the configuration, as its tool reads it: the project's, merged over the\n * section of the `defaults` of the tool's package when it gives some ({@link mergeSection}), with\n * the environment's variables the tool gave `loadConfig` over both, each that names a key of the\n * section or of its schema, as `WTF_VITE_COMPRESS` (`withEnvironment` of ./env); `undefined` when\n * none has one, which the tool takes as its own defaults. Each string in it is then read for\n * placeholders `${env:NAME}`, taken from the whole environment the tool gave (`expandPlaceholders`\n * of ./placeholder); a variable not set, or of no environment given, is an\n * `EnvPlaceholderUnsetError`. Only this, and {@link sectionOfSync}, expand them, so what shows or\n * writes the configuration never holds a secret it points at. With a `schema` it is checked, and\n * what is wrong is an {@link InvalidSectionError}, which names where the value came from and the\n * path of each value, as `wtf.vite.compress`.\n */\nexport async function sectionOf<T = unknown>(\n resolved: ResolvedConfig,\n name: string,\n schema?: SectionSchema<T>\n): Promise<T | undefined> {\n const layered = layeredOf(resolved, name, schema)\n if (!layered.given) return undefined\n if (schema === undefined) return layered.section as T\n const { issues, value } = await issuesOf(layered.section, schema)\n if (issues.length === 0) return value\n throw invalidOf(resolved, name, layered, issues)\n}\n\n/**\n * The section `name` of the configuration, as {@link sectionOf} reads it, checked synchronously,\n * as a tool that reads its config synchronously reads it with `loadConfigSync` of ./load. A schema\n * that checks asynchronously is a {@link SyncSchemaError}.\n */\nexport function sectionOfSync<T = unknown>(\n resolved: ResolvedConfig,\n name: string,\n schema?: SectionSchema<T>\n): T | undefined {\n const layered = layeredOf(resolved, name, schema)\n if (!layered.given) return undefined\n if (schema === undefined) return layered.section as T\n const { issues, value } = issuesOfSync(layered.section, schema, name)\n if (issues.length === 0) return value\n throw invalidOf(resolved, name, layered, issues)\n}\n"]}
package/dist/text.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ import type { ConfigPath } from './index.ts';
2
+ /** `path` as a person reads it: its keys joined by `.`, and an index of a list in `[]`. */
3
+ export declare const textOfPath: (path: ConfigPath) => string;
package/dist/text.js ADDED
@@ -0,0 +1,3 @@
1
+ /** `path` as a person reads it: its keys joined by `.`, and an index of a list in `[]`. */
2
+ export const textOfPath = (path) => path.map((key, at) => (/^\d+$/.test(key) ? `[${key}]` : at === 0 ? key : `.${key}`)).join('');
3
+ //# sourceMappingURL=text.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"text.js","sourceRoot":"","sources":["../src/text.ts"],"names":[],"mappings":"AAIA,2FAA2F;AAC3F,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,IAAgB,EAAU,EAAE,CACrD,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,GAAG,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,GAAG,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA","sourcesContent":["// The text of a path of the configuration, as a person reads it, which ./path and ./errors both\n// write. Internal: no export map entry names it.\nimport type { ConfigPath } from './index.ts'\n\n/** `path` as a person reads it: its keys joined by `.`, and an index of a list in `[]`. */\nexport const textOfPath = (path: ConfigPath): string =>\n path.map((key, at) => (/^\\d+$/.test(key) ? `[${key}]` : at === 0 ? key : `.${key}`)).join('')\n"]}
@@ -0,0 +1,35 @@
1
+ import type { ConfigPath, ConfigWrite } from './index.ts';
2
+ import { type LocateOptions } from './locate.ts';
3
+ /** How a value of the configuration is written: where it is looked for, of the namespace and the
4
+ * names of `ConfigNames`, each its default when it is not given, and the file to write. */
5
+ export type WriteOptions = LocateOptions & {
6
+ /**
7
+ * The file to write: where none holds the configuration, the one to make it in, the key of
8
+ * package.json (`package.json`) by default, or a JSON file of the names, as
9
+ * `<namespace>.config.json`; where one does, it must be that one, or the write is a
10
+ * `ConfigFileMismatchError`. Any other file is an `UnwritableConfigFileError`.
11
+ */
12
+ readonly file?: string;
13
+ };
14
+ /**
15
+ * Set `value` at `path` of the configuration of the project in `folder`: in the file in use, the
16
+ * key of package.json (the namespace by default) or a JSON file of the names
17
+ * (`<namespace>.config.json` by default); with none, in the key, added to the package.json at the
18
+ * root, by default, or in the JSON file `options.file` names, made. An object on the way that is
19
+ * not there is made. Nothing is written when the value is already so.
20
+ *
21
+ * Throws a `ConfigInCodeError` when the configuration is code, as `<namespace>.config.ts`; a
22
+ * `NoConfigFileError` when there is none, and no package.json at the root to hold it, and no JSON
23
+ * file is named; a `ConfigFileMismatchError` when the file named is not the one in use; an
24
+ * `UnwritableConfigFileError` when the file named is neither a JSON file of the names nor
25
+ * package.json; and a `ConfigPathError` when the path goes into a value that is no object or list.
26
+ */
27
+ export declare function setConfigValue(folder: string, path: ConfigPath, value: unknown, options: WriteOptions): Promise<ConfigWrite>;
28
+ /**
29
+ * Take away the value at `path` of the configuration of the project in `folder`, in the file in
30
+ * use: a JSON file of the names (`<namespace>.config.json` by default) or the key of package.json
31
+ * (the namespace by default). Nothing is written when no value is there, or no configuration:
32
+ * `changed` is false. An object it leaves empty stays. Throws a `ConfigInCodeError` when the
33
+ * configuration is code, and a `ConfigFileMismatchError` when the file named is not the one in use.
34
+ */
35
+ export declare function unsetConfigValue(folder: string, path: ConfigPath, options: WriteOptions): Promise<ConfigWrite>;