Compare commits

..
Author SHA1 Message Date
Julius Marminge f8b6e5b330 deeper in atom 2026-04-01 00:23:27 -07:00
Julius Marminge 744f74442a Format web tsconfig to match JSON style
- Remove trailing commas from `apps/web/tsconfig.json`
- Keep TypeScript config consistent with project formatting rules
2026-04-01 00:22:03 -07:00
Julius Marminge 23467b7b1f move test helper 2026-04-01 00:22:03 -07:00
Julius Marminge 022d3d2f3e rm reference 2026-04-01 00:19:57 -07:00
Julius Marminge 3bb72fe119 add reference 2026-04-01 00:16:44 -07:00
4859 changed files with 47009 additions and 1212222 deletions

No files matched your search

-1
View File
@@ -1 +0,0 @@
plans/
-29
View File
@@ -1,29 +0,0 @@
{
"name": "T3 Code Dev",
"image": "debian:bookworm",
"features": {
"ghcr.io/devcontainers/features/git:1": {},
"ghcr.io/devcontainers-extra/features/bun:1": {
"version": "1.3.11"
},
"ghcr.io/devcontainers/features/node:1": {
"version": "24.13.1"
},
"ghcr.io/devcontainers/features/python:1": {
"version": "3.10",
"installTools": false
}
},
"overrideFeatureInstallOrder": [
"ghcr.io/devcontainers/features/git",
"ghcr.io/devcontainers-extra/features/bun"
],
"postCreateCommand": {
"bun-install": "bun install --backend=copyfile --frozen-lockfile"
},
"customizations": {
"vscode": {
"extensions": ["oxc.oxc-vscode"]
}
}
}
-382
View File
@@ -1,382 +0,0 @@
# Remote Architecture
This document describes the target architecture for first-class remote environments in T3 Code.
It is intentionally architecture-first. It does not define a complete implementation plan or user-facing rollout checklist. The goal is to establish the core model so remote support can be added without another broad rewrite.
## Goals
- Treat remote environments as first-class product primitives, not special cases.
- Support multiple ways to reach the same environment.
- Keep the T3 server as the execution boundary.
- Let desktop, mobile, and web all share the same conceptual model.
- Avoid introducing a local control plane unless product pressure proves it is necessary.
## Non-goals
- Replacing the existing WebSocket server boundary with a custom transport protocol.
- Making SSH the only remote story.
- Syncing provider auth across machines.
- Shipping every access method in the first iteration.
## High-level architecture
T3 already has a clean runtime boundary: the client talks to a T3 server over HTTP/WebSocket, and the server owns orchestration, providers, terminals, git, and filesystem operations.
Remote support should preserve that boundary.
```text
┌──────────────────────────────────────────────┐
│ Client (desktop / mobile / web) │
│ │
│ - known environments │
│ - connection manager │
│ - environment-aware routing │
└───────────────┬──────────────────────────────┘
│
│ resolves one access endpoint
│
┌───────────────▼──────────────────────────────┐
│ Access method │
│ │
│ - direct ws / wss │
│ - tunneled ws / wss │
│ - desktop-managed ssh bootstrap + forward │
└───────────────┬──────────────────────────────┘
│
│ connects to one T3 server
│
┌───────────────▼──────────────────────────────┐
│ Execution environment = one T3 server │
│ │
│ - environment identity │
│ - provider state │
│ - projects / threads / terminals │
│ - git / filesystem / process runtime │
└──────────────────────────────────────────────┘
```
The important decision is that remoteness is expressed at the environment connection layer, not by splitting the T3 runtime itself.
## Domain model
### ExecutionEnvironment
An `ExecutionEnvironment` is one running T3 server instance.
It is the unit that owns:
- provider availability and auth state
- model availability
- projects and threads
- terminal processes
- filesystem access
- git operations
- server settings
It is identified by a stable `environmentId`.
This is the shared cross-client primitive. Desktop, mobile, and web should all reason about the same concept here.
### KnownEnvironment
A `KnownEnvironment` is a client-side saved entry for an environment the client knows how to reach.
It is not server-authored. It is local to a device or client profile.
Examples:
- a saved LAN URL
- a saved public `wss://` endpoint
- a desktop-managed SSH host entry
- a saved tunneled environment
A known environment may or may not know the target `environmentId` before first successful connect.
In the hosted web app, known environments are browser-local. A hosted pairing URL can create the saved entry, but it does not give the hosted app a server-side control plane or a copy of the session state.
### AccessEndpoint
An `AccessEndpoint` is one concrete way to reach a known environment.
This is the key abstraction that keeps SSH from taking over the model.
A single environment may have many endpoints:
- `wss://t3.example.com`
- `ws://10.0.0.25:3773`
- a tunneled relay URL
- a desktop-managed SSH tunnel that resolves to a local forwarded WebSocket URL
The environment stays the same. Only the access path changes.
### AdvertisedEndpoint
An `AdvertisedEndpoint` is a server or desktop-authored candidate endpoint for an environment. It is how the backend tells the client which URLs may be useful for pairing and reconnecting.
`AdvertisedEndpoint` is deliberately narrower than the full access model:
- it describes a concrete HTTP and WebSocket base URL pair
- it can mark the endpoint as default, available, or unavailable
- it includes reachability hints such as loopback, LAN, private, public, or tunnel
- it includes compatibility hints such as whether the endpoint can be used from the hosted HTTPS app
Clients should treat advertised endpoints as hints, not as proof that a route works from the current device. The final connection attempt still decides whether the endpoint is reachable.
The UI presents one default advertised endpoint in the network-access summary and keeps the rest behind an expandable advanced list. The default controls pairing QR codes and primary copy actions. Users can override it, but that override is a UI preference, not backend configuration.
Persist the override by stable endpoint kind rather than raw URL whenever possible. For example, a LAN endpoint should be stored as the desktop LAN endpoint preference, not as `192.168.x.y`, because the address can change when the user switches networks. Provider endpoints should use provider-specific stable keys such as Tailscale IP or Tailscale MagicDNS HTTPS. Custom endpoints may fall back to their concrete identity.
When no user default is saved, endpoint selection should prefer:
1. endpoints compatible with the hosted HTTPS app
2. explicitly default endpoints
3. non-loopback endpoints
4. loopback endpoints only for same-machine clients
This keeps endpoint discovery centralized without making any one provider, such as Tailscale or a future tunnel service, part of the core environment model.
### Endpoint providers
Endpoint providers are add-ons that contribute advertised endpoints for the current environment.
The provider boundary is intentionally outside the core environment model:
- core owns `ExecutionEnvironment`, saved environments, pairing, and connection lifecycle
- providers discover or synthesize endpoints
- providers return normalized `AdvertisedEndpoint` records
- the UI and pairing logic select from those records without knowing provider-specific commands
The first provider is Tailscale. It can discover Tailnet IP and MagicDNS addresses from the local machine and publish them as additional endpoint candidates. Future providers, such as a hosted tunnel service, should plug into the same shape rather than adding a separate remote environment path.
Provider-specific confidence should remain a hint. A Tailscale endpoint still needs a successful browser or desktop connection before the client treats it as connected.
### Hosted pairing request
A hosted pairing request is a bootstrap URL for the static web app, not a transport.
Example:
```text
https://app.t3.codes/pair?host=https://backend.example.com:3773#token=PAIRCODE
```
The hosted app reads the `host` parameter and pairing token, exchanges the token directly with that backend, then saves the resulting environment record in browser local storage.
Important constraints:
- the hosted app does not proxy HTTP or WebSocket traffic
- the backend must still be reachable directly from the browser
- HTTPS pages can only connect to HTTPS/WSS backends
- HTTP LAN endpoints should keep using direct desktop or CLI pairing URLs
- the token belongs in the URL hash so it is not sent to the hosted app origin
### RepositoryIdentity
`RepositoryIdentity` remains a best-effort logical repo grouping mechanism across environments.
It is not used for routing. It is only used for UI grouping and correlation between local and remote clones of the same repository.
### Workspace / Project
The current `Project` model remains environment-local.
That means:
- a local clone and a remote clone are different projects
- they may share a `RepositoryIdentity`
- threads still bind to one project in one environment
## Access methods
Access methods answer one question:
How does the client speak WebSocket to a T3 server?
They do not answer:
- how the server got started
- who manages the server process
- whether the environment is local or remote
### 1. Direct WebSocket access
Examples:
- `ws://10.0.0.15:3773`
- `wss://t3.example.com`
This is the base model and should be the first-class default.
Benefits:
- works for desktop, mobile, and web
- no client-specific process management required
- best fit for hosted or self-managed remote T3 deployments
Browser security rules are part of this access method. A hosted HTTPS web client can connect to `wss://` backends, but it cannot connect to plain `ws://` or `http://` LAN backends because that would be mixed content.
### 2. Tunneled WebSocket access
Examples:
- public relay URLs
- private network relay URLs
- local tunnel products such as pipenet
This is still direct WebSocket access from the client's perspective. The difference is that the route is mediated by a tunnel or relay.
For T3, tunnels are best modeled as another `AccessEndpoint`, not as a different kind of environment.
This is especially useful when:
- the host is behind NAT
- inbound ports are unavailable
- mobile must reach a desktop-hosted environment
- a machine should be reachable without exposing raw LAN or public ports
Tailscale-backed access sits here architecturally even though the current implementation is endpoint discovery rather than a T3-managed tunnel. It contributes private-network endpoints and lets the existing HTTP/WebSocket client path do the actual connection.
### 3. Desktop-managed SSH access
SSH is an access and launch helper, not a separate environment type.
The desktop main process can use SSH to:
- reach a machine
- probe it
- launch or reuse a remote T3 server
- establish a local port forward
After that, the renderer should still connect using an ordinary WebSocket URL against the forwarded local port.
This keeps the renderer transport model consistent with every other access method.
The desktop main process owns the SSH bridge because it can spawn local SSH processes, manage askpass prompts, write temporary launch scripts, and clean up forwards. The renderer receives a saved environment record and connects through the forwarded URL; it should not need SSH-specific RPC paths for normal environment traffic.
## Launch methods
Launch methods answer a different question:
How does a T3 server come to exist on the target machine?
Launch and access should stay separate in the design.
### 1. Pre-existing server
The simplest launch method is no launch at all.
The user or operator already runs T3 on the target machine, and the client connects through a direct or tunneled WebSocket endpoint.
This should be the first remote mode shipped because it validates the environment model with minimal extra machinery.
### 2. Desktop-managed remote launch over SSH
This is the main place where Zed is a useful reference.
Useful ideas to borrow from Zed:
- remote probing
- platform detection
- session directories with pid/log metadata
- reconnect-friendly launcher behavior
- desktop-owned connection UX
What should be different in T3:
- no custom stdio/socket proxy protocol between renderer and remote runtime
- no attempt to make the remote runtime look like an editor transport
- keep the final client-to-server connection as WebSocket
The recommended T3 flow is:
1. Desktop connects over SSH.
2. Desktop probes the remote machine and verifies T3 availability.
3. Desktop launches or reuses a remote T3 server.
4. Desktop establishes local port forwarding.
5. Renderer connects to the forwarded WebSocket endpoint as a normal environment.
The saved environment should remember that it was created by desktop SSH launch only for reconnect and lifecycle UX. That metadata should not change the server protocol or the environment identity model.
Failure handling should be explicit:
- SSH authentication failure should surface before any environment is saved
- remote launch failure should include remote logs or the launcher command output when available
- forwarded-port failure should leave the saved environment disconnected rather than falling back to an unrelated endpoint
- reconnect should attempt to restore the SSH bridge before reconnecting the normal WebSocket client
### 3. Client-managed local publish
This is the inverse of remote launch: a local T3 server is already running, and the client publishes it through a tunnel.
This is useful for:
- exposing a desktop-hosted environment to mobile
- temporary remote access without changing router or firewall settings
This is still a launch concern, not a new environment kind.
## Why access and launch must stay separate
These concerns are easy to conflate, but separating them prevents architectural drift.
Examples:
- A manually hosted T3 server might be reached through direct `wss`.
- The same server might also be reachable through a tunnel.
- An SSH-managed server might be launched over SSH but then reached through forwarded WebSocket.
- A local desktop server might be published through a tunnel for mobile.
In all of those cases, the `ExecutionEnvironment` is the same kind of thing.
Only the launch and access paths differ.
## Security model
Remote support must assume that some environments will be reachable over untrusted networks.
That means:
- remote-capable environments should require explicit authentication
- tunnel exposure should not rely on obscurity
- client-saved endpoints should carry enough auth metadata to reconnect safely
T3 already supports a WebSocket auth token on the server. That should become a first-class part of environment access rather than remaining an incidental query parameter convention.
For publicly reachable environments, authenticated access should be treated as required.
Hosted pairing should be treated as a client-side convenience only. The hosted app must not receive pairing tokens through query parameters, must not store pairing state server-side, and must not imply that an HTTP backend is safe or reachable from an HTTPS browser context.
## Relationship to Zed
Zed is a useful reference implementation for managed remote launch and reconnect behavior.
The relevant lessons are:
- remote bootstrap should be explicit
- reconnect should be first-class
- connection UX belongs in the client shell
- runtime ownership should stay clearly on the remote host
The important mismatch is transport shape.
Zed needs a custom proxy/server protocol because its remote boundary sits below the editor and project runtime.
T3 should not copy that part.
T3 already has the right runtime boundary:
- one T3 server per environment
- ordinary HTTP/WebSocket between client and environment
So T3 should borrow Zed's launch discipline, not its transport protocol.
## Recommended rollout
1. First-class known environments and access endpoints.
2. Direct `ws` / `wss` remote environments.
3. Authenticated tunnel-backed environments.
4. Desktop-managed SSH launch and forwarding.
5. Multi-environment UI improvements after the base runtime path is proven.
This ordering keeps the architecture network-first and transport-agnostic while still leaving room for richer managed remote flows.
-3
View File
@@ -30,6 +30,3 @@ github:Yash-Singh1
github:eggfriedrice24
github:Ymit24
github:shivamhwp
github:jappyjan
github:justsomelegs
github:UtkarshUsername
+52 -104
View File
@@ -7,140 +7,88 @@ on:
- main
jobs:
check:
name: Check
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
quality:
name: Format, Lint, Typecheck, Test, Browser Test, Build
runs-on: blacksmith-4vcpu-ubuntu-2404
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: package.json
cache: true
run-install: true
- name: Ensure Electron runtime is installed
run: vp run --filter @t3tools/desktop ensure:electron
- name: Check
run: vp check
- name: Typecheck
run: vpr typecheck
- name: Build desktop pipeline
run: vp run build:desktop
- name: Verify preload bundle output
run: |
test -f apps/desktop/dist-electron/preload.cjs
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.cjs
test:
name: Test
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
- name: Cache Bun and Turbo
uses: actions/cache@v5
with:
node-version-file: package.json
cache: true
run-install: true
- name: Ensure Electron runtime is installed
run: vp run --filter @t3tools/desktop ensure:electron
- name: Test
run: vp run test
test_browser:
name: Test Browser
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: true
path: |
~/.bun/install/cache
.turbo
key: ${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-${{ hashFiles('turbo.json') }}
restore-keys: |
${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-
- name: Cache Playwright browsers
uses: actions/cache@v5
with:
path: ~/.cache/ms-playwright
key: ${{ runner.os }}-playwright-${{ hashFiles('pnpm-lock.yaml') }}
key: ${{ runner.os }}-playwright-${{ hashFiles('bun.lock') }}
restore-keys: |
${{ runner.os }}-playwright-
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Format
run: bun run fmt:check
- name: Lint
run: bun run lint
- name: Typecheck
run: bun run typecheck
- name: Test
run: bun run test
- name: Install browser test runtime
run: vp run --filter @t3tools/web test:browser:install
- name: Browser test / Chat view
working-directory: apps/web
run: vp test run --mode browser --browser=chromium src/components/ChatView.browser.tsx
- name: Browser test / Chat markdown
working-directory: apps/web
run: vp test run --mode browser --browser=chromium src/components/ChatMarkdown.browser.tsx
- name: Browser test / Components
working-directory: apps/web
run: |
vp test run --mode browser --browser=chromium \
src/components/GitActionsControl.browser.tsx \
src/components/KeybindingsToast.browser.tsx \
src/components/ThreadTerminalDrawer.browser.tsx \
src/components/chat/MessagesTimeline.browser.tsx \
src/components/chat/ProviderModelPicker.browser.tsx \
src/components/chat/CompactComposerControlsMenu.browser.tsx \
src/components/settings/SettingsPanels.browser.tsx
cd apps/web
bunx playwright install --with-deps chromium
mobile_native_static_analysis:
name: Mobile Native Static Analysis
runs-on: blacksmith-12vcpu-macos-26
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Browser test
run: bun run --cwd apps/web test:browser
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: true
- name: Build desktop pipeline
run: bun run build:desktop
- name: Install mobile native static analysis tools
run: brew bundle install --file apps/mobile/Brewfile
- name: Lint mobile native sources
run: vp run lint:mobile
- name: Verify preload bundle output
run: |
test -f apps/desktop/dist-electron/preload.js
grep -nE "desktopBridge|getWsUrl|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
release_smoke:
name: Release Smoke
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: package.json
cache: true
run-install: true
- name: Exercise release-only workflow steps
run: node scripts/release-smoke.ts
-78
View File
@@ -1,78 +0,0 @@
name: Mobile EAS Preview
on:
pull_request:
jobs:
preview:
name: EAS Preview
runs-on: blacksmith-8vcpu-ubuntu-2404
permissions:
contents: read
pull-requests: write
env:
APP_VARIANT: preview
NODE_OPTIONS: --max-old-space-size=8192
MOBILE_VERSION_POLICY: fingerprint
steps:
- id: expo-token
name: Check for EXPO_TOKEN
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: |
if [ -n "$EXPO_TOKEN" ]; then
echo "present=true" >> "$GITHUB_OUTPUT"
else
echo "present=false" >> "$GITHUB_OUTPUT"
echo "EXPO_TOKEN is not available; skipping EAS preview."
fi
- name: Checkout
if: steps.expo-token.outputs.present == 'true'
uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Setup Vite+
if: steps.expo-token.outputs.present == 'true'
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: true
- name: Expose pnpm
if: steps.expo-token.outputs.present == 'true'
run: |
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
"$vp_pnpm_bin/pnpm" --version
- name: Setup EAS
if: steps.expo-token.outputs.present == 'true'
uses: expo/expo-github-action@v8
with:
eas-version: latest
token: ${{ secrets.EXPO_TOKEN }}
packager: pnpm
- name: Pull preview environment variables
if: steps.expo-token.outputs.present == 'true'
working-directory: apps/mobile
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: eas env:pull preview --non-interactive
- name: Deploy with fingerprint check
if: steps.expo-token.outputs.present == 'true'
uses: expo/expo-github-action/continuous-deploy-fingerprint@main
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
with:
profile: preview:dev
branch: pr-${{ github.event.pull_request.number }}
platform: all
environment: preview
working-directory: apps/mobile
github-token: ${{ secrets.GITHUB_TOKEN }}
-3
View File
@@ -124,9 +124,6 @@ jobs:
group: pr-size-${{ github.event.pull_request.number }}
cancel-in-progress: true
steps:
# This pull_request_target job may fetch untrusted PR commits only as passive
# git data. Do not add dependency installs, build/test scripts, or cache
# actions here; use pull_request plus workflow_run for that pattern instead.
- name: Checkout base repository
uses: actions/checkout@v4
with:
+95 -511
View File
@@ -1,206 +1,110 @@
name: Release
name: Release Desktop
on:
push:
tags:
- "v*.*.*"
- "!v*-nightly.*"
schedule:
- cron: "0 */3 * * *"
workflow_dispatch:
inputs:
channel:
description: "Release channel"
required: false
default: stable
type: choice
options:
- stable
- nightly
version:
description: "Release version (for example 1.2.3 or v1.2.3)"
required: false
required: true
type: string
permissions:
contents: read
id-token: none
contents: write
id-token: write
jobs:
check_changes:
name: Check for changes since last nightly
if: github.event_name == 'schedule'
runs-on: blacksmith-8vcpu-ubuntu-2404
outputs:
has_changes: ${{ steps.check.outputs.has_changes }}
steps:
- name: Checkout
uses: actions/checkout@v6
with:
fetch-depth: 0
- id: check
name: Compare HEAD to last nightly tag
run: |
last_nightly_tag=$(git tag --list 'v*-nightly.*' 'nightly-v*' --sort=-creatordate | head -n 1)
if [[ -z "$last_nightly_tag" ]]; then
echo "No previous nightly tag found. Proceeding with release."
echo "has_changes=true" >> "$GITHUB_OUTPUT"
exit 0
fi
last_nightly_sha=$(git rev-parse "$last_nightly_tag^{commit}")
head_sha=$(git rev-parse HEAD)
if [[ "$last_nightly_sha" == "$head_sha" ]]; then
echo "No changes on main since last nightly release ($last_nightly_tag). Skipping."
echo "has_changes=false" >> "$GITHUB_OUTPUT"
else
echo "Changes detected on main since $last_nightly_tag ($last_nightly_sha → $head_sha). Proceeding."
echo "has_changes=true" >> "$GITHUB_OUTPUT"
fi
preflight:
name: Preflight
needs: [check_changes]
if: |
!failure() && !cancelled() &&
(github.event_name != 'schedule' || needs.check_changes.outputs.has_changes == 'true')
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
runs-on: ubuntu-24.04
outputs:
release_channel: ${{ steps.release_meta.outputs.release_channel }}
version: ${{ steps.release_meta.outputs.version }}
tag: ${{ steps.release_meta.outputs.tag }}
release_name: ${{ steps.release_meta.outputs.name }}
short_sha: ${{ steps.release_meta.outputs.short_sha }}
previous_tag: ${{ steps.previous_tag.outputs.previous_tag }}
cli_dist_tag: ${{ steps.release_meta.outputs.cli_dist_tag }}
is_prerelease: ${{ steps.release_meta.outputs.is_prerelease }}
make_latest: ${{ steps.release_meta.outputs.make_latest }}
ref: ${{ github.sha }}
steps:
- name: Checkout
uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: true
- name: Ensure Electron runtime is installed
run: vp run --filter @t3tools/desktop ensure:electron
- id: release_meta
name: Resolve release version
shell: bash
env:
DISPATCH_CHANNEL: ${{ github.event.inputs.channel }}
DISPATCH_VERSION: ${{ github.event.inputs.version }}
NIGHTLY_DATE: ${{ github.run_started_at }}
NIGHTLY_SHA: ${{ github.sha }}
NIGHTLY_RUN_NUMBER: ${{ github.run_number }}
run: |
if [[ "${GITHUB_EVENT_NAME}" == "schedule" || ( "${GITHUB_EVENT_NAME}" == "workflow_dispatch" && "${DISPATCH_CHANNEL:-stable}" == "nightly" ) ]]; then
nightly_date="$(date -u -d "$NIGHTLY_DATE" +%Y%m%d)"
node scripts/resolve-nightly-release.ts \
--date "$nightly_date" \
--run-number "$NIGHTLY_RUN_NUMBER" \
--sha "$NIGHTLY_SHA" \
--github-output
echo "release_channel=nightly" >> "$GITHUB_OUTPUT"
echo "cli_dist_tag=nightly" >> "$GITHUB_OUTPUT"
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
echo "make_latest=false" >> "$GITHUB_OUTPUT"
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
raw="${{ github.event.inputs.version }}"
else
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
raw="${DISPATCH_VERSION}"
if [[ -z "$raw" ]]; then
echo "workflow_dispatch stable releases require the version input." >&2
exit 1
fi
else
raw="${GITHUB_REF_NAME}"
fi
version="${raw#v}"
if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]]; then
echo "Invalid release version: $raw" >&2
exit 1
fi
echo "release_channel=stable" >> "$GITHUB_OUTPUT"
echo "version=$version" >> "$GITHUB_OUTPUT"
echo "tag=v$version" >> "$GITHUB_OUTPUT"
echo "name=T3 Code v$version" >> "$GITHUB_OUTPUT"
echo "cli_dist_tag=latest" >> "$GITHUB_OUTPUT"
if [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "is_prerelease=false" >> "$GITHUB_OUTPUT"
echo "make_latest=true" >> "$GITHUB_OUTPUT"
else
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
echo "make_latest=false" >> "$GITHUB_OUTPUT"
fi
raw="${GITHUB_REF_NAME}"
fi
- name: Check
run: vp check
version="${raw#v}"
if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]]; then
echo "Invalid release version: $raw" >&2
exit 1
fi
echo "version=$version" >> "$GITHUB_OUTPUT"
echo "tag=v$version" >> "$GITHUB_OUTPUT"
if [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "is_prerelease=false" >> "$GITHUB_OUTPUT"
echo "make_latest=true" >> "$GITHUB_OUTPUT"
else
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
echo "make_latest=false" >> "$GITHUB_OUTPUT"
fi
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Lint
run: bun run lint
- name: Typecheck
run: vp run typecheck
run: bun run typecheck
- name: Test
run: vp run test
- id: previous_tag
name: Resolve previous release tag
run: |
node scripts/resolve-previous-release-tag.ts \
--channel "${{ steps.release_meta.outputs.release_channel }}" \
--current-tag "${{ steps.release_meta.outputs.tag }}" \
--github-output
run: bun run test
build:
name: Build ${{ matrix.label }}
needs: preflight
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' }}
runs-on: ${{ matrix.runner }}
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
include:
- label: macOS arm64
runner: blacksmith-12vcpu-macos-26
runner: macos-14
platform: mac
target: dmg
arch: arm64
- label: macOS x64
runner: blacksmith-12vcpu-macos-26
runner: macos-15-intel
platform: mac
target: dmg
arch: x64
- label: Linux x64
runner: blacksmith-32vcpu-ubuntu-2404
runner: ubuntu-24.04
platform: linux
target: AppImage
arch: x64
- label: Windows x64
runner: blacksmith-32vcpu-windows-2025
runner: windows-2022
platform: win
target: nsis
arch: x64
# - label: Windows arm64
# runner: windows-11-arm
# platform: win
# target: nsis
# arch: arm64
steps:
- name: Checkout
uses: actions/checkout@v6
@@ -208,110 +112,22 @@ jobs:
ref: ${{ needs.preflight.outputs.ref }}
fetch-depth: 0
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: package.json
cache: true
run-install: true
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
- name: Install Spectre-mitigated MSVC libs
if: matrix.platform == 'win'
shell: pwsh
run: |
$vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
$installPath = & $vswhere -products * -latest -property installationPath
$setupExe = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\setup.exe"
$proc = Start-Process -FilePath $setupExe `
-ArgumentList "modify", "--installPath", "`"$installPath`"", "--add", `
"Microsoft.VisualStudio.Component.VC.Tools.x86.x64.Spectre", "--quiet", "--norestart" `
-Wait -PassThru -NoNewWindow
if ($null -eq $proc -or $proc.ExitCode -ne 0) {
$code = if ($null -ne $proc) { $proc.ExitCode } else { 1 }
Write-Error "Visual Studio Installer failed with exit code $code"
exit $code
}
- name: Install ImageMagick
if: matrix.platform == 'linux'
shell: bash
run: |
if ! command -v magick >/dev/null 2>&1 && ! command -v convert >/dev/null 2>&1; then
sudo apt-get update
sudo apt-get install -y imagemagick
fi
if command -v magick >/dev/null 2>&1; then
magick -version
else
convert -version
fi
- name: Prepare Azure Trusted Signing
if: matrix.platform == 'win'
shell: pwsh
env:
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_TRUSTED_SIGNING_ENDPOINT: ${{ secrets.AZURE_TRUSTED_SIGNING_ENDPOINT }}
AZURE_TRUSTED_SIGNING_ACCOUNT_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }}
AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME }}
AZURE_TRUSTED_SIGNING_PUBLISHER_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_PUBLISHER_NAME }}
run: |
$ErrorActionPreference = "Stop"
$requiredSecrets = @(
$env:AZURE_TENANT_ID,
$env:AZURE_CLIENT_ID,
$env:AZURE_CLIENT_SECRET,
$env:AZURE_TRUSTED_SIGNING_ENDPOINT,
$env:AZURE_TRUSTED_SIGNING_ACCOUNT_NAME,
$env:AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME,
$env:AZURE_TRUSTED_SIGNING_PUBLISHER_NAME
)
if ($requiredSecrets | Where-Object { [string]::IsNullOrWhiteSpace($_) }) {
Write-Host "Azure Trusted Signing disabled; skipping TrustedSigning module preparation."
exit 0
}
try {
Install-PackageProvider `
-Name NuGet `
-MinimumVersion 2.8.5.201 `
-Force `
-Scope CurrentUser `
-ErrorAction Stop
} catch {
Write-Warning "Could not bootstrap NuGet package provider. Continuing because the runner may already have a usable provider. $($_.Exception.Message)"
}
Install-Module `
-Name TrustedSigning `
-MinimumVersion 0.5.0 `
-Force `
-AllowClobber `
-Repository PSGallery `
-Scope CurrentUser `
-ErrorAction Stop
Import-Module TrustedSigning -MinimumVersion 0.5.0 -Force
Get-Command Invoke-TrustedSigning -ErrorAction Stop
$moduleRoots = @(
[System.IO.Path]::Combine([Environment]::GetFolderPath("MyDocuments"), "PowerShell", "Modules"),
[System.IO.Path]::Combine([Environment]::GetFolderPath("MyDocuments"), "WindowsPowerShell", "Modules"),
[System.IO.Path]::Combine($env:ProgramFiles, "PowerShell", "Modules"),
[System.IO.Path]::Combine($env:ProgramFiles, "WindowsPowerShell", "Modules")
)
$modulePathEntries = @($moduleRoots + ($env:PSModulePath -split ";")) |
Where-Object { $_ -and (Test-Path $_) } |
Select-Object -Unique
"PSModulePath=$($modulePathEntries -join ';')" >> $env:GITHUB_ENV
- name: Build desktop artifact
shell: bash
env:
@@ -373,7 +189,7 @@ jobs:
echo "Signing disabled for ${{ matrix.platform }}."
fi
vp run dist:desktop:artifact "${args[@]}"
bun run dist:desktop:artifact -- "${args[@]}"
- name: Collect release assets
shell: bash
@@ -388,31 +204,18 @@ jobs:
"release/*.AppImage" \
"release/*.exe" \
"release/*.blockmap" \
"release/*.yml"; do
"release/latest*.yml"; do
for file in $pattern; do
cp "$file" release-publish/
done
done
if [[ "${{ matrix.platform }}" == "mac" && "${{ matrix.arch }}" != "arm64" ]]; then
shopt -s nullglob
for manifest in release-publish/*-mac.yml; do
mv "$manifest" "${manifest%.yml}-${{ matrix.arch }}.yml"
done
if [[ -f release-publish/latest-mac.yml ]]; then
mv release-publish/latest-mac.yml "release-publish/latest-mac-${{ matrix.arch }}.yml"
fi
fi
# Enable if Windows arm64 builds are enabled.
# Windows updater metadata is channel-specific (for example
# "latest.yml" or "nightly.yml"). Suffix each per-arch copy so the
# release job can merge matching arm64/x64 manifests back into one
# canonical manifest per channel.
# if [[ "${{ matrix.platform }}" == "win" ]]; then
# shopt -s nullglob
# for manifest in release-publish/*.yml; do
# mv "$manifest" "${manifest%.yml}-win-${{ matrix.arch }}.yml"
# done
# fi
- name: Upload build artifacts
uses: actions/upload-artifact@v7
with:
@@ -423,69 +226,50 @@ jobs:
publish_cli:
name: Publish CLI to npm
needs: [preflight, build]
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' }}
runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
permissions:
contents: read
id-token: write
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: package.json
cache: true
run-install: |
args:
- --filter=t3...
- --filter=@t3tools/web...
- --filter=@t3tools/scripts...
registry-url: https://registry.npmjs.org
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
- name: Build web package
run: vp run --filter @t3tools/web build
- name: Build CLI package
run: vp run --filter t3 build
run: bun run build --filter=@t3tools/web --filter=t3
- name: Publish CLI package
run: node apps/server/scripts/cli.ts publish --tag "${{ needs.preflight.outputs.cli_dist_tag }}" --app-version "${{ needs.preflight.outputs.version }}" --verbose
run: node apps/server/scripts/cli.ts publish --tag latest --app-version "${{ needs.preflight.outputs.version }}" --verbose
release:
name: Publish GitHub Release
needs: [preflight, build, publish_cli]
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' && needs.publish_cli.result == 'success' }}
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
runs-on: ubuntu-24.04
steps:
- id: app_token
name: Mint release app token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ secrets.RELEASE_APP_ID }}
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
- name: Checkout
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: package.json
cache: true
run-install: |
args:
- --filter=@t3tools/scripts...
- name: Download all desktop artifacts
uses: actions/download-artifact@v8
@@ -496,72 +280,17 @@ jobs:
- name: Merge macOS updater manifests
run: |
shopt -s nullglob
for x64_manifest in release-assets/*-mac-x64.yml; do
arm64_manifest="${x64_manifest%-x64.yml}.yml"
if [[ -f "$arm64_manifest" ]]; then
node scripts/merge-update-manifests.ts --platform mac "$arm64_manifest" "$x64_manifest"
rm -f "$x64_manifest"
fi
done
# - name: Merge Windows updater manifests
# run: |
# shopt -s nullglob
# found_windows_manifest=false
# for x64_manifest in release-assets/*-win-x64.yml; do
# if [[ "$(basename "$x64_manifest")" == builder-debug-* ]]; then
# continue
# fi
# arm64_manifest="${x64_manifest/-x64.yml/-arm64.yml}"
# output_manifest="${x64_manifest/-win-x64.yml/.yml}"
# if [[ ! -f "$arm64_manifest" ]]; then
# echo "Missing matching arm64 Windows manifest for $x64_manifest" >&2
# exit 1
# fi
# found_windows_manifest=true
# node scripts/merge-update-manifests.ts --platform win \
# "$arm64_manifest" \
# "$x64_manifest" \
# "$output_manifest"
# rm -f "$arm64_manifest" "$x64_manifest"
# done
# if [[ "$found_windows_manifest" != true ]]; then
# echo "No Windows updater manifests found to merge." >&2
# exit 1
# fi
node scripts/merge-mac-update-manifests.ts \
release-assets/latest-mac.yml \
release-assets/latest-mac-x64.yml
rm -f release-assets/latest-mac-x64.yml
- name: Publish release
if: needs.preflight.outputs.previous_tag != ''
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ needs.preflight.outputs.tag }}
target_commitish: ${{ needs.preflight.outputs.ref }}
name: ${{ needs.preflight.outputs.release_name }}
generate_release_notes: true
previous_tag: ${{ needs.preflight.outputs.previous_tag }}
prerelease: ${{ needs.preflight.outputs.is_prerelease }}
make_latest: ${{ needs.preflight.outputs.make_latest }}
files: |
release-assets/*.dmg
release-assets/*.zip
release-assets/*.AppImage
release-assets/*.exe
release-assets/*.blockmap
release-assets/*.yml
fail_on_unmatched_files: true
token: ${{ steps.app_token.outputs.token }}
- name: Publish first release
if: needs.preflight.outputs.previous_tag == ''
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ needs.preflight.outputs.tag }}
target_commitish: ${{ needs.preflight.outputs.ref }}
name: ${{ needs.preflight.outputs.release_name }}
name: T3 Code v${{ needs.preflight.outputs.version }}
generate_release_notes: true
prerelease: ${{ needs.preflight.outputs.is_prerelease }}
make_latest: ${{ needs.preflight.outputs.make_latest }}
@@ -571,105 +300,13 @@ jobs:
release-assets/*.AppImage
release-assets/*.exe
release-assets/*.blockmap
release-assets/*.yml
release-assets/latest*.yml
fail_on_unmatched_files: true
token: ${{ steps.app_token.outputs.token }}
deploy_web:
name: Deploy hosted web app
needs: [preflight, release]
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' }}
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
env:
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}
T3CODE_WEB_ROUTER_URL: ${{ vars.T3CODE_WEB_ROUTER_URL }}
T3CODE_WEB_LATEST_DOMAIN: ${{ vars.T3CODE_WEB_LATEST_DOMAIN }}
T3CODE_WEB_NIGHTLY_DOMAIN: ${{ vars.T3CODE_WEB_NIGHTLY_DOMAIN }}
VERCEL_TEAM_SLUG: ${{ vars.VERCEL_TEAM_SLUG }}
steps:
- name: Checkout
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: |
args:
- --filter=@t3tools/scripts...
- --filter=@t3tools/web...
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
- name: Refresh release lockfile
run: vp install --lockfile-only --ignore-scripts
- name: Deploy and alias channel
shell: bash
run: |
set -euo pipefail
if [[ -z "${VERCEL_TOKEN:-}" || -z "${VERCEL_ORG_ID:-}" || -z "${VERCEL_PROJECT_ID:-}" ]]; then
echo "Missing one or more required Vercel secrets: VERCEL_TOKEN, VERCEL_ORG_ID, VERCEL_PROJECT_ID." >&2
exit 1
fi
router_url="${T3CODE_WEB_ROUTER_URL:-https://app.t3.codes}"
latest_domain="${T3CODE_WEB_LATEST_DOMAIN:-latest.app.t3.codes}"
nightly_domain="${T3CODE_WEB_NIGHTLY_DOMAIN:-nightly.app.t3.codes}"
router_domain="${router_url#http://}"
router_domain="${router_domain#https://}"
router_domain="${router_domain%%/*}"
if [[ "${{ needs.preflight.outputs.release_channel }}" == "stable" ]]; then
channel_domain="$latest_domain"
channel_name="latest"
else
channel_domain="$nightly_domain"
channel_name="nightly"
fi
vercel_scope="${VERCEL_TEAM_SLUG:-$VERCEL_ORG_ID}"
vercel_scope_args=(--scope "$vercel_scope")
echo "Deploying hosted web app for $channel_name channel."
deployment_url="$(
vp dlx [email protected] deploy \
--prod \
--skip-domain \
--yes \
--token "$VERCEL_TOKEN" \
"${vercel_scope_args[@]}" \
--build-env "APP_VERSION=${{ needs.preflight.outputs.version }}" \
--build-env "VITE_HOSTED_APP_URL=$router_url" \
--build-env "VITE_HOSTED_APP_CHANNEL=$channel_name"
)"
echo "Aliasing $deployment_url to $channel_domain."
vp dlx [email protected] alias set "$deployment_url" "$channel_domain" \
--token "$VERCEL_TOKEN" \
"${vercel_scope_args[@]}"
if [[ "$channel_name" == "latest" && -n "$router_domain" && "$router_domain" != "$channel_domain" ]]; then
echo "Aliasing $deployment_url to router domain $router_domain."
vp dlx [email protected] alias set "$deployment_url" "$router_domain" \
--token "$VERCEL_TOKEN" \
"${vercel_scope_args[@]}"
fi
finalize:
name: Finalize release
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' && needs.preflight.outputs.release_channel == 'stable' }}
needs: [preflight, release]
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
runs-on: ubuntu-24.04
steps:
- id: app_token
name: Mint release app token
@@ -697,14 +334,15 @@ jobs:
echo "name=${APP_SLUG}[bot]" >> "$GITHUB_OUTPUT"
echo "email=${user_id}+${APP_SLUG}[bot]@users.noreply.github.com" >> "$GITHUB_OUTPUT"
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: package.json
cache: true
run-install: |
args:
- --filter=@t3tools/scripts...
- id: update_versions
name: Update version strings
@@ -714,11 +352,11 @@ jobs:
- name: Format package.json files
if: steps.update_versions.outputs.changed == 'true'
run: vp fmt apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json
run: bunx oxfmt apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json
- name: Refresh lockfile
if: steps.update_versions.outputs.changed == 'true'
run: vp install --lockfile-only --ignore-scripts
run: bun install --lockfile-only --ignore-scripts
- name: Commit and push version bump
if: steps.update_versions.outputs.changed == 'true'
@@ -726,7 +364,7 @@ jobs:
env:
RELEASE_TAG: ${{ needs.preflight.outputs.tag }}
run: |
if git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json pnpm-lock.yaml; then
if git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock; then
echo "No version changes to commit."
exit 0
fi
@@ -734,60 +372,6 @@ jobs:
git config user.name "${{ steps.app_bot.outputs.name }}"
git config user.email "${{ steps.app_bot.outputs.email }}"
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json pnpm-lock.yaml
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock
git commit -m "chore(release): prepare $RELEASE_TAG"
git push origin HEAD:main
announce_discord:
name: Announce release on Discord
if: |
always() && !cancelled() &&
needs.preflight.result == 'success' &&
needs.release.result == 'success' &&
needs.deploy_web.result == 'success' &&
(needs.finalize.result == 'success' || needs.finalize.result == 'skipped')
needs: [preflight, release, deploy_web, finalize]
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: |
args:
- --filter=@t3tools/scripts...
- name: Announce prerelease on Discord
if: needs.preflight.outputs.is_prerelease == 'true'
continue-on-error: true
env:
DISCORD_MENTION_ROLE_ID: ${{ secrets.DISCORD_RELEASE_NIGHTLY_ROLE_ID }}
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_RELEASE_WEBHOOK_URL }}
run: |
node scripts/notify-discord-release.ts prerelease \
--role-id "$DISCORD_MENTION_ROLE_ID" \
--release-name "${{ needs.preflight.outputs.release_name }}" \
--release-version "${{ needs.preflight.outputs.version }}" \
--tag "${{ needs.preflight.outputs.tag }}" \
--release-url "https://github.com/${{ github.repository }}/releases/tag/${{ needs.preflight.outputs.tag }}"
- name: Announce latest release on Discord
if: needs.preflight.outputs.make_latest == 'true'
continue-on-error: true
env:
DISCORD_MENTION_ROLE_ID: ${{ secrets.DISCORD_RELEASE_LATEST_ROLE_ID }}
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_RELEASE_WEBHOOK_URL }}
run: |
node scripts/notify-discord-release.ts latest \
--role-id "$DISCORD_MENTION_ROLE_ID" \
--release-name "${{ needs.preflight.outputs.release_name }}" \
--release-version "${{ needs.preflight.outputs.version }}" \
--tag "${{ needs.preflight.outputs.tag }}" \
--release-url "https://github.com/${{ github.repository }}/releases/tag/${{ needs.preflight.outputs.tag }}"
-5
View File
@@ -21,8 +21,3 @@ apps/web/src/components/__screenshots__
.vitest-*
__screenshots__/
.tanstack
squashfs-root/
.vercel
.gstack/
dist-electron/
.electron-runtime/
+1
View File
@@ -1,2 +1,3 @@
[tools]
node = "24.13.1"
bun = "1.3.9"
+15
View File
@@ -0,0 +1,15 @@
{
"$schema": "./node_modules/oxfmt/configuration_schema.json",
"ignorePatterns": [
".reference",
".plans",
"dist",
"dist-electron",
"node_modules",
"bun.lock",
"*.tsbuildinfo",
"**/routeTree.gen.ts",
"apps/web/public/mockServiceWorker.js"
],
"sortPackageJson": {}
}
+22
View File
@@ -0,0 +1,22 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"ignorePatterns": [
"dist",
"dist-electron",
"node_modules",
"bun.lock",
"*.tsbuildinfo",
"**/routeTree.gen.ts"
],
"plugins": ["eslint", "oxc", "react", "unicorn", "typescript"],
"categories": {
"correctness": "warn",
"suspicious": "warn",
"perf": "warn"
},
"rules": {
"react-in-jsx-scope": "off",
"eslint/no-shadow": "off",
"eslint/no-await-in-loop": "off"
}
}
-823
View File
@@ -1,823 +0,0 @@
# Server Auth Model Plan
## Purpose
Define the long-term server auth architecture for T3 Code before first-class remote environments ship.
This plan is deliberately broader than the current WebSocket token check and narrower than a complete remote collaboration system. The goal is to make the server secure by default, keep local desktop UX frictionless, and leave clean integration points for future remote access methods.
This document is written in terms of Effect-native services and layers because auth needs to be a core runtime concern, not route-local glue code.
## Primary goals
- Make auth server-wide, not WebSocket-only.
- Make insecure exposure hard to do accidentally.
- Preserve zero-login local desktop UX for desktop-managed environments.
- Support browser-native pairing and session auth.
- Leave room for native/mobile credentials later without rewriting the server boundary.
- Keep auth separate from transport and launch method.
## Non-goals
- Full multi-user authorization and RBAC.
- OAuth / SSO / enterprise identity.
- Passkeys or biometric UX in v1.
- Syncing auth state across environments.
- Designing the full remote environment product in this document.
## Core decisions
### 1. Auth is a server concern
Every privileged surface of the T3 server must go through the same auth policy engine:
- HTTP routes
- WebSocket upgrades
- RPC methods reached through WebSocket
The current split where [`/ws`](../apps/server/src/ws.ts) checks `authToken` but routes in [`http.ts`](../apps/server/src/http.ts) do not is not sufficient for a remote-capable product.
### 2. Pairing and session are different things
The system should distinguish:
- bootstrap credentials
- session credentials
Bootstrap credentials are short-lived and high-trust. They allow a client to become authenticated.
Session credentials are the durable credentials used after pairing.
Bootstrap should never become the long-lived request credential.
### 3. Auth and transport are separate
Auth must not be defined by how the client reached the server.
Examples:
- local desktop-managed server
- LAN `ws://`
- public `wss://`
- tunneled `wss://`
- SSH-forwarded `ws://127.0.0.1:<port>`
All of these should feed into the same auth model.
### 4. Exposure level changes defaults
The more exposed an environment is, the narrower the safe default should be.
Safe default expectations:
- local desktop-managed: auto-pair allowed
- loopback browser access: explicit bootstrap allowed
- non-loopback bind: auth required
- tunnel/public endpoint: auth required, explicit enablement required
### 5. Browser and native clients may use different session credentials
The auth model should support more than one session credential type even if only one ships first.
Examples:
- browser session cookie
- native bearer/device token
This should be represented in the model now, even if browser cookies are the first implementation.
## Target auth domain
### Route classes
Every route or transport entrypoint should be classified as one of:
1. `public`
2. `bootstrap`
3. `authenticated`
#### `public`
Unauthenticated by definition.
Should be extremely small. Examples:
- static shell needed to render the pairing/login UI
- favicon/assets required for the pairing screen
- a minimal server health/version endpoint if needed
#### `bootstrap`
Used only to exchange a bootstrap credential for a session.
Examples:
- Initial bootstrap envelope over file descriptor at startup
- `POST /api/auth/bootstrap`
- `GET /api/auth/session` if unauthenticated checks are part of bootstrap UX
#### `authenticated`
Everything that reveals machine state or mutates it.
Examples:
- WebSocket upgrade
- orchestration snapshot and events
- terminal open/write/close
- project search and file writes
- git routes
- attachments
- project favicon lookup
- server settings
The default stance should be: if it touches the machine, it is authenticated.
## Credential model
### Bootstrap credentials
Initial credential types to model:
- `desktop-bootstrap`
- `one-time-token`
Possible future credential types:
- `device-code`
- `passkey-assertion`
- `external-identity`
#### `desktop-bootstrap`
Used when the desktop shell manages the server and should be the only default pairing method for desktop-local environments.
Properties:
- launcher-provided
- short-lived
- one-time or bounded-use
- never shown to the user as a reusable password
#### `one-time-token`
Used for explicit browser/mobile pairing flows.
Properties:
- short TTL
- one-time use
- safe to embed in a pairing URL fragment
- exchanged for a session credential
### Session credentials
Initial credential types to model:
- `browser-session-cookie`
- `bearer-session-token`
#### `browser-session-cookie`
Primary browser credential.
Properties:
- signed
- `HttpOnly`
- bounded lifetime
- revocable by server key rotation or session invalidation
#### `bearer-session-token`
Reserved for native/mobile or non-browser clients.
Properties:
- opaque token, not a bootstrap secret
- long enough lifetime to survive reconnects
- stored in secure client storage when available
## Auth policy model
Auth behavior should be driven by an explicit environment auth policy, not route-local heuristics.
### Policy examples
#### `DesktopManagedLocalPolicy`
Default for desktop-managed local server.
Allowed bootstrap methods:
- `desktop-bootstrap`
Allowed session methods:
- `browser-session-cookie`
Disabled by default:
- `one-time-token`
- `bearer-session-token`
- password login
- public pairing
#### `LoopbackBrowserPolicy`
Used for browser access on localhost without desktop-managed bootstrap.
Allowed bootstrap methods:
- `one-time-token`
Allowed session methods:
- `browser-session-cookie`
#### `RemoteReachablePolicy`
Used when binding non-loopback or using an explicit remote/tunnel workflow.
Allowed bootstrap methods:
- `one-time-token`
- possibly `desktop-bootstrap` when a desktop shell is brokering access
Allowed session methods:
- `browser-session-cookie`
- `bearer-session-token`
#### `UnsafeNoAuthPolicy`
Should exist only as an explicit escape hatch.
Requirements:
- explicit opt-in flag
- loud startup warnings
- never defaulted automatically
## Effect-native service model
### `ServerAuth`
The main auth facade used by HTTP routes and WebSocket upgrade handling.
Responsibilities:
- classify requests
- authenticate requests
- authorize bootstrap attempts
- create sessions from bootstrap credentials
- enforce policy by environment mode
Sketch:
```ts
export interface ServerAuthShape {
readonly getCapabilities: Effect.Effect<AuthCapabilities>;
readonly authenticateHttpRequest: (
request: HttpServerRequest.HttpServerRequest,
routeClass: RouteAuthClass,
) => Effect.Effect<AuthContext, AuthError>;
readonly authenticateWebSocketUpgrade: (
request: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<AuthContext, AuthError>;
readonly exchangeBootstrapCredential: (
input: BootstrapExchangeInput,
) => Effect.Effect<SessionGrant, AuthError>;
}
export class ServerAuth extends ServiceMap.Service<ServerAuth, ServerAuthShape>()(
"t3/ServerAuth",
) {}
```
### `BootstrapCredentialService`
Owns issuance, storage, validation, and consumption of bootstrap credentials.
Responsibilities:
- issue desktop bootstrap grants
- issue one-time pairing tokens
- validate TTL and single-use semantics
- consume bootstrap grants atomically
Sketch:
```ts
export interface BootstrapCredentialServiceShape {
readonly issueDesktopBootstrap: (
input: IssueDesktopBootstrapInput,
) => Effect.Effect<BootstrapCredential>;
readonly issueOneTimeToken: (
input: IssueOneTimeTokenInput,
) => Effect.Effect<BootstrapCredential>;
readonly consume: (
presented: PresentedBootstrapCredential,
) => Effect.Effect<ConsumedBootstrapCredential, BootstrapCredentialError>;
}
```
### `SessionCredentialService`
Owns creation and validation of authenticated sessions.
Responsibilities:
- mint cookie sessions
- mint bearer sessions
- validate active session credentials
- revoke sessions if needed later
Sketch:
```ts
export interface SessionCredentialServiceShape {
readonly createBrowserSession: (
input: CreateSessionFromBootstrapInput,
) => Effect.Effect<BrowserSessionGrant, SessionCredentialError>;
readonly createBearerSession: (
input: CreateSessionFromBootstrapInput,
) => Effect.Effect<BearerSessionGrant, SessionCredentialError>;
readonly authenticateCookie: (
request: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<AuthContext, SessionCredentialError>;
readonly authenticateBearer: (
request: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<AuthContext, SessionCredentialError>;
}
```
### `ServerAuthPolicy`
Pure policy/config service that decides which credential types are allowed.
Responsibilities:
- map runtime mode and bind/exposure settings to allowed auth methods
- answer whether a route can be public
- answer whether remote exposure requires auth
This should stay mostly pure and cheap to test.
### `ServerSecretStore`
Owns long-lived server signing keys and secrets.
Responsibilities:
- get or create signing key
- rotate signing key
- abstract secure OS-backed storage vs filesystem fallback
Important:
- prefer platform secure storage when available
- support hardened filesystem fallback for headless/server-only environments
### `BrowserSessionCookieCodec`
Focused utility service for cookie encode/decode/signing behavior.
This should not own policy. It should only own the cookie format.
### `AuthRouteGuards`
Thin helper layer used by routes to enforce auth consistently.
Responsibilities:
- require auth for HTTP route handlers
- classify route auth mode
- convert auth failures into `401` / `403`
This prevents every route from re-implementing the same pattern.
Integrates with `HttpRouter.middleware` to enforce auth consistently.
## Suggested layer graph
```text
ServerSecretStore
├─> BootstrapCredentialService
├─> BrowserSessionCookieCodec
└─> SessionCredentialService
ServerAuthPolicy
├─> BootstrapCredentialService
├─> SessionCredentialService
└─> ServerAuth
ServerAuth
└─> AuthRouteGuards
```
Layer naming should follow existing repo style:
- `ServerSecretStoreLive`
- `BootstrapCredentialServiceLive`
- `SessionCredentialServiceLive`
- `ServerAuthPolicyLive`
- `ServerAuthLive`
- `AuthRouteGuardsLive`
## High-level implementation examples
### Example: WebSocket upgrade auth
Current state:
- `authToken` query param is checked in [`ws.ts`](../apps/server/src/ws.ts)
Target shape:
```ts
const websocketUpgradeAuth = HttpMiddleware.make((httpApp) =>
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
const serverAuth = yield* ServerAuth;
yield* serverAuth.authenticateWebSocketUpgrade(request);
return yield* httpApp;
}),
);
```
Then the `/ws` route becomes:
```ts
export const websocketRpcRouteLayer = HttpRouter.add(
"GET",
"/ws",
rpcWebSocketHttpEffect.pipe(
websocketUpgradeAuth,
Effect.catchTag("AuthError", (error) => toUnauthorizedResponse(error)),
),
);
```
This keeps the route itself declarative and makes auth compose like normal HTTP middleware.
### Example: authenticated HTTP route
For routes like attachments or project favicon:
```ts
const authenticatedRoute = (routeClass: RouteAuthClass) =>
HttpMiddleware.make((httpApp) =>
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
const serverAuth = yield* ServerAuth;
yield* serverAuth.authenticateHttpRequest(request, routeClass);
return yield* httpApp;
}),
);
```
Then:
```ts
export const attachmentsRouteLayer = HttpRouter.add(
"GET",
`${ATTACHMENTS_ROUTE_PREFIX}/*`,
serveAttachment.pipe(
authenticatedRoute(RouteAuthClass.Authenticated),
Effect.catchTag("AuthError", (error) => toUnauthorizedResponse(error)),
),
);
```
### Example: desktop bootstrap exchange
The desktop shell launches the local server and gets a short-lived bootstrap grant through a trusted side channel.
That grant is then exchanged for a browser cookie session when the renderer loads.
Sketch:
```ts
const pairDesktopRenderer = Effect.gen(function* () {
const bootstrapService = yield* BootstrapCredentialService;
const credential = yield* bootstrapService.issueDesktopBootstrap({
audience: "desktop-renderer",
ttlMs: 30_000,
});
return credential;
});
```
The renderer then calls a bootstrap endpoint and receives a cookie session. The bootstrap credential is consumed and becomes invalid.
### Example: one-time pairing URL
For browser-driven pairing:
```ts
const createPairingToken = Effect.gen(function* () {
const bootstrapService = yield* BootstrapCredentialService;
return yield* bootstrapService.issueOneTimeToken({
ttlMs: 5 * 60_000,
audience: "browser",
});
});
```
The server can emit a pairing URL where the token lives in the URL fragment so it is not automatically sent to the server before the client explicitly exchanges it.
## Sequence diagrams
These flows are meant to anchor the auth model in concrete user journeys.
The important invariant across all of them is:
- access method is not the auth method
- launch method is not the auth method
- bootstrap credential is not the session credential
### Normal desktop user
This is the default desktop-managed local flow.
The desktop shell is trusted to bootstrap the local renderer, but the renderer should still exchange that one-time bootstrap grant for a normal browser session cookie.
```text
Participants:
DesktopMain = Electron main
SecretStore = secure local secret backend
T3Server = local backend child process
Frontend = desktop renderer
DesktopMain -> SecretStore : getOrCreate("server-signing-key")
SecretStore --> DesktopMain : signing key available
DesktopMain -> T3Server : spawn server (--bootstrap-fd ...)
DesktopMain -> T3Server : send desktop bootstrap envelope
note over T3Server : policy = DesktopManagedLocalPolicy
note over T3Server : allowed pairing = desktop-bootstrap only
Frontend -> DesktopMain : request local bootstrap grant
DesktopMain --> Frontend : short-lived desktop bootstrap grant
Frontend -> T3Server : POST /api/auth/bootstrap
T3Server -> T3Server : validate desktop bootstrap grant
T3Server -> T3Server : create browser session
T3Server --> Frontend : Set-Cookie: session=...
Frontend -> T3Server : GET /ws + authenticated cookie
T3Server -> T3Server : validate cookie session
T3Server --> Frontend : websocket accepted
```
### `npx t3` user
This is the standalone local server flow.
There is no trusted desktop shell here, so pairing should be explicit.
```text
Participants:
UserShell = npx t3 launcher
T3Server = standalone local server
Browser = browser tab
UserShell -> T3Server : start server
T3Server -> T3Server : getOrCreate("server-signing-key")
note over T3Server : policy = LoopbackBrowserPolicy
UserShell -> T3Server : issue one-time pairing token
T3Server --> UserShell : pairing URL or pairing token
UserShell --> Browser : open /pair?token=...
Browser -> T3Server : GET /pair?token=...
T3Server -> T3Server : validate one-time token
T3Server -> T3Server : create browser session
T3Server --> Browser : Set-Cookie: session=...
T3Server --> Browser : redirect to app
Browser -> T3Server : GET /ws + authenticated cookie
T3Server --> Browser : websocket accepted
```
### Phone user with tunneled host
This is the explicit remote access flow for a browser on another device.
The tunnel only provides reachability. It must not imply trust.
Recommended UX:
- desktop shows a QR code
- desktop also shows a copyable pairing URL
- if the phone opens the host URL without a valid token, the server should render a login or pairing screen rather than granting access
```text
Participants:
DesktopUser = user at the host machine
DesktopMain = desktop app
Tunnel = tunnel provider
T3Server = T3 server
PhoneBrowser = mobile browser
DesktopUser -> DesktopMain : enable remote access via tunnel
DesktopMain -> T3Server : switch policy to RemoteReachablePolicy
DesktopMain -> Tunnel : publish local T3 endpoint
Tunnel --> DesktopMain : public https/wss URL
DesktopMain -> T3Server : issue one-time pairing token
T3Server --> DesktopMain : pairing token
DesktopMain -> DesktopUser : show QR code / shareable URL
DesktopUser -> PhoneBrowser : scan QR / open URL
PhoneBrowser -> Tunnel : GET https://public-host/pair?token=...
Tunnel -> T3Server : forward request
T3Server -> T3Server : validate one-time token
T3Server -> T3Server : create mobile browser session
T3Server --> PhoneBrowser : Set-Cookie: session=...
T3Server --> PhoneBrowser : redirect to app
PhoneBrowser -> Tunnel : GET /ws + authenticated cookie
Tunnel -> T3Server : forward websocket upgrade
T3Server --> PhoneBrowser : websocket accepted
```
### Phone user with private network
This is operationally similar to the tunnel flow, but the access endpoint is on a private network such as Tailscale.
The auth flow should stay the same.
```text
Participants:
DesktopUser = user at the host machine
T3Server = T3 server
PrivateNet = tailscale / private LAN
PhoneBrowser = mobile browser
DesktopUser -> T3Server : enable private-network access
T3Server -> T3Server : switch policy to RemoteReachablePolicy
DesktopUser -> T3Server : issue one-time pairing token
T3Server --> DesktopUser : pairing URL / QR
DesktopUser -> PhoneBrowser : open private-network URL
PhoneBrowser -> PrivateNet : GET http(s)://private-host/pair?token=...
PrivateNet -> T3Server : route request
T3Server -> T3Server : validate one-time token
T3Server -> T3Server : create mobile browser session
T3Server --> PhoneBrowser : Set-Cookie: session=...
T3Server --> PhoneBrowser : redirect to app
PhoneBrowser -> PrivateNet : GET /ws + authenticated cookie
PrivateNet -> T3Server : websocket upgrade
T3Server --> PhoneBrowser : websocket accepted
```
### Desktop user adding new SSH hosts
SSH should be treated as launch and reachability plumbing, not as the long-term auth model.
The desktop app uses SSH to start or reach the remote server, then the renderer pairs against that server using the same bootstrap/session split as every other environment.
```text
Participants:
DesktopUser = local desktop user
DesktopMain = desktop app
SSH = ssh transport/session
RemoteHost = remote machine
RemoteT3 = remote T3 server
Frontend = desktop renderer
DesktopUser -> DesktopMain : add SSH host
DesktopMain -> SSH : connect to remote host
SSH -> RemoteHost : probe environment / verify t3 availability
DesktopMain -> SSH : run remote launch command
SSH -> RemoteHost : t3 remote launch --json
RemoteHost -> RemoteT3 : start or reuse server
RemoteT3 --> RemoteHost : port + environment metadata
RemoteHost --> SSH : launch result JSON
SSH --> DesktopMain : remote server details
DesktopMain -> SSH : establish local port forward
SSH --> DesktopMain : localhost:FORWARDED_PORT ready
note over RemoteT3 : policy = RemoteReachablePolicy
note over DesktopMain,RemoteT3 : desktop may use a trusted bootstrap flow here
Frontend -> DesktopMain : request bootstrap for selected environment
DesktopMain --> Frontend : short-lived bootstrap grant
Frontend -> RemoteT3 : POST /api/auth/bootstrap via forwarded port
RemoteT3 -> RemoteT3 : validate bootstrap grant
RemoteT3 -> RemoteT3 : create browser session
RemoteT3 --> Frontend : Set-Cookie: session=...
Frontend -> RemoteT3 : GET /ws + authenticated cookie
RemoteT3 --> Frontend : websocket accepted
```
## Storage decisions
### Server secrets
Use a `ServerSecretStore` abstraction.
Preferred order (use a layer for each, resolve on startup):
1. OS secure storage if available
2. hardened filesystem fallback if not
The filesystem fallback should store only opaque signing material with strict file permissions. It should not store user passwords or reusable third-party credentials.
### Client credentials
Client-side credential persistence should prefer secure storage when available:
- desktop: OS keychain / secure store
- mobile: platform secure storage
- browser: cookie session for browser auth
This concern should stay in the client shell/runtime layer, not the server auth layer.
## What to build now
These are the parts worth building before remote environments ship:
1. `ServerAuth` service boundary.
2. route classification and route guards.
3. `ServerSecretStore` abstraction.
4. bootstrap vs session credential split.
5. browser session cookie codec as one session method.
6. explicit auth capabilities/config surfaced in contracts.
Even if only one pairing flow is used initially, these seams will keep future remote and mobile work contained.
## What to add as part of first remote-capable auth
1. Browser pairing flow using one-time bootstrap token and cookie session.
2. Desktop-managed auto-bootstrap for the local desktop-managed environment.
3. Auth-required defaults for any non-loopback or explicitly published server.
4. Explicit environment auth policy selection instead of scattered `if (host !== localhost)` checks.
## What to defer
- passkeys / WebAuthn
- iCloud Keychain / Face ID-specific UX
- multi-user permissions
- collaboration roles
- OAuth / SSO
- polished session management UI
- complex device approval flows
These can all sit on top of the same bootstrap/session/service split.
## Relationship to future remote environments
Remote access is one reason this auth model matters, but the auth model should not be remote-shaped.
Keep the design focused on:
- one T3 server
- one auth policy
- multiple credential types
- multiple future access methods
That keeps the server auth model stable even as access methods expand later.
## Recommended implementation order
### Phase 1
- Introduce route auth classes.
- Add `ServerAuth` and `AuthRouteGuards`.
- Move existing `authToken` check behind `ServerAuth`.
- Require auth for all privileged HTTP routes as well as WebSocket.
### Phase 2
- Add `ServerSecretStore` service with platform-specific layer implementations.
- `layerOSXKeychain`, `layer
- Add bootstrap/session split.
- Add browser session cookie support.
- Add one-time bootstrap exchange endpoint.
### Phase 3
- Add desktop bootstrap flow on top of the same services.
- Make desktop-managed local environments default to bootstrap-only pairing.
- Surface auth capabilities in shared contracts and renderer bootstrap.
### Phase 4
- Add non-browser bearer session support if mobile/native needs it.
- Add richer policy modes for remote-reachable environments.
## Acceptance criteria
- No privileged HTTP or WebSocket path bypasses auth policy.
- Local desktop-managed flows still avoid a visible login screen.
- Non-loopback or published environments require explicit authenticated pairing by default.
- Bootstrap and session credentials are distinct in code and in behavior.
- Auth logic is centralized in Effect services/layers rather than route-local branching.
-349
View File
@@ -1,349 +0,0 @@
# Remote Endpoints and Hosted Static App Plan
## Purpose
Make remote access feel first-class while keeping the free DIY path open.
The immediate product goal is:
- users can expose a backend through LAN, their own Tailscale, MagicDNS, a manual HTTPS endpoint, or later T3 Tunnel
- users can generate a hosted pairing link for `app.t3.codes`
- the hosted app can pair, persist, reconnect, and operate against saved environments without requiring a backend at the hosted app origin
- all transports reuse the same backend auth, WebSocket runtime, saved environment registry, and pairing UX
This plan intentionally leaves the paid T3 cloud tunnel fabric out of scope. It defines the OSS foundation that T3 Tunnel should later plug into.
## Current State
Already present or in progress:
- Server auth distinguishes bootstrap credentials from session credentials.
- One-time pairing credentials can be exchanged for browser sessions or bearer sessions.
- Saved remote environments store `httpBaseUrl`, `wsBaseUrl`, and a bearer token.
- Remote environment WebSocket connections use a short-lived WebSocket token.
- Pairing URLs can carry tokens in the URL fragment.
- Hosted `/pair?host=...#token=...` can add a saved environment.
- Hosted static startup can avoid assuming the page origin is the backend.
Main gaps:
- Reachability is represented ad hoc as `endpointUrl`, manual host input, or saved environment URLs.
- Desktop exposure, hosted pairing, manual remote environments, and future tunnels do not share one endpoint model.
- Tailscale/MagicDNS endpoints are not detected or surfaced.
- Hosted-static empty/offline states are still thin.
- Browser compatibility is not explicitly modeled, especially HTTPS hosted app to HTTP backend mixed-content failure.
## Core Decision: Add `AdvertisedEndpoint`
Add a new first-class contract instead of extending the environment descriptor.
### Why not extend `ExecutionEnvironmentDescriptor`
`ExecutionEnvironmentDescriptor` answers: "What environment is this?"
Examples:
- environment id
- label
- platform
- server version
- capabilities
`AdvertisedEndpoint` answers: "How can a client reach this environment right now?"
Examples:
- loopback URL
- LAN URL
- Tailscale IP URL
- MagicDNS/Serve URL
- manual URL
- future T3 Tunnel URL
- browser compatibility and exposure level
Those are different lifecycles. One environment can have many endpoints, endpoints can appear/disappear as network interfaces change, and the same descriptor is returned regardless of which endpoint the client used. Extending the descriptor would blur environment identity with transport reachability and make saved environments harder to reason about.
### Target Contract
Add a schema in `packages/contracts`, likely `remoteAccess.ts`:
```ts
type AdvertisedEndpointProvider =
| "loopback"
| "lan"
| "tailscale-ip"
| "tailscale-magicdns"
| "manual"
| "t3-tunnel";
type AdvertisedEndpointVisibility = "local" | "private-network" | "tailnet" | "public";
type AdvertisedEndpointCompatibility = {
hostedHttpsApp: "compatible" | "mixed-content-blocked" | "untrusted-certificate" | "unknown";
desktopApp: "compatible" | "unknown";
};
type AdvertisedEndpoint = {
id: string;
provider: AdvertisedEndpointProvider;
label: string;
httpBaseUrl: string;
wsBaseUrl: string;
visibility: AdvertisedEndpointVisibility;
compatibility: AdvertisedEndpointCompatibility;
source: "server" | "desktop" | "user";
status: "available" | "unavailable" | "unknown";
isDefault?: boolean;
};
```
Keep the contract schema-only. All classification logic belongs in `packages/shared`, `apps/server`, `apps/desktop`, or `apps/web`.
## HTTP/WS and HTTPS/WSS Readiness
The codebase is partially ready, but the UX and compatibility model are not explicit enough.
What is ready:
- Remote target parsing already derives `ws://` from `http://` and `wss://` from `https://`.
- Saved environments store both HTTP and WebSocket base URLs.
- Remote auth uses bearer tokens instead of cookies, so cross-origin hosted clients are viable.
- WebSocket connections can use a dynamically issued `wsToken`.
- Server CORS support exists for browser remote auth endpoints.
What is not solved by code alone:
- `https://app.t3.codes` cannot reliably call `http://...` or `ws://...` endpoints because browsers block mixed content.
- `wss://100.x.y.z:3773` needs a certificate the browser trusts. A raw Tailscale IP does not solve certificate trust.
- LAN `http://192.168.x.y:3773` is usable from another desktop/native context but not from the hosted HTTPS app.
- The UI needs to explain why an endpoint is copyable for desktop pairing but not hosted-app compatible.
Policy:
- Support both HTTP/WS and HTTPS/WSS at the runtime layer.
- Mark endpoint compatibility at the product layer.
- Generate `app.t3.codes` links only from endpoints that are likely hosted-browser compatible, or show a warning with an explicit fallback.
## Architecture
### Endpoint Sources
Endpoint records can come from several providers:
1. **Server runtime**
- headless bind host and port
- server-known explicit advertised host config
2. **Desktop shell**
- loopback backend URL
- LAN exposure state
- network interface discovery
- Tailscale CLI/status discovery
3. **User configuration**
- manually added hostnames
- preferred endpoint labels
- hidden/disabled endpoints
4. **Future cloud provider**
- T3 Tunnel endpoint
- billing/account status
- tunnel lifecycle state
### Endpoint Registry
Create a central runtime registry:
- `packages/contracts/src/remoteAccess.ts`
- `packages/shared/src/remoteAccess.ts` for URL normalization and compatibility classification
- `apps/server/src/remoteAccess/*` for server/headless endpoints
- `apps/desktop/src/remoteAccess/*` for desktop-discovered endpoints
- `apps/web/src/environments/endpoints/*` for client-side display and pairing selection
The web app should consume endpoint records and not care whether they came from LAN, Tailscale, or a future tunnel.
### Pairing Link Generation
Move hosted pairing link generation to endpoint-driven input:
```ts
buildHostedPairingUrl({
endpoint: AdvertisedEndpoint,
token,
});
```
Generated URL:
```text
https://app.t3.codes/pair?host=<encoded endpoint httpBaseUrl>#token=<one-time token>
```
Use fragment tokens by default. Continue accepting `?token=` for compatibility.
## Phase 1: Endpoint Abstraction
### Goals
- Centralize URL normalization, protocol derivation, and compatibility checks.
- Replace ad hoc desktop `endpointUrl` pairing logic with endpoint selection.
- Preserve all current remote behavior.
### Tasks
1. Add `AdvertisedEndpoint` schemas to `packages/contracts`.
2. Add shared helpers:
- normalize HTTP base URL
- derive WebSocket base URL
- classify loopback/private/LAN/Tailscale/public host
- classify hosted HTTPS compatibility
3. Add server endpoint discovery:
- loopback endpoint
- configured non-loopback endpoint
- explicit advertised host override
4. Add desktop endpoint discovery:
- local loopback
- LAN exposure endpoint
- endpoint status labels
5. Add WebSocket/API method or existing config field for endpoint snapshots.
6. Refactor settings connections UI:
- render endpoint rows
- endpoint picker for pairing link copy
- show compatibility warnings
7. Refactor hosted link builder to accept endpoint records.
8. Add tests for URL normalization and compatibility classification.
### Acceptance Criteria
- Existing LAN/network access UI still works.
- Pairing links are generated from endpoint records.
- Loopback endpoints never produce hosted pairing links silently.
- HTTP private-network endpoints are marked incompatible with `app.t3.codes`.
- No remote environment runtime changes are required for existing saved environments.
## Phase 2: BYO Tailscale/MagicDNS
### Goals
- Detect free DIY Tailscale reachability.
- Surface Tailscale endpoints as normal advertised endpoints.
- Keep users in control of their own tailnet.
### Tasks
1. Detect Tailscale IPs from network interfaces:
- IPv4 `100.64.0.0/10`
- mark as `provider: "tailscale-ip"`
2. Add optional desktop-side `tailscale status --json` discovery:
- MagicDNS hostname
- Tailscale Serve/Funnel HTTPS endpoint if discoverable
- graceful failure if CLI is missing
3. Add manual Tailscale endpoint override:
- hostname
- label
- preferred/default flag
4. Show Tailscale endpoint rows in settings:
- raw IP HTTP endpoint: desktop-compatible, hosted-app likely blocked
- HTTPS MagicDNS/Serve endpoint: hosted-compatible if URL is HTTPS
5. Generate pairing links using selected Tailscale endpoint.
6. Document DIY setup:
- local desktop-to-desktop over Tailscale
- hosted app requirements
- why HTTPS matters
### Acceptance Criteria
- A machine on Tailscale shows a Tailscale endpoint without paid features.
- Users can copy a Tailscale-hosted pairing link when the endpoint is HTTPS-compatible.
- Users can still copy token-only/manual values when endpoint compatibility is unknown.
- Tailscale is optional and never required for regular LAN/loopback use.
## Phase 3: Hosted Static App Completion
### Goals
- `app.t3.codes` works as a real client shell.
- It can pair, persist, reconnect, and clearly explain offline/incompatible states.
### Tasks
1. Finish hosted-static root behavior:
- no primary backend required
- saved environment hydration before initial routing decisions
- first saved environment selected as active
2. Add hosted empty state:
- no saved environments
- paste pairing URL
- add host + token
3. Add offline saved environment UI:
- last connected
- reconnect
- remove
- copy/add alternate endpoint
4. Audit primary-backend assumptions:
- command palette
- settings pages
- server config atom defaults
- keybindings
- provider/model lists
- update/desktop-only affordances
5. Add route tests for:
- hosted `/pair?host=...#token=...`
- hosted root with no saved environments
- hosted root with saved environment
- primary backend unavailable but saved environment present
6. Add deployment hardening:
- SPA fallback
- strict CSP
- no third-party scripts
- no query token logging
- disable or hide source maps in production if needed
7. Add browser error messages:
- mixed content
- unreachable backend
- CORS failure
- certificate failure
### Acceptance Criteria
- `app.t3.codes` can pair a reachable HTTPS backend and reconnect after reload.
- A saved environment can be used without any backend at `app.t3.codes`.
- Offline machines show a useful state instead of a generic boot error.
- HTTP endpoints are still supported in desktop/native/local contexts.
- Hosted HTTPS app only promises compatibility for HTTPS/WSS endpoints.
## Phase 4: Future T3 Tunnel Provider
Not part of the current implementation, but the endpoint abstraction should make it straightforward.
Future tunnel provider responsibilities:
- create endpoint with `provider: "t3-tunnel"`
- surface tunnel status
- provide stable HTTPS URL
- use existing backend pairing/session auth
- never bypass server auth
The tunnel fabric can later be Pipenet-derived, Tailscale-derived, or another reverse tunnel implementation. The rest of T3 Code should only see an `AdvertisedEndpoint`.
## Security Checklist
- Pairing tokens are short-lived and one-time.
- Generated hosted pairing links put tokens in the fragment.
- The backend remains the authorization boundary.
- Endpoint discovery never disables backend auth.
- Hosted app does not silently downgrade to HTTP.
- Tunnel/public endpoints require explicit user action.
- Client sessions remain revocable.
- Endpoint URLs and request logs must avoid recording pairing tokens.
- Future cloud tunnel must authenticate tunnel creation and tunnel data connections separately from backend pairing.
## Verification
Each implementation PR should run:
- `bun fmt`
- `bun lint`
- `bun typecheck`
- focused tests for changed backend/web behavior
- backend tests for any server-side endpoint discovery or auth changes using `bun run test`, never `bun test`
@@ -1,216 +0,0 @@
# Version Control Phase 1: VCS Driver Foundation
## Goal
Introduce a provider-neutral VCS layer and rewrite the local Git implementation as an Effect-native driver. This phase should preserve user-visible behavior while replacing the Git-first service boundary with an abstraction that can support Git, Jujutsu, and later Sapling or another viable VCS.
The existing `GitCore` implementation is a behavior reference and source of regression tests, not the target architecture. New code should follow the newer package style used by `effect-acp` and `effect-codex-app-server`: typed service tags, schema-backed tagged errors, scoped process usage, explicit decode boundaries, and no Promise-based process helper as the core execution primitive.
## Scope
- Add VCS-domain contracts in `packages/contracts/src/vcs.ts`.
- Add shared runtime parsing helpers in `packages/shared/src/vcs/*` only when they are useful to both server and web.
- Add server services under `apps/server/src/vcs`:
- `Services/VcsDriver.ts`
- `Services/VcsRepositoryResolver.ts`
- `Services/VcsProcess.ts`
- `Layers/GitVcsDriver.ts`
- `errors.ts`
- Migrate server callers from Git-specific terms where the operation is actually VCS-generic.
- Update active consumers to the new VCS APIs in the same phase; do not add backwards-compatible export shims.
- Leave source-control hosting providers out of this phase except for remote metadata needed to describe repository status.
## Non-Goals
- No GitLab, Azure DevOps, or GitHub provider rewrite yet.
- No Jujutsu driver yet, but every interface must be designed so a Jujutsu driver does not have to pretend to be Git.
- No T3 Review implementation yet.
- No broad UI redesign.
## Driver Model
Use provider-neutral nouns in new APIs:
- `VcsDriver`: local repository mechanics.
- `RepositoryIdentity`: detected VCS kind, root path, common metadata path when available, remotes.
- `WorkingCopyStatus`: dirty state, changed files, aggregate insertions/deletions, current branch/bookmark/change name.
- `ChangeSet`: a committed or pending unit of change, not necessarily a Git commit.
- `RefName`: branch, bookmark, tag, or provider-specific ref.
The initial driver capabilities should be explicit:
```ts
export interface VcsDriverCapabilities {
readonly kind: "git" | "jj" | "sapling" | "unknown";
readonly supportsWorktrees: boolean;
readonly supportsBookmarks: boolean;
readonly supportsAtomicSnapshot: boolean;
readonly supportsPushDefaultRemote: boolean;
}
```
Do not model Jujutsu as `GitCoreShape extends ...`. The Git driver can expose Git-specific implementation details internally, but the public VCS layer should describe operations by intent:
- `detectRepository(cwd)`
- `status(cwd, options)`
- `listRefs(cwd, query/pagination)`
- `checkoutRef(cwd, ref)`
- `createRef(cwd, ref, from?)`
- `createWorkspace(cwd, ref, path?)`
- `removeWorkspace(path)`
- `prepareChangeContext(cwd, filePaths?)`
- `createChange(cwd, message, options)`
- `push(cwd, target?)`
- `rangeContext(cwd, base, head)`
- `listWorkspaceFiles(cwd, options)`
## Effect Process Layer
Create a small reusable `VcsProcess` service instead of using `runProcess`.
Requirements:
- Implement with `ChildProcess` and `ChildProcessSpawner` from `effect/unstable/process`.
- Support scoped acquisition/release for long-running commands and interruption.
- Support bounded stdout/stderr collection with truncation markers.
- DO not eagerly consume full stdout/stderr, return stream apis and expose helpers for consumers so we don't consume streams to memory unnecessarily...
- Support stdin.
- Support timeout through Effect scheduling/interruption, not ad-hoc timers.
- Stream output lines to progress callbacks as Effects.
- Return a typed `ProcessOutput` value for successful execution.
- Fail with typed errors, not generic thrown exceptions.
Errors should be schema-backed tagged classes, for example:
- `VcsProcessSpawnError`
- `VcsProcessExitError`
- `VcsProcessTimeoutError`
- `VcsOutputDecodeError`
- `VcsRepositoryDetectionError`
- `VcsUnsupportedOperationError`
Every error should carry operation name, command display string, cwd when applicable, exit code when applicable, stderr/stdout tails when useful, and original cause where available. Override `message` for user readable messages that provides meaning and hints where appropriate. Errors are schema backed so the full error details will be persisted and serialized properly when stored to DB/Logfiles.
## Git Driver Rewrite
Rewrite Git support against `VcsProcess`.
Carry forward current behavior from:
- `apps/server/src/git/Layers/GitCore.ts`
- `apps/server/src/git/Layers/GitCore.test.ts`
- current Git status/branch/worktree contracts
But split the implementation into smaller modules:
- command execution and hardening config
- repository detection
- status parsing
- branch/ref parsing
- worktree operations
- commit/range context generation
- push/pull operations
Keep parsing deterministic. Prefer Git porcelain formats, null-separated output, and schema decoding for JSON-like command output. Avoid regex parsing where Git gives a structured format.
## Freshness and Local Caching
Define freshness rules in the VCS layer before adding more providers. Local VCS status is cheap enough to refresh often; network-backed status is not.
Treat these as live/local:
- repository detection for the active cwd
- working copy dirty state
- staged/unstaged/untracked file summaries
- current branch/bookmark/change name
- local branch/bookmark lists
- local worktree/workspace lists
These may run on user-visible polling, but should still be debounced and coalesced per repository root. Prefer filesystem-triggered invalidation where available, with a short fallback poll interval. Concurrent requests for the same repository/status shape should share one in-flight Effect.
Treat these as cached or explicit-refresh only:
- remote tracking branch refreshes
- ahead/behind counts that require network fetches
- default branch discovery from a remote provider
- remote branch lists beyond locally known refs
The VCS driver should expose freshness metadata with status results:
```ts
export interface VcsFreshness {
readonly source: "live-local" | "cached-local" | "cached-remote" | "explicit-remote";
readonly observedAt: string;
readonly expiresAt?: string;
}
```
Remote refreshes should be opt-in per operation, for example `refresh: "local-only" | "allow-cached-remote" | "force-remote"`. The default for background status should be `local-only`.
Use Effect `Cache` for repository identity and expensive local metadata:
- key by resolved repository root plus VCS kind
- invalidate on cwd/root changes and workspace mutation operations
- use short TTLs for local status caches when filesystem events are unavailable
- never hide command failures behind stale values unless the caller explicitly accepts stale data
## Cutover Policy
Prefer direct migration and deletion over compatibility wrappers.
Rules:
- Update consumers to call `VcsDriver`/`VcsRepositoryResolver` directly as soon as the new API exists.
- Delete migrated `GitCore` service methods and tests in the same PR that moves their consumers.
- Do not keep backwards-compatible export shims, barrel aliases, or old service names for convenience.
- Transitional modules are allowed only when a caller group is too complex or risky to migrate in the same PR.
- Every transitional module must have a narrow owner, a removal checklist, and a test proving it delegates to the new implementation.
- No new feature work may depend on transitional modules.
Expected transitional candidates:
- The highest-level `GitManager` orchestration can be migrated in slices if doing the full Commit + PR flow in one PR is too risky.
- WebSocket payload compatibility can remain only where changing it would require a coordinated UI/server protocol migration. Internal server code should still use the new VCS contracts.
## Tests
Add integration-style tests with real temporary Git repositories for the new Git driver:
- non-repository detection
- status for clean/dirty/untracked/staged states
- branch/ref list with pagination
- checkout/create branch
- worktree create/remove
- commit context generation with file filters
- commit creation with hook progress events
- push behavior against a local bare remote
- status polling does not perform remote network refresh by default
- concurrent duplicate status requests are coalesced
- bounded output/truncation
- timeout/interruption
- typed error shape for command failure and missing executable
Move or duplicate only the tests needed to prove behavior, then delete the old service tests in the same migration slice.
## Migration Steps
1. Add `vcs` contracts and tagged errors.
2. Add `VcsProcess` and unit tests around process execution semantics.
3. Add `VcsDriver` and `VcsRepositoryResolver` service contracts.
4. Implement `GitVcsDriver` with real Git command integration tests.
5. Move `GitStatusBroadcaster` and branch/worktree flows to the VCS service directly.
6. Move commit/range/push callers to the VCS service directly.
7. Delete migrated `GitCore` internals and tests as each caller group moves.
8. Add a transitional adapter only for any remaining `GitManager` path that is explicitly too complex to cut over safely in one PR.
9. Remove every transitional adapter before starting Phase 2 unless the adapter is documented as blocking on the provider cutover.
## Acceptance Criteria
- Current Git branch/status/worktree/commit behavior remains intact.
- New Git implementation does not depend on `processRunner.ts`.
- New errors are typed and inspectable by tests.
- VCS interfaces contain no GitHub/GitLab/Azure concepts.
- Active consumers use the new VCS APIs directly; any remaining transitional module has a written removal checklist and no compatibility export shim.
- Background status refresh is local-only by default and cannot hit provider rate limits.
- Jujutsu can be added by implementing a real driver instead of conforming to Git command semantics.
- `bun fmt`, `bun lint`, and `bun typecheck` pass.
@@ -1,268 +0,0 @@
# Version Control Phase 2: Source Control Provider Foundation
## Goal
Introduce a pluggable source-control provider layer and rewrite GitHub support as an Effect-native provider. This phase should preserve the existing GitHub Commit + PR flow while making GitLab and Azure DevOps additive drivers rather than branches inside GitHub-oriented code.
The existing `GitHubCli` service and GitHub-specific `GitManager` paths are behavior references. The new provider layer should use detailed tagged errors, schema decode boundaries, `effect/unstable/process`, capability flags, and provider-neutral change-request types.
## Scope
- Add provider-domain contracts in `packages/contracts/src/sourceControl.ts`.
- Add provider URL/reference parsing helpers in `packages/shared/src/sourceControl/*`.
- Add server services under `apps/server/src/sourceControl`:
- `Services/SourceControlProvider.ts`
- `Services/SourceControlProviderRegistry.ts`
- `Services/SourceControlProcess.ts`
- `Layers/GitHubSourceControlProvider.ts`
- `errors.ts`
- Migrate PR creation, PR lookup, default-branch lookup, clone URL lookup, and PR checkout through the provider layer.
- Update active consumers to the provider APIs directly; do not add backwards-compatible `GitHubCli` export shims.
- Keep GitHub as the only production provider at the end of this phase, but make GitLab and Azure implementation paths obvious and bounded.
## Non-Goals
- No GitLab implementation in this phase, except fixtures/contracts that prove the abstraction can represent merge requests.
- No Azure DevOps implementation in this phase, except URL/reference parser test cases if cheap.
- No in-app review UI yet.
- No hard dependency on one CLI forever. The first GitHub driver may use `gh`, but the interface should support REST/GraphQL implementations later.
## Provider Model
Use provider-neutral names:
- `SourceControlProvider`: hosted repository and change-request mechanics.
- `ChangeRequest`: GitHub pull request, GitLab merge request, Azure pull request.
- `ChangeRequestThread`: review or discussion thread.
- `ChangeRequestComment`: top-level or inline comment.
- `ProviderRepository`: owner/project/repo identity plus clone URLs.
Core provider operations:
- `detectRemote(remoteUrl)`
- `checkAuth(cwd)`
- `getRepository(cwd | remoteUrl)`
- `getDefaultTargetRef(repository)`
- `listChangeRequests(repository, filters)`
- `getChangeRequest(repository, reference)`
- `createChangeRequest(repository, input)`
- `checkoutChangeRequest(cwd, changeRequest, options)`
- `getCloneUrls(repository)`
Review-facing operations should be designed now, even if unimplemented:
- `listReviewThreads(changeRequest)`
- `createReviewComment(changeRequest, input)`
- `replyToReviewThread(thread, input)`
- `resolveReviewThread(thread)`
- `submitReview(changeRequest, input)`
Each operation should be guarded by capabilities:
```ts
export interface SourceControlProviderCapabilities {
readonly kind: "github" | "gitlab" | "azure-devops" | "unknown";
readonly supportsCreateChangeRequest: boolean;
readonly supportsCheckoutChangeRequest: boolean;
readonly supportsReviewThreads: boolean;
readonly supportsInlineComments: boolean;
readonly supportsDraftChangeRequests: boolean;
}
```
## Provider Registry
Add a registry that resolves a provider from repository remotes and explicit user input.
Rules:
- Detection should be pure where possible and testable without spawning CLIs.
- Remote URL parsing belongs in `packages/shared`, not server-only provider layers.
- Unknown providers should return explicit unsupported-operation errors, not silently fall back to GitHub.
- Provider selection should be stable per operation and logged with enough context to debug bad remote detection.
The registry should support multiple provider implementations at runtime, not a single dispatcher file with inline provider branches.
## Rate Limits and Provider Caching
Design the provider layer around a strict freshness budget. Provider API and CLI calls must not be part of frequent background polling unless the operation is explicitly marked safe and cached.
Default behavior:
- Pure URL/remote parsing is always live because it is local.
- Provider detection from local remotes is live-local.
- Authentication checks are cached.
- Repository metadata is cached.
- Default branch metadata is cached.
- Change-request lists are cached and refreshed on explicit user actions or coarse intervals.
- Full review threads, comments, file diffs, and timeline data are fetched only when the user opens the relevant review surface or explicitly refreshes it.
- Create/update operations invalidate affected cache keys immediately after success.
The provider API should make freshness explicit:
```ts
export interface SourceControlFreshness {
readonly source: "live-local" | "cached-provider" | "live-provider";
readonly observedAt: string;
readonly expiresAt?: string;
readonly stale?: boolean;
}
export type ProviderRefreshPolicy =
| "cache-first"
| "stale-while-revalidate"
| "force-refresh"
| "local-only";
```
Every read operation that can touch a provider should accept a refresh policy. Background UI reads should default to `cache-first` or `stale-while-revalidate`; direct user actions like pressing refresh can use `force-refresh`.
Use Effect `Cache` for provider data:
- auth status: key by provider kind, hostname, workspace identity, and account if known; TTL around minutes, not seconds
- repository metadata/default branch: key by provider repository stable ID or normalized remote URL; TTL around tens of minutes
- change-request summary lists: key by provider repository, state/filter, source ref, target ref; short TTL with stale-while-revalidate
- individual change-request summaries: key by provider repository and provider CR ID; short TTL, invalidated after create/update/comment operations
- review threads/comments/diffs: key by provider CR ID and head SHA/version when available; fetch on demand for T3 Review
Provider drivers should surface rate-limit signals when available:
- remaining quota
- reset time
- retry-after duration
- whether the limit is primary, secondary/abuse, or unknown
Rate-limit errors should be typed, retryable when the provider gives a reset/retry time, and visible enough for the UI to avoid repeatedly retrying a blocked operation.
Avoid rate-limit footguns:
- no provider calls from render loops or fast status polling
- no listing all PRs/MRs across all repos to infer one branch state
- no silent GitHub fallback for unknown providers
- no unbounded cache cardinality for branch names or free-form search queries
- no per-thread duplicate provider refresh when multiple views observe the same repository
## GitHub Provider Rewrite
Rewrite GitHub support as `GitHubSourceControlProvider`.
Carry forward behavior from:
- `apps/server/src/git/Layers/GitHubCli.ts`
- `apps/server/src/git/Layers/GitHubCli.test.ts`
- `apps/server/src/git/githubPullRequests.ts`
- GitHub-specific `GitManager` PR paths
Implementation requirements:
- Use `SourceControlProcess` built on `effect/unstable/process`, not `runProcess`.
- Decode `gh api` and `gh pr --json` responses with Effect Schema.
- Use typed errors for auth failure, missing CLI, command failure, output decode failure, unsupported reference, and provider mismatch.
- Keep stdout/stderr bounded.
- Avoid global mutable auth caches unless they are Effect `Cache` values with explicit keys, TTLs, and invalidation behavior.
- Parse provider rate-limit headers or CLI/API error payloads when available and map them to typed rate-limit errors.
- Keep GitHub nouns inside the GitHub driver; convert to `ChangeRequest` at the provider boundary.
## GitManager Cutover
Refactor `GitManager` so it coordinates three independent services:
- `VcsDriver` for local repository mechanics.
- `SourceControlProviderRegistry` for hosted provider selection.
- `TextGeneration` for message/body generation.
`GitManager` should stop depending directly on GitHub services. User-visible step labels should be provider-neutral unless the selected provider is known and the label is intentionally provider-specific.
The Commit + PR flow should become:
1. Resolve VCS repository and local status.
2. Resolve source-control provider from remotes.
3. Generate commit content through the existing text generation service.
4. Create local change through `VcsDriver`.
5. Push through `VcsDriver` or a narrow provider push helper only if the VCS requires provider-specific target syntax.
6. Generate change-request title/body.
7. Create the change request through `SourceControlProvider`.
## Cutover Policy
This phase should aggressively remove old GitHub-specific internals.
Rules:
- Move each active consumer directly to `SourceControlProviderRegistry` or a concrete provider test layer.
- Delete migrated `GitHubCli` methods, tests, and GitHub-specific helper exports in the same PR that moves their final consumer.
- Do not add compatibility export shims from `apps/server/src/git` to `apps/server/src/sourceControl`.
- Transitional modules are allowed only for a bounded `GitManager` slice that cannot move safely with the rest of the provider cutover.
- Every transitional module must have an owner comment, a removal checklist, and no public exports consumed by new code.
- Provider-neutral web parsing should replace GitHub-only parsing directly; do not keep parallel parser stacks unless a route still requires both during a single PR.
## GitLab and Azure Readiness
Use the triaged references as implementation inputs, not merge targets:
- GitLab PR #592 is useful for `glab mr` command mapping and JSON normalization.
- Azure issue #1138 defines a good first Azure slice: remote/URL detection and change-request thread setup for same-repo URLs.
The abstraction should let Phase 3 add:
- `GitLabSourceControlProvider` using `glab`.
- `AzureDevOpsSourceControlProvider` using `az repos pr` or REST APIs.
No provider should need to edit GitHub code to join the registry.
## T3 Review Design Constraint
Do not optimize only for creation/checkout. The provider layer must be able to support a future in-app review surface.
That means contracts should include stable IDs and enough metadata for:
- file-level diffs
- inline review threads
- resolved/unresolved state
- top-level discussion comments
- pending review submission
- provider URL back-links
Provider-specific fields can live in a metadata bag, but core review behavior should not require the UI to know whether the backing service is GitHub, GitLab, or Azure DevOps.
## Tests
Add tests at three levels:
- Pure parser tests for GitHub, GitLab, and Azure remote URLs and change-request references.
- Provider unit tests with fake `SourceControlProcess` output and schema decode failures.
- Integration-style GitHub CLI tests only where they can run hermetically or be skipped without hiding unit coverage.
Required cases:
- GitHub PR URL, number, and branch-ish references.
- GitLab MR URL/reference parsing.
- Azure DevOps PR URL parsing for same-repo URLs.
- unknown provider returns unsupported-operation errors.
- missing CLI and auth failures produce distinct typed errors.
- invalid CLI JSON fails at decode boundary with useful context.
## Migration Steps
1. Add `sourceControl` contracts and provider-neutral schemas.
2. Add shared remote/reference parser helpers and tests.
3. Add `SourceControlProcess` and provider errors.
4. Add provider registry with GitHub-only registration.
5. Implement `GitHubSourceControlProvider` from scratch against the new process layer.
6. Cut GitHub PR operations in `GitManager` over to the provider registry.
7. Replace web PR-reference parsing with provider-neutral parser output while keeping current GitHub UX.
8. Add provider cache metrics and tests for cache hit, stale refresh, invalidation, and rate-limit error mapping.
9. Delete the migrated `GitHubCli` implementation, tests, and GitHub-specific helper exports unless an explicit transitional checklist remains.
## Acceptance Criteria
- Existing GitHub Commit + PR and PR checkout flows still work.
- `GitManager` no longer imports or depends on `GitHubCli`.
- Active consumers use source-control provider APIs directly; any remaining transitional module has a written removal checklist and no compatibility export shim.
- Source-control contracts can represent GitHub PRs, GitLab MRs, and Azure DevOps PRs.
- Unknown/unsupported providers fail explicitly and visibly.
- GitHub command execution does not depend on `processRunner.ts`.
- Background provider reads are cached/coalesced and do not consume provider API quota on every status refresh.
- Rate-limit responses become typed errors with retry/reset metadata where available.
- The provider API includes the review operations needed by future T3 Review work, even if they are capability-gated.
- `bun fmt`, `bun lint`, and `bun typecheck` pass.
-2
View File
@@ -10,5 +10,3 @@
8. `08-precommit-format-and-lint.md`
9. `09-event-state-test-expansion.md`
10. `10-unify-process-session-abstraction.md`
19. `19-version-control-phase-1-vcs-driver-foundation.md`
20. `20-version-control-phase-2-source-control-provider-foundation.md`
-1
View File
@@ -1 +0,0 @@
alchemy/test/**
-137
View File
@@ -1,137 +0,0 @@
name: Deploy Website
on:
workflow_dispatch:
push:
branches:
- main
paths:
- "website/**"
- "packages/alchemy/**"
- "bun.lock"
- ".github/workflows/deploy.yml"
pull_request:
types:
- opened
- reopened
- synchronize
- closed
paths:
- "website/**"
- "packages/alchemy/**"
- "bun.lock"
- ".github/workflows/deploy.yml"
concurrency:
group: deploy-website-${{ github.ref }}
cancel-in-progress: false
env:
STAGE: ${{ github.event_name == 'pull_request' && format('pr-{0}',
github.event.number) || (github.ref == 'refs/heads/main' && 'prod' ||
github.ref_name) }}
jobs:
deploy:
if: ${{ github.event.action != 'closed' }}
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: write
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
# Mint a token for the alchemy-version-bot GitHub App so the PR
# preview comment (created via GitHub.Comment in alchemy.run.ts)
# posts under the bot's identity instead of `github-actions[bot]`.
# Same App as release.yml — its installation scopes already cover
# PR comments.
- name: Generate bot token
id: bot-token
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
with:
app-id: ${{ secrets.ALCHEMY_VERSION_BOT_ID }}
private-key: ${{ secrets.ALCHEMY_VERSION_BOT_PRIVATE_KEY }}
- name: Setup Bun
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
- name: Install dependencies
run: bun install
# Build the website ahead of `alchemy deploy`. The
# Cloudflare.StaticSite resource declares the same `bun run build`
# in its config and runs it as part of the create lifecycle, but
# on update plans alchemy reads `dist/` during plan.diff before
# the embedded Build resource gets a chance to (re)run, causing
# a NotFound on a fresh CI checkout. Building here makes the
# workflow correct under both create and update plans.
- name: Build website
working-directory: website
run: bun run build
- name: Deploy
working-directory: website
run: bun alchemy deploy --stage ${{ env.STAGE }} --yes
env:
# Alchemy's Cloudflare auth provider accepts either a scoped
# API token (CLOUDFLARE_API_TOKEN) or the legacy global API
# key paired with email (CLOUDFLARE_API_KEY +
# CLOUDFLARE_EMAIL). We use the latter here so CI matches
# the credentials in Doppler / .env, where only the admin
# global key is provisioned.
CLOUDFLARE_API_KEY: ${{ secrets.ADMIN_CLOUDFLARE_API_KEY }}
CLOUDFLARE_EMAIL: ${{ secrets.ADMIN_CLOUDFLARE_EMAIL }}
CLOUDFLARE_ACCOUNT_ID: ${{ env.STAGE == 'prod' &&
secrets.PROD_CLOUDFLARE_ACCOUNT_ID ||
secrets.TEST_CLOUDFLARE_ACCOUNT_ID }}
PULL_REQUEST: ${{ github.event.number }}
# On `pull_request` events GitHub Actions' built-in
# `GITHUB_SHA` is the synthetic merge commit (PR head merged
# into base) — that SHA never shows up in the PR's git log.
# `GITHUB_SHA` is also a reserved env var, so a step-level
# override is silently ignored. Pass the PR head SHA under
# a non-reserved name and read it from alchemy.run.ts.
BUILD_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
GITHUB_TOKEN: ${{ steps.bot-token.outputs.token }}
cleanup:
runs-on: ubuntu-latest
if:
${{ github.event_name == 'pull_request' && github.event.action == 'closed'
}}
permissions:
contents: read
pull-requests: write
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- name: Generate bot token
id: bot-token
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
with:
app-id: ${{ secrets.ALCHEMY_VERSION_BOT_ID }}
private-key: ${{ secrets.ALCHEMY_VERSION_BOT_PRIVATE_KEY }}
- name: Setup Bun
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
- name: Install dependencies
run: bun install
- name: Safety Check
run: |-
if [ "${{ env.STAGE }}" = "prod" ]; then
echo "ERROR: Cannot destroy prod environment in cleanup job"
exit 1
fi
- name: Destroy Preview Environment
working-directory: website
run: bun alchemy destroy --stage ${{ env.STAGE }} --yes
env:
CLOUDFLARE_API_KEY: ${{ secrets.ADMIN_CLOUDFLARE_API_KEY }}
CLOUDFLARE_EMAIL: ${{ secrets.ADMIN_CLOUDFLARE_EMAIL }}
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.TEST_CLOUDFLARE_ACCOUNT_ID }}
PULL_REQUEST: ${{ github.event.number }}
GITHUB_TOKEN: ${{ steps.bot-token.outputs.token }}
-180
View File
@@ -1,180 +0,0 @@
name: pr-package
# Publishes alchemy + better-auth + pr-package tarballs to the pr-package
# service at pkg.ing on every push to main and every PR sync. On PR close,
# deletes every tag we ever assigned for that PR so the underlying tarballs
# become orphaned and the bucket cleans them up.
on:
push:
branches: [main]
pull_request:
types: [opened, synchronize, reopened, closed]
permissions:
contents: read
pull-requests: write
env:
PR_PACKAGE_HOST: pkg.ing
NODE_VERSION: "24"
jobs:
# ── Publish on push-to-main and PR sync. ──────────────────────────────────
publish:
if: github.event_name == 'push' || (github.event_name == 'pull_request' &&
github.event.action != 'closed')
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
with:
node-version: ${{ env.NODE_VERSION }}
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
with:
bun-version: latest
- uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
with:
path: ~/.bun/install/cache
key: bun-${{ runner.os }}-${{ hashFiles('bun.lock') }}
restore-keys: |
bun-${{ runner.os }}-
- run: bun install
# Build everything: tsdown bundles alchemy (bin/ + cli lib) and tsc -b
# populates lib/ for the layer packages (better-auth, pr-package).
# Their tarballs ship both src/ and lib/, and consumers in non-bun
# runtimes resolve via the `import` condition → ./lib/index.js.
- run: bun run build:packages
- name: Compute tags
id: tags
env:
EVENT: ${{ github.event_name }}
# `head_ref` for PRs (source branch), `ref_name` for push (e.g. "main").
BRANCH: ${{ github.event_name == 'pull_request' && github.head_ref ||
github.ref_name }}
PR_NUMBER: ${{ github.event.pull_request.number }}
# PR builds run on the merge commit by default; tag the actual head sha
# so consumers can pin to a specific PR commit.
SHA: ${{ github.event_name == 'pull_request' &&
github.event.pull_request.head.sha || github.sha }}
run: |
set -euo pipefail
short="${SHA:0:7}"
long="$SHA"
tags=("$short" "$long" "$BRANCH")
if [ "$EVENT" = "pull_request" ]; then
tags+=("pr-${PR_NUMBER}")
fi
json=$(printf '%s\n' "${tags[@]}" | jq -R . | jq -s -c .)
echo "tags=$json" >> "$GITHUB_OUTPUT"
echo "short=$short" >> "$GITHUB_OUTPUT"
echo "Tags: $json"
# PR builds expire after 1 week; pushes to main omit the header and
# fall back to the worker's defaultTtl (3 weeks).
- name: Publish alchemy
env:
TOKEN: ${{ secrets.PR_PACKAGE_TOKEN }}
TAGS: ${{ steps.tags.outputs.tags }}
TTL: ${{ github.event_name == 'pull_request' && '1 week' || '' }}
working-directory: packages/alchemy
run: |
set -euo pipefail
rm -f *.tgz
bun pm pack --destination .
tgz=$(ls *.tgz)
echo "Publishing $tgz with tags $TAGS ttl=${TTL:-default}"
curl -fsSL --show-error -X PUT \
"https://${PR_PACKAGE_HOST}/projects/alchemy/packages" \
-H "Authorization: Bearer ${TOKEN}" \
-H "X-Tags: ${TAGS}" \
${TTL:+-H "X-TTL: ${TTL}"} \
-H "Content-Type: application/gzip" \
--data-binary "@${tgz}"
- name: Publish better-auth
env:
TOKEN: ${{ secrets.PR_PACKAGE_TOKEN }}
TAGS: ${{ steps.tags.outputs.tags }}
TTL: ${{ github.event_name == 'pull_request' && '1 week' || '' }}
working-directory: packages/better-auth
run: |
set -euo pipefail
rm -f *.tgz
bun pm pack --destination .
tgz=$(ls *.tgz)
echo "Publishing $tgz with tags $TAGS ttl=${TTL:-default}"
curl -fsSL --show-error -X PUT \
"https://${PR_PACKAGE_HOST}/projects/@alchemy.run/better-auth/packages" \
-H "Authorization: Bearer ${TOKEN}" \
-H "X-Tags: ${TAGS}" \
${TTL:+-H "X-TTL: ${TTL}"} \
-H "Content-Type: application/gzip" \
--data-binary "@${tgz}"
- name: Publish pr-package
env:
TOKEN: ${{ secrets.PR_PACKAGE_TOKEN }}
TAGS: ${{ steps.tags.outputs.tags }}
TTL: ${{ github.event_name == 'pull_request' && '1 week' || '' }}
working-directory: packages/pr-package
run: |
set -euo pipefail
rm -f *.tgz
bun pm pack --destination .
tgz=$(ls *.tgz)
echo "Publishing $tgz with tags $TAGS ttl=${TTL:-default}"
curl -fsSL --show-error -X PUT \
"https://${PR_PACKAGE_HOST}/projects/@alchemy.run/pr-package/packages" \
-H "Authorization: Bearer ${TOKEN}" \
-H "X-Tags: ${TAGS}" \
${TTL:+-H "X-TTL: ${TTL}"} \
-H "Content-Type: application/gzip" \
--data-binary "@${tgz}"
# PR-only: leave a sticky comment with the install URLs pinned to this
# commit. Uses pkg.ing (the canonical short host), which serves both
# the pretty alias paths and the underlying /projects/:project/tags/:tag
# API directly.
- name: Generate bot token
if: github.event_name == 'pull_request'
id: bot-token
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
with:
app-id: ${{ secrets.ALCHEMY_VERSION_BOT_ID }}
private-key: ${{ secrets.ALCHEMY_VERSION_BOT_PRIVATE_KEY }}
- name: Comment on PR
if: github.event_name == 'pull_request'
env:
GH_TOKEN: ${{ steps.bot-token.outputs.token }}
REPO: ${{ github.repository }}
PR_NUMBER: ${{ github.event.pull_request.number }}
SHORT_SHA: ${{ steps.tags.outputs.short }}
run: |
set -euo pipefail
MARKER="<!-- pr-package-comment -->"
# Use `bun add <name>@<url>` instead of `bun add <url>`. Without an
# explicit name, bun's resolver hits a DependencyLoop bug when the
# consumer already has the same package name resolved from npm
# (oven-sh/bun#5789, oven-sh/bun#17946). The aliased form bypasses
# the buggy reconciliation path and works on fresh and existing
# projects alike.
BODY=$(printf '%s\n\nInstall the packages built from this commit:\n\n**alchemy**\n```sh\nbun add alchemy@https://pkg.ing/alchemy/%s\n```\n\n**@alchemy.run/better-auth**\n```sh\nbun add @alchemy.run/better-auth@https://pkg.ing/@alchemy.run/better-auth/%s\n```\n\n**@alchemy.run/pr-package**\n```sh\nbun add @alchemy.run/pr-package@https://pkg.ing/@alchemy.run/pr-package/%s\n```\n' "$MARKER" "$SHORT_SHA" "$SHORT_SHA" "$SHORT_SHA")
existing=$(gh api --paginate \
"repos/${REPO}/issues/${PR_NUMBER}/comments" \
--jq ".[] | select(.user.login == \"alchemy-version-bot[bot]\") | select(.body | startswith(\"${MARKER}\")) | .id" \
| head -1)
if [ -n "$existing" ]; then
gh api -X PATCH "repos/${REPO}/issues/comments/${existing}" -f body="$BODY"
else
gh api -X POST "repos/${REPO}/issues/${PR_NUMBER}/comments" -f body="$BODY"
fi
-432
View File
@@ -1,432 +0,0 @@
name: Release NPM Package
on:
workflow_dispatch:
inputs:
channel:
description: "Release channel"
required: true
type: choice
default: beta
options:
- release
- beta
- alpha
- tag
spec:
description: >-
Channel-specific value. tag: REQUIRED, the explicit full version (e.g.
2.0.0-experimental.1). release: REQUIRED, patch|minor|major or an
explicit x.y.z. beta|alpha: optional, an integer N to force
2.0.0-<channel>.N; leave blank to auto-increment.
required: false
type: string
permissions:
contents: write
id-token: write
env:
NODE_VERSION: "24"
# Files produced by the bump job and consumed by every publish job + the
# final commit job. Listed once here so additions stay in sync.
BUMP_ARTIFACT_PATHS: |
packages/alchemy/lib
packages/alchemy/bin
packages/alchemy/package.json
packages/better-auth/package.json
packages/better-auth/lib
packages/pr-package/package.json
packages/pr-package/lib
bun.lock
jobs:
# ── Step 1: Compute the next version and stage the bump in-memory. ──
# No git commit: we want a failed publish to leave no orphan commit
# behind. The staged files ride to the publish jobs (and the final commit
# job) as an artifact.
bump:
runs-on: ubuntu-latest
outputs:
version: ${{ steps.bump.outputs.version }}
channel: ${{ inputs.channel }}
sha: ${{ steps.sha.outputs.sha }}
steps:
- name: Validate inputs
env:
CHANNEL: ${{ inputs.channel }}
SPEC: ${{ inputs.spec }}
run: |
case "$CHANNEL" in
tag)
if [ -z "$SPEC" ]; then
echo "::error::'tag' channel requires an explicit version in 'spec' (e.g. 2.0.0-experimental.1)"
exit 1
fi
;;
release)
if [ -z "$SPEC" ]; then
echo "::error::'release' channel requires a 'spec' (patch|minor|major|x.y.z)"
exit 1
fi
;;
esac
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
ref: ${{ github.ref }}
fetch-depth: 0
- id: sha
run: echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
with:
registry-url: https://registry.npmjs.org/
node-version: ${{ env.NODE_VERSION }}
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
with:
bun-version: latest
- uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
with:
path: ~/.bun/install/cache
key: bun-${{ runner.os }}-${{ hashFiles('bun.lock') }}
restore-keys: |
bun-${{ runner.os }}-
- run: bun install
- id: bump
env:
CHANNEL: ${{ inputs.channel }}
SPEC: ${{ inputs.spec }}
run: |
if [ -n "$SPEC" ]; then
VERSION=$(bun ./scripts/release/bump.ts "$CHANNEL" "$SPEC")
else
VERSION=$(bun ./scripts/release/bump.ts "$CHANNEL")
fi
echo "Resolved version: $VERSION (channel: $CHANNEL)"
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
# Build everything once, up front, against the bumped versions. Outputs
# ride to every publish job as the `build-output` artifact so we don't
# rebuild three times in parallel.
- run: bun run build:packages
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: bump-files
path: ${{ env.BUMP_ARTIFACT_PATHS }}
if-no-files-found: error
retention-days: 7
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: build-output
path: |
packages/*/lib
packages/*/bin
if-no-files-found: error
retention-days: 7
include-hidden-files: true
# ── Step 2: Commit (bump + changelog) and tag BEFORE publishing.
# Committing first means the publishable source of truth is the tagged
# commit; publish jobs check it out by SHA. Durability: if a previous
# attempt already committed and tagged but failed during npm publish, the
# bump job's HEAD-tag detection reuses the existing version, and this job
# detects HEAD is already at the tag and skips the commit/push.
# Skipped for `tag` channel — those releases are intentionally uncommitted.
commit-and-tag:
needs: bump
if: inputs.channel != 'tag'
runs-on: ubuntu-latest
outputs:
sha: ${{ steps.commit.outputs.sha }}
steps:
- name: Generate bot token
id: bot-token
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
with:
app-id: ${{ secrets.ALCHEMY_VERSION_BOT_ID }}
private-key: ${{ secrets.ALCHEMY_VERSION_BOT_PRIVATE_KEY }}
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
ref: ${{ github.ref }}
fetch-depth: 0
token: ${{ steps.bot-token.outputs.token }}
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
with:
node-version: ${{ env.NODE_VERSION }}
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
with:
bun-version: latest
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
name: bump-files
- uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
with:
path: ~/.bun/install/cache
key: bun-${{ runner.os }}-${{ hashFiles('bun.lock') }}
restore-keys: |
bun-${{ runner.os }}-
- run: bun install
- name: Configure git
run: |
git config user.email "alchemy-version-bot[bot]@users.noreply.github.com"
git config user.name "alchemy-version-bot[bot]"
- id: commit
name: Commit bump + changelog, tag, push
env:
VERSION: ${{ needs.bump.outputs.version }}
run: |
set -euo pipefail
TAG="v${VERSION}"
# Durability: if HEAD already points at the release tag (resumed
# run after a previous attempt committed+tagged but publish
# failed), there is nothing to do. Use HEAD as the publish SHA.
HEAD_TAG=$(git describe --exact-match --tags HEAD 2>/dev/null || true)
if [ "$HEAD_TAG" = "$TAG" ]; then
echo "HEAD is already at ${TAG}; skipping commit/tag/push"
SHA=$(git rev-parse HEAD)
echo "sha=${SHA}" >> "$GITHUB_OUTPUT"
exit 0
fi
# Generate release notes; release-notes.ts is idempotent and
# bails out if the tag heading is already present in CHANGELOG.md.
bun scripts/release/release-notes.ts "${TAG}"
# Stage bump files (overwritten by the downloaded artifact) and
# the new changelog entry as a single commit.
git add packages/alchemy/package.json \
packages/better-auth/package.json \
packages/pr-package/package.json \
bun.lock \
CHANGELOG.md
if git diff --cached --quiet; then
echo "No changes to commit (already on a release commit?)"
else
git commit -m "chore(release): ${VERSION}"
fi
if ! git rev-parse --verify "refs/tags/${TAG}" >/dev/null 2>&1; then
git tag -a "${TAG}" -m "Release ${TAG}"
fi
git push origin HEAD
if git ls-remote --exit-code --tags origin "refs/tags/${TAG}" >/dev/null 2>&1; then
echo "Tag ${TAG} already on remote, skipping tag push"
else
git push origin "refs/tags/${TAG}"
fi
SHA=$(git rev-parse HEAD)
echo "sha=${SHA}" >> "$GITHUB_OUTPUT"
# ── Step 3a: Build and publish `alchemy`. ──
# For non-tag channels, checkout the just-committed tagged SHA; for the
# `tag` channel (no commit), checkout the bump's pre-bump SHA and rely
# on the bump-files artifact instead.
publish-alchemy:
needs: [bump, commit-and-tag]
if:
always() && needs.bump.result == 'success' && (needs.commit-and-tag.result
== 'success' || needs.commit-and-tag.result == 'skipped')
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
ref: ${{ needs.commit-and-tag.outputs.sha || needs.bump.outputs.sha }}
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
with:
registry-url: https://registry.npmjs.org/
node-version: ${{ env.NODE_VERSION }}
- name: Upgrade npm for OIDC trusted publishing
run: |
npm install -g npm@latest && npm --version
sed -i '/always-auth/d' ~/.npmrc 2>/dev/null || true
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
with:
bun-version: latest
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
name: bump-files
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
name: build-output
- uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
with:
path: ~/.bun/install/cache
key: bun-${{ runner.os }}-${{ hashFiles('bun.lock') }}
restore-keys: |
bun-${{ runner.os }}-
- run: bun install
- run: bun scripts/release/publish-package.ts packages/alchemy ${{
needs.bump.outputs.channel }}
# ── Step 3b: Build and publish `@alchemy.run/better-auth`. ──
publish-better-auth:
needs: [bump, commit-and-tag, publish-alchemy]
if:
always() && needs.bump.result == 'success' && (needs.commit-and-tag.result
== 'success' || needs.commit-and-tag.result == 'skipped') &&
needs.publish-alchemy.result == 'success'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
ref: ${{ needs.commit-and-tag.outputs.sha || needs.bump.outputs.sha }}
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
with:
registry-url: https://registry.npmjs.org/
node-version: ${{ env.NODE_VERSION }}
- name: Upgrade npm for OIDC trusted publishing
run: |
npm install -g npm@latest && npm --version
sed -i '/always-auth/d' ~/.npmrc 2>/dev/null || true
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
with:
bun-version: latest
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
name: bump-files
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
name: build-output
- uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
with:
path: ~/.bun/install/cache
key: bun-${{ runner.os }}-${{ hashFiles('bun.lock') }}
restore-keys: |
bun-${{ runner.os }}-
- run: bun install
- run: bun scripts/release/publish-package.ts packages/better-auth ${{
needs.bump.outputs.channel }}
# ── Step 3c: Build and publish `@alchemy.run/pr-package`. ──
publish-pr-package:
needs: [bump, commit-and-tag, publish-alchemy]
if:
always() && needs.bump.result == 'success' && (needs.commit-and-tag.result
== 'success' || needs.commit-and-tag.result == 'skipped') &&
needs.publish-alchemy.result == 'success'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
ref: ${{ needs.commit-and-tag.outputs.sha || needs.bump.outputs.sha }}
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
with:
registry-url: https://registry.npmjs.org/
node-version: ${{ env.NODE_VERSION }}
- name: Upgrade npm for OIDC trusted publishing
run: |
npm install -g npm@latest && npm --version
sed -i '/always-auth/d' ~/.npmrc 2>/dev/null || true
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
with:
bun-version: latest
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
name: bump-files
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
name: build-output
- uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
with:
path: ~/.bun/install/cache
key: bun-${{ runner.os }}-${{ hashFiles('bun.lock') }}
restore-keys: |
bun-${{ runner.os }}-
- run: bun install
- run: bun scripts/release/publish-package.ts packages/pr-package ${{
needs.bump.outputs.channel }}
# ── Step 4: Create GitHub Release and notify Discord. ──
# Runs only after every publish job succeeded. The bump+changelog commit
# and tag were already pushed by `commit-and-tag` before publishing.
finalize:
needs:
[
bump,
commit-and-tag,
publish-alchemy,
publish-better-auth,
publish-pr-package,
]
if: inputs.channel != 'tag'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
ref: ${{ needs.commit-and-tag.outputs.sha }}
fetch-depth: 0
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
with:
node-version: ${{ env.NODE_VERSION }}
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
with:
bun-version: latest
- uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
with:
path: ~/.bun/install/cache
key: bun-${{ runner.os }}-${{ hashFiles('bun.lock') }}
restore-keys: |
bun-${{ runner.os }}-
- run: bun install
- name: Create GitHub Release
env:
VERSION: ${{ needs.bump.outputs.version }}
CHANNEL: ${{ needs.bump.outputs.channel }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: bun scripts/release/github-release.ts "v${VERSION}" "${CHANNEL}"
- name: Notify Discord
if: success() && env.DISCORD_WEBHOOK != ''
env:
DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK_URL }}
VERSION: ${{ needs.bump.outputs.version }}
CHANNEL: ${{ needs.bump.outputs.channel }}
run: bun scripts/release/discord-notify.ts "v${VERSION}" "${CHANNEL}"
-93
View File
@@ -1,93 +0,0 @@
name: test
# Smoke-tests `alchemy destroy → deploy → destroy` against each example.
# `bun test:canary` drives the whole suite — it iterates both bun and pnpm
# runtimes itself and publishes canary tarballs to pkg.ing before deploying.
on:
# TODO(sam): re-enable these when they are running reliably and not polluting our account
# push:
# branches: [main]
# pull_request:
# types: [opened, reopened, synchronize]
workflow_dispatch:
permissions:
contents: read
# Required for aws-actions/configure-aws-credentials to mint a session
# via OIDC instead of long-lived AWS_ACCESS_KEY_ID secrets.
id-token: write
env:
PKGING_HOST: pkg.ing
NODE_VERSION: "24"
# PR runs use `pr-<n>` so each PR has its own isolated cloud namespace;
# main pushes use `main`; manual `workflow_dispatch` runs use the branch
# name. Forwarded to the smoke test as $SMOKE_STAGE.
SMOKE_STAGE: ${{ github.event_name == 'pull_request' && format('pr-{0}',
github.event.number) || (github.ref == 'refs/heads/main' && 'main' ||
github.ref_name) }}
concurrency:
# Cancel an in-progress run for the same PR (or branch) when a new push
# arrives — the smoke suite mutates real cloud state, so two parallel
# runs against the same SMOKE_STAGE would race.
group: test-${{ github.ref }}
cancel-in-progress: true
jobs:
smoke:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
with:
node-version: ${{ env.NODE_VERSION }}
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
with:
bun-version: latest
- uses: pnpm/action-setup@0e279bb959325dab635dd2c09392533439d90093 # v6.0.8
with:
version: latest
- uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
with:
path: ~/.bun/install/cache
key: bun-${{ runner.os }}-${{ hashFiles('bun.lock') }}
restore-keys: bun-${{ runner.os }}-
# Bootstrap install so `bun test:canary` itself can resolve. The
# test then runs its own `bun install` + `pnpm install` in canary
# `beforeAll` after rewriting the catalog to pkg.ing tarballs, so
# there's nothing pnpm-specific to wire up here.
- run: bun install
# OIDC → short-lived AWS session. Exports AWS_ACCESS_KEY_ID,
# AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN, AWS_REGION; the
# `output-credentials: true` flag also surfaces aws-account-id as a
# step output (which we forward as `AWS_ACCOUNT_ID` below — the
# action does NOT set it as an env var on its own).
- id: aws-creds
uses: aws-actions/configure-aws-credentials@d979d5b3a71173a29b74b5b88418bfda9437d885 # v6.1.1
with:
role-to-assume: ${{ vars.AWS_ROLE_ARN }}
aws-region: ${{ vars.AWS_REGION }}
output-credentials: true
- name: Smoke
env:
# AWS — `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`,
# `AWS_SESSION_TOKEN`, `AWS_REGION` are already exported by
# configure-aws-credentials; we only need to forward the account
# id, which Alchemy's `loadFromEnv` requires when CI=true.
AWS_ACCOUNT_ID: ${{ steps.aws-creds.outputs.aws-account-id }}
CLOUDFLARE_API_TOKEN: ${{ secrets.TEST_CLOUDFLARE_API_TOKEN }}
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.TEST_CLOUDFLARE_ACCOUNT_ID }}
NEON_API_KEY: ${{ secrets.NEON_API_KEY }}
PR_PACKAGE_TOKEN: ${{ secrets.PR_PACKAGE_TOKEN }}
PKGING_HOST: ${{ env.PKGING_HOST }}
SMOKE_STAGE: ${{ env.SMOKE_STAGE }}
run: bun test:canary
-48
View File
@@ -1,48 +0,0 @@
node_modules/
dist/
/lib/
/alchemy/lib/
.out/
.test/
.DS_Store
.env
*.tsbuildinfo
.claude/
.alchemy/
# !.alchemy/github:alchemy/
# examples/*/.alchemy
.repomix-output.txt
wrangler.jsonc
# Husky - ignore generated files but keep hooks
.husky/_
!.husky/pre-commit
.smoke
.smoke.logs
smoke
# Generated by test/smoke.test.ts to make pnpm 11's deps-status check
# resolve the bun catalog. Cleaned up at end of suite.
pnpm-workspace.yaml
.svelte-kit
.astro
.wrangler
*.tgz
*.js
*.d.ts
*.map
.attest
.cache
.external
.bundle-benchmark
packages/alchemy/docs
.sonda
examples/cloudflare-worker/src/scratch.ts
!/packages/alchemy/bin/cli.js
.vendor/*
.tmp
pnpm-lock.yaml
-3
View File
@@ -1,3 +0,0 @@
[submodule "vendor/alchemy"]
path = .vendor/alchemy
url = [email protected]:alchemy-run/alchemy.git
-2
View File
@@ -1,2 +0,0 @@
bun format
git update-index --again
-1
View File
@@ -1 +0,0 @@
# see: https://opencode.ai/docs/tools/#ignore-patterns
-22
View File
@@ -1,22 +0,0 @@
{
"semi": true,
"singleQuote": false,
"tabWidth": 2,
"useTabs": false,
"printWidth": 80,
"endOfLine": "lf",
"ternaries": true,
"experimental_sort_imports": {
"order": "asc"
},
"ignorePatterns": [
"dist/**",
"*.min.js",
"**/lib/**",
"**/mdx/**",
"**/*.mdx",
"**/*.md",
"**/.vendor/**",
"**/package.json"
]
}
-8
View File
@@ -1,8 +0,0 @@
{
"$schema": "./node_modules/oxfmt/configuration_schema.json",
"rules": {
"no-misused-new": "off",
"require-yield": "off",
"no-non-null-asserted-optional-chain": "off"
}
}
Submodule .repos/alchemy-effect/.vendor/alchemy deleted from c9f5e549cf.
-65
View File
@@ -1,65 +0,0 @@
{
"diffEditor.renderSideBySide": false,
"js/ts.experimental.useTsgo": true,
"typescript.experimental.useTsgo": true,
"typescript.tsdk": "node_modules/@typescript/native-preview/lib",
"typescript.native-preview.tsdk": "node_modules/@typescript/native-preview/lib",
"typescript.enablePromptUseWorkspaceTsdk": true,
"typescript.preferences.importModuleSpecifier": "relative",
"typescript.preferences.importModuleSpecifierEnding": "js",
"oxc.enable": true,
"oxc.lint.run": "onSave",
"json.schemaDownload.enable": true,
"editor.defaultFormatter": "oxc.oxc-vscode",
"editor.codeLens": false,
"editor.formatOnSave": true,
"editor.formatOnSaveMode": "file",
"editor.inlayHints.enabled": "offUnlessPressed",
"editor.tabSize": 2,
"editor.indentSize": 2,
"editor.insertSpaces": true,
"editor.codeActionsOnSave": {
"source.fixAll": "explicit",
"source.organizeImports": "explicit"
},
"[toml]": {
"editor.defaultFormatter": "tamasfe.even-better-toml"
},
"[json]": {
"editor.defaultFormatter": "vscode.json-language-features"
},
"[jsonc]": {
"editor.defaultFormatter": "vscode.json-language-features"
},
"[markdown]": {
"editor.formatOnSave": false,
"editor.defaultFormatter": null
},
"[mdx]": {
"editor.defaultFormatter": null,
"editor.formatOnSave": false
},
"files.exclude": {
"**/__pycache__": true,
"**/*.pyc": true,
"packages/alchemy/bin/**/*.js*": true,
"packages/alchemy/bin/**/*.d*": true
},
"[typescript]": {
"editor.indentSize": 2,
"editor.defaultFormatter": "oxc.oxc-vscode"
},
"[javascript]": {
"editor.indentSize": 2,
"editor.defaultFormatter": "oxc.oxc-vscode"
},
"[typescriptreact]": {
"editor.indentSize": 2,
"editor.defaultFormatter": "oxc.oxc-vscode"
},
"[javascriptreact]": {
"editor.indentSize": 2,
"editor.defaultFormatter": "oxc.oxc-vscode"
},
"oxc.enable.oxfmt": true
}
-854
View File
@@ -1,854 +0,0 @@
# alchemy
Alchemy Effect is an Infrastructure-as-Effects (IaE) framework that extends Infrastructure-as-Code (IaC) by combining business logic and infrastructure config into a single, type-safe program expressed as Effects.
It includes a core IaC engine built with Effect. Effect provides the foundation for type-safe, composable, and testable infrastructure programs. It brings errors into the type-system and provides declarative/composable retry logic that ensure proper and reliable handling of failures.
# Concepts
- **Cloud Provider** - a cloud provider that offers a set of Services, e.g. AWS, Azure, GCP, Cloudflare, Stripe, Planetscale, Neon, etc.
- **Service** - a collection of Resources, Functions, and Bindings offered by a Cloud Provider.
- **Resource** - a named entity that is configuted with "Input Properties" and produces "Output Attributes". May or may not have Binding Contract.
- **Input Properties** - the properties passed as input to configure a Resource. Otherwise known as the "desired state" of the Resource.
- **Output Attributes** - the attributes produced by a Resource. Otherwise known as the "current state" of the Resource.
- **Stable Properties** - properties that are not affected by an Update, e.g. the ID or ARN of a Resource.
- **Function** (aka. **Runtime**) - a special kind of Resource that includes a runtime implementation expressed as a Function producing an `Effect<A, Err, Req>`. The `Req` type captures runtime dependencies, from which Infrastructure Dependencies are inferred.
- **Resource Provider** (see [Provider](./packages/alchemy/src/Provider.ts))
A Resource Provider implements the following Lifecycle Operations:
- **Diff** - compares new props with old props and determines if the Resource needs to be updated or replaced. For updates, it can also specify a list of Stable Properties that will not be changed by the update.
- **Read** - reads the current state of a Resource and returns the current Output Attributes. May return `Unowned(attrs)` to signal an existing-but-foreign resource that the engine should refuse to take over unless `--adopt` is set.
- **Pre-Create** - an optional operation that creates a stub of a Resource before reconcile runs. Used to resolve circular dependencies — e.g. Function A and B depend on each other, so we create a stub of Function A first and then `reconcile` later wires up the real dependency.
- **Reconcile** - converges a Resource's actual cloud state to the desired state described by the new Input Properties. Called for both first-time provisioning and subsequent updates. The provider receives `output` (current Attributes) and `olds` (previous Props) which may both be `undefined` on a greenfield create, both defined on an update, or `output !== undefined && olds === undefined` on an adoption. See the **Reconciler doctrine** section below for the required shape.
- **Delete** - deletes an existing Resource. It must be designed as idempotent because it is always possible for state persistence to fail after the delete operation is called. If the resource doesn't exist during deletion, it should not be considered an error.
- **Capability** - a runtime requirement of a Function (e.g. require `SQS.SendMessage` on a `SQS.Queue`). Each Capability is split into two parts: a `Binding.Service` (runtime SDK wrapper) and a `Binding.Policy` (deploy-time IAM/binding attachment).
- **Binding.Service** - an Effect Service that wraps an SDK client and exposes a `.bind(resource)` method returning a typed callable for runtime use. Provided as a Layer on the **Function** Effect so it gets bundled into the Lambda/Worker. See [Binding](./packages/alchemy/src/Binding.ts).
- **Binding.Policy** - an Effect Service that runs only at deploy time to attach IAM policies (AWS) or bindings (Cloudflare) to a Function's role/config. At runtime, `Binding.Policy` uses `Effect.serviceOption` so it gracefully becomes a no-op when the layer is not provided. Policy layers are provided on the **Stack** via `AWS.providers()()`, not on the Function.
- **Binding** - data attached to a Resource via `resource.bind(data)`. A Binding is a `{ context: PolicyContext, data: BindingData }` tuple that is collected on the Stack during plan/deploy. Bindings enable circular references between Resources — the `Binding.Policy` calls `ctx.bind({ policyStatements: [...] })` on the target Function, which records the binding data on the Stack. The Resource Provider then receives the resolved binding data in its `reconcile` lifecycle operation via the `bindings` parameter.
- **Binding Contract** - the shape of data a Resource accepts from Bindings. For example, a Lambda Function accepts `{ env?: Record<string, any>, policyStatements?: PolicyStatement[] }` because it needs environment variables and IAM policies. A Cloudflare Worker accepts `{ bindings: Worker.Binding[] }` for its native binding system. The Binding Contract is declared as the fourth type parameter on the `Resource` interface. See [Lambda Function](./packages/alchemy/src/AWS/Lambda/Function.ts) and [Cloudflare Worker](./packages/alchemy/src/Cloudflare/Workers/Worker.ts).
- **Dependency** - Resources depend on other Resources through two mechanisms:
- Output Properties of one Resource passed as Input Properties to another Resource (non-circular, directed acyclic graph)
- Bindings that attach data (IAM policies, env vars, Cloudflare bindings) from one Resource to another, enabling circular references between Resources.
- **Output** - a reference to (or derived from) a Resource's "Output Attributes". E.g. Bucket.bucketArn
- **Stack** - a collection of Resources, Functions, and Bindings that are deployed together.
- **Stack Name** - the name of a Stack, e.g. `my-stack`
- **Stage** - the stage of a Stack, e.g. `dev`, `prod`, `dev-sam`
- **Stack Instance** - a deployed instance of a Stack+Stage
- **Resource Type** - the type of a Resource, e.g. `Bucket`, `Instance`
- **Physical Name** - a unique name for a Resource, e.g. `my-bucket-1234567890`. It is usually best to generate them using the built-in createPhysicalName utility function which generates
- **Logical ID** - the logical ID identifying a resource within a Stack, e.g. `my-bucket`. It is stable across creates, updates, deletes and replaces.
- **Instance ID** - a unique identifier for an instance of a Resource. It is stable across creates, updates and deletes. It changes when a resource is replaced. It is truncated and used as the suffix of the Physical Name.
- **Event Source** - a special kind of Binding between a Function and a Resource that produces events that invoke the Function, e.g. `SQS.QueueEventSource`. Event Sources are implemented as Binding.Service + Binding.Policy pairs, where the attach logic creates/updates the event source mapping via the cloud provider API.
- **Replacement** - the process of replacing a Resource with a new one. A new one is created, downstream dependencies are updated with the new reference, and then the old one is deleted. Or, the old one is deleted first and then the new one is created.
- **Dependency Violation** - an error that some APIs call when an operation cannot be performed because a dependency is not met. E.g. you cannot delete an EIP until the NAT Gateway it is attached to is deleted. Lifecycle operations typically retry Dependency Violations.
- **Eventual Consistency** - create/update/delete operations can be eventually consistent leading to a variety of failure modes. For example, a Resource may be created but not yet available for use, or a Resource may be deleted but still appear in the console. Errors caused by eventual consistency should be retried, and lifecycle operations/tests should be carefully designed to wait for consistency before proceeding.
- **Retryable Error** - an error that can be retried. E.g. a Dependency Violation, Eventual Consistency Error, Transient Failure, etc.
- **Non-Retryable Error** - an error that cannot be retried. E.g. a Validation Error, Authorization Error, etc.
- **Retry Policy** - a policy for retrying errors. E.g. a fixed delay, exponential backoff, max retries, while some condition is true, or until some condition is true/false, etc.
# File System Conventions
Each Service's Resources follow the same pattern. Resource contract and provider are co-located in the same file. Capabilities (Binding.Service + Binding.Policy) are in separate files named after the capability.
```sh
# source files
packages/alchemy/src/{Cloud}/{Service}/index.ts # re-exports all resources and capabilities
packages/alchemy/src/{Cloud}/{Service}/{Resource}.ts # resource contract + resource provider
packages/alchemy/src/{Cloud}/{Service}/{Capability}.ts # Binding.Service + Binding.Policy for a capability
# test files
packages/alchemy/test/{Cloud}/{Service}/{Resource}.test.ts
# docs (auto-generated from source-code JSDoc - DO NOT manually edit)
website/src/content/docs/providers/{Cloud}/{Resource}.md # API reference, generated by `bun generate:api-reference`
```
Examples of actual paths:
```sh
packages/alchemy/src/AWS/S3/Bucket.ts # S3 Bucket resource + provider
packages/alchemy/src/AWS/S3/GetObject.ts # S3 GetObject Binding.Service + Binding.Policy
packages/alchemy/src/AWS/S3/PutObject.ts # S3 PutObject Binding.Service + Binding.Policy
packages/alchemy/src/AWS/SQS/Queue.ts # SQS Queue resource + provider
packages/alchemy/src/AWS/SQS/SendMessage.ts # SQS SendMessage capability
packages/alchemy/src/AWS/Kinesis/Stream.ts # Kinesis Stream resource + provider
packages/alchemy/src/AWS/Kinesis/PutRecord.ts # Kinesis PutRecord capability
packages/alchemy/src/AWS/Lambda/Function.ts # Lambda Function resource + provider
packages/alchemy/src/AWS/DynamoDB/Table.ts # DynamoDB Table resource + provider
packages/alchemy/src/AWS/DynamoDB/GetItem.ts # DynamoDB GetItem capability
packages/alchemy/src/AWS/EC2/Vpc.ts # VPC resource + provider
packages/alchemy/src/AWS/EC2/Subnet.ts # Subnet resource + provider
```
# Documentation Generation
**Source of truth:** The source code is the single source of truth for all API documentation. JSDoc comments in `packages/alchemy/src/**/*.ts` are extracted and used to generate the public API reference markdown.
:::warning
**Never edit the generated markdown files** under `website/src/content/docs/providers/{Cloud}/`. They are overwritten on every regeneration.
To "update the docs", edit the JSDoc on the source `.ts` file (resource-level JSDoc on the exported `const`, plus field-level JSDoc on each prop/attribute) and re-run the generator. There is no separate doc file to update.
:::
**How to generate docs:**
```sh
bun generate:api-reference # -> website/src/content/docs/providers/{Cloud}/{Resource}.md
```
This is the only doc generator that produces user-facing output. ([scripts/generate-api-reference.ts](./scripts/generate-api-reference.ts)) does the following:
1. Discovers resource files in `packages/alchemy/src/{Cloud}/{Service}/`
2. Parses TypeScript with `ts-morph`
3. Extracts the resource-level summary plus `@section` / `@example` blocks from JSDoc
4. Writes one markdown file per resource at `website/src/content/docs/providers/{Cloud}/{Resource}.md`
After editing JSDoc on a resource, run `bun generate:api-reference` to refresh the website docs.
**Writing good documentation:** When adding or updating a resource, ensure all Props and Attrs have JSDoc comments:
```typescript
export interface BucketProps {
/**
* Name of the bucket. If omitted, a unique name will be generated.
* Must be lowercase and between 3-63 characters.
*/
bucketName?: string;
/**
* Whether to delete all objects when the bucket is destroyed.
* @default false
*/
forceDestroy?: boolean;
}
```
The `@default` tag is used to document default values and will appear in the generated documentation.
### Examples and Sections (IMPORTANT)
**Examples are critical for documentation.** Every resource should have examples demonstrating common use cases. Use `@section` and `@example` JSDoc tags on the main Resource export to organize examples into a navigable table of contents.
**Format:**
- `@section <Section Title>` - Creates a heading in the Examples section and adds an entry to the Quick Reference table of contents
- `@example <Example Title>` - Creates a subheading for a specific code example (must follow a `@section`)
- Code blocks inside examples use standard markdown fenced code blocks (` `)
**Example:**
````typescript
/**
* An S3 bucket for storing objects.
*
* @section Creating a Bucket
* @example Basic Bucket
* ```typescript
* const bucket = yield* Bucket("my-bucket", {});
* ```
*
* @example Bucket with Force Destroy
* ```typescript
* const bucket = yield* Bucket("my-bucket", {
* forceDestroy: true,
* });
* ```
*
* @section Reading Objects
* @example Get Object from Bucket
* ```typescript
* const response = yield* getObject(bucket, { key: "my-key" });
* const body = yield* Effect.tryPromise(() => response.Body?.transformToString());
* ```
*
* @section Writing Objects
* @example Put Object to Bucket
* ```typescript
* yield* putObject(bucket, {
* key: "hello.txt",
* body: "Hello, World!",
* contentType: "text/plain",
* });
* ```
*/
export const Bucket = Resource<...>("AWS.S3.Bucket");
````
This generates:
1. A "Quick Reference" section with links to each `@section`
2. An "Examples" section with organized code examples under each section heading
**Best practices for examples:**
- Start with the simplest use case and progress to more complex ones
- Include examples for all major capabilities (GetObject, PutObject, etc.)
- Show real-world patterns like error handling, combining with other resources
- Use descriptive titles that explain what the example demonstrates
# Workflow
Development of Alchemy-Effect Resources is heavily pattern based. Each Service has many Resources that each have 0 oor more Capabilities and Event Sources. When working on a new Service, the following steps should be followed.
1. Research the AWS Service and identify its Resources, Identifier Types, Structs, Capabilities, and Event Sources. Refer to the corresponding Terraform Provider, Pulumi Provider, and CloudFormation docs for that service (use the provided tools specifically for searching these docs for services and resources).
Example (abbreviated):
Service: S3
Resources:
- Bucket
- BucketPolicy
- etc.
Bucket Capabilities:
- GetObject
- PutObject
- DeleteObject
Identifier Types:
- Bucket Name
- Bucket ARN
Structs:
- CorsRule
- LifecycleConfiguration
2. Document each of the Resource interfaces
Include the following information:
- ResourceName, e.g. Bucket, Instance, Queue
- Input Properties (for each property: Name, Type, Description, Default Value, Required, Constraints, Replaces: true/false)
- Output Attributes (for each attribute: Name, Type, Description)
3. Document each of the Capabilities and Bindings
Include the following information:
- Capability Name, e.g. `GetObject`, `PutObject` (it maps 1:1 with an AWS API)
- Constraints (e.g. `Key`)
- IAM Policies (how the capability maps to an IAM Policy, e.g. Effect: Allow, Action: s3:GetObject, Resource: `arn:aws:s3:::${bucketName}/${Key}`)
- Environment Variables (what environment variables should be added to a Lambda Function so that it can access the capability, e.g. `BUCKET_NAME`, `BUCKET_ARN`, `QUEUE_URL`, `QUEUE_ARN`, etc.)
4. Research and design each of the Lifecycle Operations
- **Diff** - identify which properties are always stable across any update, which properties change conditionally depending on new and old values, which properties trigger a replacement. This is usually just a distinct list, but can sometimes require if-this-then-that logic. Document it explicitly and exhaustively. Cross-reference with AWS CloudFormation, Terraform Provider and Pulumi Provider docs.
:::warning
You should almost never use `no-op` in the Diff. No-op should be explicitly designed as a way to say "i know this property changed, but i don't want it to trigger an update". This is an edge-case and not the norm. Usually you want diff to return `undefined` or `void` to let the engine apply the default update logic. Diff is usually just use as an optimization or to identify replacement instead of update.
:::
- **Read** - determine which API calls are required to read the Output Attributes of a Resource from the Cloud Provider state (otherwise known as refresh or synchronize resource state). This is usually a single Get{Resource} API call, but can be a complex set of calls depending on the Service. Read can also be called without the current Output Attributes because of past state persistence failures. These cases are handled by computing the deterministic Physical Name and looking it up or by searching for Resources using tags (if the Cloud Provider supports it). Read may return `Unowned(attrs)` when the resource exists but lacks our ownership tags, signalling the engine to gate adoption behind `--adopt` or `adopt(true)`.
- **Pre-Create** - determine if the Resource needs a pre-create operation. This is usually only the case for the special Function/Runtime Resources like AWS Lambda Functions. If it is required, then document which API call(s) should be called and what the empty (unit) input properties are. E.g. a Lambda Function takes a simple script that exports a no-op handler function.
- **Reconcile** - determine the API calls needed to converge the cloud's actual state to the desired state described by the new Input Properties. Reconcile must be a single flow that works whether the resource is missing (greenfield create), pre-existing under our ownership (update), or freshly adopted (`output` defined but `olds` absent). See the **Reconciler doctrine** section below.
- **Delete** - determine which APIs should be called and in what order to delete an existing Resource. Delete should be idempotent so that if the resource has already been deleted, it is not considered an error. It is common for deletions to fail because of Dependency Violations or Eventual Consistency Errors. These are not always called Dependency Violations in the API docs, so attention should be paid to investigating each API's possible error codes and how they should be handled by the Delete operation. Should we retry for a period of time, indefinitely, or fail immediately?
# Reconciler doctrine
The provider's `reconcile` function replaces the legacy `create` + `update` pair. It runs every time the engine wants to make the cloud match the desired state — whether that's the first time the resource is being provisioned, a routine update, or a takeover after `read` returned an existing cloud resource.
It receives `output: Attributes | undefined` and `olds: Props | undefined`:
| `output` | `olds` | Meaning |
| ------------ | ------------ | ------------------------------------------------- |
| `undefined` | `undefined` | Greenfield — no prior physical resource |
| defined | defined | Routine update — engine-owned resource |
| defined | `undefined` | Adoption — engine adopted via `read` |
A reconciler MUST work correctly for all three combinations. It MUST NOT branch the body on `output === undefined` and run different code paths for "create" vs "update". That pattern is just rename-and-branch and re-introduces every assumption the old `create`/`update` split made. Instead, write one flow:
```
1. Observe — derive the physical identifier; read live cloud state via getX/describeX
2. Ensure — if the resource is missing, call createX. Catch AlreadyExists/ConflictException
as a race and continue. Wait for active state if applicable.
3. Sync — for each mutable aspect (settings, sub-resources, tags, policy):
- read OBSERVED cloud state (not olds)
- compute desired state from news + bindings
- diff observed against desired
- apply only the delta API call (skip the API entirely on no-op)
4. Return — re-read final state if needed; return the fresh Attributes shape
```
Key invariants:
- **Observation > assumption.** Cloud state is authoritative. `olds` is at most a hint to skip a no-op API call; it is never the source of truth for what's actually deployed.
- **Each sync step is independently idempotent.** Crash mid-reconcile, re-run, you converge.
- **`output` is treated as a cache** for stable identifiers (physical name, ARN, immutable id). It is NOT a guarantee that the resource still exists. If it doesn't, observation falls through to "missing" and ensure recreates.
- **`AlreadyExists`/`NotFoundException`/`ResourceInUseException`-style errors are caught**, not propagated — they're races or eventual-consistency, not failures.
- **Tags use observed cloud tags as the diff baseline**, not `olds.tags` or `output.tags`. Adoption may bring you a resource with foreign tags that need to be reconciled.
:::warning
**Do not write `if (output === undefined) { /* create body */ } else { /* update body */ }`.** That is rename-and-branch, not reconciliation. The reconciler's body is one observe-ensure-sync flow that produces correct cloud state regardless of starting point.
:::
The canonical reference reconcilers cover the common shapes:
- [S3 Bucket](./packages/alchemy/src/AWS/S3/Bucket.ts) — uses `ensureBucketExists` + `syncBucketTags` + `syncBucketPolicy` helpers; each helper is itself a tiny reconciler.
- [SQS Queue](./packages/alchemy/src/AWS/SQS/Queue.ts) — observe via `getQueueUrl`, ensure via `createQueue` (tolerates `QueueNameExists` race), sync attributes by diffing `getQueueAttributes` against desired, sync tags.
- [Kinesis Stream](./packages/alchemy/src/AWS/Kinesis/Stream.ts) — many mutable aspects (mode, shards, retention, encryption, metrics), each its own observed-vs-desired sync block.
- [DynamoDB Table](./packages/alchemy/src/AWS/DynamoDB/Table.ts) — multi-API observation (table + tags + PITR + TTL), per-aspect diffing, GSI delta application.
- [EC2 Vpc](./packages/alchemy/src/AWS/EC2/Vpc.ts) — auto-assigned id, observe via `describeVpcs([output.vpcId])` with NotFound fallback to create, sync DNS attrs by reading `describeVpcAttribute`, sync tags from observed `vpc.Tags`.
- [Lambda Function](./packages/alchemy/src/AWS/Lambda/Function.ts) — uses `createOrUpdateFunction` / `createOrUpdateFunctionUrl` / `attachBindings` helpers, each idempotent.
- [Cloudflare Worker](./packages/alchemy/src/Cloudflare/Workers/Worker.ts) — non-AWS API; the underlying `putWorker` is a true upsert, so reconcile observes existing settings and delegates.
Existence-only resources (Lambda Permission, EC2 Route, EC2 RouteTableAssociation, IAM AccessKey, etc.) have nothing mutable beyond their identity. Their reconciler is just observe → if missing, create. There is no sync step.
5. Research and design the test cases for each resource. Test cases can be single or multi-step. Single-step test cases are just testing a single create success or failure mode. Multi-step cases are testing a sequence of operations, starting with create and then updating or replacing the resource multiple times. Test cases should be designed to be exhaustive and cover all possible success and failure modes, starting from simple happy paths to long, complicated aggregate (including other resources) smoke tests.
6. Implement the Resource contract and Provider in `packages/alchemy/src/{Cloud}/{Service}/{Resource}.ts`.
The Resource contract (Props, Attributes, Binding Contract) and the Resource Provider (lifecycle operations) are co-located in the same file.
Read through the established examples to understand the pattern:
- [S3 Bucket](./packages/alchemy/src/AWS/S3/Bucket.ts)
- [SQS Queue](./packages/alchemy/src/AWS/SQS/Queue.ts)
- [DynamoDB Table](./packages/alchemy/src/AWS/DynamoDB/Table.ts)
- [Kinesis Stream](./packages/alchemy/src/AWS/Kinesis/Stream.ts)
- [Lambda Function](./packages/alchemy/src/AWS/Lambda/Function.ts)
- [VPC](./packages/alchemy/src/AWS/EC2/Vpc.ts)
- [Subnet](./packages/alchemy/src/AWS/EC2/Subnet.ts)
The Resource interface takes four type parameters: `Resource<Type, Props, Attributes, BindingContract>`.
```ts
export interface Stream extends Resource<
"AWS.Kinesis.Stream",
StreamProps,
{
streamName: string;
streamArn: string;
streamStatus: StreamStatus;
}
> {}
export const Stream = Resource<Stream>("AWS.Kinesis.Stream");
```
For Resources that accept Bindings (like Lambda Function), include a fourth type parameter for the Binding Contract:
```ts
export interface Function extends Resource<
"AWS.Lambda.Function",
FunctionProps,
{
functionArn: string;
functionName: string;
functionUrl: string | undefined;
roleName: string;
roleArn: string;
},
{
env?: Record<string, any>;
policyStatements?: PolicyStatement[];
}
> {}
```
:::tip
Some Input Property types are wrapped in an `Input<T>`, but not all are. Only properties that may need to be references to another resource's Output Attribute. E.g. common use-cases are `Input<VpcId>`, `Input<QueueUrl>`, `Tags: Record<string, Input<string>>`.
:::
:::warning
For fields like `name: string`, `bucketName: string`, `bucketPrefix: string`, you should not use `Input<string>` because these properties need to be statically knowable in the `diff` function.
:::
7. Implement the Capabilities as `Binding.Service` + `Binding.Policy` pairs in `packages/alchemy/src/{Cloud}/{Service}/{Capability}.ts`.
Each capability has two parts:
- **`Binding.Service`** — runtime SDK wrapper, provided on the Function Effect (bundled into Lambda/Worker)
- **`Binding.Policy`** — deploy-time IAM policy attachment, provided on the Stack via `AWS.providers()()` (never bundled)
Read through the established capabilities to understand the pattern:
- [S3 GetObject](./packages/alchemy/src/AWS/S3/GetObject.ts) — `Binding.Service` + `Binding.Policy`
- [S3 PutObject](./packages/alchemy/src/AWS/S3/PutObject.ts) — `Binding.Service` + `Binding.Policy`
- [SQS SendMessage](./packages/alchemy/src/AWS/SQS/SendMessage.ts) — `Binding.Service` + `Binding.Policy`
- [DynamoDB GetItem](./packages/alchemy/src/AWS/DynamoDB/GetItem.ts) — `Binding.Service` + `Binding.Policy`
- [Kinesis PutRecord](./packages/alchemy/src/AWS/Kinesis/PutRecord.ts) — `Binding.Service` + `Binding.Policy`
- [Lambda InvokeFunction](./packages/alchemy/src/AWS/Lambda/InvokeFunction.ts) — `Binding.Service` + `Binding.Policy`
For Event Sources, see:
- [SQS QueueEventSource](./packages/alchemy/src/AWS/SQS/QueueEventSource.ts)
- [S3 BucketEventSource](./packages/alchemy/src/AWS/S3/BucketEventSource.ts)
The `Binding.Policy` implementation calls `ctx.bind({ policyStatements: [...] })` on the target Function, which records binding data on the Stack. The `Binding.Service` implementation resolves the Policy via `yield* Policy(resource)`, then returns a typed callable that wraps the SDK client. At runtime, the Policy is not provided and becomes a no-op.
Each capability exports four things:
```ts
// 1. The Binding.Service class
export class PutRecord extends Binding.Service<...>()("AWS.Kinesis.PutRecord") {}
// 2. The Binding.Service Live layer (provided on Function Effect)
export const PutRecordLive = Layer.effect(PutRecord, ...);
// 3. The Binding.Policy class
export class PutRecordPolicy extends Binding.Policy<...>()("AWS.Kinesis.PutRecord") {}
// 4. The Binding.Policy Live layer (provided on Stack via AWS.providers()())
export const PutRecordPolicyLive = Layer.effect(PutRecordPolicy, ...);
```
### Runtime-only methods: color with `Alchemy.RuntimeContext`
The runtime callable returned by a `Binding.Service` (the inner Effect inside `.bind(resource)`'s return) **must** declare `Alchemy.RuntimeContext` as a requirement. This is how Alchemy models "this code can only run inside a deployed Function/Worker" at the type level — analogous to a colored function.
```ts
import type { RuntimeContext } from "../../RuntimeContext.ts";
export class GetItem extends Binding.Service<
GetItem,
<T extends Table>(
table: T,
) => Effect.Effect<
(
request: GetItemRequest,
) => Effect.Effect<
DynamoDB.GetItemOutput,
DynamoDB.GetItemError,
RuntimeContext // ← runtime-only
>
>
>()("AWS.DynamoDB.GetItem") {}
```
Rules:
- **Outer Effect** (the `bind(resource)` setup) runs at the Function's init phase. It does NOT require `RuntimeContext`.
- **Inner Effect** (the actual SDK invocation) only makes sense inside a running Function. It MUST require `RuntimeContext`.
- Resolve cloud-environment services (`WorkerEnvironment`, AWS SDK clients, etc.) once during Layer construction and close over them. Do NOT leak `WorkerEnvironment` / `Lambda.FunctionEnvironment` onto the runtime callable — that couples downstream service code to a specific cloud and breaks Layer encapsulation. The Function/Worker runtime satisfies `RuntimeContext` automatically.
- The implementation can return `Effect.Effect<A, E>` without explicitly providing `RuntimeContext` (it's contravariant in `R`); just declare it on the interface.
Why this matters: consumers can build cloud-agnostic services on top of bindings using `Layer.effect(Tag, ...)` without polluting their service interface with `WorkerEnvironment`. See [Layers concept](./website/src/content/docs/concepts/layers.mdx).
After implementing, register the Policy in `AWS.providers()()`:
- Add the `*PolicyLive` layer to `bindings()` in [Providers.ts](./packages/alchemy/src/AWS/Providers.ts)
- Re-export from the service's `index.ts`
:::tip
If you need to know what AWS region or account ID the resource is being created/updated in, you can use this inside any of the lifecycle operations.
```ts
const region = yield * Region;
const account = yield * Account;
```
:::
:::warning
You should favor getting the region/account INSIDE the lifecycle operations instead of inside the Layer effect like this because then it's scoped to the resource isntead of the resource provider:
```ts
reconcile: Effect.fn(function* ({ id, news, output, session }) {
const region = yield* Region;
const accountId = yield* Account;
});
```
:::
:::warning
Do not use `Effect.orDie` in the lifecycle operations since this will crash the whole IaC engine.
:::
:::warning
**Never use `async`/`await`, raw `Promise`, `node:fs/promises`, `node:fs`, `node:os`, or `pathe` directly in resource code.** Always use the Effect platform services so that effects remain composable, traceable, retryable, and testable:
| Don't | Do |
| ---------------------------------------------------- | ----------------------------------------------------------- |
| `import fs from "node:fs/promises"` | `const fs = yield* FileSystem.FileSystem` |
| `await fs.readFile(p, "utf8")` | `yield* fs.readFileString(p)` |
| `await fs.mkdtemp(...)` | `yield* fs.makeTempDirectory({ prefix: ... })` |
| `import path from "pathe"` / `node:path` | `const path = yield* Path.Path` |
| `await fetch(...)` | `yield* HttpClient.HttpClient` + `HttpClientRequest` |
| `Effect.promise(() => listSqlFiles(dir))` | Make `listSqlFiles` itself return `Effect` and `yield*` it |
| `new Promise((res) => setTimeout(res, ms))` | `yield* Effect.sleep(Duration.millis(ms))` |
Sync, CPU-only Node APIs (e.g. `crypto.createHash().update().digest()`, `process.cwd()`, `Buffer`, `TextEncoder`) must still be wrapped in `Effect.sync(() => ...)` (or `Effect.try` if they can throw) so the call participates in the Effect runtime — tracing, interruption, and error channels. Don't call them as bare expressions inside `Effect.gen`.
```ts
const hash = yield* Effect.sync(() =>
crypto.createHash("sha256").update(input).digest("hex"),
);
const cwd = yield* Effect.sync(() => process.cwd());
```
This applies to **lifecycle operations, helpers, AND tests**. Tests must use `FileSystem.FileSystem`/`Path.Path` for any file/path access (see [Database.test.ts](./packages/alchemy/test/Cloudflare/D1/Database.test.ts) for the pattern).
:::
:::tip
If a Resource supports tags, you should always include the internal Alchemy tags to brand the resource with the app, stage and logical ID so that we can "know" that we created it and are responsible for it.
```ts
reconcile: Effect.fn(function* ({ id, news, output, session }) {
const internalTags = yield* createInternalTags(id);
const userTags = news.tags ?? {};
const allTags = { ...internalTags, ...userTags };
});
```
:::
:::warning
Do not roll your own tag diffing logic, always use `diffTags` from [Tags.ts](./packages/alchemy/src/Tags.ts), and diff against **observed cloud tags** (not `olds.tags` or `output.tags`). Adoption can hand you a resource whose tags don't match what we last persisted.
```ts
reconcile: Effect.fn(function* ({ id, news, output, session }) {
const internalTags = yield* createInternalTags(id);
const newTags = { ...news.tags, ...internalTags };
// Read tags fresh from the cloud so adoption (where tags may not match
// what we last persisted) converges correctly.
const oldTags = yield* fetchObservedTags(/* … */);
// Option 1. use `upsert` if the API expects you to create/update tags in one call
const { removed, upsert } = diffTags(oldTags, newTags);
// Option 2. use `added` and `updated` if the API expects you to create/update tags in separate calls
const { removed, added, updated } = diffTags(oldTags, newTags);
// Option 3. use `upsert` only if the API doesn't expect you to remove tags (only PUT/UPDATe)
const { upsert } = diffTags(oldTags, newTags);
```
:::
9. Implement the test cases in `packages/alchemy/test/{Cloud}/{Service}/{Resource}.test.ts`.
Read through the established test cases before continuing so that you understand the pattern and structure of the test cases.
- [S3 Bucket Test Cases](./test/AWS/S3/Bucket.test.ts)
- [SQS Queue Test Cases](./test/AWS/SQS/Queue.test.ts)
- [Lambda Function Test Cases](./test/AWS/Lambda/Function.test.ts)
- [Kinesis Stream Test Cases](./test/AWS/Kinesis/Stream.test.ts)
- [DynamoDB Table Test Cases](./test/AWS/DynamoDB/Table.test.ts)
- [VPC Test Cases](./test/AWS/EC2/Vpc.test.ts)
- [Subnet Test Cases](./test/AWS/EC2/Subnet.test.ts)
:::warning
Never use `Date.now()` when constructing the physical name of a resource. You should either:
1. Do not proide a name and rely on the resource provider to generate a unique name for you from the app, stage and logical ID.
2. Construct a deterministic one unique to each test case. But it should be the same on each subsequent run of the test case.
:::
3. Consider implementing an aggregate Smoke test that brings together multiple resources that are often used together.
See the [VPC Smoke Test](./test/AWS/EC2/Vpc.smoke.test.ts) for an example.
11. Add the resource-level JSDoc (`@section` + `@example` blocks) and field-level JSDoc on each prop/attribute on the source `.ts` file. Then run `bun generate:api-reference` to refresh `website/src/content/docs/providers/{Cloud}/{Resource}.md`. Do NOT manually edit the generated markdown.
# Test Fixtures for Effect-Native Workers / Functions
To test runtime behavior of an Effect-native Worker, Workflow, Lambda, etc., write a **fixture** that defines the Worker/Function with the bindings under test and exposes one HTTP route per behavior, then write a **test** that deploys the fixture once via `beforeAll` and drives it over HTTP.
## File system layout
Put fixtures in a `fixtures/` directory next to the test file. Each test suite owns its own fixtures — never reach across suites:
```sh
packages/alchemy/test/{Cloud}/{Service}/{Resource}.test.ts
packages/alchemy/test/{Cloud}/{Service}/fixtures/{worker|workflow|handler}.ts
```
## Fixture shape
Resolve the bindings, expose one route per behavior, default-export the class so the test can deploy it directly:
```ts
// fixtures/worker.ts
import * as Cloudflare from "@/Cloudflare/index.ts";
import * as Effect from "effect/Effect";
import { HttpServerRequest } from "effect/unstable/http/HttpServerRequest";
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
import { Gateway } from "./gateway.ts";
export default class TestWorker extends Cloudflare.Worker<TestWorker>()(
"TestWorker",
{
main: import.meta.filename,
},
Effect.gen(function* () {
const aiGateway = yield* Cloudflare.AiGateway.bind(Gateway);
return {
fetch: Effect.gen(function* () {
const request = yield* HttpServerRequest;
if (request.url.startsWith("/url")) {
const url = yield* aiGateway.getUrl().pipe(Effect.orDie);
return yield* HttpServerResponse.json({ url });
}
return HttpServerResponse.text("ok");
}),
};
}).pipe(Effect.provide(Cloudflare.AiGatewayBindingLive)),
) {}
```
## Test shape
Compose a `Stack` that deploys the fixture, share one deploy across the file with `beforeAll`/`afterAll`, drive it via `HttpClient`, and retry the first request through edge propagation:
```ts
// Service.test.ts
import * as Alchemy from "@/index.ts";
import * as Cloudflare from "@/Cloudflare";
import * as Test from "@/Test/Vitest";
import { expect } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Schedule from "effect/Schedule";
import * as HttpClient from "effect/unstable/http/HttpClient";
import TestWorker from "./fixtures/worker.ts";
const { test, beforeAll, afterAll, deploy, destroy } = Test.make({
providers: Cloudflare.providers(),
});
const Stack = Alchemy.Stack(
"ServiceTestStack",
{ providers: Cloudflare.providers(), state: Cloudflare.state() },
Effect.gen(function* () {
const worker = yield* TestWorker;
return { url: worker.url.as<string>() };
}),
);
const stack = beforeAll(deploy(Stack));
afterAll.skipIf(!!process.env.NO_DESTROY)(destroy(Stack));
test(
"deployed worker exercises the binding",
Effect.gen(function* () {
const { url } = yield* stack;
const client = yield* HttpClient.HttpClient;
const res = yield* client.get(`${url}/url`).pipe(
Effect.retry({ schedule: Schedule.exponential("500 millis"), times: 10 }),
);
expect(res.status).toBe(200);
const body = (yield* res.json) as { url: string };
expect(body.url).toContain("gateway.ai.cloudflare.com");
}),
{ timeout: 180_000 },
);
```
Notes:
- `Test.make({ providers: Cloudflare.providers() })` gives you `test`, `beforeAll`, `afterAll`, `deploy`, `destroy`.
- `beforeAll(deploy(Stack))` returns a handle (`stack` above) that every `test` body can `yield*` to get the stack outputs.
- `afterAll.skipIf(!!process.env.NO_DESTROY)(destroy(Stack))` is the standard cleanup — set `NO_DESTROY=1` locally to keep the deployment around between runs while iterating.
- Always retry the first request (`Schedule.exponential("500 millis")`) — fresh workers.dev URLs and Lambda function URLs take a few seconds to start serving 200s.
- For POST: use `client.post(url)` for empty bodies, or `HttpClient.execute(HttpClientRequest.post(url).pipe(HttpClientRequest.bodyJsonUnsafe(body)))` for typed bodies.
- **Never use `while (Date.now() < deadline)` loops to poll** for an async side effect (a workflow status, a cron fire, a queue drain, eventual-consistency read, etc.). Use `Effect.repeat` with a `Schedule` and an `until` predicate so the polling participates in the Effect runtime — tracing, interruption, and error propagation work correctly, and the intent is declarative. Cap iterations with `times: N` (or a bounded schedule) so the test fails fast instead of running until the vitest timeout:
```ts
// good — declarative, bounded, interruption-safe
const value = yield* fetchValue.pipe(
Effect.repeat({
schedule: Schedule.spaced("5 seconds"),
until: (v) => v.ready,
times: 36,
}),
);
// bad — opaque loop, ignores interruption, leaks into vitest timeout
let value: Value | undefined;
const deadline = Date.now() + 180_000;
while (Date.now() < deadline) {
value = yield* fetchValue;
if (value.ready) break;
yield* Effect.sleep("5 seconds");
}
```
See [CronEventSource.test.ts](./packages/alchemy/test/Cloudflare/Workers/CronEventSource.test.ts) for a real-world example (polling a DO via the worker's `/times` route until the cron handler fires).
## Reference implementations
- Cloudflare AiGateway — [worker fixture](./packages/alchemy/test/Cloudflare/AiGateway/worker.ts) + [test](./packages/alchemy/test/Cloudflare/AiGateway/AiGateway.test.ts) (the deploy+fetch case lives at the bottom of the file)
- Cloudflare D1Connection — [worker fixture](./packages/alchemy/test/Cloudflare/D1/d1-worker.ts) + [test](./packages/alchemy/test/Cloudflare/D1/D1Binding.test.ts)
- Cloudflare Workflow — [workflow fixture](./packages/alchemy/test/Cloudflare/Workers/fixtures/test-workflow.ts) + [worker fixture](./packages/alchemy/test/Cloudflare/Workers/fixtures/workflow-worker.ts) + [test](./packages/alchemy/test/Cloudflare/Workers/Workflow.test.ts)
- Cloudflare Cron Trigger — [worker + DO fixture](./packages/alchemy/test/Cloudflare/Workers/fixtures/cron-worker.ts) + [test](./packages/alchemy/test/Cloudflare/Workers/CronEventSource.test.ts) (cron handler writes to a DO; test polls a fetch route with `Effect.repeat` until the scheduled handler fires)
- Cloudflare Images — [effect fixture](./packages/alchemy/test/Cloudflare/Images/fixtures/effect-worker.ts) + [async fixture](./packages/alchemy/test/Cloudflare/Images/fixtures/async-worker.ts) + [test](./packages/alchemy/test/Cloudflare/Images/Images.test.ts)
- AWS Lambda (DynamoDB bindings) — [Lambda fixture](./packages/alchemy/test/AWS/DynamoDB/handler.ts) + [test](./packages/alchemy/test/AWS/DynamoDB/Bindings.test.ts) (one `describe("<BindingName>")` per binding, all driving the same deployed Lambda)
# Spec-Driven Service Bring-Up
Use @processes/AWS.md as the source of truth for bringing a single AWS service from zero to full coverage.
That process covers:
- deriving resources, bindings, event sources, and helpers from distilled
- the audit-driven implementation loop
- deterministic checks for registration and binding test coverage
- Lambda fixture testing conventions
- learned conventions like no auto-marshalling and one `describe("<BindingName>")` block per binding
Keep `AGENTS.md` high-level and update @processes/AWS.md when the process evolves.
When a canonical resource needs mutable event-source configuration and there is any chance of circularity, prefer a resource binding contract over a plain input prop. DynamoDB Streams is the reference case: `Table` owns the actual stream state, while `streams(table)` injects that state via bindings and the runtime-specific layer handles the subscription mechanics. See @processes/AWS.md for the DynamoDB Streams case study.
# Build and Type Checking
Always run type checking before committing changes:
```bash
bun tsc -b
```
This runs the TypeScript compiler in build mode, which checks all projects in the workspace. This is critical because CI will fail if there are type errors.
## Build Commands
| Command | Description |
| ----------------- | -------------------------------------------------------------------------------------------- |
| `bun tsc -b` | Type check all projects (always run before committing) |
| `bun run build` | Clean, type check, and build the alchemy package |
| `bun build:clean` | Full clean rebuild: cleans all artifacts, reinstalls dependencies, builds, and downloads env |
Use `bun build:clean` when you encounter stale build artifacts or dependency issues. It runs:
1. `bun clean .` - Removes all untracked files except .env
2. `bun i` - Reinstalls dependencies
3. `bun run build` - Builds the project
4. `bun download:env` - Downloads environment files
# Tutorial Documentation Standard
Tutorials under `website/src/content/docs/tutorial/` are **step-by-step and granular**: every code snippet introduces exactly **one** new thing, followed by a short prose explanation of just that thing. Each step gets its own `##` heading.
**Anti-pattern** — one snippet that adds multiple distinct changes, followed by a numbered list or bullet list explaining each:
````md
## Bind the DO to the Worker
```diff lang="typescript"
+import Counter from "./counter.ts";
+import { HttpServerRequest } from "...";
Effect.gen(function* () {
+ const counters = yield* Counter;
return {
fetch: Effect.gen(function* () {
+ const request = yield* HttpServerRequest;
+ if (request.url.startsWith("/counter/") && ...) {
+ const next = yield* counters.getByName(name).increment();
+ return HttpServerResponse.text(String(next));
+ }
return HttpServerResponse.text("Hello!");
}),
};
})
```
Two things just happened:
1. `yield* Counter` registers the DO ...
2. `counters.getByName(name)` returns a typed stub ...
````
**Correct** — split into one heading per step, each with one snippet and one explanation:
````md
## Bind the DO to the Worker
```diff lang="typescript"
+import Counter from "./counter.ts";
Effect.gen(function* () {
+ const counters = yield* Counter;
...
})
```
`yield* Counter` registers the DO with the Worker (binding + class-migration metadata) and hands you the namespace.
## Call the DO from `fetch`
```diff lang="typescript"
+import { HttpServerRequest } from "...";
fetch: Effect.gen(function* () {
+ const request = yield* HttpServerRequest;
+ if (request.url.startsWith("/counter/") && ...) {
+ const next = yield* counters.getByName(name).increment();
+ return HttpServerResponse.text(String(next));
+ }
return HttpServerResponse.text("Hello!");
})
```
`counters.getByName(name)` returns a typed stub — `increment()` and `get()` round-trip through Cloudflare's RPC machinery.
````
Rules of thumb:
- If you find yourself writing "Two/three things just happened", "A few things are happening here", or a numbered/bulleted list explaining separate parts of a single snippet — **split the snippet**.
- One concept ⇒ one heading ⇒ one diff snippet ⇒ one explanation paragraph (no bullets).
- Bullet/numbered lists are fine when they describe a recap, prerequisites, or genuinely list-shaped content (e.g. "the Worker now handles two routes: PUT and GET" at the end). They are **not** fine as a substitute for splitting a compound snippet.
- A single API call that internally does several things (e.g. `Cloudflare.upgrade()`) doesn't need splitting — describe its behavior in prose.
- Use `diff lang="typescript"` blocks so each step shows what's added on top of the previous step.
# Pull Request Conventions
When you automatically open a PR, it MUST follow this structure:
- **Title**: Use conventional commit format (e.g. `fix(website): mobile theme metas`, `feat(aws/s3): add bucket lifecycle rules`).
- **Description heading levels**: NEVER use `#` or `##` in the PR description. The smallest heading allowed is `###`. The PR description must NOT begin with its own title heading — GitHub already renders the PR title above it.
- **Content**: Aim for the minimal content needed to convey the idea.
- Use simple sentences. If there are multiple discrete changes, use bullet points.
- **Prefer code snippets over prose.** A short ` ```ts ` or ` ```diff ` block showing the new/changed shape is worth more than a paragraph explaining it. Reach for code first; only add prose to fill in the "why" the snippet can't show on its own.
- Be direct and succinct. Cut adjectives, justifications, and anything that reads like marketing copy. If a sentence is restating what the diff already shows, delete it.
- **Never include a "Test plan", "Testing", or checklist of TODOs.** PR descriptions document the change, not the verification process. If something needs manual verification, follow the draft-PR rule below.
- Skip examples for trivial fixes, internal refactors, or doc-only changes.
Example PR description (good — code snippet does the talking):
````
Track which state-store backend each project uses by emitting a `state_store.init` span tagged with `alchemy.state_store.kind`.
```ts
// every Layer.effect(State, …) site now wraps construction:
makeLocalState().pipe(recordStateStoreInit("local"))
```
Dashboard groups projects by kind from these spans (Axiom can't APL-query metric datasets).
````
- **Outstanding work / testing / review needed**: If there are outstanding steps, manual testing required, or review items, DO NOT leave a comment on the PR and DO NOT include them in the PR description. Instead:
1. Mark the PR as **draft**.
2. Tell the user (in the chat that initiated the PR creation) what is outstanding.
:::warning
**Markdown content must reach GitHub verbatim** — un-escaped backticks, fenced code blocks, etc. The reliable shape is to write the description to a file and pass `--body-file <path>` to `gh pr create` / `gh pr edit`:
```sh
# write the body to a temp file (use Write tool, not echo/cat heredoc)
gh pr edit 179 --body-file /tmp/pr-body.md
```
Do **not** inline the body via `--body "$(cat <<'EOF' ... EOF)"`. Even with a single-quoted heredoc some shells / `gh` versions still mangle backticks and backslashes; the resulting PR body ends up with literal `\`` sequences instead of inline code spans. `--body-file` sidesteps shell quoting entirely.
If you need to update an already-created PR's body, prefer `gh pr edit --body-file ...`. If that silently no-ops (older `gh` versions), fall back to `gh api -X PATCH repos/<owner>/<repo>/pulls/<n> -F body=@/tmp/pr-body.md`.
:::
The summary goes at the very top of the description as plain prose — NO heading above it, no `### Summary`, nothing. The PR title already serves as the title; do not repeat or re-title it. Only add `###` subheadings further down if the description genuinely has multiple sections worth separating.
Example PR description (good):
```
Persist the user's selected theme across reloads and fix a hero scroll glitch on mobile.
- Read theme from `localStorage` on mount before first paint
- Add `<meta name="theme-color">` per theme so mobile chrome matches
```
Example PR description (BAD — do not do this):
```
## Theme persistence fix ← no, the PR title already exists
### Summary ← no, summary needs no heading
Persist the user's theme...
```
File diff suppressed because it is too large. Load diff
-1
View File
@@ -1 +0,0 @@
@AGENTS.md
-85
View File
@@ -1,85 +0,0 @@
<div align="center">
<a href="https://v2.alchemy.run">
<img src="./images/readme-hero.png" alt="Alchemy — Infrastructure as Effects" width="360" />
</a>
<br />
[![npm](https://img.shields.io/npm/v/alchemy?style=flat-square&color=3f5a2a&label=alchemy)](https://www.npmjs.com/package/alchemy)
[![license](https://img.shields.io/badge/license-Apache%202.0-3f5a2a?style=flat-square)](./LICENSE)
[![discord](https://img.shields.io/badge/discord-join-3f5a2a?style=flat-square&logo=discord&logoColor=white)](https://discord.gg/jwKw8dBJdN)
**Infrastructure-as-Effects** — cloud infrastructure and application logic as a single, type-safe [Effect](https://effect.website) program.
[Docs](https://v2.alchemy.run) · [Tutorial](https://v2.alchemy.run/tutorial/part-1) · [Examples](./examples) · [Discord](https://discord.gg/jwKw8dBJdN)
</div>
---
A Worker bound to a R2 bucket and serving objects from it:
```typescript
const Bucket = Cloudflare.R2Bucket("bucket");
export default Cloudflare.Worker(
"api",
{ main: import.meta.path },
Effect.gen(function* () {
const bucket = yield* Cloudflare.R2Bucket.bind(Bucket);
return {
fetch: Effect.gen(function* () {
const request = yield* HttpServerRequest;
const object = yield* bucket.get(request.url);
return HttpServerResponse.stream(object!.body);
})
};
}),
);
```
One `bind()` wires the binding, env var, and typed connection — at deploy time and at runtime.
---
- **One program, one language.** Resources, Lambdas/Workers, IAM, and SDKs live in the same Effect program — no YAML, no second runtime.
- **Bindings, not glue code.** `S3.GetObject.bind(bucket)` wires the IAM policy, env var, and a typed SDK call in a single line.
- **Errors in the type system.** Every cloud API failure is a tagged Effect error you handle — or don't — on purpose.
- **AWS + Cloudflare today.** S3, SQS, DynamoDB, Kinesis, Lambda, EC2 / Workers, R2, D1, Durable Objects, Containers.
- **Same code, every stage.** Local dev, `plan` / `deploy`, smoke tests, and CI all share one mental model.
```sh
bun add alchemy effect
```
## Bootstrap with an AI coding agent
Paste this into Claude Code, Cursor, or any agent that can fetch a URL:
```
You are an Alchemy expert. Read https://v2.alchemy.run/llms.txt to load the
full documentation index, then act as my pair on this project.
Goal: help me set up, build, test, and deploy a cloud application with
`alchemy` (Infrastructure-as-Effects, powered by Effect).
Follow the patterns from the docs and the /examples folder. Stay idiomatic
to Effect: use Layers for wiring, return Effects from lifecycle code, and
keep infra and runtime in the same program. Ask before introducing new
dependencies or breaking conventions.
```
## Learn more
- [What is Alchemy?](https://v2.alchemy.run/what-is-alchemy) — the framework in 2 minutes
- [Getting Started](https://v2.alchemy.run/getting-started) — your first Stack
- [Tutorial](https://v2.alchemy.run/tutorial/part-1) — five-part walkthrough to a tested, CI-deployed app
- [Examples](./examples) — runnable projects on AWS and Cloudflare
- [llms.txt](https://v2.alchemy.run/llms.txt) — agent-ready documentation index
> **alchemy** is in alpha. Expect breaking changes. Come hang in our [Discord](https://discord.gg/jwKw8dBJdN).
## License
Apache-2.0
File diff suppressed because it is too large. Load diff
@@ -1,23 +0,0 @@
import * as Alchemy from "alchemy";
import * as AWS from "alchemy/AWS";
import * as Output from "alchemy/Output";
import * as Effect from "effect/Effect";
import { NetworkLive } from "./src/Network.ts";
import Server from "./src/Server.ts";
const aws = AWS.providers();
export default Alchemy.Stack(
"AwsEc2Example",
{ providers: aws, state: Alchemy.localState() },
Effect.gen(function* () {
const instance = yield* Server;
return {
instanceId: instance.instanceId,
publicIpAddress: instance.publicIpAddress,
instanceUrl: Output.interpolate`http://${instance.publicIpAddress}:3000`,
enqueueExample: Output.interpolate`http://${instance.publicIpAddress}:3000/enqueue?message=hello`,
};
}).pipe(Effect.provide(NetworkLive)),
);
@@ -1,23 +0,0 @@
{
"name": "aws-ec2-example",
"version": "0.0.0",
"private": true,
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "git+https://github.com/alchemy-run/alchemy-effect.git",
"directory": "examples/aws-ec2"
},
"scripts": {
"build": "tsc -b",
"deploy": "alchemy deploy",
"dev": "alchemy dev",
"destroy": "alchemy destroy"
},
"dependencies": {
"@distilled.cloud/aws": "catalog:",
"@effect/platform-node": "catalog:",
"alchemy": "workspace:*",
"effect": "catalog:"
}
}
@@ -1,45 +0,0 @@
import * as AWS from "alchemy/AWS";
import type { Output } from "alchemy/Output";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
export interface ExampleNetwork {
network: AWS.EC2.Network;
publicSubnetIds: Output<AWS.EC2.SubnetId>[];
appSecurityGroupId: Output<AWS.EC2.SecurityGroupId>;
}
export class Network extends Context.Service<Network, ExampleNetwork>()(
"Network",
) {}
export const NetworkLive = Layer.effect(
Network,
Effect.gen(function* () {
const network = yield* AWS.EC2.Network("Network", {
cidrBlock: "10.42.0.0/16",
availabilityZones: 2,
nat: "single",
});
const appSecurityGroup = yield* AWS.EC2.SecurityGroup("AppSecurityGroup", {
vpcId: network.vpcId,
description: "Security group for the EC2 application instance",
ingress: [
{
ipProtocol: "tcp",
fromPort: 3000,
toPort: 3000,
cidrIpv4: "0.0.0.0/0",
},
],
});
return {
network,
publicSubnetIds: network.publicSubnetIds,
appSecurityGroupId: appSecurityGroup.groupId,
};
}),
);
@@ -1,89 +0,0 @@
import * as AWS from "alchemy/AWS";
import { SQSQueueEventSource } from "alchemy/Server/SQSQueueEventSource";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Stream from "effect/Stream";
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
import { Network, NetworkLive } from "./Network.ts";
export default class Server extends AWS.EC2.Instance<Server>()(
"ServerInstance",
Effect.gen(function* () {
const imageId = yield* AWS.EC2.amazonLinux();
const network = yield* Network;
return {
main: import.meta.filename,
imageId,
instanceType: "t3.small",
subnetId: network.publicSubnetIds[0],
securityGroupIds: [network.appSecurityGroupId],
associatePublicIpAddress: true,
port: 3000,
};
}),
Effect.gen(function* () {
const queue = yield* AWS.SQS.Queue("JobsQueue", {
receiveMessageWaitTimeSeconds: 20,
visibilityTimeout: 60,
});
yield* AWS.SQS.messages(queue).subscribe((stream) =>
stream.pipe(Stream.mapEffect(Effect.logInfo), Stream.runDrain),
);
const sendMessage = yield* AWS.SQS.SendMessage.bind(queue);
return {
fetch: Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
const url = new URL(request.originalUrl);
if (request.method === "GET" && url.pathname === "/") {
return yield* HttpServerResponse.json({
ok: true,
routes: ["GET /", "GET /enqueue?message=hello"],
});
}
if (request.method === "GET" && url.pathname === "/enqueue") {
const message = url.searchParams.get("message") ?? "hello from EC2";
const body = JSON.stringify({
message,
enqueuedAt: new Date().toISOString(),
});
const result = yield* sendMessage({
MessageBody: body,
});
return yield* HttpServerResponse.json({
ok: true,
message,
messageId: result.MessageId,
});
}
return HttpServerResponse.text("Not found", { status: 404 });
}).pipe(
Effect.catch(() =>
Effect.succeed(
HttpServerResponse.text("Internal server error", { status: 500 }),
),
),
),
};
}).pipe(
Effect.provide(
Layer.provideMerge(
Layer.mergeAll(NetworkLive, SQSQueueEventSource),
Layer.mergeAll(
AWS.SQS.DeleteMessageBatchLive,
AWS.SQS.ReceiveMessageLive,
AWS.SQS.SendMessageLive,
),
),
),
),
) {}
@@ -1,16 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"include": ["alchemy.run.ts", "src/**/*.ts"],
"compilerOptions": {
"noEmit": true,
"rootDir": ".",
"module": "Preserve",
"moduleResolution": "Bundler",
"target": "ESNext"
},
"references": [
{
"path": "../../packages/alchemy/tsconfig.json"
}
]
}
@@ -1,80 +0,0 @@
import * as Alchemy from "alchemy";
import * as AWS from "alchemy/AWS";
import * as Output from "alchemy/Output";
import * as Effect from "effect/Effect";
import QueueConsumerTask from "./src/QueueConsumerTask.ts";
import ApiTask from "./src/Task.ts";
const aws = AWS.providers();
export default Alchemy.Stack(
"AwsEcsExample",
{
providers: aws,
state: Alchemy.localState(),
},
Effect.gen(function* () {
const network = yield* AWS.EC2.Network("ExampleNetwork", {
cidrBlock: "10.42.0.0/16",
availabilityZones: 2,
});
const serviceSecurityGroup = yield* AWS.EC2.SecurityGroup(
"ExampleServiceSecurityGroup",
{
vpcId: network.vpcId,
description: "Security group for the ECS example services",
ingress: [
{
ipProtocol: "tcp",
fromPort: 80,
toPort: 80,
cidrIpv4: "0.0.0.0/0",
},
{
ipProtocol: "tcp",
fromPort: 3000,
toPort: 3000,
cidrIpv4: "0.0.0.0/0",
},
],
},
);
const queue = yield* AWS.SQS.Queue("ExampleJobsQueue", {
receiveMessageWaitTimeSeconds: 20,
visibilityTimeout: 60,
});
const cluster = yield* AWS.ECS.Cluster("ExampleCluster", {});
const apiTask = yield* ApiTask;
const queuePollerTask = yield* QueueConsumerTask;
const apiService = yield* AWS.ECS.Service("ExampleApiService", {
cluster,
task: apiTask,
vpcId: network.vpcId,
subnets: network.publicSubnetIds,
securityGroups: [serviceSecurityGroup.groupId],
assignPublicIp: true,
public: true,
healthCheckPath: "/",
});
yield* AWS.ECS.Service("ExampleQueuePollerService", {
cluster,
task: queuePollerTask,
vpcId: network.vpcId,
subnets: network.publicSubnetIds,
securityGroups: [serviceSecurityGroup.groupId],
assignPublicIp: true,
desiredCount: 1,
});
return {
url: apiService.url,
queueUrl: queue.queueUrl,
enqueueExample: Output.interpolate`${apiService.url}/enqueue?message=hello`,
};
}),
);
@@ -1,23 +0,0 @@
{
"name": "aws-ecs-example",
"version": "0.0.0",
"private": true,
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "git+https://github.com/alchemy-run/alchemy-effect.git",
"directory": "examples/aws-ecs"
},
"scripts": {
"build": "tsc -b",
"deploy": "alchemy deploy",
"dev": "alchemy dev",
"destroy": "alchemy destroy"
},
"dependencies": {
"@distilled.cloud/aws": "catalog:",
"@effect/platform-node": "catalog:",
"alchemy": "workspace:*",
"effect": "catalog:"
}
}
@@ -1,16 +0,0 @@
import * as AWS from "alchemy/AWS";
import * as Context from "effect/Context";
import * as Layer from "effect/Layer";
/**
* Deploy-time binding for the ECS example’s jobs queue. Provide with
* `Layer.succeed(ExampleJobsQueue, queue)` from the stack after the queue exists.
*/
export class JobsQueue extends Context.Service<JobsQueue, AWS.SQS.Queue>()(
"JobsQueue",
) {}
export const JobsQueueLive = Layer.effect(
JobsQueue,
AWS.SQS.Queue("JobsQueue"),
);
@@ -1,41 +0,0 @@
import * as AWS from "alchemy/AWS";
import * as Server from "alchemy/Server";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Stream from "effect/Stream";
import { JobsQueue, JobsQueueLive } from "./JobsQueue.ts";
export default class QueueConsumerTask extends AWS.ECS.Task<QueueConsumerTask>()(
"QueueConsumerTask",
{
main: import.meta.filename,
cpu: 256,
memory: 512,
taskRoleManagedPolicyArns: ["arn:aws:iam::aws:policy/AmazonSQSFullAccess"],
},
Effect.gen(function* () {
const queue = yield* JobsQueue;
yield* AWS.SQS.messages(queue, {
batchSize: 10,
maximumBatchingWindowInSeconds: 20,
}).subscribe((stream) =>
stream.pipe(
Stream.runForEach((record) =>
Effect.logInfo(
`processed SQS message ${record.messageId}: ${record.body ?? ""}`,
),
),
),
);
}).pipe(
Effect.provide(
Layer.provideMerge(
Layer.mergeAll(Server.SQSQueueEventSource, JobsQueueLive),
Layer.mergeAll(
AWS.SQS.ReceiveMessageLive,
AWS.SQS.DeleteMessageBatchLive,
),
),
),
),
) {}
@@ -1,67 +0,0 @@
import * as AWS from "alchemy/AWS";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
import { JobsQueue, JobsQueueLive } from "./JobsQueue.ts";
export default class ApiTask extends AWS.ECS.Task<ApiTask>()(
"ApiTask",
{
main: import.meta.filename,
cpu: 512,
memory: 1024,
port: 3000,
},
Effect.gen(function* () {
const queue = yield* JobsQueue;
const sendMessage = yield* AWS.SQS.SendMessage.bind(queue);
return {
fetch: Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
const url = new URL(request.originalUrl);
if (request.method === "GET" && url.pathname === "/") {
return yield* HttpServerResponse.json({
ok: true,
routes: ["GET /", "GET /enqueue?message=hello"],
});
}
if (request.method === "GET" && url.pathname === "/enqueue") {
const message = url.searchParams.get("message") ?? "hello from ECS";
const body = JSON.stringify({
message,
enqueuedAt: new Date().toISOString(),
});
const result = yield* sendMessage({
MessageBody: body,
});
return yield* HttpServerResponse.json({
ok: true,
message,
messageId: result.MessageId,
});
}
return HttpServerResponse.text("Not found", { status: 404 });
}).pipe(
Effect.catch(() =>
Effect.succeed(
HttpServerResponse.text("Internal server error", { status: 500 }),
),
),
),
};
}).pipe(
Effect.provide(
Layer.mergeAll(
JobsQueueLive,
AWS.SQS.SendMessageLive,
AWS.SQS.DeleteMessageBatchLive,
),
),
),
) {}
@@ -1,16 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"include": ["alchemy.run.ts", "src/**/*.ts"],
"compilerOptions": {
"noEmit": true,
"rootDir": ".",
"module": "Preserve",
"moduleResolution": "Bundler",
"target": "ESNext"
},
"references": [
{
"path": "../../packages/alchemy/tsconfig.json"
}
]
}
@@ -1,55 +0,0 @@
# AWS EKS Auto Mode Example
This example is fully TypeScript-driven. It provisions:
- `AWS.EC2.Network`
- `AWS.EKS.AutoCluster`
- `AWS.EKS.AccessEntry` for cluster-admin access
- `AWS.EKS.Addon` for `metrics-server` and `snapshot-controller`
- `AWS.EKS.LoadBalancedWorkload` for deployment + public service composition
- `AWS.EKS.PodIdentityWorkload` for workload identity + deployment composition
- `Kubernetes.Namespace`
- `Kubernetes.Job`
There is no YAML or `kubectl apply` step. The workloads are declared in
[`alchemy.run.ts`](./alchemy.run.ts) and reconciled by the EKS cluster resource.
## Commands
```sh
bun install
bun run --filter aws-eks-example deploy
bun run --filter aws-eks-example destroy
```
## Cluster Access
By default, the example grants cluster-admin access to the IAM principal that is
running the deploy. If your current caller is not a normal IAM user or IAM role,
set this before deploy:
```sh
export EKS_ADMIN_PRINCIPAL_ARN=arn:aws:iam::123456789012:role/YourAdminRole
```
## What Gets Deployed
The example creates these in-cluster workloads in code:
- a `demo` namespace
- an `echo-server` workload created with `AWS.EKS.LoadBalancedWorkload`
- a `pod-identity-demo` workload created with `AWS.EKS.PodIdentityWorkload`
- a `cluster-info` job
The pod identity workload creates the Kubernetes service account, IAM role,
`AWS.EKS.PodIdentityAssociation`, and deployment together.
## Optional Inspection
If you want to inspect the cluster manually after deploy, you can still use your
normal kubeconfig flow, for example:
```sh
aws eks update-kubeconfig --name alchemy-eks-auto-example --region "$AWS_REGION"
kubectl get pods -n demo
```
@@ -1,251 +0,0 @@
import * as STS from "@distilled.cloud/aws/sts";
import * as Alchemy from "alchemy";
import * as AWS from "alchemy/AWS";
import * as EC2 from "alchemy/AWS/EC2";
import * as EKS from "alchemy/AWS/EKS";
import * as Kubernetes from "alchemy/Kubernetes";
import * as Output from "alchemy/Output";
import * as Config from "effect/Config";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
const aws = AWS.providers();
const EKS_ADMIN_PRINCIPAL_ARN = Config.string("EKS_ADMIN_PRINCIPAL_ARN").pipe(
Config.option,
Config.map(Option.getOrUndefined),
);
const clusterName = "alchemy-eks-auto-example";
const namespace = "demo";
const serviceAccount = "pod-identity-demo";
const toIamPrincipalArn = (arn: string): string | undefined => {
const assumedRole = arn.match(
/^arn:([^:]+):sts::([0-9]{12}):assumed-role\/(.+)\/[^/]+$/,
);
if (assumedRole) {
const [, partition, accountId, rolePath] = assumedRole;
return `arn:${partition}:iam::${accountId}:role/${rolePath}`;
}
if (arn.includes(":role/") || arn.includes(":user/")) {
return arn;
}
return undefined;
};
const resolveClusterAdminPrincipalArn = Effect.gen(function* () {
const configured = yield* EKS_ADMIN_PRINCIPAL_ARN;
if (configured) {
return configured;
}
const caller = yield* STS.getCallerIdentity({});
const principalArn =
typeof caller.Arn === "string" ? toIamPrincipalArn(caller.Arn) : undefined;
if (!principalArn) {
return yield* Effect.fail(
new Error(
"Unable to infer an IAM principal ARN for cluster access. Set EKS_ADMIN_PRINCIPAL_ARN before deploy.",
),
);
}
return principalArn;
});
export default Alchemy.Stack(
"AwsEksExample",
{
providers: aws,
state: Alchemy.localState(),
},
Effect.gen(function* () {
const tags = {
Example: "aws-eks",
Surface: "eks",
Mode: "auto",
};
const clusterAdminPrincipalArn = yield* resolveClusterAdminPrincipalArn;
const network = yield* EC2.Network("Network", {
cidrBlock: "10.42.0.0/16",
availabilityZones: 2,
nat: "single",
tags,
});
const cluster = yield* EKS.AutoCluster("Cluster", {
clusterName,
network,
tags,
});
const clusterAdmin = yield* EKS.AccessEntry("ClusterAdmin", {
clusterName: cluster.cluster.clusterName,
principalArn: clusterAdminPrincipalArn,
accessPolicies: [
{
policyArn:
"arn:aws:eks::aws:cluster-access-policy/AmazonEKSClusterAdminPolicy",
accessScope: {
type: "cluster",
},
},
],
tags,
});
const metricsServer = yield* EKS.Addon("MetricsServer", {
clusterName: cluster.cluster.clusterName,
addonName: "metrics-server",
tags,
});
const snapshotController = yield* EKS.Addon("SnapshotController", {
clusterName: cluster.cluster.clusterName,
addonName: "snapshot-controller",
tags,
});
const demoNamespace = yield* Kubernetes.Namespace("DemoNamespace", {
cluster: cluster.cluster,
name: namespace,
labels: {
"app.kubernetes.io/part-of": "aws-eks-example",
},
});
const echoServer = yield* EKS.LoadBalancedWorkload("EchoServer", {
cluster: cluster.cluster,
namespace: demoNamespace,
name: "echo-server",
labels: {
"app.kubernetes.io/name": "echo-server",
"app.kubernetes.io/part-of": "aws-eks-example",
},
replicas: 2,
containers: [
{
name: "echo-server",
image: "registry.k8s.io/echoserver:1.10",
ports: [
{
containerPort: 8080,
name: "http",
},
],
resources: {
requests: {
cpu: "50m",
memory: "64Mi",
},
limits: {
cpu: "250m",
memory: "128Mi",
},
},
},
],
ports: [
{
name: "http",
port: 80,
targetPort: 8080,
},
],
});
const podIdentityWorkload = yield* EKS.PodIdentityWorkload(
"PodIdentityDemo",
{
cluster: cluster.cluster,
namespace: demoNamespace,
name: "pod-identity-demo",
serviceAccountName: serviceAccount,
tags,
serviceAccountLabels: {
"app.kubernetes.io/name": serviceAccount,
"app.kubernetes.io/part-of": "aws-eks-example",
},
labels: {
"app.kubernetes.io/name": "pod-identity-demo",
"app.kubernetes.io/part-of": "aws-eks-example",
},
containers: [
{
name: "aws-cli",
image: "public.ecr.aws/aws-cli/aws-cli:2.17.37",
command: ["/bin/sh", "-lc"],
args: [
[
"while true; do",
" date;",
" aws sts get-caller-identity;",
" sleep 60;",
"done",
].join(" "),
],
resources: {
requests: {
cpu: "50m",
memory: "64Mi",
},
limits: {
cpu: "250m",
memory: "128Mi",
},
},
},
],
},
);
const clusterInfoJob = yield* Kubernetes.Job("ClusterInfoJob", {
cluster: cluster.cluster,
namespace: demoNamespace,
name: "cluster-info",
labels: {
"app.kubernetes.io/name": "cluster-info",
"app.kubernetes.io/part-of": "aws-eks-example",
},
containers: [
{
name: "cluster-info",
image: "public.ecr.aws/docker/library/busybox:1.36",
command: ["/bin/sh", "-lc"],
args: [
[
'echo "demo workload is running on EKS Auto Mode";',
"nslookup echo-server.demo.svc.cluster.local || true;",
].join(" "),
],
},
],
});
return {
clusterName: cluster.cluster.clusterName,
clusterArn: cluster.cluster.clusterArn,
endpoint: cluster.cluster.endpoint,
adminPrincipalArn: clusterAdmin.principalArn,
namespace: demoNamespace.name,
serviceAccount: podIdentityWorkload.serviceAccount.name,
podIdentityAssociationArn:
podIdentityWorkload.podIdentityAssociation.associationArn,
workloadRoleArn: podIdentityWorkload.roleArn,
metricsServerAddonArn: metricsServer.addonArn,
snapshotControllerAddonArn: snapshotController.addonArn,
echoDeploymentName: echoServer.deployment.name,
echoServiceName: echoServer.service?.name,
podIdentityDeploymentName: podIdentityWorkload.deployment.name,
clusterInfoJobName: clusterInfoJob.name,
accessSummary: Output.interpolate`Granted cluster-admin access on ${cluster.cluster.clusterName} to ${clusterAdmin.principalArn}.`,
workloadSummary: Output.interpolate`Demo workloads are declared in TypeScript and reconciled into namespace ${demoNamespace.name} on ${cluster.cluster.clusterName}.`,
};
}).pipe(Effect.orDie),
);
@@ -1,23 +0,0 @@
{
"name": "aws-eks-example",
"version": "0.0.0",
"private": true,
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "git+https://github.com/alchemy-run/alchemy-effect.git",
"directory": "examples/aws-eks"
},
"scripts": {
"build": "tsc -b",
"deploy": "alchemy deploy",
"dev": "alchemy dev",
"destroy": "alchemy destroy"
},
"dependencies": {
"@distilled.cloud/aws": "catalog:",
"@effect/platform-node": "catalog:",
"alchemy": "workspace:*",
"effect": "catalog:"
}
}
@@ -1,20 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"include": ["alchemy.run.ts"],
"compilerOptions": {
"noEmit": true,
"rootDir": "../..",
"module": "Preserve",
"moduleResolution": "Bundler",
"target": "ESNext",
"paths": {
"alchemy": ["../../packages/alchemy/src/index.ts"],
"alchemy/*": ["../../packages/alchemy/src/*"]
}
},
"references": [
{
"path": "../../packages/alchemy/tsconfig.json"
}
]
}
@@ -1,87 +0,0 @@
import * as Alchemy from "alchemy";
import * as AWS from "alchemy/AWS";
import * as Output from "alchemy/Output";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import JobFunction from "./src/JobFunction.ts";
const aws = AWS.providers();
const dashboardRegion = process.env.AWS_REGION ?? "us-west-2";
export default Alchemy.Stack(
"JobLambdaHttpApi",
{
providers: Layer.mergeAll(
// Fully configured cloud provider Layers go here:
aws,
),
state: Alchemy.localState(),
},
Effect.gen(function* () {
const func = yield* JobFunction;
const dashboard = yield* AWS.CloudWatch.Dashboard("JobDashboard", {
DashboardBody: func.functionName.pipe(
Output.map((functionName) => ({
widgets: [
{
type: "metric",
x: 0,
y: 0,
width: 12,
height: 6,
properties: {
title: "Lambda Invocations and Errors",
region: dashboardRegion,
stat: "Sum",
period: 300,
metrics: [
["AWS/Lambda", "Invocations", "FunctionName", functionName],
["AWS/Lambda", "Errors", "FunctionName", functionName],
],
},
},
{
type: "metric",
x: 12,
y: 0,
width: 12,
height: 6,
properties: {
title: "Lambda Duration",
region: dashboardRegion,
stat: "Average",
period: 300,
metrics: [
["AWS/Lambda", "Duration", "FunctionName", functionName],
],
},
},
],
})),
),
});
const alarm = yield* AWS.CloudWatch.Alarm("JobFunctionErrorsAlarm", {
AlarmDescription:
"Alerts when the example Lambda function reports errors.",
MetricName: "Errors",
Namespace: "AWS/Lambda",
Statistic: "Sum",
Period: 300,
EvaluationPeriods: 1,
Threshold: 1,
ComparisonOperator: "GreaterThanOrEqualToThreshold",
TreatMissingData: "notBreaching",
Dimensions: [
{
Name: "FunctionName",
Value: func.functionName,
},
],
});
return {
url: Output.interpolate`${func.functionUrl}?jobId=foo`,
dashboardName: dashboard.dashboardName,
alarmName: alarm.alarmName,
};
}),
);
@@ -1,23 +0,0 @@
{
"name": "aws-lambda-httpapi",
"version": "0.0.0",
"private": true,
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "git+https://github.com/alchemy-run/alchemy-effect.git",
"directory": "examples/aws-lambda-httpapi"
},
"scripts": {
"build": "tsc -b",
"deploy": "alchemy deploy",
"dev": "alchemy dev",
"destroy": "alchemy destroy"
},
"dependencies": {
"@distilled.cloud/aws": "catalog:",
"@effect/platform-node": "catalog:",
"alchemy": "workspace:*",
"effect": "catalog:"
}
}
@@ -1,13 +0,0 @@
import * as S from "effect/Schema";
export type JobId = S.Schema.Type<typeof JobId>;
export const JobId = S.String.annotate({
description: "The ID of the job",
});
export class Job extends S.Class<Job>("Job")({
id: JobId,
content: S.String,
}) {}
export const decodeJob = S.decodeEffect(Job);
@@ -1,106 +0,0 @@
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
import * as HttpApi from "effect/unstable/httpapi/HttpApi";
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
import * as HttpApiEndpoint from "effect/unstable/httpapi/HttpApiEndpoint";
import * as HttpApiGroup from "effect/unstable/httpapi/HttpApiGroup";
import { Job, JobId } from "./Job.ts";
import { JobNotifications, NotifyJobError } from "./JobNotifications.ts";
import { GetJobError, JobStorage, PutJobError } from "./JobStorage.ts";
export const getJob = HttpApiEndpoint.get("getJob", "/", {
success: Job,
query: {
jobId: JobId.pipe(Schema.optional),
},
});
export const createJob = HttpApiEndpoint.post("createJob", "/", {
success: JobId,
payload: Schema.Struct({
content: Schema.String,
}),
});
export const JobApi = HttpApi.make("JobApi").add(
HttpApiGroup.make("Jobs").add(getJob, createJob),
);
export const JobApiLive = HttpApiBuilder.layer(JobApi).pipe(
Layer.provide(
HttpApiBuilder.group(JobApi, "Jobs", (handlers) =>
Effect.gen(function* () {
const jobService = yield* JobStorage;
const notifications = yield* JobNotifications;
return handlers
.handle(
"getJob",
Effect.fn(function* (req) {
if (!req.query.jobId) {
return HttpServerResponse.text("Job ID is required", {
status: 400,
});
}
const job = yield* jobService.getJob(req.query.jobId).pipe(
Effect.catchTag("GetJobError", (error) =>
Effect.succeed(
HttpServerResponse.text(error.message, {
status: 500,
}),
),
),
);
if (job instanceof GetJobError) {
return HttpServerResponse.text(job.message, {
status: 500,
});
}
if (!job) {
return HttpServerResponse.text("Job not found", {
status: 404,
});
}
return job!;
}),
)
.handle(
"createJob",
Effect.fn(function* (req) {
const jobId = crypto.randomUUID();
const job = yield* jobService
.putJob({
id: jobId,
content: req.payload.content,
})
.pipe(
Effect.catchTag("PutJobError", (error) =>
Effect.succeed(error),
),
);
if (job instanceof PutJobError) {
return HttpServerResponse.text(job.message, {
status: 500,
});
}
const notificationResult = yield* notifications
.notifyJobCreated(job)
.pipe(
Effect.catchTag("NotifyJobError", (error) =>
Effect.succeed(error),
),
);
if (notificationResult instanceof NotifyJobError) {
return HttpServerResponse.text(notificationResult.message, {
status: 500,
});
}
return job.id;
}),
);
}),
),
),
);
@@ -1,29 +0,0 @@
import * as AWS from "alchemy/AWS";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Etag from "effect/unstable/http/Etag";
import * as HttpPlatform from "effect/unstable/http/HttpPlatform";
import * as HttpRouter from "effect/unstable/http/HttpRouter";
import { JobApiLive } from "./JobApi.ts";
import { JobNotificationsSNS } from "./JobNotifications.ts";
import { JobStorageDynamoDB } from "./JobStorage.ts";
export default class JobFunction extends AWS.Lambda.Function<JobFunction>()(
"JobFunction",
{
main: import.meta.filename,
url: true,
},
HttpRouter.toHttpEffect(JobApiLive).pipe(
Effect.map((fetch) => ({ fetch })),
Effect.provide(
Layer.mergeAll(
JobStorageDynamoDB,
JobNotificationsSNS,
// TODO(sam): these should be provided to us automatically
HttpPlatform.layer,
Etag.layer,
),
),
),
) {}
@@ -1,89 +0,0 @@
import * as AWS from "alchemy/AWS";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Stream from "effect/Stream";
import type { Job } from "./Job.ts";
export class NotifyJobError extends Data.TaggedError("NotifyJobError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
type JobNotification = {
type: "job.created";
job: Job;
};
export class JobNotifications extends Context.Service<
JobNotifications,
{
notifyJobCreated(job: Job): Effect.Effect<void, NotifyJobError>;
}
>()("JobNotifications") {}
export const JobNotificationsSNS = Layer.provideMerge(
Layer.effect(
JobNotifications,
Effect.gen(function* () {
const topic = yield* AWS.SNS.Topic("JobNotificationsTopic", {
attributes: {
DisplayName: "job-notifications",
},
});
const publish = yield* AWS.SNS.Publish.bind(topic);
yield* AWS.SNS.notifications(topic).subscribe((stream) =>
stream.pipe(
Stream.mapEffect((notification) =>
Effect.try({
try: () => JSON.parse(notification.Message) as JobNotification,
catch: (cause) =>
new NotifyJobError({
message: "Failed to parse SNS job notification",
cause,
}),
}).pipe(
Effect.flatMap((payload) =>
Effect.logInfo(
`Job notification received: ${payload.type} (${payload.job.id})`,
),
),
// Keep the example resilient to malformed demo messages.
Effect.catchTag("NotifyJobError", (error) =>
Effect.logWarning(error.message),
),
),
),
Stream.runDrain,
),
);
const notifyJobCreated = (job: Job) =>
publish({
Subject: "JobCreated",
Message: JSON.stringify({
type: "job.created",
job,
} satisfies JobNotification),
}).pipe(
Effect.asVoid,
Effect.mapError(
(cause) =>
new NotifyJobError({
message: `Failed to publish job notification for "${job.id}"`,
cause,
}),
),
);
return JobNotifications.of({
notifyJobCreated,
});
}),
),
Layer.mergeAll(AWS.Lambda.TopicEventSource, AWS.SNS.PublishLive),
);
@@ -1,230 +0,0 @@
import * as DynamoDB from "alchemy/AWS/DynamoDB";
import * as Lambda from "alchemy/AWS/Lambda";
import * as S3 from "alchemy/AWS/S3";
import * as SQS from "alchemy/AWS/SQS";
import * as RemovalPolicy from "alchemy/RemovalPolicy";
import { Stack } from "alchemy/Stack";
import * as Console from "effect/Console";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Stream from "effect/Stream";
import type { Job } from "./Job.ts";
export class PutJobError extends Data.TaggedError("PutJobError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
export class GetJobError extends Data.TaggedError("GetJobError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
export class JobStorage extends Context.Service<
JobStorage,
{
putJob(job: Job): Effect.Effect<Job, PutJobError>;
getJob(jobId: string): Effect.Effect<Job | undefined, GetJobError>;
}
>()("JobStorage") {}
export const JobStorageDynamoDB = Layer.provideMerge(
Layer.effect(
JobStorage,
Effect.gen(function* () {
const stack = yield* Stack;
const table = yield* DynamoDB.Table("JobsTable", {
partitionKey: "id",
attributes: {
id: "S",
},
});
const queue = yield* SQS.Queue("JobsQueue").pipe(
RemovalPolicy.retain(stack.stage === "prod"),
);
const getItem = yield* DynamoDB.GetItem.bind(table);
const putItem = yield* DynamoDB.PutItem.bind(table);
const sink = yield* SQS.QueueSink.bind(queue);
yield* DynamoDB.stream(table, {
streamViewType: "NEW_AND_OLD_IMAGES",
startingPosition: "LATEST",
batchSize: 10,
}).process((stream) =>
stream.pipe(
Stream.map((record) =>
JSON.stringify({
eventName: record.eventName,
keys: record.dynamodb.Keys,
newImage: record.dynamodb.NewImage,
oldImage: record.dynamodb.OldImage,
}),
),
Stream.run(sink),
),
);
const putJob = (job: Job) =>
putItem({
Item: {
id: { S: job.id },
content: { S: job.content },
},
}).pipe(
Effect.map(() => job),
Effect.tapError(Console.log),
Effect.catchCause((cause) =>
Effect.fail(
new PutJobError({
message: `Failed to store job "${job.id}": ${cause}`,
cause,
}),
),
),
);
const getJob = (jobId: string) =>
getItem({
Key: {
id: { S: jobId },
},
}).pipe(
Effect.flatMap((item) =>
item.Item
? Effect.try({
try: () =>
({
id: item.Item?.id?.S ?? jobId,
content: item.Item?.content?.S ?? "",
}) as Job,
catch: (cause) =>
new GetJobError({
message: `Failed to parse job "${jobId}": ${cause}`,
cause,
}),
})
: Effect.succeed(undefined),
),
Effect.tapError(Console.log),
Effect.catchCause((cause) =>
Effect.fail(
new GetJobError({
message: `Failed to load job "${jobId}": ${cause}`,
cause,
}),
),
),
);
return JobStorage.of({
putJob,
getJob,
});
}),
),
Layer.mergeAll(Lambda.TableEventSource, SQS.QueueSinkLive).pipe(
Layer.provideMerge(
Layer.mergeAll(
DynamoDB.GetItemLive,
DynamoDB.PutItemLive,
SQS.SendMessageBatchLive,
),
),
),
);
export const JobStorageS3 = Layer.provideMerge(
Layer.effect(
JobStorage,
Effect.gen(function* () {
const stack = yield* Stack;
const bucket = yield* S3.Bucket("JobsBucket");
const queue = yield* SQS.Queue("JobsQueue").pipe(
RemovalPolicy.retain(stack.stage === "prod"),
);
const getObject = yield* S3.GetObject.bind(bucket);
const putObject = yield* S3.PutObject.bind(bucket);
const sink = yield* SQS.QueueSink.bind(queue);
const putJob = (job: Job) =>
putObject({
Key: job.id,
Body: JSON.stringify(job),
}).pipe(
Effect.map(() => job),
Effect.tapError(Console.log),
Effect.catchCause((cause) =>
Effect.fail(
new PutJobError({
message: `Failed to store job "${job.id}": ${cause}`,
cause,
}),
),
),
);
const getJob = (jobId: string) =>
getObject({
Key: jobId,
}).pipe(
Effect.catchTag("NoSuchKey", () => Effect.succeed(undefined)),
Effect.flatMap(
(item) =>
item?.Body?.pipe(
Stream.decodeText,
Stream.mkString,
Effect.flatMap((body) =>
Effect.try({
try: () => JSON.parse(body) as Job,
catch: (cause) =>
new GetJobError({
message: `Failed to parse job "${jobId}": ${cause}`,
cause,
}),
}),
),
) ?? Effect.succeed(undefined),
),
Effect.tapError(Console.log),
Effect.catchCause((cause) =>
Effect.fail(
new GetJobError({
message: `Failed to load job "${jobId}": ${cause}`,
cause,
}),
),
),
);
yield* S3.notifications(bucket).subscribe((stream) =>
stream.pipe(
Stream.flatMap((item) =>
Stream.fromEffect(getJob(item.key).pipe(Effect.orDie)),
),
Stream.filter((job): job is Job => job !== undefined),
Stream.map((job) => JSON.stringify(job)),
Stream.run(sink),
),
);
return JobStorage.of({
putJob,
getJob,
});
}),
),
Layer.mergeAll(Lambda.BucketEventSource, SQS.QueueSinkLive).pipe(
Layer.provideMerge(
Layer.mergeAll(
S3.GetObjectLive,
S3.PutObjectLive,
SQS.SendMessageBatchLive,
),
),
),
);
@@ -1,16 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"include": ["alchemy.run.ts", "src/**/*.ts"],
"compilerOptions": {
"noEmit": true,
"rootDir": ".",
"module": "Preserve",
"moduleResolution": "Bundler",
"target": "ESNext"
},
"references": [
{
"path": "../../packages/alchemy/tsconfig.json"
}
]
}
@@ -1,87 +0,0 @@
import * as Alchemy from "alchemy";
import * as AWS from "alchemy/AWS";
import * as Output from "alchemy/Output";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import JobFunction from "./src/JobFunction.ts";
const aws = AWS.providers();
const dashboardRegion = process.env.AWS_REGION ?? "us-west-2";
export default Alchemy.Stack(
"JobLambdaRpc",
{
providers: Layer.mergeAll(
// Fully configured cloud provider Layers go here:
aws,
),
state: Alchemy.localState(),
},
Effect.gen(function* () {
const func = yield* JobFunction;
const dashboard = yield* AWS.CloudWatch.Dashboard("JobDashboard", {
DashboardBody: func.functionName.pipe(
Output.map((functionName) => ({
widgets: [
{
type: "metric",
x: 0,
y: 0,
width: 12,
height: 6,
properties: {
title: "Lambda Invocations and Errors",
region: dashboardRegion,
stat: "Sum",
period: 300,
metrics: [
["AWS/Lambda", "Invocations", "FunctionName", functionName],
["AWS/Lambda", "Errors", "FunctionName", functionName],
],
},
},
{
type: "metric",
x: 12,
y: 0,
width: 12,
height: 6,
properties: {
title: "Lambda Duration",
region: dashboardRegion,
stat: "Average",
period: 300,
metrics: [
["AWS/Lambda", "Duration", "FunctionName", functionName],
],
},
},
],
})),
),
});
const alarm = yield* AWS.CloudWatch.Alarm("JobFunctionErrorsAlarm", {
AlarmDescription:
"Alerts when the example Lambda function reports errors.",
MetricName: "Errors",
Namespace: "AWS/Lambda",
Statistic: "Sum",
Period: 300,
EvaluationPeriods: 1,
Threshold: 1,
ComparisonOperator: "GreaterThanOrEqualToThreshold",
TreatMissingData: "notBreaching",
Dimensions: [
{
Name: "FunctionName",
Value: func.functionName,
},
],
});
return {
url: func.functionUrl,
dashboardName: dashboard.dashboardName,
alarmName: alarm.alarmName,
};
}),
);
@@ -1,23 +0,0 @@
{
"name": "aws-lambda-rpc",
"version": "0.0.0",
"private": true,
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "git+https://github.com/alchemy-run/alchemy-effect.git",
"directory": "examples/aws-lambda-rpc"
},
"scripts": {
"build": "tsc -b",
"deploy": "alchemy deploy",
"dev": "alchemy dev",
"destroy": "alchemy destroy"
},
"dependencies": {
"@distilled.cloud/aws": "catalog:",
"@effect/platform-node": "catalog:",
"alchemy": "workspace:*",
"effect": "catalog:"
}
}
@@ -1,13 +0,0 @@
import * as S from "effect/Schema";
export type JobId = S.Schema.Type<typeof JobId>;
export const JobId = S.String.annotate({
description: "The ID of the job",
});
export class Job extends S.Class<Job>("Job")({
id: JobId,
content: S.String,
}) {}
export const decodeJob = S.decodeEffect(Job);
@@ -1,18 +0,0 @@
import * as AWS from "alchemy/AWS";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { JobNotificationsSNS } from "./JobNotifications.ts";
import { JobRpcHttpEffect } from "./JobRpcApi.ts";
import { JobStorageDynamoDB } from "./JobStorage.ts";
export default class JobFunction extends AWS.Lambda.Function<JobFunction>()(
"JobFunction",
{
main: import.meta.filename,
url: true,
},
JobRpcHttpEffect.pipe(
Effect.map((fetch) => ({ fetch })),
Effect.provide(Layer.mergeAll(JobStorageDynamoDB, JobNotificationsSNS)),
),
) {}
@@ -1,89 +0,0 @@
import * as AWS from "alchemy/AWS";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Stream from "effect/Stream";
import type { Job } from "./Job.ts";
export class NotifyJobError extends Data.TaggedError("NotifyJobError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
type JobNotification = {
type: "job.created";
job: Job;
};
export class JobNotifications extends Context.Service<
JobNotifications,
{
notifyJobCreated(job: Job): Effect.Effect<void, NotifyJobError>;
}
>()("JobNotifications") {}
export const JobNotificationsSNS = Layer.provideMerge(
Layer.effect(
JobNotifications,
Effect.gen(function* () {
const topic = yield* AWS.SNS.Topic("JobNotificationsTopic", {
attributes: {
DisplayName: "job-notifications",
},
});
const publish = yield* AWS.SNS.Publish.bind(topic);
yield* AWS.SNS.notifications(topic).subscribe((stream) =>
stream.pipe(
Stream.mapEffect((notification) =>
Effect.try({
try: () => JSON.parse(notification.Message) as JobNotification,
catch: (cause) =>
new NotifyJobError({
message: "Failed to parse SNS job notification",
cause,
}),
}).pipe(
Effect.flatMap((payload) =>
Effect.logInfo(
`Job notification received: ${payload.type} (${payload.job.id})`,
),
),
// Keep the example resilient to malformed demo messages.
Effect.catchTag("NotifyJobError", (error) =>
Effect.logWarning(error.message),
),
),
),
Stream.runDrain,
),
);
const notifyJobCreated = (job: Job) =>
publish({
Subject: "JobCreated",
Message: JSON.stringify({
type: "job.created",
job,
} satisfies JobNotification),
}).pipe(
Effect.asVoid,
Effect.mapError(
(cause) =>
new NotifyJobError({
message: `Failed to publish job notification for "${job.id}"`,
cause,
}),
),
);
return JobNotifications.of({
notifyJobCreated,
});
}),
),
Layer.mergeAll(AWS.Lambda.TopicEventSource, AWS.SNS.PublishLive),
);
@@ -1,86 +0,0 @@
import { Effect, Layer, Schema } from "effect";
import {
Rpc,
RpcGroup,
RpcSerialization,
RpcServer,
} from "effect/unstable/rpc";
import { Job, JobId } from "./Job.ts";
import { JobNotifications } from "./JobNotifications.ts";
import { JobStorage } from "./JobStorage.ts";
export class JobNotFound extends Schema.TaggedClass<JobNotFound>()(
"JobNotFound",
{ jobId: JobId },
) {}
export class GetJobFailed extends Schema.TaggedClass<GetJobFailed>()(
"GetJobFailed",
{ message: Schema.String },
) {}
export class PutJobFailed extends Schema.TaggedClass<PutJobFailed>()(
"PutJobFailed",
{ message: Schema.String },
) {}
const getJob = Rpc.make("getJob", {
success: Job,
error: Schema.Union([JobNotFound, GetJobFailed]),
payload: {
jobId: JobId,
},
});
const createJob = Rpc.make("createJob", {
success: JobId,
error: PutJobFailed,
payload: {
content: Schema.String,
},
});
export class JobRpcs extends RpcGroup.make(getJob, createJob) {}
export const JobRpcsLive = JobRpcs.toLayer(
Effect.gen(function* () {
const jobService = yield* JobStorage;
const notifications = yield* JobNotifications;
return {
getJob: ({ jobId }) =>
jobService.getJob(jobId).pipe(
Effect.mapError(
(error) =>
new GetJobFailed({
message: error.message,
}),
),
Effect.flatMap((job) =>
job ? Effect.succeed(job) : Effect.fail(new JobNotFound({ jobId })),
),
),
createJob: ({ content }) =>
Effect.gen(function* () {
const jobId = crypto.randomUUID();
const job = yield* jobService.putJob({
id: jobId,
content,
});
yield* notifications.notifyJobCreated(job);
return job.id;
}).pipe(
Effect.mapError(
(error) =>
new PutJobFailed({
message: error.message,
}),
),
),
};
}),
);
export const JobRpcHttpEffect = RpcServer.toHttpEffect(JobRpcs).pipe(
Effect.provide(Layer.mergeAll(JobRpcsLive, RpcSerialization.layerJson)),
);
@@ -1,230 +0,0 @@
import * as DynamoDB from "alchemy/AWS/DynamoDB";
import * as Lambda from "alchemy/AWS/Lambda";
import * as S3 from "alchemy/AWS/S3";
import * as SQS from "alchemy/AWS/SQS";
import * as RemovalPolicy from "alchemy/RemovalPolicy";
import { Stack } from "alchemy/Stack";
import * as Console from "effect/Console";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Stream from "effect/Stream";
import type { Job } from "./Job.ts";
export class PutJobError extends Data.TaggedError("PutJobError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
export class GetJobError extends Data.TaggedError("GetJobError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
export class JobStorage extends Context.Service<
JobStorage,
{
putJob(job: Job): Effect.Effect<Job, PutJobError>;
getJob(jobId: string): Effect.Effect<Job | undefined, GetJobError>;
}
>()("JobStorage") {}
export const JobStorageDynamoDB = Layer.provideMerge(
Layer.effect(
JobStorage,
Effect.gen(function* () {
const stack = yield* Stack;
const table = yield* DynamoDB.Table("JobsTable", {
partitionKey: "id",
attributes: {
id: "S",
},
});
const queue = yield* SQS.Queue("JobsQueue").pipe(
RemovalPolicy.retain(stack.stage === "prod"),
);
const getItem = yield* DynamoDB.GetItem.bind(table);
const putItem = yield* DynamoDB.PutItem.bind(table);
const sink = yield* SQS.QueueSink.bind(queue);
yield* DynamoDB.stream(table, {
streamViewType: "NEW_AND_OLD_IMAGES",
startingPosition: "LATEST",
batchSize: 10,
}).process((stream) =>
stream.pipe(
Stream.map((record) =>
JSON.stringify({
eventName: record.eventName,
keys: record.dynamodb.Keys,
newImage: record.dynamodb.NewImage,
oldImage: record.dynamodb.OldImage,
}),
),
Stream.run(sink),
),
);
const putJob = (job: Job) =>
putItem({
Item: {
id: { S: job.id },
content: { S: job.content },
},
}).pipe(
Effect.map(() => job),
Effect.tapError(Console.log),
Effect.catchCause((cause) =>
Effect.fail(
new PutJobError({
message: `Failed to store job "${job.id}": ${cause}`,
cause,
}),
),
),
);
const getJob = (jobId: string) =>
getItem({
Key: {
id: { S: jobId },
},
}).pipe(
Effect.flatMap((item) =>
item.Item
? Effect.try({
try: () =>
({
id: item.Item?.id?.S ?? jobId,
content: item.Item?.content?.S ?? "",
}) as Job,
catch: (cause) =>
new GetJobError({
message: `Failed to parse job "${jobId}": ${cause}`,
cause,
}),
})
: Effect.succeed(undefined),
),
Effect.tapError(Console.log),
Effect.catchCause((cause) =>
Effect.fail(
new GetJobError({
message: `Failed to load job "${jobId}": ${cause}`,
cause,
}),
),
),
);
return JobStorage.of({
putJob,
getJob,
});
}),
),
Layer.mergeAll(Lambda.TableEventSource, SQS.QueueSinkLive).pipe(
Layer.provideMerge(
Layer.mergeAll(
DynamoDB.GetItemLive,
DynamoDB.PutItemLive,
SQS.SendMessageBatchLive,
),
),
),
);
export const JobStorageS3 = Layer.provideMerge(
Layer.effect(
JobStorage,
Effect.gen(function* () {
const stack = yield* Stack;
const bucket = yield* S3.Bucket("JobsBucket");
const queue = yield* SQS.Queue("JobsQueue").pipe(
RemovalPolicy.retain(stack.stage === "prod"),
);
const getObject = yield* S3.GetObject.bind(bucket);
const putObject = yield* S3.PutObject.bind(bucket);
const sink = yield* SQS.QueueSink.bind(queue);
const putJob = (job: Job) =>
putObject({
Key: job.id,
Body: JSON.stringify(job),
}).pipe(
Effect.map(() => job),
Effect.tapError(Console.log),
Effect.catchCause((cause) =>
Effect.fail(
new PutJobError({
message: `Failed to store job "${job.id}": ${cause}`,
cause,
}),
),
),
);
const getJob = (jobId: string) =>
getObject({
Key: jobId,
}).pipe(
Effect.catchTag("NoSuchKey", () => Effect.succeed(undefined)),
Effect.flatMap(
(item) =>
item?.Body?.pipe(
Stream.decodeText,
Stream.mkString,
Effect.flatMap((body) =>
Effect.try({
try: () => JSON.parse(body) as Job,
catch: (cause) =>
new GetJobError({
message: `Failed to parse job "${jobId}": ${cause}`,
cause,
}),
}),
),
) ?? Effect.succeed(undefined),
),
Effect.tapError(Console.log),
Effect.catchCause((cause) =>
Effect.fail(
new GetJobError({
message: `Failed to load job "${jobId}": ${cause}`,
cause,
}),
),
),
);
yield* S3.notifications(bucket).subscribe((stream) =>
stream.pipe(
Stream.flatMap((item) =>
Stream.fromEffect(getJob(item.key).pipe(Effect.orDie)),
),
Stream.filter((job): job is Job => job !== undefined),
Stream.map((job) => JSON.stringify(job)),
Stream.run(sink),
),
);
return JobStorage.of({
putJob,
getJob,
});
}),
),
Layer.mergeAll(Lambda.BucketEventSource, SQS.QueueSinkLive).pipe(
Layer.provideMerge(
Layer.mergeAll(
S3.GetObjectLive,
S3.PutObjectLive,
SQS.SendMessageBatchLive,
),
),
),
);
@@ -1,16 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"include": ["alchemy.run.ts", "src/**/*.ts"],
"compilerOptions": {
"noEmit": true,
"rootDir": ".",
"module": "Preserve",
"moduleResolution": "Bundler",
"target": "ESNext"
},
"references": [
{
"path": "../../packages/alchemy/tsconfig.json"
}
]
}
@@ -1,86 +0,0 @@
import * as Alchemy from "alchemy";
import * as AWS from "alchemy/AWS";
import * as Output from "alchemy/Output";
import * as Effect from "effect/Effect";
import JobFunction from "./src/JobFunction.ts";
// AWS.providers() already provides AWSEnvironment from the SSO profile
// named by $AWS_PROFILE (defaults to "default"). To pin a different
// profile per stage, wrap with `Layer.provide(AWS.makeEnvironment({...}))`.
const aws = AWS.providers();
const dashboardRegion = process.env.AWS_REGION ?? "us-west-2";
export default Alchemy.Stack(
"JobLambda",
{
providers: aws,
state: Alchemy.localState(),
},
Effect.gen(function* () {
const func = yield* JobFunction;
const dashboard = yield* AWS.CloudWatch.Dashboard("JobDashboard", {
DashboardBody: func.functionName.pipe(
Output.map((functionName) => ({
widgets: [
{
type: "metric",
x: 0,
y: 0,
width: 12,
height: 6,
properties: {
title: "Lambda Invocations and Errors",
region: dashboardRegion,
stat: "Sum",
period: 300,
metrics: [
["AWS/Lambda", "Invocations", "FunctionName", functionName],
["AWS/Lambda", "Errors", "FunctionName", functionName],
],
},
},
{
type: "metric",
x: 12,
y: 0,
width: 12,
height: 6,
properties: {
title: "Lambda Duration",
region: dashboardRegion,
stat: "Average",
period: 300,
metrics: [
["AWS/Lambda", "Duration", "FunctionName", functionName],
],
},
},
],
})),
),
});
const alarm = yield* AWS.CloudWatch.Alarm("JobFunctionErrorsAlarm", {
AlarmDescription:
"Alerts when the example Lambda function reports errors.",
MetricName: "Errors",
Namespace: "AWS/Lambda",
Statistic: "Sum",
Period: 300,
EvaluationPeriods: 1,
Threshold: 1,
ComparisonOperator: "GreaterThanOrEqualToThreshold",
TreatMissingData: "notBreaching",
Dimensions: [
{
Name: "FunctionName",
Value: func.functionName,
},
],
});
return {
url: Output.interpolate`${func.functionUrl}?jobId=foo`,
dashboardName: dashboard.dashboardName,
alarmName: alarm.alarmName,
};
}),
);
@@ -1,24 +0,0 @@
{
"name": "aws-lambda",
"version": "0.0.0",
"private": true,
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "git+https://github.com/alchemy-run/alchemy-effect.git",
"directory": "examples/aws-lambda"
},
"scripts": {
"build": "tsc -b",
"deploy": "alchemy deploy",
"dev": "alchemy dev",
"destroy": "alchemy destroy",
"test": "bun test"
},
"dependencies": {
"@distilled.cloud/aws": "catalog:",
"@effect/platform-node": "catalog:",
"alchemy": "workspace:*",
"effect": "catalog:"
}
}
@@ -1,13 +0,0 @@
import * as S from "effect/Schema";
export type JobId = S.Schema.Type<typeof JobId>;
export const JobId = S.String.annotate({
description: "The ID of the job",
});
export class Job extends S.Class<Job>("Job")({
id: JobId,
content: S.String,
}) {}
export const decodeJob = S.decodeEffect(Job);
@@ -1,119 +0,0 @@
import * as AWS from "alchemy/AWS";
import { Stack } from "alchemy/Stack";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { HttpServerRequest } from "effect/unstable/http/HttpServerRequest";
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
import {
JobNotifications,
JobNotificationsSNS,
NotifyJobError,
} from "./JobNotifications.ts";
import {
GetJobError,
JobStorage,
JobStorageDynamoDB,
PutJobError,
} from "./JobStorage.ts";
export default class JobFunction extends AWS.Lambda.Function<JobFunction>()(
"JobFunction",
Stack.useSync((stack) => ({
main: import.meta.filename,
memory: stack.stage === "prod" ? 1024 : 512,
url: true,
})),
Effect.gen(function* () {
const jobStorage = yield* JobStorage;
const notifications = yield* JobNotifications;
return {
fetch: Effect.gen(function* () {
const request = yield* HttpServerRequest;
const url = new URL(request.originalUrl);
if (request.method === "GET" && url.pathname === "/") {
const jobId = url.searchParams.get("jobId");
if (!jobId) {
return HttpServerResponse.text("Job ID is required", {
status: 400,
});
}
const job = yield* jobStorage.getJob(jobId).pipe(
Effect.match({
onFailure: (error) => error,
onSuccess: (job) => job,
}),
);
if (job instanceof GetJobError) {
return HttpServerResponse.text(job.message, { status: 500 });
}
if (!job) {
return HttpServerResponse.text("Job not found", { status: 404 });
}
return yield* HttpServerResponse.json(job);
}
if (request.method === "POST" && url.pathname === "/") {
const content = yield* request.text;
if (!content) {
return HttpServerResponse.text("Job content is required", {
status: 400,
});
}
const job = yield* jobStorage
.putJob({
id: crypto.randomUUID(),
content,
})
.pipe(
Effect.match({
onFailure: (error) => error,
onSuccess: (job) => job,
}),
);
if (job instanceof PutJobError) {
return HttpServerResponse.text(job.message, { status: 500 });
}
const notificationResult = yield* notifications
.notifyJobCreated(job)
.pipe(
Effect.match({
onFailure: (error) => error,
onSuccess: () => undefined,
}),
);
if (notificationResult instanceof NotifyJobError) {
return HttpServerResponse.text(notificationResult.message, {
status: 500,
});
}
return yield* HttpServerResponse.json(
{ jobId: job.id },
{ status: 201 },
);
}
return HttpServerResponse.text("Not found", { status: 404 });
}),
};
}).pipe(
Effect.provide(
Layer.mergeAll(
// Services go here
JobStorageDynamoDB,
JobNotificationsSNS,
// JobStorageS3,
),
),
),
) {}
@@ -1,90 +0,0 @@
import * as AWS from "alchemy/AWS";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Stream from "effect/Stream";
import type { Job } from "./Job.ts";
export class NotifyJobError extends Data.TaggedError("NotifyJobError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
type JobNotification = {
type: "job.created";
job: Job;
};
export class JobNotifications extends Context.Service<
JobNotifications,
{
notifyJobCreated(job: Job): Effect.Effect<void, NotifyJobError>;
}
>()("JobNotifications") {}
export const JobNotificationsSNS = Layer.effect(
JobNotifications,
Effect.gen(function* () {
const topic = yield* AWS.SNS.Topic("JobNotificationsTopic", {
attributes: {
DisplayName: "job-notifications",
},
});
const publish = yield* AWS.SNS.Publish.bind(topic);
yield* AWS.SNS.notifications(topic).subscribe((stream) =>
stream.pipe(
Stream.mapEffect((notification) =>
Effect.try({
try: () => JSON.parse(notification.Message) as JobNotification,
catch: (cause) =>
new NotifyJobError({
message: "Failed to parse SNS job notification",
cause,
}),
}).pipe(
Effect.flatMap((payload) =>
Effect.logInfo(
`Job notification received: ${payload.type} (${payload.job.id})`,
),
),
// Keep the example resilient to malformed demo messages.
Effect.catchTag("NotifyJobError", (error) =>
Effect.logWarning(error.message),
),
),
),
Stream.runDrain,
),
);
const notifyJobCreated = (job: Job) =>
publish({
Subject: "JobCreated",
Message: JSON.stringify({
type: "job.created",
job,
} satisfies JobNotification),
}).pipe(
Effect.asVoid,
Effect.mapError(
(cause) =>
new NotifyJobError({
message: `Failed to publish job notification for "${job.id}"`,
cause,
}),
),
);
return JobNotifications.of({
notifyJobCreated,
});
}),
).pipe(
Layer.provideMerge(
Layer.mergeAll(AWS.Lambda.TopicEventSource, AWS.SNS.PublishLive),
),
);
@@ -1,230 +0,0 @@
import * as DynamoDB from "alchemy/AWS/DynamoDB";
import * as Lambda from "alchemy/AWS/Lambda";
import * as S3 from "alchemy/AWS/S3";
import * as SQS from "alchemy/AWS/SQS";
import * as RemovalPolicy from "alchemy/RemovalPolicy";
import { Stack } from "alchemy/Stack";
import * as Console from "effect/Console";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Stream from "effect/Stream";
import type { Job } from "./Job.ts";
export class PutJobError extends Data.TaggedError("PutJobError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
export class GetJobError extends Data.TaggedError("GetJobError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
export class JobStorage extends Context.Service<
JobStorage,
{
putJob(job: Job): Effect.Effect<Job, PutJobError>;
getJob(jobId: string): Effect.Effect<Job | undefined, GetJobError>;
}
>()("JobStorage") {}
export const JobStorageDynamoDB = Layer.provideMerge(
Layer.effect(
JobStorage,
Effect.gen(function* () {
const stack = yield* Stack;
const table = yield* DynamoDB.Table("JobsTable", {
partitionKey: "id",
attributes: {
id: "S",
},
});
const queue = yield* SQS.Queue("JobsQueue").pipe(
RemovalPolicy.retain(stack.stage === "prod"),
);
const getItem = yield* DynamoDB.GetItem.bind(table);
const putItem = yield* DynamoDB.PutItem.bind(table);
const sink = yield* SQS.QueueSink.bind(queue);
yield* DynamoDB.stream(table, {
streamViewType: "NEW_AND_OLD_IMAGES",
startingPosition: "LATEST",
batchSize: 10,
}).process((stream) =>
stream.pipe(
Stream.map((record) =>
JSON.stringify({
eventName: record.eventName,
keys: record.dynamodb.Keys,
newImage: record.dynamodb.NewImage,
oldImage: record.dynamodb.OldImage,
}),
),
Stream.run(sink),
),
);
const putJob = (job: Job) =>
putItem({
Item: {
id: { S: job.id },
content: { S: job.content },
},
}).pipe(
Effect.map(() => job),
Effect.tapError(Console.log),
Effect.catchCause((cause) =>
Effect.fail(
new PutJobError({
message: `Failed to store job "${job.id}": ${cause}`,
cause,
}),
),
),
);
const getJob = (jobId: string) =>
getItem({
Key: {
id: { S: jobId },
},
}).pipe(
Effect.flatMap((item) =>
item.Item
? Effect.try({
try: () =>
({
id: item.Item?.id?.S ?? jobId,
content: item.Item?.content?.S ?? "",
}) as Job,
catch: (cause) =>
new GetJobError({
message: `Failed to parse job "${jobId}": ${cause}`,
cause,
}),
})
: Effect.succeed(undefined),
),
Effect.tapError(Console.log),
Effect.catchCause((cause) =>
Effect.fail(
new GetJobError({
message: `Failed to load job "${jobId}": ${cause}`,
cause,
}),
),
),
);
return JobStorage.of({
putJob,
getJob,
});
}),
),
Layer.mergeAll(Lambda.TableEventSource, SQS.QueueSinkLive).pipe(
Layer.provideMerge(
Layer.mergeAll(
DynamoDB.GetItemLive,
DynamoDB.PutItemLive,
SQS.SendMessageBatchLive,
),
),
),
);
export const JobStorageS3 = Layer.provideMerge(
Layer.effect(
JobStorage,
Effect.gen(function* () {
const stack = yield* Stack;
const bucket = yield* S3.Bucket("JobsBucket");
const queue = yield* SQS.Queue("JobsQueue").pipe(
RemovalPolicy.retain(stack.stage === "prod"),
);
const getObject = yield* S3.GetObject.bind(bucket);
const putObject = yield* S3.PutObject.bind(bucket);
const sink = yield* SQS.QueueSink.bind(queue);
const putJob = (job: Job) =>
putObject({
Key: job.id,
Body: JSON.stringify(job),
}).pipe(
Effect.map(() => job),
Effect.tapError(Console.log),
Effect.catchCause((cause) =>
Effect.fail(
new PutJobError({
message: `Failed to store job "${job.id}": ${cause}`,
cause,
}),
),
),
);
const getJob = (jobId: string) =>
getObject({
Key: jobId,
}).pipe(
Effect.catchTag("NoSuchKey", () => Effect.succeed(undefined)),
Effect.flatMap(
(item) =>
item?.Body?.pipe(
Stream.decodeText,
Stream.mkString,
Effect.flatMap((body) =>
Effect.try({
try: () => JSON.parse(body) as Job,
catch: (cause) =>
new GetJobError({
message: `Failed to parse job "${jobId}": ${cause}`,
cause,
}),
}),
),
) ?? Effect.succeed(undefined),
),
Effect.tapError(Console.log),
Effect.catchCause((cause) =>
Effect.fail(
new GetJobError({
message: `Failed to load job "${jobId}": ${cause}`,
cause,
}),
),
),
);
yield* S3.notifications(bucket).subscribe((stream) =>
stream.pipe(
Stream.flatMap((item) =>
Stream.fromEffect(getJob(item.key).pipe(Effect.orDie)),
),
Stream.filter((job): job is Job => job !== undefined),
Stream.map((job) => JSON.stringify(job)),
Stream.run(sink),
),
);
return JobStorage.of({
putJob,
getJob,
});
}),
),
Layer.mergeAll(Lambda.BucketEventSource, SQS.QueueSinkLive).pipe(
Layer.provideMerge(
Layer.mergeAll(
S3.GetObjectLive,
S3.PutObjectLive,
SQS.SendMessageBatchLive,
),
),
),
);
@@ -1,23 +0,0 @@
import * as AWS from "alchemy/AWS";
import * as Alchemy from "alchemy";
import * as Test from "alchemy/Test/Bun";
import { expect } from "bun:test";
import * as Effect from "effect/Effect";
import Stack from "../alchemy.run.ts";
const { test, beforeAll, afterAll, deploy, destroy } = Test.make({
providers: AWS.providers(),
state: Alchemy.localState(),
});
const stack = beforeAll(deploy(Stack));
afterAll.skipIf(!!process.env.NO_DESTROY)(destroy(Stack));
test(
"deploys and exposes a url",
Effect.gen(function* () {
const out = (yield* stack) as unknown;
const url = typeof out === "string" ? out : (out as { url: string }).url;
expect(url).toBeString();
}),
);
@@ -1,16 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"include": ["alchemy.run.ts", "src/**/*.ts", "test/**/*.ts"],
"compilerOptions": {
"noEmit": true,
"rootDir": ".",
"module": "Preserve",
"moduleResolution": "Bundler",
"target": "ESNext"
},
"references": [
{
"path": "../../packages/alchemy/tsconfig.json"
}
]
}
@@ -1,17 +0,0 @@
import * as Alchemy from "alchemy";
import * as AWS from "alchemy/AWS";
import * as Effect from "effect/Effect";
import ServiceFunction from "./src/ServiceFunction.ts";
const aws = AWS.providers();
export default Alchemy.Stack(
"AwsRdsExample",
{ providers: aws, state: Alchemy.localState() },
Effect.gen(function* () {
const service = yield* ServiceFunction;
return {
url: service.functionUrl,
};
}),
);
@@ -1,25 +0,0 @@
{
"name": "aws-rds-example",
"version": "0.0.0",
"private": true,
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "git+https://github.com/alchemy-run/alchemy-effect.git",
"directory": "examples/aws-rds"
},
"scripts": {
"build": "tsc -b",
"deploy": "alchemy deploy",
"dev": "alchemy dev",
"destroy": "alchemy destroy"
},
"dependencies": {
"@distilled.cloud/aws": "catalog:",
"@effect/platform-node": "catalog:",
"@types/pg": "^8.18.0",
"alchemy": "workspace:*",
"effect": "catalog:",
"pg": "^8.20.0"
}
}
@@ -1,89 +0,0 @@
import * as AWS from "alchemy/AWS";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { Client } from "pg";
import { Network } from "./Network.ts";
export class SqlError extends Data.TaggedError("SqlError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
export class Database extends Context.Service<
Database,
{
query<Row extends Record<string, unknown> = Record<string, unknown>>(
statement: string,
values?: ReadonlyArray<unknown>,
): Effect.Effect<ReadonlyArray<Row>, SqlError>;
}
>()("Sql") {}
export const DatabaseAurora = Layer.effect(
Database,
Effect.gen(function* () {
const { vpc, databaseSecurityGroup } = yield* Network;
const database = yield* AWS.RDS.Aurora("Database", {
subnetIds: vpc.privateSubnetIds,
securityGroupIds: [databaseSecurityGroup.groupId],
});
const connect = yield* AWS.RDS.Connect.bind(database.cluster, {
secret: database.secret,
subnetIds: vpc.privateSubnetIds,
securityGroupIds: [databaseSecurityGroup.groupId],
});
return Database.of({
query: <Row extends Record<string, unknown>>(
statement: string,
values: ReadonlyArray<unknown> = [],
): Effect.Effect<ReadonlyArray<Row>, SqlError> =>
connect.pipe(
Effect.catch((cause) =>
Effect.fail(
new SqlError({
message: "Failed to resolve Aurora connection settings",
cause,
}),
),
),
Effect.flatMap((connection: AWS.RDS.ConnectionInfo) =>
Effect.tryPromise({
try: async () => {
const client = new Client({
host: connection.host,
port: connection.port,
database: connection.database,
user: connection.username,
password: connection.password,
// Example-only SSL posture for private Aurora connections.
ssl: connection.ssl
? { rejectUnauthorized: false }
: undefined,
});
await client.connect();
try {
const result = await client.query<Row>({
text: statement,
values: [...values],
});
return result.rows as ReadonlyArray<Row>;
} finally {
await client.end();
}
},
catch: (cause) =>
new SqlError({
message: `Failed to execute SQL statement: ${statement}`,
cause,
}),
}),
),
),
});
}),
);
@@ -1,58 +0,0 @@
import * as AWS from "alchemy/AWS";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
export interface ExampleNetwork {
vpc: AWS.EC2.Network;
functionSecurityGroup: AWS.EC2.SecurityGroup;
databaseSecurityGroup: AWS.EC2.SecurityGroup;
privateSecurityGroups: AWS.EC2.SecurityGroup[];
}
export class Network extends Context.Service<Network, ExampleNetwork>()(
"Network",
) {}
export const NetworkLive = Layer.effect(
Network,
Effect.gen(function* () {
const network = yield* AWS.EC2.Network("Network", {
cidrBlock: "10.0.0.0/16",
availabilityZones: 2,
nat: "single",
});
const functionSecurityGroup = yield* AWS.EC2.SecurityGroup(
"FunctionSecurityGroup",
{
vpcId: network.vpcId,
description: "Security group for the RDS example Lambda function",
},
);
const databaseSecurityGroup = yield* AWS.EC2.SecurityGroup(
"DatabaseSecurityGroup",
{
vpcId: network.vpcId,
description: "Security group for the RDS example Aurora cluster",
ingress: [
{
ipProtocol: "tcp",
fromPort: 5432,
toPort: 5432,
referencedGroupId: functionSecurityGroup.groupId,
description: "Allow Lambda to reach Aurora PostgreSQL",
},
],
},
);
return {
vpc: network,
functionSecurityGroup,
databaseSecurityGroup,
privateSecurityGroups: [functionSecurityGroup],
} satisfies ExampleNetwork;
}),
);
@@ -1,71 +0,0 @@
import * as AWS from "alchemy/AWS";
import { Stack } from "alchemy/Stack";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { HttpServerRequest } from "effect/unstable/http/HttpServerRequest";
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
import { Database, DatabaseAurora } from "./Database.ts";
import { NetworkLive } from "./Network.ts";
export default class ServiceFunction extends AWS.Lambda.Function<ServiceFunction>()(
"ServiceFunction",
Stack.useSync((stack) => ({
main: import.meta.filename,
memory: stack.stage === "prod" ? 1024 : 512,
runtime: "nodejs24.x",
})),
Effect.gen(function* () {
const db = yield* Database;
return {
fetch: Effect.gen(function* () {
const request = yield* HttpServerRequest;
if (
request.method === "GET" &&
new URL(request.originalUrl).pathname === "/"
) {
const response = yield* db
.query<{
database: string;
current_time: string;
current_user: string;
}>(
"select current_database() as database, now()::text as current_time, current_user::text as current_user",
)
.pipe(
Effect.match({
onFailure: (error) => ({
status: 500 as const,
body: {
ok: false,
error: error.message,
},
}),
onSuccess: (rows) => ({
status: 200 as const,
body: {
ok: true,
connection: rows[0] ?? null,
},
}),
}),
);
return yield* HttpServerResponse.json(response.body, {
status: response.status,
});
}
return HttpServerResponse.text("Not found", { status: 404 });
}),
};
}).pipe(
Effect.provide(
Layer.provideMerge(
Layer.mergeAll(DatabaseAurora),
Layer.mergeAll(NetworkLive, AWS.RDS.ConnectLive),
),
),
),
) {}
@@ -1,17 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"include": ["alchemy.run.ts", "src/**/*.ts"],
"compilerOptions": {
"noEmit": true,
"rootDir": ".",
"module": "Preserve",
"moduleResolution": "Bundler",
"customConditions": ["bun"],
"target": "ESNext"
},
"references": [
{
"path": "../../packages/alchemy/tsconfig.json"
}
]
}
@@ -1,84 +0,0 @@
import * as Alchemy from "alchemy";
import * as AWS from "alchemy/AWS";
import * as Output from "alchemy/Output";
import * as Effect from "effect/Effect";
import JobFunction from "./src/JobFunction.ts";
const aws = AWS.providers();
export default Alchemy.Stack(
"AwsRestApiProxy",
{
providers: aws,
state: Alchemy.localState(),
},
Effect.gen(function* () {
const { region, accountId } = yield* AWS.AWSEnvironment;
const fn = yield* JobFunction;
const api = yield* AWS.ApiGateway.RestApi("PublicApi", {
name: "alchemy-example-rest-api",
endpointConfiguration: { types: ["REGIONAL"] },
});
const proxyResource = yield* AWS.ApiGateway.Resource("Proxy", {
restApiId: api.restApiId,
parentId: api.rootResourceId,
pathPart: "{proxy+}",
});
const invokeUri = Output.interpolate`arn:aws:apigateway:${region}:lambda:path/2015-03-31/functions/${fn.functionArn}/invocations`;
yield* AWS.ApiGateway.Method("RootAny", {
restApiId: api.restApiId,
resourceId: api.rootResourceId,
httpMethod: "ANY",
authorizationType: "NONE",
integration: {
type: "AWS_PROXY",
integrationHttpMethod: "POST",
uri: invokeUri,
},
});
yield* AWS.ApiGateway.Method("ProxyAny", {
restApiId: api.restApiId,
resourceId: proxyResource.resourceId,
httpMethod: "ANY",
authorizationType: "NONE",
integration: {
type: "AWS_PROXY",
integrationHttpMethod: "POST",
uri: invokeUri,
},
});
const deployment = yield* AWS.ApiGateway.Deployment("Release", {
restApiId: api.restApiId,
description: "initial",
triggers: {
rootMethod: "ANY",
proxyMethod: "ANY",
},
});
const stage = yield* AWS.ApiGateway.Stage("ProdStage", {
restApiId: api.restApiId,
stageName: "prod",
deploymentId: deployment.deploymentId,
});
yield* AWS.Lambda.Permission("ApiGatewayInvoke", {
action: "lambda:InvokeFunction",
functionName: fn.functionName,
principal: "apigateway.amazonaws.com",
sourceArn: Output.interpolate`arn:aws:execute-api:${region}:${accountId}:${api.restApiId}/*/*/*`,
});
return {
invokeUrl: Output.interpolate`https://${api.restApiId}.execute-api.${region}.amazonaws.com/${stage.stageName}/`,
restApiId: api.restApiId,
};
}),
);
@@ -1,22 +0,0 @@
{
"name": "aws-rest-api",
"version": "0.0.0",
"private": true,
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "git+https://github.com/alchemy-run/alchemy-effect.git",
"directory": "examples/aws-rest-api"
},
"scripts": {
"build": "tsc -b",
"deploy": "alchemy deploy",
"dev": "alchemy dev",
"destroy": "alchemy destroy"
},
"dependencies": {
"@distilled.cloud/aws": "catalog:",
"alchemy": "workspace:*",
"effect": "catalog:"
}
}
@@ -1,22 +0,0 @@
import * as AWS from "alchemy/AWS";
import * as Effect from "effect/Effect";
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
const main = import.meta.filename;
/**
* Minimal Lambda for API Gateway `AWS_PROXY` — returns plain text.
*/
export default class JobFunction extends AWS.Lambda.Function<AWS.Lambda.Function>()(
"JobFunction",
{
main,
},
Effect.gen(function* () {
return {
fetch: Effect.gen(function* () {
return HttpServerResponse.text("Hello from REST API + Lambda");
}),
};
}),
) {}
@@ -1,16 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"include": ["alchemy.run.ts", "src/**/*.ts"],
"compilerOptions": {
"noEmit": true,
"rootDir": ".",
"module": "Preserve",
"moduleResolution": "Bundler",
"target": "ESNext"
},
"references": [
{
"path": "../../packages/alchemy/tsconfig.json"
}
]
}
@@ -1,34 +0,0 @@
# AWS Static Site Example
This example deploys a static website from the local `site/` directory using:
- `AWS.Website.StaticSite`
- private S3 origin
- CloudFront distribution
- optional ACM certificate in `us-east-1`
- optional Route 53 alias records
## Commands
```sh
bun install
bun run --filter aws-static-site-example deploy
```
## Optional Custom Domain
Set these environment variables before deploy:
```sh
export WEBSITE_DOMAIN=www.example.com
export WEBSITE_ZONE_ID=Z1234567890
export WEBSITE_ALIASES=example.com,static.example.com
```
When `WEBSITE_DOMAIN` and `WEBSITE_ZONE_ID` are provided, the example will:
- request an ACM certificate
- create Route 53 validation records
- create Route 53 alias records to CloudFront
Without them, the example still deploys and returns the CloudFront URL.
@@ -1,29 +0,0 @@
import * as Alchemy from "alchemy";
import * as AWS from "alchemy/AWS";
import * as Effect from "effect/Effect";
export default Alchemy.Stack(
"AwsStaticSiteExample",
{
providers: AWS.providers(),
state: Alchemy.localState(),
},
Effect.gen(function* () {
const site = yield* AWS.Website.StaticSite("MarketingSite", {
path: "./site",
// domain: "your.domain.com",
forceDestroy: true,
invalidation: {
paths: "all",
},
tags: {
Example: "aws-static-site",
Surface: "website",
},
});
return {
url: site.url,
};
}),
);
@@ -1,24 +0,0 @@
{
"name": "aws-static-site-example",
"version": "0.0.0",
"private": true,
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "git+https://github.com/alchemy-run/alchemy-effect.git",
"directory": "examples/aws-static-site"
},
"type": "module",
"scripts": {
"build": "tsc -b",
"deploy": "alchemy deploy",
"dev": "alchemy dev",
"destroy": "alchemy destroy"
},
"dependencies": {
"@distilled.cloud/aws": "catalog:",
"@effect/platform-node": "catalog:",
"alchemy": "workspace:*",
"effect": "catalog:"
}
}
@@ -1,22 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Static Site Docs</title>
<link rel="stylesheet" href="/styles.css" />
</head>
<body>
<main class="page">
<p class="eyebrow">docs route</p>
<h1>Static hosting can ship multiple pages too.</h1>
<p class="lede">
This page is just another file in the deployed folder and is cached by
CloudFront as a normal static asset.
</p>
<div class="actions">
<a href="/">Back home</a>
</div>
</main>
</body>
</html>
@@ -1,25 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Alchemy AWS Static Site</title>
<link rel="stylesheet" href="/styles.css" />
</head>
<body>
<main class="page">
<p class="eyebrow">alchemy example</p>
<h1>AWS static site with CloudFront, ACM, and Route 53</h1>
<p class="lede">
This site is deployed from a plain folder using
<code>AWS.Website.StaticSite</code>.
</p>
<div class="actions">
<a href="/docs/">Read the docs page</a>
<a href="https://github.com/alchemy-run/alchemy-effect"
>View the repo</a
>
</div>
</main>
</body>
</html>
@@ -1,56 +0,0 @@
html,
body {
margin: 0;
min-height: 100%;
font-family:
Inter,
ui-sans-serif,
system-ui,
-apple-system,
BlinkMacSystemFont,
"Segoe UI",
sans-serif;
background: linear-gradient(180deg, #0f172a 0%, #111827 100%);
color: #e5e7eb;
}
.page {
max-width: 48rem;
margin: 0 auto;
padding: 6rem 1.5rem;
}
.eyebrow {
text-transform: uppercase;
letter-spacing: 0.14em;
color: #93c5fd;
font-size: 0.875rem;
}
h1 {
font-size: clamp(2.5rem, 6vw, 4.5rem);
line-height: 1.05;
margin: 0.5rem 0 1rem;
}
.lede {
font-size: 1.125rem;
line-height: 1.7;
color: #cbd5e1;
}
.actions {
display: flex;
gap: 1rem;
flex-wrap: wrap;
margin-top: 2rem;
}
.actions a {
color: #0f172a;
background: #f8fafc;
text-decoration: none;
padding: 0.85rem 1.1rem;
border-radius: 999px;
font-weight: 600;
}
@@ -1,16 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"include": ["alchemy.run.ts", "src/**/*.ts"],
"compilerOptions": {
"noEmit": true,
"rootDir": ".",
"module": "Preserve",
"moduleResolution": "Bundler",
"target": "ESNext"
},
"references": [
{
"path": "../../packages/alchemy/tsconfig.json"
}
]
}
@@ -1,33 +0,0 @@
# AWS Vite Example
This example builds a Vite app and deploys it with:
- `Build.Build` for the frontend build step
- `AWS.Website.StaticSite` for S3 + CloudFront hosting
- optional ACM + Route 53 custom-domain wiring
## Commands
```sh
bun install
bun run --filter aws-vite-example build
bun run --filter aws-vite-example deploy
```
For local frontend development:
```sh
bun run --filter aws-vite-example dev:vite
```
## Optional Custom Domain
Set these environment variables before deploy:
```sh
export WEBSITE_DOMAIN=app.example.com
export WEBSITE_ZONE_ID=Z1234567890
export WEBSITE_ALIASES=www.app.example.com
```
Without them, the example still deploys and returns the CloudFront URL.
@@ -1,103 +0,0 @@
import * as Alchemy from "alchemy";
import * as AWS from "alchemy/AWS";
import * as Output from "alchemy/Output";
import * as Config from "effect/Config";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
const aws = AWS.providers();
const WEBSITE_DOMAIN = Config.string("WEBSITE_DOMAIN").pipe(
Config.option,
Config.map(Option.getOrUndefined),
(config) => config.asEffect(),
);
const WEBSITE_ZONE_ID = Config.string("WEBSITE_ZONE_ID").pipe(
Config.option,
Config.map(Option.getOrUndefined),
(config) => config.asEffect(),
);
const WEBSITE_ALIASES = Config.string("WEBSITE_ALIASES").pipe(
Config.option,
Config.map(Option.getOrUndefined),
Config.map((value) =>
value
?.split(",")
.map((part) => part.trim())
.filter(Boolean),
),
(config) => config.asEffect(),
);
export default Alchemy.Stack(
"AwsViteExample",
{ providers: aws, state: Alchemy.localState() },
Effect.gen(function* () {
/**
* Optional Route 53 / ACM config.
*
* Set these before deploying if you want a custom domain:
* - WEBSITE_DOMAIN=app.example.com
* - WEBSITE_ZONE_ID=Z1234567890
* - WEBSITE_ALIASES=www.app.example.com
*/
const websiteDomainName = yield* WEBSITE_DOMAIN;
const websiteZoneId = yield* WEBSITE_ZONE_ID;
const websiteAliases = yield* WEBSITE_ALIASES;
const websiteDomain =
websiteDomainName && websiteZoneId
? {
name: websiteDomainName,
hostedZoneId: websiteZoneId,
aliases: websiteAliases,
}
: undefined;
const site = yield* AWS.Website.StaticSite("FrontendSite", {
path: ".",
build: {
command: "bun run build",
output: "dist",
},
environment: {
VITE_STAGE: "test",
},
spa: true,
cdn: false,
tags: {
Example: "aws-vite",
Surface: "website",
},
});
const router = yield* AWS.Website.Router("FrontendRouter", {
domain: websiteDomain,
routes: {
"/*": site.routeTarget,
},
invalidation: {
paths: "all",
},
tags: {
Example: "aws-vite",
Surface: "website",
Mode: "router",
},
});
return {
url: router.url,
cloudFrontDomain: router.distribution.domainName,
distributionId: router.distribution.distributionId,
bucketName: site.bucket.bucketName,
buildHash: site.build?.hash,
assetVersion: site.files.version,
certificateArn: router.certificate?.certificateArn as any,
customDomain: websiteDomain?.name,
aliasRecordNames: router.records.map((record) => record.name),
previewHint: Output.interpolate`Run bun run dev:vite for local frontend iteration, then deploy to publish ${router.distribution.domainName}`,
};
}) as any,
);
@@ -1,12 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>AWS Vite Example</title>
<script type="module" src="/src/main.ts"></script>
</head>
<body>
<div id="app"></div>
</body>
</html>
@@ -1,31 +0,0 @@
{
"name": "aws-vite-example",
"version": "0.0.0",
"private": true,
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "git+https://github.com/alchemy-run/alchemy-effect.git",
"directory": "examples/aws-vite"
},
"type": "module",
"scripts": {
"build": "vite build",
"dev:vite": "vite",
"preview": "vite preview",
"deploy": "alchemy deploy",
"dev": "alchemy dev",
"destroy": "alchemy destroy"
},
"dependencies": {
"@cloudflare/vite-plugin": "catalog:",
"@distilled.cloud/aws": "catalog:",
"@effect/platform-node": "catalog:",
"alchemy": "workspace:*",
"effect": "catalog:"
},
"devDependencies": {
"typescript": "catalog:",
"vite": "catalog:"
}
}
@@ -1,24 +0,0 @@
import "./style.css";
const app = document.querySelector<HTMLDivElement>("#app");
if (!app) {
throw new Error("Missing #app root element");
}
app.innerHTML = `
<main class="page">
<p class="eyebrow">alchemy + vite</p>
<h1>Deploy a Vite SPA to AWS with CloudFront, ACM, and Route 53.</h1>
<p class="lede">
This example runs a Vite build and publishes the generated assets with
<code>AWS.Website.StaticSite</code> behind a shared
<code>AWS.Website.Router</code>.
</p>
<ul class="highlights">
<li>Build artifacts uploaded to a private S3 bucket</li>
<li>CloudFront Router in front of the site</li>
<li>Optional custom domain with ACM validation and Route 53 alias records</li>
</ul>
</main>
`;
@@ -1,51 +0,0 @@
html,
body {
margin: 0;
min-height: 100%;
font-family:
Inter,
ui-sans-serif,
system-ui,
-apple-system,
BlinkMacSystemFont,
"Segoe UI",
sans-serif;
background: #020617;
color: #e2e8f0;
}
#app {
min-height: 100vh;
}
.page {
max-width: 56rem;
margin: 0 auto;
padding: 6rem 1.5rem;
}
.eyebrow {
text-transform: uppercase;
letter-spacing: 0.16em;
color: #60a5fa;
font-size: 0.875rem;
}
h1 {
margin: 0.75rem 0 1rem;
font-size: clamp(2.5rem, 6vw, 4.25rem);
line-height: 1.05;
}
.lede {
font-size: 1.125rem;
line-height: 1.7;
color: #cbd5e1;
}
.highlights {
margin: 2rem 0 0;
padding-left: 1.25rem;
color: #bfdbfe;
line-height: 1.9;
}
@@ -1,18 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"include": ["alchemy.run.ts", "src/**/*.ts", "vite.config.ts"],
"compilerOptions": {
"noEmit": true,
// TODO(sam): remove this once we have a proper implementation
"noCheck": true,
"rootDir": ".",
"module": "Preserve",
"moduleResolution": "Bundler",
"target": "ESNext"
},
"references": [
{
"path": "../../packages/alchemy/tsconfig.json"
}
]
}
@@ -1,6 +0,0 @@
import { cloudflare } from "@cloudflare/vite-plugin";
import { defineConfig } from "vite";
export default defineConfig({
plugins: [cloudflare()],
});
@@ -1 +0,0 @@
!src/modules/modules.d.ts
Loaded 100 of 4859 files, more files were not shown because too many files have changed in this diff. Show more