xbintsc 0.3.18 → 0.3.25

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 (57) hide show
  1. package/dist/src/driver/bundler/graph.d.ts +2 -1
  2. package/dist/src/driver/bundler/graph.js +18 -3
  3. package/dist/src/driver/bundler/graph.js.map +1 -1
  4. package/dist/src/driver/bundler/merge.d.ts +2 -1
  5. package/dist/src/driver/bundler/merge.js +2 -2
  6. package/dist/src/driver/bundler/merge.js.map +1 -1
  7. package/dist/src/driver/compiler.js +2 -2
  8. package/dist/src/driver/compiler.js.map +1 -1
  9. package/dist/src/extensions/gui/html.d.ts +25 -0
  10. package/dist/src/extensions/gui/html.js +203 -0
  11. package/dist/src/extensions/gui/html.js.map +1 -0
  12. package/dist/src/extensions/gui/index.js +11 -0
  13. package/dist/src/extensions/gui/index.js.map +1 -1
  14. package/dist/src/extensions/registry.d.ts +29 -0
  15. package/dist/src/extensions/registry.js +14 -0
  16. package/dist/src/extensions/registry.js.map +1 -1
  17. package/dist/src/index.d.ts +1 -1
  18. package/dist/src/index.js.map +1 -1
  19. package/dist/src/lexer/scanner/identifiers.js +4 -12
  20. package/dist/src/lexer/scanner/identifiers.js.map +1 -1
  21. package/dist/tests/driver/bundler-resolve.test.d.ts +1 -0
  22. package/dist/tests/driver/bundler-resolve.test.js +230 -0
  23. package/dist/tests/driver/bundler-resolve.test.js.map +1 -0
  24. package/dist/tests/driver/modules.test.js +68 -0
  25. package/dist/tests/driver/modules.test.js.map +1 -1
  26. package/dist/tests/e2e/gui.test.js +210 -1
  27. package/dist/tests/e2e/gui.test.js.map +1 -1
  28. package/dist/tests/extensions/gui-index.test.d.ts +1 -0
  29. package/dist/tests/extensions/gui-index.test.js +49 -0
  30. package/dist/tests/extensions/gui-index.test.js.map +1 -0
  31. package/dist/tests/extensions/gui.test.d.ts +1 -0
  32. package/dist/tests/extensions/gui.test.js +177 -0
  33. package/dist/tests/extensions/gui.test.js.map +1 -0
  34. package/dist/tests/extensions/registry.test.js +36 -0
  35. package/dist/tests/extensions/registry.test.js.map +1 -1
  36. package/dist/tests/public-api.test.d.ts +1 -0
  37. package/dist/tests/public-api.test.js +31 -0
  38. package/dist/tests/public-api.test.js.map +1 -0
  39. package/package.json +1 -1
  40. package/runtime/ext_gui/document.cpp +90 -0
  41. package/runtime/ext_gui/document.h +23 -0
  42. package/runtime/ext_gui/dom.cpp +36 -0
  43. package/runtime/ext_gui/dom.h +7 -0
  44. package/runtime/ext_gui/dom_api.cpp +1247 -0
  45. package/runtime/ext_gui/dom_api.h +12 -0
  46. package/runtime/ext_gui/gui.cpp +49 -3
  47. package/runtime/ext_gui/gui_engine.h +54 -0
  48. package/runtime/ext_gui/script.cpp +63 -0
  49. package/runtime/ext_gui/window.cpp +60 -0
  50. package/src/driver/bundler/graph.ts +21 -2
  51. package/src/driver/bundler/merge.ts +3 -1
  52. package/src/driver/compiler.ts +2 -2
  53. package/src/extensions/gui/html.ts +236 -0
  54. package/src/extensions/gui/index.ts +11 -0
  55. package/src/extensions/registry.ts +39 -0
  56. package/src/index.ts +1 -1
  57. package/src/lexer/scanner/identifiers.ts +4 -11
