zitejs 0.10.0-start.21 → 0.10.0-start.22

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.
Files changed (112) hide show
  1. package/dist/cjs/auth/client.d.ts +2 -2
  2. package/dist/cjs/check/start/sourceRules.js +3 -0
  3. package/dist/cjs/cli.js +6 -0
  4. package/dist/cjs/dev/index.js +15 -0
  5. package/dist/cjs/dev/signin.d.ts +16 -0
  6. package/dist/cjs/dev/signin.js +76 -0
  7. package/dist/cjs/internal/appMode.d.ts +11 -0
  8. package/dist/cjs/internal/appMode.js +4 -1
  9. package/dist/cjs/internal/appToken.d.ts +17 -0
  10. package/dist/cjs/internal/appToken.js +26 -0
  11. package/dist/cjs/internal/platformFetch.d.ts +2 -0
  12. package/dist/cjs/internal/platformFetch.js +13 -0
  13. package/dist/cjs/internal/serviceUrls.d.ts +7 -0
  14. package/dist/cjs/internal/serviceUrls.js +16 -0
  15. package/dist/cjs/runtime/index.d.ts +1 -1
  16. package/dist/cjs/start/aiUsage.d.ts +23 -0
  17. package/dist/cjs/start/aiUsage.js +151 -0
  18. package/dist/cjs/start/devApp.d.ts +1 -0
  19. package/dist/cjs/start/devApp.js +6 -0
  20. package/dist/cjs/start/entries.js +4 -0
  21. package/dist/cjs/start/provider.d.ts +24 -0
  22. package/dist/cjs/start/provider.js +159 -0
  23. package/dist/cjs/start/types.d.ts +320 -0
  24. package/dist/cjs/start/types.js +2 -0
  25. package/dist/cjs/upload/index.js +73 -22
  26. package/dist/cjs/upload/index.test.js +35 -2
  27. package/dist/esm/auth/client.d.ts +2 -2
  28. package/dist/esm/check/start/sourceRules.js +3 -0
  29. package/dist/esm/cli.js +6 -0
  30. package/dist/esm/dev/index.js +15 -0
  31. package/dist/esm/dev/signin.d.ts +16 -0
  32. package/dist/esm/dev/signin.js +72 -0
  33. package/dist/esm/internal/appMode.d.ts +11 -0
  34. package/dist/esm/internal/appMode.js +2 -0
  35. package/dist/esm/internal/appToken.d.ts +17 -0
  36. package/dist/esm/internal/appToken.js +22 -0
  37. package/dist/esm/internal/platformFetch.d.ts +2 -0
  38. package/dist/esm/internal/platformFetch.js +8 -0
  39. package/dist/esm/internal/serviceUrls.d.ts +7 -0
  40. package/dist/esm/internal/serviceUrls.js +12 -0
  41. package/dist/esm/runtime/index.d.ts +1 -1
  42. package/dist/esm/signin/conformance.d.ts +100 -0
  43. package/dist/esm/signin/conformance.js +471 -0
  44. package/dist/esm/signin/cookies.d.ts +28 -0
  45. package/dist/esm/signin/cookies.js +59 -0
  46. package/dist/esm/signin/encoding.d.ts +9 -0
  47. package/dist/esm/signin/encoding.js +39 -0
  48. package/dist/esm/signin/endpoints.d.ts +12 -0
  49. package/dist/esm/signin/endpoints.js +29 -0
  50. package/dist/esm/signin/http.d.ts +25 -0
  51. package/dist/esm/signin/http.js +69 -0
  52. package/dist/esm/signin/index.d.ts +8 -0
  53. package/dist/esm/signin/index.js +9 -0
  54. package/dist/esm/signin/keys.d.ts +39 -0
  55. package/dist/esm/signin/keys.js +80 -0
  56. package/dist/esm/signin/paths.d.ts +2 -0
  57. package/dist/esm/signin/paths.js +2 -0
  58. package/dist/esm/signin/seal.d.ts +8 -0
  59. package/dist/esm/signin/seal.js +35 -0
  60. package/dist/esm/signin/signin.d.ts +60 -0
  61. package/dist/esm/signin/signin.js +340 -0
  62. package/dist/esm/signin/transport.d.ts +111 -0
  63. package/dist/esm/signin/transport.js +1 -0
  64. package/dist/esm/signin/verify.d.ts +77 -0
  65. package/dist/esm/signin/verify.js +155 -0
  66. package/dist/esm/start/airtable/index.d.ts +1 -1
  67. package/dist/esm/start/analytics.d.ts +5 -0
  68. package/dist/esm/start/analytics.js +77 -0
  69. package/dist/esm/start/data/index.d.ts +3 -3
  70. package/dist/esm/start/data/index.js +1 -1
  71. package/dist/esm/start/devApp.d.ts +1 -0
  72. package/dist/esm/start/devApp.js +3 -0
  73. package/dist/esm/start/devSignIn.d.ts +1 -0
  74. package/dist/esm/start/devSignIn.js +3 -0
  75. package/dist/esm/start/direct.d.ts +40 -0
  76. package/dist/esm/start/direct.js +313 -0
  77. package/dist/esm/start/entries.js +4 -0
  78. package/dist/esm/start/fetch.d.ts +1 -0
  79. package/dist/esm/start/fetch.js +4 -0
  80. package/dist/esm/start/instance.js +6 -2
  81. package/dist/esm/start/localSignIn.d.ts +18 -0
  82. package/dist/esm/start/localSignIn.js +73 -0
  83. package/dist/esm/start/outbound.d.ts +10 -1
  84. package/dist/esm/start/outbound.js +132 -22
  85. package/dist/esm/start/pageHead.d.ts +36 -0
  86. package/dist/esm/start/pageHead.js +178 -0
  87. package/dist/esm/start/provider.d.ts +24 -0
  88. package/dist/esm/start/provider.js +150 -0
  89. package/dist/esm/start/router.d.ts +6 -2
  90. package/dist/esm/start/router.js +41 -2
  91. package/dist/esm/start/server.d.ts +13 -6
  92. package/dist/esm/start/server.js +173 -42
  93. package/dist/esm/start/telemetry.d.ts +10 -0
  94. package/dist/esm/start/telemetry.js +74 -0
  95. package/dist/esm/start/types.d.ts +117 -2
  96. package/dist/esm/start/uploads.d.ts +2 -0
  97. package/dist/esm/start/uploads.js +52 -0
  98. package/dist/esm/start/version.d.ts +1 -1
  99. package/dist/esm/start/version.js +1 -1
  100. package/dist/esm/start/vite.d.ts +12 -1
  101. package/dist/esm/start/vite.js +116 -4
  102. package/dist/esm/start/workspaceSchema.d.ts +1 -0
  103. package/dist/esm/start/workspaceSchema.js +3 -0
  104. package/dist/esm/upload/index.js +74 -23
  105. package/dist/esm/upload/index.test.js +35 -2
  106. package/package.json +21 -11
  107. package/dist/cjs/auth-server/index.d.ts +0 -369
  108. package/dist/cjs/auth-server/index.js +0 -119
  109. package/dist/esm/auth-server/index.d.ts +0 -369
  110. package/dist/esm/auth-server/index.js +0 -116
  111. package/dist/esm/start/problems.d.ts +0 -19
  112. package/dist/esm/start/problems.js +0 -8
