zitejs 0.10.0-start.20 → 0.10.0-start.21

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 (60) hide show
  1. package/dist/cjs/auth/actions.d.ts +28 -0
  2. package/dist/cjs/auth/actions.js +93 -0
  3. package/dist/cjs/auth/client.d.ts +357 -0
  4. package/dist/cjs/auth/client.js +66 -0
  5. package/dist/cjs/auth/index.d.ts +2 -249
  6. package/dist/cjs/auth/index.js +11 -114
  7. package/dist/cjs/auth/index.test.js +18 -0
  8. package/dist/cjs/auth/profileUpdates.d.ts +9 -0
  9. package/dist/cjs/auth/profileUpdates.js +11 -0
  10. package/dist/cjs/check/start/sourceRules.js +70 -21
  11. package/dist/cjs/integrations/rules.js +5 -3
  12. package/dist/cjs/runtime/index.d.ts +54 -15
  13. package/dist/cjs/runtime/sendEmailParamsTypes.test-d.d.ts +1 -0
  14. package/dist/cjs/runtime/sendEmailParamsTypes.test-d.js +33 -0
  15. package/dist/cjs/sync/lib.js +10 -5
  16. package/dist/cjs/sync/lib.test.js +10 -0
  17. package/dist/esm/auth/actions.d.ts +28 -0
  18. package/dist/esm/auth/actions.js +55 -0
  19. package/dist/esm/auth/client.d.ts +357 -0
  20. package/dist/esm/auth/client.js +62 -0
  21. package/dist/esm/auth/index.d.ts +2 -249
  22. package/dist/esm/auth/index.js +2 -109
  23. package/dist/esm/auth/index.test.js +18 -0
  24. package/dist/esm/auth/profileUpdates.d.ts +9 -0
  25. package/dist/esm/auth/profileUpdates.js +6 -0
  26. package/dist/esm/check/start/sourceRules.js +70 -21
  27. package/dist/esm/integrations/rules.js +5 -3
  28. package/dist/esm/runtime/index.d.ts +54 -15
  29. package/dist/esm/runtime/sendEmailParamsTypes.test-d.d.ts +1 -0
  30. package/dist/esm/runtime/sendEmailParamsTypes.test-d.js +31 -0
  31. package/dist/esm/start/airtable/dispatch.js +3 -3
  32. package/dist/esm/start/airtable/formulas.d.ts +1 -1
  33. package/dist/esm/start/airtable/formulas.js +12 -10
  34. package/dist/esm/start/airtable/index.d.ts +2 -2
  35. package/dist/esm/start/describe.d.ts +8 -1
  36. package/dist/esm/start/describe.js +5 -3
  37. package/dist/esm/start/factories.test-d.d.ts +2 -1
  38. package/dist/esm/start/host.d.ts +2 -2
  39. package/dist/esm/start/index.d.ts +1 -1
  40. package/dist/esm/start/index.js +4 -2
  41. package/dist/esm/start/outbound.d.ts +2 -2
  42. package/dist/esm/start/outbound.js +3 -1
  43. package/dist/esm/start/router.d.ts +7 -0
  44. package/dist/esm/start/router.js +35 -0
  45. package/dist/esm/start/runLog.d.ts +2 -2
  46. package/dist/esm/start/scope.d.ts +3 -3
  47. package/dist/esm/start/server.d.ts +3 -3
  48. package/dist/esm/start/server.js +2 -1
  49. package/dist/esm/start/types.d.ts +1 -1
  50. package/dist/esm/start/version.d.ts +1 -1
  51. package/dist/esm/start/version.js +1 -1
  52. package/dist/esm/start/vite.js +3 -3
  53. package/dist/esm/start/workflow.d.ts +6 -2
  54. package/dist/esm/start/workflow.js +9 -2
  55. package/dist/esm/start/workflow.test-d.js +10 -1
  56. package/dist/esm/start/workflowRun.d.ts +5 -0
  57. package/dist/esm/start/workflowRun.js +11 -1
  58. package/dist/esm/sync/lib.js +10 -5
  59. package/dist/esm/sync/lib.test.js +10 -0
  60. package/package.json +1 -1
@@ -48,9 +48,9 @@ export type FilterOperators<V> = FilterCondition<V> | V;
48
48
  * object, the whole `{ equals: … }` is taken as the value, and the filter
49
49
  * fails.
50
50
  *
51
- * One operator per field on this path — `formulas.ts` reads
52
- * `Object.keys(condition)[0]` and drops the rest, unlike the Zite DB filter
53
- * builder which iterates them all.
51
+ * One operator per field on this path — `formulas.ts` reads the first key that
52
+ * is an operator and drops the rest, unlike the Zite DB filter builder which
53
+ * iterates them all.
54
54
  */
55
55
  export type AirtableFilterCondition<V> = FilterCondition<V> & {
56
56
  ilike?: V | V[];
@@ -257,7 +257,7 @@ export interface AirtableTableClient<T, TInput = T> {
257
257
  }): Promise<DeleteResult>;
258
258
  }
