zitejs 0.10.0-start.23 → 0.10.0-start.26

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 (40) hide show
  1. package/dist/cjs/cli.js +1 -1
  2. package/dist/cjs/dev/signin.d.ts +2 -2
  3. package/dist/cjs/dev/signin.js +5 -5
  4. package/dist/cjs/start/provider.d.ts +8 -6
  5. package/dist/cjs/start/provider.js +102 -41
  6. package/dist/cjs/start/types.d.ts +57 -13
  7. package/dist/esm/cli.js +1 -1
  8. package/dist/esm/dev/signin.d.ts +2 -2
  9. package/dist/esm/dev/signin.js +6 -6
  10. package/dist/esm/signin/conformance.js +1 -1
  11. package/dist/esm/signin/keys.d.ts +3 -7
  12. package/dist/esm/signin/keys.js +4 -10
  13. package/dist/esm/start/direct.d.ts +3 -3
  14. package/dist/esm/start/direct.js +14 -16
  15. package/dist/esm/start/index.d.ts +1 -1
  16. package/dist/esm/start/outbound.d.ts +4 -4
  17. package/dist/esm/start/outbound.js +33 -33
  18. package/dist/esm/start/pageHead.d.ts +3 -3
  19. package/dist/esm/start/pageHead.js +3 -8
  20. package/dist/esm/start/provider.d.ts +8 -6
  21. package/dist/esm/start/provider.js +100 -39
  22. package/dist/esm/start/sdk/axios.d.ts +76 -0
  23. package/dist/esm/start/sdk/axios.js +210 -0
  24. package/dist/esm/start/sdk/nodeFetch.d.ts +41 -0
  25. package/dist/esm/start/sdk/nodeFetch.js +33 -0
  26. package/dist/esm/start/sdk/undici.d.ts +34 -0
  27. package/dist/esm/start/sdk/undici.js +18 -0
  28. package/dist/esm/start/sdkPatches.d.ts +22 -0
  29. package/dist/esm/start/sdkPatches.js +359 -0
  30. package/dist/esm/start/server.d.ts +3 -3
  31. package/dist/esm/start/server.js +19 -20
  32. package/dist/esm/start/types.d.ts +57 -13
  33. package/dist/esm/start/version.d.ts +1 -1
  34. package/dist/esm/start/version.js +1 -1
  35. package/dist/esm/start/vite.js +2 -0
  36. package/package.json +2 -1
  37. package/dist/cjs/internal/appToken.d.ts +0 -17
  38. package/dist/cjs/internal/appToken.js +0 -26
  39. package/dist/esm/internal/appToken.d.ts +0 -17
  40. package/dist/esm/internal/appToken.js +0 -22