@@ -0,0 +1,155 @@
1
+ // The identity token's verifier (T5 design §6.1), the same rules as restly's `identityToken.ts` on the front and the
2
+ // dispatcher. Web Crypto only.
3
+ import { fromBase64Url, isRecord, jsonOf, utf8 } from "./encoding.js";
4
+ import { IDENTITY_KEY_KIND } from "./keys.js";
5
+ /** The `typ` every identity token carries in its header, and nothing else does. */
6
+ export const IDENTITY_TOKEN_TYPE = "zite-id+jwt";
7
+ export const DEFAULT_MAX_LIFETIME_S = 300;
8
+ const CLOCK_SKEW_S = 5;
9
+ const MAX_TOKEN_LENGTH = 8192;
10
+ const MAX_ROLES = 32;
11
+ const MODES = new Set(["live", "preview", "demo", "dev"]);
12
+ const isWhole = (value) => typeof value === "number" && Number.isSafeInteger(value);
13
+ const isText = (value, max) => typeof value === "string" && value.length <= max;
14
+ const isOptionalText = (value, max) => value === undefined || isText(value, max);
15
+ const claimsOf = (payload) => {
16
+ const { iss, sub, aud, azp, iat, exp, sid, nonce, email, name, firstName, lastName, roles, isInternal, mode, ver, preview } = payload;
17
+ if (!isText(email, 320) ||
18
+ !isText(name, 200) ||
19
+ !isOptionalText(firstName, 200) ||
20
+ !isOptionalText(lastName, 200) ||
21
+ !isOptionalText(sid, 255) ||
22
+ !isOptionalText(nonce, 255) ||
23
+ !Array.isArray(roles) ||
24
+ roles.length > MAX_ROLES ||
25
+ !roles.every((role) => isText(role, 128)) ||
26
+ typeof isInternal !== "boolean" ||
27
+ !(ver === null || (isWhole(ver) && ver >= 0))) {
28
+ return undefined;
29
+ }
30
+ return {
31
+ iss: iss,
32
+ sub: sub,
33
+ aud: aud,
34
+ ...(azp !== undefined && { azp: azp }),
35
+ iat: iat,
36
+ exp: exp,
37
+ ...(sid !== undefined && { sid }),
38
+ ...(nonce !== undefined && { nonce }),
39
+ email,
40
+ name,
41
+ ...(firstName !== undefined && { firstName }),
42
+ ...(lastName !== undefined && { lastName }),
43
+ roles: roles,
44
+ isInternal,
45
+ mode: mode,
46
+ ver,
47
+ ...(preview !== undefined && { preview: preview }),
48
+ };
49
+ };
50
+ const previewOk = (preview, mode, pinned) => {
51
+ if (mode !== "preview")
52
+ return preview === undefined;
53
+ return (isRecord(preview) &&
54
+ isWhole(preview.build) &&
55
+ preview.build >= 0 &&
56
+ isText(preview.editor, 128) &&
57
+ preview.editor.length > 0 &&
58
+ (pinned === undefined || preview.build === pinned));
59
+ };
60
+ // Imported once per process; a CryptoKey holds no request's I/O.
61
+ const imported = new Map();
62
+ const publicKey = async (raw) => {
63
+ const held = imported.get(raw);
64
+ if (held)
65
+ return held;
66
+ const bytes = fromBase64Url(raw);
67
+ if (!bytes)
68
+ return undefined;
69
+ try {
70
+ const key = await crypto.subtle.importKey("raw", bytes, { name: "Ed25519" }, false, ["verify"]);
71
+ imported.set(raw, key);
72
+ return key;
73
+ }
74
+ catch {
75
+ return undefined;
76
+ }
77
+ };
78
+ // Reported once per reason and key id, and only so many: both come from the caller.
79
+ const MAX_REPORTED = 64;
80
+ const reported = new Set();
81
+ const reportOnce = (report) => {
82
+ const key = `${report.reason} ${report.kid ?? ""}`;
83
+ if (reported.has(key) || reported.size >= MAX_REPORTED)
84
+ return;
85
+ reported.add(key);
86
+ console.warn(`[zite] refused an identity token: ${report.reason}${report.kid ? ` (kid ${report.kid})` : ""}`);
87
+ };
88
+ /**
89
+ * Verifies identity tokens against `keys`, in §6.1's order. A `kid` the keys don't know triggers one refetch. Each
90
+ * refusal is reported to `onRefusal`, by default logged once per reason and key id.
91
+ */
92
+ export const createIdentityVerifier = (keys, options = {}) => async (token, expect) => {
93
+ const refuse = (reason, kid) => {
94
+ const safeKid = kid?.slice(0, 64);
95
+ (options.onRefusal ?? reportOnce)({ reason, ...(safeKid !== undefined && { kid: safeKid }) });
96
+ return { status: "refused", reason, ...(safeKid !== undefined && { kid: safeKid }) };
97
+ };
98
+ const parts = token.length <= MAX_TOKEN_LENGTH ? token.split(".") : [];
99
+ if (parts.length !== 3)
100
+ return refuse("malformed");
101
+ const [headerPart, payloadPart, signaturePart] = parts;
102
+ const header = jsonOf(fromBase64Url(headerPart));
103
+ const payload = jsonOf(fromBase64Url(payloadPart));
104
+ const signature = fromBase64Url(signaturePart);
105
+ if (!isRecord(header) || !isRecord(payload) || !signature)
106
+ return refuse("malformed");
107
+ if (header.alg !== "EdDSA")
108
+ return refuse("alg");
109
+ if (header.typ !== IDENTITY_TOKEN_TYPE)
110
+ return refuse("typ");
111
+ const kid = typeof header.kid === "string" ? header.kid : undefined;
112
+ if (kid === undefined)
113
+ return refuse("kid");
114
+ const own = (map) => (map && Object.hasOwn(map, kid) ? map[kid] : undefined);
115
+ const entry = own(keys.current()) ?? own(await keys.refresh());
116
+ if (!entry)
117
+ return refuse("kid", kid);
118
+ if (entry.kind !== IDENTITY_KEY_KIND)
119
+ return refuse("key kind", kid);
120
+ const key = await publicKey(entry.key);
121
+ const genuine = !!key && (await crypto.subtle.verify({ name: "Ed25519" }, key, signature, utf8(`${headerPart}.${payloadPart}`)));
122
+ if (!genuine)
123
+ return refuse("signature", kid);
124
+ if (payload.iss !== expect.issuer)
125
+ return refuse("iss", kid);
126
+ if (typeof payload.aud !== "string" || payload.aud !== expect.clientId)
127
+ return refuse("aud", kid);
128
+ if (payload.azp !== undefined && payload.azp !== payload.aud)
129
+ return refuse("azp", kid);
130
+ const now = Math.floor((expect.now ?? Date.now()) / 1000);
131
+ const { iat, exp } = payload;
132
+ if (!isWhole(iat) || !isWhole(exp))
133
+ return refuse("claims", kid);
134
+ if (iat > now + CLOCK_SKEW_S)
135
+ return refuse("iat", kid);
136
+ if (exp <= iat || exp - iat > (expect.maxLifetimeS ?? DEFAULT_MAX_LIFETIME_S))
137
+ return refuse("lifetime", kid);
138
+ if (!isText(payload.sub, 255) || payload.sub.length === 0)
139
+ return refuse("sub", kid);
140
+ if (typeof payload.mode !== "string" || !MODES.has(payload.mode) || !expect.clientId.endsWith(`:${payload.mode}`)) {
141
+ return refuse("mode", kid);
142
+ }
143
+ const claims = claimsOf(payload);
144
+ if (!claims)
145
+ return refuse("claims", kid);
146
+ if (!previewOk(payload.preview, payload.mode, expect.previewBuild))
147
+ return refuse("preview", kid);
148
+ if (expect.nonce !== undefined && claims.nonce !== expect.nonce)
149
+ return refuse("nonce", kid);
150
+ if (exp <= now - CLOCK_SKEW_S)
151
+ return { status: "expired", claims };
152
+ if (expect.ver !== "any" && claims.ver !== expect.ver)
153
+ return { status: "stale", claims };
154
+ return { status: "valid", claims };
155
+ };
@@ -1,7 +1,7 @@
1
1
  import { type AirtableSettings } from "./dispatch.js";
