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
@@ -0,0 +1,28 @@
1
+ import type { ZiteStep } from "../backend/index.js";
2
+ /** What a workflow's handler gets as `step`. */
3
+ export type StartStep = Pick<ZiteStep, "run">;
4
+ export type StepLog = {
5
+ name: string;
6
+ status: "ran" | "memoized" | "failed";
7
+ durationMs?: number;
8
+ at: number;
9
+ };
10
+ type SdkCall = (integrationId: string, className: string, methodName: string, params: unknown) => Promise<unknown>;
11
+ export declare const STEP_RESULT_MAX_BYTES: number;
12
+ /**
13
+ * Each completed step's result is saved before the code after it runs, so a
14
+ * resumed run gets it back instead of running the step's side effects again.
15
+ * Only a resumed run reads saved results, once, at its first step.
16
+ */
17
+ export declare function createSteps({ call, resuming, now }: {
18
+ call: SdkCall;
19
+ resuming: boolean;
20
+ now?: () => number;
21
+ }): {
22
+ step: StartStep;
23
+ log: StepLog[];
24
+ failedStep: () => string | undefined;
25
+ /** A step that throws inside `Promise.all` ends the run while its siblings still save. */
26
+ settle: () => Promise<void>;
27
+ };
28
+ export {};
@@ -0,0 +1,97 @@
1
+ const STEPS_INTEGRATION_ID = "__steps__";
2
+ export const STEP_RESULT_MAX_BYTES = 256 * 1024;
3
+ const MAX_STEPS = 512;
4
+ const plain = (name, value) => {
5
+ let json;
6
+ try {
7
+ json = JSON.stringify(value);
8
+ }
9
+ catch (err) {
10
+ throw new Error(`step "${name}" returned a value that cannot be saved for retries: ${err instanceof Error ? err.message : String(err)}. Return plain JSON data from steps.`);
11
+ }
12
+ if (json === undefined)
13
+ return null;
14
+ if (new TextEncoder().encode(json).length > STEP_RESULT_MAX_BYTES) {
15
+ throw new Error(`step "${name}" returned more than ${STEP_RESULT_MAX_BYTES / 1024}KB. Store large data elsewhere and return a reference to it.`);
16
+ }
17
+ return JSON.parse(json);
18
+ };
19
+ /**
20
+ * Each completed step's result is saved before the code after it runs, so a
21
+ * resumed run gets it back instead of running the step's side effects again.
22
+ * Only a resumed run reads saved results, once, at its first step.
23
+ */
24
+ export function createSteps({ call, resuming, now = Date.now }) {
25
+ const seen = new Set();
26
+ const inFlight = new Set();
27
+ const log = [];
28
+ let failedStep;
29
+ let saved;
30
+ const savedResults = () => (saved ??= resuming
31
+ ? call(STEPS_INTEGRATION_ID, "Steps", "load", {}).catch((err) => {
32
+ throw new Error(`Could not read this run's saved steps (${err instanceof Error ? err.message : String(err)}); nothing ran again. Resume it once more.`);
33
+ })
34
+ : Promise.resolve(Object.create(null)));
35
+ const failed = (name, err, startedAt) => {
36
+ failedStep ??= name;
37
+ log.push({ name, status: "failed", durationMs: now() - startedAt, at: now() });
38
+ return err;
39
+ };
40
+ const body = async (name, fn) => {
41
+ const startedAt = now();
42
+ let value;
43
+ try {
44
+ value = plain(name, await fn());
45
+ }
46
+ catch (err) {
47
+ throw failed(name, err, startedAt);
48
+ }
49
+ // Awaited before the step returns: a crash after this never repeats it.
50
+ try {
51
+ await call(STEPS_INTEGRATION_ID, "Steps", "persist", { name, value, durationMs: now() - startedAt });
52
+ }
53
+ catch (err) {
54
+ throw failed(name, new Error(`Saving the result of step "${name}" failed (${err instanceof Error ? err.message : String(err)}). The step itself completed; nothing is wrong with the code — run again.`), startedAt);
55
+ }
56
+ log.push({ name, status: "ran", durationMs: now() - startedAt, at: now() });
57
+ return value;
58
+ };
59
+ const step = {
60
+ run: async (name, fn) => {
61
+ if (typeof name !== "string" || name.length === 0 || name.length > 255) {
62
+ throw new Error("step.run needs a stable name of 1 to 255 characters as its first argument");
63
+ }
64
+ if (seen.size >= MAX_STEPS)
65
+ throw new Error(`a run can take at most ${MAX_STEPS} steps — batch work inside fewer steps`);
66
+ if (typeof fn !== "function")
67
+ throw new Error(`step.run("${name}") needs a function as its second argument`);
68
+ if (seen.has(name)) {
69
+ throw new Error(`step.run was called twice with the name "${name}" in one run. Each step needs its own stable name so a retry can match saved results to steps.`);
70
+ }
71
+ seen.add(name);
72
+ const results = await savedResults();
73
+ if (Object.prototype.hasOwnProperty.call(results, name)) {
74
+ log.push({ name, status: "memoized", at: now() });
75
+ return results[name];
76
+ }
77
+ const settled = body(name, fn);
78
+ inFlight.add(settled);
79
+ try {
80
+ return (await settled);
81
+ }
82
+ finally {
83
+ inFlight.delete(settled);
84
+ }
85
+ },
86
+ };
87
+ return {
88
+ step,
89
+ log,
90
+ failedStep: () => failedStep,
91
+ /** A step that throws inside `Promise.all` ends the run while its siblings still save. */
92
+ settle: async () => {
93
+ if (inFlight.size > 0)
94
+ await Promise.allSettled([...inFlight]);
95
+ },
96
+ };
97
+ }
@@ -1,8 +1,20 @@
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`. */
1
7
  export type User = {
2
8
  id: string;
3
9
  email: string;
10
+ /** First and last name, or the email when neither is set. */
4
11
  name: string;
5
- roles: ReadonlyArray<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;
6
18
  };
7
19
  /** One server function call, as the platform's run log shows it. Input and output are truncated JSON. */
8
20
  export type RunRecord = {
@@ -13,20 +25,181 @@ export type RunRecord = {
13
25
  durationMs: number;
14
26
  input?: string;
15
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;
16
75
  error?: {
17
76
  code: string;
18
77
  message: string;
19
78
  };
20
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 host 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. */
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
+ };
129
+ /** What the host hands each request: its platform, already scoped to the app, build, request and user. */
130
+ export type PlatformBinding = {
131
+ /** Every platform call of one request goes through one session. */
132
+ session(): PlatformSession | Promise<PlatformSession>;
133
+ /** One batch per request, after its response has ended. */
134
+ runs(batch: {
135
+ runs: RunRecord[];
136
+ }): Promise<void>;
137
+ };
138
+ /** A demo is the published build serving a read-only visitor: as live, but every write is refused. */
139
+ export type HostMode = "live" | "preview" | "demo" | "validate";
140
+ export type HostInvoke = {
141
+ kind: "webhook" | "describe" | "workflow" | "register" | "warm" | "authHook" | "function";
142
+ name: string;
143
+ };
144
+ /** The per-request props the host dispatches with. Only the host can set them. */
145
+ export type HostProps = {
146
+ platform: PlatformBinding;
147
+ requestId: string;
148
+ user: User | null;
149
+ mode: HostMode;
150
+ invoke: HostInvoke | null;
151
+ /** The app's live URL, demo included: `process.env.ZITE_APP_URL`. */
152
+ appUrl?: string;
153
+ /** The app's database: `process.env.ZITE_BASE_ID`. */
154
+ baseId?: string;
155
+ /** An editor preview's access, which zitejs keeps on the app's links and calls. */
156
+ previewClaim?: string;
157
+ /** `process.env` as classic sets it: connections' vars, then the user's own secrets. */
158
+ env?: Record<string, string>;
159
+ /** Which connection each token var in `env` holds. */
160
+ envConnections?: Record<string, string>;
161
+ /** A resumed run's first attempt, whose saved steps it replays. */
162
+ runRoot?: string;
163
+ };
21
164
  /** What the host resolved for this request. Set by the generated server entry, never by the browser. */
22
165
  export type ZiteRequestContext = {
23
166
  requestId: string;
24
167
  url: string;
25
168
  user: User | null;
26
- invoke: {
27
- kind: "webhook" | "describe" | "workflow";
28
- name: string;
29
- } | null;
169
+ mode: HostMode;
170
+ invoke: HostInvoke | null;
171
+ appUrl?: string;
172
+ baseId?: string;
173
+ previewClaim?: string;
174
+ /** Classic's connection env vars the host sent, set into `process.env` for the request. */
175
+ env?: Record<string, string>;
176
+ envConnections?: Record<string, string>;
177
+ /** A resumed run's first attempt, whose saved steps it replays. */
178
+ runRoot?: string;
179
+ /** The connection each token this request was handed belongs to. */
180
+ connectionTokens?: Map<string, string>;
181
+ /** `integrations.get`'s answers this request, by name. */
182
+ connectionAnswers?: Map<string, unknown>;
183
+ /** One refresh per connection per request, however many calls got a 401. */
184
+ refreshing?: Map<string, Promise<string | undefined>>;
185
+ /** The outbound fetches, flushed with its runs. */
186
+ fetches?: FetchRecord[];
187
+ /** The secrets its fetch log redacts, longest first; cleared when a connection is learned. */
188
+ secretValues?: string[];
189
+ /** The isolate's refresh count `secretValues` was read at. */
190
+ secretsAt?: number;
191
+ /** How much of its fetch log is bodies so far. */
192
+ fetchLogChars?: number;
30
193
  /** Filled by run capture, flushed to the platform once the response ends. */
31
194
  runs: RunRecord[];
195
+ /** The data calls this request made, flushed with its runs. */
196
+ calls?: CallRecord[];
197
+ /** This request's Airtable reads, so the same one twice goes out once. */
198
+ airtableReads?: Map<string, Promise<unknown>>;
199
+ /** Records still reading a copy of a body; the flush waits for them. */
200
+ pending?: Promise<void>[];
201
+ platform?: PlatformBinding;
202
+ session?: Promise<PlatformSession>;
203
+ /** This request's router, so a page's status can follow the error it rendered. */
204
+ router?: unknown;
32
205
  };
@@ -0,0 +1 @@
1
+ export declare const ZITEJS_VERSION = "0.10.0-start.20";
@@ -0,0 +1,2 @@
1
+ // Written by scripts/write-version.mjs from package.json.
2
+ export const ZITEJS_VERSION = "0.10.0-start.20";
@@ -1,14 +1,33 @@
1
+ import { existsSync, readFileSync } from "node:fs";
1
2
  import path from "node:path";
2
3
  import { tanstackStart } from "@tanstack/react-start/plugin/vite";
3
4
  import viteReact from "@vitejs/plugin-react";
4
5
  import { ziteId } from "../vite/index.js";
5
6
  import { factoryDescriptions } from "./descriptions.js";
7
+ import { registrationHashes } from "./registrationHash.js";
6
8
  import { hasAppStart, renderStartInstance, renderStartServerEntry, renderWorkflowModules, START_INSTANCE_ENTRY, START_SERVER_ENTRY, workflowFiles, writeIfChanged, } from "./entries.js";
7
9
  // Must match the literals in ./server.ts, which the build rewrites.
8
10
  const FN_IDS_TOKEN = "__ZITE_FN_IDS__";
9
11
  const FN_DESCRIPTIONS_LITERAL = /(["'`])__ZITE_FN_DESCRIPTIONS__\1/;
