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
@@ -71,6 +71,7 @@ const FIELD_TYPE_MAP = {
71
71
  formula: "any",
72
72
  created_at: "string",
73
73
  updated_at: "string",
74
+ created_by: "string",
74
75
  updated_by: "string",
75
76
  };
76
77
  /**
@@ -96,7 +97,7 @@ const FIELD_INPUT_TYPE_MAP = {
96
97
  * rather than typed and then refused at runtime.
97
98
  *
98
99
  * Mirrors `COMPUTED_FIELD_TYPES` in the product's own `shared/bases/fields`.
99
- * The first six are rejected by `createRecordDataSchema` — each has a
100
+ * The first seven are rejected by `createRecordDataSchema` — each has a
100
101
  * `refine(val => val == null)`, so a non-null write errors (null is a no-op
101
102
  * clear). `created_at` / `updated_at` are refused differently: they have no
102
103
  * column at all, so a write is silently dropped, which is the worse outcome to
@@ -108,6 +109,7 @@ const READ_ONLY_FIELD_TYPES = new Set([
108
109
  "source",
109
110
  "formula",
110
111
  "autonumber",
112
+ "created_by",
111
113
  "updated_by",
112
114
  "created_at",
113
115
  "updated_at",
@@ -245,13 +247,8 @@ function fieldJsdoc(schemaField, table, schema) {
245
247
  const parts = [];
246
248
  if (table.primaryFieldId === schemaField.id)
247
249
  parts.push("Primary field");
248
- if (def.type === "created_at" ||
249
- def.type === "updated_at" ||
250
- def.type === "lookup" ||
251
- def.type === "formula" ||
252
- def.type === "autonumber") {
250
+ if (READ_ONLY_FIELD_TYPES.has(def.type))
253
251
  parts.push("Read-only");
254
- }
255
252
  if (def.type === "linked_record") {
256
253
  const tpl = def.template;
257
254
  if (tpl.tableId) {
@@ -479,7 +476,12 @@ function buildLinkTableComments(schema) {
479
476
  * Generate .zite/db.ts purely from ZiteSchema.
480
477
  * Pure function — no external data needed beyond what's in the schema file.
481
478
  */
