zitejs 0.10.0-start.22 → 0.10.0-start.24

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 (42) hide show
  1. package/dist/cjs/cli.js +1 -1
  2. package/dist/cjs/start/provider.d.ts +2 -2
  3. package/dist/cjs/start/provider.js +7 -7
  4. package/dist/cjs/start/types.d.ts +32 -50
  5. package/dist/cjs/sync/lib.js +23 -50
  6. package/dist/cjs/sync/sdkNames.d.ts +65 -7
  7. package/dist/cjs/sync/sdkNames.js +76 -12
  8. package/dist/cjs/sync/sdkNames.test.js +38 -0
  9. package/dist/esm/cli.js +1 -1
  10. package/dist/esm/start/airtable/built.d.ts +2 -0
  11. package/dist/esm/start/airtable/built.js +3 -0
  12. package/dist/esm/start/airtable/index.d.ts +3 -5
  13. package/dist/esm/start/airtable/index.js +4 -25
  14. package/dist/esm/start/airtable/settings.d.ts +31 -0
  15. package/dist/esm/start/airtable/settings.js +110 -0
  16. package/dist/esm/start/data/index.d.ts +21 -9
  17. package/dist/esm/start/data/index.js +26 -20
  18. package/dist/esm/start/data/names.d.ts +7 -0
  19. package/dist/esm/start/data/names.js +15 -0
  20. package/dist/esm/start/data/types.d.ts +4 -1
  21. package/dist/esm/start/direct.d.ts +16 -12
  22. package/dist/esm/start/direct.js +185 -56
  23. package/dist/esm/start/outbound.d.ts +4 -5
  24. package/dist/esm/start/outbound.js +38 -49
  25. package/dist/esm/start/provider.d.ts +2 -2
  26. package/dist/esm/start/provider.js +7 -7
  27. package/dist/esm/start/server.d.ts +17 -13
  28. package/dist/esm/start/server.js +43 -45
  29. package/dist/esm/start/telemetry.d.ts +4 -1
  30. package/dist/esm/start/telemetry.js +13 -16
  31. package/dist/esm/start/types.d.ts +32 -50
  32. package/dist/esm/start/version.d.ts +1 -1
  33. package/dist/esm/start/version.js +1 -1
  34. package/dist/esm/start/vite.d.ts +7 -1
  35. package/dist/esm/start/vite.js +68 -21
  36. package/dist/esm/start/workspaceSchema.d.ts +2 -1
  37. package/dist/esm/start/workspaceSchema.js +3 -3
  38. package/dist/esm/sync/lib.js +23 -50
  39. package/dist/esm/sync/sdkNames.d.ts +65 -7
  40. package/dist/esm/sync/sdkNames.js +73 -11
  41. package/dist/esm/sync/sdkNames.test.js +38 -0
  42. package/package.json +2 -2
package/dist/cjs/cli.js CHANGED
@@ -87,7 +87,7 @@ async function main() {
87
87
  console.error("A Start app under `vite dev` reaches Zite's data and services with these, from the app's .env:");
88
88
  console.error(" ZITE_DEV_API_KEY Your Zite API key, as the MCP takes it: mints dev tokens for the app zite.config.json's id names; each lasts 15 minutes and is renewed before it expires");
89
89
  console.error(' ZITE_DEV_TOKEN A dev token to use as it is instead, never renewed');
90
- console.error(' ZITE_URLS JSON naming the platform: {"baseRunner","backend","aiGateway"?,"runs"?,"email"?,"pdf"?,"uploads"?,"steps"?}; a service it doesn\'t name is the backend\'s');
90
+ console.error(' ZITE_URLS JSON naming the platform: {"baseRunner","backend","gateway"?,"runs"?,"email"?,"pdf"?,"uploads"?,"steps"?}; a service it doesn\'t name is the backend\'s');
91
91
  console.error(' ZITE_DEV_USER JSON of the signed-in stand-in: {"id","email","name"?,"roles"?,"isInternal"?}; unset, nobody is');
92
92
  process.exit(1);
93
93
  }
@@ -1,6 +1,6 @@
1
1
  import { type AppTokenClaims } from "../internal/appToken.js";
2
- import type { HostMode, HostProps, PlatformProvider, PlatformSession, PlatformUrls } from "./types.js";
3
- export declare const ziteProvider: (props: HostProps, session: () => Promise<PlatformSession | undefined>) => PlatformProvider;
2
+ import type { HostMode, HostProps, PlatformProvider, PlatformUrls } from "./types.js";
3
+ export declare const ziteProvider: (props: HostProps) => PlatformProvider;
4
4
  /** What `local` reads, documented in `zitejs`'s help. */
