ShtukbaseStandard
archivo del paquete→ .shtukbase/packages/chat/lens/fs-store.js

lens/fs-store.js

161 líneas, 8.4 KB.

El archivo tal como está en el paquete: el código y sus comentarios no se traducen.

  1. // fs-store.js: the space tools over a folder picked with the File System Access API (Chrome),
  2. // for chat.html opened as a plain file. Same semantics as apps/shtuk/src/core/api.ts for
  3. // tree / records.list / records.read / records.write.
  4. // Limits: front matter is a YAML subset: flat `key: value` lines (strings, numbers, booleans,
  5. // null, [a, b] lists, {k: v} flow maps) and one level of indented ` key: value` under a bare
  6. // `key:`. Other YAML is kept as written but not understood. The folder is asked for again after a reload.
  7. (function () {
  8. 'use strict';
  9. // A copy of four entries of apps/shtuk/src/core/tools.ts; chat/test/tools-sync.test.ts keeps it equal.
  10. var path = { type: 'string', description: 'Space-relative Markdown path with a leading slash.' };
  11. var TOOLS = [
  12. { name: 'tree', description: 'List Markdown pages with their paths, types, titles, and icons.', inputSchema: { type: 'object', properties: {} } },
  13. { name: 'records_list', description: 'Read a collection schema and list its records with their metadata.',
  14. inputSchema: { type: 'object', properties: { collection: { type: 'string', description: 'Path to the Markdown collection page, starting with /.' } }, required: ['collection'] } },
  15. { name: 'records_read', description: 'Read a record’s metadata and Markdown body.', inputSchema: { type: 'object', properties: { path: path }, required: ['path'] } },
  16. { name: 'records_write', description: 'Create or update a record, merging metadata and replacing the body when provided.',
  17. inputSchema: { type: 'object', properties: { path: path, meta: { type: 'object' }, body: { type: 'string' } }, required: ['path'] } }
  18. ];
  19. function scalar(v) {
  20. v = v.trim();
  21. if (v === '') return null;
  22. if (/^".*"$/.test(v)) { try { return JSON.parse(v); } catch (e) { return v.slice(1, -1); } }
  23. if (/^'.*'$/.test(v)) return v.slice(1, -1).replace(/''/g, "'");
  24. if (v === 'true' || v === 'false') return v === 'true';
  25. if (v === 'null' || v === '~') return null;
  26. if (/^-?\d+(\.\d+)?$/.test(v)) return Number(v);
  27. if (/^\[.*\]$/.test(v)) return splitFlow(v.slice(1, -1)).map(scalar);
  28. if (/^\{.*\}$/.test(v)) {
  29. var m = {};
  30. splitFlow(v.slice(1, -1)).forEach(function (kv) { var i = kv.indexOf(':'); if (i > 0) m[kv.slice(0, i).trim()] = scalar(kv.slice(i + 1)); });
  31. return m;
  32. }
  33. return v;
  34. }
  35. function splitFlow(s) {
  36. var out = [], depth = 0, cur = '', q = '';
  37. for (var i = 0; i < s.length; i++) {
  38. var c = s[i];
  39. if (q) { cur += c; if (c === q) q = ''; continue; }
  40. if (c === '"' || c === "'") q = c;
  41. if (c === '[' || c === '{') depth++;
  42. if (c === ']' || c === '}') depth--;
  43. if (c === ',' && depth === 0) { if (cur.trim()) out.push(cur.trim()); cur = ''; } else cur += c;
  44. }
  45. if (cur.trim()) out.push(cur.trim());
  46. return out;
  47. }
  48. function split(text) {
  49. var m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text);
  50. if (!m) return { head: null, body: text };
  51. return { head: m[1], body: text.slice(m[0].length) };
  52. }
  53. function parseHead(head) {
  54. var meta = {}, parent = null;
  55. (head || '').split(/\r?\n/).forEach(function (line) {
  56. var nested = /^\s+([A-Za-z0-9_-]+):\s*(.*)$/.exec(line);
  57. if (nested && parent) { meta[parent][nested[1]] = scalar(nested[2]); return; }
  58. var top = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line);
  59. if (!top) return;
  60. if (top[2].trim() === '') { meta[top[1]] = {}; parent = top[1]; } else { meta[top[1]] = scalar(top[2]); parent = null; }
  61. });
  62. return meta;
  63. }
  64. function yamlValue(v) {
  65. if (v === null || typeof v === 'number' || typeof v === 'boolean') return String(v);
  66. if (typeof v === 'string') return /^[\p{L}\p{N} _.\/-]+$/u.test(v) && !/^(true|false|null|-?\d+(\.\d+)?)$/.test(v) && v.trim() === v ? v : JSON.stringify(v);
  67. return JSON.stringify(v); // lists and maps as JSON flow, which is valid YAML
  68. }
  69. function writeHead(head, changes) {
  70. var lines = head ? head.split(/\r?\n/) : [];
  71. Object.keys(changes).forEach(function (key) {
  72. var line = key + ': ' + yamlValue(changes[key]);
  73. var at = lines.findIndex(function (l) { return l.indexOf(key + ':') === 0; });
  74. if (at < 0) { lines.push(line); return; }
  75. var end = at + 1;
  76. while (end < lines.length && /^\s+\S/.test(lines[end])) end++;
  77. lines.splice(at, end - at, line);
  78. });
  79. return lines.join('\n');
  80. }
  81. function checked(p) {
  82. if (typeof p !== 'string' || p[0] !== '/' || p.split('/').some(function (s) { return s === '..' || s === '.'; })) throw new Error('Invalid path: ' + p);
  83. return p;
  84. }
  85. function titleOf(p, meta) { return String(meta.title != null ? meta.title : p.split('/').pop().replace(/\.md$/, '')); }
  86. function FsStore(dir) { this.dir = dir; this.name = dir.name; }
  87. FsStore.prototype.list = async function () {
  88. var out = [];
  89. async function walk(handle, prefix) {
  90. for await (var entry of handle.values()) {
  91. if (entry.name[0] === '.' || entry.name === 'node_modules') continue;
  92. if (entry.kind === 'directory') await walk(entry, prefix + entry.name + '/');
  93. else if (/\.md$/.test(entry.name)) out.push(prefix + entry.name);
  94. }
  95. }
  96. await walk(this.dir, '/');
  97. return out.sort();
  98. };
  99. FsStore.prototype.handle = async function (p, create) {
  100. var parts = checked(p).slice(1).split('/'), h = this.dir;
  101. for (var i = 0; i < parts.length - 1; i++) h = await h.getDirectoryHandle(parts[i], { create: !!create });
  102. return h.getFileHandle(parts[parts.length - 1], { create: !!create });
  103. };
  104. FsStore.prototype.text = async function (p) {
  105. try { return await (await (await this.handle(p)).getFile()).text(); }
  106. catch (e) { if (e && e.name === 'NotFoundError') return null; throw e; }
  107. };
  108. FsStore.prototype.read = async function (p) {
  109. var t = await this.text(p);
  110. if (t == null) throw new Error('Not found: ' + p);
  111. var s = split(t);
  112. return { path: p, meta: parseHead(s.head), body: s.body };
  113. };
  114. FsStore.prototype.call = async function (action, args) {
  115. args = args || {};
  116. var self = this;
  117. switch (action) {
  118. case 'space.info': return { name: this.name, layout: null, lenses: [] };
  119. case 'tree':
  120. return Promise.all((await this.list()).map(async function (p) {
  121. var meta = (await self.read(p)).meta;
  122. return { path: p, type: meta.type || 'Page', title: titleOf(p, meta), icon: meta.icon || null };
  123. }));
  124. case 'records.list': {
  125. var c = checked(args.collection), meta = (await this.read(c)).meta;
  126. if (meta.type !== 'Collection') throw new Error('Not a Collection: ' + c);
  127. var folder = (meta.items && meta.items.path) || meta.writeTo || c.replace(/\.md$/, '');
  128. var prefix = folder === '/' ? '/' : String(folder).replace(/\/$/, '') + '/';
  129. var direct = (await this.list()).filter(function (p) { return p.indexOf(prefix) === 0 && p.slice(prefix.length).indexOf('/') < 0 && p !== c; });
  130. var items = await Promise.all(direct.map(async function (p) { var m = (await self.read(p)).meta; return { path: p, meta: m, title: titleOf(p, m) }; }));
  131. return { collection: { path: c, title: titleOf(c, meta), icon: meta.icon || null, properties: meta.properties || {} }, items: items };
  132. }
  133. case 'records.read': return this.read(checked(args.path));
  134. case 'records.write': {
  135. var p = checked(args.path);
  136. if (!/\.md$/.test(p)) throw new Error('Not a Markdown path: ' + p);
  137. if (args.meta != null && (typeof args.meta !== 'object' || Array.isArray(args.meta))) throw new Error('meta must be a map');
  138. if (args.body != null && typeof args.body !== 'string') throw new Error('body must be a string');
  139. var old = await this.text(p), s = split(old || '');
  140. var head = writeHead(s.head, args.meta || {});
  141. var body = args.body != null ? args.body : s.body;
  142. var text = (head ? '---\n' + head + '\n---\n' : '') + body;
  143. var w = await (await this.handle(p, true)).createWritable();
  144. await w.write(text);
  145. await w.close();
  146. return { path: p };
  147. }
  148. default: throw new Error('Unknown action: ' + action);
  149. }
  150. };
  151. window.chatFs = {
  152. supported: typeof window.showDirectoryPicker === 'function',
  153. tools: TOOLS,
  154. open: async function () { return new FsStore(await window.showDirectoryPicker({ mode: 'readwrite' })); },
  155. _parse: function (t) { var s = split(t); return { meta: parseHead(s.head), body: s.body }; },
  156. _write: writeHead
  157. };
  158. })();