@cortexkit/common-auth 0.44.0 → 0.46.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 (55) hide show
  1. package/dist/commands/builtins.d.ts +20 -1
  2. package/dist/commands/builtins.js +28 -12
  3. package/dist/commands/index.d.ts +1 -1
  4. package/dist/commands/menu.d.ts +6 -1
  5. package/dist/commands/menu.js +1 -0
  6. package/dist/fs/file-read-cache.d.ts +3 -0
  7. package/dist/fs/file-read-cache.js +9 -5
  8. package/dist/fs/refresh-file-lock.d.ts +11 -0
  9. package/dist/fs/refresh-file-lock.js +159 -11
  10. package/dist/fs/with-lock.d.ts +2 -0
  11. package/dist/fs/with-lock.js +1 -1
  12. package/dist/routing-accessor/index.d.ts +17 -0
  13. package/dist/routing-accessor/index.js +13 -0
  14. package/dist/settings/define.d.ts +35 -0
  15. package/dist/settings/define.js +52 -0
  16. package/dist/settings/descriptors.d.ts +97 -0
  17. package/dist/settings/descriptors.js +81 -0
  18. package/dist/settings/edit.d.ts +24 -0
  19. package/dist/settings/edit.js +229 -0
  20. package/dist/settings/fs.d.ts +6 -0
  21. package/dist/settings/fs.js +19 -0
  22. package/dist/settings/handle.d.ts +30 -0
  23. package/dist/settings/handle.js +228 -0
  24. package/dist/settings/index.d.ts +10 -0
  25. package/dist/settings/index.js +7 -0
  26. package/dist/settings/lock-errors.d.ts +2 -0
  27. package/dist/settings/lock-errors.js +15 -0
  28. package/dist/settings/move.d.ts +76 -0
  29. package/dist/settings/move.js +351 -0
  30. package/dist/settings/parse.d.ts +24 -0
  31. package/dist/settings/parse.js +65 -0
  32. package/dist/settings/paths.d.ts +12 -0
  33. package/dist/settings/paths.js +48 -0
  34. package/dist/settings/refusal.d.ts +7 -0
  35. package/dist/settings/refusal.js +15 -0
  36. package/dist/settings/resolve.d.ts +15 -0
  37. package/dist/settings/resolve.js +51 -0
  38. package/dist/settings/schema.d.ts +29 -0
  39. package/dist/settings/schema.js +81 -0
  40. package/dist/settings/snapshot.d.ts +24 -0
  41. package/dist/settings/snapshot.js +150 -0
  42. package/dist/settings/update.d.ts +6 -0
  43. package/dist/settings/update.js +139 -0
  44. package/dist/settings/write.d.ts +26 -0
  45. package/dist/settings/write.js +88 -0
  46. package/dist/setup/command-error.d.ts +1 -1
  47. package/dist/setup/command-error.js +3 -2
  48. package/dist/setup/command.js +5 -1
  49. package/dist/setup/enroll.js +3 -3
  50. package/dist/setup/enrollment-access.d.ts +1 -1
  51. package/dist/setup/enrollment-access.js +13 -4
  52. package/dist/setup/types.d.ts +4 -0
  53. package/dist/tui-prefs/watcher.d.ts +3 -1
  54. package/dist/tui-prefs/watcher.js +41 -18
  55. package/package.json +5 -1
