@columnus/api-cli 0.3.1 → 0.4.0

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 (2) hide show
  1. package/dist/cli.js +194 -17
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -24272,8 +24272,152 @@ function generateClientPullFiles(input2) {
24272
24272
  `
24273
24273
  );
24274
24274
  files.set(".env.example", generateEnvExample(input2.convexUrl));
24275
+ if (input2.consumer?.sdk && accesses.some(editorAccessEnabled)) {
24276
+ files.set("src/generated/cms-hooks.ts", generateCmsHooksTs(readableTables));
24277
+ if (input2.consumer.tanstackStart) {
24278
+ files.set("src/generated/tanstack-start/cms-server.ts", CMS_SERVER_TS);
24279
+ files.set("src/generated/tanstack-start/cms-session.server.ts", CMS_SESSION_SERVER_TS);
24280
+ }
24281
+ }
24275
24282
  return files;
24276
24283
  }
24284
+ function generateCmsHooksTs(tables) {
24285
+ const sorted = [...tables].sort((a, b) => a.name.localeCompare(b.name));
24286
+ const rowHooks = sorted.map((table) => {
24287
+ const doc = docTypeName(table.name);
24288
+ return `
24289
+ export function use${table.name}Rows(options: CmsRowsHookOptions<${doc}> = {}) {
24290
+ const { results, status } = use${table.name}List(options.query);
24291
+ return useCmsRows(${JSON.stringify(table.name)}, { live: results, ssr: options.ssr, status });
24292
+ }`;
24293
+ }).join("\n");
24294
+ const docImports = sorted.map((t) => ` ${docTypeName(t.name)},`).join("\n");
24295
+ const listImports = sorted.map((t) => ` use${t.name}List,`).join("\n");
24296
+ return `${READ_API_BANNER}import { useMemo } from "react";
24297
+ import { mergePreviewAssetUrlMap, useCmsRows, useCmsSsrAssetUrls } from "@columnus/sdk/cms";
24298
+ import type {
24299
+ ${docImports}
24300
+ } from "./documents.js";
24301
+ import {
24302
+ useAssetExpansions,
24303
+ useAssetOriginals,
24304
+ ${listImports}
24305
+ } from "./hooks.js";
24306
+ import type { Query } from "./query.js";
24307
+
24308
+ export type CmsRowsHookOptions<T> = {
24309
+ query?: Query | null;
24310
+ /** Rows the route loader fetched on the server. */
24311
+ ssr?: readonly T[];
24312
+ };
24313
+ ${rowHooks}
24314
+
24315
+ /** Asset id \u2192 URL: the preview rendition, else the original, else the loader's \`CmsSsrAssetUrls\`. */
24316
+ export function useAssetUrls(assetIds: readonly string[]): Map<string, string> {
24317
+ // By value: callers pass a new array each render.
24318
+ const key = JSON.stringify(assetIds);
24319
+ const ids = useMemo(() => [...new Set((JSON.parse(key) as string[]).filter(Boolean))], [key]);
24320
+ const expansions = useAssetExpansions(ids);
24321
+ const originals = useAssetOriginals(ids);
24322
+ const ssr = useCmsSsrAssetUrls();
24323
+ return useMemo(
24324
+ () => mergePreviewAssetUrlMap(ids, expansions, originals, ssr),
24325
+ [ids, expansions, originals, ssr],
24326
+ );
24327
+ }
24328
+ `;
24329
+ }
24330
+ var CMS_SERVER_TS = `${READ_API_BANNER}// \`createServerFn\` must stay at module top level under \`src/\` for the Start
24331
+ // plugin to compile it. The cookie helpers load from cms-session.server.ts inside
24332
+ // the handlers, so @tanstack/react-start/server stays out of the client graph.
24333
+ // These POST functions rely on the site's CSRF protection: keep
24334
+ // \`createCsrfMiddleware\` (or an origin check) installed in \`src/start.ts\`.
24335
+ import { createServerFn, createServerOnlyFn } from "@tanstack/react-start";
24336
+ import { parseLoginInput, type EditorSession } from "@columnus/sdk/cms/server";
24337
+
24338
+ export type CmsEditorSessionDto = EditorSession | null;
24339
+
24340
+ const session = () => import("./cms-session.server");
24341
+
24342
+ /** In-process cookie \u2192 editor session for route loaders (SSR). */
24343
+ export const resolveEditorSession = createServerOnlyFn(
24344
+ async (): Promise<CmsEditorSessionDto> => (await session()).resolveEditorSession(),
24345
+ );
24346
+
24347
+ export const getEditorSession = createServerFn({ method: "GET" }).handler(
24348
+ async (): Promise<CmsEditorSessionDto> => (await session()).resolveEditorSession(),
24349
+ );
24350
+
24351
+ export const sendLoginCode = createServerFn({ method: "POST" })
24352
+ .validator(parseLoginInput)
24353
+ .handler(async ({ data }) => {
24354
+ await (await session()).sendLoginCode(data.email);
24355
+ return { ok: true as const };
24356
+ });
24357
+
24358
+ /** Sets the session cookie; returns the user only, never the session token. */
24359
+ export const verifyLoginCode = createServerFn({ method: "POST" })
24360
+ .validator(parseLoginInput)
24361
+ .handler(async ({ data }) => (await session()).verifyLoginCode(data.email, data.otp));
24362
+
24363
+ export const signOut = createServerFn({ method: "POST" }).handler(async () => {
24364
+ await (await session()).signOut();
24365
+ return { ok: true as const };
24366
+ });
24367
+
24368
+ /** Convex JWT minted from the session cookie, for the browser's \`setAuth\`. */
24369
+ export const getConvexJwt = createServerFn({ method: "GET" }).handler(
24370
+ async (): Promise<{ token: string | null }> => (await session()).mintConvexJwt(),
24371
+ );
24372
+
24373
+ export const cms = {
24374
+ resolveEditorSession,
24375
+ getEditorSession,
24376
+ sendLoginCode,
24377
+ verifyLoginCode,
24378
+ signOut,
24379
+ getConvexJwt,
24380
+ };
24381
+ `;
24382
+ var CMS_SESSION_SERVER_TS = `${READ_API_BANNER}// Server only: the \`.server.ts\` name lets Start's import protection keep
24383
+ // @tanstack/react-start/server out of the client graph. The session token lives
24384
+ // in the httpOnly cookie and nothing here returns it.
24385
+ import { deleteCookie, getCookie, setCookie } from "@tanstack/react-start/server";
24386
+ import { CMS_SESSION_COOKIE, createCmsSessionApi } from "@columnus/sdk/cms/server";
24387
+
24388
+ const api = createCmsSessionApi({
24389
+ convexUrl: process.env.VITE_CONVEX_URL || import.meta.env.VITE_CONVEX_URL,
24390
+ });
24391
+
24392
+ /** The flags of \`serializeSessionCookie\`; Secure except in local development. */
24393
+ const cookieOptions = {
24394
+ httpOnly: true,
24395
+ path: "/",
24396
+ sameSite: "lax",
24397
+ secure: process.env.NODE_ENV === "production",
24398
+ } as const;
24399
+
24400
+ const sessionToken = () => getCookie(CMS_SESSION_COOKIE) ?? null;
24401
+
24402
+ export const resolveEditorSession = () => api.resolveEditor(sessionToken());
24403
+
24404
+ export const mintConvexJwt = () => api.mintConvexJwt(sessionToken());
24405
+
24406
+ export const sendLoginCode = (email: string) => api.sendLoginCode(email);
24407
+
24408
+ export async function verifyLoginCode(email: string, otp: string | undefined) {
24409
+ const { token, user } = await api.verifyLoginCode(email, otp);
24410
+ setCookie(CMS_SESSION_COOKIE, token, cookieOptions);
24411
+ return { user };
24412
+ }
24413
+
24414
+ /** Clears the cookie first, so a failed revoke still signs this browser out. */
24415
+ export async function signOut() {
24416
+ const token = sessionToken();
24417
+ deleteCookie(CMS_SESSION_COOKIE, cookieOptions);
24418
+ await api.signOut(token);
24419
+ }
24420
+ `;
24277
24421
  function generateProposalApiRefsTs(profileSlug, tables, accesses) {
24278
24422
  const byName = new Map(tables.map((table) => [table.name, table]));
24279
24423
  const refs = [];
@@ -24712,8 +24856,9 @@ export function ${hookName}(id: ${doc}["_id"] | undefined) {
24712
24856
  }).join("\n");
24713
24857
  const docImports = sorted.map((t) => ` ${docTypeName(t.name)},`).join("\n");
24714
24858
  const refImports = sorted.flatMap((t) => [` list${t.name}Ref,`, ` get${t.name}Ref,`]).join("\n");
24715
- return `${READ_API_BANNER}import { usePaginatedQuery, useQuery } from "convex/react";
24716
- import { anyApi } from "convex/server";
24859
+ return `${READ_API_BANNER}import { useMemo } from "react";
24860
+ import { usePaginatedQuery, useQueries, useQuery, type RequestForQueries } from "convex/react";
24861
+ import { anyApi, type FunctionReference } from "convex/server";
24717
24862
  import type { Query } from "./query.js";
24718
24863
  import type {
24719
24864
  ${docImports}
@@ -24726,24 +24871,45 @@ ${listHooks}
24726
24871
 
24727
24872
  ${getHooks}
24728
24873
 
24729
- export function useAssetOriginals(assetIds: string[]) {
24874
+ // Ids per call the Read API accepts (\`apps/columnus/convex/columnus/read/assets.ts\` in Columnus).
24875
+ const MAX_ASSET_ORIGINALS_BATCH = 100;
24876
+ const MAX_ASSET_EXPANSIONS_BATCH = 25;
24877
+ const getAssetOriginalsRef = anyApi.columnus.read.assets.getAssetOriginals;
24878
+ const getAssetExpansionsRef = anyApi.columnus.read.assets.getAssetExpansions;
24879
+ // Rows stay \`any\`, as a single \`useQuery\` on an \`anyApi\` reference returns them.
24880
+ const NO_ROWS: any[] = [];
24881
+
24882
+ /** One query per batch of ids; every batch's rows in id order once all have loaded, else none. */
24883
+ function useAssetBatches(query: FunctionReference<"query">, assetIds: string[], size: number) {
24730
24884
  const apiToken = readApiToken();
24731
- const ids = assetIds.filter(Boolean);
24732
- const results = useQuery(
24733
- anyApi.columnus.read.assets.getAssetOriginals,
24734
- ids.length > 0 ? { apiToken, assetIds: ids } : "skip",
24735
- );
24736
- return results ?? [];
24885
+ const key = JSON.stringify(assetIds.filter(Boolean));
24886
+ const queries = useMemo(() => {
24887
+ const ids: string[] = JSON.parse(key);
24888
+ const batches: RequestForQueries = {};
24889
+ for (let i = 0; i < ids.length; i += size) {
24890
+ batches[i] = { query, args: { apiToken, assetIds: ids.slice(i, i + size) } };
24891
+ }
24892
+ return batches;
24893
+ }, [query, apiToken, key, size]);
24894
+ const results = useQueries(queries);
24895
+ return useMemo(() => {
24896
+ const rows: any[] = [];
24897
+ for (const batch of Object.keys(queries)) {
24898
+ const result = results[batch];
24899
+ if (result instanceof Error) throw result;
24900
+ if (result === undefined) return NO_ROWS;
24901
+ rows.push(...result);
24902
+ }
24903
+ return rows;
24904
+ }, [queries, results]);
24905
+ }
24906
+
24907
+ export function useAssetOriginals(assetIds: string[]) {
24908
+ return useAssetBatches(getAssetOriginalsRef, assetIds, MAX_ASSET_ORIGINALS_BATCH);
24737
24909
  }
24738
24910
 
24739
24911
  export function useAssetExpansions(assetIds: string[]) {
24740
- const apiToken = readApiToken();
24741
- const ids = assetIds.filter(Boolean);
24742
- const results = useQuery(
24743
- anyApi.columnus.read.assets.getAssetExpansions,
24744
- ids.length > 0 ? { apiToken, assetIds: ids } : "skip",
24745
- );
24746
- return results ?? [];
24912
+ return useAssetBatches(getAssetExpansionsRef, assetIds, MAX_ASSET_EXPANSIONS_BATCH);
24747
24913
  }
24748
24914
  `;
24749
24915
  }