5
5
  export declare const LOCAL_ENV: {
6
6
  readonly token: "ZITE_DEV_TOKEN";
@@ -12,21 +12,21 @@ const expiresWithin = (token, ms) => {
12
12
  const claims = (0, appToken_js_1.appTokenClaims)(token);
13
13
  return claims !== undefined && claims.exp * 1000 - Date.now() < ms;
14
14
  };
15
- const URL_NAMES = ["baseRunner", "backend", "aiGateway", "runs", "email", "pdf", "uploads", "steps"];
16
- // `local` may leave out the AI gateway (a call on Zite's AI key is then refused), `runs` (a preview sends no analytics,
15
+ const URL_NAMES = ["baseRunner", "backend", "gateway", "runs", "email", "pdf", "uploads", "steps"];
16
+ // `local` may leave out the gateway (a call on Zite's AI key is then refused), `runs` (a preview sends no analytics,
17
17
  // and `local` keeps no run detail) and each service's own URL (the backend then answers it).
18
- const OPTIONAL_URLS = new Set(["aiGateway", "runs", "email", "pdf", "uploads", "steps"]);
18
+ const OPTIONAL_URLS = new Set(["gateway", "runs", "email", "pdf", "uploads", "steps"]);
19
19
  const trimmed = (urls) => Object.fromEntries(URL_NAMES.flatMap((name) => (urls[name] ? [[name, urls[name].replace(/\/+$/, "")]] : [])));
20
- const ziteProvider = (props, session) => {
20
+ const ziteProvider = (props) => {
21
21
  let current = props.appToken;
22
22
  let renewing;
23
23
  const renew = async () => {
24
24
  try {
25
- const fresh = await (await session())?.appToken?.();
25
+ const fresh = await props.platform.appToken();
26
26
  return typeof fresh === "string" && fresh ? fresh : undefined;
27
27
  }
28
28
  catch (error) {
29
- // A host that predates renewal: the token holds until it expires.
29
+ // The token held still serves until it expires.
30
30
  console.error("[zite] couldn't renew the app token", error);
31
31
  return undefined;
32
32
  }
@@ -60,7 +60,7 @@ const localUrls = (raw) => {
60
60
  const given = (parsed ?? {});
61
61
  const isUrl = (value) => typeof value === "string" && /^https?:\/\//.test(value);
62
62
  if (URL_NAMES.some((name) => (given[name] === undefined ? !OPTIONAL_URLS.has(name) : !isUrl(given[name])))) {
63
- throw new Error(`${exports.LOCAL_ENV.urls} must be JSON naming the baseRunner and backend URLs, and may name aiGateway, runs, email, pdf, uploads and steps`);
63
+ throw new Error(`${exports.LOCAL_ENV.urls} must be JSON naming the baseRunner and backend URLs, and may name gateway, runs, email, pdf, uploads and steps`);
64
64
  }
65
65
  return trimmed(given);
66
66
  };
@@ -50,10 +50,7 @@ export type PlatformCallInput = {
50
50
  /** The access decision the call ran under; the platform may narrow on it but never widens. */
51
51
  access: AccessKind;
52
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
- */
53
+ /** A call's answer. Errors come back as values, so the one the app sees keeps its code. */
57
54
  export type PlatformCallResult = {
58
55
  value: unknown;
59
56
  } | {
@@ -96,40 +93,8 @@ export type FetchRecord = {
96
93
  /** What a call on the org's own AI key used, for analytics. */
97
94
  ai?: AiUsageRecord;
98
95
  };
99
- export type PlatformSession = {
100
- call(call: PlatformCallInput): Promise<PlatformCallResult>;
101
- /** As `PlatformBinding.runs`, on a session the request already holds, with its data calls and fetches. */
102
- runs(batch: {
103
- runs: RunRecord[];
104
- calls?: CallRecord[];
105
- fetches?: FetchRecord[];
106
- }): Promise<void>;
107
- /** After a provider answered 401: the connection refreshed, as `integrations.get` now answers it. */
108
- refreshConnection(name: string): Promise<PlatformCallResult>;
109
- /** A call on Zite's own AI key, which the host makes with the real key: for a request with no token or gateway. */
110
- aiFetch(request: Request): Promise<Response>;
111
- /** The build's base and SDK names, which the app's data dispatch translates against. */
112
- dataContext(): Promise<{
113
- baseId: string | null;
114
- nameMappings: unknown;
115
- }>;
116
- /** One base-runner request; the host holds it to the build's base and adds the key and acting user. */
117
- dataFetch(request: {
118
- method: string;
119
- path: string;
120
- body?: string;
121
- }): Promise<Response>;
122
- /** An integration's settings as the build declares them; null for one it doesn't, or that runs on the platform. */
123
- integrationSettings(integrationId: string): Promise<{
124
- serviceType: string;
125
- baseId?: string;
126
- nameMappings?: unknown;
127
- } | null>;
128
- /** A new app token for this request, when the one it holds is about to expire. */
129
- appToken?(): Promise<string>;
130
- };
131
96
  /**
132
- * Where the platform's services answer this app: `aiGateway` takes calls on Zite's AI key, `runs` a live page's
97
+ * Where the platform's services answer this app: `gateway` takes calls on a key Zite pays for, `runs` a live page's
133
98
  * analytics and each request's run detail. `email`, `pdf`, `uploads` (the upload session) and `steps` (a workflow
134
99
  * run's saved steps) are each that service's own endpoint, which the platform picks per workspace; without one, the
135
100
  * backend's route answers it.
@@ -137,7 +102,7 @@ export type PlatformSession = {
137
102
  export type PlatformUrls = {
138
103
  baseRunner: string;
139
104
  backend: string;
140
- aiGateway?: string;
105
+ gateway?: string;
141
106
  runs?: string;
142
107
  email?: string;
143
108
  pdf?: string;
@@ -155,14 +120,13 @@ export type PlatformProvider = {
155
120
  user(): User | null;
156
121
  urls: PlatformUrls | undefined;
157
122
  };
158
- /** What the host hands each request: its platform, already scoped to the app, build, request and user. */
123
+ /**
124
+ * What the host hands each request beside its app token: the token's renewal, for an answer that outlives the one it
125
+ * was dispatched with. Its presence in props is what marks a request the host dispatched.
126
+ */
159
127
  export type PlatformBinding = {
160
- /** Every platform call of one request goes through one session. */
161
- session(): PlatformSession | Promise<PlatformSession>;
162
- /** One batch per request, after its response has ended. */
163
- runs(batch: {
164
- runs: RunRecord[];
165
- }): Promise<void>;
128
+ /** The request's app token, signed again when it's about to expire; null once it can't be. */
129
+ appToken(): Promise<string | null>;
166
130
  };
167
131
  /** A demo is the published build serving a read-only visitor: as live, but every write is refused. */
168
132
  export type HostMode = "live" | "preview" | "demo" | "validate";
@@ -189,6 +153,13 @@ export type PagePlan = {
189
153
  short_name: string;
190
154
  } | null;
191
155
  };
156
+ /** `ZiteMeta.getWorkspace()`'s answer: where the app and its workspace are in Zite. */
157
+ export type ZiteWorkspace = {
158
+ workspaceHomeUrl: string;
159
+ editorUrl: string;
160
+ appPublicIdentifier: string;
161
+ projectPublicIdentifier: string;
162
+ };
192
163
  /** A marketplace demo's listing, which the platform's runtime shows the visitor. */
193
164
  export type DemoListing = {
194
165
  listingSlug: string;
@@ -262,6 +233,13 @@ export type HostProps = {
262
233
  page?: HostPage;
263
234
  /** The app's access mode, from the platform's records: an internal app serves no page or call to nobody. */
264
235
  accessMode?: "internal" | "external";
236
+ /** `ZiteMeta.getWorkspace()`'s answer, from the build's config; absent for a build published before it was kept. */
237
+ workspace?: ZiteWorkspace;
238
+ /**
239
+ * `integrations.get`'s answers, by connection name, real as classic's, when the host already loaded them for the
240
+ * request: a registration's one connection, and none for a demo. Without them the app asks the backend on its token.
241
+ */
242
+ connections?: Record<string, Record<string, unknown>>;
265
243
  };
266
244
  /** What the host resolved for this request. Set by the generated server entry, never by the browser. */
267
245
  export type HostRequestState = {
@@ -301,20 +279,24 @@ export type HostRequestState = {
301
279
  airtableReads?: Map<string, Promise<unknown>>;
302
280
  /** Records still reading a copy of a body; the flush waits for them. */
303
281
  pending?: Promise<void>[];
304
- platform?: PlatformBinding;
305
- session?: Promise<PlatformSession>;
306
282
  provider?: PlatformProvider;
307
283
  /** The request context's, which keeps a send going after the response. */
308
284
  waitUntil?: (promise: Promise<unknown>) => void;
309
- /** This request's direct base-runner calls in flight, capped as the host's relay capped them. */
285
+ /** This request's base-runner calls in flight, capped as the host once capped them; base-runner's per-app bucket bounds the app. */
310
286
  dataSlots?: {
311
287
  data: () => Promise<() => void>;
312
288
  sql: () => Promise<() => void>;
313
289
  };
314
- /** This request's calls on Zite's AI key waiting on the gateway's answer, capped as the host's relay capped them. */
315
- aiSlots?: () => Promise<() => void>;
290
+ /** This request's calls on Zite's AI key waiting on the gateway's answer, capped as the host once capped them. */
291
+ gatewaySlots?: () => Promise<() => void>;
316
292
  /** This request's router, so a page's status can follow the error it rendered. */
317
293
  router?: unknown;
318
294
  /** The platform's head entries for its pages; unset when the host writes them itself. */
319
295
  head?: PlatformHead;
296
+ workspace?: ZiteWorkspace;
297
+ connections?: Record<string, Record<string, unknown>>;
298
+ /** The backend's connections, asked once this request when the host didn't hand them over. */
299
+ connectionsLoad?: Promise<{
300
+ connections: Record<string, Record<string, unknown>>;
301
+ }>;
320
302
  };
@@ -13,7 +13,6 @@ exports.generateIntegrationsIndex = generateIntegrationsIndex;
13
13
  const parser_1 = require("@babel/parser");
14
14
  const sdkNames_js_1 = require("./sdkNames.js");
15
15
  const rules_js_1 = require("../integrations/rules.js");
16
- const AUTH_USERS_TABLE_ID = "zite_user";
17
16
  /**
18
17
  * What a field's value looks like when a record is READ back.
19
18
  *
@@ -353,62 +352,36 @@ function fieldJsdoc(schemaField, table, schema) {
353
352
  * name stability across schema changes.
354
353
  */
355
354
  function generateSchema(database, existingSchema) {
356
- const existingTableById = new Map();
357
- for (const t of existingSchema?.tables ?? []) {
358
- existingTableById.set(t.id, t);
359
- }
360
- const drafts = [];
361
- for (const table of database.tables) {
362
- if (table.id === AUTH_USERS_TABLE_ID)
363
- continue;
364
- const existingTable = existingTableById.get(table.id);
365
- const existingFieldById = new Map();
366
- for (const f of existingTable?.fields ?? []) {
367
- existingFieldById.set(f.id, f);
355
+ // A name from the existing schema is locked: it is what the app is compiling
356
+ // against, and only moves if it is reserved or collides.
357
+ const { names, renames } = (0, sdkNames_js_1.allocateLiveNames)(database.tables, existingSchema);
358
+ if (renames.length > 0) {
359
+ // Never silent: a rename means the accessor a developer would reach for is
360
+ // not the one that got emitted.
361
+ for (const line of (0, sdkNames_js_1.describeRenames)(renames)) {
362
+ console.warn(`[zitejs] SDK name collision resolved: ${line}`);
368
363
  }
369
- // `sdkName` is filled in by `allocateSchemaNames` below; the draft carries
370
- // what each name would like to be and whether user code already depends on
371
- // it. A name from the existing schema is locked — it is what the app is
372
- // compiling against — and only moves if it is reserved or collides.
373
- const fields = table.fields.map((field) => {
374
- const existing = (0, sdkNames_js_1.keepValidSdkName)(existingFieldById.get(field.id)?.sdkName);
375
- const { id: _id, order: _order, ...definition } = field;
364
+ }
365
+ const liveTables = new Map(database.tables.map((table) => [table.id, table]));
366
+ return {
367
+ tables: names.tables.map((named) => {
368
+ const table = liveTables.get(named.id);
369
+ const liveFields = new Map(table.fields.map((field) => [field.id, field]));
376
370
  return {
377
- field: { id: field.id, sdkName: "", definition },
378
- draft: {
379
- preferred: existing ?? (0, sdkNames_js_1.toSdkName)(field.name),
380
- locked: existing !== undefined,
381
- },
382
- };
383
- });
384
- const existingName = (0, sdkNames_js_1.keepValidSdkName)(existingTable?.sdkName);
385
- drafts.push({
386
- table: {
387
371
  id: table.id,
388
- sdkName: "",
372
+ sdkName: named.sdkName,
389
373
  // Always the live name — never `existingTable?.name`. Locking it the way
390
374
  // `sdkName` is locked would freeze it at the first name the table ever
391
375
  // had, which is the one thing this is here to avoid.
392
376
  name: table.name,
393
377
  primaryFieldId: table.primaryFieldId,
394
- fields: [],
395
- },
396
- draft: {
397
- preferred: existingName ?? (0, sdkNames_js_1.toSdkName)(table.name),
398
- locked: existingName !== undefined,
399
- },
400
- fields,
401
- });
402
- }
403
- const { tables, renames } = (0, sdkNames_js_1.allocateSchemaNames)(drafts);
404
- if (renames.length > 0) {
405
- // Never silent: a rename means the accessor a developer would reach for is
406
- // not the one that got emitted.
407
- for (const line of (0, sdkNames_js_1.describeRenames)(renames)) {
408
- console.warn(`[zitejs] SDK name collision resolved: ${line}`);
409
- }
410
- }
411
- return { tables };
378
+ fields: named.fields.map((namedField) => {
379
+ const { id, order: _order, ...definition } = liveFields.get(namedField.id);
380
+ return { id, sdkName: namedField.sdkName, definition };
381
+ }),
382
+ };
383
+ }),
384
+ };
412
385
  }
413
386
  function generateSentinelSdkTypes() {
414
387
  return [
@@ -510,7 +483,7 @@ function generateDbTs(inputSchema, { hasStartApps = false } = {}) {
510
483
  console.warn(`[zitejs] Repaired SDK name in zite.schema.json: ${line}`);
511
484
  }
512
485
  }
513
- const tables = schema.tables.filter((table) => table.id !== AUTH_USERS_TABLE_ID);
486
+ const tables = schema.tables.filter((table) => table.id !== sdkNames_js_1.AUTH_USERS_TABLE_ID);
514
487
  lines.push("// Auto-generated by zitejs generate. Do not edit manually.");
515
488
  lines.push("//");
516
489
  if (hasStartApps) {
@@ -79,20 +79,28 @@ export declare class SdkNameAllocator {
79
79
  private readonly taken;
80
80
  private readonly reserved;
81
81
  private readonly derive;
82
+ private readonly fold?;
83
+ private readonly folded;
82
84
  constructor(opts?: {
83
85
  reserved?: readonly string[];
84
86
  derive?: (name: string) => string[];
87
+ /**
88
+ * The key under which two names are the same to something downstream,
89
+ * which a fresh name must not share with one already claimed.
90
+ */
91
+ fold?: (name: string) => string;
85
92
  });
86
93
  private keysFor;
87
94
  private isFree;
88
95
  /** Free right now, without claiming it. */
89
- available(name: string): boolean;
96
+ available(name: string, fresh?: boolean): boolean;
90
97
  private claim;
91
98
  /**
92
99
  * `name`, or the first `name2`, `name3`… that is free. Suffixes start at 2
93
100
  * because that is what the name means: the second table called Notifications.
101
+ * A `fresh` name also steers clear of every claimed name's `fold`.
94
102
  */
95
- allocate(preferred: string): string;
103
+ allocate(preferred: string, fresh?: boolean): string;
96
104
  }
97
105
  /**
98
106
  * Existing sdkNames are preserved across syncs so user code keeps compiling,
@@ -113,23 +121,38 @@ interface NameDraft {
113
121
  */
114
122
  locked: boolean;
115
123
  }
116
- export interface SchemaNameDraft {
117
- table: ZiteSchemaTable;
124
+ export interface NameDraftOf<T, F> {
125
+ table: T;
118
126
  draft: NameDraft;
119
127
  fields: Array<{
120
- field: ZiteSchemaField;
128
+ field: F;
121
129
  draft: NameDraft;
122
130
  }>;
123
131
  }
132
+ export type SchemaNameDraft = NameDraftOf<ZiteSchemaTable, ZiteSchemaField>;
124
133
  /**
125
134
  * Resolve every drafted name to a unique, unreserved one.
126
135
  *
127
136
  * Two passes per namespace: locked names claim first in declaration order, then
128
137
  * fresh ones fill in around them. Without that ordering a new table could take
129
138
  * an accessor an existing app already imports.
139
+ *
140
+ * A fresh name also differs from every other name ignoring case, as base-runner's
141
+ * SQL resolver tells names apart: it refuses a whole base when two differ only
142
+ * by case. Fields compare by their sdkName, tables by the class name the client
143
+ * sends. Locked names keep theirs even when they already clash.
130
144
  */
131
- export declare function allocateSchemaNames(drafts: SchemaNameDraft[]): {
132
- tables: ZiteSchemaTable[];
145
+ export declare function allocateSchemaNames<T extends {
146
+ id: string;
147
+ }, F extends {
148
+ id: string;
149
+ }>(drafts: NameDraftOf<T, F>[]): {
150
+ tables: Array<Omit<T, "sdkName" | "fields"> & {
151
+ sdkName: string;
152
+ fields: Array<Omit<F, "sdkName"> & {
153
+ sdkName: string;
154
+ }>;
155
+ }>;
133
156
  renames: SdkNameRename[];
134
157
  };
135
158
  /**
@@ -141,6 +164,41 @@ export declare function normalizeSchemaNames(schema: ZiteSchema): {
141
164
  schema: ZiteSchema;
142
165
  renames: SdkNameRename[];
143
166
  };
167
+ /** A schema's SDK names alone, keyed by id, as a server build carries them. */
168
+ export interface SchemaNames {
169
+ tables: Array<{
170
+ id: string;
171
+ sdkName: string;
172
+ fields: Array<{
173
+ id: string;
174
+ sdkName: string;
175
+ }>;
176
+ }>;
177
+ }
178
+ /** The names `generateDbTs` emits for a schema, without its definitions. */
179
+ export declare function schemaNamesOf(schema: ZiteSchema): SchemaNames;
180
+ /** The table `generateDbTs` never emits a client for: Zite's own users, read through `zite.auth`. */
181
+ export declare const AUTH_USERS_TABLE_ID = "zite_user";
182
+ /** A table as base-runner lists it, which both `zitejs generate` and a running build read. */
183
+ export interface LiveTable {
184
+ id: string;
185
+ name: string;
186
+ deletedAt?: unknown;
187
+ fields: ReadonlyArray<{
188
+ id: string;
189
+ name: string;
190
+ deletedAt?: unknown;
191
+ }>;
192
+ }
193
+ /**
194
+ * The SDK names for a base's tables as they are now: `existing`'s name for every id it knows, locked, and a fresh one
195
+ * from `toSdkName` for each table or field it doesn't. `zitejs generate` writes these into zite.schema.json, and a
196
+ * running build fills in what was added since it was built with the same, so the two can't drift.
197
+ */
198
+ export declare function allocateLiveNames(live: readonly LiveTable[], existing?: SchemaNames): {
199
+ names: SchemaNames;
200
+ renames: SdkNameRename[];
201
+ };
144
202
  /** One line per rename, for a generator that has no logger of its own. */
145
203
  export declare function describeRenames(renames: SdkNameRename[]): string[];
146
204
  export {};
@@ -22,13 +22,15 @@
22
22
  * cannot compile.
23
23
  */
24
24
  Object.defineProperty(exports, "__esModule", { value: true });
25
- exports.SdkNameAllocator = exports.RESERVED_FIELD_ACCESSORS = exports.RESERVED_IDENTIFIERS = exports.RESERVED_TABLE_ACCESSORS = void 0;
25
+ exports.AUTH_USERS_TABLE_ID = exports.SdkNameAllocator = exports.RESERVED_FIELD_ACCESSORS = exports.RESERVED_IDENTIFIERS = exports.RESERVED_TABLE_ACCESSORS = void 0;
26
26
  exports.toPascalCase = toPascalCase;
27
27
  exports.toCamelCase = toCamelCase;
28
28
  exports.toSdkName = toSdkName;
29
29
  exports.keepValidSdkName = keepValidSdkName;
30
30
  exports.allocateSchemaNames = allocateSchemaNames;
31
31
  exports.normalizeSchemaNames = normalizeSchemaNames;
32
+ exports.schemaNamesOf = schemaNamesOf;
33
+ exports.allocateLiveNames = allocateLiveNames;
32
34
  exports.describeRenames = describeRenames;
33
35
  // The case helpers live here rather than in lib.ts so this module has no import
34
36
  // back into it — `lib.ts` needs the allocator, and a cycle between the two is
@@ -121,39 +123,46 @@ class SdkNameAllocator {
121
123
  taken = new Set();
122
124
  reserved;
123
125
  derive;
126
+ fold;
127
+ folded = new Set();
124
128
  constructor(opts = {}) {
125
129
  this.reserved = new Set([
126
130
  ...exports.RESERVED_IDENTIFIERS,
127
131
  ...(opts.reserved ?? []),
128
132
  ]);
129
133
  this.derive = opts.derive ?? (() => []);
134
+ this.fold = opts.fold;
130
135
  }
131
136
  keysFor(name) {
132
137
  return [name, ...this.derive(name)];
133
138
  }
134
- isFree(name) {
135
- return this.keysFor(name).every((key) => !this.taken.has(key) && !this.reserved.has(key));
139
+ isFree(name, fresh) {
140
+ return (this.keysFor(name).every((key) => !this.taken.has(key) && !this.reserved.has(key)) &&
141
+ !(fresh && this.fold && this.folded.has(this.fold(name))));
136
142
  }
137
143
  /** Free right now, without claiming it. */
138
- available(name) {
139
- return this.isFree(name);
144
+ available(name, fresh = false) {
145
+ return this.isFree(name, fresh);
140
146
  }
141
147
  claim(name) {
142
148
  for (const key of this.keysFor(name))
143
149
  this.taken.add(key);
150
+ if (this.fold)
151
+ this.folded.add(this.fold(name));
144
152
  return name;
145
153
  }
146
154
  /**
147
155
  * `name`, or the first `name2`, `name3`… that is free. Suffixes start at 2
148
156
  * because that is what the name means: the second table called Notifications.
157
+ * A `fresh` name also steers clear of every claimed name's `fold`.
149
158
  */
150
- allocate(preferred) {
159
+ allocate(preferred, fresh = false) {
151
160
  const base = preferred || "_";
152
- if (this.isFree(base))
161
+ if (this.isFree(base, fresh))
153
162
  return this.claim(base);
154
163
  for (let suffix = 2; suffix <= MAX_SUFFIX_ATTEMPTS; suffix++) {
155
164
  const candidate = `${base}${suffix}`;
156
- if (this.isFree(candidate))
165
+ if (this.isFree(candidate, fresh))
157
166
  return this.claim(candidate);
158
167
  }
159
168
  // Unreachable: each attempt blocks at most two keys, so a free candidate
@@ -180,6 +189,11 @@ function keepValidSdkName(sdkName) {
180
189
  * Two passes per namespace: locked names claim first in declaration order, then
181
190
  * fresh ones fill in around them. Without that ordering a new table could take
182
191
  * an accessor an existing app already imports.
192
+ *
193
+ * A fresh name also differs from every other name ignoring case, as base-runner's
194
+ * SQL resolver tells names apart: it refuses a whole base when two differ only
195
+ * by case. Fields compare by their sdkName, tables by the class name the client
196
+ * sends. Locked names keep theirs even when they already clash.
183
197
  */
184
198
  function allocateSchemaNames(drafts) {
185
199
  const renames = [];
@@ -187,6 +201,7 @@ function allocateSchemaNames(drafts) {
187
201
  reserved: exports.RESERVED_TABLE_ACCESSORS,
188
202
  // The PascalCase form is its own pair of exported declarations.
189
203
  derive: (name) => [`type:${toPascalCase(name)}`],
204
+ fold: (name) => toPascalCase(name).toLowerCase(),
190
205
  });
191
206
  const resolved = new Map();
192
207
  for (const pass of [true, false]) {
@@ -195,7 +210,7 @@ function allocateSchemaNames(drafts) {
195
210
  continue;
196
211
  if (pass && !tableNames.available(entry.draft.preferred))
197
212
  continue;
198
- const sdkName = tableNames.allocate(entry.draft.preferred);
213
+ const sdkName = tableNames.allocate(entry.draft.preferred, !pass);
199
214
  resolved.set(entry.table.id, sdkName);
200
215
  if (sdkName !== entry.draft.preferred) {
201
216
  renames.push({
@@ -212,7 +227,7 @@ function allocateSchemaNames(drafts) {
212
227
  for (const entry of drafts) {
213
228
  if (resolved.has(entry.table.id))
214
229
  continue;
215
- const sdkName = tableNames.allocate(entry.draft.preferred);
230
+ const sdkName = tableNames.allocate(entry.draft.preferred, true);
216
231
  resolved.set(entry.table.id, sdkName);
217
232
  renames.push({
218
233
  kind: "table",
@@ -224,6 +239,7 @@ function allocateSchemaNames(drafts) {
224
239
  const tables = drafts.map((entry) => {
225
240
  const fieldNames = new SdkNameAllocator({
226
241
  reserved: exports.RESERVED_FIELD_ACCESSORS,
242
+ fold: (name) => name.toLowerCase(),
227
243
  });
228
244
  const resolvedFields = new Map();
229
245
  for (const pass of [true, false]) {
@@ -232,7 +248,7 @@ function allocateSchemaNames(drafts) {
232
248
  continue;
233
249
  if (pass && !fieldNames.available(draft.preferred))
234
250
  continue;
235
- const sdkName = fieldNames.allocate(draft.preferred);
251
+ const sdkName = fieldNames.allocate(draft.preferred, !pass);
236
252
  resolvedFields.set(field.id, sdkName);
237
253
  if (sdkName !== draft.preferred) {
238
254
  renames.push({
@@ -248,7 +264,7 @@ function allocateSchemaNames(drafts) {
248
264
  for (const { field, draft } of entry.fields) {
249
265
  if (resolvedFields.has(field.id))
250
266
  continue;
251
- const sdkName = fieldNames.allocate(draft.preferred);
267
+ const sdkName = fieldNames.allocate(draft.preferred, true);
252
268
  resolvedFields.set(field.id, sdkName);
253
269
  renames.push({
254
270
  kind: "field",
@@ -291,6 +307,54 @@ function normalizeSchemaNames(schema) {
291
307
  })));
292
308
  return { schema: { tables }, renames };
293
309
  }
310
+ /** The names `generateDbTs` emits for a schema, without its definitions. */
311
+ function schemaNamesOf(schema) {
312
+ return {
313
+ tables: normalizeSchemaNames(schema).schema.tables.map((table) => ({
314
+ id: table.id,
315
+ sdkName: table.sdkName,
316
+ fields: table.fields.map((field) => ({
317
+ id: field.id,
318
+ sdkName: field.sdkName,
319
+ })),
320
+ })),
321
+ };
322
+ }
323
+ /** The table `generateDbTs` never emits a client for: Zite's own users, read through `zite.auth`. */
324
+ exports.AUTH_USERS_TABLE_ID = "zite_user";
325
+ /**
326
+ * The SDK names for a base's tables as they are now: `existing`'s name for every id it knows, locked, and a fresh one
327
+ * from `toSdkName` for each table or field it doesn't. `zitejs generate` writes these into zite.schema.json, and a
328
+ * running build fills in what was added since it was built with the same, so the two can't drift.
329
+ */
330
+ function allocateLiveNames(live, existing) {
331
+ const known = new Map(existing?.tables.map((table) => [table.id, table]));
332
+ const drafts = live
333
+ .filter((table) => table.id !== exports.AUTH_USERS_TABLE_ID && !table.deletedAt)
334
+ .map((table) => {
335
+ const knownTable = known.get(table.id);
336
+ const knownFields = new Map(knownTable?.fields.map((field) => [field.id, field.sdkName]));
337
+ const kept = keepValidSdkName(knownTable?.sdkName);
338
+ return {
339
+ table: { id: table.id },
340
+ draft: { preferred: kept ?? toSdkName(table.name), locked: kept !== undefined },
341
+ fields: table.fields
342
+ .filter((field) => !field.deletedAt)
343
+ .map((field) => {
344
+ const keptField = keepValidSdkName(knownFields.get(field.id));
345
+ return {
346
+ field: { id: field.id },
347
+ draft: {
348
+ preferred: keptField ?? toSdkName(field.name),
349
+ locked: keptField !== undefined,
350
+ },
351
+ };
352
+ }),
353
+ };
354
+ });
355
+ const { tables, renames } = allocateSchemaNames(drafts);
356
+ return { names: { tables }, renames };
357
+ }
294
358
  /** One line per rename, for a generator that has no logger of its own. */
295
359
  function describeRenames(renames) {
296
360
  return renames.map((r) => r.kind === "table"
@@ -172,6 +172,44 @@ const recordTypeKeys = (source, typeName) => {
172
172
  (0, vitest_1.expect)(schema.tables[0].fields[0].sdkName).toBe("time");
173
173
  });
174
174
  });
175
+ // base-runner's SQL resolver refuses a whole base when two names differ only by
176
+ // case, so a fresh name must not match an existing one ignoring case.
177
+ (0, vitest_1.describe)("names that differ only by case", () => {
178
+ const locked = (tables) => ({
179
+ tables: tables.map((table) => ({
180
+ ...table,
181
+ fields: table.fields.map(([id, sdkName]) => ({ id, sdkName, definition: { type: "single_line_text" } })),
182
+ })),
183
+ });
184
+ const fieldsOf = (schema) => Object.fromEntries(schema.tables[0].fields.map((f) => [f.id, f.sdkName]));
185
+ (0, vitest_1.it)("step a fresh field around a baked one, so aPIKey and a new API Key don't break SQL", () => {
186
+ const schema = (0, lib_js_1.generateSchema)(database([{ id: "tbl_1", name: "Keys", fields: [field("fld_old", "API Key"), field("fld_new", "API Key")] }]), locked([{ id: "tbl_1", sdkName: "keys", fields: [["fld_old", "aPIKey"]] }]));
187
+ (0, vitest_1.expect)(fieldsOf(schema)).toEqual({ fld_old: "aPIKey", fld_new: "apiKey2" });
188
+ });
189
+ (0, vitest_1.it)("step a fresh field around another fresh one", () => {
190
+ const schema = (0, lib_js_1.generateSchema)(database([{ id: "tbl_1", name: "Keys", fields: [field("fld_1", "API Key"), field("fld_2", "A PI Key")] }]));
191
+ (0, vitest_1.expect)(fieldsOf(schema)).toEqual({ fld_1: "apiKey", fld_2: "aPiKey2" });
192
+ });
193
+ (0, vitest_1.it)("step a fresh table around a baked one by the class name the client sends", () => {
194
+ const schema = (0, lib_js_1.generateSchema)(database([
195
+ { id: "tbl_old", name: "VIP Customers", fields: [] },
196
+ { id: "tbl_new", name: "VIP Customers", fields: [] },
197
+ ]), locked([{ id: "tbl_old", sdkName: "vIPCustomers", fields: [] }]));
198
+ (0, vitest_1.expect)(schema.tables.map((t) => t.sdkName)).toEqual(["vIPCustomers", "vipCustomers2"]);
199
+ });
200
+ (0, vitest_1.it)("never move a baked name, even two that already clash", () => {
201
+ const schema = (0, lib_js_1.generateSchema)(database([{ id: "tbl_1", name: "Keys", fields: [field("fld_1", "API Key"), field("fld_2", "Api key")] }]), locked([{ id: "tbl_1", sdkName: "keys", fields: [["fld_1", "aPIKey"], ["fld_2", "apiKey"]] }]));
202
+ (0, vitest_1.expect)(fieldsOf(schema)).toEqual({ fld_1: "aPIKey", fld_2: "apiKey" });
203
+ (0, vitest_1.expect)((0, sdkNames_js_1.normalizeSchemaNames)(schema).renames).toEqual([]);
204
+ });
205
+ (0, vitest_1.it)("leave a fresh name alone when it matches one only in another table", () => {
206
+ const schema = (0, lib_js_1.generateSchema)(database([
207
+ { id: "tbl_1", name: "Keys", fields: [field("fld_1", "API Key")] },
208
+ { id: "tbl_2", name: "Other", fields: [field("fld_2", "API Key")] },
209
+ ]), locked([{ id: "tbl_1", sdkName: "keys", fields: [["fld_1", "aPIKey"]] }]));
210
+ (0, vitest_1.expect)(schema.tables[1].fields[0].sdkName).toBe("apiKey");
211
+ });
212
+ });
175
213
  (0, vitest_1.describe)("normalizeSchemaNames", () => {
176
214
  (0, vitest_1.it)("is a no-op on a well-formed schema", () => {
177
215
  const schema = {