@silverbulletmd/silverbullet 2.10.0 → 2.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/README.md +4 -4
  2. package/client/asset_bundle/bundle.ts +0 -1
  3. package/client/config.ts +343 -0
  4. package/client/markdown_parser/constants.ts +3 -1
  5. package/client/plugos/hooks/command.ts +0 -5
  6. package/client/plugos/hooks/event.ts +0 -6
  7. package/client/plugos/hooks/mq.ts +0 -3
  8. package/client/plugos/hooks/slash_command.ts +1 -7
  9. package/client/plugos/hooks/syscall.ts +0 -4
  10. package/client/plugos/manifest_cache.ts +0 -32
  11. package/client/plugos/plug.ts +0 -3
  12. package/client/plugos/plug_compile.ts +3 -13
  13. package/client/plugos/sandboxes/worker_sandbox.ts +19 -9
  14. package/client/plugos/syscalls/editor.ts +128 -53
  15. package/client/plugos/syscalls/event.ts +0 -2
  16. package/client/plugos/syscalls/fetch.ts +0 -4
  17. package/client/plugos/syscalls/icon.ts +46 -0
  18. package/client/plugos/syscalls/index.ts +33 -13
  19. package/client/plugos/syscalls/jsonschema.ts +0 -1
  20. package/client/plugos/syscalls/mq.ts +0 -1
  21. package/client/plugos/syscalls/navigator.ts +143 -0
  22. package/client/plugos/syscalls/search.ts +44 -0
  23. package/client/plugos/syscalls/shell.ts +0 -1
  24. package/client/plugos/syscalls/space.ts +250 -7
  25. package/client/plugos/syscalls/sync.ts +56 -4
  26. package/client/plugos/syscalls/system.ts +38 -0
  27. package/client/plugos/system.ts +7 -5
  28. package/client/plugos/worker_runtime.ts +0 -2
  29. package/client/space_lua/aggregates.ts +0 -16
  30. package/client/space_lua/ast.ts +0 -5
  31. package/client/space_lua/ast_narrow.ts +0 -5
  32. package/client/space_lua/budget.ts +113 -0
  33. package/client/space_lua/budget_ui.ts +49 -0
  34. package/client/space_lua/eval.ts +113 -88
  35. package/client/space_lua/labels.ts +0 -4
  36. package/client/space_lua/numeric.ts +0 -5
  37. package/client/space_lua/parse.ts +0 -17
  38. package/client/space_lua/quarantine.ts +127 -0
  39. package/client/space_lua/query_collection.ts +3 -47
  40. package/client/space_lua/query_env.ts +0 -2
  41. package/client/space_lua/render_lua_markdown.ts +2 -7
  42. package/client/space_lua/render_widget.ts +18 -1
  43. package/client/space_lua/runtime.ts +50 -70
  44. package/client/space_lua/stdlib/format.ts +0 -12
  45. package/client/space_lua/stdlib/js.ts +0 -2
  46. package/client/space_lua/stdlib/load.ts +0 -1
  47. package/client/space_lua/stdlib/math.ts +0 -7
  48. package/client/space_lua/stdlib/net.ts +0 -4
  49. package/client/space_lua/stdlib/os.ts +0 -10
  50. package/client/space_lua/stdlib/pattern.ts +10 -15
  51. package/client/space_lua/stdlib/space_lua.ts +1 -2
  52. package/client/space_lua/stdlib/string_pack.ts +0 -3
  53. package/client/space_lua/stdlib/table.ts +0 -5
  54. package/client/space_lua/stdlib.ts +18 -31
  55. package/client/space_lua/tonumber.ts +0 -9
  56. package/dist/plug-compile.js +2 -3
  57. package/package.json +13 -3
  58. package/plug-api/lib/async.ts +1 -6
  59. package/plug-api/lib/collation.ts +22 -0
  60. package/plug-api/lib/crypto.ts +16 -15
  61. package/plug-api/lib/dates.ts +33 -0
  62. package/plug-api/lib/fuzzy.ts +282 -0
  63. package/plug-api/lib/json.ts +0 -6
  64. package/plug-api/lib/limited_map.ts +0 -2
  65. package/plug-api/lib/link_write.ts +27 -0
  66. package/plug-api/lib/ref.ts +28 -5
  67. package/plug-api/lib/resolve.ts +0 -1
  68. package/plug-api/lib/resolve_path.ts +290 -0
  69. package/plug-api/lib/shortcut.ts +15 -0
  70. package/plug-api/lib/tags.ts +0 -3
  71. package/plug-api/lib/transclusion.ts +28 -1
  72. package/plug-api/lib/tree.ts +0 -5
  73. package/plug-api/lib/yaml.ts +3 -42
  74. package/plug-api/syscall.ts +1 -5
  75. package/plug-api/syscalls/config.ts +2 -2
  76. package/plug-api/syscalls/editor.ts +59 -213
  77. package/plug-api/syscalls/icon.ts +18 -0
  78. package/plug-api/syscalls/index.ts +22 -4
  79. package/plug-api/syscalls/search.ts +11 -0
  80. package/plug-api/syscalls/space.ts +122 -5
  81. package/plug-api/syscalls/sync.ts +23 -2
  82. package/plug-api/syscalls/system.ts +46 -0
  83. package/plug-api/syscalls.ts +2 -0
  84. package/plug-api/system_mock.ts +13 -0
  85. package/plug-api/types/client.ts +4 -3
  86. package/plug-api/types/datastore.ts +11 -2
  87. package/plug-api/types/index.ts +10 -0
  88. package/plug-api/types/profile.ts +13 -0
  89. package/plug-api/types/revisions.ts +67 -0
  90. package/plug-api/ui/description.ts +64 -0
  91. package/plug-api/ui/hover.ts +69 -0
  92. package/plug-api/ui/index.ts +58 -2
  93. package/plug-api/ui/scroll.ts +30 -0
  94. package/plug-api/ui/tree_model.ts +263 -0
  95. package/plug-api/ui/tree_types.ts +66 -0
  96. package/plug-api/ui/use_fit_collapse.ts +67 -0
  97. package/plugs/builtin_plugs.ts +0 -1
  98. package/plugs/index/types.ts +9 -0
  99. package/plug-api/lib/memory_cache.ts +0 -21
  100. /package/plug-api/{ui → lib}/panel_styles.ts +0 -0
