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,4 @@
1
+ // The generated server entry's first import: an SDK client an app builds at load (`new OpenAI()` at a module's top
2
+ // level) keeps the fetch it found then, so the wrapper must already be in place.
3
+ import { watchOutboundFetches } from "./outbound.js";
4
+ watchOutboundFetches();
@@ -8,8 +8,12 @@ import { isSignInRequired, loginHref, setFailedStatus } from "./index.js";
8
8
  import { errorOf, preview } from "./runLog.js";
9
9
  import { currentHost } from "./host.js";
10
10
  import { getHost, inScope } from "./scope.js";
11
- // TanStack drops its default CSRF check once an app has a start instance.
12
- const csrf = createCsrfMiddleware({ filter: (ctx) => ctx.handlerType === "serverFn" });
11
+ // TanStack drops its default CSRF check once an app has a start instance. Server functions, and every other unsafe
12
+ // request a browser's cookies ride on: the app's own routes too, as Zite's front checks them.
13
+ const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
14
+ const csrf = createCsrfMiddleware({
15
+ filter: (ctx) => ctx.handlerType === "serverFn" || (!SAFE_METHODS.has(ctx.request.method) && ctx.request.headers.has("cookie")),
16
+ });
13
17
  // The app's own request middleware runs inside this one. On a server-function request
14
18
  // what it throws crosses to the browser as thrown, and only an Error goes through the
15
19
  // zite-error adapter.
@@ -0,0 +1,18 @@
1
+ import type { IdentityClaims, SignIn } from "../signin/index.js";
2
+ import type { PlatformUrls, User } from "./types.js";
3
+ /** What the module reads, from env or from the `.zite/dev.env` that `zitejs dev` writes. */
4
+ export declare const LOCAL_SIGNIN_ENV: {
5
+ readonly config: "ZITE_SIGNIN";
6
+ readonly secret: "ZITE_AUTH_SECRET";
7
+ };
8
+ type Env = Record<string, string | undefined>;
9
+ /** Where the backend serves the platform's public keys, for an unknown `kid`. */
10
+ export declare const SIGNING_KEYS_PATH = "/v1/zite/public/start/signing-keys";
11
+ /**
12
+ * The module for this request, when the env names an issuer; undefined otherwise, and whenever `ZITE_DEV_USER` is
13
+ * set: the stand-in wins, with no network, as agent sandboxes need.
14
+ */
15
+ export declare const localSignIn: (env: Env, urls: PlatformUrls, request: Request) => Promise<SignIn | undefined>;
16
+ /** The identity as app code reads it. Off Zite no role names are known, so each role is named by its id. */
17
+ export declare const userOfIdentity: (claims: IdentityClaims | null) => User | null;
18
+ export {};
@@ -0,0 +1,73 @@
1
+ // The sign-in module mounted in the app, off Zite (T5 design §5.9). On Zite the dispatcher's own copy runs and this
2
+ // is never reached: a request with props never selects `local`.
3
+ import { platformFetch } from "../internal/platformFetch.js";
4
+ import { devSignIn } from "./devSignIn.js";
5
+ import { LOCAL_ENV } from "./provider.js";
6
+ /** What the module reads, from env or from the `.zite/dev.env` that `zitejs dev` writes. */
7
+ export const LOCAL_SIGNIN_ENV = { config: "ZITE_SIGNIN", secret: "ZITE_AUTH_SECRET" };
8
+ const configOf = (raw) => {
9
+ let given;
10
+ try {
11
+ given = JSON.parse(raw);
12
+ }
13
+ catch {
14
+ given = undefined;
15
+ }
16
+ const config = (given ?? {});
17
+ const optional = ["redirectUri", "secret", "keysUrl"].every((name) => config[name] === undefined || typeof config[name] === "string");
18
+ if (typeof config.issuer !== "string" || typeof config.clientId !== "string" || !optional) {
19
+ throw new Error(`${LOCAL_SIGNIN_ENV.config} must be JSON naming the issuer and clientId, and may name redirectUri, secret and keysUrl`);
20
+ }
21
+ return config;
22
+ };
23
+ /** Where the backend serves the platform's public keys, for an unknown `kid`. */
24
+ export const SIGNING_KEYS_PATH = "/v1/zite/public/start/signing-keys";
25
+ const send = (request) => platformFetch(request);
26
+ /**
27
+ * The module for this request, when the env names an issuer; undefined otherwise, and whenever `ZITE_DEV_USER` is
28
+ * set: the stand-in wins, with no network, as agent sandboxes need.
29
+ */
30
+ export const localSignIn = async (env, urls, request) => {
31
+ if (env[LOCAL_ENV.user])
32
+ return undefined;
33
+ const raw = env[LOCAL_SIGNIN_ENV.config] ?? devSignIn?.[LOCAL_SIGNIN_ENV.config];
34
+ if (!raw)
35
+ return undefined;
36
+ const secret = env[LOCAL_SIGNIN_ENV.secret] ?? devSignIn?.[LOCAL_SIGNIN_ENV.secret];
37
+ if (!secret)
38
+ throw new Error(`${LOCAL_SIGNIN_ENV.config} needs ${LOCAL_SIGNIN_ENV.secret}, which seals the session cookie: run \`zitejs dev\` to write both`);
39
+ const config = configOf(raw);
40
+ const [app = "", mode] = config.clientId.split(":");
41
+ // Only the developer's client for now; a self-hosted one comes with private key JWT.
42
+ if (mode !== "dev")
43
+ throw new Error(`${LOCAL_SIGNIN_ENV.config} names ${config.clientId}; off Zite the client is <app>:dev`);
44
+ const { aesGcmSealer, createSignIn, httpTransport, remoteIdentityKeys } = await import("../signin/index.js");
45
+ const sealer = aesGcmSealer(secret);
46
+ return createSignIn({
47
+ issuer: config.issuer,
48
+ clientId: config.clientId,
49
+ app,
50
+ mode,
51
+ ver: "any",
52
+ redirectUri: config.redirectUri,
53
+ keys: remoteIdentityKeys(config.keysUrl ?? `${urls.backend}${SIGNING_KEYS_PATH}`, { fetch: send }),
54
+ cookies: { secure: new URL(request.url).protocol === "https:", framed: false },
55
+ transport: httpTransport({
56
+ issuer: config.issuer,
57
+ clientId: config.clientId,
58
+ clientAuth: config.secret ? { kind: "secret", secret: config.secret } : { kind: "none" },
59
+ sealer,
60
+ fetch: send,
61
+ }),
62
+ });
63
+ };
64
+ /** The identity as app code reads it. Off Zite no role names are known, so each role is named by its id. */
65
+ export const userOfIdentity = (claims) => claims && {
66
+ id: claims.sub,
67
+ email: claims.email,
68
+ name: claims.name,
69
+ ...(claims.firstName !== undefined && { firstName: claims.firstName }),
70
+ ...(claims.lastName !== undefined && { lastName: claims.lastName }),
71
+ roles: claims.roles.map((id) => ({ id, name: id })),
72
+ isInternal: claims.isInternal,
73
+ };
@@ -3,9 +3,18 @@
3
3
  * it: logged, every secret it knows redacted, with the connection whose token