@@ -25060,6 +25226,16 @@ async function syncPullEnvLocal(target, convexUrl, token) {
25060
25226
  }
25061
25227
 
25062
25228
  // src/pull.ts
25229
+ async function readConsumer(target) {
25230
+ let manifest = {};
25231
+ try {
25232
+ manifest = JSON.parse(await fs.readFile(path3.join(target, "package.json"), "utf8"));
25233
+ } catch (error62) {
25234
+ if (error62.code !== "ENOENT") throw error62;
25235
+ }
25236
+ const lists = (name) => Object.hasOwn(manifest.dependencies ?? {}, name) || Object.hasOwn(manifest.devDependencies ?? {}, name);
25237
+ return { sdk: lists("@columnus/sdk"), tanstackStart: lists("@tanstack/react-start") };
25238
+ }
25063
25239
  async function pullReadApi(config2) {
25064
25240
  if (!isApiTokenFormat(config2.token)) {
25065
25241
  throw new Error("Token must start with col_ (see Columnus /api \u2192 Create token)");
@@ -25071,7 +25247,8 @@ async function pullReadApi(config2) {
25071
25247
  apiVersion: introspect.apiVersion,
25072
25248
  manifestHash: introspect.manifestHash,
25073
25249
  tables: introspect.tables,
25074
- tableAccess: introspect.tableAccess
25250
+ tableAccess: introspect.tableAccess,
25251
+ consumer: await readConsumer(config2.target)
25075
25252
  });
25076
25253
  const filesWritten = [];
25077
25254
  for (const [relPath, contents] of files) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@columnus/api-cli",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "columnus-api pull and dev — live-sync read API codegen for Columnus consumer apps",