12
+ const ROUTE_FILES_LITERAL = /(["'`])__ZITE_ROUTE_FILES__\1/;
13
+ const REGISTRATION_HASHES_LITERAL = /(["'`])__ZITE_REGISTRATION_HASHES__\1/;
14
+ // TanStack's generator writes each route file's id into its createFileRoute call and keeps it in step.
15
+ const FILE_ROUTE_ID = /\bcreateFileRoute\(\s*(["'`])([^"'`]+)\1\s*\)/;
10
16
  // zitejs's empty registry, which the build replaces with the app's.
11
17
  const WORKFLOW_REGISTRY = /[\\/]zitejs[\\/]dist[\\/]esm[\\/]start[\\/]workflowModules\.js$/;
18
+ // zitejs's null auth-hooks module, which the build points at the app's `zite.auth.ts`.
19
+ const AUTH_HOOKS_REGISTRY = /[\\/]zitejs[\\/]dist[\\/]esm[\\/]start[\\/]authHooksModule\.js$/;
20
+ const AUTH_HOOKS_FILE = "zite.auth.ts";
21
+ const SOURCE_LANGS = {
22
+ ".ts": "ts",
23
+ ".mts": "ts",
24
+ ".cts": "ts",
25
+ ".tsx": "tsx",
26
+ ".js": "js",
27
+ ".mjs": "js",
28
+ ".cjs": "js",
29
+ ".jsx": "jsx",
30
+ };
12
31
  // Platform-pinned Worker settings. The deploy uses its own fixed template, so
13
32
  // these only have to match it; apps don't carry a wrangler config.
14
33
  const WORKER_COMPATIBILITY_DATE = "2026-09-25";
@@ -32,8 +51,9 @@ export function zite(options = {}) {
32
51
  // Platform-owned, so they're rewritten whenever they differ. Sandboxes run the
33
52
  // image's zitejs for `generate`, which may predate Start; the plugin can't.
34
53
  const appDir = process.cwd();
35
- if (!options.serverEntry)
36
- writeIfChanged(appDir, START_SERVER_ENTRY, renderStartServerEntry());
54
+ if (!options.serverEntry) {
55
+ writeIfChanged(appDir, START_SERVER_ENTRY, renderStartServerEntry(options.cloudflare === false ? "node" : "cloudflare"));
56
+ }
37
57
  writeIfChanged(appDir, START_INSTANCE_ENTRY, renderStartInstance(hasAppStart(appDir)));
38
58
  // Every server function TanStack's compiler found, from its own hook, by id.
39
59
  const ids = new Map();
@@ -66,22 +86,63 @@ export function zite(options = {}) {
66
86
  },
67
87
  };
68
88
  },
89
+ // Each new isolate loads the whole server bundle, so its size is cold-start
90
+ // time; Vite leaves SSR output unminified.
91
+ configEnvironment: (name, config) => name === "ssr" && options.cloudflare !== false && config.build?.minify === undefined ? { build: { minify: true } } : undefined,
69
92
  };
70
- // Each server function's `description` option, by name, for the editor.
93
+ // Each server function's `description` option, by name, and each route's file, by route id: for the editor.
71
94
  const descriptions = new Map();
95
+ const routeFiles = new Map();
96
+ // Each provider trigger's registration hash, by automation id, from its source: for publish.
97
+ const hashes = new Map();
72
98
  const srcDir = `${path.join(appDir, "src")}${path.sep}`;
73
99
  const functionIds = {
74
100
  name: "zite:function-ids",
75
101
  apply: "build",
76
- transform(code, id) {
77
- if (this.environment?.config.consumer !== "server" || !id.startsWith(srcDir) || !code.includes("description"))
102
+ async transform(code, id) {
103
+ if (this.environment?.config.consumer !== "server" || !id.startsWith(srcDir))
104
+ return;
105
+ const file = id.split("?")[0];
106
+ const routeId = FILE_ROUTE_ID.exec(code)?.[2];
107
+ if (routeId && !id.includes("?"))
108
+ routeFiles.set(routeId, path.relative(appDir, file).split(path.sep).join("/"));
109
+ if (code.includes("description")) {
110
+ try {
111
+ for (const [name, text] of factoryDescriptions(this.parse(code)))
112
+ descriptions.set(name, text);
113
+ }
114
+ catch {
115
+ // An unreadable module shows no descriptions.
116
+ }
117
+ }
118
+ if (id.includes("?") || !code.includes("createAutomation"))
78
119
  return;
120
+ // Read as the app wrote them, so neither this build's transforms nor its minifier can change a hash.
121
+ const modules = {
122
+ load: (target) => {
123
+ if (!existsSync(target))
124
+ return undefined;
125
+ const source = readFileSync(target, "utf-8");
126
+ const lang = SOURCE_LANGS[path.extname(target)];
127
+ try {
128
+ return { code: source, program: lang ? this.parse(source, { lang }) : undefined };
129
+ }
130
+ catch {
131
+ return { code: source };
132
+ }
133
+ },
134
+ resolve: async (source, importer) => {
135
+ const resolved = await this.resolve(source, importer);
136
+ const target = resolved && !resolved.external ? resolved.id.split("?")[0] : "";
137
+ return target && path.isAbsolute(target) && !/[\\/]node_modules[\\/]/.test(target) ? target : undefined;
138
+ },
139
+ };
79
140
  try {
80
- for (const [name, text] of factoryDescriptions(this.parse(code)))
81
- descriptions.set(name, text);
141
+ for (const [name, hash] of await registrationHashes(file, modules))
142
+ hashes.set(name, hash);
82
143
  }
83
144
  catch {
84
- // Display-only: an unreadable module just shows no descriptions.
145
+ // Describe hashes these triggers from the build.
85
146
  }
86
147
  },
87
148
  generateBundle(_, bundle) {
@@ -91,7 +152,10 @@ export function zite(options = {}) {
91
152
  continue;
92
153
  if (chunk.code.includes(FN_IDS_TOKEN))
93
154
  chunk.code = chunk.code.replace(FN_IDS_TOKEN, [...ids.keys()].join(","));
94
- chunk.code = chunk.code.replace(FN_DESCRIPTIONS_LITERAL, () => JSON.stringify(JSON.stringify(described)));
155
+ chunk.code = chunk.code
156
+ .replace(FN_DESCRIPTIONS_LITERAL, () => JSON.stringify(JSON.stringify(described)))
157
+ .replace(ROUTE_FILES_LITERAL, () => JSON.stringify(JSON.stringify(Object.fromEntries(routeFiles))))
158
+ .replace(REGISTRATION_HASHES_LITERAL, () => JSON.stringify(JSON.stringify(Object.fromEntries(hashes))));
95
159
  }
96
160
  },
97
161
  };
@@ -99,7 +163,20 @@ export function zite(options = {}) {
99
163
  name: "zite:workflow-registry",
100
164
  load: (id) => (WORKFLOW_REGISTRY.test(id.split("?")[0]) ? renderWorkflowModules(appDir, workflowFiles(appDir)) : undefined),
101
165
  };
166
+ const authHooksRegistry = {
167
+ name: "zite:auth-hooks",
168
+ load: (id) => {
169
+ if (!AUTH_HOOKS_REGISTRY.test(id.split("?")[0]))
170
+ return undefined;
171
+ const file = path.join(appDir, AUTH_HOOKS_FILE);
172
+ return existsSync(file)
173
+ ? `export const authHooksModule = () => import(${JSON.stringify(file)});\n`
174
+ : "export const authHooksModule = null;\n";
175
+ },
176
+ };
102
177
  return [
178
+ // First, so ids name lines in the source, before TanStack splits a route's component out of it.
179
+ ziteId(),
103
180
  tanstackStart({
104
181
  // TanStack resolves these from `src/`.
105
182
  server: { entry: `../${serverEntry.replace(/\.ts$/, "")}` },
@@ -122,7 +199,7 @@ export function zite(options = {}) {
122
199
  behavior: "error",
123
200
  client: {
124
201
  // Appended to TanStack's own.
125
- specifiers: ["zitejs/start/server", "zitejs/start/describe", "zitejs/runtime"],
202
+ specifiers: ["zitejs/start/server", "zitejs/start/worker", "zitejs/start/describe", "zitejs/runtime"],
126
203
  // Replaces TanStack's list, so its `**/*.server.*` is restated. File
127
204
  // patterns also catch `zitejs/db` and `zitejs/integrations`, which the
128
205
  // aliases above rewrite before specifiers are matched.
@@ -132,9 +209,9 @@ export function zite(options = {}) {
132
209
  }),
133
210
  options.cloudflare !== false ? loadCloudflare(serverEntry) : null,
134
211
  viteReact(),
135
- ziteId(),
136
212
  compileZitejs,
137
213
  functionIds,
138
214
  workflowRegistry,
215
+ authHooksRegistry,
139
216
  ];
140
217
  }
@@ -0,0 +1,6 @@
1
+ import { type ZiteServerOptions } from "./server.js";
2
+ export type ZiteWorker = new (ctx: unknown, env: unknown) => {
3
+ fetch(request: Request): Promise<Response>;
4
+ };
5
+ /** A Start app's Worker. The host sends it every request, with that request's props. */
6
+ export declare function createZiteWorker(options: ZiteServerOptions): ZiteWorker;
@@ -0,0 +1,12 @@
1
+ // For the generated server entry of a Workers build only. Apps never import this.
2
+ import { WorkerEntrypoint } from "cloudflare:workers";
3
+ import { createZiteHandlers } from "./server.js";
4
+ /** A Start app's Worker. The host sends it every request, with that request's props. */
5
+ export function createZiteWorker(options) {
6
+ const handlers = createZiteHandlers(options);
7
+ return class extends WorkerEntrypoint {
8
+ async fetch(request) {
9
+ return handlers.fetch(request, this.env, this.ctx);
10
+ }
11
+ };
12
+ }
@@ -1,36 +1,66 @@
1
- import type { ZiteTrigger, ZiteTriggerContext } from "../backend/index.js";
1
+ import type { ZiteTrigger, ZiteTriggerContext, ZiteTriggerSubscribe, ZiteTriggerUnsubscribe } from "../backend/index.js";
2
2
  import type { ZiteSchedule } from "../schedules/index.js";
3
+ import type { StartStep } from "./steps.js";
3
4
  declare const WORKFLOW: unique symbol;
4
- export type WorkflowConfig = {
5
- /** What this workflow does, in a sentence. Shown in the editor. */
5
+ type ProviderTriggerBase = Extract<ZiteTrigger, {
6
+ every?: never;
7
+ events?: never;
8
+ table?: never;
9
+ form?: never;
10
+ }>;
11
+ /**
12
+ * A provider trigger, registered with the provider by its `subscribe` when the
13
+ * app is published and taken down by its `unsubscribe` when it no longer is.
14
+ * Both run on the platform with only the trigger's own connection.
15
+ */
16
+ export type StartProviderTrigger = ProviderTriggerBase & {
17
+ subscribe: ZiteTriggerSubscribe;
18
+ unsubscribe?: ZiteTriggerUnsubscribe;
19
+ };
20
+ /** Database and form triggers aren't supported in a Start automation yet. */
21
+ export type StartTrigger = Exclude<ZiteTrigger, ProviderTriggerBase | {
22
+ table: string;
23
+ } | {
24
+ form: string;
25
+ }> | StartProviderTrigger;
26
+ export type AutomationConfig = {
27
+ /** What this automation does, in a sentence. Shown in the editor. */
6
28
  description?: string;
7
29
  } & ({
8
30
  schedule: ZiteSchedule;
9
31
  trigger?: never;
10
32
  } | {
11
- trigger: ZiteTrigger;
33
+ trigger: StartTrigger;
12
34
  schedule?: never;
35
+ } | {
36
+ schedule?: never;
37
+ trigger?: never;
13
38
  });
14
- /** What a workflow's handler gets. A trigger adds `trigger`, typed by the kind it declares. */
15
- export type WorkflowArgs<TConfig extends WorkflowConfig> = {
39
+ /**
40
+ * What an automation's handler gets. A trigger adds `trigger`, typed by the kind it declares.
41
+ * `step.run(name, fn)` runs `fn` once per run: its result is saved before the code after it,
42
+ * and a failed run resumed from run history replays completed steps from their saved results.
43
+ */
44
+ export type AutomationArgs<TConfig extends AutomationConfig> = {
16
45
  input: unknown;
46
+ step: StartStep;
17
47
  } & (TConfig extends {
18
48
  trigger: infer T;
19
49
  } ? {
20
50
  trigger: ZiteTriggerContext<T>;
21
51
  } : unknown);
22
- export type Workflow<TConfig extends WorkflowConfig = WorkflowConfig> = {
52
+ export type Automation<TConfig extends AutomationConfig = AutomationConfig> = {
23
53
  readonly [WORKFLOW]: true;
24
54
  readonly config: TConfig;
25
- readonly handler: (args: WorkflowArgs<TConfig>) => unknown;
55
+ readonly handler: (args: AutomationArgs<TConfig>) => unknown;
26
56
  };
27
57
  /**
28
58
  * Scheduled or triggered work, in a `*.server.ts` file:
29
- * `export const nightly = createWorkflow({ schedule }).handler(async () => { ... })`.
59
+ * `export const nightly = createAutomation({ schedule }).handler(async () => { ... })`.
30
60
  * Only the platform runs it. It has no user and no URL, and reads data like a server function does.
31
61
  */
32
- export declare function createWorkflow<const TConfig extends WorkflowConfig>(config: TConfig): {
33
- handler: (fn: (args: WorkflowArgs<TConfig>) => unknown) => Workflow<TConfig>;
62
+ export declare function createAutomation<const TConfig extends AutomationConfig>(config: TConfig): {
63
+ handler: (fn: (args: AutomationArgs<TConfig>) => unknown) => Automation<TConfig>;
34
64
  };
35
- export declare const isWorkflow: (value: unknown) => value is Workflow;
65
+ export declare const isAutomation: (value: unknown) => value is Automation;
36
66
  export {};
@@ -2,12 +2,12 @@
2
2
  const WORKFLOW = Symbol.for("zitejs:workflow");
3
3
  /**
4
4
  * Scheduled or triggered work, in a `*.server.ts` file:
5
- * `export const nightly = createWorkflow({ schedule }).handler(async () => { ... })`.
5
+ * `export const nightly = createAutomation({ schedule }).handler(async () => { ... })`.
6
6
  * Only the platform runs it. It has no user and no URL, and reads data like a server function does.
7
7
  */
8
- export function createWorkflow(config) {
8
+ export function createAutomation(config) {
9
9
  return {
10
10
  handler: (fn) => ({ [WORKFLOW]: true, config, handler: fn }),
11
11
  };
12
12
  }
13
- export const isWorkflow = (value) => typeof value === "object" && value !== null && value[WORKFLOW] === true;
13
+ export const isAutomation = (value) => typeof value === "object" && value !== null && value[WORKFLOW] === true;