@tylix/compiler 0.5.2 → 0.6.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.
@@ -1,29 +1,115 @@
1
+ import { findSectionBoundaries } from '../parser/parsePageFile.js'
2
+ // import { A, B as C } from "pkg" -> components from a package manifest
3
+ // import Card from "./a/Card" -> one local .tyx file, named by you
4
+ //
5
+ // `[ \t\r]*` at the ends (never `\s*`) so a match can't swallow
6
+ // neighbouring blank lines; `[^}]*` lets the braces span lines.
1
7
  const IMPORT_LINE_RE =
2
- /^\s*import\s*\{\s*([^}]+)\s*\}\s*from\s*["']([^"']+)["']\s*;?\s*$/gm
3
-
4
- // Tylix pages/components can import named components from an
5
- // installed package (e.g. `import { IconCheck, IconTrash } from
6
- // "tylix-icons"`), the same way a local component under
7
- // app/pages/components/ works -- this is a source-level rewrite
8
- // step, not a grammar addition. Import lines never reach
9
- // parsePageFile's script/template splitter or the Parser/Lexer at
10
- // all; they're stripped out of the raw file text before any of that
11
- // runs. Only package specifiers (no leading "." or "/") are handled
12
- // here -- local components are already auto-discovered by
13
- // loadComponents() scanning app/pages/components/, so a relative
14
- // import isn't a case this needs to cover.
8
+ /^[ \t]*import(?:\s*\{([^}]*)\}|\s+([A-Za-z_$][\w$]*))\s*from\s*["']([^"']+)["']\s*;?[ \t\r]*$/gm
9
+
10
+ const NAME_RE = /^[A-Z][A-Za-z0-9_$]*$/
11
+ const NAMED_ITEM_RE =
12
+ /^([A-Z][A-Za-z0-9_$]*)(?:\s+as\s+([A-Z][A-Za-z0-9_$]*))?$/
13
+
14
+ // Imports are only recognised BEFORE the template, so code samples
15
+ // inside <pre> blocks are never rewritten.
16
+ function headEnd(source) {
17
+ const sectionTemplate = findSectionBoundaries(source).find(
18
+ (b) => b.keyword === 'template',
19
+ )
20
+ const legacy = source.search(/<template[\s>]/)
21
+ const ends = [sectionTemplate ? sectionTemplate.start : -1, legacy].filter(
22
+ (n) => n >= 0,
23
+ )
24
+ return ends.length > 0 ? Math.min(...ends) : source.length
25
+ }
26
+
27
+ // Each removed import is replaced by the SAME number of newlines, so
28
+ // every line below it keeps its original line number (parse errors
29
+ // and typecheck diagnostics depend on that).
30
+ //
31
+ // Returns { imports, source } where each import is
32
+ // { kind: 'package' | 'local', specifier, line,
33
+ // names: [{ imported, local }] }
34
+ // `local` is the tag name the page uses; `imported` is the name in
35
+ // the package manifest (null for local files, which hold one
36
+ // component each).
15
37
  export function extractImports(source) {
16
- const imports = []
17
- const cleaned = source.replace(IMPORT_LINE_RE, (match, namesRaw, pkg) => {
18
- if (pkg.startsWith('.') || pkg.startsWith('/')) {
19
- return match // not a supported target -- leave as a normal parse error
38
+ const end = headEnd(source)
39
+ const head = source.slice(0, end)
40
+ const packages = new Map() // specifier -> import entry
41
+ const locals = []
42
+ const taken = new Map() // local name -> specifier
43
+
44
+ const claim = (local, specifier, line) => {
45
+ if (taken.has(local) && taken.get(local) !== specifier) {
46
+ throw new Error(
47
+ `"${local}" is imported twice (from "${taken.get(local)}" and "${specifier}", line ${line}); give one of them a different name`,
48
+ )
20
49
  }
21
- const names = namesRaw
22
- .split(',')
23
- .map((n) => n.trim())
24
- .filter(Boolean)
25
- imports.push({ names, package: pkg })
26
- return ''
27
- })
28
- return { imports, source: cleaned }
29
- }
50
+ taken.set(local, specifier)
51
+ }
52
+
53
+ const cleaned = head.replace(
54
+ IMPORT_LINE_RE,
55
+ (match, braced, bare, specifier, offset) => {
56
+ const line = head.slice(0, offset).split('\n').length
57
+
58
+ if (specifier.startsWith('/')) {
59
+ throw new Error(
60
+ `Absolute import "${specifier}" at line ${line} is not supported; use a relative path`,
61
+ )
62
+ }
63
+
64
+ if (specifier.startsWith('.')) {
65
+ if (braced !== undefined) {
66
+ throw new Error(
67
+ `Line ${line}: a local file holds one component, so write: import Name from "${specifier}"`,
68
+ )
69
+ }
70
+ if (!NAME_RE.test(bare)) {
71
+ throw new Error(
72
+ `Line ${line}: component name "${bare}" must start with an uppercase letter`,
73
+ )
74
+ }
75
+ claim(bare, specifier, line)
76
+ locals.push({
77
+ kind: 'local',
78
+ specifier,
79
+ line,
80
+ names: [{ imported: null, local: bare }],
81
+ })
82
+ } else {
83
+ if (bare !== undefined) {
84
+ throw new Error(
85
+ `Line ${line}: packages export named components, so write: import { ${bare} } from "${specifier}"`,
86
+ )
87
+ }
88
+ let entry = packages.get(specifier)
89
+ if (!entry) {
90
+ entry = { kind: 'package', specifier, line, names: [] }
91
+ packages.set(specifier, entry)
92
+ }
93
+ for (const raw of braced.split(',').map((n) => n.trim()).filter(Boolean)) {
94
+ const m = NAMED_ITEM_RE.exec(raw)
95
+ if (!m) {
96
+ throw new Error(
97
+ `Line ${line}: cannot import "${raw}" from "${specifier}" (expected Name or Name as Other, PascalCase)`,
98
+ )
99
+ }
100
+ const imported = m[1]
101
+ const local = m[2] ?? m[1]
102
+ claim(local, specifier, line)
103
+ entry.names.push({ imported, local })
104
+ }
105
+ }
106
+
107
+ return match.replace(/[^\n]/g, '') // keep the newlines only
108
+ },
109
+ )
110
+
111
+ return {
112
+ imports: [...packages.values(), ...locals],
113
+ source: cleaned + source.slice(end),
114
+ }
115
+ }
@@ -0,0 +1,186 @@
1
+ import fs from 'node:fs/promises'
2
+ import path from 'node:path'
3
+ import { extractImports } from './extractImports.js'
4
+
5
+ // A component package ships a manifest at its root mapping exported
6
+ // names to the .tyx file that defines them:
7
+ // { "IconCheck": "icons/IconCheck.tyx" }
8
+ const MANIFEST_FILE = 'tylix-components.json'
9
+ const PACKAGE_NAME_RE = /^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/
10
+
11
+ const fileCache = new Map() // absolute path -> { mtimeMs, text }
12
+
13
+ async function readCached(file) {
14
+ const stat = await fs.stat(file)
15
+ const hit = fileCache.get(file)
16
+ if (hit && hit.mtimeMs === stat.mtimeMs) return hit.text
17
+ const text = await fs.readFile(file, 'utf-8')
18
+ fileCache.set(file, { mtimeMs: stat.mtimeMs, text })
19
+ return text
20
+ }
21
+
22
+ // Walks up from startDir so packages hoisted into a workspace root
23
+ // resolve too. fs.stat follows symlinks (workspace-linked packages).
24
+ async function findPackageDir(pkgName, startDir) {
25
+ let dir = path.resolve(startDir)
26
+ while (true) {
27
+ const candidate = path.join(dir, 'node_modules', pkgName)
28
+ try {
29
+ if ((await fs.stat(candidate)).isDirectory()) return candidate
30
+ } catch {
31
+ // keep walking up
32
+ }
33
+ const parent = path.dirname(dir)
34
+ if (parent === dir) return null
35
+ dir = parent
36
+ }
37
+ }
38
+
39
+ // baseDir: project root (local imports may not escape it).
40
+ // fromFile: absolute path of the importing .tyx file (relative
41
+ // specifiers resolve against its folder).
42
+ // stack: files currently being resolved, used to catch circular
43
+ // imports. Internal: callers leave it out.
44
+ //
45
+ // Returns { [localTagName]: sourceText }. Each source has its own
46
+ // import lines already blanked out (line numbers kept), and whatever
47
+ // those imports pulled in (icons, other components) is included in the
48
+ // result under its own tag name, so a component can import other
49
+ // components and the page does not need to know about them.
50
+ export async function resolveImportedComponents(
51
+ imports,
52
+ { baseDir, fromFile = null, stack = [] },
53
+ ) {
54
+ const root = path.resolve(baseDir)
55
+ const components = {}
56
+ const owner = {}
57
+
58
+ // The same name backed by the same text (two components both importing
59
+ // IconArrowRight) is fine. Different text under one name is an error.
60
+ const add = (local, text, from) => {
61
+ if (Object.hasOwn(components, local)) {
62
+ if (components[local] === text) return
63
+ throw new Error(
64
+ `Component "${local}" is provided by both ${owner[local]} and ${from}`,
65
+ )
66
+ }
67
+ components[local] = text
68
+ owner[local] = from
69
+ }
70
+
71
+ // Strips a component file's own imports, resolves them relative to that
72
+ // file, adds what they provide to the result, and returns the cleaned
73
+ // source.
74
+ const expand = async (text, file, label) => {
75
+ let extracted
76
+ try {
77
+ extracted = extractImports(text)
78
+ } catch (err) {
79
+ err.message = `In ${label}: ${err.message}`
80
+ throw err
81
+ }
82
+
83
+ if (extracted.imports.length > 0) {
84
+ const nested = await resolveImportedComponents(extracted.imports, {
85
+ baseDir,
86
+ fromFile: file,
87
+ stack: [...stack, file],
88
+ })
89
+ for (const [name, nestedText] of Object.entries(nested)) {
90
+ add(name, nestedText, label)
91
+ }
92
+ }
93
+
94
+ return extracted.source
95
+ }
96
+
97
+ for (const imp of imports) {
98
+ if (imp.kind === 'local') {
99
+ if (!fromFile) {
100
+ throw new Error(
101
+ `Cannot resolve "${imp.specifier}" (line ${imp.line}): the importing file's path was not provided`,
102
+ )
103
+ }
104
+ let file = path.resolve(path.dirname(fromFile), imp.specifier)
105
+ if (!path.extname(file)) file += '.tyx'
106
+ if (!file.startsWith(root + path.sep)) {
107
+ throw new Error(
108
+ `Import "${imp.specifier}" (line ${imp.line}) points outside the project`,
109
+ )
110
+ }
111
+ if (stack.includes(file)) {
112
+ throw new Error(
113
+ `Circular import: ${[...stack, file].map((f) => path.relative(root, f)).join(' -> ')}`,
114
+ )
115
+ }
116
+
117
+ let text
118
+ try {
119
+ text = await readCached(file)
120
+ } catch {
121
+ throw new Error(
122
+ `Cannot find component file for "${imp.specifier}" imported at line ${imp.line} (looked for ${file})`,
123
+ )
124
+ }
125
+
126
+ const source = await expand(text, file, path.relative(root, file))
127
+ add(imp.names[0].local, source, file)
128
+ continue
129
+ }
130
+
131
+ // package import
132
+ if (!PACKAGE_NAME_RE.test(imp.specifier)) {
133
+ throw new Error(`Invalid package name "${imp.specifier}" in import`)
134
+ }
135
+ const pkgDir = await findPackageDir(imp.specifier, root)
136
+ if (!pkgDir) {
137
+ throw new Error(
138
+ `Cannot resolve components from "${imp.specifier}": not found in node_modules (searched from ${root} upwards). Is it installed?`,
139
+ )
140
+ }
141
+
142
+ let manifest
143
+ try {
144
+ manifest = JSON.parse(await readCached(path.join(pkgDir, MANIFEST_FILE)))
145
+ } catch {
146
+ throw new Error(
147
+ `Cannot resolve components from "${imp.specifier}": missing or invalid ${MANIFEST_FILE} in ${pkgDir}`,
148
+ )
149
+ }
150
+
151
+ for (const { imported, local } of imp.names) {
152
+ if (
153
+ !Object.hasOwn(manifest, imported) ||
154
+ typeof manifest[imported] !== 'string'
155
+ ) {
156
+ throw new Error(
157
+ `"${imp.specifier}" does not export a component named "${imported}" (checked ${MANIFEST_FILE})`,
158
+ )
159
+ }
160
+ const file = path.resolve(pkgDir, manifest[imported])
161
+ if (!file.startsWith(pkgDir + path.sep)) {
162
+ throw new Error(
163
+ `"${imp.specifier}" maps "${imported}" outside its own directory (${manifest[imported]})`,
164
+ )
165
+ }
166
+ if (stack.includes(file)) {
167
+ throw new Error(`Circular import: ${[...stack, file].join(' -> ')}`)
168
+ }
169
+
170
+ const label = `${imp.specifier}:${imported}`
171
+ const source = await expand(await readCached(file), file, label)
172
+ add(local, source, label)
173
+ }
174
+ }
175
+
176
+ return components
177
+ }
178
+
179
+ // One call for the whole job: strip the import lines and load what
180
+ // they point at.
181
+ export async function collectImports(source, options) {
182
+ const { imports, source: cleaned } = extractImports(source)
183
+ const components =
184
+ imports.length > 0 ? await resolveImportedComponents(imports, options) : {}
185
+ return { source: cleaned, components }
186
+ }
package/src/index.js CHANGED
@@ -2,6 +2,7 @@ export * from './parser/parseComponent.js'
2
2
  export * from './parser/Parser.js'
3
3
  export * from './parser/parseTemplate.js'
4
4
  export * from './parser/parseExpressionString.js'
5
+ export * from './parser/languageOptions.js'
5
6
  export * from './lexer/Lexer.js'
6
7
  export * from './lexer/tokenTypes.js'
7
8
  export * from './ast/nodes.js'
@@ -18,6 +19,6 @@ export * from './typecheck/typecheckVirtualFile.js'
18
19
  export * from './typecheckPage.js'
19
20
  export * from './typecheck/transpileHelperSource.js'
20
21
  export * from './imports/extractImports.js'
21
- export * from './imports/resolvePackageComponents.js'
22
+ export * from './imports/resolveImports.js'
22
23
  export * from './runtime/capability.js'
23
- export * from './codegen/generateCapability.js'
24
+ export * from './codegen/generateCapability.js'