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/rt.js CHANGED
@@ -72,8 +72,38 @@ export const _$sf = async (url, args) => {
72
72
  };
73
73
 
74
74
  /** Runs a server function for a request from the browser: the arguments are a JSON array. */
75
- export const _$call = async (fn, r, x) =>
76
- Array.isArray(r.json) ? x.json({ v: (await fn(...r.json)) ?? null }) : x.json({ error: 'send the arguments as a JSON array' }, 400);
75
+ export const _$call = async (fn, r, x, types) => {
76
+ if (!Array.isArray(r.json)) return x.json({ error: 'send the arguments as a JSON array' }, 400);
77
+ // A server function in a #strict file: arguments that aren't of its types never reach it.
78
+ if (types && (r.json.length > types.length || !types.every((p, i) => (r.json[i] === undefined || r.json[i] === null ? p.optional || _$ok(r.json[i], p.type) : _$ok(r.json[i], p.type)))))
79
+ return x.json({ error: "the arguments aren't of the types the function takes" }, 400);
80
+ return x.json({ v: (await fn(...r.json)) ?? null });
81
+ };
82
+
83
+ /** Is this JSON value of type x (see types.js)? What JSON can't carry, like a function, isn't checked here. */
84
+ export function _$ok(v, x) {
85
+ switch (x.k) {
86
+ case 'string':
87
+ case 'number':
88
+ case 'boolean':
89
+ return typeof v === x.k;
90
+ case 'null':
91
+ return v === null;
92
+ case 'undefined':
93
+ case 'void':
94
+ return v == null; // JSON has no undefined: null stands for it
95
+ case 'lit':
96
+ return v === x.v;
97
+ case 'array':
98
+ return Array.isArray(v) && v.every((y) => _$ok(y, x.of));
99
+ case 'object':
100
+ return !!v && typeof v === 'object' && !Array.isArray(v) && Object.entries(x.fields).every(([n, f]) => (v[n] == null ? f.optional || _$ok(v[n], f.type) : _$ok(v[n], f.type)));
101
+ case 'union':
102
+ return x.of.some((y) => _$ok(v, y));
103
+ default:
104
+ return true;
105
+ }
106
+ }
77
107
 
78
108
  /** A render: numbers component instances, collects the page's events, and holds the CSRF token. */