482
- export function generateDbTs(inputSchema) {
479
+ /**
480
+ * `hasStartApps` rewords the usage notes for a workspace where the code using
481
+ * the client isn't only classic endpoints. A classic-only workspace keeps the
482
+ * old wording, so its committed db.ts doesn't change.
483
+ */
484
+ export function generateDbTs(inputSchema, { hasStartApps = false } = {}) {
483
485
  const lines = [];
484
486
  // Defensive, and idempotent: a schema whose names are already unique and
485
487
  // unreserved normalizes to itself. It matters for a `zite.schema.json`
@@ -496,7 +498,13 @@ export function generateDbTs(inputSchema) {
496
498
  const tables = schema.tables.filter((table) => table.id !== AUTH_USERS_TABLE_ID);
497
499
  lines.push("// Auto-generated by zitejs generate. Do not edit manually.");
498
500
  lines.push("//");
499
- lines.push("// Usage in endpoint files (src/api/*.ts):");
501
+ if (hasStartApps) {
502
+ lines.push("// Usage in server code: a classic app's endpoints (src/api/*.ts), or a Start");
503
+ lines.push("// app's server functions and *.server.ts files:");
504
+ }
505
+ else {
506
+ lines.push("// Usage in endpoint files (src/api/*.ts):");
507
+ }
500
508
  lines.push('// import { zite } from "zitejs/db";');
501
509
  lines.push("//");
502
510
  lines.push('// Always use "zitejs/db" — never use relative paths like "../../.zite/db".');
@@ -507,9 +515,9 @@ export function generateDbTs(inputSchema) {
507
515
  lines.push("// filters: { fieldName: value } for equality, or { fieldName: { <op>: value } }");
508
516
  lines.push("// operators: contains, not, in, notIn, lt, lte, gt, gte");
509
517
  lines.push('// `not: null` means "is set". An empty `in: []` matches nothing; an', "// empty `notIn: []` applies no filter.");
510
- lines.push("// sort is currently IGNORED here — it is stripped before the request.", "// (it does work on zite.auth.findAllUsers). Order in SQL instead.");
518
+ lines.push('// sort: [{ field: "fieldName", direction: "asc" | "desc" }]');
511
519
  lines.push("// limit defaults to 500, max 2000; offset is a row count (a number)");
512
- lines.push('// a filter value of `undefined` is REJECTED (it would query unfiltered', '// and match an arbitrary record). Check the value first.');
520
+ lines.push("// a filter value of `undefined` is REJECTED (it would query unfiltered", "// and match an arbitrary record). Check the value first.");
513
521
  lines.push("// .findOne({ id?, filters?, fields? }) → T | undefined");
514
522
  lines.push("// .create({ record }) → T");
515
523
  lines.push("// .update({ id, record }) → { id: string, fields: Partial<T> }");
@@ -551,7 +559,9 @@ export function generateDbTs(inputSchema) {
551
559
  lines.push('// - Auth users are available as "ziteUsers" with id, name, email, firstName, lastName, and image');
552
560
  lines.push("// - Soft-deleted rows are excluded automatically — no WHERE deleted_at IS NULL");
553
561
  lines.push("// - SELECT only — use .create/.update/.delete for writes");
554
- lines.push('// - Load the "zite:sql" skill for full SQL reference (formulas, lookups, etc.)');
562
+ lines.push(hasStartApps
563
+ ? '// - In the Zite editor, the "zite:sql" skill is the full SQL reference (formulas, lookups, etc.)'
564
+ : '// - Load the "zite:sql" skill for full SQL reference (formulas, lookups, etc.)');
555
565
  lines.push(...buildLinkTableComments(schema));
556
566
  lines.push("import { createTableClient, createSqlClient, createAuthClient } from 'zitejs/runtime';");
557
567
  lines.push("");
@@ -1109,7 +1119,11 @@ export function normalizeAirtableLockNames(lock) {
1109
1119
  });
1110
1120
  return { lock: { ...lock, tables }, renames };
1111
1121
  }
1112
- export function generateAirtableTs(inputLock) {
1122
+ /** Where an app keeps the server code a generated client is used from. */
1123
+ const serverCodeIn = (runtime) => runtime === "start"
1124
+ ? "server functions and *.server.ts files"
1125
+ : "endpoint files (src/api/*.ts)";
1126
+ export function generateAirtableTs(inputLock, runtime = "classic") {
1113
1127
  if (inputLock.tables.length === 0)
1114
1128
  return null;
1115
1129
  const { lock, renames } = normalizeAirtableLockNames(inputLock);
@@ -1122,7 +1136,7 @@ export function generateAirtableTs(inputLock) {
1122
1136
  "// Auto-generated by zitejs generate from zite.lock. Do not edit manually.",
1123
1137
  "// Airtable SDK — uses createAirtableClient from zitejs/runtime.",
1124
1138
  "//",
1125
- "// Usage in endpoint files (src/api/*.ts) — one client is exported per table:",
1139
+ `// Usage in ${serverCodeIn(runtime)} — one client is exported per table:`,
1126
1140
  `// import { ${lock.tables[0]?.sdkName ?? "TableName"} } from 'zitejs/integrations';`,
1127
1141
  "//",
1128
1142
  "// Always use 'zitejs/integrations' — never a relative path like",
@@ -1217,13 +1231,13 @@ export function generateBackendWrapperTs(envVarNames = []) {
1217
1231
  "// Auto-generated type-narrowing wrapper. Do not edit manually.",
1218
1232
  "// Re-exports createEndpoint with context.user typed to the app User.",
1219
1233
  "",
1220
- "import type { ZiteRequestContext as _ZiteRequestContext, ZiteScheduledContext, ZiteErrorCode, ZiteSchedule, ZiteStep, ZiteStreamInterface, ZiteTrigger, ZiteTriggerContext, ZiteWebhook } from 'zitejs/backend/base';",
1234
+ "import type { ZiteRequestContext as _ZiteRequestContext, ZiteScheduledContext, ZiteErrorCode, ZiteSchedule, ZiteStep, ZiteStreamInterface, ZiteTrigger, ZiteTriggerContext, ZiteEndpointInput, ZiteWebhook } from 'zitejs/backend/base';",
1221
1235
  "import type { User } from 'zitejs/auth';",
1222
1236
  "",
1223
1237
  "export type { ZiteErrorCode, ZiteSchedule, ZiteScheduledContext, ZiteStep, ZiteStreamInterface, ZiteTrigger, ZiteWebhook };",
1224
1238
  // A trigger's registration exports are typed against these, and they
1225
1239
  // only reach app code through this file.
1226
- "export type { ZiteTriggerContext, ZiteTriggerDeliveryInfo, ZiteTriggerDeliveryRun, ZiteTriggerRun, ZiteTriggerSubscribe, ZiteTriggerSubscribeInput, ZiteTriggerSubscribeResult, ZiteTriggerUnsubscribe, ZiteTriggerUnsubscribeInput } from 'zitejs/backend/base';",
1240
+ "export type { ZiteDatabaseTriggerEvent, ZiteDatabaseTriggerInput, ZiteFormTriggerInput, ZiteTriggerContext, ZiteTriggerDeliveryInfo, ZiteTriggerDeliveryRun, ZiteTriggerRun, ZiteTriggerSubscribe, ZiteTriggerSubscribeInput, ZiteTriggerSubscribeResult, ZiteTriggerUnsubscribe, ZiteTriggerUnsubscribeInput } from 'zitejs/backend/base';",
1227
1241
  // The pre-monorepo SDK put this in scope for every endpoint, so migrated
1228
1242
  // code can name it. `createEndpoint` infers the same thing without it.
1229
1243
  "export type InferSchemaType<T> = T extends { _output: infer U } ? U : T;",
@@ -1311,12 +1325,12 @@ export function generateBackendWrapperTs(envVarNames = []) {
1311
1325
  " schedule?: TSchedule;",
1312
1326
  " /** When set, an inbound webhook can also trigger this endpoint. Like `schedule`, it widens `context` — a webhook fire has no session. */",
1313
1327
  " webhook?: TWebhook;",
1314
- " /** When set, a connection's events (registered by this file's own `subscribe` export) or a poll (`every`) also fire this endpoint. Like `webhook`, it widens `context` — a trigger fire has no session. */",
1328
+ " /** When set, a connection's events (registered by this file's own `subscribe` export), a poll (`every`), a change to one of the project's tables (`table`) or a submission to one of its forms (`form`) also fire this endpoint. Like `webhook`, it widens `context` — a trigger fire has no session. */",
1315
1329
  " trigger?: TTrigger;",
1316
1330
  " execute: (",
1317
1331
  " params: {",
1318
- " input: TInput;",
1319
- " /** Durable steps: step.run(name, fn) runs fn once per logical run — its result is saved before anything after it executes, and a resumed run replays completed steps from their saved results. Provided by the platform; never define a local stand-in. */",
1332
+ " input: ZiteEndpointInput<TInput, TTrigger>;",
1333
+ ' /** Durable steps: step.run(name, fn) runs fn once per logical run — its result is saved before anything after it executes, and a resumed run replays completed steps from their saved results. In a run fired by a schedule, webhook or trigger, step.sleep(name, "2d") pauses the run and a failed step is tried again. Provided by the platform; never define a local stand-in. */',
1320
1334
  " step: ZiteStep;",
1321
1335
  " context: TSchedule extends ZiteSchedule ? ZiteRequestContext | ZiteScheduledContext : TWebhook extends ZiteWebhook ? ZiteRequestContext | ZiteScheduledContext : TTrigger extends ZiteTrigger ? ZiteRequestContext | ZiteScheduledContext : ZiteRequestContext;",
1322
1336
  // Mirrors the base module: a trigger's run gets `trigger`.
@@ -1370,12 +1384,12 @@ export function findEmailIntegrationId(appConfig, workspaceConfig) {
1370
1384
  * SDK bridge, resolved via the `zitejs/email` alias. `integrationId` is the
1371
1385
  * connected integration's key.
1372
1386
  */
1373
- export function generateEmailSdk(integrationId) {
1387
+ export function generateEmailSdk(integrationId, runtime = "classic") {
1374
1388
  return [
1375
1389
  "// Auto-generated by zitejs generate from zite.config.json. Do not edit manually.",
1376
1390
  "// Email SDK — sends through the Zite email gateway via the runtime bridge.",
1377
1391
  "//",
1378
- "// Usage in endpoint files (src/api/*.ts):",
1392
+ `// Usage in ${serverCodeIn(runtime)}:`,
1379
1393
  "// import { Email } from 'zitejs/email';",
1380
1394
  "//",
1381
1395
  "// Always use 'zitejs/email' — never a relative path like '../../.zite/integrations/email'.",
@@ -328,6 +328,22 @@ describe('generateDbTs table names in comments', () => {
328
328
  expect(syntaxErrorsIn(generateDbTs(schemaWithTableNamed(name)))).toEqual([]);
329
329
  });
330
330
  });
331
+ describe('generateDbTs usage notes', () => {
332
+ const schema = { tables: [] };
333
+ // A classic-only workspace regenerates db.ts on every sandbox boot, so a
334
+ // changed comment would land in its next commit and rebuild every app.
335
+ it('keeps the classic wording in a classic-only workspace', () => {
336
+ const out = generateDbTs(schema);
337
+ expect(out).toContain('// Usage in endpoint files (src/api/*.ts):');
338
+ expect(out).toContain('// - Load the "zite:sql" skill for full SQL reference');
339
+ });
340
+ it('names where both runtimes keep server code once a Start app exists', () => {
341
+ const out = generateDbTs(schema, { hasStartApps: true });
342
+ expect(out).toContain("// Usage in server code: a classic app's endpoints (src/api/*.ts), or a Start\n// app's server functions and *.server.ts files:");
343
+ expect(out).toContain('// - In the Zite editor, the "zite:sql" skill is the full SQL reference');
344
+ expect(out).not.toContain('Usage in endpoint files');
345
+ });
346
+ });
331
347
  describe('generateApiTs endpoint file names', () => {
332
348
  // An endpoint filename is the LLM's raw `writeFile` path argument — nothing
333
349
  // validates its characters — and it lands in an import specifier, a comment
@@ -422,44 +438,98 @@ describe('findEmailIntegrationId', () => {
422
438
  expect(findEmailIntegrationId(undefined, undefined)).toBeUndefined();
423
439
  });
424
440
  });
425
- describe('generateIntegrationsIndex', () => {
426
- // Not import.meta: this file also compiles to CommonJS. Vitest runs from the repo root.
427
- const runtimePath = resolve('src/runtime/index.ts');
428
- /** Type errors in `usage` compiled beside the generated file, `zitejs/runtime` mapped to this source. */
429
- const typeErrorsIn = (generated, usage, airtable) => {
430
- const files = {
431
- '/app/.zite/integrations/index.ts': generated,
432
- ...(airtable ? { '/app/.zite/integrations/airtable.ts': airtable } : {}),
433
- '/app/src/usage.ts': usage,
434
- };
435
- const options = {
436
- strict: true,
437
- noEmit: true,
438
- target: ts.ScriptTarget.ES2022,
439
- module: ts.ModuleKind.ESNext,
440
- moduleResolution: ts.ModuleResolutionKind.Bundler,
441
- skipLibCheck: true,
442
- baseUrl: '/app',
443
- paths: {
444
- 'zitejs/runtime': [runtimePath],
445
- 'zitejs/integrations': ['/app/.zite/integrations/index.ts'],
441
+ // Not import.meta: this file also compiles to CommonJS. Vitest runs from the repo root.
442
+ const runtimePath = resolve('src/runtime/index.ts');
443
+ /** Type errors in the `/app/` files, `zitejs/runtime` mapped to this source. */
444
+ const appTypeErrors = (files, paths) => {
445
+ const options = {
446
+ strict: true,
447
+ noEmit: true,
448
+ target: ts.ScriptTarget.ES2022,
449
+ module: ts.ModuleKind.ESNext,
450
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
451
+ skipLibCheck: true,
452
+ baseUrl: '/app',
453
+ paths: { 'zitejs/runtime': [runtimePath], ...paths },
454
+ };
455
+ const host = ts.createCompilerHost(options);
456
+ const { getSourceFile, fileExists, readFile, directoryExists } = host;
457
+ host.fileExists = f => f in files || fileExists(f);
458
+ host.directoryExists = d => Object.keys(files).some(f => f.startsWith(`${d}/`)) ||
459
+ (directoryExists?.(d) ?? false);
460
+ host.readFile = f => files[f] ?? readFile(f);
461
+ host.getSourceFile = (f, lang, ...rest) => f in files
462
+ ? ts.createSourceFile(f, files[f], lang)
463
+ : getSourceFile(f, lang, ...rest);
464
+ const program = ts.createProgram(Object.keys(files), options, host);
465
+ return ts
466
+ .getPreEmitDiagnostics(program)
467
+ .filter(d => d.file?.fileName.startsWith('/app/'))
468
+ .map(d => ts.flattenDiagnosticMessageText(d.messageText, ' '));
469
+ };
470
+ describe('generateDbTs created_by and updated_by', () => {
471
+ const schema = {
472
+ tables: [
473
+ {
474
+ id: 'tbl1',
475
+ sdkName: 'tasks',
476
+ fields: [
477
+ {
478
+ id: 'fld1',
479
+ sdkName: 'title',
480
+ definition: { name: 'Title', type: 'single_line_text', template: {} },
481
+ },
482
+ {
483
+ id: 'fld2',
484
+ sdkName: 'createdBy',
485
+ definition: { name: 'Created By', type: 'created_by', template: {} },
486
+ },
487
+ {
488
+ id: 'fld3',
489
+ sdkName: 'updatedBy',
490
+ definition: { name: 'Last Modified By', type: 'updated_by', template: {} },
491
+ },
492
+ ],
446
493
  },
447
- };
448
- const host = ts.createCompilerHost(options);
449
- const { getSourceFile, fileExists, readFile, directoryExists } = host;
450
- host.fileExists = f => f in files || fileExists(f);
451
- host.directoryExists = d => Object.keys(files).some(f => f.startsWith(`${d}/`)) ||
452
- (directoryExists?.(d) ?? false);
453
- host.readFile = f => files[f] ?? readFile(f);
454
- host.getSourceFile = (f, lang, ...rest) => f in files
455
- ? ts.createSourceFile(f, files[f], lang)
456
- : getSourceFile(f, lang, ...rest);
457
- const program = ts.createProgram(Object.keys(files), options, host);
458
- return ts
459
- .getPreEmitDiagnostics(program)
460
- .filter(d => d.file?.fileName.startsWith('/app/'))
461
- .map(d => ts.flattenDiagnosticMessageText(d.messageText, ' '));
494
+ ],
462
495
  };
496
+ const typeErrorsIn = (usage) => appTypeErrors({ '/app/.zite/db.ts': generateDbTs(schema), '/app/src/usage.ts': usage }, { 'zitejs/db': ['/app/.zite/db.ts'] });
497
+ const EQUAL = 'type Equal<A, B> = (<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false;';
498
+ // TanStack Start's serializability check rejects `unknown`, so a server
499
+ // function returning a raw row failed typecheck while created_by fell through.
500
+ it('reads both as a user id', () => {
501
+ expect(typeErrorsIn([
502
+ "import type { TasksRecordType } from 'zitejs/db';",
503
+ EQUAL,
504
+ "export const createdBy: Equal<TasksRecordType['createdBy'], string | undefined> = true;",
505
+ "export const updatedBy: Equal<TasksRecordType['updatedBy'], string | undefined> = true;",
506
+ ].join('\n'))).toEqual([]);
507
+ });
508
+ it('leaves both out of the input type', () => {
509
+ expect(typeErrorsIn([
510
+ "import type { TasksRecordInput } from 'zitejs/db';",
511
+ EQUAL,
512
+ "export const writable: Equal<keyof TasksRecordInput, 'title'> = true;",
513
+ ].join('\n'))).toEqual([]);
514
+ });
515
+ it('filters both by a user id', () => {
516
+ expect(typeErrorsIn([
517
+ "import { zite } from 'zitejs/db';",
518
+ 'export const mine = (userId: string) => [',
519
+ ' zite.tasks.findAll({ filters: { createdBy: userId } }),',
520
+ ' zite.tasks.findAll({ filters: { updatedBy: { in: [userId] } } }),',
521
+ ' zite.tasks.findOne({ filters: { createdBy: { not: null } } }),',
522
+ '];',
523
+ ].join('\n'))).toEqual([]);
524
+ expect(typeErrorsIn("import { zite } from 'zitejs/db';\nvoid zite.tasks.findAll({ filters: { createdBy: 42 } });")).toHaveLength(1);
525
+ });
526
+ });
527
+ describe('generateIntegrationsIndex', () => {
528
+ const typeErrorsIn = (generated, usage, airtable) => appTypeErrors({
529
+ '/app/.zite/integrations/index.ts': generated,
530
+ ...(airtable ? { '/app/.zite/integrations/airtable.ts': airtable } : {}),
531
+ '/app/src/usage.ts': usage,
532
+ }, { 'zitejs/integrations': ['/app/.zite/integrations/index.ts'] });
463
533
  it('emits the client typed by name', () => {
464
534
  expect(generateIntegrationsIndex([
465
535
  { name: 'team', serviceType: 'slack', perUser: false },
@@ -7,7 +7,7 @@ export declare const timeFormatEnum: readonly ["12h", "24h"];
7
7
  export type TimeFormat = (typeof timeFormatEnum)[number];
8
8
  export declare const durationFormatEnum: readonly ["h:mm", "h:mm:ss", "h:mm:ss.s", "h:mm:ss.ss", "h:mm:ss.sss"];
9
9
  export type DurationFormat = (typeof durationFormatEnum)[number];
10
- export declare const fieldTypeEnum: readonly ["currency", "single_line_text", "long_text", "rich_text", "number", "single_select", "multiple_select", "date", "datetime", "checkbox", "attachments", "email", "url", "phone_number", "rating", "duration", "percent", "linked_record", "lookup", "source", "formula", "autonumber", "created_at", "updated_at", "rollup", "updated_by", "user"];
10
+ export declare const fieldTypeEnum: readonly ["currency", "single_line_text", "long_text", "rich_text", "number", "single_select", "multiple_select", "date", "datetime", "checkbox", "attachments", "email", "url", "phone_number", "rating", "duration", "percent", "linked_record", "lookup", "source", "formula", "autonumber", "created_at", "updated_at", "rollup", "created_by", "updated_by", "user"];
11
11
  export type FieldType = (typeof fieldTypeEnum)[number];
12
12
  export declare const fieldTypeSchema: z.ZodEnum<{
13
13
  number: "number";
@@ -35,6 +35,7 @@ export declare const fieldTypeSchema: z.ZodEnum<{
35
35
  created_at: "created_at";
36
36
  updated_at: "updated_at";
37
37
  rollup: "rollup";
38
+ created_by: "created_by";
38
39
  updated_by: "updated_by";
39
40
  user: "user";
40
41
  }>;
@@ -240,6 +241,7 @@ export declare const rollupTemplateSchema: z.ZodObject<{
240
241
  text: "text";
241
242
  }>>;
242
243
  }, z.core.$strip>;
244
+ export declare const createdByTemplateSchema: z.ZodObject<{}, z.core.$strip>;
243
245
  export declare const updatedByTemplateSchema: z.ZodObject<{}, z.core.$strip>;
244
246
  export declare const userTemplateSchema: z.ZodObject<{
245
247
  allowMultiple: z.ZodPipe<z.ZodOptional<z.ZodNullable<z.ZodBoolean>>, z.ZodTransform<boolean, boolean | null | undefined>>;
@@ -554,6 +556,10 @@ export declare const publicFieldDefinitionSchema: z.ZodDiscriminatedUnion<[z.Zod
554
556
  text: "text";
555
557
  }>>;
556
558
  }, z.core.$strip>;
559
+ }, z.core.$strip>, z.ZodObject<{
560
+ name: z.ZodString;
561
+ type: z.ZodLiteral<"created_by">;
562
+ template: z.ZodObject<{}, z.core.$strip>;
557
563
  }, z.core.$strip>, z.ZodObject<{
558
564
  name: z.ZodString;
559
565
  type: z.ZodLiteral<"updated_by">;
@@ -661,6 +667,7 @@ export type FieldTemplateMap = {
661
667
  linked_record: z.infer<typeof linkedRecordTemplateSchema>;
662
668
  lookup: z.infer<typeof lookupTemplateSchema>;
663
669
  rollup: z.infer<typeof rollupTemplateSchema>;
670
+ created_by: z.infer<typeof createdByTemplateSchema>;
664
671
  updated_by: z.infer<typeof updatedByTemplateSchema>;
665
672
  user: z.infer<typeof userTemplateSchema>;
666
673
  source: z.infer<typeof sourceTemplateSchema>;
@@ -42,6 +42,7 @@ export const fieldTypeEnum = [
42
42
  "created_at",
43
43
  "updated_at",
44
44
  "rollup",
45
+ "created_by",
45
46
  "updated_by",
46
47
  "user",
47
48
  ];
@@ -180,6 +181,7 @@ export const rollupTemplateSchema = z.object({
180
181
  .enum(["text", "number", "date", "boolean", "array"])
181
182
  .optional(),
182
183
  });
184
+ export const createdByTemplateSchema = z.object({});
183
185
  export const updatedByTemplateSchema = z.object({});
184
186
  export const userTemplateSchema = z.object({
185
187
  allowMultiple: z
@@ -326,6 +328,10 @@ export const publicFieldDefinitionSchema = z.discriminatedUnion("type", [
326
328
  type: z.literal("rollup"),
327
329
  template: rollupTemplateSchema,
328
330
  }),
331
+ basePublicFieldSchema.extend({
332
+ type: z.literal("created_by"),
333
+ template: createdByTemplateSchema,
334
+ }),
329
335
  basePublicFieldSchema.extend({
330
336
  type: z.literal("updated_by"),
331
337
  template: updatedByTemplateSchema,
@@ -253,6 +253,10 @@ export declare const fieldSchema: z.ZodIntersection<z.ZodObject<{
253
253
  text: "text";
254
254
  }>>;
255
255
  }, z.core.$strip>;
256
+ }, z.core.$strip>, z.ZodObject<{
257
+ name: z.ZodString;
258
+ type: z.ZodLiteral<"created_by">;
259
+ template: z.ZodObject<{}, z.core.$strip>;
256
260
  }, z.core.$strip>, z.ZodObject<{
257
261
  name: z.ZodString;
258
262
  type: z.ZodLiteral<"updated_by">;
@@ -605,6 +609,10 @@ export declare const tableSchema: z.ZodObject<{
605
609
  text: "text";
606
610
  }>>;
607
611
  }, z.core.$strip>;
612
+ }, z.core.$strip>, z.ZodObject<{
613
+ name: z.ZodString;
614
+ type: z.ZodLiteral<"created_by">;
615
+ template: z.ZodObject<{}, z.core.$strip>;
608
616
  }, z.core.$strip>, z.ZodObject<{
609
617
  name: z.ZodString;
610
618
  type: z.ZodLiteral<"updated_by">;
@@ -952,6 +960,10 @@ export declare const publicTableDefinitionSchema: z.ZodObject<{
952
960
  text: "text";
953
961
  }>>;
954
962
  }, z.core.$strip>;
963
+ }, z.core.$strip>, z.ZodObject<{
964
+ name: z.ZodString;
965
+ type: z.ZodLiteral<"created_by">;
966
+ template: z.ZodObject<{}, z.core.$strip>;
955
967
  }, z.core.$strip>, z.ZodObject<{
956
968
  name: z.ZodString;
957
969
  type: z.ZodLiteral<"updated_by">;
@@ -1301,6 +1313,10 @@ export declare const databaseSchema: z.ZodObject<{
1301
1313
  text: "text";
1302
1314
  }>>;
1303
1315
  }, z.core.$strip>;
1316
+ }, z.core.$strip>, z.ZodObject<{
1317
+ name: z.ZodString;
1318
+ type: z.ZodLiteral<"created_by">;
1319
+ template: z.ZodObject<{}, z.core.$strip>;
1304
1320
  }, z.core.$strip>, z.ZodObject<{
1305
1321
  name: z.ZodString;
1306
1322
  type: z.ZodLiteral<"updated_by">;
@@ -1,5 +1,6 @@
1
1
  import { useCallback, useState } from 'react';
2
2
  import { getApiUrl, getFlowId } from '../auth/config.js';
3
+ import { platformMode } from '../internal/appMode.js';
3
4
  import { ZITE_APP_ACTION_HOSTNAME_PREFIX, ZITE_APP_EDITOR_HOSTNAME_PREFIX, ZITE_SANDBOX_DOMAINS, } from '../auth/constants.js';
4
5
  export class FileUploadError extends Error {
5
6
  constructor(message) {
@@ -7,7 +8,16 @@ export class FileUploadError extends Error {
7
8
  this.name = 'FileUploadError';
8
9
  }
9
10
  }
10
- function getZiteAppMode(hostname) {
11
+ /** As the platform served the page or request; a classic app's from its hostname. */
12
+ function getZiteAppMode() {
13
+ const served = platformMode();
14
+ if (served)
15
+ return served === 'preview' || served === 'validate' ? 'preview' : 'live';
16
+ // On a server, outside any request the platform served: there's no telling a preview from live.
17
+ if (typeof window === 'undefined') {
18
+ throw new FileUploadError('Upload from a page, or from a request the platform is serving');
19
+ }
20
+ const { hostname } = window.location;
11
21
  const maybeId = hostname.split('.')[0];
12
22
  if (maybeId?.startsWith(ZITE_APP_EDITOR_HOSTNAME_PREFIX))
13
23
  return 'preview';
@@ -75,7 +85,7 @@ function authHeaders() {
75
85
  }
76
86
  async function performUpload(data, filename) {
77
87
  const blob = toUploadBlob(data);
78
- const mode = getZiteAppMode(window.location.hostname);
88
+ const mode = getZiteAppMode();
79
89
  const flowId = getFlowId();
80
90
  const sessionRes = await fetch(getApiUrl() + '/v1/zite/public/' + flowId + '/upload-session?mode=' + mode, {
81
91
  method: 'POST',
@@ -1,4 +1,6 @@
1
1
  import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import { AsyncLocalStorage } from 'node:async_hooks';
3
+ import { keepRenderedMode } from '../internal/appMode.js';
2
4
  import { FileUploadError, toUploadBlob, uploadFile } from './index.js';
3
5
  vi.mock('../auth/config.js', () => ({
4
6
  getApiUrl: () => 'https://api.example.com',
@@ -91,3 +93,40 @@ describe('uploadFile', () => {
91
93
  await expect(upload).rejects.toThrow('File size exceeds maximum of 20 MB');
92
94
  });
93
95
  });
96
+ // SDK-10: a Start app's mode is the platform's, never guessed from where the page is served.
97
+ describe('the mode an upload goes under', () => {
98
+ const sessionUrl = async () => {
99
+ fetchMock.mockResolvedValueOnce({
100
+ ok: true,
101
+ json: async () => ({ success: true, presignedUrl: 'https://s3.example.com/put', fileUrl: 'https://uploads.zite.com/f.txt' }),
102
+ });
103
+ fetchMock.mockResolvedValueOnce({ ok: true });
104
+ await uploadFile({ data: 'hi', filename: 'f.txt' });
105
+ return String(fetchMock.mock.calls[0][0]);
106
+ };
107
+ afterEach(() => keepRenderedMode(undefined));
108
+ it('is the one the page was rendered in, on any host', async () => {
109
+ keepRenderedMode('preview');
110
+ expect(await sessionUrl()).toContain('mode=preview');
111
+ });
112
+ it("is the request's own on the server, where there's no page", async () => {
113
+ vi.stubGlobal('window', undefined);
114
+ const store = new AsyncLocalStorage();
115
+ globalThis[Symbol.for('zitejs:host-context')] = store;
116
+ try {
117
+ expect(await store.run({ mode: 'validate' }, sessionUrl)).toContain('mode=preview');
118
+ }
119
+ finally {
120
+ delete globalThis[Symbol.for('zitejs:host-context')];
121
+ }
122
+ });
123
+ it('is refused on a server outside any request the platform served, never guessed as live', async () => {
124
+ vi.stubGlobal('window', undefined);
125
+ await expect(uploadFile({ data: 'hi', filename: 'f.txt' })).rejects.toThrow(FileUploadError);
126
+ expect(fetchMock).not.toHaveBeenCalled();
127
+ });
128
+ it("is a classic app's from its hostname, as before", async () => {
129
+ vi.stubGlobal('window', { location: { hostname: 'zite-editor-app_123.zite.so' } });
130
+ expect(await sessionUrl()).toContain('mode=preview');
131
+ });
132
+ });
@@ -69,11 +69,12 @@ export function ziteId() {
69
69
  name: "vite-plugin-zite-id",
70
70
  enforce: "pre",
71
71
  async transform(code, id) {
72
- if (!validExtensions.has(path.extname(id)) ||
73
- id.includes("node_modules")) {
72
+ // TanStack's route code splitting moves a route's component into its own module, `route.tsx?tsr-split=…`.
73
+ const file = id.split("?")[0];
74
+ if (!validExtensions.has(path.extname(file)) || file.includes("node_modules")) {
74
75
  return null;
75
76
  }
76
- const relativePath = path.relative(cwd, id);
77
+ const relativePath = path.relative(cwd, file);
77
78
  try {
78
79
  const ast = parse(code, {
79
80
  sourceType: "module",
@@ -128,6 +129,10 @@ export function ziteId() {
128
129
  if (!isTagged) {
129
130
  return;
130
131
  }
132
+ // A module split from one already tagged keeps its tags.
133
+ if (openingElement.attributes?.some((attr) => attr.type === "JSXAttribute" && attr.name?.name === "data-zite-id")) {
134
+ return;
135
+ }
131
136
  const line = openingElement.loc?.start?.line ?? 0;
132
137
  const col = openingElement.loc?.start?.column ?? 0;
133
138
  const dataComponentId = `${relativePath}|${line}|${col}`;
@@ -1,16 +1,24 @@
1
1
  import path from 'path';
2
2
  import { describe, expect, it } from 'vitest';
3
3
  import { ziteId } from './index.js';
4
- async function transform(code) {
4
+ async function transform(code, file = 'src/App.tsx') {
5
5
  const plugin = ziteId();
6
6
  const handler = plugin.transform;
7
- const result = await handler(code, path.join(process.cwd(), 'src/App.tsx'));
7
+ const result = await handler(code, path.join(process.cwd(), file));
8
8
  if (!result) {
9
9
  throw new Error('transform returned null');
10
10
  }
11
11
  return result.code;
12
12
  }
13
13
  describe('ziteId', () => {
14
+ it("tags a route's component that TanStack split into its own module, by the source file", async () => {
15
+ const code = await transform('const a = <p>Hi</p>;', 'src/routes/index.tsx?tsr-split=component');
16
+ expect(code).toContain('<p data-zite-id="src/routes/index.tsx|1|10" data-zite-editable="true">');
17
+ });
18
+ it('leaves an element that already has its tag', async () => {
19
+ const code = await transform('const a = <p data-zite-id="src/routes/index.tsx|1|10">Hi</p>;');
20
+ expect(code.match(/data-zite-id/g)).toHaveLength(1);
21
+ });
14
22
  it('tags html and svg elements without a component name', async () => {
15
23
  const code = await transform('const a = <div><svg><path d="M0" /></svg><p>Hello</p></div>;');
16
24
  expect(code).toContain('<div data-zite-id="src/App.tsx|1|10">');