@hamur/adapter-angular 0.0.0-stage → 0.0.1

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