@acryldev/app-settings 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +14 -2
- package/index.ts +270 -0
- package/lib/index.js +231 -0
- package/lib/index.js.map +1 -0
- package/lib/types/index.d.ts +80 -0
- package/lib/types/merge.d.ts +16 -0
- package/lib/types/tsdown.config.d.ts +2 -0
- package/merge.ts +79 -0
- package/package.json +42 -3
- package/plugin.json +16 -0
- package/test/settings.test.ts +99 -0
- package/tsconfig.json +21 -0
- package/tsdown.config.ts +23 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 acrylblends
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,15 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @acryldev/app-settings
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Validated settings per namespace in one YAML file in the app's home: defaults, base and stored layers, watch, update.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npm install @acryldev/app-settings
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
It is a Cordis plugin: its peer dependency is `@deepseek-ai/cordis`, and an app registers it as a row of its `blend.yaml`.
|
|
12
|
+
|
|
13
|
+
## Source and license
|
|
14
|
+
|
|
15
|
+
Part of [ACRYL](https://github.com/acryldev/acryl): [`plugins/app-settings`](https://github.com/acryldev/acryl/tree/main/plugins/app-settings). MIT license.
|
package/index.ts
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The settings service (`ctx.settings`): per-namespace sections kept in one YAML file in the app's home.
|
|
3
|
+
*
|
|
4
|
+
* Extracted from ACRYL (`plugins/settings`). Plugins register a namespace with a schemastery schema and read the resolved value,
|
|
5
|
+
* which layers schema defaults, the registrant's `base`, and the stored section, in that order. Writes are validated, atomic (write a
|
|
6
|
+
* temporary file, then rename) and run one at a time in commit order; watchers see them in that order; an event announces each change.
|
|
7
|
+
*/
|
|
8
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
9
|
+
import { dirname, join } from 'node:path'
|
|
10
|
+
import type {} from '@acryldev/instance'
|
|
11
|
+
import { type Context, Service } from '@deepseek-ai/cordis'
|
|
12
|
+
import z from '@deepseek-ai/schemastery'
|
|
13
|
+
import { parseDocument, stringify } from 'yaml'
|
|
14
|
+
import { cloneJsonShaped, deepEqualJson, isPlainObject, mergeLayers } from './merge.ts'
|
|
15
|
+
|
|
16
|
+
const NAMESPACE_PATTERN = /^[a-z][a-z0-9-]*$/
|
|
17
|
+
export const DEFAULT_FILENAME = 'settings.yaml'
|
|
18
|
+
|
|
19
|
+
/** When a namespace's changes take effect for its owner. */
|
|
20
|
+
export type SettingsApplies = 'live' | 'restart'
|
|
21
|
+
|
|
22
|
+
export interface SettingsRegisterOptions<T> {
|
|
23
|
+
/** Values resolved below the stored layer (for example, what the app's composition chose). */
|
|
24
|
+
base?: Partial<T>
|
|
25
|
+
/** When the owner applies a change; shown to settings screens. Defaults to `live`. */
|
|
26
|
+
applies?: SettingsApplies
|
|
27
|
+
/** Reject a resolved value the schema cannot express as invalid; a throw refuses the write that produced it. */
|
|
28
|
+
validate?: (value: T) => void
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** One registered namespace, as a settings screen sees it. */
|
|
32
|
+
export interface SettingsDescriptor {
|
|
33
|
+
readonly namespace: string
|
|
34
|
+
/** The schemastery schema, serialized. */
|
|
35
|
+
readonly schema: unknown
|
|
36
|
+
readonly value: unknown
|
|
37
|
+
/** Bumps on every committed write. */
|
|
38
|
+
readonly revision: number
|
|
39
|
+
readonly applies: SettingsApplies
|
|
40
|
+
/** The stored section, when there is one. */
|
|
41
|
+
readonly user?: unknown
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The owner's handle on one namespace. */
|
|
45
|
+
export interface SettingsScope<T> {
|
|
46
|
+
/** Current resolved value: schema defaults, then `base`, then the stored section. */
|
|
47
|
+
get(): T
|
|
48
|
+
/** Observe committed changes; callbacks run one at a time in commit order. Returns the function that stops watching. */
|
|
49
|
+
watch(callback: (next: T, prev: T) => void | Promise<void>): () => void
|
|
50
|
+
/** Merge a patch into the stored section and persist it. */
|
|
51
|
+
update(patch: object): Promise<void>
|
|
52
|
+
/** Replace the stored section; `replace({})` resets every key to its base or default. */
|
|
53
|
+
replace(section: object): Promise<void>
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface SettingsConfig {
|
|
57
|
+
/** Absolute path of the YAML file; empty or absent means `<app home>/settings.yaml`. */
|
|
58
|
+
filename?: string
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
declare module '@deepseek-ai/cordis' {
|
|
62
|
+
interface Context {
|
|
63
|
+
settings: Settings
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
interface Events {
|
|
67
|
+
/** A committed change to one namespace's resolved value, after the file was written; never for an equal value. */
|
|
68
|
+
'settings/updated'(namespace: string, next: unknown, prev: unknown): void
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
interface Entry {
|
|
73
|
+
readonly namespace: string
|
|
74
|
+
readonly schema: z<unknown>
|
|
75
|
+
readonly options: SettingsRegisterOptions<unknown>
|
|
76
|
+
resolved: unknown
|
|
77
|
+
revision: number
|
|
78
|
+
readonly watchers: Set<Watcher>
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
interface Watcher {
|
|
82
|
+
readonly callback: (next: unknown, prev: unknown) => void | Promise<void>
|
|
83
|
+
active: boolean
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function assertNamespace(value: string): void {
|
|
87
|
+
if (!NAMESPACE_PATTERN.test(value))
|
|
88
|
+
throw new TypeError(`settings: namespace "${value}" must match ${String(NAMESPACE_PATTERN)}`)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function readDocument(filename: string): Record<string, unknown> {
|
|
92
|
+
if (!existsSync(filename)) return {}
|
|
93
|
+
const parsed = parseDocument(readFileSync(filename, 'utf8'), { prettyErrors: true })
|
|
94
|
+
if (parsed.errors.length > 0) {
|
|
95
|
+
throw new Error(
|
|
96
|
+
`settings: invalid settings file ${filename}: ${parsed.errors.map((error) => error.message).join('; ')}`,
|
|
97
|
+
)
|
|
98
|
+
}
|
|
99
|
+
const value: unknown = parsed.toJS() ?? {}
|
|
100
|
+
if (!isPlainObject(value))
|
|
101
|
+
throw new Error(`settings: ${filename} must be a map of namespace sections`)
|
|
102
|
+
return value
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** The service. One instance serves one app home. */
|
|
106
|
+
export class Settings extends Service {
|
|
107
|
+
readonly filename: string
|
|
108
|
+
private document: Record<string, unknown>
|
|
109
|
+
private readonly entries = new Map<string, Entry>()
|
|
110
|
+
/** Writes and watcher notifications run one at a time, in commit order. */
|
|
111
|
+
private tail: Promise<void> = Promise.resolve()
|
|
112
|
+
private disposed = false
|
|
113
|
+
|
|
114
|
+
constructor(ctx: Context, config: SettingsConfig = {}) {
|
|
115
|
+
super(ctx, 'settings')
|
|
116
|
+
this.filename = config.filename ? config.filename : join(ctx.appInstance.home, DEFAULT_FILENAME)
|
|
117
|
+
this.document = readDocument(this.filename)
|
|
118
|
+
ctx.effect(
|
|
119
|
+
() => async () => {
|
|
120
|
+
this.disposed = true
|
|
121
|
+
await this.tail
|
|
122
|
+
},
|
|
123
|
+
'settings: settle pending writes',
|
|
124
|
+
)
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Register a namespace and return its handle. A stored section that fails the schema rejects the registration. */
|
|
128
|
+
register<T>(
|
|
129
|
+
namespace: string,
|
|
130
|
+
schema: z<T>,
|
|
131
|
+
options: SettingsRegisterOptions<T> = {},
|
|
132
|
+
): SettingsScope<T> {
|
|
133
|
+
assertNamespace(namespace)
|
|
134
|
+
if (this.entries.has(namespace))
|
|
135
|
+
throw new Error(`settings: namespace "${namespace}" is already registered`)
|
|
136
|
+
const entry: Entry = {
|
|
137
|
+
namespace,
|
|
138
|
+
schema: schema as z<unknown>,
|
|
139
|
+
options: options as SettingsRegisterOptions<unknown>,
|
|
140
|
+
resolved: undefined,
|
|
141
|
+
revision: 0,
|
|
142
|
+
watchers: new Set(),
|
|
143
|
+
}
|
|
144
|
+
entry.resolved = this.resolve(entry, this.section(namespace))
|
|
145
|
+
this.entries.set(namespace, entry)
|
|
146
|
+
this.ctx.effect(
|
|
147
|
+
() => () => void this.entries.delete(namespace),
|
|
148
|
+
`settings: namespace ${namespace}`,
|
|
149
|
+
)
|
|
150
|
+
return this.scopeFor<T>(entry)
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** The resolved value of a registered namespace, or `undefined` when nobody registered it. */
|
|
154
|
+
get(namespace: string): unknown {
|
|
155
|
+
return this.entries.get(namespace)?.resolved
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Merge a patch into a namespace by name (for a settings route that never held the scope). An unregistered namespace is refused. */
|
|
159
|
+
update(namespace: string, patch: Readonly<Record<string, unknown>>): Promise<void> {
|
|
160
|
+
const entry = this.entries.get(namespace)
|
|
161
|
+
if (entry === undefined)
|
|
162
|
+
return Promise.reject(new Error(`settings: namespace "${namespace}" is not registered`))
|
|
163
|
+
return this.commit(entry, (current) => mergeLayers(current, cloneJsonShaped({ ...patch })))
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Every registered namespace, for settings screens. */
|
|
167
|
+
describe(): SettingsDescriptor[] {
|
|
168
|
+
return [...this.entries.values()].map((entry) => {
|
|
169
|
+
const stored = this.document[entry.namespace]
|
|
170
|
+
return {
|
|
171
|
+
namespace: entry.namespace,
|
|
172
|
+
schema: entry.schema.toJSON(),
|
|
173
|
+
value: entry.resolved,
|
|
174
|
+
revision: entry.revision,
|
|
175
|
+
applies: entry.options.applies ?? 'live',
|
|
176
|
+
...(stored === undefined ? {} : { user: structuredClone(stored) }),
|
|
177
|
+
}
|
|
178
|
+
})
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
private section(namespace: string): Record<string, unknown> {
|
|
182
|
+
const stored = this.document[namespace]
|
|
183
|
+
if (stored === undefined) return {}
|
|
184
|
+
if (!isPlainObject(stored))
|
|
185
|
+
throw new Error(`settings: section "${namespace}" in ${this.filename} must be a map`)
|
|
186
|
+
return stored
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
private resolve(entry: Entry, user: Record<string, unknown>): unknown {
|
|
190
|
+
const base = (entry.options.base ?? {}) as Record<string, unknown>
|
|
191
|
+
const value = entry.schema(mergeLayers(base, user))
|
|
192
|
+
entry.options.validate?.(value)
|
|
193
|
+
return value
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
private scopeFor<T>(entry: Entry): SettingsScope<T> {
|
|
197
|
+
return {
|
|
198
|
+
get: () => entry.resolved as T,
|
|
199
|
+
watch: (callback) => {
|
|
200
|
+
const watcher: Watcher = { callback: callback as Watcher['callback'], active: true }
|
|
201
|
+
entry.watchers.add(watcher)
|
|
202
|
+
return () => {
|
|
203
|
+
watcher.active = false
|
|
204
|
+
entry.watchers.delete(watcher)
|
|
205
|
+
}
|
|
206
|
+
},
|
|
207
|
+
update: (patch) =>
|
|
208
|
+
this.commit(entry, (current) =>
|
|
209
|
+
mergeLayers(current, cloneJsonShaped(patch as Record<string, unknown>)),
|
|
210
|
+
),
|
|
211
|
+
replace: (section) =>
|
|
212
|
+
this.commit(entry, () => cloneJsonShaped(section as Record<string, unknown>)),
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** One write: compute, validate, persist atomically, then notify. A refused write changes nothing. */
|
|
217
|
+
private commit(
|
|
218
|
+
entry: Entry,
|
|
219
|
+
next: (current: Record<string, unknown>) => Record<string, unknown>,
|
|
220
|
+
): Promise<void> {
|
|
221
|
+
const run = async (): Promise<void> => {
|
|
222
|
+
if (this.disposed) throw new Error('settings: the service is disposed')
|
|
223
|
+
const nextSection = next(this.section(entry.namespace))
|
|
224
|
+
const nextValue = this.resolve(entry, nextSection)
|
|
225
|
+
const prevValue = entry.resolved
|
|
226
|
+
const nextDocument = { ...this.document, [entry.namespace]: nextSection }
|
|
227
|
+
if (Object.keys(nextSection).length === 0) delete nextDocument[entry.namespace]
|
|
228
|
+
this.persist(nextDocument)
|
|
229
|
+
this.document = nextDocument
|
|
230
|
+
entry.revision += 1
|
|
231
|
+
entry.resolved = nextValue
|
|
232
|
+
if (deepEqualJson(prevValue, nextValue)) return
|
|
233
|
+
this.ctx.emit('settings/updated', entry.namespace, nextValue, prevValue)
|
|
234
|
+
for (const watcher of [...entry.watchers]) {
|
|
235
|
+
if (!watcher.active) continue
|
|
236
|
+
try {
|
|
237
|
+
await watcher.callback(nextValue, prevValue)
|
|
238
|
+
} catch (cause) {
|
|
239
|
+
this.ctx.logger?.error?.(
|
|
240
|
+
`settings: watcher for "${entry.namespace}" failed: ${cause instanceof Error ? cause.message : String(cause)}`,
|
|
241
|
+
)
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
const result = this.tail.then(run, run)
|
|
246
|
+
this.tail = result.then(
|
|
247
|
+
() => undefined,
|
|
248
|
+
() => undefined,
|
|
249
|
+
)
|
|
250
|
+
return result
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
private persist(document: Record<string, unknown>): void {
|
|
254
|
+
mkdirSync(dirname(this.filename), { recursive: true })
|
|
255
|
+
const temporary = `${this.filename}.${String(process.pid)}.tmp`
|
|
256
|
+
writeFileSync(temporary, stringify(document), { mode: 0o600 })
|
|
257
|
+
renameSync(temporary, this.filename)
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** The plugin: mount it after `instance`. */
|
|
262
|
+
export const settings = {
|
|
263
|
+
name: 'settings',
|
|
264
|
+
inject: ['appInstance'],
|
|
265
|
+
apply(ctx: Context, config: SettingsConfig) {
|
|
266
|
+
new Settings(ctx, config ?? {})
|
|
267
|
+
},
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
export { z }
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { Service } from "@deepseek-ai/cordis";
|
|
4
|
+
import z from "@deepseek-ai/schemastery";
|
|
5
|
+
import { parseDocument, stringify } from "yaml";
|
|
6
|
+
//#region merge.ts
|
|
7
|
+
/** Pure helpers for layering a user section over a base and for detaching JSON data. */
|
|
8
|
+
/** Whether a value is a plain data object (not an array, null, or class instance). */
|
|
9
|
+
function isPlainObject(value) {
|
|
10
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
11
|
+
const proto = Object.getPrototypeOf(value);
|
|
12
|
+
return proto === Object.prototype || proto === null;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Deep-merge `patch` over `base`: plain objects merge key by key, every other value (arrays included) replaces,
|
|
16
|
+
* and `undefined` entries in the patch are skipped.
|
|
17
|
+
*/
|
|
18
|
+
function mergeLayers(base, patch) {
|
|
19
|
+
const merged = { ...base };
|
|
20
|
+
for (const [key, value] of Object.entries(patch)) {
|
|
21
|
+
if (value === void 0) continue;
|
|
22
|
+
const current = merged[key];
|
|
23
|
+
merged[key] = isPlainObject(current) && isPlainObject(value) ? mergeLayers(current, value) : value;
|
|
24
|
+
}
|
|
25
|
+
return merged;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Detach one write input and reject anything YAML would distort on a reload round trip: only plain objects, arrays,
|
|
29
|
+
* strings, finite numbers, booleans and `null` pass.
|
|
30
|
+
* @throws TypeError naming the `$`-rooted path of the first rejected value.
|
|
31
|
+
*/
|
|
32
|
+
function cloneJsonShaped(root) {
|
|
33
|
+
const visiting = /* @__PURE__ */ new WeakSet();
|
|
34
|
+
const clone = (value, path) => {
|
|
35
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return value;
|
|
36
|
+
if (typeof value === "number") {
|
|
37
|
+
if (!Number.isFinite(value)) throw new TypeError(`settings: ${path} is a non-finite number`);
|
|
38
|
+
return value;
|
|
39
|
+
}
|
|
40
|
+
if (Array.isArray(value)) {
|
|
41
|
+
if (visiting.has(value)) throw new TypeError(`settings: ${path} is a circular reference`);
|
|
42
|
+
visiting.add(value);
|
|
43
|
+
const entries = value.map((entry, index) => clone(entry, `${path}[${String(index)}]`));
|
|
44
|
+
visiting.delete(value);
|
|
45
|
+
return entries;
|
|
46
|
+
}
|
|
47
|
+
if (isPlainObject(value)) {
|
|
48
|
+
if (visiting.has(value)) throw new TypeError(`settings: ${path} is a circular reference`);
|
|
49
|
+
visiting.add(value);
|
|
50
|
+
const out = {};
|
|
51
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
52
|
+
if (entry === void 0) continue;
|
|
53
|
+
out[key] = clone(entry, `${path}.${key}`);
|
|
54
|
+
}
|
|
55
|
+
visiting.delete(value);
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
throw new TypeError(`settings: ${path} is ${value === void 0 ? "undefined" : `a ${typeof value}`}, which cannot be stored`);
|
|
59
|
+
};
|
|
60
|
+
return clone(root, "$");
|
|
61
|
+
}
|
|
62
|
+
/** Structural JSON equality for two detached values. */
|
|
63
|
+
function deepEqualJson(a, b) {
|
|
64
|
+
if (a === b) return true;
|
|
65
|
+
if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((entry, index) => deepEqualJson(entry, b[index]));
|
|
66
|
+
if (isPlainObject(a) && isPlainObject(b)) {
|
|
67
|
+
const keys = Object.keys(a);
|
|
68
|
+
return keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && deepEqualJson(a[key], b[key]));
|
|
69
|
+
}
|
|
70
|
+
return false;
|
|
71
|
+
}
|
|
72
|
+
//#endregion
|
|
73
|
+
//#region index.ts
|
|
74
|
+
/**
|
|
75
|
+
* The settings service (`ctx.settings`): per-namespace sections kept in one YAML file in the app's home.
|
|
76
|
+
*
|
|
77
|
+
* Extracted from ACRYL (`plugins/settings`). Plugins register a namespace with a schemastery schema and read the resolved value,
|
|
78
|
+
* which layers schema defaults, the registrant's `base`, and the stored section, in that order. Writes are validated, atomic (write a
|
|
79
|
+
* temporary file, then rename) and run one at a time in commit order; watchers see them in that order; an event announces each change.
|
|
80
|
+
*/
|
|
81
|
+
const NAMESPACE_PATTERN = /^[a-z][a-z0-9-]*$/;
|
|
82
|
+
const DEFAULT_FILENAME = "settings.yaml";
|
|
83
|
+
function assertNamespace(value) {
|
|
84
|
+
if (!NAMESPACE_PATTERN.test(value)) throw new TypeError(`settings: namespace "${value}" must match ${String(NAMESPACE_PATTERN)}`);
|
|
85
|
+
}
|
|
86
|
+
function readDocument(filename) {
|
|
87
|
+
if (!existsSync(filename)) return {};
|
|
88
|
+
const parsed = parseDocument(readFileSync(filename, "utf8"), { prettyErrors: true });
|
|
89
|
+
if (parsed.errors.length > 0) throw new Error(`settings: invalid settings file ${filename}: ${parsed.errors.map((error) => error.message).join("; ")}`);
|
|
90
|
+
const value = parsed.toJS() ?? {};
|
|
91
|
+
if (!isPlainObject(value)) throw new Error(`settings: ${filename} must be a map of namespace sections`);
|
|
92
|
+
return value;
|
|
93
|
+
}
|
|
94
|
+
/** The service. One instance serves one app home. */
|
|
95
|
+
var Settings = class extends Service {
|
|
96
|
+
filename;
|
|
97
|
+
document;
|
|
98
|
+
entries = /* @__PURE__ */ new Map();
|
|
99
|
+
/** Writes and watcher notifications run one at a time, in commit order. */
|
|
100
|
+
tail = Promise.resolve();
|
|
101
|
+
disposed = false;
|
|
102
|
+
constructor(ctx, config = {}) {
|
|
103
|
+
super(ctx, "settings");
|
|
104
|
+
this.filename = config.filename ? config.filename : join(ctx.appInstance.home, DEFAULT_FILENAME);
|
|
105
|
+
this.document = readDocument(this.filename);
|
|
106
|
+
ctx.effect(() => async () => {
|
|
107
|
+
this.disposed = true;
|
|
108
|
+
await this.tail;
|
|
109
|
+
}, "settings: settle pending writes");
|
|
110
|
+
}
|
|
111
|
+
/** Register a namespace and return its handle. A stored section that fails the schema rejects the registration. */
|
|
112
|
+
register(namespace, schema, options = {}) {
|
|
113
|
+
assertNamespace(namespace);
|
|
114
|
+
if (this.entries.has(namespace)) throw new Error(`settings: namespace "${namespace}" is already registered`);
|
|
115
|
+
const entry = {
|
|
116
|
+
namespace,
|
|
117
|
+
schema,
|
|
118
|
+
options,
|
|
119
|
+
resolved: void 0,
|
|
120
|
+
revision: 0,
|
|
121
|
+
watchers: /* @__PURE__ */ new Set()
|
|
122
|
+
};
|
|
123
|
+
entry.resolved = this.resolve(entry, this.section(namespace));
|
|
124
|
+
this.entries.set(namespace, entry);
|
|
125
|
+
this.ctx.effect(() => () => void this.entries.delete(namespace), `settings: namespace ${namespace}`);
|
|
126
|
+
return this.scopeFor(entry);
|
|
127
|
+
}
|
|
128
|
+
/** The resolved value of a registered namespace, or `undefined` when nobody registered it. */
|
|
129
|
+
get(namespace) {
|
|
130
|
+
return this.entries.get(namespace)?.resolved;
|
|
131
|
+
}
|
|
132
|
+
/** Merge a patch into a namespace by name (for a settings route that never held the scope). An unregistered namespace is refused. */
|
|
133
|
+
update(namespace, patch) {
|
|
134
|
+
const entry = this.entries.get(namespace);
|
|
135
|
+
if (entry === void 0) return Promise.reject(/* @__PURE__ */ new Error(`settings: namespace "${namespace}" is not registered`));
|
|
136
|
+
return this.commit(entry, (current) => mergeLayers(current, cloneJsonShaped({ ...patch })));
|
|
137
|
+
}
|
|
138
|
+
/** Every registered namespace, for settings screens. */
|
|
139
|
+
describe() {
|
|
140
|
+
return [...this.entries.values()].map((entry) => {
|
|
141
|
+
const stored = this.document[entry.namespace];
|
|
142
|
+
return {
|
|
143
|
+
namespace: entry.namespace,
|
|
144
|
+
schema: entry.schema.toJSON(),
|
|
145
|
+
value: entry.resolved,
|
|
146
|
+
revision: entry.revision,
|
|
147
|
+
applies: entry.options.applies ?? "live",
|
|
148
|
+
...stored === void 0 ? {} : { user: structuredClone(stored) }
|
|
149
|
+
};
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
section(namespace) {
|
|
153
|
+
const stored = this.document[namespace];
|
|
154
|
+
if (stored === void 0) return {};
|
|
155
|
+
if (!isPlainObject(stored)) throw new Error(`settings: section "${namespace}" in ${this.filename} must be a map`);
|
|
156
|
+
return stored;
|
|
157
|
+
}
|
|
158
|
+
resolve(entry, user) {
|
|
159
|
+
const base = entry.options.base ?? {};
|
|
160
|
+
const value = entry.schema(mergeLayers(base, user));
|
|
161
|
+
entry.options.validate?.(value);
|
|
162
|
+
return value;
|
|
163
|
+
}
|
|
164
|
+
scopeFor(entry) {
|
|
165
|
+
return {
|
|
166
|
+
get: () => entry.resolved,
|
|
167
|
+
watch: (callback) => {
|
|
168
|
+
const watcher = {
|
|
169
|
+
callback,
|
|
170
|
+
active: true
|
|
171
|
+
};
|
|
172
|
+
entry.watchers.add(watcher);
|
|
173
|
+
return () => {
|
|
174
|
+
watcher.active = false;
|
|
175
|
+
entry.watchers.delete(watcher);
|
|
176
|
+
};
|
|
177
|
+
},
|
|
178
|
+
update: (patch) => this.commit(entry, (current) => mergeLayers(current, cloneJsonShaped(patch))),
|
|
179
|
+
replace: (section) => this.commit(entry, () => cloneJsonShaped(section))
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
/** One write: compute, validate, persist atomically, then notify. A refused write changes nothing. */
|
|
183
|
+
commit(entry, next) {
|
|
184
|
+
const run = async () => {
|
|
185
|
+
if (this.disposed) throw new Error("settings: the service is disposed");
|
|
186
|
+
const nextSection = next(this.section(entry.namespace));
|
|
187
|
+
const nextValue = this.resolve(entry, nextSection);
|
|
188
|
+
const prevValue = entry.resolved;
|
|
189
|
+
const nextDocument = {
|
|
190
|
+
...this.document,
|
|
191
|
+
[entry.namespace]: nextSection
|
|
192
|
+
};
|
|
193
|
+
if (Object.keys(nextSection).length === 0) delete nextDocument[entry.namespace];
|
|
194
|
+
this.persist(nextDocument);
|
|
195
|
+
this.document = nextDocument;
|
|
196
|
+
entry.revision += 1;
|
|
197
|
+
entry.resolved = nextValue;
|
|
198
|
+
if (deepEqualJson(prevValue, nextValue)) return;
|
|
199
|
+
this.ctx.emit("settings/updated", entry.namespace, nextValue, prevValue);
|
|
200
|
+
for (const watcher of [...entry.watchers]) {
|
|
201
|
+
if (!watcher.active) continue;
|
|
202
|
+
try {
|
|
203
|
+
await watcher.callback(nextValue, prevValue);
|
|
204
|
+
} catch (cause) {
|
|
205
|
+
this.ctx.logger?.error?.(`settings: watcher for "${entry.namespace}" failed: ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
const result = this.tail.then(run, run);
|
|
210
|
+
this.tail = result.then(() => void 0, () => void 0);
|
|
211
|
+
return result;
|
|
212
|
+
}
|
|
213
|
+
persist(document) {
|
|
214
|
+
mkdirSync(dirname(this.filename), { recursive: true });
|
|
215
|
+
const temporary = `${this.filename}.${String(process.pid)}.tmp`;
|
|
216
|
+
writeFileSync(temporary, stringify(document), { mode: 384 });
|
|
217
|
+
renameSync(temporary, this.filename);
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
/** The plugin: mount it after `instance`. */
|
|
221
|
+
const settings = {
|
|
222
|
+
name: "settings",
|
|
223
|
+
inject: ["appInstance"],
|
|
224
|
+
apply(ctx, config) {
|
|
225
|
+
new Settings(ctx, config ?? {});
|
|
226
|
+
}
|
|
227
|
+
};
|
|
228
|
+
//#endregion
|
|
229
|
+
export { DEFAULT_FILENAME, Settings, settings, z };
|
|
230
|
+
|
|
231
|
+
//# sourceMappingURL=index.js.map
|
package/lib/index.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../merge.ts","../index.ts"],"sourcesContent":["/** Pure helpers for layering a user section over a base and for detaching JSON data. */\n\n/** Whether a value is a plain data object (not an array, null, or class instance). */\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false\n const proto: unknown = Object.getPrototypeOf(value)\n return proto === Object.prototype || proto === null\n}\n\n/**\n * Deep-merge `patch` over `base`: plain objects merge key by key, every other value (arrays included) replaces,\n * and `undefined` entries in the patch are skipped.\n */\nexport function mergeLayers(\n base: Record<string, unknown>,\n patch: Record<string, unknown>,\n): Record<string, unknown> {\n const merged: Record<string, unknown> = { ...base }\n for (const [key, value] of Object.entries(patch)) {\n if (value === undefined) continue\n const current = merged[key]\n merged[key] =\n isPlainObject(current) && isPlainObject(value) ? mergeLayers(current, value) : value\n }\n return merged\n}\n\n/**\n * Detach one write input and reject anything YAML would distort on a reload round trip: only plain objects, arrays,\n * strings, finite numbers, booleans and `null` pass.\n * @throws TypeError naming the `$`-rooted path of the first rejected value.\n */\nexport function cloneJsonShaped(root: Record<string, unknown>): Record<string, unknown> {\n const visiting = new WeakSet<object>()\n const clone = (value: unknown, path: string): unknown => {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return value\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) throw new TypeError(`settings: ${path} is a non-finite number`)\n return value\n }\n if (Array.isArray(value)) {\n if (visiting.has(value)) throw new TypeError(`settings: ${path} is a circular reference`)\n visiting.add(value)\n const entries = value.map((entry, index) => clone(entry, `${path}[${String(index)}]`))\n visiting.delete(value)\n return entries\n }\n if (isPlainObject(value)) {\n if (visiting.has(value)) throw new TypeError(`settings: ${path} is a circular reference`)\n visiting.add(value)\n const out: Record<string, unknown> = {}\n for (const [key, entry] of Object.entries(value)) {\n if (entry === undefined) continue\n out[key] = clone(entry, `${path}.${key}`)\n }\n visiting.delete(value)\n return out\n }\n throw new TypeError(\n `settings: ${path} is ${value === undefined ? 'undefined' : `a ${typeof value}`}, which cannot be stored`,\n )\n }\n return clone(root, '$') as Record<string, unknown>\n}\n\n/** Structural JSON equality for two detached values. */\nexport function deepEqualJson(a: unknown, b: unknown): boolean {\n if (a === b) return true\n if (Array.isArray(a) && Array.isArray(b))\n return a.length === b.length && a.every((entry, index) => deepEqualJson(entry, b[index]))\n if (isPlainObject(a) && isPlainObject(b)) {\n const keys = Object.keys(a)\n return (\n keys.length === Object.keys(b).length &&\n keys.every((key) => Object.hasOwn(b, key) && deepEqualJson(a[key], b[key]))\n )\n }\n return false\n}\n","/**\n * The settings service (`ctx.settings`): per-namespace sections kept in one YAML file in the app's home.\n *\n * Extracted from ACRYL (`plugins/settings`). Plugins register a namespace with a schemastery schema and read the resolved value,\n * which layers schema defaults, the registrant's `base`, and the stored section, in that order. Writes are validated, atomic (write a\n * temporary file, then rename) and run one at a time in commit order; watchers see them in that order; an event announces each change.\n */\nimport { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport type {} from '@acryldev/instance'\nimport { type Context, Service } from '@deepseek-ai/cordis'\nimport z from '@deepseek-ai/schemastery'\nimport { parseDocument, stringify } from 'yaml'\nimport { cloneJsonShaped, deepEqualJson, isPlainObject, mergeLayers } from './merge.ts'\n\nconst NAMESPACE_PATTERN = /^[a-z][a-z0-9-]*$/\nexport const DEFAULT_FILENAME = 'settings.yaml'\n\n/** When a namespace's changes take effect for its owner. */\nexport type SettingsApplies = 'live' | 'restart'\n\nexport interface SettingsRegisterOptions<T> {\n /** Values resolved below the stored layer (for example, what the app's composition chose). */\n base?: Partial<T>\n /** When the owner applies a change; shown to settings screens. Defaults to `live`. */\n applies?: SettingsApplies\n /** Reject a resolved value the schema cannot express as invalid; a throw refuses the write that produced it. */\n validate?: (value: T) => void\n}\n\n/** One registered namespace, as a settings screen sees it. */\nexport interface SettingsDescriptor {\n readonly namespace: string\n /** The schemastery schema, serialized. */\n readonly schema: unknown\n readonly value: unknown\n /** Bumps on every committed write. */\n readonly revision: number\n readonly applies: SettingsApplies\n /** The stored section, when there is one. */\n readonly user?: unknown\n}\n\n/** The owner's handle on one namespace. */\nexport interface SettingsScope<T> {\n /** Current resolved value: schema defaults, then `base`, then the stored section. */\n get(): T\n /** Observe committed changes; callbacks run one at a time in commit order. Returns the function that stops watching. */\n watch(callback: (next: T, prev: T) => void | Promise<void>): () => void\n /** Merge a patch into the stored section and persist it. */\n update(patch: object): Promise<void>\n /** Replace the stored section; `replace({})` resets every key to its base or default. */\n replace(section: object): Promise<void>\n}\n\nexport interface SettingsConfig {\n /** Absolute path of the YAML file; empty or absent means `<app home>/settings.yaml`. */\n filename?: string\n}\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context {\n settings: Settings\n }\n\n interface Events {\n /** A committed change to one namespace's resolved value, after the file was written; never for an equal value. */\n 'settings/updated'(namespace: string, next: unknown, prev: unknown): void\n }\n}\n\ninterface Entry {\n readonly namespace: string\n readonly schema: z<unknown>\n readonly options: SettingsRegisterOptions<unknown>\n resolved: unknown\n revision: number\n readonly watchers: Set<Watcher>\n}\n\ninterface Watcher {\n readonly callback: (next: unknown, prev: unknown) => void | Promise<void>\n active: boolean\n}\n\nfunction assertNamespace(value: string): void {\n if (!NAMESPACE_PATTERN.test(value))\n throw new TypeError(`settings: namespace \"${value}\" must match ${String(NAMESPACE_PATTERN)}`)\n}\n\nfunction readDocument(filename: string): Record<string, unknown> {\n if (!existsSync(filename)) return {}\n const parsed = parseDocument(readFileSync(filename, 'utf8'), { prettyErrors: true })\n if (parsed.errors.length > 0) {\n throw new Error(\n `settings: invalid settings file ${filename}: ${parsed.errors.map((error) => error.message).join('; ')}`,\n )\n }\n const value: unknown = parsed.toJS() ?? {}\n if (!isPlainObject(value))\n throw new Error(`settings: ${filename} must be a map of namespace sections`)\n return value\n}\n\n/** The service. One instance serves one app home. */\nexport class Settings extends Service {\n readonly filename: string\n private document: Record<string, unknown>\n private readonly entries = new Map<string, Entry>()\n /** Writes and watcher notifications run one at a time, in commit order. */\n private tail: Promise<void> = Promise.resolve()\n private disposed = false\n\n constructor(ctx: Context, config: SettingsConfig = {}) {\n super(ctx, 'settings')\n this.filename = config.filename ? config.filename : join(ctx.appInstance.home, DEFAULT_FILENAME)\n this.document = readDocument(this.filename)\n ctx.effect(\n () => async () => {\n this.disposed = true\n await this.tail\n },\n 'settings: settle pending writes',\n )\n }\n\n /** Register a namespace and return its handle. A stored section that fails the schema rejects the registration. */\n register<T>(\n namespace: string,\n schema: z<T>,\n options: SettingsRegisterOptions<T> = {},\n ): SettingsScope<T> {\n assertNamespace(namespace)\n if (this.entries.has(namespace))\n throw new Error(`settings: namespace \"${namespace}\" is already registered`)\n const entry: Entry = {\n namespace,\n schema: schema as z<unknown>,\n options: options as SettingsRegisterOptions<unknown>,\n resolved: undefined,\n revision: 0,\n watchers: new Set(),\n }\n entry.resolved = this.resolve(entry, this.section(namespace))\n this.entries.set(namespace, entry)\n this.ctx.effect(\n () => () => void this.entries.delete(namespace),\n `settings: namespace ${namespace}`,\n )\n return this.scopeFor<T>(entry)\n }\n\n /** The resolved value of a registered namespace, or `undefined` when nobody registered it. */\n get(namespace: string): unknown {\n return this.entries.get(namespace)?.resolved\n }\n\n /** Merge a patch into a namespace by name (for a settings route that never held the scope). An unregistered namespace is refused. */\n update(namespace: string, patch: Readonly<Record<string, unknown>>): Promise<void> {\n const entry = this.entries.get(namespace)\n if (entry === undefined)\n return Promise.reject(new Error(`settings: namespace \"${namespace}\" is not registered`))\n return this.commit(entry, (current) => mergeLayers(current, cloneJsonShaped({ ...patch })))\n }\n\n /** Every registered namespace, for settings screens. */\n describe(): SettingsDescriptor[] {\n return [...this.entries.values()].map((entry) => {\n const stored = this.document[entry.namespace]\n return {\n namespace: entry.namespace,\n schema: entry.schema.toJSON(),\n value: entry.resolved,\n revision: entry.revision,\n applies: entry.options.applies ?? 'live',\n ...(stored === undefined ? {} : { user: structuredClone(stored) }),\n }\n })\n }\n\n private section(namespace: string): Record<string, unknown> {\n const stored = this.document[namespace]\n if (stored === undefined) return {}\n if (!isPlainObject(stored))\n throw new Error(`settings: section \"${namespace}\" in ${this.filename} must be a map`)\n return stored\n }\n\n private resolve(entry: Entry, user: Record<string, unknown>): unknown {\n const base = (entry.options.base ?? {}) as Record<string, unknown>\n const value = entry.schema(mergeLayers(base, user))\n entry.options.validate?.(value)\n return value\n }\n\n private scopeFor<T>(entry: Entry): SettingsScope<T> {\n return {\n get: () => entry.resolved as T,\n watch: (callback) => {\n const watcher: Watcher = { callback: callback as Watcher['callback'], active: true }\n entry.watchers.add(watcher)\n return () => {\n watcher.active = false\n entry.watchers.delete(watcher)\n }\n },\n update: (patch) =>\n this.commit(entry, (current) =>\n mergeLayers(current, cloneJsonShaped(patch as Record<string, unknown>)),\n ),\n replace: (section) =>\n this.commit(entry, () => cloneJsonShaped(section as Record<string, unknown>)),\n }\n }\n\n /** One write: compute, validate, persist atomically, then notify. A refused write changes nothing. */\n private commit(\n entry: Entry,\n next: (current: Record<string, unknown>) => Record<string, unknown>,\n ): Promise<void> {\n const run = async (): Promise<void> => {\n if (this.disposed) throw new Error('settings: the service is disposed')\n const nextSection = next(this.section(entry.namespace))\n const nextValue = this.resolve(entry, nextSection)\n const prevValue = entry.resolved\n const nextDocument = { ...this.document, [entry.namespace]: nextSection }\n if (Object.keys(nextSection).length === 0) delete nextDocument[entry.namespace]\n this.persist(nextDocument)\n this.document = nextDocument\n entry.revision += 1\n entry.resolved = nextValue\n if (deepEqualJson(prevValue, nextValue)) return\n this.ctx.emit('settings/updated', entry.namespace, nextValue, prevValue)\n for (const watcher of [...entry.watchers]) {\n if (!watcher.active) continue\n try {\n await watcher.callback(nextValue, prevValue)\n } catch (cause) {\n this.ctx.logger?.error?.(\n `settings: watcher for \"${entry.namespace}\" failed: ${cause instanceof Error ? cause.message : String(cause)}`,\n )\n }\n }\n }\n const result = this.tail.then(run, run)\n this.tail = result.then(\n () => undefined,\n () => undefined,\n )\n return result\n }\n\n private persist(document: Record<string, unknown>): void {\n mkdirSync(dirname(this.filename), { recursive: true })\n const temporary = `${this.filename}.${String(process.pid)}.tmp`\n writeFileSync(temporary, stringify(document), { mode: 0o600 })\n renameSync(temporary, this.filename)\n }\n}\n\n/** The plugin: mount it after `instance`. */\nexport const settings = {\n name: 'settings',\n inject: ['appInstance'],\n apply(ctx: Context, config: SettingsConfig) {\n new Settings(ctx, config ?? {})\n },\n}\n\nexport { z }\n"],"mappings":";;;;;;;;AAGA,SAAgB,cAAc,OAAkD;CAC9E,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,GAAG,OAAO;CAChF,MAAM,QAAiB,OAAO,eAAe,KAAK;CAClD,OAAO,UAAU,OAAO,aAAa,UAAU;AACjD;;;;;AAMA,SAAgB,YACd,MACA,OACyB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Y;GACxE,IAAI,OAAO,KAAK,WAAW,CAAC,CAAC,WAAW,GAAG,OAAO,aAAa,MAAM;GACrE,KAAK,QAAQ,YAAY;GACzB,KAAK,WAAW;GAChB,MAAM,YAAY;GAClB,MAAM,WAAW;GACjB,IAAI,cAAc,WAAW,SAAS,GAAG;GACzC,KAAK,IAAI,KAAK,oBAAoB,MAAM,WAAW,WAAW,SAAS;GACvE,KAAK,MAAM,WAAW,CAAC,GAAG,MAAM,QAAQ,GAAG;IACzC,IAAI,CAAC,QAAQ,QAAQ;IACrB,IAAI;KACF,MAAM,QAAQ,SAAS,WAAW,SAAS;IAC7C,SAAS,OAAO;KACd,KAAK,IAAI,QAAQ,QACf,0BAA0B,MAAM,UAAU,YAAY,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAC7G;IACF;GACF;EACF;EACA,MAAM,SAAS,KAAK,KAAK,KAAK,KAAK,GAAG;EACtC,KAAK,OAAO,OAAO,WACX,KAAA,SACA,KAAA,CACR;EACA,OAAO;CACT;CAEA,QAAgB,UAAyC;EACvD,UAAU,QAAQ,KAAK,QAAQ,GAAG,EAAE,WAAW,KAAK,CAAC;EACrD,MAAM,YAAY,GAAG,KAAK,SAAS,GAAG,OAAO,QAAQ,GAAG,EAAE;EAC1D,cAAc,WAAW,UAAU,QAAQ,GAAG,EAAE,MAAM,IAAM,CAAC;EAC7D,WAAW,WAAW,KAAK,QAAQ;CACrC;AACF;;AAGA,MAAa,WAAW;CACtB,MAAM;CACN,QAAQ,CAAC,aAAa;CACtB,MAAM,KAAc,QAAwB;EAC1C,IAAI,SAAS,KAAK,UAAU,CAAC,CAAC;CAChC;AACF"}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { type Context, Service } from '@deepseek-ai/cordis';
|
|
2
|
+
import z from '@deepseek-ai/schemastery';
|
|
3
|
+
export declare const DEFAULT_FILENAME = "settings.yaml";
|
|
4
|
+
/** When a namespace's changes take effect for its owner. */
|
|
5
|
+
export type SettingsApplies = 'live' | 'restart';
|
|
6
|
+
export interface SettingsRegisterOptions<T> {
|
|
7
|
+
/** Values resolved below the stored layer (for example, what the app's composition chose). */
|
|
8
|
+
base?: Partial<T>;
|
|
9
|
+
/** When the owner applies a change; shown to settings screens. Defaults to `live`. */
|
|
10
|
+
applies?: SettingsApplies;
|
|
11
|
+
/** Reject a resolved value the schema cannot express as invalid; a throw refuses the write that produced it. */
|
|
12
|
+
validate?: (value: T) => void;
|
|
13
|
+
}
|
|
14
|
+
/** One registered namespace, as a settings screen sees it. */
|
|
15
|
+
export interface SettingsDescriptor {
|
|
16
|
+
readonly namespace: string;
|
|
17
|
+
/** The schemastery schema, serialized. */
|
|
18
|
+
readonly schema: unknown;
|
|
19
|
+
readonly value: unknown;
|
|
20
|
+
/** Bumps on every committed write. */
|
|
21
|
+
readonly revision: number;
|
|
22
|
+
readonly applies: SettingsApplies;
|
|
23
|
+
/** The stored section, when there is one. */
|
|
24
|
+
readonly user?: unknown;
|
|
25
|
+
}
|
|
26
|
+
/** The owner's handle on one namespace. */
|
|
27
|
+
export interface SettingsScope<T> {
|
|
28
|
+
/** Current resolved value: schema defaults, then `base`, then the stored section. */
|
|
29
|
+
get(): T;
|
|
30
|
+
/** Observe committed changes; callbacks run one at a time in commit order. Returns the function that stops watching. */
|
|
31
|
+
watch(callback: (next: T, prev: T) => void | Promise<void>): () => void;
|
|
32
|
+
/** Merge a patch into the stored section and persist it. */
|
|
33
|
+
update(patch: object): Promise<void>;
|
|
34
|
+
/** Replace the stored section; `replace({})` resets every key to its base or default. */
|
|
35
|
+
replace(section: object): Promise<void>;
|
|
36
|
+
}
|
|
37
|
+
export interface SettingsConfig {
|
|
38
|
+
/** Absolute path of the YAML file; empty or absent means `<app home>/settings.yaml`. */
|
|
39
|
+
filename?: string;
|
|
40
|
+
}
|
|
41
|
+
declare module '@deepseek-ai/cordis' {
|
|
42
|
+
interface Context {
|
|
43
|
+
settings: Settings;
|
|
44
|
+
}
|
|
45
|
+
interface Events {
|
|
46
|
+
/** A committed change to one namespace's resolved value, after the file was written; never for an equal value. */
|
|
47
|
+
'settings/updated'(namespace: string, next: unknown, prev: unknown): void;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/** The service. One instance serves one app home. */
|
|
51
|
+
export declare class Settings extends Service {
|
|
52
|
+
readonly filename: string;
|
|
53
|
+
private document;
|
|
54
|
+
private readonly entries;
|
|
55
|
+
/** Writes and watcher notifications run one at a time, in commit order. */
|
|
56
|
+
private tail;
|
|
57
|
+
private disposed;
|
|
58
|
+
constructor(ctx: Context, config?: SettingsConfig);
|
|
59
|
+
/** Register a namespace and return its handle. A stored section that fails the schema rejects the registration. */
|
|
60
|
+
register<T>(namespace: string, schema: z<T>, options?: SettingsRegisterOptions<T>): SettingsScope<T>;
|
|
61
|
+
/** The resolved value of a registered namespace, or `undefined` when nobody registered it. */
|
|
62
|
+
get(namespace: string): unknown;
|
|
63
|
+
/** Merge a patch into a namespace by name (for a settings route that never held the scope). An unregistered namespace is refused. */
|
|
64
|
+
update(namespace: string, patch: Readonly<Record<string, unknown>>): Promise<void>;
|
|
65
|
+
/** Every registered namespace, for settings screens. */
|
|
66
|
+
describe(): SettingsDescriptor[];
|
|
67
|
+
private section;
|
|
68
|
+
private resolve;
|
|
69
|
+
private scopeFor;
|
|
70
|
+
/** One write: compute, validate, persist atomically, then notify. A refused write changes nothing. */
|
|
71
|
+
private commit;
|
|
72
|
+
private persist;
|
|
73
|
+
}
|
|
74
|
+
/** The plugin: mount it after `instance`. */
|
|
75
|
+
export declare const settings: {
|
|
76
|
+
name: string;
|
|
77
|
+
inject: string[];
|
|
78
|
+
apply(ctx: Context, config: SettingsConfig): void;
|
|
79
|
+
};
|
|
80
|
+
export { z };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** Pure helpers for layering a user section over a base and for detaching JSON data. */
|
|
2
|
+
/** Whether a value is a plain data object (not an array, null, or class instance). */
|
|
3
|
+
export declare function isPlainObject(value: unknown): value is Record<string, unknown>;
|
|
4
|
+
/**
|
|
5
|
+
* Deep-merge `patch` over `base`: plain objects merge key by key, every other value (arrays included) replaces,
|
|
6
|
+
* and `undefined` entries in the patch are skipped.
|
|
7
|
+
*/
|
|
8
|
+
export declare function mergeLayers(base: Record<string, unknown>, patch: Record<string, unknown>): Record<string, unknown>;
|
|
9
|
+
/**
|
|
10
|
+
* Detach one write input and reject anything YAML would distort on a reload round trip: only plain objects, arrays,
|
|
11
|
+
* strings, finite numbers, booleans and `null` pass.
|
|
12
|
+
* @throws TypeError naming the `$`-rooted path of the first rejected value.
|
|
13
|
+
*/
|
|
14
|
+
export declare function cloneJsonShaped(root: Record<string, unknown>): Record<string, unknown>;
|
|
15
|
+
/** Structural JSON equality for two detached values. */
|
|
16
|
+
export declare function deepEqualJson(a: unknown, b: unknown): boolean;
|
package/merge.ts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/** Pure helpers for layering a user section over a base and for detaching JSON data. */
|
|
2
|
+
|
|
3
|
+
/** Whether a value is a plain data object (not an array, null, or class instance). */
|
|
4
|
+
export function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
5
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) return false
|
|
6
|
+
const proto: unknown = Object.getPrototypeOf(value)
|
|
7
|
+
return proto === Object.prototype || proto === null
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Deep-merge `patch` over `base`: plain objects merge key by key, every other value (arrays included) replaces,
|
|
12
|
+
* and `undefined` entries in the patch are skipped.
|
|
13
|
+
*/
|
|
14
|
+
export function mergeLayers(
|
|
15
|
+
base: Record<string, unknown>,
|
|
16
|
+
patch: Record<string, unknown>,
|
|
17
|
+
): Record<string, unknown> {
|
|
18
|
+
const merged: Record<string, unknown> = { ...base }
|
|
19
|
+
for (const [key, value] of Object.entries(patch)) {
|
|
20
|
+
if (value === undefined) continue
|
|
21
|
+
const current = merged[key]
|
|
22
|
+
merged[key] =
|
|
23
|
+
isPlainObject(current) && isPlainObject(value) ? mergeLayers(current, value) : value
|
|
24
|
+
}
|
|
25
|
+
return merged
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Detach one write input and reject anything YAML would distort on a reload round trip: only plain objects, arrays,
|
|
30
|
+
* strings, finite numbers, booleans and `null` pass.
|
|
31
|
+
* @throws TypeError naming the `$`-rooted path of the first rejected value.
|
|
32
|
+
*/
|
|
33
|
+
export function cloneJsonShaped(root: Record<string, unknown>): Record<string, unknown> {
|
|
34
|
+
const visiting = new WeakSet<object>()
|
|
35
|
+
const clone = (value: unknown, path: string): unknown => {
|
|
36
|
+
if (value === null || typeof value === 'string' || typeof value === 'boolean') return value
|
|
37
|
+
if (typeof value === 'number') {
|
|
38
|
+
if (!Number.isFinite(value)) throw new TypeError(`settings: ${path} is a non-finite number`)
|
|
39
|
+
return value
|
|
40
|
+
}
|
|
41
|
+
if (Array.isArray(value)) {
|
|
42
|
+
if (visiting.has(value)) throw new TypeError(`settings: ${path} is a circular reference`)
|
|
43
|
+
visiting.add(value)
|
|
44
|
+
const entries = value.map((entry, index) => clone(entry, `${path}[${String(index)}]`))
|
|
45
|
+
visiting.delete(value)
|
|
46
|
+
return entries
|
|
47
|
+
}
|
|
48
|
+
if (isPlainObject(value)) {
|
|
49
|
+
if (visiting.has(value)) throw new TypeError(`settings: ${path} is a circular reference`)
|
|
50
|
+
visiting.add(value)
|
|
51
|
+
const out: Record<string, unknown> = {}
|
|
52
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
53
|
+
if (entry === undefined) continue
|
|
54
|
+
out[key] = clone(entry, `${path}.${key}`)
|
|
55
|
+
}
|
|
56
|
+
visiting.delete(value)
|
|
57
|
+
return out
|
|
58
|
+
}
|
|
59
|
+
throw new TypeError(
|
|
60
|
+
`settings: ${path} is ${value === undefined ? 'undefined' : `a ${typeof value}`}, which cannot be stored`,
|
|
61
|
+
)
|
|
62
|
+
}
|
|
63
|
+
return clone(root, '$') as Record<string, unknown>
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Structural JSON equality for two detached values. */
|
|
67
|
+
export function deepEqualJson(a: unknown, b: unknown): boolean {
|
|
68
|
+
if (a === b) return true
|
|
69
|
+
if (Array.isArray(a) && Array.isArray(b))
|
|
70
|
+
return a.length === b.length && a.every((entry, index) => deepEqualJson(entry, b[index]))
|
|
71
|
+
if (isPlainObject(a) && isPlainObject(b)) {
|
|
72
|
+
const keys = Object.keys(a)
|
|
73
|
+
return (
|
|
74
|
+
keys.length === Object.keys(b).length &&
|
|
75
|
+
keys.every((key) => Object.hasOwn(b, key) && deepEqualJson(a[key], b[key]))
|
|
76
|
+
)
|
|
77
|
+
}
|
|
78
|
+
return false
|
|
79
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@acryldev/app-settings",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Validated settings per namespace in one YAML file in the app's home: defaults, base and stored layers, watch, update.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/acryldev/acryl.git",
|
|
9
|
+
"directory": "plugins/app-settings"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/acryldev/acryl/tree/main/plugins/app-settings#readme",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/acryldev/acryl/issues"
|
|
14
|
+
},
|
|
15
|
+
"type": "module",
|
|
16
|
+
"engines": {
|
|
17
|
+
"node": "^22.19.0 || >=24.0.0"
|
|
18
|
+
},
|
|
19
|
+
"main": "./lib/index.js",
|
|
20
|
+
"types": "./lib/types/index.d.ts",
|
|
21
|
+
"exports": {
|
|
22
|
+
".": {
|
|
23
|
+
"types": "./lib/types/index.d.ts",
|
|
24
|
+
"default": "./lib/index.js"
|
|
25
|
+
},
|
|
26
|
+
"./package.json": "./package.json"
|
|
27
|
+
},
|
|
28
|
+
"dependencies": {
|
|
29
|
+
"@acryldev/instance": "0.1.2",
|
|
30
|
+
"@deepseek-ai/schemastery": "3.18.4",
|
|
31
|
+
"yaml": "2.9.0"
|
|
32
|
+
},
|
|
33
|
+
"peerDependencies": {
|
|
34
|
+
"@deepseek-ai/cordis": "^4.0.2"
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"@deepseek-ai/cordis": "4.0.4",
|
|
38
|
+
"@types/node": "^22.20.0",
|
|
39
|
+
"tsdown": "0.22.2",
|
|
40
|
+
"typescript": "6.0.3"
|
|
41
|
+
},
|
|
42
|
+
"scripts": {
|
|
43
|
+
"build": "tsdown && tsc -p tsconfig.json --emitDeclarationOnly"
|
|
44
|
+
}
|
|
6
45
|
}
|
package/plugin.json
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "app-settings",
|
|
3
|
+
"description": "Validated settings per namespace in one YAML file in the app's home: defaults, base and stored layers, watch, update.",
|
|
4
|
+
"requires": ["instance"],
|
|
5
|
+
"inject": ["appInstance"],
|
|
6
|
+
"provides": ["settings"],
|
|
7
|
+
"dependencies": {
|
|
8
|
+
"@deepseek-ai/cordis": "4.0.4",
|
|
9
|
+
"@deepseek-ai/schemastery": "3.18.4",
|
|
10
|
+
"yaml": "2.9.0"
|
|
11
|
+
},
|
|
12
|
+
"mount": "mount it after instance: root.plugin(settings, {}); then ctx.settings.register('my-plugin', Schema)",
|
|
13
|
+
"entries": {
|
|
14
|
+
"": "index.ts"
|
|
15
|
+
}
|
|
16
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import assert from 'node:assert/strict'
|
|
2
|
+
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
|
3
|
+
import { tmpdir } from 'node:os'
|
|
4
|
+
import { join } from 'node:path'
|
|
5
|
+
import { afterEach, test } from 'node:test'
|
|
6
|
+
import { instance, pinnedInstance } from '@acryldev/instance'
|
|
7
|
+
import { Context } from '@deepseek-ai/cordis'
|
|
8
|
+
import { settings, z } from '../index.ts'
|
|
9
|
+
|
|
10
|
+
const homes: string[] = []
|
|
11
|
+
afterEach(() => {
|
|
12
|
+
for (const home of homes.splice(0)) rmSync(home, { recursive: true, force: true })
|
|
13
|
+
})
|
|
14
|
+
|
|
15
|
+
async function boot(home = mkdtempSync(join(tmpdir(), 'settings-test-'))) {
|
|
16
|
+
homes.push(home)
|
|
17
|
+
const root = new Context()
|
|
18
|
+
await root.plugin(instance, pinnedInstance(home)).await()
|
|
19
|
+
const fiber = root.plugin(settings, {})
|
|
20
|
+
await fiber.await()
|
|
21
|
+
return { root, fiber, home, file: join(home, 'settings.yaml') }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const Theme = z.object({
|
|
25
|
+
mode: z.union(['light', 'dark']).default('light'),
|
|
26
|
+
size: z.natural().default(14),
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
test('layers schema defaults, then base, then the stored section', async () => {
|
|
30
|
+
const home = mkdtempSync(join(tmpdir(), 'settings-test-'))
|
|
31
|
+
writeFileSync(join(home, 'settings.yaml'), 'theme:\n size: 18\n')
|
|
32
|
+
const { root } = await boot(home)
|
|
33
|
+
const scope = root.settings.register('theme', Theme, { base: { mode: 'dark' } })
|
|
34
|
+
assert.deepEqual(scope.get(), { mode: 'dark', size: 18 })
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
test('an update is validated, persisted to YAML and read back by a fresh service', async () => {
|
|
38
|
+
const { root, fiber, home, file } = await boot()
|
|
39
|
+
const scope = root.settings.register('theme', Theme)
|
|
40
|
+
await scope.update({ mode: 'dark' })
|
|
41
|
+
assert.match(readFileSync(file, 'utf8'), /mode: dark/)
|
|
42
|
+
await assert.rejects(scope.update({ mode: 'purple' }))
|
|
43
|
+
assert.equal(scope.get().mode, 'dark')
|
|
44
|
+
await fiber.dispose()
|
|
45
|
+
const again = await boot(home)
|
|
46
|
+
assert.equal(again.root.settings.register('theme', Theme).get().mode, 'dark')
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
test('watchers and the event see committed changes in order, and never an unchanged value', async () => {
|
|
50
|
+
const { root } = await boot()
|
|
51
|
+
const scope = root.settings.register('theme', Theme)
|
|
52
|
+
const seen: string[] = []
|
|
53
|
+
scope.watch((next) => void seen.push(`watch:${next.size}`))
|
|
54
|
+
root.on(
|
|
55
|
+
'settings/updated',
|
|
56
|
+
(namespace, next) => void seen.push(`event:${namespace}:${(next as { size: number }).size}`),
|
|
57
|
+
)
|
|
58
|
+
await Promise.all([
|
|
59
|
+
scope.update({ size: 15 }),
|
|
60
|
+
scope.update({ size: 16 }),
|
|
61
|
+
scope.update({ size: 16 }),
|
|
62
|
+
])
|
|
63
|
+
assert.deepEqual(seen, ['event:theme:15', 'watch:15', 'event:theme:16', 'watch:16'])
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
test('replace({}) resets to base and defaults and removes the section from the file', async () => {
|
|
67
|
+
const { root, file } = await boot()
|
|
68
|
+
const scope = root.settings.register('theme', Theme)
|
|
69
|
+
await scope.update({ size: 20 })
|
|
70
|
+
await scope.replace({})
|
|
71
|
+
assert.deepEqual(scope.get(), { mode: 'light', size: 14 })
|
|
72
|
+
assert.doesNotMatch(readFileSync(file, 'utf8'), /theme/)
|
|
73
|
+
})
|
|
74
|
+
|
|
75
|
+
test('refuses bad namespaces, double registration and values YAML would distort', async () => {
|
|
76
|
+
const { root } = await boot()
|
|
77
|
+
assert.throws(() => root.settings.register('Bad Name', Theme), /namespace/)
|
|
78
|
+
root.settings.register('theme', Theme)
|
|
79
|
+
assert.throws(() => root.settings.register('theme', Theme), /already registered/)
|
|
80
|
+
await assert.rejects(root.settings.update('theme', { size: Number.NaN }), /non-finite/)
|
|
81
|
+
await assert.rejects(root.settings.update('nobody', {}), /not registered/)
|
|
82
|
+
})
|
|
83
|
+
|
|
84
|
+
test('describe lists namespaces for a settings screen, and a namespace leaves with its owner', async () => {
|
|
85
|
+
const { root } = await boot()
|
|
86
|
+
const owner = root.plugin({
|
|
87
|
+
name: 'owner',
|
|
88
|
+
inject: ['settings'],
|
|
89
|
+
apply: (ctx: Context) => void ctx.settings.register('theme', Theme),
|
|
90
|
+
})
|
|
91
|
+
await owner.await()
|
|
92
|
+
assert.deepEqual(
|
|
93
|
+
root.settings.describe().map((entry) => entry.namespace),
|
|
94
|
+
['theme'],
|
|
95
|
+
)
|
|
96
|
+
await owner.dispose()
|
|
97
|
+
assert.deepEqual(root.settings.describe(), [])
|
|
98
|
+
assert.equal(existsSync(join(root.appInstance.home, 'settings.yaml')), false)
|
|
99
|
+
})
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"target": "ES2024",
|
|
4
|
+
"lib": ["ES2024", "DOM", "DOM.Iterable"],
|
|
5
|
+
"module": "NodeNext",
|
|
6
|
+
"moduleResolution": "NodeNext",
|
|
7
|
+
"allowImportingTsExtensions": true,
|
|
8
|
+
"erasableSyntaxOnly": true,
|
|
9
|
+
"rootDir": ".",
|
|
10
|
+
"outDir": "lib",
|
|
11
|
+
"declaration": true,
|
|
12
|
+
"declarationDir": "lib/types",
|
|
13
|
+
"esModuleInterop": true,
|
|
14
|
+
"strict": true,
|
|
15
|
+
"noImplicitOverride": true,
|
|
16
|
+
"verbatimModuleSyntax": true,
|
|
17
|
+
"skipLibCheck": true,
|
|
18
|
+
"types": ["node"]
|
|
19
|
+
},
|
|
20
|
+
"include": ["*.ts"]
|
|
21
|
+
}
|
package/tsdown.config.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs'
|
|
2
|
+
import { defineConfig } from 'tsdown'
|
|
3
|
+
|
|
4
|
+
/** The package's importable files, exactly as `plugin.json`'s `entries` names them (the copy path uses the same table). */
|
|
5
|
+
const { entries } = JSON.parse(readFileSync(new URL('./plugin.json', import.meta.url), 'utf8')) as {
|
|
6
|
+
entries: Record<string, string>
|
|
7
|
+
}
|
|
8
|
+
const entry = Object.fromEntries(
|
|
9
|
+
Object.entries(entries).map(([, file]) => [file.replace(/.ts$/, ''), file]),
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
export default defineConfig({
|
|
13
|
+
name: '@acryldev/app-settings',
|
|
14
|
+
entry,
|
|
15
|
+
outDir: 'lib',
|
|
16
|
+
format: 'esm',
|
|
17
|
+
platform: 'node',
|
|
18
|
+
target: 'es2024',
|
|
19
|
+
fixedExtension: false,
|
|
20
|
+
dts: false,
|
|
21
|
+
clean: true,
|
|
22
|
+
sourcemap: true,
|
|
23
|
+
})
|