goaljs 0.5.0 → 0.7.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/src/add.js ADDED
@@ -0,0 +1,179 @@
1
+ // goal add <tool>: sets a tool up in the app. A recipe (recipes/<tool>.js) says, for each range of
2
+ // the tool's versions, which packages to install and what the app needs around them: files, lines in
3
+ // files like .gitignore, package.json scripts, goal.config.js keys, commands to run once, and what to
4
+ // do next. Recipes are data, kept up to date by pull request (see recipes/README.md).
5
+ //
6
+ // Nothing of the app's is overwritten: a file that's there already is kept and the recipe's version
7
+ // shown, a package the app has already isn't installed again, and its version picks the recipe.
8
+
9
+ import { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync } from 'node:fs';
10
+ import { join, dirname } from 'node:path';
11
+ import { execSync } from 'node:child_process';
12
+ import { fileURLToPath, pathToFileURL } from 'node:url';
13
+ import { parse } from '@babel/parser';
14
+
15
+ const RECIPES = join(dirname(fileURLToPath(import.meta.url)), '..', 'recipes');
16
+ const HELP = 'https://github.com/goallabs/goal/tree/main/recipes';
17
+
18
+ /** Every recipe, by file name. */
19
+ export async function recipes(dir = RECIPES) {
20
+ const all = [];
21
+ for (const f of readdirSync(dir).filter((f) => f.endsWith('.js')).sort()) all.push((await import(pathToFileURL(join(dir, f)).href)).default);
22
+ return all;
23
+ }
24
+
25
+ /** 4.3.5-rc.1 → [4, 3, 5]; 4 → [4, 0, 0] */
26
+ const parts = (v) => {
27
+ const p = v.split('-')[0].split('.').map(Number);
28
+ return [p[0], p[1] ?? 0, p[2] ?? 0];
29
+ };
30
+
31
+ /**
32
+ * Is the version in the range? Ranges are npm's, in part: `4` or `4.x` (any 4), `>=0.30 <0.32`
33
+ * (all of them), `3 || 4` (either). A version may be partial: `3` is 3.0.0 to a comparison.
34
+ */
35
+ export function satisfies(version, range) {
36
+ const v = parts(version);
37
+ const cmp = (w) => v[0] - w[0] || v[1] - w[1] || v[2] - w[2];
38
+ return range.split('||').some((alt) =>
39
+ alt
40
+ .trim()
41
+ .split(/\s+/)
42
+ .every((c) => {
43
+ const [, op, n] = /^(>=|<=|>|<|=)?(.*)$/.exec(c);
44
+ if (!op) return n.split('.').filter((x) => x !== 'x' && x !== '*').every((x, i) => v[i] === Number(x)); // 3 is 3.0.0 here too
45
+ const d = cmp(parts(n));
46
+ return { '>=': d >= 0, '<=': d <= 0, '>': d > 0, '<': d < 0, '=': d === 0 }[op];
47
+ }),
48
+ );
49
+ }
50
+
51
+ /** The recipe's entry for a version of its package; its newest without one. */
52
+ export function pick(recipe, version) {
53
+ if (!version) return recipe.versions[0];
54
+ const v = recipe.versions.find((e) => satisfies(version, e.range));
55
+ if (!v) throw new Error(`goal add has no recipe for ${recipe.package} ${version}, only for ${recipe.versions.map((e) => e.range).join(', ')}. To add one, see ${HELP}`);
56
+ return v;
57
+ }
58
+
59
+ /** Is this line, or one that means the same, in the list? `dist` and `/dist/`, `KEY=a` and `KEY=b` do. */
60
+ const has = (lines, line) => {
61
+ const key = (l) => /^[A-Za-z_]\w*=/.exec(l.trim())?.[0] ?? l.trim().replace(/^\/|\/$/g, '');
62
+ return lines.some((l) => key(l) === key(line));
63
+ };
64
+
65
+ /** The app's version of a package, from a range like ^4.1.0; nothing for a tag, a URL or a path. */
66
+ const coerce = (range) => /^[\^~=v]*(\d+(\.\d+){0,2})/.exec(range ?? '')?.[1];
67
+
68
+ /** goal.config.js gets the recipe's keys, and the import they need, unless it has them already. */
69
+ function configure(app, c, log) {
70
+ const file = join(app, 'goal.config.js');
71
+ const prop = (k) => (c.keys[k] === k ? k : `${k}: ${c.keys[k]}`);
72
+ if (!existsSync(file)) {
73
+ writeFileSync(file, `${c.import}\n\nexport default {\n${Object.keys(c.keys).map((k) => ` ${prop(k)},\n`).join('')}};\n`);
74
+ return log(' created goal.config.js');
75
+ }
76
+ let text = readFileSync(file, 'utf8');
77
+ let body;
78
+ try {
79
+ body = parse(text, { sourceType: 'module' }).program.body;
80
+ } catch {
81
+ body = [];
82
+ }
83
+ const obj = body.find((n) => n.type === 'ExportDefaultDeclaration')?.declaration;
84
+ if (obj?.type !== 'ObjectExpression')
85
+ return log(` goal.config.js: add this to it yourself (its default export isn't an object to add to):\n ${c.import}\n ${Object.keys(c.keys).map(prop).join(', ')}`);
86
+ const keys = new Set(obj.properties.map((p) => p.key?.name ?? p.key?.value));
87
+ const missing = Object.keys(c.keys).filter((k) => !keys.has(k));
88
+ if (!missing.length) return log(` kept goal.config.js: it has ${Object.keys(c.keys).join(', ')} already`);
89
+ text = text.slice(0, obj.start + 1) + missing.map((k) => `\n ${prop(k)},`).join('') + text.slice(obj.start + 1);
90
+ if (!text.includes(c.import)) {
91
+ const at = body.filter((n) => n.type === 'ImportDeclaration').at(-1)?.end;
92
+ text = at === undefined ? `${c.import}\n${text}` : `${text.slice(0, at)}\n${c.import}${text.slice(at)}`;
93
+ }
94
+ writeFileSync(file, text);
95
+ log(` added ${missing.join(', ')} to goal.config.js`);
96
+ }
97
+
98
+ const sh = (cmd, cwd) => execSync(cmd, { cwd, stdio: 'inherit' });
99
+
100
+ /**
101
+ * Sets a tool up in the app: `spec` is the recipe's name, with a version to pick the recipe for one
102
+ * (`tailwindcss@3`). Without a name, lists the recipes. `run` runs a command in the app's folder.
103
+ */
104
+ export async function add(app, spec, { log = console.log, run = sh, dir } = {}) {
105
+ const all = await recipes(dir);
106
+ if (!spec) {
107
+ log('goal add <tool> [app folder] sets a tool up in the app. Recipes:');
108
+ for (const r of all) log(` ${[r.name, ...(r.aliases ?? [])].join(', ').padEnd(24)} ${r.about} (${r.versions.map((e) => e.range).join(', ')})`);
109
+ return;
110
+ }
111
+ const at = spec.lastIndexOf('@');
112
+ const [name, version] = at > 0 ? [spec.slice(0, at), spec.slice(at + 1)] : [spec];
113
+ const recipe = all.find((r) => r.name === name || r.package === name || r.aliases?.includes(name));
114
+ if (!recipe) throw new Error(`goal add has no recipe for ${name}; it has ${all.map((r) => r.name).join(', ')}. To add one, see ${HELP}`);
115
+
116
+ const pkgFile = join(app, 'package.json');
117
+ const read = () => (existsSync(pkgFile) ? JSON.parse(readFileSync(pkgFile, 'utf8')) : { private: true });
118
+ let pkg = read();
119
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
120
+ const mine = coerce(deps[recipe.package]);
121
+ const e = pick(recipe, version ?? mine);
122
+ log(`${recipe.name}: the recipe for ${recipe.package} ${e.range}${mine && !version ? ` (the app has ${deps[recipe.package]})` : ''}`);
123
+
124
+ if (pkg.type !== 'module') {
125
+ pkg.type = 'module';
126
+ writeFileSync(pkgFile, JSON.stringify(pkg, null, 2) + '\n');
127
+ log(' set "type": "module" in package.json: goal.js apps are ES modules');
128
+ }
129
+ for (const [field, flag] of [['dependencies', '--save'], ['devDependencies', '--save-dev']]) {
130
+ const names = Object.keys(e[field] ?? {}).filter((n) => !(n in deps));
131
+ for (const n of Object.keys(e[field] ?? {}).filter((n) => n in deps)) log(` kept ${n} ${deps[n]}`);
132
+ if (!names.length) continue;
133
+ const cmd = `npm install ${flag} ${names.map((n) => `${n}@${e[field][n]}`).join(' ')}`;
134
+ log(` $ ${cmd}`);
135
+ run(cmd, app);
136
+ }
137
+
138
+ for (const [f, text] of Object.entries(e.files ?? {})) {
139
+ const file = join(app, f);
140
+ if (!existsSync(file)) {
141
+ mkdirSync(dirname(file), { recursive: true });
142
+ writeFileSync(file, text);
143
+ log(` created ${f}`);
144
+ } else if (readFileSync(file, 'utf8') === text) log(` kept ${f}: it's set up already`);
145
+ else log(` kept ${f}, which isn't the recipe's. The recipe's:\n${text.trimEnd().replace(/^(?=.)/gm, ' ')}`);
146
+ }
147
+ // Lines a file needs: at its start (prepend), like a stylesheet's @import, or at its end (lines)
148
+ for (const [where, ops] of [['start', e.prepend], ['end', e.lines]])
149
+ for (const [f, want] of Object.entries(ops ?? {})) {
150
+ const file = join(app, f);
151
+ const text = existsSync(file) ? readFileSync(file, 'utf8') : '';
152
+ const now = text.split(/\r?\n/);
153
+ const add = want.filter((l) => !has(now, l));
154
+ if (!add.length) continue;
155
+ mkdirSync(dirname(file), { recursive: true });
156
+ const lines = add.join('\n') + '\n';
157
+ writeFileSync(file, where === 'start' ? lines + text : text + (text && !text.endsWith('\n') ? '\n' : '') + lines);
158
+ log(` added to ${f}: ${add.join(', ')}`);
159
+ }
160
+ pkg = read(); // as npm left it
161
+ const placeholder = /^echo "Error: no test specified" && exit 1$/; // npm init's
162
+ const scripts = Object.entries(e.scripts ?? {}).filter(([k, v]) => {
163
+ if (!pkg.scripts?.[k] || placeholder.test(pkg.scripts[k])) return true;
164
+ if (pkg.scripts[k] !== v) log(` kept the script ${k}: ${pkg.scripts[k]} (the recipe's: ${v})`);
165
+ return false;
166
+ });
167
+ if (scripts.length) {
168
+ pkg.scripts = { ...pkg.scripts, ...Object.fromEntries(scripts) };
169
+ writeFileSync(pkgFile, JSON.stringify(pkg, null, 2) + '\n');
170
+ log(` added the script${scripts.length > 1 ? 's' : ''} ${scripts.map(([k]) => k).join(', ')} to package.json`);
171
+ }
172
+ if (e.config) configure(app, e.config, log);
173
+ for (const cmd of e.run ?? []) {
174
+ log(` $ ${cmd}`);
175
+ run(cmd, app);
176
+ }
177
+ log('Next:');
178
+ for (const n of [...(e.next ?? []), `Docs: ${recipe.docs}`]) log(` - ${n}`);
179
+ }
package/src/app.js CHANGED
@@ -153,12 +153,20 @@ function table(routes) {
153
153
  .sort((a, b) => a.n - b.n || a.i - b.i);
154
154
  }