4
4
  * it carries and what an org's own AI key used; a 401 on a connection's token
5
5
  * refreshed and sent once more; and a call on Zite's own AI key sent to the
6
- * host over the app's platform binding.
6
+ * AI gateway on the request's app token, or to the host over the app's
7
+ * platform binding when there's no token or gateway.
7
8
  */
8
9
  import type { HostRequestState } from "./types.js";
10
+ /** At the gateway, the connection a call on Zite's AI key bills to: the marker's, which the token takes the place of. */
11
+ export declare const AI_CONNECTION_HEADER = "x-zite-ai-connection";
9
12
  /** An `integrations.get` answer, whose values name the calls that carry them. */
10
13
  export declare const rememberConnection: (host: HostRequestState, name: string, connection: unknown) => void;
14
+ /** An `integrations.get` answer with each token this isolate has since refreshed swapped for its replacement. */
15
+ export declare const withRefreshedTokens: (answer: unknown) => unknown;
16
+ /** A connection on Zite's AI key as `integrations.get` answers it, its `baseUrl` at the provider's gateway. */
17
+ export declare const withAiGatewayUrl: (host: HostRequestState, answer: unknown) => unknown;
11
18
  export declare const createOutboundFetch: (nativeFetch: typeof fetch) => typeof fetch;
19
+ /** Wraps the global fetch once. Next patches fetch for the same reason: the run log must hear of each. */
20
+ export declare const watchOutboundFetches: () => void;
@@ -3,9 +3,13 @@
3
3
  * it: logged, every secret it knows redacted, with the connection whose token
4
4
  * it carries and what an org's own AI key used; a 401 on a connection's token
5
5
  * refreshed and sent once more; and a call on Zite's own AI key sent to the
6
- * host over the app's platform binding.
6
+ * AI gateway on the request's app token, or to the host over the app's
7
+ * platform binding when there's no token or gateway.
7
8
  */
