# Putnami TypeScript framework > Every page of https://putnami.dev/docs/frameworks/typescript as raw Markdown, in navigation order. The index of the whole site is https://putnami.dev/llms.txt. --- Page: TypeScript Source: https://putnami.dev/doc-markdown?path=%2Fdocs%2Fframeworks%2Ftypescript # TypeScript TypeScript is Putnami's most complete application surface: React SSR, API routes, forms, auth, data, storage, events, health, telemetry, and build tooling in one workspace-native stack. > Use it when you want a full-stack app or API where frontend, backend, data access, and runtime behavior share one set of conventions. ## Choose your path | Goal | Start here | Then read | |------|------------|-----------| | Create your first TypeScript project | [Getting Started](/docs/frameworks/typescript/getting-started) | [How To / Guides](/docs/how-to), [Extension phases](/docs/frameworks/typescript/extension), [Overview](/docs/frameworks/typescript/overview) | | Build a full-stack web app | [Web](/docs/frameworks/typescript/web) | [React routing](/docs/frameworks/typescript/react-routing), [Forms & actions](/docs/frameworks/typescript/forms-and-actions), [Static files](/docs/frameworks/typescript/static-files) | | Build an API service | [API](/docs/frameworks/typescript/api) | [HTTP & middleware](/docs/frameworks/typescript/http-and-middleware), [Errors & responses](/docs/frameworks/typescript/errors-and-responses) | | Add users and sessions | [Auth](/docs/frameworks/typescript/auth) | [Sessions](/docs/frameworks/typescript/sessions), [Configuration](/docs/frameworks/typescript/configuration) | | Store application data | [Persistence](/docs/frameworks/typescript/persistence) | [Document storage](/docs/frameworks/typescript/document), [Storage](/docs/frameworks/typescript/storage) | | Add async and realtime behavior | [Events](/docs/frameworks/typescript/events) | [WebSockets & streaming](/docs/frameworks/typescript/websockets), [Caching](/docs/frameworks/typescript/caching) | | Make it production-readable | [Health checks](/docs/frameworks/typescript/health-checks) | [Telemetry](/docs/frameworks/typescript/telemetry), [Logging](/docs/frameworks/typescript/logging), [Platform endpoints](/docs/frameworks/typescript/platform-endpoints) | | Measure your own audience | [Analytics](/docs/frameworks/typescript/analytics) | [Web](/docs/frameworks/typescript/web), [Persistence](/docs/frameworks/typescript/persistence), [Add web analytics](/docs/how-to/add-web-analytics) | | Serve a site in several languages | [Localization](/docs/frameworks/typescript/localization) | [Web](/docs/frameworks/typescript/web), [React routing](/docs/frameworks/typescript/react-routing) | ## The application model Putnami TypeScript apps are composed from small runtime plugins: 1. **Application** owns lifecycle and startup. 2. **Modules** group related capabilities such as auth, API, or data. 3. **Plugins** register servers, routes, providers, hooks, health checks, and generated assets. That model lets a small app stay small while still having a clear upgrade path to a larger service: ```ts application() .use(http()) .use(api()) .use(react()) .use(sql()); ``` ## Capability map | Capability | Read | Why it matters | |------------|------|----------------| | Toolchain | [Extension phases](/docs/frameworks/typescript/extension) | Detection, dependencies, generate, build, test, lint, serve, publish, Docker, and caching | | Composition | [Overview](/docs/frameworks/typescript/overview), [Plugins & lifecycle](/docs/frameworks/typescript/plugins-and-lifecycle) | How apps are assembled and started | | Runtime wiring | [Dependency injection](/docs/frameworks/typescript/dependency-injection), [Configuration](/docs/frameworks/typescript/configuration) | Explicit dependencies, typed config, request scopes | | Contracts | [Schema](/docs/frameworks/typescript/schema), [Proto & gRPC](/docs/frameworks/typescript/proto-grpc), [Smart client](/docs/frameworks/typescript/smart-client) | Typed boundaries between services and clients | | Operations | [Testing](/docs/frameworks/typescript/testing), [Health checks](/docs/frameworks/typescript/health-checks), [Telemetry](/docs/frameworks/typescript/telemetry) | Confidence before deploy and signals after deploy | | Audience measurement | [Analytics](/docs/frameworks/typescript/analytics) | Cookieless page views, declared actions, and daily aggregates in your own database | | Localization | [Localization](/docs/frameworks/typescript/localization) | Locale routes, typed messages, reviewed catalogs, alternates for search engines | | Domain boundaries | [Domain access contracts](/docs/frameworks/typescript/domain-access-contracts) | A declared DARC import enforced at runtime: freshness bounds, ordering, one writer, rebuild (experimental) | ## Recommended first hour 1. Start with [Getting Started](/docs/frameworks/typescript/getting-started) to create a web app, API service, or library. 2. Use [How To / Guides](/docs/how-to) for the first concrete task. 3. Read [Extension phases](/docs/frameworks/typescript/extension) when build, test, serve, publish, or Docker behavior matters. 4. Read [Overview](/docs/frameworks/typescript/overview) to understand the package map. 5. Pick [Web](/docs/frameworks/typescript/web) or [API](/docs/frameworks/typescript/api) depending on your first app shape. 6. Add [Configuration](/docs/frameworks/typescript/configuration) and [Dependency injection](/docs/frameworks/typescript/dependency-injection) before the app grows implicit wiring. --- Page: TypeScript Getting Started Source: https://putnami.dev/doc-markdown?path=%2Fdocs%2Fframeworks%2Ftypescript%2Fgetting-started # TypeScript Getting Started This page takes you from an empty directory to a running Putnami app with [Bun](https://bun.sh/) alone: no Putnami CLI, no workspace. It then shows the Putnami CLI as the next step, for a workspace of several projects. Follow it top to bottom: every command runs from a shell, and each step says what you should see. ## Prerequisites Bun 1.4 or later, on macOS or Linux: ```bash bun --version ``` When the command is missing or prints an older release, install Bun with `curl -fsSL https://bun.sh/install | bash`, open a new shell, and check again. The first install also needs network access to the npm registry. ## Create the app For a React application, server-rendered, with file-based pages: ```bash bun create @putnami my-app cd my-app bun install bun dev ``` For an HTTP API service, with JSON endpoints and no React: ```bash bun create @putnami my-api --template server cd my-api bun install bun dev ``` `bun create @putnami` runs the package `@putnami/create`. It writes the project into a new or empty directory and prints the next commands: ```text Created my-app from typescript-web in my-app Next: cd my-app bun install bun dev ``` `bun install` installs the `@putnami/*` packages at the release that `@putnami/create` shipped with, and writes `bun.lock`. ## Run it `bun dev` generates the routes, serves the app on port 3000, and keeps running. Once the server accepts connections, it prints this line, with its own duration: ```text putnami-dev: generated in 1240ms, serving on port 3000 ``` The server's own log, printed before it, names the same address: `⚡️ listening http://localhost:3000`. Open : - the web app answers with its home page, which links to `/about` and `/guestbook`; - the API service answers `{"message":"Hello, World!"}`, and `curl 'http://localhost:3000/?name=Putnami'` answers `{"message":"Hello, Putnami!"}`. Edit a file under `src/` and save it: `bun dev` generates again and reloads the server, and a new route file answers without a restart. Stop it with `Ctrl-C`. Port 3000 taken? `bun dev` says so; serve on another port with `PORT=3001 bun dev`. ## Where the code goes | Path | Holds | |------|-------| | `src/main.ts` | The application: the plugins it uses | | `src/serve.ts` | The entry `bun dev` serves | | `src/app/` | Web app: one folder per route, with `page.tsx`, `loader.ts`, `action.ts`, and `layout.tsx` around them | | `src/api/` | API service: one file per method and route, such as `get.ts` for `GET /` | | `test/` | The tests `bun test` runs | | `AGENTS.md` | What a coding agent needs: the commands, and where each package's reference lives | Each `@putnami/*` package ships a quick reference at `node_modules/@putnami//AI.md`. ## Test it ```bash bun test ``` The tests start the app in process with `createTestApp` and call it over HTTP; a web app's first run generates its pages, so it takes a few seconds more. A test that needs PostgreSQL reads the database from `DATABASE_URL`: ```bash DATABASE_URL=postgres://postgres:postgres@localhost:5432/app bun test ``` See [Testing](/docs/frameworks/typescript/testing) for the test app, and [Persistence](/docs/frameworks/typescript/persistence) for the database. Bun runs TypeScript without checking its types, so `bun test` passes a test over code the project's `tsconfig.json` refuses, such as `process.env.PORT` where the strict config asks for `process.env['PORT']`. Check the types on their own with: ```bash bun run typecheck ``` It runs `tsc --noEmit` with the `typescript` the project installs, and prints the compiler's diagnostics. ## Build it ```bash bun run build ``` `bun run build` generates the routes, bundles the app, type-checks the project, and compiles it into one production executable, `dist/serve.bundled--` (for instance `dist/serve.bundled-linux-x64`). A type error prints the compiler's diagnostics and stops the build before it compiles anything, as `putnami build` does; `bun run typecheck` checks the same sources and the tests, without building. Run the executable from the project directory: ```bash PORT=8080 ./dist/serve.bundled-linux-x64 ``` A web app's executable serves its client files, the scripts and stylesheets the browser loads, from `.gen/public` under the directory it runs from: started from anywhere else, its pages render but their scripts and styles answer with an error. To run the app on another machine, build its container image instead: `--image` compiles for Linux and stages the client files and a `Dockerfile` beside the executable. ```bash bun run build -- --image docker build dist ``` `bun dev`, `bun test` and `bun run build` run the generate step themselves. To run it alone, to read the generated code under `.gen/`: ```bash bun run putnami-generate ``` ## Style it A page, a layout or a component of a web app styles itself by importing CSS: a plain stylesheet such as the template's `src/app/styles.css`, a CSS Module (`*.module.css`), or Tailwind. The build compiles them into hashed static files, and `bun dev` rebuilds them when a `.css` file changes. See [Styling](/docs/frameworks/typescript/web#styling); the full guide ships with the package, at `node_modules/@putnami/web/doc/styling.md`. ## Try the canary npmjs receives `@putnami/create` at each release. Every build of `main` publishes it to the `canary` dist-tag of `https://npm.putnami.dev`, which serves the `@putnami` scope only: to try the canary, map the scope in `~/.bunfig.toml`, then pass the registry to the project. ```toml [install.scopes] "@putnami" = "https://npm.putnami.dev" ``` ```bash bunx @putnami/create@canary my-app --registry https://npm.putnami.dev ``` ## Next: the Putnami CLI The app above runs with Bun alone. The Putnami CLI runs the same steps across a workspace of projects, TypeScript, Go and Python, and adds lint, the impacted gate, publishing and container images. Install it on macOS or Linux; the second line makes `putnami` reachable in the shell you are in: ```bash curl -fsSL https://putnami.dev/install.sh | bash export PATH="$HOME/.putnami/bin:$PATH" ``` [Getting Started](/docs/getting-started) says what the installer checks and does. Then, from an empty directory: ```bash putnami init ``` You do not install Bun for the CLI: `putnami init` uses a Bun the machine already holds when it fits, and installs one under the Putnami home otherwise. The workspace records the release in `package.json#packageManager` and `putnami.lock.json`, and every task runs with that exact release. | You need... | Template | What you get | |-------------|----------|--------------| | A React SSR application | `typescript-web` | File-based pages, layouts, loaders, actions, islands, static assets | | An HTTP API service | `typescript-server` | API routing, handlers, tests, application runtime | | A shared TypeScript package | `typescript-library` | Package exports, tests, workspace dependency wiring | ```bash putnami projects create web --template typescript-web putnami deps install putnami serve web ``` `putnami init ` also creates a first project from the `typescript-web` template, and `--template server` from `typescript-server`; `putnami init --help` lists every template. The daily loop: ```bash putnami serve web putnami test web putnami lint,test,build --impacted ``` `--impacted` keeps the feedback loop scoped to the projects affected by your branch. ## With Bun alone Without the Putnami CLI or a workspace, `bun create` starts the same web or API project from the same templates: ```bash bun create @putnami web # a React SSR application bun create @putnami api --template server # an HTTP API service cd web bun install bun dev ``` `bun create @putnami` runs the package `@putnami/create`. The project it creates pins each `@putnami/*` package to the release that package shipped with, and runs `bun dev`, `bun test` and `bun run build` with Bun alone. Its `AGENTS.md` points an agent at each package's `node_modules/@putnami//AI.md`. npmjs receives `@putnami/create` at each release. Every build of `main` publishes it to the `canary` dist-tag of `https://npm.putnami.dev`, which serves the `@putnami` scope only: to try the canary, map the scope in `~/.bunfig.toml`, then pass the registry to the project. ```toml [install.scopes] "@putnami" = "https://npm.putnami.dev" ``` ```bash bunx @putnami/create@canary web --registry https://npm.putnami.dev ``` ## What to look at first Start with the project shape, then add framework depth only when the app needs it: 1. [Web](/docs/frameworks/typescript/web) for React SSR, routing, loaders, actions, and islands. 2. [API](/docs/frameworks/typescript/api) for HTTP endpoints and server-side handlers. 3. [Configuration](/docs/frameworks/typescript/configuration) when the first environment variable appears. 4. [Dependency injection](/docs/frameworks/typescript/dependency-injection) before runtime wiring becomes implicit. 5. [Testing](/docs/frameworks/typescript/testing) before the project becomes a dependency for another project. 6. [Persistence](/docs/frameworks/typescript/persistence) when the service needs Postgres: the connection, migrations, and tests against the database. 7. [Publish & Docker](/docs/frameworks/typescript/extension/publish-and-docker) to build the binary or the container image. ## Read next - [TypeScript overview](/docs/frameworks/typescript/overview) for the package map and runtime model. - [Extension](/docs/frameworks/typescript/extension) for build, test, lint, serve, publish, and Docker behavior. - [CLI](/docs/tooling-&-workspace) for the shared graph and CLI model. --- Page: TypeScript Extension Source: https://putnami.dev/doc-markdown?path=%2Fdocs%2Fframeworks%2Ftypescript%2Fextension # TypeScript Extension The `@putnami/typescript` extension is the TypeScript project lifecycle inside a Putnami workspace. It owns project detection, dependency setup, generation, build, test, lint, serve, packaging, and TypeScript-specific publish behavior. Use this page as the map. The detailed lifecycle is split by phase so you can jump to the part of the pipeline you are debugging or configuring. ## Extension phases | Phase | Start here | What it explains | |-------|------------|------------------| | Project setup | [Project detection](/docs/frameworks/typescript/extension/project-detection) | Which projects the extension owns and how templates activate it | | Dependencies | [Dependencies & install](/docs/frameworks/typescript/extension/dependencies-and-install) | Bun, Biome, workspace install, and extension dependencies | | Generation | [Generate phase](/docs/frameworks/typescript/extension/generate-phase) | Pre-build hooks, generated exports, and generated assets | | Feedback loop | [Build, test & lint](/docs/frameworks/typescript/extension/build-test-lint) | Compile phases, Bun tests, Biome format/lint | | Local runtime | [Serve & watch](/docs/frameworks/typescript/extension/serve-and-watch) | Entrypoints, ports, hot reload, and multi-service mode | | Release artifacts | [Publish & Docker](/docs/frameworks/typescript/extension/publish-and-docker) | npm packages, archives, Docker images, and stable releases | | Repeatability | [Configuration & caching](/docs/frameworks/typescript/extension/configuration-and-caching) | Cache inputs, task dependencies, and project options | ## Enable the extension Most TypeScript templates enable it for you: ```bash putnami projects create web --template typescript-web putnami deps install ``` To add it to an existing workspace: ```bash putnami deps add @putnami/typescript putnami deps install ``` The extension is auto-discovered from workspace dependencies and activates on TypeScript projects with the matching package metadata. ## External tools - [Bun](https://bun.sh) for runtime, bundling, tests, and executable compilation - [Biome](https://biomejs.dev) for formatting and linting - TypeScript declaration generation for library and application packages ## Daily loop ```bash putnami serve web putnami test web putnami lint,test,build --impacted ``` Use the phase pages when a command becomes unclear. The sidebar keeps `Getting Started`, `How To / Guides`, `Extension`, and `Framework / Capabilities` visible so readers can move between task-oriented and reference-oriented material. --- Page: Project Detection Source: https://putnami.dev/doc-markdown?path=%2Fdocs%2Fframeworks%2Ftypescript%2Fextension%2Fproject-detection # Project Detection The TypeScript extension runs only in project context. It is responsible for TypeScript projects that live inside the Putnami workspace graph: web apps, API services, libraries, and extension packages. ## What activates it The extension is available when the workspace depends on `@putnami/typescript`. Project templates wire the project metadata automatically: ```bash putnami projects create web --template typescript-web putnami projects create api --template typescript-server putnami projects create ui --template typescript-library ``` For existing projects, add the extension at the workspace level: ```bash putnami deps add @putnami/typescript putnami deps install ``` ## Project shapes | Template | Extension behavior | |----------|--------------------| | `typescript-web` | Build React SSR routes, generated assets, serve entrypoint, and deployable runtime output | | `typescript-server` | Build API handlers, application runtime, tests, and server entrypoint | | `typescript-library` | Build package exports, declaration files, and test output | ## Entrypoint signals The extension reads package metadata to understand how a project should run: - `exports` controls package entrypoints - `./serve` identifies a serve entrypoint when present - `bin` entries and `build.compile` identify executable outputs - project config can add generated assets, publish channels, and compile targets ## Scope boundary The extension does not replace workspace orchestration. Putnami still decides project order, impacted projects, cache reuse, and cross-project dependencies. The extension provides the TypeScript-specific jobs that run inside that orchestration. --- Page: Dependencies & Install Source: https://putnami.dev/doc-markdown?path=%2Fdocs%2Fframeworks%2Ftypescript%2Fextension%2Fdependencies-and-install # Dependencies & Install The TypeScript extension keeps JavaScript and TypeScript dependency setup workspace-native. You should use Putnami dependency commands, not package-manager commands directly. ## Install the extension ```bash putnami deps add @putnami/typescript putnami deps install ``` `putnami deps install` installs workspace dependencies and keeps project links consistent with the Putnami graph. ## Toolchain The extension uses: - Bun for install, runtime, bundling, tests, and executable compilation - Biome for format and lint - TypeScript for declaration output The workspace install phase ensures required TypeScript dev dependencies exist at the workspace root when needed. ## When to run install Run dependency install after: - creating a TypeScript project from a template - adding or removing a workspace dependency - changing extension dependencies - pulling a branch that changed the lockfile or workspace package metadata ```bash putnami deps install ``` ## Upgrading Putnami packages `putnami upgrade --deps` pins `@putnami/*` packages to the selected release in the workspace root `package.json`. It updates both `dependencies` and `overrides` so direct and transitive Putnami packages resolve to the same version before the workspace install runs. Workspaces that enable the `@putnami/cloud` extension also have the npm `@putnami/cloud` runtime package pinned during `putnami upgrade --deps`, even before an app adds it directly. ## Project dependencies Workspace dependencies should stay visible to Putnami. That lets `--impacted` select the right build, test, and lint jobs. Use project references and workspace package metadata rather than hidden local imports. If one project consumes generated assets from another, keep that relationship in the normal workspace dependency graph. --- Page: Generate Phase Source: https://putnami.dev/doc-markdown?path=%2Fdocs%2Fframeworks%2Ftypescript%2Fextension%2Fgenerate-phase # Generate Phase `generate` runs before TypeScript build and test jobs. It prepares generated source, exports, and static assets so downstream phases see a complete project. ## What generate does Key steps: - discover pre-build hooks from plugin dependencies - run hooks in ascending `order`, ties broken by extension name - write generated source and export metadata to `.gen/` - copy configured generated assets into the project output Generate is not a command of its own: `putnami build` and `putnami test` run it first. ```bash putnami build . putnami build . --clear ``` ## Options | Option | Use | |--------|-----| | `--verbose` | Show detailed generation output | | `--clear` | Clear the dist folder before building | ## Pre-build hooks A dependency contributes a pre-build hook by shipping a `putnami.extension.json` at its package root that declares `hooks.preBuild`: ```json { "$schema": "https://putnami.dev/schemas/putnami-extension.json", "name": "@my/extension", "hooks": { "preBuild": { "kind": "command", "command": "bun", "args": ["run", "{extensionRoot}/bin/generate"], "cwd": "{projectRoot}", "timeoutMs": 120000 } } } ``` The runner expands `{workspaceRoot}`, `{projectRoot}` and `{extensionRoot}` in the arguments, appends `--putnami-context `, the JSON job context, and sets `PUTNAMI_PREBUILD_CONTEXT=true`. The hook writes JSONL events on stdout; its last one, the `summary`, carries the exports and assets it produced and its route evaluation, `data.httpRoutes`, which every pre-build hook reports: `{"v":1,"state":"complete"}` once it has evaluated its route contribution, or `{"v":1,"state":"unavailable","reason":""}` when it could not. A hook that omits it or reports it `unavailable` fails generate with `HTTP_ROUTES_UNAVAILABLE`, which names the hook and the cause. Hooks run in ascending `order`, `0` by default: raise it for a hook that must observe what the others generated. ## Create a hook `runHookCommand` from `@putnami/utils/hooks` parses the arguments, reads the context and writes the events and the summary: ```ts import { completeHttpRoutesEvaluation } from '@putnami/application/http-routes'; import { runHookCommand, standardHookModel } from '@putnami/utils/hooks'; await runHookCommand({ model: standardHookModel.extend({ name: 'generate' }), extension: '@my/extension', hook: 'preBuild', run: async (_options, context) => { // Write generated sources under context.outputRoot. return { exports: { './generated': `${context.outputRoot}/main.ts` }, data: { httpRoutes: completeHttpRoutesEvaluation() }, }; }, }); ``` Declare the hook's entry point in the `package.json` `bin` map: besides `src/`, the build transpiles only the scripts the `bin` map names, and the npm packager ships them next to the copied `putnami.extension.json`. A hook script missing from `bin` ships without its runnable `.js`. ```json { "name": "@my/extension", "bin": { "my-extension-generate": "./bin/generate.ts" } } ``` --- Page: Build, Test & Lint Source: https://putnami.dev/doc-markdown?path=%2Fdocs%2Fframeworks%2Ftypescript%2Fextension%2Fbuild-test-lint # Build, Test & Lint The fast feedback loop for TypeScript projects is `build`, `test`, and `lint`. All three commands run inside the Putnami project graph, so dependency order and cache reuse stay consistent across the workspace. ## Build Build compiles TypeScript packages for distribution with Bun and TypeScript declaration output. Default build phases: 1. `generate` - pre-build hooks and generated artifacts 2. `transpile` - JavaScript package output in `output/lib` 3. `types` - declaration output in `output/types` `compile` is opt-in and creates standalone executable output. ```bash putnami build . putnami build . --compile putnami build . --compile --compile-target bun-linux-x64 ``` Common options: - `--generate`, `--transpile`, `--types`, `--compile` to select phases - `--target ` - `--bundle ` - `--sourcemap ` - `--minify ` - `--fast` to skip type generation - `--clear` to wipe the output folder first ## Test Tests run through Bun's test runner. ```bash putnami test . putnami test . --coverage ``` Behavior: - discovers `**/*.{test,spec}.{ts,tsx,js,jsx}` - returns `SKIP` when no tests are found - produces JUnit output - can produce LCOV coverage - type-checks every TypeScript file of the project, tests included Bun strips types when it runs a test, so the `test~types` step type-checks the project, dot-directories such as `.gen` included: with `bun check` when the Bun that runs it supports it (1.4.4 or later), and with `tsc --noEmit` otherwise, on the same tsconfig and compiler options. Setting `type-checker` to `tsc` or `bun` in `options["@putnami/typescript:test"]` chooses one; only that parameter chooses, never an import or a script. `bun check` checks with the TypeScript 7 that Bun embeds; a `baseUrl` in the tsconfig chain stops it before it checks, and so do `moduleResolution` `node` or `node10` and `target` `es5` when the runner is Vitest or Jest, where `tsc` accepts them: remove those options or keep `tsc` there. It uses the tsconfig and the compiler options of `build~types`. A type error in a test fails `putnami test`. `node_modules`, `dist`, `.putnami` and nested projects stay out. Useful options: - `--timeout ` - `--coverage` - `--coverage-threshold ` - `--test-name-pattern ` - `--update-snapshots` - `--pass-with-no-tests ` - `--type-checker ` ## Lint Lint uses Biome for format and static checks. ```bash putnami lint . putnami lint . --fix false putnami lint . --unsafe-fixes ``` `putnami lint .` fixes what it can by default, with safe fixes only: they never change what the code means. Biome's unsafe fixes can, so they apply only with `--unsafe-fixes`; an ESLint project has no unsafe class and ignores the flag. `--fix false` only reports, the canonical CI target. The phases are in the [lint reference](https://github.com/putnami/putnami/blob/main/typescript/extension/doc/04-lint.md). Config resolution: 1. project `biome.json` 2. workspace root `biome.json` 3. built-in config from `@putnami/typescript` Lint also refuses a test that hides a failure: `.only(` (and `fit(`), a `.skip(` outside a guard (and `xit(`), and a `.skipIf(`, `.if(`, `if`, `case`, `&&` or ternary whose condition names flakiness or CI. A string key, `test['only'](`, counts as `.only(`. Any other condition, in `skipIf()`, an `if`, an `&&` or a ternary, counts as a guard. A skip that stays on purpose carries `// putnami:allow-skip ` on its line or on a comment line just above, and lint reports it as a warning. Set `"@putnami/typescript:lint": { "skip-guard": false }` under `options` in `putnami.workspace.json` to turn the guard off. Lint also checks every relative link and anchor in the project's `README.md` files and `doc/` trees, and fails on one that does not resolve. Set `"lint": { "docs-links": false }` under `options` in a project's `putnami.json` to turn the check off for that project. --- Page: Serve & Watch Source: https://putnami.dev/doc-markdown?path=%2Fdocs%2Fframeworks%2Ftypescript%2Fextension%2Fserve-and-watch # Serve & Watch `serve` starts a TypeScript development server and keeps generated output current while you work. ## Entrypoint resolution The extension resolves the application entrypoint from: 1. `./serve` in `package.json` exports 2. `--entrypoint ` 3. a fast build fallback when no serve export exists ```bash putnami serve . putnami serve . --port 4000 putnami serve . --entrypoint src/server.ts ``` `putnami serve`, the compiled binary and the container image all run `src/serve.ts` (the `./serve` export) and resolve the same `conf/` config, `putnami.port` included. A `PORT` variable, which an image sets, still outranks `putnami.port`. `putnami serve` sets `PORT=0` and reaches the service at a stable address derived from its project id, so `putnami.port` does not place it; see [Run your system locally](/docs/how-to/run-your-system-locally). See [What the compiled binary runs](/docs/frameworks/typescript/extension/publish-and-docker#what-the-compiled-binary-runs). ## Options | Option | Use | |--------|-----| | `--entrypoint ` | Override the serve entrypoint | | `--watch ` | Enable or disable watch mode | | `--port ` | With one selected project, place its address on this port for the run | | `--debug` | Forward `LOG_LEVEL=debug` to the application | | `--inspect`, `--inspect-wait`, `--inspect-brk` | Enable Bun inspector modes | ## Without the CLI A project the `typescript-server` and `typescript-web` templates create runs with Bun alone, without the Putnami CLI or a `putnami.workspace.json`. `@putnami/application` ships the commands its scripts call: ```bash bun dev # putnami-dev: generate, serve under Bun's watch, generate again on each change bun test # createTestApp runs the generate step when an output is missing or stale bun run build # putnami-build: the production executable, --image for the container build context ``` `putnami serve` reloads the server through Bun's watch. `bun dev` also pushes edits to the open browser without a reload: see [Hot updates in development](/docs/frameworks/typescript/web#hot-updates-in-development). The details are in the [`putnami-dev`](https://github.com/putnami/putnami/blob/main/typescript/framework/application/doc/dev.md) and [`putnami-build`](https://github.com/putnami/putnami/blob/main/typescript/framework/application/doc/build.md) guides; tests are in [Testing](/docs/frameworks/typescript/testing#tests-without-the-cli). ## Multi-service mode Declare runtime service dependencies in `package.json`: ```json { "putnami": { "runsWith": ["catalogue-api", "profile-api"] } } ``` Then run: ```bash putnami serve web-app --watch ``` Putnami starts the web app and its declared services together. If `runsWith` is absent, serve walks the dependency graph for projects with `./serve` exports. ## Port conflicts The serve job checks for port conflicts before starting. Conflicts are resolved interactively, or automatically in CI, and the selected port is saved to project config for future runs. --- Page: Publish & Docker Source: https://putnami.dev/doc-markdown?path=%2Fdocs%2Fframeworks%2Ftypescript%2Fextension%2Fpublish-and-docker # Publish & Docker The TypeScript extension contributes TypeScript-specific release artifacts. It owns the `npm` ecosystem profile — the coordinate and version rules, the shape of the workspace's `registries.npm` entry, and the job that reports each published member — and publishes to the `oci` ecosystem the extension SDK owns. ## Package a service as an image `putnami package` builds only the channels you turn on. With no channel on, `putnami package --projects api` fails and names the option to set; under `--all` or `--impacted` it warns and goes on. Turn the image channel on in the project's `putnami.json`: ```json { "name": "api", "options": { "package": { "docker": true, "port": 8080 } } } ``` Each key under `options.package` is the default of the `putnami package` flag with the same name, so `"docker": true` is `--docker` and `"port": 8080` is `--port 8080`. ```bash putnami package --projects api --docker-load --docker-tag local docker run --rm -p 8080:8080 -e DATABASE_URL='postgres://user:pass@host.docker.internal:5432/app?sslmode=disable' api:local ``` Add `--platform linux/arm64` on Apple silicon. The image holds the compiled binary and the project's `.gen/public` assets, on a distroless base. ### The image port The image sets `PORT` and exposes that port: 3000 unless you pass `--port` or set `options.package.port`. `http()` listens on its `port` option when you pass one, then on `PORT`, then on the `putnami.port` config value (3000). Leave the port out of `http()` so the service follows `PORT`, and set `options.package.port` to the port you publish. To change it at run time, pass `-e PORT=8080`. ### What the compiled binary runs `putnami build --compile` and the image compile one entry point. For an application built on `@putnami/application`, it is a generated file, `.gen/src/serve.bundled.ts`. That file runs the same entry as `putnami serve`: `src/serve.ts`, or the file under `src/` the `./serve` export names. A project with neither gets `bootstrapServe(app)` on the `app` that `package.json#main` exports (`src/main.ts` by default). The binary embeds the project's `conf/.env.yaml` and every `conf/.env..yaml`, so it reads the same base and environment files as `putnami serve`, `putnami.port` included, from any directory and in the image, where the `PORT` the image sets outranks `putnami.port`. The machine-local overrides `conf/.env.local.yaml` and `conf/.env.prod.yaml`, which the workspace's `.gitignore` ignores, stay out of it. It reads `NODE_ENV` and `APP_ENV` when it runs: the image sets `NODE_ENV=production`, so `conf/.env.production.yaml` applies over `conf/.env.yaml`, and the framework runs in production mode (no development error pages). With `putnami.port: 8080` in `conf/.env.yaml`, the binary listens on 8080 wherever it runs; the image's `PORT` follows [The image port](#the-image-port). The binary embeds no `conf/.secrets.*` file. Pass secrets and per-deployment values with environment variables: fields declared with `Env(...)`, `${VAR}` references in the conf files, `CONFIG_DATA` (a YAML document), and `DATABASE_URL` for the database. See [Configuration](/docs/frameworks/typescript/configuration) and [Persistence](/docs/frameworks/typescript/persistence#database-configuration). To run the binary without Docker: ```bash putnami build --projects api --compile PORT=8080 .putnami/out/api/~build/compile/serve.bundled-darwin-arm64 ``` ## Publish channels Enable channels in project config: ```json { "publish": ["npm", "archives"] } ``` Common commands: ```bash putnami build . putnami publish . putnami build . putnami publish . --channel canary ``` Options include: - `--channel ` — the release-set channels this publication advances - `--visibility ` — the per-publication level of the declared chain - `--access ` - `--registry ` — an override for one publication - `--dry-run` There is no `--stable` and no `--also-branch-tag`. A version is derived from git: a commit tagged with its line's tag publishes that version, any other commit publishes the next version with an ordered pre-release suffix. A channel is advanced by the release, never by a publisher, so no dist-tag is written on any path. ## Registries The npm endpoints come from the workspace's `registries.npm` entry, overridable per project: ```json { "registries": { "npm": { "publish": "https://npm.example.com", "scopes": { "@acme": "https://npm.example.com" } } } } ``` `publish` is where a publication uploads. Each `scopes` entry becomes one `@:registry=` line in the workspace `.npmrc`, and `upgrade --channel` reads each package's dist-tag on the registry its own scope names. No registry URL is hard-coded in the extension, and `--registry` is an override for a single command rather than the place a workspace declares its registry. ## Docker When the `docker` publish channel is enabled, the extension generates a Dockerfile based on `oven/bun:slim` and copies the pre-compiled standalone bundle into the container. ```json { "publish": ["npm", "docker"] } ``` ```bash putnami build my-app --compile putnami publish my-app ``` Docker options: - `--docker-registry ` — an **override**; the declared target is `registries.oci.publish` - `--docker-tag ` - `--platform ` - `--port ` The publisher pushes by digest and tags the version only. An image project yields an `oci` member of the release set, keyed by its repository path, so a workload's image travels in the same snapshot as the packages published beside it. ## Versions Build output uses the version of the project's version line, derived from git: the line's last tag advanced by the conventional commits that touch it, plus `--` on any untagged commit. Release a line with `putnami version tag --scope `; see [Version Management](../../../../tooling/cli/doc/14-version-management.md). --- Page: Configuration & Caching Source: https://putnami.dev/doc-markdown?path=%2Fdocs%2Fframeworks%2Ftypescript%2Fextension%2Fconfiguration-and-caching # Configuration & Caching TypeScript jobs are cache-aware. Cache inputs are declared per phase so `--impacted` and repeated local runs can skip work that has not changed. ## Job dependencies | Job | Depends on | Cache behavior | |-----|------------|----------------| | `generate` | `^generate` | Cached from source, package metadata, and generation inputs | | `build` | `generate`, `^build` | Cached from source, config, package metadata, and docs/assets | | `test` | `generate` | Cached from source, tests, and package metadata | | `lint` | none | Cached from source, Biome config, and package metadata | | `serve` | `build --fast` | Never cached | | `publish` | `build --transpile --types`, `^publish` | Uses build outputs | ## Common cache inputs Build and test cache keys include files such as: - `src/**/*.ts` - `src/**/*.tsx` - `test/**/*.ts` - `test/**/*.tsx` - `package.json` - `tsconfig.json` - `tsconfig.app.json` - `tsconfig.lib.json` - `biome.json` - `doc/**/*` ## Project options Use project configuration for behavior that should be reproducible across local, CI, and preview runs: - generated asset paths - compile targets - publish channels - serve port choices - coverage thresholds - Biome config paths Run the final branch check through Putnami, not a language-specific tool: ```bash putnami lint,test,build --impacted ``` --- Page: Overview Source: https://putnami.dev/doc-markdown?path=%2Fdocs%2Fframeworks%2Ftypescript%2Foverview # Overview Putnami frameworks are composable plugins. You only bring the parts you need for each app, and the CLI orchestrates them together. This modular architecture lets you start simple and add capabilities as your application grows. ## Packages at a glance - **@putnami/application** - HTTP servers, middleware, API routing, WebSockets, sessions, OAuth, static files - **@putnami/web** - React SSR, file-based routing, loaders, actions, streaming, hydration - **@putnami/database** - PostgreSQL integration, entities, repositories, migrations, queries - **@putnami/document** - Portable document collections, typed repositories, cursor pagination, memory and Firestore adapters - **@putnami/storage** - Object storage, bucket declarations, presigned URLs, pluggable backends - **@putnami/ui** - UI components and theming, design system, accessible components - **@putnami/runtime** - Foundation utilities, DI container, config, logging, validation - **@putnami/utils** - The declarative schema vocabulary plus shared browser/server helpers - **@putnami/cli-protocol** - Typed, validated reader for Putnami CLI machine output - **@putnami/codehost-protocol** - The code-host slugs and their words: pull or merge request, diff tab, the Putnami note marker ## Application composition Every Putnami application starts with an `Application` instance. You compose functionality by chaining `.use()` calls with plugins and modules. Prefer the `application()` factory: ```ts import { application, http, api, staticFiles } from '@putnami/application'; import { react } from '@putnami/web'; import { sql } from '@putnami/database'; export const app = () => application() .use(http({ port: 3000 })) .use(api()) .use(react()) .use(sql()) .use(staticFiles({ publicFolder: 'public' })); ``` ### Modules Group related plugins into reusable modules with `module()`. The hierarchy is **Application > Module > Plugin**: ```ts import { application, module, http, api, oAuth2 } from '@putnami/application'; const authModule = module('auth') .use(oAuth2()) .use(api({ prefix: '/auth' })); export const app = () => application() .use(http({ port: 3000 })) .use(authModule); ``` Modules are composable — they can contain plugins, sub-modules, and DI providers. Only the Application has a startable lifecycle; modules are structural units. Use `composeModules()` when a set of sibling feature modules should satisfy each other's DI requirements as one mounted unit. ### Plugin lifecycle Each plugin can hook into four lifecycle phases: 1. **generate()** - Runs at build time for code generation and asset compilation 2. **warmup()** - Runs before the app starts for route registration and cache preloading 3. **start()** - Starts servers, opens database connections, initializes background tasks 4. **stop()** - Graceful shutdown in reverse order of registration ## Architecture patterns ### Full-stack web application For applications with a React frontend and API backend: ```ts import { application, http, api, staticFiles, oAuth2 } from '@putnami/application'; import { react } from '@putnami/web'; import { sql } from '@putnami/database'; export const app = () => application() .use(http({ port: 3000 })) .use(sql()) .use(oAuth2()) .use(api()) .use(react()) .use(staticFiles({ publicFolder: 'public' })); ``` ### API-only service For microservices or backend APIs without a frontend: ```ts import { application, http, api } from '@putnami/application'; import { sql } from '@putnami/database'; export const app = () => application() .use(http({ port: 3000 })) .use(sql()) .use(api()); ``` ### Background job runner For one-shot jobs or scheduled tasks: ```ts import { application } from '@putnami/application'; import { sql } from '@putnami/database'; export const job = () => application() .use(sql()) .run(async () => { // Perform your job logic here console.log('Job completed'); }); ``` ## How to choose packages ### Building a web UI Start with `@putnami/web` and `@putnami/ui`: ```ts import { application, http, staticFiles } from '@putnami/application'; import { react } from '@putnami/web'; export const app = () => application() .use(http()) .use(react()) .use(staticFiles()); ``` Key features: - Server-side rendering with React 19 streaming - File-based routing in `src/app/` - Typed loaders for data fetching - Actions for form handling - Document helpers for SEO ### Building an API Start with `@putnami/application` and the `api()` plugin: ```ts import { application, http, api } from '@putnami/application'; export const app = () => application() .use(http({ port: 3000 })) .use(api()); ``` Key features: - File-based route discovery - Request context with typed body parsing - Response helpers for JSON, redirects, errors - Middleware composition - WebSocket support ### Adding persistence Add `@putnami/database` for PostgreSQL support: ```ts import { application } from '@putnami/application'; import { sql } from '@putnami/database'; export const app = () => application() .use(sql()); ``` Key features: - Entity decorators (`@Table`, `@Column`, `@Key`) - Repository pattern with type-safe queries - Migration management - Multi-database support - Query operators for complex filters ### Adding document storage Add `@putnami/document` when your data is document-shaped and you want portable repositories across memory and Firestore: ```ts import { application } from '@putnami/application'; import { document } from '@putnami/document'; export const app = () => application() .use(document()); ``` Key features: - Declarative `Collection`, `Field`, and `DocumentId` builders - Typed repositories with cursor-based pagination - Portable query operators across adapters - Single-store transactions - Named document stores and optional strict index enforcement ### Adding authentication Add the `oAuth2()` plugin for OAuth2/OIDC support: ```ts import { application, http, oAuth2 } from '@putnami/application'; export const app = () => application() .use(http()) .use(oAuth2()); ``` Key features: - OAuth2 provider integration - Session management - Token handling - Protected route helpers ### Shared concerns Use `@putnami/runtime` for cross-cutting functionality: ```ts import { useLogger, useConfig } from '@putnami/runtime'; class MyService { private logger = useLogger('MyService'); doWork() { this.logger.info('Working...'); } } ``` Key features: - Dependency injection with singleton and request scopes - Typed configuration with validation - Structured logging - Error handling utilities ## Project structure A typical Putnami project follows this structure: ```text my-app/ src/ main.ts # Application entry point app/ # Routes and pages page.tsx # Homepage (React) loader.ts # Homepage data loader api/ health/ get.ts # GET /api/health users/ get.ts # GET /api/users post.ts # POST /api/users [id]/ get.ts # GET /api/users/:id entities/ # Database entities user.ts services/ # Business logic user.service.ts lib/ # Utilities public/ # Static assets .env.local.yaml # Local configuration package.json tsconfig.json ``` ## Next steps Dive deeper into each framework capability: - [Web](/docs/frameworks/typescript/web) - React SSR and file-based routing - [API](/docs/frameworks/typescript/api) - HTTP routes and request handling - [Auth](/docs/frameworks/typescript/auth) - OAuth2 and authentication - [Persistence](/docs/frameworks/typescript/persistence) - Database entities and queries - [Document storage](/docs/frameworks/typescript/document) - Document collections and repository APIs - [Storage](/docs/frameworks/typescript/storage) - Object storage and file uploads - [Configuration](/docs/frameworks/typescript/configuration) - Typed config management - [Plugins & Lifecycle](/docs/frameworks/typescript/plugins-and-lifecycle) - Custom plugins - [HTTP & Middleware](/docs/frameworks/typescript/http-and-middleware) - Request processing - [Dependency Injection](/docs/frameworks/typescript/dependency-injection) - Service management --- Page: UI System Source: https://putnami.dev/doc-markdown?path=%2Fdocs%2Fframeworks%2Ftypescript%2Fui # UI System Use `@putnami/ui` for server-renderable React components, responsive layout, light/dark theming, interaction semantics, and sanitized rich content. Routing, loaders, actions, and authorization belong to `@putnami/web` and `@putnami/application`. ## Installation ```bash putnami deps add @putnami/ui ``` ## Start with the theme ```tsx import { Button, Container, Heading, Text, ThemeProvider, VStack } from '@putnami/ui'; export function App() { return ( Account Manage your profile. ); } ``` `ThemeProvider` accepts `light`, `dark`, or `system`. It emits one bootstrap script that resolves the persisted/system preference before paint and marks the root element with `data-color-mode`. Existing component classes follow later mode changes because mode-dependent colors use semantic CSS custom properties. When writing custom Emotion styles, use `var(--color-*)` for mode-dependent colors. Values read from `theme.colors.*` are serialized into the SSR class and will not change merely because `data-color-mode` changes. Typed spacing, radii, typography, breakpoints, and other mode-independent tokens remain safe to read from the theme object. ## Responsive layout Layout primitives include `Box`, `Flex`, `Grid`, `Stack`, `HStack`, `VStack`, `Container`, and `Page`. Responsive arrays are mobile-first: ```tsx import { Box, Grid } from '@putnami/ui'; {/* cards */} ; ``` The first value is the base rule; later values map to `sm`, `md`, `lg`, `xl`, and `xxl`. Null values skip a breakpoint and values beyond the catalog are ignored. Components never need to read the browser viewport during render, so server and browser emit the same CSS. ## Components and interaction semantics The public component families are: - typography and data display: `Heading`, `Text`, `Card`, `Table`, `Badge`, `Avatar`, `Divider`, `CodeBlock`; - form and feedback: `Button`, `Input`, `Alert`, `Progress`, `Spinner`, `ToastProvider`, `useToast`; - navigation: `Link`, `Tabs`, `Breadcrumb`, `Pagination`; - overlays: `Modal`, `Drawer`, `Dropdown`, `Popover`, `Tooltip`; - icons: built-in SVG components plus `createIcon()`; - Emotion integration: typed `styled`, `css`, and `keyframes`. Loading buttons expose busy and disabled state. Modal/drawer surfaces expose dialog semantics only while open. Tabs expose selection and roving-tabindex state and support Arrow, Home, and End navigation across enabled items. Overlay focus helpers wrap Tab at the surface boundary and support Escape/outside-click dismissal. These primitives do not make arbitrary application composition accessible by themselves. Provide meaningful labels, content order, trigger relationships, and initial focus for your workflow. ## Safe rich content `MarkdownRenderer` accepts pre-rendered HTML and sanitizes it at the raw HTML sink: ```tsx import { MarkdownRenderer } from '@putnami/ui'; ; ``` Its allowlist preserves structural headings, lists, tables, code blocks, documented Shiki variables, code-group/Mermaid data attributes, and `aria-*` attributes. It removes scripts/styles and their contents, embedded browsing contexts, comments, event attributes, unsafe inline styles, and dangerous URL schemes after decoding entity/control-character obfuscation. New browsing contexts receive `rel="noopener noreferrer"`. `MarkdownContent` is only a styled container. If you inject raw HTML into it, sanitize explicitly: ```tsx import { MarkdownContent, sanitizeHtml } from '@putnami/ui'; ; ``` ## Support and compatibility `@putnami/ui` is a public, documented, maintained package classified `stable`. Its UI-system specification and accepted ADRs for SSR color mode and rich content live next to the package source. The promise covers deterministic server/browser styling, mobile-first responsive compilation, the documented semantics and focus/keyboard behavior of interactive primitives, and the allowlist boundary used by `MarkdownRenderer`. UI visibility never grants route access; enforce authorization on the server. The package makes no default-framework or cross-language parity claim. Before v1.0.0, minor `0.x` releases may contain documented breaking changes. --- Page: Web Source: https://putnami.dev/doc-markdown?path=%2Fdocs%2Fframeworks%2Ftypescript%2Fweb # Web Use `@putnami/web` for server-side rendering, file-based routing, server-owned data loading and mutation, explicit static rendering, bounded islands, and client hydration. It uses React 19 and streams the response: the head and the shell leave as soon as the shell is ready, and each Suspense boundary follows when its data resolves. ## Getting started ### Installation ```bash putnami deps add @putnami/web ``` ### Entry point ```ts import { application, http, staticFiles } from '@putnami/application'; import { react } from '@putnami/web'; export const app = () => application() .use(http({ port: 3000 })) .use(react()) .use(staticFiles({ publicFolder: 'public' })); ``` ### Configuration options ```ts react({ scanFolder: 'app', // Folder to scan for routes (default: 'app') autoScan: true, // Auto-discover routes (default: true) publicFolder: 'public', // Static assets folder (default: 'public') ssrTimeout: 3000, // SSR render timeout in ms (default: 3000) crawlerUserAgents: '…', // User agents that wait for every Suspense boundary (default: crawlers and link previews) minify: true, // Minify client bundles (default: true) sourcemap: 'external', // 'none' | 'inline' | 'external' (default: 'external') splitting: false, // Code splitting (default: false) isDevelopment: false, // Development mode (default: NODE_ENV check) }) ``` React routes enable security headers and action CSRF validation by default. Opting out is explicit; see [Security defaults](#security-defaults). ## Browser and server boundary The package publishes separate default/server and browser entrypoints, built as separate dependency graphs. The server graph owns route discovery, SSR, loaders, actions, static generation, dependency injection, and request middleware. The browser graph owns hydration, navigation, form enhancement, document updates, and islands. A browser bundle cannot acquire server authority by importing a shared route module. `page()` and `layout()` exist in both graphs so the same component source can be loaded on either side. In the browser, server middleware methods are inert and warn once. Declarative `.secure()` metadata can hide unavailable UI, but it is only a hint: the generated page, loader, and action endpoints always enforce the real middleware on the server. Function guards cannot be serialized and default-deny in client UI gating. ### Module path inheritance When used inside a module with `.path()`, the React plugin automatically inherits the module path as its basename. All routes are served under the module path prefix, and client-side navigation uses it as the router basename: ```ts import { module } from '@putnami/application'; const dashboard = module('dashboard') .path('/dashboard') .use(react()); // Pages served at /dashboard, /dashboard/settings, etc. const app = application() .use(http({ port: 3000 })) .use(dashboard); ``` ## File-based routing Routes are automatically discovered from your `src/app/` folder. Each folder becomes a route segment, and special files define the route behavior. ### Route files - **page.tsx** - React component for the route - **loader.ts** - Server-side data fetching - **action.ts** - Form submission handler - **layout.tsx** - Shared layout wrapper - **error.tsx** - Error boundary component ### Example structure ```text src/app/ page.tsx # / loader.ts # Data for / layout.tsx # Root layout about/ page.tsx # /about users/ page.tsx # /users loader.ts # Data for /users [id]/ page.tsx # /users/:id loader.ts # Data for /users/:id blog/ page.tsx # /blog [...slug]/ page.tsx # /blog/* (catch-all) ``` ### Dynamic routes Use brackets for dynamic segments: - `[id]/` - Single dynamic segment (`/users/123`) - `[...slug]/` - Catch-all segment (`/blog/2024/my-post`) ## Pages and loaders ### Basic page ```tsx // src/app/page.tsx export default function HomePage() { return (

