@hamur/adapter-angular 0.0.0-stage → 0.0.2
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/LICENSE +22 -0
- package/README.md +42 -2
- package/dist/chunks/browser-index-7h7x2xz2.js +131 -0
- package/dist/chunks/browser-index-nann848q.js +205 -0
- package/dist/chunks/browser-index-qn8q5fa2.js +580 -0
- package/dist/src/adapter.js +1075 -0
- package/dist/src/error-page.js +34 -0
- package/dist/src/index.js +1729 -0
- package/dist/src/keepalive.js +0 -0
- package/dist/src/runtime/client.js +21 -0
- package/dist/src/runtime/island.js +92 -0
- package/dist/src/runtime/server.js +175 -0
- package/dist/types/src/activation.d.ts +20 -0
- package/dist/types/src/adapter.d.ts +7 -0
- package/dist/types/src/app.d.ts +6 -0
- package/dist/types/src/async-data.d.ts +21 -0
- package/dist/types/src/client-parts.d.ts +35 -0
- package/dist/types/src/compile.d.ts +99 -0
- package/dist/types/src/context.d.ts +74 -0
- package/dist/types/src/data.d.ts +65 -0
- package/dist/types/src/definition.d.ts +13 -0
- package/dist/types/src/error-page.d.ts +8 -0
- package/dist/types/src/error.d.ts +4 -0
- package/dist/types/src/form.d.ts +68 -0
- package/dist/types/src/head.d.ts +12 -0
- package/dist/types/src/hmr.d.ts +14 -0
- package/dist/types/src/hydration.d.ts +16 -0
- package/dist/types/src/index.d.ts +24 -0
- package/dist/types/src/indicators.d.ts +76 -0
- package/dist/types/src/island.d.ts +42 -0
- package/dist/types/src/keepalive.d.ts +1 -0
- package/dist/types/src/link.d.ts +68 -0
- package/dist/types/src/markdown-page.d.ts +10 -0
- package/dist/types/src/markdown.d.ts +40 -0
- package/dist/types/src/mask.d.ts +12 -0
- package/dist/types/src/navigate.d.ts +17 -0
- package/dist/types/src/outlet.d.ts +76 -0
- package/dist/types/src/request.d.ts +31 -0
- package/dist/types/src/routing.d.ts +47 -0
- package/dist/types/src/runtime/client.d.ts +29 -0
- package/dist/types/src/runtime/hydration-dev.d.ts +1 -0
- package/dist/types/src/runtime/hydration.d.ts +8 -0
- package/dist/types/src/runtime/island.d.ts +8 -0
- package/dist/types/src/runtime/server.d.ts +15 -0
- package/dist/types/src/server-island.d.ts +24 -0
- package/dist/types/src/state.d.ts +14 -0
- package/dist/types/src/svg.d.ts +15 -0
- package/dist/types/src/time.d.ts +40 -0
- package/dist/types/src/wrapper.d.ts +21 -0
- package/package.json +77 -4
- package/src/activation.ts +83 -0
- package/src/adapter.ts +107 -0
- package/src/app.ts +12 -0
- package/src/async-data.ts +105 -0
- package/src/client-parts.ts +107 -0
- package/src/compile.ts +963 -0
- package/src/context.ts +189 -0
- package/src/data.ts +389 -0
- package/src/definition.ts +144 -0
- package/src/error-page.ts +30 -0
- package/src/error.ts +15 -0
- package/src/form.ts +182 -0
- package/src/head.ts +63 -0
- package/src/hmr.ts +61 -0
- package/src/hydration.ts +120 -0
- package/src/index.ts +98 -0
- package/src/indicators.ts +220 -0
- package/src/island.ts +89 -0
- package/src/keepalive.ts +1 -0
- package/src/link.ts +214 -0
- package/src/markdown-page.ts +31 -0
- package/src/markdown.ts +140 -0
- package/src/mask.ts +36 -0
- package/src/navigate.ts +22 -0
- package/src/outlet.ts +316 -0
- package/src/request.ts +170 -0
- package/src/routing.ts +218 -0
- package/src/runtime/client.ts +140 -0
- package/src/runtime/contract.d.ts +4 -0
- package/src/runtime/hydration-dev.ts +18 -0
- package/src/runtime/hydration.ts +7 -0
- package/src/runtime/island.ts +109 -0
- package/src/runtime/server.ts +228 -0
- package/src/server-island.ts +67 -0
- package/src/state.ts +70 -0
- package/src/svg.ts +65 -0
- package/src/time.ts +115 -0
- package/src/wrapper.ts +187 -0
package/src/compile.ts
ADDED
|
@@ -0,0 +1,963 @@
|
|
|
1
|
+
import { existsSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs"
|
|
2
|
+
import { dirname, join, relative, sep } from "node:path"
|
|
3
|
+
import type * as AngularCli from "@angular/compiler-cli"
|
|
4
|
+
import type * as AngularLinker from "@angular/compiler-cli/linker"
|
|
5
|
+
import type * as AngularLinkerBabel from "@angular/compiler-cli/linker/babel"
|
|
6
|
+
import type ts from "typescript"
|
|
7
|
+
import type { AdapterBuildContext, AdapterTransform } from "hamur/adapter"
|
|
8
|
+
import { readDefinition, selectorOf } from "./definition.ts"
|
|
9
|
+
|
|
10
|
+
const COMPILE_ID = /^(?!.*[\\/]node_modules[\\/]).*\.[cm]?ts$/
|
|
11
|
+
/** Packages of the `@hamur` scope ship their partial-compiled components under the name of the source, `src/<name>.ts`. */
|
|
12
|
+
const LINK_ID = /[\\/]node_modules[\\/](?:.+\.m?js|(?:.+[\\/])?@hamur[\\/][^\\/]+[\\/]src[\\/].+\.ts)$/
|
|
13
|
+
|
|
14
|
+
const SCRIPT = /\.[cm]?ts$/
|
|
15
|
+
const DECORATED = /^\s*@(?:Component|Directive|Pipe|NgModule|Injectable)\s*\(/m
|
|
16
|
+
const ENTRY = /^(?:(pages|layouts)\/.+|(app|error))\.[cm]?ts$/
|
|
17
|
+
const NOT_AN_ENTRY = /\.load\.[cm]?ts$|\.d\.[cm]?ts$/
|
|
18
|
+
const KINDS: Record<string, string> = { pages: "page", layouts: "layout", app: "app root", error: "error page" }
|
|
19
|
+
const MAP_COMMENT = /\n\/\/# sourceMappingURL=\S+\s*$/
|
|
20
|
+
const STYLE_LANG = /\.(scss|sass|less|styl|stylus)$/
|
|
21
|
+
const PREPROCESSED: Record<string, string> = {
|
|
22
|
+
scss: "sass",
|
|
23
|
+
sass: "sass",
|
|
24
|
+
less: "less",
|
|
25
|
+
styl: "stylus",
|
|
26
|
+
stylus: "stylus",
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
interface Babel {
|
|
30
|
+
transformAsync(code: string, options: Record<string, unknown>): Promise<{ code?: string | null } | null>
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
interface Angular {
|
|
34
|
+
cli: typeof AngularCli
|
|
35
|
+
ts: typeof ts
|
|
36
|
+
needsLinking: typeof AngularLinker.needsLinking
|
|
37
|
+
linkerPlugin: ReturnType<typeof AngularLinkerBabel.createEs2015LinkerPlugin>
|
|
38
|
+
babel: Babel
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface AngularEmit {
|
|
42
|
+
code: string
|
|
43
|
+
map?: string
|
|
44
|
+
/** The declarations, emitted by `compilePartial` only. */
|
|
45
|
+
types?: string
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** One error line of the program, with the real path of the file it names. */
|
|
49
|
+
interface Problem {
|
|
50
|
+
file?: string
|
|
51
|
+
line: string
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const real = (path: string): string => {
|
|
55
|
+
try {
|
|
56
|
+
return realpathSync(path)
|
|
57
|
+
} catch {
|
|
58
|
+
return path
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const angulars = new Map<string, Promise<Angular>>()
|
|
63
|
+
|
|
64
|
+
/** The app's own `@angular/compiler-cli`, and the `typescript` and `@babel/core` it resolves from its own directory. */
|
|
65
|
+
function loadAngular(rootDir: string): Promise<Angular> {
|
|
66
|
+
const dir = dirname(Bun.resolveSync("@angular/compiler-cli/package.json", rootDir))
|
|
67
|
+
let loaded = angulars.get(dir)
|
|
68
|
+
if (!loaded) angulars.set(dir, (loaded = importAngular(rootDir, dir)))
|
|
69
|
+
return loaded
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async function importAngular(rootDir: string, dir: string): Promise<Angular> {
|
|
73
|
+
const cli = (await import(Bun.resolveSync("@angular/compiler-cli", rootDir))) as typeof AngularCli
|
|
74
|
+
const linker = (await import(Bun.resolveSync("@angular/compiler-cli/linker", rootDir))) as typeof AngularLinker
|
|
75
|
+
const linkerBabel = (await import(
|
|
76
|
+
Bun.resolveSync("@angular/compiler-cli/linker/babel", rootDir)
|
|
77
|
+
)) as typeof AngularLinkerBabel
|
|
78
|
+
const typescript = (await import(Bun.resolveSync("typescript", dir))) as { default: typeof ts }
|
|
79
|
+
const babel = (await import(Bun.resolveSync("@babel/core", dir))) as Babel
|
|
80
|
+
return {
|
|
81
|
+
cli,
|
|
82
|
+
ts: typescript.default,
|
|
83
|
+
needsLinking: linker.needsLinking,
|
|
84
|
+
linkerPlugin: linkerBabel.createEs2015LinkerPlugin({
|
|
85
|
+
linkerJitMode: false,
|
|
86
|
+
fileSystem: new cli.NodeJSFileSystem(),
|
|
87
|
+
logger: new cli.ConsoleLogger(cli.LogLevel.warn),
|
|
88
|
+
}),
|
|
89
|
+
babel,
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function scripts(dir: string): string[] {
|
|
94
|
+
const found: string[] = []
|
|
95
|
+
for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : 1))) {
|
|
96
|
+
if (entry.name === "node_modules" || entry.name.startsWith(".")) continue
|
|
97
|
+
const path = join(dir, entry.name)
|
|
98
|
+
if (entry.isDirectory()) found.push(...scripts(path))
|
|
99
|
+
else if (SCRIPT.test(entry.name)) found.push(path)
|
|
100
|
+
}
|
|
101
|
+
return found
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** In the workspace the package's own components are sources outside `node_modules`, compiled with the app; published, they are partial-compiled and linked. */
|
|
105
|
+
function ownComponents(): string[] {
|
|
106
|
+
if (/[\\/]node_modules[\\/]/.test(import.meta.dir)) return []
|
|
107
|
+
return scripts(import.meta.dir).filter(
|
|
108
|
+
(file) => !file.endsWith(".test.ts") && DECORATED.test(readFileSync(file, "utf8")),
|
|
109
|
+
)
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** The directories of the `@hamur/*` packages the app links from the workspace that have an `./angular` export. */
|
|
113
|
+
function modulePackages(rootDir: string): string[] {
|
|
114
|
+
const scope = join(rootDir, "node_modules", "@hamur")
|
|
115
|
+
if (!existsSync(scope)) return []
|
|
116
|
+
return readdirSync(scope)
|
|
117
|
+
.map((name) => real(join(scope, name)))
|
|
118
|
+
.filter((dir) => {
|
|
119
|
+
if (/[\\/]node_modules[\\/]/.test(dir)) return false
|
|
120
|
+
try {
|
|
121
|
+
const { exports } = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")) as { exports?: object }
|
|
122
|
+
return typeof exports === "object" && exports !== null && "./angular" in exports
|
|
123
|
+
} catch {
|
|
124
|
+
return false
|
|
125
|
+
}
|
|
126
|
+
})
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* In the workspace the components of a module's `./angular` entry (`@hamur/image`, `@hamur/icon`) are roots of the app's
|
|
131
|
+
* program, like the adapter's own; published, they are partial-compiled and linked, the same as the adapter's.
|
|
132
|
+
*/
|
|
133
|
+
function moduleComponents(rootDir: string): string[] {
|
|
134
|
+
return modulePackages(rootDir).flatMap((dir) =>
|
|
135
|
+
scripts(join(dir, "src")).filter(
|
|
136
|
+
(file) => !file.endsWith(".test.ts") && DECORATED.test(readFileSync(file, "utf8")),
|
|
137
|
+
),
|
|
138
|
+
)
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** The nearest directory holding both `a` and `b`. */
|
|
142
|
+
function commonDir(a: string, b: string): string {
|
|
143
|
+
let dir = a
|
|
144
|
+
while (relative(dir, b).startsWith("..")) dir = dirname(dir)
|
|
145
|
+
return dir
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* In the workspace the package's components are roots outside the app, and Angular emits a reference to a symbol only inside
|
|
150
|
+
* the compiler's `rootDir`, which defaults to the app's directory (`NG3004`): one that holds both is its logical project, also as the last of the `rootDirs` the generated tsconfig lists.
|
|
151
|
+
*/
|
|
152
|
+
function workspaceRoot(rootDir: string, base: ts.CompilerOptions): ts.CompilerOptions {
|
|
153
|
+
if (!ownComponents().length) return {}
|
|
154
|
+
const root = [...modulePackages(rootDir), real(dirname(import.meta.dir))].reduce(commonDir, real(rootDir))
|
|
155
|
+
return { rootDir: root, ...(base.rootDirs ? { rootDirs: [...base.rootDirs, root] } : {}) }
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Every `.ts` file under `app/`, then the package's own components; `server/` is never a root. */
|
|
159
|
+
function rootNames(rootDir: string): string[] {
|
|
160
|
+
const app = join(rootDir, "app")
|
|
161
|
+
return [...(existsSync(app) ? scripts(app) : []), ...ownComponents(), ...moduleComponents(rootDir)]
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const shown = (rootDir: string, file: string): string => relative(rootDir, file).split(sep).join("/")
|
|
165
|
+
|
|
166
|
+
/** `app/pages/x.ts(12,5): error NG8002: …`, the uncolored line `formatDiagnostics` does not print. */
|
|
167
|
+
function diagnosticProblem(typescript: typeof ts, diagnostic: ts.Diagnostic, rootDir: string): Problem {
|
|
168
|
+
const code = diagnostic.code < 0 ? `NG${String(-diagnostic.code).slice(2)}` : `TS${diagnostic.code}`
|
|
169
|
+
const message = typescript.flattenDiagnosticMessageText(diagnostic.messageText, "\n")
|
|
170
|
+
if (!diagnostic.file || diagnostic.start === undefined) return { line: `error ${code}: ${message}` }
|
|
171
|
+
const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start)
|
|
172
|
+
return {
|
|
173
|
+
file: real(diagnostic.file.fileName),
|
|
174
|
+
line: `${shown(rootDir, diagnostic.file.fileName)}(${line + 1},${character + 1}): error ${code}: ${message}`,
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function isComponent(typescript: typeof ts, node: ts.ClassDeclaration | ts.ClassExpression): boolean {
|
|
179
|
+
return (typescript.getDecorators(node) ?? []).some(({ expression }) => {
|
|
180
|
+
if (!typescript.isCallExpression(expression)) return false
|
|
181
|
+
const callee = expression.expression
|
|
182
|
+
if (typescript.isIdentifier(callee)) return callee.text === "Component"
|
|
183
|
+
return typescript.isPropertyAccessExpression(callee) && callee.name.text === "Component"
|
|
184
|
+
})
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** What a default export is when it is not a `@Component` class; `undefined` when it is one. */
|
|
188
|
+
function found(typescript: typeof ts, node: ts.Node): string | undefined {
|
|
189
|
+
if (typescript.isExportAssignment(node)) return found(typescript, node.expression)
|
|
190
|
+
if (typescript.isVariableDeclaration(node))
|
|
191
|
+
return node.initializer ? found(typescript, node.initializer) : "undefined"
|
|
192
|
+
if (
|
|
193
|
+
typescript.isParenthesizedExpression(node) ||
|
|
194
|
+
typescript.isAsExpression(node) ||
|
|
195
|
+
typescript.isSatisfiesExpression(node)
|
|
196
|
+
)
|
|
197
|
+
return found(typescript, node.expression)
|
|
198
|
+
if (typescript.isClassDeclaration(node) || typescript.isClassExpression(node))
|
|
199
|
+
return isComponent(typescript, node) ? undefined : "class without @Component"
|
|
200
|
+
if (typescript.isFunctionLike(node)) return "function"
|
|
201
|
+
if (typescript.isObjectLiteralExpression(node)) return "object"
|
|
202
|
+
if (typescript.isArrayLiteralExpression(node)) return "array"
|
|
203
|
+
if (typescript.isStringLiteralLike(node) || typescript.isTemplateExpression(node)) return "string"
|
|
204
|
+
if (typescript.isNumericLiteral(node)) return "number"
|
|
205
|
+
return "other value"
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** A page, layout, app root or error page default-exports a `@Component` class. */
|
|
209
|
+
function defaultExportErrors(
|
|
210
|
+
typescript: typeof ts,
|
|
211
|
+
program: ts.Program,
|
|
212
|
+
rootDir: string,
|
|
213
|
+
roots: readonly string[],
|
|
214
|
+
): Problem[] {
|
|
215
|
+
const checker = program.getTypeChecker()
|
|
216
|
+
const app = join(rootDir, "app")
|
|
217
|
+
const errors: Problem[] = []
|
|
218
|
+
for (const file of roots) {
|
|
219
|
+
const rel = shown(app, file)
|
|
220
|
+
const entry = ENTRY.exec(rel)
|
|
221
|
+
if (!entry || NOT_AN_ENTRY.test(rel)) continue
|
|
222
|
+
const source = program.getSourceFile(file)
|
|
223
|
+
const module = source && checker.getSymbolAtLocation(source)
|
|
224
|
+
const exported = module && checker.tryGetMemberInModuleExports("default", module)
|
|
225
|
+
if (!exported) continue
|
|
226
|
+
const symbol = exported.flags & typescript.SymbolFlags.Alias ? checker.getAliasedSymbol(exported) : exported
|
|
227
|
+
const node = symbol.valueDeclaration ?? symbol.declarations?.[0]
|
|
228
|
+
const kind = node ? found(typescript, node) : "undefined"
|
|
229
|
+
if (kind !== undefined)
|
|
230
|
+
errors.push({
|
|
231
|
+
file: real(file),
|
|
232
|
+
line: `${shown(rootDir, file)}: the default export of an Angular ${KINDS[entry[1] ?? entry[2]!]} must be a class with @Component (found: ${kind})`,
|
|
233
|
+
})
|
|
234
|
+
}
|
|
235
|
+
return errors
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** `./x.scss` as a component names it: the style file relative to the file that names it. */
|
|
239
|
+
function asWritten(containingFile: string, resourceFile: string): string {
|
|
240
|
+
const path = relative(dirname(containingFile), resourceFile).split(sep).join("/")
|
|
241
|
+
return path.startsWith("../") ? path : `./${path}`
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
interface HostOptions {
|
|
245
|
+
rootDir: string
|
|
246
|
+
preprocessStyle: AdapterBuildContext["preprocessStyle"]
|
|
247
|
+
/** Receives each emitted `.js` and map under the real path of its source. */
|
|
248
|
+
files: Map<string, AngularEmit>
|
|
249
|
+
/** Each resource the program reads, and each file a preprocessed style file imported (`dependencies`) with that style file. */
|
|
250
|
+
onResource?(file: string, from?: string): void
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* The program's compiler host: the emit goes into `files`; resources are read through `readResource`, so Angular preloads
|
|
255
|
+
* them and a `styleUrl` in a style language goes through `preprocessStyle`.
|
|
256
|
+
*/
|
|
257
|
+
function compilerHost(ng: Angular, options: AngularCli.CompilerOptions, setup: HostOptions): AngularCli.CompilerHost {
|
|
258
|
+
const host = ng.cli.createCompilerHost({ options })
|
|
259
|
+
host.writeFile = (fileName, text, _bom, _onError, sources) => {
|
|
260
|
+
const source = sources?.[0]
|
|
261
|
+
if (!source) return
|
|
262
|
+
const key = real(source.fileName)
|
|
263
|
+
const entry = setup.files.get(key) ?? { code: "" }
|
|
264
|
+
if (fileName.endsWith(".map")) entry.map = text
|
|
265
|
+
else if (fileName.endsWith(".d.ts")) entry.types = text
|
|
266
|
+
else if (/\.[cm]?js$/.test(fileName)) entry.code = text.replace(MAP_COMMENT, "")
|
|
267
|
+
else return
|
|
268
|
+
setup.files.set(key, entry)
|
|
269
|
+
}
|
|
270
|
+
host.readResource = (file) => {
|
|
271
|
+
const text = host.readFile(file)
|
|
272
|
+
if (text === undefined) throw new Error(`${shown(setup.rootDir, file)}: cannot be read`)
|
|
273
|
+
setup.onResource?.(file)
|
|
274
|
+
return text
|
|
275
|
+
}
|
|
276
|
+
host.transformResource = async (data, context) => {
|
|
277
|
+
const file = context.resourceFile
|
|
278
|
+
const lang = file ? STYLE_LANG.exec(file)?.[1] : undefined
|
|
279
|
+
if (!file || !lang) return null
|
|
280
|
+
if (!setup.preprocessStyle)
|
|
281
|
+
throw new Error(
|
|
282
|
+
`${shown(setup.rootDir, context.containingFile)}: styleUrl "${asWritten(context.containingFile, file)}" needs the @hamur/css module: install @hamur/css and ${PREPROCESSED[lang]} and add "@hamur/css" to modules`,
|
|
283
|
+
)
|
|
284
|
+
const css = await setup.preprocessStyle({ lang, code: data, file })
|
|
285
|
+
for (const dependency of css.dependencies) setup.onResource?.(dependency, file)
|
|
286
|
+
return { content: css.code }
|
|
287
|
+
}
|
|
288
|
+
return host
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** The errors of the three `getNg*Diagnostics` and of `check`; warnings are not printed. */
|
|
292
|
+
function problemsOf(
|
|
293
|
+
ng: Angular,
|
|
294
|
+
program: AngularCli.NgtscProgram,
|
|
295
|
+
rootDir: string,
|
|
296
|
+
check?: (program: ts.Program) => Problem[],
|
|
297
|
+
): Problem[] {
|
|
298
|
+
const problems = [
|
|
299
|
+
...program.getNgOptionDiagnostics(),
|
|
300
|
+
...program.getNgStructuralDiagnostics(),
|
|
301
|
+
...program.getNgSemanticDiagnostics(),
|
|
302
|
+
]
|
|
303
|
+
.filter((diagnostic) => diagnostic.category === ng.ts.DiagnosticCategory.Error)
|
|
304
|
+
.map((diagnostic) => diagnosticProblem(ng.ts, diagnostic, rootDir))
|
|
305
|
+
if (check) problems.push(...check(program.getTsProgram()))
|
|
306
|
+
return problems
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Emits the source files whose real path `emits` keeps. TypeScript type-checks each file it emits in full, and in the
|
|
311
|
+
* workspace the program also holds the core's sources that the package's own components import.
|
|
312
|
+
*/
|
|
313
|
+
function emitOnly(program: AngularCli.NgtscProgram, emits: (file: string) => boolean): void {
|
|
314
|
+
program.emit({
|
|
315
|
+
emitCallback: ({
|
|
316
|
+
program: tsProgram,
|
|
317
|
+
targetSourceFile,
|
|
318
|
+
writeFile,
|
|
319
|
+
cancellationToken,
|
|
320
|
+
emitOnlyDtsFiles,
|
|
321
|
+
customTransformers,
|
|
322
|
+
}) =>
|
|
323
|
+
targetSourceFile && !emits(real(targetSourceFile.fileName))
|
|
324
|
+
? { emitSkipped: true, diagnostics: [] }
|
|
325
|
+
: tsProgram.emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers),
|
|
326
|
+
})
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** One `NgtscProgram` over `roots`, emitted into memory for the files `emits` keeps: real source path to its JavaScript and, with `sourceMap`, its map. */
|
|
330
|
+
async function emitProgram(
|
|
331
|
+
ng: Angular,
|
|
332
|
+
rootDir: string,
|
|
333
|
+
roots: readonly string[],
|
|
334
|
+
options: AngularCli.CompilerOptions,
|
|
335
|
+
preprocessStyle: AdapterBuildContext["preprocessStyle"],
|
|
336
|
+
emits: (file: string) => boolean,
|
|
337
|
+
check?: (program: ts.Program) => Problem[],
|
|
338
|
+
): Promise<Map<string, AngularEmit>> {
|
|
339
|
+
const files = new Map<string, AngularEmit>()
|
|
340
|
+
const program = new ng.cli.NgtscProgram(
|
|
341
|
+
roots,
|
|
342
|
+
options,
|
|
343
|
+
compilerHost(ng, options, { rootDir, preprocessStyle, files }),
|
|
344
|
+
)
|
|
345
|
+
await program.loadNgStructureAsync()
|
|
346
|
+
const problems = problemsOf(ng, program, rootDir, check)
|
|
347
|
+
if (problems.length) throw new Error(problems.map((problem) => problem.line).join("\n"))
|
|
348
|
+
// A load file's `#server` pulls `server/` into the program; its emit must not replace the server files in the client build.
|
|
349
|
+
const server = `${real(join(rootDir, "server"))}${sep}`
|
|
350
|
+
emitOnly(program, (file) => emits(file) && !file.startsWith(server))
|
|
351
|
+
return files
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
function readConfig(typescript: typeof ts, file: string): Record<string, unknown> | undefined {
|
|
355
|
+
if (!existsSync(file)) return undefined
|
|
356
|
+
const read = typescript.readConfigFile(file, typescript.sys.readFile)
|
|
357
|
+
if (read.error) throw new Error(`${file}: ${typescript.flattenDiagnosticMessageText(read.error.messageText, "\n")}`)
|
|
358
|
+
return read.config as Record<string, unknown>
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/** `<buildDir>/tsconfig.app.json`, the app's `angularCompilerOptions`, then the options that win. */
|
|
362
|
+
function compilerOptions(typescript: typeof ts, ctx: AdapterBuildContext): AngularCli.CompilerOptions {
|
|
363
|
+
const appFile = join(ctx.buildDir, "tsconfig.app.json")
|
|
364
|
+
const app = readConfig(typescript, appFile)
|
|
365
|
+
const base: ts.CompilerOptions = app
|
|
366
|
+
? typescript.parseJsonConfigFileContent(app, typescript.sys, dirname(appFile)).options
|
|
367
|
+
: {
|
|
368
|
+
moduleResolution: typescript.ModuleResolutionKind.Bundler,
|
|
369
|
+
lib: ["lib.esnext.d.ts", "lib.dom.d.ts", "lib.dom.iterable.d.ts"],
|
|
370
|
+
types: [],
|
|
371
|
+
strict: true,
|
|
372
|
+
skipLibCheck: true,
|
|
373
|
+
allowImportingTsExtensions: true,
|
|
374
|
+
}
|
|
375
|
+
const angular = (readConfig(typescript, join(ctx.rootDir, "tsconfig.json"))?.angularCompilerOptions ?? {}) as Record<
|
|
376
|
+
string,
|
|
377
|
+
unknown
|
|
378
|
+
>
|
|
379
|
+
return {
|
|
380
|
+
...base,
|
|
381
|
+
...angular,
|
|
382
|
+
...workspaceRoot(ctx.rootDir, base),
|
|
383
|
+
compilationMode: "full",
|
|
384
|
+
strictTemplates: true,
|
|
385
|
+
module: typescript.ModuleKind.ESNext,
|
|
386
|
+
target: typescript.ScriptTarget.ES2022,
|
|
387
|
+
declaration: false,
|
|
388
|
+
noEmit: false,
|
|
389
|
+
emitDeclarationOnly: false,
|
|
390
|
+
noEmitOnError: false,
|
|
391
|
+
sourceMap: ctx.dev,
|
|
392
|
+
inlineSources: ctx.dev,
|
|
393
|
+
...(ctx.hmr ? { _enableHmr: true } : {}),
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
const programs = new Map<string, { stamp: string; files: Promise<Map<string, AngularEmit>> }>()
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* The app's program, shared by the client and server builds of one `hamur build`: the client and server steps
|
|
401
|
+
* find the same roots unchanged and take the same emit; a later build in the process whose roots changed compiles again.
|
|
402
|
+
*/
|
|
403
|
+
export function angularProgram(ctx: AdapterBuildContext): Promise<Map<string, AngularEmit>> {
|
|
404
|
+
const roots = rootNames(ctx.rootDir)
|
|
405
|
+
const stamp = roots
|
|
406
|
+
.map((file) => {
|
|
407
|
+
const stat = statSync(file)
|
|
408
|
+
return `${file}:${stat.size}:${stat.mtimeMs}`
|
|
409
|
+
})
|
|
410
|
+
.join("\n")
|
|
411
|
+
const key = `${ctx.rootDir}\0${ctx.buildDir}\0${ctx.dev}`
|
|
412
|
+
const hit = programs.get(key)
|
|
413
|
+
if (hit?.stamp === stamp) return hit.files
|
|
414
|
+
const app = `${real(ctx.rootDir)}${sep}`
|
|
415
|
+
const own = new Set([...ownComponents(), ...moduleComponents(ctx.rootDir)].map(real))
|
|
416
|
+
const files = loadAngular(ctx.rootDir).then((ng) =>
|
|
417
|
+
emitProgram(
|
|
418
|
+
ng,
|
|
419
|
+
ctx.rootDir,
|
|
420
|
+
roots,
|
|
421
|
+
compilerOptions(ng.ts, ctx),
|
|
422
|
+
ctx.preprocessStyle,
|
|
423
|
+
(path) => path.startsWith(app) || own.has(path),
|
|
424
|
+
(program) => defaultExportErrors(ng.ts, program, ctx.rootDir, roots),
|
|
425
|
+
),
|
|
426
|
+
)
|
|
427
|
+
programs.set(key, { stamp, files })
|
|
428
|
+
return files
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
const stampOf = (file: string): string => {
|
|
432
|
+
const stat = statSync(file, { throwIfNoEntry: false })
|
|
433
|
+
return stat ? `${stat.mtimeMs}:${stat.size}` : "missing"
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
const devPrograms = new Map<string, AngularDevProgram>()
|
|
437
|
+
const devBases = new Map<string, string>()
|
|
438
|
+
|
|
439
|
+
/** The one program of a `hamur dev` process for `rootDir` and `buildDir`, shared by every step that process makes. */
|
|
440
|
+
export function angularDevProgram(ctx: AdapterBuildContext): AngularDevProgram {
|
|
441
|
+
const key = `${ctx.rootDir}\0${ctx.buildDir}`
|
|
442
|
+
let program = devPrograms.get(key)
|
|
443
|
+
if (!program) devPrograms.set(key, (program = new AngularDevProgram(ctx)))
|
|
444
|
+
return program
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/** The dev program of `rootDir` and `buildDir` once a load built it; the adapter's hooks read it. */
|
|
448
|
+
export const devProgramOf = (rootDir: string, buildDir: string): AngularDevProgram | undefined =>
|
|
449
|
+
devPrograms.get(`${rootDir}\0${buildDir}`)
|
|
450
|
+
|
|
451
|
+
/** Drops the dev program and base URL of `rootDir` and `buildDir`: a closed `hamur dev` must not keep its whole `NgtscProgram`. */
|
|
452
|
+
export function releaseDevProgram(rootDir: string, buildDir: string): void {
|
|
453
|
+
devPrograms.delete(`${rootDir}\0${buildDir}`)
|
|
454
|
+
devBases.delete(`${rootDir}\0${buildDir}`)
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/** `app.baseURL`, which the `modules:done` hook records for the `ɵɵgetReplaceMetadataURL` rewrite. */
|
|
458
|
+
export function setDevBaseURL(rootDir: string, buildDir: string, baseURL: string): void {
|
|
459
|
+
devBases.set(`${rootDir}\0${buildDir}`, baseURL)
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
const HMR_URL = /(ɵɵgetReplaceMetadataURL\([^()]*?,\s*)import\.meta\.url\)/g
|
|
463
|
+
const HMR_LISTEN = /import\.meta\.hot\s*&&\s*import\.meta\.hot\.on\(\s*(["'])angular:component-update\1/g
|
|
464
|
+
const HMR_FIRST_LOAD = /\b([A-Za-z_$][\w$]*_HmrLoad)\(Date\.now\(\)\)/g
|
|
465
|
+
const HMR_FOOTER = `
|
|
466
|
+
import { onDevEvent as ɵhamurOnDevEvent } from "hamur/app";
|
|
467
|
+
function ɵhamurNgOn(event, handler) { queueMicrotask(() => ɵhamurOnDevEvent(event, handler)); }
|
|
468
|
+
`
|
|
469
|
+
|
|
470
|
+
/**
|
|
471
|
+
* Angular's HMR initializer (`_enableHmr`) listens on `import.meta.hot` and resolves the update module
|
|
472
|
+
* against `import.meta.url`. In the client its listener goes to `onDevEvent`, one microtask later since an app root runs before
|
|
473
|
+
* the dev client entry makes the channel, and its base becomes `app.baseURL`; on the server its first load is dropped.
|
|
474
|
+
*/
|
|
475
|
+
export function rewriteHmrInitializer(code: string, target: "client" | "server", baseURL: string): string {
|
|
476
|
+
if (target === "server") return code.replace(HMR_FIRST_LOAD, "void 0")
|
|
477
|
+
const listened = code.replace(HMR_LISTEN, `ɵhamurNgOn("angular:component-update"`)
|
|
478
|
+
if (listened === code) return code
|
|
479
|
+
const base = `new URL(${JSON.stringify(baseURL)}, location.href).href`
|
|
480
|
+
return `${listened.replace(HMR_URL, (_call, head: string) => `${head}${base})`)}${HMR_FOOTER}`
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
export interface AngularHotUpdate {
|
|
484
|
+
/** Angular's id of the component, the URI-encoded `<file>@<ClassName>` its initializer compares. */
|
|
485
|
+
id: string
|
|
486
|
+
/** The update module `emitHmrUpdateModule` gave. */
|
|
487
|
+
code: string
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/**
|
|
491
|
+
* Built on the first load, then built again with the last good `NgtscProgram` as `oldProgram` when a load finds a
|
|
492
|
+
* root whose text, or a resource whose stamp, changed. Unchanged source files keep their `ts.SourceFile`, so Angular reuses
|
|
493
|
+
* their analysis and emits only the files the change reaches.
|
|
494
|
+
*/
|
|
495
|
+
export class AngularDevProgram {
|
|
496
|
+
/** The real paths the last build emitted. */
|
|
497
|
+
emitted: string[] = []
|
|
498
|
+
private readonly ctx: AdapterBuildContext
|
|
499
|
+
private readonly root: string
|
|
500
|
+
private readonly app: string
|
|
501
|
+
private readonly server: string
|
|
502
|
+
private readonly own: Set<string>
|
|
503
|
+
private readonly files = new Map<string, AngularEmit>()
|
|
504
|
+
/** Real path of each source file of the program to the text it compiled. */
|
|
505
|
+
private readonly texts = new Map<string, string>()
|
|
506
|
+
/** Each resource the program read (templates, style files, a style file's imports) to its stamp when read. */
|
|
507
|
+
private readonly resources = new Map<string, string>()
|
|
508
|
+
/** A style file's import to the style files that import it: Angular tracks the style file, not its imports. */
|
|
509
|
+
private readonly importers = new Map<string, Set<string>>()
|
|
510
|
+
private readonly sourceFiles = new Map<string, { stamp: string; file: ts.SourceFile }>()
|
|
511
|
+
/** Real path of each component file to the real paths of the resources it reads (`getResourceDependencies`). */
|
|
512
|
+
private readonly resourcesOf = new Map<string, Set<string>>()
|
|
513
|
+
/** Component files a hot update left with errors. */
|
|
514
|
+
private readonly broken = new Set<string>()
|
|
515
|
+
private options: AngularCli.CompilerOptions | undefined
|
|
516
|
+
private program: AngularCli.NgtscProgram | undefined
|
|
517
|
+
private problems: Problem[] = []
|
|
518
|
+
private failure: Error | undefined
|
|
519
|
+
private built = false
|
|
520
|
+
private queue: Promise<void> = Promise.resolve()
|
|
521
|
+
|
|
522
|
+
constructor(ctx: AdapterBuildContext) {
|
|
523
|
+
this.ctx = ctx
|
|
524
|
+
this.root = `${real(ctx.rootDir)}${sep}`
|
|
525
|
+
this.app = `${real(join(ctx.rootDir, "app"))}${sep}`
|
|
526
|
+
this.server = `${real(join(ctx.rootDir, "server"))}${sep}`
|
|
527
|
+
this.own = new Set([...ownComponents(), ...moduleComponents(ctx.rootDir)].map(real))
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/** As in a build: a load file's `#server` pulls `server/` into the program, whose emit must not replace the server files in the client. */
|
|
531
|
+
private emits(path: string): boolean {
|
|
532
|
+
return (path.startsWith(this.root) && !path.startsWith(this.server)) || this.own.has(path)
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/** The emit of `path` (a real path) after any build its load calls for; throws the program's errors for that file. */
|
|
536
|
+
async load(path: string): Promise<AngularEmit | undefined> {
|
|
537
|
+
if (!this.emits(path)) return undefined
|
|
538
|
+
const text = existsSync(path) ? readFileSync(path, "utf8") : undefined
|
|
539
|
+
const next = this.queue.then(async () => {
|
|
540
|
+
const modified = this.modifiedResources()
|
|
541
|
+
if (this.built && modified.length === 0 && !this.stale(path, text)) return
|
|
542
|
+
await this.build(modified)
|
|
543
|
+
})
|
|
544
|
+
this.queue = next.catch(() => {})
|
|
545
|
+
await next
|
|
546
|
+
if (this.failure) throw this.failure
|
|
547
|
+
if (!this.texts.has(path)) return undefined
|
|
548
|
+
const problems = this.problems.filter(
|
|
549
|
+
(problem) => problem.file === undefined || problem.file === path || this.reads(path, problem.file),
|
|
550
|
+
)
|
|
551
|
+
if (problems.length) throw new Error(problems.map((problem) => problem.line).join("\n"))
|
|
552
|
+
return this.files.get(path)
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
private stale(path: string, text: string | undefined): boolean {
|
|
556
|
+
const compiled = this.texts.get(path)
|
|
557
|
+
if (compiled !== undefined) return compiled !== text
|
|
558
|
+
return text !== undefined && path.startsWith(this.app) && SCRIPT.test(path) && !/\.d\.[cm]?ts$/.test(path)
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
/** The stamps of the resources the components of `path` read, so `hamur dev`'s cache misses after an edit of one. */
|
|
562
|
+
version(path: string): string {
|
|
563
|
+
const files = this.resourcesOf.get(path)
|
|
564
|
+
if (!files) return ""
|
|
565
|
+
return [...files, ...this.styleImportsOf(files)]
|
|
566
|
+
.sort()
|
|
567
|
+
.map((file) => `${file}:${stampOf(file)}`)
|
|
568
|
+
.join("\n")
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
/** Real paths of the component files that read `file`, a resource or a file a style resource imports; none for any other file. */
|
|
572
|
+
dependentsOf(file: string): string[] {
|
|
573
|
+
const path = real(file)
|
|
574
|
+
return [...this.resourcesOf.keys()].filter((component) => this.reads(component, path))
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
/**
|
|
578
|
+
* Builds the program again for an edit of `file` and gives the update module of each component that
|
|
579
|
+
* reads it. A component left with errors is in `reload` instead, so Bun loads it again and shows the error, and once more
|
|
580
|
+
* after the fix; a file that is no resource gives neither.
|
|
581
|
+
*/
|
|
582
|
+
async hotUpdate(file: string): Promise<{ updates: AngularHotUpdate[]; reload: string[] }> {
|
|
583
|
+
const path = real(file)
|
|
584
|
+
const resources = [...this.resources.keys()].filter((resource) => real(resource) === path)
|
|
585
|
+
if (!resources.length) return { updates: [], reload: [] }
|
|
586
|
+
const next = this.queue.then(async () => {
|
|
587
|
+
const modified = this.modifiedResources()
|
|
588
|
+
if (modified.length) await this.build(modified)
|
|
589
|
+
})
|
|
590
|
+
this.queue = next.catch(() => {})
|
|
591
|
+
await next
|
|
592
|
+
const components = this.dependentsOf(path)
|
|
593
|
+
const program = this.program
|
|
594
|
+
const failing =
|
|
595
|
+
this.failure || !program
|
|
596
|
+
? components
|
|
597
|
+
: components.filter((component) =>
|
|
598
|
+
this.problems.some(
|
|
599
|
+
(problem) => problem.file === component || (!!problem.file && this.reads(component, problem.file)),
|
|
600
|
+
),
|
|
601
|
+
)
|
|
602
|
+
if (failing.length || !program) {
|
|
603
|
+
for (const component of failing) this.broken.add(component)
|
|
604
|
+
return { updates: [], reload: failing }
|
|
605
|
+
}
|
|
606
|
+
const reload = components.filter((component) => this.broken.delete(component))
|
|
607
|
+
const ng = await loadAngular(this.ctx.rootDir)
|
|
608
|
+
const styles = resources.flatMap((resource) => [...(this.importers.get(resource) ?? [])])
|
|
609
|
+
const nodes = new Set<ts.Declaration>()
|
|
610
|
+
for (const resource of [...resources, ...styles]) {
|
|
611
|
+
for (const node of program.compiler.getComponentsWithTemplateFile(resource)) nodes.add(node)
|
|
612
|
+
for (const node of program.compiler.getComponentsWithStyleFile(resource)) nodes.add(node)
|
|
613
|
+
}
|
|
614
|
+
const updates: AngularHotUpdate[] = []
|
|
615
|
+
for (const node of nodes) {
|
|
616
|
+
if (!ng.ts.isClassDeclaration(node) || !node.name) continue
|
|
617
|
+
const code = program.compiler.emitHmrUpdateModule(node)
|
|
618
|
+
const name = node.name.text.replace(/[$]/g, "\\$&")
|
|
619
|
+
const emitted = this.files.get(real(node.getSourceFile().fileName))?.code ?? ""
|
|
620
|
+
const id = new RegExp(`"([^"]*%40${name})"`).exec(emitted)?.[1]
|
|
621
|
+
if (code !== null && id) updates.push({ id, code })
|
|
622
|
+
}
|
|
623
|
+
return { updates, reload }
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/** Whether the component file `component` reads `file`: one of its resources, or a file one of its style resources imports. */
|
|
627
|
+
private reads(component: string, file: string): boolean {
|
|
628
|
+
const files = this.resourcesOf.get(component)
|
|
629
|
+
return !!files && (files.has(file) || this.styleImportsOf(files).includes(file))
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
/** Real paths of the files the style resources among `files` imported (their preprocessor `dependencies`). */
|
|
633
|
+
private styleImportsOf(files: ReadonlySet<string>): string[] {
|
|
634
|
+
const found: string[] = []
|
|
635
|
+
for (const [dependency, importers] of this.importers)
|
|
636
|
+
if ([...importers].some((importer) => files.has(real(importer)))) found.push(real(dependency))
|
|
637
|
+
return found
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
private modifiedResources(): string[] {
|
|
641
|
+
const modified = new Set<string>()
|
|
642
|
+
for (const [file, stamp] of this.resources) {
|
|
643
|
+
if (stampOf(file) === stamp) continue
|
|
644
|
+
modified.add(file)
|
|
645
|
+
for (const importer of this.importers.get(file) ?? []) modified.add(importer)
|
|
646
|
+
}
|
|
647
|
+
return [...modified]
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
private async build(modified: string[]): Promise<void> {
|
|
651
|
+
const ng = await loadAngular(this.ctx.rootDir)
|
|
652
|
+
const options = (this.options ??= compilerOptions(ng.ts, this.ctx))
|
|
653
|
+
const roots = rootNames(this.ctx.rootDir)
|
|
654
|
+
const written = new Map<string, AngularEmit>()
|
|
655
|
+
const host = compilerHost(ng, options, {
|
|
656
|
+
rootDir: this.ctx.rootDir,
|
|
657
|
+
preprocessStyle: this.ctx.preprocessStyle,
|
|
658
|
+
files: written,
|
|
659
|
+
onResource: (file, from) => {
|
|
660
|
+
this.resources.set(file, stampOf(file))
|
|
661
|
+
if (from) {
|
|
662
|
+
const importers = this.importers.get(file) ?? new Set()
|
|
663
|
+
this.importers.set(file, importers.add(from))
|
|
664
|
+
}
|
|
665
|
+
},
|
|
666
|
+
})
|
|
667
|
+
host.getModifiedResourceFiles = () => new Set(modified)
|
|
668
|
+
const read = host.getSourceFile.bind(host)
|
|
669
|
+
host.getSourceFile = (fileName, language, onError, fresh) => {
|
|
670
|
+
const stamp = /[\\/]node_modules[\\/]/.test(fileName) ? "" : stampOf(fileName)
|
|
671
|
+
const hit = this.sourceFiles.get(fileName)
|
|
672
|
+
if (hit && hit.stamp === stamp && !fresh) return hit.file
|
|
673
|
+
const file = read(fileName, language, onError, fresh)
|
|
674
|
+
if (file) this.sourceFiles.set(fileName, { stamp, file })
|
|
675
|
+
return file
|
|
676
|
+
}
|
|
677
|
+
for (const file of modified) this.resources.set(file, stampOf(file))
|
|
678
|
+
const program = new ng.cli.NgtscProgram(roots, options, host, this.program)
|
|
679
|
+
this.built = true
|
|
680
|
+
this.record(program)
|
|
681
|
+
try {
|
|
682
|
+
await program.loadNgStructureAsync()
|
|
683
|
+
} catch (error) {
|
|
684
|
+
this.failure = error instanceof Error ? error : new Error(String(error))
|
|
685
|
+
return
|
|
686
|
+
}
|
|
687
|
+
this.failure = undefined
|
|
688
|
+
this.resourcesOf.clear()
|
|
689
|
+
for (const source of program.getTsProgram().getSourceFiles()) {
|
|
690
|
+
if (source.isDeclarationFile) continue
|
|
691
|
+
const resources = program.compiler.getResourceDependencies(source)
|
|
692
|
+
if (resources.length) this.resourcesOf.set(real(source.fileName), new Set(resources.map(real)))
|
|
693
|
+
}
|
|
694
|
+
this.problems = problemsOf(ng, program, this.ctx.rootDir, (tsProgram) =>
|
|
695
|
+
defaultExportErrors(ng.ts, tsProgram, this.ctx.rootDir, roots),
|
|
696
|
+
)
|
|
697
|
+
emitOnly(program, (path) => this.emits(path))
|
|
698
|
+
this.program = program
|
|
699
|
+
this.emitted = [...written.keys()].filter((file) => this.texts.has(file))
|
|
700
|
+
for (const file of this.emitted) this.files.set(file, written.get(file)!)
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
/** The texts the program compiled, so a load of an unchanged file does not build again, even when the build fails. */
|
|
704
|
+
private record(program: AngularCli.NgtscProgram): void {
|
|
705
|
+
this.texts.clear()
|
|
706
|
+
for (const source of program.getTsProgram().getSourceFiles()) {
|
|
707
|
+
if (source.isDeclarationFile) continue
|
|
708
|
+
const path = real(source.fileName)
|
|
709
|
+
if (path.startsWith(this.root) || this.own.has(path)) this.texts.set(path, source.text)
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
/** The directories of `<buildDir>` where the core writes the modules the adapter generates. */
|
|
715
|
+
const GENERATED = ["svg", "markdown", "client-components", "server-components"] as const
|
|
716
|
+
type Generated = (typeof GENERATED)[number]
|
|
717
|
+
|
|
718
|
+
function generatedKind(ctx: AdapterBuildContext, id: string): Generated | undefined {
|
|
719
|
+
const path = real(id)
|
|
720
|
+
return GENERATED.find((dir) => path.startsWith(`${real(join(ctx.buildDir, dir))}${sep}`))
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
const generatedEmits = new Map<string, { hash: string; emit: Promise<AngularEmit> }>()
|
|
724
|
+
|
|
725
|
+
/**
|
|
726
|
+
* A module the adapter generated is not a root of the app's program, which is made before the core writes it. It is its own
|
|
727
|
+
* program of one root, compiled with the app's options and kept for as long as its text stays the same.
|
|
728
|
+
*/
|
|
729
|
+
function compileGenerated(ctx: AdapterBuildContext, id: string, code: string): Promise<AngularEmit> {
|
|
730
|
+
const path = real(id)
|
|
731
|
+
const hash = `${ctx.dev}\0${Bun.hash(code)}`
|
|
732
|
+
const hit = generatedEmits.get(path)
|
|
733
|
+
if (hit?.hash === hash) return hit.emit
|
|
734
|
+
const emit = loadAngular(ctx.rootDir).then(async (ng) => {
|
|
735
|
+
const files = await emitProgram(
|
|
736
|
+
ng,
|
|
737
|
+
ctx.rootDir,
|
|
738
|
+
[path],
|
|
739
|
+
{ ...compilerOptions(ng.ts, ctx), _enableHmr: false },
|
|
740
|
+
ctx.preprocessStyle,
|
|
741
|
+
(file) => file === path,
|
|
742
|
+
)
|
|
743
|
+
const emitted = files.get(path)
|
|
744
|
+
if (!emitted)
|
|
745
|
+
throw new Error(`${shown(ctx.rootDir, id)}: the Angular program emitted nothing for the generated module`)
|
|
746
|
+
return emitted
|
|
747
|
+
})
|
|
748
|
+
generatedEmits.set(path, { hash, emit })
|
|
749
|
+
emit.catch(() => {
|
|
750
|
+
if (generatedEmits.get(path)?.emit === emit) generatedEmits.delete(path)
|
|
751
|
+
})
|
|
752
|
+
return emit
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
const WRAPPER = /^\/\* hamur-angular-component (\{.*\}) \*\//
|
|
756
|
+
const pascal = (segment: string) =>
|
|
757
|
+
segment
|
|
758
|
+
.split(/[^A-Za-z0-9]+/)
|
|
759
|
+
.filter(Boolean)
|
|
760
|
+
.map((part) => part[0]!.toUpperCase() + part.slice(1))
|
|
761
|
+
.join("")
|
|
762
|
+
|
|
763
|
+
/** `components/base/Button.ts` → `BaseButton`, as the core names a component file. */
|
|
764
|
+
function componentName(path: string): string {
|
|
765
|
+
const segments = path.split("/")
|
|
766
|
+
if (segments.length > 1 && segments[segments.length - 1] === "index") segments.pop()
|
|
767
|
+
return segments.map(pascal).join("")
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
type Suffix = "client" | "server"
|
|
771
|
+
|
|
772
|
+
/** The `app/components/**\/<name>.client.ts` or `.server.ts` file the core named `name`, for the build that was not given its path. */
|
|
773
|
+
function componentFile(rootDir: string, suffix: Suffix, name: string): string | undefined {
|
|
774
|
+
const dir = join(rootDir, "app", "components")
|
|
775
|
+
if (!existsSync(dir)) return undefined
|
|
776
|
+
const end = new RegExp(`\\.${suffix}\\.[cm]?ts$`)
|
|
777
|
+
return scripts(dir).find((file) => {
|
|
778
|
+
const rel = relative(dir, file).split(sep).join("/")
|
|
779
|
+
return end.test(rel) && componentName(rel.replace(end, "")) === name
|
|
780
|
+
})
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
const componentFiles = (rootDir: string): string[] => {
|
|
784
|
+
const dir = join(rootDir, "app", "components")
|
|
785
|
+
return existsSync(dir) ? scripts(dir).filter((file) => /\.(?:client|server)\.[cm]?ts$/.test(file)) : []
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
interface WrapperSpec {
|
|
789
|
+
kind: Suffix
|
|
790
|
+
name: string
|
|
791
|
+
target: "client" | "server"
|
|
792
|
+
file?: string
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
/** The decorator is written through a constant so this file is not taken for a component of the package. */
|
|
796
|
+
const COMPONENT = "@Component"
|
|
797
|
+
|
|
798
|
+
/**
|
|
799
|
+
* The module of a client-only or server-only component for one build, as TypeScript: a component with the selector and the
|
|
800
|
+
* inputs of the real one and no template, which the app's program compiles. Its behaviour is `runtime/<target>`.
|
|
801
|
+
*/
|
|
802
|
+
async function wrapperSource(ctx: AdapterBuildContext, spec: WrapperSpec): Promise<string> {
|
|
803
|
+
const file = spec.file ?? componentFile(ctx.rootDir, spec.kind, spec.name)
|
|
804
|
+
if (!file)
|
|
805
|
+
throw new Error(`${spec.name}.${spec.kind}: there is no app/components/**/${spec.name}.${spec.kind}.ts file`)
|
|
806
|
+
const emitted = ctx.dev ? await angularDevProgram(ctx).load(real(file)) : (await angularProgram(ctx)).get(real(file))
|
|
807
|
+
const definition = emitted && readDefinition(emitted.code)
|
|
808
|
+
if (!definition)
|
|
809
|
+
throw new Error(
|
|
810
|
+
`${shown(ctx.rootDir, file)}: a .${spec.kind} component must default-export a class with @Component`,
|
|
811
|
+
)
|
|
812
|
+
const q = JSON.stringify
|
|
813
|
+
const fields = definition.inputs.map((_, index) => `i${index}`)
|
|
814
|
+
const call =
|
|
815
|
+
spec.kind === "client"
|
|
816
|
+
? `clientComponent(${spec.target === "client" ? `() => import(${q(file)})` : ""})`
|
|
817
|
+
: `serverComponent(${[q(spec.name), ...(spec.target === "server" ? ["component"] : [])].join(", ")})`
|
|
818
|
+
return `import { Component, type OnChanges, type OnInit, type SimpleChanges } from "@angular/core";
|
|
819
|
+
import { ${spec.kind === "client" ? "clientComponent" : "serverComponent"} } from ${q(`@hamur/adapter-angular/runtime/${spec.target}`)};
|
|
820
|
+
${spec.kind === "server" && spec.target === "server" ? `import component from ${q(file)};\n` : ""}
|
|
821
|
+
const names: Record<string, string> = ${q(Object.fromEntries(fields.map((field, index) => [field, definition.inputs[index]])))};
|
|
822
|
+
|
|
823
|
+
${COMPONENT}({
|
|
824
|
+
selector: ${q(selectorOf(definition.selectors))},
|
|
825
|
+
template: "",
|
|
826
|
+
inputs: ${q(fields.map((field, index) => `${field}: ${definition.inputs[index]}`))},
|
|
827
|
+
})
|
|
828
|
+
export default class Wrapper implements OnChanges, OnInit {
|
|
829
|
+
${fields.map((field) => ` ${field}: unknown = undefined;`).join("\n")}
|
|
830
|
+
private readonly controller = ${call};
|
|
831
|
+
|
|
832
|
+
ngOnChanges(changes: SimpleChanges): void {
|
|
833
|
+
for (const [key, change] of Object.entries(changes)) this.controller.set(names[key]!, change.currentValue);
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
ngOnInit(): void {
|
|
837
|
+
this.controller.init();
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
`
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
/** The emitted code of a file of the program, of a module the adapter generated, or the wrapper of a client-only or server-only component; any other `.ts` goes on through the chain. */
|
|
844
|
+
export function compileStep(ctx: AdapterBuildContext): AdapterTransform {
|
|
845
|
+
let files: Promise<Map<string, AngularEmit>> | undefined
|
|
846
|
+
const dev = ctx.dev ? angularDevProgram(ctx) : undefined
|
|
847
|
+
const key = `${ctx.rootDir}\0${ctx.buildDir}`
|
|
848
|
+
return {
|
|
849
|
+
name: "hamur-angular-compile",
|
|
850
|
+
filter: { id: COMPILE_ID },
|
|
851
|
+
...(dev
|
|
852
|
+
? {
|
|
853
|
+
version: (id: string) =>
|
|
854
|
+
[
|
|
855
|
+
dev.version(real(id)),
|
|
856
|
+
...(/^(?:client|server)-components$/.test(generatedKind(ctx, id) ?? "")
|
|
857
|
+
? componentFiles(ctx.rootDir).map((file) => `${file}:${stampOf(file)}`)
|
|
858
|
+
: []),
|
|
859
|
+
].join("\n"),
|
|
860
|
+
}
|
|
861
|
+
: {}),
|
|
862
|
+
async transform(source, { id }) {
|
|
863
|
+
const kind = generatedKind(ctx, id)
|
|
864
|
+
if (kind === "client-components" || kind === "server-components") {
|
|
865
|
+
const marker = WRAPPER.exec(source)
|
|
866
|
+
if (!marker) return undefined
|
|
867
|
+
const wrapper = id.replace(/\.ts$/, ".wrapper.ts")
|
|
868
|
+
const text = await wrapperSource(ctx, JSON.parse(marker[1]!) as WrapperSpec)
|
|
869
|
+
if (!existsSync(wrapper) || readFileSync(wrapper, "utf8") !== text) writeFileSync(wrapper, text)
|
|
870
|
+
const emitted = await compileGenerated(ctx, wrapper, text)
|
|
871
|
+
return { code: emitted.code, ...(emitted.map ? { map: emitted.map } : {}), loader: "js" }
|
|
872
|
+
}
|
|
873
|
+
if (kind) {
|
|
874
|
+
const emitted = await compileGenerated(ctx, id, source)
|
|
875
|
+
return { code: emitted.code, ...(emitted.map ? { map: emitted.map } : {}), loader: "js" }
|
|
876
|
+
}
|
|
877
|
+
let emitted: AngularEmit | undefined
|
|
878
|
+
if (dev) emitted = await dev.load(real(id))
|
|
879
|
+
else {
|
|
880
|
+
files ??= angularProgram(ctx)
|
|
881
|
+
emitted = (await files).get(real(id))
|
|
882
|
+
}
|
|
883
|
+
if (!emitted) return undefined
|
|
884
|
+
const code = ctx.hmr ? rewriteHmrInitializer(emitted.code, ctx.target, devBases.get(key) ?? "/") : emitted.code
|
|
885
|
+
return { code, ...(emitted.map ? { map: emitted.map } : {}), loader: "js" }
|
|
886
|
+
},
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
/** The package may be reached through a symlink, so the client runtime is matched by its path's tail and the import is relative to it. */
|
|
891
|
+
const CLIENT_RUNTIME = /[\\/]adapter-angular[\\/]src[\\/]runtime[\\/]client\.ts$/
|
|
892
|
+
|
|
893
|
+
/** In `hamur dev` the client runtime imports `./hydration-dev.ts` first, which feeds the hydration mismatch report; a build adds nothing. */
|
|
894
|
+
export function hydrationStep(): AdapterTransform {
|
|
895
|
+
return {
|
|
896
|
+
name: "hamur-angular-hydration",
|
|
897
|
+
filter: { id: CLIENT_RUNTIME },
|
|
898
|
+
transform: (code) => `import "./hydration-dev.ts"; ${code}`,
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
const linked = new Map<string, { size: number; code: string }>()
|
|
903
|
+
|
|
904
|
+
/** Angular's linker on a partial-compiled package file (`ɵɵngDeclare*`), kept per path and size for the life of the process. */
|
|
905
|
+
export function linkStep(ctx: AdapterBuildContext): AdapterTransform {
|
|
906
|
+
return {
|
|
907
|
+
name: "hamur-angular-link",
|
|
908
|
+
filter: { id: LINK_ID },
|
|
909
|
+
async transform(code, { id }) {
|
|
910
|
+
const ng = await loadAngular(ctx.rootDir)
|
|
911
|
+
if (!ng.needsLinking(id, code)) return undefined
|
|
912
|
+
const hit = linked.get(id)
|
|
913
|
+
if (hit?.size === code.length) return hit.code
|
|
914
|
+
const result = await ng.babel.transformAsync(code, {
|
|
915
|
+
filename: id,
|
|
916
|
+
plugins: [ng.linkerPlugin],
|
|
917
|
+
configFile: false,
|
|
918
|
+
babelrc: false,
|
|
919
|
+
compact: false,
|
|
920
|
+
sourceMaps: false,
|
|
921
|
+
})
|
|
922
|
+
const out = result?.code ?? code
|
|
923
|
+
linked.set(id, { size: code.length, code: out })
|
|
924
|
+
return out
|
|
925
|
+
},
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
/** The package's own components in `compilationMode: "partial"`, as `scripts/release.ts` publishes them: real source path to JavaScript and declarations. */
|
|
930
|
+
export async function compilePartial(packageDir: string, from = packageDir): Promise<Map<string, AngularEmit>> {
|
|
931
|
+
const ng = await loadAngular(from)
|
|
932
|
+
const roots = scripts(join(packageDir, "src")).filter(
|
|
933
|
+
(file) => !file.endsWith(".test.ts") && DECORATED.test(readFileSync(file, "utf8")),
|
|
934
|
+
)
|
|
935
|
+
const own = new Set(roots.map(real))
|
|
936
|
+
const files = await emitProgram(
|
|
937
|
+
ng,
|
|
938
|
+
packageDir,
|
|
939
|
+
roots,
|
|
940
|
+
{
|
|
941
|
+
compilationMode: "partial",
|
|
942
|
+
module: ng.ts.ModuleKind.ESNext,
|
|
943
|
+
target: ng.ts.ScriptTarget.ES2022,
|
|
944
|
+
moduleResolution: ng.ts.ModuleResolutionKind.Bundler,
|
|
945
|
+
lib: ["lib.esnext.d.ts", "lib.dom.d.ts", "lib.dom.iterable.d.ts"],
|
|
946
|
+
types: [],
|
|
947
|
+
strict: true,
|
|
948
|
+
strictTemplates: true,
|
|
949
|
+
skipLibCheck: true,
|
|
950
|
+
allowImportingTsExtensions: true,
|
|
951
|
+
declaration: true,
|
|
952
|
+
noEmit: false,
|
|
953
|
+
},
|
|
954
|
+
undefined,
|
|
955
|
+
(file) => own.has(file),
|
|
956
|
+
)
|
|
957
|
+
return new Map(
|
|
958
|
+
roots.flatMap((file) => {
|
|
959
|
+
const emitted = files.get(real(file))
|
|
960
|
+
return emitted ? [[real(file), emitted] as const] : []
|
|
961
|
+
}),
|
|
962
|
+
)
|
|
963
|
+
}
|