@@ -0,0 +1,290 @@
1
+ import type { Path } from "./ref.ts";
2
+ import { fileName, folderName } from "./resolve.ts";
3
+
4
+ export type ResolveResult = {
5
+ path: Path;
6
+ exists: boolean;
7
+ ambiguous: boolean;
8
+ candidates?: Path[];
9
+ };
10
+
11
+ export type PathIndex = {
12
+ has(path: string): boolean;
13
+ candidates(basename: string): Path[];
14
+ };
15
+
16
+ export class BasenameIndex implements PathIndex {
17
+ private paths = new Set<string>();
18
+ private byBasename = new Map<string, Set<string>>();
19
+ // Keys whose bucket holds more than one path, maintained incrementally so a
20
+ // snapshot of every collision costs O(collisions), not a walk of the space.
21
+ private collidingKeys = new Set<string>();
22
+
23
+ rebuild(paths: Iterable<string>): void {
24
+ this.clear();
25
+ for (const path of paths) {
26
+ this.add(path);
27
+ }
28
+ }
29
+
30
+ clear(): void {
31
+ this.paths.clear();
32
+ this.byBasename.clear();
33
+ this.collidingKeys.clear();
34
+ }
35
+
36
+ add(path: string): void {
37
+ if (this.paths.has(path)) {
38
+ return;
39
+ }
40
+ this.paths.add(path);
41
+ const key = basenameKey(path);
42
+ let bucket = this.byBasename.get(key);
43
+ if (!bucket) {
44
+ bucket = new Set();
45
+ this.byBasename.set(key, bucket);
46
+ }
47
+ bucket.add(path);
48
+ if (bucket.size > 1) {
49
+ this.collidingKeys.add(key);
50
+ }
51
+ }
52
+
53
+ delete(path: string): void {
54
+ if (!this.paths.delete(path)) {
55
+ return;
56
+ }
57
+ const key = basenameKey(path);
58
+ const bucket = this.byBasename.get(key);
59
+ if (!bucket) {
60
+ return;
61
+ }
62
+ bucket.delete(path);
63
+ if (bucket.size < 2) {
64
+ this.collidingKeys.delete(key);
65
+ }
66
+ if (bucket.size === 0) {
67
+ this.byBasename.delete(key);
68
+ }
69
+ }
70
+
71
+ has(path: string): boolean {
72
+ return this.paths.has(path);
73
+ }
74
+
75
+ candidates(basename: string): Path[] {
76
+ const bucket = this.byBasename.get(basename.toLowerCase());
77
+ return bucket ? ([...bucket] as Path[]) : [];
78
+ }
79
+
80
+ /**
81
+ * Every basename carried by more than one file, with the files that carry
82
+ * it. Under the "a bare link exists iff its basename is unique" invariant
83
+ * collisions are rare, so this is a small snapshot of a large space — which
84
+ * is what makes it cheap to ship across the sandbox boundary.
85
+ */
86
+ collidingBuckets(): Record<string, Path[]> {
87
+ const result: Record<string, Path[]> = {};
88
+ for (const key of this.collidingKeys) {
89
+ result[key] = [...this.byBasename.get(key)!] as Path[];
90
+ }
91
+ return result;
92
+ }
93
+ }
94
+
95
+ function basenameKey(path: string): string {
96
+ return fileName(path).toLowerCase();
97
+ }
98
+
99
+ function folderSegments(path: Path): string[] {
100
+ const folder = folderName(path);
101
+ return folder === "" ? [] : folder.split("/");
102
+ }
103
+
104
+ function sharedDepth(a: string[], b: string[]): number {
105
+ let i = 0;
106
+ while (i < a.length && i < b.length && a[i] === b[i]) {
107
+ i++;
108
+ }
109
+ return i;
110
+ }
111
+
112
+ /**
113
+ * Ranks same-basename candidates relative to the linking page: deepest shared
114
+ * folder prefix first, then shallowest, then lexicographic. Obsidian ranks the
115
+ * vault root above the linking page's own folder; inverting that is deliberate
116
+ * (see the design spec) — root-wins would resolve a link inside `docs/api/` to
117
+ * a sibling project's root-level file whenever a space is opened at a wider
118
+ * root. Root preference survives as the shallowest-path rule, since the root is
119
+ * always depth 0.
120
+ */
121
+ export function rankCandidates(candidates: Path[], fromPage: Path): Path[] {
122
+ const from = folderSegments(fromPage);
123
+ return [...candidates].sort((a, b) => {
124
+ const aFolder = folderSegments(a);
125
+ const bFolder = folderSegments(b);
126
+ const proximity = sharedDepth(bFolder, from) - sharedDepth(aFolder, from);
127
+ if (proximity !== 0) {
128
+ return proximity;
129
+ }
130
+ const depth = aFolder.length - bFolder.length;
131
+ if (depth !== 0) {
132
+ return depth;
133
+ }
134
+ return a < b ? -1 : a > b ? 1 : 0;
135
+ });
136
+ }
137
+
138
+ /**
139
+ * What a sandboxed caller gets back for one requested path: whether that exact
140
+ * path exists, plus every file sharing its basename. Ranking deliberately stays
141
+ * out of the syscall — it runs in the caller, from the same pure function the
142
+ * client uses, so there is only ever one implementation of it.
143
+ */
144
+ export type PathLookup = {
145
+ exact: boolean;
146
+ candidates: Path[];
147
+ };
148
+
149
+ /**
150
+ * Adapts a batch of lookups into a {@link PathIndex}. Exact-path answers stay
151
+ * keyed by the requested path, while candidates are re-keyed by basename —
152
+ * which is how both `resolvePath` and `writeLinkPath` ask for them. Keying
153
+ * candidates by the requested path instead silently returns none for anything
154
+ * in a folder.
155
+ */
156
+ export function lookupIndex(lookups: Record<string, PathLookup>): PathIndex {
157
+ const byBasename = new Map<string, Path[]>();
158
+ for (const [path, lookup] of Object.entries(lookups)) {
159
+ byBasename.set(basenameKey(path), lookup.candidates);
160
+ }
161
+ return {
162
+ has: (path) => lookups[path]?.exact ?? false,
163
+ candidates: (basename) => byBasename.get(basename.toLowerCase()) ?? [],
164
+ };
165
+ }
166
+
167
+ /**
168
+ * A {@link PathIndex} for *write-format decisions only*, built from just the
169
+ * colliding buckets of {@link BasenameIndex.collidingBuckets}. Enough for
170
+ * {@link writeLinkPath} on paths of files that exist: a basename outside the
171
+ * buckets is unique by construction, so `candidates` answers with a
172
+ * single-entry stand-in, and `has` only ever needs to look inside a bucket
173
+ * (every exact path a suffix could be shadowed by shares the suffix's own
174
+ * basename). Not a resolution index — do not hand it to `resolvePath` callers.
175
+ */
176
+ export function collisionIndex(colliding: Record<string, Path[]>): PathIndex {
177
+ return {
178
+ has: (path) =>
179
+ colliding[basenameKey(path)]?.includes(path as Path) ?? false,
180
+ candidates: (basename) =>
181
+ colliding[basename.toLowerCase()] ?? ([basename] as Path[]),
182
+ };
183
+ }
184
+
185
+ export type LinkWriteFormat = "shortest" | "shortest-suffix" | "full-path";
186
+
187
+ /**
188
+ * Renders a target path as link text. `shortest` writes the bare name only when
189
+ * that name is unique in the space — the rule that maintains the "a bare link
190
+ * exists iff its basename is unique" invariant on the write side — and the
191
+ * full path otherwise. `shortest-suffix` differs only in the colliding case:
192
+ * instead of the full path it writes the shortest path suffix that resolves
193
+ * back to exactly this file, which keeps even disambiguated links independent
194
+ * of where the space root sits.
195
+ */
196
+ export function writeLinkPath(
197
+ target: Path,
198
+ format: LinkWriteFormat,
199
+ index: PathIndex,
200
+ ): Path {
201
+ if (format === "full-path") {
202
+ return target;
203
+ }
204
+ const bare = fileName(target);
205
+ if (index.candidates(bare).length === 1) {
206
+ return bare;
207
+ }
208
+ if (format === "shortest") {
209
+ return target;
210
+ }
211
+ // Every rival a suffix could collide with shares the target's basename, so
212
+ // the basename bucket is a complete rival list and resolvePath can verify
213
+ // each candidate outright: rejected when it is another file's exact path,
214
+ // ambiguous, or resolving elsewhere. fromPage is irrelevant — only
215
+ // unambiguous resolutions are accepted, and those are page-independent.
216
+ const segments = target.split("/");
217
+ for (let i = segments.length - 2; i >= 1; i--) {
218
+ const candidate = segments.slice(i).join("/") as Path;
219
+ const resolution = resolvePath(candidate, "" as Path, index);
220
+ if (
221
+ resolution.exists &&
222
+ !resolution.ambiguous &&
223
+ resolution.path === target
224
+ ) {
225
+ return candidate;
226
+ }
227
+ }
228
+ return target;
229
+ }
230
+
231
+ /**
232
+ * Resolves a parsed ref path against the space. Exact paths always win, so
233
+ * every link that resolves today keeps resolving to the same file. A bare name
234
+ * falls back to a space-wide basename lookup; more than one survivor means the
235
+ * "bare link iff unique basename" invariant is violated, which resolves
236
+ * deterministically but is reported as ambiguous so callers can flag it.
237
+ *
238
+ * A qualified path with no exact match falls back to a path-suffix lookup:
239
+ * `api/Auth` finds `docs/api/Auth.md` when that is the only file whose path
240
+ * ends that way. This is what lets a space opened at a wider root — the parent
241
+ * of the `docs/` folder it was authored in — keep its qualified links working,
242
+ * not just its bare ones, and it matches Obsidian accepting partial paths as
243
+ * linkpaths.
244
+ */
245
+ export function resolvePath(
246
+ path: Path,
247
+ fromPage: Path,
248
+ index: PathIndex,
249
+ ): ResolveResult {
250
+ if (path === "") {
251
+ return { path, exists: true, ambiguous: false };
252
+ }
253
+ if (index.has(path)) {
254
+ // An exact path match is fully determined by the link text, so it is never
255
+ // reported ambiguous — even when other files share the basename. For a
256
+ // root-level file the bare and qualified forms are the same string, so
257
+ // there is nothing the author could write instead and the warning could
258
+ // never be cleared.
259
+ return { path, exists: true, ambiguous: false };
260
+ }
261
+
262
+ // A bare name is just the degenerate suffix, so one matcher serves both
263
+ // lookups: a candidate matches when, `/`-prefixed, its path ends with `/`
264
+ // plus the ref.
265
+ const suffix = `/${path.toLowerCase()}`;
266
+ const candidates = index
267
+ .candidates(fileName(path))
268
+ .filter((candidate) => `/${candidate.toLowerCase()}`.endsWith(suffix));
269
+ if (candidates.length === 0) {
270
+ return { path, exists: false, ambiguous: false };
271
+ }
272
+ // The overwhelmingly common case under the bare-iff-unique invariant, on
273
+ // the per-rendered-link path: skip the case filter and the ranking sort.
274
+ if (candidates.length === 1) {
275
+ return { path: candidates[0], exists: true, ambiguous: false };
276
+ }
277
+
278
+ const caseSuffix = `/${path}`;
279
+ const exactCase = candidates.filter((candidate) =>
280
+ `/${candidate}`.endsWith(caseSuffix),
281
+ );
282
+ if (exactCase.length === 1) {
283
+ return { path: exactCase[0], exists: true, ambiguous: false };
284
+ }
285
+ const ranked = rankCandidates(
286
+ exactCase.length > 0 ? exactCase : candidates,
287
+ fromPage,
288
+ );
289
+ return { path: ranked[0], exists: true, ambiguous: true, candidates: ranked };
290
+ }
@@ -2,6 +2,21 @@ export const isMacLike =
2
2
  typeof navigator !== "undefined" &&
