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,159 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.localPlatform = exports.mintDevToken = exports.resetDevToken = exports.localModeOf = exports.localUrls = exports.LOCAL_ENV = exports.ziteProvider = void 0;
4
+ // The one place zitejs knows where the platform is. `zite`: Zite's dispatcher hands each request its app token, the
5
+ // platform's URLs and who is calling, in props. `local`: a developer's machine, with a dev token the backend minted.
6
+ const appToken_js_1 = require("../internal/appToken.js");
7
+ const platformFetch_js_1 = require("../internal/platformFetch.js");
8
+ const devApp_js_1 = require("./devApp.js");
9
+ // A streamed answer can outlive the request's deadline, which the token's expiry follows.
10
+ const RENEW_WITHIN_MS = 30_000;
11
+ const expiresWithin = (token, ms) => {
12
+ const claims = (0, appToken_js_1.appTokenClaims)(token);
13
+ return claims !== undefined && claims.exp * 1000 - Date.now() < ms;
14
+ };
15
+ const URL_NAMES = ["baseRunner", "backend", "aiGateway", "runs", "email", "pdf", "uploads", "steps"];
16
+ // `local` may leave out the AI gateway (a call on Zite's AI key is then refused), `runs` (a preview sends no analytics,
17
+ // and `local` keeps no run detail) and each service's own URL (the backend then answers it).
18
+ const OPTIONAL_URLS = new Set(["aiGateway", "runs", "email", "pdf", "uploads", "steps"]);
19
+ const trimmed = (urls) => Object.fromEntries(URL_NAMES.flatMap((name) => (urls[name] ? [[name, urls[name].replace(/\/+$/, "")]] : [])));
20
+ const ziteProvider = (props, session) => {
21
+ let current = props.appToken;
22
+ let renewing;
23
+ const renew = async () => {
24
+ try {
25
+ const fresh = await (await session())?.appToken?.();
26
+ return typeof fresh === "string" && fresh ? fresh : undefined;
27
+ }
28
+ catch (error) {
29
+ // A host that predates renewal: the token holds until it expires.
30
+ console.error("[zite] couldn't renew the app token", error);
31
+ return undefined;
32
+ }
33
+ };
34
+ return {
35
+ kind: "zite",
36
+ urls: props.urls && trimmed(props.urls),
37
+ user: () => props.user,
38
+ token: async () => {
39
+ if (!current || !expiresWithin(current, RENEW_WITHIN_MS))
40
+ return current;
41
+ renewing ??= renew().finally(() => (renewing = undefined));
42
+ current = (await renewing) ?? current;
43
+ return current;
44
+ },
45
+ };
46
+ };
47
+ exports.ziteProvider = ziteProvider;
48
+ /** What `local` reads, documented in `zitejs`'s help. */
49
+ exports.LOCAL_ENV = { token: "ZITE_DEV_TOKEN", apiKey: "ZITE_DEV_API_KEY", urls: "ZITE_URLS", user: "ZITE_DEV_USER" };
50
+ const processEnv = () => globalThis.process?.env;
51
+ /** `ZITE_URLS`, or a throw saying what it must name. */
52
+ const localUrls = (raw) => {
53
+ let parsed;
54
+ try {
55
+ parsed = JSON.parse(raw ?? "");
56
+ }
57
+ catch {
58
+ parsed = undefined;
59
+ }
60
+ const given = (parsed ?? {});
61
+ const isUrl = (value) => typeof value === "string" && /^https?:\/\//.test(value);
62
+ if (URL_NAMES.some((name) => (given[name] === undefined ? !OPTIONAL_URLS.has(name) : !isUrl(given[name])))) {
63
+ throw new Error(`${exports.LOCAL_ENV.urls} must be JSON naming the baseRunner and backend URLs, and may name aiGateway, runs, email, pdf, uploads and steps`);
64
+ }
65
+ return trimmed(given);
66
+ };
67
+ exports.localUrls = localUrls;
68
+ const localUser = (raw) => {
69
+ if (!raw)
70
+ return null;
71
+ let given;
72
+ try {
73
+ given = JSON.parse(raw);
74
+ }
75
+ catch {
76
+ given = undefined;
77
+ }
78
+ if (typeof given?.id !== "string" || typeof given.email !== "string") {
79
+ throw new Error(`${exports.LOCAL_ENV.user} must be JSON with the stand-in user's id and email`);
80
+ }
81
+ const roles = Array.isArray(given.roles) ? given.roles : [];
82
+ return {
83
+ id: given.id,
84
+ email: given.email,
85
+ name: typeof given.name === "string" ? given.name : given.email,
86
+ roles: roles.map((role) => (typeof role === "string" ? { id: role, name: role } : role)),
87
+ isInternal: given.isInternal === true,
88
+ };
89
+ };
90
+ const MODES = new Set(["live", "preview", "demo"]);
91
+ /** The mode a dev token names; preview for one it doesn't. */
92
+ const localModeOf = (claims) => MODES.has(claims?.mode) ? claims?.mode : "preview";
93
+ exports.localModeOf = localModeOf;
94
+ // The backend mints them for 15 minutes.
95
+ const RENEW_DEV_TOKEN_WITHIN_MS = 60_000;
96
+ const MINT_TIMEOUT_MS = 10_000;
97
+ // Per isolate, only a minted token, never a pending mint: Workers ties a request's I/O to that request.
98
+ let held;
99
+ /** For tests: forget the minted dev token. */
100
+ const resetDevToken = () => {
101
+ held = undefined;
102
+ };
103
+ exports.resetDevToken = resetDevToken;
104
+ const mintDevToken = async (backend, appId, apiKey) => {
105
+ const response = await (0, platformFetch_js_1.platformFetch)(new Request(`${backend}/v1/start/apps/${encodeURIComponent(appId)}/dev-token`, {
106
+ method: "POST",
107
+ headers: { authorization: `Bearer ${apiKey}` },
108
+ signal: AbortSignal.timeout(MINT_TIMEOUT_MS),
109
+ }));
110
+ const answer = (await response.json().catch(() => null));
111
+ if (response.ok && typeof answer?.token === "string")
112
+ return answer.token;
113
+ const why = [answer?.message, answer?.error].find((text) => typeof text === "string");
114
+ throw new Error(`The backend didn't mint a dev token for app ${appId} with ${exports.LOCAL_ENV.apiKey}: ${response.status}${why ? ` ${why}` : ""}`);
115
+ };
116
+ exports.mintDevToken = mintDevToken;
117
+ /** The app's dev token, minted with the developer's key, and minted again when it's about to expire. */
118
+ const mintedDevToken = (backend, appId, apiKey) => {
119
+ const key = `${backend} ${appId} ${apiKey}`;
120
+ let minting;
121
+ return async () => {
122
+ const current = held?.key === key ? held.token : undefined;
123
+ if (current && !expiresWithin(current, RENEW_DEV_TOKEN_WITHIN_MS))
124
+ return current;
125
+ minting ??= (0, exports.mintDevToken)(backend, appId, apiKey).finally(() => (minting = undefined));
126
+ try {
127
+ const token = await minting;
128
+ held = { key, token };
129
+ return token;
130
+ }
131
+ catch (error) {
132
+ if (!current || expiresWithin(current, 0))
133
+ throw error;
134
+ console.error("[zite] couldn't renew the dev token; using the one held until it expires", error);
135
+ return current;
136
+ }
137
+ };
138
+ };
139
+ // A given dev token is used as it is. A key mints them only under `vite dev`, which knows the app's id.
140
+ const localToken = (env, appId) => {
141
+ const given = env[exports.LOCAL_ENV.token];
142
+ if (given)
143
+ return () => async () => given;
144
+ const apiKey = env[exports.LOCAL_ENV.apiKey];
145
+ return apiKey && appId ? (backend) => mintedDevToken(backend, appId, apiKey) : undefined;
146
+ };
147
+ /**
148
+ * `local` when the developer set a dev token, or a key to mint them with, else undefined. Throws on env it can't read,
149
+ * so a typo fails loudly rather than signing nobody in.
150
+ */
151
+ const localPlatform = (env = processEnv() ?? {}, appId = devApp_js_1.devAppId) => {
152
+ const token = localToken(env, appId);
153
+ if (!token)
154
+ return undefined;
155
+ const urls = (0, exports.localUrls)(env[exports.LOCAL_ENV.urls]);
156
+ const user = localUser(env[exports.LOCAL_ENV.user]);
157
+ return { kind: "local", urls, user: () => user, token: token(urls.backend) };
158
+ };
159
+ exports.localPlatform = localPlatform;
@@ -0,0 +1,320 @@
1
+ import type { AiUsageRecord } from "./aiUsage.js";
2
+ export type Role = {
3
+ id: string;
4
+ name: string;
5
+ };
6
+ /** As classic's `context.user`, plus `name`. */
7
+ export type User = {
8
+ id: string;
9
+ email: string;
10
+ /** First and last name, or the email when neither is set. */
11
+ name: string;
12
+ firstName?: string;
13
+ lastName?: string;
14
+ /** The built-in roles, then the ones assigned on the Members tab. */
15
+ roles: ReadonlyArray<Role>;
16
+ /** A member of the workspace's team, not an external user. */
17
+ isInternal: boolean;
18
+ };
19
+ /** One server function call, as the platform's run log shows it. Input and output are truncated JSON. */
20
+ export type RunRecord = {
21
+ fn: string;
22
+ name?: string;
23
+ nested: boolean;
24
+ startedAt: number;
25
+ durationMs: number;
26
+ input?: string;
27
+ output?: string;
28
+ error?: {
29
+ code: string;
30
+ message: string;
31
+ stack?: string;
32
+ };
33
+ /** A workflow's steps, as they ran, replayed or failed. */
34
+ steps?: {
35
+ name: string;
36
+ status: "ran" | "memoized" | "failed";
37
+ durationMs?: number;
38
+ at: number;
39
+ }[];
40
+ /** The step a failed workflow stopped in, where a resume picks up. */
41
+ failedStep?: string;
42
+ };
43
+ export type AccessKind = "signedIn" | "anyone" | "webhook" | "workflow";
44
+ /** One data, integration or email call. Who is calling is the platform's to know, never the app's to say. */
45
+ export type PlatformCallInput = {
46
+ integrationId: string;
47
+ className: string;
48
+ methodName: string;
49
+ params: unknown;
50
+ /** The access decision the call ran under; the platform may narrow on it but never widens. */
51
+ access: AccessKind;
52
+ };
53
+ /**
54
+ * A call's answer. Errors come back as values: Workers RPC keeps a thrown
55
+ * error's message but drops its code.
56
+ */
57
+ export type PlatformCallResult = {
58
+ value: unknown;
59
+ } | {
60
+ error: {
61
+ code: string;
62
+ message: string;
63
+ userFacingMessage?: string;
64
+ };
65
+ };
66
+ /** One data call the app's own dispatch made, for its run's detail. */
67
+ export type CallRecord = {
68
+ integrationId: string;
69
+ className: string;
70
+ methodName: string;
71
+ at: number;
72
+ durationMs: number;
73
+ inputs?: string;
74
+ outputs?: string;
75
+ error?: {
76
+ code: string;
77
+ message: string;
78
+ };
79
+ };
80
+ /** An outbound fetch, by host and path (never its query), with the connection whose token it carried. */
81
+ export type FetchRecord = {
82
+ at: number;
83
+ method: string;
84
+ /** Whole, with every secret the request knows redacted. */
85
+ url: string;
86
+ /** As classic's run log shows it: cut short, secrets redacted. */
87
+ requestBody?: string;
88
+ status?: number;
89
+ durationMs: number;
90
+ error?: string;
91
+ connection?: string;
92
+ /** Sent again with a refreshed token after a 401. */
93
+ retried?: true;
94
+ /** On Zite's own AI key, which the platform meters itself. */
95
+ ziteAi?: true;
96
+ /** What a call on the org's own AI key used, for analytics. */
97
+ ai?: AiUsageRecord;
98
+ };
99
+ export type PlatformSession = {
100
+ call(call: PlatformCallInput): Promise<PlatformCallResult>;
101
+ /** As `PlatformBinding.runs`, on a session the request already holds, with its data calls and fetches. */
102
+ runs(batch: {
103
+ runs: RunRecord[];
104
+ calls?: CallRecord[];
105
+ fetches?: FetchRecord[];
106
+ }): Promise<void>;
107
+ /** After a provider answered 401: the connection refreshed, as `integrations.get` now answers it. */
108
+ refreshConnection(name: string): Promise<PlatformCallResult>;
109
+ /** A call on Zite's own AI key, which the host makes with the real key: for a request with no token or gateway. */
110
+ aiFetch(request: Request): Promise<Response>;
111
+ /** The build's base and SDK names, which the app's data dispatch translates against. */
112
+ dataContext(): Promise<{
113
+ baseId: string | null;
114
+ nameMappings: unknown;
115
+ }>;
116
+ /** One base-runner request; the host holds it to the build's base and adds the key and acting user. */
117
+ dataFetch(request: {
118
+ method: string;
119
+ path: string;
120
+ body?: string;
121
+ }): Promise<Response>;
122
+ /** An integration's settings as the build declares them; null for one it doesn't, or that runs on the platform. */
123
+ integrationSettings(integrationId: string): Promise<{
124
+ serviceType: string;
125
+ baseId?: string;
126
+ nameMappings?: unknown;
127
+ } | null>;
128
+ /** A new app token for this request, when the one it holds is about to expire. */
129
+ appToken?(): Promise<string>;
130
+ };
131
+ /**
132
+ * Where the platform's services answer this app: `aiGateway` takes calls on Zite's AI key, `runs` a live page's
133
+ * analytics and each request's run detail. `email`, `pdf`, `uploads` (the upload session) and `steps` (a workflow
134
+ * run's saved steps) are each that service's own endpoint, which the platform picks per workspace; without one, the
135
+ * backend's route answers it.
136
+ */
137
+ export type PlatformUrls = {
138
+ baseRunner: string;
139
+ backend: string;
140
+ aiGateway?: string;
141
+ runs?: string;
142
+ email?: string;
143
+ pdf?: string;
144
+ uploads?: string;
145
+ steps?: string;
146
+ };
147
+ /**
148
+ * Where the platform is for one request, and what reaches it: Zite's dispatcher through props, or a developer's
149
+ * machine through env. The only zitejs code that knows which.
150
+ */
151
+ export type PlatformProvider = {
152
+ kind: "zite" | "local";
153
+ /** The request's app token, renewed when it's about to expire; undefined when the host sent none. */
154
+ token(): Promise<string | undefined>;
155
+ user(): User | null;
156
+ urls: PlatformUrls | undefined;
157
+ };
158
+ /** What the host hands each request: its platform, already scoped to the app, build, request and user. */
159
+ export type PlatformBinding = {
160
+ /** Every platform call of one request goes through one session. */
161
+ session(): PlatformSession | Promise<PlatformSession>;
162
+ /** One batch per request, after its response has ended. */
163
+ runs(batch: {
164
+ runs: RunRecord[];
165
+ }): Promise<void>;
166
+ };
167
+ /** A demo is the published build serving a read-only visitor: as live, but every write is refused. */
168
+ export type HostMode = "live" | "preview" | "demo" | "validate";
169
+ /**
170
+ * The build's page settings, as the platform baked them at publish from the app's settings and name. What the settings
171
+ * set (`seo*`, `favicon`, an installable app's) replaces what a page sets; the rest fills what it leaves out.
172
+ */
173
+ export type PagePlan = {
174
+ fallbackTitle: string;
175
+ seoTitle?: string;
176
+ fallbackDescription: string;
177
+ seoDescription?: string;
178
+ /** A social image: the app's thumbnail, else its screenshot. */
179
+ image?: string;
180
+ seoImage?: string;
181
+ favicon?: string;
182
+ /** For a page with no icon of its own and none configured. */
183
+ defaultFavicon: string;
184
+ /** An installable app's; unset otherwise. */
185
+ appleTouchIcon?: string;
186
+ /** Served at `/manifest.webmanifest` when the app is installable. */
187
+ manifest: {
188
+ theme_color: string;
189
+ short_name: string;
190
+ } | null;
191
+ };
192
+ /** A marketplace demo's listing, which the platform's runtime shows the visitor. */
193
+ export type DemoListing = {
194
+ listingSlug: string;
195
+ listingUrl: string;
196
+ };
197
+ /** What the platform adds to every page's head. A host that sends none writes its tags into the HTML itself. */
198
+ export type HostPage = {
199
+ plan: PagePlan;
200
+ /** The platform's runtime script, which the editor's preview and the badge run on. */
201
+ runtimeUrl?: string;
202
+ demo?: DemoListing;
203
+ };
204
+ /** The platform's head entries for one request, as the page renders them and carries them to the browser. */
205
+ export type PlatformHead = {
206
+ title: string;
207
+ description: string;
208
+ image?: string;
209
+ icon: string;
210
+ /** Which of those the app's settings set, so they replace what a page sets. */
211
+ fromSettings: {
212
+ title: boolean;
213
+ description: boolean;
214
+ image: boolean;
215
+ icon: boolean;
216
+ };
217
+ /** An installable app's, which replaces a page's own as its manifest and app metadata do. */
218
+ appleTouchIcon?: string;
219
+ manifest?: {
220
+ themeColor: string;
221
+ shortName: string;
222
+ };
223
+ runtimeUrl?: string;
224
+ demo?: DemoListing;
225
+ /** Zite's badge, as the org's plan says. */
226
+ branding: boolean;
227
+ analytics: {
228
+ appId: string;
229
+ enabled: boolean;
230
+ endpointUrl: string;
231
+ };
232
+ };
233
+ export type HostInvoke = {
234
+ kind: "webhook" | "describe" | "workflow" | "register" | "warm" | "authHook" | "function";
235
+ name: string;
236
+ };
237
+ /** The per-request props the host dispatches with. Only the host can set them. */
238
+ export type HostProps = {
239
+ platform: PlatformBinding;
240
+ requestId: string;
241
+ user: User | null;
242
+ mode: HostMode;
243
+ invoke: HostInvoke | null;
244
+ /** The app's live URL, demo included: `process.env.ZITE_APP_URL`. */
245
+ appUrl?: string;
246
+ /** The app's database: `process.env.ZITE_BASE_ID`. */
247
+ baseId?: string;
248
+ /** An editor preview's access, which zitejs keeps on the app's links and calls. */
249
+ previewClaim?: string;
250
+ /** `process.env` as classic sets it: connections' vars, then the user's own secrets. */
251
+ env?: Record<string, string>;
252
+ /** Which connection each token var in `env` holds. */
253
+ envConnections?: Record<string, string>;
254
+ /** Each connection's service, which the calls made with its token are counted under. */
255
+ connectionServices?: Record<string, string>;
256
+ /** A resumed run's first attempt, whose saved steps it replays. */
257
+ runRoot?: string;
258
+ /** This request's app token, sent only to `urls`. */
259
+ appToken?: string;
260
+ urls?: PlatformUrls;
261
+ /** Sent with a page or route request by a host that leaves its head to zitejs. */
262
+ page?: HostPage;
263
+ /** The app's access mode, from the platform's records: an internal app serves no page or call to nobody. */
264
+ accessMode?: "internal" | "external";
265
+ };
266
+ /** What the host resolved for this request. Set by the generated server entry, never by the browser. */
267
+ export type HostRequestState = {
268
+ requestId: string;
269
+ url: string;
270
+ user: User | null;
271
+ mode: HostMode;
272
+ invoke: HostInvoke | null;
273
+ appUrl?: string;
274
+ baseId?: string;
275
+ previewClaim?: string;
276
+ /** Classic's connection env vars the host sent, set into `process.env` for the request. */
277
+ env?: Record<string, string>;
278
+ envConnections?: Record<string, string>;
279
+ connectionServices?: Record<string, string>;
280
+ /** A resumed run's first attempt, whose saved steps it replays. */
281
+ runRoot?: string;
282
+ /** The connection each token this request was handed belongs to. */
283
+ connectionTokens?: Map<string, string>;
284
+ /** `integrations.get`'s answers this request, by name. */
285
+ connectionAnswers?: Map<string, unknown>;
286
+ /** One refresh per connection per request, however many calls got a 401. */
287
+ refreshing?: Map<string, Promise<string | undefined>>;
288
+ /** The outbound fetches, flushed with its runs. */
289
+ fetches?: FetchRecord[];
290
+ /** The secrets its fetch log redacts, longest first; cleared when a connection is learned. */
291
+ secretValues?: string[];
292
+ /** The isolate's refresh count `secretValues` was read at. */
293
+ secretsAt?: number;
294
+ /** How much of its fetch log is bodies so far. */
295
+ fetchLogChars?: number;
296
+ /** Filled by run capture, flushed to the platform once the response ends. */
297
+ runs: RunRecord[];
298
+ /** The data calls this request made, flushed with its runs. */
299
+ calls?: CallRecord[];
300
+ /** This request's Airtable reads, so the same one twice goes out once. */
301
+ airtableReads?: Map<string, Promise<unknown>>;
302
+ /** Records still reading a copy of a body; the flush waits for them. */
303
+ pending?: Promise<void>[];
304
+ platform?: PlatformBinding;
305
+ session?: Promise<PlatformSession>;
306
+ provider?: PlatformProvider;
307
+ /** The request context's, which keeps a send going after the response. */
308
+ waitUntil?: (promise: Promise<unknown>) => void;
309
+ /** This request's direct base-runner calls in flight, capped as the host's relay capped them. */
310
+ dataSlots?: {
311
+ data: () => Promise<() => void>;
312
+ sql: () => Promise<() => void>;
313
+ };
314
+ /** This request's calls on Zite's AI key waiting on the gateway's answer, capped as the host's relay capped them. */
315
+ aiSlots?: () => Promise<() => void>;
316
+ /** This request's router, so a page's status can follow the error it rendered. */
317
+ router?: unknown;
318
+ /** The platform's head entries for its pages; unset when the host writes them itself. */
319
+ head?: PlatformHead;
320
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -7,6 +7,8 @@ exports.useUpload = useUpload;
7
7
  const react_1 = require("react");
8
8
  const config_js_1 = require("../auth/config.js");
9
9
  const appMode_js_1 = require("../internal/appMode.js");
10
+ const platformFetch_js_1 = require("../internal/platformFetch.js");
11
+ const serviceUrls_js_1 = require("../internal/serviceUrls.js");
10
12
  const constants_js_1 = require("../auth/constants.js");
11
13
  class FileUploadError extends Error {
12
14
  constructor(message) {
@@ -90,22 +92,76 @@ function authHeaders() {
90
92
  : null;
91
93
  return token ? { Authorization: 'Bearer ' + token } : {};
92
94
  }
93
- async function performUpload(data, filename) {
94
- const blob = toUploadBlob(data);
95
+ // On Start the session's answer says whether to complete, and where. No credential goes with it, so the app token never
96
+ // reaches an origin the platform didn't name in the app's props.
97
+ const startCompletion = session => session.completeUrl ? { url: session.completeUrl, headers: {} } : undefined;
98
+ /** On a Start server holding an app token: the platform's uploads service, which reads the app and mode from the token. */
99
+ async function tokenRoutes() {
100
+ const provider = (0, appMode_js_1.platformProvider)();
101
+ const urls = provider?.urls;
102
+ const token = urls ? await provider?.token() : undefined;
103
+ if (!urls || !token)
104
+ return undefined;
105
+ return {
106
+ session: body => (0, platformFetch_js_1.platformFetch)(new Request((0, serviceUrls_js_1.serviceUrl)(urls, 'uploads'), {
107
+ method: 'POST',
108
+ headers: {
109
+ 'Content-Type': 'application/json',
110
+ Authorization: 'Bearer ' + token,
111
+ },
112
+ body,
113
+ })),
114
+ completion: startCompletion,
115
+ };
116
+ }
117
+ /** In a Start page: the app's own server, which asks the platform on its request's token, in the mode it was served. */
118
+ function pageRoutes() {
119
+ if (typeof window === 'undefined' || !(0, appMode_js_1.platformMode)())
120
+ return undefined;
121
+ return {
122
+ session: body => fetch(serviceUrls_js_1.UPLOAD_SESSION_PATH, {
123
+ method: 'POST',
124
+ headers: { 'Content-Type': 'application/json' },
125
+ body,
126
+ }),
127
+ completion: startCompletion,
128
+ };
129
+ }
130
+ /** A classic app's, and a Start server's on a host that sent no token. */
131
+ function publicRoutes() {
95
132
  const mode = getZiteAppMode();
96
133
  const flowId = (0, config_js_1.getFlowId)();
97
- const sessionRes = await fetch((0, config_js_1.getApiUrl)() + '/v1/zite/public/' + flowId + '/upload-session?mode=' + mode, {
98
- method: 'POST',
99
- headers: {
100
- 'Content-Type': 'application/json',
101
- ...authHeaders(),
102
- },
103
- body: JSON.stringify({
104
- filename,
105
- uploadLength: blob.size,
106
- contentType: blob.type || 'application/octet-stream',
134
+ return {
135
+ session: body => fetch((0, config_js_1.getApiUrl)() + '/v1/zite/public/' + flowId + '/upload-session?mode=' + mode, {
136
+ method: 'POST',
137
+ headers: {
138
+ 'Content-Type': 'application/json',
139
+ ...authHeaders(),
140
+ },
141
+ body,
107
142
  }),
108
- });
143
+ // Gateways that predate the storage ledger omit the token. The file is
144
+ // already at fileUrl, so those uploads still succeed.
145
+ completion: session => session.completionToken
146
+ ? {
147
+ url: (0, config_js_1.getApiUrl)() +
148
+ '/v1/zite/public/' +
149
+ flowId +
150
+ '/complete-upload?mode=' +
151
+ mode,
152
+ headers: authHeaders(),
153
+ }
154
+ : undefined,
155
+ };
156
+ }
157
+ async function performUpload(data, filename) {
158
+ const blob = toUploadBlob(data);
159
+ const routes = (await tokenRoutes()) ?? pageRoutes() ?? publicRoutes();
160
+ const sessionRes = await routes.session(JSON.stringify({
161
+ filename,
162
+ uploadLength: blob.size,
163
+ contentType: blob.type || 'application/octet-stream',
164
+ }));
109
165
  if (!sessionRes.ok) {
110
166
  throw new FileUploadError(await readErrorMessage(sessionRes, 'Upload failed'));
111
167
  }
@@ -123,18 +179,13 @@ async function performUpload(data, filename) {
123
179
  if (!putRes.ok) {
124
180
  throw new FileUploadError('Upload failed');
125
181
  }
126
- // Gateways that predate the storage ledger omit the token. The file is
127
- // already at fileUrl, so those uploads still succeed.
128
- if (session.completionToken) {
129
- const completeRes = await fetch((0, config_js_1.getApiUrl)() +
130
- '/v1/zite/public/' +
131
- flowId +
132
- '/complete-upload?mode=' +
133
- mode, {
182
+ const completion = routes.completion(session);
183
+ if (completion) {
184
+ const completeRes = await fetch(completion.url, {
134
185
  method: 'POST',
135
186
  headers: {
136
187
  'Content-Type': 'application/json',
137
- ...authHeaders(),
188
+ ...completion.headers,
138
189
  },
139
190
  body: JSON.stringify({ completionToken: session.completionToken }),
140
191
  });
@@ -95,6 +95,39 @@ const fetchMock = vitest_1.vi.fn();
95
95
  await (0, vitest_1.expect)(upload).rejects.toThrow('File size exceeds maximum of 20 MB');
96
96
  });
97
97
  });
98
+ (0, vitest_1.describe)("a Start page's upload", () => {
99
+ (0, vitest_1.afterEach)(() => (0, appMode_js_1.keepRenderedMode)(undefined));
100
+ const answer = (session) => {
101
+ fetchMock
102
+ .mockResolvedValueOnce({ ok: true, json: async () => ({ success: true, presignedUrl: 'https://s3.example.com/put', fileUrl: 'https://uploads.zite.com/f.txt', ...session }) })
103
+ .mockResolvedValueOnce({ ok: true })
104
+ .mockResolvedValueOnce({ ok: true, json: async () => ({ success: true }) });
105
+ };
106
+ (0, vitest_1.it)("asks the page's own origin, with no credential, and never the API host", async () => {
107
+ vitest_1.vi.stubGlobal('localStorage', { getItem: () => 'classic-session-token' });
108
+ (0, appMode_js_1.keepRenderedMode)('live');
109
+ answer({});
110
+ await (0, index_js_1.uploadFile)({ data: 'hello', filename: 'a.txt' });
111
+ (0, vitest_1.expect)(fetchMock.mock.calls.map(([url]) => String(url))).toEqual(['/__zite/uploads/session', 'https://s3.example.com/put']);
112
+ const [, init] = fetchMock.mock.calls[0];
113
+ (0, vitest_1.expect)(init.headers).toEqual({ 'Content-Type': 'application/json' });
114
+ (0, vitest_1.expect)(JSON.parse(init.body)).toEqual({ filename: 'a.txt', uploadLength: 5, contentType: 'text/plain' });
115
+ });
116
+ (0, vitest_1.it)('completes only where the answer names, with its completion token and no other credential', async () => {
117
+ vitest_1.vi.stubGlobal('localStorage', { getItem: () => 'classic-session-token' });
118
+ (0, appMode_js_1.keepRenderedMode)('live');
119
+ answer({ completeUrl: 'https://uploads.example.com/complete', completionToken: 'ct1' });
120
+ await (0, index_js_1.uploadFile)({ data: 'hello', filename: 'a.txt' });
121
+ const [url, init] = fetchMock.mock.calls[2];
122
+ (0, vitest_1.expect)(url).toBe('https://uploads.example.com/complete');
123
+ (0, vitest_1.expect)(init.headers).toEqual({ 'Content-Type': 'application/json' });
124
+ (0, vitest_1.expect)(JSON.parse(init.body)).toEqual({ completionToken: 'ct1' });
125
+ fetchMock.mockReset();
126
+ answer({ completionToken: 'ct2' });
127
+ await (0, index_js_1.uploadFile)({ data: 'hello', filename: 'a.txt' });
128
+ (0, vitest_1.expect)(fetchMock).toHaveBeenCalledTimes(2);
129
+ });
130
+ });
98
131
  // SDK-10: a Start app's mode is the platform's, never guessed from where the page is served.
99
132
  (0, vitest_1.describe)('the mode an upload goes under', () => {
100
133
  const sessionUrl = async () => {
@@ -107,9 +140,9 @@ const fetchMock = vitest_1.vi.fn();
107
140
  return String(fetchMock.mock.calls[0][0]);
108
141
  };
109
142
  (0, vitest_1.afterEach)(() => (0, appMode_js_1.keepRenderedMode)(undefined));
110
- (0, vitest_1.it)('is the one the page was rendered in, on any host', async () => {
143
+ (0, vitest_1.it)("in a Start page, is the one the app's own server is asked in, not a query the page writes", async () => {
111
144
  (0, appMode_js_1.keepRenderedMode)('preview');
112
- (0, vitest_1.expect)(await sessionUrl()).toContain('mode=preview');
145
+ (0, vitest_1.expect)(await sessionUrl()).toBe('/__zite/uploads/session');
113
146
  });
114
147
  (0, vitest_1.it)("is the request's own on the server, where there's no page", async () => {
115
148
  vitest_1.vi.stubGlobal('window', undefined);
@@ -5,7 +5,7 @@ export declare const authClient: import("better-auth/react").ReactAuthClient<{
5
5
  plugins: ({
6
6
  id: "magic-link";
7
7
  version: string;
8
- $InferServerPlugin: ReturnType<(options: import("better-auth/plugins").MagicLinkOptions) => {
8
+ $InferServerPlugin: ReturnType<(options: import("better-auth/plugins/magic-link").MagicLinkOptions) => {
9
9
  id: "magic-link";
10
10
  version: string;
11
11
  endpoints: {
@@ -110,7 +110,7 @@ export declare const authClient: import("better-auth/react").ReactAuthClient<{
110
110
  window: number;
111
111
  max: number;
112
112
  }[];
113
- options: import("better-auth/plugins").MagicLinkOptions;
113
+ options: import("better-auth/plugins/magic-link").MagicLinkOptions;
114
114
  }>;
115
115
  } | {
116
116
  id: "additional-fields-client";