@teable/app 5.0.1 → 6.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/dist/build/cli.js CHANGED
@@ -1,10 +1,12 @@
1
1
  #!/usr/bin/env bun
2
2
  import {
3
- buildServer
4
- } from "../chunks/5QIBCQL5.js";
3
+ buildServer,
4
+ buildWorker
5
+ } from "../chunks/TXLTJKEX.js";
6
+ import "../chunks/VMIIUPHE.js";
5
7
 
6
8
  // src/build/cli.ts
7
- import { mkdirSync, writeFileSync } from "node:fs";
9
+ import { mkdirSync, rmSync, writeFileSync } from "node:fs";
8
10
  import { join } from "node:path";
9
11
  var [command] = process.argv.slice(2);
10
12
  var root = process.cwd();
@@ -13,6 +15,13 @@ if (command === "build") {
13
15
  mkdirSync(join(root, "dist"), { recursive: true });
14
16
  writeFileSync(join(root, "dist/server.js"), bundle.code);
15
17
  console.log(`dist/server.js ${(bundle.bytes / 1024).toFixed(0)} KiB`);
18
+ const worker = await buildWorker({ root });
19
+ if (worker === null) {
20
+ rmSync(join(root, "dist/worker.js"), { force: true });
21
+ } else {
22
+ writeFileSync(join(root, "dist/worker.js"), worker.code);
23
+ console.log(`dist/worker.js ${(worker.bytes / 1024).toFixed(0)} KiB`);
24
+ }
16
25
  } else {
17
26
  console.error("usage: teable-app build");
18
27
  process.exit(1);
@@ -1,3 +1,4 @@
1
+ import type { ClientRequest, IncomingMessage, ServerResponse } from "node:http";
1
2
  export interface ServerBundle {
2
3
  /** One ES module; imports only `cloudflare:*`. */
3
4
  code: string;
@@ -17,6 +18,16 @@ export declare function buildServer(options: {
17
18
  /** Build-time constants, as in esbuild's `define`. */
18
19
  define?: Record<string, string>;
19
20
  }): Promise<ServerBundle>;
21
+ /**
22
+ * Bundle the app's own Worker (`src/worker/index.ts`) into the one ES module
23
+ * the platform uploads with its pages; null when the app has none, and the
24
+ * platform's Worker serves its pages.
25
+ */
26
+ export declare function buildWorker(options: {
27
+ root: string;
28
+ entry?: string;
29
+ minify?: boolean;
30
+ }): Promise<ServerBundle | null>;
20
31
  /**
21
32
  * Vite / Vitest plugin: import `.sql` files as text, as the server build does.
22
33
  * drizzle-kit's durable-sqlite migrations import their SQL files directly.
@@ -29,3 +40,97 @@ export declare function sqlAsText(): {
29
40
  map: null;
30
41
  } | undefined;
31
42
  };
43
+ /**
44
+ * `teable()`, the Vite plugin that stands in for the runtime while an app
45
+ * is developed (ADR 0014, 7.), on Vite's own host, as `@teable/app/testing`
46
+ * stands in for the app's host in tests.
47
+ *
48
+ * - Vite serves the pages. A navigation by someone the pages' access keeps
49
+ * out is sent to sign in first, as on the platform.
50
+ * - `/.teable/` signs in: the developer picks who to be (each space role, a
51
+ * non-member, signed out), a development session only this plugin trusts.
52
+ * - `${APPS_PATH}/<appId>/` is the app's API, answered by the stand-in in
53
+ * `../dev/host.ts`, which runs the app's server code in workerd on a local
54
+ * database (`.teable/`), and runs it again after every change to it.
55
+ * - The app's own Worker (`src/worker/index.ts`) runs in workerd with the
56
+ * props it gets on the platform, for what no page file answers and the
57
+ * paths `public/_routes.json` includes.
58
+ *
59
+ * With `remote`, the API is a runtime's instead (this repository's `bun run
60
+ * dev` points it at the local runtime): calls carry the token given, or
61
+ * none once the developer signs out, and there is no Worker.
62
+ */
63
+ export interface TeableOptions {
64
+ /** The app's id; `teable.json`'s by default. */
65
+ appId?: string;
66
+ /** A runtime to call instead of running the app here, and the token to call it with. */
67
+ remote?: {
68
+ url: string;
69
+ token?: string;
70
+ };
71
+ }
72
+ type Next = (error?: unknown) => void;
73
+ type Middleware = (req: IncomingMessage, res: ServerResponse, next: Next) => void;
74
+ /** What the plugin uses of Vite's dev server. */
75
+ interface DevServer {
76
+ config: {
77
+ root: string;
78
+ logger: {
79
+ info(message: string): void;
80
+ error(message: string): void;
81
+ };
82
+ };
83
+ middlewares: {
84
+ use(middleware: Middleware): void;
85
+ };
86
+ httpServer: {
87
+ once(event: "listening", listener: () => void): void;
88
+ address(): unknown;
89
+ } | null;
90
+ watcher: {
91
+ on(event: "change" | "add" | "unlink", listener: (file: string) => void): void;
92
+ };
93
+ }
94
+ /** What the plugin uses of the proxy Vite forwards a path with. */
95
+ interface Proxy {
96
+ on(event: "proxyReq" | "proxyReqWs", listener: (out: ClientRequest, req: IncomingMessage) => void): void;
97
+ }
98
+ /**
99
+ * The runtime's stand-in: Vite's pages, the app's API and its Worker, and
100
+ * signing in as whoever the developer picks.
101
+ */
102
+ export declare function teable(options?: TeableOptions): {
103
+ name: string;
104
+ config(config: {
105
+ root?: string;
106
+ }, env: {
107
+ command: string;
108
+ }): Promise<{
109
+ define: {
110
+ "import.meta.env.VITE_TEABLE_APP_ID": string;
111
+ };
112
+ server?: undefined;
113
+ } | {
114
+ define: {
115
+ "import.meta.env.VITE_TEABLE_APP_ID": string;
116
+ };
117
+ server: {
118
+ proxy: {
119
+ "/api/v4/apps": {
120
+ target: string;
121
+ ws: boolean;
122
+ changeOrigin: boolean;
123
+ configure: ((proxy: Proxy) => void) | undefined;
124
+ };
125
+ "/.teable"?: {
126
+ target: string;
127
+ ws: boolean;
128
+ changeOrigin: boolean;
129
+ configure: ((proxy: Proxy) => void) | undefined;
130
+ } | undefined;
131
+ };
132
+ };
133
+ }>;
134
+ configureServer(server: DevServer): (() => void) | undefined;
135
+ };
136
+ export {};
@@ -1,8 +1,13 @@
1
1
  import {
2
2
  buildServer,
3
- sqlAsText
4
- } from "../chunks/5QIBCQL5.js";
3
+ buildWorker,
4
+ sqlAsText,
5
+ teable
6
+ } from "../chunks/TXLTJKEX.js";
7
+ import "../chunks/VMIIUPHE.js";
5
8
  export {
6
9
  buildServer,
7
- sqlAsText
10
+ buildWorker,
11
+ sqlAsText,
12
+ teable
8
13
  };
@@ -1,11 +1,12 @@
1
1
  import {
2
2
  describeTables
3
- } from "./LV3ZHKKL.js";
3
+ } from "./N7LBNIRZ.js";
4
4
  import {
5
5
  CAPABILITIES,
6
6
  PROTOCOL_VERSION,
7
- admit
8
- } from "./JQWQD45Z.js";
7
+ admit,
8
+ isPageAccess
9
+ } from "./VMIIUPHE.js";
9
10
 