Welcome to my app

); } ``` ### Page with loader ```ts // src/app/users/loader.ts import { loader } from '@putnami/web'; export default loader(async () => { const users = await fetchUsers(); return { users }; }); ``` ```tsx // src/app/users/page.tsx import { useLoaderData } from '@putnami/web'; interface LoaderData { users: { id: string; name: string }[]; } export default function UsersPage() { const { users } = useLoaderData(); return (

Users

    {users.map(user => (
  • {user.name}
  • ))}
); } ``` ### Dynamic route loader ```ts // src/app/users/[id]/loader.ts import { loader } from '@putnami/web'; import { NotFoundException } from '@putnami/runtime'; export default loader(async (ctx) => { const { id } = ctx.params; const user = await findUser(id); if (!user) { throw new NotFoundException('User not found'); } return { user }; }); ``` The page answers `404` with the nearest not-found page, on a full page load and on a client navigation alike. Any `HttpException` a loader throws answers with its own status. ### Loader with query parameters ```ts // src/app/search/loader.ts import { loader } from '@putnami/web'; import { Int, Optional } from '@putnami/runtime'; export default loader() .query({ q: Optional(String), page: Optional(Int) }) .handle(async (ctx) => { const params = ctx.queryParams(); const query = params.q ?? ''; const page = params.page ?? 1; const results = await search(query, page); return { results, query, page }; }); ``` Loaders always execute on the server. Their return value is script-context escaped before it enters hydration data; it must still be serializable. Declared params/query schemas validate before the handler runs, and `.inject()` resolves services from the active request scope. ## Layouts Layouts wrap pages and persist across navigation. Use them for shared UI like headers, sidebars, and footers. ### Root layout ```tsx // src/app/layout.tsx import { Outlet } from '@putnami/web'; export default function RootLayout() { return (
My App
Copyright 2025
); } ``` Security declared by a layout propagates to descendant SSR pages, loader JSON endpoints, action endpoints, and not-found boundaries, including lazy routes. It does not affect sibling routes outside that layout. ## Rendering modes Rendering mode is explicit and is never inferred from component source. ```tsx import { island, page } from '@putnami/web'; // SSG: complete HTML, no full-page hydration bundle. export default page().static().render(AboutPage); // ISR: revalidate by time or cache tag. export const News = page().static({ revalidate: 60 }).render(NewsPage); export const Post = page() .static({ revalidate: { tags: ['posts'] }, paths: listPostParams }) .render(PostPage); // A component declared in Counter.island.tsx hydrates independently. export const CounterIsland = island().load('visible').render(Counter); ``` A colocated `loader().static()` runs at build time and bakes its data into the HTML. It receives a request-free context: reading headers, cookies, session, or other request data raises `StaticRenderViolation`. Dynamic static routes require a `paths` option that returns finite values, and generated splats cannot escape or alias the static output root. A dynamic route without finite paths stays live. A static loader can read the build version with `getBuildInfo()?.version`. When a pre-rendered page shows that version, the build records it beside the static HTML, and the server replaces it with its own version when it serves the page at its route. A page restored from the build cache, or served from an image deployed under another release id, shows the running version. A bare release tag such as `1.0.0` is not replaced, because page content can contain the same text. Other build fields, such as `sha` or `buildTime`, keep their build-time values. Island props are escaped for their script embedding. Load strategies are `load`, `idle`, `visible`, and `media`; if the requested observer is unavailable, hydration falls back to immediate rather than leaving a dead control. Every build emits `.gen/putnami-web-manifest.json`, sorted deterministically by route. It records render mode, hydration, static DI proof, and per-route client JavaScript bytes. `putnami-web-manifest-diff` makes changes reviewable and `putnami-web-manifest-budget` enforces the committed byte budget. ### Nested layouts ```tsx // src/app/dashboard/layout.tsx import { Outlet } from '@putnami/web'; export default function DashboardLayout() { return (
); } ``` ### Layout with loader ```ts // src/app/dashboard/layout.loader.ts import { useUser, HttpResponse } from '@putnami/application'; import { loader } from '@putnami/web'; export default loader(async () => { const user = await useUser(); if (!user) { return HttpResponse.redirect('/login'); } return { user }; }); ``` ### Sharing data with outlet context ```tsx // src/app/dashboard/layout.tsx import { Outlet, useLoaderData } from '@putnami/web'; export default function DashboardLayout() { const { user } = useLoaderData<{ user: User }>(); return (
Welcome, {user.name}
); } ``` ```tsx // src/app/dashboard/settings/page.tsx import { useOutletContext } from '@putnami/web'; export default function SettingsPage() { const { user } = useOutletContext<{ user: User }>(); return
Settings for {user.email}
; } ``` ## Document and SEO Control the document head with built-in components. ### Setting page title and meta ```tsx import { Title, Meta, Lang, Favicon } from '@putnami/web'; export default function AboutPage() { return ( <> About Us - My App

About Us

Welcome to our company...

); } ``` ### Dynamic titles from loader data ```tsx import { Title, useLoaderData } from '@putnami/web'; export default function UserPage() { const { user } = useLoaderData<{ user: { name: string } }>(); return ( <> {user.name} - My App

{user.name}

); } ``` ### Adding scripts and styles ```tsx import { Script, Style } from '@putnami/web'; export default function Page() { return ( <>