@dybai/dsh-editor 0.0.0-stage → 0.5.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.
- package/LICENSE +21 -0
- package/README.md +91 -2
- package/client.js +5440 -0
- package/cordis.patch.yml +4 -0
- package/host/preferences-service.js +481 -0
- package/host/write-service.js +109 -0
- package/icon.svg +5 -0
- package/index.js +182 -0
- package/locale/en.json +99 -0
- package/locale/zh.json +99 -0
- package/package.json +45 -4
package/cordis.patch.yml
ADDED
|
@@ -0,0 +1,481 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Editor preference persistence over one DSH storage KV unit.
|
|
3
|
+
*
|
|
4
|
+
* `createPreferencesService({ kv, now })` builds the Host half of the editor's
|
|
5
|
+
* user-preference stores over ONE unit:
|
|
6
|
+
*
|
|
7
|
+
* - `mode_associations` — the complete set of `glob → modeId` associations
|
|
8
|
+
* the "open as default" / "reset to default" menu writes;
|
|
9
|
+
* - `keymap` — the framework's SELF-MANAGED key bindings for the actions
|
|
10
|
+
* save / saveAll / deleteLines (record key = action id, value =
|
|
11
|
+
* `{ code, modifiers, updatedAt }`), written by the status-bar keymap
|
|
12
|
+
* recorder;
|
|
13
|
+
* - `settings` — the editor's behavior toggles (record key = setting name,
|
|
14
|
+
* value = `{ value, updatedAt }`), written by the status-bar settings
|
|
15
|
+
* panel; unknown-to-this-build keys are never read, so newer clients may
|
|
16
|
+
* store more settings than this build knows.
|
|
17
|
+
*
|
|
18
|
+
* All tables share ONE monotonic `updatedAt` stamp carried by the unit's
|
|
19
|
+
* global singleton, round-tripped for compare-and-set updates.
|
|
20
|
+
*
|
|
21
|
+
* The module imports NOTHING on purpose: `kv` is a `StorageBackend` KvFacet
|
|
22
|
+
* (`open(descriptor)` → unit with `loadAll()/putRecord/deleteRecord(s)/
|
|
23
|
+
* setGlobal/close`, the DSH storage contract) and `now` produces the
|
|
24
|
+
* millisecond stamps, so the factory is unit-testable with in-memory fakes
|
|
25
|
+
* and runs under any profile's node_modules layout.
|
|
26
|
+
*
|
|
27
|
+
* Concurrency shape:
|
|
28
|
+
* - the unit opens lazily on first use and the open is memoized (concurrent
|
|
29
|
+
* callers share one `open` promise; a rejecting open forgets the memo so a
|
|
30
|
+
* later call retries);
|
|
31
|
+
* - every mutating call (`setModePreferences`, `setKeymap`) runs inside ONE
|
|
32
|
+
* internal write chain (promise queue) that serializes writes — the KV unit
|
|
33
|
+
* does NOT serialize writes itself, and each write must read fresh state,
|
|
34
|
+
* diff records, and restamp the global as one uninterrupted critical
|
|
35
|
+
* section. A rejected write never poisons the chain. Reads stay outside the
|
|
36
|
+
* chain: `loadAll` re-reads the medium and never mutates, so a read may
|
|
37
|
+
* honestly observe a write that settled a beat earlier.
|
|
38
|
+
*
|
|
39
|
+
* Shared CAS token: the unit's global `updatedAt` is the compare-and-set
|
|
40
|
+
* guard for BOTH tables. A `setKeymap` write restamps the token, so a
|
|
41
|
+
* concurrent `setModePreferences` carrying the older token fails its CAS with
|
|
42
|
+
* `mode-preferences/conflict` (and symmetrically `keymap/conflict`) — the
|
|
43
|
+
* client refetches and retries. That is intentional: one unit, one stamp, no
|
|
44
|
+
* cross-table lost updates.
|
|
45
|
+
*
|
|
46
|
+
* Failure policy: fail loud. A backend whose medium rejects (`loadAll` on an
|
|
47
|
+
* unmounted backend, a closed unit) propagates that rejection to the caller.
|
|
48
|
+
*
|
|
49
|
+
* @module @dybai/dsh-editor/host/preferences-service
|
|
50
|
+
*/
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Static identity and shape of the `dsh_editor` KV unit (storage contract).
|
|
54
|
+
* Unit and table names must satisfy the DSH storage contract's
|
|
55
|
+
* `UNIT_NAME_RE = /^[a-z][a-z0-9_]*$/` (lowercase/digits/underscores only) —
|
|
56
|
+
* the earlier `dsh-editor` / `modeAssociations` spellings were rejected by
|
|
57
|
+
* `open()`, so NO data was ever persisted under them and this unit starts
|
|
58
|
+
* fresh at version 1 with no migration surface.
|
|
59
|
+
*/
|
|
60
|
+
const UNIT_DESCRIPTOR = Object.freeze({
|
|
61
|
+
name: 'dsh_editor',
|
|
62
|
+
version: 1,
|
|
63
|
+
tables: Object.freeze(['mode_associations', 'keymap', 'settings']),
|
|
64
|
+
hasGlobal: true
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
/** Table whose records are the associations: record key = glob. */
|
|
68
|
+
const TABLE = 'mode_associations';
|
|
69
|
+
/** Table whose records are the key bindings: record key = action id. */
|
|
70
|
+
const KEYMAP_TABLE = 'keymap';
|
|
71
|
+
/** Table whose records are the behavior toggles: record key = setting name. */
|
|
72
|
+
const SETTINGS_TABLE = 'settings';
|
|
73
|
+
|
|
74
|
+
/** Setting names this build knows; unknown keys in a payload are rejected. */
|
|
75
|
+
const SETTINGS_KEYS = new Set(['autoReloadClean', 'highlightActiveLine', 'showLineNumbers']);
|
|
76
|
+
|
|
77
|
+
/** Keymap action ids the editor framework owns (spec §6). */
|
|
78
|
+
const KEYMAP_ACTIONS = new Set(['save', 'saveAll', 'deleteLines']);
|
|
79
|
+
/** Storable `KeyboardEvent.code` alphabet for a keymap binding. */
|
|
80
|
+
const KEYMAP_CODE_RE = /^(Key[A-Z]|Digit[0-9])$/;
|
|
81
|
+
/** Abstract modifier vocabulary for a keymap binding. */
|
|
82
|
+
const KEYMAP_MODIFIERS = new Set(['primary', 'control', 'alt', 'shift', 'meta']);
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Build the plain-Error stand-in for a DOMException AbortError; the storage
|
|
86
|
+
* and RPC layers only switch on `name`, so a real DOMException is unnecessary.
|
|
87
|
+
* @returns a fresh Error with `name` 'AbortError'.
|
|
88
|
+
*/
|
|
89
|
+
function abortError() {
|
|
90
|
+
const error = new Error('aborted');
|
|
91
|
+
error.name = 'AbortError';
|
|
92
|
+
return error;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Reject immediately when the caller's signal is already aborted.
|
|
97
|
+
* @param signal - caller cancellation (`AbortSignal`-shaped), last parameter
|
|
98
|
+
* of every service method per the SRC cancellation convention.
|
|
99
|
+
*/
|
|
100
|
+
function throwIfAborted(signal) {
|
|
101
|
+
if (signal !== undefined && signal !== null && signal.aborted === true) throw abortError();
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Build a stable-code error (`message` === `code`, plus a `.code` property the
|
|
106
|
+
* client can switch on).
|
|
107
|
+
* @param code - stable discriminant, e.g. 'mode-preferences/conflict'.
|
|
108
|
+
* @returns a fresh Error carrying the code.
|
|
109
|
+
*/
|
|
110
|
+
function codedError(code) {
|
|
111
|
+
const error = new Error(code);
|
|
112
|
+
error.code = code;
|
|
113
|
+
return error;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Read the `updatedAt` number out of the unit's global singleton.
|
|
118
|
+
* @param global - the global slot as `loadAll` returned it (`null` when never
|
|
119
|
+
* written).
|
|
120
|
+
* @returns the stored number, or 0 when nothing was written yet.
|
|
121
|
+
*/
|
|
122
|
+
function globalUpdatedAt(global) {
|
|
123
|
+
if (global !== null && typeof global === 'object' && typeof global.updatedAt === 'number') {
|
|
124
|
+
return global.updatedAt;
|
|
125
|
+
}
|
|
126
|
+
return 0;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* One table's records out of a `loadAll` snapshot (`{}` when absent).
|
|
131
|
+
* @param snapshot - the `loadAll` result.
|
|
132
|
+
* @param name - table name.
|
|
133
|
+
* @returns the table's record map.
|
|
134
|
+
*/
|
|
135
|
+
function tableOf(snapshot, name) {
|
|
136
|
+
return snapshot.tables !== null && typeof snapshot.tables === 'object' ? snapshot.tables[name] ?? {} : {};
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Validate the keymap payload: a NON-EMPTY array of
|
|
141
|
+
* `{ action ∈ {save, saveAll, deleteLines}, code: /^(Key[A-Z]|Digit[0-9])$/,
|
|
142
|
+
* modifiers: array ⊆ {primary, control, alt, shift, meta} }` with unique
|
|
143
|
+
* action ids and no two bindings sharing one (code, modifier-set) combo — a
|
|
144
|
+
* duplicated combo would make dispatch ambiguous. Extra properties are
|
|
145
|
+
* tolerated (only the contract fields are read).
|
|
146
|
+
* @param bindings - the caller's payload.
|
|
147
|
+
* @returns whether the payload is storable.
|
|
148
|
+
*/
|
|
149
|
+
function isValidKeymapBindings(bindings) {
|
|
150
|
+
if (!Array.isArray(bindings) || bindings.length === 0) return false;
|
|
151
|
+
const actions = new Set();
|
|
152
|
+
const combos = new Set();
|
|
153
|
+
for (const binding of bindings) {
|
|
154
|
+
if (binding === null || typeof binding !== 'object') return false;
|
|
155
|
+
if (!KEYMAP_ACTIONS.has(binding.action)) return false;
|
|
156
|
+
if (actions.has(binding.action)) return false; // duplicate action
|
|
157
|
+
actions.add(binding.action);
|
|
158
|
+
if (typeof binding.code !== 'string' || !KEYMAP_CODE_RE.test(binding.code)) return false;
|
|
159
|
+
if (!Array.isArray(binding.modifiers)) return false;
|
|
160
|
+
const set = new Set();
|
|
161
|
+
for (const modifier of binding.modifiers) {
|
|
162
|
+
if (typeof modifier !== 'string' || !KEYMAP_MODIFIERS.has(modifier)) return false;
|
|
163
|
+
set.add(modifier);
|
|
164
|
+
}
|
|
165
|
+
const combo = `${binding.code}|${[...set].sort().join('+')}`;
|
|
166
|
+
if (combos.has(combo)) return false; // duplicate combo across actions
|
|
167
|
+
combos.add(combo);
|
|
168
|
+
}
|
|
169
|
+
return true;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Validate the associations payload: an array of
|
|
174
|
+
* `{ glob: non-empty string, modeId: non-empty string }`. Extra properties are
|
|
175
|
+
* tolerated (only the contract fields are read); duplicate globs are not
|
|
176
|
+
* rejected — the complete-set write upserts by glob, so the last entry wins.
|
|
177
|
+
* @param associations - the caller's payload.
|
|
178
|
+
* @returns whether the payload is storable.
|
|
179
|
+
*/
|
|
180
|
+
function isValidAssociations(associations) {
|
|
181
|
+
if (!Array.isArray(associations)) return false;
|
|
182
|
+
for (const entry of associations) {
|
|
183
|
+
if (entry === null || typeof entry !== 'object') return false;
|
|
184
|
+
if (typeof entry.glob !== 'string' || entry.glob.length === 0) return false;
|
|
185
|
+
if (typeof entry.modeId !== 'string' || entry.modeId.length === 0) return false;
|
|
186
|
+
}
|
|
187
|
+
return true;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Validate the settings payload: a plain object whose keys are all setting
|
|
192
|
+
* names this build knows and whose values are all booleans. An EMPTY object
|
|
193
|
+
* is valid — it means "reset to defaults" (full-set replace deletes every
|
|
194
|
+
* stored record). Extra/unknown keys are rejected so a typo never silently
|
|
195
|
+
* persists a setting this build would never read back.
|
|
196
|
+
* @param settings - the caller's payload.
|
|
197
|
+
* @returns whether the payload is storable.
|
|
198
|
+
*/
|
|
199
|
+
function isValidSettings(settings) {
|
|
200
|
+
if (settings === null || typeof settings !== 'object' || Array.isArray(settings)) return false;
|
|
201
|
+
for (const key of Object.keys(settings)) {
|
|
202
|
+
if (!SETTINGS_KEYS.has(key)) return false;
|
|
203
|
+
if (typeof settings[key] !== 'boolean') return false;
|
|
204
|
+
}
|
|
205
|
+
return true;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Build the mode-preferences service.
|
|
210
|
+
* @param kv - a `StorageBackend` KvFacet (`open(descriptor)` → `KvUnit`).
|
|
211
|
+
* @param now - clock producing millisecond `updatedAt` stamps.
|
|
212
|
+
* @returns the service (methods on its prototype so a Host SRC registration
|
|
213
|
+
* can read them for remote discovery); also carries `close()` for disposal.
|
|
214
|
+
*/
|
|
215
|
+
export function createPreferencesService({ kv, now }) {
|
|
216
|
+
if (kv === undefined || kv === null || typeof kv.open !== 'function') {
|
|
217
|
+
throw new Error('dsh-editor: createPreferencesService requires a kv facet with open(descriptor)');
|
|
218
|
+
}
|
|
219
|
+
if (typeof now !== 'function') {
|
|
220
|
+
throw new Error('dsh-editor: createPreferencesService requires a now() clock function');
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** Memoized `kv.open(UNIT_DESCRIPTOR)`; undefined until first use. */
|
|
224
|
+
let unitPromise;
|
|
225
|
+
/** Tail of the serialized write queue; always settled, never rejecting. */
|
|
226
|
+
let writeChain = Promise.resolve();
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Open the unit lazily, memoizing the open so concurrent callers share one
|
|
230
|
+
* promise. A rejecting open forgets the memo so a later call retries
|
|
231
|
+
* instead of caching the failure forever.
|
|
232
|
+
* @returns the open unit promise.
|
|
233
|
+
*/
|
|
234
|
+
function openUnit() {
|
|
235
|
+
if (unitPromise === undefined) {
|
|
236
|
+
const opening = kv.open(UNIT_DESCRIPTOR);
|
|
237
|
+
unitPromise = opening;
|
|
238
|
+
opening.catch(() => {
|
|
239
|
+
if (unitPromise === opening) unitPromise = undefined;
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
return unitPromise;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Append one serialized job to the write chain. The returned promise
|
|
247
|
+
* settles with the job's outcome while the chain's tail stays resolved,
|
|
248
|
+
* so one rejected write never poisons the next.
|
|
249
|
+
* @param job - async critical section to run once all earlier writes settled.
|
|
250
|
+
* @returns the job's own outcome.
|
|
251
|
+
*/
|
|
252
|
+
function enqueue(job) {
|
|
253
|
+
const run = writeChain.then(job, job);
|
|
254
|
+
writeChain = run.then(
|
|
255
|
+
() => {},
|
|
256
|
+
() => {}
|
|
257
|
+
);
|
|
258
|
+
return run;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
return Object.create({
|
|
262
|
+
/**
|
|
263
|
+
* Read the complete association set.
|
|
264
|
+
* @param signal - caller cancellation (last parameter, SRC convention).
|
|
265
|
+
* @returns `{ associations: [{ glob, modeId }] sorted by glob, updatedAt }`
|
|
266
|
+
* — `updatedAt` is 0 before the first successful set.
|
|
267
|
+
*/
|
|
268
|
+
async getModePreferences(signal) {
|
|
269
|
+
throwIfAborted(signal);
|
|
270
|
+
const unit = await openUnit();
|
|
271
|
+
const snapshot = await unit.loadAll();
|
|
272
|
+
throwIfAborted(signal);
|
|
273
|
+
const records = tableOf(snapshot, TABLE);
|
|
274
|
+
const associations = Object.keys(records)
|
|
275
|
+
.filter((glob) => {
|
|
276
|
+
const value = records[glob];
|
|
277
|
+
return value !== null && typeof value === 'object';
|
|
278
|
+
})
|
|
279
|
+
.sort()
|
|
280
|
+
.map((glob) => ({ glob, modeId: records[glob].modeId }));
|
|
281
|
+
return { associations, updatedAt: globalUpdatedAt(snapshot.global) };
|
|
282
|
+
},
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* Replace the complete association set (records absent from the array
|
|
286
|
+
* are deleted), restamping the unit's global `updatedAt`.
|
|
287
|
+
* @param associations - the complete new set; validated before the
|
|
288
|
+
* write chain, so an invalid payload never touches storage.
|
|
289
|
+
* @param expectedUpdatedAt - compare-and-set guard: when provided and
|
|
290
|
+
* not equal to the storage's current `updatedAt`, the write rejects
|
|
291
|
+
* with `mode-preferences/conflict` and storage is untouched. Omit (or
|
|
292
|
+
* pass `undefined`) to write unconditionally.
|
|
293
|
+
* @param signal - caller cancellation (last parameter, SRC convention).
|
|
294
|
+
* @returns `{ updatedAt }` of the settled write.
|
|
295
|
+
*/
|
|
296
|
+
async setModePreferences(associations, expectedUpdatedAt, signal) {
|
|
297
|
+
if (!isValidAssociations(associations)) {
|
|
298
|
+
throw codedError('mode-preferences/invalid-associations');
|
|
299
|
+
}
|
|
300
|
+
throwIfAborted(signal);
|
|
301
|
+
return enqueue(async () => {
|
|
302
|
+
throwIfAborted(signal);
|
|
303
|
+
const unit = await openUnit();
|
|
304
|
+
const snapshot = await unit.loadAll();
|
|
305
|
+
const records = tableOf(snapshot, TABLE);
|
|
306
|
+
const currentUpdatedAt = globalUpdatedAt(snapshot.global);
|
|
307
|
+
if (expectedUpdatedAt !== undefined && expectedUpdatedAt !== currentUpdatedAt) {
|
|
308
|
+
throw codedError('mode-preferences/conflict');
|
|
309
|
+
}
|
|
310
|
+
const existingKeys = Object.keys(records);
|
|
311
|
+
if (existingKeys.length > 0) {
|
|
312
|
+
await unit.deleteRecords(TABLE, existingKeys);
|
|
313
|
+
}
|
|
314
|
+
const updatedAt = now();
|
|
315
|
+
for (const { glob, modeId } of associations) {
|
|
316
|
+
await unit.putRecord(TABLE, glob, { modeId, updatedAt });
|
|
317
|
+
}
|
|
318
|
+
await unit.setGlobal({ updatedAt });
|
|
319
|
+
throwIfAborted(signal);
|
|
320
|
+
return { updatedAt };
|
|
321
|
+
});
|
|
322
|
+
},
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Read the complete framework keymap (spec §6: the self-managed
|
|
326
|
+
* save/saveAll/deleteLines bindings).
|
|
327
|
+
* @param signal - caller cancellation (last parameter, SRC convention).
|
|
328
|
+
* @returns `{ bindings: [{ action, code, modifiers }] sorted by action,
|
|
329
|
+
* updatedAt }` — `bindings` is empty before the first successful set
|
|
330
|
+
* (the client then falls back to its built-in defaults); `updatedAt`
|
|
331
|
+
* is the SHARED token (see the module doc: associations and keymap
|
|
332
|
+
* CAS against the same global stamp).
|
|
333
|
+
*/
|
|
334
|
+
async getKeymap(signal) {
|
|
335
|
+
throwIfAborted(signal);
|
|
336
|
+
const unit = await openUnit();
|
|
337
|
+
const snapshot = await unit.loadAll();
|
|
338
|
+
throwIfAborted(signal);
|
|
339
|
+
const records = tableOf(snapshot, KEYMAP_TABLE);
|
|
340
|
+
const bindings = Object.keys(records)
|
|
341
|
+
.filter((action) => KEYMAP_ACTIONS.has(action) && records[action] !== null && typeof records[action] === 'object')
|
|
342
|
+
.sort()
|
|
343
|
+
.map((action) => ({
|
|
344
|
+
action,
|
|
345
|
+
code: records[action].code,
|
|
346
|
+
modifiers: Array.isArray(records[action].modifiers) ? records[action].modifiers : undefined
|
|
347
|
+
}));
|
|
348
|
+
return { bindings, updatedAt: globalUpdatedAt(snapshot.global) };
|
|
349
|
+
},
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* Replace the complete keymap (records absent from the array are
|
|
353
|
+
* deleted), restamping the unit's SHARED global `updatedAt` — which
|
|
354
|
+
* invalidates any pending associations CAS against the older token.
|
|
355
|
+
* @param bindings - the complete new set (`[{ action, code, modifiers }]`);
|
|
356
|
+
* validated before the write chain, so an invalid payload never
|
|
357
|
+
* touches storage.
|
|
358
|
+
* @param expectedUpdatedAt - compare-and-set guard against the SHARED
|
|
359
|
+
* token: when provided and not equal to the storage's current
|
|
360
|
+
* `updatedAt`, the write rejects with `keymap/conflict` and storage is
|
|
361
|
+
* untouched. Omit (or pass `undefined`) to write unconditionally.
|
|
362
|
+
* @param signal - caller cancellation (last parameter, SRC convention).
|
|
363
|
+
* @returns `{ updatedAt }` of the settled write.
|
|
364
|
+
*/
|
|
365
|
+
async setKeymap(bindings, expectedUpdatedAt, signal) {
|
|
366
|
+
if (!isValidKeymapBindings(bindings)) {
|
|
367
|
+
throw codedError('keymap/invalid');
|
|
368
|
+
}
|
|
369
|
+
throwIfAborted(signal);
|
|
370
|
+
return enqueue(async () => {
|
|
371
|
+
throwIfAborted(signal);
|
|
372
|
+
const unit = await openUnit();
|
|
373
|
+
const snapshot = await unit.loadAll();
|
|
374
|
+
const records = tableOf(snapshot, KEYMAP_TABLE);
|
|
375
|
+
const currentUpdatedAt = globalUpdatedAt(snapshot.global);
|
|
376
|
+
if (expectedUpdatedAt !== undefined && expectedUpdatedAt !== currentUpdatedAt) {
|
|
377
|
+
throw codedError('keymap/conflict');
|
|
378
|
+
}
|
|
379
|
+
const existingKeys = Object.keys(records);
|
|
380
|
+
if (existingKeys.length > 0) {
|
|
381
|
+
await unit.deleteRecords(KEYMAP_TABLE, existingKeys);
|
|
382
|
+
}
|
|
383
|
+
const updatedAt = now();
|
|
384
|
+
for (const { action, code, modifiers } of bindings) {
|
|
385
|
+
await unit.putRecord(KEYMAP_TABLE, action, { code, modifiers, updatedAt });
|
|
386
|
+
}
|
|
387
|
+
await unit.setGlobal({ updatedAt });
|
|
388
|
+
throwIfAborted(signal);
|
|
389
|
+
return { updatedAt };
|
|
390
|
+
});
|
|
391
|
+
},
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* Read the stored behavior settings (spec: the settings panel's
|
|
395
|
+
* toggles). Settings this build knows but storage never wrote come
|
|
396
|
+
* back absent — the client applies its own defaults; unknown keys
|
|
397
|
+
* that somehow reached the medium (older bug, hand edit) are ignored.
|
|
398
|
+
* @param signal - caller cancellation (last parameter, SRC convention).
|
|
399
|
+
* @returns `{ settings: { [name]: boolean }, updatedAt }` — `updatedAt`
|
|
400
|
+
* is the SHARED token (see the module doc).
|
|
401
|
+
*/
|
|
402
|
+
async getSettings(signal) {
|
|
403
|
+
throwIfAborted(signal);
|
|
404
|
+
const unit = await openUnit();
|
|
405
|
+
const snapshot = await unit.loadAll();
|
|
406
|
+
throwIfAborted(signal);
|
|
407
|
+
const records = tableOf(snapshot, SETTINGS_TABLE);
|
|
408
|
+
const settings = {};
|
|
409
|
+
for (const key of SETTINGS_KEYS) {
|
|
410
|
+
const record = records[key];
|
|
411
|
+
if (record !== null && typeof record === 'object' && typeof record.value === 'boolean') {
|
|
412
|
+
settings[key] = record.value;
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
return { settings, updatedAt: globalUpdatedAt(snapshot.global) };
|
|
416
|
+
},
|
|
417
|
+
|
|
418
|
+
/**
|
|
419
|
+
* Replace the complete settings set (records absent from the object
|
|
420
|
+
* are deleted; `{}` resets to defaults), restamping the unit's SHARED
|
|
421
|
+
* global `updatedAt`.
|
|
422
|
+
* @param settings - the complete new set (keys ⊆ known setting names,
|
|
423
|
+
* values all booleans); validated before the write chain, so an
|
|
424
|
+
* invalid payload never touches storage.
|
|
425
|
+
* @param expectedUpdatedAt - compare-and-set guard against the SHARED
|
|
426
|
+
* token: when provided and not equal to the storage's current
|
|
427
|
+
* `updatedAt`, the write rejects with `settings/conflict` and storage
|
|
428
|
+
* is untouched. Omit (or pass `undefined`) to write unconditionally.
|
|
429
|
+
* @param signal - caller cancellation (last parameter, SRC convention).
|
|
430
|
+
* @returns `{ updatedAt }` of the settled write.
|
|
431
|
+
*/
|
|
432
|
+
async setSettings(settings, expectedUpdatedAt, signal) {
|
|
433
|
+
if (!isValidSettings(settings)) {
|
|
434
|
+
throw codedError('settings/invalid');
|
|
435
|
+
}
|
|
436
|
+
throwIfAborted(signal);
|
|
437
|
+
return enqueue(async () => {
|
|
438
|
+
throwIfAborted(signal);
|
|
439
|
+
const unit = await openUnit();
|
|
440
|
+
const snapshot = await unit.loadAll();
|
|
441
|
+
const records = tableOf(snapshot, SETTINGS_TABLE);
|
|
442
|
+
const currentUpdatedAt = globalUpdatedAt(snapshot.global);
|
|
443
|
+
if (expectedUpdatedAt !== undefined && expectedUpdatedAt !== currentUpdatedAt) {
|
|
444
|
+
throw codedError('settings/conflict');
|
|
445
|
+
}
|
|
446
|
+
const existingKeys = Object.keys(records);
|
|
447
|
+
if (existingKeys.length > 0) {
|
|
448
|
+
await unit.deleteRecords(SETTINGS_TABLE, existingKeys);
|
|
449
|
+
}
|
|
450
|
+
const updatedAt = now();
|
|
451
|
+
for (const key of Object.keys(settings)) {
|
|
452
|
+
await unit.putRecord(SETTINGS_TABLE, key, { value: settings[key], updatedAt });
|
|
453
|
+
}
|
|
454
|
+
await unit.setGlobal({ updatedAt });
|
|
455
|
+
throwIfAborted(signal);
|
|
456
|
+
return { updatedAt };
|
|
457
|
+
});
|
|
458
|
+
},
|
|
459
|
+
|
|
460
|
+
/**
|
|
461
|
+
* Drain the write chain, close the unit when one was opened, and forget
|
|
462
|
+
* the open so a later call reopens lazily. Idempotent; wired into the
|
|
463
|
+
* plugin's effect cleanup so a fiber restart never trips the storage
|
|
464
|
+
* contract's "same unit opened twice" rejection.
|
|
465
|
+
* @returns resolution after the unit (if any) is released.
|
|
466
|
+
*/
|
|
467
|
+
async close() {
|
|
468
|
+
const closing = writeChain.then(async () => {
|
|
469
|
+
if (unitPromise === undefined) return;
|
|
470
|
+
const unit = await unitPromise;
|
|
471
|
+
unitPromise = undefined;
|
|
472
|
+
await unit.close();
|
|
473
|
+
});
|
|
474
|
+
writeChain = closing.then(
|
|
475
|
+
() => {},
|
|
476
|
+
() => {}
|
|
477
|
+
);
|
|
478
|
+
return closing;
|
|
479
|
+
}
|
|
480
|
+
});
|
|
481
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Workspace file-write service — the Host half's editor save path.
|
|
3
|
+
*
|
|
4
|
+
* `createFileService(fs, sandboxPolicy, sessions)` builds the whole-file text
|
|
5
|
+
* write with optimistic version checking that the browser editor calls as
|
|
6
|
+
* `dshEditor/writeFile`. Moved verbatim from the plugin entry (`index.js`)
|
|
7
|
+
* into this unit-testable module; every capability is injected, so the module
|
|
8
|
+
* imports nothing.
|
|
9
|
+
*
|
|
10
|
+
* The sandbox policy is resolved for the OWNING session
|
|
11
|
+
* (`sandboxPolicy.resolve({ session })`), so the write is evaluated against
|
|
12
|
+
* the session's own workspace boundary exactly like the agent's own file
|
|
13
|
+
* tools; an omitted policy would classify the gateway call as agentless and
|
|
14
|
+
* check it against the deployment fallback root.
|
|
15
|
+
*
|
|
16
|
+
* @module @dybai/dsh-editor/host/write-service
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/** Character cap for one editor write. */
|
|
20
|
+
const MAX_CONTENT_CHARS = 4 * 1024 * 1024;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Build the file-write service.
|
|
24
|
+
* @param fs - the Host filesystem service (`resolve`/`writeText`).
|
|
25
|
+
* @param sandboxPolicy - the sandbox-policy service (`resolve`).
|
|
26
|
+
* @param sessions - the session registry (`get`).
|
|
27
|
+
* @returns the service instance (method on its prototype for SRC discovery).
|
|
28
|
+
*/
|
|
29
|
+
export function createFileService(fs, sandboxPolicy, sessions) {
|
|
30
|
+
const NUL = /\u0000/;
|
|
31
|
+
return Object.create({
|
|
32
|
+
/**
|
|
33
|
+
* Write one whole text file inside the Session's workspace.
|
|
34
|
+
* @param workspaceFileScope - Gateway-resolved `{ sessionId, workspaceRoot }` for the wire session id.
|
|
35
|
+
* @param path - absolute path or workspace-relative path, as `workspaceFiles.read` accepts.
|
|
36
|
+
* @param content - complete replacement text.
|
|
37
|
+
* @param baseVersion - version the edit was based on; an empty string writes unconditionally.
|
|
38
|
+
* @param signal - caller cancellation (last parameter, SRC convention).
|
|
39
|
+
* @returns `{ operation, version }` of the settled write.
|
|
40
|
+
*/
|
|
41
|
+
async writeFile(workspaceFileScope, path, content, baseVersion, signal) {
|
|
42
|
+
if (typeof path !== 'string' || path.length === 0) {
|
|
43
|
+
throw new Error('dsh-editor: "path" must be a non-empty string');
|
|
44
|
+
}
|
|
45
|
+
if (typeof content !== 'string') {
|
|
46
|
+
throw new Error('dsh-editor: "content" must be a string');
|
|
47
|
+
}
|
|
48
|
+
if (content.length > MAX_CONTENT_CHARS) {
|
|
49
|
+
throw new Error(`dsh-editor: content is larger than the ${MAX_CONTENT_CHARS} character write cap`);
|
|
50
|
+
}
|
|
51
|
+
if (NUL.test(content)) {
|
|
52
|
+
throw new Error('dsh-editor: content contains NUL bytes and cannot be written as text');
|
|
53
|
+
}
|
|
54
|
+
const scope =
|
|
55
|
+
workspaceFileScope !== null && typeof workspaceFileScope === 'object' ? workspaceFileScope : {};
|
|
56
|
+
const cwd = scope.workspaceRoot;
|
|
57
|
+
const session = typeof scope.sessionId === 'string' ? sessions.get(scope.sessionId) : undefined;
|
|
58
|
+
// The write must be evaluated under the OWNING session's policy: a
|
|
59
|
+
// gateway call without a policy is classified as agentless and checked
|
|
60
|
+
// against the deployment fallback root (`process.cwd()`), which denies
|
|
61
|
+
// files that sit inside the session workspace.
|
|
62
|
+
const policy = sandboxPolicy.resolve(session === undefined ? {} : { session });
|
|
63
|
+
const target = await fs.resolve(path, cwd === undefined ? { signal } : { cwd, signal });
|
|
64
|
+
const expected =
|
|
65
|
+
typeof baseVersion === 'string' && baseVersion.length > 0
|
|
66
|
+
? { kind: 'replaceIfVersion', version: baseVersion }
|
|
67
|
+
: undefined;
|
|
68
|
+
let outcome;
|
|
69
|
+
try {
|
|
70
|
+
outcome = await fs.writeText(target, content, expected, signal, policy);
|
|
71
|
+
} catch (error) {
|
|
72
|
+
throw remoteOf(error);
|
|
73
|
+
}
|
|
74
|
+
return { operation: outcome.operation, version: outcome.version };
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Translate a thrown error into the wire failure the Typert Gateway keeps
|
|
81
|
+
* intact. The Gateway's failure encoder preserves `code` ONLY for errors
|
|
82
|
+
* carrying the structural RemoteError marker; everything else degrades to
|
|
83
|
+
* `gateway/internal` with just the message. The fs layer's `FsError` has no
|
|
84
|
+
* marker, so a stale-version rejection (`FS_STALE_VERSION`) would reach the
|
|
85
|
+
* browser as an anonymous failure and the editor's `/stale/i` conflict
|
|
86
|
+
* detection would never fire — so stale rejections are re-wrapped here with
|
|
87
|
+
* the marker (code, message, empty details) and everything else propagates
|
|
88
|
+
* unchanged.
|
|
89
|
+
* @param error - the caught rejection.
|
|
90
|
+
* @returns the same rejection when it is already marker-carrying, a
|
|
91
|
+
* marker-carrying twin of it when its `code` is `FS_STALE_VERSION`, otherwise
|
|
92
|
+
* the original error.
|
|
93
|
+
*/
|
|
94
|
+
function remoteOf(error) {
|
|
95
|
+
if (
|
|
96
|
+
error !== null &&
|
|
97
|
+
typeof error === 'object' &&
|
|
98
|
+
error.isDSHRemoteError !== true &&
|
|
99
|
+
error.code === 'FS_STALE_VERSION'
|
|
100
|
+
) {
|
|
101
|
+
const remote = new Error(error instanceof Error ? error.message : String(error));
|
|
102
|
+
remote.name = 'RemoteError';
|
|
103
|
+
remote.isDSHRemoteError = true;
|
|
104
|
+
remote.code = 'FS_STALE_VERSION';
|
|
105
|
+
remote.details = {};
|
|
106
|
+
return remote;
|
|
107
|
+
}
|
|
108
|
+
return error;
|
|
109
|
+
}
|
package/icon.svg
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" aria-hidden="true">
|
|
2
|
+
<path d="M6 3.75h8.5L19 8.25V20.25H6z" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round"/>
|
|
3
|
+
<path d="M14 3.75v4.5h4.5" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round"/>
|
|
4
|
+
<path d="m8.9 16.1 5.6-5.6 1.9 1.9-5.6 5.6-2.5.6z" stroke="currentColor" stroke-width="1.3" stroke-linejoin="round"/>
|
|
5
|
+
</svg>
|