zitejs 0.10.0-start.2 → 0.10.0-start.20

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 (171) hide show
  1. package/dist/cjs/auth/index.d.ts +2 -2
  2. package/dist/cjs/auth/index.js +6 -0
  3. package/dist/cjs/auth/index.test.js +30 -0
  4. package/dist/cjs/auth/previewClaim.d.ts +7 -0
  5. package/dist/cjs/auth/previewClaim.js +16 -0
  6. package/dist/cjs/backend/index.d.ts +121 -3
  7. package/dist/cjs/backend/index.test.js +58 -0
  8. package/dist/cjs/bundle/index.d.ts +8 -0
  9. package/dist/cjs/bundle/index.js +9 -8
  10. package/dist/cjs/check/index.d.ts +45 -1
  11. package/dist/cjs/check/index.js +198 -109
  12. package/dist/cjs/check/start/problem.d.ts +11 -0
  13. package/dist/cjs/check/start/problem.js +5 -0
  14. package/dist/cjs/check/start/routeTree.d.ts +9 -0
  15. package/dist/cjs/check/start/routeTree.js +111 -0
  16. package/dist/cjs/check/start/sourceRules.d.ts +8 -0
  17. package/dist/cjs/check/start/sourceRules.js +1110 -0
  18. package/dist/cjs/check/start/tsgo.d.ts +2 -0
  19. package/dist/cjs/check/start/tsgo.js +35 -0
  20. package/dist/cjs/cli.js +1 -1
  21. package/dist/cjs/client/index.d.ts +24 -0
  22. package/dist/cjs/dev/index.js +14 -4
  23. package/dist/cjs/integrations/rules.d.ts +13 -0
  24. package/dist/cjs/integrations/rules.js +29 -0
  25. package/dist/cjs/integrations/rules.test.js +1 -0
  26. package/dist/cjs/internal/appMode.d.ts +3 -0
  27. package/dist/cjs/internal/appMode.js +15 -0
  28. package/dist/cjs/runtime/index.d.ts +13 -13
  29. package/dist/cjs/start/entries.d.ts +10 -4
  30. package/dist/cjs/start/entries.js +23 -6
  31. package/dist/cjs/steps/index.d.ts +78 -0
  32. package/dist/cjs/steps/index.js +507 -0
  33. package/dist/cjs/steps/index.test.d.ts +1 -0
  34. package/dist/cjs/steps/index.test.js +635 -0
  35. package/dist/cjs/sync/index.js +2 -1
  36. package/dist/cjs/sync/lib.d.ts +10 -3
  37. package/dist/cjs/sync/lib.js +35 -21
  38. package/dist/cjs/sync/lib.test.js +106 -36
  39. package/dist/cjs/types/fields.d.ts +8 -1
  40. package/dist/cjs/types/fields.js +7 -1
  41. package/dist/cjs/types/tables.d.ts +16 -0
  42. package/dist/cjs/upload/index.js +12 -2
  43. package/dist/cjs/upload/index.test.js +39 -0
  44. package/dist/cjs/vite/index.js +8 -3
  45. package/dist/cjs/vite/index.test.js +10 -2
  46. package/dist/esm/auth/index.d.ts +2 -2
  47. package/dist/esm/auth/index.js +6 -0
  48. package/dist/esm/auth/index.test.js +30 -0
  49. package/dist/esm/auth/previewClaim.d.ts +7 -0
  50. package/dist/esm/auth/previewClaim.js +12 -0
  51. package/dist/esm/backend/index.d.ts +121 -3
  52. package/dist/esm/backend/index.test.js +58 -0
  53. package/dist/esm/bundle/index.d.ts +8 -0
  54. package/dist/esm/bundle/index.js +8 -8
  55. package/dist/esm/check/index.d.ts +45 -1
  56. package/dist/esm/check/index.js +198 -113
  57. package/dist/esm/check/start/problem.d.ts +11 -0
  58. package/dist/esm/check/start/problem.js +1 -0
  59. package/dist/esm/check/start/routeTree.d.ts +9 -0
  60. package/dist/esm/check/start/routeTree.js +70 -0
  61. package/dist/esm/check/start/sourceRules.d.ts +8 -0
  62. package/dist/esm/check/start/sourceRules.js +1107 -0
  63. package/dist/esm/check/start/tsgo.d.ts +2 -0
  64. package/dist/esm/check/start/tsgo.js +29 -0
  65. package/dist/esm/cli.js +1 -1
  66. package/dist/esm/client/index.d.ts +24 -0
  67. package/dist/esm/dev/index.js +16 -6
  68. package/dist/esm/integrations/rules.d.ts +13 -0
  69. package/dist/esm/integrations/rules.js +29 -0
  70. package/dist/esm/integrations/rules.test.js +1 -0
  71. package/dist/esm/internal/appMode.d.ts +3 -0
  72. package/dist/esm/internal/appMode.js +10 -0
  73. package/dist/esm/runtime/index.d.ts +13 -13
  74. package/dist/esm/start/aiUsage.d.ts +23 -0
  75. package/dist/esm/start/aiUsage.js +146 -0
  76. package/dist/esm/start/airtable/arrayFields.d.ts +10 -0
  77. package/dist/esm/start/airtable/arrayFields.js +30 -0
  78. package/dist/esm/start/airtable/dispatch.d.ts +54 -0
  79. package/dist/esm/start/airtable/dispatch.js +483 -0
  80. package/dist/esm/start/airtable/formulas.d.ts +70 -0
  81. package/dist/esm/start/airtable/formulas.js +258 -0
  82. package/dist/esm/start/airtable/index.d.ts +8 -0
  83. package/dist/esm/start/airtable/index.js +54 -0
  84. package/dist/esm/start/authHooks.d.ts +7 -0
  85. package/dist/esm/start/authHooks.js +10 -0
  86. package/dist/esm/start/authHooksModule.d.ts +1 -0
  87. package/dist/esm/start/authHooksModule.js +3 -0
  88. package/dist/esm/start/clientErrorMessage.test.d.ts +1 -0
  89. package/dist/esm/start/clientErrorMessage.test.js +105 -0
  90. package/dist/esm/start/credentials.d.ts +2 -0
  91. package/dist/esm/start/credentials.js +2 -0
  92. package/dist/esm/start/data/baseRunner.d.ts +92 -0
  93. package/dist/esm/start/data/baseRunner.js +83 -0
  94. package/dist/esm/start/data/dispatch.d.ts +16 -0
  95. package/dist/esm/start/data/dispatch.js +198 -0
  96. package/dist/esm/start/data/index.d.ts +15 -0
  97. package/dist/esm/start/data/index.js +58 -0
  98. package/dist/esm/start/data/sqlNameMappings.d.ts +58 -0
  99. package/dist/esm/start/data/sqlNameMappings.js +92 -0
  100. package/dist/esm/start/data/transformations.d.ts +97 -0
  101. package/dist/esm/start/data/transformations.js +262 -0
  102. package/dist/esm/start/data/types.d.ts +91 -0
  103. package/dist/esm/start/data/types.js +14 -0
  104. package/dist/esm/start/describe.d.ts +35 -5
  105. package/dist/esm/start/describe.js +74 -22
  106. package/dist/esm/start/entries.d.ts +10 -4
  107. package/dist/esm/start/entries.js +21 -5
  108. package/dist/esm/start/errors.d.ts +63 -0
  109. package/dist/esm/start/errors.js +146 -0
  110. package/dist/esm/start/errors.test.d.ts +1 -0
  111. package/dist/esm/start/errors.test.js +23 -0
  112. package/dist/esm/start/factories.test-d.d.ts +1 -0
  113. package/dist/esm/start/factories.test-d.js +20 -0
  114. package/dist/esm/start/index.d.ts +32 -27
  115. package/dist/esm/start/index.js +77 -47
  116. package/dist/esm/start/instance.d.ts +4 -4
  117. package/dist/esm/start/instance.js +54 -11
  118. package/dist/esm/start/outbound.d.ts +11 -0
  119. package/dist/esm/start/outbound.js +398 -0
  120. package/dist/esm/start/previewClaim.d.ts +7 -0
  121. package/dist/esm/start/previewClaim.js +23 -0
  122. package/dist/esm/start/problems.js +1 -1
  123. package/dist/esm/start/quiet.d.ts +2 -0
  124. package/dist/esm/start/quiet.js +27 -0
  125. package/dist/esm/start/redactSecrets.d.ts +15 -0
  126. package/dist/esm/start/redactSecrets.js +154 -0
  127. package/dist/esm/start/redactSecrets.test.d.ts +1 -0
  128. package/dist/esm/start/redactSecrets.test.js +151 -0
  129. package/dist/esm/start/registration.d.ts +13 -0
  130. package/dist/esm/start/registration.js +21 -0
  131. package/dist/esm/start/registrationHash.d.ts +22 -0
  132. package/dist/esm/start/registrationHash.js +470 -0
  133. package/dist/esm/start/router.d.ts +18 -4
  134. package/dist/esm/start/router.js +134 -11
  135. package/dist/esm/start/runLog.d.ts +7 -4
  136. package/dist/esm/start/runLog.js +64 -6
  137. package/dist/esm/start/scope.d.ts +2 -2
  138. package/dist/esm/start/server.d.ts +40 -36
  139. package/dist/esm/start/server.js +320 -48
  140. package/dist/esm/start/steps.d.ts +28 -0
  141. package/dist/esm/start/steps.js +97 -0
  142. package/dist/esm/start/types.d.ts +178 -5
  143. package/dist/esm/start/version.d.ts +1 -0
  144. package/dist/esm/start/version.js +2 -0
  145. package/dist/esm/start/vite.js +88 -11
  146. package/dist/esm/start/worker.d.ts +6 -0
  147. package/dist/esm/start/worker.js +12 -0
  148. package/dist/esm/start/workflow.d.ts +42 -12
  149. package/dist/esm/start/workflow.js +3 -3
  150. package/dist/esm/start/workflow.test-d.js +41 -8
  151. package/dist/esm/start/workflowModules.js +1 -1
  152. package/dist/esm/start/workflowRun.d.ts +21 -8
  153. package/dist/esm/start/workflowRun.js +29 -8
  154. package/dist/esm/steps/index.d.ts +78 -0
  155. package/dist/esm/steps/index.js +502 -0
  156. package/dist/esm/steps/index.test.d.ts +1 -0
  157. package/dist/esm/steps/index.test.js +633 -0
  158. package/dist/esm/sync/index.js +2 -1
  159. package/dist/esm/sync/lib.d.ts +10 -3
  160. package/dist/esm/sync/lib.js +35 -21
  161. package/dist/esm/sync/lib.test.js +106 -36
  162. package/dist/esm/types/fields.d.ts +8 -1
  163. package/dist/esm/types/fields.js +6 -0
  164. package/dist/esm/types/tables.d.ts +16 -0
  165. package/dist/esm/upload/index.js +12 -2
  166. package/dist/esm/upload/index.test.js +39 -0
  167. package/dist/esm/vite/index.js +8 -3
  168. package/dist/esm/vite/index.test.js +10 -2
  169. package/package.json +37 -16
  170. package/dist/cjs/start/problems.d.ts +0 -19
  171. package/dist/cjs/start/problems.js +0 -11