@@ -0,0 +1,351 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { basename, dirname, join, resolve } from 'node:path';
3
+ import { isDeepStrictEqual } from 'node:util';
4
+ import { ensurePrivateDirectory, PrivateFileError, } from '../fs/private-files.js';
5
+ import { LockContentionError, LockOwnershipError, lockPathFor, withLock, } from '../fs/with-lock.js';
6
+ import { LockStack, POOL_LOCK_DEFAULTS, } from '../store/refresh-lock.js';
7
+ import { validateValue } from './descriptors.js';
8
+ import { SettingsFs } from './fs.js';
9
+ import { rethrowSettingsLockError } from './lock-errors.js';
10
+ import { SettingsRefusal } from './refusal.js';
11
+ let stepHook;
12
+ /** Internal test hook, not part of the settings subpath's public exports. */
13
+ export function setSettingsMoveStepHookForTest(hook) {
14
+ stepHook = hook;
15
+ }
16
+ function emptyResult(outcome) {
17
+ return {
18
+ outcome,
19
+ unmapped: [],
20
+ differing: [],
21
+ noteFailures: [],
22
+ postPublishFailures: [],
23
+ };
24
+ }
25
+ function hasCode(error, code) {
26
+ return (error !== null &&
27
+ typeof error === 'object' &&
28
+ 'code' in error &&
29
+ error.code === code);
30
+ }
31
+ async function exists(path) {
32
+ try {
33
+ await SettingsFs.lstat(path);
34
+ return true;
35
+ }
36
+ catch (error) {
37
+ if (hasCode(error, 'ENOENT'))
38
+ return false;
39
+ throw error;
40
+ }
41
+ }
42
+ function log(options, level, message, data) {
43
+ try {
44
+ options.log[level](message, data);
45
+ }
46
+ catch {
47
+ // Diagnostics must not turn a completed publication into a failure.
48
+ }
49
+ }
50
+ function lockFailure(error, path, name) {
51
+ let original = error;
52
+ const seen = new Set();
53
+ while (original !== null &&
54
+ typeof original === 'object' &&
55
+ !seen.has(original)) {
56
+ seen.add(original);
57
+ if (original instanceof LockContentionError ||
58
+ original instanceof LockOwnershipError ||
59
+ original instanceof PrivateFileError) {
60
+ break;
61
+ }
62
+ if (!('cause' in original))
63
+ break;
64
+ original = original.cause;
65
+ }
66
+ try {
67
+ rethrowSettingsLockError(original, path, name);
68
+ }
69
+ catch (mapped) {
70
+ return {
71
+ ...emptyResult(mapped instanceof SettingsRefusal && mapped.code === 'settings-busy'
72
+ ? 'busy'
73
+ : 'failed'),
74
+ cause: error,
75
+ };
76
+ }
77
+ }
78
+ function merge(options, legacy, mapped, result) {
79
+ result.unmapped = [...mapped.unmapped];
80
+ const bySetting = new Map();
81
+ for (const entry of mapped.entries) {
82
+ const source = legacy[entry.source];
83
+ if (!Number.isInteger(entry.source) || !source?.present) {
84
+ throw new TypeError(`Move entry has no present source: ${entry.source}`);
85
+ }
86
+ const declaration = Object.hasOwn(options.definition.settings, entry.setting)
87
+ ? options.definition.settings[entry.setting]
88
+ : undefined;
89
+ const reason = !declaration
90
+ ? 'unknown-setting'
91
+ : !validateValue(declaration.value, entry.value)
92
+ ? 'invalid-value'
93
+ : undefined;
94
+ if (reason) {
95
+ result.unmapped.push({ source: entry.source, key: entry.setting, reason });
96
+ continue;
97
+ }
98
+ const entries = bySetting.get(entry.setting) ?? [];
99
+ entries.push({ ...entry, host: source.host });
100
+ bySetting.set(entry.setting, entries);
101
+ }
102
+ const document = { schema_version: 1 };
103
+ for (const [setting, declaration] of Object.entries(options.definition.settings)) {
104
+ const entries = bySetting.get(setting)?.sort((a, b) => a.source - b.source);
105
+ const primary = entries?.[0];
106
+ if (!entries || !primary)
107
+ continue;
108
+ const hosts = new Map();
109
+ if (declaration.overrides?.host) {
110
+ for (const host of ['opencode', 'pi']) {
111
+ const first = entries.find((entry) => entry.host === host);
112
+ if (first && !isDeepStrictEqual(first.value, primary.value)) {
113
+ hosts.set(host, first.value);
114
+ }
115
+ }
116
+ }
117
+ Object.defineProperty(document, setting, {
118
+ value: hosts.size
119
+ ? { default: primary.value, ...Object.fromEntries(hosts) }
120
+ : primary.value,
121
+ enumerable: true,
122
+ });
123
+ const values = entries.map((entry) => ({
124
+ source: entry.source,
125
+ host: entry.host,
126
+ value: entry.value,
127
+ }));
128
+ if (values.some(({ host, value }) => !isDeepStrictEqual(hosts.has(host) ? hosts.get(host) : primary.value, value))) {
129
+ result.differing.push({ setting, values });
130
+ log(options, 'info', `Differing legacy settings: ${setting}`, { values });
131
+ }
132
+ }
133
+ return document;
134
+ }
135
+ async function removeStaleTemps(target) {
136
+ const prefix = `${basename(target)}.move-`;
137
+ const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.tmp$/i;
138
+ for (const name of await SettingsFs.readdir(dirname(target))) {
139
+ if (name.startsWith(prefix) && uuid.test(name.slice(prefix.length))) {
140
+ await SettingsFs.unlink(join(dirname(target), name));
141
+ }
142
+ }
143
+ }
144
+ async function writeNotes(options, legacy, result) {
145
+ for (const source of legacy) {
146
+ if (!source.present)
147
+ continue;
148
+ const path = `${source.path}.MOVED_READPLEASE`;
149
+ try {
150
+ let file;
151
+ try {
152
+ file = await SettingsFs.open(path, 'wx');
153
+ }
154
+ catch (error) {
155
+ if (hasCode(error, 'EEXIST'))
156
+ continue;
157
+ throw error;
158
+ }
159
+ try {
160
+ await file.writeFile(`Settings moved to ${options.target}.\nA rollback loses changes made after the move.\n`, 'utf8');
161
+ }
162
+ finally {
163
+ await file.close();
164
+ }
165
+ }
166
+ catch (error) {
167
+ result.noteFailures.push({ path, error });
168
+ log(options, 'warn', 'Could not write settings move note', {
169
+ path,
170
+ error,
171
+ });
172
+ }
173
+ }
174
+ }
175
+ async function publish(options, legacy, document, moveLock, stack, result) {
176
+ const { target } = options;
177
+ const temp = `${target}.move-${randomUUID()}.tmp`;
178
+ let staged = false;
179
+ try {
180
+ const file = await SettingsFs.open(temp, 'wx', 0o644);
181
+ staged = true;
182
+ try {
183
+ const header = [
184
+ `// Settings moved on ${new Date().toISOString().slice(0, 10)} (UTC) from:`,
185
+ ...options.sources.map((source) => `// ${JSON.stringify(source.path)}`),
186
+ ].join('\n');
187
+ await file.writeFile(`${header}\n${JSON.stringify(document, null, 2)}\n`, 'utf8');
188
+ await file.sync();
189
+ }
190
+ finally {
191
+ await file.close();
192
+ }
193
+ await stepHook?.('staged', { target, temp });
194
+ await stepHook?.('before-publish', { target, temp });
195
+ await moveLock.assertOwned();
196
+ await stack.assertAll();
197
+ try {
198
+ await SettingsFs.link(temp, target);
199
+ }
200
+ catch (error) {
201
+ if (!hasCode(error, 'EEXIST'))
202
+ throw error;
203
+ result.outcome = 'aborted-target-appeared';
204
+ return result;
205
+ }
206
+ result.outcome = 'moved';
207
+ try {
208
+ await SettingsFs.unlink(temp);
209
+ staged = false;
210
+ }
211
+ catch (error) {
212
+ result.postPublishFailures.push({ step: 'temp-unlink', error });
213
+ log(options, 'warn', 'Settings move temp cleanup failed', { temp, error });
214
+ }
215
+ if (process.platform !== 'win32') {
216
+ try {
217
+ const folder = await SettingsFs.open(dirname(target), 'r');
218
+ try {
219
+ await folder.sync();
220
+ }
221
+ finally {
222
+ await folder.close();
223
+ }
224
+ }
225
+ catch (error) {
226
+ result.postPublishFailures.push({ step: 'directory-sync', error });
227
+ log(options, 'warn', 'Settings move directory sync failed', {
228
+ target,
229
+ error,
230
+ });
231
+ }
232
+ }
233
+ await writeNotes(options, legacy, result);
234
+ return result;
235
+ }
236
+ finally {
237
+ if (staged && result.outcome !== 'moved') {
238
+ await SettingsFs.unlink(temp).catch(() => { });
239
+ }
240
+ }
241
+ }
242
+ /** Move legacy settings without replacing an existing target or changing a source. */
243
+ export async function moveSettingsOnce(options) {
244
+ try {
245
+ if (options.separateInstall)
246
+ return emptyResult('separate-install');
247
+ if (await exists(options.target))
248
+ return emptyResult('done-already');
249
+ if (!(await options.fence()))
250
+ return emptyResult('fence-closed');
251
+ const folder = dirname(options.target);
252
+ if (process.platform === 'win32')
253
+ await ensurePrivateDirectory(folder);
254
+ else
255
+ await SettingsFs.mkdir(folder, { recursive: true, mode: 0o700 });
256
+ let settled;
257
+ try {
258
+ return await withLock(options.target, { name: 'settings-move', ...POOL_LOCK_DEFAULTS }, async (moveLock) => {
259
+ const stack = new LockStack(POOL_LOCK_DEFAULTS, {});
260
+ try {
261
+ const skipped = new Set();
262
+ const seen = new Map();
263
+ for (const source of options.sources) {
264
+ for (const spec of source.locks) {
265
+ const path = resolve(spec.path);
266
+ const names = seen.get(path) ?? new Set();
267
+ if (names.has(spec.name))
268
+ continue;
269
+ names.add(spec.name);
270
+ seen.set(path, names);
271
+ const lockFolder = dirname(lockPathFor(spec.path, spec.name));
272
+ if (!(await exists(lockFolder))) {
273
+ skipped.add(lockFolder);
274
+ continue;
275
+ }
276
+ try {
277
+ await stack.acquire(spec);
278
+ }
279
+ catch (error) {
280
+ settled = lockFailure(error, spec.path, spec.name);
281
+ return settled;
282
+ }
283
+ }
284
+ }
285
+ if (await exists(options.target)) {
286
+ settled = emptyResult('done-already');
287
+ }
288
+ else if (!(await options.fence())) {
289
+ settled = emptyResult('fence-closed');
290
+ }
291
+ else {
292
+ await removeStaleTemps(options.target);
293
+ await stepHook?.('locked', { target: options.target });
294
+ const legacy = [];
295
+ for (const source of options.sources) {
296
+ let text;
297
+ try {
298
+ text = await SettingsFs.readFile(source.path, 'utf8');
299
+ }
300
+ catch (error) {
301
+ if (!hasCode(error, 'ENOENT'))
302
+ throw error;
303
+ legacy.push({
304
+ host: source.host,
305
+ path: source.path,
306
+ present: false,
307
+ });
308
+ continue;
309
+ }
310
+ legacy.push({
311
+ host: source.host,
312
+ path: source.path,
313
+ present: true,
314
+ value: source.read(text),
315
+ });
316
+ }
317
+ const mapped = await options.map(legacy);
318
+ for (const path of skipped) {
319
+ if (await exists(path)) {
320
+ settled = emptyResult('busy');
321
+ return settled;
322
+ }
323
+ }
324
+ const result = emptyResult('failed');
325
+ const document = merge(options, legacy, mapped, result);
326
+ settled = await publish(options, legacy, document, moveLock, stack, result);
327
+ }
328
+ }
329
+ catch (cause) {
330
+ settled = { ...emptyResult('failed'), cause };
331
+ }
332
+ finally {
333
+ await stack.releaseAll();
334
+ }
335
+ return settled;
336
+ });
337
+ }
338
+ catch (error) {
339
+ if (!settled)
340
+ return lockFailure(error, options.target, 'settings-move');
341
+ if (settled.outcome === 'moved') {
342
+ settled.postPublishFailures.push({ step: 'lock-release', error });
343
+ }
344
+ log(options, 'warn', 'Settings move lock release failed', { error });
345
+ return settled;
346
+ }
347
+ }
348
+ catch (cause) {
349
+ return { ...emptyResult('failed'), cause };
350
+ }
351
+ }
@@ -0,0 +1,24 @@
1
+ import { type Node, type ParseError } from 'jsonc-parser';
2
+ interface ParsedText {
3
+ /** Text without the optional leading BOM; tree offsets refer to this text. */
4
+ text: string;
5
+ hasBom: boolean;
6
+ tree: Node | undefined;
7
+ }
8
+ export interface ParsedSettings extends ParsedText {
9
+ parseable: true;
10
+ value: Record<string, unknown>;
11
+ duplicateKeyPaths: string[][];
12
+ hasDuplicates: boolean;
13
+ }
14
+ export interface UnparseableSettings extends ParsedText {
15
+ parseable: false;
16
+ errors: ParseError[];
17
+ }
18
+ export type SettingsParseResult = ParsedSettings | UnparseableSettings;
19
+ /** Define own data properties so JSON keys never invoke prototype setters. */
20
+ export declare function defineSettingsKey(target: Record<string, unknown>, key: string, value: unknown): void;
21
+ /** Convert in document order, retaining the last occurrence of a repeated key. */
22
+ export declare function settingsValueFromTree(node: Node, onDuplicate?: (keyPath: string[]) => void, keyPath?: string[]): unknown;
23
+ export declare function parseSettings(source: string): SettingsParseResult;
24
+ export {};
@@ -0,0 +1,65 @@
1
+ import { parseTree } from 'jsonc-parser';
2
+ /** Define own data properties so JSON keys never invoke prototype setters. */
3
+ export function defineSettingsKey(target, key, value) {
4
+ Object.defineProperty(target, key, {
5
+ value,
6
+ enumerable: true,
7
+ writable: true,
8
+ configurable: true,
9
+ });
10
+ }
11
+ /** Convert in document order, retaining the last occurrence of a repeated key. */
12
+ export function settingsValueFromTree(node, onDuplicate = () => { }, keyPath = []) {
13
+ if (node.type === 'object') {
14
+ const value = {};
15
+ for (const property of node.children ?? []) {
16
+ const [keyNode, valueNode] = property.children ?? [];
17
+ if (!keyNode || !valueNode)
18
+ continue;
19
+ const key = keyNode.value;
20
+ const path = [...keyPath, key];
21
+ if (Object.hasOwn(value, key))
22
+ onDuplicate(path);
23
+ defineSettingsKey(value, key, settingsValueFromTree(valueNode, onDuplicate, path));
24
+ }
25
+ return value;
26
+ }
27
+ if (node.type === 'array') {
28
+ return (node.children ?? []).map((child, index) => settingsValueFromTree(child, onDuplicate, [...keyPath, String(index)]));
29
+ }
30
+ return node.value;
31
+ }
32
+ export function parseSettings(source) {
33
+ const hasBom = source.startsWith('\uFEFF');
34
+ const text = hasBom ? source.slice(1) : source;
35
+ // Do not use trim(): it would silently discard a second or misplaced BOM.
36
+ if (/^[\x20\t\r\n]*$/.test(text)) {
37
+ return {
38
+ parseable: true,
39
+ text,
40
+ hasBom,
41
+ tree: undefined,
42
+ value: {},
43
+ duplicateKeyPaths: [],
44
+ hasDuplicates: false,
45
+ };
46
+ }
47
+ const errors = [];
48
+ const tree = parseTree(text, errors, { allowTrailingComma: true });
49
+ if (errors.length || tree?.type !== 'object') {
50
+ return { parseable: false, text, hasBom, tree, errors };
51
+ }
52
+ const paths = new Map();
53
+ const value = settingsValueFromTree(tree, (path) => {
54
+ paths.set(JSON.stringify(path), path);
55
+ });
56
+ return {
57
+ parseable: true,
58
+ text,
59
+ hasBom,
60
+ tree,
61
+ value,
62
+ duplicateKeyPaths: [...paths.values()],
63
+ hasDuplicates: paths.size > 0,
64
+ };
65
+ }
@@ -0,0 +1,12 @@
1
+ interface ConfigDirOptions {
2
+ env: Readonly<Record<string, string | undefined>>;
3
+ platform: NodeJS.Platform;
4
+ homedir: string;
5
+ }
6
+ export declare function isAbsoluteForPlatform(path: string, platform: NodeJS.Platform): boolean;
7
+ export declare function cortexkitConfigDir({ env, platform, homedir, }: ConfigDirOptions): string;
8
+ export declare function settingsFilePath({ plugin, override, ...options }: ConfigDirOptions & {
9
+ plugin: string;
10
+ override?: string;
11
+ }): string;
12
+ export {};
@@ -0,0 +1,48 @@
1
+ import { posix, win32 } from 'node:path';
2
+ import { SettingsRefusal } from './refusal.js';
3
+ export function isAbsoluteForPlatform(path, platform) {
4
+ if (platform !== 'win32')
5
+ return path.startsWith('/');
6
+ // Verbatim and device prefixes have an implicit root in Rust's path model.
7
+ if (path.startsWith('\\\\?\\') || path.startsWith('\\\\.\\'))
8
+ return true;
9
+ if (/^[a-zA-Z]:[\\/]/.test(path))
10
+ return true;
11
+ // Ordinary UNC prefixes accept either separator, but need server and share.
12
+ return /^[\\/]{2}[^\\/]+[\\/][^\\/]+/.test(path);
13
+ }
14
+ export function cortexkitConfigDir({ env, platform, homedir, }) {
15
+ const paths = platform === 'win32' ? win32 : posix;
16
+ const absolute = (value) => value !== undefined && isAbsoluteForPlatform(value, platform);
17
+ let base;
18
+ if (absolute(env.XDG_CONFIG_HOME)) {
19
+ base = env.XDG_CONFIG_HOME;
20
+ }
21
+ else if (platform === 'win32' && absolute(env.APPDATA)) {
22
+ base = env.APPDATA;
23
+ }
24
+ else {
25
+ let home = platform === 'win32' ? env.USERPROFILE : env.HOME;
26
+ if (!absolute(home)) {
27
+ // commons cortexkit-paths' dirs.rs reports no directory when every home
28
+ // and config variable is unusable. Accepting the caller's absolute
29
+ // homedir instead is the one deliberate addition to that Rust rule.
30
+ if (!absolute(homedir)) {
31
+ throw new SettingsRefusal('settings-unavailable', 'No absolute home or config directory is available');
32
+ }
33
+ home = homedir;
34
+ }
35
+ base =
36
+ platform === 'win32'
37
+ ? paths.join(paths.join(home, 'AppData'), 'Roaming')
38
+ : paths.join(home, '.config');
39
+ }
40
+ return paths.join(base, 'cortexkit');
41
+ }
42
+ export function settingsFilePath({ plugin, override, ...options }) {
43
+ if (override && isAbsoluteForPlatform(override, options.platform)) {
44
+ return override;
45
+ }
46
+ const paths = options.platform === 'win32' ? win32 : posix;
47
+ return paths.join(cortexkitConfigDir(options), `${plugin}.jsonc`);
48
+ }
@@ -0,0 +1,7 @@
1
+ export declare const SETTINGS_REFUSAL_CODES: readonly ["settings-unparseable", "settings-newer-version", "settings-invalid-value", "settings-busy", "settings-unavailable"];
2
+ export type SettingsRefusalCode = (typeof SETTINGS_REFUSAL_CODES)[number];
3
+ export declare class SettingsRefusal extends Error {
4
+ readonly code: SettingsRefusalCode;
5
+ readonly name = "SettingsRefusal";
6
+ constructor(code: SettingsRefusalCode, message: string, options?: ErrorOptions);
7
+ }
@@ -0,0 +1,15 @@
1
+ export const SETTINGS_REFUSAL_CODES = Object.freeze([
2
+ 'settings-unparseable',
3
+ 'settings-newer-version',
4
+ 'settings-invalid-value',
5
+ 'settings-busy',
6
+ 'settings-unavailable',
7
+ ]);
8
+ export class SettingsRefusal extends Error {
9
+ code;
10
+ name = 'SettingsRefusal';
11
+ constructor(code, message, options) {
12
+ super(message, options);
13
+ this.code = code;
14
+ }
15
+ }
@@ -0,0 +1,15 @@
1
+ import type { SettingDeclaration, SettingsDefinition } from './define.js';
2
+ import { type ValueOf } from './descriptors.js';
3
+ import type { SettingsSnapshot } from './snapshot.js';
4
+ export interface GetOptions {
5
+ readonly host: string;
6
+ readonly model?: string;
7
+ readonly project?: string;
8
+ }
9
+ /** The caller selects the project snapshot for the requested project, if any. */
10
+ export interface ResolutionSnapshots {
11
+ readonly user?: SettingsSnapshot;
12
+ readonly project?: SettingsSnapshot;
13
+ }
14
+ /** Resolve sanitized snapshots without reading files or adding report entries. */
15
+ export declare function resolveSetting<S extends Readonly<Record<string, SettingDeclaration>>, K extends keyof S & string>(definition: SettingsDefinition<S>, name: K, options: GetOptions, snapshots?: ResolutionSnapshots): ValueOf<S[K]['value']>;
@@ -0,0 +1,51 @@
1
+ import { isJsonObject, } from './descriptors.js';
2
+ import { defineSettingsKey } from './parse.js';
3
+ function valueAtLevel(declaration, name, snapshot, options) {
4
+ if (!snapshot || !Object.hasOwn(snapshot.settings, name))
5
+ return undefined;
6
+ const value = snapshot.settings[name];
7
+ if (declaration.overrides === undefined || !isJsonObject(value))
8
+ return value;
9
+ const { model, host } = options;
10
+ if (declaration.overrides.model &&
11
+ model !== undefined &&
12
+ model !== 'default' &&
13
+ model !== 'opencode' &&
14
+ model !== 'pi' &&
15
+ Object.hasOwn(value, model)) {
16
+ return value[model];
17
+ }
18
+ if (declaration.overrides.host &&
19
+ (host === 'opencode' || host === 'pi') &&
20
+ Object.hasOwn(value, host)) {
21
+ return value[host];
22
+ }
23
+ return Object.hasOwn(value, 'default') ? value.default : undefined;
24
+ }
25
+ /** Snapshot validation has already removed unusable values and unknown fields. */
26
+ function resolveValue(descriptor, levels) {
27
+ if (descriptor.kind !== 'object') {
28
+ return levels.find((value) => value !== undefined);
29
+ }
30
+ const result = {};
31
+ for (const [key, field] of Object.entries(descriptor.fields)) {
32
+ const candidates = levels.map((value) => isJsonObject(value) && Object.hasOwn(value, key) ? value[key] : undefined);
33
+ defineSettingsKey(result, key, resolveValue(field, candidates));
34
+ }
35
+ return result;
36
+ }
37
+ /** Resolve sanitized snapshots without reading files or adding report entries. */
38
+ export function resolveSetting(definition, name, options, snapshots = {}) {
39
+ if (!Object.hasOwn(definition.settings, name)) {
40
+ throw new TypeError(`Undeclared setting: ${name}`);
41
+ }
42
+ const declaration = definition.settings[name];
43
+ const levels = [];
44
+ if (declaration.project === 'allowed' && options.project !== undefined) {
45
+ levels.push(valueAtLevel(declaration, name, snapshots.project, options));
46
+ }
47
+ levels.push(valueAtLevel(declaration, name, snapshots.user, options));
48
+ levels.push(declaration.default);
49
+ // Clone even a whole-list or whole-record winner so callers cannot mutate it.
50
+ return structuredClone(resolveValue(declaration.value, levels));
51
+ }
@@ -0,0 +1,29 @@
1
+ import type { SettingsDefinition } from './define.js';
2
+ interface JsonSchema {
3
+ type?: 'boolean' | 'integer' | 'number' | 'string' | 'array' | 'object';
4
+ minimum?: number;
5
+ maximum?: number;
6
+ enum?: string[];
7
+ items?: JsonSchema;
8
+ properties?: Record<string, JsonSchema>;
9
+ additionalProperties?: boolean | JsonSchema;
10
+ required?: string[];
11
+ anyOf?: JsonSchema[];
12
+ propertyNames?: {
13
+ not: {
14
+ enum: string[];
15
+ };
16
+ };
17
+ }
18
+ /**
19
+ * Generate the plugin's JSON Schema deterministically from its settings definition.
20
+ * Plugins ship the generated schema and check their parsed shipped file with:
21
+ * `expect(shippedSchema).toEqual(settingsJsonSchema(definition))`.
22
+ */
23
+ export declare function settingsJsonSchema(definition: SettingsDefinition): {
24
+ $schema: string;
25
+ type: 'object';
26
+ properties: Record<string, JsonSchema>;
27
+ additionalProperties: false;
28
+ };
29
+ export {};