@aigne/afs-json 1.11.0-beta → 1.11.0-beta.10

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/dist/index.mjs CHANGED
@@ -1,11 +1,22 @@
1
+ import { __decorate } from "./_virtual/_@oxc-project_runtime@0.108.0/helpers/decorate.mjs";
2
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
1
3
  import { readFile, stat, writeFile } from "node:fs/promises";
2
4
  import { basename, dirname, extname, isAbsolute, join } from "node:path";
5
+ import { AFSNotFoundError } from "@aigne/afs";
6
+ import { AFSBaseProvider, Delete, Explain, List, Meta, Read, Rename, Search, Stat, Write } from "@aigne/afs/provider";
3
7
  import { camelize, optionalize, zodParse } from "@aigne/afs/utils/zod";
8
+ import { joinURL } from "ufo";
4
9
  import { parse, stringify } from "yaml";
5
10
  import { z } from "zod";
6
11
 
7
12
  //#region src/index.ts
8
13
  const LIST_MAX_LIMIT = 1e3;
14
+ /** Hidden key for storing AFS metadata (mirrors FS provider's .afs directory) */
15
+ const AFS_KEY = ".afs";
16
+ /** Subkey for storing metadata (mirrors FS provider's meta.yaml file) */
17
+ const META_KEY = "meta";
18
+ /** Subkey for storing child node metadata (mirrors FS provider's .nodes directory) */
19
+ const NODES_KEY = ".nodes";
9
20
  const afsJSONOptionsSchema = camelize(z.object({
10
21
  name: optionalize(z.string()),
11
22
  jsonPath: z.string().describe("The path to the JSON/YAML file to mount"),
@@ -19,26 +30,51 @@ const afsJSONOptionsSchema = camelize(z.object({
19
30
  * JSON/YAML objects are treated as directories, and properties/array items as files.
20
31
  * Supports nested structures and path-based access to data values.
21
32
  */
22
- var AFSJSON = class AFSJSON {
33
+ var AFSJSON = class AFSJSON extends AFSBaseProvider {
23
34
  static schema() {
24
35
  return afsJSONOptionsSchema;
25
36
  }
26
- static async load({ filepath, parsed }) {
37
+ static manifest() {
38
+ return {
39
+ name: "json",
40
+ description: "JSON or YAML file — navigate and edit structured data as a tree.\n- Objects and arrays become directories, primitives become leaf nodes\n- Read/write individual values, search across structure\n- Path structure: `/{key}/{nested-key}` (arrays indexed by position)",
41
+ uriTemplate: "json://{localPath+}",
42
+ category: "structured-data",
43
+ schema: z.object({ localPath: z.string() }),
44
+ tags: [
45
+ "json",
46
+ "yaml",
47
+ "structured-data"
48
+ ]
49
+ };
50
+ }
51
+ static async load({ basePath, config } = {}) {
27
52
  return new AFSJSON({
28
- ...await AFSJSON.schema().parseAsync(parsed),
29
- cwd: dirname(filepath)
53
+ ...await AFSJSON.schema().parseAsync(config),
54
+ cwd: basePath
30
55
  });
31
56
  }
57
+ name;
58
+ description;
59
+ accessMode;
60
+ agentSkills;
32
61
  jsonData = null;
33
62
  fileStats = {};
34
63
  fileFormat = "json";
64
+ resolvedJsonPath;
35
65
  constructor(options) {
66
+ super();
36
67
  this.options = options;
68
+ if (options.localPath && !options.jsonPath) options.jsonPath = options.localPath;
37
69
  zodParse(afsJSONOptionsSchema, options);
38
70
  let jsonPath;
39
71
  jsonPath = options.jsonPath.replaceAll("${CWD}", process.cwd());
40
72
  if (jsonPath.startsWith("~/")) jsonPath = join(process.env.HOME || "", jsonPath.slice(2));
41
73
  if (!isAbsolute(jsonPath)) jsonPath = join(options.cwd || process.cwd(), jsonPath);
74
+ if (!existsSync(jsonPath)) {
75
+ mkdirSync(dirname(jsonPath), { recursive: true });
76
+ writeFileSync(jsonPath, "{}", "utf8");
77
+ }
42
78
  const ext = extname(jsonPath).toLowerCase();
43
79
  this.fileFormat = ext === ".yaml" || ext === ".yml" ? "yaml" : "json";
44
80
  const extensions = [
@@ -55,12 +91,400 @@ var AFSJSON = class AFSJSON {
55
91
  this.description = options.description;
56
92
  this.agentSkills = options.agentSkills;
57
93
  this.accessMode = options.accessMode ?? (options.agentSkills ? "readonly" : "readwrite");
58
- this.options.jsonPath = jsonPath;
94
+ this.resolvedJsonPath = jsonPath;
95
+ }
96
+ /**
97
+ * Read metadata for a JSON node via /.meta or /path/.meta
98
+ * Returns stored metadata merged with computed type information
99
+ * Note: Meta is read-only. To write metadata, use write() with payload.meta.
100
+ */
101
+ async readMetaHandler(ctx) {
102
+ await this.ensureLoaded();
103
+ const nodePath = joinURL("/", ctx.params.path ?? "");
104
+ const segments = this.getPathSegments(nodePath);
105
+ const value = this.getValueAtPath(this.jsonData, segments);
106
+ if (value === void 0) throw new AFSNotFoundError(nodePath);
107
+ const isDir = this.isDirectoryValue(value);
108
+ const children = isDir ? this.getChildren(value) : [];
109
+ let type;
110
+ if (Array.isArray(value)) type = "array";
111
+ else if (value === null) type = "null";
112
+ else if (typeof value === "object") type = "object";
113
+ else type = typeof value;
114
+ const storedMeta = this.loadMeta(nodePath) || {};
115
+ const computedMeta = {
116
+ type,
117
+ path: nodePath
118
+ };
119
+ if (isDir) {
120
+ computedMeta.childrenCount = children.length;
121
+ if (Array.isArray(value)) computedMeta.length = value.length;
122
+ else computedMeta.keys = Object.keys(value).filter((k) => !this.isMetaKey(k));
123
+ } else computedMeta.value = value;
124
+ if (this.fileStats.birthtime) computedMeta.created = this.fileStats.birthtime;
125
+ if (this.fileStats.mtime) computedMeta.modified = this.fileStats.mtime;
126
+ return this.buildEntry(joinURL(nodePath, ".meta"), {
127
+ meta: storedMeta,
128
+ content: computedMeta,
129
+ createdAt: this.fileStats.birthtime,
130
+ updatedAt: this.fileStats.mtime
131
+ });
132
+ }
133
+ async listHandler(ctx) {
134
+ await this.ensureLoaded();
135
+ const normalizedPath = ctx.params.path ? `/${ctx.params.path}` : "/";
136
+ const options = ctx.options;
137
+ const limit = Math.min(options?.limit || LIST_MAX_LIMIT, LIST_MAX_LIMIT);
138
+ const maxChildren = typeof options?.maxChildren === "number" ? options.maxChildren : Number.MAX_SAFE_INTEGER;
139
+ const maxDepth = options?.maxDepth ?? 1;
140
+ const segments = this.getPathSegments(normalizedPath);
141
+ const value = this.getValueAtPath(this.jsonData, segments);
142
+ if (value === void 0) throw new AFSNotFoundError(normalizedPath);
143
+ if (maxDepth === 0) return { data: [] };
144
+ if (!this.isDirectoryValue(value)) return { data: [] };
145
+ const entries = [];
146
+ const rootChildren = this.getChildren(value);
147
+ const queue = (rootChildren.length > maxChildren ? rootChildren.slice(0, maxChildren) : rootChildren).map((child) => ({
148
+ path: normalizedPath === "/" ? `/${child.key}` : `${normalizedPath}/${child.key}`,
149
+ value: child.value,
150
+ depth: 1
151
+ }));
152
+ while (queue.length > 0) {
153
+ const item = queue.shift();
154
+ if (!item) break;
155
+ const { path: itemPath, value: itemValue, depth } = item;
156
+ const entry = this.valueToAFSEntry(itemPath, itemValue);
157
+ entries.push(entry);
158
+ if (entries.length >= limit) break;
159
+ if (this.isDirectoryValue(itemValue) && depth < maxDepth) {
160
+ const children = this.getChildren(itemValue);
161
+ const childrenToProcess = children.length > maxChildren ? children.slice(0, maxChildren) : children;
162
+ for (const child of childrenToProcess) {
163
+ const childPath = itemPath === "/" ? `/${child.key}` : `${itemPath}/${child.key}`;
164
+ queue.push({
165
+ path: childPath,
166
+ value: child.value,
167
+ depth: depth + 1
168
+ });
169
+ }
170
+ }
171
+ }
172
+ return { data: entries };
173
+ }
174
+ async readHandler(ctx) {
175
+ await this.ensureLoaded();
176
+ const normalizedPath = ctx.params.path ? `/${ctx.params.path}` : "/";
177
+ const segments = this.getPathSegments(normalizedPath);
178
+ const value = this.getValueAtPath(this.jsonData, segments);
179
+ if (value === void 0) throw new AFSNotFoundError(normalizedPath);
180
+ return this.valueToAFSEntry(normalizedPath, value);
181
+ }
182
+ /**
183
+ * Write handler - supports writing content and/or metadata
184
+ *
185
+ * | payload | behavior |
186
+ * |---------|----------|
187
+ * | { content } | write content only |
188
+ * | { metadata } | write metadata only (to .afs storage) |
189
+ * | { content, metadata } | write both |
190
+ */
191
+ async writeHandler(ctx, payload) {
192
+ await this.ensureLoaded();
193
+ const normalizedPath = ctx.params.path ? `/${ctx.params.path}` : "/";
194
+ const segments = this.getPathSegments(normalizedPath);
195
+ if (payload.content !== void 0) this.setValueAtPath(this.jsonData, segments, payload.content);
196
+ if (payload.meta !== void 0 && typeof payload.meta === "object") {
197
+ const finalMeta = {
198
+ ...this.loadMeta(normalizedPath) || {},
199
+ ...payload.meta
200
+ };
201
+ this.saveMeta(normalizedPath, finalMeta);
202
+ }
203
+ await this.saveToFile();
204
+ const newValue = this.getValueAtPath(this.jsonData, segments);
205
+ const isDir = this.isDirectoryValue(newValue);
206
+ const children = isDir ? this.getChildren(newValue) : [];
207
+ const storedMeta = this.loadMeta(normalizedPath) || {};
208
+ return { data: {
209
+ id: normalizedPath,
210
+ path: normalizedPath,
211
+ content: payload.content !== void 0 ? payload.content : newValue,
212
+ summary: payload.summary,
213
+ createdAt: this.fileStats.birthtime,
214
+ updatedAt: this.fileStats.mtime,
215
+ meta: {
216
+ ...storedMeta,
217
+ childrenCount: isDir ? children.length : void 0
218
+ },
219
+ userId: payload.userId,
220
+ sessionId: payload.sessionId,
221
+ linkTo: payload.linkTo
222
+ } };
223
+ }
224
+ async deleteHandler(ctx) {
225
+ await this.ensureLoaded();
226
+ const normalizedPath = ctx.params.path ? `/${ctx.params.path}` : "/";
227
+ const options = ctx.options;
228
+ const segments = this.getPathSegments(normalizedPath);
229
+ const value = this.getValueAtPath(this.jsonData, segments);
230
+ if (value === void 0) throw new AFSNotFoundError(normalizedPath);
231
+ if (this.isDirectoryValue(value) && this.getChildren(value).length > 0 && !options?.recursive) throw new Error(`Cannot delete directory '${normalizedPath}' without recursive option. Set recursive: true to delete directories.`);
232
+ this.deleteValueAtPath(this.jsonData, segments);
233
+ await this.saveToFile();
234
+ return { message: `Successfully deleted: ${normalizedPath}` };
235
+ }
236
+ async renameHandler(ctx, newPath) {
237
+ await this.ensureLoaded();
238
+ const normalizedOldPath = ctx.params.path ? `/${ctx.params.path}` : "/";
239
+ const normalizedNewPath = this.normalizePath(newPath);
240
+ const options = ctx.options;
241
+ const oldSegments = this.getPathSegments(normalizedOldPath);
242
+ const newSegments = this.getPathSegments(normalizedNewPath);
243
+ const oldValue = this.getValueAtPath(this.jsonData, oldSegments);
244
+ if (oldValue === void 0) throw new AFSNotFoundError(normalizedOldPath);
245
+ if (this.getValueAtPath(this.jsonData, newSegments) !== void 0 && !options?.overwrite) throw new Error(`Destination '${normalizedNewPath}' already exists. Set overwrite: true to replace it.`);
246
+ this.setValueAtPath(this.jsonData, newSegments, oldValue);
247
+ this.deleteValueAtPath(this.jsonData, oldSegments);
248
+ await this.saveToFile();
249
+ return { message: `Successfully renamed '${normalizedOldPath}' to '${normalizedNewPath}'` };
250
+ }
251
+ async searchHandler(ctx, query, options) {
252
+ await this.ensureLoaded();
253
+ const normalizedPath = ctx.params.path ? `/${ctx.params.path}` : "/";
254
+ const limit = Math.min(options?.limit || LIST_MAX_LIMIT, LIST_MAX_LIMIT);
255
+ const caseSensitive = options?.caseSensitive ?? false;
256
+ const segments = this.getPathSegments(normalizedPath);
257
+ const rootValue = this.getValueAtPath(this.jsonData, segments);
258
+ if (rootValue === void 0) throw new AFSNotFoundError(normalizedPath);
259
+ const entries = [];
260
+ const searchQuery = caseSensitive ? query : query.toLowerCase();
261
+ const searchInValue = (valuePath, value) => {
262
+ if (entries.length >= limit) return;
263
+ let matched = false;
264
+ if (!this.isDirectoryValue(value)) {
265
+ const valueStr = typeof value === "string" ? value : JSON.stringify(value);
266
+ if ((caseSensitive ? valueStr : valueStr.toLowerCase()).includes(searchQuery)) matched = true;
267
+ }
268
+ if (matched) entries.push(this.valueToAFSEntry(valuePath, value));
269
+ if (this.isDirectoryValue(value)) {
270
+ const children = this.getChildren(value);
271
+ for (const child of children) {
272
+ if (entries.length >= limit) break;
273
+ searchInValue(valuePath === "/" ? `/${child.key}` : `${valuePath}/${child.key}`, child.value);
274
+ }
275
+ }
276
+ };
277
+ searchInValue(normalizedPath, rootValue);
278
+ return {
279
+ data: entries,
280
+ message: entries.length >= limit ? `Results truncated to limit ${limit}` : void 0
281
+ };
282
+ }
283
+ async statHandler(ctx) {
284
+ await this.ensureLoaded();
285
+ const normalizedPath = ctx.params.path ? `/${ctx.params.path}` : "/";
286
+ const segments = this.getPathSegments(normalizedPath);
287
+ const value = this.getValueAtPath(this.jsonData, segments);
288
+ if (value === void 0) throw new AFSNotFoundError(normalizedPath);
289
+ const isDir = this.isDirectoryValue(value);
290
+ const children = isDir ? this.getChildren(value) : [];
291
+ const meta = { ...this.loadMeta(normalizedPath) };
292
+ if (isDir) meta.childrenCount = children.length;
293
+ return { data: {
294
+ id: segments.length > 0 ? segments[segments.length - 1] : "/",
295
+ path: normalizedPath,
296
+ createdAt: this.fileStats.birthtime,
297
+ updatedAt: this.fileStats.mtime,
298
+ meta
299
+ } };
300
+ }
301
+ async readCapabilitiesHandler(_ctx) {
302
+ await this.ensureLoaded();
303
+ const operations = [
304
+ "list",
305
+ "read",
306
+ "stat",
307
+ "explain",
308
+ "search"
309
+ ];
310
+ if (this.accessMode === "readwrite") operations.push("write", "delete", "rename");
311
+ return {
312
+ id: "/.meta/.capabilities",
313
+ path: "/.meta/.capabilities",
314
+ content: {
315
+ schemaVersion: 1,
316
+ provider: this.name,
317
+ description: this.description || `JSON/YAML virtual filesystem (${this.fileFormat} format)`,
318
+ tools: [],
319
+ actions: [],
320
+ operations: this.getOperationsDeclaration()
321
+ },
322
+ meta: {
323
+ kind: "afs:capabilities",
324
+ operations
325
+ }
326
+ };
327
+ }
328
+ async explainHandler(ctx) {
329
+ await this.ensureLoaded();
330
+ const normalizedPath = joinURL("/", ctx.params.path ?? "");
331
+ const format = ctx.options?.format || "markdown";
332
+ const segments = this.getPathSegments(normalizedPath);
333
+ const value = this.getValueAtPath(this.jsonData, segments);
334
+ if (value === void 0) throw new AFSNotFoundError(normalizedPath);
335
+ const nodeName = segments.length > 0 ? segments[segments.length - 1] : "/";
336
+ const isDir = this.isDirectoryValue(value);
337
+ const storedMeta = this.loadMeta(normalizedPath);
338
+ const lines = [];
339
+ if (format === "markdown") {
340
+ lines.push(`# ${nodeName}`);
341
+ lines.push("");
342
+ lines.push(`**Path:** \`${normalizedPath}\``);
343
+ lines.push(`**Format:** ${this.fileFormat.toUpperCase()}`);
344
+ if (normalizedPath === "/") {
345
+ const topType = Array.isArray(this.jsonData) ? "array" : "object";
346
+ const children = this.getChildren(this.jsonData);
347
+ lines.push(`**Structure:** ${topType}`);
348
+ lines.push(`**Top-level keys:** ${children.length}`);
349
+ if (children.length > 0) {
350
+ lines.push("");
351
+ lines.push("## Keys");
352
+ lines.push("");
353
+ for (const child of children.slice(0, 30)) {
354
+ const childVal = child.value;
355
+ const childType = this.describeType(childVal);
356
+ lines.push(`- \`${child.key}\` — ${childType}`);
357
+ }
358
+ if (children.length > 30) lines.push(`- ... and ${children.length - 30} more`);
359
+ }
360
+ } else if (Array.isArray(value)) {
361
+ lines.push(`**Type:** array`);
362
+ lines.push(`**Elements:** ${value.length}`);
363
+ if (value.length > 0) {
364
+ const elementType = this.describeType(value[0]);
365
+ const isHomogeneous = value.every((v) => this.describeType(v) === elementType);
366
+ lines.push(`**Element type:** ${isHomogeneous ? elementType : "mixed"}`);
367
+ }
368
+ } else if (typeof value === "object" && value !== null) {
369
+ const children = this.getChildren(value);
370
+ lines.push(`**Type:** object`);
371
+ lines.push(`**Keys:** ${children.length}`);
372
+ if (children.length > 0) {
373
+ lines.push("");
374
+ lines.push("## Keys");
375
+ lines.push("");
376
+ for (const child of children.slice(0, 30)) {
377
+ const childType = this.describeType(child.value);
378
+ lines.push(`- \`${child.key}\` — ${childType}`);
379
+ }
380
+ if (children.length > 30) lines.push(`- ... and ${children.length - 30} more`);
381
+ }
382
+ } else {
383
+ const valType = value === null ? "null" : typeof value;
384
+ lines.push(`**Type:** ${valType}`);
385
+ const valStr = String(value);
386
+ if (valStr.length > 200) lines.push(`**Value:** ${valStr.slice(0, 200)}...`);
387
+ else lines.push(`**Value:** ${valStr}`);
388
+ }
389
+ if (storedMeta) {
390
+ lines.push("");
391
+ lines.push("## Metadata");
392
+ for (const [key, val] of Object.entries(storedMeta)) lines.push(`- **${key}:** ${JSON.stringify(val)}`);
393
+ }
394
+ } else {
395
+ lines.push(`${nodeName} (${isDir ? "directory" : "value"})`);
396
+ lines.push(`Path: ${normalizedPath}`);
397
+ lines.push(`Format: ${this.fileFormat}`);
398
+ if (isDir) {
399
+ const children = this.getChildren(value);
400
+ lines.push(`Children: ${children.length}`);
401
+ } else {
402
+ const valStr = String(value);
403
+ lines.push(`Type: ${value === null ? "null" : typeof value}`);
404
+ lines.push(`Value: ${valStr.length > 200 ? `${valStr.slice(0, 200)}...` : valStr}`);
405
+ }
406
+ }
407
+ return {
408
+ content: lines.join("\n"),
409
+ format
410
+ };
411
+ }
412
+ /**
413
+ * Get a human-readable type description for a JSON value.
414
+ */
415
+ describeType(value) {
416
+ if (value === null) return "null";
417
+ if (Array.isArray(value)) return `array[${value.length}]`;
418
+ if (typeof value === "object") return `object{${Object.keys(value).filter((k) => !this.isMetaKey(k)).length} keys}`;
419
+ return typeof value;
420
+ }
421
+ /**
422
+ * Check if a key is a hidden meta key that should be filtered from listings
423
+ */
424
+ isMetaKey(key) {
425
+ return key === AFS_KEY;
426
+ }
427
+ /**
428
+ * Load metadata for a node.
429
+ *
430
+ * Storage location depends on node type (mirrors FS provider's .afs structure):
431
+ * - Objects: `.afs.meta` key within the object itself
432
+ * - Primitives: parent's `.afs[".nodes"][key].meta`
433
+ */
434
+ loadMeta(nodePath) {
435
+ const segments = this.getPathSegments(nodePath);
436
+ const value = this.getValueAtPath(this.jsonData, segments);
437
+ if (value === void 0) return null;
438
+ if (this.isDirectoryValue(value) && !Array.isArray(value)) {
439
+ const afs$1 = value[AFS_KEY];
440
+ if (afs$1 && typeof afs$1 === "object" && !Array.isArray(afs$1)) {
441
+ const meta$1 = afs$1[META_KEY];
442
+ if (meta$1 && typeof meta$1 === "object" && !Array.isArray(meta$1)) return meta$1;
443
+ }
444
+ return null;
445
+ }
446
+ if (segments.length === 0) return null;
447
+ const parentSegments = segments.slice(0, -1);
448
+ const nodeKey = segments[segments.length - 1];
449
+ const parentValue = this.getValueAtPath(this.jsonData, parentSegments);
450
+ if (!parentValue || Array.isArray(parentValue) || typeof parentValue !== "object") return null;
451
+ const afs = parentValue[AFS_KEY];
452
+ if (!afs || typeof afs !== "object" || Array.isArray(afs)) return null;
453
+ const nodes = afs[NODES_KEY];
454
+ if (!nodes || typeof nodes !== "object" || Array.isArray(nodes)) return null;
455
+ const nodeEntry = nodes[nodeKey];
456
+ if (!nodeEntry || typeof nodeEntry !== "object" || Array.isArray(nodeEntry)) return null;
457
+ const meta = nodeEntry[META_KEY];
458
+ if (!meta || typeof meta !== "object" || Array.isArray(meta)) return null;
459
+ return meta;
460
+ }
461
+ /**
462
+ * Save metadata for a node.
463
+ *
464
+ * Storage location depends on node type (mirrors FS provider's .afs structure):
465
+ * - Objects: `.afs.meta` key within the object itself
466
+ * - Primitives: parent's `.afs[".nodes"][key].meta`
467
+ */
468
+ saveMeta(nodePath, meta) {
469
+ const segments = this.getPathSegments(nodePath);
470
+ const value = this.getValueAtPath(this.jsonData, segments);
471
+ if (value === void 0) throw new AFSNotFoundError(nodePath);
472
+ if (this.isDirectoryValue(value) && !Array.isArray(value)) {
473
+ if (!value[AFS_KEY]) value[AFS_KEY] = {};
474
+ value[AFS_KEY][META_KEY] = meta;
475
+ return;
476
+ }
477
+ if (segments.length === 0) throw new Error("Cannot save meta for root when root is not an object");
478
+ const parentSegments = segments.slice(0, -1);
479
+ const nodeKey = segments[segments.length - 1];
480
+ const parentValue = this.getValueAtPath(this.jsonData, parentSegments);
481
+ if (!parentValue || typeof parentValue !== "object") throw new Error(`Parent path is not an object`);
482
+ if (Array.isArray(parentValue)) throw new Error(`Cannot save meta for array elements`);
483
+ if (!parentValue[AFS_KEY]) parentValue[AFS_KEY] = {};
484
+ if (!parentValue[AFS_KEY][NODES_KEY]) parentValue[AFS_KEY][NODES_KEY] = {};
485
+ if (!parentValue[AFS_KEY][NODES_KEY][nodeKey]) parentValue[AFS_KEY][NODES_KEY][nodeKey] = {};
486
+ parentValue[AFS_KEY][NODES_KEY][nodeKey][META_KEY] = meta;
59
487
  }
60
- name;
61
- description;
62
- accessMode;
63
- agentSkills;
64
488
  /**
65
489
  * Load JSON/YAML data from file. Called lazily on first access.
66
490
  * Uses YAML parser which can handle both JSON and YAML formats.
@@ -68,12 +492,12 @@ var AFSJSON = class AFSJSON {
68
492
  async ensureLoaded() {
69
493
  if (this.jsonData !== null) return;
70
494
  try {
71
- const stats = await stat(this.options.jsonPath);
495
+ const stats = await stat(this.resolvedJsonPath);
72
496
  this.fileStats = {
73
497
  birthtime: stats.birthtime,
74
498
  mtime: stats.mtime
75
499
  };
76
- this.jsonData = parse(await readFile(this.options.jsonPath, "utf8"));
500
+ this.jsonData = parse(await readFile(this.resolvedJsonPath, "utf8"));
77
501
  } catch (error) {
78
502
  if (error.code === "ENOENT") this.jsonData = {};
79
503
  else throw error;
@@ -86,22 +510,14 @@ var AFSJSON = class AFSJSON {
86
510
  let content;
87
511
  if (this.fileFormat === "yaml") content = stringify(this.jsonData);
88
512
  else content = JSON.stringify(this.jsonData, null, 2);
89
- await writeFile(this.options.jsonPath, content, "utf8");
90
- const stats = await stat(this.options.jsonPath);
513
+ await writeFile(this.resolvedJsonPath, content, "utf8");
514
+ const stats = await stat(this.resolvedJsonPath);
91
515
  this.fileStats = {
92
516
  birthtime: this.fileStats.birthtime || stats.birthtime,
93
517
  mtime: stats.mtime
94
518
  };
95
519
  }
96
520
  /**
97
- * Normalize path to ensure consistent format
98
- */
99
- normalizePath(path) {
100
- let normalized = path.startsWith("/") ? path : `/${path}`;
101
- if (normalized.length > 1 && normalized.endsWith("/")) normalized = normalized.slice(0, -1);
102
- return normalized;
103
- }
104
- /**
105
521
  * Get path segments from normalized path
106
522
  */
107
523
  getPathSegments(path) {
@@ -187,20 +603,20 @@ var AFSJSON = class AFSJSON {
187
603
  /**
188
604
  * Check if a value is a "directory" (object or array with children)
189
605
  */
190
- isDirectory(value) {
606
+ isDirectoryValue(value) {
191
607
  if (Array.isArray(value)) return true;
192
608
  if (typeof value === "object" && value !== null) return true;
193
609
  return false;
194
610
  }
195
611
  /**
196
- * Get children of a directory value
612
+ * Get children of a directory value (filters out .afs meta key)
197
613
  */
198
614
  getChildren(value) {
199
615
  if (Array.isArray(value)) return value.map((item, index) => ({
200
616
  key: String(index),
201
617
  value: item
202
618
  }));
203
- if (typeof value === "object" && value !== null) return Object.entries(value).map(([key, val]) => ({
619
+ if (typeof value === "object" && value !== null) return Object.entries(value).filter(([key]) => !this.isMetaKey(key)).map(([key, val]) => ({
204
620
  key,
205
621
  value: val
206
622
  }));
@@ -210,158 +626,32 @@ var AFSJSON = class AFSJSON {
210
626
  * Convert a JSON value to an AFSEntry
211
627
  */
212
628
  valueToAFSEntry(path, value) {
213
- const isDir = this.isDirectory(value);
629
+ const isDir = this.isDirectoryValue(value);
214
630
  const children = isDir ? this.getChildren(value) : [];
215
- return {
216
- id: path,
217
- path,
631
+ const kind = Array.isArray(value) ? "json:array" : isDir ? "json:object" : "json:value";
632
+ return this.buildEntry(path, {
218
633
  content: isDir ? void 0 : value,
219
- createdAt: this.fileStats.birthtime,
220
- updatedAt: this.fileStats.mtime,
221
- metadata: {
222
- type: isDir ? "directory" : "file",
223
- childrenCount: isDir ? children.length : void 0
224
- }
225
- };
226
- }
227
- async list(path, options) {
228
- await this.ensureLoaded();
229
- const normalizedPath = this.normalizePath(path);
230
- const limit = Math.min(options?.limit || LIST_MAX_LIMIT, LIST_MAX_LIMIT);
231
- const maxChildren = typeof options?.maxChildren === "number" ? options.maxChildren : Number.MAX_SAFE_INTEGER;
232
- const maxDepth = options?.maxDepth ?? 1;
233
- const segments = this.getPathSegments(normalizedPath);
234
- const value = this.getValueAtPath(this.jsonData, segments);
235
- if (value === void 0) throw new Error(`Path not found: ${normalizedPath}`);
236
- const entries = [];
237
- const queue = [{
238
- path: normalizedPath,
239
- value,
240
- depth: 0
241
- }];
242
- while (queue.length > 0) {
243
- const item = queue.shift();
244
- if (!item) break;
245
- const { path: itemPath, value: itemValue, depth } = item;
246
- const entry = this.valueToAFSEntry(itemPath, itemValue);
247
- entries.push(entry);
248
- if (entries.length >= limit) {
249
- if (entry.metadata) entry.metadata.childrenTruncated = true;
250
- break;
251
- }
252
- if (this.isDirectory(itemValue) && depth < maxDepth) {
253
- const children = this.getChildren(itemValue);
254
- const childrenToProcess = children.length > maxChildren ? children.slice(0, maxChildren) : children;
255
- if (childrenToProcess.length < children.length && entry.metadata) entry.metadata.childrenTruncated = true;
256
- for (const child of childrenToProcess) {
257
- const childPath = itemPath === "/" ? `/${child.key}` : `${itemPath}/${child.key}`;
258
- queue.push({
259
- path: childPath,
260
- value: child.value,
261
- depth: depth + 1
262
- });
263
- }
264
- }
265
- }
266
- return { data: entries };
267
- }
268
- async read(path, _options) {
269
- await this.ensureLoaded();
270
- const normalizedPath = this.normalizePath(path);
271
- const segments = this.getPathSegments(normalizedPath);
272
- const value = this.getValueAtPath(this.jsonData, segments);
273
- if (value === void 0) return {
274
- data: void 0,
275
- message: `Path not found: ${normalizedPath}`
276
- };
277
- return { data: this.valueToAFSEntry(normalizedPath, value) };
278
- }
279
- async write(path, entry, _options) {
280
- await this.ensureLoaded();
281
- const normalizedPath = this.normalizePath(path);
282
- const segments = this.getPathSegments(normalizedPath);
283
- this.setValueAtPath(this.jsonData, segments, entry.content);
284
- await this.saveToFile();
285
- const newValue = this.getValueAtPath(this.jsonData, segments);
286
- const isDir = this.isDirectory(newValue);
287
- const children = isDir ? this.getChildren(newValue) : [];
288
- return { data: {
289
- id: normalizedPath,
290
- path: normalizedPath,
291
- content: entry.content,
292
- summary: entry.summary,
293
- description: entry.description,
294
- createdAt: this.fileStats.birthtime,
295
- updatedAt: this.fileStats.mtime,
296
- metadata: {
297
- ...entry.metadata,
298
- type: isDir ? "directory" : "file",
634
+ meta: {
635
+ kind,
299
636
  childrenCount: isDir ? children.length : void 0
300
637
  },
301
- userId: entry.userId,
302
- sessionId: entry.sessionId,
303
- linkTo: entry.linkTo
304
- } };
305
- }
306
- async delete(path, options) {
307
- await this.ensureLoaded();
308
- const normalizedPath = this.normalizePath(path);
309
- const segments = this.getPathSegments(normalizedPath);
310
- const value = this.getValueAtPath(this.jsonData, segments);
311
- if (value === void 0) throw new Error(`Path not found: ${normalizedPath}`);
312
- if (this.isDirectory(value) && this.getChildren(value).length > 0 && !options?.recursive) throw new Error(`Cannot delete directory '${normalizedPath}' without recursive option. Set recursive: true to delete directories.`);
313
- this.deleteValueAtPath(this.jsonData, segments);
314
- await this.saveToFile();
315
- return { message: `Successfully deleted: ${normalizedPath}` };
316
- }
317
- async rename(oldPath, newPath, options) {
318
- await this.ensureLoaded();
319
- const normalizedOldPath = this.normalizePath(oldPath);
320
- const normalizedNewPath = this.normalizePath(newPath);
321
- const oldSegments = this.getPathSegments(normalizedOldPath);
322
- const newSegments = this.getPathSegments(normalizedNewPath);
323
- const oldValue = this.getValueAtPath(this.jsonData, oldSegments);
324
- if (oldValue === void 0) throw new Error(`Source path not found: ${normalizedOldPath}`);
325
- if (this.getValueAtPath(this.jsonData, newSegments) !== void 0 && !options?.overwrite) throw new Error(`Destination '${normalizedNewPath}' already exists. Set overwrite: true to replace it.`);
326
- this.setValueAtPath(this.jsonData, newSegments, oldValue);
327
- this.deleteValueAtPath(this.jsonData, oldSegments);
328
- await this.saveToFile();
329
- return { message: `Successfully renamed '${normalizedOldPath}' to '${normalizedNewPath}'` };
330
- }
331
- async search(path, query, options) {
332
- await this.ensureLoaded();
333
- const normalizedPath = this.normalizePath(path);
334
- const limit = Math.min(options?.limit || LIST_MAX_LIMIT, LIST_MAX_LIMIT);
335
- const caseSensitive = options?.caseSensitive ?? false;
336
- const segments = this.getPathSegments(normalizedPath);
337
- const rootValue = this.getValueAtPath(this.jsonData, segments);
338
- if (rootValue === void 0) throw new Error(`Path not found: ${normalizedPath}`);
339
- const entries = [];
340
- const searchQuery = caseSensitive ? query : query.toLowerCase();
341
- const searchInValue = (valuePath, value) => {
342
- if (entries.length >= limit) return;
343
- let matched = false;
344
- if (!this.isDirectory(value)) {
345
- const valueStr = typeof value === "string" ? value : JSON.stringify(value);
346
- if ((caseSensitive ? valueStr : valueStr.toLowerCase()).includes(searchQuery)) matched = true;
347
- }
348
- if (matched) entries.push(this.valueToAFSEntry(valuePath, value));
349
- if (this.isDirectory(value)) {
350
- const children = this.getChildren(value);
351
- for (const child of children) {
352
- if (entries.length >= limit) break;
353
- searchInValue(valuePath === "/" ? `/${child.key}` : `${valuePath}/${child.key}`, child.value);
354
- }
355
- }
356
- };
357
- searchInValue(normalizedPath, rootValue);
358
- return {
359
- data: entries,
360
- message: entries.length >= limit ? `Results truncated to limit ${limit}` : void 0
361
- };
638
+ createdAt: this.fileStats.birthtime,
639
+ updatedAt: this.fileStats.mtime
640
+ });
362
641
  }
363
642
  };
643
+ __decorate([Meta("/:path*")], AFSJSON.prototype, "readMetaHandler", null);
644
+ __decorate([List("/:path*", { handleDepth: true })], AFSJSON.prototype, "listHandler", null);
645
+ __decorate([Read("/:path*")], AFSJSON.prototype, "readHandler", null);
646
+ __decorate([Write("/:path*")], AFSJSON.prototype, "writeHandler", null);
647
+ __decorate([Delete("/:path*")], AFSJSON.prototype, "deleteHandler", null);
648
+ __decorate([Rename("/:path*")], AFSJSON.prototype, "renameHandler", null);
649
+ __decorate([Search("/:path*")], AFSJSON.prototype, "searchHandler", null);
650
+ __decorate([Stat("/:path*")], AFSJSON.prototype, "statHandler", null);
651
+ __decorate([Read("/.meta/.capabilities")], AFSJSON.prototype, "readCapabilitiesHandler", null);
652
+ __decorate([Explain("/:path*")], AFSJSON.prototype, "explainHandler", null);
653
+ var src_default = AFSJSON;
364
654
 
365
655
  //#endregion
366
- export { AFSJSON };
656
+ export { AFSJSON, src_default as default };
367
657
  //# sourceMappingURL=index.mjs.map