create-signet-app 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 The Signet authors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # create-signet-app
2
2
 
3
3
  Scaffold a Vite + React 19 + TypeScript + Tailwind v4 app wired to
4
- `@nimit9/signet-tokens`, `@nimit9/signet-ui` and `@nimit9/signet-lib`.
4
+ `@dapplelight/signet-tokens`, `@dapplelight/signet-ui` and `@dapplelight/signet-lib`.
5
5
 
6
6
  ```bash
7
7
  bun run packages/create-signet-app/src/index.ts apps/my-app --theme cinematic
@@ -19,23 +19,69 @@ copy-paste, not configuration.
19
19
 
20
20
  ## What you get
21
21
 
22
- - `dev` / `build` / `preview` / `lint` / `typecheck` — the script names already
23
- used across the existing repos, so muscle memory carries over
22
+ - `dev` / `build` / `preview` / `lint` / `typecheck` / `test` — the script names
23
+ already used across the existing repos, so muscle memory carries over
24
+ - **TanStack Router**, file-based, with `/` and a placeholder `/login`.
25
+ `CONVENTIONS.md` does not pick a router; this follows app-a. Routes live in
26
+ `src/routes`; the Vite plugin regenerates `src/routeTree.gen.ts` on every
27
+ `dev` and `build` and splits each route into its own chunk. The generated file
28
+ is committed so `tsc` passes before Vite has run, and Biome ignores it.
29
+ `/login` renders a card and nothing else — wire it to your own auth; the
30
+ template does not choose a provider
31
+ - **sonner** for toasts (the `CONVENTIONS.md` choice): `<Toaster />` in
32
+ `main.tsx`, from `src/components/toaster.tsx`, which follows light/dark and
33
+ draws on the theme's popover tokens. Call `toast()` from `"sonner"`
34
+ - `src/router.test.ts` (`bun test`), which checks `/` and `/login` each resolve
35
+ to their route
36
+ - `.github/workflows/ci.yml`: `bun install --frozen-lockfile`, lint, typecheck,
37
+ test, build. Commit `bun.lock`
24
38
  - `tsconfig.json` with app/node project references, strict, path alias `@/*`
25
- - eslint flat config, **fixed** (see below)
39
+ - Biome for lint and format (`biome check .`), replacing the copied eslint config (see below)
26
40
  - `src/app.css` importing the chosen theme
27
- - `main.tsx` with `ThemeProvider`, a `QueryClient` on Signet defaults, and a
28
- single-redirect 401 handler
41
+ - `main.tsx` with `ThemeProvider`, a `QueryClient` on Signet defaults, the
42
+ router, and a single-redirect 401 handler. The redirect is a full page load to
43
+ `/login` (built with `router.buildLocation`, so deleting the route fails
44
+ typecheck): it drops the old session's cached queries and re-arms the
45
+ one-shot handler. In production the host must fall back to `index.html` for
46
+ unknown paths
29
47
  - `index.html` with a blocking script that applies the stored theme before first
30
48
  paint — React mounts too late, and without it there is a visible flash
31
49
  - `src/lib/api.ts` with a configured `createApiClient`
32
50
 
51
+ ## `--template api`: a Worker API
52
+
53
+ `bun create-signet-app my-api --template api` scaffolds a Hono Worker with:
54
+
55
+ - `requestId`, `errorHandler` and `parseBody` from `@dapplelight/signet-server`, so
56
+ every error is the envelope with a code and a request id
57
+ - exact per-IP rate limiting on `/api/*`: the `RateLimitCounter` Durable Object
58
+ is exported from the entry, bound as `RATE_LIMIT` and created by the first
59
+ migration in `wrangler.jsonc` — nothing to set up by hand
60
+ - `src/env.ts`: a zod schema through `createEnv` from
61
+ `@dapplelight/signet-server/env`, validated lazily on first read (Cloudflare runs
62
+ module scope with no secrets during deploy). `initRuntimeEnv` hands it the
63
+ bindings on each request, and `env.APP_ENV` decides whether 500s hide their
64
+ message — failing closed (hidden) if the env does not validate. Add a var to
65
+ the schema, then read `env.KEY`
66
+ - `test/env.test.ts` (`bun test`) and `.github/workflows/ci.yml`: lint,
67
+ typecheck, test and `wrangler deploy --dry-run`
68
+
69
+ Append migration tags; never edit one that has been deployed. A Worker entry
70
+ may export only handlers and classes (workerd: "Incorrect type for map entry").
71
+
72
+ Its test scaffolds outside the monorepo, installs, typechecks, lints, bundles
73
+ with wrangler, then runs it under `wrangler dev` and checks the envelope and
74
+ that exactly 60 requests pass before a 429. Removing the `RateLimitCounter`
75
+ export fails it: wrangler refuses to bundle a Worker whose Durable Object is
76
+ not exported.
77
+
33
78
  ## Two bugs this fixes in the copied setup
34
79
 
35
80
  **`import.meta.env` did not typecheck.** The copied `tsconfig.app.json` omits
36
81
  `"types": ["vite/client"]`, so `tsc -b` fails on any use of an env var.
37
82
 
38
- **The eslint config is broken against current versions.** The config in the
83
+ **The copied eslint config is broken against current versions**, which is one
84
+ reason the scaffold ships Biome instead. The config in the
39
85
  existing repos uses `reactHooks.configs.flat.recommended`, which was removed in
40
86
  `eslint-plugin-react-hooks` 5.2. Installing fresh gives:
41
87
 
@@ -49,14 +95,23 @@ config into anything new produces a crash.
49
95
 
50
96
  ## Test
51
97
 
52
- `bun run test` scaffolds a real app, installs, builds and lints it, then asserts
98
+ Both templates ship `_gitignore` and `_github`, renamed to `.gitignore` and
99
+ `.github` on scaffold: npm strips `.gitignore` from a package and may drop
100
+ dot-directories.
101
+
102
+ `bun run test` scaffolds a real app, installs, typechecks, runs its tests,
103
+ builds and lints it, checks the build emitted a `login-*.js` route chunk and
104
+ that `.github/workflows/ci.yml` exists and only calls scripts that exist, then asserts
53
105
  the chosen theme reached the production CSS bundle (`.text-sm{font-size:1rem}`
54
106
  and `.rounded-lg{border-radius:.1875rem}` for cinematic, not editorial's
55
107
  `0.8125rem` / `.75rem`). Both bugs above were caught by that test on its first
56
108
  run.
57
109
 
58
- ## Limitation
110
+ ## Scaffolded apps work anywhere
111
+
112
+ Dependencies are real ranges (`^0.1.2`) against the published packages, so a
113
+ scaffolded app installs from npm and runs outside this repo. Inside the
114
+ monorepo bun still links the local copies, because the range matches the
115
+ workspace version — so development keeps using source with no extra step.
59
116
 
60
- Dependencies are declared `workspace:*`, so a scaffolded app must live inside
61
- the Signet monorepo (`apps/*`). Publishing the packages to a registry would lift
62
- that; until then, scaffold into `apps/`.
117
+ The packages are public, so no npm token is needed.
package/package.json CHANGED
@@ -1,21 +1,26 @@
1
1
  {
2
2
  "name": "create-signet-app",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
+ "license": "MIT",
4
5
  "description": "Scaffold a Vite + React + Tailwind app wired to Signet.",
5
6
  "type": "module",
6
7
  "bin": {
7
8
  "create-signet-app": "./src/index.ts"
8
9
  },
10
+ "publishConfig": {
11
+ "access": "public"
12
+ },
9
13
  "files": [
10
14
  "src",
11
- "template"
15
+ "template",
16
+ "template-api"
12
17
  ],
13
18
  "scripts": {
14
- "typecheck": "tsc --noEmit",
15
- "test": "bun run test/scaffold.ts"
19
+ "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json",
20
+ "test": "bun run test/scaffold.ts && bun run test/scaffold-api.ts"
16
21
  },
17
22
  "devDependencies": {
18
23
  "@types/bun": "^1.4.2",
19
24
  "typescript": "^7.0.2"
20
25
  }
21
- }
26
+ }
package/src/index.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  #!/usr/bin/env bun
2
+
2
3
  /**
3
4
  * create-signet-app — scaffold a Vite + React + TypeScript + Tailwind v4 app
4
- * wired to @nimit9/signet-tokens, @nimit9/signet-ui and @nimit9/signet-lib.
5
+ * wired to @dapplelight/signet-tokens, @dapplelight/signet-ui and @dapplelight/signet-lib.
5
6
  *
6
7
  * Exists because the audit found the same setup rebuilt by hand 13 times, and
7
8
  * the five-package eslint config copied as a block into exactly 8 of 23 repos
@@ -9,29 +10,53 @@
9
10
  * current plugin versions. Biome replaces the whole graph with one binary.
10
11
  */