@@ -0,0 +1,236 @@
1
+ /**
2
+ * GUI `.html` asset loader.
3
+ *
4
+ * `import html from "./index.html"` normally yields the file contents as a
5
+ * string. When the file contains scripts, the loader also compiles them: each
6
+ * script body is wrapped in a function `(window, document) => { … }`,
7
+ * registered through the `__registerScript` builtin, and the element is
8
+ * replaced by an inert `<script data-xt-id="<hash>"></script>` marker. The
9
+ * engine runs the matching functions once the document has been parsed (see
10
+ * `runtime/ext_gui/script.cpp`).
11
+ *
12
+ * This is how xbintsc supports `<script>` without a JavaScript engine: the body
13
+ * is ordinary TypeScript compiled by the existing front end, ahead of time.
14
+ *
15
+ * Inline `<script lang="ts">body</script>` bodies are wrapped directly. External
16
+ * `<script src="./app.ts">` files are read, their top-level `import`/`export
17
+ * … from` statements are hoisted to the generated module (with relative
18
+ * specifiers rewritten so they resolve from the HTML file), and the remaining
19
+ * statements are wrapped in the script function. All scripts run in document
20
+ * order after parsing (there is no "eager" execution point), i.e. every script
21
+ * is effectively `defer`red.
22
+ */
23
+
24
+ import { existsSync, readFileSync } from "node:fs";
25
+ import { dirname, relative, resolve } from "node:path";
26
+ import {
27
+ ModifierKind,
28
+ SyntaxKind,
29
+ type ExportDeclaration,
30
+ type ImportDeclaration,
31
+ type Modifier,
32
+ type Statement,
33
+ type StringLiteral,
34
+ } from "../../ast/nodes.js";
35
+ import { DiagnosticBag } from "../../diagnostics/diagnostic.js";
36
+ import { SourceFile } from "../../diagnostics/source.js";
37
+ import { Parser } from "../../parser/parser.js";
38
+ import { hashString } from "../../driver/cache.js";
39
+ import type { AssetLoadResult } from "../registry.js";
40
+
41
+ /** Matches an inline `<script …>body</script>` element, attributes included. */
42
+ const SCRIPT_RE = /<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi;
43
+ /** `<script src>` targets that are URLs (http:, data:, //host, …). */
44
+ const URL_SPEC = /^[a-z][a-z0-9+.-]*:/i;
45
+
46
+ /** Read a (double/single/unquoted) attribute value from a tag's attribute text. */
47
+ function attribute(attributes: string, name: string): string | undefined {
48
+ const pattern = new RegExp(
49
+ `(?:^|\\s)${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'=<>\`]+))`,
50
+ "i",
51
+ );
52
+ const match = pattern.exec(attributes);
53
+ if (!match) return undefined;
54
+ return match[1] ?? match[2] ?? match[3];
55
+ }
56
+
57
+ /**
58
+ * Whether a script should be compiled. Defaults to TypeScript for a bare
59
+ * `<script>`; `type="module"` and the usual JS/TS MIME types are accepted,
60
+ * while data blocks (`application/json`, `text/template`, …) are left alone.
61
+ */
62
+ function isExecutable(type: string | undefined, lang: string | undefined): boolean {
63
+ if (lang && /^(ts|tsx|typescript|js|jsx|javascript)$/i.test(lang)) return true;
64
+ if (type === undefined) return true;
65
+ switch (type.toLowerCase()) {
66
+ case "module":
67
+ case "text/typescript":
68
+ case "application/typescript":
69
+ case "text/javascript":
70
+ case "application/javascript":
71
+ case "text/ecmascript":
72
+ case "application/ecmascript":
73
+ return true;
74
+ default:
75
+ return false;
76
+ }
77
+ }
78
+
79
+ /** Rewrite a relative import specifier so it resolves from the HTML file. */
80
+ function rewriteSpecifier(htmlPath: string, scriptPath: string, specifier: string): string {
81
+ if (!specifier.startsWith(".")) return specifier;
82
+ const absolute = resolve(dirname(scriptPath), specifier);
83
+ let rel = relative(dirname(htmlPath), absolute).split("\\").join("/");
84
+ if (!rel.startsWith(".")) rel = `./${rel}`;
85
+ return rel;
86
+ }
87
+
88
+ /** The original text of an import/re-export with its specifier rewritten. */
89
+ function rewriteSpecifierText(
90
+ htmlPath: string,
91
+ scriptPath: string,
92
+ source: string,
93
+ statement: Statement,
94
+ specifier: StringLiteral,
95
+ ): string {
96
+ const rewritten = rewriteSpecifier(htmlPath, scriptPath, specifier.value);
97
+ return source.slice(statement.start, specifier.start) + JSON.stringify(rewritten) + source.slice(specifier.end, statement.end);
98
+ }
99
+
100
+ /** Every local binding an import declaration introduces. */
101
+ function importLocalNames(declaration: ImportDeclaration): string[] {
102
+ const names: string[] = [];
103
+ const clause = declaration.importClause;
104
+ if (!clause) return names;
105
+ if (clause.name) names.push(clause.name.text);
106
+ const bindings = clause.namedBindings;
107
+ if (bindings) {
108
+ if (bindings.kind === SyntaxKind.NamedImports) {
109
+ for (const element of bindings.elements) names.push(element.name.text);
110
+ } else {
111
+ names.push(bindings.name.text);
112
+ }
113
+ }
114
+ return names;
115
+ }
116
+
117
+ interface CompiledModule {
118
+ /** Hoisted `import`/`export … from` statements (specifiers rewritten). */
119
+ imports: string[];
120
+ /** Local names the hoisted imports introduce. */
121
+ localNames: string[];
122
+ /** The module body, wrapped as a script function by the caller. */
123
+ body: string;
124
+ }
125
+
126
+ /** Split an external script module into hoisted imports and a body. */
127
+ function compileModuleSource(htmlPath: string, scriptPath: string): CompiledModule {
128
+ const source = readFileSync(scriptPath, "utf8");
129
+ const bag = new DiagnosticBag();
130
+ const parsed = new Parser(new SourceFile(scriptPath, source), bag).parseSourceFile();
131
+ const chars = source.split("");
132
+ const imports: string[] = [];
133
+ const localNames: string[] = [];
134
+ const blank = (start: number, end: number): void => {
135
+ for (let i = start; i < end; i += 1) chars[i] = " ";
136
+ };
137
+
138
+ for (const statement of parsed.statements) {
139
+ if (statement.kind === SyntaxKind.ImportDeclaration) {
140
+ const declaration = statement as ImportDeclaration;
141
+ /* The front-end has no side-effect `import "x"` form; spell it as an
142
+ * empty named import so the dependency is still loaded. */
143
+ const hoisted = declaration.importClause
144
+ ? rewriteSpecifierText(htmlPath, scriptPath, source, statement, declaration.moduleSpecifier)
145
+ : `import {} from ${JSON.stringify(rewriteSpecifier(htmlPath, scriptPath, declaration.moduleSpecifier.value))}`;
146
+ imports.push(hoisted);
147
+ localNames.push(...importLocalNames(declaration));
148
+ blank(statement.start, statement.end);
149
+ continue;
150
+ }
151
+ if (statement.kind === SyntaxKind.ExportDeclaration) {
152
+ const declaration = statement as ExportDeclaration;
153
+ if (declaration.moduleSpecifier) {
154
+ imports.push(rewriteSpecifierText(htmlPath, scriptPath, source, statement, declaration.moduleSpecifier));
155
+ }
156
+ blank(statement.start, statement.end);
157
+ continue;
158
+ }
159
+ if (statement.kind === SyntaxKind.ExportAssignment) {
160
+ /* `export default …` is meaningless in a script module; drop it. */
161
+ blank(statement.start, statement.end);
162
+ continue;
163
+ }
164
+ /* Strip `export`/`export default` so the statement is valid inside the
165
+ * generated function. */
166
+ const modifiers = (statement as { modifiers?: Modifier[] }).modifiers ?? [];
167
+ for (const modifier of modifiers) {
168
+ if (modifier.modifierKind === ModifierKind.Export || modifier.modifierKind === ModifierKind.Default) {
169
+ blank(modifier.start, modifier.end);
170
+ }
171
+ }
172
+ }
173
+
174
+ return { imports, localNames, body: chars.join("") };
175
+ }
176
+
177
+ /** Resolve a `<script src>` value to a local file path (ignoring `?`/`#`). */
178
+ function resolveScriptPath(htmlPath: string, src: string): string {
179
+ const clean = src.split(/[?#]/, 1)[0] ?? src;
180
+ return resolve(dirname(htmlPath), clean);
181
+ }
182
+
183
+ /** Rewrite `<script>` bodies into registered AOT functions + an HTML string. */
184
+ export function loadHtmlAsset(path: string, source: string): AssetLoadResult {
185
+ const scripts: Array<{ id: string; body: string }> = [];
186
+ const imports: string[] = [];
187
+ const importedText = new Set<string>();
188
+ const bound = new Set<string>();
189
+
190
+ const html = source.replace(SCRIPT_RE, (match, attributes: string, inlineBody: string) => {
191
+ if (!isExecutable(attribute(attributes, "type"), attribute(attributes, "lang"))) return match;
192
+ const src = attribute(attributes, "src");
193
+
194
+ if (src !== undefined && !URL_SPEC.test(src) && !src.startsWith("//")) {
195
+ const scriptPath = resolveScriptPath(path, src);
196
+ if (!existsSync(scriptPath)) {
197
+ throw new Error(`gui: <script src="${src}"> not found (looked for ${scriptPath})`);
198
+ }
199
+ const compiled = compileModuleSource(path, scriptPath);
200
+ for (const text of compiled.imports) {
201
+ if (!importedText.has(text)) {
202
+ importedText.add(text);
203
+ imports.push(text);
204
+ }
205
+ }
206
+ for (const name of compiled.localNames) {
207
+ if (bound.has(name)) {
208
+ throw new Error(
209
+ `gui: <script src="${src}"> imports '${name}', already imported by another <script src>; alias it in ${scriptPath}`,
210
+ );
211
+ }
212
+ bound.add(name);
213
+ }
214
+ const id = hashString(compiled.body);
215
+ scripts.push({ id, body: compiled.body });
216
+ return `<script data-xt-id="${id}"></script>`;
217
+ }
218
+
219
+ /* A `src` URL, or a data block: leave the element untouched. */
220
+ if (src !== undefined) return match;
221
+ if (inlineBody.trim() === "") return match;
222
+ const id = hashString(inlineBody);
223
+ scripts.push({ id, body: inlineBody });
224
+ return `<script data-xt-id="${id}"></script>`;
225
+ });
226
+
227
+ const parts: string[] = [...imports];
228
+ for (const { id, body } of scripts) {
229
+ parts.push(
230
+ `function __xt_script_${id}(window: any, document: any): void {\n${body}\n}\n` +
231
+ `__registerScript(${JSON.stringify(id)}, __xt_script_${id});`,
232
+ );
233
+ }
234
+ parts.push(`export default ${JSON.stringify(html)};`);
235
+ return { moduleSource: parts.join("\n") };
236
+ }
@@ -25,6 +25,7 @@ import { join } from "node:path";
25
25
  import type { Extension, ExtensionModule } from "../registry.js";
26
26
  import { findRuntimeDir, platformSlug } from "../../driver/paths.js";
27
27
  import { findRuntimeLibrary } from "../../driver/runtime-lib.js";
28
+ import { loadHtmlAsset } from "./html.js";
28
29
 
29
30
  /** Top-level `gui` module bindings. */
30
31
  const guiModule: ExtensionModule = {
@@ -104,4 +105,14 @@ export const guiExtension: Extension = {
104
105
  return ["-lX11", "-lwayland-client", "-lEGL", "-lGL", "-ldl", "-lpthread", "-lstdc++"];
105
106
  },
106
107
  modules: () => ({ gui: guiModule }),
108
+ /**
109
+ * `__registerScript(id, fn)` is emitted by the `.html` asset loader and
110
+ * called at module initialization; it records the AOT-compiled `<script>`
111
+ * body so the engine can run it after parsing a document.
112
+ */
113
+ builtins: () => ({
114
+ __registerScript: { symbol: "xt_register_script" },
115
+ }),
116
+ /** Rewrite imported `.html` assets (see `html.ts`). */
117
+ assetLoaders: () => ({ ".html": loadHtmlAsset }),
107
118
  };
@@ -52,6 +52,24 @@ export interface ExtensionModule {
52
52
  readonly namespace?: string;
53
53
  }
54
54
 
55
+ /** The result of an extension asset loader rewriting one imported file. */
56
+ export interface AssetLoadResult {
57
+ /**
58
+ * The TypeScript source the bundler parses in place of the raw file. It may
59
+ * contain its own `import`/`export` statements, which are followed normally.
60
+ */
61
+ readonly moduleSource: string;
62
+ /**
63
+ * Extra files the transformed module depends on that are *not* reached
64
+ * through imports (for cache invalidation). Imported files are already
65
+ * tracked by the bundler.
66
+ */
67
+ readonly dependencies?: readonly string[];
68
+ }
69
+
70
+ /** Rewrites an imported file (selected by extension) into a TS module. */
71
+ export type AssetLoader = (path: string, source: string) => AssetLoadResult;
72
+
55
73
  export interface Extension {
56
74
  readonly name: string;
57
75
  /** Description shown by `xbintsc ext list`. */
@@ -75,6 +93,13 @@ export interface Extension {
75
93
  builtins?(): Readonly<Record<string, BuiltinFunction>>;
76
94
  /** Modules importable as `import ... from "<specifier>"`. */
77
95
  modules?(): Readonly<Record<string, ExtensionModule>>;
96
+ /**
97
+ * Rewrite imported assets into TS modules, keyed by file extension
98
+ * (including the dot, e.g. `".html"`). The bundler consults these right
99
+ * after reading a file and before parsing it, so the core compiler never
100
+ * learns about any particular asset format.
101
+ */
102
+ assetLoaders?(): Readonly<Record<string, AssetLoader>>;
78
103
  }
79
104
 
80
105
  export class ExtensionRegistry {
@@ -159,6 +184,20 @@ export class ExtensionRegistry {
159
184
  return merged;
160
185
  }
161
186
 
187
+ /**
188
+ * Flatten every registered extension's asset loaders, keyed by file
189
+ * extension. A later extension overrides an earlier one for the same
190
+ * extension (mirroring `modules()`).
191
+ */
192
+ assetLoaders(): Readonly<Record<string, AssetLoader>> {
193
+ const merged: Record<string, AssetLoader> = {};
194
+ for (const extension of this.extensions.values()) {
195
+ const loaders = extension.assetLoaders?.();
196
+ if (loaders) Object.assign(merged, loaders);
197
+ }
198
+ return merged;
199
+ }
200
+
162
201
  runtimeSources(): readonly string[] {
163
202
  const sources: string[] = [];
164
203
  for (const extension of this.extensions.values()) {
package/src/index.ts CHANGED
@@ -29,7 +29,7 @@ export {
29
29
  numberLiteral,
30
30
  booleanLiteral,
31
31
  } from "./codegen/values.js";
32
- export { ExtensionRegistry, createDefaultRegistry, coreExtension, type Extension, type ExtensionModule, type ModuleExport, type ModuleExports } from "./extensions/registry.js";
32
+ export { ExtensionRegistry, createDefaultRegistry, coreExtension, type Extension, type ExtensionModule, type ModuleExport, type ModuleExports, type AssetLoader, type AssetLoadResult } from "./extensions/registry.js";
33
33
  export { bundledExtensions } from "./extensions/catalog.js";
34
34
  export { nodeExtension } from "./extensions/node/index.js";
35
35
  export type { NodeModule } from "./extensions/node/module.js";
@@ -2,9 +2,8 @@
2
2
  * Identifier scanning (identifiers, keywords and private `#name`s).
3
3
  */
4
4
 
5
- import { DiagnosticCode } from "../../diagnostics/diagnostic.js";
6
5
  import { KEYWORDS, Token, TokenKind } from "../token.js";
7
- import { Char, isIdentifierPart } from "../char.js";
6
+ import { isIdentifierPart } from "../char.js";
8
7
  import type { Scanner } from "../scanner.js";
9
8
 
10
9
  export interface IdentifierMethods {
@@ -14,17 +13,11 @@ export interface IdentifierMethods {
14
13
  export const identifierMethods: IdentifierMethods = {
15
14
  scanIdentifier(this: Scanner, start: number, precededByLineBreak: boolean): Token {
16
15
  this.pos++;
16
+ /* `\` is itself an identifier part, so unicode escapes such as `a\u0041b`
17
+ * are kept verbatim in the identifier text (see the lexer tests). */
17
18
  while (this.pos < this.text.length) {
18
- const ch = this.text.charCodeAt(this.pos);
19
- if (isIdentifierPart(ch)) {
19
+ if (isIdentifierPart(this.text.charCodeAt(this.pos))) {
20
20
  this.pos++;
21
- } else if (ch === Char.Backslash && this.text.charCodeAt(this.pos + 1) === Char.LowerU) {
22
- this.pos += 2;
23
- const hex = this.text.slice(this.pos, this.pos + 4);
24
- this.pos += 4;
25
- if (!/^[0-9a-fA-F]{4}$/.test(hex)) {
26
- this.error(DiagnosticCode.InvalidEscape, "Invalid unicode escape in identifier", this.pos - 4, this.pos);
27
- }
28
21
  } else {
29
22
  break;
30
23
  }