@@ -1,5 +1,8 @@
1
+ import type { RunRecord, ZiteRequestContext } from "./types.js";
1
2
  export declare const preview: (value: unknown) => string | undefined;
2
- export declare const errorOf: (error: unknown) => {
3
- code: string;
4
- message: string;
5
- };
3
+ export declare const errorOf: (error: unknown) => NonNullable<RunRecord["error"]>;
4
+ /**
5
+ * A server route's run, which run capture doesn't see: its body in, and its status and body out. The bodies are
6
+ * read from copies after the fact, so the response never waits; the run log waits for them before it flushes.
7
+ */
8
+ export declare function recordRoute<T>(host: ZiteRequestContext | undefined, request: Request, run: () => Promise<T>): Promise<T>;
@@ -1,5 +1,7 @@
1
- import { ZiteError } from "./index.js";
2
- const PREVIEW_LIMIT = 8_000;
1
+ import { asZiteError } from "./errors.js";
2
+ // Classic's per-field cap. The host caps again; this keeps a large value from crossing at all.
3
+ const RUN_FIELD_LIMIT = 50 * 1024;
4
+ const capped = (text) => (text.length > RUN_FIELD_LIMIT ? `${text.slice(0, RUN_FIELD_LIMIT)}…` : text);
3
5
  export const preview = (value) => {
4
6
  if (value === undefined)
5
7
  return undefined;
@@ -7,12 +9,68 @@ export const preview = (value) => {
7
9
  return "[stream]";
8
10
  try {
9
11
  const json = JSON.stringify(value);
10
- return json && json.length > PREVIEW_LIMIT ? `${json.slice(0, PREVIEW_LIMIT)}…` : json;
12
+ return json === undefined ? undefined : capped(json);
11
13
  }
12
14
  catch {
13
15
  return "[unserializable]";
14
16
  }
15
17
  };
16
- export const errorOf = (error) => error instanceof ZiteError
17
- ? { code: error.code, message: error.message }
18
- : { code: "INTERNAL_ERROR", message: error instanceof Error ? error.message : String(error) };
18
+ export const errorOf = (error) => ({
19
+ code: asZiteError(error)?.code ?? "INTERNAL_ERROR",
20
+ message: error instanceof Error ? error.message : String(error),
21
+ ...(error instanceof Error && error.stack ? { stack: capped(error.stack) } : {}),
22
+ });
23
+ const TEXT_BODY = /^(application\/(json|x-www-form-urlencoded)|text\/(?!event-stream))/i;
24
+ // Up to the cap of a copy of the body, so the app still reads the original. Uploads and streams aren't read.
25
+ const bodyText = async (message) => {
26
+ if (!message.body || !TEXT_BODY.test(message.headers.get("content-type") ?? ""))
27
+ return undefined;
28
+ const reader = message.clone().body.pipeThrough(new TextDecoderStream()).getReader();
29
+ let text = "";
30
+ try {
31
+ while (text.length <= RUN_FIELD_LIMIT) {
32
+ const { done, value } = await reader.read();
33
+ if (done)
34
+ break;
35
+ text += value;
36
+ }
37
+ }
38
+ finally {
39
+ reader.cancel().catch(() => { });
40
+ }
41
+ return capped(text);
42
+ };
43
+ /**
44
+ * A server route's run, which run capture doesn't see: its body in, and its status and body out. The bodies are
45
+ * read from copies after the fact, so the response never waits; the run log waits for them before it flushes.
46
+ */
47
+ export async function recordRoute(host, request, run) {
48
+ if (!host)
49
+ return run();
50
+ const startedAt = Date.now();
51
+ const path = new URL(request.url).pathname;
52
+ const input = bodyText(request).catch(() => undefined);
53
+ const record = (outcome) => {
54
+ const durationMs = Date.now() - startedAt;
55
+ const recorded = (async () => {
56
+ const fields = { input: await input, ...(await outcome) };
57
+ host.runs.push({ fn: `route:${request.method} ${path}`, name: path, nested: false, startedAt, durationMs, ...fields });
58
+ })();
59
+ (host.pending ??= []).push(recorded.catch(() => { }));
60
+ };
61
+ try {
62
+ const out = await run();
63
+ const response = out instanceof Response ? out : out?.response;
64
+ if (response instanceof Response) {
65
+ record(bodyText(response).then((body) => ({ output: preview({ status: response.status, body }) }), () => ({})));
66
+ }
67
+ else {
68
+ record(Promise.resolve({}));
69
+ }
70
+ return out;
71
+ }
72
+ catch (error) {
73
+ record(Promise.resolve({ error: errorOf(error) }));
74
+ throw error;
75
+ }
76
+ }
@@ -1,5 +1,5 @@
1
- import type { User, ZiteRequestContext } from "./types.js";
2
- export type AccessKind = "signedIn" | "anyone" | "webhook" | "workflow";
1
+ import type { AccessKind, User, ZiteRequestContext } from "./types.js";
2
+ export type { AccessKind } from "./types.js";
3
3
  export type AccessScope = {
4
4
  kind: AccessKind;
5
5
  user: User | null;
@@ -1,49 +1,53 @@
1
- import { type AccessKind } from "./scope.js";
2
- import type { RunRecord, ZiteRequestContext } from "./types.js";
1
+ import type { HostProps, PlatformBinding, ZiteRequestContext } from "./types.js";
3
2
  export { runWithHost } from "./scope.js";
4
3
  export { describeApp } from "./describe.js";
5
- export type { RunRecord } from "./types.js";
6
- export type PlatformCallInput = {
7
- integrationId: string;
8
- className: string;
9
- methodName: string;
10
- params: unknown;
11
- access: AccessKind;
12
- userId: string | null;
13
- requestId: string;
14
- };
15
- /** The `ZITE` service binding the host's Platform entrypoint gives every app script. */
16
- export type PlatformBinding = {
17
- call(call: PlatformCallInput): Promise<unknown>;
18
- /** One batch per request, after its response has ended. */
19
- runs(batch: {
20
- requestId: string;
21
- runs: RunRecord[];
22
- }): Promise<void>;
23
- };
4
+ export type { HostProps, PlatformBinding, PlatformCallInput, PlatformCallResult, PlatformSession, RunRecord } from "./types.js";
5
+ /**
6
+ * Routes every zitejs data, integration and email call to this request's
7
+ * platform, on one session, and only inside an access scope. The access kind
8
+ * travels with the call so the platform can record what a page read and narrow
9
+ * anonymous reads.
10
+ */
11
+ export declare function installPlatformTransport(): void;
12
+ /** What the host dispatched this request with. Headers are ignored: props are the only thing it alone can set. */
13
+ export declare function hostContextFromProps(request: Request, props: HostProps): ZiteRequestContext;
24
14
  /**
25
- * Routes every zitejs data, integration and email call through `call`, and only
26
- * inside an access scope. The access kind travels with the call so the platform
27
- * can record what a page read and, later, narrow anonymous reads.
15
+ * A request the host didn't dispatch: the host's warm-up, `zitejs describe` under `vite preview`, and tests. Only the
16
+ * host can set props, so without them a build answers warm and describe and nobody is signed in. An entry that passes
17
+ * its own platform (tests, local dev) owns its requests and may say who is calling in `x-zite-*` headers.
28
18
  */
29
- export declare function installPlatformTransport(call: (input: PlatformCallInput) => Promise<unknown>): void;
30
- /** The host's `x-zite-*` headers. Only the host can set them: the front strips them from public traffic. */
31
- export declare function hostContextFromRequest(request: Request): ZiteRequestContext;
19
+ export declare function hostContextFromRequest(request: Request, platform?: PlatformBinding): ZiteRequestContext;
32
20
  /** Every server function TanStack compiled, written in by `zite()` at build. Empty in dev, where TanStack doesn't call its id hook. */
33
21
  export declare const builtFunctionIds: () => string[];
34
22
  /** Each server function's `description` option, written in by `zite()` at build. */
35
23
  export declare const builtFunctionDescriptions: () => Record<string, string>;
24
+ /** Each route's file, by route id, written in by `zite()` at build. */
25
+ export declare const builtRouteFiles: () => Record<string, string>;
26
+ /** Each provider trigger's registration hash, by automation id, written in by `zite()` at build from its source. */
27
+ export declare const builtRegistrationHashes: () => Record<string, string>;
36
28
  type Fetch = (request: Request, ...rest: unknown[]) => Promise<Response> | Response;
37
- /**
38
- * The fetch handler of a Start app's server entry. Describe calls get the app's
39
- * description; everything else runs TanStack with the host's identity in
40
- * server-only storage. Platform calls go to the `ZITE` binding from the Worker's
41
- * env, or to `platform` when a test or local dev supplies one.
42
- */
43
- export declare function createZiteFetch(options: {
29
+ /** On describe's answer: the zitejs this build's server code was bundled from. */
30
+ export declare const RUNTIME_VERSION_HEADER = "x-zitejs-version";
31
+ export type ZiteServerOptions = {
44
32
  handler: {
45
- fetch: Fetch;
33
+ fetch(request: Request, ...rest: unknown[]): Promise<Response> | Response;
46
34
  };
47
35
  getRouter: () => unknown;
48
36
  platform?: PlatformBinding;
49
- }): Fetch;
37
+ /** The app's start instance, which a test run of a server function runs under. */
38
+ startInstance: {
39
+ getOptions: () => unknown;
40
+ };
41
+ };
42
+ export type ZiteHandlers = {
43
+ fetch: Fetch;
44
+ };
45
+ /**
46
+ * The handlers of a Start app's server entry. A request the host dispatched
47
+ * carries its identity and platform in props; anything else (describe under
48
+ * `vite preview`, tests) reads `x-zite-*` headers and uses `platform` if one
49
+ * is given.
50
+ */
51
+ export declare function createZiteHandlers(options: ZiteServerOptions): ZiteHandlers;
52
+ /** The fetch handler alone, for the Node entry. */
53
+ export declare function createZiteFetch(options: ZiteServerOptions): Fetch;
@@ -1,46 +1,169 @@
1
+ // For the generated server entry only. Apps never import this.
2
+ import { createServerEntry } from "@tanstack/react-start/server";
3
+ import { createSsrRpc } from "@tanstack/react-start/ssr-rpc";
4
+ import { runWithStartContext } from "@tanstack/start-storage-context";
5
+ import { asZiteError, isZiteErrorCode, ZiteError, ZITE_ERROR_STATUS } from "./errors.js";
1
6
  import { describeApp } from "./describe.js";
2
- import { preview } from "./runLog.js";
3
- import { getHost, requireScope, runWithHost } from "./scope.js";
7
+ import { runRegistration } from "./registration.js";
8
+ import { isAuthHookName, loadAuthHooks } from "./authHooks.js";
9
+ import { errorOf, preview } from "./runLog.js";
10
+ import { DATA_INTEGRATION_ID, dataContextOf, runDataCall } from "./data/index.js";
11
+ import { airtableSettingsOf, runAirtableCall } from "./airtable/index.js";
12
+ import { withoutConsole } from "./quiet.js";
13
+ import { createOutboundFetch, rememberConnection } from "./outbound.js";
14
+ import { INTEGRATIONS_PLATFORM_ID } from "./credentials.js";
15
+ import { getHost, requireScope, runInScope, runWithHost } from "./scope.js";
16
+ import { ZITEJS_VERSION } from "./version.js";
4
17
  import { loadWorkflows, loggedInput, runWorkflow } from "./workflowRun.js";
5
18
  export { runWithHost } from "./scope.js";
6
19
  export { describeApp } from "./describe.js";
7
20
  /**
8
- * Routes every zitejs data, integration and email call through `call`, and only
9
- * inside an access scope. The access kind travels with the call so the platform
10
- * can record what a page read and, later, narrow anonymous reads.
21
+ * Routes every zitejs data, integration and email call to this request's
22
+ * platform, on one session, and only inside an access scope. The access kind
23
+ * travels with the call so the platform can record what a page read and narrow
24
+ * anonymous reads.
11
25
  */
12
- export function installPlatformTransport(call) {
13
- const sdkCall = (integrationId, className, methodName, params) => {
26
+ export function installPlatformTransport() {
27
+ const sdkCall = async (integrationId, className, methodName, params) => {
14
28
  const scope = requireScope(`${className}.${methodName}`);
15
- return call({
16
- integrationId,
17
- className,
18
- methodName,
19
- params,
20
- access: scope.kind,
21
- userId: scope.user?.id ?? null,
22
- requestId: getHost()?.requestId ?? "",
23
- });
29
+ const host = getHost();
30
+ const getsConnection = integrationId === INTEGRATIONS_PLATFORM_ID && methodName === "get";
31
+ const name = String(params?.name ?? "");
32
+ // Fails closed: no platform means no platform access, never a fallback.
33
+ if (!host?.platform)
34
+ throw new Error("The Zite platform binding is missing");
35
+ host.session ??= Promise.resolve(host.platform.session());
36
+ const session = await host.session;
37
+ if (integrationId === DATA_INTEGRATION_ID) {
38
+ const found = await dataContextOf(session);
39
+ return recordCall(host, { integrationId, className, methodName, params }, () => runDataCall(session, found, host.mode, methodName, params));
40
+ }
41
+ if (!integrationId.startsWith("__")) {
42
+ const airtable = await airtableSettingsOf(session, integrationId);
43
+ if (airtable) {
44
+ return recordCall(host, { integrationId, className, methodName, params }, () => runAirtableCall(host, session, integrationId, airtable, methodName, params, scope.kind));
45
+ }
46
+ }
47
+ const result = await session.call({ integrationId, className, methodName, params, access: scope.kind });
48
+ if (getsConnection)
49
+ return connectionAnswer(host, name, result);
50
+ if ("value" in result)
51
+ return result.value;
52
+ const { code, message, userFacingMessage } = result.error;
53
+ throw new ZiteError({ code: isZiteErrorCode(code) ? code : "INTERNAL_ERROR", message, userFacingMessage });
24
54
  };
25
55
  globalThis.__wrapSdkCall = sdkCall;
56
+ watchOutboundFetches();
26
57
  }
58
+ /** `integrations.get`'s answer, whose values then name the calls made with them. */
59
+ const connectionAnswer = (host, name, result) => {
60
+ if ("value" in result) {
61
+ rememberConnection(host, name, result.value);
62
+ return result.value;
63
+ }
64
+ const { code, message, userFacingMessage } = result.error;
65
+ throw new ZiteError({ code: isZiteErrorCode(code) ? code : "INTERNAL_ERROR", message, userFacingMessage });
66
+ };
67
+ /** A data call the app made itself, recorded as the host recorded the ones it made. */
68
+ const recordCall = async (host, call, run) => {
69
+ const at = Date.now();
70
+ const record = {
71
+ integrationId: call.integrationId,
72
+ className: call.className,
73
+ methodName: call.methodName,
74
+ at,
75
+ inputs: preview(call.params),
76
+ };
77
+ try {
78
+ const value = await run();
79
+ (host.calls ??= []).push({ ...record, durationMs: Date.now() - at, outputs: preview(value) });
80
+ return value;
81
+ }
82
+ catch (error) {
83
+ const { code, message } = errorOf(error);
84
+ (host.calls ??= []).push({ ...record, durationMs: Date.now() - at, error: { code, message } });
85
+ throw error;
86
+ }
87
+ };
88
+ // Keyed on globalThis so two copies of zitejs in one bundle wrap fetch once.
89
+ const WATCHED_KEY = Symbol.for("zitejs:outbound-fetch");
90
+ // Next patches fetch for the same reason: the run log must hear of each.
91
+ const watchOutboundFetches = () => {
92
+ const marks = globalThis;
93
+ if (marks[WATCHED_KEY])
94
+ return;
95
+ marks[WATCHED_KEY] = true;
96
+ globalThis.fetch = createOutboundFetch(globalThis.fetch.bind(globalThis));
97
+ };
27
98
  const decodeUser = (value) => JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(value.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0))));
28
- /** The host's `x-zite-*` headers. Only the host can set them: the front strips them from public traffic. */
29
- export function hostContextFromRequest(request) {
99
+ const INVOKE_KINDS = new Set(["webhook", "describe", "workflow", "register", "warm", "authHook", "function"]);
100
+ // What a request without props may ask for: neither runs app code on anyone's behalf.
101
+ const UNHOSTED_INVOKE_KINDS = new Set(["warm", "describe"]);
102
+ /** What the host dispatched this request with. Headers are ignored: props are the only thing it alone can set. */
103
+ export function hostContextFromProps(request, props) {
104
+ return {
105
+ requestId: props.requestId,
106
+ url: request.url,
107
+ user: props.user,
108
+ mode: props.mode,
109
+ invoke: props.invoke,
110
+ appUrl: props.appUrl,
111
+ baseId: props.baseId,
112
+ previewClaim: props.previewClaim,
113
+ env: props.env,
114
+ envConnections: props.envConnections,
115
+ runRoot: props.runRoot,
116
+ runs: [],
117
+ platform: props.platform,
118
+ };
119
+ }
120
+ // Classic sets these per run. Node and workerd both refuse getters on process.env, so each request writes what the
121
+ // host sent, which is the same for every request a build serves: the live URL even on a demo.
122
+ // The connection vars the last request set, so one gone since (an integration removed) doesn't linger.
123
+ let connectionEnvKeys = new Set();
124
+ const setRequestEnv = ({ appUrl, baseId, env: connectionEnv }) => {
125
+ const env = globalThis.process?.env;
126
+ if (!env)
127
+ return;
128
+ if (appUrl)
129
+ env.ZITE_APP_URL = appUrl;
130
+ if (baseId)
131
+ env.ZITE_BASE_ID = baseId;
132
+ if (!connectionEnv)
133
+ return;
134
+ for (const key of connectionEnvKeys)
135
+ if (!Object.hasOwn(connectionEnv, key))
136
+ delete env[key];
137
+ for (const [key, value] of Object.entries(connectionEnv)) {
138
+ if (key.startsWith("ZITE_"))
139
+ env[key] = value;
140
+ }
141
+ connectionEnvKeys = new Set(Object.keys(connectionEnv));
142
+ };
143
+ /**
144
+ * A request the host didn't dispatch: the host's warm-up, `zitejs describe` under `vite preview`, and tests. Only the
145
+ * host can set props, so without them a build answers warm and describe and nobody is signed in. An entry that passes
146
+ * its own platform (tests, local dev) owns its requests and may say who is calling in `x-zite-*` headers.
147
+ */
148
+ export function hostContextFromRequest(request, platform) {
30
149
  const { headers } = request;
31
- const user = headers.get("x-zite-user");
150
+ const trusted = platform !== undefined;
151
+ const user = trusted ? headers.get("x-zite-user") : null;
32
152
  const [kind, name = ""] = headers.get("x-zite-invoke")?.split(":") ?? [];
153
+ const kinds = trusted ? INVOKE_KINDS : UNHOSTED_INVOKE_KINDS;
33
154
  return {
34
- requestId: headers.get("x-zite-request-id") ?? crypto.randomUUID(),
155
+ requestId: (trusted && headers.get("x-zite-request-id")) || crypto.randomUUID(),
35
156
  url: request.url,
36
157
  user: user ? decodeUser(user) : null,
37
- invoke: kind === "webhook" || kind === "describe" || kind === "workflow" ? { kind, name } : null,
158
+ mode: "live",
159
+ invoke: kinds.has(kind) ? { kind: kind, name } : null,
38
160
  runs: [],
161
+ platform,
39
162
  };
40
163
  }
41
164
  /** Every server function TanStack compiled, written in by `zite()` at build. Empty in dev, where TanStack doesn't call its id hook. */
42
165
  export const builtFunctionIds = () => "__ZITE_FN_IDS__".split(",").filter((id) => id && !id.startsWith("__ZITE"));
43
- const parseDescriptions = (json) => {
166
+ const parseBuiltJson = (json) => {
44
167
  try {
45
168
  return JSON.parse(json);
46
169
  }
@@ -49,17 +172,54 @@ const parseDescriptions = (json) => {
49
172
  }
50
173
  };
51
174
  /** Each server function's `description` option, written in by `zite()` at build. */
52
- export const builtFunctionDescriptions = () => parseDescriptions("__ZITE_FN_DESCRIPTIONS__");
175
+ export const builtFunctionDescriptions = () => parseBuiltJson("__ZITE_FN_DESCRIPTIONS__");
176
+ /** Each route's file, by route id, written in by `zite()` at build. */
177
+ export const builtRouteFiles = () => parseBuiltJson("__ZITE_ROUTE_FILES__");
178
+ /** Each provider trigger's registration hash, by automation id, written in by `zite()` at build from its source. */
179
+ export const builtRegistrationHashes = () => parseBuiltJson("__ZITE_REGISTRATION_HASHES__");
53
180
  // Server functions also run while a streamed page renders, so the run log is
54
- // complete only once the body has been read to the end.
181
+ // complete only once the body ends: read to the end, cancelled by the reader or
182
+ // failed. A TransformStream's flush hears only the first.
55
183
  const onBodyEnd = (response, done) => {
56
184
  if (!response.body) {
57
185
  done();
58
186
  return response;
59
187
  }
60
- return new Response(response.body.pipeThrough(new TransformStream({ flush: done })), response);
188
+ const reader = response.body.getReader();
189
+ let ended = false;
190
+ const end = () => {
191
+ if (ended)
192
+ return;
193
+ ended = true;
194
+ done();
195
+ };
196
+ const body = new ReadableStream({
197
+ async pull(controller) {
198
+ try {
199
+ const { done: finished, value } = await reader.read();
200
+ if (finished) {
201
+ end();
202
+ controller.close();
203
+ }
204
+ else {
205
+ controller.enqueue(value);
206
+ }
207
+ }
208
+ catch (error) {
209
+ end();
210
+ controller.error(error);
211
+ }
212
+ },
213
+ cancel(reason) {
214
+ end();
215
+ return reader.cancel(reason);
216
+ },
217
+ });
218
+ return new Response(body, response);
61
219
  };
62
220
  const INVOKE_PATH = "/_zite/invoke";
221
+ /** On describe's answer: the zitejs this build's server code was bundled from. */
222
+ export const RUNTIME_VERSION_HEADER = "x-zitejs-version";
63
223
  // The host sends `{ input }`; a platform-fired run's input carries the runner's
64
224
  // `__cron`, `__poll` or `__webhook` state, exactly as for classic endpoints.
65
225
  async function invokeWorkflow(request, host, workflows) {
@@ -71,7 +231,7 @@ async function invokeWorkflow(request, host, workflows) {
71
231
  return Response.json({ ok: false, error: { code: "NOT_FOUND", message: `No workflow named ${name}` } }, { status: 404 });
72
232
  const input = (await request.json().catch(() => ({})))?.input;
73
233
  const startedAt = Date.now();
74
- const result = await runWorkflow(found.workflow, input);
234
+ const result = await runWorkflow(found.workflow, input, { resuming: host.runRoot !== undefined });
75
235
  host.runs.push({
76
236
  fn: `workflow:${found.id}`,
77
237
  name: found.id,
@@ -80,47 +240,159 @@ async function invokeWorkflow(request, host, workflows) {
80
240
  durationMs: Date.now() - startedAt,
81
241
  input: preview(loggedInput(input)),
82
242
  ...(result.ok ? { output: preview(result.output) } : { error: result.error }),
243
+ ...(result.steps ? { steps: result.steps } : {}),
244
+ ...(!result.ok && result.failedStep !== undefined ? { failedStep: result.failedStep } : {}),
83
245
  });
84
246
  return Response.json(result, { status: result.ok ? 200 : 500 });
85
247
  }
248
+ // The host sends `{ input }`, an editor's test run of a server function. It runs
249
+ // as a call from a page would on the server: its own middleware decides access
250
+ // for the user the host dispatched with, validates the input and records the run.
251
+ async function invokeFunction(request, options) {
252
+ if (request.method !== "POST" || new URL(request.url).pathname !== INVOKE_PATH)
253
+ return new Response("Not found", { status: 404 });
254
+ const id = getHost()?.invoke?.name ?? "";
255
+ if (!builtFunctionIds().includes(id)) {
256
+ return Response.json({ ok: false, error: { code: "NOT_FOUND", message: `No server function ${id}` } }, { status: 404 });
257
+ }
258
+ const input = (await request.json().catch(() => ({})))?.input;
259
+ const startContext = {
260
+ request,
261
+ getRouter: options.getRouter,
262
+ startOptions: (await options.startInstance.getOptions()) ?? {},
263
+ executedRequestMiddlewares: new Set(),
264
+ contextAfterGlobalMiddlewares: {},
265
+ handlerType: "serverFn",
266
+ };
267
+ // In TanStack's request event too, which the function's own status setting reads.
268
+ return createServerEntry({
269
+ fetch: async () => {
270
+ try {
271
+ const answer = (await runWithStartContext(startContext, () => createSsrRpc(id)({ data: input, context: {} })));
272
+ if ("error" in answer)
273
+ throw answer.error;
274
+ return Response.json({ ok: true, output: answer.result ?? null });
275
+ }
276
+ catch (error) {
277
+ return Response.json({ ok: false, error: errorOf(error) }, { status: 500 });
278
+ }
279
+ },
280
+ }).fetch(request, undefined);
281
+ }
282
+ // The host sends `{ op, input }`: `subscribe` with the platform's notification
283
+ // URL and secret, or `unsubscribe` with what `subscribe` returned.
284
+ async function invokeRegistration(request, host, workflows) {
285
+ if (request.method !== "POST" || new URL(request.url).pathname !== INVOKE_PATH)
286
+ return new Response("Not found", { status: 404 });
287
+ const name = host.invoke?.name ?? "";
288
+ const body = (await request.json().catch(() => null));
289
+ const result = await runRegistration(workflows, name, body?.op, body?.input);
290
+ if (!result) {
291
+ return Response.json({ ok: false, error: { code: "NOT_FOUND", message: `${name} has no ${String(body?.op)}` } }, { status: 404 });
292
+ }
293
+ return Response.json(result, { status: result.ok ? 200 : 500 });
294
+ }
295
+ // The host sends `{ input }`, the same fields classic hooks get. A hook runs as
296
+ // a workflow does: no user, and the app's data and integrations through its platform.
297
+ async function invokeAuthHook(request, host) {
298
+ if (request.method !== "POST" || new URL(request.url).pathname !== INVOKE_PATH)
299
+ return new Response("Not found", { status: 404 });
300
+ const name = host.invoke?.name ?? "";
301
+ const hook = isAuthHookName(name) ? (await loadAuthHooks())[name] : undefined;
302
+ if (!hook) {
303
+ return Response.json({ ok: false, error: { code: "NOT_FOUND", message: `No auth hook named ${name}` } }, { status: 404 });
304
+ }
305
+ const input = (await request.json().catch(() => ({})))?.input ?? {};
306
+ const startedAt = Date.now();
307
+ try {
308
+ const output = await runInScope({ kind: "workflow", user: null }, () => hook(input));
309
+ host.runs.push({ fn: `authHook:${name}`, name, nested: false, startedAt, durationMs: Date.now() - startedAt, input: preview(input), output: preview(output) });
310
+ return Response.json({ ok: true, output: output ?? null });
311
+ }
312
+ catch (error) {
313
+ const failed = errorOf(error);
314
+ host.runs.push({ fn: `authHook:${name}`, name, nested: false, startedAt, durationMs: Date.now() - startedAt, input: preview(input), error: failed });
315
+ return Response.json({ ok: false, error: failed }, { status: 500 });
316
+ }
317
+ }
318
+ // TanStack renders any loader error as a 500. A page refused with a ZiteError
319
+ // (a missing role, a record that isn't there) answers with that error's status.
320
+ const pageStatus = (host) => {
321
+ const matches = host.router?.state?.matches;
322
+ const failed = asZiteError(matches?.find((match) => match.status === "error")?.error);
323
+ return failed ? ZITE_ERROR_STATUS[failed.code] : undefined;
324
+ };
86
325
  /**
87
- * The fetch handler of a Start app's server entry. Describe calls get the app's
88
- * description; everything else runs TanStack with the host's identity in
89
- * server-only storage. Platform calls go to the `ZITE` binding from the Worker's
90
- * env, or to `platform` when a test or local dev supplies one.
326
+ * The handlers of a Start app's server entry. A request the host dispatched
327
+ * carries its identity and platform in props; anything else (describe under
328
+ * `vite preview`, tests) reads `x-zite-*` headers and uses `platform` if one
329
+ * is given.
91
330
  */
92
- export function createZiteFetch(options) {
93
- let binding = options.platform;
94
- // Fails closed: no binding means no platform access, never a fallback.
95
- const platform = () => {
96
- if (!binding)
97
- throw new Error("The Zite platform binding is missing");
98
- return binding;
99
- };
100
- installPlatformTransport((call) => platform().call(call));
331
+ export function createZiteHandlers(options) {
332
+ installPlatformTransport();
101
333
  // Loaded on first use, so a page request never pays for importing workflow modules.
102
334
  let workflows;
103
335
  const loadedWorkflows = () => (workflows ??= loadWorkflows());
104
- return async (request, ...rest) => {
105
- binding ??= rest[0]?.ZITE;
106
- if (request.headers.get("x-zite-invoke") === "describe") {
336
+ const serve = async (request, ctx) => {
337
+ const host = ctx?.props?.platform
338
+ ? hostContextFromProps(request, ctx.props)
339
+ : hostContextFromRequest(request, options.platform);
340
+ setRequestEnv(host);
341
+ // Starting this isolate was the point: the platform warms a build before its
342
+ // first visitors, and no app code runs.
343
+ if (host.invoke?.kind === "warm")
344
+ return new Response(null, { status: 204 });
345
+ if (host.invoke?.kind === "describe") {
107
346
  return Response.json(await describeApp({
108
347
  fnIds: builtFunctionIds(),
109
348
  descriptions: builtFunctionDescriptions(),
349
+ routeFiles: builtRouteFiles(),
350
+ registrationHashes: builtRegistrationHashes(),
110
351
  getRouter: options.getRouter,
111
352
  request,
112
353
  workflows: await loadedWorkflows(),
113
- }));
354
+ }), { headers: { [RUNTIME_VERSION_HEADER]: ZITEJS_VERSION } });
114
355
  }
115
- const host = hostContextFromRequest(request);
116
- const response = await runWithHost(host, async () => host.invoke?.kind === "workflow" ? invokeWorkflow(request, host, await loadedWorkflows()) : options.handler.fetch(request));
356
+ let response = await runWithHost(host, async () => host.invoke?.kind === "workflow"
357
+ ? invokeWorkflow(request, host, await loadedWorkflows())
358
+ : host.invoke?.kind === "function"
359
+ ? invokeFunction(request, options)
360
+ : host.invoke?.kind === "register"
361
+ ? withoutConsole(async () => invokeRegistration(request, host, await loadedWorkflows()))
362
+ : host.invoke?.kind === "authHook"
363
+ ? invokeAuthHook(request, host)
364
+ : options.handler.fetch(request));
365
+ const status = response.status === 500 ? pageStatus(host) : undefined;
366
+ if (status)
367
+ response = new Response(response.body, { status, headers: response.headers });
117
368
  return onBodyEnd(response, () => {
118
- if (!host.runs.length || !binding)
369
+ const { platform } = host;
370
+ if ((!host.runs.length && !host.calls?.length && !host.fetches?.length && !host.pending?.length) || !platform)
119
371
  return;
120
- const flushed = binding.runs({ requestId: host.requestId, runs: host.runs }).catch((error) => {
372
+ // On the request's session when it has one: one call, not another binding round trip.
373
+ const flushed = (async () => {
374
+ await Promise.all(host.pending ?? []);
375
+ if (!host.runs.length && !host.calls?.length && !host.fetches?.length)
376
+ return;
377
+ const batch = {
378
+ runs: host.runs,
379
+ ...(host.calls?.length && { calls: host.calls }),
380
+ ...(host.fetches?.length && { fetches: host.fetches }),
381
+ };
382
+ // Only a session takes fetches.
383
+ if (host.fetches?.length)
384
+ host.session ??= Promise.resolve(platform.session());
385
+ const session = host.session ? await host.session : undefined;
386
+ await (session ? session.runs(batch) : platform.runs(batch));
387
+ })().catch((error) => {
121
388
  console.error("[zite] couldn't record runs", error);
122
389
  });
123
- rest[1]?.waitUntil(flushed);
390
+ ctx?.waitUntil(flushed);
124
391
  });
125
392
  };
393
+ return { fetch: (request, ...rest) => serve(request, rest[1]) };
394
+ }
395
+ /** The fetch handler alone, for the Node entry. */
396
+ export function createZiteFetch(options) {
397
+ return createZiteHandlers(options).fetch;
126
398
  }