@zenstackhq/cli 3.9.0-beta.1 → 3.9.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.
package/dist/index.mjs CHANGED
@@ -29,9 +29,10 @@ import { PostgresDialect } from "@zenstackhq/orm/dialects/postgres";
29
29
  import { SqliteDialect } from "@zenstackhq/orm/dialects/sqlite";
30
30
  import { PolicyPlugin } from "@zenstackhq/plugin-policy";
31
31
  import { RPCApiHandler } from "@zenstackhq/server/api";
32
- import { ZenStackMiddleware } from "@zenstackhq/server/express";
33
- import cors from "cors";
34
- import express from "express";
32
+ import { createHonoHandler } from "@zenstackhq/server/hono";
33
+ import { serve } from "@hono/node-server";
34
+ import { Hono } from "hono";
35
+ import { cors } from "hono/cors";
35
36
  import "mixpanel";
36
37
  import * as os$1 from "os";
37
38
  import process$1, { env } from "node:process";
@@ -270,6 +271,32 @@ function startUsageTipsFetch() {
270
271
  }
271
272
  };
272
273
  }
274
+ function isPackageInstalled(pkgName) {
275
+ try {
276
+ createRequire(path.resolve(process.cwd(), "package.json")).resolve(pkgName);
277
+ return true;
278
+ } catch {
279
+ return false;
280
+ }
281
+ }
282
+ async function loadPackage(pkgName) {
283
+ try {
284
+ return await import(pkgName);
285
+ } catch (importErr) {
286
+ let projectRequire;
287
+ try {
288
+ projectRequire = createRequire(path.resolve(process.cwd(), "package.json"));
289
+ return await import(pathToFileURL(projectRequire.resolve(pkgName)).href);
290
+ } catch (resolvedImportErr) {
291
+ try {
292
+ return projectRequire(pkgName);
293
+ } catch (requireErr) {
294
+ if (process.env["DEBUG"]) console.error(importErr, resolvedImportErr, requireErr);
295
+ return null;
296
+ }
297
+ }
298
+ }
299
+ }
273
300
  //#endregion
274
301
  //#region src/actions/check.ts
