orvyn-lang 0.1.1 → 0.3.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 (74) hide show
  1. package/GUIDE.md +149 -0
  2. package/LANGUAGE.md +877 -24
  3. package/README.md +227 -131
  4. package/brand/orvyn-sunset-animated.svg +15 -0
  5. package/package.json +3 -1
  6. package/src/cli/orvyn.js +216 -489
  7. package/src/core/signal.js +104 -6
  8. package/src/devtools/runtime.js +25 -1
  9. package/src/lang/a11y.js +102 -0
  10. package/src/lang/auth.js +239 -0
  11. package/src/lang/bundle-native.js +10 -6
  12. package/src/lang/codegen.js +498 -64
  13. package/src/lang/device.js +41 -0
  14. package/src/lang/doctor.js +60 -0
  15. package/src/lang/env.js +27 -0
  16. package/src/lang/errors.js +513 -0
  17. package/src/lang/form.js +160 -0
  18. package/src/lang/index.js +2 -1
  19. package/src/lang/lexer.js +2 -0
  20. package/src/lang/list.js +44 -0
  21. package/src/lang/native/android/MainActivity.kt +43 -4
  22. package/src/lang/native/android/OrvynDevice.kt +163 -0
  23. package/src/lang/native/android/OrvynEngine.kt +154 -7
  24. package/src/lang/native/android/OrvynRenderer.kt +519 -40
  25. package/src/lang/native/android.js +74 -11
  26. package/src/lang/native/build.js +130 -60
  27. package/src/lang/native/config.js +108 -0
  28. package/src/lang/native/ios/OrvynApp.swift +6 -0
  29. package/src/lang/native/ios/OrvynEngine.swift +268 -4
  30. package/src/lang/native/ios/OrvynViews.swift +429 -31
  31. package/src/lang/native/ios.js +75 -2
  32. package/src/lang/native-runtime.js +423 -57
  33. package/src/lang/page.js +52 -0
  34. package/src/lang/parser.js +243 -15
  35. package/src/lang/prerender.js +300 -0
  36. package/src/lang/read-import.js +11 -0
  37. package/src/lang/router.js +266 -0
  38. package/src/lang/runtime-shared.js +820 -10
  39. package/src/lang/runtime.js +375 -52
  40. package/src/lang/select.js +13 -0
  41. package/src/lang/server-code.js +233 -0
  42. package/src/lang/server-export.js +78 -0
  43. package/src/lang/server-libs.js +53 -0
  44. package/src/lang/server.js +409 -0
  45. package/src/lang/test-runner.js +134 -0
  46. package/src/lang/types.js +312 -0
  47. package/src/lang/validation.js +55 -0
  48. package/src/lang/vite-plugin.js +82 -3
  49. package/src/lang/web-overlay.js +578 -0
  50. package/src/lang/widgets.js +94 -0
  51. package/src/lang/words.js +38 -0
  52. package/src/runtime/mount.js +116 -27
  53. package/src/runtime/patch.js +90 -11
  54. package/src/runtime/style.js +11 -1
  55. package/src/styling/fluid.js +91 -4
  56. package/src/styling/spec.js +306 -0
  57. package/src/core/context.js +0 -19
  58. package/src/core/lifecycle.js +0 -8
  59. package/src/core/resource.js +0 -27
  60. package/src/core/router.js +0 -20
  61. package/src/core/theme.js +0 -10
  62. package/src/devtools/devicePreview/PreviewFrame.js +0 -214
  63. package/src/devtools/devicePreview/index.js +0 -6
  64. package/src/devtools/overlay.js +0 -105
  65. package/src/runtime/createRenderer.js +0 -22
  66. package/src/runtime/h.js +0 -93
  67. package/src/runtime/hydrate.js +0 -59
  68. package/src/runtime/jsx-dev-runtime.js +0 -7
  69. package/src/runtime/jsx-runtime.js +0 -13
  70. package/src/runtime/partialHydration.js +0 -154
  71. package/src/runtime/platform.js +0 -135
  72. package/src/runtime/renderToStream.js +0 -127
  73. package/src/runtime/renderToString.js +0 -121
  74. package/src/runtime/resume.js +0 -62
@@ -16,6 +16,7 @@ const BINARY_PRECEDENCE = {
16
16
  "%": 6
17
17
  };
18
18
  const ASSIGN_OPS = /* @__PURE__ */ new Set(["=", "+=", "-=", "*=", "/="]);
