@teable/app 0.0.0-stage → 5.0.1

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.
@@ -0,0 +1,52 @@
1
+ import type { Caller, Change } from "../protocol.js";
2
+ /**
3
+ * The changefeed and history of an app's database (ADR 0004).
4
+ *
5
+ * Owns `_teable_context` (the invocation a write is running as),
6
+ * `_teable_invocations` (which method call, by whom, when) and
7
+ * `_teable_changes` (every row change, written by triggers on the app's
8
+ * tables), and how long they are kept. One feed serves realtime updates,
9
+ * history and other apps' subscriptions.
10
+ */
11
+ /** Tables, triggers and indexes whose names start with this belong to the platform. */
12
+ export declare const RESERVED_PREFIX = "_teable_";
13
+ /**
14
+ * What a trigger reports when a row changes outside a write method: from a
15
+ * read, or from code a write left running after it returned (an `await`).
16
+ */
17
+ export declare const OUTSIDE_WRITE = "teable: rows change only inside write methods";
18
+ /** `name` as an SQL identifier. */
19
+ export declare function ident(name: string): string;
20
+ /** Remove every changefeed trigger, so migrations can drop and rebuild columns freely. */
21
+ export declare function dropTriggers(sql: SqlStorage): void;
22
+ /** Make the changefeed triggers match the tables that exist right now. */
23
+ export declare function syncTriggers(sql: SqlStorage): void;
24
+ /** Record a write method call and attribute the row changes that follow to it. */
25
+ export declare function beginInvocation(sql: SqlStorage, method: string, caller: Caller, at: number): number;
26
+ export declare function endInvocation(sql: SqlStorage): void;
27
+ /**
28
+ * The sequence number of the latest change ever recorded. Sequence numbers
29
+ * are never reused (AUTOINCREMENT), and SQLite keeps the highest one even
30
+ * after retention has emptied the table, so the cursor never goes back.
31
+ */
32
+ export declare function currentCursor(sql: SqlStorage): number;
33
+ /** Tables changed after `before`, for realtime fan-out. */
34
+ export declare function changedTablesSince(sql: SqlStorage, before: number): string[];
35
+ /**
36
+ * Changes after `since`, oldest first, or null when some of them have expired:
37
+ * the subscriber fell behind retention and has to read the data again.
38
+ */
39
+ export declare function readChanges(sql: SqlStorage, since: number, limit: number): Change[] | null;
40
+ /** How long history (invocations, changes, dead tasks) is kept. */
41
+ export declare const HISTORY_MS: number;
42
+ /**
43
+ * Drop expired history at the end of the write `invocation`: the oldest
44
+ * expired changes, at most PRUNE_BATCH more than the write made (so retention
45
+ * keeps up with bulk writes while each write pays for a bounded batch), then
46
+ * the expired invocations that have no changes left.
47
+ *
48
+ * Invocations are in time order and changes in invocation order, so the
49
+ * expired rows are the oldest. Retention reads them and the first row that is
50
+ * kept, never the rest: a write where nothing has expired reads one row.
51
+ */
52
+ export declare function pruneHistory(sql: SqlStorage, now: number, invocation: number): void;
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Five-field cron (minute hour day-of-month month day-of-week) evaluated in an
3
+ * IANA time zone. Fields take `*`, numbers, ranges `a-b`, steps `*\/n` and
4
+ * `a-b/n`, and lists `a,b`. Day of week is 0-6 from Sunday (7 is Sunday too).
5
+ * When both day fields are restricted, a day matches either, as in cron.
6
+ *
7
+ * When the clocks change, a schedule that fires every hour follows the clock: a
8
+ * time the clock skips does not happen, and a time it shows twice happens
9
+ * twice. Any other schedule fires once for each of its times, the way calendars
10
+ * do (RFC 5545): a time shown twice fires the first time, and a skipped time
11
+ * fires as if the clocks had not changed yet, which is the length of the skip
12
+ * later (02:30 fires at 03:30 when 02:00 jumps to 03:00).
13
+ */
14
+ interface Parsed {
15
+ minutes: number[];
16
+ hours: number[];
17
+ days: Set<number>;
18
+ months: Set<number>;
19
+ weekdays: Set<number>;
20
+ daysRestricted: boolean;
21
+ weekdaysRestricted: boolean;
22
+ }
23
+ export declare function parseCron(expression: string): Parsed;
24
+ /** The first time after `after` (epoch ms) that the expression fires in `timeZone`. */
25
+ export declare function nextFire(expression: string, timeZone: string, after: number): number;
26
+ export {};
@@ -0,0 +1,21 @@
1
+ import { z } from "zod";
2
+ import type { AppErrorShape, ErrorCode } from "../protocol.js";
3
+ /** An error reported to the caller on purpose, by the app or the SDK. Anything else is INTERNAL. */
4
+ export declare class AppError extends Error {
5
+ readonly code: ErrorCode;
6
+ readonly issues: AppErrorShape["issues"];
7
+ constructor(code: ErrorCode, message: string, issues?: AppErrorShape["issues"]);
8
+ }
9
+ /**
10
+ * The codes an app raises. The others belong to the platform: the host
11
+ * reports UNAUTHENTICATED, UNKNOWN_METHOD and RATE_LIMITED, SQLite
12
+ * CONSTRAINT, and anything unexpected is INTERNAL.
13
+ */
14
+ declare const FAIL_CODES: readonly ["BAD_INPUT", "FORBIDDEN", "NOT_FOUND", "CONFLICT"];
15
+ /** Stop the method and report `code` to the caller. Data written so far is rolled back. */
16
+ export declare function fail(code: (typeof FAIL_CODES)[number], message: string): never;
17
+ /** Convert anything thrown by a method into the error shape callers see. */
18
+ export declare function toErrorShape(error: unknown): AppErrorShape;
19
+ /** What failed validation, field by field, as callers see it. */
20
+ export declare function issuesOf(error: z.ZodError): NonNullable<AppErrorShape["issues"]>;
21
+ export {};
@@ -0,0 +1,36 @@
1
+ import type { AppManifest } from "../protocol.js";
2
+ /**
3
+ * Bringing an app's database to its code: the platform's tables, the app's
4
+ * migrations, and the changefeed and schedules derived from both.
5
+ *
6
+ * The platform's tables live next to the app's own, so data and the state of
7
+ * work in flight (tasks, changes not yet delivered) commit together. Their DDL
8
+ * is here; the modules that use them own their queries.
9
+ */
10
+ /** What `drizzle-kit generate` emits as `drizzle/migrations.js` for the durable-sqlite driver. */
11
+ export interface Migrations {
12
+ journal: {
13
+ entries: {
14
+ idx: number;
15
+ when: number;
16
+ tag: string;
17
+ breakpoints: boolean;
18
+ }[];
19
+ };
20
+ migrations: Record<string, string>;
21
+ }
22
+ /**
23
+ * The platform's tables, one entry per version, applied in order and recorded
24
+ * in `_teable_meta`. Append-only, like an app's migrations: never edit an
25
+ * entry that may have run anywhere; change the layout with a new entry.
26
+ */
27
+ export declare const PLATFORM_MIGRATIONS: readonly (readonly string[])[];
28
+ /** The layout of the platform's tables this version of the SDK reads and writes. */
29
+ export declare const PLATFORM_VERSION: number;
30
+ /**
31
+ * Bring the database to the app in one transaction: the platform's tables,
32
+ * the pending migrations, the check that the result is what the app's code
33
+ * declares, then the changefeed triggers and schedules derived from it. If
34
+ * anything fails nothing changes, and the error says what and how to fix it.
35
+ */
36
+ export declare function prepareDatabase(storage: DurableObjectStorage, migrations: Migrations, app: Pick<AppManifest, "tables" | "methods">): Promise<void>;
@@ -0,0 +1,16 @@
1
+ import type { MethodInfo } from "../protocol.js";
2
+ /**
3
+ * Tasks that run on a cron (ADR 0002). The definition lives on the task; the
4
+ * next fire time lives in `_teable_schedules`, so a restart neither skips nor
5
+ * repeats a run.
6
+ */
7
+ /** Make the stored schedules match the scheduled tasks among the app's methods. */
8
+ export declare function syncSchedules(sql: SqlStorage, methods: readonly MethodInfo[], now: number): void;
9
+ /**
10
+ * Enqueue every scheduled task that is due and move its schedule to the next
11
+ * fire time after `now`. Runs missed while the app slept fire once, not once
12
+ * per missed slot.
13
+ */
14
+ export declare function fireDueSchedules(sql: SqlStorage, now: number): void;
15
+ /** When the next scheduled task fires, or null. */
16
+ export declare function nextScheduleAt(sql: SqlStorage): number | null;
@@ -0,0 +1,51 @@
1
+ import type { TaskFailure } from "../protocol.js";
2
+ /**
3
+ * The task queue (ADR 0002): async work that runs outside transactions, at
4
+ * least once, retried with backoff until it succeeds or runs out of attempts.
5
+ *
6
+ * Owns `_teable_tasks` and the queue's policy: how long a claim lasts, how
7
+ * many tasks one wake runs, how long to wait before a retry, and when dead
8
+ * tasks go. Also `_teable_attempts`: the attempts started since the last
9
+ * report to the host, which meters them (ADR 0006).
10
+ */
11
+ /** Attempts a task gets unless it declares `maxAttempts`. */
12
+ export declare const DEFAULT_MAX_ATTEMPTS = 8;
13
+ /** How the queue runs a task it has claimed. */
14
+ interface TaskHandler {
15
+ maxAttempts: number;
16
+ run(input: unknown, attempt: number): Promise<void> | void;
17
+ }
18
+ /**
19
+ * Queue `method` to run at `runAt`. `input` is the JSON text the task will
20
+ * receive; `invocation` is the write that enqueued it (none for schedules).
21
+ */
22
+ export declare function enqueueTask(sql: SqlStorage, task: {
23
+ method: string;
24
+ input: string;
25
+ runAt: number;
26
+ invocation: number | null;
27
+ }, now: number): void;
28
+ /**
29
+ * Run the tasks due at `now`, oldest first, at most one batch. `handlerFor`
30
+ * says how to run each task; a task this version of the app no longer defines
31
+ * gets one attempt, which fails. Every attempt is counted for the host to
32
+ * meter (`takeAttempts`). Returns the runs that failed: the host logs them,
33
+ * and nothing else sees a task fail.
34
+ */
35
+ export declare function runDueTasks(storage: DurableObjectStorage, now: number, handlerFor: (method: string) => TaskHandler | undefined): Promise<TaskFailure[]>;
36
+ /**
37
+ * The attempts started since the last report, crashed ones included, which
38
+ * are forgotten as they are taken: each attempt is reported once. A host that
39
+ * fails before it meters a report loses it rather than billing it twice
40
+ * (ADR 0006).
41
+ */
42
+ export declare function takeAttempts(sql: SqlStorage): number;
43
+ /** When the earliest pending task is due (or its lease runs out), or null. */
44
+ export declare function nextTaskAt(sql: SqlStorage): number | null;
45
+ /**
46
+ * Dead tasks are history (ADR 0004), kept as long as changes, counted from
47
+ * when they died. A bounded batch of expired ones goes with every wake, where
48
+ * tasks die, and with every write, like the rest of the history.
49
+ */
50
+ export declare function pruneDeadTasks(sql: SqlStorage, now: number): void;
51
+ export {};
@@ -0,0 +1,38 @@
1
+ /**
2
+ * @teable/app/testing — drive an app from vitest running in workerd.
3
+ *
4
+ * const app = testApp(env.APP.getByName("test"));
5
+ * const order = await app.call(placeOrder, { skuId, qty: 2 });
6
+ * await app.runTasks();
7
+ */
8
+ import type { z } from "zod";
9
+ import { type AppFacet, type Caller, type Change, type InvokeResult, type Jsonify, type JsonValue } from "./protocol.js";
10
+ import { type AnyMethod, type InputSchema, type ReadMethod, type WriteMethod } from "./server/app.js";
11
+ /** Who calls unless a test says otherwise: an owner of the app's space. */
12
+ export declare const OWNER: Caller;
13
+ type Callable = ReadMethod<InputSchema, unknown> | WriteMethod<InputSchema, unknown>;
14
+ type Returned<M> = M extends {
15
+ handler(ctx: never): infer R;
16
+ } ? R : never;
17
+ export declare function testApp(stub: unknown, caller?: Caller): {
18
+ facet: AppFacet;
19
+ /** The same app, called by someone else. */
20
+ as: (other: Caller) => /*elided*/ any;
21
+ /** Call and get the raw result, including errors and effects. */
22
+ invoke: (method: AnyMethod | string, input?: JsonValue) => Promise<InvokeResult>;
23
+ /**
24
+ * Call and get the value as the app's callers get it: JSON in and out, so
25
+ * Dates arrive as ISO strings. A failure throws what a page's client
26
+ * throws: a MethodError with the HTTP status of its code.
27
+ */
28
+ call<M extends Callable>(method: M, input?: z.input<M["input"]>): Promise<Jsonify<Returned<M>>>;
29
+ /**
30
+ * Run every task due before `until` (default: a year from now), including
31
+ * tasks they enqueue. Returns how many attempts ran.
32
+ */
33
+ runTasks(until?: number): Promise<number>;
34
+ /** Changes after `since`; throws if some of them are no longer kept. */
35
+ changes(since?: number): Promise<Change[]>;
36
+ manifest: () => Promise<import("./protocol.js").AppManifest>;
37
+ };
38
+ export {};
@@ -0,0 +1,69 @@
1
+ import {
2
+ methodName
3
+ } from "./chunks/EVNB2DU2.js";
4
+ import "./chunks/LV3ZHKKL.js";
5
+ import {
6
+ MethodError
7
+ } from "./chunks/323GVFSV.js";
8
+ import {
9
+ ERROR_STATUS
10
+ } from "./chunks/JQWQD45Z.js";
11
+
12
+ // src/testing.ts
13
+ var OWNER = { kind: "user", userId: "test-owner", role: "owner", via: "api" };
14
+ var YEAR = 365 * 24 * 60 * 6e4;
15
+ function viaJson(value) {
16
+ return value === void 0 ? void 0 : JSON.parse(JSON.stringify(value));
17
+ }
18
+ function testApp(stub, caller = OWNER) {
19
+ const facet = stub;
20
+ return {
21
+ facet,
22
+ /** The same app, called by someone else. */
23
+ as: (other) => testApp(stub, other),
24
+ /** Call and get the raw result, including errors and effects. */
25
+ invoke: (method, input) => facet.invoke({
26
+ method: typeof method === "string" ? method : methodName(method),
27
+ input,
28
+ caller
29
+ }),
30
+ /**
31
+ * Call and get the value as the app's callers get it: JSON in and out, so
32
+ * Dates arrive as ISO strings. A failure throws what a page's client
33
+ * throws: a MethodError with the HTTP status of its code.
34
+ */
35
+ async call(method, input) {
36
+ const result = await facet.invoke({
37
+ method: methodName(method),
38
+ input: viaJson(input),
39
+ caller
40
+ });
41
+ if (!result.ok) throw new MethodError(result.error, ERROR_STATUS[result.error.code]);
42
+ return viaJson(result.value);
43
+ },
44
+ /**
45
+ * Run every task due before `until` (default: a year from now), including
46
+ * tasks they enqueue. Returns how many attempts ran.
47
+ */
48
+ async runTasks(until = Date.now() + YEAR) {
49
+ let total = 0;
50
+ for (let round = 0; round < 1e3; round++) {
51
+ const { attempts, failed } = await facet.wake(until);
52
+ if (attempts === 0 && failed.length === 0) return total;
53
+ total += attempts;
54
+ }
55
+ throw new Error("Tasks keep enqueueing tasks; stopped after 1000 rounds");
56
+ },
57
+ /** Changes after `since`; throws if some of them are no longer kept. */
58
+ async changes(since = 0) {
59
+ const changes = await facet.changes(since);
60
+ if (changes === null) throw new Error(`Changes after ${since} are no longer kept`);
61
+ return changes;
62
+ },
63
+ manifest: () => facet.manifest()
64
+ };
65
+ }
66
+ export {
67
+ OWNER,
68
+ testApp
69
+ };
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "@teable/app",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "5.0.1",
4
+ "description": "Write a Teable app as a Drizzle schema plus methods",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/teableio/teable-next.git",
9
+ "directory": "packages/app"
10
+ },
11
+ "type": "module",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "default": "./dist/index.js"
16
+ },
17
+ "./protocol": {
18
+ "types": "./dist/protocol.d.ts",
19
+ "default": "./dist/protocol.js"
20
+ },
21
+ "./schema": {
22
+ "types": "./dist/schema.d.ts",
23
+ "default": "./dist/schema.js"
24
+ },
25
+ "./client": {
26
+ "types": "./dist/client.d.ts",
27
+ "default": "./dist/client.js"
28
+ },
29
+ "./testing": {
30
+ "types": "./dist/testing.d.ts",
31
+ "default": "./dist/testing.js"
32
+ },
33
+ "./build": {
34
+ "types": "./dist/build/index.d.ts",
35
+ "default": "./dist/build/index.js"
36
+ }
37
+ },
38
+ "bin": {
39
+ "teable-app": "./dist/build/cli.js"
40
+ },
41
+ "files": [
42
+ "dist"
43
+ ],
44
+ "engines": {
45
+ "node": ">=18",
46
+ "bun": ">=1.2"
47
+ },
48
+ "publishConfig": {
49
+ "access": "public",
50
+ "provenance": true
51
+ },
52
+ "dependencies": {
53
+ "drizzle-orm": "0.45.4",
54
+ "esbuild": "0.28.2",
55
+ "zod": "4.6.7"
56
+ }
57
+ }