3
3
  /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);
4
4
 
5
+ /**
6
+ * The key hint a command shows: its platform-appropriate binding(s),
7
+ * prettified. Several bindings for one command are joined with `|`.
8
+ */
9
+ export function keyboardHint(def: {
10
+ key?: string | string[];
11
+ mac?: string | string[];
12
+ }): string | undefined {
13
+ const binding = isMacLike && def.mac ? def.mac : def.key;
14
+ if (!binding) return undefined;
15
+ const shortcuts = Array.isArray(binding) ? binding : [binding];
16
+ if (shortcuts.length === 0) return undefined;
17
+ return shortcuts.map(prettifyShortcut).join(" | ");
18
+ }
19
+
5
20
  export function prettifyShortcut(shortcut: string): string {
6
21
  if (!isMacLike) return shortcut;
7
22
  const pretty = shortcut
@@ -6,7 +6,6 @@ export function isMetaTag(tag: string): boolean {
6
6
  /** Extract the name from hashtag text, removing # prefix and <angle brackets> if necessary */
7
7
  export function extractHashtag(text: string): string {
8
8
  if (text[0] !== "#") {
9
- // you shouldn't call this function at all
10
9
  console.error("extractHashtag called on already clean string", text);
11
10
  return text;
12
11
  } else if (text[1] === "<") {
@@ -14,11 +13,9 @@ export function extractHashtag(text: string): string {
14
13
  // this is malformed: #<name but maybe we're trying to autocomplete
15
14
  return text.slice(2);
16
15
  } else {
17
- // this is correct #<name>
18
16
  return text.slice(2, -1);
19
17
  }
20
18
  } else {
21
- // this is just #name
22
19
  return text.slice(1);
23
20
  }
24
21
  }
@@ -3,9 +3,15 @@ import {
3
3
  wikiLinkRegex,
4
4
  } from "../../client/markdown_parser/constants.ts";
5
5
  import {
6
+ encodeRef,
6
7
  getNameFromPath,
7
8
  parseToRef,
9
+ type Path,
8
10
  } from "@silverbulletmd/silverbullet/lib/ref";
11
+ import {
12
+ type PathIndex,
13
+ resolvePath,
14
+ } from "@silverbulletmd/silverbullet/lib/resolve_path";
9
15
 
10
16
  export type LinkType = "wikilink" | "markdownlink";
11
17
  /**
@@ -83,7 +89,6 @@ export function parseTransclusion(text: string): Transclusion | null {
83
89
  ({ stringRef: url, alias } = match.groups);
84
90
  linktype = "wikilink";
85
91
  } else {
86
- // We found no match
87
92
  return null;
88
93
  }
89
94
 
@@ -102,6 +107,28 @@ export function parseTransclusion(text: string): Transclusion | null {
102
107
  };
103
108
  }
104
109
 
110
+ /**
111
+ * Rewrites a wiki-link transclusion's target to the path it resolves to, the
112
+ * same way plain wiki links resolve.
113
+ */
114
+ export function resolveTransclusionUrl(
115
+ t: Transclusion,
116
+ fromPage: Path,
117
+ index: PathIndex,
118
+ ): void {
119
+ if (t.linktype !== "wikilink") {
120
+ return;
121
+ }
122
+ const ref = parseToRef(t.url);
123
+ if (!ref || ref.path === "") {
124
+ return;
125
+ }
126
+ const resolution = resolvePath(ref.path, fromPage, index);
127
+ if (resolution.exists && resolution.path !== ref.path) {
128
+ t.url = encodeRef({ ...ref, path: resolution.path });
129
+ }
130
+ }
131
+
105
132
  export function nameFromTransclusion(t: Transclusion): string {
106
133
  const ref = parseToRef(t.url);
107
134
  if (!ref) {
@@ -114,7 +114,6 @@ export function replaceNodesMatching(
114
114
  tree.children[i] = subst;
115
115
  i++;
116
116
  } else {
117
- // null = delete
118
117
  tree.children.splice(i, 1);
119
118
  // don't increment i — next child shifted into this position
120
119
  }
@@ -140,7 +139,6 @@ export async function replaceNodesMatchingAsync(
140
139
  tree.children[i] = subst;
141
140
  i++;
142
141
  } else {
143
- // null = delete
144
142
  tree.children.splice(i, 1);
145
143
  }
146
144
  } else {
@@ -281,11 +279,9 @@ export function nodeAtPos(tree: ParseTree, pos: number): ParseTree | null {
281
279
  for (const child of tree.children) {
282
280
  const n = nodeAtPos(child, pos);
283
281
  if (n && n.text !== undefined) {
284
- // Got a text node, let's return its parent
285
282
  return tree;
286
283
  }
287
284
  if (n) {
288
- // Got it
289
285
  return n;
290
286
  }
291
287
  }
@@ -321,7 +317,6 @@ export function normalizeTableRow(
321
317
  // Fix leading-pipe mismatch: row has leading delimiter but header doesn't
322
318
  if (headerHasLeadingDelim === false) {
323
319
  if (row.children.length > 0 && row.children[0].type === "TableDelimiter") {
324
- // Insert empty cell after the leading delimiter
325
320
  row.children.splice(1, 0, { type: "TableCell", children: [] });
326
321
  }
327
322
  }
@@ -1,19 +1,16 @@
1
- // Define the patch structure
2
1
  export interface YamlPatch {
3
2
  op: "set-key" | "delete-key";
4
- path: string; // Still assuming simple, top-level key names
3
+ path: string; // Top-level key names only
5
4
  value?: any; // Required for set-key, not used for delete-key
6
5
  }
7
6
 
8
- // Helper function specifically for serializing scalar types
9
7
  function serializeToYamlScalar(
10
8
  value: string | number | boolean | null,
11
9
  ): string {
12
10
  if (typeof value === "string") {
13
- // Always quote empty strings and strings with special characters
14
11
  if (
15
12
  value === "" || // Empty string
16
- value.match(/[:{#}[],&*!|>'"%@`]/) || // Special YAML characters (added % and ")
13
+ value.match(/[:{#}[],&*!|>'"%@`]/) || // Special YAML characters
17
14
  /^\d+(\.\d+)?([eE][+-]?\d+)?$/.test(value) || // Looks like a number
18
15
  value.includes(":") || // Contains colons
19
16
  ["true", "false", "null", "yes", "no", "on", "off"].includes(
@@ -22,7 +19,6 @@ function serializeToYamlScalar(
22
19
  ) {
23
20
  return JSON.stringify(value);
24
21
  }
25
- // Simple strings without special chars/meaning don't need quotes
26
22
  return value;
27
23
  } else if (
28
24
  typeof value === "number" ||
@@ -31,12 +27,9 @@ function serializeToYamlScalar(
31
27
  ) {
32
28
  return String(value);
33
29
  }
34
- // Default for unsupported scalar types (e.g., undefined)
35
30
  return "null";
36
31
  }
37
32
 
38
- // Updated helper function to serialize various JS types to YAML string representations
39
- // Added baseIndentation parameter for handling nested lists correctly (though we only use it for top-level lists here)
40
33
  function serializeToYamlValue(
41
34
  value: any,
42
35
  baseIndentation: string = "",
@@ -45,9 +38,7 @@ function serializeToYamlValue(
45
38
  if (value.length === 0) {
46
39
  return "[]"; // Use flow style for empty arrays for simplicity
47
40
  }
48
- // Determine indentation for list items (base + 2 spaces)
49
41
  const itemIndentation = `${baseIndentation} `;
50
- // Format each item recursively, preceded by '- ' marker
51
42
  return (
52
43
  "\n" +
53
44
  value
@@ -57,11 +48,8 @@ function serializeToYamlValue(
57
48
  )
58
49
  .join("\n")
59
50
  );
60
- // Note: serializeToYamlValue is used recursively here to handle nested arrays/objects if needed in future
61
- // However, the current `applyMinimalSetKeyPatches` only handles top-level keys.
62
51
  } else if (typeof value === "object" && value !== null) {
63
- // Basic object serialization (not requested, but good to consider)
64
- // This is highly simplified and doesn't handle nesting well without more context
52
+ // Nested object serialization is limited.
65
53
  const itemIndentation = `${baseIndentation} `;
66
54
  const entries = Object.entries(value);
67
55
  if (entries.length === 0) return "{}"; // Flow style empty objects
@@ -78,7 +66,6 @@ function serializeToYamlValue(
78
66
  .join("\n")
79
67
  );
80
68
  } else {
81
- // Handle scalars using the dedicated function
82
69
  return serializeToYamlScalar(value);
83
70
  }
84
71
  }
@@ -88,14 +75,12 @@ export function applyPatches(yamlString: string, patches: YamlPatch[]): string {
88
75
 
89
76
  for (const patch of patches) {
90
77
  if (patch.op === "delete-key") {
91
- // Handle delete operation
92
78
  const key = patch.path;
93
79
  const lines = currentYaml.split("\n");
94
80
  let keyLineIndex = -1;
95
81
  let startDeleteIndex = -1;
96
82
  let endDeleteIndex = -1;
97
83
 
98
- // Find the key line
99
84
  for (let i = 0; i < lines.length; i++) {
100
85
  const line = lines[i];
101
86
  const trimmedLine = line.trim();
@@ -121,16 +106,12 @@ export function applyPatches(yamlString: string, patches: YamlPatch[]): string {
121
106
  }
122
107
  }
123
108
 
124
- // Determine the indentation of the key
125
109
  const keyIndent = lines[i].match(/^(\s*)/)?.[1] || "";
126
110
 
127
- // Look forwards to find all content belonging to this key
128
- // This includes list items and nested objects
129
111
  for (let j = i + 1; j < lines.length; j++) {
130
112
  const nextLine = lines[j];
131
113
  const trimmedNextLine = nextLine.trim();
132
114
 
133
- // Empty line - continue looking
134
115
  if (trimmedNextLine === "") {
135
116
  continue;
136
117
  }
@@ -147,13 +128,10 @@ export function applyPatches(yamlString: string, patches: YamlPatch[]): string {
147
128
  }
148
129
  }
149
130
 
150
- // Check indentation of next non-empty, non-comment line
151
131
  const nextIndent = nextLine.match(/^(\s*)/)?.[1] || "";
152
132
  if (nextIndent.length > keyIndent.length) {
153
- // This line is indented more than the key, so it belongs to the key
154
133
  endDeleteIndex = j;
155
134
  } else {
156
- // This line is at same or less indentation, so it's a new key
157
135
  break;
158
136
  }
159
137
  }
@@ -163,12 +141,9 @@ export function applyPatches(yamlString: string, patches: YamlPatch[]): string {
163
141
  }
164
142
 
165
143
  if (keyLineIndex !== -1) {
166
- // Delete the lines from startDeleteIndex to endDeleteIndex (inclusive)
167
144
  const beforeDelete = lines.slice(0, startDeleteIndex);
168
145
  const afterDelete = lines.slice(endDeleteIndex + 1);
169
146
 
170
- // Clean up excessive empty lines at the boundary
171
- // Remove trailing empty lines from beforeDelete
172
147
  while (
173
148
  beforeDelete.length > 0 &&
174
149
  beforeDelete[beforeDelete.length - 1].trim() === ""
@@ -194,7 +169,6 @@ export function applyPatches(yamlString: string, patches: YamlPatch[]): string {
194
169
  currentYaml += "\n";
195
170
  }
196
171
  }
197
- // If key not found, do nothing
198
172
  continue;
199
173
  }
200
174
 
@@ -202,25 +176,21 @@ export function applyPatches(yamlString: string, patches: YamlPatch[]): string {
202
176
 
203
177
  const key = patch.path;
204
178
 
205
- // Split the YAML into lines for easier processing
206
179
  const lines = currentYaml.split("\n");
207
180
  let keyLineIndex = -1;
208
181
  let commentBlock = "";
209
182
  let trailingComments = "";
210
183
  let inlineComment = "";
211
184
 
212
- // Find the key line and collect comments
213
185
  for (let i = 0; i < lines.length; i++) {
214
186
  const line = lines[i];
215
187
  const trimmedLine = line.trim();
216
188
  if (trimmedLine.startsWith(`${key}:`)) {
217
189
  keyLineIndex = i;
218
- // Extract inline comment if present
219
190
  const commentMatch = line.match(/#.*$/);
220
191
  if (commentMatch) {
221
192
  inlineComment = commentMatch[0];
222
193
  }
223
- // Look backwards for comments
224
194
  for (let j = i - 1; j >= 0; j--) {
225
195
  const prevLine = lines[j].trim();
226
196
  if (prevLine.startsWith("#")) {
@@ -229,7 +199,6 @@ export function applyPatches(yamlString: string, patches: YamlPatch[]): string {
229
199
  break;
230
200
  }
231
201
  }
232
- // Look forwards for comments
233
202
  for (let j = i + 1; j < lines.length; j++) {
234
203
  const nextLine = lines[j].trim();
235
204
  if (nextLine.startsWith("#")) {
@@ -242,16 +211,12 @@ export function applyPatches(yamlString: string, patches: YamlPatch[]): string {
242
211
  }
243
212
  }
244
213
 
245
- // Serialize the new value
246
214
  const serializedNewValue = serializeToYamlValue(patch.value);
247
215
 
248
- // Create the replacement line
249
216
  let replacementLine: string;
250
217
  if (serializedNewValue.startsWith("\n")) {
251
- // For lists/objects, the key line ends with just ':'
252
218
  replacementLine = `${key}:${inlineComment}${serializedNewValue}`;
253
219
  } else {
254
- // For scalars, format as key: value
255
220
  replacementLine = `${key}: ${serializedNewValue}${
256
221
  inlineComment ? ` ${inlineComment}` : ""
257
222
  }`;
@@ -267,7 +232,6 @@ export function applyPatches(yamlString: string, patches: YamlPatch[]): string {
267
232
  keyLineIndex + 1 + trailingComments.split("\n").filter(Boolean).length,
268
233
  );
269
234
 
270
- // Build the new content
271
235
  const newContent = [
272
236
  ...beforeKey,
273
237
  ...commentBlock.split("\n").filter(Boolean),
@@ -276,10 +240,8 @@ export function applyPatches(yamlString: string, patches: YamlPatch[]): string {
276
240
  ...afterKey,
277
241
  ];
278
242
 
279
- // Join lines and ensure proper newlines
280
243
  currentYaml = `${newContent.join("\n").replace(/\n*$/, "\n")}\n`;
281
244
  } else {
282
- // Key not found: Add the new key-value pair to the end
283
245
  const newLineBlock = replacementLine;
284
246
  if (currentYaml.trim() === "") {
285
247
  currentYaml = `${newLineBlock}\n`;
@@ -289,6 +251,5 @@ export function applyPatches(yamlString: string, patches: YamlPatch[]): string {
289
251
  }
290
252
  }
291
253
 
292
- // Ensure the result ends with a newline
293
254
  return currentYaml.replace(/\n*$/, "\n");
294
255
  }
@@ -1,8 +1,4 @@
1
- // declare global {
2
- // function syscall(name: string, ...args: any[]): Promise<any>;
3
- // }
4
-
5
- // This is the case when running tests only, so giving it a dummy syscall function
1
+ // Tests may load this module without a syscall host.
6
2
  if (typeof (globalThis as any).syscall === "undefined") {
7
3
  (globalThis as any).syscall = () => {
8
4
  throw new Error("Not implemented here");
@@ -15,14 +15,14 @@ export function get<T>(path: string | string[], defaultValue: T): Promise<T> {
15
15
  * @param path The path to set the value at
16
16
  * @param value The value to set
17
17
  */
18
- export function set<T>(path: string, value: T): Promise<void>;
18
+ export function set<T>(path: string | string[], value: T): Promise<void>;
19
19
  /**
20
20
  * Sets multiple config values at once.
21
21
  * @param values An object containing key-value pairs to set
22
22
  */
23
23
  export function set(values: Record<string, any>): Promise<void>;
24
24
  export function set<T>(
25
- pathOrValues: string | Record<string, any>,
25
+ pathOrValues: string | string[] | Record<string, any>,
26
26
  value?: T,
27
27
  ): Promise<void> {
28
28
  return syscall("config.set", pathOrValues, value);