clarusjs 0.13.0 → 0.15.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.
Files changed (53) hide show
  1. package/dist/check/generate.d.ts +2 -5
  2. package/dist/check/generate.js +148 -13
  3. package/dist/cli/check.d.ts +4 -0
  4. package/dist/cli/check.js +3 -1
  5. package/dist/cli/mapper.js +19 -1
  6. package/dist/cli/project.d.ts +4 -0
  7. package/dist/cli/project.js +1 -1
  8. package/dist/compiler/class-style.d.ts +1 -1
  9. package/dist/compiler/class-style.js +6 -2
  10. package/dist/compiler/components.d.ts +32 -0
  11. package/dist/compiler/components.js +63 -0
  12. package/dist/compiler/emit-client.js +33 -4
  13. package/dist/compiler/emit-server.js +21 -11
  14. package/dist/compiler/html-expr.d.ts +11 -2
  15. package/dist/compiler/html-expr.js +38 -20
  16. package/dist/compiler/icon.d.ts +1 -1
  17. package/dist/compiler/icon.js +4 -0
  18. package/dist/compiler/index.d.ts +13 -1
  19. package/dist/compiler/index.js +64 -2
  20. package/dist/compiler/ir.d.ts +39 -0
  21. package/dist/compiler/ir.js +104 -11
  22. package/dist/compiler/lint.js +12 -1
  23. package/dist/compiler/parse.d.ts +44 -0
  24. package/dist/compiler/parse.js +93 -10
  25. package/dist/compiler/script.d.ts +21 -1
  26. package/dist/compiler/script.js +58 -3
  27. package/dist/compiler/shared.d.ts +6 -0
  28. package/dist/compiler/shared.js +14 -0
  29. package/dist/fetch/index.d.ts +157 -3
  30. package/dist/fetch/index.js +135 -14
  31. package/dist/forms/index.js +15 -3
  32. package/dist/runtime/attrs.d.ts +6 -0
  33. package/dist/runtime/attrs.js +16 -0
  34. package/dist/runtime/dom.d.ts +42 -1
  35. package/dist/runtime/dom.js +152 -23
  36. package/dist/runtime/html.d.ts +6 -0
  37. package/dist/runtime/html.js +12 -0
  38. package/dist/runtime/index.d.ts +1 -1
  39. package/dist/runtime/index.js +1 -1
  40. package/dist/runtime/loader.js +32 -6
  41. package/dist/runtime/router.d.ts +6 -1
  42. package/dist/runtime/router.js +1 -1
  43. package/dist/runtime/server.d.ts +20 -2
  44. package/dist/runtime/server.js +48 -8
  45. package/dist/server/handler.d.ts +28 -1
  46. package/dist/server/handler.js +48 -2
  47. package/dist/server/modes.d.ts +2 -0
  48. package/dist/server/modes.js +5 -1
  49. package/dist/server/views.d.ts +1 -1
  50. package/dist/server/views.js +1 -1
  51. package/dist/vite/plugin.d.ts +19 -0
  52. package/dist/vite/plugin.js +61 -14
  53. package/package.json +1 -1
@@ -2,18 +2,30 @@ import { parseExpressionAt } from 'acorn';
2
2
  import { iconElement } from './icon.js';
3
3
  import { ClarusError } from './errors.js';
4
4
  import { FOR_IMPLICIT, importNames } from './parse.js';
5
- import { analyzeScript, mutationsOf, writesTo, checkExpr, checkHandler, referencesNames, scriptNames, splitImports } from './script.js';
5
+ import { analyzeScript, providesIn, mutationsOf, writesTo, checkExpr, checkHandler, referencesNames, scriptNames, serverScriptParts, splitImports } from './script.js';
6
6
  const ATTACH_MODES = ['load', 'idle', 'visible', 'interaction'];
7
- const SPREAD_REFUSED = new Set(['iframe', 'frame', 'embed', 'object', 'base', 'link', 'script', 'meta']);
7
+ export const SPREAD_REFUSED = new Set(['iframe', 'frame', 'embed', 'object', 'base', 'link', 'script', 'meta']);
8
8
  const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
9
9
  const iconBodies = new WeakMap();