155
155
 
156
+ /** A path parameter: text, or a number for one typed {id: number}, which matches only a number. */
157
+ function param(r, name, seg, params) {
158
+ if (r.types?.[name] !== 'number') return !!(params[name] = seg);
159
+ if (!/^-?\d+(\.\d+)?$/.test(seg)) return false;
160
+ params[name] = Number(seg);
161
+ return true;
162
+ }
163
+
156
164
  function match(routes, method, segs) {
157
165
  const allow = new Set();
158
166
  for (const r of routes) {
159
167
  if (r.segs.length !== segs.length) continue;
160
168
  const params = {};
161
- if (!r.segs.every((s, i) => (s[0] === '{' ? ((params[s.slice(1, -1)] = segs[i]), true) : s === segs[i]))) continue;
169
+ if (!r.segs.every((s, i) => (s[0] === '{' ? param(r, s.slice(1, -1), segs[i], params) : s === segs[i]))) continue;
162
170
  if (r.method === method) return { route: r, params };
163
171
  allow.add(r.method);
164
172
  }
@@ -178,7 +186,8 @@ function keptState(header) {
178
186
  /**
179
187
  * A request handler for node:http.
180
188
  * @param {{ method: string, path: string, handler: Function }[]} routes
181
- * @param {{ dev?: boolean, staticDirs?: string[], config?: { csp?: string | false, csrf?: boolean, bodyLimit?: number }, log?: (e: Error) => void }} [opts]
189
+ * @param {{ dev?: boolean, staticDirs?: string[], config?: { csp?: string | false, csrf?: boolean, bodyLimit?: number, onError?: (e: Error, request?: object) => void }, log?: (e: Error) => void }} [opts]
190
+ * config.onError: called with each error a route or server function throws, and the request
182
191
  */
183
192
  export function createApp(routes, { dev = false, staticDirs = [], config = {}, log = console.error } = {}) {
184
193
  const sorted = table(routes);
@@ -198,6 +207,7 @@ export function createApp(routes, { dev = false, staticDirs = [], config = {}, l
198
207
  res.end(req.method === 'HEAD' ? undefined : body);
199
208
  };
200
209
  const fail = (status, title) => send(status, HTML, errorPage(title));
210
+ let request;
201
211
 
202
212
  try {
203
213
  const url = new URL(req.url, 'http://localhost');
@@ -263,7 +273,7 @@ export function createApp(routes, { dev = false, staticDirs = [], config = {}, l
263
273
  return j < 0 ? null : kept.splice(0, j + 1).pop().s;
264
274
  };
265
275
  }
266
- const request = { method, path: url.pathname, url, params: m.params, query: Object.fromEntries(url.searchParams), headers: req.headers, cookies, form, files, json: body };
276
+ request = { method, path: url.pathname, url, params: m.params, query: Object.fromEntries(url.searchParams), headers: req.headers, cookies, form, files, json: body };
267
277
  const cookie = (name, value, opts) => setCookies.push(serializeCookie(name, value, opts));
268
278
  const out = await m.route.handler(request, { ctx, redirect, json, notFound, cookie });
269
279
  if (isHtml(out)) return send(200, HTML, page(out.s, [...ctx.ev], nonce, token, dev));
@@ -273,6 +283,11 @@ export function createApp(routes, { dev = false, staticDirs = [], config = {}, l
273
283
  } catch (e) {
274
284
  if (e.status === 413) return fail(413, 'Too large');
275
285
  log(e);
286
+ // goal.config.js's onError hears of it too, say to report it to an error tracker. It runs after the
287
+ // answer is on its way, and an error of its own is logged.
288
+ Promise.resolve()
289
+ .then(() => config.onError?.(e, request))
290
+ .catch(log);
276
291
  return dev ? send(500, 'text/plain; charset=utf-8', String(e.stack)) : fail(500, 'Something went wrong');
277
292
  }
278
293
  };
package/src/build.js CHANGED
@@ -3,8 +3,11 @@
3
3
  // app/**/*.goal -> dist/server/**.js (components and routes) and one client chunk per
4
4
  // interactive component in dist/client/c/
5
5
  // app/**/*.js -> dist/server/**.js as they are, for server code the .goal files import
6
- // app/public/ -> dist/public/, served as files
7
- // app/goal.config.js opt-outs of the security defaults (see src/app.js)
6
+ // app/public/ -> dist/public/, served as files; stylesheets through PostCSS when the app
7
+ // has a postcss.config.js (see css.js)
8
+ // app/goal.config.js opt-outs of the security defaults and the error hook (see src/app.js),
9
+ // copied with the server code
10
+ // app/.env -> process.env, for goal start and goal dev
8
11
 
9
12
  import { readFileSync, writeFileSync, mkdirSync, readdirSync, existsSync, cpSync, rmSync, watch } from 'node:fs';
10
13
  import { join, relative, dirname, resolve, sep, posix } from 'node:path';
@@ -13,9 +16,11 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
13
16
  import { gzipSync } from 'node:zlib';
14
17
  import * as esbuild from 'esbuild';
15
18
  import { compile } from './compiler.js';
19
+ import { exportsOf } from './types.js';
16
20
  import { desugar } from './syntax.js';
17
21
  import { loaderScript } from './server.js';
18
22
  import { createApp } from './app.js';
23
+ import { postcss } from './css.js';
19
24
 
20
25
 
21
26
  const SRC = dirname(fileURLToPath(import.meta.url));
@@ -65,11 +70,47 @@ const entriesPlugin = (entries, renders) => {
65
70
  };
66
71
  };
67
72
 
73
+ /**
74
+ * What the .goal files tell each other: the server functions each exports, so files can import them,
75
+ * and what a #strict file that imports one gets from it (see types.js), each read once.
76
+ */
77
+ function linker(app, all) {
78
+ const exported = new Map();
79
+ for (const rel of all.filter((f) => f.endsWith('.goal')))
80
+ exported.set(rel, desugar(readFileSync(join(app, rel), 'utf8'), rel).serverFns.filter((f) => f.exported).map((f) => f.name));
81
+ const typed = new Map();
82
+ const to = (rel, spec) => posix.join(posix.dirname(rel), spec);
83
+ return {
84
+ serverFunctions: (rel) => (spec) => (exported.has(to(rel, spec)) ? { base: to(rel, spec).slice(0, -5), names: exported.get(to(rel, spec)) } : null),
85
+ typesOf: (rel) => (spec) => {
86
+ const target = to(rel, spec);
87
+ if (!exported.has(target)) return null;
88
+ if (!typed.has(target)) typed.set(target, exportsOf(readFileSync(join(app, target), 'utf8'), target));
89
+ return typed.get(target);
90
+ },
91
+ };
92
+ }
93
+
94
+ /** goal check: compiles every .goal file as goal build does, types too, and gives each file's first error. */
95
+ export function check(app) {
96
+ const all = files(app);
97
+ const link = linker(app, all);
98
+ const errors = [];
99
+ for (const rel of all.filter((f) => f.endsWith('.goal')))
100
+ try {
101
+ compile(readFileSync(join(app, rel), 'utf8'), { file: rel, base: rel.slice(0, -5), rt: RT, keyed: KEYED, serverFunctions: link.serverFunctions(rel), typesOf: link.typesOf(rel) });
102
+ } catch (e) {
103
+ errors.push(e.message);
104
+ }
105
+ return errors;
106
+ }
107
+
68
108
  /**
69
109
  * Compiles an app into dist/. Throws on a compile error or a duplicate route.
70
110
  * `dev` keeps chunks readable with source maps back to the .goal files; otherwise they are minified
71
111
  * and the source stays on the server. `publicPath` is where the site is served from.
72
- * @returns {Promise<{ version: string, chunks: { url: string, bytes: number, gzip: number }[], loader: number, routes: string[] }>}
112
+ * @returns {Promise<{ version: string, chunks: { url: string, bytes: number, gzip: number }[], loader: number, routes: string[], css: boolean }>}
113
+ * css: whether the stylesheets went through PostCSS
73
114
  */
74
115
  export async function build(app, { out = join(app, 'dist'), dev = false, publicPath = '/' } = {}) {
75
116
  const version = Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
@@ -80,24 +121,16 @@ export async function build(app, { out = join(app, 'dist'), dev = false, publicP
80
121
  const renders = new Map(); // render modules, by .goal file
81
122
  rmSync(out, { recursive: true, force: true });
82
123
  const all = files(app);
83
- // The server functions each .goal file exports, so files can import them from each other.
84
- const exported = new Map();
85
- for (const rel of all.filter((f) => f.endsWith('.goal')))
86
- exported.set(rel, desugar(readFileSync(join(app, rel), 'utf8'), rel).serverFns.filter((f) => f.exported).map((f) => f.name));
124
+ const link = linker(app, all);
87
125
  for (const rel of all) {
88
- if (rel === 'goal.config.js') continue;
89
126
  if (!rel.endsWith('.goal')) {
90
127
  if (/\.(m?js|json)$/.test(rel)) write(join(out, 'server', rel), readFileSync(join(app, rel)));
91
128
  continue;
92
129
  }
93
130
  const base = rel.slice(0, -5);
94
- const serverFunctions = (spec) => {
95
- const target = posix.join(posix.dirname(rel), spec);
96
- return exported.has(target) ? { base: target.slice(0, -5), names: exported.get(target) } : null;
97
- };
98
131
  // In dev a chunk's URL names the build, so a page updated live loads the new code.
99
132
  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 });
133
+ const r = compile(readFileSync(join(app, rel), 'utf8'), { file: rel, base, rt: RT, keyed: KEYED, chunk, dev, serverFunctions: link.serverFunctions(rel), typesOf: link.typesOf(rel) });
101
134
  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}`);
102
135
  write(join(out, 'server', base + '.js'), server);
103
136
  if (r.routes.length || r.serverFunctions.length) routeFiles.push(base);
@@ -150,8 +183,15 @@ export async function build(app, { out = join(app, 'dist'), dev = false, publicP
150
183
  routeFiles.map((f, i) => `import { _$routes as r${i} } from './${f}.js?v=${version}';\n`).join('') +
151
184
  `export default [${routeFiles.map((_, i) => `...r${i}`).join(', ')}];\n`,
152
185
  );
153
- if (existsSync(join(app, 'public'))) cpSync(join(app, 'public'), join(out, 'public'), { recursive: true });
154
- return { version, chunks, loader: gzipSync(loaderScript()).length, routes: routes.map((r) => r.label) };
186
+ // The server code is ES modules, whatever the app's package.json says.
187
+ write(join(out, 'server', 'package.json'), '{ "type": "module" }\n');
188
+ const css = await postcss(app, dev);
189
+ if (existsSync(join(app, 'public'))) {
190
+ cpSync(join(app, 'public'), join(out, 'public'), { recursive: true });
191
+ for (const f of css ? readdirSync(join(app, 'public'), { recursive: true }).filter((f) => f.endsWith('.css')) : [])
192
+ writeFileSync(join(out, 'public', f), await css(readFileSync(join(app, 'public', f), 'utf8'), join(app, 'public', f), join(out, 'public', f)));
193
+ }
194
+ return { version, chunks, loader: gzipSync(loaderScript()).length, routes: routes.map((r) => r.label), css: !!css };
155
195
  }
156
196
 
157
197
  /**
@@ -159,7 +199,8 @@ export async function build(app, { out = join(app, 'dist'), dev = false, publicP
159
199
  * of pages listening at /_goal/hmr for live updates (goal dev).
160
200
  */
161
201
  export async function serve(app, { out = join(app, 'dist'), port = 3000, dev = false, version = () => '', log = console.error, hmr } = {}) {
162
- const configFile = join(app, 'goal.config.js');
202
+ if (existsSync(join(app, '.env'))) process.loadEnvFile(join(app, '.env')); // what the environment has already wins
203
+ const configFile = join(out, 'server', 'goal.config.js');
163
204
  const config = existsSync(configFile) ? (await import(pathToFileURL(configFile).href)).default : {};
164
205
  const routesFile = pathToFileURL(join(out, 'server', '_routes.js')).href;
165
206
  const server = createServer(async (req, res) => {
@@ -192,7 +233,9 @@ export async function dev(app, { port = 3000, log = console.log } = {}) {
192
233
  const r = await build(app, { dev: true });
193
234
  version = r.version;
194
235
  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 });
236
+ const type = changed.length && changed.every((f) => f.endsWith('.css')) ? 'css' : 'update';
237
+ tell({ type, version });
238
+ if (type === 'update' && r.css) tell({ type: 'css', version }); // PostCSS may make new CSS from the code, as Tailwind does
196
239
  } catch (e) {
197
240
  log(e.message);
198
241
  tell({ type: 'error', message: e.message });
package/src/cli.js CHANGED
@@ -1,14 +1,31 @@
1
- // goal build [app] | goal start [app] [--port N] | goal dev [app] [--port N]
1
+ // goal build [app] | goal start [app] [--port N] | goal dev [app] [--port N] | goal check [app]
2
+ // | goal add [tool] [app]
2
3
 
3
- import { build, serve, dev } from './build.js';
4
+ import { build, serve, dev, check } from './build.js';
5
+ import { add } from './add.js';
4
6
 
5
- const USAGE = 'usage: goal build|start|dev [app folder] [--port 3000]';
7
+ const USAGE = 'usage: goal build|start|dev|check [app folder] [--port 3000]\n goal add [tool] [app folder]';
6
8
 
7
- export async function main(argv, log = console.log) {
9
+ /** The command, the app's folder (the current one by default), the port (3000 by default), and goal add's tool. */
10
+ export function args(argv) {
8
11
  const [cmd, ...rest] = argv;
9
12
  const i = rest.indexOf('--port');
10
13
  const port = i < 0 ? 3000 : Number(rest.splice(i, 2)[1]);
11
- const app = rest[0] ?? '.';
14
+ const tool = cmd === 'add' ? rest.shift() : undefined;
15
+ return { cmd, app: rest[0] ?? '.', port, tool };
16
+ }
17
+
18
+ export async function main(argv, log = console.log, opts = {}) {
19
+ const { cmd, app, port, tool } = args(argv);
20
+ if (cmd === 'add') {
21
+ try {
22
+ await add(app, tool, { log, ...opts });
23
+ return 0;
24
+ } catch (e) {
25
+ log(e.message);
26
+ return 1;
27
+ }
28
+ }
12
29
  if (cmd === 'build') {
13
30
  try {
14
31
  const r = await build(app);
@@ -21,6 +38,17 @@ export async function main(argv, log = console.log) {
21
38
  return 1;
22
39
  }
23
40
  }
41
+ if (cmd === 'check') {
42
+ try {
43
+ const errors = check(app);
44
+ for (const e of errors) log(e);
45
+ log(errors.length ? `${errors.length} file${errors.length === 1 ? '' : 's'} with errors` : 'no errors');
46
+ return errors.length ? 1 : 0;
47
+ } catch (e) {
48
+ log(e.message); // a file that doesn't parse
49
+ return 1;
50
+ }
51
+ }
24
52
  if (cmd === 'start' || cmd === 'dev') {
25
53
  const server = await (cmd === 'dev' ? dev(app, { port, log }) : serve(app, { port }));
26
54
  log(`http://localhost:${server.address().port}`);
package/src/compiler.js CHANGED
@@ -32,6 +32,9 @@ import { generate } from '@babel/generator';
32
32
  import * as t from '@babel/types';
33
33
  import { desugar, errorAt, GoalError } from './syntax.js';
34
34
  import { URL_ATTRS, _$u } from './rt.js';
35
+ import { check } from './types.js';
36
+
37
+ export { exportsOf } from './types.js'; // what a .goal file gives a #strict file importing it: for the editor too
35
38
 
36
39
  export { GoalError };
37
40
 
@@ -77,7 +80,8 @@ function emit(node) {
77
80
  * Compiles one .goal file.
78
81
  * @param {string} source
79
82
  * @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]
83
+ * serverFunctions?: (specifier: string) => { base: string, names: string[] } | null, dev?: boolean,
84
+ * typesOf?: (specifier: string) => object | null }} [opts]
81
85
  * file: the name in errors and source maps; base: the file's path without .goal, which names its
82
86
  * server functions' URLs (/_m/<base>/<name>); rt and keyed: where compiled code imports the helpers
83
87
  * and the keyed list patcher from;
@@ -93,6 +97,7 @@ export function compile(source, opts = {}) {
93
97
  SRC = { source, file };
94
98
  const ast = parse(d.code, { sourceType: 'module', plugins: ['jsx'] });
95
99
  relocate(ast, source, d.map, file.split('/').at(-1)); // source maps name the file next to the compiled one
100
+ const typed = d.strict ? check(ast, d, opts.typesOf, fail) : null; // types: what other .goal files export comes from typesOf
96
101
 
97
102
  // Server functions this file can call: its own, and the ones it imports from other .goal files.
98
103
  for (const f of d.serverFns) o.sfns.set(f.name, `/_m/${base}/${f.name}`);
@@ -126,14 +131,14 @@ export function compile(source, opts = {}) {
126
131
  t.variableDeclarator(
127
132
  t.identifier('_$routes'),
128
133
  t.arrayExpression([
129
- ...d.routes.map((r) => routeEntry(r.method, r.path, t.identifier(r.name))),
134
+ ...d.routes.map((r) => routeEntry(r.method, r.path, t.identifier(r.name), r.types)),
130
135
  ...endpoints.map((f) =>
131
136
  routeEntry(
132
137
  'POST',
133
138
  f.path,
134
139
  t.arrowFunctionExpression(
135
140
  [t.identifier('r'), t.identifier('x')],
136
- t.callExpression(t.identifier('_$call'), [t.identifier(f.name), t.identifier('r'), t.identifier('x')]),
141
+ t.callExpression(t.identifier('_$call'), [t.identifier(f.name), t.identifier('r'), t.identifier('x'), ...(typed ? [t.valueToNode(typed.params.get(f.name))] : [])]),
137
142
  ),
138
143
  ),
139
144
  ),
@@ -152,11 +157,12 @@ export function compile(source, opts = {}) {
152
157
  };
153
158
  }
154
159
 
155
- const routeEntry = (method, path, handler) =>
160
+ const routeEntry = (method, path, handler, types = {}) =>
156
161
  t.objectExpression([
157
162
  t.objectProperty(t.identifier('method'), t.stringLiteral(method)),
158
163
  t.objectProperty(t.identifier('path'), t.stringLiteral(path)),
159
164
  t.objectProperty(t.identifier('handler'), handler),
165
+ ...(Object.keys(types).length ? [t.objectProperty(t.identifier('types'), t.valueToNode(types))] : []), // typed path parameters
160
166
  ]);
161
167
 
162
168
  // ---------------------------------------------------------------------------------------------
package/src/css.js ADDED
@@ -0,0 +1,30 @@
1
+ // Stylesheets through PostCSS. When the app has a postcss.config.js (or .mjs, .cjs), each .css file in
2
+ // public/ goes through the plugins it names before it's served: Tailwind CSS, autoprefixer and the
3
+ // like. goal build writes the result to dist/public/; the Vite plugin answers it on request. PostCSS
4
+ // and its plugins are the app's own packages, found from the app's folder.
5
+
6
+ import { existsSync } from 'node:fs';
7
+ import { createRequire } from 'node:module';
8
+ import { resolve } from 'node:path';
9
+ import { pathToFileURL } from 'node:url';
10
+
11
+ /** The app's PostCSS config file, if it has one. */
12
+ export const postcssConfig = (app) => ['postcss.config.js', 'postcss.config.mjs', 'postcss.config.cjs'].map((f) => resolve(app, f)).find((f) => existsSync(f));
13
+
14
+ /**
15
+ * The app's PostCSS, as `(css, from, to) => Promise<string>`, or null when the app has no PostCSS
16
+ * config. The config is read anew each time, so goal dev sees it change. `dev` adds source maps.
17
+ */
18
+ export async function postcss(app, dev = false) {
19
+ const file = postcssConfig(app);
20
+ if (!file) return null;
21
+ const require = createRequire(file);
22
+ const load = async (name) => (await import(pathToFileURL(require.resolve(name)).href)).default;
23
+ let config = (await import(`${pathToFileURL(file).href}?v=${Date.now()}`)).default;
24
+ if (typeof config === 'function') config = await config({ env: dev ? 'development' : 'production' });
25
+ // { plugins: { name: options } }, each plugin a package of the app's, or { plugins: [plugin(), ...] }
26
+ const { plugins = [] } = config;
27
+ const list = Array.isArray(plugins) ? plugins : await Promise.all(Object.entries(plugins).filter(([, o]) => o !== false).map(async ([name, o]) => (await load(name))(o)));
28
+ const run = await load('postcss');
29
+ return async (css, from, to) => (await run(list).process(css, { from, to, map: dev && { inline: true } })).css;
30
+ }
package/src/eslint.js ADDED
@@ -0,0 +1,106 @@
1
+ // ESLint for .goal files:
2
+ //
3
+ // // eslint.config.js
4
+ // import goal from 'goaljs/eslint';
5
+ // export default [js.configs.recommended, ...goal.configs.recommended];
6
+ //
7
+ // ESLint checks the JavaScript each .goal file becomes (see syntax.js): routes as functions, {if} as
8
+ // ternaries, types taken out, a route's path parameters as its function's. A problem is reported
9
+ // where it is in the .goal file, and a fix is kept when the text it changes is the file's own.
10
+ // Problems in code goal.js wrote, like a route's parameters, aren't the file's and are left out. A
11
+ // file that doesn't parse gets its parse error.
12
+
13
+ import { desugar } from './syntax.js';
14
+
15
+ const seen = new Map(); // by file: what preprocess made of it, for postprocess
16
+
17
+ /** Where each line starts. */
18
+ const starts = (text) => {
19
+ const s = [0];
20
+ for (let i = 0; i < text.length; i++) if (text[i] === '\n') s.push(i + 1);
21
+ return s;
22
+ };
23
+
24
+ const processor = {
25
+ meta: { name: 'goal' },
26
+ supportsAutofix: true,
27
+ preprocess(text, file) {
28
+ try {
29
+ const r = desugar(text, file);
30
+ // The compiler declares a route's path parameters in its function; here they're its parameters.
31
+ let code = r.code;
32
+ const added = [];
33
+ for (const route of r.routes.filter((x) => x.params.length)) {
34
+ const at = code.indexOf(`${route.name}(request, _$x`) + route.name.length + 13;
35
+ const ins = `, { ${route.params.join(', ')} }`;
36
+ code = code.slice(0, at) + ins + code.slice(at);
37
+ added.push({ at, length: ins.length });
38
+ }
39
+ seen.set(file, { text, code, map: r.map, added, from: starts(code), to: starts(text) });
40
+ return [{ text: code, filename: 'goal.jsx' }];
41
+ } catch (e) {
42
+ seen.set(file, { error: e });
43
+ return [];
44
+ }
45
+ },
46
+ postprocess([messages = []], file) {
47
+ const f = seen.get(file);
48
+ seen.delete(file);
49
+ if (f.error) return [{ ruleId: null, fatal: true, severity: 2, message: f.error.message.replace(/^.*?:\d+:\d+: /, ''), line: f.error.line, column: f.error.column }];
50
+ // From a place in what ESLint saw, to one in the desugared code (-1 in a path parameter added)
51
+ const desugared = (o) => {
52
+ let d = 0;
53
+ for (const a of f.added) {
54
+ if (o < a.at) break;
55
+ if (o < a.at + a.length) return -1;
56
+ d += a.length;
57
+ }
58
+ return o - d;
59
+ };
60
+ const at = (line, column) => f.map(desugared(f.from[line - 1] + column - 1));
61
+ const ours = (line, column) => {
62
+ const o = desugared(f.from[line - 1] + column - 1);
63
+ return o < 0 || f.map(o) === f.map(o + 1); // goal.js's code maps to one place
64
+ };
65
+ const place = (o) => {
66
+ const line = f.to.findLastIndex((s) => s <= o);
67
+ return { line: line + 1, column: o - f.to[line] + 1 };
68
+ };
69
+ // A fix or suggestion over the file's own text, at its place in the file
70
+ const fix = (x) => {
71
+ const [a, b] = x.range.map((o) => f.map(desugared(o)));
72
+ return f.text.slice(a, b) === f.code.slice(...x.range) ? { range: [a, b], text: x.text } : undefined;
73
+ };
74
+ return messages
75
+ .filter((m) => !m.line || !ours(m.line, m.column))
76
+ .map((m) => {
77
+ if (!m.line) return m;
78
+ const out = { ...m, ...place(at(m.line, m.column)) };
79
+ if (m.endLine) {
80
+ const end = place(at(m.endLine, m.endColumn));
81
+ out.endLine = end.line;
82
+ out.endColumn = end.column;
83
+ }
84
+ if (m.fix) out.fix = fix(m.fix);
85
+ if (m.suggestions) out.suggestions = m.suggestions.map((s) => ({ ...s, fix: fix(s.fix) })).filter((s) => s.fix);
86
+ if (!out.fix) delete out.fix;
87
+ return out;
88
+ });
89
+ },
90
+ };
91
+
92
+ const plugin = { meta: { name: 'goaljs' }, processors: { goal: processor }, configs: {} };
93
+
94
+ plugin.configs.recommended = [
95
+ { files: ['**/*.goal'], plugins: { goal: plugin }, processor: 'goal/goal' },
96
+ {
97
+ files: ['**/*.goal/*.jsx'],
98
+ languageOptions: {
99
+ parserOptions: { ecmaFeatures: { jsx: true } },
100
+ globals: { redirect: 'readonly', json: 'readonly', notFound: 'readonly', cookie: 'readonly' }, // a route's helpers
101
+ },
102
+ rules: { 'no-var': 'off' }, // var is a component's state
103
+ },
104
+ ];
105
+
106
+ export default plugin;