275
302
  /**
@@ -926,7 +953,9 @@ const mysql = {
926
953
  }
927
954
  },
928
955
  async introspect(connectionString, options) {
929
- const connection = await (await import("mysql2/promise")).createConnection(connectionString);
956
+ const mod = await loadPackage("mysql2/promise");
957
+ if (!mod) throw new CliError("Package \"mysql2\" is required for MySQL support. Please install it with: npm install mysql2");
958
+ const connection = await (mod.createConnection ? mod : mod.default ?? mod).createConnection(connectionString);
930
959
  try {
931
960
  const databaseName = new URL(connectionString).pathname.replace("/", "");
932
961
  if (!databaseName) throw new CliError("Database name not found in connection string");
@@ -1424,8 +1453,10 @@ const postgresql = {
1424
1453
  }
1425
1454
  },
1426
1455
  async introspect(connectionString, options) {
1427
- const { Client } = await import("pg");
1428
- const client = new Client({ connectionString });
1456
+ const pg = await loadPackage("pg");
1457
+ const ClientClass = pg?.Client || pg?.default?.Client;
1458
+ if (!ClientClass) throw new CliError("Package \"pg\" is required for PostgreSQL support. Please install it with: npm install pg");
1459
+ const client = new ClientClass({ connectionString });
1429
1460
  await client.connect();
1430
1461
  try {
1431
1462
  const { rows: tables } = await client.query(tableIntrospectionQuery);
@@ -1951,7 +1982,9 @@ const sqlite = {
1951
1982
  },
1952
1983
  getDefaultDatabaseType() {},
1953
1984
  async introspect(connectionString, _options) {
1954
- const SQLite = (await import("better-sqlite3")).default;
1985
+ const mod = await loadPackage("better-sqlite3");
1986
+ const SQLite = mod?.default || mod;
1987
+ if (!SQLite) throw new CliError("Package \"better-sqlite3\" is required for SQLite support. Please install it with: npm install better-sqlite3");
1955
1988
  const db = new SQLite(connectionString, { readonly: true });
1956
1989
  try {
1957
1990
  const all = (sql) => {
@@ -2213,9 +2246,21 @@ async function runPull(options) {
2213
2246
  returnServices: true,
2214
2247
  mergeImports: treatAsFile
2215
2248
  });
2216
- const SUPPORTED_PROVIDERS = Object.keys(providers);
2217
- const datasource = getDatasource(model);
2218
- if (!SUPPORTED_PROVIDERS.includes(datasource.provider)) throw new CliError(`Unsupported datasource provider: ${datasource.provider}`);
2249
+ let datasource;
2250
+ if (options.provider && options.databaseUrl) {
2251
+ let databaseUrl = options.databaseUrl;
2252
+ if (options.provider === "sqlite" && databaseUrl.startsWith("file:")) {
2253
+ databaseUrl = new URL(databaseUrl, `file:${model.$document.uri.path}`).pathname;
2254
+ if (process.platform === "win32" && databaseUrl[0] === "/") databaseUrl = databaseUrl.slice(1);
2255
+ }
2256
+ datasource = {
2257
+ provider: options.provider,
2258
+ url: databaseUrl,
2259
+ defaultSchema: "public",
2260
+ allSchemas: ["public"]
2261
+ };
2262
+ } else datasource = getDatasource(model);
2263
+ if (!Object.keys(providers).includes(datasource.provider)) throw new CliError(`Unsupported datasource provider: ${datasource.provider}`);
2219
2264
  const provider = providers[datasource.provider];
2220
2265
  if (!provider) throw new CliError(`No introspection provider found for: ${datasource.provider}`);
2221
2266
  spinner.start("Introspecting database...");
@@ -2255,16 +2300,17 @@ async function runPull(options) {
2255
2300
  });
2256
2301
  resolvedRelations.push(...relations);
2257
2302
  }
2303
+ const schemasMatch = (a, b) => (a ?? "") === (b ?? "");
2258
2304
  for (const relation of resolvedRelations) {
2259
2305
  const similarRelations = resolvedRelations.filter((rr) => {
2260
- return rr !== relation && (rr.schema === relation.schema && rr.table === relation.table && rr.references.schema === relation.references.schema && rr.references.table === relation.references.table || rr.schema === relation.references.schema && rr.columns[0] === relation.references.columns[0] && rr.references.schema === relation.schema && rr.references.table === relation.table);
2306
+ return rr !== relation && (schemasMatch(rr.schema, relation.schema) && rr.table === relation.table && schemasMatch(rr.references.schema, relation.references.schema) && rr.references.table === relation.references.table || schemasMatch(rr.schema, relation.references.schema) && rr.table === relation.references.table && schemasMatch(rr.references.schema, relation.schema) && rr.references.table === relation.table);
2261
2307
  }).length;
2262
2308
  syncRelation({
2263
2309
  model: newModel,
2264
2310
  relation,
2265
2311
  services,
2266
2312
  options,
2267
- selfRelation: relation.references.schema === relation.schema && relation.references.table === relation.table,
2313
+ selfRelation: schemasMatch(relation.references.schema, relation.schema) && relation.references.table === relation.table,
2268
2314
  similarRelations
2269
2315
  });
2270
2316
  }
@@ -3034,10 +3080,17 @@ function getVersion() {
3034
3080
  async function checkNewVersion() {
3035
3081
  const currVersion = getVersion();
3036
3082
  let latestVersion;
3083
+ let timer;
3037
3084
  try {
3038
- latestVersion = await getLatestVersion();
3085
+ const fetchPromise = getLatestVersion();
3086
+ fetchPromise.catch(() => {});
3087
+ latestVersion = await Promise.race([fetchPromise, new Promise((_, reject) => {
3088
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error("version check timed out")), CHECK_VERSION_TIMEOUT + 1e3);
3089
+ })]);
3039
3090
  } catch {
3040
3091
  return;
3092
+ } finally {
3093
+ clearTimeout(timer);
3041
3094
  }
3042
3095
  if (latestVersion && currVersion && semver.gt(latestVersion, currVersion)) console.log(`A newer version ${colors.cyan(latestVersion)} is available.`);
3043
3096
  }
@@ -3059,24 +3112,16 @@ const ProxyAuthError = {
3059
3112
  INVALID_TIMESTAMP: "Request timestamp is expired or invalid",
3060
3113
  INVALID_SIGNATURE_FORMAT: "Invalid x-zenstack-signature format"
3061
3114
  };
3062
- function rejectAuth(res, code) {
3063
- return res.status(401).json({
3115
+ function rejectAuth(c, code) {
3116
+ return c.json({
3064
3117
  code,
3065
3118
  message: ProxyAuthError[code]
3066
- });
3119
+ }, 401);
3067
3120
  }
3068
- /**
3069
- * Represents the identity claim embedded in the Authorization header.
3070
- * The bearer token is a plain base64-encoded JSON string.
3071
- */
3072
3121
  const UserClaimSchema = z.discriminatedUnion("type", [z.object({ type: z.literal("superUser") }), z.object({
3073
3122
  type: z.literal("user"),
3074
3123
  data: z.record(z.string(), z.unknown())
3075
3124
  })]);
