Saving modules to files

This commit is contained in:
Dustin Swan 2026-04-01 21:55:30 -06:00
parent ed103ed2cb
commit d6466555df
No known key found for this signature in database
GPG key ID: 30D46587E2100467
3 changed files with 62 additions and 3 deletions

View file

@ -12,9 +12,13 @@ textEditor = name \
buffersKey = "textEditorBuffers";
# load from staging buffers if it exists there. if not, load from source
source = getAt [buffersKey, name]
| None \ getSource name
| Some v \ v;
# source = getAt [buffersKey, name]
# | None \ getSource name
# | Some v \ v;
source = getModuleSource name
| Some s \ s
| None \ getSource name;
lines = split "\n" source;

View file

@ -122,6 +122,12 @@ export const _rt = {
if (!def) return "";
return prettyPrint(def);
},
getModuleSource: (moduleName: string) => {
const moduleDefs = [...definitions.values()]
.filter(d => d.module === moduleName);
if (moduleDefs.length === 0) return { _tag: 'None' };
return { _tag: 'Some', _0: moduleDefs.map(d => prettyPrint(d)).join('\n\n') };
},
"saveImage!": () => {
const saved: Record<string, string> = {};
for (const [name, ast] of definitions) {
@ -138,6 +144,22 @@ export const _rt = {
URL.revokeObjectURL(url);
return { _tag: 'Ok' };
},
"saveModule!": (moduleName: string) => {
const moduleDefs = [...definitions.values()]
.filter(d => d.module === moduleName);
if (moduleDefs.length === 0) return { _tag: 'Err', _0: 'No module: ' + moduleName };
const content = '@' + moduleName + '\n\n' +
moduleDefs.map(d => prettyPrint(d)).join('\n\n') + '\n\n@\n';
fetch('/api/save', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ filename: moduleName, content })
});
return { _tag: 'Defined', _0: moduleName };
},
rebind: (name: string, pathOrValue: any, maybeValue?: any) => {
if (maybeValue === undefined) {
store[name] = pathOrValue;

33
vite.config.ts Normal file
View file

@ -0,0 +1,33 @@
import { defineConfig } from 'vite'
import fs from 'fs'
import path from 'path'
export default defineConfig({
plugins: [{
name: 'cg-save',
configureServer(server) {
server.middlewares.use('/api/save', (req, res) => {
if (req.method !== 'POST') {
res.statusCode = 405;
res.end();
return;
}
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => {
try {
const { filename, content } = JSON.parse(body);
const filePath = path.join(__dirname, 'src/cg2', filename + '.cg');
fs.writeFileSync(filePath, content);
res.statusCode = 200;
res.end(JSON.stringify({ ok: true }));
} catch (e: any) {
res.statusCode = 500;
res.end(JSON.stringify({ error: e.message }));
}
});
});
}
}]
})