2
2
  import type { PlatformSession, HostRequestState } from "../types.js";
3
3
  /** The build's Airtable integration `integrationId`, or undefined when it isn't one. */
4
- export declare const airtableSettingsOf: (session: PlatformSession, integrationId: string) => Promise<AirtableSettings | undefined>;
4
+ export declare const airtableSettingsOf: (session: Pick<PlatformSession, "integrationSettings">, integrationId: string) => Promise<AirtableSettings | undefined>;
5
5
  /** One generated Airtable table call, run here with the connection's token, which the outbound fetch refreshes on a 401. */
6
6
  export declare function runAirtableCall(host: HostRequestState, session: PlatformSession, integrationId: string, settings: AirtableSettings, methodName: string, params: unknown, access: "signedIn" | "anyone" | "webhook" | "workflow"): Promise<unknown>;
7
7
  /** For tests: forget what this isolate learned. */
@@ -0,0 +1,5 @@
1
+ import type { HostRequestState } from "./types.js";
2
+ /** A request's body as text, or undefined once it runs past `max` bytes. */
3
+ export declare const textUpTo: (request: Request, max: number) => Promise<string | undefined>;
4
+ /** A beacon from the runtime: a batch of events, or one. Only a live page's reach the platform. */
5
+ export declare const takeAnalytics: (request: Request, host: HostRequestState) => Promise<Response>;
@@ -0,0 +1,77 @@
1
+ // The runtime's page analytics, taken on the app's own origin and handed to the platform's runs service on the
2
+ // request's token. The service checks the events and stamps the org and app from the token, never from the page.
3
+ import { platformFetch } from "../internal/platformFetch.js";
4
+ import { directAccess } from "./direct.js";
5
+ const MAX_ANALYTICS_BYTES = 256 * 1024;
6
+ const RUNS_TIMEOUT_MS = 5_000;
7
+ const accepted = () => Response.json({ accepted: true }, { status: 202 });
8
+ /** A request's body as text, or undefined once it runs past `max` bytes. */
9
+ export const textUpTo = async (request, max) => {
10
+ if (!request.body)
11
+ return "";
12
+ const reader = request.body.getReader();
13
+ const chunks = [];
14
+ let size = 0;
15
+ for (;;) {
16
+ const { done, value } = await reader.read();
17
+ if (done)
18
+ break;
19
+ size += value.byteLength;
20
+ if (size > max) {
21
+ await reader.cancel();
22
+ return undefined;
23
+ }
24
+ chunks.push(value);
25
+ }
26
+ const bytes = new Uint8Array(size);
27
+ let at = 0;
28
+ for (const chunk of chunks) {
29
+ bytes.set(chunk, at);
30
+ at += chunk.byteLength;
31
+ }
32
+ return new TextDecoder().decode(bytes);
33
+ };
34
+ const parsed = (raw) => {
35
+ if (raw === undefined)
36
+ return undefined;
37
+ try {
38
+ return JSON.parse(raw);
39
+ }
40
+ catch {
41
+ return undefined;
42
+ }
43
+ };
44
+ // Workers sets the visitor's country on the request; Node has none.
45
+ const countryOf = (request) => {
46
+ const country = request.headers.get("cf-ipcountry") ?? request.cf?.country;
47
+ return typeof country === "string" ? country : undefined;
48
+ };
49
+ /** A beacon from the runtime: a batch of events, or one. Only a live page's reach the platform. */
50
+ export const takeAnalytics = async (request, host) => {
51
+ if (request.method !== "POST")
52
+ return new Response("Method not allowed", { status: 405 });
53
+ if (host.mode !== "live")
54
+ return accepted();
55
+ const access = await directAccess(host);
56
+ if (!access?.urls.runs)
57
+ return accepted();
58
+ const body = parsed(await textUpTo(request, MAX_ANALYTICS_BYTES));
59
+ if (body === undefined)
60
+ return Response.json({ error: "Invalid analytics payload" }, { status: 400 });
61
+ const events = body && typeof body === "object" && "events" in body ? body.events : [body];
62
+ try {
63
+ const answer = await platformFetch(new Request(`${access.urls.runs}/ingest`, {
64
+ method: "POST",
65
+ headers: { authorization: `Bearer ${access.token}`, "content-type": "application/json" },
66
+ body: JSON.stringify({ kind: "analytics", events, userAgent: request.headers.get("user-agent") ?? "", country: countryOf(request) }),
67
+ signal: AbortSignal.timeout(RUNS_TIMEOUT_MS),
68
+ }));
69
+ if (!answer.ok && answer.status !== 400)
70
+ console.error(`[zite] page analytics not kept: the runs service answered ${answer.status}`);
71
+ return new Response(answer.body, { status: answer.status, headers: { "content-type": "application/json" } });
72
+ }
73
+ catch (error) {
74
+ console.error("[zite] page analytics not kept", error);
75
+ return accepted();
76
+ }
77
+ };
@@ -7,9 +7,9 @@ type Found = {
7
7
  nameMappings: DataNameMappings | null;
8
8
  };