19
+ const AUTH_KEYS = ["login", "home", "logout", "refresh", "api", "keepSaved", "onLogout", "header", "scheme"];
19
20
  class Parser {
20
21
  tokens;
21
22
  pos = 0;
@@ -99,21 +100,72 @@ class Parser {
99
100
  }
100
101
  parseDecl() {
101
102
  const token = this.peek();
102
- const saved = token.type === "ident" && token.value === "saved" && this.is("state", 1);
103
- if (saved) this.next();
104
- if (this.eat("state")) {
103
+ const saved = token.type === "ident" && token.value === "saved" && (this.is("state", 1) || this.is("(", 1));
104
+ let savedVersion;
105
+ let savedMigrate;
106
+ if (saved) {
107
+ this.next();
108
+ if (this.eat("(")) {
109
+ this.groupDepth++;
110
+ const verToken = this.peek();
111
+ savedVersion = this.parseExpr();
112
+ if (savedVersion.kind !== "Number" || !Number.isInteger(savedVersion.value) || savedVersion.value < 1) {
113
+ this.fail("saved version must be a positive whole number, like saved(2) state ...", verToken);
114
+ }
115
+ if (this.eat(",")) savedMigrate = this.parseExpr();
116
+ this.expect(")", "to close saved(version)");
117
+ this.groupDepth--;
118
+ }
119
+ }
120
+ if (token.type === "ident" && token.value === "type" && this.peek(1).type === "ident" && this.is("{", 2)) {
121
+ this.next();
122
+ const name = this.next();
123
+ if (!/^[A-Z]/.test(name.value)) this.fail(`Type names start with a capital letter, like "${capitalize(name.value)}"`, name);
124
+ this.next();
125
+ const fields = [];
126
+ this.skipNewlines();
127
+ while (!this.is("}")) {
128
+ const field = this.peek();
129
+ if (field.type === "eof") this.fail('Missing "}" to close the type', field);
130
+ if (field.type !== "ident" && field.type !== "keyword") this.fail("Expected a field, like name: text", field);
131
+ this.next();
132
+ this.expect(":", `after "${field.value}"`);
133
+ const ref = this.parseTypeRef();
134
+ const optional = this.eat("?");
135
+ if (fields.some((f) => f.name === field.value)) this.fail(`"${field.value}" is listed twice`, field);
136
+ fields.push({ name: field.value, type: ref, optional, line: field.line, col: field.col });
137
+ this.eat(",");
138
+ this.skipNewlines();
139
+ }
140
+ this.next();
141
+ this.endOfLine("after type");
142
+ return { kind: "Type", name: name.value, fields, line: token.line, col: token.col };
143
+ }
144
+ if (saved && this.expect("state", 'after "saved(...)"') || this.eat("state")) {
105
145
  const name = this.expectIdent('after "state"');
146
+ const typed = this.optionalType();
106
147
  this.expect("=", `after "state ${name.value}"`);
107
148
  const init = this.parseExpr();
108
149
  this.endOfLine("after state declaration");
109
- return { kind: "State", name: name.value, init, saved, line: token.line, col: token.col };
150
+ return {
151
+ kind: "State",
152
+ name: name.value,
153
+ ...typed,
154
+ init,
155
+ saved,
156
+ ...savedVersion ? { savedVersion } : {},
157
+ ...savedMigrate ? { savedMigrate } : {},
158
+ line: token.line,
159
+ col: token.col
160
+ };
110
161
  }
111
162
  if (this.eat("let")) {
112
163
  const name = this.expectIdent('after "let"');
164
+ const typed = this.optionalType();
113
165
  this.expect("=", `after "let ${name.value}"`);
114
166
  const init = this.parseExpr();
115
167
  this.endOfLine("after let declaration");
116
- return { kind: "Const", name: name.value, init, line: token.line, col: token.col };
168
+ return { kind: "Const", name: name.value, ...typed, init, line: token.line, col: token.col };
117
169
  }
118
170
  if (this.eat("use")) {
119
171
  const names = [];
@@ -129,15 +181,53 @@ class Parser {
129
181
  this.endOfLine("after use");
130
182
  return { kind: "Use", names, path: path.value, line: token.line, col: token.col };
131
183
  }
184
+ if (token.type === "ident" && token.value === "auth" && this.is("{", 1)) {
185
+ this.next();
186
+ this.next();
187
+ this.groupDepth++;
188
+ const entries = [];
189
+ const seen = /* @__PURE__ */ new Set();
190
+ while (!this.is("}")) {
191
+ const key = this.peek();
192
+ if (key.type === "eof") this.fail('Missing "}" to close auth { ... }', key);
193
+ if (key.type !== "ident" || !AUTH_KEYS.includes(key.value)) {
194
+ this.fail(`"${key.value}" is not an auth setting. Use: ${AUTH_KEYS.join(", ")}`, key);
195
+ }
196
+ if (seen.has(key.value)) this.fail(`"${key.value}" is set twice in auth { ... }`, key);
197
+ seen.add(key.value);
198
+ this.next();
199
+ this.expect(":", `after "${key.value}", like ${key.value}: ...`);
200
+ entries.push({ key: key.value, value: this.parseExpr() });
201
+ this.eat(",");
202
+ }
203
+ this.expect("}", "to close auth { ... }");
204
+ this.groupDepth--;
205
+ this.endOfLine("after auth { ... }");
206
+ const pos = { line: token.line, col: token.col };
207
+ const call = {
208
+ kind: "Call",
209
+ callee: { kind: "Member", object: { kind: "Ident", name: "auth", ...pos }, property: "setup", ...pos },
210
+ args: [{ kind: "Object", entries, ...pos }],
211
+ ...pos
212
+ };
213
+ return { kind: "Start", body: [{ kind: "ExprStmt", expr: call, ...pos }], ...pos };
214
+ }
215
+ if (token.type === "ident" && token.value === "test" && this.peek(1).type === "string") {
216
+ this.next();
217
+ const name = this.next();
218
+ return { kind: "Test", name: name.value, body: this.parseBlock(), line: token.line, col: token.col };
219
+ }
132
220
  if (this.eat("start")) {
133
221
  const body = this.parseBlock();
134
222
  return { kind: "Start", body, line: token.line, col: token.col };
135
223
  }
136
224
  if (this.eat("fn")) {
137
225
  const name = this.expectIdent('after "fn"');
226
+ this.paramTypes = {};
138
227
  const params = this.parseParams();
228
+ const paramTypes = this.paramTypes;
139
229
  const body = this.parseBlock();
140
- return { kind: "Fn", name: name.value, params, body, line: token.line, col: token.col };
230
+ return { kind: "Fn", name: name.value, params, ...Object.keys(paramTypes).length ? { paramTypes } : {}, body, line: token.line, col: token.col };
141
231
  }
142
232
  if (this.is("screen") || this.is("component")) {
143
233
  const type = this.next().value;
@@ -145,21 +235,53 @@ class Parser {
145
235
  if (!/^[A-Z]/.test(name.value)) {
146
236
  this.fail(`${type} names must start with a capital letter, like "${capitalize(name.value)}"`, name);
147
237
  }
238
+ this.paramTypes = {};
148
239
  const params = this.is("(") ? this.parseParams() : [];
149
- const body = this.parseViewBlock();
150
- return { kind: "Screen", type, name: name.value, params, body, line: token.line, col: token.col };
240
+ const paramTypes = this.paramTypes;
241
+ let requiresAuth = false;
242
+ const req = this.peek();
243
+ if (req.type === "ident" && req.value === "requires") {
244
+ this.next();
245
+ if (type !== "screen") this.fail('Only screens can use "requires auth", not components', req);
246
+ const what = this.peek();
247
+ if (what.type !== "ident" || what.value !== "auth") this.fail('Write "requires auth", like: screen Profile requires auth { ... }', what);
248
+ this.next();
249
+ requiresAuth = true;
250
+ }
251
+ const { locals, nodes, page, prebuild } = this.parseScreenBody();
252
+ if (prebuild && (type !== "screen" || params.length !== 1)) {
253
+ this.fail('"prebuild" belongs in a screen with one value, like: screen Product(id) { prebuild: [1, 2] ... }', name);
254
+ }
255
+ if (page && type !== "screen") this.fail('Only screens can have "page", not components', name);
256
+ return { kind: "Screen", ...page ? { page } : {}, ...prebuild ? { prebuild } : {}, type, name: name.value, params, ...Object.keys(paramTypes).length ? { paramTypes } : {}, ...requiresAuth ? { requiresAuth } : {}, ...locals.length ? { locals } : {}, body: nodes, line: token.line, col: token.col };
151
257
  }
152
258
  this.fail(
153
259
  `Unexpected ${describe(token)}. A file can only contain state, let, fn, screen, component, start or use`,
154
260
  token
155
261
  );
156
262
  }
263
+ paramTypes = {};
264
+ // text, number, yesno, Product, list of Product
265
+ parseTypeRef() {
266
+ const name = this.expectIdent("for a type, like text or Product");
267
+ if (name.value === "list" && this.peek().type === "ident" && this.peek().value === "of") {
268
+ this.next();
269
+ return { list: this.parseTypeRef() };
270
+ }
271
+ return { name: name.value };
272
+ }
273
+ // the ": Product" part of `state cart: Product = ...`, when there is one
274
+ optionalType() {
275
+ return this.eat(":") ? { type: this.parseTypeRef() } : {};
276
+ }
157
277
  parseParams() {
158
278
  this.expect("(", "to start the parameter list");
159
279
  this.groupDepth++;
160
280
  const params = [];
161
281
  while (!this.is(")")) {
162
- params.push(this.expectIdent("for a parameter").value);
282
+ const name = this.expectIdent("for a parameter").value;
283
+ params.push(name);
284
+ if (this.eat(":")) this.paramTypes[name] = this.parseTypeRef();
163
285
  if (!this.eat(",")) break;
164
286
  }
165
287
  this.expect(")", "to close the parameter list");
@@ -182,10 +304,16 @@ class Parser {
182
304
  }
183
305
  parseStatement() {
184
306
  const token = this.peek();
307
+ if (token.type === "ident" && token.value === "fail" && this.peek(1).type === "string") {
308
+ this.next();
309
+ const pos = { line: token.line, col: token.col };
310
+ return { kind: "ExprStmt", expr: { kind: "Call", callee: { kind: "Ident", name: "fail", ...pos }, args: [this.parseExpr()], ...pos }, ...pos };
311
+ }
185
312
  if (this.eat("let")) {
186
313
  const name = this.expectIdent('after "let"');
314
+ const typed = this.optionalType();
187
315
  this.expect("=", `after "let ${name.value}"`);
188
- return { kind: "Let", name: name.value, init: this.parseExpr(), line: token.line, col: token.col };
316
+ return { kind: "Let", name: name.value, ...typed, init: this.parseExpr(), line: token.line, col: token.col };
189
317
  }
190
318
  if (this.eat("if")) {
191
319
  const cond = this.parseExpr();
@@ -212,6 +340,14 @@ class Parser {
212
340
  const value = end.type === "newline" || this.is("}") ? null : this.parseExpr();
213
341
  return { kind: "Return", value, line: token.line, col: token.col };
214
342
  }
343
+ if (this.eat("try")) {
344
+ const body = this.parseBlock();
345
+ this.expect("catch", 'after "try { ... }"');
346
+ let catchName = null;
347
+ if (this.peek().type === "ident") catchName = this.next().value;
348
+ const catchBody = this.parseBlock();
349
+ return { kind: "Try", body, catchName, catchBody, line: token.line, col: token.col };
350
+ }
215
351
  const expr = this.parseExpr();
216
352
  const opToken = this.peek();
217
353
  if (opToken.type === "punct" && ASSIGN_OPS.has(opToken.value)) {
@@ -225,12 +361,86 @@ class Parser {
225
361
  return { kind: "ExprStmt", expr, line: token.line, col: token.col };
226
362
  }
227
363
  // --- view ----------------------------------------------------------------
364
+ parseScreenBody() {
365
+ let page;
366
+ let prebuild;
367
+ this.expect("{", "to start the view");
368
+ const locals = [];
369
+ const nodes = [];
370
+ this.skipNewlines();
371
+ while (!this.is("}")) {
372
+ if (this.peek().type === "eof") this.fail('Missing "}" to close the view', this.peek());
373
+ const token = this.peek();
374
+ if (token.type === "ident" && token.value === "prebuild" && this.is(":", 1)) {
375
+ if (prebuild) this.fail('A screen can have only one "prebuild" line', token);
376
+ this.next();
377
+ this.next();
378
+ prebuild = this.parseExpr();
379
+ this.endOfLine("after prebuild");
380
+ this.skipNewlines();
381
+ continue;
382
+ }
383
+ if (token.type === "ident" && token.value === "page" && this.peek(1).type === "ident" && this.is(":", 2)) {
384
+ if (page) this.fail('A screen can have only one "page" line', token);
385
+ this.next();
386
+ page = [];
387
+ do {
388
+ this.skipNewlines();
389
+ const key = this.expectIdent("in page");
390
+ if (!["title", "description", "image", "type", "author", "date", "noindex"].includes(key.value)) {
391
+ this.fail(`page has no "${key.value}". Use: title, description, image, type, author, date, noindex`, key);
392
+ }
393
+ this.expect(":", `after "${key.value}"`);
394
+ page.push({ key: key.value, value: { kind: "Expr", expr: this.parseExpr() }, line: key.line, col: key.col });
395
+ } while (this.eat(","));
396
+ this.endOfLine("after page");
397
+ this.skipNewlines();
398
+ continue;
399
+ }
400
+ const saved = token.type === "ident" && token.value === "saved" && (this.is("state", 1) || this.is("(", 1));
401
+ if (saved || this.is("state") || this.is("let")) {
402
+ const kind = saved ? "saved state" : token.value;
403
+ if (saved) {
404
+ this.fail("saved state belongs at the top level of a file, not inside a component or screen. Use state without saved here", token);
405
+ }
406
+ if (nodes.length > 0) {
407
+ this.fail(`Put ${kind} at the top of the component or screen, before any elements`, token);
408
+ }
409
+ if (this.eat("state")) {
410
+ const name = this.expectIdent('after "state"');
411
+ const typed = this.optionalType();
412
+ this.expect("=", `after "state ${name.value}"`);
413
+ locals.push({ kind: "State", name: name.value, ...typed, init: this.parseExpr(), saved: false, line: token.line, col: token.col });
414
+ } else {
415
+ this.next();
416
+ const name = this.expectIdent('after "let"');
417
+ const typed = this.optionalType();
418
+ this.expect("=", `after "let ${name.value}"`);
419
+ locals.push({ kind: "Const", name: name.value, ...typed, init: this.parseExpr(), line: token.line, col: token.col });
420
+ }
421
+ this.endOfLine(`after ${kind} declaration`);
422
+ this.skipNewlines();
423
+ continue;
424
+ }
425
+ nodes.push(this.parseViewNode());
426
+ this.endOfLine("after element");
427
+ this.skipNewlines();
428
+ }
429
+ this.next();
430
+ return { locals, nodes, page, prebuild };
431
+ }
228
432
  parseViewBlock() {
229
433
  this.expect("{", "to start the view");
230
434
  const nodes = [];
231
435
  this.skipNewlines();
232
436
  while (!this.is("}")) {
233
437
  if (this.peek().type === "eof") this.fail('Missing "}" to close the view', this.peek());
438
+ const token = this.peek();
439
+ const saved = token.type === "ident" && token.value === "saved" && (this.is("state", 1) || this.is("(", 1));
440
+ if (saved || this.is("state") || this.is("let")) {
441
+ const kind = saved ? "saved state" : token.value;
442
+ this.fail(`Put ${kind} at the top of the component or screen, outside elements, if, or for`, token);
443
+ }
234
444
  nodes.push(this.parseViewNode());
235
445
  this.endOfLine("after element");
236
446
  this.skipNewlines();
@@ -253,8 +463,13 @@ class Parser {
253
463
  const name = this.expectIdent('after "for"');
254
464
  this.expect("in", `after "for ${name.value}"`);
255
465
  const iter = this.parseExpr();
466
+ let key;
467
+ if (this.peek().type === "ident" && this.peek().value === "key") {
468
+ this.next();
469
+ key = this.parseExpr();
470
+ }
256
471
  const body = this.parseViewBlock();
257
- return { kind: "ViewFor", name: name.value, iter, body, line: token.line, col: token.col };
472
+ return { kind: "ViewFor", name: name.value, iter, ...key ? { key } : {}, body, line: token.line, col: token.col };
258
473
  }
259
474
  if (token.type !== "ident" || !/^[A-Z]/.test(token.value)) {
260
475
  this.fail(
@@ -350,10 +565,19 @@ class Parser {
350
565
  this.next();
351
566
  this.groupDepth++;
352
567
  const args = [];
568
+ const named = [];
353
569
  while (!this.is(")")) {
354
- args.push(this.parseExpr());
570
+ const key = this.peek();
571
+ if ((key.type === "ident" || key.type === "keyword") && this.is(":", 1)) {
572
+ this.next();
573
+ this.next();
574
+ named.push({ key: key.value, value: this.parseExpr() });
575
+ } else {
576
+ args.push(this.parseExpr());
577
+ }
355
578
  if (!this.eat(",")) break;
356
579
  }
580
+ if (named.length) args.push({ kind: "Object", entries: named, line: token.line, col: token.col });
357
581
  this.expect(")", "to close the function call");
358
582
  this.groupDepth--;
359
583
  expr = { kind: "Call", callee: expr, args, line: token.line, col: token.col };
@@ -417,8 +641,12 @@ class Parser {
417
641
  this.fail('Expected a field name, like { name: "Asha" }', key);
418
642
  }
419
643
  this.next();
420
- this.expect(":", `after "${key.value}"`);
421
- entries.push({ key: key.value, value: this.parseExpr() });
644
+ if (key.type === "ident" && (this.is(",") || this.is("}"))) {
645
+ entries.push({ key: key.value, value: { kind: "Ident", name: key.value, line: key.line, col: key.col } });
646
+ } else {
647
+ this.expect(":", `after "${key.value}"`);
648
+ entries.push({ key: key.value, value: this.parseExpr() });
649
+ }
422
650
  if (!this.eat(",")) break;
423
651
  }
424
652
  this.expect("}", "to close the object");
@@ -484,7 +712,7 @@ class Parser {
484
712
  return raw.map((part, index) => {
485
713
  if (index % 2 === 0) return part;
486
714
  try {
487
- const inner = new Parser(tokenize(part));
715
+ const inner = new Parser(tokenize(part).map((t) => ({ ...t, line: token.line, col: token.col })));
488
716
  const expr = inner.parseExpr();
489
717
  if (inner.peek().type !== "eof") {
490
718
  inner.fail(`Unexpected ${describe(inner.peek())}`, inner.peek());
@@ -0,0 +1,300 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import { runInNewContext } from "node:vm";
5
+ import { orvynLang } from "./vite-plugin.js";
6
+ import { configFile } from "./native/config.js";
7
+ const AI_CRAWLERS = ["GPTBot", "ClaudeBot", "Google-Extended", "PerplexityBot", "CCBot", "Applebot-Extended"];
8
+ const VOID = /* @__PURE__ */ new Set(["img", "input", "br", "hr", "meta", "link"]);
9
+ const UNITLESS_TEXT = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
10
+ class Node_ {
11
+ childNodes = [];
12
+ parentNode = null;
13
+ attributes = /* @__PURE__ */ new Map();
14
+ data = "";
15
+ value = "";
16
+ disabled = false;
17
+ checked = false;
18
+ style = {
19
+ setProperty(name, value) {
20
+ this[name] = value;
21
+ },
22
+ removeProperty(name) {
23
+ delete this[name];
24
+ }
25
+ };
26
+ classList = {
27
+ add: (name) => this.setAttribute("class", [this.getAttribute("class"), name].filter(Boolean).join(" "))
28
+ };
29
+ nodeName;
30
+ constructor(nodeName) {
31
+ this.nodeName = nodeName;
32
+ }
33
+ get textContent() {
34
+ return this.nodeName === "#text" ? this.data : this.childNodes.map((n) => n.textContent).join("");
35
+ }
36
+ set textContent(value) {
37
+ if (this.nodeName === "#text") {
38
+ this.data = String(value);
39
+ return;
40
+ }
41
+ this.childNodes = [];
42
+ if (value !== "") this.appendChild(Object.assign(new Node_("#text"), { data: String(value) }));
43
+ }
44
+ appendChild(child) {
45
+ return this.insertBefore(child, null);
46
+ }
47
+ insertBefore(child, before) {
48
+ if (child.nodeName === "#fragment") {
49
+ for (const n of [...child.childNodes]) this.insertBefore(n, before);
50
+ return child;
51
+ }
52
+ child.remove();
53
+ const at = before ? this.childNodes.indexOf(before) : -1;
54
+ this.childNodes.splice(at < 0 ? this.childNodes.length : at, 0, child);
55
+ child.parentNode = this;
56
+ return child;
57
+ }
58
+ prepend(child) {
59
+ this.insertBefore(child, this.childNodes[0] ?? null);
60
+ }
61
+ replaceChild(next, old) {
62
+ this.insertBefore(next, old);
63
+ old.remove();
64
+ }
65
+ remove() {
66
+ if (!this.parentNode) return;
67
+ this.parentNode.childNodes.splice(this.parentNode.childNodes.indexOf(this), 1);
68
+ this.parentNode = null;
69
+ }
70
+ setAttribute(name, value) {
71
+ this.attributes.set(name, String(value));
72
+ }
73
+ getAttribute(name) {
74
+ return this.attributes.get(name) ?? null;
75
+ }
76
+ removeAttribute(name) {
77
+ this.attributes.delete(name);
78
+ }
79
+ addEventListener() {
80
+ }
81
+ removeEventListener() {
82
+ }
83
+ all() {
84
+ return [this, ...this.childNodes.flatMap((n) => n.all())];
85
+ }
86
+ querySelector(selector) {
87
+ const [, tag, name, value] = selector.match(/^(\w*)(?:\[([\w-]+)(?:="([^"]*)")?\])?$/) ?? [];
88
+ return this.all().slice(1).find((n) => (!tag || n.nodeName === tag) && (!name || (value === void 0 ? n.attributes.has(name) : n.getAttribute(name) === value))) ?? null;
89
+ }
90
+ toHTML() {
91
+ if (this.nodeName === "#text") return UNITLESS_TEXT(this.data);
92
+ const attributes = new Map(this.attributes);
93
+ const css = Object.entries(this.style).filter(([, v]) => typeof v === "string" && v !== "").map(([k, v]) => `${k.startsWith("--") ? k : k.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}:${v}`);
94
+ if (css.length) attributes.set("style", css.join(";"));
95
+ const open = `<${this.nodeName}${[...attributes].map(([k, v]) => ` ${k}="${UNITLESS_TEXT(v)}"`).join("")}>`;
96
+ if (VOID.has(this.nodeName)) return open;
97
+ const raw = this.nodeName === "style" || this.nodeName === "script";
98
+ const inside = raw ? this.textContent.replace(/<\//g, "<\\/") : this.childNodes.map((n) => n.toHTML()).join("");
99
+ return `${open}${inside}</${this.nodeName}>`;
100
+ }
101
+ }
102
+ function fakeDocument() {
103
+ const head = new Node_("head");
104
+ const body = new Node_("body");
105
+ return {
106
+ head,
107
+ body,
108
+ title: "",
109
+ createElement: (tag) => new Node_(tag.toLowerCase()),
110
+ createTextNode: (data) => Object.assign(new Node_("#text"), { data: String(data) }),
111
+ createDocumentFragment: () => new Node_("#fragment"),
112
+ getElementById: (id) => [head, body].flatMap((n) => n.all()).find((n) => n.getAttribute("id") === id) ?? null,
113
+ querySelector: (s) => head.querySelector(s) ?? body.querySelector(s)
114
+ };
115
+ }
116
+ async function bundle(entry, env) {
117
+ const { build } = await import("vite");
118
+ const ext = import.meta.url.endsWith(".ts") ? ".ts" : ".js";
119
+ const runtime = resolve(new URL(".", import.meta.url).pathname, `runtime${ext}`);
120
+ const result = await build({
121
+ configFile: false,
122
+ logLevel: "silent",
123
+ plugins: [orvynLang({ env, dev: false })],
124
+ resolve: { alias: [{ find: /^orvyn\/lang\/runtime$/, replacement: runtime }] },
125
+ define: { "import.meta.env.DEV": "false", "import.meta.env.PROD": "true" },
126
+ build: { write: false, minify: false, lib: { entry, formats: ["iife"], name: "OrvynApp", fileName: () => "app.js" }, rollupOptions: { output: { exports: "named" } } }
127
+ });
128
+ return (Array.isArray(result) ? result[0] : result).output.find((item) => item.type === "chunk").code;
129
+ }
130
+ function draw(code, path, site) {
131
+ const document = fakeDocument();
132
+ const location = { origin: site, pathname: path, search: "", hash: "" };
133
+ const network = { pending: 0, failed: [] };
134
+ const timers = /* @__PURE__ */ new Set();
135
+ const buildFetch = (url, init = {}) => {
136
+ const address = String(url);
137
+ const method = String(init.method ?? "GET").toUpperCase();
138
+ if (method !== "GET" || !/^https?:\/\//i.test(address)) return new Promise(() => {
139
+ });
140
+ network.pending++;
141
+ return fetch(address, { headers: init.headers, signal: AbortSignal.timeout(15e3) }).then((response) => {
142
+ if (!response.ok) network.failed.push(`${address} answered ${response.status}`);
143
+ return response;
144
+ }, (error) => {
145
+ network.failed.push(`${address}: ${error.message}`);
146
+ throw error;
147
+ }).finally(() => {
148
+ network.pending--;
149
+ });
150
+ };
151
+ const context = {
152
+ document,
153
+ location,
154
+ Node: Node_,
155
+ URL,
156
+ queueMicrotask,
157
+ performance,
158
+ window: { location, history: { pushState() {
159
+ }, replaceState() {
160
+ } }, addEventListener() {
161
+ }, removeEventListener() {
162
+ } },
163
+ fetch: buildFetch,
164
+ setTimeout: (fn, ms) => {
165
+ const t = setTimeout(fn, ms);
166
+ timers.add(t);
167
+ return t;
168
+ },
169
+ clearTimeout,
170
+ console: { log() {
171
+ }, warn() {
172
+ }, error() {
173
+ } }
174
+ };
175
+ context.globalThis = context;
176
+ runInNewContext(`${code}
177
+ globalThis.__app = OrvynApp`, context);
178
+ const target = document.createElement("div");
179
+ target.setAttribute("id", "app");
180
+ document.body.appendChild(target);
181
+ const stop = context.__app.mountApp(target);
182
+ const ready = async () => {
183
+ for (let quiet = 0; quiet < 5; ) {
184
+ await new Promise((resolve2) => setTimeout(resolve2, network.pending ? 20 : 1));
185
+ quiet = network.pending ? 0 : quiet + 1;
186
+ }
187
+ if (network.failed.length) throw new Error(`${path}: could not get the data. ${network.failed[0]}`);
188
+ };
189
+ const close = () => {
190
+ stop();
191
+ for (const timer of timers) clearTimeout(timer);
192
+ };
193
+ return { document, target, context, ready, close };
194
+ }
195
+ async function listed(name, screen) {
196
+ const values = await screen.__prebuild();
197
+ if (!Array.isArray(values)) throw new Error(`prebuild in ${name} must be a list, like [1, 2, 3]`);
198
+ return values.map((value) => {
199
+ const one = String(value && typeof value === "object" ? value[screen.__params[0]] : value);
200
+ if (!/^[A-Za-z0-9_-][A-Za-z0-9._-]*$/.test(one) || value == null) {
201
+ throw new Error(`prebuild in ${name}: "${one}" can't be part of an address. Use letters, numbers, - and _`);
202
+ }
203
+ return `/${name.toLowerCase()}/${one}`;
204
+ });
205
+ }
206
+ async function renderPages(entry, options = {}) {
207
+ const code = await bundle(resolve(entry), options.env);
208
+ const site = (options.site ?? "").replace(/\/$/, "");
209
+ const first = draw(code, "/", site);
210
+ const screens = first.context.__app.screens;
211
+ const home = screens.App ?? Object.entries(screens).find(([name]) => !["NotFound", "ErrorPage"].includes(name))?.[1];
212
+ const paths = [];
213
+ try {
214
+ for (const [name, screen] of Object.entries(screens)) {
215
+ if (["NotFound", "ErrorPage"].includes(name) || screen.__requiresAuth) continue;
216
+ if (screen.__prebuild) paths.push(...await listed(name, screen));
217
+ else if (!screen.__params?.length) paths.push(screen === home ? "/" : `/${name.toLowerCase()}`);
218
+ }
219
+ } finally {
220
+ first.close();
221
+ }
222
+ if (screens.NotFound) paths.push("/404");
223
+ const pages = [];
224
+ for (const path of paths) {
225
+ const { document, target, ready, close } = draw(code, path, site);
226
+ try {
227
+ await ready();
228
+ const questions = target.all().filter((n) => n.getAttribute("data-orvyn-question") !== null).map((n) => ({
229
+ "@type": "Question",
230
+ name: n.getAttribute("data-orvyn-question"),
231
+ acceptedAnswer: { "@type": "Answer", text: n.childNodes.slice(1).map((c) => c.textContent).join(" ").trim() }
232
+ }));
233
+ const faq = questions.length ? `<script type="application/ld+json">${JSON.stringify({ "@context": "https://schema.org", "@type": "FAQPage", mainEntity: questions }).replace(/</g, "\\u003c")}<\/script>` : "";
234
+ pages.push({
235
+ path,
236
+ title: document.title,
237
+ noindex: path === "/404" || Boolean(document.head.querySelector('meta[name="robots"]')),
238
+ head: document.head.childNodes.filter((n) => n.nodeName !== "title").map((n) => n.toHTML()).join("\n") + faq,
239
+ body: target.childNodes.map((n) => n.toHTML()).join("")
240
+ });
241
+ } finally {
242
+ close();
243
+ }
244
+ }
245
+ return { pages, site };
246
+ }
247
+ function insertPage(template, page) {
248
+ let html = template;
249
+ if (page.title) {
250
+ html = html.replace(/<title>[\s\S]*?<\/title>/, () => `<title>${UNITLESS_TEXT(page.title)}</title>`);
251
+ }
252
+ html = html.replace("</head>", () => `${page.head}
253
+ </head>`);
254
+ const target = /<div id="app">\s*<\/div>/;
255
+ if (!target.test(html)) throw new Error(`index.html needs an empty <div id="app"></div>`);
256
+ return html.replace(target, () => `<div id="app" class="orvyn-app" data-orvyn-static>${page.body}</div>`);
257
+ }
258
+ async function prerender(cwd, entry, outDir, env) {
259
+ const path = configFile(cwd);
260
+ const config = path ? (await import(pathToFileURL(path).href)).default ?? {} : {};
261
+ const template = readFileSync(join(outDir, "index.html"), "utf-8");
262
+ const { pages, site } = await renderPages(entry, { env, site: config.site });
263
+ const written = [];
264
+ const write = (file, content) => {
265
+ mkdirSync(join(outDir, file, ".."), { recursive: true });
266
+ writeFileSync(join(outDir, file), content);
267
+ written.push(file);
268
+ };
269
+ write("app.html", template);
270
+ for (const page of pages) {
271
+ const file = page.path === "/" ? "index.html" : page.path === "/404" ? "404.html" : `${page.path.slice(1)}/index.html`;
272
+ write(file, insertPage(template, page));
273
+ }
274
+ const mine = (file) => existsSync(join(cwd, "public", file));
275
+ if (site && !mine("sitemap.xml")) {
276
+ const urls = pages.filter((p) => !p.noindex).map((p) => ` <url><loc>${UNITLESS_TEXT(site + p.path)}</loc></url>`);
277
+ write("sitemap.xml", `<?xml version="1.0" encoding="UTF-8"?>
278
+ <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
279
+ ${urls.join("\n")}
280
+ </urlset>
281
+ `);
282
+ }
283
+ if (!mine("robots.txt")) {
284
+ const blocked = config.seo?.allowAI === false ? AI_CRAWLERS.map((bot) => `User-agent: ${bot}
285
+ Disallow: /
286
+
287
+ `).join("") : "";
288
+ write("robots.txt", `${blocked}User-agent: *
289
+ Allow: /
290
+ ${site ? `
291
+ Sitemap: ${site}/sitemap.xml
292
+ ` : ""}`);
293
+ }
294
+ return written;
295
+ }
296
+ export {
297
+ insertPage,
298
+ prerender,
299
+ renderPages
300
+ };