goaljs 0.1.1 → 0.4.0
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/README.md +4 -2
- package/package.json +11 -2
- package/src/app.js +33 -4
- package/src/build.js +48 -10
- package/src/compiler.js +162 -27
- package/src/hmr.js +65 -0
- package/src/keyed.js +14 -2
- package/src/loader.js +61 -36
- package/src/rt.js +118 -0
- package/src/server.js +14 -4
- package/src/vite.js +107 -0
package/README.md
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
<img src="https://goallabs.github.io/goal/assets/goal.svg" alt="" width="72" height="72">
|
|
2
|
+
|
|
1
3
|
# goal.js
|
|
2
4
|
|
|
3
5
|
A compiled JavaScript framework where **`var` is state** and **`let`/`const` are computed**. Pages are
|
|
@@ -37,7 +39,7 @@ export function Counter({ start }) {
|
|
|
37
39
|
|
|
38
40
|
```bash
|
|
39
41
|
npm install goaljs
|
|
40
|
-
npx goal dev . # build the app in this folder, serve it on http://localhost:3000,
|
|
42
|
+
npx goal dev . # build the app in this folder, serve it on http://localhost:3000, update live on save
|
|
41
43
|
```
|
|
42
44
|
|
|
43
45
|
[Getting started](https://goallabs.github.io/goal/getting-started) walks through a first app. The docs
|
|
@@ -52,7 +54,7 @@ also cover [routes](https://goallabs.github.io/goal/routes),
|
|
|
52
54
|
|
|
53
55
|
```bash
|
|
54
56
|
npm install
|
|
55
|
-
npm run demo # builds examples/demo, serves it on http://localhost:3000,
|
|
57
|
+
npm run demo # builds examples/demo, serves it on http://localhost:3000, updates live on save
|
|
56
58
|
npm test # the tests, with 100% coverage of src/ required
|
|
57
59
|
npm run bench:virtual # a 100,000-row virtual list in headless Chrome: speed and memory
|
|
58
60
|
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "goaljs",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "goal.js: var is state, let/const are computed, server-rendered and resumable",
|
|
5
5
|
"homepage": "https://goallabs.github.io/goal/",
|
|
6
6
|
"repository": {
|
|
@@ -44,6 +44,14 @@
|
|
|
44
44
|
"happy-dom": "^21.0.4",
|
|
45
45
|
"vitest": "^5.1.1"
|
|
46
46
|
},
|
|
47
|
+
"peerDependencies": {
|
|
48
|
+
"vite": ">=6"
|
|
49
|
+
},
|
|
50
|
+
"peerDependenciesMeta": {
|
|
51
|
+
"vite": {
|
|
52
|
+
"optional": true
|
|
53
|
+
}
|
|
54
|
+
},
|
|
47
55
|
"bin": {
|
|
48
56
|
"goal": "bin/goal.js"
|
|
49
57
|
},
|
|
@@ -53,6 +61,7 @@
|
|
|
53
61
|
"./rt": "./src/rt.js",
|
|
54
62
|
"./loader": "./src/loader.js",
|
|
55
63
|
"./build": "./src/build.js",
|
|
56
|
-
"./keyed": "./src/keyed.js"
|
|
64
|
+
"./keyed": "./src/keyed.js",
|
|
65
|
+
"./vite": "./src/vite.js"
|
|
57
66
|
}
|
|
58
67
|
}
|
package/src/app.js
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
import { randomBytes, timingSafeEqual } from 'node:crypto';
|
|
14
14
|
import { readFileSync, statSync } from 'node:fs';
|
|
15
15
|
import { extname, resolve, sep } from 'node:path';
|
|
16
|
-
import {
|
|
16
|
+
import { isHtml, _$ctx } from './rt.js';
|
|
17
17
|
import { page } from './server.js';
|
|
18
18
|
|
|
19
19
|
const TYPES = {
|
|
@@ -165,6 +165,16 @@ function match(routes, method, segs) {
|
|
|
165
165
|
return allow.size ? { allow: [...allow] } : null;
|
|
166
166
|
}
|
|
167
167
|
|
|
168
|
+
/** The state a page kept for each component, sent with a live update; anything else counts as none. */
|
|
169
|
+
function keptState(header) {
|
|
170
|
+
try {
|
|
171
|
+
const v = JSON.parse(header);
|
|
172
|
+
return v && typeof v === 'object' ? v : {};
|
|
173
|
+
} catch {
|
|
174
|
+
return {};
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
168
178
|
/**
|
|
169
179
|
* A request handler for node:http.
|
|
170
180
|
* @param {{ method: string, path: string, handler: Function }[]} routes
|
|
@@ -198,13 +208,27 @@ export function createApp(routes, { dev = false, staticDirs = [], config = {}, l
|
|
|
198
208
|
|
|
199
209
|
let method = req.method === 'HEAD' ? 'GET' : req.method;
|
|
200
210
|
let form = {};
|
|
211
|
+
const files = {};
|
|
201
212
|
let body;
|
|
202
213
|
if (!SAFE.has(req.method)) {
|
|
203
214
|
const raw = await readBody(req, limit);
|
|
204
215
|
const type = (req.headers['content-type'] ?? '').split(';')[0].trim();
|
|
205
216
|
if (raw.length) {
|
|
206
217
|
if (type === 'application/x-www-form-urlencoded') form = Object.fromEntries(new URLSearchParams(raw.toString()));
|
|
207
|
-
else if (type === '
|
|
218
|
+
else if (type === 'multipart/form-data') {
|
|
219
|
+
// A form with files: its fields go in form, and each file input's files in files, by name.
|
|
220
|
+
// A file input left empty arrives as an empty field.
|
|
221
|
+
let data;
|
|
222
|
+
try {
|
|
223
|
+
data = await new Response(raw, { headers: { 'content-type': req.headers['content-type'] } }).formData();
|
|
224
|
+
} catch {
|
|
225
|
+
return fail(400, 'Bad request');
|
|
226
|
+
}
|
|
227
|
+
for (const [name, v] of data) {
|
|
228
|
+
if (typeof v === 'string') form[name] = v;
|
|
229
|
+
else (files[name] ??= []).push({ name: v.name, type: v.type, size: v.size, data: Buffer.from(await v.arrayBuffer()) });
|
|
230
|
+
}
|
|
231
|
+
} else if (type === 'application/json') {
|
|
208
232
|
try {
|
|
209
233
|
body = JSON.parse(raw);
|
|
210
234
|
} catch {
|
|
@@ -230,10 +254,15 @@ export function createApp(routes, { dev = false, staticDirs = [], config = {}, l
|
|
|
230
254
|
if (m.allow) return send(405, HTML, errorPage('Method not allowed'), { allow: m.allow.join(', ') });
|
|
231
255
|
|
|
232
256
|
const ctx = _$ctx(token);
|
|
233
|
-
|
|
257
|
+
if (dev && req.headers['x-goal-hmr']) {
|
|
258
|
+
// goal dev: a live update (see hmr.js). Each component gets the state the page kept for it.
|
|
259
|
+
const kept = (ctx.hmr = keptState(req.headers['x-goal-hmr']));
|
|
260
|
+
ctx.k = (chunk, i) => (kept[i]?.c === chunk ? kept[i].s : null);
|
|
261
|
+
}
|
|
262
|
+
const request = { method, path: url.pathname, url, params: m.params, query: Object.fromEntries(url.searchParams), headers: req.headers, cookies, form, files, json: body };
|
|
234
263
|
const cookie = (name, value, opts) => setCookies.push(serializeCookie(name, value, opts));
|
|
235
264
|
const out = await m.route.handler(request, { ctx, redirect, json, notFound, cookie });
|
|
236
|
-
if (out
|
|
265
|
+
if (isHtml(out)) return send(200, HTML, page(out.s, [...ctx.ev], nonce, token, dev));
|
|
237
266
|
if (out === undefined) return send(204);
|
|
238
267
|
if (out?.[REPLY]) return send(out.status, out.type, out.body, out.headers);
|
|
239
268
|
throw new Error('a route returns markup, redirect(), json(), notFound() or nothing');
|
package/src/build.js
CHANGED
|
@@ -47,7 +47,11 @@ const noGoal = {
|
|
|
47
47
|
};
|
|
48
48
|
|
|
49
49
|
/** Client modules as esbuild entry points, each resolved from its .goal file's folder. */
|
|
50
|
-
|
|
50
|
+
/**
|
|
51
|
+
* Client modules as esbuild entry points, each resolved from its .goal file's folder, and the render
|
|
52
|
+
* modules they import (`goal-render:./Panel.goal`, see renderModule in compiler.js), by .goal file.
|
|
53
|
+
*/
|
|
54
|
+
const entriesPlugin = (entries, renders) => {
|
|
51
55
|
// Each entry sits, in name, next to its .goal file, so source maps name that file from the app folder.
|
|
52
56
|
const byPath = new Map([...entries.values()].map((e) => [join(e.dir, `${e.name}.goal.js`), e]));
|
|
53
57
|
return {
|
|
@@ -55,6 +59,8 @@ const entriesPlugin = (entries) => {
|
|
|
55
59
|
setup(b) {
|
|
56
60
|
b.onResolve({ filter: /^goal-entry:/ }, (a) => ({ path: join(entries.get(a.path.slice(11)).dir, `${entries.get(a.path.slice(11)).name}.goal.js`) }));
|
|
57
61
|
b.onLoad({ filter: /\.goal\.js$/ }, (a) => ({ contents: byPath.get(a.path).code, resolveDir: byPath.get(a.path).dir, loader: 'js' }));
|
|
62
|
+
b.onResolve({ filter: /^goal-render:/ }, (a) => ({ path: `${resolve(a.resolveDir, a.path.slice(12))}.render.js` }));
|
|
63
|
+
b.onLoad({ filter: /\.goal\.render\.js$/ }, (a) => ({ contents: renders.get(a.path.slice(0, -10)), resolveDir: dirname(a.path), loader: 'js' }));
|
|
58
64
|
},
|
|
59
65
|
};
|
|
60
66
|
};
|
|
@@ -71,6 +77,7 @@ export async function build(app, { out = join(app, 'dist'), dev = false, publicP
|
|
|
71
77
|
const routes = [];
|
|
72
78
|
const routeFiles = [];
|
|
73
79
|
const entries = new Map(); // client modules, by output name
|
|
80
|
+
const renders = new Map(); // render modules, by .goal file
|
|
74
81
|
rmSync(out, { recursive: true, force: true });
|
|
75
82
|
const all = files(app);
|
|
76
83
|
// The server functions each .goal file exports, so files can import them from each other.
|
|
@@ -88,7 +95,9 @@ export async function build(app, { out = join(app, 'dist'), dev = false, publicP
|
|
|
88
95
|
const target = posix.join(posix.dirname(rel), spec);
|
|
89
96
|
return exported.has(target) ? { base: target.slice(0, -5), names: exported.get(target) } : null;
|
|
90
97
|
};
|
|
91
|
-
|
|
98
|
+
// In dev a chunk's URL names the build, so a page updated live loads the new code.
|
|
99
|
+
const chunk = (n) => `${publicPath}c/${base}.${n}.js${dev ? `?v=${version}` : ''}`;
|
|
100
|
+
const r = compile(readFileSync(join(app, rel), 'utf8'), { file: rel, base, rt: RT, keyed: KEYED, chunk, serverFunctions, dev });
|
|
92
101
|
const server = r.server.replace(/((?:from|import)\s*["'])(\.{1,2}\/[^"']+?)(\.goal|\.m?js)(["'])/g, (_, a, p, ext, b) => `${a}${p}${ext === '.goal' ? '.js' : ext}?v=${version}${b}`);
|
|
93
102
|
write(join(out, 'server', base + '.js'), server);
|
|
94
103
|
if (r.routes.length || r.serverFunctions.length) routeFiles.push(base);
|
|
@@ -99,6 +108,7 @@ export async function build(app, { out = join(app, 'dist'), dev = false, publicP
|
|
|
99
108
|
if (other) throw new Error(`${rel}: route ${route.method} ${route.path} is already in ${other.file}`);
|
|
100
109
|
routes.push({ key, file: rel, label: `${route.method} ${route.path}` });
|
|
101
110
|
}
|
|
111
|
+
renders.set(resolve(app, rel), r.render);
|
|
102
112
|
for (const c of r.clients) entries.set(`${base}.${c.name}`, { code: c.code, dir: resolve(app, dirname(rel)), name: `${posix.basename(base)}.${c.name}` });
|
|
103
113
|
}
|
|
104
114
|
// All browser code in one bundle with code splitting: each component is its own file, and code
|
|
@@ -119,7 +129,7 @@ export async function build(app, { out = join(app, 'dist'), dev = false, publicP
|
|
|
119
129
|
format: 'esm',
|
|
120
130
|
write: false,
|
|
121
131
|
logLevel: 'silent',
|
|
122
|
-
plugins: [entriesPlugin(entries), noGoal],
|
|
132
|
+
plugins: [entriesPlugin(entries, renders), noGoal],
|
|
123
133
|
})
|
|
124
134
|
).outputFiles;
|
|
125
135
|
// A chunk with a keyed list imports the patcher from its own file, next to the chunks.
|
|
@@ -144,39 +154,67 @@ export async function build(app, { out = join(app, 'dist'), dev = false, publicP
|
|
|
144
154
|
return { version, chunks, loader: gzipSync(loaderScript()).length, routes: routes.map((r) => r.label) };
|
|
145
155
|
}
|
|
146
156
|
|
|
147
|
-
/**
|
|
148
|
-
|
|
157
|
+
/**
|
|
158
|
+
* Serves a built app. `dev` shows error details; `version` names the build to load; `hmr`, the set
|
|
159
|
+
* of pages listening at /_goal/hmr for live updates (goal dev).
|
|
160
|
+
*/
|
|
161
|
+
export async function serve(app, { out = join(app, 'dist'), port = 3000, dev = false, version = () => '', log = console.error, hmr } = {}) {
|
|
149
162
|
const configFile = join(app, 'goal.config.js');
|
|
150
163
|
const config = existsSync(configFile) ? (await import(pathToFileURL(configFile).href)).default : {};
|
|
151
164
|
const routesFile = pathToFileURL(join(out, 'server', '_routes.js')).href;
|
|
152
165
|
const server = createServer(async (req, res) => {
|
|
166
|
+
if (hmr && req.url === '/_goal/hmr') {
|
|
167
|
+
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store' });
|
|
168
|
+
res.write(': goal dev\n\n');
|
|
169
|
+
hmr.add(res);
|
|
170
|
+
req.on('close', () => hmr.delete(res));
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
153
173
|
const routes = (await import(`${routesFile}?v=${version()}`)).default;
|
|
154
174
|
return createApp(routes, { dev, config, log, staticDirs: [join(out, 'client'), join(out, 'public')] })(req, res);
|
|
155
175
|
});
|
|
156
176
|
return new Promise((ok) => server.listen(port, () => ok(server)));
|
|
157
177
|
}
|
|
158
178
|
|
|
159
|
-
/**
|
|
179
|
+
/**
|
|
180
|
+
* Builds, serves with error details, and builds again when a source file changes. Open pages update
|
|
181
|
+
* live (see hmr.js): after a build they're told that a stylesheet changed, that code did, or what the
|
|
182
|
+
* compile error is.
|
|
183
|
+
*/
|
|
160
184
|
export async function dev(app, { port = 3000, log = console.log } = {}) {
|
|
161
185
|
let version = '';
|
|
162
|
-
const
|
|
186
|
+
const pages = new Set();
|
|
187
|
+
const tell = (m) => {
|
|
188
|
+
for (const res of pages) res.write(`data: ${JSON.stringify(m)}\n\n`);
|
|
189
|
+
};
|
|
190
|
+
const rebuild = async (changed = []) => {
|
|
163
191
|
try {
|
|
164
192
|
const r = await build(app, { dev: true });
|
|
165
193
|
version = r.version;
|
|
166
194
|
log(`built: ${r.routes.length} route(s), ${r.chunks.length} chunk(s)`);
|
|
195
|
+
tell({ type: changed.length && changed.every((f) => f.endsWith('.css')) ? 'css' : 'update', version });
|
|
167
196
|
} catch (e) {
|
|
168
197
|
log(e.message);
|
|
198
|
+
tell({ type: 'error', message: e.message });
|
|
169
199
|
}
|
|
170
200
|
};
|
|
171
201
|
await rebuild();
|
|
172
202
|
process.setSourceMapsEnabled(true); // stack traces point at the .goal files
|
|
173
|
-
const server = await serve(app, { port, dev: true, version: () => version, log });
|
|
203
|
+
const server = await serve(app, { port, dev: true, version: () => version, log, hmr: pages });
|
|
174
204
|
let timer;
|
|
205
|
+
let changed = [];
|
|
175
206
|
const watcher = watch(app, { recursive: true }, (_, f) => {
|
|
176
207
|
if (!/\.(goal|m?js|json|css)$/.test(String(f)) || String(f).startsWith('dist')) return;
|
|
208
|
+
changed.push(String(f));
|
|
177
209
|
clearTimeout(timer);
|
|
178
|
-
timer = setTimeout(rebuild, 30);
|
|
210
|
+
timer = setTimeout(() => rebuild(changed.splice(0)), 30);
|
|
179
211
|
});
|
|
180
|
-
|
|
212
|
+
// The pages' streams stay open, so close them for the server to close.
|
|
213
|
+
const close = server.close.bind(server);
|
|
214
|
+
server.close = (done) => {
|
|
215
|
+
watcher.close();
|
|
216
|
+
for (const res of pages) res.end();
|
|
217
|
+
return close(done);
|
|
218
|
+
};
|
|
181
219
|
return server;
|
|
182
220
|
}
|
package/src/compiler.js
CHANGED
|
@@ -36,7 +36,7 @@ import { URL_ATTRS, _$u } from './rt.js';
|
|
|
36
36
|
export { GoalError };
|
|
37
37
|
|
|
38
38
|
const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
|
|
39
|
-
const HELPERS = ['_$m', '_$h', '_$a', '_$e', '_$u', '_$pa', '_$ctx', '_$sf', '_$call', '_$hl', '_$L'];
|
|
39
|
+
const HELPERS = ['_$m', '_$h', '_$a', '_$e', '_$u', '_$pa', '_$ctx', '_$sf', '_$call', '_$hl', '_$L', '_$B', '_$f'];
|
|
40
40
|
const ROUTE_HELPERS = ['redirect', 'json', 'notFound', 'cookie'];
|
|
41
41
|
const FORM_METHODS = ['get', 'post', 'put', 'patch', 'delete'];
|
|
42
42
|
|
|
@@ -76,18 +76,19 @@ function emit(node) {
|
|
|
76
76
|
/**
|
|
77
77
|
* Compiles one .goal file.
|
|
78
78
|
* @param {string} source
|
|
79
|
-
* @param {{ file?: string, base?: string, rt?: string,
|
|
80
|
-
* serverFunctions?: (specifier: string) => { base: string, names: string[] } | null }} [opts]
|
|
79
|
+
* @param {{ file?: string, base?: string, rt?: string, keyed?: string, chunk?: (name: string) => string,
|
|
80
|
+
* serverFunctions?: (specifier: string) => { base: string, names: string[] } | null, dev?: boolean }} [opts]
|
|
81
81
|
* file: the name in errors and source maps; base: the file's path without .goal, which names its
|
|
82
82
|
* server functions' URLs (/_m/<base>/<name>); rt and keyed: where compiled code imports the helpers
|
|
83
83
|
* and the keyed list patcher from;
|
|
84
84
|
* chunk: the URL the browser loads a component's client module from; serverFunctions: the server
|
|
85
|
-
* functions another .goal file exports, for imports of it
|
|
85
|
+
* functions another .goal file exports, for imports of it; dev: for goal dev, where a component
|
|
86
|
+
* rendered for a live update starts from the state the page kept (see hmr.js).
|
|
86
87
|
*/
|
|
87
88
|
export function compile(source, opts = {}) {
|
|
88
89
|
const file = opts.file ?? 'input.goal';
|
|
89
90
|
const base = opts.base ?? file.replace(/\.goal$/, '');
|
|
90
|
-
const o = { file, rt: opts.rt ?? 'goaljs/rt', keyed: opts.keyed ?? 'goaljs/keyed', chunk: opts.chunk ?? ((n) => `/${n}.js`), sfns: new Map() };
|
|
91
|
+
const o = { file, rt: opts.rt ?? 'goaljs/rt', keyed: opts.keyed ?? 'goaljs/keyed', chunk: opts.chunk ?? ((n) => `/${n}.js`), dev: !!opts.dev, sfns: new Map() };
|
|
91
92
|
const d = desugar(source, file);
|
|
92
93
|
SRC = { source, file };
|
|
93
94
|
const ast = parse(d.code, { sourceType: 'module', plugins: ['jsx'] });
|
|
@@ -106,10 +107,12 @@ export function compile(source, opts = {}) {
|
|
|
106
107
|
const server = transform(ast, 'server', o, d.routes);
|
|
107
108
|
const client = transform(ast, 'client', o, d.routes);
|
|
108
109
|
const clients = [];
|
|
110
|
+
const keys = new Map(); // the props each component's browser code reads: the page gets those
|
|
109
111
|
for (const c of client.components.filter((c) => c.interactive)) {
|
|
110
|
-
const
|
|
111
|
-
clients.push({ name: c.name, code });
|
|
112
|
-
|
|
112
|
+
const m = clientModule(client.program, c, o);
|
|
113
|
+
clients.push({ name: c.name, code: m.code });
|
|
114
|
+
keys.set(c.name, m.keys);
|
|
115
|
+
server.components.find((s) => s.name === c.name).keys.elements.push(...m.keys.map((k) => t.stringLiteral(k)));
|
|
113
116
|
}
|
|
114
117
|
|
|
115
118
|
const body = server.program;
|
|
@@ -141,6 +144,7 @@ export function compile(source, opts = {}) {
|
|
|
141
144
|
);
|
|
142
145
|
return {
|
|
143
146
|
server: emit(body.node),
|
|
147
|
+
render: renderModule(ast, o, d.routes, keys),
|
|
144
148
|
clients,
|
|
145
149
|
components: server.components.map(({ name, interactive, events }) => ({ name, interactive, events })),
|
|
146
150
|
routes: d.routes.map(({ method, path }) => ({ method, path })),
|
|
@@ -313,7 +317,7 @@ function component(fn, program, mode, o) {
|
|
|
313
317
|
const events = [...cx.events];
|
|
314
318
|
const param = fn.node.params[0];
|
|
315
319
|
const keys = t.arrayExpression([]); // the props the browser needs, filled in from the client module
|
|
316
|
-
const info = { name, interactive, events, state, binds: cx.binds, hs: cx.hs, param, keys, dyn: cx.dyn, offset: cx.offset, tpls: cx.tpls, cache: cx.cache };
|
|
320
|
+
const info = { name, interactive, events, state, binds: cx.binds, hs: cx.hs, param, keys, dyn: cx.dyn, offset: cx.offset, tpls: cx.tpls, cache: cx.cache, b: !!cx.b };
|
|
317
321
|
program.pushContainer('body', cx.tpls);
|
|
318
322
|
|
|
319
323
|
if (mode === 'server') {
|
|
@@ -323,6 +327,7 @@ function component(fn, program, mode, o) {
|
|
|
323
327
|
const pre = [];
|
|
324
328
|
if (param) pre.push(t.variableDeclaration('let', [t.variableDeclarator(patternOf(param), pId)]));
|
|
325
329
|
pre.push(t.variableDeclaration('const', [t.variableDeclarator(cx.iId, t.updateExpression('++', t.memberExpression(cx.cId, t.identifier('i'))))]));
|
|
330
|
+
if ((o.dev || o.render) && interactive && state.length) pre.push(keptState(fn, cx, o.chunk(name).split('?')[0], state));
|
|
326
331
|
if (events.length) pre.push(t.expressionStatement(t.callExpression(t.memberExpression(cx.cId, t.identifier('e')), [t.valueToNode(events)])));
|
|
327
332
|
if (cx.dyn) {
|
|
328
333
|
// The server only numbers the handlers made while rendering; the browser keeps them.
|
|
@@ -341,6 +346,27 @@ function component(fn, program, mode, o) {
|
|
|
341
346
|
|
|
342
347
|
const patternOf = (param) => (t.isAssignmentPattern(param) ? param.left : param);
|
|
343
348
|
|
|
349
|
+
/**
|
|
350
|
+
* A component rendered again keeps its state: in goal dev, for a live update (the page sends it, see
|
|
351
|
+
* app.js), and in the browser, where a parent renders it again (the loader finds it, see _$B). ctx.k
|
|
352
|
+
* gives the state the component in this place had; its vars start from it instead of their initial
|
|
353
|
+
* values, and a var it didn't have starts as written.
|
|
354
|
+
*/
|
|
355
|
+
function keptState(fn, cx, chunk, state) {
|
|
356
|
+
const kept = t.identifier('_$o');
|
|
357
|
+
for (const name of state) {
|
|
358
|
+
const d = fn.scope.getBinding(name).path.node;
|
|
359
|
+
d.init = t.conditionalExpression(
|
|
360
|
+
t.logicalExpression('&&', kept, t.binaryExpression('in', t.stringLiteral(name), kept)),
|
|
361
|
+
t.memberExpression(kept, t.identifier(name)),
|
|
362
|
+
d.init ?? t.identifier('undefined'),
|
|
363
|
+
);
|
|
364
|
+
}
|
|
365
|
+
// const _$o = _$c.k?.(chunk, _$i);
|
|
366
|
+
const call = t.optionalCallExpression(t.memberExpression(cx.cId, t.identifier('k')), [t.stringLiteral(chunk), cx.iId], true);
|
|
367
|
+
return t.variableDeclaration('const', [t.variableDeclarator(kept, call)]);
|
|
368
|
+
}
|
|
369
|
+
|
|
344
370
|
const ROOT = Symbol('root attributes');
|
|
345
371
|
|
|
346
372
|
function rootAttrs(cx, url, state, param, pId, keys) {
|
|
@@ -449,11 +475,14 @@ function element(p, cx, top, root, row) {
|
|
|
449
475
|
if (!t.isJSXIdentifier(nameNode)) fail('use plain tag names and component names, like <div> or <Counter>', nameNode);
|
|
450
476
|
const tag = nameNode.name;
|
|
451
477
|
if (/^[A-Z]/.test(tag)) {
|
|
452
|
-
if (cx.kind === 'route'
|
|
478
|
+
if (cx.kind === 'route') return componentCall(p, cx, tag, false);
|
|
479
|
+
if (cx.kind === 'component' && !root && !row && !cx.inRow) return componentCall(p, cx, tag, top);
|
|
453
480
|
fail(
|
|
454
|
-
cx.kind
|
|
455
|
-
?
|
|
456
|
-
:
|
|
481
|
+
cx.kind !== 'component'
|
|
482
|
+
? `<${tag}> goes in a route or in a component`
|
|
483
|
+
: root
|
|
484
|
+
? `a component's root is an element: put <${tag}> inside one`
|
|
485
|
+
: `<${tag}> can't go inside a keyed list's row yet`,
|
|
457
486
|
p.node,
|
|
458
487
|
);
|
|
459
488
|
}
|
|
@@ -475,12 +504,12 @@ function element(p, cx, top, root, row) {
|
|
|
475
504
|
row.key = v.node.expression;
|
|
476
505
|
continue;
|
|
477
506
|
}
|
|
478
|
-
//
|
|
507
|
+
// A list in markup that is patched as a whole: inside an element in an {if}, or in another list's
|
|
508
|
+
// row. Its rows carry their key (m-k), and the patch finds each row by it (rt.js). A list that
|
|
509
|
+
// never changes renders once, and needs none.
|
|
479
510
|
const list = mapOf(p);
|
|
480
511
|
if (!list) fail('key goes on the outer element of a list row: items.map((x) => <li key={x.id}>...</li>)', a.node);
|
|
481
|
-
if (cx.inRow
|
|
482
|
-
if (cx.kind === 'component' && changes(list, cx))
|
|
483
|
-
fail('a keyed list that changes goes straight in the markup, or straight in an {if} or a ternary: <ul>{items.map((x) => <li key={x.id}>...</li>)}</ul>', a.node);
|
|
512
|
+
if (cx.inRow || (cx.kind === 'component' && changes(list, cx))) parts.push(t.callExpression(t.identifier('_$a'), [t.stringLiteral('m-k'), v.node.expression]));
|
|
484
513
|
continue;
|
|
485
514
|
}
|
|
486
515
|
if (/^on/i.test(name)) {
|
|
@@ -493,10 +522,10 @@ function element(p, cx, top, root, row) {
|
|
|
493
522
|
ons.push([`${ev}:r${row.hs.length}`]); // the row's own handler, found from the row at run time
|
|
494
523
|
row.hs.push(v.node.expression);
|
|
495
524
|
} else if (top) {
|
|
496
|
-
ons.push([`${ev}:${cx.hs.length}
|
|
525
|
+
ons.push([`${ev}:${cx.hs.length}`, ...owner(cx)]);
|
|
497
526
|
cx.hs.push(v.node.expression);
|
|
498
527
|
} else {
|
|
499
|
-
ons.push([`${ev}:`, t.callExpression(t.identifier('_$hd'), [v.node.expression])]);
|
|
528
|
+
ons.push([`${ev}:`, t.callExpression(t.identifier('_$hd'), [v.node.expression]), ...owner(cx)]);
|
|
500
529
|
cx.dyn++;
|
|
501
530
|
}
|
|
502
531
|
continue;
|
|
@@ -603,15 +632,43 @@ const changes = (e, cx) => uses(e, cx.scope, cx.reactive) || uses(e, cx.scope, c
|
|
|
603
632
|
/** A `{...}` hole: in the fixed part of a component, one that can change becomes a binding between markers. */
|
|
604
633
|
function hole(c, cx, top, parts) {
|
|
605
634
|
const dyn = cx.dyn;
|
|
635
|
+
cx.at = cx.binds?.length; // in a component, the binding it becomes: components rendered in it look for theirs there
|
|
606
636
|
inner(c.get('expression'), cx);
|
|
607
637
|
const ex = t.callExpression(t.identifier('_$h'), [c.node.expression]);
|
|
608
638
|
if (top && (cx.dyn > dyn || changes(c.get('expression'), cx))) {
|
|
639
|
+
if (readsChildren(c.get('expression'), cx))
|
|
640
|
+
fail('put {children} in the fixed part of the component: they belong to its parent, so a {...} hole that renders again can\'t hold them', c.node);
|
|
609
641
|
const k = cx.binds.length;
|
|
610
642
|
cx.binds.push({ k: [0, k], e: ex });
|
|
611
643
|
parts.push('<!--', cx.iId, `.${k}-->`, ex, '<!--/-->');
|
|
612
644
|
} else parts.push(ex);
|
|
613
645
|
}
|
|
614
646
|
|
|
647
|
+
/** In children's markup, a handler names the component it belongs to: m-on="click:0@<instance>". */
|
|
648
|
+
const owner = (cx, always) => {
|
|
649
|
+
if (!cx.own && !always) return [];
|
|
650
|
+
if (cx.mode !== 'client') return ['@', cx.iId];
|
|
651
|
+
cx.b = true; // rendered in the browser: the instance running now (rt.js)
|
|
652
|
+
return ['@', t.callExpression(t.memberExpression(t.memberExpression(t.identifier('_$B'), t.identifier('r')), t.identifier('getAttribute')), [t.stringLiteral('m-i')])];
|
|
653
|
+
};
|
|
654
|
+
|
|
655
|
+
/** Does the code at `path` read the component's children prop? */
|
|
656
|
+
function readsChildren(path, cx) {
|
|
657
|
+
let hit = false;
|
|
658
|
+
const check = (p) => {
|
|
659
|
+
const b = p.scope.getBinding(p.node.name);
|
|
660
|
+
if (b?.kind !== 'param' || b.scope !== cx.scope) return;
|
|
661
|
+
if (p.node.name === 'children' || (p.parentPath.isMemberExpression({ object: p.node, computed: false }) && p.parent.property.name === 'children')) hit = true;
|
|
662
|
+
};
|
|
663
|
+
if (path.isIdentifier()) check(path);
|
|
664
|
+
path.traverse({
|
|
665
|
+
Identifier(p) {
|
|
666
|
+
if (p.isReferencedIdentifier()) check(p);
|
|
667
|
+
},
|
|
668
|
+
});
|
|
669
|
+
return hit;
|
|
670
|
+
}
|
|
671
|
+
|
|
615
672
|
const isMap = (e) => e.isCallExpression() && t.isMemberExpression(e.node.callee, { computed: false }) && e.node.callee.property.name === 'map';
|
|
616
673
|
|
|
617
674
|
/** The `.map(...)` call whose callback returns this element, when the element is a list row. */
|
|
@@ -759,28 +816,71 @@ function markup(p, cx) {
|
|
|
759
816
|
return t.callExpression(t.identifier('_$m'), [template(parts)]);
|
|
760
817
|
}
|
|
761
818
|
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
819
|
+
/**
|
|
820
|
+
* A component in markup. On the server it renders there; in a {...} hole the browser renders it too,
|
|
821
|
+
* with the browser context (_$B, from the file's render module). In the fixed part of a component,
|
|
822
|
+
* one whose props read state becomes a hole of its own, rendered again when they change.
|
|
823
|
+
*/
|
|
824
|
+
function componentCall(p, cx, tag, top) {
|
|
765
825
|
const props = [];
|
|
826
|
+
let live = false; // a prop reads state
|
|
766
827
|
for (const a of p.get('openingElement.attributes')) {
|
|
767
828
|
if (a.isJSXSpreadAttribute()) fail('spread props are not supported yet', a.node);
|
|
768
829
|
if (!t.isJSXIdentifier(a.node.name)) fail('namespaced props are not supported', a.node);
|
|
769
830
|
const name = a.node.name.name;
|
|
770
|
-
if (/^on/i.test(name)) fail(`a component can't take a function prop (${name}) yet`, a.node);
|
|
771
831
|
const v = a.get('value');
|
|
832
|
+
// A function prop: a handler of this component, which the child calls from its own handlers.
|
|
833
|
+
if (/^on/.test(name) || (v.isJSXExpressionContainer() && v.get('expression').isFunction())) {
|
|
834
|
+
if (!cx.hs) fail(`a function prop (${name}) goes to a component inside a component, where it runs as a handler`, a.node);
|
|
835
|
+
if (!v.isJSXExpressionContainer()) fail(`${name} takes a function: ${name}={(x) => ...}`, a.node);
|
|
836
|
+
let h;
|
|
837
|
+
if (top) {
|
|
838
|
+
h = t.numericLiteral(cx.hs.length);
|
|
839
|
+
cx.hs.push(v.node.expression);
|
|
840
|
+
} else {
|
|
841
|
+
h = t.callExpression(t.identifier('_$hd'), [v.node.expression]);
|
|
842
|
+
cx.dyn++;
|
|
843
|
+
}
|
|
844
|
+
props.push(t.objectProperty(t.stringLiteral(name), t.callExpression(t.identifier('_$f'), [h, owner(cx, true)[1]])));
|
|
845
|
+
continue;
|
|
846
|
+
}
|
|
772
847
|
let value;
|
|
773
848
|
if (!v.node) value = t.booleanLiteral(true);
|
|
774
849
|
else if (v.isStringLiteral()) value = v.node;
|
|
775
850
|
else if (v.isJSXExpressionContainer()) {
|
|
776
|
-
if (
|
|
777
|
-
fail(`prop \`${name}\` depends on state; props that change come in the next milestone`, a.node);
|
|
851
|
+
if (top && changes(v.get('expression'), cx)) live = true;
|
|
778
852
|
inner(v.get('expression'), cx);
|
|
779
853
|
value = v.node.expression;
|
|
780
854
|
} else fail('a prop value is "text" or {expression}', a.node);
|
|
781
855
|
props.push(t.objectProperty(t.stringLiteral(name), value));
|
|
782
856
|
}
|
|
783
|
-
|
|
857
|
+
// Children: markup of this component, given to the child as `children`. Their bindings and
|
|
858
|
+
// handlers are this component's (owner), wherever the child puts them.
|
|
859
|
+
if (p.node.children.some((c) => !t.isJSXText(c) || cleanText(c.value) !== '')) {
|
|
860
|
+
if (cx.kind === 'route') {
|
|
861
|
+
const parts = [];
|
|
862
|
+
children(p, cx, false, parts);
|
|
863
|
+
props.push(t.objectProperty(t.stringLiteral('children'), t.callExpression(t.identifier('_$m'), [template(parts)])));
|
|
864
|
+
} else {
|
|
865
|
+
const parts = [];
|
|
866
|
+
const was = cx.own;
|
|
867
|
+
cx.own = true;
|
|
868
|
+
children(p, cx, top && !live, parts);
|
|
869
|
+
cx.own = was;
|
|
870
|
+
props.push(t.objectProperty(t.stringLiteral('children'), t.callExpression(t.identifier('_$m'), [template(parts)])));
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
// In the browser it renders in a hole: this one's own, or the hole it is in.
|
|
874
|
+
let ctx = cx.cId;
|
|
875
|
+
if (cx.mode === 'client' && (live || !top)) {
|
|
876
|
+
cx.b = true;
|
|
877
|
+
ctx = t.callExpression(t.memberExpression(t.identifier('_$B'), t.identifier('h')), [t.numericLiteral(live ? cx.binds.length : cx.at)]);
|
|
878
|
+
}
|
|
879
|
+
const call = t.callExpression(t.identifier(tag), [t.objectExpression(props), ctx]);
|
|
880
|
+
if (!live) return [call];
|
|
881
|
+
const k = cx.binds.length;
|
|
882
|
+
cx.binds.push({ k: [0, k], e: call }); // the render's HTML, as the hole's value
|
|
883
|
+
return ['<!--', cx.iId, `.${k}-->`, call, '<!--/-->'];
|
|
784
884
|
}
|
|
785
885
|
|
|
786
886
|
// Text in markup, with whitespace cleaned the way React does it.
|
|
@@ -829,16 +929,49 @@ function importHelpers(rt) {
|
|
|
829
929
|
return t.importDeclaration(HELPERS.map((h) => t.importSpecifier(t.identifier(h), t.identifier(h))), t.stringLiteral(rt));
|
|
830
930
|
}
|
|
831
931
|
|
|
932
|
+
/** Components imported from a .goal file render in the browser from its render module (see renderModule). */
|
|
933
|
+
function renderImport(s) {
|
|
934
|
+
if (t.isImportDeclaration(s) && s.source.value.endsWith('.goal') && s.specifiers.every((x) => /^[A-Z]/.test(x.local.name))) s.source = t.stringLiteral(`goal-render:${s.source.value}`);
|
|
935
|
+
return s;
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
/**
|
|
939
|
+
* A file's components as the browser renders them, inside a {...} hole or with props that change:
|
|
940
|
+
* the server's templates, each component keeping the state of the one in its place (keptState).
|
|
941
|
+
* Routes and server functions stay on the server, and so does whatever the components don't use.
|
|
942
|
+
*/
|
|
943
|
+
function renderModule(ast, o, routes, keys) {
|
|
944
|
+
const r = transform(ast, 'server', { ...o, render: true }, routes);
|
|
945
|
+
for (const c of r.components) c.keys.elements.push(...(keys.get(c.name) ?? []).map((k) => t.stringLiteral(k)));
|
|
946
|
+
const names = new Set(r.components.map((c) => c.name));
|
|
947
|
+
const server = new Set([...routes.map((x) => x.name), ...o.own]);
|
|
948
|
+
const body = [importHelpers(o.rt)];
|
|
949
|
+
for (const s of r.program.node.body) {
|
|
950
|
+
const d = t.isExportNamedDeclaration(s) || t.isExportDefaultDeclaration(s) ? s.declaration : s;
|
|
951
|
+
if (t.isFunctionDeclaration(d) && server.has(d.id.name)) continue;
|
|
952
|
+
if (t.isFunctionDeclaration(d) && names.has(d.id.name)) body.push(t.exportNamedDeclaration(t.cloneNode(d, true)));
|
|
953
|
+
else if (t.isStatement(d)) body.push(renderImport(t.cloneNode(d, true)));
|
|
954
|
+
}
|
|
955
|
+
const file = t.file(t.program(body));
|
|
956
|
+
prune(programPath(file), names);
|
|
957
|
+
return emit(file);
|
|
958
|
+
}
|
|
959
|
+
|
|
832
960
|
function clientModule(program, info, o) {
|
|
833
961
|
const body = [importHelpers(o.rt)];
|
|
962
|
+
const others = []; // the file's other components: it renders them from the file's render module
|
|
834
963
|
let comp;
|
|
835
964
|
for (const s of program.node.body) {
|
|
836
965
|
const d = t.isExportNamedDeclaration(s) || t.isExportDefaultDeclaration(s) ? s.declaration : s;
|
|
837
966
|
if (t.isFunctionDeclaration(d) && (/^[A-Z]/.test(d.id.name) || o.own.has(d.id.name))) {
|
|
838
967
|
if (d.id.name === info.name) comp = d;
|
|
839
|
-
|
|
968
|
+
else if (!o.own.has(d.id.name)) others.push(d.id.name);
|
|
969
|
+
} else if (t.isStatement(d) && !/^_\$t\d/.test(d.declarations?.[0].id.name)) body.push(renderImport(t.cloneNode(d, true))); // `export { a }` and `export default expr` are dropped
|
|
840
970
|
}
|
|
841
971
|
body.push(...info.tpls.map((x) => t.cloneNode(x, true)), ...clientComponent(comp, info)); // row templates before _$k reads them
|
|
972
|
+
if (others.length) body.splice(1, 0, t.importDeclaration(others.map((n) => t.importSpecifier(t.identifier(n), t.identifier(n))), t.stringLiteral(`goal-render:./${o.file.split('/').at(-1)}`)));
|
|
973
|
+
if (info.b) body.push(t.exportNamedDeclaration(null, [t.exportSpecifier(t.identifier('_$B'), t.identifier('_$B'))], t.stringLiteral(o.rt))); // the loader gives renders the state they keep
|
|
974
|
+
if (info.binds.some((b) => b.k[0] === 0)) body.push(t.exportNamedDeclaration(null, [t.exportSpecifier(t.identifier('_$hm'), t.identifier('_$hm'))], t.stringLiteral(o.rt)));
|
|
842
975
|
if (info.binds.some((b) => b.k[0] === 2))
|
|
843
976
|
body.push(
|
|
844
977
|
t.exportNamedDeclaration(null, [t.exportSpecifier(t.identifier('_$lp'), t.identifier('_$lp'))], t.stringLiteral(o.keyed)),
|
|
@@ -937,6 +1070,8 @@ const pure = (n) =>
|
|
|
937
1070
|
(t.isTemplateLiteral(n) ? n.expressions.every(pure) : t.isLiteral(n)) ||
|
|
938
1071
|
(t.isMemberExpression(n) && pure(n.object) && (!n.computed || pure(n.property))) ||
|
|
939
1072
|
((t.isBinaryExpression(n) || t.isLogicalExpression(n)) && pure(n.left) && pure(n.right)) ||
|
|
1073
|
+
(t.isArrayExpression(n) && n.elements.every(pure)) ||
|
|
1074
|
+
(t.isObjectExpression(n) && n.properties.every((p) => t.isObjectProperty(p) && !p.computed && pure(p.value))) ||
|
|
940
1075
|
(t.isConditionalExpression(n) && pure(n.test) && pure(n.consequent) && pure(n.alternate));
|
|
941
1076
|
|
|
942
1077
|
/** Which props the browser code reads: only those are written into the page. */
|
package/src/hmr.js
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
// goal dev's live updates, in the page. After each build the dev server says what changed (see dev()
|
|
2
|
+
// in build.js). A stylesheet is swapped in place. For code, the page asks the server for itself again,
|
|
3
|
+
// sending the state each component has now, and puts the new body in place of the old one: the
|
|
4
|
+
// components keep their state, and the loader runs the new code on the next event. A compile error
|
|
5
|
+
// shows over the page until a build works again. Only goal dev pages have this.
|
|
6
|
+
|
|
7
|
+
/** Listens for the dev server's updates. `connect` opens the stream; tests pass their own. */
|
|
8
|
+
export function hmr(d, w, connect = (url) => new w.EventSource(url)) {
|
|
9
|
+
let box; // the compile error, over the page
|
|
10
|
+
const show = (text) => {
|
|
11
|
+
box?.remove();
|
|
12
|
+
box = null;
|
|
13
|
+
if (!text) return;
|
|
14
|
+
box = d.createElement('pre');
|
|
15
|
+
box.id = 'goal-dev-error';
|
|
16
|
+
box.textContent = text;
|
|
17
|
+
Object.assign(box.style, {
|
|
18
|
+
position: 'fixed',
|
|
19
|
+
inset: '0',
|
|
20
|
+
zIndex: '2147483647',
|
|
21
|
+
margin: '0',
|
|
22
|
+
padding: '24px',
|
|
23
|
+
overflow: 'auto',
|
|
24
|
+
whiteSpace: 'pre-wrap',
|
|
25
|
+
background: '#1b1b1f',
|
|
26
|
+
color: '#ffb4ab',
|
|
27
|
+
font: '14px/1.5 ui-monospace, Menlo, monospace',
|
|
28
|
+
});
|
|
29
|
+
d.body.append(box);
|
|
30
|
+
};
|
|
31
|
+
const events = (doc) => JSON.parse(doc.querySelector('meta[name="goal-events"]')?.content || '[]');
|
|
32
|
+
|
|
33
|
+
async function update() {
|
|
34
|
+
const kept = {}; // by instance number: which component, and its state now
|
|
35
|
+
for (const el of d.querySelectorAll('[m-c]'))
|
|
36
|
+
kept[el.getAttribute('m-i')] = { c: el.getAttribute('m-c').split('?')[0], s: el.$s ?? JSON.parse(el.getAttribute('m-s') || '{}') };
|
|
37
|
+
const header = JSON.stringify(kept);
|
|
38
|
+
if (header.length > 8000) return w.location.reload(); // more than a request header should carry
|
|
39
|
+
const res = await w.fetch(w.location.href, { headers: { 'x-goal-hmr': header } });
|
|
40
|
+
const text = await res.text();
|
|
41
|
+
if (!res.ok) return show(text); // the route failed: goal dev answers with the stack
|
|
42
|
+
const next = new w.DOMParser().parseFromString(text, 'text/html');
|
|
43
|
+
const now = events(d);
|
|
44
|
+
if (events(next).some((e) => !now.includes(e))) return w.location.reload(); // the loader listens only for the events it started with
|
|
45
|
+
for (const s of next.querySelectorAll('script')) s.remove(); // this page's loader and updates keep running
|
|
46
|
+
const { scrollX: x, scrollY: y } = w;
|
|
47
|
+
const focused = d.activeElement?.id;
|
|
48
|
+
d.title = next.title;
|
|
49
|
+
d.body.replaceWith(d.adoptNode(next.body));
|
|
50
|
+
w.scrollTo(x, y);
|
|
51
|
+
if (focused) d.getElementById(focused)?.focus();
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
connect('/_goal/hmr').onmessage = (e) => {
|
|
55
|
+
const m = JSON.parse(e.data);
|
|
56
|
+
if (m.type === 'error') return show(m.message);
|
|
57
|
+
show(null);
|
|
58
|
+
if (m.type === 'update') return update();
|
|
59
|
+
for (const link of d.querySelectorAll('link[rel="stylesheet"]')) {
|
|
60
|
+
const u = new URL(link.href);
|
|
61
|
+
u.searchParams.set('v', m.version);
|
|
62
|
+
link.href = u.href;
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
}
|
package/src/keyed.js
CHANGED
|
@@ -4,6 +4,8 @@
|
|
|
4
4
|
// one batch, rows that are gone are removed, and of the kept rows only those out of order are moved
|
|
5
5
|
// (the rest are the longest run already in order).
|
|
6
6
|
|
|
7
|
+
import { into } from './rt.js';
|
|
8
|
+
|
|
7
9
|
const set = (el, name, v, off = v == null || v === false) =>
|
|
8
10
|
name === 'value' ? (el.value = off ? '' : v)
|
|
9
11
|
: name === 'checked' ? (el.checked = !off)
|
|
@@ -16,7 +18,7 @@ const put = (row, [kind, path, name], v) => {
|
|
|
16
18
|
for (const p of path) el = el.children[p];
|
|
17
19
|
const x = el.firstChild;
|
|
18
20
|
if (kind) set(el, name, v);
|
|
19
|
-
else if (/[<&]/.test(v)) el.
|
|
21
|
+
else if (/[<&]/.test(v)) into(el.ownerDocument, el, el.firstChild, null, v); // markup: into the nodes there, keyed rows by key
|
|
20
22
|
else if (x?.nodeType === 3 && !x.nextSibling) x.data = v;
|
|
21
23
|
else el.textContent = v;
|
|
22
24
|
};
|
|
@@ -53,8 +55,18 @@ export function _$lp(d, c, a, b, tpl, parts) {
|
|
|
53
55
|
for (; end.data !== '/'; end = end.nextSibling) old.push(end); // rows are all elements, up to the end marker
|
|
54
56
|
const parent = end.parentNode;
|
|
55
57
|
// Writes a kept row's changed values in place; says no when the row has to be made again.
|
|
58
|
+
// Writes a kept row's changed values in place. A row whose values have no fixed place gets its new
|
|
59
|
+
// markup put into its nodes (rt.js), so what stays the same, an input's focus too, is kept.
|
|
56
60
|
const keep = (r, o, n) => {
|
|
57
|
-
if (r !== o)
|
|
61
|
+
if (r !== o)
|
|
62
|
+
for (let k = 3; k < r.length; k++)
|
|
63
|
+
if (r[k] !== o[k]) {
|
|
64
|
+
if (!parts) {
|
|
65
|
+
into(d, n.parentNode, n, n.nextSibling, tpl(r));
|
|
66
|
+
return 1;
|
|
67
|
+
}
|
|
68
|
+
put(n, parts[k - 3], r[k]);
|
|
69
|
+
}
|
|
58
70
|
return 1;
|
|
59
71
|
};
|
|
60
72
|
// Rows that stay where they were, at the start and at the end, are patched where they are.
|
package/src/loader.js
CHANGED
|
@@ -22,7 +22,9 @@ export function boot(d, events, load = (u) => import(u)) {
|
|
|
22
22
|
};
|
|
23
23
|
for (const t of ['pointerover', 'focusin']) d.addEventListener(t, warm, true);
|
|
24
24
|
// A run of the component from its state: [values, handlers, read the state, the state read].
|
|
25
|
+
// When it renders components in the browser (m._$B, rt.js), they look for theirs inside it.
|
|
25
26
|
const run = (m, r) => {
|
|
27
|
+
if (m._$B) m._$B.r = r;
|
|
26
28
|
const x = m.default(r.$s, r.$p);
|
|
27
29
|
x[3] = x[2]();
|
|
28
30
|
return x;
|
|
@@ -32,41 +34,67 @@ export function boot(d, events, load = (u) => import(u)) {
|
|
|
32
34
|
const todo = [];
|
|
33
35
|
for (let el = e.target; el.getAttribute; el = el.parentNode)
|
|
34
36
|
for (const pair of (el.getAttribute('m-on') || '').split(' ')) {
|
|
35
|
-
const [type,
|
|
37
|
+
const [type, at] = pair.split(':');
|
|
36
38
|
if (type !== e.type) continue;
|
|
37
39
|
if (type === 'submit') e.preventDefault(); // must happen now, before the module loads
|
|
38
|
-
|
|
40
|
+
const [h, owner] = at.split('@'); // a handler in children's markup names the component it belongs to
|
|
41
|
+
todo.push([owner ? el.closest(`[m-i="${owner}"]`) : el.closest('[m-c]'), h, el]);
|
|
42
|
+
}
|
|
43
|
+
for (const r of new Set(todo.map((x) => x[0])))
|
|
44
|
+
await act(
|
|
45
|
+
r,
|
|
46
|
+
todo.filter((t) => t[0] === r).map(([, h, el]) => (m, x) => (h[0] === 'r' ? m._$lh(el, r, x, h, e) : x[1][h](e))), // r: a keyed list row's handler (keyed.js)
|
|
47
|
+
);
|
|
48
|
+
};
|
|
49
|
+
// Runs handlers of the component at root r (each call gets its module and run), saves the state
|
|
50
|
+
// they changed and patches it, and again when the calls to server functions they made answer.
|
|
51
|
+
const act = async (r, calls) => {
|
|
52
|
+
const m = await get(r);
|
|
53
|
+
r.$s ||= json(r, 'm-s');
|
|
54
|
+
r.$p ||= props(r);
|
|
55
|
+
const x = (r.$x ||= run(m, r));
|
|
56
|
+
const save = () => {
|
|
57
|
+
const now = x[2]();
|
|
58
|
+
if (!r.$x) {
|
|
59
|
+
// Its parent rendered it again while it waited (rt.js): start from what the page shows now.
|
|
60
|
+
r.$s = json(r, 'm-s');
|
|
61
|
+
r.$p = props(r);
|
|
62
|
+
r.$x = run(m, r);
|
|
63
|
+
}
|
|
64
|
+
for (const k in now) if (now[k] !== x[3][k]) r.$s[k] = now[k]; // only what these handlers changed
|
|
65
|
+
x[3] = now;
|
|
66
|
+
};
|
|
67
|
+
const update = () => {
|
|
68
|
+
const y = run(m, r);
|
|
69
|
+
patch(d, r, m, r.$x[0], y[0]);
|
|
70
|
+
r.$x = y;
|
|
71
|
+
};
|
|
72
|
+
const outs = calls.map((f) => f(m, x));
|
|
73
|
+
save();
|
|
74
|
+
update();
|
|
75
|
+
if (outs.some((o) => o?.then))
|
|
76
|
+
try {
|
|
77
|
+
await Promise.all(outs); // calls to server functions
|
|
78
|
+
} finally {
|
|
79
|
+
save();
|
|
80
|
+
update();
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
// A component's props. A function prop is written {$h, $i}: calling it runs handler $h of the
|
|
84
|
+
// component that gave it, instance $i (see _$f in rt.js).
|
|
85
|
+
const props = (r) =>
|
|
86
|
+
JSON.parse(r.getAttribute('m-p') || '{}', (k, v) => (v?.$h === undefined ? v : (...a) => act(d.querySelector(`[m-i="${v.$i}"]`), [(m, x) => x[1][v.$h](...a)])));
|
|
87
|
+
// The page's events, and those of components rendered in the browser later (rt.js).
|
|
88
|
+
const on = new Set();
|
|
89
|
+
const listen = (list) => {
|
|
90
|
+
for (const ev of list)
|
|
91
|
+
if (!on.has(ev)) {
|
|
92
|
+
on.add(ev);
|
|
93
|
+
d.addEventListener(ev, go, true);
|
|
39
94
|
}
|
|
40
|
-
for (const r of new Set(todo.map((x) => x[0]))) {
|
|
41
|
-
const m = await get(r);
|
|
42
|
-
r.$s ||= json(r, 'm-s');
|
|
43
|
-
r.$p ||= json(r, 'm-p');
|
|
44
|
-
const x = (r.$x ||= run(m, r));
|
|
45
|
-
const save = () => {
|
|
46
|
-
const now = x[2]();
|
|
47
|
-
for (const k in now) if (now[k] !== x[3][k]) r.$s[k] = now[k]; // only what these handlers changed
|
|
48
|
-
x[3] = now;
|
|
49
|
-
};
|
|
50
|
-
const update = () => {
|
|
51
|
-
const y = run(m, r);
|
|
52
|
-
patch(d, r, m, r.$x[0], y[0]);
|
|
53
|
-
r.$x = y;
|
|
54
|
-
};
|
|
55
|
-
const outs = todo
|
|
56
|
-
.filter((t) => t[0] === r)
|
|
57
|
-
.map(([, h, el]) => (h[0] === 'r' ? m._$lh(el, r, x, h, e) : x[1][h](e))); // r: a keyed list row's handler (keyed.js)
|
|
58
|
-
save();
|
|
59
|
-
update();
|
|
60
|
-
if (outs.some((o) => o?.then))
|
|
61
|
-
try {
|
|
62
|
-
await Promise.all(outs); // calls to server functions
|
|
63
|
-
} finally {
|
|
64
|
-
save();
|
|
65
|
-
update();
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
95
|
};
|
|
69
|
-
|
|
96
|
+
listen(events);
|
|
97
|
+
d.addEventListener('goal:listen', (e) => listen(e.detail));
|
|
70
98
|
}
|
|
71
99
|
|
|
72
100
|
/** Updates the bindings whose value changed between `a` and `b`. */
|
|
@@ -92,10 +120,7 @@ function patch(d, r, m, a, b) {
|
|
|
92
120
|
while ((c = w.nextNode()) && c.data !== `${i}.${n}`);
|
|
93
121
|
r.$m[n] = c;
|
|
94
122
|
}
|
|
95
|
-
if (kind)
|
|
96
|
-
|
|
97
|
-
const tpl = d.createElement('template');
|
|
98
|
-
tpl.innerHTML = v;
|
|
99
|
-
c.after(tpl.content);
|
|
123
|
+
if (kind) m._$lp(d, c, a[j], v, name, parts); // a keyed list (keyed.js)
|
|
124
|
+
else m._$hm(d, c, v); // a hole's markup, into the nodes there (rt.js)
|
|
100
125
|
});
|
|
101
126
|
}
|
package/src/rt.js
CHANGED
|
@@ -10,15 +10,21 @@ export const _$e = (v) => {
|
|
|
10
10
|
};
|
|
11
11
|
|
|
12
12
|
/** Compiled markup: HTML that is already safe, so `_$h` doesn't escape it again. */
|
|
13
|
+
const MARKUP = Symbol.for('goal.markup'); // the same in every copy of this module (Vite loads its own)
|
|
14
|
+
|
|
13
15
|
export class Html {
|
|
14
16
|
constructor(s) {
|
|
15
17
|
this.s = s;
|
|
18
|
+
this[MARKUP] = true;
|
|
16
19
|
}
|
|
17
20
|
toString() {
|
|
18
21
|
return this.s;
|
|
19
22
|
}
|
|
20
23
|
}
|
|
21
24
|
|
|
25
|
+
/** Is it markup a compiled template made, whichever copy of this module made it? */
|
|
26
|
+
export const isHtml = (v) => v?.[MARKUP] === true;
|
|
27
|
+
|
|
22
28
|
/** Marks a compiled template as markup. Only compiled code makes these. */
|
|
23
29
|
export const _$m = (s) => new Html(s);
|
|
24
30
|
|
|
@@ -79,6 +85,55 @@ export const _$ctx = (t = '') => ({
|
|
|
79
85
|
},
|
|
80
86
|
});
|
|
81
87
|
|
|
88
|
+
/**
|
|
89
|
+
* The context of components rendered in the browser: inside a {...} hole, or with props that change.
|
|
90
|
+
* Their instance numbers start where no server render reaches, their forms get the page's CSRF
|
|
91
|
+
* token, and the loader starts listening for their events.
|
|
92
|
+
*/
|
|
93
|
+
export const _$B = {
|
|
94
|
+
i: 1e6,
|
|
95
|
+
r: null, // the component running now: the loader sets it before each run
|
|
96
|
+
/**
|
|
97
|
+
* The context for the components rendered in hole `n` of the component running now. Each one
|
|
98
|
+
* keeps the state of the component in its place, if it is the same (see keptState in compiler.js):
|
|
99
|
+
* the components in that hole now, in order. One where there was none starts as written.
|
|
100
|
+
*/
|
|
101
|
+
h(n) {
|
|
102
|
+
const r = this.r;
|
|
103
|
+
const d = r.ownerDocument;
|
|
104
|
+
const w = d.createTreeWalker(r, 128);
|
|
105
|
+
let c;
|
|
106
|
+
while ((c = w.nextNode()) && c.data !== `${r.getAttribute('m-i')}.${n}`);
|
|
107
|
+
const q = [];
|
|
108
|
+
for (let x = c.nextSibling; x.nodeType !== 8 || x.data !== '/'; x = x.nextSibling)
|
|
109
|
+
if (x.nodeType === 1) q.push(...(x.hasAttribute('m-c') ? [x] : []), ...x.querySelectorAll('[m-c]'));
|
|
110
|
+
const b = this;
|
|
111
|
+
return {
|
|
112
|
+
get i() {
|
|
113
|
+
return b.i;
|
|
114
|
+
},
|
|
115
|
+
set i(v) {
|
|
116
|
+
b.i = v;
|
|
117
|
+
},
|
|
118
|
+
t: d.querySelector('meta[name="goal-csrf"]').content, // a page with components that run has it
|
|
119
|
+
e: (list) => d.dispatchEvent(new CustomEvent('goal:listen', { detail: list })),
|
|
120
|
+
k: (chunk) => {
|
|
121
|
+
const j = q.findIndex((x) => x.getAttribute('m-c').split('?')[0] === chunk);
|
|
122
|
+
if (j < 0) return null;
|
|
123
|
+
const x = q.splice(0, j + 1).pop();
|
|
124
|
+
return x.$s ?? JSON.parse(x.getAttribute('m-s')); // only a component with state asks
|
|
125
|
+
},
|
|
126
|
+
};
|
|
127
|
+
},
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* A function prop: handler `h` of the component instance `i` that gives it. It runs nothing where it
|
|
132
|
+
* is made; the page gets {$h, $i}, and the loader turns that into a function that runs the handler
|
|
133
|
+
* in that component, as an event would.
|
|
134
|
+
*/
|
|
135
|
+
export const _$f = (h, i) => Object.assign(() => {}, { toJSON: () => ({ $h: h, $i: i }) });
|
|
136
|
+
|
|
82
137
|
/** The server's rendering of a keyed list (see keyed.js): each row through its template. */
|
|
83
138
|
export const _$hl = (rows, tpl) => rows.map(tpl).join('');
|
|
84
139
|
|
|
@@ -94,3 +149,66 @@ export function _$lh(el, root, x, h, e) {
|
|
|
94
149
|
|
|
95
150
|
/** A keyed list in the browser: its rows, and `h(item, index)`, the handlers of one row. */
|
|
96
151
|
export const _$L = (rows, h) => ((rows.h = h), rows);
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* A `{...}` hole's new markup, put into the nodes after its start marker `c` (see into).
|
|
155
|
+
*/
|
|
156
|
+
export function _$hm(d, c, html) {
|
|
157
|
+
let end = c.nextSibling;
|
|
158
|
+
while (end.nodeType !== 8 || end.data !== '/') end = end.nextSibling;
|
|
159
|
+
into(d, c.parentNode, c.nextSibling, end, html);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* New markup, put into the nodes of `parent` from `at` up to `end` (null: its last). A node of the
|
|
164
|
+
* same kind as the new one in its place is kept and updated, so a focused input stays focused and
|
|
165
|
+
* keeps what was typed; a row with a key (`m-k`) is found by its key, and moved there. The others
|
|
166
|
+
* are added or removed.
|
|
167
|
+
*/
|
|
168
|
+
export function into(d, parent, at, end, html) {
|
|
169
|
+
const t = d.createElement('template');
|
|
170
|
+
t.innerHTML = html;
|
|
171
|
+
kids(parent, at, end, t.content);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const key = (n) => (n.nodeType === 1 ? n.getAttribute('m-k') : null);
|
|
175
|
+
|
|
176
|
+
function kids(parent, at, end, to) {
|
|
177
|
+
for (let n = to.firstChild, next; n; n = next) {
|
|
178
|
+
next = n.nextSibling;
|
|
179
|
+
const k = key(n);
|
|
180
|
+
let old = at;
|
|
181
|
+
if (k !== null) while (old !== end && key(old) !== k) old = old.nextSibling;
|
|
182
|
+
if (old !== end && old.nodeName === n.nodeName && key(old) === k) {
|
|
183
|
+
if (old === at) at = at.nextSibling;
|
|
184
|
+
else parent.insertBefore(old, at);
|
|
185
|
+
same(old, n);
|
|
186
|
+
} else parent.insertBefore(n, at);
|
|
187
|
+
}
|
|
188
|
+
while (at !== end) {
|
|
189
|
+
const x = at.nextSibling;
|
|
190
|
+
at.remove();
|
|
191
|
+
at = x;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function same(a, b) {
|
|
196
|
+
if (a.nodeType !== 1) {
|
|
197
|
+
if (a.data !== b.data) a.data = b.data;
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
for (const { name } of [...a.attributes]) if (!b.hasAttribute(name)) attr(a, name, null);
|
|
201
|
+
for (const { name, value } of b.attributes) if (a.getAttribute(name) !== value) attr(a, name, value);
|
|
202
|
+
kids(a, a.firstChild, null, b);
|
|
203
|
+
// A component rendered again in the browser, with its state now (see _$B.k): its attributes say
|
|
204
|
+
// all, so the loader reads it afresh on its next event.
|
|
205
|
+
if (a.hasAttribute('m-c')) a.$s = a.$p = a.$x = a.$m = undefined;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** An attribute that changed. As when the page is rendered, a form control's value and checked follow it. */
|
|
209
|
+
function attr(a, name, v) {
|
|
210
|
+
if (v === null) a.removeAttribute(name);
|
|
211
|
+
else a.setAttribute(name, v);
|
|
212
|
+
if (name === 'value') a.value = v ?? '';
|
|
213
|
+
if (name === 'checked') a.checked = v !== null;
|
|
214
|
+
}
|
package/src/server.js
CHANGED
|
@@ -12,24 +12,34 @@ export function render(Component, props = {}, ctx = _$ctx()) {
|
|
|
12
12
|
return { html, events: [...ctx.ev] };
|
|
13
13
|
}
|
|
14
14
|
|
|
15
|
+
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
15
16
|
const EVENTS = '"__GOAL_EVENTS__"';
|
|
16
17
|
let loaderCode;
|
|
17
18
|
/** The loader, minified, starting itself; the page puts its events where EVENTS is. */
|
|
18
19
|
export function loaderScript() {
|
|
19
|
-
const src = readFileSync(join(
|
|
20
|
+
const src = readFileSync(join(HERE, 'loader.js'), 'utf8');
|
|
20
21
|
loaderCode ??= transformSync(`${src.replace('export function boot', 'function boot')}\nboot(document, ${EVENTS});`, { format: 'iife', minify: true }).code.trim();
|
|
21
22
|
return loaderCode;
|
|
22
23
|
}
|
|
23
24
|
|
|
25
|
+
let hmrCode;
|
|
26
|
+
/** goal dev's live updates in the page (hmr.js), minified, starting itself. */
|
|
27
|
+
export function hmrScript() {
|
|
28
|
+
hmrCode ??= transformSync(`${readFileSync(join(HERE, 'hmr.js'), 'utf8').replace('export function hmr', 'function hmr')}\nhmr(document, window);`, { format: 'iife', minify: true }).code.trim();
|
|
29
|
+
return hmrCode;
|
|
30
|
+
}
|
|
31
|
+
|
|
24
32
|
/**
|
|
25
33
|
* A whole HTML document. Markup that starts with <html> is the document itself; anything else goes
|
|
26
34
|
* in a plain one. The loader goes in only when there are events, with the request's CSP nonce, and
|
|
27
|
-
* the CSRF token that server function calls send.
|
|
35
|
+
* the CSRF token that server function calls send. In goal dev (`dev`), every page also gets the
|
|
36
|
+
* live updates, and the events it listens for, which an update compares.
|
|
28
37
|
*/
|
|
29
|
-
export function page(html, events, nonce, token = '') {
|
|
30
|
-
|
|
38
|
+
export function page(html, events, nonce, token = '', dev = false) {
|
|
39
|
+
let script = events.length
|
|
31
40
|
? `<meta name="goal-csrf" content="${_$e(token)}"><script type="module" nonce="${nonce}">${loaderScript().replace(EVENTS, JSON.stringify(events))}</script>`
|
|
32
41
|
: '';
|
|
42
|
+
if (dev) script += `<meta name="goal-events" content="${_$e(JSON.stringify(events))}"><script type="module" nonce="${nonce}">${hmrScript()}</script>`;
|
|
33
43
|
if (/^<html[\s>]/.test(html)) {
|
|
34
44
|
const i = html.lastIndexOf('</body>');
|
|
35
45
|
return '<!doctype html>' + (i < 0 ? html + script : html.slice(0, i) + script + html.slice(i));
|
package/src/vite.js
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// goal.js in Vite's dev server:
|
|
2
|
+
//
|
|
3
|
+
// // vite.config.js
|
|
4
|
+
// import { goal } from 'goaljs/vite';
|
|
5
|
+
// export default { plugins: [goal()] };
|
|
6
|
+
//
|
|
7
|
+
// Vite serves the app: its modules and the public folder. Any other request goes to the app's routes
|
|
8
|
+
// and server functions, read from the .goal files with Vite's SSR loader and answered the way goal dev
|
|
9
|
+
// answers them: error details, the security defaults, live updates. Each component's browser code is a
|
|
10
|
+
// module of its own (`/ui/Panel.goal?goal-client=Panel`), and so is each file's render module
|
|
11
|
+
// (`?goal-render`), which the browser renders components from. When a file changes, the open pages are
|
|
12
|
+
// told as goal dev tells them (see hmr.js): a stylesheet is swapped in place, and code renders the page
|
|
13
|
+
// again with each component's state.
|
|
14
|
+
|
|
15
|
+
import { readFileSync, readdirSync } from 'node:fs';
|
|
16
|
+
import { dirname, join, relative, resolve, sep } from 'node:path';
|
|
17
|
+
import { fileURLToPath } from 'node:url';
|
|
18
|
+
import { compile } from './compiler.js';
|
|
19
|
+
import { desugar } from './syntax.js';
|
|
20
|
+
import { createApp } from './app.js';
|
|
21
|
+
|
|
22
|
+
const SRC = dirname(fileURLToPath(import.meta.url)); // compiled code imports the helpers from here
|
|
23
|
+
const SKIP = new Set(['node_modules', 'dist', 'public']);
|
|
24
|
+
const slash = (p) => p.split(sep).join('/');
|
|
25
|
+
|
|
26
|
+
/** The .goal files under `dir`, as paths from `root`. */
|
|
27
|
+
function goals(dir, root) {
|
|
28
|
+
return readdirSync(dir, { withFileTypes: true }).flatMap((d) => {
|
|
29
|
+
if (d.isDirectory()) return SKIP.has(d.name) ? [] : goals(join(dir, d.name), root);
|
|
30
|
+
return d.name.endsWith('.goal') ? [slash(relative(root, join(dir, d.name)))] : [];
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* @param {{ config?: { csp?: string | false, csrf?: boolean, bodyLimit?: number } }} [options]
|
|
36
|
+
* config: what goal.config.js would hold (see app.js)
|
|
37
|
+
*/
|
|
38
|
+
export function goal({ config = {} } = {}) {
|
|
39
|
+
let root;
|
|
40
|
+
let version = 1; // in the URL of each component's module: a page updated live loads the new code
|
|
41
|
+
const pages = new Set(); // the pages listening for live updates
|
|
42
|
+
const tell = (m) => {
|
|
43
|
+
for (const res of pages) res.write(`data: ${JSON.stringify(m)}\n\n`);
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
return {
|
|
47
|
+
name: 'goal',
|
|
48
|
+
config: () => ({ appType: 'custom' }), // the app's routes answer pages, not an index.html
|
|
49
|
+
configResolved(c) {
|
|
50
|
+
root = c.root;
|
|
51
|
+
},
|
|
52
|
+
resolveId(id, importer) {
|
|
53
|
+
if (id.startsWith('goal-render:')) return `${resolve(dirname(importer), id.slice(12))}?goal-render&v=${version}`;
|
|
54
|
+
},
|
|
55
|
+
transform(source, id, opts) {
|
|
56
|
+
const [file, query] = id.split('?');
|
|
57
|
+
if (!file.endsWith('.goal')) return;
|
|
58
|
+
const rel = slash(relative(root, file));
|
|
59
|
+
const r = compile(source, {
|
|
60
|
+
file: rel,
|
|
61
|
+
base: rel.slice(0, -5),
|
|
62
|
+
rt: join(SRC, 'rt.js'),
|
|
63
|
+
keyed: join(SRC, 'keyed.js'),
|
|
64
|
+
dev: true,
|
|
65
|
+
chunk: (n) => `/${rel}?goal-client=${n}&v=${version}`,
|
|
66
|
+
serverFunctions: (spec) => {
|
|
67
|
+
const target = resolve(dirname(file), spec);
|
|
68
|
+
const names = desugar(readFileSync(target, 'utf8'), spec).serverFns.filter((f) => f.exported).map((f) => f.name);
|
|
69
|
+
return { base: slash(relative(root, target)).slice(0, -5), names };
|
|
70
|
+
},
|
|
71
|
+
});
|
|
72
|
+
const q = new URLSearchParams(query);
|
|
73
|
+
if (q.has('goal-client')) return r.clients.find((c) => c.name === q.get('goal-client')).code;
|
|
74
|
+
if (q.has('goal-render')) return r.render;
|
|
75
|
+
if (opts?.ssr) return r.server;
|
|
76
|
+
throw new Error(`browser code can't import the .goal file ${rel}; move shared helpers into a .js file`);
|
|
77
|
+
},
|
|
78
|
+
configureServer(server) {
|
|
79
|
+
// After Vite's own middleware: what it doesn't serve, the app answers.
|
|
80
|
+
return () =>
|
|
81
|
+
server.middlewares.use(async (req, res) => {
|
|
82
|
+
if (req.url === '/_goal/hmr') {
|
|
83
|
+
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store' });
|
|
84
|
+
res.write(': goal dev\n\n');
|
|
85
|
+
pages.add(res);
|
|
86
|
+
req.on('close', () => pages.delete(res));
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
let routes;
|
|
90
|
+
try {
|
|
91
|
+
routes = (await Promise.all(goals(root, root).map((f) => server.ssrLoadModule(`/${f}`)))).flatMap((m) => m._$routes ?? []);
|
|
92
|
+
} catch (e) {
|
|
93
|
+
res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });
|
|
94
|
+
return res.end(e.message); // a compile error: the page shows it over itself (hmr.js)
|
|
95
|
+
}
|
|
96
|
+
createApp(routes, { dev: true, config, log: (e) => server.config.logger.error(e.stack) })(req, res);
|
|
97
|
+
});
|
|
98
|
+
},
|
|
99
|
+
handleHotUpdate({ file, server }) {
|
|
100
|
+
if (!/\.(goal|m?js|json|css)$/.test(file) || file.includes('/node_modules/')) return;
|
|
101
|
+
version++;
|
|
102
|
+
server.moduleGraph.invalidateAll(); // the server code reads the new files
|
|
103
|
+
tell({ type: file.endsWith('.css') ? 'css' : 'update', version });
|
|
104
|
+
return []; // the pages update themselves
|
|
105
|
+
},
|
|
106
|
+
};
|
|
107
|
+
}
|