9
9
  /** The build's base and SDK names, asked of the platform once per isolate. */
10
- export declare const dataContextOf: (session: PlatformSession) => Promise<Found>;
11
- /** One `zite.*` call, translated here and sent to base-runner through the platform. */
12
- export declare function runDataCall(session: PlatformSession, found: Found, mode: HostMode, methodName: string, sent: unknown): Promise<unknown>;
10
+ export declare const dataContextOf: (session: Pick<PlatformSession, "dataContext">) => Promise<Found>;
11
+ /** One `zite.*` call, translated here and sent to base-runner: on the app token, or through the host's session. */
12
+ export declare function runDataCall(session: Pick<PlatformSession, "dataFetch">, found: Found, mode: HostMode, methodName: string, sent: unknown): Promise<unknown>;
13
13
  /** For tests: forget what this isolate learned. */
14
14
  export declare const resetDataDispatch: () => void;
15
15
  export {};
@@ -34,7 +34,7 @@ const tableIdOf = (nameMappings, sent) => {
34
34
  }
35
35
  return sent;
36
36
  };
37
- /** One `zite.*` call, translated here and sent to base-runner through the platform. */
37
+ /** One `zite.*` call, translated here and sent to base-runner: on the app token, or through the host's session. */
38
38
  export async function runDataCall(session, found, mode, methodName, sent) {
39
39
  const params = sent && typeof sent === "object" && typeof sent.tableId === "string"
40
40
  ? { ...sent, tableId: tableIdOf(found.nameMappings, sent.tableId) }
@@ -0,0 +1 @@
1
+ export declare const devAppId: string | null;
@@ -0,0 +1,3 @@
1
+ // Null as published. Under `vite dev`, `zite()` replaces this module with the app's id from its zite.config.json: the
2
+ // app the `local` provider mints dev tokens for.
3
+ export const devAppId = null;
@@ -0,0 +1 @@
1
+ export declare const devSignIn: Readonly<Record<string, string>> | null;
@@ -0,0 +1,3 @@
1
+ // Null as published. Under `vite dev`, `zite()` replaces this module in the server environment with what `zitejs dev`
2
+ // wrote to the app's `.zite/dev.env`: Cloudflare's plugin only reads the app's own `.env` into workerd.
3
+ export const devSignIn = null;
@@ -0,0 +1,40 @@
1
+ import type { HostRequestState, PagePlan, PlatformCallInput, PlatformCallResult, PlatformSession, PlatformUrls } from "./types.js";
2
+ export type DirectAccess = {
3
+ token: string;
4
+ urls: PlatformUrls;
5
+ };
6
+ type Connection = Record<string, unknown> & {
7
+ status?: unknown;
8
+ message?: unknown;
9
+ userFacingMessage?: unknown;
10
+ };
11
+ type Connections = {
12
+ connections: Record<string, Connection>;
13
+ env: Record<string, string>;
14
+ envConnections: Record<string, string>;
15
+ };
16
+ export declare const sessionOf: (host: HostRequestState) => Promise<PlatformSession | undefined>;
17
+ /** The request's token and where to send it, renewed first if it's about to expire; undefined on the relay. */
18
+ export declare const directAccess: (host: HostRequestState) => Promise<DirectAccess | undefined>;
19
+ /** At most `max` at once, the rest in turn; each take resolves with its release. */
20
+ export declare const limiter: (max: number) => () => Promise<() => void>;
21
+ /** The app's own data dispatch's requests, to base-runner on the token, which says the base, mode and user. */
22
+ export declare const directDataFetch: (host: HostRequestState) => ({ method, path, body }: {
23
+ method: string;
24
+ path: string;
25
+ body?: string;
26
+ }) => Promise<Response>;
27
+ /** `GET connections` for `local`, which has no host to hand them over in props. Stale if the backend didn't answer. */
28
+ export declare const localConnections: (access: DirectAccess) => Promise<Connections>;
29
+ /** The build's page settings for `local`, which has no host to send them; null when the backend has none to give. */
30
+ export declare const localPagePlan: (access: DirectAccess) => Promise<PagePlan | null>;
31
+ /** For tests: forget what this isolate learned. */
32
+ export declare const resetLocalConnections: () => void;
33
+ /**
34
+ * A platform call on the token: undefined without one, or for a call only the host's session answers (`ZiteMeta`,
35
+ * and `integrations.get` on Zite). Errors come back as values, as the relay's do.
36
+ */
37
+ export declare const directCall: (host: HostRequestState, input: PlatformCallInput) => Promise<PlatformCallResult | undefined>;
38
+ /** After a provider answered 401: the connection refreshed by the backend, or by the host's session without a token. */
39
+ export declare const refreshConnection: (host: HostRequestState, name: string) => Promise<PlatformCallResult | undefined>;
40
+ export {};
@@ -0,0 +1,313 @@
1
+ // Data and services on the request's app token, sent straight to the platform. Without a token, the host's session
2
+ // relays them as before. Each answer is shaped as the host's relay shaped it, so what an app sees doesn't change.
3
+ import { appTokenClaims } from "../internal/appToken.js";
4
+ import { platformFetch } from "../internal/platformFetch.js";
5
+ import { serviceUrl } from "../internal/serviceUrls.js";
6
+ import { INTEGRATIONS_PLATFORM_ID } from "./credentials.js";
7
+ import { DEMO_UNAVAILABLE_MESSAGE } from "./data/dispatch.js";
8
+ import { isZiteErrorCode } from "./errors.js";
9
+ import { errorOf, preview } from "./runLog.js";
10
+ import { STEP_RESULT_MAX_BYTES } from "./steps.js";
11
+ import { sendRunReport } from "./telemetry.js";
12
+ const STEPS_INTEGRATION_ID = "__steps__";
13
+ const PDF_INTEGRATION_ID = "__pdf__";
14
+ const SCHEDULES_INTEGRATION_ID = "__schedules__";
15
+ const BACKEND_TIMEOUT_MS = 5_000;
16
+ // Attachments take up to 30 s each, and a render 30 s, as on classic.
17
+ const SDK_TIMEOUT_MS = 90_000;
18
+ // One request's fan-out, as the host capped it; base-runner's per-app bucket is what enforces.
19
+ const DATA_CONCURRENCY = 16;
20
+ const SQL_CONCURRENCY = 4;
21
+ const SQL_PATH = /\/sql(?:\?|$)/;
22
+ class PlatformError extends Error {
23
+ route;
24
+ status;
25
+ constructor(route, status) {
26
+ super(`${route} answered ${status}`);
27
+ this.route = route;
28
+ this.status = status;
29
+ }
30
+ }
31
+ const DEMO_REFUSED = { error: { code: "FORBIDDEN", message: DEMO_UNAVAILABLE_MESSAGE } };
32
+ export const sessionOf = async (host) => {
33
+ if (!host.platform)
34
+ return undefined;
35
+ host.session ??= Promise.resolve(host.platform.session());
36
+ return host.session;
37
+ };
38
+ /** The request's token and where to send it, renewed first if it's about to expire; undefined on the relay. */
39
+ export const directAccess = async (host) => {
40
+ const urls = host.provider?.urls;
41
+ const token = urls ? await host.provider?.token() : undefined;
42
+ return urls && token ? { token, urls } : undefined;
43
+ };
44
+ const send = (access, url, init) => platformFetch(new Request(url, {
45
+ method: init.method,
46
+ headers: { authorization: `Bearer ${access.token}`, "content-type": "application/json" },
47
+ body: init.body,
48
+ ...(init.timeoutMs && { signal: AbortSignal.timeout(init.timeoutMs) }),
49
+ }));
50
+ const platformJson = async (access, method, url, route, body) => {
51
+ const response = await send(access, url, {
52
+ method,
53
+ body: body === undefined ? undefined : JSON.stringify(body),
54
+ timeoutMs: BACKEND_TIMEOUT_MS,
55
+ });
56
+ if (!response.ok)
57
+ throw new PlatformError(route, response.status);
58
+ return (await response.json());
59
+ };
60
+ const backendJson = (access, method, path, body) => platformJson(access, method, `${access.urls.backend}/v1/start/app${path}`, path, body);
61
+ /** At most `max` at once, the rest in turn; each take resolves with its release. */
62
+ export const limiter = (max) => {
63
+ let active = 0;
64
+ const waiting = [];
65
+ return async () => {
66
+ if (active < max)
67
+ active++;
68
+ else
69
+ await new Promise((resolve) => waiting.push(resolve));
70
+ let released = false;
71
+ return () => {
72
+ if (released)
73
+ return;
74
+ released = true;
75
+ const next = waiting.shift();
76
+ if (next)
77
+ next();
78
+ else
79
+ active--;
80
+ };
81
+ };
82
+ };
83
+ /** The app's own data dispatch's requests, to base-runner on the token, which says the base, mode and user. */
84
+ export const directDataFetch = (host) => async ({ method, path, body }) => {
85
+ const slots = (host.dataSlots ??= { data: limiter(DATA_CONCURRENCY), sql: limiter(SQL_CONCURRENCY) });
86
+ const release = await (SQL_PATH.test(path) ? slots.sql : slots.data)();
87
+ try {
88
+ const access = await directAccess(host);
89
+ if (!access)
90
+ throw new Error("The Zite platform binding is missing");
91
+ return await send(access, `${access.urls.baseRunner}${path}`, { method, body });
92
+ }
93
+ finally {
94
+ release();
95
+ }
96
+ };
97
+ /** As the host answered a demo: email pretends to succeed; schedules and connections act as the author, so are refused. */
98
+ const demoAnswer = (input) => {
99
+ if (input.className === "Email" && input.methodName === "send")
100
+ return { value: { success: true } };
101
+ if (input.integrationId === SCHEDULES_INTEGRATION_ID || input.integrationId === INTEGRATIONS_PLATFORM_ID)
102
+ return DEMO_REFUSED;
103
+ return undefined;
104
+ };
105
+ const sdkRoute = (host, input) => input.className === "Email" && input.methodName === "send"
106
+ ? { route: "email", body: { integrationId: input.integrationId, params: input.params, mode: host.mode } }
107
+ : input.integrationId === PDF_INTEGRATION_ID && input.methodName === "renderHtml"
108
+ ? { route: "pdf", body: { params: input.params } }
109
+ : input.integrationId === SCHEDULES_INTEGRATION_ID
110
+ ? { route: "schedules", body: { methodName: input.methodName, params: input.params } }
111
+ : undefined;
112
+ // A 4xx naming a ZiteError code, or any 400, says what the app got wrong, as its error; anything else is ours.
113
+ const sdk = async (access, { route, body }) => {
114
+ const url = route === "schedules" ? `${access.urls.backend}/v1/start/app/schedules` : serviceUrl(access.urls, route);
115
+ const response = await send(access, url, {
116
+ method: "POST",
117
+ body: JSON.stringify(body),
118
+ timeoutMs: SDK_TIMEOUT_MS,
119
+ });
120
+ const answer = (await response.json().catch(() => null));
121
+ const message = typeof answer?.error === "string" ? answer.error : `The ${route === "pdf" ? "PDF" : route} call failed`;
122
+ if (response.status >= 400 && response.status < 500 && isZiteErrorCode(answer?.code))
123
+ return { error: { code: answer.code, message } };
124
+ if (response.status === 400)
125
+ return { error: { code: "BAD_REQUEST", message } };
126
+ if (!response.ok)
127
+ throw new PlatformError(route, response.status);
128
+ return { value: answer };
129
+ };
130
+ /** `step.run`'s saves and a resumed run's read of them; the workflow and run come from the token. */
131
+ const steps = async (host, access, { methodName, params }) => {
132
+ const refused = (message) => ({ error: { code: "BAD_REQUEST", message } });
133
+ if (host.invoke?.kind !== "workflow")
134
+ return refused("step.run runs only in a workflow");
135
+ // Before any step's value leaves the app: with no workspace database there's nowhere to keep it.
136
+ if (appTokenClaims(access.token)?.base === null)
137
+ return refused("Durable steps need the workspace database, and this app has none");
138
+ const url = serviceUrl(access.urls, "steps");
139
+ if (methodName === "load") {
140
+ return { value: (await platformJson(access, "GET", url, "steps")).memos };
141
+ }
142
+ if (methodName !== "persist")
143
+ return refused(`Unknown steps method: ${methodName}`);
144
+ const { name, value, durationMs } = (params ?? {});
145
+ if (typeof name !== "string" || name.length === 0 || name.length > 255)
146
+ return refused("A step needs a name of 1 to 255 characters");
147
+ if (new TextEncoder().encode(JSON.stringify(value ?? null)).length > STEP_RESULT_MAX_BYTES) {
148
+ return refused(`step "${name}" returned more than ${STEP_RESULT_MAX_BYTES / 1024}KB`);
149
+ }
150
+ await platformJson(access, "POST", url, "steps", {
151
+ workflow: host.invoke.name,
152
+ name,
153
+ value: value ?? null,
154
+ ...(Number.isInteger(durationMs) && durationMs >= 0 && { durationMs }),
155
+ });
156
+ return { value: { persisted: true } };
157
+ };
158
+ // Per isolate, as the host keeps them: until the token's settings version moves, or a minute without one.
159
+ const CONNECTIONS_REUSE_MS = 60_000;
160
+ const CONNECTIONS_MAX_AGE_MS = 10 * 60_000;
161
+ // Only answers, never a pending call: Workers ties a request's I/O to that request.
162
+ let localHeld;
163
+ /** `GET connections` for `local`, which has no host to hand them over in props. Stale if the backend didn't answer. */
164
+ export const localConnections = async (access) => {
165
+ const claims = appTokenClaims(access.token);
166
+ const key = `${claims?.app ?? ""}:${claims?.ver ?? ""}`;
167
+ const reuseMs = typeof claims?.ver === "number" ? CONNECTIONS_MAX_AGE_MS : CONNECTIONS_REUSE_MS;
168
+ if (localHeld?.key === key && Date.now() - localHeld.at < reuseMs)
169
+ return localHeld.answer;
170
+ try {
171
+ const answer = await backendJson(access, "GET", "/connections");
172
+ localHeld = {
173
+ key,
174
+ at: Date.now(),
175
+ answer: { connections: answer.connections ?? {}, env: answer.env ?? {}, envConnections: answer.envConnections ?? {} },
176
+ };
177
+ }
178
+ catch (error) {
179
+ if (!localHeld)
180
+ throw error;
181
+ console.error("[zite] couldn't refresh connections; using the last ones", error);
182
+ }
183
+ return localHeld.answer;
184
+ };
185
+ // A dev token names the newest build, whose page settings change only with another.
186
+ const PAGE_REUSE_MS = 60_000;
187
+ let localPage;
188
+ /** The build's page settings for `local`, which has no host to send them; null when the backend has none to give. */
189
+ export const localPagePlan = async (access) => {
190
+ const claims = appTokenClaims(access.token);
191
+ const key = `${claims?.app ?? ""}:${claims?.build ?? ""}`;
192
+ if (localPage?.key === key && Date.now() - localPage.at < PAGE_REUSE_MS)
193
+ return localPage.plan;
194
+ let plan = null;
195
+ try {
196
+ plan = (await backendJson(access, "GET", "/page")).page ?? null;
197
+ }
198
+ catch (error) {
199
+ console.error("[zite] couldn't load the app's page settings, so its pages get none of the platform's head", error);
200
+ }
201
+ localPage = { key, at: Date.now(), plan };
202
+ return plan;
203
+ };
204
+ /** For tests: forget what this isolate learned. */
205
+ export const resetLocalConnections = () => {
206
+ localHeld = undefined;
207
+ localPage = undefined;
208
+ };
209
+ const notFound = (name) => ({ error: { code: "BAD_REQUEST", message: `Integration ${name} not found` } });
210
+ /** `integrations.get` for `local`, answered as the host answers it. */
211
+ const localIntegration = async (access, { methodName, params }) => {
212
+ const name = params?.name;
213
+ if (methodName !== "get" || typeof name !== "string" || !name) {
214
+ return { error: { code: "BAD_REQUEST", message: "integrations.get(name): name must be a non-empty string" } };
215
+ }
216
+ const { connections } = await localConnections(access);
217
+ const answer = Object.hasOwn(connections, name) ? connections[name] : undefined;
218
+ if (!answer)
219
+ return notFound(name);
220
+ if (answer.status === "unavailable") {
221
+ return {
222
+ error: {
223
+ code: "INTERNAL_ERROR",
224
+ message: String(answer.message),
225
+ ...(typeof answer.userFacingMessage === "string" && { userFacingMessage: answer.userFacingMessage }),
226
+ },
227
+ };
228
+ }
229
+ return { value: answer };
230
+ };
231
+ const somethingWentWrong = (host, input, error) => {
232
+ console.error("[zite] platform call failed", {
233
+ requestId: host.requestId,
234
+ call: `${input.className}.${input.methodName}`,
235
+ error: errorOf(error).message,
236
+ });
237
+ return { error: { code: "INTERNAL_ERROR", message: "Something went wrong" } };
238
+ };
239
+ // Sent as the call ends rather than with the response's flush, which a request past its deadline never reaches.
240
+ // `local` has no run log to send it to.
241
+ const report = (host, record) => {
242
+ if (host.provider?.kind === "local") {
243
+ (host.calls ??= []).push(record);
244
+ return;
245
+ }
246
+ const sent = sendRunReport(host, { runs: [], calls: [record] }).catch((error) => console.error("[zite] couldn't record a platform call", error));
247
+ host.waitUntil?.(sent);
248
+ };
249
+ // The host recorded the calls it relayed, failures included; going direct, the app records them for its run.
250
+ const recorded = async (host, input, run) => {
251
+ const at = Date.now();
252
+ const result = await run().catch((error) => somethingWentWrong(host, input, error));
253
+ report(host, {
254
+ integrationId: input.integrationId,
255
+ className: input.className,
256
+ methodName: input.methodName,
257
+ at,
258
+ durationMs: Date.now() - at,
259
+ inputs: preview(input.params),
260
+ ...("value" in result ? { outputs: preview(result.value) } : { error: { code: result.error.code, message: result.error.message } }),
261
+ });
262
+ return result;
263
+ };
264
+ /**
265
+ * A platform call on the token: undefined without one, or for a call only the host's session answers (`ZiteMeta`,
266
+ * and `integrations.get` on Zite). Errors come back as values, as the relay's do.
267
+ */
268
+ export const directCall = async (host, input) => {
269
+ const access = await directAccess(host);
270
+ if (!access)
271
+ return undefined;
272
+ const local = host.provider?.kind === "local";
273
+ const demo = host.mode === "demo" ? demoAnswer(input) : undefined;
274
+ if (demo)
275
+ return demo;
276
+ try {
277
+ if (input.integrationId === STEPS_INTEGRATION_ID)
278
+ return await steps(host, access, input);
279
+ if (input.integrationId === INTEGRATIONS_PLATFORM_ID)
280
+ return local ? await localIntegration(access, input) : undefined;
281
+ const route = sdkRoute(host, input);
282
+ if (route)
283
+ return await recorded(host, input, () => sdk(access, route));
284
+ return local ? { error: { code: "NOT_FOUND", message: `${input.className}.${input.methodName} isn't served yet` } } : undefined;
285
+ }
286
+ catch (error) {
287
+ return somethingWentWrong(host, input, error);
288
+ }
289
+ };
290
+ /** After a provider answered 401: the connection refreshed by the backend, or by the host's session without a token. */
291
+ export const refreshConnection = async (host, name) => {
292
+ const access = await directAccess(host);
293
+ if (!access)
294
+ return (await sessionOf(host))?.refreshConnection(name);
295
+ if (host.mode === "demo")
296
+ return DEMO_REFUSED;
297
+ let refreshed;
298
+ try {
299
+ refreshed = (await backendJson(access, "POST", `/connections/${encodeURIComponent(name)}/refresh`))
300
+ .connection;
301
+ }
302
+ catch (error) {
303
+ return error instanceof PlatformError && error.status === 404
304
+ ? notFound(name)
305
+ : { error: { code: "INTERNAL_ERROR", message: `Integration ${name} could not be refreshed` } };
306
+ }
307
+ if (refreshed && localHeld && host.provider?.kind === "local") {
308
+ localHeld.answer = { ...localHeld.answer, connections: { ...localHeld.answer.connections, [name]: refreshed } };
309
+ }
310
+ if (refreshed?.status !== "connected")
311
+ return { error: { code: "INTERNAL_ERROR", message: `Integration ${name} is not connected` } };
312
+ return { value: refreshed };
313
+ };
@@ -11,6 +11,8 @@ const APP_START_FILES = ["src/start.ts", "src/start.tsx"];
11
11
  */
12
12
  export const renderStartServerEntry = (target = "cloudflare") => target === "cloudflare"
13
13
  ? `// Generated by zitejs for TanStack Start apps. The platform owns this file.
14
+ // First, so an SDK client an app module builds as it loads gets zitejs's fetch.
15
+ import 'zitejs/start/fetch';
14
16
  import handler from '@tanstack/react-start/server-entry';
15
17
  import { createZiteWorker } from 'zitejs/start/worker';
16
18
  import { getRouter } from '../src/router';
@@ -19,6 +21,8 @@ import { startInstance } from './start';
19
21
  export default createZiteWorker({ handler, getRouter, startInstance });
20
22
  `
21
23
  : `// Generated by zitejs for TanStack Start apps. The platform owns this file.
24
+ // First, so an SDK client an app module builds as it loads gets zitejs's fetch.
25
+ import 'zitejs/start/fetch';
22
26
  import handler, { createServerEntry } from '@tanstack/react-start/server-entry';
23
27
  import { createZiteFetch } from 'zitejs/start/server';
24
28
  import { getRouter } from '../src/router';
@@ -0,0 +1 @@
1
+ export {};