259
259
  export declare function createAirtableClient<T, TInput = T>(integrationId: string, className: string, implicitParams: Record<string, unknown>): AirtableTableClient<T, TInput>;
260
- /** A block of content in an email body. */
260
+ /** A block of the older `body` format. New emails are written with `html`. */
261
261
  export type EmailBlock = {
262
262
  type: "text";
263
263
  content: string;
@@ -266,11 +266,11 @@ export type EmailBlock = {
266
266
  label: string;
267
267
  href: string;
268
268
  alignment?: "left" | "center" | "right";
269
- /** A hex or `rgb()` color; defaults to the platform's button color. */
269
+ /** Hex colour, e.g. "#7c2d3a". Defaults to the platform blue. */
270
270
  backgroundColor?: string;
271
- /** A hex or `rgb()` color; defaults to white. */
271
+ /** Hex colour. Defaults to white. */
272
272
  textColor?: string;
273
- /** Corner radius in pixels; defaults to 6. */
273
+ /** Corner radius in pixels. Defaults to 6. */
274
274
  borderRadius?: number;
275
275
  } | {
276
276
  type: "image";
@@ -286,25 +286,23 @@ export type EmailBlock = {
286
286
  type: "divider";
287
287
  borderColor?: string;
288
288
  };
289
- export interface SendEmailParams {
289
+ interface SendEmailBaseParams {
290
290
  /** Recipient address(es). Must be valid emails — never placeholders like "me". */
291
291
  to: string | string[];
292
292
  subject: string;
293
- /** Email body as an array of content blocks. */
294
- body: EmailBlock[];
295
293
  cc?: string[];
296
294
  bcc?: string[];
297
295
  replyTo?: string;
298
- /** 'formatted' (default) for styled HTML, 'plain' for text-only. */
299
- layout?: "formatted" | "plain";
300
296
  /**
301
297
  * Text direction of the email. Use 'rtl' for right-to-left languages
302
298
  * (Hebrew, Arabic) — sets dir="rtl" on the email wrapper and right-aligns
303
- * text blocks. HTML like `<div dir="rtl">` inside text blocks is stripped
304
- * by the sanitizer and will NOT work. Defaults to 'ltr'.
299
+ * text. Defaults to 'ltr'.
305
300
  */
306
301
  direction?: "ltr" | "rtl";
307
- /** Custom logo shown above the email content (header area), for branding. */
302
+ /**
303
+ * Logo shown above the email content (header area), for branding. On an
304
+ * html email it replaces the brand kit's logo.
305
+ */
308
306
  logo?: {
309
307
  url: string;
310
308
  width?: number;
@@ -317,9 +315,50 @@ export interface SendEmailParams {
317
315
  contentType?: string;
318
316
  }[];
319
317
  }
318
+ /** An email written as HTML. */
319
+ export interface SendHtmlEmailParams extends SendEmailBaseParams {
320
+ /**
321
+ * Email-safe HTML: tables for layout, inline styles, `<a class="button">`
322
+ * for buttons. Sanitized and its `<style>` rules inlined at send time.
323
+ */
324
+ html: string;
325
+ /** Plain-text part. Generated from `html` when omitted. */
326
+ text?: string;
327
+ /**
328
+ * 'formatted' (default) puts the html in a card under the logo, in the
329
+ * app's brand kit; 'plain' drops the card and logo.
330
+ */
331
+ layout?: "formatted" | "plain";
332
+ /**
333
+ * Hex colour around the card, or behind a plain email's text as a sheet
334
+ * the width of its column. Defaults to the brand kit's.
335
+ */
336
+ background?: string;
337
+ /** Hex colour of the card in a formatted email. Defaults to the brand kit's. */
338
+ cardBackground?: string;
339
+ body?: never;
340
+ }
341
+ /**
342
+ * An email in the older block format. Existing emails keep working; new ones
343
+ * are written with `html`.
344
+ */
345
+ export interface SendBlocksEmailParams extends SendEmailBaseParams {
346
+ /** Email body as an array of content blocks. */
347
+ body: EmailBlock[];
348
+ /**
349
+ * 'formatted' (default) for styled HTML, 'plain' for text-only. HTML like
350
+ * `<div dir="rtl">` inside text blocks is stripped by the sanitizer.
351
+ */
352
+ layout?: "formatted" | "plain";
353
+ html?: never;
354
+ text?: never;
355
+ }
356
+ export type SendEmailParams = SendHtmlEmailParams | SendBlocksEmailParams;
320
357
  export interface SendEmailResult {
321
358
  success: boolean;
322
359
  messageId: string;
360
+ /** Problems that did not stop the send, e.g. an email large enough for Gmail to clip. */
361
+ warnings?: string[];
323
362
  }
324
363
  export interface EmailClient {
325
364
  send(params: SendEmailParams): Promise<SendEmailResult>;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,31 @@
1
+ import { expectTypeOf, test } from "vitest";
2
+ test("an email is written as html or as blocks, not both", () => {
3
+ expectTypeOf({
4
+ to: "a@example.com",
5
+ subject: "Hi",
6
+ html: "<p>Hi</p>",
7
+ layout: "plain",
8
+ background: "#e8efe6",
9
+ }).toExtend();
10
+ expectTypeOf({
11
+ to: "a@example.com",
12
+ subject: "Hi",
13
+ body: [{ type: "text", content: "Hi" }],
14
+ }).toExtend();
15
+ expectTypeOf({
16
+ to: "a@example.com",
17
+ subject: "Hi",
18
+ html: "<p>Hi</p>",
19
+ body: [],
20
+ }).not.toExtend();
21
+ expectTypeOf({
22
+ to: "a@example.com",
23
+ subject: "Hi",
24
+ html: "<p>Hi</p>",
25
+ layout: "none",
26
+ }).not.toExtend();
27
+ expectTypeOf({
28
+ to: "a@example.com",
29
+ subject: "Hi",
30
+ }).not.toExtend();
31
+ });
@@ -1,7 +1,7 @@
1
1
  // Ported from restly's apps/cloudflare-lambda/src/integrations/airtable.ts (`executeAirtableCall`), classic's
2
- // dispatch, which the Airtable goldens are recorded from, with a fetch client in place of the npm SDK. Keep the two
3
- // in step. Differences: fields come back by id from every request, so a rename since the lock never unmaps one;
4
- // the schema is the lock's (`nameMappings`), as the build bakes it; the per-base limiter is gone.
2
+ // dispatch, with a fetch client in place of the npm SDK. Keep the two in step. Differences: fields come back by id
3
+ // from every request, so a rename since the lock never unmaps one; the schema is the lock's (`nameMappings`), as the
4
+ // build bakes it; the per-base limiter is gone.
5
5
  import { filtersToFormula as buildFiltersFormula, isRecordId } from "./formulas.js";
6
6
  const SDK_ID_FIELD = "id";
7
7
  const UNIQUE_RECORD_ID_KEY = "recordID";
@@ -26,7 +26,7 @@ export declare const isNestedCondition: (value: unknown) => value is Partial<Rec
26
26
  /**
27
27
  * Check if a string is a valid Airtable record ID
28
28
  */
29
- export declare const isValidRecordId: (value: string) => boolean;
29
+ export declare const isValidRecordId: (value: unknown) => value is string;
30
30
  export declare const isRecordId: (value: unknown) => value is string;
31
31
  export type FiltersToFormulaOptions = {
32
32
  /**
@@ -43,9 +43,7 @@ const SDK_ID_FIELD = 'id';
43
43
  /**
44
44
  * Check if a string is a valid Airtable record ID
45
45
  */
46
- export const isValidRecordId = (value) => {
47
- return !!value.match(AIRTABLE_RECORD_ID_REGEX);
48
- };
46
+ export const isValidRecordId = (value) => typeof value === 'string' && AIRTABLE_RECORD_ID_REGEX.test(value);
49
47
  /**
50
48
  * Escape a string value for an Airtable formula. Backslashes go first: a
51
49
  * caller's trailing backslash would otherwise escape the closing quote and let
@@ -58,13 +56,16 @@ export const isRecordId = (value) => typeof value === 'string' && isValidRecordI
58
56
  const anyRecordIdOf = (recordIds) => recordIds.length
59
57
  ? `OR(${recordIds.map(id => `RECORD_ID() = '${id}'`).join(', ')})`
60
58
  : 'FALSE()';
59
+ // A linked record's id comes as a one-item list.
60
+ const singleValue = (value) => Array.isArray(value) && value.length === 1 ? value[0] : value;
61
61
  /**
62
- * Format a value for use in Airtable formulas
62
+ * Format a value for use in Airtable formulas. A lookup's value, or a linked
63
+ * record's primary value, comes as a one-item list, at any depth.
63
64
  */
64
- // A lookup's value, or a linked record's id or primary value, comes as a one-item list.
65
- const singleValue = (value) => Array.isArray(value) && value.length === 1 ? value[0] : value;
66
- const getAirtableFilterValue = (given) => {
67
- const value = singleValue(given);
65
+ const getAirtableFilterValue = (value) => {
66
+ if (Array.isArray(value) && value.length === 1) {
67
+ return getAirtableFilterValue(value[0]);
68
+ }
68
69
  if (value instanceof Date) {
69
70
  if (!Number.isFinite(value.getTime())) {
70
71
  throw new Error('Invalid Date passed to Airtable filter formula. Use a valid Date or ISO date string.');
@@ -164,8 +165,9 @@ export const filtersToFormula = async ({ filters, tableSchema, getPrimaryFieldFo
164
165
  // Resolve record IDs to primary field values
165
166
  if (linkedRecordOptions?.linkedTableId) {
166
167
  value = (await Promise.all(linkedRecords.map(async (recordValue) => {
167
- if (isValidRecordId(recordValue)) {
168
- const primaryColumn = await getPrimaryFieldForRecord(linkedRecordOptions.linkedTableId, recordValue);
168
+ const recordId = singleValue(recordValue);
169
+ if (isValidRecordId(recordId)) {
170
+ const primaryColumn = await getPrimaryFieldForRecord(linkedRecordOptions.linkedTableId, recordId);
169
171
  if (primaryColumn) {
170
172
  return primaryColumn;
171
173
  }
@@ -1,8 +1,8 @@
1
1
  import { type AirtableSettings } from "./dispatch.js";
2
- import type { PlatformSession, ZiteRequestContext } from "../types.js";
2
+ import type { PlatformSession, HostRequestState } from "../types.js";
3
3
  /** The build's Airtable integration `integrationId`, or undefined when it isn't one. */
4
4
  export declare const airtableSettingsOf: (session: PlatformSession, integrationId: string) => Promise<AirtableSettings | undefined>;
5
5
  /** One generated Airtable table call, run here with the connection's token, which the outbound fetch refreshes on a 401. */
6
- export declare function runAirtableCall(host: ZiteRequestContext, session: PlatformSession, integrationId: string, settings: AirtableSettings, methodName: string, params: unknown, access: "signedIn" | "anyone" | "webhook" | "workflow"): Promise<unknown>;
6
+ export declare function runAirtableCall(host: HostRequestState, session: PlatformSession, integrationId: string, settings: AirtableSettings, methodName: string, params: unknown, access: "signedIn" | "anyone" | "webhook" | "workflow"): Promise<unknown>;
7
7
  /** For tests: forget what this isolate learned. */
8
8
  export declare const resetAirtableSettings: () => void;
@@ -73,7 +73,10 @@ type RouteLike = {
73
73
  };
74
74
  export declare function describePages(routesById: Record<string, RouteLike>, files?: Record<string, string>): DescribedPage[];
75
75
  export declare function describeRoutes(routesById: Record<string, RouteLike>, files?: Record<string, string>): DescribedRoute[];
76
- export declare function describeWorkflows(workflows: LoadedWorkflow[], hashes?: Record<string, string>): DescribedWorkflow[];
76
+ export declare function describeWorkflows(workflows: LoadedWorkflow[], hashes?: Record<string, string>, unfinished?: Array<{
77
+ id: string;
78
+ file: string;
79
+ }>): DescribedWorkflow[];
77
80
  export declare function describeApp(opts: {
78
81
  fnIds: string[];
79
82
  descriptions?: Record<string, string>;
@@ -82,5 +85,9 @@ export declare function describeApp(opts: {
82
85
  getRouter: () => unknown;
83
86
  request: Request;
84
87
  workflows?: LoadedWorkflow[];
88
+ unfinishedWorkflows?: Array<{
89
+ id: string;
90
+ file: string;
91
+ }>;
85
92
  }): Promise<Description>;
86
93
  export {};
@@ -146,10 +146,11 @@ export function describeRoutes(routesById, files = {}) {
146
146
  }
147
147
  return out;
148
148
  }
149
+ const HANDLER_MISSING = "workflow-handler-missing: give createAutomation its function with .handler(async (args) => { ... }), not in its config";
149
150
  // A workflow's id is its export name: what the host invokes it by and the editor shows. `hashes` are the registration
150
151
  // hashes zite() read from the app's source; one it couldn't read is hashed from the built functions, names numbered.
151
- export function describeWorkflows(workflows, hashes = {}) {
152
- return workflows.map(({ id, file, workflow }) => {
152
+ export function describeWorkflows(workflows, hashes = {}, unfinished = []) {
153
+ const described = workflows.map(({ id, file, workflow }) => {
153
154
  const problems = [];
154
155
  if (id === "default")
155
156
  problems.push("workflow-default-export: export it by name, which becomes its id");
@@ -180,6 +181,7 @@ export function describeWorkflows(workflows, hashes = {}) {
180
181
  };
181
182
  return { id, file, description, trigger: declared, registration, problems };
182
183
  });
184
+ return [...described, ...unfinished.map(({ id, file }) => ({ id, file, problems: [HANDLER_MISSING] }))];
183
185
  }
184
186
  export async function describeApp(opts) {
185
187
  const functions = [];
@@ -193,7 +195,7 @@ export async function describeApp(opts) {
193
195
  functions,
194
196
  routes: describeRoutes(routesById, opts.routeFiles),
195
197
  pages: describePages(routesById, opts.routeFiles),
196
- workflows: describeWorkflows(opts.workflows ?? [], opts.registrationHashes),
198
+ workflows: describeWorkflows(opts.workflows ?? [], opts.registrationHashes, opts.unfinishedWorkflows),
197
199
  authHooks: Object.keys(await loadAuthHooks()),
198
200
  };
199
201
  }
@@ -1 +1,2 @@
1
- export {};
1
+ import type { ZiteRequestContext } from "./index.js";
2
+ export type Unexported = ZiteRequestContext;
@@ -1,3 +1,3 @@
1
- import type { ZiteRequestContext } from "./types.js";
1
+ import type { HostRequestState } from "./types.js";
2
2
  export declare const HOST_STORE_KEY: unique symbol;
3
- export declare const currentHost: () => ZiteRequestContext | undefined;
3
+ export declare const currentHost: () => HostRequestState | undefined;
@@ -1,5 +1,5 @@
1
1
  import type { User } from "./types.js";
2
- export type { Role, User, ZiteRequestContext } from "./types.js";
2
+ export type { Role, User } from "./types.js";
3
3
  export { isSignInRequired, SIGN_IN_REQUIRED, ZiteError, ZITE_ERROR_STATUS, type ZiteErrorCode, type ZiteErrorOptions, } from "./errors.js";
4
4
  export { createZiteRouter, type ZiteRouterContext } from "./router.js";
5
5
  export { createAutomation, type StartProviderTrigger, type StartTrigger, type Automation, type AutomationArgs, type AutomationConfig, } from "./workflow.js";
@@ -132,8 +132,10 @@ export const webhook = Object.assign(webhookMiddleware(false), { paused: webhook
132
132
  export const role = (id) => tag(createMiddleware()
133
133
  .middleware([signedIn])
134
134
  .server(({ next, context, serverFnMeta }) => withStatus(!!serverFnMeta, async () => {
135
- if (!hasRole(context.user, id))
136
- throw new ZiteError("FORBIDDEN", `Requires the ${id} role`);
135
+ if (!hasRole(context.user, id)) {
136
+ // A role's id means nothing to the app's users; the editor still reads which one.
137
+ throw new ZiteError({ code: "FORBIDDEN", message: `Requires the ${id} role`, userFacingMessage: "You don't have access to this." });
138
+ }
137
139
  return next();
138
140
  })), { kind: "role", role: id });
139
141
  // TanStack's compiler tags every server function it compiles with an id. A
@@ -5,7 +5,7 @@
5
5
  * refreshed and sent once more; and a call on Zite's own AI key sent to the
6
6
  * host over the app's platform binding.
7
7
  */
8
- import type { ZiteRequestContext } from "./types.js";
8
+ import type { HostRequestState } from "./types.js";
9
9
  /** An `integrations.get` answer, whose values name the calls that carry them. */
10
- export declare const rememberConnection: (host: ZiteRequestContext, name: string, connection: unknown) => void;
10
+ export declare const rememberConnection: (host: HostRequestState, name: string, connection: unknown) => void;
11
11
  export declare const createOutboundFetch: (nativeFetch: typeof fetch) => typeof fetch;
@@ -337,8 +337,10 @@ export const createOutboundFetch = (nativeFetch) => async (input, init) => {
337
337
  record({ status: refused.status });
338
338
  return refused;
339
339
  }
340
- // Whole, so it crosses RPC as bytes whatever stream the app built it from.
340
+ // Whole, so it crosses RPC as bytes whatever stream the app built it from, and sized, so the host
341
+ // reserves only what it is rather than the most it allows.
341
342
  const body = base.body ? await base.arrayBuffer() : undefined;
343
+ headers.set("content-length", String(body?.byteLength ?? 0));
342
344
  const response = await session.aiFetch(new Request(ai.target, { method: base.method, headers, body, redirect: "manual" }));
343
345
  record({ status: response.status });
344
346
  return response;
@@ -1,5 +1,6 @@
1
1
  import { QueryClient } from "@tanstack/react-query";
2
2
  import { type AnyRoute, type RouterConstructorOptions, type RouterHistory } from "@tanstack/react-router";
3
+ import { type ProfileChanges } from "../auth/profileUpdates.js";
3
4
  import type { HostMode, User } from "./types.js";
4
5
  export declare const QUERY_STALE_TIME_MS = 30000;
5
6
  /** The router context every Zite app's root route declares: `createRootRouteWithContext<ZiteRouterContext>()`. */
@@ -13,6 +14,12 @@ type Dehydrated = {
13
14
  };
14
15
  /** @internal What a page carries to the browser beside its queries: the signed-in user, and the mode it was served in. */
15
16
  export declare const dehydrateZite: (context: ZiteRouterContext) => Dehydrated;
17
+ /** @internal The user after a profile edit, named as the host names them: first and last name, else the email. */
18
+ export declare const withProfile: (user: User, changes: ProfileChanges) => User;
19
+ /** @internal In the browser: `updateProfile` from zitejs/auth updates the router's user and reruns its guards and loaders. */
20
+ export declare const refreshOnProfileUpdate: (router: {
21
+ invalidate: () => Promise<void>;
22
+ }, context: ZiteRouterContext) => void;
16
23
  /** @internal Takes in what the page carried. */
17
24
  export declare const hydrateZite: (context: ZiteRouterContext, dehydrated: Dehydrated) => void;
18
25
  type ZiteRouterOptions<TRouteTree extends AnyRoute> = Omit<RouterConstructorOptions<TRouteTree, "never", false, RouterHistory, Dehydrated>, "context" | "dehydrate" | "hydrate">;
@@ -6,10 +6,30 @@ import { asCrossed, errorFromThrown, isSignInError, withThrownRejections } from
6
6
  import { carryPreviewClaim, PREVIEW_CLAIM_PARAM, previewClaim } from "./previewClaim.js";
7
7
  import { currentHost } from "./host.js";
8
8
  import { keepRenderedMode } from "../internal/appMode.js";
9
+ import { onProfileUpdated } from "../auth/profileUpdates.js";
9
10
  // Long enough that a page's queries don't refetch as the browser picks it up, short enough to stay fresh.
10
11
  export const QUERY_STALE_TIME_MS = 30_000;
11
12
  /** @internal What a page carries to the browser beside its queries: the signed-in user, and the mode it was served in. */
12
13
  export const dehydrateZite = (context) => ({ user: context.user, mode: currentHost()?.mode });
14
+ /** @internal The user after a profile edit, named as the host names them: first and last name, else the email. */
15
+ export const withProfile = (user, changes) => {
16
+ const { firstName: _firstName, lastName: _lastName, ...rest } = user;
17
+ const firstName = changes.firstName !== undefined ? changes.firstName : user.firstName;
18
+ const lastName = changes.lastName !== undefined ? changes.lastName : user.lastName;
19
+ return {
20
+ ...rest,
21
+ name: [firstName, lastName].filter(Boolean).join(" ") || user.email,
22
+ ...(firstName && { firstName }),
23
+ ...(lastName && { lastName }),
24
+ };
25
+ };
26
+ /** @internal In the browser: `updateProfile` from zitejs/auth updates the router's user and reruns its guards and loaders. */
27
+ export const refreshOnProfileUpdate = (router, context) => onProfileUpdated((changes) => {
28
+ if (!context.user)
29
+ return;
30
+ context.user = withProfile(context.user, changes);
31
+ void router.invalidate();
32
+ });
13
33
  /** @internal Takes in what the page carried. */
14
34
  export const hydrateZite = (context, dehydrated) => {
15
35
  context.user = dehydrated.user;
@@ -153,5 +173,20 @@ export function createZiteRouter(options) {
153
173
  const host = currentHost();
154
174
  if (host)
155
175
  host.router = router;
176
+ if (typeof window === "undefined")
177
+ refuseOtherRequests(router, host);
178
+ else
179
+ refreshOnProfileUpdate(router, context);
156
180
  return router;
157
181
  }
182
+ // A router built once for the isolate would render the first visitor's user and cached queries into every
183
+ // later visitor's page, and its guards would treat everyone as that visitor.
184
+ const refuseOtherRequests = (router, builtFor) => {
185
+ const load = router.load.bind(router);
186
+ router.load = async (...args) => {
187
+ if (currentHost() !== builtFor) {
188
+ throw new Error("This router was built for another request. Call createZiteRouter inside getRouter, so each request gets its own.");
189
+ }
190
+ return load(...args);
191
+ };
192
+ };
@@ -1,8 +1,8 @@
1
- import type { RunRecord, ZiteRequestContext } from "./types.js";
1
+ import type { RunRecord, HostRequestState } from "./types.js";
2
2
  export declare const preview: (value: unknown) => string | undefined;
3
3
  export declare const errorOf: (error: unknown) => NonNullable<RunRecord["error"]>;
4
4
  /**
5
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
6
  * read from copies after the fact, so the response never waits; the run log waits for them before it flushes.
7
7
  */
8
- export declare function recordRoute<T>(host: ZiteRequestContext | undefined, request: Request, run: () => Promise<T>): Promise<T>;
8
+ export declare function recordRoute<T>(host: HostRequestState | undefined, request: Request, run: () => Promise<T>): Promise<T>;
@@ -1,4 +1,4 @@
1
- import type { AccessKind, User, ZiteRequestContext } from "./types.js";
1
+ import type { AccessKind, User, HostRequestState } from "./types.js";
2
2
  export type { AccessKind } from "./types.js";
3
3
  export type AccessScope = {
4
4
  kind: AccessKind;
@@ -11,5 +11,5 @@ export declare class NoAccessDecisionError extends Error {
11
11
  constructor(what: string);
12
12
  }
13
13
  export declare const requireScope: (what: string) => AccessScope;
14
- export declare const runWithHost: <T>(host: ZiteRequestContext, fn: () => T) => T;
15
- export declare const getHost: () => ZiteRequestContext | undefined;
14
+ export declare const runWithHost: <T>(host: HostRequestState, fn: () => T) => T;
15
+ export declare const getHost: () => HostRequestState | undefined;
@@ -1,4 +1,4 @@
1
- import type { HostProps, PlatformBinding, ZiteRequestContext } from "./types.js";
1
+ import type { HostProps, PlatformBinding, HostRequestState } from "./types.js";
2
2
  export { runWithHost } from "./scope.js";
3
3
  export { describeApp } from "./describe.js";
4
4
  export type { HostProps, PlatformBinding, PlatformCallInput, PlatformCallResult, PlatformSession, RunRecord } from "./types.js";
@@ -10,13 +10,13 @@ export type { HostProps, PlatformBinding, PlatformCallInput, PlatformCallResult,
10
10
  */
11
11
  export declare function installPlatformTransport(): void;
12
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;
13
+ export declare function hostContextFromProps(request: Request, props: HostProps): HostRequestState;
14
14
  /**
15
15
  * A request the host didn't dispatch: the host's warm-up, `zitejs describe` under `vite preview`, and tests. Only the
16
16
  * host can set props, so without them a build answers warm and describe and nobody is signed in. An entry that passes
17
17
  * its own platform (tests, local dev) owns its requests and may say who is calling in `x-zite-*` headers.
18
18
  */
19
- export declare function hostContextFromRequest(request: Request, platform?: PlatformBinding): ZiteRequestContext;
19
+ export declare function hostContextFromRequest(request: Request, platform?: PlatformBinding): HostRequestState;
20
20
  /** Every server function TanStack compiled, written in by `zite()` at build. Empty in dev, where TanStack doesn't call its id hook. */
21
21
  export declare const builtFunctionIds: () => string[];
22
22
  /** Each server function's `description` option, written in by `zite()` at build. */
@@ -14,7 +14,7 @@ import { createOutboundFetch, rememberConnection } from "./outbound.js";
14
14
  import { INTEGRATIONS_PLATFORM_ID } from "./credentials.js";
15
15
  import { getHost, requireScope, runInScope, runWithHost } from "./scope.js";
16
16
  import { ZITEJS_VERSION } from "./version.js";
17
- import { loadWorkflows, loggedInput, runWorkflow } from "./workflowRun.js";
17
+ import { loadUnfinishedWorkflows, loadWorkflows, loggedInput, runWorkflow } from "./workflowRun.js";
18
18
  export { runWithHost } from "./scope.js";
19
19
  export { describeApp } from "./describe.js";
20
20
  /**
@@ -351,6 +351,7 @@ export function createZiteHandlers(options) {
351
351
  getRouter: options.getRouter,
352
352
  request,
353
353
  workflows: await loadedWorkflows(),
354
+ unfinishedWorkflows: await loadUnfinishedWorkflows(),
354
355
  }), { headers: { [RUNTIME_VERSION_HEADER]: ZITEJS_VERSION } });
355
356
  }
356
357
  let response = await runWithHost(host, async () => host.invoke?.kind === "workflow"
@@ -162,7 +162,7 @@ export type HostProps = {
162
162
  runRoot?: string;
163
163
  };
164
164
  /** What the host resolved for this request. Set by the generated server entry, never by the browser. */
165
- export type ZiteRequestContext = {
165
+ export type HostRequestState = {
166
166
  requestId: string;
167
167
  url: string;
168
168
  user: User | null;
@@ -1 +1 @@
1
- export declare const ZITEJS_VERSION = "0.10.0-start.20";
1
+ export declare const ZITEJS_VERSION = "0.10.0-start.21";
@@ -1,2 +1,2 @@
1
1
  // Written by scripts/write-version.mjs from package.json.
2
- export const ZITEJS_VERSION = "0.10.0-start.20";
2
+ export const ZITEJS_VERSION = "0.10.0-start.21";
@@ -201,9 +201,9 @@ export function zite(options = {}) {
201
201
  // Appended to TanStack's own.
202
202
  specifiers: ["zitejs/start/server", "zitejs/start/worker", "zitejs/start/describe", "zitejs/runtime"],
203
203
  // Replaces TanStack's list, so its `**/*.server.*` is restated. File
204
- // patterns also catch `zitejs/db` and `zitejs/integrations`, which the
205
- // aliases above rewrite before specifiers are matched.
206
- files: ["**/*.server.*", "**/.zite/db.ts", "**/.zite/integrations/**"],
204
+ // patterns also catch `zitejs/db`, `zitejs/integrations` and `zitejs/meta`,
205
+ // which the aliases above rewrite before specifiers are matched.
206
+ files: ["**/*.server.*", "**/.zite/db.ts", "**/.zite/integrations/**", "**/.zite/meta.ts"],
207
207
  },
208
208
  },
209
209
  }),
@@ -2,6 +2,7 @@ import type { ZiteTrigger, ZiteTriggerContext, ZiteTriggerSubscribe, ZiteTrigger
2
2
  import type { ZiteSchedule } from "../schedules/index.js";
3
3
  import type { StartStep } from "./steps.js";
4
4
  declare const WORKFLOW: unique symbol;
5
+ declare const UNFINISHED: unique symbol;
5
6
  type ProviderTriggerBase = Extract<ZiteTrigger, {
6
7
  every?: never;
7
8
  events?: never;
@@ -15,7 +16,7 @@ type ProviderTriggerBase = Extract<ZiteTrigger, {
15
16
  */
16
17
  export type StartProviderTrigger = ProviderTriggerBase & {
17
18
  subscribe: ZiteTriggerSubscribe;
18
- unsubscribe?: ZiteTriggerUnsubscribe;
19
+ unsubscribe: ZiteTriggerUnsubscribe;
19
20
  };
20
21
  /** Database and form triggers aren't supported in a Start automation yet. */
21
22
  export type StartTrigger = Exclude<ZiteTrigger, ProviderTriggerBase | {
@@ -59,8 +60,11 @@ export type Automation<TConfig extends AutomationConfig = AutomationConfig> = {
59
60
  * `export const nightly = createAutomation({ schedule }).handler(async () => { ... })`.
60
61
  * Only the platform runs it. It has no user and no URL, and reads data like a server function does.
61
62
  */
62
- export declare function createAutomation<const TConfig extends AutomationConfig>(config: TConfig): {
63
+ export declare function createAutomation<const TConfig extends AutomationConfig>(config: TConfig & Record<Exclude<keyof TConfig, "description" | "schedule" | "trigger">, never>): {
64
+ [UNFINISHED]: boolean;
63
65
  handler: (fn: (args: AutomationArgs<TConfig>) => unknown) => Automation<TConfig>;
64
66
  };
65
67
  export declare const isAutomation: (value: unknown) => value is Automation;
68
+ /** `createAutomation(...)` exported without its `.handler()`, which nothing would ever run. */
69
+ export declare const isUnfinishedAutomation: (value: unknown) => boolean;
66
70
  export {};
@@ -1,13 +1,20 @@
1
1
  // Shared across copies of zitejs in one bundle, like the access scope.
2
2
  const WORKFLOW = Symbol.for("zitejs:workflow");
3
+ const UNFINISHED = Symbol.for("zitejs:automation-without-handler");
3
4
  /**
4
5
  * Scheduled or triggered work, in a `*.server.ts` file:
5
6
  * `export const nightly = createAutomation({ schedule }).handler(async () => { ... })`.
6
7
  * Only the platform runs it. It has no user and no URL, and reads data like a server function does.
7
8
  */
8
- export function createAutomation(config) {
9
+ export function createAutomation(
10
+ // Inferring TConfig skips the excess-key check, so a classic `{ handler }` in the config would typecheck.
11
+ config) {
9
12
  return {
13
+ [UNFINISHED]: true,
10
14
  handler: (fn) => ({ [WORKFLOW]: true, config, handler: fn }),
11
15
  };
12
16
  }
13
- export const isAutomation = (value) => typeof value === "object" && value !== null && value[WORKFLOW] === true;
17
+ const tagged = (value, tag) => typeof value === "object" && value !== null && value[tag] === true;
18
+ export const isAutomation = (value) => tagged(value, WORKFLOW);
19
+ /** `createAutomation(...)` exported without its `.handler()`, which nothing would ever run. */
20
+ export const isUnfinishedAutomation = (value) => tagged(value, UNFINISHED);
@@ -19,9 +19,11 @@ describe("createAutomation handler args", () => {
19
19
  expectTypeOf(trigger).toEqualTypeOf();
20
20
  });
21
21
  });
22
- it("registers a provider trigger with subscribe", () => {
22
+ it("registers a provider trigger with subscribe, and takes it down with unsubscribe", () => {
23
23
  // @ts-expect-error nothing would register it with the provider
24
24
  createAutomation({ trigger: { integration: "asana" } });
25
+ // @ts-expect-error its registration would outlive it
26
+ createAutomation({ trigger: { integration: "asana", subscribe: async () => ({ externalId: "w1" }) } });
25
27
  createAutomation({
26
28
  trigger: {
27
29
  integration: "github",
@@ -29,6 +31,7 @@ describe("createAutomation handler args", () => {
29
31
  expectTypeOf(input.notificationUrl).toEqualTypeOf();
30
32
  return { externalId: "1", secret: input.secret };
31
33
  },
34
+ unsubscribe: async () => { },
32
35
  },
33
36
  });
34
37
  });
@@ -50,6 +53,12 @@ describe("createAutomation handler args", () => {
50
53
  expectTypeOf(await step.run("count", () => 3)).toEqualTypeOf();
51
54
  });
52
55
  });
56
+ it("takes its function in .handler(), not in its config as classic's does", () => {
57
+ // @ts-expect-error nothing would run it
58
+ createAutomation({ trigger: { every: "5m" }, handler: async () => { } });
59
+ // @ts-expect-error nor any other key it doesn't know
60
+ createAutomation({ description: "Nightly", retries: 3 });
61
+ });
53
62
  it("takes a schedule or a trigger, not both", () => {
54
63
  // @ts-expect-error an automation runs on one or the other
55
64
  createAutomation({ schedule: { scheduleType: "oneTime", fireAt: "x", timezone: "UTC" }, trigger: { every: "5m" } });
@@ -88,6 +88,11 @@ export type LoadedWorkflow = {
88
88
  };
89
89
  /** Every exported workflow in the app, by export name. */
90
90
  export declare function loadWorkflows(modules?: Record<string, () => Promise<Record<string, unknown>>>): Promise<LoadedWorkflow[]>;
91
+ /** Each `createAutomation(...)` exported without its `.handler()`, by export name: describe refuses them. */
92
+ export declare function loadUnfinishedWorkflows(modules?: Record<string, () => Promise<Record<string, unknown>>>): Promise<Array<{
93
+ id: string;
94
+ file: string;
95
+ }>>;
91
96
  /** The input as the run log keeps it: a trigger's `seen` list can hold thousands of ids. */
92
97
  export declare const loggedInput: (rawInput: unknown) => unknown;
93
98
  export {};