diff --git a/.github/workflows/compat.yml b/.github/workflows/compat.yml new file mode 100644 index 0000000..d98a4ed --- /dev/null +++ b/.github/workflows/compat.yml @@ -0,0 +1,99 @@ +name: Angular compatibility + +# Builds an Angular CLI app (compat/fixture) against every Angular version the +# packages claim to support, zoneless and with Zone.js, and checks that it +# streams and hydrates: compat/run.mjs. The peer ranges in packages/*/package.json +# list exactly what this matrix checks. + +on: + pull_request: + paths: + - 'packages/**' + - 'compat/**' + - '.github/workflows/compat.yml' + push: + branches: [main] + paths: + - 'packages/**' + - 'compat/**' + - '.github/workflows/compat.yml' + # Every Monday, so a new Angular patch or `next` shows up before users do. + schedule: + - cron: '0 5 * * 1' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: compat-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + pack: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: pnpm/action-setup@v4 + # The workspace needs Node 26. + - uses: actions/setup-node@v4 + with: + node-version: 26 + cache: pnpm + - run: pnpm install --frozen-lockfile + # The two packages an Angular CLI app installs, packed as npm would get them. + - run: | + mkdir -p packs + for name in core angular-ssr; do + (cd packages/$name && pnpm run build && pnpm pack --pack-destination ../../packs) + done + - uses: actions/upload-artifact@v4 + with: + name: packs + path: packs/*.tgz + + check: + needs: pack + runs-on: ubuntu-latest + # `next` is Angular's upcoming release: a failure there is a warning about + # what is coming, not a broken build. + continue-on-error: ${{ matrix.angular == 'next' }} + strategy: + fail-fast: false + matrix: + # The newest patch of each supported minor, the lowest supported patch + # of each older major, and what Angular releases next. + angular: + [ + '19.2', + '19.2.22', + '20.3', + '20.3.21', + '21.2', + '21.2.13', + '22.0', + '22.1', + '22.2', + '22.3', + 'next', + ] + mode: [zoneless, zone] + name: Angular ${{ matrix.angular }}, ${{ matrix.mode }} + steps: + - uses: actions/checkout@v4 + # Node 22 is supported by every Angular version in the matrix. + - uses: actions/setup-node@v4 + with: + node-version: 22 + - uses: actions/download-artifact@v4 + with: + name: packs + path: packs + # ubuntu-latest has Chrome at /usr/bin/google-chrome. + - run: node compat/run.mjs --angular '${{ matrix.angular }}' --mode ${{ matrix.mode }} --packs packs + - if: always() + uses: actions/upload-artifact@v4 + with: + name: result-${{ matrix.angular }}-${{ matrix.mode }} + path: compat/.work/*/result.json + if-no-files-found: ignore diff --git a/AGENTS.md b/AGENTS.md index 519113e..99423a0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -188,6 +188,14 @@ together; the short version: - **Angular version is pinned to exactly `22.3.0-rc.0`** in every project. Do not bump any `@angular/*` package on its own; ngp imports private `@angular/compiler-cli` APIs and only works against that exact release. + The packages themselves support more (19.2.22+, 20.3.21+, 21.2.13+, 22): + `compat/` is an Angular CLI app outside the workspace that + `node compat/run.mjs --angular --mode ` installs, + builds and checks (curl-style timing plus headless Chrome) against one + version, and `.github/workflows/compat.yml` runs it as a matrix. Change the + peer ranges only together with that matrix, and run the affected rows + locally after changing anything in `packages/core` or `packages/angular-ssr` + that touches Angular's internals. - **Styles**: component `styleUrl` files go through Vite's Sass pipeline. Inline `styles` are plain CSS only, no Sass there. - **Icons (movies)**: ``. Adding an icon means dropping the diff --git a/README.md b/README.md index cd5d0e4..ae1a23d 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,7 @@ to npm under `@push-based/`: | `packages/angular-ssr` | `@push-based/angular-ssr-stream-angular-ssr`: `withStreaming()`, for `@angular/ssr` in Angular CLI apps. | | `apps/example-*` | One small app per runtime, all rendering `libs/stream-example`. Built in CI, not deployed. | | `apps/example-angular-cli` | An app made by `ng new --ssr`, built by `ng build`, with `@angular/ssr` streaming. Built in CI. | +| `compat` | An Angular CLI app and the script that checks the packages against one Angular version, for CI. | | `libs/stream-example` | `@angular-ssr-stream/stream-example`: the page every example renders, a shell and one slow widget. | | `libs/design-system` | `@angular-ssr-stream/design-system`: the PushBased design system the demo and the docs share. Private. | | `press-kit` | The logo in every form: symbol, lockups, favicons and the social preview, with how to use them. | @@ -239,8 +240,10 @@ publishes to npm on the `next` dist-tag with provenance. The first run needs `@push-based` scope. The packages use private Angular APIs (`ɵ`-prefixed), so their Angular peer -range is narrow (`~22.3.0-rc.0`) and every Angular minor needs a check and a -release. +range is what `compat/` proves: an Angular CLI app, built and run against the +latest patch of every supported minor and the lowest patch of each, zoneless +and with Zone.js, by `.github/workflows/compat.yml`. A new Angular minor gets +a row in that matrix first, and joins the peer ranges once it passes. ## How the pieces fit diff --git a/apps/docs/src/content/concepts/angular-streaming-ssr.md b/apps/docs/src/content/concepts/angular-streaming-ssr.md index a16056f..9fa5f0b 100644 --- a/apps/docs/src/content/concepts/angular-streaming-ssr.md +++ b/apps/docs/src/content/concepts/angular-streaming-ssr.md @@ -142,7 +142,9 @@ app runs: shell, so a part that fails afterwards cannot turn the response into an error page or a redirect. - **It is not part of Angular.** The library leans on Angular internals, so it - supports a narrow range of Angular versions. With the Angular CLI it works + supports the versions a check in CI proves, 19.2 to 22 today; see + [Compatibility](../getting-started/installation.md#compatibility). With the + Angular CLI it works inside `@angular/ssr`, streaming the routes it renders on the server; every other setup renders without `@angular/ssr`. [Caveats and limitations](../reference/limitations.md) has the list. diff --git a/apps/docs/src/content/getting-started/angular-cli.md b/apps/docs/src/content/getting-started/angular-cli.md index 1d6d884..97390dd 100644 --- a/apps/docs/src/content/getting-started/angular-cli.md +++ b/apps/docs/src/content/getting-started/angular-cli.md @@ -164,6 +164,23 @@ piece: Streamed responses carry `Cache-Control: no-store`, whatever the route's headers say: a cached copy of a partial response would be worse than none. +## Angular 19 to 21 + +The steps above are for Angular 22, which `ng new` gives you today. On 19.2, +20.3 or 21.2, check the patch against the +[compatibility table](installation.md#compatibility), then: + +- **Turn on incremental hydration.** Angular 22 does it by default; before + that, add `withIncrementalHydration()` from `@angular/platform-browser` to + `provideClientHydration()`. Without it nothing streams, and the server warns. +- **Check `main.server.ts`.** Its `bootstrap` has to take the + `BootstrapContext` it is called with and pass it to + `bootstrapApplication()`, as in step 4. `ng new` writes it that way in every + supported version, but an app made before Angular's security fix that added + it may still have a `bootstrap` that takes no argument: add it. +- **On 19**, zoneless is `provideExperimentalZonelessChangeDetection()`. Zone.js + works as well. + ## 8. Behind a proxy A proxy, a CDN or compression middleware can hold the response back until it diff --git a/apps/docs/src/content/getting-started/installation.md b/apps/docs/src/content/getting-started/installation.md index 9e4ed48..d8af38e 100644 --- a/apps/docs/src/content/getting-started/installation.md +++ b/apps/docs/src/content/getting-started/installation.md @@ -1,11 +1,8 @@ ## Requirements -- **Angular `~22.3.0-rc.0`**, standalone, with incremental hydration. - Zoneless or with Zone.js: on the server, the requests the renderer follows - run outside the Angular zone, so Zone.js doesn't hold the shell back for - them. The packages use private Angular APIs (the `ɵ`-prefixed ones), so - their supported range is narrow: each Angular minor needs a check and a - release. +- **Angular 19.2, 20.3, 21.2 or 22**, from the patch each row of + [the compatibility table](#compatibility) names, standalone, with + incremental hydration. Zoneless or with Zone.js. - **A server that speaks web `Request` and `Response`**, directly or through one of the adapters below. - **A build that compiles Angular for the server**, one of two: @@ -20,10 +17,49 @@ `AngularAppEngine`, server routes and render modes are not available; see [Caveats and limitations](../reference/limitations.md). +## Compatibility + +The packages use private Angular APIs (the `ɵ`-prefixed ones), which can +change in any release. So the supported versions are the ones a check proves, +not a guess: every row below is built and run in CI, zoneless and with +Zone.js, as an app made by the Angular CLI. The server has to send the shell +before the data and the widget in a chunk after it, with `@angular/ssr`'s +statuses, headers and redirects intact. In Chrome, the widget has to hydrate +from the server's HTML, with Angular's hydration checks on, and answer a +click. + +| Angular | From | Zoneless | Zone.js | What the app needs | +| ------- | ------- | -------- | ------- | -------------------------------------------------------------------------------- | +| 22 | 22.0.0 | Yes | Yes | Nothing extra: incremental hydration is on by default | +| 21.2 | 21.2.13 | Yes | Yes | `withIncrementalHydration()` in `provideClientHydration()` | +| 20.3 | 20.3.21 | Yes | Yes | `withIncrementalHydration()` in `provideClientHydration()` | +| 19.2 | 19.2.22 | Yes | Yes | `withIncrementalHydration()`, and `provideExperimentalZonelessChangeDetection()` | + +Not supported: + +- **Angular 18 and older**, which have no incremental hydration. +- **19.0, 19.1, 20.0 to 20.2, 21.0 and 21.1, and the patches below each row's + "From".** They lack two security fixes Angular backported only to the last + minor of each major: the server's host check (`ɵisHostAllowed`), and passing + the server platform to `bootstrapApplication()`, which the renderer + bootstraps through. + +With incremental hydration off, the server renders no `@defer` block with a +`hydrate` trigger, so nothing streams. In development the server says so in a +warning. + +The ngp setups are the exception: ngp builds exactly `22.3.0-rc.0`, and no +other version. + +The matrix is in `.github/workflows/compat.yml` and runs +[`compat/run.mjs`](https://github.com/push-based/angular-ssr-stream/blob/main/compat/run.mjs) +for each row, on every pull request that touches the packages, and every week +against Angular's `next` too. A new Angular minor gets a row there first, and +joins the peer ranges once it passes. + ## Install -Releases go to npm's `next` dist-tag while the supported Angular is a release -candidate: +Releases go to npm's `next` dist-tag for now: ```bash npm install @push-based/angular-ssr-stream-core@next diff --git a/apps/docs/src/content/reference/limitations.md b/apps/docs/src/content/reference/limitations.md index 067072c..f783e74 100644 --- a/apps/docs/src/content/reference/limitations.md +++ b/apps/docs/src/content/reference/limitations.md @@ -3,7 +3,8 @@ - **It leans on Angular internals**: the layout of serialized hydration data, `ɵannotateForHydration`, the dehydrated block registry, and `DeferBlockFixture`'s way of rendering a block. This is why the supported - Angular range is narrow. + Angular versions are the ones CI checks, listed under + [Compatibility](../getting-started/installation.md#compatibility). - **`hydrate when` is rendered by hand on the server.** Angular renders it during a template update, which throws `NG0600` from the second request on if the component has signal queries. The buffered fallback cannot work around that, so diff --git a/compat/.gitignore b/compat/.gitignore new file mode 100644 index 0000000..3c1b3b2 --- /dev/null +++ b/compat/.gitignore @@ -0,0 +1 @@ +.work/ diff --git a/compat/browser.mjs b/compat/browser.mjs new file mode 100644 index 0000000..3923d47 --- /dev/null +++ b/compat/browser.mjs @@ -0,0 +1,172 @@ +// Opens a page in headless Chrome over the DevTools protocol, with nothing +// but Node's own WebSocket, and reports whether the streamed widget hydrated +// from the server's HTML. + +import { spawn } from 'node:child_process'; +import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +const CANDIDATES = [ + process.env['CHROME_PATH'], + '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', + '/usr/bin/google-chrome', + '/usr/bin/google-chrome-stable', + '/usr/bin/chromium', + '/usr/bin/chromium-browser', +]; + +function findChrome() { + const found = CANDIDATES.find((candidate) => candidate && existsSync(candidate)); + if (!found) { + throw new Error('No Chrome found: set CHROME_PATH.'); + } + return found; +} + +/** + * Starts headless Chrome on a free DevTools port, and resolves with that port + * once Chrome has written it to `DevToolsActivePort` in its profile, which is + * steadier than watching its log. + */ +async function launchChrome() { + const profile = mkdtempSync(join(tmpdir(), 'compat-chrome-')); + const chrome = spawn( + findChrome(), + [ + '--headless=new', + '--remote-debugging-port=0', + '--no-first-run', + '--no-default-browser-check', + '--no-sandbox', + '--disable-gpu', + '--disable-dev-shm-usage', + `--user-data-dir=${profile}`, + 'about:blank', + ], + { stdio: ['ignore', 'ignore', 'pipe'] }, + ); + let output = ''; + chrome.stderr.on('data', (data) => (output += data)); + + const deadline = Date.now() + 60000; + for (;;) { + try { + const [port] = readFileSync(join(profile, 'DevToolsActivePort'), 'utf8').split('\n'); + if (port) { + return { chrome, profile, port }; + } + } catch { + // Not written yet. + } + if (Date.now() > deadline || chrome.exitCode !== null) { + chrome.kill(); + rmSync(profile, { recursive: true, force: true }); + throw new Error(`Chrome did not start:\n${output.slice(-2000)}`); + } + await new Promise((resolve) => setTimeout(resolve, 100)); + } +} + +/** + * @returns {Promise<{ + * streamed: boolean, done: boolean, widgetText: string | null, + * hydratedAttr: string | null, debugStatus: string | null, + * zone: boolean, click: string, errors: string[] + * }>} + */ +export async function checkInBrowser(url, { waitMs = 5000 } = {}) { + // A cold start on a CI runner can be slow, and a first launch can die; + // one more try is cheaper than a red cell. + let launched; + try { + launched = await launchChrome(); + } catch { + launched = await launchChrome(); + } + const { chrome, profile, port } = launched; + + try { + const targets = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json(); + const page = targets.find((target) => target.type === 'page'); + + const ws = new WebSocket(page.webSocketDebuggerUrl); + await new Promise((resolve, reject) => { + ws.addEventListener('open', resolve, { once: true }); + ws.addEventListener('error', reject, { once: true }); + }); + + let id = 0; + const pending = new Map(); + const errors = []; + ws.addEventListener('message', (event) => { + const message = JSON.parse(event.data); + if (message.id && pending.has(message.id)) { + pending.get(message.id)(message); + pending.delete(message.id); + } + if (message.method === 'Runtime.consoleAPICalled' && message.params.type === 'error') { + errors.push( + 'console: ' + + message.params.args + .map((arg) => arg.value ?? arg.description) + .join(' ') + .slice(0, 300), + ); + } + if (message.method === 'Runtime.exceptionThrown') { + const details = message.params.exceptionDetails; + errors.push('exception: ' + (details.exception?.description ?? details.text).slice(0, 300)); + } + }); + const send = (method, params = {}) => + new Promise((resolve) => { + const callId = ++id; + pending.set(callId, resolve); + ws.send(JSON.stringify({ id: callId, method, params })); + }); + const evaluate = async (expression) => + (await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true })) + .result?.result?.value; + + await send('Runtime.enable'); + await send('Page.enable'); + await send('Page.navigate', { url }); + await new Promise((resolve) => setTimeout(resolve, waitMs)); + + const report = await evaluate(`(() => { + const widget = document.querySelector('[data-widget]'); + return { + streamed: typeof window.__ngs !== 'undefined', + done: Boolean(window.__ngs && window.__ngs.done), + widgetText: widget && widget.textContent.trim().replace(/\\s+/g, ' '), + hydratedAttr: widget && widget.getAttribute('data-hydrated'), + debugStatus: (widget && widget.__ngDebugHydrationInfo__ && widget.__ngDebugHydrationInfo__.status) || null, + zone: typeof Zone !== 'undefined', + }; + })()`); + const click = await evaluate(`(async () => { + const button = document.querySelector('[data-widget] button'); + if (!button) return 'no button'; + const count = () => button.closest('[data-widget]').textContent.match(/Count: (\\d+)/)?.[1]; + const before = count(); + button.click(); + await new Promise((resolve) => setTimeout(resolve, 300)); + return before + ' -> ' + count(); + })()`); + + ws.close(); + return { ...report, click, errors }; + } finally { + // Chrome goes on writing to its profile for a moment after it is told to + // stop, so wait for it to exit before cleaning up after it. + const exited = new Promise((resolve) => chrome.once('exit', resolve)); + chrome.kill(); + await Promise.race([exited, new Promise((resolve) => setTimeout(resolve, 5000))]); + try { + rmSync(profile, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }); + } catch { + // A temporary folder; the OS clears it eventually. + } + } +} diff --git a/compat/fixture/angular.json b/compat/fixture/angular.json new file mode 100644 index 0000000..77be5a8 --- /dev/null +++ b/compat/fixture/angular.json @@ -0,0 +1,61 @@ +{ + "$schema": "./node_modules/@angular/cli/lib/config/schema.json", + "version": 1, + "cli": { + "analytics": false + }, + "newProjectRoot": "projects", + "projects": { + "fixture": { + "projectType": "application", + "root": "", + "sourceRoot": "src", + "prefix": "app", + "architect": { + "build": { + "builder": "@angular/build:application", + "options": { + "outputPath": "dist/fixture", + "browser": "src/main.ts", + "index": "src/index.html", + "tsConfig": "tsconfig.app.json", + "assets": [ + { + "glob": "**/*", + "input": "public" + } + ], + "server": "src/main.server.ts", + "outputMode": "server", + "ssr": { + "entry": "src/server.ts" + } + }, + "configurations": { + "production": { + "outputHashing": "all" + }, + "development": { + "optimization": false, + "extractLicenses": false, + "sourceMap": true + } + }, + "defaultConfiguration": "production" + }, + "serve": { + "builder": "@angular/build:dev-server", + "configurations": { + "production": { + "buildTarget": "fixture:build:production" + }, + "development": { + "buildTarget": "fixture:build:development" + } + }, + "defaultConfiguration": "development" + } + } + } + } +} diff --git a/compat/fixture/public/apple-touch-icon.png b/compat/fixture/public/apple-touch-icon.png new file mode 100644 index 0000000..3510af7 Binary files /dev/null and b/compat/fixture/public/apple-touch-icon.png differ diff --git a/compat/fixture/public/favicon.ico b/compat/fixture/public/favicon.ico new file mode 100644 index 0000000..f8851d1 Binary files /dev/null and b/compat/fixture/public/favicon.ico differ diff --git a/compat/fixture/public/favicon.svg b/compat/fixture/public/favicon.svg new file mode 100644 index 0000000..03d5f36 --- /dev/null +++ b/compat/fixture/public/favicon.svg @@ -0,0 +1,5 @@ + + angular-ssr-stream + + + diff --git a/compat/fixture/src/app/app.config.ts b/compat/fixture/src/app/app.config.ts new file mode 100644 index 0000000..a9b6728 --- /dev/null +++ b/compat/fixture/src/app/app.config.ts @@ -0,0 +1,24 @@ +import { HttpBackend, provideHttpClient, withFetch, withInterceptors } from '@angular/common/http'; +import type { ApplicationConfig } from '@angular/core'; +import { + provideClientHydration, + withEventReplay, + withIncrementalHydration, +} from '@angular/platform-browser'; +import { provideRouter } from '@angular/router'; +import { provideStreamHydration, streamHttpInterceptor } from '@push-based/angular-ssr-stream-core'; +import { routes } from './app.routes'; +import { FakeBackend } from './backend'; +import { changeDetection } from './change-detection'; + +export const appConfig: ApplicationConfig = { + providers: [ + changeDetection, + provideRouter(routes), + provideHttpClient(withFetch(), withInterceptors([streamHttpInterceptor])), + { provide: HttpBackend, useExisting: FakeBackend }, + // On by default from Angular 22; 19 to 21 need it spelled out. + provideClientHydration(withEventReplay(), withIncrementalHydration()), + provideStreamHydration(), + ], +}; diff --git a/compat/fixture/src/app/app.routes.server.ts b/compat/fixture/src/app/app.routes.server.ts new file mode 100644 index 0000000..7fad02b --- /dev/null +++ b/compat/fixture/src/app/app.routes.server.ts @@ -0,0 +1,8 @@ +import { RenderMode, type ServerRoute } from '@angular/ssr'; + +export const serverRoutes: ServerRoute[] = [ + { path: 'teapot', renderMode: RenderMode.Server, status: 418, headers: { 'X-Route': 'teapot' } }, + { path: 'static', renderMode: RenderMode.Prerender }, + { path: 'csr', renderMode: RenderMode.Client }, + { path: '**', renderMode: RenderMode.Server }, +]; diff --git a/compat/fixture/src/app/app.routes.ts b/compat/fixture/src/app/app.routes.ts new file mode 100644 index 0000000..8bf1f7a --- /dev/null +++ b/compat/fixture/src/app/app.routes.ts @@ -0,0 +1,12 @@ +import type { Routes } from '@angular/router'; +import { NotFound } from './not-found'; +import { Page } from './page'; + +export const routes: Routes = [ + { path: '', component: Page }, + { path: 'teapot', component: Page }, + { path: 'static', component: Page }, + { path: 'csr', component: Page }, + { path: 'old', redirectTo: 'teapot' }, + { path: '**', component: NotFound }, +]; diff --git a/compat/fixture/src/app/app.ts b/compat/fixture/src/app/app.ts new file mode 100644 index 0000000..2a070fc --- /dev/null +++ b/compat/fixture/src/app/app.ts @@ -0,0 +1,9 @@ +import { Component } from '@angular/core'; +import { RouterOutlet } from '@angular/router'; + +@Component({ + selector: 'app-root', + imports: [RouterOutlet], + template: '', +}) +export class App {} diff --git a/compat/fixture/src/app/backend.ts b/compat/fixture/src/app/backend.ts new file mode 100644 index 0000000..23f881e --- /dev/null +++ b/compat/fixture/src/app/backend.ts @@ -0,0 +1,29 @@ +import { isPlatformBrowser } from '@angular/common'; +import { + type HttpBackend, + type HttpEvent, + type HttpRequest, + HttpResponse, +} from '@angular/common/http'; +import { Injectable, PLATFORM_ID, inject } from '@angular/core'; +import { type Observable, map, timer } from 'rxjs'; + +/** How long the widget's data takes to arrive. */ +export const DELAY_MS = 2000; + +export interface WidgetData { + answeredBy: 'server' | 'browser'; +} + +/** A fake API inside the app: answers every request after `DELAY_MS`. */ +@Injectable({ providedIn: 'root' }) +export class FakeBackend implements HttpBackend { + private readonly inBrowser = isPlatformBrowser(inject(PLATFORM_ID)); + + handle(request: HttpRequest): Observable> { + const body: WidgetData = { answeredBy: this.inBrowser ? 'browser' : 'server' }; + return timer(DELAY_MS).pipe( + map(() => new HttpResponse({ status: 200, url: request.urlWithParams, body })), + ); + } +} diff --git a/compat/fixture/src/app/not-found.ts b/compat/fixture/src/app/not-found.ts new file mode 100644 index 0000000..d0f1a8e --- /dev/null +++ b/compat/fixture/src/app/not-found.ts @@ -0,0 +1,15 @@ +import { Component, RESPONSE_INIT, inject } from '@angular/core'; + +/** Sets the status from inside the app, the way `@angular/ssr` documents it. */ +@Component({ + selector: 'app-not-found', + template: '

