Compiled binary example

Try it
This example runs inside the Setu-TS repository. To start a similar project:
npm create @setu-ts my-app -- --template rest
cd my-app && npm install
npm run start:dev
The commands further down run inside a clone of the repository.

Build the kernel application as a standalone executable.

pnpm --dir apps/compiled-binary run build:sea
./.tmp/compiled-binary/server
pnpm --dir apps/compiled-binary run smoke

The smoke task compiles an executable, starts it, and requests /health.

Read the example deep dive for the concept and source walkthrough.

Read, in order

setu.config.ts

import { createApplication } from '@setu-ts/kernel';
import type { IKernelApplication } from '@setu-ts/kernel';
import { RuntimePlugin } from '@setu-ts/runtime';

/** Builds the application embedded in the standalone executable, without starting it. */
export function createApp(): IKernelApplication {
  const app = createApplication({ plugins: [RuntimePlugin()] });
  app.router.get('/health', (ctx) => ctx.response.json({ status: 'ok' }));
  return app;
}

sea.ts

/* eslint-disable no-console -- an executable reports startup and shutdown failures on stderr. */
/**
 * The entry `build-sea.ts` bundles as CommonJS for Node's single executable.
 *
 * `main.ts` cannot be bundled directly: CommonJS has no top-level `await`.
 */
import { createRuntimeServices } from '@setu-ts/runtime';
import { createApp } from './setu.config.ts';

async function main(): Promise<void> {
  const runtime = createRuntimeServices();
  const app = createApp();
  await app.start({ port: Number(process.argv[2] ?? 3000) });

  for (const signal of ['SIGTERM', 'SIGINT'] as const) {
    runtime.onSignal?.(signal, () => {
      void app
        .stop()
        .then(() => runtime.exit(0))
        .catch((error: unknown) => {
          console.error('Graceful shutdown failed:', error);
          runtime.exit(1);
        });
    });
  }
}

main().catch((error: unknown) => {
  console.error(error);
  process.exitCode = 1;
});

smoke.ts

import assert from 'node:assert/strict';
import { after, before, describe, it } from 'node:test';
import { fileURLToPath } from 'node:url';
import { run } from '../../scripts/lib/run.ts';
import { freePort, startHost, stopHost, waitForHttp } from '../smoke-helpers.ts';
import type { Host } from '../smoke-helpers.ts';

const BINARY = fileURLToPath(new URL('../../.tmp/compiled-binary/server', import.meta.url));

describe('compiled-binary example', () => {
  let server: Host;
  let baseUrl: string;

  before(async () => {
    const built = await run('pnpm', ['run', 'build:sea'], { inherit: true });
    assert.equal(built.code, 0, 'the single-executable build failed');
    const port = await freePort();
    baseUrl = `http://127.0.0.1:${port}`;
    server = startHost(BINARY, [String(port)]);
    await waitForHttp(`${baseUrl}/health`, { label: 'The compiled executable' });
  });

  after(async () => {
    assert.equal(await stopHost(server), 0, 'the executable did not shut down cleanly');
  });

  it('serves /health from the standalone executable', async () => {
    const response = await fetch(`${baseUrl}/health`);

    assert.equal(response.status, 200);
    assert.deepEqual(await response.json(), { status: 'ok' });
  });
});