Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

keybindings.ts

718 lines24.9 KB

1import {
2 KeybindingRule,
3 KeybindingsConfig,
4 KeybindingsConfigError,
5 KeybindingShortcut,
6 KeybindingWhenNode,
7 MAX_KEYBINDINGS_COUNT,
8 ResolvedKeybindingRule,
9 ResolvedKeybindingsConfig,
10 type ServerRemoveKeybindingInput,
11 type ServerUpsertKeybindingInput,
12 type ServerConfigIssue,
13} from "@t3tools/contracts";
14import * as Array from "effect/Array";
15import * as Cache from "effect/Cache";
16import * as Cause from "effect/Cause";
17import * as Deferred from "effect/Deferred";
18import * as Duration from "effect/Duration";
19import * as Effect from "effect/Effect";
20import * as Exit from "effect/Exit";
21import * as FileSystem from "effect/FileSystem";
22import * as Path from "effect/Path";
23import * as Layer from "effect/Layer";
24import * as Predicate from "effect/Predicate";
25import * as PubSub from "effect/PubSub";
26import * as Result from "effect/Result";
27import * as Schema from "effect/Schema";
28import * as SchemaIssue from "effect/SchemaIssue";
29import * as SchemaTransformation from "effect/SchemaTransformation";
30import * as Ref from "effect/Ref";
31import * as Context from "effect/Context";
32import * as Scope from "effect/Scope";
33import * as Stream from "effect/Stream";
34import * as Semaphore from "effect/Semaphore";
35import * as ServerConfig from "./config.ts";
36import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
37import { fromJsonStringPretty, fromLenientJson } from "@t3tools/shared/schemaJson";
38import {
39 DEFAULT_KEYBINDINGS,
40 mergeWithDefaultKeybindings,
41 compileResolvedKeybindingRule,
42 compileResolvedKeybindingsConfig,
43 parseKeybindingShortcut,
44} from "@t3tools/shared/keybindings";
45​
46export {
47 DEFAULT_KEYBINDINGS,
48 compileResolvedKeybindingRule,
49 compileResolvedKeybindingsConfig,
50 parseKeybindingShortcut,
51};
52​
53export const ResolvedKeybindingFromConfig = KeybindingRule.pipe(
54 Schema.decodeTo(
55 Schema.toType(ResolvedKeybindingRule),
56 SchemaTransformation.transformEffect({
57 decode: (rule) =>
58 Effect.succeed(compileResolvedKeybindingRule(rule)).pipe(
59 Effect.filterOrFail(
60 Predicate.isNotNull,
61 () =>
62 new SchemaIssue.InvalidValue({
63 message: "Invalid keybinding rule",
64 }),
65 ),
66 Effect.map((resolved) => resolved),
67 ),
68​
69 encode: Effect.fn("keybindings.encode")(function* (resolved) {
70 const key = encodeShortcut(resolved.shortcut);
71 if (!key) {
72 return yield* Effect.fail(
73 new SchemaIssue.InvalidValue({
74 message: "Resolved shortcut cannot be encoded to key string",
75 }),
76 );
77 }
78​
79 const when = resolved.whenAst ? encodeWhenAst(resolved.whenAst) : undefined;
80 return {
81 key,
82 command: resolved.command,
83 when,
84 };
85 }),
86 }),
87 ),
88);
89​
90function isSameKeybindingRule(left: KeybindingRule, right: KeybindingRule): boolean {
91 return (
92 left.command === right.command &&
93 left.key === right.key &&
94 (left.when ?? undefined) === (right.when ?? undefined)
95 );
97​
98const LATE_DEFAULT_KEYBINDINGS: ReadonlyArray<{
99 readonly id: string;
100 readonly alongside: KeybindingRule;
101 readonly rule: KeybindingRule;
102}> = [
103 {
104 id: "composer.sendBackground:mod+enter",
105 alongside: {
106 key: "mod+alt+enter",
107 command: "composer.sendBackground",
108 when: "composerFocus && draftThreadRoute",
109 },
110 rule: {
111 key: "mod+enter",
112 command: "composer.sendBackground",
113 when: "composerFocus && draftThreadRoute",
114 },
115 },
116];
117​
118function keybindingShortcutContext(rule: KeybindingRule): string | null {
119 const parsed = parseKeybindingShortcut(rule.key);
120 if (!parsed) return null;
121 const encoded = encodeShortcut(parsed);
122 if (!encoded) return null;
123 return `${encoded}\u0000${rule.when ?? ""}`;
125​
126function hasSameShortcutContext(left: KeybindingRule, right: KeybindingRule): boolean {
127 const leftContext = keybindingShortcutContext(left);
128 const rightContext = keybindingShortcutContext(right);
129 if (!leftContext || !rightContext) return false;
130 return leftContext === rightContext;
132​
133function keybindingRuleFromUpsertInput(input: ServerUpsertKeybindingInput): KeybindingRule {
134 return input.when === undefined
135 ? { key: input.key, command: input.command }
136 : { key: input.key, command: input.command, when: input.when };
138​
139function replaceTargetFromUpsertInput(input: ServerUpsertKeybindingInput): KeybindingRule | null {
140 if (!input.replace) return null;
141 return input.replace.when === undefined
142 ? { key: input.replace.key, command: input.replace.command }
143 : { key: input.replace.key, command: input.replace.command, when: input.replace.when };
145​
146function keybindingRuleFromRemoveInput(input: ServerRemoveKeybindingInput): KeybindingRule {
147 return input.when === undefined
148 ? { key: input.key, command: input.command }
149 : { key: input.key, command: input.command, when: input.when };
151​
152function encodeShortcut(shortcut: KeybindingShortcut): string | null {
153 const modifiers: string[] = [];
154 if (shortcut.modKey) modifiers.push("mod");
155 if (shortcut.metaKey) modifiers.push("meta");
156 if (shortcut.ctrlKey) modifiers.push("ctrl");
157 if (shortcut.altKey) modifiers.push("alt");
158 if (shortcut.shiftKey) modifiers.push("shift");
159 if (!shortcut.key) return null;
160 if (shortcut.key !== "+" && shortcut.key.includes("+")) return null;
161 const key = shortcut.key === " " ? "space" : shortcut.key;
162 return [...modifiers, key].join("+");
164​
165function encodeWhenAst(node: KeybindingWhenNode): string {
166 switch (node.type) {
167 case "identifier":
168 return node.name;
169 case "not":
170 return `!(${encodeWhenAst(node.node)})`;
171 case "and":
172 return `(${encodeWhenAst(node.left)} && ${encodeWhenAst(node.right)})`;
173 case "or":
174 return `(${encodeWhenAst(node.left)} || ${encodeWhenAst(node.right)})`;
175 }
177​
178const RawKeybindingsEntries = fromLenientJson(Schema.Array(Schema.Unknown));
179const KeybindingsConfigPrettyJson = fromJsonStringPretty(KeybindingsConfig);
180const decodeKeybindingRuleExit = Schema.decodeUnknownExit(KeybindingRule);
181const decodeResolvedKeybindingFromConfigExit = Schema.decodeExit(ResolvedKeybindingFromConfig);
182const decodeRawKeybindingsEntriesExit = Schema.decodeUnknownExit(RawKeybindingsEntries);
183const encodeKeybindingsConfigPrettyJson = Schema.encodeEffect(KeybindingsConfigPrettyJson);
184​
185export interface KeybindingsConfigState {
186 readonly keybindings: ResolvedKeybindingsConfig;
187 readonly issues: readonly ServerConfigIssue[];
189​
190export interface KeybindingsChangeEvent {
191 readonly keybindings: ResolvedKeybindingsConfig;
192 readonly issues: readonly ServerConfigIssue[];
194​
195function trimIssueMessage(message: string): string {
196 const trimmed = message.trim();
197 return trimmed.length > 0 ? trimmed : "Invalid keybindings configuration.";
199​
200function malformedConfigIssue(detail: string): ServerConfigIssue {
201 return {
202 kind: "keybindings.malformed-config",
203 message: trimIssueMessage(detail),
204 };
206​
207function invalidEntryIssue(index: number, detail: string): ServerConfigIssue {
208 return {
209 kind: "keybindings.invalid-entry",
210 index,
211 message: trimIssueMessage(detail),
212 };
214​
215export class Keybindings extends Context.Service<
216 Keybindings,
217 {
218 readonly start: Effect.Effect<void, KeybindingsConfigError>;
219​
220 readonly ready: Effect.Effect<void, KeybindingsConfigError>;
221​
222 readonly syncDefaultKeybindingsOnStartup: Effect.Effect<void, KeybindingsConfigError>;
223​
224 readonly loadConfigState: Effect.Effect<KeybindingsConfigState, KeybindingsConfigError>;
225​
226 readonly getSnapshot: Effect.Effect<KeybindingsConfigState, KeybindingsConfigError>;
227​
228 readonly streamChanges: Stream.Stream<KeybindingsChangeEvent>;
229​
230 /** Acquire before reading a snapshot to buffer changes until the stream starts. */
231 readonly subscribeChanges: Effect.Effect<
232 Stream.Stream<KeybindingsChangeEvent>,
233 never,
234 Scope.Scope
235 >;
236​
237 /**
238 * Writes config atomically and enforces the max rule count by truncating
239 * oldest entries when needed.
240 */
241 readonly upsertKeybindingRule: (
242 input: ServerUpsertKeybindingInput,
243 ) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;
244​
245 readonly removeKeybindingRule: (
246 input: ServerRemoveKeybindingInput,
247 ) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;
248 }
249>()("t3/keybindings") {}
250​
251const make = Effect.gen(function* () {
252 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
253 const fs = yield* FileSystem.FileSystem;
254 const path = yield* Path.Path;
255 const upsertSemaphore = yield* Semaphore.make(1);
256 const resolvedConfigCacheKey = "resolved" as const;
257 const changesPubSub = yield* PubSub.unbounded<KeybindingsChangeEvent>();
258 const startedRef = yield* Ref.make(false);
259 const startedDeferred = yield* Deferred.make<void, KeybindingsConfigError>();
260 const watcherScope = yield* Scope.make("sequential");
261 yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));
262 const emitChange = (configState: KeybindingsConfigState) =>
263 PubSub.publish(changesPubSub, configState).pipe(Effect.asVoid);
264​
265 const readConfigExists = fs.exists(keybindingsConfigPath).pipe(
266 Effect.mapError(
267 (cause) =>
268 new KeybindingsConfigError({
269 configPath: keybindingsConfigPath,
270 detail: "failed to access keybindings config",
271 cause,
272 }),
273 ),
274 );
275​
276 const readRawConfig = fs.readFileString(keybindingsConfigPath).pipe(
277 Effect.mapError(
278 (cause) =>
279 new KeybindingsConfigError({
280 configPath: keybindingsConfigPath,
281 detail: "failed to read keybindings config",
282 cause,
283 }),
284 ),
285 );
286​
287 const loadWritableCustomKeybindingsConfig = Effect.fn(function* (): Effect.fn.Return<
288 readonly KeybindingRule[],
289 KeybindingsConfigError
290 > {
291 if (!(yield* readConfigExists)) {
292 return [];
293 }
294​
295 const rawConfig = yield* readRawConfig.pipe(
296 Effect.flatMap(Schema.decodeEffect(RawKeybindingsEntries)),
297 Effect.mapError(
298 (cause) =>
299 new KeybindingsConfigError({
300 configPath: keybindingsConfigPath,
301 detail: "expected JSON array",
302 cause,
303 }),
304 ),
305 );
306​
307 return yield* Effect.forEach(rawConfig, (entry) =>
308 Effect.gen(function* () {
309 const decodedRule = decodeKeybindingRuleExit(entry);
310 if (decodedRule._tag === "Failure") {
311 yield* Effect.logWarning("ignoring invalid keybinding entry", {
312 path: keybindingsConfigPath,
313 entry,
314 error: Cause.pretty(decodedRule.cause),
315 });
316 return null;
317 }
318 const resolved = decodeResolvedKeybindingFromConfigExit(decodedRule.value);
319 if (resolved._tag === "Failure") {
320 yield* Effect.logWarning("ignoring invalid keybinding entry", {
321 path: keybindingsConfigPath,
322 entry,
323 error: Cause.pretty(resolved.cause),
324 });
325 return null;
326 }
327 return decodedRule.value;
328 }),
329 ).pipe(Effect.map(Array.filter(Predicate.isNotNull)));
330 });
331​
332 const loadRuntimeCustomKeybindingsConfig = Effect.fn(function* (): Effect.fn.Return<
333 {
334 readonly keybindings: readonly KeybindingRule[];
335 readonly issues: readonly ServerConfigIssue[];
336 },
337 KeybindingsConfigError
338 > {
339 if (!(yield* readConfigExists)) {
340 return { keybindings: [], issues: [] };
341 }
342​
343 const rawConfig = yield* readRawConfig;
344 const decodedEntries = decodeRawKeybindingsEntriesExit(rawConfig);
345 if (decodedEntries._tag === "Failure") {
346 const detail = `expected JSON array (${Cause.pretty(decodedEntries.cause)})`;
347 return {
348 keybindings: [],
349 issues: [malformedConfigIssue(detail)],
350 };
351 }
352​
353 const keybindings: KeybindingRule[] = [];
354 const issues: ServerConfigIssue[] = [];
355 for (const [index, entry] of decodedEntries.value.entries()) {
356 const decodedRule = decodeKeybindingRuleExit(entry);
357 if (decodedRule._tag === "Failure") {
358 const detail = Cause.pretty(decodedRule.cause);
359 issues.push(invalidEntryIssue(index, detail));
360 yield* Effect.logWarning("ignoring invalid keybinding entry", {
361 path: keybindingsConfigPath,
362 index,
363 entry,
364 error: detail,
365 });
366 continue;
367 }
368​
369 const resolvedRule = decodeResolvedKeybindingFromConfigExit(decodedRule.value);
370 if (resolvedRule._tag === "Failure") {
371 const detail = Cause.pretty(resolvedRule.cause);
372 issues.push(invalidEntryIssue(index, detail));
373 yield* Effect.logWarning("ignoring invalid keybinding entry", {
374 path: keybindingsConfigPath,
375 index,
376 entry,
377 error: detail,
378 });
379 continue;
380 }
381 keybindings.push(decodedRule.value);
382 }
383​
384 return { keybindings, issues };
385 });
386​
387 const appliedMigrationsPath = path.join(
388 path.dirname(keybindingsConfigPath),
389 "keybindings-migrations",
390 );
391 const readAppliedMigrationIds = fs.readFileString(appliedMigrationsPath).pipe(
392 Effect.map((contents) => new Set(contents.split("\n").filter((line) => line.length > 0))),
393 Effect.orElseSucceed(() => new Set<string>()),
394 );
395 const recordAppliedMigrations = (ids: Iterable<string>) =>
396 writeFileStringAtomically({
397 filePath: appliedMigrationsPath,
398 contents: `${[...new Set(ids)].join("\n")}\n`,
399 }).pipe(
400 Effect.provideService(FileSystem.FileSystem, fs),
401 Effect.provideService(Path.Path, path),
402 Effect.mapError(
403 (cause) =>
404 new KeybindingsConfigError({
405 configPath: keybindingsConfigPath,
406 detail: "failed to record keybinding migrations",
407 cause,
408 }),
409 ),
410 );
411​
412 const writeConfigAtomically = (rules: readonly KeybindingRule[]) => {
413 return encodeKeybindingsConfigPrettyJson(rules).pipe(
414 Effect.map((encoded) => `${encoded}\n`),
415 Effect.flatMap((encoded) =>
416 writeFileStringAtomically({
417 filePath: keybindingsConfigPath,
418 contents: encoded,
419 }).pipe(
420 Effect.provideService(FileSystem.FileSystem, fs),
421 Effect.provideService(Path.Path, path),
422 ),
423 ),
424 Effect.mapError(
425 (cause) =>
426 new KeybindingsConfigError({
427 configPath: keybindingsConfigPath,
428 detail: "failed to write keybindings config",
429 cause,
430 }),
431 ),
432 );
433 };
434​
435 const loadConfigStateFromDisk = loadRuntimeCustomKeybindingsConfig().pipe(
436 Effect.map(({ keybindings, issues }) => ({
437 keybindings: mergeWithDefaultKeybindings(compileResolvedKeybindingsConfig(keybindings)),
438 issues,
439 })),
440 );
441​
442 const resolvedConfigCache = yield* Cache.makeWith<
443 typeof resolvedConfigCacheKey,
444 KeybindingsConfigState,
445 KeybindingsConfigError
446 >(() => loadConfigStateFromDisk, {
447 capacity: 1,
448 timeToLive: (exit) => (Exit.isSuccess(exit) ? Duration.infinity : Duration.zero),
449 });
450​
451 const loadConfigStateFromCacheOrDisk = Cache.get(resolvedConfigCache, resolvedConfigCacheKey);
452​
453 const revalidateAndEmit = upsertSemaphore.withPermits(1)(
454 Effect.gen(function* () {
455 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
456 const configState = yield* loadConfigStateFromCacheOrDisk;
457 yield* emitChange(configState);
458 }),
459 );
460​
461 const syncDefaultKeybindingsOnStartup = upsertSemaphore.withPermits(1)(
462 Effect.gen(function* () {
463 const appliedMigrationIds = yield* readAppliedMigrationIds;
464 const pendingLateDefaults = LATE_DEFAULT_KEYBINDINGS.filter(
465 (late) => !appliedMigrationIds.has(late.id),
466 );
467 const configExists = yield* readConfigExists;
468 if (!configExists) {
469 yield* writeConfigAtomically(DEFAULT_KEYBINDINGS);
470 if (pendingLateDefaults.length > 0) {
471 yield* recordAppliedMigrations([
472 ...appliedMigrationIds,
473 ...LATE_DEFAULT_KEYBINDINGS.map((late) => late.id),
474 ]);
475 }
476 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
477 return;
478 }
479​
480 const runtimeConfig = yield* loadRuntimeCustomKeybindingsConfig();
481 if (runtimeConfig.issues.length > 0) {
482 yield* Effect.logWarning(
483 "skipping startup keybindings default sync because config has issues",
484 {
485 path: keybindingsConfigPath,
486 issues: runtimeConfig.issues,
487 },
488 );
489 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
490 return;
491 }
492 const customConfig = runtimeConfig.keybindings;
493 const existingCommands = new Set(customConfig.map((entry) => entry.command));
494 const missingDefaults: KeybindingRule[] = [];
495 const shortcutConflictWarnings: Array<{
496 defaultCommand: KeybindingRule["command"];
497 conflictingCommand: KeybindingRule["command"];
498 key: string;
499 when: string | null;
500 }> = [];
501 for (const defaultRule of DEFAULT_KEYBINDINGS) {
502 if (existingCommands.has(defaultRule.command)) {
503 continue;
504 }
505 const conflictingEntry = customConfig.find((entry) =>
506 hasSameShortcutContext(entry, defaultRule),
507 );
508 if (conflictingEntry) {
509 shortcutConflictWarnings.push({
510 defaultCommand: defaultRule.command,
511 conflictingCommand: conflictingEntry.command,
512 key: defaultRule.key,
513 when: defaultRule.when ?? null,
514 });
515 continue;
516 }
517 missingDefaults.push(defaultRule);
518 }
519 for (const { alongside, rule } of pendingLateDefaults) {
520 if (
521 customConfig.some((entry) => isSameKeybindingRule(entry, alongside)) &&
522 !customConfig.some((entry) => hasSameShortcutContext(entry, rule))
523 ) {
524 missingDefaults.push(rule);
525 }
526 }
527 for (const conflict of shortcutConflictWarnings) {
528 yield* Effect.logWarning("skipping default keybinding due to shortcut conflict", {
529 path: keybindingsConfigPath,
530 defaultCommand: conflict.defaultCommand,
531 conflictingCommand: conflict.conflictingCommand,
532 key: conflict.key,
533 when: conflict.when,
534 reason: "shortcut context already used by existing rule",
535 });
536 }
537 if (missingDefaults.length > 0) {
538 const matchingDefaults = Array.filterMap(DEFAULT_KEYBINDINGS, (defaultRule) =>
539 customConfig.some((entry) => isSameKeybindingRule(entry, defaultRule))
540 ? Result.succeed(defaultRule.command)
541 : Result.failVoid,
542 );
543 if (matchingDefaults.length > 0) {
544 yield* Effect.logWarning("default keybinding rule already defined in user config", {
545 path: keybindingsConfigPath,
546 commands: matchingDefaults,
547 });
548 }
549 }
550​
551 // Keep only defaults that fit, before persisted rules so existing
552 // custom shortcuts retain priority when their conditions overlap.
553 const availableSlots = Math.max(0, MAX_KEYBINDINGS_COUNT - customConfig.length);
554 const defaultsToAppend = missingDefaults.slice(0, availableSlots);
555 const skippedDefaults = missingDefaults.slice(availableSlots);
556 if (skippedDefaults.length > 0) {
557 yield* Effect.logWarning("skipping default keybinding backfill at max entries", {
558 path: keybindingsConfigPath,
559 maxEntries: MAX_KEYBINDINGS_COUNT,
560 commands: skippedDefaults.map((rule) => rule.command),
561 });
562 }
563 if (defaultsToAppend.length > 0) {
564 yield* writeConfigAtomically([...defaultsToAppend, ...customConfig]);
565 }
566 const settledLateDefaults = pendingLateDefaults.filter(
567 (late) => !skippedDefaults.includes(late.rule),
568 );
569 if (settledLateDefaults.length > 0) {
570 yield* recordAppliedMigrations([
571 ...appliedMigrationIds,
572 ...settledLateDefaults.map((late) => late.id),
573 ]);
574 }
575 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
576 }),
577 );
578​
579 const startWatcher = Effect.gen(function* () {
580 const keybindingsConfigDir = path.dirname(keybindingsConfigPath);
581 const keybindingsConfigFile = path.basename(keybindingsConfigPath);
582 const keybindingsConfigPathResolved = path.resolve(keybindingsConfigPath);
583​
584 yield* fs.makeDirectory(keybindingsConfigDir, { recursive: true }).pipe(
585 Effect.mapError(
586 (cause) =>
587 new KeybindingsConfigError({
588 configPath: keybindingsConfigPath,
589 detail: "failed to prepare keybindings config directory",
590 cause,
591 }),
592 ),
593 );
594​
595 const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));
596​
597 // Editors emit multiple events per save (truncate, write, rename) and
598 // `fs.watch` can fire before the content has been flushed to disk.
599 const debouncedKeybindingsEvents = fs.watch(keybindingsConfigDir).pipe(
600 Stream.filter((event) => {
601 return (
602 event.path === keybindingsConfigFile ||
603 event.path === keybindingsConfigPath ||
604 path.resolve(keybindingsConfigDir, event.path) === keybindingsConfigPathResolved
605 );
606 }),
607 Stream.debounce(Duration.millis(100)),
608 );
609​
610 yield* Stream.runForEach(debouncedKeybindingsEvents, () => revalidateAndEmitSafely).pipe(
611 Effect.ignoreCause({ log: true }),
612 Effect.forkIn(watcherScope),
613 Effect.asVoid,
614 );
615 });
616​
617 const start = Effect.gen(function* () {
618 const alreadyStarted = yield* Ref.get(startedRef);
619 if (alreadyStarted) {
620 return yield* Deferred.await(startedDeferred);
621 }
622​
623 yield* Ref.set(startedRef, true);
624 const startup = Effect.gen(function* () {
625 yield* startWatcher;
626 yield* syncDefaultKeybindingsOnStartup;
627 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
628 yield* loadConfigStateFromCacheOrDisk;
629 });
630​
631 const startupExit = yield* Effect.exit(startup);
632 if (startupExit._tag === "Failure") {
633 yield* Deferred.failCause(startedDeferred, startupExit.cause).pipe(Effect.orDie);
634 return yield* Effect.failCause(startupExit.cause);
635 }
636​
637 yield* Deferred.succeed(startedDeferred, undefined).pipe(Effect.orDie);
638 });
639​
640 return {
641 start,
642 ready: Deferred.await(startedDeferred),
643 syncDefaultKeybindingsOnStartup,
644 loadConfigState: loadConfigStateFromCacheOrDisk,
645 getSnapshot: loadConfigStateFromCacheOrDisk,
646 get streamChanges() {
647 return Stream.fromPubSub(changesPubSub);
648 },
649 get subscribeChanges() {
650 return PubSub.subscribe(changesPubSub).pipe(Effect.map(Stream.fromSubscription));
651 },
652 upsertKeybindingRule: (input) =>
653 upsertSemaphore.withPermits(1)(
654 Effect.gen(function* () {
655 const customConfig = yield* loadWritableCustomKeybindingsConfig();
656 const rule = keybindingRuleFromUpsertInput(input);
657 const replaceTarget = replaceTargetFromUpsertInput(input);
658 const nextConfig = [
659 ...customConfig.filter((entry) => {
660 if (replaceTarget) {
661 return (
662 !isSameKeybindingRule(entry, replaceTarget) && !isSameKeybindingRule(entry, rule)
663 );
664 }
665 return !isSameKeybindingRule(entry, rule);
666 }),
667 rule,
668 ];
669 const cappedConfig =
670 nextConfig.length > MAX_KEYBINDINGS_COUNT
671 ? nextConfig.slice(-MAX_KEYBINDINGS_COUNT)
672 : nextConfig;
673 if (nextConfig.length > MAX_KEYBINDINGS_COUNT) {
674 yield* Effect.logWarning("truncating keybindings config to max entries", {
675 path: keybindingsConfigPath,
676 maxEntries: MAX_KEYBINDINGS_COUNT,
677 });
678 }
679 yield* writeConfigAtomically(cappedConfig);
680 const nextResolved = mergeWithDefaultKeybindings(
681 compileResolvedKeybindingsConfig(cappedConfig),
682 );
683 yield* Cache.set(resolvedConfigCache, resolvedConfigCacheKey, {
684 keybindings: nextResolved,
685 issues: [],
686 });
687 yield* emitChange({
688 keybindings: nextResolved,
689 issues: [],
690 });
691 return nextResolved;
692 }),
693 ),
694 removeKeybindingRule: (input) =>
695 upsertSemaphore.withPermits(1)(
696 Effect.gen(function* () {
697 const customConfig = yield* loadWritableCustomKeybindingsConfig();
698 const target = keybindingRuleFromRemoveInput(input);
699 const nextConfig = customConfig.filter((entry) => !isSameKeybindingRule(entry, target));
700 yield* writeConfigAtomically(nextConfig);
701 const nextResolved = mergeWithDefaultKeybindings(
702 compileResolvedKeybindingsConfig(nextConfig),
703 );
704 yield* Cache.set(resolvedConfigCache, resolvedConfigCacheKey, {
705 keybindings: nextResolved,
706 issues: [],
707 });
708 yield* emitChange({
709 keybindings: nextResolved,
710 issues: [],
711 });
712 return nextResolved;
713 }),
714 ),
715 } satisfies Keybindings["Service"];
716});
717​
718export const layer = Layer.effect(Keybindings, make);