79
109
  export const _$ctx = (t = '') => ({
package/src/syntax.js CHANGED
@@ -3,18 +3,22 @@
3
3
  // route GET /users/{id} { ... } a route, at the top level of a file
4
4
  // {if (a) <p>A</p> else if (b) <p>B</p> else <p>C</p>} if/else as a value, inside markup
5
5
  // server function addNote(text) { ... } runs on the server, called from the browser
6
+ // #strict, then name: Type and type Note = { ... } types, in a file that starts with #strict
6
7
  //
7
8
  // desugar() parses the file with acorn (extended for these two forms), and rewrites them into plain
8
9
  // JavaScript + JSX with small text edits: a route becomes `async function _$r0(request, _$x) { ... }`
9
10
  // an if becomes a chain of ternaries, and a server function becomes an async function. `map` turns a position in the output back into one in the
10
- // source, so errors point at what the author wrote.
11
+ // source, so errors point at what the author wrote. Types are read into `types` and taken out of the
12
+ // code (see types.js, which checks them).
11
13
 
12
14
  import { Parser, tokTypes as tt } from 'acorn';
13
15
  import jsx from 'acorn-jsx';
14
16
 
15
17
  export const METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'];
16
18
  const SERVER = /^server[ \t]+function[ \t]+([A-Za-z_$][\w$]*)/;
17
- const SEGMENT = /^(?:[A-Za-z0-9\-._~]+|\{[A-Za-z_][A-Za-z0-9_]*\})$/;
19
+ const SEGMENT = /^(?:[A-Za-z0-9\-._~]+|\{[A-Za-z_][A-Za-z0-9_]*(?:[ \t]*:[ \t]*(?:string|number))?\})$/;
20
+ const STRICT = /^\s*#strict[ \t]*(?=\r?\n|$)/;
21
+ const BASIC = new Set(['string', 'number', 'boolean', 'unknown', 'Markup', 'undefined']);
18
22
 
19
23
  export class GoalError extends Error {
20
24
  constructor(message, file, line, column) {
@@ -35,16 +39,23 @@ export function errorAt(source, file, pos, message) {
35
39
  const Base = Parser.extend(jsx());
36
40
 
37
41
  /**
38
- * @returns {{ code: string, routes: { method: string, path: string, params: string[], name: string }[],
39
- * serverFns: { name: string, exported: boolean }[], map: (pos: number) => number }}
42
+ * @returns {{ code: string, routes: { method: string, path: string, params: string[], types: object, name: string }[],
43
+ * serverFns: { name: string, exported: boolean }[], map: (pos: number) => number, strict: boolean,
44
+ * types: { decls: Map<string, { type: object, exported: boolean, at: number }>, at: Map<number, object> } }}
45
+ * types.at: the type written for the binding or function that starts at that source position
40
46
  */
41
47
  export function desugar(source, file) {
42
48
  const edits = [];
43
49
  const routes = [];
44
50
  const serverFns = [];
51
+ const types = { decls: new Map(), at: new Map() };
45
52
  const fail = (pos, message) => {
46
53
  throw errorAt(source, file, pos, message);
47
54
  };
55
+ const s = STRICT.exec(source);
56
+ const strict = !!s;
57
+ if (s) edits.push({ at: s.index + s[0].indexOf('#'), del: 7, ins: '' });
58
+ const input = s ? source.slice(0, s.index) + s[0].replace('#strict', ' ') + source.slice(s.index + s[0].length) : source;
48
59
 
49
60
  class GoalParser extends Base {
50
61
  isServerFn() {
@@ -52,12 +63,128 @@ export function desugar(source, file) {
52
63
  }
53
64
 
54
65
  shouldParseExportStatement() {
66
+ if (this.isTypeDecl()) {
67
+ this.goalExportAt = this.lastTokStart; // the export keyword goes with the declaration
68
+ return true;
69
+ }
55
70
  if (!this.isServerFn()) return super.shouldParseExportStatement();
56
71
  this.goalExport = true;
57
72
  return true;
58
73
  }
59
74
 
75
+ isTypeDecl() {
76
+ return this.type === tt.name && this.value === 'type' && /^type[ \t]+[A-Za-z_$][\w$]*[ \t]*=/.test(this.input.slice(this.start));
77
+ }
78
+
79
+ // Types: read into `types`, and taken out of the code.
80
+ typed(at) {
81
+ if (!strict) fail(at, 'types go in a #strict file: put #strict on the first line');
82
+ }
83
+
84
+ goalAnnotation(at) {
85
+ this.typed(this.start);
86
+ const from = this.start;
87
+ this.next();
88
+ types.at.set(at, this.goalType());
89
+ edits.push({ at: from, del: this.lastTokEnd - from, ins: '' });
90
+ }
91
+
92
+ parseBindingAtom() {
93
+ const node = super.parseBindingAtom();
94
+ if (this.type === tt.colon) this.goalAnnotation(node.start);
95
+ return node;
96
+ }
97
+
98
+ parseFunctionParams(node) {
99
+ super.parseFunctionParams(node);
100
+ if (this.type === tt.colon) this.goalAnnotation(-node.start - 1); // a function's result: keyed apart from its name
101
+ }
102
+
103
+ parseParenItem(item) {
104
+ if (this.type === tt.colon) this.goalAnnotation(item.start); // an arrow function's parameter
105
+ return item;
106
+ }
107
+
108
+ goalTypeDecl() {
109
+ const at = this.goalExportAt ?? this.start;
110
+ const exported = this.goalExportAt !== undefined;
111
+ this.goalExportAt = undefined;
112
+ this.typed(at);
113
+ const node = this.startNode();
114
+ this.next();
115
+ node.id = this.parseIdent();
116
+ if (types.decls.has(node.id.name)) fail(node.id.start, `the type ${node.id.name} is declared twice`);
117
+ this.expect(tt.eq);
118
+ types.decls.set(node.id.name, { type: this.goalType(), exported, at: node.id.start });
119
+ this.eat(tt.semi);
120
+ edits.push({ at, del: this.lastTokEnd - at, ins: '' });
121
+ return this.finishNode(node, 'GoalType');
122
+ }
123
+
124
+ // T | U, T[], string, 'a', { name: T, other?: U }, (x: T) => U, (T), a declared name
125
+ goalType() {
126
+ const of = [this.goalList()];
127
+ while (this.eat(tt.bitwiseOR)) of.push(this.goalList());
128
+ return of.length > 1 ? { k: 'union', of } : of[0];
129
+ }
130
+
131
+ goalList() {
132
+ let t = this.goalPrimary();
133
+ while (this.type === tt.bracketL && this.input[this.end] === ']') {
134
+ this.next();
135
+ this.next();
136
+ t = { k: 'array', of: t };
137
+ }
138
+ return t;
139
+ }
140
+
141
+ goalPrimary() {
142
+ const at = this.start;
143
+ const v = this.value;
144
+ if (this.eat(tt.string)) return { k: 'lit', v };
145
+ if (this.eat(tt.num)) return { k: 'lit', v };
146
+ if (this.eat(tt._true) || this.eat(tt._false)) return { k: 'lit', v: v === 'true' };
147
+ if (this.eat(tt._null)) return { k: 'null' };
148
+ if (this.eat(tt._void)) return { k: 'void' }; // what a function that returns nothing gives
149
+ if (this.eat(tt.name)) return BASIC.has(v) ? { k: v } : { k: 'ref', name: v, at };
150
+ if (this.eat(tt.braceL)) {
151
+ const fields = {};
152
+ while (!this.eat(tt.braceR)) {
153
+ const name = this.value;
154
+ if (this.type !== tt.name && this.type !== tt.string && !this.type.keyword) fail(this.start, 'write a field as name: type');
155
+ this.next();
156
+ const optional = this.eat(tt.question);
157
+ this.expect(tt.colon);
158
+ fields[name] = { type: this.goalType(), optional };
159
+ if (!this.eat(tt.comma) && !this.eat(tt.semi) && this.type !== tt.braceR) fail(this.start, 'separate the fields with commas');
160
+ }
161
+ return { k: 'object', fields };
162
+ }
163
+ if (this.eat(tt.parenL)) {
164
+ if (this.type === tt.parenR || (this.type === tt.name && /^[A-Za-z_$][\w$]*\s*\??\s*:/.test(this.input.slice(this.start)))) {
165
+ const params = [];
166
+ while (!this.eat(tt.parenR)) {
167
+ this.next(); // the parameter's name: only its type matters
168
+ const optional = this.eat(tt.question);
169
+ this.expect(tt.colon);
170
+ params.push({ type: this.goalType(), optional });
171
+ if (this.type !== tt.parenR) this.expect(tt.comma);
172
+ }
173
+ this.expect(tt.arrow);
174
+ return { k: 'fn', params, returns: this.goalType() };
175
+ }
176
+ const t = this.goalType();
177
+ this.expect(tt.parenR);
178
+ return t;
179
+ }
180
+ return fail(at, 'write a type: string, number, boolean, a list like Note[], or an object like { id: number }');
181
+ }
182
+
60
183
  parseStatement(context, topLevel, exports) {
184
+ if (this.isTypeDecl()) {
185
+ if (!topLevel && this.goalExportAt === undefined) fail(this.start, 'declare a type at the top level of a file');
186
+ return this.goalTypeDecl();
187
+ }
61
188
  if (this.isServerFn()) {
62
189
  if (!topLevel && !this.goalExport) fail(this.start, 'declare a server function at the top level of a file');
63
190
  serverFns.push({ name: SERVER.exec(this.input.slice(this.start))[1], exported: !!this.goalExport });
@@ -74,20 +201,23 @@ export function desugar(source, file) {
74
201
 
75
202
  goalRoute() {
76
203
  const start = this.start;
77
- const m = /^route[ \t]+(\S+)[ \t]+(\S+)[ \t]+\{/.exec(this.input.slice(start));
204
+ const m = /^route[ \t]+(\S+)[ \t]+((?:\{[^}\n]*\}|[^\s{])+)[ \t]+\{/.exec(this.input.slice(start));
78
205
  if (!m) fail(start, 'write a route as: route GET /path { ... }');
79
206
  const [head, method, path] = m;
80
207
  if (!METHODS.includes(method)) fail(start, `unknown method ${method}; use ${METHODS.join(', ')}`);
81
208
  const segs = path === '/' ? [] : path.slice(1).split('/');
82
209
  if (path[0] !== '/' || !segs.every((s) => SEGMENT.test(s)))
83
210
  fail(start, `write the path with plain words and {name} parameters, like /users/{id} (not ${path})`);
84
- const params = segs.filter((s) => s[0] === '{').map((s) => s.slice(1, -1));
211
+ const params = segs.filter((s) => s[0] === '{').map((s) => s.slice(1, -1).split(':')[0].trim());
212
+ const typed = segs.filter((s) => s.includes(':'));
213
+ if (typed.length) this.typed(start);
214
+ const types = Object.fromEntries(typed.map((s) => s.slice(1, -1).split(':').map((x) => x.trim())));
85
215
  for (const [i, p] of params.entries()) {
86
216
  if (params.indexOf(p) !== i) fail(start, `the path names {${p}} twice`);
87
217
  if (p === 'request') fail(start, 'name the path parameter something other than {request}');
88
218
  }
89
219
  const name = `_$r${routes.length}`;
90
- routes.push({ method, path, params, name });
220
+ routes.push({ method, path: path.replace(/\{([A-Za-z0-9_]+)[^}]*\}/g, '{$1}'), params, types, name });
91
221
  const brace = start + head.length - 1;
92
222
  edits.push({ at: start, del: brace - start, ins: `async function ${name}(request, _$x) ` });
93
223
  const node = this.startNode();
@@ -133,7 +263,7 @@ export function desugar(source, file) {
133
263
  }
134
264
 
135
265
  try {
136
- GoalParser.parse(source, { ecmaVersion: 'latest', sourceType: 'module', allowHashBang: true });
266
+ GoalParser.parse(input, { ecmaVersion: 'latest', sourceType: 'module', allowHashBang: true });
137
267
  } catch (e) {
138
268
  if (e instanceof GoalError) throw e;
139
269
  fail(e.pos, e.message.replace(/ \(\d+:\d+\)$/, ''));
@@ -158,5 +288,5 @@ export function desugar(source, file) {
158
288
  }
159
289
  return pos - shift;
160
290
  };
161
- return { code, routes, serverFns, map };
291
+ return { code, routes, serverFns, map, strict, types };
162
292
  }