Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 78 additions & 6 deletions napi/angular-compiler/test/ssr-manifest.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { execFileSync } from 'node:child_process'
import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { basename, dirname, join } from 'node:path'
import { runInNewContext } from 'node:vm'

import { afterAll, describe, it, expect } from 'vitest'
import { createBuilder } from 'vite'
import { afterAll, describe, it, expect, onTestFinished } from 'vitest'
/**
* Tests for SSR manifest generation.
*
Expand All @@ -21,6 +23,8 @@ import {
generateAppEngineManifestCode,
} from '../vite-plugin/angular-ssr-manifest-plugin.js'

const manifestId = 'virtual:oxc-angular/ssr-manifest'

describe('SSR Manifest Generation (Issue #60)', () => {
describe('generateAppManifestCode', () => {
it('should generate valid app manifest code with bootstrap import', () => {
Expand Down Expand Up @@ -128,7 +132,72 @@ describe('SSR Manifest Generation (Issue #60)', () => {
)

expect(transform('client')).toBeUndefined()
expect(transform('server')?.code).toContain('ɵsetAngularAppManifest')
expect(transform('server')?.code).toContain(manifestId)
})

it('evaluates entry imports, registers both manifests, then constructs the engine', async () => {
const root = mkdtempSync(join(tmpdir(), 'oxc-angular-ssr-order-'))
onTestFinished(() => rmSync(root, { recursive: true, force: true }))
writeFileSync(join(root, 'trace.mjs'), 'export const events = []')
writeFileSync(
join(root, 'compiler.mjs'),
"import { events } from './trace.mjs'; events.push('compiler')",
)
writeFileSync(join(root, 'main.server.ts'), 'export default () => {}')
writeFileSync(
join(root, 'ssr.mjs'),
`
import { events } from './trace.mjs'
events.push('ssr')
export function ɵsetAngularAppManifest() { events.push('app manifest') }
export function ɵsetAngularAppEngineManifest() { events.push('engine manifest') }
export function ɵgetOrCreateAngularServerApp() {}
export function ɵdestroyAngularServerApp() {}
export function ɵextractRoutesAndCreateRouteTree() {}
`,
)
writeFileSync(
join(root, 'server.js'),
`
import './compiler.mjs'
import { events } from './trace.mjs'
class AngularNodeAppEngine { constructor() { events.push('engine') } }
new AngularNodeAppEngine()
export function view() { return <h1 /> }
console.log(JSON.stringify(events))
`,
)

const builder = await createBuilder({
configFile: false,
root,
logLevel: 'silent',
plugins: [ssrManifestPlugin({ ssrEntry: 'main.server.ts' })],
resolve: { alias: { '@angular/ssr': join(root, 'ssr.mjs') } },
environments: {
ssr: {
build: {
rolldownOptions: {
input: join(root, 'server.js'),
moduleTypes: { '.js': 'jsx' },
transform: { jsx: { runtime: 'classic' } },
output: { entryFileNames: 'server.mjs' },
},
},
},
},
})
await builder.build(builder.environments.ssr)
const output = execFileSync(process.execPath, [join(root, 'dist/server.mjs')], {
encoding: 'utf8',
})
expect(JSON.parse(output)).toEqual([
'compiler',
'ssr',
'app manifest',
'engine manifest',
'engine',
])
})

it('should not inject the manifests twice', () => {
Expand Down Expand Up @@ -245,10 +314,13 @@ describe('SSR Manifest Generation (Issue #60)', () => {
/** The server's buildStart, then a transform of each module. */
async server(...modules: string[]): Promise<(string | undefined)[]> {
await plugin.buildStart.handler.call(context('ssr'))
return modules.map(
(code, i) =>
plugin.transform.call(context('ssr'), code, join(root, `src/server${i}.ts`))?.code,
)
const ctx = context('ssr')
return modules.map((code, i) => {
const id = join(root, `src/server${i}.ts`)
if (!plugin.transform.call(ctx, code, id)) return
const manifest = plugin.resolveId.call(ctx, manifestId, id)
return plugin.load.call(ctx, manifest.id)
})
},
/** The server's renderChunk of a chunk with `code`. */
async render(code: string): Promise<string | undefined> {
Expand Down
79 changes: 53 additions & 26 deletions napi/angular-compiler/vite-plugin/angular-ssr-manifest-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,10 @@ export interface SsrManifestPluginOptions {
const PAGE_TOKEN = '__oxc_angular_index_server_html__'
const PAGE_SIZE_TOKEN = '__oxc_angular_index_server_html_size__'

const MANIFEST_ID = 'virtual:oxc-angular/ssr-manifest'
const MANIFEST_IMPORT = `import '${MANIFEST_ID}';`
const MANIFEST_PREFIX = '\0' + MANIFEST_ID + '.js?entry='

const MINIMAL_PAGE = '<!DOCTYPE html><html><head></head><body><app-root></app-root></body></html>'

type Environment = NonNullable<Rolldown.PluginContext['environment']>
Expand Down Expand Up @@ -292,6 +296,9 @@ export function ssrManifestPlugin(options: SsrManifestPluginOptions): Plugin {
let stampFailed = false
const servers = new Map<string, ServerState>()

const manifestEntry = (id: string) =>
resolve(resolvedConfig.root, decodeURIComponent(id.slice(MANIFEST_PREFIX.length)))

const serverState = (name: string): ServerState => {
let state = servers.get(name)
if (!state) servers.set(name, (state = { waiting: 0, building: false, warned: false }))
Expand Down Expand Up @@ -486,32 +493,9 @@ export function ssrManifestPlugin(options: SsrManifestPluginOptions): Plugin {
!id.includes('node_modules') &&
!id.startsWith('\0') &&
(code.includes('AngularNodeAppEngine') || code.includes('AngularAppEngine')) &&
!code.includes('ɵsetAngularAppManifest')
!code.includes('ɵsetAngularAppManifest') &&
!code.includes(MANIFEST_IMPORT)
) {
const baseHref = resolvedConfig.base || '/'

// Compute the import path for main.server.ts relative to the current file
const fileDir = dirname(id)
let ssrEntryImport = normalizePath(relative(fileDir, ssrEntryPath)).replace(/\.ts$/, '')
if (!ssrEntryImport.startsWith('.')) {
ssrEntryImport = './' + ssrEntryImport
}

// In `vite build --app --watch`, renderChunk fills in the page.
const appManifest = isAppWatchServer(this.environment, this.meta)
? generateAppManifestCode({ ssrEntryImport, baseHref, indexHtmlContent: '' })
.replace('size: 0,', `size: ${PAGE_SIZE_TOKEN},`)
.replace('Promise.resolve(``)', `Promise.resolve(${PAGE_TOKEN})`)
: generateAppManifestCode({
ssrEntryImport,
baseHref,
indexHtmlContent: indexHtmlContent || '',
})

const engineManifest = generateAppEngineManifestCode({
basePath: baseHref,
})

// Only warn about the page when a manifest embeds it, once per build.
const warning = fallbackWarnings.get(this.environment.name)
if (warning) {
Expand All @@ -520,12 +504,55 @@ export function ssrManifestPlugin(options: SsrManifestPluginOptions): Plugin {
}

return {
code: appManifest + engineManifest + code,
// ESM evaluates this last dependency after the user's imports (including
// @angular/compiler), but before the entry constructs its app engine.
code: `${code}\n${MANIFEST_IMPORT}\n`,
map: null,
}
}
},

resolveId(source, importer, options) {
if (!importer || this.environment?.config.consumer !== 'server') return
if (source === MANIFEST_ID) {
const entry = normalizePath(relative(resolvedConfig.root, importer))
return { id: MANIFEST_PREFIX + encodeURIComponent(entry), moduleSideEffects: true }
}
// Resolve Angular and the bootstrap from the same entry as before injection.
if (importer.startsWith(MANIFEST_PREFIX)) {
return this.resolve(source, normalizePath(manifestEntry(importer)), options)
}
},

load(id) {
if (!id.startsWith(MANIFEST_PREFIX) || this.environment?.config.consumer !== 'server') return
const baseHref = resolvedConfig.base || '/'

// Compute the import path for main.server.ts relative to the current file
const fileDir = dirname(manifestEntry(id))
let ssrEntryImport = normalizePath(relative(fileDir, ssrEntryPath)).replace(/\.ts$/, '')
if (!ssrEntryImport.startsWith('.')) {
ssrEntryImport = './' + ssrEntryImport
}

// In `vite build --app --watch`, renderChunk fills in the page.
const appManifest = isAppWatchServer(this.environment, this.meta)
? generateAppManifestCode({ ssrEntryImport, baseHref, indexHtmlContent: '' })
.replace('size: 0,', `size: ${PAGE_SIZE_TOKEN},`)
.replace('Promise.resolve(``)', `Promise.resolve(${PAGE_TOKEN})`)
: generateAppManifestCode({
ssrEntryImport,
baseHref,
indexHtmlContent: indexHtmlContent || '',
})

const engineManifest = generateAppEngineManifestCode({
basePath: baseHref,
})

return appManifest + engineManifest
},

async renderChunk(code) {
const environment = this.environment
if (environment?.config.consumer !== 'server' || !code.includes(PAGE_TOKEN)) return null
Expand Down