@aigne/afs-json 1.11.0-beta.5 → 1.11.0-beta.7

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