10
11
  // src/server/errors.ts
11
12
  import { z } from "zod";
@@ -834,7 +835,10 @@ function createApp(options) {
834
835
  * Object class. It keeps the method map's type, which pages read.
835
836
  */
836
837
  define(methods) {
837
- return defineApp(options.schema, options.migrations, methods, options.capabilities ?? []);
838
+ return defineApp(options.schema, options.migrations, methods, {
839
+ capabilities: options.capabilities ?? [],
840
+ pages: { access: options.pages?.access ?? "viewer" }
841
+ });
838
842
  }
839
843
  };
840
844
  }
@@ -844,7 +848,12 @@ function methodName(method) {
844
848
  if (name === void 0) throw new Error("This method is not registered in define()");
845
849
  return name;
846
850
  }
847
- function defineApp(schema, migrations, methods, capabilities) {
851
+ function defineApp(schema, migrations, methods, { capabilities, pages }) {
852
+ if (!isPageAccess(pages.access)) {
853
+ throw new Error(
854
+ `Pages access "${pages.access}" must be a space role (owner, creator, editor, commenter, viewer) or "public"`
855
+ );
856
+ }
848
857
  for (const capability of capabilities) {
849
858
  if (!CAPABILITIES.includes(capability)) {
850
859
  throw new Error(`Unknown capability "${capability}" (known: ${CAPABILITIES.join(", ")})`);
@@ -868,7 +877,8 @@ function defineApp(schema, migrations, methods, capabilities) {
868
877
  protocol: PROTOCOL_VERSION,
869
878
  methods: Object.entries(methods).map(([name, m]) => describeMethod(name, m)),
870
879
  tables,
871
- capabilities: [...new Set(capabilities)]
880
+ capabilities: [...new Set(capabilities)],
881
+ pages
872
882
  };
873
883
  const byName = new Map(Object.entries(methods));
874
884
  return class App extends DurableObject {
@@ -2,8 +2,9 @@ import {
2
2
  APPS_PATH,
3
3
  ERROR_STATUS,
4
4
  FILE_NAME_HEADER,
5
+ SESSION_PATH,
5
6
  fileKeyPath
6
- } from "./JQWQD45Z.js";
7
+ } from "./VMIIUPHE.js";
7
8
 
8
9
  // src/client.ts
9
10
  var MethodError = class extends Error {
@@ -32,13 +33,14 @@ function createClient(options) {
32
33
  const dataKey = ["teable-app", options.appId];
33
34
  async function request(path, init = {
34
35
  method: "GET"
35
- }) {
36
+ }, prefix = `${APPS_PATH}/${options.appId}`) {
36
37
  const token = options.token?.();
37
- const response = await doFetch(`${base()}${APPS_PATH}/${options.appId}${path}`, {
38
+ const response = await doFetch(`${base()}${prefix}${path}`, {
38
39
  method: init.method,
39
40
  headers: { ...token ? { Authorization: `Bearer ${token}` } : {}, ...init.headers },
40
41
  body: init.body ?? null
41
42
  });
43
+ if (response.status === 204) return null;
42
44
  const body = await response.json().catch(() => null);
43
45
  if (!response.ok) {
44
46
  const error = body?.error ?? {
@@ -107,7 +109,15 @@ function createClient(options) {
107
109
  share: async (file, shareOptions) => await request(
108
110
  `/files/${fileKeyPath(file.key)}/public`,
109
111
  json(shareOptions ?? {})
110
- )
112
+ ),
113
+ session: async () => await request("/session", { method: "GET" }, SESSION_PATH),
114
+ signIn: (returnTo) => {
115
+ const back = returnTo ?? (page ? `${page.pathname}${page.search}${page.hash}` : "/");
116
+ page?.assign(`${base()}${SESSION_PATH}/sign-in?return=${encodeURIComponent(back)}`);
117
+ },
118
+ signOut: async () => {
119
+ await request("/sign-out", { method: "POST" }, SESSION_PATH);
120
+ }
111
121
  };
112
122
  }
113
123
 
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  DEFAULT_CURRENCY,
3
3
  currencyDigits
4
- } from "./JQWQD45Z.js";
4
+ } from "./VMIIUPHE.js";
5
5
 
6
6
  // src/schema.ts
7
7
  import { getTableColumns, getTableName, is } from "drizzle-orm";
@@ -0,0 +1,353 @@
1
+ import {
2
+ APPS_PATH,
3
+ APP_COMPATIBILITY_DATE,
4
+ ASSETS_HEADER,
5
+ DEV_PATHS,
6
+ SESSION_PATH,
7
+ checkAccess
8
+ } from "./VMIIUPHE.js";
9
+
10
+ // src/build/index.ts
11
+ import { existsSync, readFileSync } from "node:fs";
12
+ import { createServer } from "node:net";
13
+ import { join, relative, sep } from "node:path";
14
+ import { fileURLToPath } from "node:url";
15
+ import { build } from "esbuild";
16
+ var SERVER_ENTRY = "src/server/index.ts";
17
+ var WORKER_ENTRY = "src/worker/index.ts";
18
+ var WORKERD = {
19
+ bundle: true,
20
+ format: "esm",
21
+ platform: "neutral",
22
+ target: "es2024",
23
+ conditions: ["workerd", "worker", "browser"],
24
+ mainFields: ["module", "main"],
25
+ external: ["cloudflare:*"],
26
+ loader: { ".sql": "text" },
27
+ legalComments: "none",
28
+ write: false,
29
+ logLevel: "silent"
30
+ };
31
+ async function buildServer(options) {
32
+ const entry = options.entry ?? SERVER_ENTRY;
33
+ const result = await build({
34
+ ...WORKERD,
35
+ absWorkingDir: options.root,
36
+ stdin: {
37
+ contents: `export { App } from ${JSON.stringify(`./${entry}`)};`,
38
+ resolveDir: options.root,
39
+ sourcefile: "teable-app-entry.js",
40
+ loader: "js"
41
+ },
42
+ define: options.define ?? {},
43
+ minify: options.minify ?? true
44
+ }).catch((error) => {
45
+ const reasons = error.errors?.map((e) => e.text) ?? [String(error)];
46
+ if (reasons.some((r) => r.includes("No matching export") && r.includes('"App"'))) {
47
+ throw new Error(`${entry} must export the class from define() as "App"`);
48
+ }
49
+ throw new Error(`Could not build ${entry}: ${reasons.join("; ")}`);
50
+ });
51
+ const [output] = result.outputFiles ?? [];
52
+ if (output === void 0) throw new Error("esbuild produced no output");
53
+ return { code: output.text, bytes: output.contents.byteLength };
54
+ }
55
+ async function buildWorker(options) {
56
+ const entry = options.entry ?? WORKER_ENTRY;
57
+ if (!existsSync(join(options.root, entry))) return null;
58
+ const result = await build({
59
+ ...WORKERD,
60
+ absWorkingDir: options.root,
61
+ entryPoints: [entry],
62
+ minify: options.minify ?? true
63
+ }).catch((error) => {
64
+ const reasons = error.errors?.map((e) => e.text) ?? [String(error)];
65
+ throw new Error(`Could not build ${entry}: ${reasons.join("; ")}`);
66
+ });
67
+ const [output] = result.outputFiles ?? [];
68
+ if (output === void 0) throw new Error("esbuild produced no output");
69
+ return { code: output.text, bytes: output.contents.byteLength };
70
+ }
71
+ function sqlAsText() {
72
+ return {
73
+ name: "teable:sql-as-text",
74
+ enforce: "pre",
75
+ transform(code, id) {
76
+ if (!id.endsWith(".sql")) return void 0;
77
+ return { code: `export default ${JSON.stringify(code)};`, map: null };
78
+ }
79
+ };
80
+ }
81
+ var DEV_SESSION = "teable_dev_session";
82
+ function appIdOf(root) {
83
+ try {
84
+ const file = JSON.parse(readFileSync(join(root, "teable.json"), "utf8"));
85
+ return file.appId || "app";
86
+ } catch {
87
+ return "app";
88
+ }
89
+ }
90
+ function freePort() {
91
+ return new Promise((resolve, reject) => {
92
+ const server = createServer();
93
+ server.once("error", reject);
94
+ server.listen(0, "127.0.0.1", () => {
95
+ const { port } = server.address();
96
+ server.close(() => resolve(port));
97
+ });
98
+ });
99
+ }
100
+ var isNavigation = (req) => req.headers["sec-fetch-mode"] === "navigate" && (req.method === "GET" || req.method === "HEAD");
101
+ var isRuntimePath = (path) => [SESSION_PATH, APPS_PATH].some((prefix) => path === prefix || path.startsWith(`${prefix}/`));
102
+ var signedOut = (req) => new RegExp(`(?:^|;\\s*)${DEV_SESSION}=anonymous(?:;|$)`).test(req.headers.cookie ?? "");
103
+ async function bodyOf(req) {
104
+ if (req.method === "GET" || req.method === "HEAD") return void 0;
105
+ const chunks = [];
106
+ for await (const chunk of req) chunks.push(chunk);
107
+ return new Uint8Array(Buffer.concat(chunks));
108
+ }
109
+ async function send(res, response) {
110
+ const headers = {};
111
+ response.headers.forEach((value, name) => {
112
+ if (!["set-cookie", "content-encoding", "content-length"].includes(name)) headers[name] = value;
113
+ });
114
+ const cookies = response.headers.getSetCookie();
115
+ if (cookies.length > 0) headers["set-cookie"] = cookies;
116
+ res.writeHead(response.status, headers);
117
+ res.end(Buffer.from(await response.arrayBuffer()));
118
+ }
119
+ async function forward(req, res, target) {
120
+ const headers = new Headers();
121
+ for (const [name, value] of Object.entries(req.headers)) {
122
+ if (value === void 0 || ["host", "connection", "content-length"].includes(name)) continue;
123
+ headers.set(name, Array.isArray(value) ? value.join(", ") : value);
124
+ }
125
+ const body = await bodyOf(req);
126
+ await send(res, await fetch(target, { method: req.method, headers, body, redirect: "manual" }));
127
+ }
128
+ function workerFirst(root) {
129
+ let routes = {};
130
+ try {
131
+ routes = JSON.parse(readFileSync(join(root, "public/_routes.json"), "utf8"));
132
+ } catch {
133
+ }
134
+ const glob = (pattern) => new RegExp(
135
+ `^${pattern.split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*")}$`
136
+ );
137
+ const include = (routes.include ?? []).map(glob);
138
+ const exclude = (routes.exclude ?? []).map(glob);
139
+ return (path) => include.some((re) => re.test(path)) && !exclude.some((re) => re.test(path));
140
+ }
141
+ function html(res, body, status = 200) {
142
+ res.writeHead(status, { "Content-Type": "text/html; charset=utf-8" });
143
+ res.end(
144
+ `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Teable app (development)</title><style>body{font:16px/1.5 system-ui,sans-serif;max-width:30rem;margin:12vh auto;padding:0 1.5rem}button{display:block;width:100%;margin:.4rem 0;padding:.6rem .8rem;font:inherit;text-align:left;border:1px solid #d4d4d4;border-radius:.5rem;background:#fff;cursor:pointer}</style></head><body>${body}</body></html>`
145
+ );
146
+ }
147
+ function teable(options = {}) {
148
+ let appId = options.appId ?? "app";
149
+ let workerd = "";
150
+ const serving = (command) => command === "serve" && !process.env.VITEST;
151
+ return {
152
+ name: "teable",
153
+ async config(config, env) {
154
+ appId = options.appId ?? appIdOf(config.root ?? process.cwd());
155
+ const define = { "import.meta.env.VITE_TEABLE_APP_ID": JSON.stringify(appId) };
156
+ if (!serving(env.command)) return { define };
157
+ const { remote } = options;
158
+ let target;
159
+ let configure;
160
+ if (remote) {
161
+ target = remote.url;
162
+ configure = (proxy2) => {
163
+ const sign = (out, req) => {
164
+ out.removeHeader("cookie");
165
+ if (remote.token && !signedOut(req))
166
+ out.setHeader("Authorization", `Bearer ${remote.token}`);
167
+ };
168
+ proxy2.on("proxyReq", sign);
169
+ proxy2.on("proxyReqWs", sign);
170
+ };
171
+ } else {
172
+ workerd = `http://127.0.0.1:${await freePort()}`;
173
+ target = workerd;
174
+ }
175
+ const proxy = { target, ws: true, changeOrigin: remote !== void 0, configure };
176
+ return {
177
+ define,
178
+ server: { proxy: { [APPS_PATH]: proxy, ...remote ? {} : { [SESSION_PATH]: proxy } } }
179
+ };
180
+ },
181
+ configureServer(server) {
182
+ if (!workerd && !options.remote) return;
183
+ if (options.remote) {
184
+ server.middlewares.use(remoteMiddleware(options.remote, appId));
185
+ return;
186
+ }
187
+ return localRuntime(server, appId, workerd);
188
+ }
189
+ };
190
+ }
191
+ function localRuntime(server, appId, workerd) {
192
+ const root = server.config.root;
193
+ const log = server.config.logger;
194
+ let hasWorker = false;
195
+ let started;
196
+ const deploy = async () => {
197
+ const [code, worker] = await Promise.all([
198
+ buildServer({ root, minify: false }),
199
+ buildWorker({ root, minify: false })
200
+ ]);
201
+ hasWorker = worker !== null;
202
+ const deployed = await fetch(`${workerd}${DEV_PATHS.deploy}`, {
203
+ method: "POST",
204
+ body: JSON.stringify({ server: code.code, worker: worker?.code ?? null })
205
+ });
206
+ if (!deployed.ok) {
207
+ const { error } = await deployed.json();
208
+ throw new Error(error.message);
209
+ }
210
+ log.info(`teable: ${appId} runs here${hasWorker ? ", with its Worker" : ""}`);
211
+ };
212
+ const start = async () => {
213
+ const address = server.httpServer?.address();
214
+ const { Miniflare, convertV4MiniflareOptions } = await import("miniflare");
215
+ const host = await build({
216
+ entryPoints: [fileURLToPath(import.meta.resolve("@teable/app/dev-host"))],
217
+ bundle: true,
218
+ format: "esm",
219
+ platform: "neutral",
220
+ target: "es2024",
221
+ external: ["cloudflare:*"],
222
+ write: false,
223
+ logLevel: "silent"
224
+ });
225
+ const { port } = new URL(workerd);
226
+ const mf = new Miniflare(
227
+ convertV4MiniflareOptions({
228
+ host: "127.0.0.1",
229
+ port: Number(port),
230
+ modules: true,
231
+ script: host.outputFiles[0]?.text ?? "",
232
+ compatibilityDate: APP_COMPATIBILITY_DATE,
233
+ durableObjects: { HOST: { className: "DevHost", useSQLite: true } },
234
+ workerLoaders: { LOADER: {} },
235
+ r2Buckets: ["FILES"],
236
+ bindings: { APP_ID: appId, PAGES: `http://localhost:${address?.port ?? 5173}` },
237
+ resourcePersistencePath: join(root, ".teable")
238
+ })
239
+ );
240
+ await mf.ready;
241
+ await deploy().catch((error) => log.error(`teable: not started: ${String(error)}`));
242
+ };
243
+ server.httpServer?.once("listening", () => {
244
+ started = start().catch((error) => {
245
+ log.error(
246
+ `teable: not started: ${error instanceof Error ? error.stack ?? error.message : String(error)}`
247
+ );
248
+ });
249
+ });
250
+ const redeploy = (file) => {
251
+ const path = relative(root, file).split(sep).join("/");
252
+ if (!/^(src\/(server|worker)|drizzle)\//.test(path)) return;
253
+ void started?.then(deploy).catch((error) => log.error(`teable: not started: ${String(error)}`));
254
+ };
255
+ for (const event of ["change", "add", "unlink"]) server.watcher.on(event, redeploy);
256
+ const isWorkerFirst = workerFirst(root);
257
+ server.middlewares.use((req, res, next) => {
258
+ void (async () => {
259
+ const url = req.url ?? "/";
260
+ const path = url.split("?")[0] ?? "/";
261
+ if (req.headers[ASSETS_HEADER.toLowerCase()]) return next();
262
+ await started;
263
+ if (isRuntimePath(path)) return next();
264
+ if (isNavigation(req)) {
265
+ const gate = await fetch(`${workerd}${DEV_PATHS.gate}?path=${encodeURIComponent(url)}`, {
266
+ headers: { Cookie: req.headers.cookie ?? "" },
267
+ redirect: "manual"
268
+ });
269
+ if (gate.status !== 204) return send(res, gate);
270
+ }
271
+ if (hasWorker && isWorkerFirst(path)) {
272
+ return forward(req, res, `${workerd}${DEV_PATHS.worker}${url}`);
273
+ }
274
+ next();
275
+ })().catch(next);
276
+ });
277
+ return () => server.middlewares.use((req, res, next) => {
278
+ const original = req.originalUrl;
279
+ if (!hasWorker || req.headers[ASSETS_HEADER.toLowerCase()] || isNavigation(req)) {
280
+ return next();
281
+ }
282
+ forward(req, res, `${workerd}${DEV_PATHS.worker}${original ?? req.url ?? "/"}`).catch(next);
283
+ });
284
+ }
285
+ function remoteMiddleware(remote, appId) {
286
+ const runtime = remote.url.replace(/\/$/, "");
287
+ const manifest = async (req) => {
288
+ const token = signedOut(req) ? void 0 : remote.token;
289
+ const response = await fetch(`${runtime}${APPS_PATH}/${appId}/manifest`, {
290
+ headers: token ? { Authorization: `Bearer ${token}` } : {}
291
+ });
292
+ return response.ok ? await response.json() : null;
293
+ };
294
+ const cookie = (who) => `${DEV_SESSION}=${who}; Path=/; HttpOnly; SameSite=Lax`;
295
+ const onHost = (path) => path?.startsWith("/") && !path.startsWith("//") ? path : "/";
296
+ return (req, res, next) => {
297
+ void (async () => {
298
+ const url = new URL(req.url ?? "/", "http://localhost");
299
+ switch (`${req.method} ${url.pathname}`) {
300
+ case `GET ${SESSION_PATH}/sign-in`: {
301
+ if (!signedOut(req) && !url.searchParams.has("choose")) {
302
+ res.writeHead(302, { Location: onHost(url.searchParams.get("return")) });
303
+ return res.end();
304
+ }
305
+ const back = onHost(url.searchParams.get("return")).replace(/"/g, "&quot;");
306
+ return html(
307
+ res,
308
+ `<h1>Sign in to the app</h1><p>Development, against ${runtime}: be the person the token names, or nobody.</p><form method="post"><input type="hidden" name="return" value="${back}"><button name="who" value="token">The token's person</button><button name="who" value="anonymous">Signed out</button></form>`
309
+ );
310
+ }
311
+ case `POST ${SESSION_PATH}/sign-in`: {
312
+ const form = new URLSearchParams(Buffer.from(await bodyOf(req) ?? []).toString());
313
+ const who = form.get("who") === "token" ? "token" : "anonymous";
314
+ res.writeHead(303, { Location: onHost(form.get("return")), "Set-Cookie": cookie(who) });
315
+ return res.end();
316
+ }
317
+ case `GET ${SESSION_PATH}/session`: {
318
+ const caller = (await manifest(req))?.caller ?? { kind: "anonymous", via: "web" };
319
+ res.writeHead(200, { "Content-Type": "application/json" });
320
+ return res.end(JSON.stringify({ caller, expiresAt: null }));
321
+ }
322
+ case `POST ${SESSION_PATH}/sign-out`:
323
+ res.writeHead(204, { "Set-Cookie": cookie("anonymous") });
324
+ return res.end();
325
+ }
326
+ if (isNavigation(req) && !isRuntimePath(url.pathname)) {
327
+ const described = await manifest(req);
328
+ const caller = described?.caller ?? { kind: "anonymous", via: "web" };
329
+ const denied = checkAccess(caller, described?.pages?.access ?? "viewer");
330
+ const signIn = `${SESSION_PATH}/sign-in?return=${encodeURIComponent(req.url ?? "/")}`;
331
+ if (denied === "UNAUTHENTICATED") {
332
+ res.writeHead(302, { Location: signIn });
333
+ return res.end();
334
+ }
335
+ if (denied !== null) {
336
+ return html(
337
+ res,
338
+ `<h1>You cannot open this app</h1><p><a href="${signIn}&choose">Sign in as someone else</a></p>`,
339
+ 403
340
+ );
341
+ }
342
+ }
343
+ next();
344
+ })().catch(next);
345
+ };
346
+ }
347
+
348
+ export {
349
+ buildServer,
350
+ buildWorker,
351
+ sqlAsText,
352
+ teable
353
+ };
@@ -1,5 +1,5 @@
1
1
  // src/protocol.ts
2
- var PROTOCOL_VERSION = 5;
2
+ var PROTOCOL_VERSION = 6;
3
3
  var APP_COMPATIBILITY_DATE = "2026-12-01";
4
4
  var SPACE_ROLES = ["owner", "creator", "editor", "commenter", "viewer"];
5
5
  var EVERY_CAPABILITY = { files: true, http: true };
@@ -59,6 +59,16 @@ var ERROR_STATUS = {
59
59
  RATE_LIMITED: 429,
60
60
  INTERNAL: 500
61
61
  };
62
+ function isPageAccess(access) {
63
+ return access === "public" || SPACE_ROLES.includes(access);
64
+ }
65
+ var DEV_PATHS = {
66
+ deploy: "/__teable/deploy",
67
+ gate: "/__teable/gate",
68
+ worker: "/__teable/worker"
69
+ };
70
+ var ASSETS_HEADER = "X-Teable-Assets";
71
+ var SESSION_PATH = "/.teable";
62
72
  var APPS_PATH = "/api/v4/apps";
63
73
  var FILE_NAME_HEADER = "X-File-Name";
64
74
  function fileKeyPath(key) {
@@ -66,6 +76,7 @@ function fileKeyPath(key) {
66
76
  return `${key.slice(0, slash)}/${encodeURIComponent(key.slice(slash + 1))}`;
67
77
  }
68
78
  var DEPLOY_HEADERS = { commit: "X-Teable-Commit", message: "X-Teable-Message" };
79
+ var DEPLOY_PARTS = { server: "server", worker: "worker", pages: "pages" };
69
80
  function checkAccess(caller, access) {
70
81
  if (caller.kind === "system") return null;
71
82
  if (access === "internal") return "FORBIDDEN";
@@ -104,10 +115,15 @@ export {
104
115
  DEFAULT_CURRENCY,
105
116
  currencyDigits,
106
117
  ERROR_STATUS,
118
+ isPageAccess,
119
+ DEV_PATHS,
120
+ ASSETS_HEADER,
121
+ SESSION_PATH,
107
122
  APPS_PATH,
108
123
  FILE_NAME_HEADER,
109
124
  fileKeyPath,
110
125
  DEPLOY_HEADERS,
126
+ DEPLOY_PARTS,
111
127
  checkAccess,
112
128
  admit,
113
129
  isMember,