11
12
 
12
- import { cp, mkdir, readFile, readdir, rename, writeFile } from "node:fs/promises"
13
13
  import { existsSync } from "node:fs"
14
+ import { cp, mkdir, readdir, readFile, rename, writeFile } from "node:fs/promises"
14
15
  import { basename, join, resolve } from "node:path"
15
16
 
16
17
  const THEMES = ["editorial", "cinematic"] as const
17
18
  type Theme = (typeof THEMES)[number]
19
+ const TEMPLATES = ["web", "api"] as const
20
+ type Template = (typeof TEMPLATES)[number]
21
+
22
+ // The api template: a Hono Worker with Signet's request id, error envelope,
23
+ // validation and exact Durable Object rate limiting already wired.
24
+ const API_DEPS = {
25
+ "@dapplelight/signet-server": "^0.3.0",
26
+ hono: "^4.13.8",
27
+ zod: "^4.6.5",
28
+ }
29
+
30
+ const API_DEV_DEPS = {
31
+ "@biomejs/biome": "^2.5.14",
32
+ "@types/bun": "^1.4.2",
33
+ typescript: "^7.0.2",
34
+ wrangler: "^4.136.3",
35
+ }
18
36
 
19
37
  const DEPS = {
20
- "@nimit9/signet-lib": "workspace:*",
21
- "@nimit9/signet-tokens": "workspace:*",
22
- "@nimit9/signet-ui": "workspace:*",
38
+ // Real ranges, not workspace:* — the packages are published, so a scaffolded
39
+ // app installs from npm and works anywhere. Inside this monorepo bun still
40
+ // links the local copies, because the range matches the workspace version.
41
+ "@dapplelight/signet-lib": "^0.2.0",
42
+ "@dapplelight/signet-tokens": "^0.2.0",
43
+ "@dapplelight/signet-ui": "^0.2.0",
23
44
  "@tanstack/react-query": "^5.103.2",
45
+ "@tanstack/react-router": "^1.170.39",
24
46
  "class-variance-authority": "^0.7.1",
25
47
  clsx: "^2.1.1",
26
48
  "lucide-react": "^1.47.0",
27
49
  react: "^19.3.0",
28
50
  "react-dom": "^19.3.0",
51
+ sonner: "^2.0.8",
29
52
  "tailwind-merge": "^3.7.0",
30
53
  }
