@teable/create-app 0.0.0-stage → 1.0.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 Teable, Inc.
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,3 +1,32 @@
1
- # Temporary Holding Version
1
+ # @teable/create-app
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Start a Teable app: a Drizzle schema plus read, write and task methods that
4
+ Teable runs with its own SQLite database, with an HTTP API, MCP tools and
5
+ React pages.
6
+
7
+ ```sh
8
+ npx @teable/create-app my-app --app-id <appId> # or: bunx @teable/create-app, npm init @teable/app
9
+ cd my-app && bun install && bun run check
10
+ ```
11
+
12
+ `create-teable-app <dir> [--app-id <id>]` writes a blank app into `<dir>`,
13
+ which must be absent or empty (a lone `.git` is fine), and `teable.json`
14
+ naming the app on Teable; without `--app-id` it names none. The app's
15
+ `AGENTS.md` (read by Claude Code through `CLAUDE.md`, and by other agents)
16
+ holds its rules, commands and how to publish it with `teable app publish`.
17
+ It needs [Bun](https://bun.sh).
18
+
19
+ ## The Agent Skill
20
+
21
+ `skill/teable-next-app/SKILL.md` tells an agent when to build a Teable app,
22
+ how to start one or pick one up, and the loop from edit to publish. Copy the
23
+ directory where your agent reads skills, for Claude Code
24
+ `~/.claude/skills/teable-next-app/`.
25
+
26
+ ## Where it comes from
27
+
28
+ The scaffold is `templates/blank` of the teable-next repository, copied when
29
+ this package is packed, with the versions of `@teable/app` and the other
30
+ packages it was released with. The repository typechecks, tests and builds
31
+ that template like any app, and this package's tests install, check and build
32
+ a scaffolded app outside the repository.
@@ -0,0 +1,103 @@
1
+ #!/usr/bin/env node
2
+ // @ts-check
3
+ /**
4
+ * create-teable-app <dir> [--app-id <id>]
5
+ *
6
+ * Writes a blank Teable app into <dir>: the scaffold this package carries
7
+ * (templates/blank of the teable-next repository, with the versions it was
8
+ * released with) and teable.json, which names the app on Teable. <dir> must
9
+ * be absent or empty; a lone .git is fine, so a fresh repository can take it.
10
+ *
11
+ * npx runs this with Node from node_modules, where Node runs no TypeScript,
12
+ * so it is JavaScript, and it imports only Node's own modules: nothing to
13
+ * install, and Bun runs it too.
14
+ */
15
+ import {
16
+ cpSync,
17
+ existsSync,
18
+ readdirSync,
19
+ readFileSync,
20
+ renameSync,
21
+ statSync,
22
+ writeFileSync,
23
+ } from "node:fs";
24
+ import { basename, join, relative, resolve } from "node:path";
25
+ import { fileURLToPath } from "node:url";
26
+ import { parseArgs } from "node:util";
27
+
28
+ const USAGE = "usage: create-teable-app <dir> [--app-id <id>]";
29
+ const TEMPLATE = fileURLToPath(new URL("../dist/template", import.meta.url));
30
+
31
+ /**
32
+ * @param {string} message
33
+ * @returns {never}
34
+ */
35
+ function fail(message) {
36
+ console.error(`${message}\n${USAGE}`);
37
+ process.exit(1);
38
+ }
39
+
40
+ /** @param {string[]} argv */
41
+ function parse(argv) {
42
+ try {
43
+ return parseArgs({
44
+ args: argv,
45
+ options: { "app-id": { type: "string" }, help: { type: "boolean", short: "h" } },
46
+ allowPositionals: true,
47
+ });
48
+ } catch (error) {
49
+ return fail(error instanceof Error ? error.message : String(error));
50
+ }
51
+ }
52
+
53
+ /** Absent, or a directory holding nothing but perhaps .git. @param {string} dir */
54
+ function isEmpty(dir) {
55
+ if (!existsSync(dir)) return true;
56
+ return statSync(dir).isDirectory() && readdirSync(dir).every((entry) => entry === ".git");
57
+ }
58
+
59
+ /** An npm package name from the directory's name. @param {string} dir */
60
+ function packageName(dir) {
61
+ const name = basename(dir)
62
+ .toLowerCase()
63
+ .replace(/[^a-z0-9._~-]+/g, "-")
64
+ .replace(/^[._-]+|-+$/g, "");
65
+ return name || "teable-app";
66
+ }
67
+
68
+ const { values, positionals } = parse(process.argv.slice(2));
69
+ if (values.help) {
70
+ console.log(USAGE);
71
+ process.exit(0);
72
+ }
73
+ const [target, ...extra] = positionals;
74
+ if (target === undefined) fail("Name the directory to create the app in.");
75
+ if (extra.length > 0) fail(`One directory only; also got: ${extra.join(" ")}`);
76
+ const appId = values["app-id"];
77
+ if (appId !== undefined && appId.trim() === "") fail("--app-id needs the app's id.");
78
+ if (!existsSync(TEMPLATE)) fail(`No scaffold at ${TEMPLATE}: this package was packed without it.`);
79
+
80
+ const dir = resolve(target);
81
+ if (!isEmpty(dir)) fail(`${dir} exists and is not an empty directory.`);
82
+
83
+ cpSync(TEMPLATE, dir, { recursive: true });
84
+ renameSync(join(dir, "gitignore"), join(dir, ".gitignore"));
85
+ const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
86
+ writeFileSync(
87
+ join(dir, "package.json"),
88
+ `${JSON.stringify({ ...pkg, name: packageName(dir) }, null, 2)}\n`,
89
+ );
90
+ writeFileSync(join(dir, "teable.json"), `${JSON.stringify(appId ? { appId } : {}, null, 2)}\n`);
91
+
92
+ const where = relative(process.cwd(), dir) || ".";
93
+ /** The path as a shell takes it. */
94
+ const shell = /^[\w@%+=:,./-]+$/.test(where) ? where : `'${where.replaceAll("'", "'\\''")}'`;
95
+ console.log(`Created a Teable app in ${where}.
96
+
97
+ cd ${shell}
98
+ bun install
99
+ bun run check
100
+
101
+ AGENTS.md has the rules, the commands and how to publish.`);
102
+ if (appId === undefined)
103
+ console.log("teable.json names no app yet: add its appId before publishing.");
@@ -0,0 +1,271 @@
1
+ # Teable app
2
+
3
+ This repository is one Teable app: a Drizzle schema plus read, write and task
4
+ methods, written with `@teable/app`. Teable runs it on Cloudflare in a Durable
5
+ Object with its own SQLite database, and makes an HTTP API and MCP tools from
6
+ its methods. Change it here, run the checks, and publish it with
7
+ `teable app publish`.
8
+
9
+ It starts as an example (a `notes` table, `listNotes`, `addNote`, a page, a
10
+ test at each level) that shows the whole shape. Replace it with the app the
11
+ user needs.
12
+
13
+ ## Layout
14
+
15
+ | Path | What it is |
16
+ | ---------------------- | ------------------------------------------------------------------------------------------------------------------------- |
17
+ | `src/server/schema.ts` | Tables, with their rules (Drizzle). drizzle-kit loads it in Node: it imports only `drizzle-orm` and `@teable/app/schema`. |
18
+ | `src/server/index.ts` | Methods. `export const App = app.define({ ... })` names them; Teable runs this module. |
19
+ | `drizzle/` | Migrations written by `bun run db:generate`, and `migrations.js`, which lists them. |
20
+ | `src/web/` | Pages: React, TanStack Router and Query, Tailwind on shadcn's tokens. `app.ts` holds the client and the query cache. |
21
+ | `test/` | Method tests. They run in workerd, against a real SQLite database. |
22
+ | `src/**/*.test.tsx` | Page tests, in jsdom, against a stubbed client. |
23
+ | `teable.json` | `appId`: which app on Teable this is. The `teable` CLI and the pages read it; leave it as it is. |
24
+ | `dist/` | What `bun run build` writes: `server.js`, which publishing uploads, and `pages/`. Not committed. |
25
+
26
+ ## Commands
27
+
28
+ ```sh
29
+ bun install
30
+ bun run check # typecheck, tests, migration checks; before every push
31
+ bun run build # dist/server.js (what publish uploads) and dist/pages/
32
+ bun run db:generate --name <change> # after changing schema.ts: the next migration
33
+ bun run test [file] [-t <name>] # tests only, or some of them
34
+ teable app push -m "<what changed>" # commit, and save the source to Teable
35
+ teable app publish # deploy dist/server.js, with its commit, as the next version
36
+ teable app versions # published versions, newest first: when, by whom, which commit
37
+ teable app rollback --version <n> # deploy version n's code again, as the next version
38
+ ```
39
+
40
+ `teable app <command> --help` lists every option. There is no local server
41
+ (`dev`): the runtime that hosts apps is not published. Tests are the loop:
42
+ methods against a real database, pages against a stubbed client. Publish to
43
+ see the app running.
44
+
45
+ ## The rules, and why
46
+
47
+ 1. **Data is touched only through the app's methods.** Pages, the API, MCP
48
+ tools, tasks and other apps all call methods; there is no other way into
49
+ the database. Why: the database exists only inside the app's Durable
50
+ Object, and every change is recorded with the call that made it (realtime
51
+ updates, history). SQLite triggers refuse a row change made outside a
52
+ write method.
53
+ 2. **Read and write handlers are synchronous; anything that waits is a
54
+ task.** No `async`, `await` or `fetch` in a read or a write. Why: a write
55
+ runs in one SQLite transaction, so its rows and the tasks it enqueues
56
+ commit or roll back together, and a read runs in one that fails if
57
+ anything was written. A transaction cannot wait on the network without
58
+ stopping the whole app. Returning a Promise is a type error and fails at
59
+ runtime.
60
+ 3. **Rules SQLite can enforce live in SQLite:** `.notNull()`, `check()`,
61
+ `.unique()`, `.references()`, generated columns, triggers. Methods hold
62
+ the rest. Why: a constraint holds for every write, including methods
63
+ written later, table edits and tasks; a check in one method holds only
64
+ there. A method may check first to give a readable message
65
+ (`fail("CONFLICT", "...")`); the constraint stays as the guarantee.
66
+ 4. **Migrations are append-only.** Never edit, delete, rename or reorder a
67
+ migration that a published version contained; change the schema with a
68
+ new one. Why: the live database has run them, and the SDK refuses to start
69
+ code whose migrations were edited, removed, or dated before ones already
70
+ applied, so publishing fails. Before the first publish nothing has run
71
+ anywhere: replace the example and generate `drizzle/` again (delete it,
72
+ then `bun run db:generate --name init`). In a cloned app, treat every
73
+ migration as published.
74
+ 5. **Capabilities are declared.** The app has no network and no platform
75
+ services except those it lists in `createApp`, as
76
+ `capabilities: ["files", "http"]`. Why: Teable wires in only what is
77
+ declared and shows the list to the people who run the app. Using one that
78
+ is not declared fails with a message that says how to declare it.
79
+
80
+ Also:
81
+
82
+ - Pages import server code with `import type` only, so no server code
83
+ (Drizzle, zod, `cloudflare:` modules) reaches the browser.
84
+ - Server code runs in workerd: Web APIs, no `node:` modules, no DOM.
85
+ `src/server/tsconfig.json` checks it without the DOM.
86
+ - Method results are JSON: Dates arrive as ISO strings; bigint and binary
87
+ columns are refused.
88
+ - Method names and inputs are the app's public API (HTTP, MCP, pages).
89
+ Renaming one or changing its input breaks its callers.
90
+ - Table names starting with `_teable_` are reserved.
91
+ - One app is one Durable Object: up to 10 GB, one thread, 128 MB of memory.
92
+ Keep each call small, and page through long lists (`limit`).
93
+ - Teable has no secrets store for apps yet. Never put keys or tokens in code
94
+ or git; ask the user.
95
+
96
+ ## How to
97
+
98
+ ### Add a table
99
+
100
+ 1. Declare it in `src/server/schema.ts` and export it, with its rules on it.
101
+ `col` from `@teable/app/schema` adds kinds SQLite cannot express:
102
+ `col.money({ currency })` (an integer in minor units), `col.user()`,
103
+ `col.attachments()`.
104
+ 2. `bun run db:generate --name <change>` writes `drizzle/NNNN_<change>.sql`
105
+ and its snapshot, and adds it to `drizzle/migrations.js`. Read the SQL;
106
+ commit all of it.
107
+ 3. A new NOT NULL column on a table that has rows needs `.default(...)`, or
108
+ the migration fails on live data.
109
+ 4. For SQL drizzle-kit does not write (triggers, backfills),
110
+ `bun run db:generate --custom --name <change>` makes an empty migration.
111
+ drizzle-kit changes most columns by rebuilding the table, which drops the
112
+ table's triggers: create them again in that same migration. The SDK
113
+ refuses a migration that loses one.
114
+
115
+ ### Add a read or a write
116
+
117
+ ```ts
118
+ export const markPaid = app.write({
119
+ description: "Mark an invoice paid", // shown in the API and to MCP clients
120
+ input: z.object({ id: z.number().int() }), // z from @teable/app
121
+ output: schemaOf(invoices), // what callers get; schemaOf from @teable/app/schema
122
+ access: "editor", // reads default to viewer, writes to editor
123
+ handler: ({ db, input }) =>
124
+ db.update(invoices).set({ paid: true }).where(eq(invoices.id, input.id)).returning().get() ??
125
+ fail("NOT_FOUND", `No invoice ${input.id}`),
126
+ });
127
+
128
+ export const App = app.define({ listInvoices, markPaid });
129
+ ```
130
+
131
+ - Its key in `define()` is its name in the API, MCP and pages.
132
+ - `output` says what it returns. Callers get what it outputs (keys it does
133
+ not declare are dropped); the API's response body, the MCP tool's output
134
+ schema and the builder's view come from it, and pages are typed by it. Build
135
+ it from the tables: `schemaOf(table)` for a row (`.pick`, `.omit`,
136
+ `.extend`), `schemaOf(table.column)` for one value. They carry the column's
137
+ kind, so callers tell money (and its currency) from a number.
138
+ - Return plain data: end Drizzle queries with `.all()`, `.get()` or `.run()`.
139
+ - `fail(code, message)` refuses the call with `BAD_INPUT`, `FORBIDDEN`,
140
+ `NOT_FOUND` or `CONFLICT`; nothing the write did is kept.
141
+ - `access`: the least space role that may call it (`viewer`, `commenter`,
142
+ `editor`, `creator`, `owner`), `public` (anyone, signed in or not) or
143
+ `internal` (only the app's own tasks). Finer rules check `caller` in the
144
+ handler.
145
+ - Inputs arrive as JSON. Take a date as `z.iso.datetime()` or
146
+ `z.coerce.date()`, never `z.date()`.
147
+ - Add a test in `test/`.
148
+
149
+ ### Add a page
150
+
151
+ 1. Write it in `src/web/<page>.tsx`. Read with
152
+ `useQuery({ queryKey: client.queryKey("listInvoices", input), queryFn: () => client.call("listInvoices", input) })`;
153
+ write with `useMutation`, then
154
+ `queryClient.invalidateQueries({ queryKey: client.dataKey })`. Names,
155
+ inputs and results are typed from `App`; tasks and internal methods are
156
+ not callable.
157
+ 2. Add its route in `src/web/main.tsx` (`createRoute`, then
158
+ `rootRoute.addChildren`).
159
+ 3. Style it with Tailwind classes on shadcn's tokens (`bg-primary`,
160
+ `text-muted-foreground`, `border-border`, `text-destructive`); they are in
161
+ `styles.css`. Write the text in the user's language.
162
+ 4. Test it next to it (`<page>.test.tsx`), with a client whose `fetch` the
163
+ test answers, as `notes.test.tsx` does.
164
+
165
+ ### Add a task or a schedule
166
+
167
+ ```ts
168
+ export const sendReminder = app.task({
169
+ input: z.object({ id: z.number().int() }),
170
+ handler: async ({ input, call, http }) => {
171
+ const invoice = await call(getInvoice, input); // data only through methods
172
+ await http.fetch("https://...", { method: "POST", body: JSON.stringify(invoice) });
173
+ await call(markReminded, input); // a write; access "internal" keeps it to tasks
174
+ },
175
+ });
176
+
177
+ // In a write: runs after the write commits, and not at all if it fails.
178
+ enqueue(sendReminder, { id }, { delayMs: 60 * 60_000 });
179
+
180
+ // On a schedule; its input must accept {}.
181
+ export const dailyDigest = app.task({
182
+ schedule: { cron: "0 9 * * *", timezone: "Asia/Shanghai" },
183
+ handler: async ({ call }) => {
184
+ await call(recordDigest, {});
185
+ },
186
+ });
187
+ ```
188
+
189
+ - Register tasks in `define()` too. They run outside transactions and are
190
+ never exposed.
191
+ - A failed run is retried after 1 s, 2 s, 4 s and so on, up to an hour
192
+ apart, until `maxAttempts` (8 by default): make tasks idempotent.
193
+ - A schedule missed while the app slept runs once, not once per missed time.
194
+ - Test with `await app.runTasks()`; `app.runTasks(until)` moves the clock.
195
+
196
+ ### Use a capability
197
+
198
+ Declare it in `createApp`, then use it in tasks, from their context:
199
+
200
+ - `files`: `files.put({ name, type, data })` stores a file and returns an
201
+ `Attachment` to keep in a `col.attachments()` column through a write;
202
+ `files.get(key)`; `files.share(key, { expiresInSeconds })` makes a link
203
+ anyone can open. Pages upload with `client.upload(file)` (editors, up to
204
+ 100 MB) and read with `client.fileUrl(attachment)`. Inputs that take files
205
+ validate them with `z.array(attachment)` from `@teable/app/schema`.
206
+ - `http`: the app's own `fetch()` reaches other services, so npm SDKs work
207
+ as they are; `http.fetch` is the same. Only tasks can wait for an answer.
208
+ Teable meters every request and refuses its own hosts.
209
+
210
+ These two are all there is; an app cannot add another.
211
+
212
+ ### Test
213
+
214
+ ```ts
215
+ const app = testApp(env.APP.getByName(crypto.randomUUID())); // new app, empty database
216
+ await app.call(addNote, { text: "hi" }); // as an owner, through JSON, as callers get it
217
+ await app.as({ kind: "user", userId: "u2", role: "viewer", via: "web" }).call(listNotes);
218
+ await app.runTasks(); // run due tasks, and the tasks they enqueue
219
+ await app.changes(); // the changefeed: every row change, with its call
220
+ ```
221
+
222
+ A refused call throws `MethodError` (`error.code`, `error.message`,
223
+ `status`). Before its first call, a new app runs the migrations and checks
224
+ that the database has what `schema.ts` declares, so every test also checks
225
+ the migrations.
226
+
227
+ ## When something fails
228
+
229
+ | You see | Do |
230
+ | ------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
231
+ | `read and write handlers must be synchronous` (type error), or `returned a Promise` | Take `async`/`await` out of the handler; move the waiting into a task the write enqueues. |
232
+ | `returned what its output schema refuses, at <path>` | The handler returned what `output` does not accept (a missing key, a null, another type): fix one or the other. |
233
+ | `returned a ... at result ... Did you forget .get() or .all()?` | End the query with `.all()`, `.get()` or `.run()`. |
234
+ | `Read method "..." wrote data` | Make it a write. |
235
+ | `The database does not match schema.ts` | `schema.ts` changed without a migration: `bun run db:generate`. |
236
+ | `Migration ... removed trigger ...` | Create the trigger again in that migration, after the rebuild. |
237
+ | `Migration ... drops table ..., and dropping a table deletes its rows first` | Do what the message says: change the reference to `NO ACTION` or `RESTRICT` in a migration of its own first. |
238
+ | `Migration ... changed after it was applied`, or `was applied but is missing` | A published migration was edited or deleted. Restore it from git, and make the change in a new migration. |
239
+ | `Migration ... is older than the latest applied migration` | It was generated before one that is already live: delete it (its `.sql`, snapshot and entries) and generate it again. |
240
+ | `CONSTRAINT`: `CHECK constraint failed: <name>`, `UNIQUE ...`, `NOT NULL ...`, `FOREIGN KEY ...` | A rule in SQLite refused the input; the rule works. For a readable message, check first in the method and `fail(...)`. Never drop a constraint to make a call pass. |
241
+ | `BAD_INPUT`: `Input does not match the method's schema` | `issues` names the fields that failed the input's zod schema. |
242
+ | `Declare capabilities: [...] in createApp`, or `not permitted to access the internet` | Declare the capability; use it in a task. |
243
+ | `must export the class from define() as "App"` (build) | `export const App = app.define({ ... })` in `src/server/index.ts`. |
244
+ | `Stripping types is currently unsupported for files under node_modules` | Vite or Vitest ran on Node; run them through `bun run test` and `bun run build`. |
245
+ | `FORBIDDEN` from `teable app publish` or `rollback` | Publishing takes the `creator` or `owner` role in the app's space; ask the user. |
246
+ | `CONFLICT` from `teable app rollback` | That version lacks a migration the live database has run: roll forward with a new version instead. |
247
+ | `RATE_LIMITED` (HTTP 429) | Wait as long as `Retry-After` says, then try again. |
248
+ | `Deploy rejected: built for app protocol N; this runtime speaks M` (publish) | `bun add @teable/app@latest`, then check, build and publish again. |
249
+ | `Deploy rejected` with `Migration ... failed: ...` (publish) | The migration does not fit the live rows (a NOT NULL column without a default, a CHECK some rows break): make it handle them (a default, an `UPDATE` first). A rejected migration never ran: edit it. |
250
+
251
+ ## Publishing
252
+
253
+ Once `bun run check` and `bun run build` pass, push and publish:
254
+ `teable app push -m "<what changed>"`, then `teable app publish`. Do not wait
255
+ to be asked: publishing is how the user gets the change, and a publish that
256
+ fails changes nothing. It takes the `creator` or `owner` role in the app's
257
+ space. Teable starts the new version on a copy of the live data first,
258
+ running its migrations, then on the live data, and makes it live only if both
259
+ work; open pages read everything again. Every version records when it was
260
+ published, by whom, and from which commit. Then tell the user what changed.
261
+ The methods are live at once through the API
262
+ (`/api/v4/apps/<appId>/methods/<name>`, described at `.../openapi.json`), MCP
263
+ (`/api/v4/apps/<appId>/mcp`) and the app on Teable; Teable does not serve
264
+ `dist/pages` yet.
265
+
266
+ `teable app rollback` deploys an earlier version's code again, as the next
267
+ version. It cannot go back past a migration: the live database has run it,
268
+ and code without it does not start, so the rollback is refused (`CONFLICT`);
269
+ undo a schema change with a new migration. A rollback changes only what
270
+ runs, not this repository: fix or revert the code here before publishing
271
+ again, or the next publish brings it back.
@@ -0,0 +1 @@
1
+ @AGENTS.md
@@ -0,0 +1,22 @@
1
+ {
2
+ "$schema": "https://ui.shadcn.com/schema.json",
3
+ "style": "new-york",
4
+ "rsc": false,
5
+ "tsx": true,
6
+ "tailwind": {
7
+ "config": "",
8
+ "css": "src/web/styles.css",
9
+ "baseColor": "neutral",
10
+ "cssVariables": true
11
+ },
12
+ "aliases": {
13
+ "components": "@/components",
14
+ "utils": "@/lib/utils",
15
+ "ui": "@/components/ui",
16
+ "lib": "@/lib",
17
+ "hooks": "@/hooks"
18
+ },
19
+ "registries": {
20
+ "@teable": "https://teable.ai/r/{name}.json"
21
+ }
22
+ }
@@ -0,0 +1,6 @@
1
+ CREATE TABLE `notes` (
2
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
3
+ `text` text NOT NULL,
4
+ `createdAt` integer DEFAULT (unixepoch() * 1000) NOT NULL,
5
+ CONSTRAINT "note_text_not_blank" CHECK(trim("notes"."text") <> '')
6
+ );
@@ -0,0 +1,55 @@
1
+ {
2
+ "version": "6",
3
+ "dialect": "sqlite",
4
+ "id": "38b2accd-10fa-4dee-b111-417bcba3e7ed",
5
+ "prevId": "00000000-0000-0000-0000-000000000000",
6
+ "tables": {
7
+ "notes": {
8
+ "name": "notes",
9
+ "columns": {
10
+ "id": {
11
+ "name": "id",
12
+ "type": "integer",
13
+ "primaryKey": true,
14
+ "notNull": true,
15
+ "autoincrement": true
16
+ },
17
+ "text": {
18
+ "name": "text",
19
+ "type": "text",
20
+ "primaryKey": false,
21
+ "notNull": true,
22
+ "autoincrement": false
23
+ },
24
+ "createdAt": {
25
+ "name": "createdAt",
26
+ "type": "integer",
27
+ "primaryKey": false,
28
+ "notNull": true,
29
+ "autoincrement": false,
30
+ "default": "(unixepoch() * 1000)"
31
+ }
32
+ },
33
+ "indexes": {},
34
+ "foreignKeys": {},
35
+ "compositePrimaryKeys": {},
36
+ "uniqueConstraints": {},
37
+ "checkConstraints": {
38
+ "note_text_not_blank": {
39
+ "name": "note_text_not_blank",
40
+ "value": "trim(\"notes\".\"text\") <> ''"
41
+ }
42
+ }
43
+ }
44
+ },
45
+ "views": {},
46
+ "enums": {},
47
+ "_meta": {
48
+ "schemas": {},
49
+ "tables": {},
50
+ "columns": {}
51
+ },
52
+ "internal": {
53
+ "indexes": {}
54
+ }
55
+ }
@@ -0,0 +1,13 @@
1
+ {
2
+ "version": "7",
3
+ "dialect": "sqlite",
4
+ "entries": [
5
+ {
6
+ "idx": 0,
7
+ "version": "6",
8
+ "when": 1796289550119,
9
+ "tag": "0000_init",
10
+ "breakpoints": true
11
+ }
12
+ ]
13
+ }
@@ -0,0 +1,10 @@
1
+ import journal from './meta/_journal.json';
2
+ import m0000 from './0000_init.sql';
3
+
4
+ export default {
5
+ journal,
6
+ migrations: {
7
+ m0000
8
+ }
9
+ }
10
+
@@ -0,0 +1,8 @@
1
+ import { defineConfig } from "drizzle-kit";
2
+
3
+ export default defineConfig({
4
+ dialect: "sqlite",
5
+ driver: "durable-sqlite",
6
+ schema: "./src/server/schema.ts",
7
+ out: "./drizzle",
8
+ });
@@ -0,0 +1,8 @@
1
+ node_modules/
2
+ dist/
3
+ .wrangler/
4
+ .dev.vars
5
+ .env
6
+ .env.*
7
+ *.log
8
+ .DS_Store
@@ -0,0 +1,12 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>Notes</title>
7
+ </head>
8
+ <body>
9
+ <div id="root"></div>
10
+ <script type="module" src="/src/web/main.tsx"></script>
11
+ </body>
12
+ </html>
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@teable/template-blank",
3
+ "version": "0.0.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "scripts": {
7
+ "check": "bun run typecheck && bun run test && drizzle-kit check",
8
+ "build": "teable-app build && vite build",
9
+ "db:generate": "drizzle-kit generate",
10
+ "typecheck": "tsc -p . && tsc -p src/server",
11
+ "test": "vitest run"
12
+ },
13
+ "dependencies": {
14
+ "@tanstack/react-query": "5.108.4",
15
+ "@tanstack/react-router": "1.170.46",
16
+ "@teable/app": "^5.0.0",
17
+ "drizzle-orm": "0.45.4",
18
+ "react": "19.3.1",
19
+ "react-dom": "19.3.1"
20
+ },
21
+ "devDependencies": {
22
+ "@cloudflare/vitest-plugin": "1.10.2",
23
+ "@cloudflare/workers-types": "5.20261201.1",
24
+ "@tailwindcss/vite": "4.3.5",
25
+ "@testing-library/react": "16.3.3",
26
+ "@types/node": "26.6.11",
27
+ "@types/react": "19.3.3",
28
+ "@types/react-dom": "19.3.0",
29
+ "@vitejs/plugin-react": "6.3.1",
30
+ "drizzle-kit": "0.31.11",
31
+ "jsdom": "31.0.1",
32
+ "shadcn": "4.23.1",
33
+ "tailwindcss": "4.3.5",
34
+ "tw-animate-css": "1.4.0",
35
+ "typescript": "7.0.2",
36
+ "vite": "8.4.1",
37
+ "vitest": "5.1.2"
38
+ }
39
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * A blank Teable app: one table, one read, one write. Replace them with the
3
+ * app's own; AGENTS.md says how.
4
+ */
5
+ import { createApp, z } from "@teable/app";
6
+ import { schemaOf } from "@teable/app/schema";
7
+ import { desc } from "drizzle-orm";
8
+ import migrations from "../../drizzle/migrations";
9
+ import * as schema from "./schema";
10
+ import { notes } from "./schema";
11
+
12
+ const app = createApp({ schema, migrations });
13
+
14
+ export const listNotes = app.read({
15
+ description: "Notes, newest first",
16
+ output: z.array(schemaOf(notes)),
17
+ handler: ({ db }) => db.select().from(notes).orderBy(desc(notes.id)).all(),
18
+ });
19
+
20
+ export const addNote = app.write({
21
+ description: "Add a note",
22
+ // That the text is not blank is the table's CHECK constraint, not this schema's.
23
+ input: z.object({ text: z.string() }),
24
+ output: schemaOf(notes),
25
+ handler: ({ db, input }) => db.insert(notes).values(input).returning().get(),
26
+ });
27
+
28
+ export const App = app.define({ listNotes, addNote });
@@ -0,0 +1,13 @@
1
+ import { sql } from "drizzle-orm";
2
+ import { check, integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
3
+
4
+ export const notes = sqliteTable(
5
+ "notes",
6
+ {
7
+ id: integer().primaryKey({ autoIncrement: true }),
8
+ text: text().notNull(),
9
+ createdAt: integer({ mode: "timestamp_ms" }).notNull().default(sql`(unixepoch() * 1000)`),
10
+ },
11
+ // A rule SQLite can hold lives here, not in a method: every write path gets it.
12
+ (t) => [check("note_text_not_blank", sql`trim(${t.text}) <> ''`)],
13
+ );
@@ -0,0 +1,10 @@
1
+ {
2
+ // The app's server code runs in workerd: Workers globals, no DOM.
3
+ "extends": "../../tsconfig.base.json",
4
+ "compilerOptions": {
5
+ // drizzle-kit writes the migrations index as JavaScript.
6
+ "allowJs": true,
7
+ "types": ["@cloudflare/workers-types"]
8
+ },
9
+ "include": ["."]
10
+ }
@@ -0,0 +1,35 @@
1
+ import { QueryClient } from "@tanstack/react-query";
2
+ import { createClient, MethodError, type RealtimeEvent } from "@teable/app/client";
3
+ import type * as server from "../server";
4
+
5
+ /**
6
+ * This app's methods, typed from the `App` the server code exports: the names
7
+ * its define() registered, without internal methods and tasks.
8
+ */
9
+ export const client = createClient<typeof server>({
10
+ appId: import.meta.env.VITE_TEABLE_APP_ID,
11
+ });
12
+
13
+ /**
14
+ * The query cache every page shares. A failed read is asked again only when
15
+ * another answer may come, so a refusal (not a member, one of the app's
16
+ * rules) shows at once instead of after three more tries.
17
+ */
18
+ export const queryClient = new QueryClient({
19
+ defaultOptions: {
20
+ queries: {
21
+ retry: (failures, error) =>
22
+ failures < 3 && (!(error instanceof MethodError) || error.retryable),
23
+ },
24
+ },
25
+ });
26
+
27
+ /**
28
+ * What pages read again when the app reports an event (`client.subscribe`):
29
+ * method results after any; the manifest too after a new version went live or
30
+ * the connection was down, since either may have changed it.
31
+ */
32
+ export function refetchAfter(event: RealtimeEvent): void {
33
+ queryClient.invalidateQueries({ queryKey: client.dataKey });
34
+ if (event.type !== "changes") queryClient.invalidateQueries({ queryKey: client.manifestKey });
35
+ }
@@ -0,0 +1,49 @@
1
+ import { QueryClientProvider } from "@tanstack/react-query";
2
+ import {
3
+ createRootRoute,
4
+ createRoute,
5
+ createRouter,
6
+ Outlet,
7
+ RouterProvider,
8
+ } from "@tanstack/react-router";
9
+ import { StrictMode } from "react";
10
+ import { createRoot } from "react-dom/client";
11
+ import { client, queryClient, refetchAfter } from "./app";
12
+ import { NotesPage } from "./notes";
13
+ import "./styles.css";
14
+
15
+ const rootRoute = createRootRoute({
16
+ component: () => (
17
+ <main className="mx-auto max-w-2xl p-6">
18
+ <Outlet />
19
+ </main>
20
+ ),
21
+ });
22
+
23
+ const notesRoute = createRoute({
24
+ getParentRoute: () => rootRoute,
25
+ path: "/",
26
+ component: NotesPage,
27
+ });
28
+
29
+ const router = createRouter({ routeTree: rootRoute.addChildren([notesRoute]) });
30
+
31
+ declare module "@tanstack/react-router" {
32
+ interface Register {
33
+ router: typeof router;
34
+ }
35
+ }
36
+
37
+ const root = document.getElementById("root");
38
+ if (root) {
39
+ // One subscription for every page: whatever changes the app (this page,
40
+ // another tab, the API, a task, a deploy), pages read again what it made stale.
41
+ client.subscribe(refetchAfter);
42
+ createRoot(root).render(
43
+ <StrictMode>
44
+ <QueryClientProvider client={queryClient}>
45
+ <RouterProvider router={router} />
46
+ </QueryClientProvider>
47
+ </StrictMode>,
48
+ );
49
+ }
@@ -0,0 +1,45 @@
1
+ import { QueryClientProvider } from "@tanstack/react-query";
2
+ import { fireEvent, render, screen } from "@testing-library/react";
3
+ import { expect, it, vi } from "vitest";
4
+ import type * as server from "../server";
5
+ import { queryClient } from "./app";
6
+ import { NotesPage } from "./notes";
7
+
8
+ /** The runtime the page's client talks to; the test says how it answers. */
9
+ const runtime = vi.hoisted(() => ({ fetch: vi.fn<typeof fetch>() }));
10
+
11
+ // The app's own query cache, with a client that reaches the stand-in runtime.
12
+ vi.mock(import("./app"), async (importOriginal) => {
13
+ const { createClient } = await import("@teable/app/client");
14
+ return {
15
+ ...(await importOriginal()),
16
+ client: createClient<typeof server>({ appId: "test", fetch: runtime.fetch }),
17
+ };
18
+ });
19
+
20
+ it("shows the notes and adds one through addNote", async () => {
21
+ const notes = [{ id: 1, text: "first", createdAt: "2026-12-03T08:00:00.000Z" }];
22
+ runtime.fetch.mockImplementation(async (url, init) => {
23
+ const method = new URL(String(url)).pathname.split("/").pop();
24
+ if (method === "addNote") {
25
+ const { text } = JSON.parse(String(init?.body)) as { text: string };
26
+ notes.unshift({ id: notes.length + 1, text, createdAt: new Date().toISOString() });
27
+ return Response.json(notes[0]);
28
+ }
29
+ return Response.json(notes);
30
+ });
31
+ render(
32
+ <QueryClientProvider client={queryClient}>
33
+ <NotesPage />
34
+ </QueryClientProvider>,
35
+ );
36
+ expect(await screen.findByText("first")).toBeTruthy();
37
+
38
+ fireEvent.change(screen.getByLabelText("New note"), { target: { value: "second" } });
39
+ fireEvent.click(screen.getByRole("button", { name: "Add" }));
40
+ expect(await screen.findByText("second")).toBeTruthy();
41
+ expect(runtime.fetch).toHaveBeenCalledWith(
42
+ expect.stringMatching(/\/apps\/test\/methods\/addNote$/),
43
+ expect.objectContaining({ method: "POST", body: JSON.stringify({ text: "second" }) }),
44
+ );
45
+ });
@@ -0,0 +1,64 @@
1
+ import { useMutation, useQuery } from "@tanstack/react-query";
2
+ import { useState } from "react";
3
+ import { client, queryClient } from "./app";
4
+
5
+ /** The notes, newest first, and a box to add one. */
6
+ export function NotesPage() {
7
+ const notes = useQuery({
8
+ queryKey: client.queryKey("listNotes"),
9
+ queryFn: () => client.call("listNotes"),
10
+ });
11
+ const [text, setText] = useState("");
12
+ const add = useMutation({
13
+ mutationFn: (text: string) => client.call("addNote", { text }),
14
+ onSuccess: () => {
15
+ setText("");
16
+ return queryClient.invalidateQueries({ queryKey: client.dataKey });
17
+ },
18
+ });
19
+ // A page with nothing to show says why: the app's refusal, or the network's.
20
+ const error = add.error ?? notes.error;
21
+
22
+ return (
23
+ <section className="space-y-4">
24
+ <h1 className="font-semibold text-xl">Notes</h1>
25
+ <form
26
+ className="flex gap-2"
27
+ onSubmit={(event) => {
28
+ event.preventDefault();
29
+ add.mutate(text);
30
+ }}
31
+ >
32
+ <input
33
+ aria-label="New note"
34
+ value={text}
35
+ onChange={(event) => setText(event.target.value)}
36
+ className="flex-1 rounded-md border border-input bg-background px-3 py-2 text-sm"
37
+ />
38
+ <button
39
+ type="submit"
40
+ disabled={text.trim() === "" || add.isPending}
41
+ className="rounded-md bg-primary px-4 py-2 text-primary-foreground text-sm disabled:opacity-50"
42
+ >
43
+ Add
44
+ </button>
45
+ </form>
46
+ {error && (
47
+ <p role="alert" className="text-destructive text-sm">
48
+ {error.message}
49
+ </p>
50
+ )}
51
+ {notes.data ? (
52
+ <ul className="divide-y divide-border rounded-md border border-border">
53
+ {notes.data.map((note) => (
54
+ <li key={note.id} className="px-3 py-2 text-sm">
55
+ {note.text}
56
+ </li>
57
+ ))}
58
+ </ul>
59
+ ) : (
60
+ !notes.error && <p className="text-muted-foreground text-sm">Loading…</p>
61
+ )}
62
+ </section>
63
+ );
64
+ }
@@ -0,0 +1,137 @@
1
+ @import "tailwindcss";
2
+
3
+ /*
4
+ * shadcn's standard stylesheet for style new-york, base color neutral, CSS
5
+ * variables, Tailwind v4 (what the shop template's components.json declares),
6
+ * as the shadcn CLI writes it: tw-animate-css (enter and exit animations),
7
+ * shadcn/tailwind.css (the data-open: style variants that dialogs, popovers
8
+ * and menus use) and the tokens. Registry components style themselves with
9
+ * these.
10
+ *
11
+ * From this comment to the end, templates/shop/src/web/styles.css and
12
+ * apps/web/src/styles.css are identical, so the builder looks like the apps it
13
+ * builds.
14
+ */
15
+ @import "tw-animate-css";
16
+ @import "shadcn/tailwind.css";
17
+
18
+ @custom-variant dark (&:is(.dark *));
19
+
20
+ :root {
21
+ --background: oklch(1 0 0);
22
+ --foreground: oklch(0.145 0 0);
23
+ --card: oklch(1 0 0);
24
+ --card-foreground: oklch(0.145 0 0);
25
+ --popover: oklch(1 0 0);
26
+ --popover-foreground: oklch(0.145 0 0);
27
+ --primary: oklch(0.205 0 0);
28
+ --primary-foreground: oklch(0.985 0 0);
29
+ --secondary: oklch(0.97 0 0);
30
+ --secondary-foreground: oklch(0.205 0 0);
31
+ --muted: oklch(0.97 0 0);
32
+ --muted-foreground: oklch(0.556 0 0);
33
+ --accent: oklch(0.97 0 0);
34
+ --accent-foreground: oklch(0.205 0 0);
35
+ --destructive: oklch(0.577 0.245 27.325);
36
+ --border: oklch(0.922 0 0);
37
+ --input: oklch(0.922 0 0);
38
+ --ring: oklch(0.708 0 0);
39
+ --chart-1: oklch(0.87 0 0);
40
+ --chart-2: oklch(0.556 0 0);
41
+ --chart-3: oklch(0.439 0 0);
42
+ --chart-4: oklch(0.371 0 0);
43
+ --chart-5: oklch(0.269 0 0);
44
+ --radius: 0.625rem;
45
+ --sidebar: oklch(0.985 0 0);
46
+ --sidebar-foreground: oklch(0.145 0 0);
47
+ --sidebar-primary: oklch(0.205 0 0);
48
+ --sidebar-primary-foreground: oklch(0.985 0 0);
49
+ --sidebar-accent: oklch(0.97 0 0);
50
+ --sidebar-accent-foreground: oklch(0.205 0 0);
51
+ --sidebar-border: oklch(0.922 0 0);
52
+ --sidebar-ring: oklch(0.708 0 0);
53
+ }
54
+
55
+ .dark {
56
+ --background: oklch(0.145 0 0);
57
+ --foreground: oklch(0.985 0 0);
58
+ --card: oklch(0.205 0 0);
59
+ --card-foreground: oklch(0.985 0 0);
60
+ --popover: oklch(0.205 0 0);
61
+ --popover-foreground: oklch(0.985 0 0);
62
+ --primary: oklch(0.922 0 0);
63
+ --primary-foreground: oklch(0.205 0 0);
64
+ --secondary: oklch(0.269 0 0);
65
+ --secondary-foreground: oklch(0.985 0 0);
66
+ --muted: oklch(0.269 0 0);
67
+ --muted-foreground: oklch(0.708 0 0);
68
+ --accent: oklch(0.269 0 0);
69
+ --accent-foreground: oklch(0.985 0 0);
70
+ --destructive: oklch(0.704 0.191 22.216);
71
+ --border: oklch(1 0 0 / 10%);
72
+ --input: oklch(1 0 0 / 15%);
73
+ --ring: oklch(0.556 0 0);
74
+ --chart-1: oklch(0.87 0 0);
75
+ --chart-2: oklch(0.556 0 0);
76
+ --chart-3: oklch(0.439 0 0);
77
+ --chart-4: oklch(0.371 0 0);
78
+ --chart-5: oklch(0.269 0 0);
79
+ --sidebar: oklch(0.205 0 0);
80
+ --sidebar-foreground: oklch(0.985 0 0);
81
+ --sidebar-primary: oklch(0.488 0.243 264.376);
82
+ --sidebar-primary-foreground: oklch(0.985 0 0);
83
+ --sidebar-accent: oklch(0.269 0 0);
84
+ --sidebar-accent-foreground: oklch(0.985 0 0);
85
+ --sidebar-border: oklch(1 0 0 / 10%);
86
+ --sidebar-ring: oklch(0.556 0 0);
87
+ }
88
+
89
+ @theme inline {
90
+ --color-background: var(--background);
91
+ --color-foreground: var(--foreground);
92
+ --color-card: var(--card);
93
+ --color-card-foreground: var(--card-foreground);
94
+ --color-popover: var(--popover);
95
+ --color-popover-foreground: var(--popover-foreground);
96
+ --color-primary: var(--primary);
97
+ --color-primary-foreground: var(--primary-foreground);
98
+ --color-secondary: var(--secondary);
99
+ --color-secondary-foreground: var(--secondary-foreground);
100
+ --color-muted: var(--muted);
101
+ --color-muted-foreground: var(--muted-foreground);
102
+ --color-accent: var(--accent);
103
+ --color-accent-foreground: var(--accent-foreground);
104
+ --color-destructive: var(--destructive);
105
+ --color-border: var(--border);
106
+ --color-input: var(--input);
107
+ --color-ring: var(--ring);
108
+ --color-chart-1: var(--chart-1);
109
+ --color-chart-2: var(--chart-2);
110
+ --color-chart-3: var(--chart-3);
111
+ --color-chart-4: var(--chart-4);
112
+ --color-chart-5: var(--chart-5);
113
+ --radius-sm: calc(var(--radius) * 0.6);
114
+ --radius-md: calc(var(--radius) * 0.8);
115
+ --radius-lg: var(--radius);
116
+ --radius-xl: calc(var(--radius) * 1.4);
117
+ --radius-2xl: calc(var(--radius) * 1.8);
118
+ --radius-3xl: calc(var(--radius) * 2.2);
119
+ --radius-4xl: calc(var(--radius) * 2.6);
120
+ --color-sidebar: var(--sidebar);
121
+ --color-sidebar-foreground: var(--sidebar-foreground);
122
+ --color-sidebar-primary: var(--sidebar-primary);
123
+ --color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
124
+ --color-sidebar-accent: var(--sidebar-accent);
125
+ --color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
126
+ --color-sidebar-border: var(--sidebar-border);
127
+ --color-sidebar-ring: var(--sidebar-ring);
128
+ }
129
+
130
+ @layer base {
131
+ * {
132
+ @apply border-border outline-ring/50;
133
+ }
134
+ body {
135
+ @apply bg-background text-foreground;
136
+ }
137
+ }
@@ -0,0 +1 @@
1
+ {}
@@ -0,0 +1,10 @@
1
+ declare namespace Cloudflare {
2
+ interface Env {
3
+ APP: DurableObjectNamespace;
4
+ }
5
+ }
6
+
7
+ declare module "*.sql" {
8
+ const sql: string;
9
+ export default sql;
10
+ }
@@ -0,0 +1,29 @@
1
+ import { env } from "cloudflare:test";
2
+ import { MethodError } from "@teable/app/client";
3
+ import { testApp } from "@teable/app/testing";
4
+ import { expect, it } from "vitest";
5
+ import { addNote, listNotes } from "../src/server";
6
+
7
+ /**
8
+ * A new app on an empty database. Before its first call the SDK runs the
9
+ * migrations and checks that the database has what schema.ts declares.
10
+ */
11
+ const fresh = () => testApp(env.APP.getByName(crypto.randomUUID()));
12
+
13
+ it("keeps notes, newest first", async () => {
14
+ const app = fresh();
15
+ await app.call(addNote, { text: "first" });
16
+ await app.call(addNote, { text: "second" });
17
+ expect((await app.call(listNotes)).map((note) => note.text)).toEqual(["second", "first"]);
18
+ });
19
+
20
+ it("refuses a blank note: the CHECK constraint holds that rule", async () => {
21
+ const app = fresh();
22
+ const error = await app.call(addNote, { text: " " }).catch((e: unknown) => e);
23
+ expect(error).toBeInstanceOf(MethodError);
24
+ expect((error as MethodError).error).toEqual({
25
+ code: "CONSTRAINT",
26
+ message: "CHECK constraint failed: note_text_not_blank",
27
+ });
28
+ expect(await app.call(listNotes)).toEqual([]);
29
+ });
@@ -0,0 +1,5 @@
1
+ export { App } from "../src/server";
2
+
3
+ export default {
4
+ fetch: () => new Response("test worker"),
5
+ } satisfies ExportedHandler;
@@ -0,0 +1,19 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2024",
4
+ "lib": ["ES2024"],
5
+ "module": "preserve",
6
+ "moduleResolution": "bundler",
7
+ "moduleDetection": "force",
8
+ "strict": true,
9
+ "noUncheckedIndexedAccess": true,
10
+ "noImplicitOverride": true,
11
+ "noFallthroughCasesInSwitch": true,
12
+ "verbatimModuleSyntax": true,
13
+ "isolatedModules": true,
14
+ "resolveJsonModule": true,
15
+ "skipLibCheck": true,
16
+ "noEmit": true,
17
+ "types": []
18
+ }
19
+ }
@@ -0,0 +1,13 @@
1
+ {
2
+ "extends": "./tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "allowJs": true,
5
+ "lib": ["ES2024", "DOM", "DOM.Iterable"],
6
+ "jsx": "react-jsx",
7
+ "types": ["@cloudflare/workers-types", "@cloudflare/vitest-plugin/types", "vite/client"],
8
+ "paths": { "@/*": ["./src/*"] }
9
+ },
10
+ "include": ["src", "test", "drizzle", "drizzle.config.ts", "vite.config.ts"],
11
+ // Checked without the DOM by src/server/tsconfig.json.
12
+ "exclude": ["src/server"]
13
+ }
@@ -0,0 +1,43 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { cloudflareTest } from "@cloudflare/vitest-plugin";
3
+ import tailwindcss from "@tailwindcss/vite";
4
+ import { sqlAsText } from "@teable/app/build";
5
+ import { APP_COMPATIBILITY_DATE } from "@teable/app/protocol";
6
+ import react from "@vitejs/plugin-react";
7
+ import { defineConfig } from "vitest/config";
8
+
9
+ /** Which Teable app this is, as teable.json says; pages call its methods. */
10
+ const { appId = "" } = JSON.parse(
11
+ readFileSync(new URL("./teable.json", import.meta.url), "utf8"),
12
+ ) as { appId?: string };
13
+
14
+ /** The app's pages, and its tests. */
15
+ export default defineConfig({
16
+ plugins: [react(), tailwindcss()],
17
+ // `@/` is src/, as tsconfig.json's paths say.
18
+ resolve: { tsconfigPaths: true },
19
+ define: { "import.meta.env.VITE_TEABLE_APP_ID": JSON.stringify(appId) },
20
+ build: { outDir: "dist/pages" },
21
+ test: {
22
+ projects: [
23
+ {
24
+ // The app's methods, run in workerd against real SQLite, with none of
25
+ // the pages' configuration.
26
+ extends: false,
27
+ plugins: [
28
+ sqlAsText(),
29
+ cloudflareTest({
30
+ wrangler: { configPath: "./wrangler.test.jsonc" },
31
+ miniflare: { compatibilityDate: APP_COMPATIBILITY_DATE },
32
+ }),
33
+ ],
34
+ test: { name: "server", include: ["test/**/*.test.ts"] },
35
+ },
36
+ {
37
+ // Pages, in jsdom, resolved and compiled as the pages are.
38
+ extends: true,
39
+ test: { name: "web", environment: "jsdom", include: ["src/**/*.test.{ts,tsx}"] },
40
+ },
41
+ ],
42
+ },
43
+ });
@@ -0,0 +1,7 @@
1
+ // Test-only Worker: runs the app as a plain Durable Object.
2
+ {
3
+ "name": "teable-app-test",
4
+ "main": "test/worker.ts",
5
+ "durable_objects": { "bindings": [{ "name": "APP", "class_name": "App" }] },
6
+ "migrations": [{ "tag": "v1", "new_sqlite_classes": ["App"] }]
7
+ }
package/package.json CHANGED
@@ -1,6 +1,24 @@
1
1
  {
2
2
  "name": "@teable/create-app",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Start a Teable app: a blank app, the instructions agents read in it, and the teable-next-app Agent Skill",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/teableio/teable-next.git",
9
+ "directory": "packages/create-app"
10
+ },
11
+ "type": "module",
12
+ "bin": {
13
+ "create-teable-app": "./bin/create-teable-app.js"
14
+ },
15
+ "files": [
16
+ "bin",
17
+ "dist/template",
18
+ "skill"
19
+ ],
20
+ "publishConfig": {
21
+ "access": "public",
22
+ "provenance": true
23
+ }
24
+ }
@@ -0,0 +1,88 @@
1
+ ---
2
+ name: teable-next-app
3
+ description: Build, change, test and publish a Teable app (teable-next) — a Drizzle schema plus read, write and task methods that Teable runs with its own SQLite database and turns into an HTTP API and MCP tools, with React pages. Use when the user wants an app, tool or internal system built on Teable (a tracker, CRM, approval flow, inventory, booking, dashboard with its own data and rules), or wants one changed, fixed or published, or the working directory holds an app repository (teable.json, @teable/app in package.json). Not for editing records, fields or views of a classic Teable base.
4
+ ---
5
+
6
+ # Teable apps (teable-next)
7
+
8
+ A Teable app is a repository: a Drizzle schema (`src/server/schema.ts`), read,
9
+ write and task methods (`src/server/index.ts`, with `@teable/app`), migrations
10
+ (`drizzle/`), pages (`src/web/`) and tests. Teable runs it on Cloudflare, one
11
+ Durable Object with its own SQLite database per app, and makes an HTTP API
12
+ and MCP tools from its methods. You build it in a shell, like any project,
13
+ and publish it with the `teable` CLI.
14
+
15
+ ## When to use it
16
+
17
+ - The user wants software with its own data and rules: records that move
18
+ through states, checks that refuse bad input, work that runs later or on a
19
+ schedule, calls to other services, pages, an API.
20
+ - The working directory, or one the user names, holds an app: `teable.json`
21
+ at its root, `@teable/app` in `package.json`, an `AGENTS.md`.
22
+ - Not for reading or editing a classic Teable base (tables, fields, views,
23
+ records): that is the `teable` CLI's base commands, not an app.
24
+
25
+ ## Start
26
+
27
+ ```sh
28
+ teable app init --name "<app name>" # a new app: creates it on Teable, checks out its repository
29
+ teable app clone --app-id <appId> # an app that exists: checks out its repository
30
+ teable app pull # in a checkout you have: bring it up to date first
31
+ ```
32
+
33
+ Without the `teable` CLI (Claude Code on someone's own machine, say),
34
+ `npx @teable/create-app <dir> --app-id <appId>` (or `bunx`) writes the same
35
+ blank app; leave out `--app-id` to try one locally, and `git init` it. Then
36
+ `bun install`, and read the app's `AGENTS.md` before changing anything: it is
37
+ the app's own instructions, current for the SDK the app uses.
38
+
39
+ ## The loop
40
+
41
+ 1. Edit: schema, methods, migrations, pages, tests.
42
+ 2. `bun run check`: typecheck, tests (methods in workerd against a real
43
+ database, pages in jsdom), migration checks.
44
+ 3. `bun run build`: `dist/server.js`, which publishing uploads.
45
+ 4. `teable app push -m "<what changed>"`: commit and save the source to
46
+ Teable as a new version.
47
+ 5. `teable app publish`: Teable runs the new version's migrations on a copy
48
+ of the live data, then on the live data, and makes it live only if both
49
+ work. Publish as soon as the checks pass; do not wait to be asked. It
50
+ takes the `creator` or `owner` role in the app's space. Then tell the user
51
+ what changed.
52
+
53
+ `teable app versions` lists published versions, with who published each and
54
+ from which commit. `teable app rollback --version <n>` deploys an earlier
55
+ version's code again, as the next version; it is refused past a migration
56
+ (roll forward instead), and it leaves the repository as it is, so fix or
57
+ revert the code before the next publish. There is no local server: tests are
58
+ the loop, publishing shows the running app.
59
+
60
+ ## The rules
61
+
62
+ Each is explained, with why, in the app's `AGENTS.md` ("The rules, and why"):
63
+
64
+ 1. Data is touched only through the app's methods.
65
+ 2. Read and write handlers are synchronous; anything that waits (`fetch`, AI,
66
+ email, payments) is a task, retried until it succeeds.
67
+ 3. Rules SQLite can enforce live in SQLite: NOT NULL, CHECK, UNIQUE, foreign
68
+ keys, triggers. Methods hold the rest.
69
+ 4. Migrations are append-only: once published, never edit or delete one; add
70
+ a new one with `bun run db:generate`.
71
+ 5. Capabilities are declared: the app gets no network (`http`) and no files
72
+ (`files`) unless `createApp` lists them.
73
+
74
+ ## Where to look in the app's AGENTS.md
75
+
76
+ | To | Section |
77
+ | ----------------------------------------------------- | ------------------------ |
78
+ | Find your way around the repository | Layout |
79
+ | Know the rules and why they hold | The rules, and why |
80
+ | Run checks, build, push, publish, roll back | Commands |
81
+ | Add a table and its migration | How to: Add a table |
82
+ | Add a read or a write, its access and its errors | How to: Add a read... |
83
+ | Add a page | How to: Add a page |
84
+ | Run work later, on a schedule, or against a service | How to: Add a task... |
85
+ | Store files, call other services | How to: Use a capability |
86
+ | Write tests | How to: Test |
87
+ | Understand an error from a check, a test or a publish | When something fails |
88
+ | Know what publishing does | Publishing |