@tylix/compiler 2.1.0 → 2.2.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tylix/compiler",
3
- "version": "2.1.0",
3
+ "version": "2.2.0",
4
4
  "description": "Compiler for Tylix .tyx pages and components: parses, type-checks and compiles them to server-rendered HTML and client JavaScript.",
5
5
  "license": "MIT",
6
6
  "author": "Mbiyrukzz",
@@ -13,14 +13,14 @@
13
13
  "ssr",
14
14
  "components"
15
15
  ],
16
- "homepage": "https://github.com/Mbiyrukzz/tylix/tree/main/packages/compiler#readme",
16
+ "homepage": "https://github.com/tylixjs/tylix/tree/main/packages/compiler#readme",
17
17
  "repository": {
18
18
  "type": "git",
19
- "url": "git+https://github.com/Mbiyrukzz/tylix.git",
19
+ "url": "git+https://github.com/tylixjs/tylix.git",
20
20
  "directory": "packages/compiler"
21
21
  },
22
22
  "bugs": {
23
- "url": "https://github.com/Mbiyrukzz/tylix/issues"
23
+ "url": "https://github.com/tylixjs/tylix/issues"
24
24
  },
25
25
  "engines": {
26
26
  "node": ">=22.13"
@@ -290,7 +290,25 @@ return __Class;
290
290
  // `fallbackClassName` ALWAYS decides the class name -- for native
291
291
  // `component Card` files too -- so two files that both declare Card
292
292
  // can live in one page.
293
+ // Every page compiles every component in the app (and the layout), and the
294
+ // result only depends on these three inputs, so it is kept. A 120-page app
295
+ // recompiled ~60 components per request before. Errors are not cached.
296
+ const compiledComponents = new Map()
297
+ const MAX_COMPILED = 2000
298
+
293
299
  function compileComponentSource(source, fallbackClassName, language) {
300
+ const key = `${fallbackClassName}\0${JSON.stringify(language)}\0${source}`
301
+ const hit = compiledComponents.get(key)
302
+ if (hit) return hit
303
+ const compiled = compileComponentSourceUncached(source, fallbackClassName, language)
304
+ if (compiledComponents.size >= MAX_COMPILED) {
305
+ compiledComponents.delete(compiledComponents.keys().next().value)
306
+ }
307
+ compiledComponents.set(key, Object.freeze(compiled))
308
+ return compiled
309
+ }
310
+
311
+ function compileComponentSourceUncached(source, fallbackClassName, language) {
294
312
  const isNativeComponent = /^\s*component\s+\w+/.test(source)
295
313
 
296
314
  if (isNativeComponent) {
@@ -331,6 +349,11 @@ function compileComponentSource(source, fallbackClassName, language) {
331
349
  return { classSource, code, rootVar, className: fallbackClassName }
332
350
  }
333
351
 
352
+ // Generated script segments known to parse (see the check at the end of
353
+ // renderPageDocument).
354
+ const parsedSegments = new Set()
355
+ const MAX_PARSED_SEGMENTS = 500
356
+
334
357
  function applyLineOffset(err, offset) {
335
358
  const match = /at line (\d+)/.exec(err.message)
336
359
  if (match) {
@@ -361,12 +384,51 @@ function parseTemplateWithLineOffset(template, offset, language) {
361
384
  }
362
385
  }
363
386
 
364
- export async function renderPageDocument(
387
+ // Where a precompiled page's props go. `tylix build` renders each page
388
+ // with this in place of the props and records where it is (see
389
+ // renderPageBundleEntry); a server then puts serializeProps(props) there.
390
+ // It is a valid JavaScript expression on its own, so the file is also a
391
+ // working page with no props.
392
+ export const PROPS_SLOT = '/*__TYLIX_PROPS__*/{}'
393
+
394
+ // "</script" anywhere in an inline script (a <pre> sample, a route prop, a
395
+ // string) would end the script element early, and "<!--" can start an
396
+ // HTML comment inside it. Both replacements mean the same thing to the JS
397
+ // engine.
398
+ function escapeInlineScript(code) {
399
+ return code.replace(/<\/(script)/gi, '<\\/$1').replace(/<!--/g, '<\\!--')
400
+ }
401
+
402
+ // A page's props as the document embeds them: JSON, escaped for an inline
403
+ // script. Filling a bundle entry's slot with this gives exactly the
404
+ // document renderPageDocument() makes for the same props.
405
+ export function serializeProps(props = {}) {
406
+ if (props === null || typeof props !== 'object' || Array.isArray(props)) {
407
+ throw new TypeError('Page props must be a plain object')
408
+ }
409
+ return escapeInlineScript(JSON.stringify(props))
410
+ }
411
+
412
+ // The whole page as HTML, with `props` embedded.
413
+ export async function renderPageDocument(source, childComponents = {}, options = {}) {
414
+ const props = options.props ?? {}
415
+ const { html } = await renderDocument(source, childComponents, options, JSON.stringify(props))
416
+ return html
417
+ }
418
+
419
+ // The page for a precompiled bundle: `html` contains PROPS_SLOT once, at
420
+ // the UTF-16 index `slot`, where the props go. Only that occurrence is the
421
+ // slot: a page that shows the text itself (a code sample, say) keeps its
422
+ // own copy. Takes the same options as renderPageDocument except `props`.
423
+ export async function renderPageBundleEntry(source, childComponents = {}, options = {}) {
424
+ return renderDocument(source, childComponents, options, PROPS_SLOT)
425
+ }
426
+
427
+ async function renderDocument(
365
428
  source,
366
429
  childComponents = {},
367
430
  {
368
431
  layout = null,
369
- props = {},
370
432
  apiHelpers = '',
371
433
  channelsPort = null,
372
434
  // Stylesheets to link in <head>, in order. createApp passes the ones
@@ -396,6 +458,8 @@ export async function renderPageDocument(
396
458
  // (see loadingScreen.js). false turns it off.
397
459
  loadingScreen = true,
398
460
  } = {},
461
+ // The page's props as JavaScript: their JSON, or PROPS_SLOT.
462
+ propsCode = '{}',
399
463
  ) {
400
464
  // createApp already has a variable called `language` that holds
401
465
  // 'typescript' | 'javascript'. Passing that here would silently fall
@@ -585,7 +649,7 @@ ${layoutCompiled.code}
585
649
 
586
650
  // If __ready() rejects (a failed needs/prefetch call), log it and keep
587
651
  // going so the page still renders, instead of showing a blank screen.
588
- const inlineScript = `
652
+ const scriptBefore = `
589
653
  ${loadingClassSource || !loadingBar ? 'window.__TYLIX_CUSTOM_LOADING__ = true;' : ''}
590
654
 
591
655
  ${RUNTIME_SOURCE}
@@ -617,7 +681,9 @@ ${layoutClassSource}
617
681
  ${loadingClassSource}
618
682
 
619
683
  document.addEventListener("DOMContentLoaded", () => {
620
- const instance = __tylixExpose(new ${pageName}(${JSON.stringify(props)}), ${pageName}, { kind: "page", name: ${JSON.stringify(pageName)} });
684
+ const instance = __tylixExpose(new ${pageName}(`
685
+ // The props go here (see renderDocument's `propsCode`).
686
+ const scriptAfter = `), ${pageName}, { kind: "page", name: ${JSON.stringify(pageName)} });
621
687
  const components = {};
622
688
  ${childRegistrations}
623
689
  (async function (document, instance, components) {
@@ -673,8 +739,13 @@ ${layoutMountCode}
673
739
 
674
740
  for (const segment of scriptSegments) {
675
741
  if (!segment.code || segment.code.trim().length === 0) continue
742
+ // The runtime sources and most components are the same on every page;
743
+ // parsing them once is enough.
744
+ if (parsedSegments.has(segment.code)) continue
676
745
  try {
677
746
  new Function(segment.code)
747
+ if (parsedSegments.size >= MAX_PARSED_SEGMENTS) parsedSegments.clear()
748
+ parsedSegments.add(segment.code)
678
749
  } catch (err) {
679
750
  const genErr = new Error(
680
751
  `Generated JavaScript failed to parse in "${segment.name}": ${err.message}`,
@@ -684,6 +755,11 @@ ${layoutMountCode}
684
755
  }
685
756
  }
686
757
 
758
+ // The text either side of the props is generated from the page and may
759
+ // contain anything, including PROPS_SLOT itself, so the slot is tracked
760
+ // by position from here on, never searched for.
761
+ const inlineScript = scriptBefore + propsCode + scriptAfter
762
+
687
763
  try {
688
764
  new Function(inlineScript)
689
765
  } catch (err) {
@@ -694,14 +770,13 @@ ${layoutMountCode}
694
770
  throw genErr
695
771
  }
696
772
 
697
- // A "</script" anywhere in the generated code (a <pre> sample, a
698
- // route prop, a string) would end the script element early, and
699
- // "<!--" can start an HTML comment inside it. Both replacements mean
700
- // the same thing to the JS engine. Done AFTER the validation above,
701
- // which must see the unescaped source.
702
- const safeScript = inlineScript
703
- .replace(/<\/(script)/gi, '<\\/$1')
704
- .replace(/<!--/g, '<\\!--')
773
+ // Escaped AFTER the validation above, which must see the unescaped
774
+ // source. Escaping the three parts separately gives the same text as
775
+ // escaping the whole: the parts meet at "(" and ")", which no escaped
776
+ // sequence contains.
777
+ const safeBefore = escapeInlineScript(scriptBefore)
778
+ const safeProps = escapeInlineScript(propsCode)
779
+ const safeAfter = escapeInlineScript(scriptAfter)
705
780
 
706
781
  const themeScript = `<script>
707
782
  (function () {
@@ -718,13 +793,32 @@ ${layoutMountCode}
718
793
  head: [channelsPortScript, themeScript, styleLinks, extraHead, headTags, styleTag]
719
794
  .filter((part) => part && part.length > 0)
720
795
  .join('\n '),
721
- body: `${loadingScreen ? loadingScreenHtml({ root: '#app' }) + '\n ' : ''}<div id="app"></div>\n <script>${safeScript}</script>`,
722
796
  }
797
+ const bodyBefore = `${loadingScreen ? loadingScreenHtml({ root: '#app' }) + '\n ' : ''}<div id="app"></div>\n <script>${safeBefore}`
798
+ values.body = `${bodyBefore}${safeProps}${safeAfter}</script>`
723
799
 
724
800
  // One pass with a function replacer, so a "$&" or a placeholder-looking
725
801
  // string inside the generated script is never treated as a pattern or
726
802
  // substituted a second time.
727
803
  // HTML comments are left alone, so a note like "scripts go before
728
804
  // %tylix.head%" in app/index.html doesn't get a second copy of the head.
729
- return shell.replace(/<!--[\s\S]*?-->|%tylix\.(title|head|body)%/g, (match, key) => (key ? values[key] : match))
805
+ //
806
+ // `slot` is where the props start in the finished document.
807
+ let html = ''
808
+ let slot = -1
809
+ let last = 0
810
+ for (const match of shell.matchAll(/<!--[\s\S]*?-->|%tylix\.(title|head|body)%/g)) {
811
+ html += shell.slice(last, match.index)
812
+ const key = match[1]
813
+ if (key === 'body') {
814
+ if (slot !== -1) {
815
+ throw new Error('app/index.html contains %tylix.body% more than once; a page can only be mounted once.')
816
+ }
817
+ slot = html.length + bodyBefore.length
818
+ }
819
+ html += key ? values[key] : match[0]
820
+ last = match.index + match[0].length
821
+ }
822
+ html += shell.slice(last)
823
+ return { html, slot }
730
824
  }
@@ -0,0 +1,20 @@
1
+ import { createRequire } from 'node:module'
2
+
3
+ const require = createRequire(import.meta.url)
4
+
5
+ // TypeScript is a ~9 MB CommonJS file that takes ~400 ms to load. It is
6
+ // required on first use instead of imported at the top of a module, so
7
+ // `tylix dev`, `tylix start` and every CLI command that never checks or
8
+ // transpiles anything start without it.
9
+ export function loadTypescript() {
10
+ return require('typescript')
11
+ }
12
+
13
+ // The installed version, read without loading the compiler (cache keys).
14
+ export function typescriptVersion() {
15
+ try {
16
+ return require('typescript/package.json').version
17
+ } catch {
18
+ return 'unknown'
19
+ }
20
+ }
@@ -1,4 +1,7 @@
1
- import ts from 'typescript'
1
+ import crypto from 'node:crypto'
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+ import { loadTypescript, typescriptVersion } from './loadTypescript.js'
2
5
 
3
6
  // Transpiles a single .ts source file to plain, browser-runnable JS.
4
7
  // Used for app/useApi/*.ts helpers, which get concatenated as raw
@@ -13,12 +16,41 @@ import ts from 'typescript'
13
16
  // with no cross-file type information to check against, and the
14
17
  // project's own typecheckPage already covers .tyx pages -- this is
15
18
  // purely a syntax-stripping step, not a second typechecking pass.
19
+ //
20
+ // Results are cached on disk (node_modules/.cache/tylix/ts, keyed by the
21
+ // source and the TypeScript version), so a server start whose helpers
22
+ // haven't changed never loads the TypeScript compiler at all.
23
+ const CACHE_DIR = path.join(process.cwd(), 'node_modules', '.cache', 'tylix', 'ts')
24
+ let version
25
+
26
+ function cacheFile(source) {
27
+ version ??= typescriptVersion()
28
+ const hash = crypto.createHash('sha256').update(version).update('\0').update(source).digest('hex')
29
+ return path.join(CACHE_DIR, `${hash.slice(0, 32)}.js`)
30
+ }
31
+
16
32
  export function transpileTsToJs(source) {
33
+ const file = cacheFile(source)
34
+ try {
35
+ return fs.readFileSync(file, 'utf8')
36
+ } catch {}
37
+
38
+ const ts = loadTypescript()
17
39
  const result = ts.transpileModule(source, {
18
40
  compilerOptions: {
19
41
  target: ts.ScriptTarget.ES2022,
20
42
  module: ts.ModuleKind.ESNext,
21
43
  },
22
44
  })
45
+
46
+ try {
47
+ fs.mkdirSync(CACHE_DIR, { recursive: true })
48
+ // Write then rename, so a crash never leaves half a file behind.
49
+ const tmp = `${file}.${process.pid}.tmp`
50
+ fs.writeFileSync(tmp, result.outputText)
51
+ fs.renameSync(tmp, file)
52
+ } catch {
53
+ // Read-only node_modules, full disk: still correct, just not cached.
54
+ }
23
55
  return result.outputText
24
56
  }
@@ -1,4 +1,8 @@
1
- import ts from 'typescript'
1
+ import { loadTypescript } from './loadTypescript.js'
2
+
3
+ // Set by the first typecheckSource() call. TypeScript takes ~400 ms to load,
4
+ // so a server that never type-checks a page never pays for it.
5
+ let ts
2
6
  import { fileURLToPath } from 'node:url'
3
7
 
4
8
  const VIRTUAL_FILE_NAME = '__tylix_virtual_page.ts'
@@ -31,6 +35,7 @@ export function typecheckSource(
31
35
  apiHelpersSource = '',
32
36
  compilerOptions = {},
33
37
  ) {
38
+ ts ??= loadTypescript()
34
39
  const options = {
35
40
  strict: true,
36
41
  target: ts.ScriptTarget.ES2022,