9
+ import { isPlatformRequest } from "../internal/platformFetch.js";
8
10
  import { AI_USAGE_HOSTS, meterAiResponse, withStreamUsage } from "./aiUsage.js";
11
+ import { DEMO_UNAVAILABLE_MESSAGE } from "./data/dispatch.js";
12
+ import { directAccess, limiter, refreshConnection, sessionOf } from "./direct.js";
9
13
  import { REDACTED, redactKnown, secretForms } from "./redactSecrets.js";
10
14
  import { getHost } from "./scope.js";
11
15
  const MAX_FETCHES = 500;
@@ -13,10 +17,12 @@ const MAX_FETCHES = 500;
13
17
  const MIN_TOKEN_LENGTH = 8;
14
18
  // As classic: Workers send no User-Agent, and some APIs (GitHub) refuse a request without one.
15
19
  const DEFAULT_USER_AGENT = "zite";
16
- // The backend's stand-in for Zite's own AI key, which only the host answers.
20
+ // The backend's stand-in for Zite's own AI key, naming the connection a call bills to. Nowhere is it a key.
17
21
  const AI_MARKER = /^zite_ai_gateway:[a-z]+:(.+)$/;
18
- // Where a provider SDK given the connection's `baseUrl` sends it; it never resolves.
22
+ // The gateway's name in a connection's `baseUrl`, which zitejs resolves to the provider's `urls.aiGateway`.
19
23
  const AI_HOST = "zite-ai.invalid";
24
+ /** At the gateway, the connection a call on Zite's AI key bills to: the marker's, which the token takes the place of. */
25
+ export const AI_CONNECTION_HEADER = "x-zite-ai-connection";
20
26
  // A provider's own base URL at the host: `/v1` is OpenAI's, Anthropic's SDK sends it in the path.
21
27
  const AI_PROVIDER_HOSTS = {
22
28
  "api.openai.com": { provider: "openai", strip: "/v1" },
@@ -30,6 +36,8 @@ const MAX_ERROR_CHARS = 1_000;
30
36
  const SECRET_HEADER = /auth|key|token|secret|signature|password|cookie|session/i;
31
37
  // Usage still being read when the request's log is flushed isn't waited on for longer.
32
38
  const USAGE_WAIT_MS = 10_000;
39
+ // A request's calls on Zite's AI key at once, until each is answered, as the host's relay had them.
40
+ const AI_CONCURRENCY = 4;
33
41
  // Tokens refreshed in this isolate, which a later request's props may not name yet.
34
42
  const MAX_REFRESHED = 50;
35
43
  const refreshedTokens = new Map();
@@ -65,6 +73,18 @@ export const rememberConnection = (host, name, connection) => {
65
73
  }
66
74
  }
67
75
  };
76
+ /** An `integrations.get` answer with each token this isolate has since refreshed swapped for its replacement. */
77
+ export const withRefreshedTokens = (answer) => {
78
+ if (replacements.size === 0 || !answer || typeof answer !== "object")
79
+ return answer;
80
+ let swapped;
81
+ for (const [field, value] of Object.entries(answer)) {
82
+ const fresh = typeof value === "string" ? replacements.get(value) : undefined;
83
+ if (fresh)
84
+ (swapped ??= { ...answer })[field] = fresh;
85
+ }
86
+ return swapped ?? answer;
87
+ };
68
88
  const bare = (value) => value.replace(/^(?:Bearer|Token)\s+/i, "");
69
89
  const isUrl = (value) => /^https?:\/\//i.test(value);
70
90
  /** Every value this request knows is secret, longest first. */
@@ -209,22 +229,62 @@ const swapHeaders = (headers, from, to) => {
209
229
  headers.set(name, value.split(from).join(to));
210
230
  }
211
231
  };