10
10
  export function lower(parsed, file, source, options = {}) {
11
11
  const fail = (text, at) => { throw new ClarusError(text, file, source, at); };
12
12
  const stateful = !!parsed.script || parsed.inputs.some((i) => i.model);
13
+ if (parsed.events.length && !parsed.script)
14
+ fail('@event needs a <script> that sends it with emit(\'name\', value)', parsed.events[0].start);
15
+ if (parsed.contexts.length && stateful)
16
+ fail('@context is only for components without <script> or @model for now: an island has no context in the browser. Read it in a component without a script, or pass it in as a prop', parsed.contexts[0].start);
17
+ for (const c of parsed.contexts)
18
+ if (parsed.inputs.some((i) => i.name === c.name))
19
+ fail(`"${c.name}" is already an @input`, c.nameStart);
13
20
  const warnings = [];
21
+ const ss = parsed.serverScript;
22
+ if (ss && stateful)
23
+ fail('<script server> runs on the server only, and this component is an island (it has a <script> or a @model input): load the data in a parent, or in a page\'s <script server>, and pass it to the island as props', ss.tag);
24
+ const server = ss ? serverScriptParts(ss.code, file, source, ss.start) : undefined;
14
25
  const modelNames = new Set(parsed.inputs.filter((i) => i.model).map((i) => i.name));
15
26
  const split = parsed.script ? splitImports(parsed.script.code, file, source, parsed.script.start) : { imports: [], body: '' };
16
27
  const signals = parsed.script ? analyzeScript(split.body, file, source, parsed.script.start) : new Map();
28
+ const provides = parsed.script ? providesIn(split, file, source, parsed.script.start) : false;
17
29
  const scriptScope = parsed.script ? new Set([...signals.keys(), ...scriptNames(parsed.script.code)]) : new Set();
18
30
  const inputNames = new Set(stateful ? parsed.inputs.filter((i) => !i.model).map((i) => i.name).filter((name) => !signals.has(name)) : []);
19
31
  for (const name of inputNames) {
@@ -71,6 +83,7 @@ export function lower(parsed, file, source, options = {}) {
71
83
  let eventElementCount = 0;
72
84
  let attrElementCount = 0;
73
85
  let formCount = 0;
86
+ let useCount = 0;
74
87
  let selectModel;
75
88
  let engineScope = null;
76
89
  const sameRoot = (path, at) => {
@@ -125,6 +138,27 @@ export function lower(parsed, file, source, options = {}) {
125
138
  out.push({ kind: 'if', branches, block });
126
139
  return;
127
140
  }
141
+ if (node.type === 'await') {
142
+ checkExpr(node.expr, file, source, node.exprStart);
143
+ const block = stateful ? blockCount++ : -1;
144
+ const parent = out;
145
+ const parentScope = scopeKey;
146
+ const lowerBranch = (children, k) => {
147
+ const list = [];
148
+ out = list;
149
+ if (stateful)
150
+ scopeKey = `${block}.${k}`;
151
+ children.forEach((child) => visit(child, rawText));
152
+ return list;
153
+ };
154
+ const pending = lowerBranch(node.pending, 0);
155
+ const then = node.then ? { name: node.then.name, nodes: lowerBranch(node.then.children, 1) } : null;
156
+ const caught = node.catch ? { name: node.catch.name, nodes: lowerBranch(node.catch.children, 2) } : null;
157
+ out = parent;
158
+ scopeKey = parentScope;
159
+ out.push({ kind: 'await', expr: node.expr, pending, then, catch: caught, block });
160
+ return;
161
+ }
128
162
  if (node.type === 'for') {
129
163
  checkExpr(node.list, file, source, node.listStart);
130
164
  if (node.track !== null)
@@ -181,9 +215,12 @@ export function lower(parsed, file, source, options = {}) {
181
215
  let attach;
182
216
  let cls;
183
217
  const paths = [];
218
+ const listens = [];
184
219
  for (const a of node.attrs) {
185
220
  if (/^(class|style)\./.test(a.name))
186
221
  fail(`a component takes a static class="…" only: [${a.name}] is for elements`, a.start);
222
+ if (a.kind === 'prop' && a.name === 'use')
223
+ fail('[use] is for elements: put it on an element inside the component', a.start);
187
224
  if (a.kind === 'prop' && a.name === '...') {
188
225
  if (props.some((p) => p.name === '...'))
189
226
  fail('one [...] per element', a.start);
@@ -210,17 +247,32 @@ export function lower(parsed, file, source, options = {}) {
210
247
  paths.push({ name: a.name, expr: modelPath(a.expr, modelNames) });
211
248
  models.push({ name: a.name, set });
212
249
  }
250
+ else if (a.kind === 'event') {
251
+ if (!stateful)
252
+ fail('event bindings need a <script> with state; this component is static', a.start);
253
+ checkHandler(a.expr, file, source, a.start);
254
+ listens.push({ name: a.name, handler: a.expr });
255
+ }
256
+ else if (a.kind === 'interp') {
257
+ for (const p of a.parts)
258
+ if (typeof p !== 'string')
259
+ checkExpr(p.expr, file, source, p.start);
260
+ props.push({ name: a.name, expr: `[${a.parts.map((p) => (typeof p === 'string' ? JSON.stringify(p) : `(${p.expr})`)).join(', ')}].join('')` });
261
+ }
262
+ else if (a.kind === 'static' && a.name !== 'attach') {
263
+ props.push({ name: a.name, expr: JSON.stringify(a.value) });
264
+ }
213
265
  else if (a.kind === 'static' && a.name === 'attach') {
214
266
  if (typeof a.value !== 'string' || !ATTACH_MODES.includes(a.value))
215
267
  fail(`attach must be one of ${ATTACH_MODES.join(', ')}`, a.start);
216
268
  attach = a.value;
217
269
  }
218
270
  else
219
- fail(`component <${node.tag}> only takes [prop] and [(prop)] bindings and attach="…"`, a.start);
271
+ fail(`component <${node.tag}> only takes [prop], [(prop)] and (event) bindings and attach="…"`, a.start);
220
272
  }
221
273
  const hasContent = node.children.some((c) => c.type !== 'text' || c.value.trim());
222
274
  const readsState = props.some((p) => referencesNames(p.expr, scriptScope) || referencesNames(p.expr, loopNames));
223
- const region = stateful && (hasContent || readsState || models.length > 0) ? regionCount++ : -1;
275
+ const region = stateful && (hasContent || readsState || models.length > 0 || listens.length > 0 || provides) ? regionCount++ : -1;
224
276
  const parentScope = scopeKey;
225
277
  if (region >= 0)
226
278
  scopeKey = `c${region}`;
@@ -238,30 +290,46 @@ export function lower(parsed, file, source, options = {}) {
238
290
  continue;
239
291
  if (fills.some((f) => f.name === child.name))
240
292
  fail(`slot "${child.name}" is filled twice`, child.start);
241
- fills.push({ name: child.name, nodes: lowerList(child.children) });
293
+ if (child.params !== undefined) {
294
+ if (stateful)
295
+ fail(`@slot('${child.name}', …) receives data from the slot, which isn't supported inside an island yet: render this component outside the island, or pass the data as props`, child.start);
296
+ slotParamsCheck(child.params, file, source, child.paramsStart);
297
+ }
298
+ fills.push({ name: child.name, ...(child.params !== undefined ? { params: child.params } : {}), nodes: lowerList(child.children) });
242
299
  }
243
300
  const rest = node.children.filter((c) => c.type !== 'fill');
244
301
  const children = rest.every((c) => c.type === 'text' && !c.value.trim()) ? [] : lowerList(rest);
302
+ if (children.length && fills.some((f) => f.name === 'default'))
303
+ fail('the default slot is filled twice: by @slot(\'default\') and by content outside any @slot', node.start);
245
304
  scopeKey = parentScope;
246
- out.push({ kind: 'component', name: node.tag, props, ...(models.length ? { models } : {}), children, fills, region, ...(attach ? { attach } : {}), ...(paths.length ? { paths } : {}), ...(cls ? { class: cls } : {}) });
305
+ out.push({ kind: 'component', name: node.tag, props, ...(models.length ? { models } : {}), ...(listens.length ? { listens } : {}), children, fills, region, ...(attach ? { attach } : {}), ...(paths.length ? { paths } : {}), ...(cls ? { class: cls } : {}) });
247
306
  return;
248
307
  }
249
308
  if (node.tag === 'slot') {
250
- if (stateful)
251
- fail('<slot /> is only supported in components without <script>', node.start);
309
+ if (stateful && scopeKey !== undefined)
310
+ fail('in an island, <slot /> goes outside @if, @for and @await blocks and component content: the browser re-renders those, and slot content only exists on the server', node.start);
252
311
  let name = 'default';
312
+ const props = [];
253
313
  for (const a of node.attrs) {
254
314
  if (a.kind === 'static' && a.name === 'name' && typeof a.value === 'string' && a.value)
255
315
  name = a.value;
316
+ else if (a.kind === 'prop' && /^[A-Za-z_$][\w$]*$/.test(a.name)) {
317
+ checkExpr(a.expr, file, source, a.start + a.name.length + 4);
318
+ props.push({ name: a.name, expr: a.expr });
319
+ }
256
320
  else
257
- fail('<slot> only takes name="…"', a.start);
321
+ fail('<slot> only takes name="…", and the data it passes to its fill as [name]="expression"', a.start);
258
322
  }
259
323
  const fallback = [];
260
324
  const parent = out;
261
325
  out = fallback;
262
326
  node.children.forEach((child) => visit(child, rawText));
263
327
  out = parent;
264
- out.push({ kind: 'slot', name, fallback });
328
+ if (stateful && props.length)
329
+ fail('in an island, a slot passes no data: render the component outside the island to use [name]="…" on <slot>', node.start);
330
+ if (stateful && fallback.length)
331
+ fail('in an island, a slot has no fallback content', node.start);
332
+ out.push({ kind: 'slot', name, props, fallback });
265
333
  return;
266
334
  }
267
335
  const outerSelect = selectModel;
@@ -372,11 +440,19 @@ export function lower(parsed, file, source, options = {}) {
372
440
  const reactive = stateful && (referencesNames(a.expr, scriptScope) || referencesNames(a.expr, loopNames));
373
441
  const skip = [...new Set(attrs.filter((x) => x !== a && x.kind !== 'event').map((x) => x.name.toLowerCase()))];
374
442
  const at = new ClarusError('', file, source, a.start);
375
- const node_ = { kind: 'attr', name: '...', value: { expr: a.expr }, reactive, index: -1, tag: node.tag, skip, where: `${file}:${at.line}:${at.column}` };
443
+ const node_ = { kind: 'attr', name: '...', value: { expr: a.expr }, reactive, index: -1, tag: node.tag, skip, ...(a.expr === '__cl_attrs' ? {} : { where: `${file}:${at.line}:${at.column}` }) };
376
444
  if (reactive)
377
445
  dynamic.push(node_);
378
446
  out.push(node_);
379
447
  }
448
+ else if (a.kind === 'prop' && a.name === 'use') {
449
+ if (!stateful)
450
+ fail('[use] needs a <script> (an island): behaviours run in the browser', a.start);
451
+ checkExpr(a.expr, file, source, a.start);
452
+ const index = useCount++;
453
+ emitStatic(` data-cl-u="${index}"`);
454
+ out.push({ kind: 'use', expr: a.expr, index });
455
+ }
380
456
  else if (a.kind === 'prop' && a.name === 'engine') {
381
457
  if (!stateful)
382
458
  fail('[engine] needs a <script> (an island): the forms engine runs in the browser', a.start);
@@ -445,14 +521,31 @@ export function lower(parsed, file, source, options = {}) {
445
521
  imports: parsed.imports,
446
522
  script: parsed.script ? split.body : undefined,
447
523
  scriptImports: split.imports.map((imp) => imp.text),
524
+ ...(server ? { server } : {}),
448
525
  dataImports: parsed.dataImports,
449
526
  signals,
450
527
  stateful,
451
528
  nodes,
452
529
  events,
530
+ sends: parsed.events.length > 0,
531
+ contexts: parsed.contexts,
532
+ provides,
453
533
  warnings,
454
534
  };
455
535
  }
536
+ function slotParamsCheck(params, file, source, at) {
537
+ const bad = () => { throw new ClarusError('a fill names what its slot passes like a function parameter: @slot(\'row\', { item }) or @slot(\'row\', props)', file, source, at); };
538
+ try {
539
+ const node = parseExpressionAt(`(${params}) => 0`, 0, { ecmaVersion: 'latest' });
540
+ if (node.type !== 'ArrowFunctionExpression' || node.params?.length !== 1 || node.end !== params.length + 7)
541
+ bad();
542
+ }
543
+ catch (err) {
544
+ if (err instanceof ClarusError)
545
+ throw err;
546
+ bad();
547
+ }
548
+ }
456
549
  function pathSegments(path) {
457
550
  const root = /^[A-Za-z_$][\w$]*/.exec(path)?.[0];
458
551
  if (!root)
@@ -1,5 +1,5 @@
1
1
  import { ClarusError } from './errors.js';
2
- import { importNames, parse } from './parse.js';
2
+ import { awaitLists, importNames, parse } from './parse.js';
3
3
  const FIELDS = new Set(['input', 'select', 'textarea', 'meter', 'output', 'progress']);
4
4
  const IGNORE_RE = /\{\{--\s*clarusjs-ignore\b([\w\s,-]*?)\s*--\}\}/g;
5
5
  function* elements(nodes) {
@@ -18,6 +18,9 @@ function* elements(nodes) {
18
18
  }
19
19
  else if (n.type === 'fill')
20
20
  yield* elements(n.children);
21
+ else if (n.type === 'await')
22
+ for (const kids of awaitLists(n))
23
+ yield* elements(kids);
21
24
  }
22
25
  }
23
26
  function* expressions(nodes) {
@@ -52,6 +55,11 @@ function* expressions(nodes) {
52
55
  }
53
56
  else if (n.type === 'fill')
54
57
  yield* expressions(n.children);
58
+ else if (n.type === 'await') {
59
+ yield n.expr;
60
+ for (const kids of awaitLists(n))
61
+ yield* expressions(kids);
62
+ }
55
63
  }
56
64
  }
57
65
  const has = (el, name) => el.attrs.some((a) => a.name === name);
@@ -66,6 +74,8 @@ function named(nodes, components) {
66
74
  return n.branches.some((b) => named(b.children, components));
67
75
  if (n.type === 'for')
68
76
  return named(n.children, components);
77
+ if (n.type === 'await')
78
+ return awaitLists(n).some((kids) => named(kids, components));
69
79
  if (n.type !== 'element')
70
80
  return false;
71
81
  if (components.has(n.tag) || n.tag === 'slot' || n.tag === 'title' || labelled(n))
@@ -135,6 +145,7 @@ export function lint(source, file, config = {}, extra = []) {
135
145
  const corpus = [
136
146
  ...expressions(parsed.nodes),
137
147
  parsed.script?.code ?? '',
148
+ parsed.serverScript?.code ?? '',
138
149
  ...parsed.inputs.flatMap((i) => [i.type, i.default ?? '']),
139
150
  ...parsed.types.map((t) => t.type),
140
151
  ].join('\n');
@@ -32,6 +32,16 @@ export type Attr = {
32
32
  })[];
33
33
  start: number;
34
34
  };
35
+ /** An @await's lists of children: pending, then @then's and @catch's (those it has). */
36
+ export declare const awaitLists: (n: Extract<TemplateNode, {
37
+ type: 'await';
38
+ }>) => TemplateNode[][];
39
+ /** An @await's @then or @catch: the name it binds, and its content. */
40
+ export type AwaitBranch = {
41
+ name: string;
42
+ nameStart: number;
43
+ children: TemplateNode[];
44
+ };
35
45
  /**
36
46
  * A node of a template's syntax tree: an element, text, a `{{ }}` hole, an `@if`, an `@for`, a slot fill…
37
47
  * @see https://clarusjs.com/reference/compiler#parse
@@ -63,9 +73,19 @@ export type TemplateNode = {
63
73
  children: TemplateNode[];
64
74
  }[];
65
75
  start: number;
76
+ } | {
77
+ type: 'await';
78
+ expr: string;
79
+ exprStart: number;
80
+ pending: TemplateNode[];
81
+ then: AwaitBranch | null;
82
+ catch: AwaitBranch | null;
83
+ start: number;
66
84
  } | {
67
85
  type: 'fill';
68
86
  name: string;
87
+ params?: string;
88
+ paramsStart?: number;
69
89
  children: TemplateNode[];
70
90
  start: number;
71
91
  } | {
@@ -116,6 +136,17 @@ export type ImportDecl = {
116
136
  from: string;
117
137
  start: number;
118
138
  };
139
+ /**
140
+ * An `@event` declaration (#442): the event's name and the type of the value it sends, with their offsets.
141
+ * @see https://clarusjs.com/guide/events#from-a-child-island-to-its-parent
142
+ */
143
+ export type EventDecl = {
144
+ name: string;
145
+ type: string;
146
+ start: number;
147
+ nameStart: number;
148
+ typeStart: number;
149
+ };
119
150
  export type TypeDecl = {
120
151
  kind: 'type' | 'interface';
121
152
  name: string;
@@ -131,6 +162,10 @@ export type TypeDecl = {
131
162
  */
132
163
  export type ParsedFile = {
133
164
  inputs: InputDecl[];
165
+ /** `@event change: string` (#442): what the component sends its parent, and its value's type ('void' when none). */
166
+ events: EventDecl[];
167
+ /** `@context tabs: Type` (#465): values a component around this one provides; same shape as an @input. */
168
+ contexts: InputDecl[];
134
169
  imports: ImportDecl[];
135
170
  typeImports: TypeImport[];
136
171
  types: TypeDecl[];
@@ -139,6 +174,12 @@ export type ParsedFile = {
139
174
  code: string;
140
175
  start: number;
141
176
  };
177
+ /** <script server> (#430): runs at render on the server only. `tag` = offset of `<script`. */
178
+ serverScript?: {
179
+ code: string;
180
+ start: number;
181
+ tag: number;
182
+ };
142
183
  styles: {
143
184
  css: string;
144
185
  mode: 'scoped' | 'global' | 'plain';
@@ -149,6 +190,9 @@ export type ParsedFile = {
149
190
  from: string;
150
191
  start: number;
151
192
  }[];
193
+ /** `@layout none` (#456): the page renders without its folder and config layouts. `layoutStart`: where it is. */
194
+ layout?: 'none';
195
+ layoutStart?: number;
152
196
  nodes: TemplateNode[];
153
197
  };
154
198
  /** The names a @for row has besides its item: $index, $count, $first, $last, $even, $odd. */
@@ -1,4 +1,5 @@
1
1
  import { ClarusError } from './errors.js';
2
+ export const awaitLists = (n) => [n.pending, ...(n.then ? [n.then.children] : []), ...(n.catch ? [n.catch.children] : [])];
2
3
  export const FOR_IMPLICIT = ['$index', '$count', '$first', '$last', '$even', '$odd'];
3
4
  const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
4
5
  const DATA_IMPORT_RE = /^@import\s+(\{[^}]*\})\s+from\s+(['"])(.+?)\2\s*$/d;
@@ -7,7 +8,7 @@ const IMPORT_RE = /^@import\s+([A-Za-z_$][\w-]*)\s+from\s+(['"])(.+?)\2\s*$/;
7
8
  const CSS_IMPORT_RE = /^@import\s+(['"])(.+?)\1\s*$/;
8
9
  const typeNames = (clause) => clause.startsWith('{') ? clause.slice(1, -1).split(',').map((p) => p.trim().replace(/^type\s+/, '').split(/\s+as\s+/).pop().trim()).filter(Boolean) : [clause.trim()];
9
10
  export function parse(source, file) {
10
- const out = { inputs: [], imports: [], typeImports: [], types: [], dataImports: [], styles: [], cssImports: [], nodes: [] };
11
+ const out = { inputs: [], events: [], contexts: [], imports: [], typeImports: [], types: [], dataImports: [], styles: [], cssImports: [], nodes: [] };
11
12
  let i = 0;
12
13
  const fail = (text, at) => { throw new ClarusError(text, file, source, at); };
13
14
  const atLineStart = (at) => /^[ \t]*$/.test(source.slice(source.lastIndexOf('\n', at - 1) + 1, at));
@@ -16,8 +17,8 @@ export function parse(source, file) {
16
17
  const lineStart = i + (source.slice(i, end).length - source.slice(i, end).trimStart().length);
17
18
  const line = source.slice(i, end).trim();
18
19
  let m;
19
- if (/^@(input|model)\s/.test(line)) {
20
- return inputDecl(lineStart, line.startsWith('@model'));
20
+ if (/^@(input|model|context)\s/.test(line)) {
21
+ return inputDecl(lineStart, line.startsWith('@model'), line.startsWith('@context'));
21
22
  }
22
23
  else if (/^@(type|interface)\s/.test(line)) {
23
24
  return typeDecl(lineStart);
@@ -39,6 +40,20 @@ export function parse(source, file) {
39
40
  fail(`@import without a name only takes a stylesheet (.css): "${m[2]}"`, i);
40
41
  out.cssImports.push({ from: m[2], start: i });
41
42
  }
43
+ else if (/^@event(\s|$)/.test(line)) {
44
+ const d = /^@event\s+([A-Za-z_$][\w$-]*)\s*(?::\s*(\S[\s\S]*?))?\s*$/.exec(line);
45
+ if (!d)
46
+ fail('@event takes a name and the type of its value: @event change: string (or @event close for none)', i);
47
+ const nameStart = lineStart + line.indexOf(d[1], 6);
48
+ const typeStart = d[2] ? lineStart + line.lastIndexOf(d[2]) : nameStart;
49
+ out.events.push({ name: d[1], type: d[2] ?? 'void', start: i, nameStart, typeStart });
50
+ }
51
+ else if ((m = /^@layout(?:\s+(\S+))?\s*$/.exec(line))) {
52
+ if (m[1] !== 'none')
53
+ fail('@layout only takes none: @layout none renders the page without its folder and config layouts', i);
54
+ out.layout = 'none';
55
+ out.layoutStart = i;
56
+ }
42
57
  else
43
58
  fail(`unknown or malformed directive "${line.split(/\s/)[0]}"`, i);
44
59
  i = end;
@@ -64,8 +79,8 @@ export function parse(source, file) {
64
79
  }
65
80
  return source.length;
66
81
  }
67
- function inputDecl(lineStart, model) {
68
- const directive = model ? '@model' : '@input';
82
+ function inputDecl(lineStart, model, context = false) {
83
+ const directive = context ? '@context' : model ? '@model' : '@input';
69
84
  const malformed = () => fail(`unknown or malformed directive "${directive}"`, i);
70
85
  let pos = lineStart + directive.length;
71
86
  while (source[pos] === ' ' || source[pos] === '\t')
@@ -116,7 +131,8 @@ export function parse(source, file) {
116
131
  malformed();
117
132
  fallback = { default: value, defaultStart: at };
118
133
  }
119
- out.inputs.push({ name, type, start: i, nameStart, typeStart, ...fallback, ...(model ? { model: true } : {}) });
134
+ ;
135
+ (context ? out.contexts : out.inputs).push({ name, type, start: i, nameStart, typeStart, ...fallback, ...(model ? { model: true } : {}) });
120
136
  i = end;
121
137
  }
122
138
  function typeDecl(lineStart) {
@@ -285,6 +301,49 @@ export function parse(source, file) {
285
301
  }
286
302
  return fail(`unclosed ( after ${keyword}`, open);
287
303
  }
304
+ function awaitBlock() {
305
+ const start = i;
306
+ i += 6;
307
+ const { cond: expr, condStart: exprStart } = condition('@await');
308
+ const open = () => {
309
+ while (/\s/.test(source[i] ?? ''))
310
+ i++;
311
+ if (source[i] !== '{')
312
+ fail('expected { to open the block', i);
313
+ i++;
314
+ };
315
+ open();
316
+ const pending = children({ tag: '@await', start, block: true });
317
+ let then = null;
318
+ let caught = null;
319
+ for (;;) {
320
+ const save = i;
321
+ while (/\s/.test(source[i] ?? ''))
322
+ i++;
323
+ const kw = /^@(then|catch)[\s(]/.exec(source.slice(i, i + 7))?.[1];
324
+ if (!kw) {
325
+ i = save;
326
+ break;
327
+ }
328
+ const at = i;
329
+ if (kw === 'then' && caught)
330
+ fail('@then comes before @catch', at);
331
+ if ((kw === 'then' && then) || (kw === 'catch' && caught))
332
+ fail(`only one @${kw} per @await`, at);
333
+ i += kw.length + 1;
334
+ const { cond: name, condStart: nameStart } = condition(`@${kw}`);
335
+ const what = kw === 'then' ? 'value' : 'error';
336
+ if (!/^[A-Za-z_$][\w$]*$/.test(name))
337
+ fail(`@${kw} takes a name for the ${what}: @${kw} (${what})`, nameStart);
338
+ open();
339
+ const branch = { name, nameStart, children: children({ tag: `@${kw}`, start: at, block: true }) };
340
+ if (kw === 'then')
341
+ then = branch;
342
+ else
343
+ caught = branch;
344
+ }
345
+ return { type: 'await', expr, exprStart, pending, then, catch: caught, start };
346
+ }
288
347
  function ifBlock() {
289
348
  const start = i;
290
349
  i += 3;
@@ -406,16 +465,18 @@ export function parse(source, file) {
406
465
  function fillBlock() {
407
466
  const start = i;
408
467
  i += 5;
409
- const { cond } = condition('@slot');
410
- const m = /^(['"])([\w-]+)\1$/.exec(cond);
468
+ const { cond, condStart } = condition('@slot');
469
+ const m = /^(['"])([\w-]+)\1\s*(?:,\s*([\s\S]*\S))?\s*$/.exec(cond);
411
470
  if (!m)
412
- fail(`@slot needs a quoted name, like @slot('aside')`, start);
471
+ fail(`@slot needs a quoted name, like @slot('aside'), or @slot('row', { item }) for a slot that passes data`, start);
472
+ const params = m[3];
473
+ const paramsStart = params === undefined ? undefined : condStart + cond.indexOf(params, m[1].length * 2 + m[2].length);
413
474
  while (/\s/.test(source[i] ?? ''))
414
475
  i++;
415
476
  if (source[i] !== '{')
416
477
  fail('expected { to open the block', i);
417
478
  i++;
418
- return { type: 'fill', name: m[2], children: children({ tag: '@slot', start, block: true }), start };
479
+ return { type: 'fill', name: m[2], ...(params !== undefined ? { params, paramsStart } : {}), children: children({ tag: '@slot', start, block: true }), start };
419
480
  }
420
481
  function children(parent) {
421
482
  const nodes = [];
@@ -447,6 +508,14 @@ export function parse(source, file) {
447
508
  nodes.push(ifBlock());
448
509
  textStart = i;
449
510
  }
511
+ else if (/^@await[\s(]/.test(source.slice(i, i + 7))) {
512
+ flush();
513
+ nodes.push(awaitBlock());
514
+ textStart = i;
515
+ }
516
+ else if (/^@(then|catch)[\s(]/.test(source.slice(i, i + 7))) {
517
+ fail(`${/^@\w+/.exec(source.slice(i))[0]} without @await before it`, i);
518
+ }
450
519
  else if (/^@for[\s(]/.test(source.slice(i, i + 5))) {
451
520
  flush();
452
521
  nodes.push(forBlock());
@@ -525,6 +594,20 @@ export function parse(source, file) {
525
594
  nodes.push({ type: 'element', tag, attrs: list, children: kids, start });
526
595
  i = selfClosing ? i : end + '</script>'.length;
527
596
  }
597
+ else if (tag === 'script' && list.some((a) => a.name === 'server')) {
598
+ if (parent)
599
+ fail('<script server> must be at the top level (it runs once per render, before the template)', start);
600
+ if (out.serverScript)
601
+ fail('only one <script server> block is allowed', start);
602
+ const other = list.find((a) => a.name !== 'server');
603
+ if (other)
604
+ fail('<script server> takes no other attributes', other.start);
605
+ const end = source.indexOf('</script>', i);
606
+ if (end === -1)
607
+ fail('unclosed <script server>', start);
608
+ out.serverScript = { code: source.slice(i, end), start: i, tag: start };
609
+ i = end + '</script>'.length;
610
+ }
528
611
  else if (tag === 'script') {
529
612
  if (parent)
530
613
  fail('<script> must be at the top level (a component script); add `inline` for a script that runs where it stands', start);
@@ -15,13 +15,22 @@ export declare function scriptNames(code: string): Set<string>;
15
15
  * Island scripts are bundled for the browser, so `node:` imports are a build error.
16
16
  */
17
17
  /** Import statements (text and offset in `code`), and the body with them blanked out. */
18
- export declare function splitImports(code: string, file: string, source: string, offset: number): {
18
+ export declare function splitImports(code: string, file: string, source: string, offset: number, server?: boolean): {
19
19
  imports: {
20
20
  text: string;
21
21
  start: number;
22
22
  }[];
23
23
  body: string;
24
24
  };
25
+ /**
26
+ * A `<script server>` (#430): its imports (hoisted to the server module, `node:` allowed: it never reaches a browser),
27
+ * the rest (run at the top of render), and whether it awaits at the top level (then render is async).
28
+ */
29
+ export declare function serverScriptParts(code: string, file: string, source: string, offset: number): {
30
+ imports: string[];
31
+ body: string;
32
+ awaits: boolean;
33
+ };
25
34
  /**
26
35
  * Where type annotations go for type checking: `: any` after the untyped parameters of the script's own functions
27
36
  * (declarations, `const f = (x) => …`, class methods) and of callbacks passed straight to them (`record((p) => …)`).
@@ -44,6 +53,17 @@ export declare function rewriteClient(code: string, signals: Signals, options?:
44
53
  forms?: string;
45
54
  }): string;
46
55
  export declare function rewriteClientExpr(expr: string, signals: Signals): string;
56
+ /**
57
+ * provide(key, value) calls (#465): the key must be a string literal naming a value; provide itself is reserved (a
58
+ * script may not declare or import its own). True when the script provides anything. Shared by build and check.
59
+ */
60
+ export declare function providesIn(split: {
61
+ imports: {
62
+ text: string;
63
+ start: number;
64
+ }[];
65
+ body: string;
66
+ }, file: string, source: string, offset: number): boolean;
47
67
  export declare function rewriteServer(code: string): string;
48
68
  export declare function referencesSignal(expr: string, signals: Signals): boolean;
49
69
  /**