Not found

', +}) +export class NotFound { + constructor() { + const init = inject(RESPONSE_INIT, { optional: true }); + if (init) { + init.status = 404; + } + } +} diff --git a/compat/fixture/src/app/page.ts b/compat/fixture/src/app/page.ts new file mode 100644 index 0000000..fcec3c6 --- /dev/null +++ b/compat/fixture/src/app/page.ts @@ -0,0 +1,39 @@ +import { HttpClient } from '@angular/common/http'; +import { Component, afterNextRender, inject, signal } from '@angular/core'; +import { toSignal } from '@angular/core/rxjs-interop'; +import type { WidgetData } from './backend'; + +/** A shell sent at once, and one widget that streams in when its data is there. */ +@Component({ + selector: 'app-page', + template: ` +
+

Compatibility fixture

+

Sent at once.

+
+ @defer (on immediate; hydrate when widget()) { +
+ @if (widget(); as data) { +
+

Answered by the {{ data.answeredBy }}.

+

Count: {{ count() }}

+ +
+ } @else { +

Loading…

+ } +
+ } +
+
+ `, +}) +export class Page { + protected readonly widget = toSignal(inject(HttpClient).get('/api/widget')); + protected readonly hydrated = signal(false); + protected readonly count = signal(0); + + constructor() { + afterNextRender(() => this.hydrated.set(true)); + } +} diff --git a/compat/fixture/src/index.html b/compat/fixture/src/index.html new file mode 100644 index 0000000..e33584a --- /dev/null +++ b/compat/fixture/src/index.html @@ -0,0 +1,13 @@ + + + + + angular-ssr-stream compatibility fixture + + + + + + + + diff --git a/compat/fixture/src/main.server.ts b/compat/fixture/src/main.server.ts new file mode 100644 index 0000000..7da01b7 --- /dev/null +++ b/compat/fixture/src/main.server.ts @@ -0,0 +1,13 @@ +import { bootstrapApplication } from '@angular/platform-browser'; +import { App } from './app/app'; +import { config } from './app/app.config.server'; + +// `BootstrapContext`, spelled so that it compiles on every Angular version the +// fixture runs on: the type isn't exported by all of them. +type BootstrapContext = Parameters[2]; + +const bootstrap = (context: BootstrapContext) => bootstrapApplication(App, config, context); + +export default bootstrap; + +export { streamingRenderer } from '@push-based/angular-ssr-stream-angular-ssr/renderer'; diff --git a/compat/fixture/src/main.ts b/compat/fixture/src/main.ts new file mode 100644 index 0000000..3b1a614 --- /dev/null +++ b/compat/fixture/src/main.ts @@ -0,0 +1,5 @@ +import { bootstrapApplication } from '@angular/platform-browser'; +import { App } from './app/app'; +import { appConfig } from './app/app.config'; + +bootstrapApplication(App, appConfig).catch((error) => console.error(error)); diff --git a/compat/fixture/src/server.ts b/compat/fixture/src/server.ts new file mode 100644 index 0000000..fb62390 --- /dev/null +++ b/compat/fixture/src/server.ts @@ -0,0 +1,31 @@ +import { + AngularNodeAppEngine, + createNodeRequestHandler, + isMainModule, + writeResponseToNodeResponse, +} from '@angular/ssr/node'; +import { withStreaming } from '@push-based/angular-ssr-stream-angular-ssr'; +import express from 'express'; +import { join } from 'node:path'; + +const browserDistFolder = join(import.meta.dirname, '../browser'); + +const app = express(); +// The host check reads NG_ALLOWED_HOSTS where @angular/ssr has one. +const angularApp = withStreaming(new AngularNodeAppEngine()); + +app.use(express.static(browserDistFolder, { maxAge: '1y', index: false, redirect: false })); + +app.use((req, res, next) => { + angularApp + .handle(req) + .then((response) => (response ? writeResponseToNodeResponse(response, res) : next())) + .catch(next); +}); + +if (isMainModule(import.meta.url)) { + const port = Number(process.env['PORT'] ?? 4000); + app.listen(port, () => console.log(`Listening on http://localhost:${port}`)); +} + +export const reqHandler = createNodeRequestHandler(app); diff --git a/compat/fixture/tsconfig.app.json b/compat/fixture/tsconfig.app.json new file mode 100644 index 0000000..9ee006f --- /dev/null +++ b/compat/fixture/tsconfig.app.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "types": ["node"] + }, + "include": ["src/**/*.ts"] +} diff --git a/compat/fixture/tsconfig.json b/compat/fixture/tsconfig.json new file mode 100644 index 0000000..30d64ce --- /dev/null +++ b/compat/fixture/tsconfig.json @@ -0,0 +1,28 @@ +/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */ +/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */ +{ + "compileOnSave": false, + "compilerOptions": { + "noImplicitOverride": true, + "noPropertyAccessFromIndexSignature": true, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": true, + "skipLibCheck": true, + "isolatedModules": true, + "experimentalDecorators": true, + "importHelpers": true, + "target": "ES2022", + "module": "preserve" + }, + "angularCompilerOptions": { + "enableI18nLegacyMessageIdFormat": false, + "strictInjectionParameters": true, + "strictInputAccessModifiers": true + }, + "files": [], + "references": [ + { + "path": "./tsconfig.app.json" + } + ] +} diff --git a/compat/run.mjs b/compat/run.mjs new file mode 100644 index 0000000..ec8ce78 --- /dev/null +++ b/compat/run.mjs @@ -0,0 +1,365 @@ +#!/usr/bin/env node +// Checks the packages against one Angular version, the way an app made by the +// Angular CLI uses them: installs that version into a copy of `fixture/`, with +// the packages packed from this repository, builds it, starts its server and +// checks what it sends and what a browser makes of it. +// +// node compat/run.mjs --angular 21.2 --mode zoneless +// +// --angular A minor (`21.2`, the latest patch of it), an exact version, or a +// dist-tag (`next`). +// --mode `zoneless` or `zone`. +// --packs A folder with the packed packages. Packed from the repository +// when left out. +// +// Exits non-zero when a check fails. Writes the outcome to +// `compat/.work/