31
54
 
32
55
  const DEV_DEPS = {
33
56
  "@biomejs/biome": "^2.5.14",
34
- "@tailwindcss/vite": "^4.3.3",
57
+ "@tailwindcss/vite": "^4.3.3",
58
+ "@tanstack/router-plugin": "^1.168.40",
59
+ "@types/bun": "^1.4.2",
35
60
  "@types/node": "^26.6.2",
36
61
  "@types/react": "^19.3.0",
37
62
  "@types/react-dom": "^19.3.0",
@@ -45,6 +70,7 @@ function parseArgs(argv: string[]) {
45
70
  const args = argv.slice(2)
46
71
  let name: string | undefined
47
72
  let theme: Theme = "editorial"
73
+ let template: Template = "web"
48
74
 
49
75
  for (let i = 0; i < args.length; i++) {
50
76
  const a = args[i]
@@ -54,16 +80,27 @@ function parseArgs(argv: string[]) {
54
80
  throw new Error(`Unknown theme "${v}". Available: ${THEMES.join(", ")}`)
55
81
  }
56
82
  theme = v as Theme
83
+ } else if (a === "--template") {
84
+ const v = args[++i]
85
+ if (!TEMPLATES.includes(v as Template)) {
86
+ throw new Error(`Unknown template "${v}". Available: ${TEMPLATES.join(", ")}`)
87
+ }
88
+ template = v as Template
57
89
  } else if (a === "--help" || a === "-h") {
58
90
  console.log(`
59
91
  create-signet-app <directory> [options]
60
92
 
61
93
  Options:
62
- -t, --theme <name> ${THEMES.join(" | ")} (default: editorial)
94
+ --template <kind> web | api (default: web)
95
+ web: Vite + React + Signet UI
96
+ api: Hono Worker with the error envelope, request ids,
97
+ validation and Durable Object rate limiting
98
+ -t, --theme <name> ${THEMES.join(" | ")} (default: editorial; web only)
63
99
  -h, --help
64
100
 
65
- Example:
101
+ Examples:
66
102
  bun create-signet-app my-app --theme cinematic
103
+ bun create-signet-app my-api --template api
67
104
  `)
68
105
  process.exit(0)
69
106
  } else if (!a.startsWith("-")) {
@@ -74,7 +111,7 @@ Example:
74
111
  }
75
112
 
76
113
  if (!name) throw new Error("Missing target directory.\nUsage: create-signet-app <directory>")
77
- return { name, theme }
114
+ return { name, theme, template }
78
115
  }
79
116
 
80
117
  /** Replace placeholders in every text file under dir. */
@@ -98,7 +135,7 @@ async function substitute(dir: string, vars: Record<string, string>) {
98
135
  }
99
136
 
100
137
  async function main() {
101
- const { name, theme } = parseArgs(process.argv)
138
+ const { name, theme, template } = parseArgs(process.argv)
102
139
  const target = resolve(process.cwd(), name)
103
140
  const appName = basename(target)
104
141
 
@@ -106,13 +143,19 @@ async function main() {
106
143
  throw new Error(`${target} already exists and is not empty.`)
107
144
  }
108
145
 
109
- const templateDir = resolve(import.meta.dirname, "../template")
146
+ const templateDir = resolve(
147
+ import.meta.dirname,
148
+ template === "api" ? "../template-api" : "../template",
149
+ )
110
150
  await mkdir(target, { recursive: true })
111
151
  await cp(templateDir, target, { recursive: true })
112
152
 
113
153
  // npm strips a file literally named .gitignore from published packages, so
114
154
  // the template ships it as _gitignore and it is renamed on scaffold.
155
+ // .github goes the same way: npm can drop dot-directories from a package, so
156
+ // the CI workflow ships under _github.
115
157
  await rename(join(target, "_gitignore"), join(target, ".gitignore"))
158
+ await rename(join(target, "_github"), join(target, ".github"))
116
159
 
117
160
  await substitute(target, { __APP_NAME__: appName, __THEME__: theme })
118
161
 
@@ -124,31 +167,55 @@ async function main() {
124
167
  private: true,
125
168
  version: "0.1.0",
126
169
  type: "module",
127
- scripts: {
128
- dev: "vite",
129
- build: "tsc -b && vite build",
130
- preview: "vite preview",
131
- lint: "biome check .",
132
- format: "biome check --write .",
133
- typecheck: "tsc -b --noEmit",
134
- },
135
- dependencies: DEPS,
136
- devDependencies: DEV_DEPS,
170
+ scripts:
171
+ template === "api"
172
+ ? {
173
+ dev: "wrangler dev",
174
+ deploy: "wrangler deploy",
175
+ lint: "biome check .",
176
+ format: "biome check --write .",
177
+ typecheck: "tsc --noEmit && tsc --noEmit -p tsconfig.test.json",
178
+ test: "bun test",
179
+ }
180
+ : {
181
+ dev: "vite",
182
+ build: "tsc -b && vite build",
183
+ preview: "vite preview",
184
+ lint: "biome check .",
185
+ format: "biome check --write .",
186
+ typecheck: "tsc -b --noEmit",
187
+ test: "bun test",
188
+ },
189
+ dependencies: template === "api" ? API_DEPS : DEPS,
190
+ devDependencies: template === "api" ? API_DEV_DEPS : DEV_DEPS,
137
191
  },
138
192
  null,
139
193
  2,
140
194
  )}\n`,
141
195
  )
142
196
 
143
- console.log(`
197
+ console.log(
198
+ template === "api"
199
+ ? `
200
+ Created ${appName}, a Worker API.
201
+
202
+ cd ${name}
203
+ bun install
204
+ bun dev
205
+
206
+ Rate limiting is exact and per IP, backed by the RateLimitCounter Durable
207
+ Object in wrangler.jsonc. Append migration tags; never edit a deployed one.
208
+ `
209
+ : `
144
210
  Created ${appName} with the ${theme} theme.
145
211
 
146
212
  cd ${name}
147
213
  bun install
148
214
  bun dev
149
215
 
150
- Switch themes by editing the @nimit9/signet-tokens import in src/app.css.
151
- `)
216
+ Switch themes by editing the @dapplelight/signet-tokens import in src/app.css.
217
+ `,
218
+ )
152
219
  }
153
220
 
154
221
  main().catch((err: unknown) => {
@@ -0,0 +1,22 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ permissions:
9
+ contents: read
10
+
11
+ jobs:
12
+ verify:
13
+ runs-on: ubuntu-latest
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+ - uses: oven-sh/setup-bun@v2
17
+ # Commit bun.lock: --frozen-lockfile fails the build if it is missing or stale.
18
+ - run: bun install --frozen-lockfile
19
+ - run: bun run lint
20
+ - run: bun run typecheck
21
+ - run: bun run test
22
+ - run: bun run build
@@ -1,15 +1,50 @@
1
1
  {
2
2
  "$schema": "https://biomejs.dev/schemas/2.5.14/schema.json",
3
- "vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true },
4
- "files": { "ignoreUnknown": true },
5
- "formatter": { "enabled": true, "indentStyle": "space", "indentWidth": 2, "lineWidth": 100 },
6
- "javascript": { "formatter": { "quoteStyle": "double", "semicolons": "asNeeded" } },
3
+ "vcs": {
4
+ "enabled": true,
5
+ "clientKind": "git",
6
+ "useIgnoreFile": true
7
+ },
8
+ "files": {
9
+ "ignoreUnknown": true,
10
+ "includes": ["**", "!**/routeTree.gen.ts"]
11
+ },
12
+ "formatter": {
13
+ "enabled": true,
14
+ "indentStyle": "space",
15
+ "indentWidth": 2,
16
+ "lineWidth": 100
17
+ },
18
+ "javascript": {
19
+ "formatter": {
20
+ "quoteStyle": "double",
21
+ "semicolons": "asNeeded"
22
+ }
23
+ },
7
24
  "linter": {
8
25
  "enabled": true,
9
26
  "rules": {
10
- "correctness": { "useExhaustiveDependencies": "warn", "useHookAtTopLevel": "error" },
11
- "suspicious": { "noExplicitAny": "warn" }
27
+ "correctness": {
28
+ "useExhaustiveDependencies": "warn",
29
+ "useHookAtTopLevel": "error"
30
+ },
31
+ "suspicious": {
32
+ "noExplicitAny": "warn"
33
+ }
12
34
  }
13
35
  },
14
- "assist": { "actions": { "source": { "organizeImports": "on" } } }
36
+ "assist": {
37
+ "actions": {
38
+ "source": {
39
+ "organizeImports": "on"
40
+ }
41
+ }
42
+ },
43
+ "css": {
44
+ "parser": {
45
+ "cssModules": false,
46
+ "allowWrongLineComments": false,
47
+ "tailwindDirectives": true
48
+ }
49
+ }
15
50
  }
@@ -1,3 +1,9 @@
1
1
  @import "tailwindcss";
2
- @import "@nimit9/signet-tokens/__THEME__.css";
3
- @import "@nimit9/signet-tokens/base.css";
2
+ @import "@dapplelight/signet-tokens/__THEME__.css";
3
+ @import "@dapplelight/signet-tokens/base.css";
4
+
5
+ /* Tailwind does not scan node_modules, and @dapplelight/signet-ui ships compiled JS
6
+ whose class names must be seen or every component renders unstyled. The theme
7
+ cannot declare this — a package does not know where it is installed.
8
+ Must come after the @import rules: CSS requires imports first. */
9
+ @source "../node_modules/@dapplelight/signet-ui/dist";
@@ -0,0 +1,13 @@
1
+ import { useTheme } from "@dapplelight/signet-ui/components/theme-provider"
2
+ import { Toaster as Sonner, type ToasterProps } from "sonner"
3
+
4
+ // sonner draws its own surface. These point it at the theme's popover tokens
5
+ // and follow the light/dark choice, so a toast reshapes with the theme like
6
+ // every other component. Call `toast()` from "sonner" anywhere.
7
+ const TOKENS =
8
+ "[--normal-bg:var(--color-popover)] [--normal-text:var(--color-popover-foreground)] [--normal-border:var(--color-border)] [--border-radius:var(--radius-lg)]"
9
+
10
+ export function Toaster(props: ToasterProps) {
11
+ const { resolvedTheme } = useTheme()
12
+ return <Sonner theme={resolvedTheme} className={TOKENS} {...props} />
13
+ }
@@ -1,7 +1,7 @@
1
- import { createApiClient } from "@nimit9/signet-lib/api"
1
+ import { createApiClient } from "@dapplelight/signet-lib/api"
2
2
 
3
3
  export const api = createApiClient({
4
4
  baseUrl: import.meta.env.VITE_API_BASE ?? "/api",
5
5
  })
6
6
 
7
- export { ApiError, AuthError } from "@nimit9/signet-lib/api"
7
+ export { ApiError, AuthError } from "@dapplelight/signet-lib/api"
@@ -1,16 +1,24 @@
1
- import { onAuthErrorRedirect, queryDefaults } from "@nimit9/signet-lib/api/query-client"
2
- import { ThemeProvider } from "@nimit9/signet-ui/components/theme-provider"
1
+ import { onAuthErrorRedirect, queryDefaults } from "@dapplelight/signet-lib/api/query-client"
2
+ import { ThemeProvider } from "@dapplelight/signet-ui/components/theme-provider"
3
3
  import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
4
+ import { RouterProvider } from "@tanstack/react-router"
4
5
  import { StrictMode } from "react"
5
6
  import { createRoot } from "react-dom/client"
6
- import App from "./App"
7
+ import { Toaster } from "./components/toaster"
8
+ import { createAppRouter } from "./router"
7
9
  import "./app.css"
8
10
 
9
11
  const queryClient = new QueryClient({ defaultOptions: queryDefaults() })
12
+ const router = createAppRouter()
10
13
 
11
- // One redirect on session expiry, however many requests fail at once.
14
+ // One redirect on session expiry, however many requests fail at once. A full
15
+ // page load, not router.navigate: it drops every cached query of the old
16
+ // session, and it re-arms this one-shot handler for the next session.
17
+ // buildLocation types "/login" against the route tree, so removing the route
18
+ // fails typecheck. In production the host must serve index.html for unknown
19
+ // paths (SPA fallback) or this reload 404s.
12
20
  onAuthErrorRedirect(queryClient, () => {
13
- window.location.href = "/login"
21
+ window.location.assign(router.buildLocation({ to: "/login" }).href)
14
22
  })
15
23
 
16
24
  const rootElement = document.getElementById("root")
@@ -20,7 +28,8 @@ createRoot(rootElement).render(
20
28
  <StrictMode>
21
29
  <ThemeProvider>
22
30
  <QueryClientProvider client={queryClient}>
23
- <App />
31
+ <RouterProvider router={router} />
32
+ <Toaster />
24
33
  </QueryClientProvider>
25
34
  </ThemeProvider>
26
35
  </StrictMode>,
@@ -0,0 +1,77 @@
1
+ /* eslint-disable */
2
+
3
+ // @ts-nocheck
4
+
5
+ // noinspection JSUnusedGlobalSymbols
6
+
7
+ // This file was automatically generated by TanStack Router.
8
+ // You should NOT make any changes in this file as it will be overwritten.
9
+ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.
10
+
11
+ import { Route as rootRouteImport } from "./routes/__root"
12
+ import { Route as IndexRouteImport } from "./routes/index"
13
+ import { Route as LoginRouteImport } from "./routes/login"
14
+
15
+ const IndexRoute = IndexRouteImport.update({
16
+ id: "/",
17
+ path: "/",
18
+ getParentRoute: () => rootRouteImport,
19
+ } as any)
20
+ const LoginRoute = LoginRouteImport.update({
21
+ id: "/login",
22
+ path: "/login",
23
+ getParentRoute: () => rootRouteImport,
24
+ } as any)
25
+
26
+ export interface FileRoutesByFullPath {
27
+ "/": typeof IndexRoute
28
+ "/login": typeof LoginRoute
29
+ }
30
+ export interface FileRoutesByTo {
31
+ "/": typeof IndexRoute
32
+ "/login": typeof LoginRoute
33
+ }
34
+ export interface FileRoutesById {
35
+ __root__: typeof rootRouteImport
36
+ "/": typeof IndexRoute
37
+ "/login": typeof LoginRoute
38
+ }
39
+ export interface FileRouteTypes {
40
+ fileRoutesByFullPath: FileRoutesByFullPath
41
+ fullPaths: "/" | "/login"
42
+ fileRoutesByTo: FileRoutesByTo
43
+ to: "/" | "/login"
44
+ id: "__root__" | "/" | "/login"
45
+ fileRoutesById: FileRoutesById
46
+ }
47
+ export interface RootRouteChildren {
48
+ IndexRoute: typeof IndexRoute
49
+ LoginRoute: typeof LoginRoute
50
+ }
51
+
52
+ declare module "@tanstack/react-router" {
53
+ interface FileRoutesByPath {
54
+ "/": {
55
+ id: "/"
56
+ path: "/"
57
+ fullPath: "/"
58
+ preLoaderRoute: typeof IndexRouteImport
59
+ parentRoute: typeof rootRouteImport
60
+ }
61
+ "/login": {
62
+ id: "/login"
63
+ path: "/login"
64
+ fullPath: "/login"
65
+ preLoaderRoute: typeof LoginRouteImport
66
+ parentRoute: typeof rootRouteImport
67
+ }
68
+ }
69
+ }
70
+
71
+ const rootRouteChildren: RootRouteChildren = {
72
+ IndexRoute: IndexRoute,
73
+ LoginRoute: LoginRoute,
74
+ }
75
+ export const routeTree = rootRouteImport
76
+ ._addFileChildren(rootRouteChildren)
77
+ ._addFileTypes<FileRouteTypes>()
@@ -0,0 +1,11 @@
1
+ import { expect, test } from "bun:test"
2
+ import { createMemoryHistory } from "@tanstack/react-router"
3
+ import { createAppRouter } from "./router"
4
+
5
+ // "/login" is where main.tsx sends a 401. If that route goes, the redirect
6
+ // lands on a not-found page, so it is checked here, not assumed.
7
+ test.each(["/", "/login"])("%s resolves to its own route", async (path) => {
8
+ const router = createAppRouter(createMemoryHistory({ initialEntries: [path] }))
9
+ await router.load()
10
+ expect(router.state.matches.at(-1)?.routeId).toBe(path)
11
+ })
@@ -0,0 +1,17 @@
1
+ import { createRouter, type RouterHistory } from "@tanstack/react-router"
2
+ import { routeTree } from "./routeTree.gen"
3
+
4
+ // routeTree.gen.ts is generated from src/routes by the router plugin in
5
+ // vite.config.ts on every `dev` and `build`. It is committed so `tsc` can
6
+ // typecheck before Vite has run; do not edit it by hand.
7
+
8
+ /** A history argument is for tests; the app uses the browser's. */
9
+ export function createAppRouter(history?: RouterHistory) {
10
+ return createRouter({ routeTree, history, defaultPreload: "intent" })
11
+ }
12
+
13
+ declare module "@tanstack/react-router" {
14
+ interface Register {
15
+ router: ReturnType<typeof createAppRouter>
16
+ }
17
+ }
@@ -0,0 +1,22 @@
1
+ import { ThemeToggle } from "@dapplelight/signet-ui/components/theme-toggle"
2
+ import { createRootRoute, Link, Outlet } from "@tanstack/react-router"
3
+
4
+ export const Route = createRootRoute({
5
+ component: RootLayout,
6
+ })
7
+
8
+ function RootLayout() {
9
+ return (
10
+ <div className="min-h-dvh bg-background text-foreground">
11
+ <header className="flex items-center justify-between border-b border-border px-6 py-4">
12
+ <Link to="/" className="font-medium">
13
+ __APP_NAME__
14
+ </Link>
15
+ <ThemeToggle />
16
+ </header>
17
+ <main className="mx-auto max-w-3xl p-6">
18
+ <Outlet />
19
+ </main>
20
+ </div>
21
+ )
22
+ }
@@ -0,0 +1,28 @@
1
+ import { Badge } from "@dapplelight/signet-ui/components/badge"
2
+ import { Button } from "@dapplelight/signet-ui/components/button"
3
+ import { Card, CardContent, CardHeader, CardTitle } from "@dapplelight/signet-ui/components/card"
4
+ import { createFileRoute } from "@tanstack/react-router"
5
+ import { toast } from "sonner"
6
+
7
+ export const Route = createFileRoute("/")({
8
+ component: Home,
9
+ })
10
+
11
+ function Home() {
12
+ return (
13
+ <Card>
14
+ <CardHeader>
15
+ <CardTitle>Running on the __THEME__ theme</CardTitle>
16
+ </CardHeader>
17
+ <CardContent className="flex flex-wrap items-center gap-3">
18
+ <Button onClick={() => toast.success("Saved")}>Show a toast</Button>
19
+ <Button variant="outline">Outline</Button>
20
+ <Badge>Badge</Badge>
21
+ <p className="w-full text-sm text-muted-foreground">
22
+ Swap the theme import in <code>src/app.css</code> and everything here reshapes — colour,
23
+ radius, type scale and motion. No component changes.
24
+ </p>
25
+ </CardContent>
26
+ </Card>
27
+ )
28
+ }
@@ -0,0 +1,24 @@
1
+ import { Card, CardContent, CardHeader, CardTitle } from "@dapplelight/signet-ui/components/card"
2
+ import { createFileRoute } from "@tanstack/react-router"
3
+
4
+ // Where the 401 handler in main.tsx sends the user. A placeholder: wire it to
5
+ // your own auth (a form posting to your API, an OAuth button) — the template
6
+ // deliberately does not pick an auth provider.
7
+ export const Route = createFileRoute("/login")({
8
+ component: Login,
9
+ })
10
+
11
+ function Login() {
12
+ return (
13
+ <Card className="mx-auto max-w-sm">
14
+ <CardHeader>
15
+ <CardTitle>Sign in</CardTitle>
16
+ </CardHeader>
17
+ <CardContent>
18
+ <p className="text-sm text-muted-foreground">
19
+ Your session has ended or you are not signed in. Replace this page with your sign-in flow.
20
+ </p>
21
+ </CardContent>
22
+ </Card>
23
+ )
24
+ }
@@ -21,5 +21,6 @@
21
21
  },
22
22
  "types": ["vite/client"]
23
23
  },
24
- "include": ["src"]
24
+ "include": ["src"],
25
+ "exclude": ["src/**/*.test.ts", "src/**/*.test.tsx"]
25
26
  }
@@ -1,4 +1,8 @@
1
1
  {
2
2
  "files": [],
3
- "references": [{ "path": "./tsconfig.app.json" }, { "path": "./tsconfig.node.json" }]
3
+ "references": [
4
+ { "path": "./tsconfig.app.json" },
5
+ { "path": "./tsconfig.node.json" },
6
+ { "path": "./tsconfig.test.json" }
7
+ ]
4
8
  }
@@ -0,0 +1,8 @@
1
+ {
2
+ "extends": "./tsconfig.app.json",
3
+ "compilerOptions": {
4
+ "types": ["vite/client", "bun"]
5
+ },
6
+ "include": ["src/**/*.test.ts", "src/**/*.test.tsx"],
7
+ "exclude": []
8
+ }
@@ -1,10 +1,17 @@
1
1
  import path from "node:path"
2
2
  import tailwindcss from "@tailwindcss/vite"
3
+ import { tanstackRouter } from "@tanstack/router-plugin/vite"
3
4
  import react from "@vitejs/plugin-react"
4
5
  import { defineConfig } from "vite"
5
6
 
6
7
  export default defineConfig({
7
- plugins: [react(), tailwindcss()],
8
+ plugins: [
9
+ // Must come before react(): it generates src/routeTree.gen.ts from
10
+ // src/routes and splits each route into its own chunk.
11
+ tanstackRouter({ target: "react", autoCodeSplitting: true, quoteStyle: "double" }),
12
+ react(),
13
+ tailwindcss(),
14
+ ],
8
15
  resolve: {
9
16
  alias: { "@": path.resolve(import.meta.dirname, "./src") },
10
17
  },
@@ -0,0 +1,24 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ permissions:
9
+ contents: read
10
+
11
+ jobs:
12
+ verify:
13
+ runs-on: ubuntu-latest
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+ - uses: oven-sh/setup-bun@v2
17
+ # Commit bun.lock: --frozen-lockfile fails the build if it is missing or stale.
18
+ - run: bun install --frozen-lockfile
19
+ - run: bun run lint
20
+ - run: bun run typecheck
21
+ - run: bun run test
22
+ # Bundles the Worker exactly as a deploy would, without credentials or
23
+ # uploading: catches a missing Durable Object export or a bad binding.
24
+ - run: bun run deploy --dry-run --outdir dist
@@ -0,0 +1,9 @@
1
+ node_modules
2
+ dist
3
+ .env
4
+ .env.local
5
+ *.tsbuildinfo
6
+ .DS_Store
7
+ .wrangler
8
+ .vercel
9
+ .dev.vars
@@ -0,0 +1,49 @@
1
+ {
2
+ "$schema": "https://biomejs.dev/schemas/2.5.14/schema.json",
3
+ "vcs": {
4
+ "enabled": true,
5
+ "clientKind": "git",
6
+ "useIgnoreFile": true
7
+ },
8
+ "files": {
9
+ "ignoreUnknown": true
10
+ },
11
+ "formatter": {
12
+ "enabled": true,
13
+ "indentStyle": "space",
14
+ "indentWidth": 2,
15
+ "lineWidth": 100
16
+ },
17
+ "javascript": {
18
+ "formatter": {
19
+ "quoteStyle": "double",
20
+ "semicolons": "asNeeded"
21
+ }
22
+ },
23
+ "linter": {
24
+ "enabled": true,
25
+ "rules": {
26
+ "correctness": {
27
+ "useExhaustiveDependencies": "warn",
28
+ "useHookAtTopLevel": "error"
29
+ },
30
+ "suspicious": {
31
+ "noExplicitAny": "warn"
32
+ }
33
+ }
34
+ },
35
+ "assist": {
36
+ "actions": {
37
+ "source": {
38
+ "organizeImports": "on"
39
+ }
40
+ }
41
+ },
42
+ "css": {
43
+ "parser": {
44
+ "cssModules": false,
45
+ "allowWrongLineComments": false,
46
+ "tailwindDirectives": true
47
+ }
48
+ }
49
+ }
@@ -0,0 +1,16 @@
1
+ import { createEnv } from "@dapplelight/signet-server/env"
2
+ import { z } from "zod"
3
+
4
+ // Every var and secret this Worker reads, declared once. Add a key here, then
5
+ // read it as `env.KEY` — never from `c.env` or `process.env` directly.
6
+ // Bindings that are not strings (RATE_LIMIT) are typed on the Hono app instead.
7
+ export const envSchema = z.object({
8
+ APP_ENV: z.enum(["development", "staging", "production"]).default("development"),
9
+ })
10
+
11
+ export type Env = z.infer<typeof envSchema>
12
+
13
+ // Lazy: validated on first read, not at import. Cloudflare runs module scope
14
+ // during deploy validation with no secrets, so an eager check would fail a good
15
+ // deploy. The first request calls initRuntimeEnv() before anything reads this.
16
+ export const env = createEnv(envSchema)
@@ -0,0 +1,55 @@
1
+ import { initRuntimeEnv } from "@dapplelight/signet-server/env"
2
+ import { errorHandler } from "@dapplelight/signet-server/http"
3
+ import { parseBody } from "@dapplelight/signet-server/http/validate"
4
+ import { rateLimit } from "@dapplelight/signet-server/middleware/rate-limit"
5
+ import {
6
+ durableObjectStore,
7
+ type RateLimitNamespace,
8
+ } from "@dapplelight/signet-server/middleware/rate-limit-do"
9
+ import { requestId } from "@dapplelight/signet-server/middleware/request-id"
10
+ import { Hono } from "hono"
11
+ import { z } from "zod"
12
+ import { env } from "./env"
13
+
14
+ // The Durable Object behind the rate limiter. wrangler.jsonc binds it as
15
+ // RATE_LIMIT and its first migration creates it. A Worker entry may export only
16
+ // handlers and classes like this one — workerd rejects anything else (a string
17
+ // constant) with "Incorrect type for map entry".
18
+ export { RateLimitCounter } from "@dapplelight/signet-server/middleware/rate-limit-do"
19
+
20
+ type AppEnv = {
21
+ Bindings: { RATE_LIMIT: RateLimitNamespace; APP_ENV?: string }
22
+ Variables: { reqId: string }
23
+ }
24
+
25
+ const app = new Hono<AppEnv>()
26
+ // Bindings arrive per request on Workers. Hand them over first, then read
27
+ // vars through the validated `env` from ./env. Reading env.APP_ENV here
28
+ // validates on the first request, so a bad or missing var fails loudly
29
+ // instead of whenever a handler happens to read it.
30
+ .use("*", async (c, next) => {
31
+ initRuntimeEnv(c.env)
32
+ void env.APP_ENV
33
+ await next()
34
+ })
35
+ .use("*", requestId())
36
+ // Exact per-IP limit: one Durable Object per scope:key.
37
+ .use("/api/*", rateLimit<AppEnv>({ store: (c) => durableObjectStore(c.env.RATE_LIMIT), max: 60 }))
38
+ .get("/api/health", (c) => c.json({ ok: true }))
39
+ .post("/api/echo", async (c) => {
40
+ const { message } = await parseBody(c, z.object({ message: z.string().min(1) }))
41
+ return c.json({ message })
42
+ })
43
+ .onError(errorHandler({ isProduction }))
44
+
45
+ // Fails closed: if the env does not validate, treat it as production so a 500
46
+ // hides its message instead of leaking it.
47
+ function isProduction(): boolean {
48
+ try {
49
+ return env.APP_ENV === "production"
50
+ } catch {
51
+ return true
52
+ }
53
+ }
54
+
55
+ export default app
@@ -0,0 +1,16 @@
1
+ import { expect, test } from "bun:test"
2
+ import { createEnv } from "@dapplelight/signet-server/env"
3
+ import { envSchema } from "../src/env"
4
+
5
+ test("APP_ENV defaults to development", () => {
6
+ expect(envSchema.parse({}).APP_ENV).toBe("development")
7
+ })
8
+
9
+ test("an unknown APP_ENV is rejected, not treated as development", () => {
10
+ expect(envSchema.safeParse({ APP_ENV: "prod" }).success).toBe(false)
11
+ })
12
+
13
+ test("createEnv validates lazily, on first read", () => {
14
+ const env = createEnv(envSchema, { source: () => ({ APP_ENV: "nope" }) })
15
+ expect(() => env.APP_ENV).toThrow("Invalid environment variables")
16
+ })
@@ -0,0 +1,14 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "ESNext",
5
+ "moduleResolution": "bundler",
6
+ "lib": ["ES2022", "DOM", "DOM.Iterable"],
7
+ "types": [],
8
+ "strict": true,
9
+ "skipLibCheck": true,
10
+ "isolatedModules": true,
11
+ "noEmit": true
12
+ },
13
+ "include": ["src"]
14
+ }
@@ -0,0 +1,7 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "types": ["bun"]
5
+ },
6
+ "include": ["src", "test"]
7
+ }
@@ -0,0 +1,13 @@
1
+ {
2
+ "$schema": "node_modules/wrangler/config-schema.json",
3
+ "name": "__APP_NAME__",
4
+ "main": "src/index.ts",
5
+ "compatibility_date": "2025-09-19",
6
+ "vars": { "APP_ENV": "development" },
7
+ "durable_objects": {
8
+ "bindings": [{ "name": "RATE_LIMIT", "class_name": "RateLimitCounter" }]
9
+ },
10
+ // Migration tags are this Worker's history: append new tags, never edit one
11
+ // that has been deployed.
12
+ "migrations": [{ "tag": "v1", "new_sqlite_classes": ["RateLimitCounter"] }]
13
+ }
@@ -1,32 +0,0 @@
1
- import { Badge } from "@nimit9/signet-ui/components/badge"
2
- import { Button } from "@nimit9/signet-ui/components/button"
3
- import { Card, CardContent, CardHeader, CardTitle } from "@nimit9/signet-ui/components/card"
4
- import { ThemeToggle } from "@nimit9/signet-ui/components/theme-toggle"
5
-
6
- export default function App() {
7
- return (
8
- <div className="min-h-dvh bg-background text-foreground">
9
- <header className="flex items-center justify-between border-b border-border px-6 py-4">
10
- <span className="font-medium">__APP_NAME__</span>
11
- <ThemeToggle />
12
- </header>
13
-
14
- <main className="mx-auto max-w-3xl p-6">
15
- <Card>
16
- <CardHeader>
17
- <CardTitle>Running on the __THEME__ theme</CardTitle>
18
- </CardHeader>
19
- <CardContent className="flex flex-wrap items-center gap-3">
20
- <Button>Primary</Button>
21
- <Button variant="outline">Outline</Button>
22
- <Badge>Badge</Badge>
23
- <p className="w-full text-sm text-muted-foreground">
24
- Swap the theme import in <code>src/app.css</code> and everything here reshapes —
25
- colour, radius, type scale and motion. No component changes.
26
- </p>
27
- </CardContent>
28
- </Card>
29
- </main>
30
- </div>
31
- )
32
- }