@lumibase/sdk 2.0.0 → 2.2.1

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.
package/dist/index.js CHANGED
@@ -88,16 +88,35 @@ function createLumiClient(opts) {
88
88
  }
89
89
  return refreshInFlight;
90
90
  }
91
- async function rawRequest(path, init = {}, retried = false) {
91
+ function buildHeaders(init) {
92
92
  const headers = new Headers(init.headers);
93
93
  for (const [key, value] of Object.entries(opts.headers ?? {})) {
94
94
  headers.set(key, value);
95
95
  }
96
96
  headers.set("authorization", `Bearer ${currentToken}`);
97
97
  headers.set("x-lumi-site", opts.siteId);
98
- if (!headers.has("content-type") && init.body) {
98
+ const isForm = typeof FormData !== "undefined" && init.body instanceof FormData;
99
+ if (!headers.has("content-type") && init.body && !isForm) {
99
100
  headers.set("content-type", "application/json");
100
101
  }
102
+ return headers;
103
+ }
104
+ async function rawFetch(path, init = {}, retried = false) {
105
+ const res = await fetcher(`${base}${path}`, { ...init, headers: buildHeaders(init) });
106
+ if (res.ok) return res;
107
+ if (res.status === 401 && !retried && currentRefreshToken && await attemptRefresh()) {
108
+ return rawFetch(path, init, true);
109
+ }
110
+ if (res.status === 401 && opts.onUnauthorized) {
111
+ try {
112
+ opts.onUnauthorized();
113
+ } catch {
114
+ }
115
+ }
116
+ throw new LumiError(res.status, toErrorBody(res.status, parseResponseBody(await res.text())), res.headers);
117
+ }
118
+ async function rawRequest(path, init = {}, retried = false) {
119
+ const headers = buildHeaders(init);
101
120
  const res = await fetcher(`${base}${path}`, { ...init, headers });
102
121
  const text = await res.text();
103
122
  const body = parseResponseBody(text);
@@ -125,6 +144,7 @@ function createLumiClient(opts) {
125
144
  siteId: opts.siteId,
126
145
  fetcher,
127
146
  rawRequest,
147
+ rawFetch: (path, init) => rawFetch(path, init),
128
148
  async request(command) {
129
149
  return command(this);
130
150
  },
@@ -315,6 +335,29 @@ var AudienceClient = class {
315
335
  }
316
336
  };
317
337
 
338
+ // src/realtime/retain.ts
339
+ var holders = /* @__PURE__ */ new WeakMap();
340
+ function realtimeHolders(client) {
341
+ return holders.get(client) ?? 0;
342
+ }
343
+ function retainRealtime(client) {
344
+ const count = realtimeHolders(client);
345
+ holders.set(client, count + 1);
346
+ if (count === 0) client.connect();
347
+ let released = false;
348
+ return () => {
349
+ if (released) return;
350
+ released = true;
351
+ const next = realtimeHolders(client) - 1;
352
+ if (next <= 0) {
353
+ holders.delete(client);
354
+ client.disconnect();
355
+ } else {
356
+ holders.set(client, next);
357
+ }
358
+ };
359
+ }
360
+
318
361
  // src/realtime/index.ts
319
362
  var RealtimeClient = class {
320
363
  constructor(opts) {
@@ -517,6 +560,10 @@ var RealtimeClient = class {
517
560
  };
518
561
 
519
562
  // src/rest/legacy.ts
563
+ function ifMatchInit(options) {
564
+ if (options?.ifMatch === void 0) return {};
565
+ return { headers: { "if-match": `"${options.ifMatch}"` } };
566
+ }
520
567
  function withQuery(path, params = {}) {
521
568
  const qs = new URLSearchParams();
522
569
  for (const [key, value] of Object.entries(params)) {
@@ -625,7 +672,31 @@ function legacyRest() {
625
672
  deleteField: fields.delete,
626
673
  listRelations: relations.list,
627
674
  createRelation: relations.create,
628
- deleteRelation: relations.delete
675
+ deleteRelation: relations.delete,
676
+ /**
677
+ * Collection form layout (#750): tabs / groups / dividers + conditions.
678
+ * Typed loosely so the SDK stays decoupled from contracts; parse with
679
+ * `parseFormLayout` from `@lumibase/contracts/form-layout`.
680
+ */
681
+ getFormLayout: (name) => client.rawRequest(
682
+ `/api/v1/collections/${name}/form-layout`
683
+ ),
684
+ setFormLayout: (name, layout) => client.rawRequest(
685
+ `/api/v1/collections/${name}/form-layout`,
686
+ { method: "PUT", body: JSON.stringify({ layout }) }
687
+ ),
688
+ /**
689
+ * Expression index advice for filtering on a JSON path (#729). `cast`
690
+ * defaults to the declared type of a top-level field; nested paths
691
+ * must name it. Read-only: the DDL is returned, never executed.
692
+ */
693
+ indexAdvice: (name, path, cast) => {
694
+ const params = new URLSearchParams({ path });
695
+ if (cast) params.set("cast", cast);
696
+ return client.rawRequest(
697
+ `/api/v1/collections/${encodeURIComponent(name)}/index-advice?${params.toString()}`
698
+ );
699
+ }
629
700
  };
630
701
  function items(name) {
631
702
  function buildQuery(params) {
@@ -638,6 +709,8 @@ function legacyRest() {
638
709
  if (params.offset !== void 0)
639
710
  qs.set("offset", String(params.offset));
640
711
  if (params.status) qs.set("status", params.status);
712
+ if (params.publicationState) qs.set("publicationState", params.publicationState);
713
+ if (params.modifiedSincePublish) qs.set("modifiedSincePublish", "true");
641
714
  const s = qs.toString();
642
715
  return s ? `?${s}` : "";
643
716
  }
@@ -656,19 +729,90 @@ function legacyRest() {
656
729
  method: "POST",
657
730
  body: JSON.stringify(input)
658
731
  }),
659
- patch: (id, input) => client.rawRequest(`${base}/${id}`, {
732
+ patch: (id, input, options) => client.rawRequest(`${base}/${id}`, {
660
733
  method: "PATCH",
661
- body: JSON.stringify(input)
734
+ body: JSON.stringify(input),
735
+ ...ifMatchInit(options)
662
736
  }),
663
- replace: (id, input) => client.rawRequest(`${base}/${id}`, {
737
+ replace: (id, input, options) => client.rawRequest(`${base}/${id}`, {
664
738
  method: "PUT",
739
+ ...ifMatchInit(options),
665
740
  body: JSON.stringify(input)
666
741
  }),
667
742
  delete: (id) => client.rawRequest(`${base}/${id}`, { method: "DELETE" }),
743
+ /**
744
+ * Stream the collection as CSV or JSON (#727). Resolves with the
745
+ * unread `Response`: pipe `res.body` to a file, or `await res.text()`.
746
+ * Uses the caller's read permission; filters use the list syntax.
747
+ */
748
+ export: (params = {}) => {
749
+ const qs = new URLSearchParams();
750
+ if (params.format) qs.set("format", params.format);
751
+ if (params.fields?.length) qs.set("fields", params.fields.join(","));
752
+ if (params.locales?.length) qs.set("locales", params.locales.join(","));
753
+ if (params.relations) qs.set("relations", params.relations);
754
+ if (params.filter) qs.set("filter", JSON.stringify(params.filter));
755
+ if (params.sort?.length) qs.set("sort", params.sort.join(","));
756
+ if (params.status) qs.set("status", params.status);
757
+ const s = qs.toString();
758
+ return client.rawFetch(`${base}/export${s ? `?${s}` : ""}`);
759
+ },
668
760
  bulk: (op, payload) => client.rawRequest(`${base}/bulk`, {
669
761
  method: "POST",
670
762
  body: JSON.stringify({ op, items: payload })
671
763
  }),
764
+ /**
765
+ * Save-as-copy (#689): a draft copy with unique fields suffixed
766
+ * (`-copy`, `-copy-2`, …). Goes through the normal create path.
767
+ */
768
+ duplicate: (id, options = {}) => client.rawRequest(`${base}/${encodeURIComponent(id)}/duplicate`, {
769
+ method: "POST",
770
+ body: JSON.stringify(options)
771
+ }),
772
+ /**
773
+ * Manual ordering (#690) on a `meta.manualSort` collection: place `id`
774
+ * right after `after` (null = first) or right before `before`.
775
+ */
776
+ reorder: (id, target) => client.rawRequest(`${base}/${encodeURIComponent(id)}/reorder`, {
777
+ method: "POST",
778
+ body: JSON.stringify(target)
779
+ }),
780
+ /**
781
+ * Patch without recording a revision (#693) — for autosave and
782
+ * machine writes. Agent-authored writes keep their revision anyway.
783
+ */
784
+ patchWithoutRevision: (id, input) => client.rawRequest(`${base}/${id}?saveRevision=false`, {
785
+ method: "PATCH",
786
+ body: JSON.stringify(input)
787
+ }),
788
+ /**
789
+ * Hierarchical collections (#749) on a `meta.tree.enabled` collection.
790
+ * Reads apply the caller's row rules; the anchor must be readable.
791
+ */
792
+ tree: {
793
+ children: (parent, params) => {
794
+ const q = buildQuery(params);
795
+ const sep = q ? "&" : "?";
796
+ return client.rawRequest(
797
+ `${base}${q}${sep}tree=children&parent=${encodeURIComponent(parent ?? "null")}`
798
+ );
799
+ },
800
+ subtree: (parent, params) => {
801
+ const q = buildQuery(params);
802
+ const sep = q ? "&" : "?";
803
+ return client.rawRequest(
804
+ `${base}${q}${sep}tree=subtree&parent=${encodeURIComponent(parent ?? "null")}`
805
+ );
806
+ },
807
+ ancestors: (node) => client.rawRequest(
808
+ `${base}?tree=ancestors&node=${encodeURIComponent(node)}`
809
+ ),
810
+ /** Move an item and its subtree; `position` is its 0-based index among the new siblings. */
811
+ move: (id, input) => client.rawRequest(`${base}/${id}/move`, {
812
+ method: "POST",
813
+ body: JSON.stringify(input)
814
+ })
815
+ },
672
816
  listRevisions: (id) => client.rawRequest(`${base}/${id}/revisions`),
673
817
  revertRevision: (id, revisionId) => client.rawRequest(`${base}/${id}/revert/${revisionId}`, {
674
818
  method: "POST"
@@ -925,10 +1069,66 @@ function legacyRest() {
925
1069
  method: "PATCH",
926
1070
  body: JSON.stringify(patch)
927
1071
  }),
928
- delete: (id) => client.rawRequest(`/api/v1/files/folders/${id}`, { method: "DELETE" })
1072
+ delete: (id) => client.rawRequest(`/api/v1/files/folders/${id}`, { method: "DELETE" }),
1073
+ /** Nested folder tree with id paths (`/a/b/`) and name paths (#701). */
1074
+ tree: () => client.rawRequest("/api/v1/files/folders/tree")
929
1075
  };
930
1076
  const files = {
931
- list: () => client.rawRequest("/api/v1/files"),
1077
+ /**
1078
+ * List / filter the library. Without a query: the first 1000 files,
1079
+ * newest first. `meta` carries `{ total, limit, offset }`.
1080
+ */
1081
+ list: (query) => {
1082
+ const q = new URLSearchParams();
1083
+ if (query?.folder !== void 0) q.set("folder", query.folder);
1084
+ if (query?.subfolders) q.set("subfolders", "true");
1085
+ if (query?.search) q.set("search", query.search);
1086
+ if (query?.mime?.length) q.set("mime", query.mime.join(","));
1087
+ if (query?.ids?.length) q.set("ids", query.ids.join(","));
1088
+ if (query?.limit !== void 0) q.set("limit", String(query.limit));
1089
+ if (query?.offset !== void 0) q.set("offset", String(query.offset));
1090
+ const qs = q.toString();
1091
+ return client.rawRequest(`/api/v1/files${qs ? `?${qs}` : ""}`);
1092
+ },
1093
+ get: (id) => client.rawRequest(`/api/v1/files/${encodeURIComponent(id)}`),
1094
+ /**
1095
+ * Replace the bytes behind a file in place (#703): same id, key, folder
1096
+ * and references; `version` bumps. Pass `expectedVersion` to refuse
1097
+ * (409) when someone replaced it since you loaded it.
1098
+ */
1099
+ replaceContent: (id, body, opts) => {
1100
+ const q = opts.filename ? `?filename=${encodeURIComponent(opts.filename)}` : "";
1101
+ const headers = { "content-type": opts.mime };
1102
+ if (opts.expectedVersion !== void 0) headers["if-match"] = `"v${opts.expectedVersion}"`;
1103
+ return client.rawRequest(`/api/v1/files/${encodeURIComponent(id)}/content${q}`, {
1104
+ method: "PUT",
1105
+ body,
1106
+ headers
1107
+ });
1108
+ },
1109
+ /** URL that serves the current bytes; pass `version` for an immutable, cacheable URL. */
1110
+ contentUrl: (id, version) => `${client.url.replace(/\/$/, "")}/api/v1/files/${encodeURIComponent(id)}/content${version !== void 0 ? `?v=${version}` : ""}`,
1111
+ versions: (id) => client.rawRequest(`/api/v1/files/${encodeURIComponent(id)}/versions`),
1112
+ restoreVersion: (id, versionId) => client.rawRequest(
1113
+ `/api/v1/files/${encodeURIComponent(id)}/versions/${encodeURIComponent(versionId)}/restore`,
1114
+ { method: "POST" }
1115
+ ),
1116
+ /** Items and pages that reference the file (#706). */
1117
+ usage: (id) => client.rawRequest(`/api/v1/files/${encodeURIComponent(id)}/usage`),
1118
+ /** Files with the same content hash (lowercase hex SHA-256). */
1119
+ duplicates: (hash) => client.rawRequest(`/api/v1/files/duplicates?hash=${encodeURIComponent(hash)}`),
1120
+ /** Bulk move and/or merge editorial metadata (alt, title, caption, credit, tags). */
1121
+ bulk: (input) => client.rawRequest("/api/v1/files/bulk", {
1122
+ method: "POST",
1123
+ body: JSON.stringify(input)
1124
+ }),
1125
+ settings: {
1126
+ get: () => client.rawRequest("/api/v1/files/settings"),
1127
+ update: (patch) => client.rawRequest("/api/v1/files/settings", {
1128
+ method: "PUT",
1129
+ body: JSON.stringify(patch)
1130
+ })
1131
+ },
932
1132
  create: (input) => client.rawRequest("/api/v1/files", {
933
1133
  method: "POST",
934
1134
  body: JSON.stringify(input)
@@ -937,7 +1137,12 @@ function legacyRest() {
937
1137
  method: "PATCH",
938
1138
  body: JSON.stringify(patch)
939
1139
  }),
940
- delete: (id) => client.rawRequest(`/api/v1/files/${id}`, { method: "DELETE" }),
1140
+ /**
1141
+ * Safe delete (#706): a referenced file answers 409 `FILE_IN_USE` with the
1142
+ * references in `errors[0].details.usage`; repeat with `{ confirm: true }`
1143
+ * to delete anyway (unless the site's policy is `block`).
1144
+ */
1145
+ delete: (id, opts) => client.rawRequest(`/api/v1/files/${id}${opts?.confirm ? "?confirm=true" : ""}`, { method: "DELETE" }),
941
1146
  getPresignedUrl: (filename) => client.rawRequest("/api/v1/files/presigned-url", {
942
1147
  method: "POST",
943
1148
  body: JSON.stringify({ filename })
@@ -1068,6 +1273,23 @@ function legacyRest() {
1068
1273
  target: { type: "api_key", id }
1069
1274
  })
1070
1275
  };
1276
+ const preview = {
1277
+ mintToken: (input) => client.rawRequest("/api/v1/preview/token", {
1278
+ method: "POST",
1279
+ body: JSON.stringify(input)
1280
+ }),
1281
+ listTokens: () => client.rawRequest("/api/v1/preview/tokens"),
1282
+ revokeToken: (id) => client.rawRequest(`/api/v1/preview/tokens/${encodeURIComponent(id)}/revoke`, {
1283
+ method: "POST"
1284
+ }),
1285
+ /** Rotation: revoke every live preview token of the site (site admin). */
1286
+ revokeAll: () => client.rawRequest("/api/v1/preview/tokens/revoke-all", { method: "POST" }),
1287
+ getSettings: () => client.rawRequest("/api/v1/preview/settings"),
1288
+ updateSettings: (input) => client.rawRequest("/api/v1/preview/settings", {
1289
+ method: "PUT",
1290
+ body: JSON.stringify(input)
1291
+ })
1292
+ };
1071
1293
  const shares = {
1072
1294
  create: (input) => client.rawRequest("/api/v1/shares", {
1073
1295
  method: "POST",
@@ -1096,10 +1318,44 @@ function legacyRest() {
1096
1318
  body: JSON.stringify(patch)
1097
1319
  }),
1098
1320
  delete: (id) => client.rawRequest(`/api/v1/deployments/targets/${id}`, { method: "DELETE" }),
1099
- deploy: (id, input = {}) => client.rawRequest(`/api/v1/deployments/targets/${id}/deploy`, {
1100
- method: "POST",
1101
- body: JSON.stringify(input)
1102
- })
1321
+ /**
1322
+ * Resolves with the deployment (201), or — when the target belongs to
1323
+ * an approval-gated environment (#743) — with a `pending_approval`
1324
+ * outcome (202).
1325
+ */
1326
+ deploy: (id, input = {}) => client.rawRequest(
1327
+ `/api/v1/deployments/targets/${id}/deploy`,
1328
+ {
1329
+ method: "POST",
1330
+ body: JSON.stringify(input)
1331
+ }
1332
+ )
1333
+ },
1334
+ // Environments, promotion and deploy approvals (#743).
1335
+ access: () => client.rawRequest("/api/v1/deployments/access"),
1336
+ environments: {
1337
+ list: () => client.rawRequest("/api/v1/deployments/environments"),
1338
+ update: (environments) => client.rawRequest("/api/v1/deployments/environments", {
1339
+ method: "PUT",
1340
+ body: JSON.stringify({ environments })
1341
+ }),
1342
+ deploy: (key, input = {}) => client.rawRequest(
1343
+ `/api/v1/deployments/environments/${encodeURIComponent(key)}/deploy`,
1344
+ { method: "POST", body: JSON.stringify(input) }
1345
+ ),
1346
+ promote: (key, input = {}) => client.rawRequest(
1347
+ `/api/v1/deployments/environments/${encodeURIComponent(key)}/promote`,
1348
+ { method: "POST", body: JSON.stringify(input) }
1349
+ )
1350
+ },
1351
+ approvals: {
1352
+ list: (status = "pending") => client.rawRequest(
1353
+ `/api/v1/deployments/approvals?status=${encodeURIComponent(status)}`
1354
+ ),
1355
+ decide: (id, input) => client.rawRequest(
1356
+ `/api/v1/deployments/approvals/${encodeURIComponent(id)}/decide`,
1357
+ { method: "POST", body: JSON.stringify(input) }
1358
+ )
1103
1359
  },
1104
1360
  list: (params) => {
1105
1361
  const qs = new URLSearchParams();
@@ -1112,14 +1368,46 @@ function legacyRest() {
1112
1368
  logs: (id) => client.rawRequest(`/api/v1/deployments/${id}/logs`),
1113
1369
  refresh: (id) => client.rawRequest(`/api/v1/deployments/${id}/refresh`, { method: "POST" })
1114
1370
  };
1371
+ const imports = {
1372
+ /**
1373
+ * Upload a CSV or JSON export file and queue it. Resolves with the job
1374
+ * (`202`); poll `get(id)` until `status` is terminal.
1375
+ */
1376
+ create: (collection, file, opts = {}) => {
1377
+ const qs = new URLSearchParams({ collection });
1378
+ if (opts.format) qs.set("format", opts.format);
1379
+ if (opts.mode) qs.set("mode", opts.mode);
1380
+ const form = new FormData();
1381
+ const blob = typeof file === "string" ? new Blob([file], { type: "application/octet-stream" }) : file;
1382
+ form.append("file", blob, opts.filename ?? `${collection}.${opts.format ?? "csv"}`);
1383
+ return client.rawRequest(`/api/v1/imports?${qs.toString()}`, { method: "POST", body: form });
1384
+ },
1385
+ list: (params = {}) => {
1386
+ const qs = new URLSearchParams();
1387
+ if (params.collection) qs.set("collection", params.collection);
1388
+ if (params.status) qs.set("status", params.status);
1389
+ if (params.limit !== void 0) qs.set("limit", String(params.limit));
1390
+ const s = qs.toString();
1391
+ return client.rawRequest(`/api/v1/imports${s ? `?${s}` : ""}`);
1392
+ },
1393
+ get: (id) => client.rawRequest(`/api/v1/imports/${encodeURIComponent(id)}`),
1394
+ errors: (id) => client.rawRequest(
1395
+ `/api/v1/imports/${encodeURIComponent(id)}/errors`
1396
+ ),
1397
+ /** The error report as a CSV download (`row,id,message`). */
1398
+ errorsCsv: (id) => client.rawFetch(`/api/v1/imports/${encodeURIComponent(id)}/errors?format=csv`),
1399
+ cancel: (id) => client.rawRequest(`/api/v1/imports/${encodeURIComponent(id)}/cancel`, { method: "POST" })
1400
+ };
1115
1401
  return {
1116
1402
  schema,
1117
1403
  items,
1404
+ imports,
1118
1405
  roles,
1119
1406
  policies,
1120
1407
  access,
1121
1408
  apiKeys,
1122
1409
  shares,
1410
+ preview,
1123
1411
  me,
1124
1412
  permissions,
1125
1413
  presets,
@@ -1415,7 +1703,7 @@ function readItem(collection, id, fields) {
1415
1703
  const res = await client.rawRequest(
1416
1704
  `/api/v1/items/${collection}/${id}${fields?.length ? `?fields=${fields.join(",")}` : ""}`
1417
1705
  );
1418
- return res;
1706
+ return res.data;
1419
1707
  };
1420
1708
  }
1421
1709
  function exportAccessManifest() {
@@ -1797,6 +2085,583 @@ function graphql(endpoint = "/api/v1/graphql") {
1797
2085
  };
1798
2086
  }
1799
2087
 
2088
+ // src/typegen/shared.ts
2089
+ var TRANSLATABLE_INTERFACE = "translatable-text";
2090
+ var FILE_INTERFACE = "file";
2091
+ var FILES_INTERFACE = "files";
2092
+ function fieldShape(field) {
2093
+ if (field.kind === "m2o") return { kind: "m2o" };
2094
+ if (field.kind === "o2m" || field.kind === "m2m") {
2095
+ return { kind: "to-many", target: field.target || "unknown" };
2096
+ }
2097
+ if (field.kind === "m2a") return { kind: "m2a" };
2098
+ if (field.interface === TRANSLATABLE_INTERFACE) return { kind: "localized" };
2099
+ if (field.interface === FILES_INTERFACE || field.type === "files") return { kind: "files" };
2100
+ if (field.interface === FILE_INTERFACE) return { kind: "file" };
2101
+ if (field.enum && field.enum.length > 0) return { kind: "enum", values: field.enum };
2102
+ if (field.primaryKey) return { kind: "primary-key" };
2103
+ return { kind: "scalar" };
2104
+ }
2105
+ function isOptional(field) {
2106
+ return !field.required;
2107
+ }
2108
+ function isNullable(field) {
2109
+ return !field.required || field.nullable;
2110
+ }
2111
+ function hasIntegerPrimaryKey(collection) {
2112
+ return collection?.primaryKeyType === "integer" || collection?.primaryKeyType === "bigInteger";
2113
+ }
2114
+ function relationsOf(collection) {
2115
+ return collection.relations ?? [];
2116
+ }
2117
+ function capitalize(str) {
2118
+ return str.charAt(0).toUpperCase() + str.slice(1);
2119
+ }
2120
+ var IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
2121
+ function propertyKey(name) {
2122
+ return IDENTIFIER.test(name) ? name : JSON.stringify(name);
2123
+ }
2124
+ function filterManifest(manifest, filters) {
2125
+ const { include, exclude } = filters;
2126
+ if (!include?.length && !exclude?.length) return manifest;
2127
+ return {
2128
+ ...manifest,
2129
+ collections: manifest.collections.filter(
2130
+ (collection) => (!include?.length || include.includes(collection.name)) && !(exclude?.length && exclude.includes(collection.name))
2131
+ )
2132
+ };
2133
+ }
2134
+
2135
+ // src/typegen/richtext.ts
2136
+ var RICHTEXT_TS_DECLARATIONS = `export type RichTextMark = 'bold' | 'italic' | 'underline' | 'strike' | 'code' | 'superscript' | 'subscript';
2137
+
2138
+ export interface RichTextRef {
2139
+ kind: 'item' | 'file';
2140
+ collection?: string;
2141
+ id: string;
2142
+ }
2143
+
2144
+ export type RichTextInline =
2145
+ | { type: 'text'; text: string; marks?: RichTextMark[] }
2146
+ | { type: 'link'; href: string; content: RichTextInline[] }
2147
+ | { type: 'ref'; ref: RichTextRef; content: RichTextInline[] }
2148
+ | { type: 'embed'; ref: RichTextRef; alt?: string }
2149
+ | { type: 'break' }
2150
+ | { type: 'footnote'; label: string };
2151
+
2152
+ export interface RichTextTableRow {
2153
+ header?: boolean;
2154
+ cells: RichTextBlock[][];
2155
+ }
2156
+
2157
+ export type RichTextBlock =
2158
+ | { type: 'paragraph'; content: RichTextInline[] }
2159
+ | { type: 'heading'; level: 1 | 2 | 3 | 4 | 5 | 6; content: RichTextInline[] }
2160
+ | { type: 'quote'; content: RichTextBlock[] }
2161
+ | { type: 'list'; ordered: boolean; start?: number; items: RichTextBlock[][] }
2162
+ | { type: 'code'; language?: string; text: string }
2163
+ | { type: 'rule' }
2164
+ | { type: 'embed'; ref: RichTextRef; alt?: string }
2165
+ | { type: 'table'; rows: RichTextTableRow[]; caption?: string; headerColumn?: boolean; align?: Array<'left' | 'center' | 'right' | null> }
2166
+ | { type: 'footnote'; label: string; content: RichTextBlock[] }
2167
+ | { type: 'custom'; name: string; data: Record<string, unknown> };
2168
+
2169
+ export interface RichTextDocument {
2170
+ type: 'doc';
2171
+ version: 1;
2172
+ content: RichTextBlock[];
2173
+ }`;
2174
+ var RICHTEXT_ZOD = "z.object({ type: z.literal('doc'), version: z.literal(1), content: z.array(z.record(z.string(), z.unknown())) })";
2175
+
2176
+ // src/typegen/zod.ts
2177
+ var DEFAULT_ZOD_IMPORT = "zod";
2178
+ function generateZod(manifest, options = {}) {
2179
+ const importSource = options.importSource ?? DEFAULT_ZOD_IMPORT;
2180
+ const byName = new Map(manifest.collections.map((collection) => [collection.name, collection]));
2181
+ const blocks = manifest.collections.map((collection) => {
2182
+ const name = capitalize(collection.name);
2183
+ const props = collection.fields.map((field) => ` ${propertyKey(field.name)}: ${fieldValidator(field, collection, byName)},`).join("\n");
2184
+ return [
2185
+ `export const ${name}Schema = z.object({`,
2186
+ props,
2187
+ "});",
2188
+ `export type ${name} = z.infer<typeof ${name}Schema>;`
2189
+ ].filter((line) => line !== "").join("\n");
2190
+ });
2191
+ const map = [
2192
+ "export const LumibaseSchemas = {",
2193
+ ...manifest.collections.map(
2194
+ (collection) => ` ${propertyKey(collection.name)}: ${capitalize(collection.name)}Schema,`
2195
+ ),
2196
+ "} as const;"
2197
+ ].join("\n");
2198
+ return [`import { z } from ${JSON.stringify(importSource)};`, ...blocks, map].join("\n\n");
2199
+ }
2200
+ function fieldValidator(field, collection, byName) {
2201
+ const shape = fieldShape(field);
2202
+ let schema;
2203
+ switch (shape.kind) {
2204
+ case "to-many": {
2205
+ const target = byName.get(shape.target);
2206
+ const id = target ? primaryKeyValidator(target) : "z.union([z.string(), z.number()])";
2207
+ return withOptional(field, `z.array(z.union([${id}, z.record(z.string(), z.unknown())]))`);
2208
+ }
2209
+ case "m2a":
2210
+ return withOptional(
2211
+ field,
2212
+ "z.array(z.object({ collection: z.string(), item: z.unknown() }))"
2213
+ );
2214
+ case "localized":
2215
+ schema = "z.record(z.string(), z.string())";
2216
+ break;
2217
+ case "file":
2218
+ schema = "z.string()";
2219
+ break;
2220
+ case "files":
2221
+ schema = "z.array(z.string())";
2222
+ break;
2223
+ case "enum":
2224
+ return wrap(field, `z.enum(${JSON.stringify(shape.values)})`);
2225
+ case "primary-key":
2226
+ return wrap(field, primaryKeyValidator(collection));
2227
+ case "m2o":
2228
+ return wrap(field, scalarValidator(field.type));
2229
+ case "scalar":
2230
+ schema = scalarValidator(field.type);
2231
+ break;
2232
+ }
2233
+ if (field.encrypted) schema = `z.union([${schema}, z.literal('***')])`;
2234
+ return wrap(field, schema);
2235
+ }
2236
+ function primaryKeyValidator(collection) {
2237
+ const type = collection.primaryKeyType ?? "nanoid";
2238
+ return type === "integer" || type === "bigInteger" ? "z.number().int()" : "z.string()";
2239
+ }
2240
+ function scalarValidator(type) {
2241
+ switch (type) {
2242
+ case "string":
2243
+ case "text":
2244
+ case "hash":
2245
+ case "csv":
2246
+ case "uuid":
2247
+ case "date":
2248
+ case "datetime":
2249
+ case "dateTime":
2250
+ case "time":
2251
+ case "timestamp":
2252
+ return "z.string()";
2253
+ case "integer":
2254
+ return "z.number().int()";
2255
+ case "bigInteger":
2256
+ case "decimal":
2257
+ case "float":
2258
+ return "z.number()";
2259
+ case "boolean":
2260
+ return "z.boolean()";
2261
+ case "geometry":
2262
+ return "z.record(z.string(), z.unknown())";
2263
+ case "richtext":
2264
+ return RICHTEXT_ZOD;
2265
+ default:
2266
+ return "z.unknown()";
2267
+ }
2268
+ }
2269
+ function wrap(field, schema) {
2270
+ return withOptional(field, isNullable(field) ? `${schema}.nullable()` : schema);
2271
+ }
2272
+ function withOptional(field, schema) {
2273
+ return isOptional(field) ? `${schema}.optional()` : schema;
2274
+ }
2275
+
2276
+ // src/typegen/graphql-sdl.ts
2277
+ function generateGraphQLSdl(manifest) {
2278
+ const collections = manifest.collections.filter((collection) => GRAPHQL_NAME.test(collection.name));
2279
+ const typeNames = new Map(collections.map((collection) => [collection.name, pascalCase(collection.name)]));
2280
+ const blocks = ["scalar JSON", "scalar DateTime"];
2281
+ for (const collection of collections) {
2282
+ blocks.push(objectType(typeNames.get(collection.name), itemFields(collection, typeNames)));
2283
+ }
2284
+ if (collections.some((c) => c.fields.some((f) => !f.system && f.type === "richtext" && !RESERVED.has(f.name) && GRAPHQL_NAME.test(f.name)))) {
2285
+ blocks.push(objectType("RichText", ["json: JSON", "html: String", "markdown: String", "text: String"]));
2286
+ }
2287
+ const query = ["_collections: [String!]!"];
2288
+ const mutation = [];
2289
+ const subscription = [];
2290
+ for (const collection of collections) {
2291
+ const name = collection.name;
2292
+ const type = typeNames.get(name);
2293
+ query.push(
2294
+ `${name}(filter: JSON, sort: [String!], limit: Int, offset: Int, status: String, publicationState: PublicationState, modifiedSincePublish: Boolean): [${type}!]!`,
2295
+ `${name}_by_id(id: ID!, publicationState: PublicationState): ${type}`
2296
+ );
2297
+ mutation.push(
2298
+ `create_${name}(data: JSON!, status: String, sort: Int): ${type}!`,
2299
+ `update_${name}(id: ID!, data: JSON, status: String, sort: Int): ${type}!`,
2300
+ `delete_${name}(id: ID!): Boolean!`
2301
+ );
2302
+ subscription.push(`${name}_events: ItemEvent!`);
2303
+ }
2304
+ blocks.push(objectType("Query", query));
2305
+ if (collections.length > 0) blocks.push("enum PublicationState {\n live\n preview\n all\n}");
2306
+ if (mutation.length > 0) blocks.push(objectType("Mutation", mutation));
2307
+ if (subscription.length > 0) {
2308
+ blocks.push(objectType("Subscription", subscription));
2309
+ blocks.push(
2310
+ objectType("ItemEvent", [
2311
+ "collection: String!",
2312
+ "action: String!",
2313
+ "itemId: ID!",
2314
+ "item: JSON"
2315
+ ])
2316
+ );
2317
+ }
2318
+ return `${blocks.join("\n\n")}
2319
+ `;
2320
+ }
2321
+ var STRUCTURAL = [
2322
+ ["id", "ID!"],
2323
+ ["status", "String"],
2324
+ ["sort", "Int"],
2325
+ ["createdAt", "DateTime"],
2326
+ ["updatedAt", "DateTime"],
2327
+ ["userCreated", "String"],
2328
+ ["userUpdated", "String"],
2329
+ ["_data", "JSON"],
2330
+ // Publication state (#687), underscored so a content field keeps its name.
2331
+ ["_firstPublishedAt", "DateTime"],
2332
+ ["_publishedAt", "DateTime"],
2333
+ ["_hasUnpublishedChanges", "Boolean"]
2334
+ ];
2335
+ var RESERVED = /* @__PURE__ */ new Set([
2336
+ "id",
2337
+ "status",
2338
+ "sort",
2339
+ "createdAt",
2340
+ "updatedAt",
2341
+ "userCreated",
2342
+ "userUpdated",
2343
+ "created_at",
2344
+ "updated_at",
2345
+ "user_created",
2346
+ "user_updated",
2347
+ "_data",
2348
+ "_firstPublishedAt",
2349
+ "_publishedAt",
2350
+ "_hasUnpublishedChanges"
2351
+ ]);
2352
+ var GRAPHQL_NAME = /^[_A-Za-z][_0-9A-Za-z]*$/;
2353
+ function itemFields(collection, typeNames) {
2354
+ const fields = new Map(STRUCTURAL);
2355
+ for (const field of collection.fields) {
2356
+ if (field.system || RESERVED.has(field.name) || !GRAPHQL_NAME.test(field.name)) continue;
2357
+ fields.set(field.name, scalarFor(field.type));
2358
+ }
2359
+ for (const relation of relationsOf(collection)) {
2360
+ const nested = relationField(collection, relation, typeNames);
2361
+ if (!nested || !GRAPHQL_NAME.test(nested.name) || fields.has(nested.name)) continue;
2362
+ fields.set(nested.name, nested.args ? `${nested.args}: ${nested.type}` : nested.type);
2363
+ }
2364
+ return [...fields].map(([name, type]) => type.startsWith("(") ? `${name}${type}` : `${name}: ${type}`);
2365
+ }
2366
+ function relationField(collection, relation, typeNames) {
2367
+ const many = relation.manyCollection ?? (relation.kind === "m2o" ? collection.name : relation.target);
2368
+ const one = relation.oneCollection ?? (relation.kind === "m2o" ? relation.target : collection.name);
2369
+ const stored = relation.relationType ?? (many === collection.name ? relation.kind : void 0);
2370
+ if (stored === "m2o" && many === collection.name) {
2371
+ const target = typeNames.get(one);
2372
+ return target ? { name: relation.alias ?? m2oAlias(relation, one), type: target } : null;
2373
+ }
2374
+ if (stored === "o2m" && one === collection.name) {
2375
+ const target = typeNames.get(many);
2376
+ return target ? { name: relation.alias ?? many, args: "(limit: Int, offset: Int)", type: `[${target}!]!` } : null;
2377
+ }
2378
+ return null;
2379
+ }
2380
+ function m2oAlias(relation, oneCollection) {
2381
+ const manyField = relation.manyField ?? relation.field;
2382
+ return manyField.endsWith("_id") ? manyField.slice(0, -3) : oneCollection;
2383
+ }
2384
+ function scalarFor(type) {
2385
+ switch (type) {
2386
+ case "boolean":
2387
+ return "Boolean";
2388
+ case "integer":
2389
+ return "Int";
2390
+ case "float":
2391
+ case "decimal":
2392
+ return "Float";
2393
+ case "bigInteger":
2394
+ return "String";
2395
+ // `datetime` is the canonical FieldType spelling; `dateTime` is legacy (#865).
2396
+ case "datetime":
2397
+ case "dateTime":
2398
+ case "date":
2399
+ case "time":
2400
+ case "timestamp":
2401
+ return "DateTime";
2402
+ case "richtext":
2403
+ return "RichText";
2404
+ case "json":
2405
+ case "csv":
2406
+ case "geometry":
2407
+ case "files":
2408
+ case "m2o":
2409
+ case "o2m":
2410
+ case "m2m":
2411
+ case "m2a":
2412
+ return "JSON";
2413
+ default:
2414
+ return "String";
2415
+ }
2416
+ }
2417
+ function pascalCase(name) {
2418
+ return name.split("_").filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
2419
+ }
2420
+ function objectType(name, fields) {
2421
+ return `type ${name} {
2422
+ ${fields.map((field) => ` ${field}`).join("\n")}
2423
+ }`;
2424
+ }
2425
+
2426
+ // src/typegen/openapi.ts
2427
+ function generateOpenApi(manifest, options = {}) {
2428
+ const byName = new Map(manifest.collections.map((collection) => [collection.name, collection]));
2429
+ const bases = /* @__PURE__ */ new Map();
2430
+ const taken = /* @__PURE__ */ new Set();
2431
+ for (const collection of manifest.collections) {
2432
+ const raw = collection.name.replace(/[^a-zA-Z0-9._-]/g, "_");
2433
+ let base = raw;
2434
+ for (let n = 2; taken.has(base); n += 1) base = `${raw}_${n}`;
2435
+ taken.add(base);
2436
+ bases.set(collection.name, base);
2437
+ }
2438
+ const ctx = {
2439
+ primaryKeySchema: (name) => hasIntegerPrimaryKey(byName.get(name)) ? { type: "integer" } : { type: "string" },
2440
+ projectionRef: (name) => {
2441
+ const base = bases.get(name);
2442
+ return base ? `#/components/schemas/${base}.Projection` : null;
2443
+ }
2444
+ };
2445
+ const schemas = {
2446
+ ErrorObject: {
2447
+ type: "object",
2448
+ properties: { code: { type: "string" }, message: { type: "string" } },
2449
+ required: ["code"]
2450
+ },
2451
+ ErrorResponse: {
2452
+ type: "object",
2453
+ properties: { errors: { type: "array", items: { $ref: "#/components/schemas/ErrorObject" } } },
2454
+ required: ["errors"]
2455
+ },
2456
+ PaginationMeta: {
2457
+ type: "object",
2458
+ properties: {
2459
+ total: { type: "integer", minimum: 0, description: "Omitted when the request passed `meta=none`." },
2460
+ limit: { type: "integer", minimum: 1, maximum: 200 },
2461
+ offset: { type: "integer", minimum: 0 }
2462
+ },
2463
+ required: ["limit", "offset"]
2464
+ }
2465
+ };
2466
+ for (const collection of manifest.collections) {
2467
+ addCollectionSchemas(schemas, collection, bases.get(collection.name), ctx);
2468
+ }
2469
+ return {
2470
+ openapi: "3.1.0",
2471
+ info: {
2472
+ title: options.title ?? "LumiBase content schemas",
2473
+ version: options.version ?? `manifest-v${manifest.version}`,
2474
+ description: "Component schemas generated by `lumibase types` from the typegen manifest. For paths and a per-caller view, use the live document at /api/v1/openapi.json."
2475
+ },
2476
+ components: { schemas }
2477
+ };
2478
+ }
2479
+ var timestamp = { type: "string", format: "date-time" };
2480
+ var nullableTimestamp = { type: ["string", "null"], format: "date-time" };
2481
+ var nullableString = { type: ["string", "null"] };
2482
+ var expandedObject = {
2483
+ type: "object",
2484
+ description: "Expanded record (requested with `fields=<name>.*`)."
2485
+ };
2486
+ var fileId = { type: "string", description: "File id (`/api/v1/files/{id}`)." };
2487
+ var FIELD_TYPE_JSON_SCHEMA = {
2488
+ string: { type: "string" },
2489
+ text: { type: "string" },
2490
+ hash: { type: "string" },
2491
+ csv: { type: "string" },
2492
+ integer: { type: "integer" },
2493
+ bigInteger: { type: "integer", format: "int64" },
2494
+ decimal: { type: "number" },
2495
+ float: { type: "number" },
2496
+ boolean: { type: "boolean" },
2497
+ json: {},
2498
+ uuid: { type: "string", format: "uuid" },
2499
+ date: { type: "string", format: "date" },
2500
+ datetime: { type: "string", format: "date-time" },
2501
+ dateTime: { type: "string", format: "date-time" },
2502
+ time: { type: "string", format: "time" },
2503
+ timestamp: { type: "string", format: "date-time" },
2504
+ geometry: { type: "object", additionalProperties: true, description: "GeoJSON geometry object." },
2505
+ richtext: {
2506
+ type: "object",
2507
+ required: ["type", "version", "content"],
2508
+ properties: {
2509
+ type: { type: "string", enum: ["doc"] },
2510
+ version: { type: "integer", enum: [1] },
2511
+ content: { type: "array", items: { type: "object", additionalProperties: true } }
2512
+ },
2513
+ description: "Portable rich-text document (see the RichTextDocument type)."
2514
+ }
2515
+ };
2516
+ function withNull(schema) {
2517
+ if (Object.keys(schema).length === 0) return schema;
2518
+ const type = schema["type"];
2519
+ if (typeof type === "string" && !("enum" in schema)) return { ...schema, type: [type, "null"] };
2520
+ if (typeof type === "string" && Array.isArray(schema["enum"])) {
2521
+ return { ...schema, type: [type, "null"], enum: [...schema["enum"], null] };
2522
+ }
2523
+ return { anyOf: [schema, { type: "null" }] };
2524
+ }
2525
+ function referenceOrId(target, ctx, shape) {
2526
+ const id = ctx.primaryKeySchema(target);
2527
+ if (shape !== "projection") return id;
2528
+ const ref = ctx.projectionRef(target);
2529
+ return ref ? { anyOf: [id, { $ref: ref }] } : { anyOf: [id, expandedObject] };
2530
+ }
2531
+ function fieldSchema(field, collection, ctx, shape) {
2532
+ const relation = relationsOf(collection).find((candidate) => candidate.field === field.name);
2533
+ const kind = fieldShape(field);
2534
+ let schema;
2535
+ if (field.kind === "m2o" && field.target) {
2536
+ schema = referenceOrId(field.target, ctx, shape);
2537
+ } else if (kind.kind === "to-many" || relation && (relation.kind === "o2m" || relation.kind === "m2m")) {
2538
+ const target = kind.kind === "to-many" ? kind.target : relation?.target;
2539
+ schema = { type: "array", items: referenceOrId(target, ctx, shape) };
2540
+ } else if (kind.kind === "m2a" || relation?.kind === "m2a") {
2541
+ schema = {
2542
+ type: "array",
2543
+ items: {
2544
+ type: "object",
2545
+ properties: { collection: { type: "string" }, item: {} },
2546
+ required: ["collection", "item"]
2547
+ }
2548
+ };
2549
+ } else if (kind.kind === "localized") {
2550
+ schema = {
2551
+ type: "object",
2552
+ description: 'Per-locale values keyed by locale code (e.g. `{ "en": "\u2026", "vi": "\u2026" }`).',
2553
+ additionalProperties: { type: "string" }
2554
+ };
2555
+ } else if (kind.kind === "file") {
2556
+ schema = shape === "projection" ? { anyOf: [fileId, expandedObject] } : fileId;
2557
+ } else if (kind.kind === "files") {
2558
+ schema = { type: "array", items: shape === "projection" ? { anyOf: [fileId, expandedObject] } : fileId };
2559
+ } else if (field.type === "alias") {
2560
+ return null;
2561
+ } else if (kind.kind === "enum") {
2562
+ schema = { type: "string", enum: [...new Set(kind.values)] };
2563
+ } else {
2564
+ schema = { ...FIELD_TYPE_JSON_SCHEMA[field.type] ?? {} };
2565
+ }
2566
+ if (field.encrypted && shape !== "input") {
2567
+ schema = { anyOf: [schema, { const: "***", description: "Masked: caller lacks `read_decrypted`." }] };
2568
+ }
2569
+ if (isNullable(field)) schema = withNull(schema);
2570
+ if (field.readonly && shape !== "input") schema = { ...schema, readOnly: true };
2571
+ return schema;
2572
+ }
2573
+ function addCollectionSchemas(schemas, collection, base, ctx) {
2574
+ const userFields = collection.fields.filter((field) => !field.system);
2575
+ const ref = (suffix) => ({ $ref: `#/components/schemas/${base}.${suffix}` });
2576
+ const fieldProps = {};
2577
+ const projectionProps = {
2578
+ id: { ...ctx.primaryKeySchema(collection.name), readOnly: true },
2579
+ status: { type: "string" },
2580
+ sort: { type: "integer" },
2581
+ user_created: nullableString,
2582
+ user_updated: nullableString,
2583
+ created_at: timestamp,
2584
+ updated_at: timestamp
2585
+ };
2586
+ const required = [];
2587
+ for (const field of userFields) {
2588
+ const item = fieldSchema(field, collection, ctx, "item");
2589
+ const projection = fieldSchema(field, collection, ctx, "projection");
2590
+ if (item) {
2591
+ fieldProps[field.name] = item;
2592
+ if (field.required) required.push(field.name);
2593
+ }
2594
+ if (projection) projectionProps[field.name] = projection;
2595
+ }
2596
+ schemas[`${base}.Fields`] = {
2597
+ type: "object",
2598
+ description: `User fields of \`${collection.name}\`.`,
2599
+ properties: fieldProps,
2600
+ ...required.length > 0 ? { required } : {}
2601
+ };
2602
+ schemas[`${base}.Item`] = {
2603
+ type: "object",
2604
+ properties: {
2605
+ id: { ...ctx.primaryKeySchema(collection.name), readOnly: true },
2606
+ status: { type: "string", description: "`draft`, `published`, `archived`, or a custom workflow value." },
2607
+ sort: { type: "integer" },
2608
+ data: ref("Fields"),
2609
+ publishAt: nullableTimestamp,
2610
+ unpublishAt: nullableTimestamp,
2611
+ userCreated: nullableString,
2612
+ userUpdated: nullableString,
2613
+ createdAt: { ...timestamp, readOnly: true },
2614
+ updatedAt: { ...timestamp, readOnly: true }
2615
+ },
2616
+ required: ["id", "status", "data"]
2617
+ };
2618
+ schemas[`${base}.Projection`] = {
2619
+ type: "object",
2620
+ description: "Flat shape returned when the request passes `fields=`; only requested keys are present.",
2621
+ properties: projectionProps
2622
+ };
2623
+ const inputSchema = (withRequired) => {
2624
+ const props = {};
2625
+ const req = [];
2626
+ for (const field of userFields) {
2627
+ if (field.readonly || field.generated) continue;
2628
+ const schema = fieldSchema(field, collection, ctx, "input");
2629
+ if (!schema) continue;
2630
+ props[field.name] = schema;
2631
+ if (withRequired && field.required) req.push(field.name);
2632
+ }
2633
+ return {
2634
+ type: "object",
2635
+ properties: {
2636
+ data: { type: "object", properties: props, ...req.length > 0 ? { required: req } : {} },
2637
+ status: { type: "string" },
2638
+ sort: { type: "integer" },
2639
+ publishAt: nullableTimestamp,
2640
+ unpublishAt: nullableTimestamp
2641
+ },
2642
+ ...withRequired ? { required: ["data"] } : {}
2643
+ };
2644
+ };
2645
+ schemas[`${base}.CreateInput`] = inputSchema(true);
2646
+ schemas[`${base}.UpdateInput`] = inputSchema(false);
2647
+ const itemOrProjection = { anyOf: [ref("Item"), ref("Projection")] };
2648
+ schemas[`${base}.Response`] = {
2649
+ type: "object",
2650
+ description: "Single-item envelope.",
2651
+ properties: { data: itemOrProjection },
2652
+ required: ["data"]
2653
+ };
2654
+ schemas[`${base}.ListResponse`] = {
2655
+ type: "object",
2656
+ description: "A page of items.",
2657
+ properties: {
2658
+ data: { type: "array", items: itemOrProjection },
2659
+ meta: { $ref: "#/components/schemas/PaginationMeta" }
2660
+ },
2661
+ required: ["data"]
2662
+ };
2663
+ }
2664
+
1800
2665
  // src/typegen/index.ts
1801
2666
  var DEFAULT_IMPORT_SOURCE = "@lumibase/sdk";
1802
2667
  function generateTypes(manifest, options = {}) {
@@ -1807,71 +2672,112 @@ function generateTypes(manifest, options = {}) {
1807
2672
  return generatePerCollection(manifest, branded, importSource);
1808
2673
  }
1809
2674
  function generateSingleFile(manifest, branded, importSource) {
2675
+ const known = new Set(manifest.collections.map((c) => c.name));
1810
2676
  const imports = [
1811
2677
  `import type { ID, Locale } from '${importSource}';`,
1812
2678
  branded ? `import type { Brand } from '${importSource}';` : ""
1813
2679
  ].filter(Boolean).join("\n");
1814
2680
  const collectionInterfaces = manifest.collections.map((coll) => {
1815
- const base = generateCollectionInterface(coll, branded);
2681
+ const base = generateCollectionInterface(coll, branded, known);
1816
2682
  const expanded = generateExpandedType(coll);
1817
2683
  return [base, expanded].filter(Boolean).join("\n\n");
1818
2684
  }).join("\n\n");
2685
+ const blockTypes = generateBlockTypes(manifest, branded, known);
2686
+ const richText = manifest.collections.some((c) => c.fields.some((f) => f.type === "richtext")) ? RICHTEXT_TS_DECLARATIONS : "";
1819
2687
  const collectionsMap = `export interface LumibaseCollections {
1820
- ${manifest.collections.map((c) => ` ${c.name}: ${capitalize(c.name)};`).join("\n")}
2688
+ ${manifest.collections.map((c) => ` ${c.name}: ${capitalize2(c.name)};`).join("\n")}
1821
2689
  }`;
1822
2690
  const schemaType = "export type LumibaseSchema = LumibaseCollections;";
2691
+ const body = [richText, collectionInterfaces, blockTypes, collectionsMap, schemaType].filter(Boolean).join("\n\n");
1823
2692
  return `${imports}
1824
2693
 
1825
- ${collectionInterfaces}
1826
-
1827
- ${collectionsMap}
1828
-
1829
- ${schemaType}`;
2694
+ ${body}`;
1830
2695
  }
1831
2696
  function generatePerCollection(manifest, branded, importSource) {
1832
2697
  return generateSingleFile(manifest, branded, importSource);
1833
2698
  }
1834
- function generateCollectionInterface(coll, branded) {
2699
+ function generateCollectionInterface(coll, branded, known) {
1835
2700
  const fields = coll.fields.map((f) => {
1836
- const tsType = mapFieldTypeToTs(f, coll, branded);
2701
+ const tsType = mapFieldTypeToTs(f, coll, branded, known);
1837
2702
  const optional = f.required ? "" : "?";
1838
2703
  const readonly = f.readonly || f.generated ? "readonly " : "";
1839
2704
  return ` ${readonly}${f.name}${optional}: ${tsType};`;
1840
2705
  }).join("\n");
1841
- return `export interface ${capitalize(coll.name)} {
2706
+ return `export interface ${capitalize2(coll.name)} {
1842
2707
  ${fields}
1843
2708
  }`;
1844
2709
  }
1845
2710
  function generateExpandedType(coll) {
1846
2711
  const relations = coll.relations ?? [];
1847
2712
  if (relations.length === 0) {
1848
- return `export type ${capitalize(coll.name)}Expanded = ${capitalize(coll.name)};`;
2713
+ return `export type ${capitalize2(coll.name)}Expanded = ${capitalize2(coll.name)};`;
1849
2714
  }
1850
2715
  const omittedKeys = relations.map((relation) => quoteProperty(relation.field)).join(" | ");
1851
2716
  const fields = relations.map((relation) => ` ${relation.field}?: ${expandedRelationType(relation)};`).join("\n");
1852
- return `export type ${capitalize(coll.name)}Expanded = Omit<${capitalize(coll.name)}, ${omittedKeys}> & {
2717
+ return `export type ${capitalize2(coll.name)}Expanded = Omit<${capitalize2(coll.name)}, ${omittedKeys}> & {
1853
2718
  ${fields}
1854
2719
  };`;
1855
2720
  }
1856
2721
  function expandedRelationType(relation) {
1857
2722
  if (relation.kind === "m2o") {
1858
- return `${capitalize(relation.target)} | ${capitalize(relation.target)}Expanded | null`;
2723
+ return `${capitalize2(relation.target)} | ${capitalize2(relation.target)}Expanded | null`;
1859
2724
  }
1860
2725
  if (relation.kind === "o2m" || relation.kind === "m2m") {
1861
- return `Array<${capitalize(relation.target)} | ${capitalize(relation.target)}Expanded>`;
2726
+ return `Array<${capitalize2(relation.target)} | ${capitalize2(relation.target)}Expanded>`;
1862
2727
  }
1863
2728
  return `Array<{ collection: string; item: unknown }>`;
1864
2729
  }
1865
- function mapFieldTypeToTs(field, coll, branded) {
2730
+ function generateBlockTypes(manifest, branded, known) {
2731
+ const byName = new Map(manifest.collections.map((c) => [c.name, c]));
2732
+ const referenced = /* @__PURE__ */ new Set();
2733
+ for (const coll of manifest.collections) {
2734
+ for (const f of coll.fields) {
2735
+ if (f.type === "blocks") for (const t of f.allowedBlocks ?? []) referenced.add(t);
2736
+ }
2737
+ }
2738
+ return [...referenced].filter((name) => byName.has(name)).sort().map((name) => {
2739
+ const coll = byName.get(name);
2740
+ const dataFields = coll.fields.filter((f) => !f.system && !f.primaryKey).map((f) => {
2741
+ const optional = f.required ? "" : "?";
2742
+ return ` ${f.name}${optional}: ${mapFieldTypeToTs(f, coll, branded, known)};`;
2743
+ }).join("\n");
2744
+ const t = capitalize2(name);
2745
+ return `export interface ${t}BlockData {
2746
+ ${dataFields}
2747
+ }
2748
+
2749
+ export interface ${t}Block {
2750
+ id: string;
2751
+ type: ${JSON.stringify(name)};
2752
+ data: ${t}BlockData;
2753
+ }`;
2754
+ }).join("\n\n");
2755
+ }
2756
+ function blocksUnionType(field, isKnown) {
2757
+ const members = (field.allowedBlocks ?? []).map(
2758
+ (name) => isKnown(name) ? `${capitalize2(name)}Block` : `{ id: string; type: ${JSON.stringify(name)}; data: Record<string, unknown> }`
2759
+ );
2760
+ if (members.length === 0) return "Array<{ id: string; type: string; data: Record<string, unknown> }>";
2761
+ return `Array<${members.join(" | ")}>`;
2762
+ }
2763
+ function mapFieldTypeToTs(field, coll, branded, known = /* @__PURE__ */ new Set()) {
2764
+ if (field.type === "blocks") {
2765
+ return nullable(field, blocksUnionType(field, (name) => known.has(name)));
2766
+ }
1866
2767
  if (field.kind === "m2o") {
1867
2768
  return nullable(field, mapScalarFieldType(field, branded));
1868
2769
  }
1869
2770
  if (field.kind === "o2m" || field.kind === "m2m") {
1870
- return `${capitalize(field.target || "unknown")}[]`;
2771
+ return `${capitalize2(field.target || "unknown")}[]`;
1871
2772
  }
1872
2773
  if (field.kind === "m2a") {
1873
2774
  return `Array<{ collection: string; item: unknown }>`;
1874
2775
  }
2776
+ const shape = fieldShape(field);
2777
+ if (shape.kind === "localized" || shape.kind === "file" || shape.kind === "files") {
2778
+ const wire = shape.kind === "localized" ? "Partial<Record<Locale, string>>" : shape.kind === "file" ? "string" : "string[]";
2779
+ return nullable(field, field.encrypted ? `${wire} | '***'` : wire);
2780
+ }
1875
2781
  if (field.enum && field.enum.length > 0) {
1876
2782
  return nullable(field, field.enum.map((v) => JSON.stringify(v)).join(" | "));
1877
2783
  }
@@ -1884,7 +2790,9 @@ function mapFieldTypeToTs(field, coll, branded) {
1884
2790
  const tsType = mapScalarFieldType(field, branded);
1885
2791
  return nullable(field, field.encrypted ? `${tsType} | '***'` : tsType);
1886
2792
  }
2793
+ var ZONED_DATETIME_TS = "{ instant: string; tz: string; offset: string }";
1887
2794
  function mapScalarFieldType(field, branded) {
2795
+ if (field.timezone) return ZONED_DATETIME_TS;
1888
2796
  const typeMap = {
1889
2797
  string: "string",
1890
2798
  text: "string",
@@ -1893,14 +2801,18 @@ function mapScalarFieldType(field, branded) {
1893
2801
  integer: "number",
1894
2802
  bigInteger: "number",
1895
2803
  decimal: "number",
2804
+ float: "number",
1896
2805
  boolean: "boolean",
1897
2806
  json: "unknown",
1898
2807
  uuid: mapPrimaryKeyType("uuid", branded, field.branded),
1899
2808
  date: "string",
1900
2809
  datetime: "string",
2810
+ dateTime: "string",
1901
2811
  time: "string",
1902
2812
  timestamp: "string",
1903
- geometry: "GeoJSON.Geometry"
2813
+ geometry: "GeoJSON.Geometry",
2814
+ geopoint: "{ lat: number; lng: number }",
2815
+ richtext: "RichTextDocument"
1904
2816
  };
1905
2817
  return typeMap[field.type] || "unknown";
1906
2818
  }
@@ -1915,7 +2827,7 @@ function mapPrimaryKeyType(primaryKeyType, branded, brand) {
1915
2827
  if (branded) return `Brand<'${brand || "ID"}', string>`;
1916
2828
  return "ID";
1917
2829
  }
1918
- function capitalize(str) {
2830
+ function capitalize2(str) {
1919
2831
  return str.charAt(0).toUpperCase() + str.slice(1);
1920
2832
  }
1921
2833
  function quoteProperty(name) {
@@ -1948,8 +2860,12 @@ export {
1948
2860
  AudienceClient,
1949
2861
  DECISION_ERROR_CODES,
1950
2862
  DEFAULT_IMPORT_SOURCE,
2863
+ DEFAULT_ZOD_IMPORT,
2864
+ FILES_INTERFACE,
2865
+ FILE_INTERFACE,
1951
2866
  LumiError,
1952
2867
  RealtimeClient,
2868
+ TRANSLATABLE_INTERFACE,
1953
2869
  ackCdcSubscription,
1954
2870
  checkCdcPipelineHealth,
1955
2871
  createAgentArtifact,
@@ -1970,8 +2886,12 @@ export {
1970
2886
  evaluateAgentArtifact,
1971
2887
  exportAccessManifest,
1972
2888
  extractSeo,
2889
+ filterManifest,
1973
2890
  generateAgentApp,
2891
+ generateGraphQLSdl,
2892
+ generateOpenApi,
1974
2893
  generateTypes,
2894
+ generateZod,
1975
2895
  getEffectivePreset,
1976
2896
  getReview,
1977
2897
  getReviewProfile,
@@ -2000,7 +2920,9 @@ export {
2000
2920
  readCdcSubscription,
2001
2921
  readItem,
2002
2922
  readItems,
2923
+ realtimeHolders,
2003
2924
  replayCdcSubscription,
2925
+ retainRealtime,
2004
2926
  retryAgentRun,
2005
2927
  reviewContentHash,
2006
2928
  reviewDraft,