3076
- /**
3077
- * Accepts a public key in either PEM format or as a raw base64 / base64url DER string
3078
- * (without the `-----BEGIN PUBLIC KEY-----` markers) and always returns a PEM string.
3079
- */
3080
3125
  function normalizePublicKey(key) {
3081
3126
  key = key.trim();
3082
3127
  if (key.startsWith("-----BEGIN PUBLIC KEY-----")) return key;
@@ -3087,21 +3132,21 @@ async function run(options) {
3087
3132
  ...options,
3088
3133
  studioAuthKey: options.studioAuthKey ?? process.env["ZENSTACK_STUDIO_AUTH_KEY"]
3089
3134
  };
3090
- if (!options.studioAuthKey) console.warn(colors.yellow("Warning: This proxy has no authentication. Do not expose it to the public network.\nTo secure it, get an API key from ZenStack Studio and set it via the ZENSTACK_STUDIO_AUTH_KEY environment variable."));
3091
3135
  const allowedLogLevels = ["error", "query"];
3092
3136
  const log = options.logLevel?.filter((level) => allowedLogLevels.includes(level));
3093
- const schemaFile = getSchemaFile(options.schema);
3137
+ const schemaFile = await resolveSchema(options);
3094
3138
  console.log(colors.gray(`Loading ZModel schema from: ${schemaFile}`));
3095
3139
  let outputPath = getOutputPath(options, schemaFile);
3096
3140
  if (!path.isAbsolute(outputPath)) outputPath = path.resolve(process.cwd(), outputPath);
3097
- const dataSource = (await loadSchemaDocument(schemaFile)).declarations.find(isDataSource);
3141
+ const model = await loadSchemaDocument(schemaFile);
3142
+ const dataSource = model.declarations.find(isDataSource);
3098
3143
  let databaseUrl = options.databaseUrl;
3099
3144
  if (!databaseUrl) {
3100
3145
  const schemaUrl = dataSource?.fields.find((f) => f.name === "url")?.value;
3101
3146
  if (!schemaUrl) throw new CliError(`The schema's "datasource" does not have a "url" field, please provide it with -d option.`);
3102
3147
  databaseUrl = evaluateUrl(schemaUrl);
3103
3148
  }
3104
- const dialect = await createDialect(getStringLiteral(dataSource?.fields.find((f) => f.name === "provider")?.value), databaseUrl, outputPath);
3149
+ const dialect = await createDialect(getStringLiteral(dataSource?.fields.find((f) => f.name === "provider")?.value), databaseUrl, model.$document.uri.path);
3105
3150
  const schemaModule = await createJiti(typeof __filename !== "undefined" ? __filename : import.meta.url).import(path.join(outputPath, "schema"));
3106
3151
  const schema = schemaModule.schema;
3107
3152
  const omit = {};
@@ -3124,6 +3169,7 @@ async function run(options) {
3124
3169
  const authDb = db.$use(new PolicyPlugin());
3125
3170
  if (options.studioAuthKey) console.log(colors.gray("Access policy plugin enabled for authorization."));
3126
3171
  startServer(db, schemaModule.schema, options, authDb);
3172
+ if (!options.studioAuthKey) console.warn(colors.yellow("Warning: This proxy has no authentication. Do not expose it to the public network.\nTo secure it, get an API key from ZenStack Studio and set it via the ZENSTACK_STUDIO_AUTH_KEY environment variable."));
3127
3173
  }
3128
3174
  function evaluateUrl(schemaUrl) {
3129
3175
  if (isLiteralExpr(schemaUrl)) return getStringLiteral(schemaUrl);
@@ -3144,87 +3190,69 @@ function redactDatabaseUrl(url) {
3144
3190
  return url;
3145
3191
  }
3146
3192
  }
3147
- async function createDialect(provider, databaseUrl, outputPath) {
3193
+ async function createDialect(provider, databaseUrl, schemaFilePath) {
3148
3194
  switch (provider) {
3149
3195
  case "sqlite": {
3150
3196
  let SQLite;
3151
- try {
3152
- SQLite = (await import("better-sqlite3")).default;
3153
- } catch {
3154
- throw new CliError(`Package "better-sqlite3" is required for SQLite support. Please install it with: npm install better-sqlite3`);
3155
- }
3197
+ const mod = await loadPackage("better-sqlite3");
3198
+ if (mod) SQLite = mod.default || mod;
3199
+ else throw new CliError(`Package "better-sqlite3" is required for SQLite support. Please install it with: npm install better-sqlite3`);
3156
3200
  let resolvedUrl = databaseUrl.trim();
3157
3201
  if (resolvedUrl.startsWith("file:")) {
3158
- const filePath = resolvedUrl.substring(5);
3159
- if (!path.isAbsolute(filePath)) resolvedUrl = path.join(outputPath, filePath);
3202
+ resolvedUrl = new URL(resolvedUrl, `file:${schemaFilePath}`).pathname;
3203
+ if (process.platform === "win32" && resolvedUrl[0] === "/") resolvedUrl = resolvedUrl.slice(1);
3160
3204
  }
3161
3205
  console.log(colors.gray(`Connecting to SQLite database at: ${resolvedUrl}`));
3162
3206
  return new SqliteDialect({ database: new SQLite(resolvedUrl) });
3163
3207
  }
3164
3208
  case "postgresql": {
3165
3209
  let PgPool;
3166
- try {
3167
- PgPool = (await import("pg")).Pool;
3168
- } catch {
3169
- throw new CliError(`Package "pg" is required for PostgreSQL support. Please install it with: npm install pg`);
3170
- }
3210
+ const mod = await loadPackage("pg");
3211
+ if (mod) PgPool = mod.Pool || mod.default?.Pool;
3212
+ else throw new CliError(`Package "pg" is required for PostgreSQL support. Please install it with: npm install pg`);
3171
3213
  console.log(colors.gray(`Connecting to PostgreSQL database at: ${redactDatabaseUrl(databaseUrl)}`));
3172
3214
  return new PostgresDialect({ pool: new PgPool({ connectionString: databaseUrl }) });
3173
3215
  }
3174
3216
  case "mysql": {
3175
3217
  let createMysqlPool;
3176
- try {
3177
- createMysqlPool = (await import("mysql2")).createPool;
3178
- } catch {
3179
- throw new CliError(`Package "mysql2" is required for MySQL support. Please install it with: npm install mysql2`);
3180
- }
3218
+ const mod = await loadPackage("mysql2");
3219
+ if (mod) createMysqlPool = mod.createPool || mod.default?.createPool;
3220
+ else throw new CliError(`Package "mysql2" is required for MySQL support. Please install it with: npm install mysql2`);
3181
3221
  console.log(colors.gray(`Connecting to MySQL database at: ${redactDatabaseUrl(databaseUrl)}`));
3182
3222
  return new MysqlDialect({ pool: createMysqlPool(databaseUrl) });
3183
3223
  }
3184
3224
  default: throw new CliError(`Unsupported database provider: ${provider}`);
3185
3225
  }
3186
3226
  }
3187
- function createProxyApp(client, schema, authDb, auth) {
3188
- const app = express();
3189
- app.use(cors());
3190
- app.use(express.json({
3191
- limit: "5mb",
3192
- verify: (req, _res, buf) => {
3193
- req.rawBody = buf.toString("utf8");
3194
- }
3195
- }));
3196
- app.use(express.urlencoded({
3197
- extended: true,
3198
- limit: "5mb"
3199
- }));
3200
- if (auth?.studioAuthKey) {
3201
- const toleranceSecs = auth.signatureToleranceSecs;
3202
- const normalizedKey = normalizePublicKey(auth.studioAuthKey);
3203
- app.use(["/api/model", "/api/schema"], createSignatureMiddleware(normalizedKey, toleranceSecs));
3204
- }
3205
- app.use("/api/model", ZenStackMiddleware({
3206
- apiHandler: new RPCApiHandler({ schema }),
3207
- getClient: (req) => resolveClient(client, authDb, req, !!auth?.studioAuthKey)
3227
+ function createProxyApp(optionsOrClient, schema, authDb, auth) {
3228
+ let options;
3229
+ if ("client" in optionsOrClient && "schema" in optionsOrClient) options = optionsOrClient;
3230
+ else options = {
3231
+ client: optionsOrClient,
3232
+ schema,
3233
+ authDb,
3234
+ auth
3235
+ };
3236
+ const app = new Hono();
3237
+ app.use("*", cors(options.cors));
3238
+ if (options.auth?.studioAuthKey) {
3239
+ const toleranceSecs = options.auth.signatureToleranceSecs;
3240
+ const sigMiddleware = createSignatureMiddleware(normalizePublicKey(options.auth.studioAuthKey), toleranceSecs);
3241
+ app.use("/api/model/*", sigMiddleware);
3242
+ app.use("/api/schema", sigMiddleware);
3243
+ }
3244
+ app.use("/api/model/*", createHonoHandler({
3245
+ apiHandler: new RPCApiHandler({ schema: options.schema }),
3246
+ getClient: (c) => resolveClient(options.client, options.authDb ?? options.client, c, !!options.auth?.studioAuthKey)
3208
3247
  }));
3209
- app.get("/api/schema", (_req, res) => {
3210
- res.json({
3211
- ...schema,
3248
+ app.get("/api/schema", (c) => {
3249
+ return c.json({
3250
+ ...options.schema,
3212
3251
  zenstackVersion: getVersion()
3213
3252
  });
3214
3253
  });
3215
3254
  return app;
3216
3255
  }
3217
- /**
3218
- * Creates an Express middleware that verifies the ed25519 signature on every request.
3219
- *
3220
- * The signature header format is: `t=<unix-timestamp>,v1=<base64url-signature>`
3221
- *
3222
- * The signed message is constructed as:
3223
- * - GET requests: `<raw-query-string><timestamp>[<authorizationToken>]`
3224
- * - Other methods: `<raw-body><timestamp>[<authorizationToken>]`
3225
- *
3226
- * `authorizationToken` is the bearer token value from the `Authorization` header (if present).
3227
- */
3228
3256
  function createSignatureMiddleware(publicKey, toleranceSeconds) {
3229
3257
  let lastInvalidSigWarnAt = 0;
3230
3258
  const WARN_THROTTLE_SECS = 60;
@@ -3235,48 +3263,41 @@ function createSignatureMiddleware(publicKey, toleranceSeconds) {
3235
3263
  console.warn(colors.yellow("Warning: Received a request with an invalid signature. Please double-check whether you have the correct public API key configured."));
3236
3264
  }
3237
3265
  }
3238
- return (req, res, next) => {
3239
- const signatureHeader = req.headers["x-zenstack-signature"];
3240
- if (!signatureHeader || typeof signatureHeader !== "string") return rejectAuth(res, "MISSING_SIGNATURE_HEADER");
3266
+ return async (c, next) => {
3267
+ const signatureHeader = c.req.header("x-zenstack-signature");
3268
+ if (!signatureHeader) return rejectAuth(c, "MISSING_SIGNATURE_HEADER");
3241
3269
  const parts = signatureHeader.split(",");
3242
3270
  const timestampPart = parts.find((p) => p.startsWith("t="));
3243
3271
  const sigPart = parts.find((p) => p.startsWith("v1="));
3244
- if (!timestampPart || !sigPart) return rejectAuth(res, "INVALID_SIGNATURE_FORMAT");
3272
+ if (!timestampPart || !sigPart) return rejectAuth(c, "INVALID_SIGNATURE_FORMAT");
3245
3273
  const timestamp = timestampPart.substring(2);
3246
3274
  const sig = sigPart.substring(3);
3247
3275
  const requestTime = parseInt(timestamp, 10);
3248
3276
  const now = Math.floor(Date.now() / 1e3);
3249
- if (isNaN(requestTime) || Math.abs(now - requestTime) > toleranceSeconds) return rejectAuth(res, "INVALID_TIMESTAMP");
3277
+ if (isNaN(requestTime) || Math.abs(now - requestTime) > toleranceSeconds) return rejectAuth(c, "INVALID_TIMESTAMP");
3250
3278
  let payload;
3251
- if (req.method === "GET" || req.method === "DELETE") {
3252
- const qMark = req.originalUrl.indexOf("?");
3253
- payload = qMark >= 0 ? req.originalUrl.substring(qMark + 1) : "";
3254
- } else payload = req.rawBody ?? "";
3255
- const authHeader = req.headers["authorization"];
3279
+ if (c.req.method === "GET" || c.req.method === "DELETE") {
3280
+ const rawUrl = c.req.url;
3281
+ const qMark = rawUrl.indexOf("?");
3282
+ payload = qMark >= 0 ? rawUrl.substring(qMark + 1) : "";
3283
+ } else payload = await c.req.text();
3284
+ const authHeader = c.req.header("authorization");
3256
3285
  const authorizationToken = authHeader && authHeader.startsWith("Bearer ") ? authHeader.substring(7) : void 0;
3257
3286
  const message = authorizationToken ? `${payload}${timestamp}${authorizationToken}` : `${payload}${timestamp}`;
3258
3287
  try {
3259
3288
  if (!verify(null, Buffer.from(message, "utf8"), publicKey, Buffer.from(sig, "base64url"))) {
3260
3289
  warnInvalidSignature();
3261
- return rejectAuth(res, "INVALID_SIGNATURE_FORMAT");
3290
+ return rejectAuth(c, "INVALID_SIGNATURE_FORMAT");
3262
3291
  }
3263
3292
  } catch {
3264
3293
  warnInvalidSignature();
3265
- return rejectAuth(res, "INVALID_SIGNATURE_FORMAT");
3294
+ return rejectAuth(c, "INVALID_SIGNATURE_FORMAT");
3266
3295
  }
3267
3296
  return next();
3268
3297
  };
3269
3298
  }
3270
- /**
3271
- * Resolves the appropriate client for a request based on the Authorization header.
3272
- *
3273
- * - No studioAuthKey configured (authDb is undefined): always return the base client.
3274
- * - SuperUser claim: return the base client (full access, no policy enforcement).
3275
- * - Regular user claim: return authDb with the user identity set via $setAuth.
3276
- * - No / invalid token: return the base client.
3277
- */
3278
- function resolveClient(client, authDb, req, isAuthKeyEnabled) {
3279
- const authHeader = req.headers["authorization"];
3299
+ function resolveClient(client, authDb, c, isAuthKeyEnabled) {
3300
+ const authHeader = c.req.header("authorization");
3280
3301
  if (!isAuthKeyEnabled && !authHeader) return client;
3281
3302
  if (!authHeader?.startsWith("Bearer ")) return authDb;
3282
3303
  const token = authHeader.substring(7);
@@ -3291,10 +3312,18 @@ function resolveClient(client, authDb, req, isAuthKeyEnabled) {
3291
3312
  else return authDb.$setAuth(claim.data);
3292
3313
  }
3293
3314
  function startServer(client, schema, options, authDb) {
3294
- const server = createProxyApp(client, schema, authDb, options.studioAuthKey ? {
3295
- studioAuthKey: options.studioAuthKey,
3296
- signatureToleranceSecs: options.signatureToleranceSecs
3297
- } : void 0).listen(options.port, () => {
3315
+ const server = serve({
3316
+ fetch: createProxyApp({
3317
+ client,
3318
+ schema,
3319
+ authDb,
3320
+ auth: options.studioAuthKey ? {
3321
+ studioAuthKey: options.studioAuthKey,
3322
+ signatureToleranceSecs: options.signatureToleranceSecs
3323
+ } : void 0
3324
+ }).fetch,
3325
+ port: options.port
3326
+ }, () => {
3298
3327
  console.log(`ZenStack proxy server is running on port: ${options.port}`);
3299
3328
  console.log(`You can visit ZenStack Studio at: ${colors.blue("https://studio.zenstack.dev")}`);
3300
3329
  });
@@ -3318,6 +3347,121 @@ function startServer(client, schema, options, authDb) {
3318
3347
  process.exit(0);
3319
3348
  });
3320
3349
  }
3350
+ async function resolveSchema(options) {
3351
+ if (!options.introspect) try {
3352
+ return getSchemaFile(options.schema);
3353
+ } catch (err) {
3354
+ if (!(err instanceof CliError)) throw err;
3355
+ const dbFlag = !!process.env["DATABASE_URL"] ? "" : "-d <databaseUrl>";
3356
+ throw new CliError(`No ZModel schema file found in default locations.
3357
+ • If you have an existing schema file, specify it explicitly:\n npx @zenstackhq/cli studio --schema <path> ${dbFlag}\n • Otherwise, auto-generate from the database:\n npx @zenstackhq/cli studio --introspect ${dbFlag}`);
3358
+ }
3359
+ else {
3360
+ const databaseUrl = options.databaseUrl ?? process.env["DATABASE_URL"];
3361
+ if (!databaseUrl) throw new CliError("--introspect requires a database connection — pass -d <url> or set DATABASE_URL.");
3362
+ const providerType = getProviderFromUrl(databaseUrl);
3363
+ await installDbDriverPackage(providerType);
3364
+ const schemaFile = await introspectAndGenerateSchema(databaseUrl, providerType, !options.databaseUrl);
3365
+ await run$5({
3366
+ schema: schemaFile,
3367
+ silent: false,
3368
+ watch: false
3369
+ });
3370
+ console.log(colors.yellow("\n⚠ The generated schema has no access policies.\n All data is accessible without restriction.\n Edit " + colors.cyan(schemaFile) + " to add access policies.\n"));
3371
+ return schemaFile;
3372
+ }
3373
+ }
3374
+ function getProviderFromUrl(url) {
3375
+ if (url.startsWith("postgres://") || url.startsWith("postgresql://")) return "postgresql";
3376
+ if (url.startsWith("mysql://")) return "mysql";
3377
+ if (url.startsWith("file:") || url.startsWith("sqlite:")) return "sqlite";
3378
+ throw new CliError(`Unable to determine database type from URL: ${url}`);
3379
+ }
3380
+ async function installDbDriverPackage(providerType) {
3381
+ const driverPackage = (() => {
3382
+ switch (providerType) {
3383
+ case "postgresql": return {
3384
+ name: "pg",
3385
+ dev: false
3386
+ };
3387
+ case "mysql": return {
3388
+ name: "mysql2",
3389
+ dev: false
3390
+ };
3391
+ case "sqlite": return {
3392
+ name: "better-sqlite3",
3393
+ dev: false
3394
+ };
3395
+ }
3396
+ })();
3397
+ if (isPackageInstalled(driverPackage.name)) return;
3398
+ let pm = await detect();
3399
+ if (!pm) pm = {
3400
+ agent: "npm",
3401
+ name: "npm"
3402
+ };
3403
+ console.log(colors.gray(`Using package manager: ${pm.agent}`));
3404
+ const resolved = resolveCommand(pm.agent, "add", [driverPackage.name, ...driverPackage.dev ? [pm.agent.startsWith("yarn") || pm.agent === "bun" ? "--dev" : "--save-dev"] : []]);
3405
+ if (!resolved) throw new CliError(`Unable to determine how to install package "${driverPackage.name}". Please install it manually.`);
3406
+ const spinner = ora(`Installing "${driverPackage.name}"`).start();
3407
+ try {
3408
+ execSync$1(`${resolved.command} ${resolved.args.join(" ")}`, { cwd: process.cwd() });
3409
+ spinner.succeed();
3410
+ } catch (e) {
3411
+ spinner.fail();
3412
+ throw e;
3413
+ }
3414
+ }
3415
+ function adjustSqliteUrlForSchema(url) {
3416
+ let prefix = "";
3417
+ let filePath = url;
3418
+ if (url.startsWith("file:")) {
3419
+ prefix = "file:";
3420
+ filePath = url.substring(5);
3421
+ } else if (url.startsWith("sqlite:")) {
3422
+ prefix = "sqlite:";
3423
+ filePath = url.substring(7);
3424
+ }
3425
+ if (!path.isAbsolute(filePath)) {
3426
+ const adjustedPath = path.join("..", filePath).replace(/\\/g, "/");
3427
+ return {
3428
+ isRelative: true,
3429
+ adjustedUrl: `${prefix}${adjustedPath}`
3430
+ };
3431
+ }
3432
+ return {
3433
+ isRelative: false,
3434
+ adjustedUrl: url
3435
+ };
3436
+ }
3437
+ async function introspectAndGenerateSchema(databaseUrl, providerType, urlFromEnv) {
3438
+ let urlExpr;
3439
+ if (providerType === "sqlite") {
3440
+ const { isRelative, adjustedUrl } = adjustSqliteUrlForSchema(databaseUrl);
3441
+ if (isRelative) {
3442
+ urlExpr = `'${adjustedUrl}'`;
3443
+ databaseUrl = adjustedUrl;
3444
+ } else urlExpr = urlFromEnv ? "env(\"DATABASE_URL\")" : `'${databaseUrl}'`;
3445
+ } else urlExpr = urlFromEnv ? "env(\"DATABASE_URL\")" : `'${databaseUrl}'`;
3446
+ const minimalSchema = `datasource db {\n provider = '${providerType}'\n url = ${urlExpr}\n}\n`;
3447
+ const schemaDir = path.resolve("zenstack");
3448
+ const schemaFile = path.join(schemaDir, "schema.zmodel");
3449
+ fs.mkdirSync(schemaDir, { recursive: true });
3450
+ fs.writeFileSync(schemaFile, minimalSchema, "utf-8");
3451
+ await runPull({
3452
+ schema: schemaFile,
3453
+ output: schemaFile,
3454
+ databaseUrl,
3455
+ provider: providerType,
3456
+ modelCasing: "pascal",
3457
+ fieldCasing: "none",
3458
+ alwaysMap: false,
3459
+ quote: "single",
3460
+ indent: 4
3461
+ });
3462
+ console.log(colors.green(`\n✅ Schema generated: ${colors.cyan(schemaFile)}`));
3463
+ return schemaFile;
3464
+ }
3321
3465
  //#endregion
3322
3466
  //#region src/utils/is-ci.ts
3323
3467
  const isInCi = env["CI"] !== "0" && env["CI"] !== "false" && ("CI" in env || "CONTINUOUS_INTEGRATION" in env || Object.keys(env).some((key) => key.startsWith("CI_")));
@@ -3573,7 +3717,7 @@ Arguments following -- are passed to the seed script. E.g.: "zen db seed -- --us
3573
3717
  const parsed = parseInt(v, 10);
3574
3718
  if (isNaN(parsed) || parsed < 0) throw new CliError(`--signatureToleranceSecs must be a positive integer, got: ${v}`);
3575
3719
  return parsed;
3576
- })).addOption(noVersionCheckOption).action(proxyAction);
3720
+ })).addOption(new Option("--introspect", "Introspect the database to generate a schema when no schema file is found")).addOption(noVersionCheckOption).action(proxyAction);
3577
3721
  program.addHelpCommand("help [command]", "Display help for a command");
3578
3722
  program.hook("preAction", async (_thisCommand, actionCommand) => {
3579
3723
  if (actionCommand.getOptionValue("versionCheck") !== false) await checkNewVersion();