package file→ .shtukbase/packages/chat/lens/fs-store.js
lens/fs-store.js
161 lines, 8.4 KB.
- // fs-store.js: the space tools over a folder picked with the File System Access API (Chrome),
- // for chat.html opened as a plain file. Same semantics as apps/shtuk/src/core/api.ts for
- // tree / records.list / records.read / records.write.
- // Limits: front matter is a YAML subset: flat `key: value` lines (strings, numbers, booleans,
- // null, [a, b] lists, {k: v} flow maps) and one level of indented ` key: value` under a bare
- // `key:`. Other YAML is kept as written but not understood. The folder is asked for again after a reload.
- (function () {
- 'use strict';
- // A copy of four entries of apps/shtuk/src/core/tools.ts; chat/test/tools-sync.test.ts keeps it equal.
- var path = { type: 'string', description: 'Space-relative Markdown path with a leading slash.' };
- var TOOLS = [
- { name: 'tree', description: 'List Markdown pages with their paths, types, titles, and icons.', inputSchema: { type: 'object', properties: {} } },
- { name: 'records_list', description: 'Read a collection schema and list its records with their metadata.',
- inputSchema: { type: 'object', properties: { collection: { type: 'string', description: 'Path to the Markdown collection page, starting with /.' } }, required: ['collection'] } },
- { name: 'records_read', description: 'Read a record’s metadata and Markdown body.', inputSchema: { type: 'object', properties: { path: path }, required: ['path'] } },
- { name: 'records_write', description: 'Create or update a record, merging metadata and replacing the body when provided.',
- inputSchema: { type: 'object', properties: { path: path, meta: { type: 'object' }, body: { type: 'string' } }, required: ['path'] } }
- ];
- function scalar(v) {
- v = v.trim();
- if (v === '') return null;
- if (/^".*"$/.test(v)) { try { return JSON.parse(v); } catch (e) { return v.slice(1, -1); } }
- if (/^'.*'$/.test(v)) return v.slice(1, -1).replace(/''/g, "'");
- if (v === 'true' || v === 'false') return v === 'true';
- if (v === 'null' || v === '~') return null;
- if (/^-?\d+(\.\d+)?$/.test(v)) return Number(v);
- if (/^\[.*\]$/.test(v)) return splitFlow(v.slice(1, -1)).map(scalar);
- if (/^\{.*\}$/.test(v)) {
- var m = {};
- 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)); });
- return m;
- }
- return v;
- }
- function splitFlow(s) {
- var out = [], depth = 0, cur = '', q = '';
- for (var i = 0; i < s.length; i++) {
- var c = s[i];
- if (q) { cur += c; if (c === q) q = ''; continue; }
- if (c === '"' || c === "'") q = c;
- if (c === '[' || c === '{') depth++;
- if (c === ']' || c === '}') depth--;
- if (c === ',' && depth === 0) { if (cur.trim()) out.push(cur.trim()); cur = ''; } else cur += c;
- }
- if (cur.trim()) out.push(cur.trim());
- return out;
- }
- function split(text) {
- var m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text);
- if (!m) return { head: null, body: text };
- return { head: m[1], body: text.slice(m[0].length) };
- }
- function parseHead(head) {
- var meta = {}, parent = null;
- (head || '').split(/\r?\n/).forEach(function (line) {
- var nested = /^\s+([A-Za-z0-9_-]+):\s*(.*)$/.exec(line);
- if (nested && parent) { meta[parent][nested[1]] = scalar(nested[2]); return; }
- var top = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line);
- if (!top) return;
- if (top[2].trim() === '') { meta[top[1]] = {}; parent = top[1]; } else { meta[top[1]] = scalar(top[2]); parent = null; }
- });
- return meta;
- }
- function yamlValue(v) {
- if (v === null || typeof v === 'number' || typeof v === 'boolean') return String(v);
- 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);
- return JSON.stringify(v); // lists and maps as JSON flow, which is valid YAML
- }
- function writeHead(head, changes) {
- var lines = head ? head.split(/\r?\n/) : [];
- Object.keys(changes).forEach(function (key) {
- var line = key + ': ' + yamlValue(changes[key]);
- var at = lines.findIndex(function (l) { return l.indexOf(key + ':') === 0; });
- if (at < 0) { lines.push(line); return; }
- var end = at + 1;
- while (end < lines.length && /^\s+\S/.test(lines[end])) end++;
- lines.splice(at, end - at, line);
- });
- return lines.join('\n');
- }
- function checked(p) {
- if (typeof p !== 'string' || p[0] !== '/' || p.split('/').some(function (s) { return s === '..' || s === '.'; })) throw new Error('Invalid path: ' + p);
- return p;
- }
- function titleOf(p, meta) { return String(meta.title != null ? meta.title : p.split('/').pop().replace(/\.md$/, '')); }
- function FsStore(dir) { this.dir = dir; this.name = dir.name; }
- FsStore.prototype.list = async function () {
- var out = [];
- async function walk(handle, prefix) {
- for await (var entry of handle.values()) {
- if (entry.name[0] === '.' || entry.name === 'node_modules') continue;
- if (entry.kind === 'directory') await walk(entry, prefix + entry.name + '/');
- else if (/\.md$/.test(entry.name)) out.push(prefix + entry.name);
- }
- }
- await walk(this.dir, '/');
- return out.sort();
- };
- FsStore.prototype.handle = async function (p, create) {
- var parts = checked(p).slice(1).split('/'), h = this.dir;
- for (var i = 0; i < parts.length - 1; i++) h = await h.getDirectoryHandle(parts[i], { create: !!create });
- return h.getFileHandle(parts[parts.length - 1], { create: !!create });
- };
- FsStore.prototype.text = async function (p) {
- try { return await (await (await this.handle(p)).getFile()).text(); }
- catch (e) { if (e && e.name === 'NotFoundError') return null; throw e; }
- };
- FsStore.prototype.read = async function (p) {
- var t = await this.text(p);
- if (t == null) throw new Error('Not found: ' + p);
- var s = split(t);
- return { path: p, meta: parseHead(s.head), body: s.body };
- };
- FsStore.prototype.call = async function (action, args) {
- args = args || {};
- var self = this;
- switch (action) {
- case 'space.info': return { name: this.name, layout: null, lenses: [] };
- case 'tree':
- return Promise.all((await this.list()).map(async function (p) {
- var meta = (await self.read(p)).meta;
- return { path: p, type: meta.type || 'Page', title: titleOf(p, meta), icon: meta.icon || null };
- }));
- case 'records.list': {
- var c = checked(args.collection), meta = (await this.read(c)).meta;
- if (meta.type !== 'Collection') throw new Error('Not a Collection: ' + c);
- var folder = (meta.items && meta.items.path) || meta.writeTo || c.replace(/\.md$/, '');
- var prefix = folder === '/' ? '/' : String(folder).replace(/\/$/, '') + '/';
- var direct = (await this.list()).filter(function (p) { return p.indexOf(prefix) === 0 && p.slice(prefix.length).indexOf('/') < 0 && p !== c; });
- 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) }; }));
- return { collection: { path: c, title: titleOf(c, meta), icon: meta.icon || null, properties: meta.properties || {} }, items: items };
- }
- case 'records.read': return this.read(checked(args.path));
- case 'records.write': {
- var p = checked(args.path);
- if (!/\.md$/.test(p)) throw new Error('Not a Markdown path: ' + p);
- if (args.meta != null && (typeof args.meta !== 'object' || Array.isArray(args.meta))) throw new Error('meta must be a map');
- if (args.body != null && typeof args.body !== 'string') throw new Error('body must be a string');
- var old = await this.text(p), s = split(old || '');
- var head = writeHead(s.head, args.meta || {});
- var body = args.body != null ? args.body : s.body;
- var text = (head ? '---\n' + head + '\n---\n' : '') + body;
- var w = await (await this.handle(p, true)).createWritable();
- await w.write(text);
- await w.close();
- return { path: p };
- }
- default: throw new Error('Unknown action: ' + action);
- }
- };
- window.chatFs = {
- supported: typeof window.showDirectoryPicker === 'function',
- tools: TOOLS,
- open: async function () { return new FsStore(await window.showDirectoryPicker({ mode: 'readwrite' })); },
- _parse: function (t) { var s = split(t); return { meta: parseHead(s.head), body: s.body }; },
- _write: writeHead
- };
- })();