@@ -0,0 +1,359 @@
1
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { transformWithOxc } from "vite";
5
+ /**
6
+ * Classic's cloudflare-lambda prebundle (restly `apps/cloudflare-lambda/scripts/prebundle.ts`) fixed its SDKs for workerd
7
+ * inside each SDK's own bundle; Azure Blob, jimp and pdfkit need the same kind of fix. A Start server is one bundle with
8
+ * React, TanStack and the app, so every patch here is scoped to the modules of the package it fixes, or to the imports
9
+ * those modules make. The one exception is `node-fetch`, whose transport is broken in workerd for every caller.
10
+ */
11
+ const SHIMS = path.join(path.dirname(fileURLToPath(import.meta.url)), "sdk");
12
+ const NODE_FETCH_SHIM = path.join(SHIMS, "nodeFetch.js");
13
+ const SLACK_AXIOS_SHIM = path.join(SHIMS, "axios.js");
14
+ const JSFORCE_UNDICI_SHIM = path.join(SHIMS, "undici.js");
15
+ const EMPTY_MODULE = "\0zite-sdk:empty";
16
+ const PACKAGE_DIR = /[\\/]node_modules[\\/](?:@[^\\/]+[\\/])?[^\\/]+(?=[\\/])/g;
17
+ const packages = new Map();
18
+ /** @internal The installed package a module file belongs to, from its innermost `node_modules`. */
19
+ export const packageOf = (file) => {
20
+ let dir;
21
+ for (const match of file.matchAll(PACKAGE_DIR))
22
+ dir = file.slice(0, match.index + match[0].length);
23
+ if (!dir)
24
+ return undefined;
25
+ if (!packages.has(dir)) {
26
+ try {
27
+ const json = JSON.parse(readFileSync(path.join(dir, "package.json"), "utf-8"));
28
+ const browser = typeof json.browser === "object" && json.browser !== null ? json.browser : undefined;
29
+ packages.set(dir, { name: json.name ?? path.basename(dir), version: json.version ?? "unknown", dir, browser });
30
+ }
31
+ catch {
32
+ packages.set(dir, null);
33
+ }
34
+ }
35
+ return packages.get(dir) ?? undefined;
36
+ };
37
+ const describePackage = (pkg) => `${pkg.name} ${pkg.version}`;
38
+ const cleanId = (id) => id.split("?")[0];
39
+ // googleapis-common builds a multipart upload by hand. Its browser path, which the `window` rewrite below selects, appends
40
+ // a part only `if (typeof part.body === 'string')`, so every binary media upload lands as a 0-byte file. Its Node path
41
+ // builds a `stream.PassThrough`, which workerd sends as "[object Object]". This rebuilds the body as a Blob (ZIT-5059).
42
+ const MULTIPART_OPEN = " function browserMultipartUpload(multipart) {";
43
+ const MULTIPART_PATCHED = `function browserMultipartUpload(multipart) {
44
+ const boundary = randomUUID();
45
+ const finale = \`--\${boundary}--\`;
46
+ headers['content-type'] = \`multipart/related; boundary=\${boundary}\`;
47
+ return (async () => {
48
+ const parts = [];
49
+ for (const part of multipart) {
50
+ parts.push(\`--\${boundary}\\r\\ncontent-type: \${part['content-type']}\\r\\n\\r\\n\`);
51
+ parts.push(await __zitePartToBlobPart(part.body));
52
+ parts.push('\\r\\n');
53
+ }
54
+ parts.push(finale);
55
+ options.data = new Blob(parts);
56
+ })();
57
+ }
58
+ async function __zitePartToBlobPart(body) {
59
+ if (typeof body === 'string' || body instanceof Blob) return body;
60
+ if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) return body;
61
+ if (body && typeof body.getReader === 'function') return new Blob([await new Response(body).arrayBuffer()]);
62
+ if (body && typeof body[Symbol.asyncIterator] === 'function') {
63
+ const chunks = [];
64
+ for await (const chunk of body) chunks.push(typeof chunk === 'string' ? chunk : new Uint8Array(chunk));
65
+ return new Blob(chunks);
66
+ }
67
+ throw new Error(
68
+ 'Unsupported media.body type for a Google multipart upload: ' +
69
+ (body === null || body === undefined ? String(body) : body.constructor?.name || typeof body) +
70
+ '. Pass a string, Buffer, Uint8Array, ArrayBuffer, Blob, or a stream.',
71
+ );
72
+ }`;
73
+ /** @internal googleapis-common's `apirequest.js` with binary multipart uploads fixed; null when its shape has changed. */
74
+ export const patchGoogleMultipart = (code) => {
75
+ const start = code.indexOf(MULTIPART_OPEN);
76
+ // Anchored on the declaration: `multipartUpload` above it has the same string guard.
77
+ const end = start === -1 ? -1 : code.indexOf("\n }\n", start);
78
+ const callSite = "browserMultipartUpload(multipart);";
79
+ if (end === -1 || !code.slice(start, end).includes("if (typeof part.body === 'string') {") || !code.includes(callSite))
80
+ return null;
81
+ // Now async, and called from inside `async createAPIRequestAsync`.
82
+ return `${code.slice(0, start)} ${MULTIPART_PATCHED}${code.slice(end + "\n }".length)}`.replace(callSite, `await ${callSite}`);
83
+ };
84
+ // jsforce hands fetch a Node PassThrough as the request body, which workerd's fetch can't read, and pipes the response
85
+ // body into a Node stream, which hangs in workerd or, on a fetch Response, has no `.pipe()` at all.
86
+ const JSFORCE_REQUEST_BODY = /\bbody: input\b/;
87
+ const JSFORCE_RESPONSE_BODY = /readWhatwgReadableStream\(res\.body,\s*output\)|(?:[\w$]+\.)?Readable\.fromWeb\(res\.body\)\.pipe\(output\)|res\.body\.pipe\(output\)/;
88
+ const JSFORCE_READ_TEXT = "res.text().then(function (t) { output.write(t); output.end(); }).catch(function (e) { output.destroy(e); })";
89
+ /** @internal jsforce's `request.js` on fetch bodies; null when its shape has changed. */
90
+ export const patchJsforceRequest = (code) => JSFORCE_REQUEST_BODY.test(code) && JSFORCE_RESPONSE_BODY.test(code)
91
+ ? code.replace(JSFORCE_REQUEST_BODY, "body: request.body").replace(JSFORCE_RESPONSE_BODY, JSFORCE_READ_TEXT)
92
+ : null;
93
+ const SLACK_REDIRECT_ERROR = /redirect:\s*(["'])error\1/g;
94
+ // By package name rather than path, so an aliased or nested install is patched too.
95
+ const TRANSFORMED = new Set(["googleapis-common", "jsforce", "stripe", "@slack/web-api", "pdfkit"]);
96
+ const AWS_PACKAGE = /^@(?:aws-sdk|smithy|aws-crypto)\//;
97
+ const NODE_ENTRY_PACKAGE = /^(?:@azure\/|@typespec\/|@jimp\/|jimp$)/;
98
+ const AWS_PATH = /[\\/]node_modules[\\/]@(?:aws-sdk|smithy|aws-crypto)[\\/]/;
99
+ // What each package must have had patched by the end of a build that loaded it, and what a miss costs.
100
+ const EXPECTED = {
101
+ "googleapis-common": {
102
+ isBrowser: "isbrowser.js no longer checks `window`, so uploads take the Node path, which workerd sends as \"[object Object]\"",
103
+ multipart: "browserMultipartUpload no longer matches, so binary media uploads send 0 bytes",
104
+ },
105
+ jsforce: { request: "request.js no longer matches, so requests with a body hang and responses fail to read" },
106
+ pdfkit: { "browser build": "its browser build no longer matches, so it throws as it loads or has no standard fonts" },
107
+ "@slack/web-api": { transport: "it neither imports axios nor sends `redirect: 'error'`, so its transport is unknown to the patch" },
108
+ stripe: { "node entry": "its ESM worker entry wasn't reached or has no Node sibling, so webhooks.constructEvent stays async-only" },
109
+ };
110
+ /** The SDK patches a Start server build needs in workerd, as classic's prebundle applied them. */
111
+ export function sdkPatches() {
112
+ const seen = new Map();
113
+ const note = (pkg, patch) => {
114
+ const entry = seen.get(pkg.dir) ?? { pkg, done: new Set() };
115
+ if (patch)
116
+ entry.done.add(patch);
117
+ seen.set(pkg.dir, entry);
118
+ };
119
+ const core = {
120
+ name: "zite:sdk-patches",
121
+ buildStart() {
122
+ seen.clear();
123
+ },
124
+ async resolveId(source, importer, options) {
125
+ if (!importer)
126
+ return undefined;
127
+ const resolveOptions = { kind: options.kind, isEntry: options.isEntry, custom: options.custom, skipSelf: true };
128
+ if (source === "node-fetch")
129
+ return NODE_FETCH_SHIM;
130
+ // Real axios and undici for the app; Slack 7's and jsforce's own imports get shims.
131
+ if (source === "axios" || source === "undici") {
132
+ const pkg = packageOf(importer);
133
+ if (source === "axios" && pkg?.name === "@slack/web-api") {
134
+ note(pkg, "transport");
135
+ return SLACK_AXIOS_SHIM;
136
+ }
137
+ return source === "undici" && pkg?.name === "jsforce" ? JSFORCE_UNDICI_SHIM : undefined;
138
+ }
139
+ // These pick their build through a `browser` export condition, which Cloudflare's conditions select: Azure's touches
140
+ // `document` as it loads, and jimp's is an empty stub. Their Node `import` entries run in workerd.
141
+ const name = packageName(source);
142
+ if (name && NODE_ENTRY_PACKAGE.test(name)) {
143
+ const resolved = await this.resolve(source, importer, resolveOptions);
144
+ const pkg = resolved && !resolved.external ? packageOf(cleanId(resolved.id)) : undefined;
145
+ if (!resolved || !pkg || pkg.name !== name)
146
+ return resolved;
147
+ const subpath = `.${source.slice(name.length)}`;
148
+ const target = nodeImportEntry(pkg, subpath);
149
+ if (!target && subpath === ".")
150
+ this.warn(`[zite] ${describePackage(pkg)}: no Node \`import\` entry in its exports, so it keeps its browser build`);
151
+ return target ?? resolved;
152
+ }
153
+ // The AWS SDK swaps its Node wiring for fetch and WebCrypto through the package.json `browser` field, which a server
154
+ // build doesn't read. Without it a client loads its Node runtime config against @aws-sdk/core's browser entry and
155
+ // throws as it's constructed.
156
+ if (AWS_PATH.test(importer) || AWS_PACKAGE.test(source)) {
157
+ const resolved = await this.resolve(source, importer, resolveOptions);
158
+ if (!resolved || resolved.external)
159
+ return resolved;
160
+ const file = cleanId(resolved.id);
161
+ const pkg = packageOf(file);
162
+ if (!pkg || !AWS_PACKAGE.test(pkg.name))
163
+ return resolved;
164
+ const target = awsBrowserTarget(pkg, file);
165
+ if (target === false)
166
+ return EMPTY_MODULE;
167
+ if (target)
168
+ return (await this.resolve(target, importer, resolveOptions)) ?? resolved;
169
+ if (/^@aws-sdk\/client-/.test(pkg.name) && /[\\/]runtimeConfig\.js$/.test(file)) {
170
+ this.warn(`[zite] ${describePackage(pkg)}: no browser runtime config, so the client loads its Node one and fails in workerd`);
171
+ }
172
+ return resolved;
173
+ }
174
+ return undefined;
175
+ },
176
+ load(id) {
177
+ return id === EMPTY_MODULE ? "module.exports = {};\n" : undefined;
178
+ },
179
+ async transform(code, id) {
180
+ const file = cleanId(id);
181
+ const pkg = packageOf(file);
182
+ if (!pkg || !TRANSFORMED.has(pkg.name))
183
+ return undefined;
184
+ note(pkg);
185
+ let out = code;
186
+ // Stripe's worker entry pairs fetch with WebCrypto, which can't verify a webhook synchronously, so
187
+ // `webhooks.constructEvent` throws. Classic ran its Node entry with the fetch client as the default.
188
+ if (pkg.name === "stripe") {
189
+ const entries = stripeEntries(pkg);
190
+ if (entries && file === entries.worker) {
191
+ note(pkg, "node entry");
192
+ return { code: stripeWrapper(entries.worker, entries.node), map: null };
193
+ }
194
+ return undefined;
195
+ }
196
+ // Cloudflare's conditions give pdfkit's browser build, which reads `import.meta.url` as it loads (undefined in workerd)
197
+ // and, unlike its Node build, has no standard fonts until the app registers them.
198
+ if (pkg.name === "pdfkit") {
199
+ if (!/[\\/]pdfkit\.browser\.mjs$/.test(file))
200
+ return undefined;
201
+ const patched = patchPdfkitBrowser(code, standardFontModules(file));
202
+ if (!patched)
203
+ return undefined;
204
+ note(pkg, "browser build");
205
+ return { code: patched, map: null };
206
+ }
207
+ // Slack 8 calls fetch with `redirect: 'error'`, which workerd refuses outright. Slack throws on any status but 200, so
208
+ // a redirect still fails the call.
209
+ if (pkg.name === "@slack/web-api") {
210
+ const patched = code.replace(SLACK_REDIRECT_ERROR, "redirect: 'manual'");
211
+ if (patched === code)
212
+ return undefined;
213
+ note(pkg, "transport");
214
+ return { code: patched, map: null };
215
+ }
216
+ if (pkg.name === "googleapis-common" && /[\\/]apirequest\.js$/.test(file)) {
217
+ const patched = patchGoogleMultipart(out);
218
+ if (patched) {
219
+ out = patched;
220
+ note(pkg, "multipart");
221
+ }
222
+ }
223
+ if (pkg.name === "jsforce" && /[\\/]request\.js$/.test(file) && !/[\\/]browser[\\/]browser[\\/]/.test(file)) {
224
+ const patched = patchJsforceRequest(out);
225
+ if (patched) {
226
+ out = patched;
227
+ note(pkg, "request");
228
+ }
229
+ }
230
+ // googleapis-common picks its multipart path by testing `window`. Classic defined `window` as `globalThis` for its
231
+ // whole googleapis bundle; here only this package's modules see it.
232
+ if (pkg.name === "googleapis-common" && /\bwindow\b/.test(out)) {
233
+ if (/[\\/]isbrowser\.js$/.test(file) && /typeof window/.test(out))
234
+ note(pkg, "isBrowser");
235
+ const result = await transformWithOxc(out, file, { lang: "js", sourceType: "unambiguous", define: { window: "globalThis" }, sourcemap: true });
236
+ return { code: result.code, map: result.map };
237
+ }
238
+ return out === code ? undefined : { code: out, map: null };
239
+ },
240
+ buildEnd() {
241
+ for (const { pkg, done } of seen.values()) {
242
+ for (const [patch, consequence] of Object.entries(EXPECTED[pkg.name] ?? {})) {
243
+ if (!done.has(patch))
244
+ this.warn(`[zite] ${describePackage(pkg)} is unpatched for workerd: ${consequence}`);
245
+ }
246
+ }
247
+ },
248
+ };
249
+ return {
250
+ ...core,
251
+ enforce: "pre",
252
+ // Server code only: browsers run these SDKs as published.
253
+ applyToEnvironment: (environment) => environment.config.consumer === "server",
254
+ // `vite dev` pre-bundles dependencies apart from the plugin pipeline, so the same hooks join that build.
255
+ configEnvironment: (name, _config, { command }) => name === "ssr" && command === "serve" ? { optimizeDeps: { rolldownOptions: { plugins: [core] } } } : undefined,
256
+ };
257
+ }
258
+ // The ESM entries the workerd and Node conditions pick, from Stripe's own exports.
259
+ const stripeEntryCache = new Map();
260
+ const stripeEntries = (pkg) => {
261
+ if (!stripeEntryCache.has(pkg.dir))
262
+ stripeEntryCache.set(pkg.dir, readStripeEntries(pkg));
263
+ return stripeEntryCache.get(pkg.dir) ?? null;
264
+ };
265
+ const readStripeEntries = (pkg) => {
266
+ try {
267
+ const { exports } = JSON.parse(readFileSync(path.join(pkg.dir, "package.json"), "utf-8"));
268
+ const worker = importTarget(exports?.workerd);
269
+ const node = importTarget(exports?.default);
270
+ return worker && node && existsSync(path.join(pkg.dir, node)) ? { worker: path.join(pkg.dir, worker), node: path.join(pkg.dir, node) } : null;
271
+ }
272
+ catch {
273
+ return null;
274
+ }
275
+ };
276
+ // An exports condition's ESM file, whether it's `{ import: file }` or `{ import: { types, default: file } }`.
277
+ const importTarget = (condition) => {
278
+ if (typeof condition === "string")
279
+ return condition;
280
+ if (typeof condition !== "object" || condition === null)
281
+ return undefined;
282
+ const branches = condition;
283
+ return importTarget(branches.import ?? branches.default);
284
+ };
285
+ // Classic's `stripeFetchWrapper`, in place of the worker entry: the Node entry, so the synchronous webhook verifier keeps
286
+ // node:crypto, with the fetch client as the default, because the Node client waits on a socket event workerd never sends.
287
+ const stripeWrapper = (workerEntry, nodeEntry) => {
288
+ const relative = path.relative(path.dirname(workerEntry), nodeEntry).split(path.sep).join("/");
289
+ return `import StripeNode from ${JSON.stringify(relative.startsWith(".") ? relative : `./${relative}`)};
290
+ function Stripe(key, config) {
291
+ // stripe-node still takes a bare API version string as its config.
292
+ const options = typeof config === "string" ? { apiVersion: config } : config ?? {};
293
+ return new StripeNode(key, { httpClient: StripeNode.createFetchHttpClient(), ...options });
294
+ }
295
+ Object.setPrototypeOf(Stripe, StripeNode);
296
+ Stripe.prototype = StripeNode.prototype;
297
+ Stripe.Stripe = Stripe;
298
+ Stripe.default = Stripe;
299
+ export { Stripe };
300
+ export default Stripe;
301
+ `;
302
+ };
303
+ /** @internal Where a package's `browser` field sends one of its files: a path, false for an empty module, or none. */
304
+ export const awsBrowserTarget = (pkg, file) => {
305
+ const rel = `./${path.relative(pkg.dir, file).split(path.sep).join("/")}`;
306
+ // xml-builder's browser parser is built on DOMParser, which workerd lacks; its default parser is plain JS.
307
+ if (pkg.name === "@aws-sdk/xml-builder") {
308
+ const plain = file.replace(/xml-parser\.browser\.js$/, "xml-parser.js");
309
+ return plain !== file && existsSync(plain) ? plain : undefined;
310
+ }
311
+ for (const [key, value] of Object.entries(pkg.browser ?? {})) {
312
+ if (!key.startsWith("./"))
313
+ continue;
314
+ if (key === rel || `${key}.js` === rel || `${key}/index.js` === rel)
315
+ return value === false ? false : path.join(pkg.dir, value);
316
+ }
317
+ return undefined;
318
+ };
319
+ /** @internal The package a bare specifier names, scoped or not; null for a relative or absolute one. */
320
+ export const packageName = (source) => {
321
+ if (source.startsWith(".") || source.startsWith("/") || source.startsWith("\0") || source.includes(":"))
322
+ return null;
323
+ const parts = source.split("/");
324
+ return source.startsWith("@") ? (parts.length > 1 ? parts.slice(0, 2).join("/") : null) : parts[0];
325
+ };
326
+ // A package's own exports for one subpath, with its `browser` and `react-native` conditions passed over.
327
+ const nodeImportEntry = (pkg, subpath) => {
328
+ try {
329
+ const { exports } = JSON.parse(readFileSync(path.join(pkg.dir, "package.json"), "utf-8"));
330
+ const entry = typeof exports === "object" && exports !== null && "." in exports ? exports[subpath] : subpath === "." ? exports : undefined;
331
+ const target = importTarget(entry);
332
+ return target && existsSync(path.join(pkg.dir, target)) ? path.join(pkg.dir, target) : undefined;
333
+ }
334
+ catch {
335
+ return undefined;
336
+ }
337
+ };
338
+ const standardFontModules = (browserBuild) => {
339
+ try {
340
+ return readdirSync(path.join(path.dirname(browserBuild), "standard-fonts")).filter((file) => file.endsWith(".mjs"));
341
+ }
342
+ catch {
343
+ return [];
344
+ }
345
+ };
346
+ /** @internal pdfkit's browser build with a fixed module URL and the 14 standard fonts registered; null when its shape has changed. */
347
+ export const patchPdfkitBrowser = (code, fontModules) => {
348
+ if (!code.includes("import.meta.url") || !/\bregisterStdFonts\b/.test(code) || fontModules.length === 0)
349
+ return null;
350
+ // Only a key for its in-memory files, so any URL that parses will do.
351
+ const located = code.replaceAll("import.meta.url", JSON.stringify("file:///bundle/node_modules/pdfkit/js/pdfkit.browser.mjs"));
352
+ const fonts = fontModules.map((file, i) => ({ name: `__ziteStdFont${i}`, file }));
353
+ return [
354
+ ...fonts.map(({ name, file }) => `import ${name} from ${JSON.stringify(`./standard-fonts/${file}`)};`),
355
+ located,
356
+ `registerStdFonts(${fonts.map(({ name }) => name).join(", ")});`,
357
+ "",
358
+ ].join("\n");
359
+ };
@@ -1,7 +1,7 @@
1
1
  import type { HostProps, PlatformProvider, HostRequestState } from "./types.js";
2
2
  export { runWithHost } from "./scope.js";
3
3
  export { describeApp } from "./describe.js";
4
- export type { HostProps, PlatformBinding, PlatformCallInput, PlatformCallResult, PlatformProvider, PlatformUrls, RunRecord, } from "./types.js";
4
+ export type { AppContext, HostProps, PlatformBinding, PlatformCallInput, PlatformCallResult, PlatformProvider, PlatformUrls, RunRecord, } from "./types.js";
5
5
  /**
6
6
  * Routes every zitejs data, integration and email call to this request's
7
7
  * platform on its app token, and only inside an access scope. The access kind
@@ -22,8 +22,8 @@ export declare function hostContextFromProps(request: Request, props: HostProps)
22
22
  export declare function hostContextFromRequest(request: Request, provider?: PlatformProvider): HostRequestState;
23
23
  /**
24
24
  * A request under `vite dev` with the `local` provider: the developer's dev token reaches the platform, and the
25
- * stand-in user is signed in. Headers still invoke only warm and describe. Its token's mode, base and app URL come
26
- * once the token does, with `loadLocal`.
25
+ * stand-in user is signed in. Headers still invoke only warm and describe. Its mode, base and app URL come once the
26
+ * backend has said what the token is for, with `loadLocal`.
27
27
  */
28
28
  export declare function hostContextFromLocal(request: Request, provider: PlatformProvider): HostRequestState;
29
29
  /** Every server function TanStack compiled, written in by `zite()` at build. Empty in dev, where TanStack doesn't call its id hook. */
@@ -10,7 +10,7 @@ import { errorOf, preview } from "./runLog.js";
10
10
  import { DATA_INTEGRATION_ID, runDataCall } from "./data/index.js";
11
11
  import { airtableSettingsOf, runAirtableCall } from "./airtable/index.js";
12
12
  import { withoutConsole } from "./quiet.js";
13
- import { rememberConnection, watchOutboundFetches, withAiGatewayUrl, withRefreshedTokens } from "./outbound.js";
13
+ import { rememberConnection, watchOutboundFetches, withGatewayUrl, withRefreshedTokens } from "./outbound.js";
14
14
  import { INTEGRATIONS_PLATFORM_ID } from "./credentials.js";
15
15
  import { connectionsOnToken, directAccess, directCall, directDataFetch, localPagePlan, NoPlatformError } from "./direct.js";
16
16
  import { takeAnalytics } from "./analytics.js";
@@ -18,10 +18,9 @@ import { takeUploadSession } from "./uploads.js";
18
18
  import { UPLOAD_SESSION_PATH } from "../internal/serviceUrls.js";
19
19
  import { sendRunReport } from "./telemetry.js";
20
20
  import { ANALYTICS_PATH, platformHeadOf } from "./pageHead.js";
21
- import { localModeOf, localPlatform, ziteProvider } from "./provider.js";
21
+ import { localPlatform, ziteProvider } from "./provider.js";
22
22
  import { localSignIn, userOfIdentity } from "./localSignIn.js";
23
23
  import { isSignInPath } from "../signin/paths.js";
24
- import { appTokenClaims } from "../internal/appToken.js";
25
24
  import { getHost, requireScope, runInScope, runWithHost } from "./scope.js";
26
25
  import { workspaceSchemaNames } from "./workspaceSchema.js";
27
26
  import { ZITEJS_VERSION } from "./version.js";
@@ -48,7 +47,7 @@ export function installPlatformTransport() {
48
47
  const access = await directAccess(host);
49
48
  if (!access)
50
49
  throw new NoPlatformError();
51
- const target = { baseId: host.baseId ?? appTokenClaims(access.token)?.base ?? null, names: workspaceSchemaNames };
50
+ const target = { baseId: (await host.provider?.context())?.baseId ?? null, names: workspaceSchemaNames };
52
51
  return recordCall(host, { integrationId, className, methodName, params }, () => runDataCall({ dataFetch: directDataFetch(host) }, target, host.mode, methodName, params));
53
52
  }
54
53
  const airtable = integrationId.startsWith("__") ? undefined : airtableSettingsOf(integrationId);
@@ -76,7 +75,7 @@ export function installPlatformTransport() {
76
75
  /** `integrations.get`'s answer, whose values then name the calls made with them. */
77
76
  const connectionAnswer = (host, name, result) => {
78
77
  if ("value" in result) {
79
- const value = withAiGatewayUrl(host, withRefreshedTokens(result.value));
78
+ const value = withGatewayUrl(host, withRefreshedTokens(result.value));
80
79
  rememberConnection(host, name, value);
81
80
  return value;
82
81
  }
@@ -116,8 +115,8 @@ export function hostContextFromProps(request, props) {
116
115
  user: props.user,
117
116
  mode: props.mode,
118
117
  invoke: props.invoke,
119
- appUrl: props.appUrl,
120
- baseId: props.baseId,
118
+ appUrl: props.appUrl ?? undefined,
119
+ baseId: props.baseId ?? undefined,
121
120
  previewClaim: props.previewClaim,
122
121
  env: props.env,
123
122
  envConnections: props.envConnections,
@@ -129,7 +128,7 @@ export function hostContextFromProps(request, props) {
129
128
  provider: ziteProvider(props),
130
129
  };
131
130
  if (props.page)
132
- host.head = platformHeadOf(props.page, { url: request.url, mode: props.mode, token: props.appToken });
131
+ host.head = platformHeadOf(props.page, { url: request.url, mode: props.mode, context: props });
133
132
  return host;
134
133
  }
135
134
  // Classic sets these per run. Node and workerd both refuse getters on process.env, so each request writes what the
@@ -181,8 +180,8 @@ const invokeOf = (headers, kinds) => {
181
180
  };
182
181
  /**
183
182
  * A request under `vite dev` with the `local` provider: the developer's dev token reaches the platform, and the
184
- * stand-in user is signed in. Headers still invoke only warm and describe. Its token's mode, base and app URL come
185
- * once the token does, with `loadLocal`.
183
+ * stand-in user is signed in. Headers still invoke only warm and describe. Its mode, base and app URL come once the
184
+ * backend has said what the token is for, with `loadLocal`.
186
185
  */
187
186
  export function hostContextFromLocal(request, provider) {
188
187
  return {
@@ -209,22 +208,22 @@ const signInRequired = (request) => {
209
208
  login.searchParams.set("redirectUrl", url.href);
210
209
  return new Response(null, { status: 302, headers: { location: login.pathname + login.search } });
211
210
  };
212
- // No host hands `local` what its token grants, its connections' env or its page settings, so it reads them before app
213
- // code runs. A dev token the backend won't mint fails the request, saying why.
211
+ // No host hands `local` what its token is for, its connections' env or its page settings, so it reads them before app
212
+ // code runs. A dev token the backend won't mint or describe fails the request, saying why.
214
213
  const loadLocal = async (host, request) => {
215
214
  const access = await directAccess(host);
216
- const claims = access ? appTokenClaims(access.token) : undefined;
217
- host.mode = localModeOf(claims);
218
- host.appUrl = claims?.appUrl ?? undefined;
219
- host.baseId = claims?.base ?? undefined;
220
- if (!access)
215
+ if (!access || !host.provider)
221
216
  return;
217
+ const context = await host.provider.context();
218
+ host.mode = context.mode;
219
+ host.appUrl = context.appUrl ?? undefined;
220
+ host.baseId = context.baseId ?? undefined;
222
221
  const [connections, plan] = await Promise.all([
223
- connectionsOnToken(access).catch((error) => {
222
+ connectionsOnToken(access, context).catch((error) => {
224
223
  console.error("[zite] couldn't load the app's connections", error);
225
224
  return undefined;
226
225
  }),
227
- opensPage(request) ? localPagePlan(access) : null,
226
+ opensPage(request) ? localPagePlan(access, context) : null,
228
227
  ]);
229
228
  if (connections) {
230
229
  host.env = connections.env;
@@ -232,7 +231,7 @@ const loadLocal = async (host, request) => {
232
231
  }
233
232
  // The backend serves the platform's runtime, wherever `local` points it.
234
233
  if (plan) {
235
- host.head = platformHeadOf({ plan, runtimeUrl: `${access.urls.backend}/runtime/app-runtime.js` }, { url: host.url, mode: host.mode, token: access.token });
234
+ host.head = platformHeadOf({ plan, runtimeUrl: `${access.urls.backend}/runtime/app-runtime.js` }, { url: host.url, mode: host.mode, context });
236
235
  }
237
236
  };
238
237
  /** Every server function TanStack compiled, written in by `zite()` at build. Empty in dev, where TanStack doesn't call its id hook. */
@@ -94,7 +94,7 @@ export type FetchRecord = {
94
94
  ai?: AiUsageRecord;
95
95
  };
96
96
  /**
97
- * Where the platform's services answer this app: `aiGateway` takes calls on Zite's AI key, `runs` a live page's
97
+ * Where the platform's services answer this app: `gateway` takes calls on a key Zite pays for, `runs` a live page's
98
98
  * analytics and each request's run detail. `email`, `pdf`, `uploads` (the upload session) and `steps` (a workflow
99
99
  * run's saved steps) are each that service's own endpoint, which the platform picks per workspace; without one, the
100
100
  * backend's route answers it.
@@ -102,7 +102,7 @@ export type FetchRecord = {
102
102
  export type PlatformUrls = {
103
103
  baseRunner: string;
104
104
  backend: string;
105
- aiGateway?: string;
105
+ gateway?: string;
106
106
  runs?: string;
107
107
  email?: string;
108
108
  pdf?: string;
@@ -117,19 +117,47 @@ export type PlatformProvider = {
117
117
  kind: "zite" | "local";
118
118
  /** The request's app token, renewed when it's about to expire; undefined when the host sent none. */
119
119
  token(): Promise<string | undefined>;
120
+ /** What the platform says of the request's app and build: the host's props, or `local`'s backend on the dev token. */
121
+ context(): Promise<AppContext>;
120
122
  user(): User | null;
121
123
  urls: PlatformUrls | undefined;
122
124
  };
125
+ /** An app token with its expiry, which travels beside it: zitejs never reads the token itself. */
126
+ export type ExpiringToken = {
127
+ token: string;
128
+ /** Milliseconds since the epoch. */
129
+ expiresAt: number;
130
+ };
123
131
  /**
124
132
  * What the host hands each request beside its app token: the token's renewal, for an answer that outlives the one it
125
133
  * was dispatched with. Its presence in props is what marks a request the host dispatched.
126
134
  */
127
135
  export type PlatformBinding = {
128
136
  /** The request's app token, signed again when it's about to expire; null once it can't be. */
129
- appToken(): Promise<string | null>;
137
+ appToken(): Promise<ExpiringToken | null>;
130
138
  };
131
139
  /** A demo is the published build serving a read-only visitor: as live, but every write is refused. */
132
140
  export type HostMode = "live" | "preview" | "demo" | "validate";
141
+ /**
142
+ * What the platform's records say of the request's app and build. The platform signs the same into the app token,
143
+ * which zitejs only sends: it learns these from the host's props, or under `vite dev` from the backend.
144
+ */
145
+ export type AppContext = {
146
+ /** The app's public identifier. */
147
+ appId: string;
148
+ /** The build's snapshot id; a dev token's is the app's newest. */
149
+ buildId: number;
150
+ /** The app's database: `process.env.ZITE_BASE_ID`. Null when the app has none. */
151
+ baseId: string | null;
152
+ /** Never `validate`, which no platform serves in. */
153
+ mode: Exclude<HostMode, "validate">;
154
+ /** The org settings version the request was served under; null when it couldn't be read. */
155
+ orgSettingsVersion: number | null;
156
+ /** Whether the org's plan shows Zite's badge. */
157
+ showZiteBadge: boolean;
158
+ /** The app's live URL, demo included: `process.env.ZITE_APP_URL`. Null when the platform has none to give. */
159
+ appUrl: string | null;
160
+ };
133
161
  /**
134
162
  * The build's page settings, as the platform baked them at publish from the app's settings and name. What the settings
135
163
  * set (`seo*`, `favicon`, an installable app's) replaces what a page sets; the rest fills what it leaves out.
@@ -205,17 +233,31 @@ export type HostInvoke = {
205
233
  kind: "webhook" | "describe" | "workflow" | "register" | "warm" | "authHook" | "function";
206
234
  name: string;
207
235
  };
236
+ /** One of `integrations.get`'s answers, as the platform resolved the connection for the request. */
237
+ export type HostConnection = {
238
+ status: "connected";
239
+ accessToken: string;
240
+ [extra: string]: string | undefined;
241
+ } | {
242
+ status: "missing" | "expired";
243
+ connectUrl: string;
244
+ } | {
245
+ status: "unavailable";
246
+ message: string;
247
+ userFacingMessage?: string;
248
+ connectUrl?: string;
249
+ serviceId?: number;
250
+ };
208
251
  /** The per-request props the host dispatches with. Only the host can set them. */
209
- export type HostProps = {
252
+ export type HostProps = AppContext & {
210
253
  platform: PlatformBinding;
211
254
  requestId: string;
212
255
  user: User | null;
213
- mode: HostMode;
214
- invoke: HostInvoke | null;
215
- /** The app's live URL, demo included: `process.env.ZITE_APP_URL`. */
216
- appUrl?: string;
217
- /** The app's database: `process.env.ZITE_BASE_ID`. */
218
- baseId?: string;
256
+ /** A warm-up or a describe goes without props. */
257
+ invoke: {
258
+ kind: Exclude<HostInvoke["kind"], "warm" | "describe">;
259
+ name: string;
260
+ } | null;
219
261
  /** An editor preview's access, which zitejs keeps on the app's links and calls. */
220
262
  previewClaim?: string;
221
263
  /** `process.env` as classic sets it: connections' vars, then the user's own secrets. */
@@ -228,18 +270,20 @@ export type HostProps = {
228
270
  runRoot?: string;
229
271
  /** This request's app token, sent only to `urls`. */
230
272
  appToken?: string;
273
+ /** When `appToken` expires, in milliseconds since the epoch; absent without one. */
274
+ appTokenExpiresAt?: number;
231
275
  urls?: PlatformUrls;
232
276
  /** Sent with a page or route request by a host that leaves its head to zitejs. */
233
277
  page?: HostPage;
234
278
  /** The app's access mode, from the platform's records: an internal app serves no page or call to nobody. */
235
- accessMode?: "internal" | "external";
279
+ accessMode: "internal" | "external";
236
280
  /** `ZiteMeta.getWorkspace()`'s answer, from the build's config; absent for a build published before it was kept. */
237
281
  workspace?: ZiteWorkspace;
238
282
  /**
239
283
  * `integrations.get`'s answers, by connection name, real as classic's, when the host already loaded them for the
240
284
  * request: a registration's one connection, and none for a demo. Without them the app asks the backend on its token.
241
285
  */
242
- connections?: Record<string, Record<string, unknown>>;
286
+ connections?: Record<string, HostConnection>;
243
287
  };
244
288
  /** What the host resolved for this request. Set by the generated server entry, never by the browser. */
245
289
  export type HostRequestState = {
@@ -288,7 +332,7 @@ export type HostRequestState = {
288
332
  sql: () => Promise<() => void>;
289
333
  };
290
334
  /** This request's calls on Zite's AI key waiting on the gateway's answer, capped as the host once capped them. */
291
- aiSlots?: () => Promise<() => void>;
335
+ gatewaySlots?: () => Promise<() => void>;
292
336
  /** This request's router, so a page's status can follow the error it rendered. */
293
337
  router?: unknown;
294
338
  /** The platform's head entries for its pages; unset when the host writes them itself. */
@@ -1 +1 @@
1
- export declare const ZITEJS_VERSION = "0.10.0-start.23";
1
+ export declare const ZITEJS_VERSION = "0.10.0-start.26";
@@ -1,2 +1,2 @@
1
1
  // Written by scripts/write-version.mjs from package.json.
2
- export const ZITEJS_VERSION = "0.10.0-start.23";
2
+ export const ZITEJS_VERSION = "0.10.0-start.26";
@@ -10,6 +10,7 @@ import { nameMappingsOf } from "./data/names.js";
10
10
  import { airtableSettingsFrom } from "./airtable/settings.js";
11
11
  import { factoryDescriptions } from "./descriptions.js";
12
12
  import { registrationHashes } from "./registrationHash.js";
13
+ import { sdkPatches } from "./sdkPatches.js";
13
14
  import { hasAppStart, renderStartInstance, renderStartServerEntry, renderWorkflowModules, START_INSTANCE_ENTRY, START_SERVER_ENTRY, workflowFiles, writeIfChanged, } from "./entries.js";
14
15
  // Must match the literals in ./server.ts, which the build rewrites.
15
16
  const FN_IDS_TOKEN = "__ZITE_FN_IDS__";
@@ -363,6 +364,7 @@ export function zite(options = {}) {
363
364
  },
364
365
  }),
365
366
  options.cloudflare !== false ? loadCloudflare(serverEntry) : null,
367
+ options.cloudflare !== false ? sdkPatches() : null,
366
368
  viteReact(),
367
369
  compileZitejs,
368
370
  functionIds,