212
- /** Where a call on Zite's AI key goes at the host, whether the app named the provider or the `baseUrl` it was given. */
213
- const aiTarget = (url, headers) => {
214
- const marker = [...headers].map(([, value]) => AI_MARKER.exec(bare(value))).find(Boolean);
215
- if (url.hostname === AI_HOST)
216
- return { target: url, connection: marker?.[1] };
232
+ /** The provider's AI gateway, from `urls.aiGateway`. */
233
+ const gatewayOf = (host) => {
234
+ const configured = host.provider?.urls?.aiGateway;
235
+ if (!configured)
236
+ return undefined;
237
+ try {
238
+ return new URL(configured);
239
+ }
240
+ catch {
241
+ return undefined;
242
+ }
243
+ };
244
+ /** `url`'s provider and path when it's under `base`'s path, which names the provider next. */
245
+ const underBase = (url, basePath) => {
246
+ const prefix = basePath.replace(/\/+$/, "");
247
+ if (!url.pathname.startsWith(`${prefix}/`))
248
+ return undefined;
249
+ const [provider = "", ...rest] = url.pathname.slice(prefix.length + 1).split("/");
250
+ return { provider, path: `/${rest.join("/")}${url.search}` };
251
+ };
252
+ /** A call on Zite's AI key, whether the app named the provider, the `baseUrl` it was given, or the gateway itself. */
253
+ const aiCallOf = (url, headers, gateway) => {
254
+ const found = [...headers].map(([, value]) => AI_MARKER.exec(bare(value))).find(Boolean);
255
+ const marker = found ? { marker: found[0], connection: found[1] } : { marker: undefined, connection: undefined };
256
+ if (url.hostname === AI_HOST) {
257
+ const route = underBase(url, "");
258
+ return route && { ...route, ...marker };
259
+ }
260
+ if (!found)
261
+ return undefined;
262
+ if (gateway && url.origin === gateway.origin) {
263
+ const route = underBase(url, gateway.pathname);
264
+ return route && { ...route, ...marker };
265
+ }
217
266
  const route = AI_PROVIDER_HOSTS[url.hostname];
218
- if (!route || !marker)
267
+ if (!route)
219
268
  return undefined;
220
269
  const path = url.pathname.startsWith(route.strip) ? url.pathname.slice(route.strip.length) : url.pathname;
221
- return { target: new URL(`https://${AI_HOST}/${route.provider}${path}${url.search}`), connection: marker[1] };
270
+ return { provider: route.provider, path: `${path}${url.search}`, ...marker };
222
271
  };
223
- const sessionOf = async (host) => {
224
- if (!host.platform)
225
- return undefined;
226
- host.session ??= Promise.resolve(host.platform.session());
227
- return host.session;
272
+ /** A connection on Zite's AI key as `integrations.get` answers it, its `baseUrl` at the provider's gateway. */
273
+ export const withAiGatewayUrl = (host, answer) => {
274
+ const gateway = gatewayOf(host);
275
+ const baseUrl = answer?.baseUrl;
276
+ if (!gateway || typeof baseUrl !== "string" || !answer || typeof answer !== "object")
277
+ return answer;
278
+ let url;
279
+ try {
280
+ url = new URL(baseUrl);
281
+ }
282
+ catch {
283
+ return answer;
284
+ }
285
+ if (url.hostname !== AI_HOST)
286
+ return answer;
287
+ return { ...answer, baseUrl: `${gateway.origin}${gateway.pathname.replace(/\/+$/, "")}${url.pathname}` };
228
288
  };
229
289
  /** The token to send instead of `token`, refreshed once per connection per request. */
230
290
  const freshToken = async (host, token, connection) => {
@@ -235,8 +295,7 @@ const freshToken = async (host, token, connection) => {
235
295
  let pending = refreshing.get(connection);
236
296
  if (!pending) {
237
297
  pending = (async () => {
238
- const session = await sessionOf(host);
239
- const result = session ? await session.refreshConnection(connection) : undefined;
298
+ const result = await refreshConnection(host, connection);
240
299
  if (!result || !("value" in result))
241
300
  return undefined;
242
301
  const fresh = result.value;
@@ -262,11 +321,33 @@ const freshToken = async (host, token, connection) => {
262
321
  }
263
322
  return value;
264
323
  };
265
- const aiUnavailable = () => Response.json({ error: { type: "unavailable", message: "Zite's AI key works only in an app Zite hosts" } }, { status: 503 });
324
+ const aiRefusal = (status, type, message) => Response.json({ error: { type, code: type, message } }, { status });
325
+ const aiUnavailable = (host) => aiRefusal(503, "unavailable", host.provider?.kind === "local"
326
+ ? "Zite's AI key needs the AI gateway: name aiGateway in ZITE_URLS"
327
+ : "Zite's AI key works only in an app Zite hosts");
328
+ /**
329
+ * A call on Zite's AI key at the gateway, the marker swapped for the request's app token. The token goes to the
330
+ * gateway's origin alone: the target is built from it, and a redirect is handed back rather than followed.
331
+ */
332
+ const toAiGateway = async (nativeFetch, base, headers, call, gateway, token) => {
333
+ const target = new URL(`${gateway.origin}${gateway.pathname.replace(/\/+$/, "")}/${call.provider}${call.path}`);
334
+ const sent = new Headers(headers);
335
+ sent.delete(AI_CONNECTION_HEADER);
336
+ sent.delete("content-length");
337
+ // As for a connection's call: a Node SDK that asks for gzip inflates a body Workers already inflated.
338
+ sent.delete("accept-encoding");
339
+ if (call.marker && call.connection) {
340
+ swapHeaders(sent, call.marker, token);
341
+ sent.set(AI_CONNECTION_HEADER, call.connection);
342
+ }
343
+ // Whole, so it goes with its length and the gateway holds only what it is.
344
+ const body = base.body ? await base.arrayBuffer() : undefined;
345
+ return nativeFetch(new Request(target, { method: base.method, headers: sent, body, redirect: "manual", signal: base.signal }));
346
+ };
266
347
  const cfOf = (request) => request.cf;
267
348
  export const createOutboundFetch = (nativeFetch) => async (input, init) => {
268
349
  const host = getHost();
269
- if (!host)
350
+ if (!host || isPlatformRequest(input))
270
351
  return nativeFetch(input, init);
271
352
  let url;
272
353
  try {
@@ -279,7 +360,8 @@ export const createOutboundFetch = (nativeFetch) => async (input, init) => {
279
360
  if (!headers.has("user-agent"))
280
361
  headers.set("user-agent", DEFAULT_USER_AGENT);
281
362
  const method = (init?.method ?? (input instanceof Request ? input.method : "GET")).toUpperCase();
282
- const ai = aiTarget(url, headers);
363
+ const gateway = gatewayOf(host);
364
+ const ai = aiCallOf(url, headers, gateway);
283
365
  const found = ai ? undefined : carried(headers, url, tokensOf(host));
284
366
  const startedAt = Date.now();
285
367
  const sentBody = bodyText(init?.body);
@@ -331,9 +413,27 @@ export const createOutboundFetch = (nativeFetch) => async (input, init) => {
331
413
  const base = new Request(input, usageBody === undefined ? init : { ...init, body: usageBody });
332
414
  if (ai) {
333
415
  try {
416
+ // As the gateway and the host refuse it: a demo has no AI on Zite's key.
417
+ if (host.mode === "demo") {
418
+ const refused = aiRefusal(403, "permission_denied", DEMO_UNAVAILABLE_MESSAGE);
419
+ record({ status: refused.status });
420
+ return refused;
421
+ }
422
+ const access = gateway ? await directAccess(host) : undefined;
423
+ if (gateway && access) {
424
+ const release = await (host.aiSlots ??= limiter(AI_CONCURRENCY))();
425
+ try {
426
+ const response = await toAiGateway(nativeFetch, base, headers, ai, gateway, access.token);
427
+ record({ status: response.status });
428
+ return response;
429
+ }
430
+ finally {
431
+ release();
432
+ }
433
+ }
334
434
  const session = await sessionOf(host);
335
435
  if (!session) {
336
- const refused = aiUnavailable();
436
+ const refused = aiUnavailable(host);
337
437
  record({ status: refused.status });
338
438
  return refused;
339
439
  }
@@ -341,7 +441,7 @@ export const createOutboundFetch = (nativeFetch) => async (input, init) => {
341
441
  // reserves only what it is rather than the most it allows.
342
442
  const body = base.body ? await base.arrayBuffer() : undefined;
343
443
  headers.set("content-length", String(body?.byteLength ?? 0));
344
- const response = await session.aiFetch(new Request(ai.target, { method: base.method, headers, body, redirect: "manual" }));
444
+ const response = await session.aiFetch(new Request(`https://${AI_HOST}/${ai.provider}${ai.path}`, { method: base.method, headers, body, redirect: "manual" }));
345
445
  record({ status: response.status });
346
446
  return response;
347
447
  }
@@ -398,3 +498,13 @@ export const createOutboundFetch = (nativeFetch) => async (input, init) => {
398
498
  throw error;
399
499
  }
400
500
  };
501
+ // Keyed on globalThis so two copies of zitejs in one bundle wrap fetch once.
502
+ const WATCHED_KEY = Symbol.for("zitejs:outbound-fetch");
503
+ /** Wraps the global fetch once. Next patches fetch for the same reason: the run log must hear of each. */
504
+ export const watchOutboundFetches = () => {
505
+ const marks = globalThis;
506
+ if (marks[WATCHED_KEY])
507
+ return;
508
+ marks[WATCHED_KEY] = true;
509
+ globalThis.fetch = createOutboundFetch(globalThis.fetch.bind(globalThis));
510
+ };
@@ -0,0 +1,36 @@
1
+ import type { HostMode, HostPage, PlatformHead } from "./types.js";
2
+ /** Where the runtime posts a page's analytics: its `endpointUrl` and then its own path. */
3
+ export declare const ANALYTICS_PATH = "/__zite/public/zite/analytics";
4
+ type Tag = Record<string, unknown>;
5
+ type Meta = Tag & {
6
+ title?: unknown;
7
+ name?: unknown;
8
+ property?: unknown;
9
+ content?: unknown;
10
+ };
11
+ /** What a route's `head()` answers. */
12
+ export type RouteHead = {
13
+ meta?: Array<Meta | undefined>;
14
+ links?: Array<Tag | undefined>;
15
+ scripts?: Array<Tag | undefined>;
16
+ styles?: unknown;
17
+ };
18
+ /** For one request: the plan its host sent, the badge its token carries, and analytics on a live page. */
19
+ export declare const platformHeadOf: (page: HostPage, request: {
20
+ url: string;
21
+ mode: HostMode;
22
+ token: string | undefined;
23
+ }) => PlatformHead;
24
+ /**
25
+ * The root route's head: the platform's entries first, so TanStack lets the app's own win wherever both set a title,
26
+ * the same meta, or an icon or manifest link, except where the platform replaced the app's own.
27
+ */
28
+ export declare const rootHead: (given: RouteHead | undefined, head: PlatformHead) => RouteHead;
29
+ /**
30
+ * A deeper route's head. The root rendered social metadata from the app's name; a route that sets its own title or
31
+ * description has the social metadata follow it, unless the app's settings or the app itself set it on the way down.
32
+ */
33
+ export declare const routeHead: (given: RouteHead | undefined, head: PlatformHead, above: Array<{
34
+ meta?: unknown;
35
+ }>) => RouteHead | undefined;
36
+ export {};
@@ -0,0 +1,178 @@
1
+ // The platform's part of every page's head: its runtime, the badge and analytics config, an installable app's manifest,
2
+ // the metadata the app's settings set, and what the app's own head() leaves out. Isomorphic: head() runs on the server and again in the browser.
3
+ import { appTokenClaims } from "../internal/appToken.js";
4
+ /** Where the runtime posts a page's analytics: its `endpointUrl` and then its own path. */
5
+ export const ANALYTICS_PATH = "/__zite/public/zite/analytics";
6
+ const ANALYTICS_ENDPOINT = "/__zite";
7
+ /** Served by the platform when the app is installable. */
8
+ const MANIFEST_PATH = "/manifest.webmanifest";
9
+ /** For one request: the plan its host sent, the badge its token carries, and analytics on a live page. */
10
+ export const platformHeadOf = (page, request) => {
11
+ const { plan } = page;
12
+ const claims = request.token ? appTokenClaims(request.token) : undefined;
13
+ const image = plan.seoImage ?? plan.image;
14
+ return {
15
+ title: plan.seoTitle ?? plan.fallbackTitle,
16
+ description: plan.seoDescription ?? plan.fallbackDescription,
17
+ ...(image && { image }),
18
+ icon: plan.favicon ?? plan.defaultFavicon,
19
+ fromSettings: {
20
+ title: plan.seoTitle !== undefined,
21
+ description: plan.seoDescription !== undefined,
22
+ image: plan.seoImage !== undefined,
23
+ icon: plan.favicon !== undefined,
24
+ },
25
+ ...(plan.appleTouchIcon && { appleTouchIcon: plan.appleTouchIcon }),
26
+ ...(plan.manifest && { manifest: { themeColor: plan.manifest.theme_color, shortName: plan.manifest.short_name } }),
27
+ ...(page.runtimeUrl && { runtimeUrl: page.runtimeUrl }),
28
+ ...(page.demo && { demo: { listingSlug: page.demo.listingSlug, listingUrl: page.demo.listingUrl } }),
29
+ // As the host decided before it read the org's plan, when there's no token to say.
30
+ branding: claims?.branding ?? true,
31
+ analytics: {
32
+ appId: claims?.app ?? "",
33
+ // Previews are the builder's own visits; demos aren't the app's.
34
+ enabled: request.mode === "live",
35
+ endpointUrl: `${new URL(request.url).origin}${ANALYTICS_ENDPOINT}`,
36
+ },
37
+ };
38
+ };
39
+ // Safe inside a <script>: nothing in it can close the tag.
40
+ const scriptJson = (value) => JSON.stringify(value).replace(/</g, "\\u003c");
41
+ // The entries zitejs added, so a deeper route can tell the app's own from them.
42
+ const made = new WeakSet();
43
+ const platform = (tags) => {
44
+ for (const tag of tags)
45
+ made.add(tag);
46
+ return tags;
47
+ };
48
+ const metaKey = (meta) => {
49
+ const key = meta?.name ?? meta?.property;
50
+ return typeof key === "string" ? key : undefined;
51
+ };
52
+ // The last one wins, as TanStack renders a route's own head.
53
+ const lastText = (metas, pick) => {
54
+ for (let i = metas.length - 1; i >= 0; i--) {
55
+ const value = metas[i] && pick(metas[i]);
56
+ if (typeof value === "string")
57
+ return value.trim();
58
+ }
59
+ return undefined;
60
+ };
61
+ const titleOf = (metas) => lastText(metas, (meta) => meta.title);
62
+ const descriptionOf = (metas) => lastText(metas, (meta) => (metaKey(meta) === "description" ? meta.content : undefined));
63
+ // Social metadata follows the page's own title and description, as classic's does.
64
+ const followTitle = (title) => [
65
+ { property: "og:title", content: title },
66
+ { property: "og:site_name", content: title || "Zite" },
67
+ { name: "twitter:title", content: title },
68
+ ];
69
+ const followDescription = (description) => [
70
+ { property: "og:description", content: description },
71
+ { name: "twitter:description", content: description },
72
+ ];
73
+ const rels = (link) => String(link?.rel ?? "").toLowerCase().split(/\s+/);
74
+ const PWA_METAS = ["theme-color", "mobile-web-app-capable", "apple-mobile-web-app-capable", "apple-mobile-web-app-title"];
75
+ // Only the platform writes these; a page's own copy would stand in for its badge, analytics or demo listing.
76
+ const PLATFORM_SCRIPTS = ["data-zite-branding", "data-zite-analytics", "data-zite-demo"];
77
+ /** A route's own head, less what the platform sets over it, as classic's index.html had it replaced. */
78
+ const withoutReplaced = (own, head) => {
79
+ if (!own)
80
+ return own;
81
+ // The editor's settings are the user's deliberate choice, so they win over what a page sets.
82
+ const { fromSettings } = head;
83
+ const replaced = new Set([
84
+ ...(fromSettings.title ? ["og:title", "og:site_name", "twitter:title"] : []),
85
+ ...(fromSettings.description ? ["description", "og:description", "twitter:description"] : []),
86
+ ...(fromSettings.image ? ["og:image", "twitter:image"] : []),
87
+ ...(head.manifest ? PWA_METAS : []),
88
+ ]);
89
+ const replacedLink = (link) => {
90
+ const rel = rels(link);
91
+ if (rel.includes("manifest"))
92
+ return !!head.manifest;
93
+ if (rel.includes("apple-touch-icon"))
94
+ return !!head.appleTouchIcon;
95
+ return rel.includes("icon") && fromSettings.icon;
96
+ };
97
+ return {
98
+ ...own,
99
+ ...(own.meta && {
100
+ meta: own.meta.filter((meta) => !(meta && ((fromSettings.title && meta.title !== undefined) || replaced.has(metaKey(meta) ?? "")))),
101
+ }),
102
+ ...(own.links && { links: own.links.filter((link) => !replacedLink(link)) }),
103
+ ...(own.scripts && { scripts: own.scripts.filter((script) => !PLATFORM_SCRIPTS.some((marker) => script && marker in script)) }),
104
+ };
105
+ };
106
+ /**
107
+ * The root route's head: the platform's entries first, so TanStack lets the app's own win wherever both set a title,
108
+ * the same meta, or an icon or manifest link, except where the platform replaced the app's own.
109
+ */
110
+ export const rootHead = (given, head) => {
111
+ const own = withoutReplaced(given, head);
112
+ const ownMeta = own?.meta ?? [];
113
+ const ownLinks = own?.links ?? [];
114
+ const title = titleOf(ownMeta) || head.title;
115
+ const description = descriptionOf(ownMeta) || head.description;
116
+ const meta = [
117
+ { title: head.title },
118
+ { name: "viewport", content: "width=device-width, initial-scale=1" },
119
+ { name: "description", content: head.description },
120
+ ...followTitle(title),
121
+ ...followDescription(description),
122
+ { property: "og:type", content: "website" },
123
+ { name: "twitter:card", content: "summary_large_image" },
124
+ ...(head.image
125
+ ? [
126
+ { property: "og:image", content: head.image },
127
+ { name: "twitter:image", content: head.image },
128
+ ]
129
+ : []),
130
+ ...(head.manifest
131
+ ? [
132
+ { name: "theme-color", content: head.manifest.themeColor },
133
+ { name: "mobile-web-app-capable", content: "yes" },
134
+ { name: "apple-mobile-web-app-capable", content: "yes" },
135
+ { name: "apple-mobile-web-app-title", content: head.manifest.shortName },
136
+ ]
137
+ : []),
138
+ ];
139
+ const ownIcon = ownLinks.some((link) => rels(link).includes("icon"));
140
+ const ownAppleIcon = ownLinks.some((link) => rels(link).includes("apple-touch-icon"));
141
+ const ownManifest = ownLinks.some((link) => rels(link).includes("manifest"));
142
+ const links = [
143
+ ...(ownIcon ? [] : [{ rel: "icon", type: "image/x-icon", href: head.icon }]),
144
+ // Zite's icon would stand in for one the page set, unless the app is installable and has its own.
145
+ ...(ownAppleIcon || (ownIcon && !head.appleTouchIcon) ? [] : [{ rel: "apple-touch-icon", href: head.appleTouchIcon ?? head.icon }]),
146
+ ...(head.manifest && !ownManifest ? [{ rel: "manifest", href: MANIFEST_PATH, crossOrigin: "use-credentials" }] : []),
147
+ ];
148
+ // The demo's listing before the runtime, whose demo bridge reads it as it starts.
149
+ const scripts = [
150
+ ...(head.demo ? [{ "data-zite-demo": "true", children: `window.__ziteDemo = ${scriptJson(head.demo)};` }] : []),
151
+ ...(head.runtimeUrl ? [{ src: head.runtimeUrl }] : []),
152
+ { "data-zite-branding": "true", children: `window.__ziteBranding = ${head.branding};` },
153
+ { "data-zite-analytics": "true", children: `window.__ziteAnalytics = ${scriptJson(head.analytics)};` },
154
+ ];
155
+ return {
156
+ ...own,
157
+ meta: [...platform(meta), ...ownMeta],
158
+ links: [...platform(links), ...ownLinks],
159
+ scripts: [...platform(scripts), ...(own?.scripts ?? [])],
160
+ };
161
+ };
162
+ /**
163
+ * A deeper route's head. The root rendered social metadata from the app's name; a route that sets its own title or
164
+ * description has the social metadata follow it, unless the app's settings or the app itself set it on the way down.
165
+ */
166
+ export const routeHead = (given, head, above) => {
167
+ const own = withoutReplaced(given, head);
168
+ const ownMeta = own?.meta ?? [];
169
+ const title = titleOf(ownMeta);
170
+ const description = descriptionOf(ownMeta);
171
+ if (!title && !description)
172
+ return own;
173
+ const appSet = new Set([...above.flatMap((match) => (Array.isArray(match.meta) ? match.meta : [])), ...ownMeta]
174
+ .filter((meta) => meta && !made.has(meta))
175
+ .map(metaKey));
176
+ const follow = [...(title ? followTitle(title) : []), ...(description ? followDescription(description) : [])].filter((meta) => !appSet.has(metaKey(meta)));
177
+ return follow.length ? { ...own, meta: [...platform(follow), ...ownMeta] } : own;
178
+ };
@@ -0,0 +1,24 @@
1
+ import { type AppTokenClaims } from "../internal/appToken.js";
2
+ import type { HostMode, HostProps, PlatformProvider, PlatformSession, PlatformUrls } from "./types.js";
3
+ export declare const ziteProvider: (props: HostProps, session: () => Promise<PlatformSession | undefined>) => PlatformProvider;
4
+ /** What `local` reads, documented in `zitejs`'s help. */
5
+ export declare const LOCAL_ENV: {
6
+ readonly token: "ZITE_DEV_TOKEN";
7
+ readonly apiKey: "ZITE_DEV_API_KEY";
8
+ readonly urls: "ZITE_URLS";
9
+ readonly user: "ZITE_DEV_USER";
10
+ };
11
+ type Env = Record<string, string | undefined>;
12
+ /** `ZITE_URLS`, or a throw saying what it must name. */
13
+ export declare const localUrls: (raw: string | undefined) => PlatformUrls;
14
+ /** The mode a dev token names; preview for one it doesn't. */
15
+ export declare const localModeOf: (claims: AppTokenClaims | undefined) => HostMode;
16
+ /** For tests: forget the minted dev token. */
17
+ export declare const resetDevToken: () => void;
18
+ export declare const mintDevToken: (backend: string, appId: string, apiKey: string) => Promise<string>;
19
+ /**
20
+ * `local` when the developer set a dev token, or a key to mint them with, else undefined. Throws on env it can't read,
21
+ * so a typo fails loudly rather than signing nobody in.
22
+ */
23
+ export declare const localPlatform: (env?: Env, appId?: string | null) => PlatformProvider | undefined;
24
+ export {};