@donotdev/cli 0.3.6 → 0.3.8

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.
@@ -9078,6 +9078,9 @@ var init_typed_file_operations = __esm({
9078
9078
  });
9079
9079
 
9080
9080
  // packages/tooling/src/utils/type-guards.ts
9081
+ function isRecord(value) {
9082
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9083
+ }
9081
9084
  function isObjectLike(value) {
9082
9085
  return typeof value === "object" && value !== null;
9083
9086
  }
@@ -30675,6 +30678,314 @@ var init_dist9 = __esm({
30675
30678
  }
30676
30679
  });
30677
30680
 
30681
+ // packages/tooling/src/utils/supabase-management.ts
30682
+ var supabase_management_exports = {};
30683
+ __export(supabase_management_exports, {
30684
+ MGMT_API_BASE: () => MGMT_API_BASE,
30685
+ SESSION_POOLER_PORT: () => SESSION_POOLER_PORT,
30686
+ cleanupOldEntityMigrations: () => cleanupOldEntityMigrations,
30687
+ createProject: () => createProject,
30688
+ deployEdgeFunction: () => deployEdgeFunction,
30689
+ executeMigration: () => executeMigration,
30690
+ extractProjectRef: () => extractProjectRef,
30691
+ getAuthConfig: () => getAuthConfig,
30692
+ getProject: () => getProject,
30693
+ listApiKeys: () => listApiKeys,
30694
+ listEdgeFunctions: () => listEdgeFunctions,
30695
+ listMigrationHistory: () => listMigrationHistory,
30696
+ parseProjectRef: () => parseProjectRef,
30697
+ queryDatabase: () => queryDatabase,
30698
+ redactSecrets: () => redactSecrets,
30699
+ tableExists: () => tableExists,
30700
+ updateAuthConfig: () => updateAuthConfig
30701
+ });
30702
+ function createAdminClient(supabaseUrl, secretKey) {
30703
+ return createClient(supabaseUrl, secretKey, {
30704
+ auth: {
30705
+ autoRefreshToken: false,
30706
+ persistSession: false
30707
+ }
30708
+ });
30709
+ }
30710
+ function parseProjectRef(supabaseUrl) {
30711
+ return supabaseUrl?.match(/https?:\/\/([a-z0-9]+)\.supabase\.co/)?.[1];
30712
+ }
30713
+ function extractProjectRef(supabaseUrl) {
30714
+ const ref = parseProjectRef(supabaseUrl);
30715
+ if (!ref) {
30716
+ throw new Error(
30717
+ `Cannot extract project ref from URL: ${supabaseUrl}. Expected format: https://<ref>.supabase.co`
30718
+ );
30719
+ }
30720
+ return ref;
30721
+ }
30722
+ function redactSecrets(text, secrets) {
30723
+ let out = text;
30724
+ const values = secrets.filter((s2) => s2.length > 0).flatMap((s2) => [s2, encodeURIComponent(s2)]);
30725
+ for (const value of [...new Set(values)].sort((a2, b) => b.length - a2.length)) {
30726
+ out = out.split(value).join("***");
30727
+ }
30728
+ return out.replace(/sbp_[A-Za-z0-9]+/g, "sbp_***").replace(/sb_secret_[A-Za-z0-9_-]+/g, "sb_secret_***").replace(/(postgres(?:ql)?:\/\/[^:/@\s]+:)[^@\s]+@/g, "$1***@").replace(/(PGPASSWORD=["']?)[^"'\s]+/g, "$1***");
30729
+ }
30730
+ async function cleanupOldEntityMigrations(supabaseDir, latestFile) {
30731
+ const migrationsDir = joinPath(supabaseDir, "migrations");
30732
+ if (!pathExists(migrationsDir)) return;
30733
+ let oldFiles;
30734
+ try {
30735
+ oldFiles = await findFiles(migrationsDir, "*_entity_tables.sql");
30736
+ } catch {
30737
+ return;
30738
+ }
30739
+ const latestBasename = getBasename(latestFile);
30740
+ const toRemove = oldFiles.filter((f3) => getBasename(f3) !== latestBasename);
30741
+ if (toRemove.length === 0) return;
30742
+ for (const f3 of toRemove) {
30743
+ try {
30744
+ removeSync(f3);
30745
+ } catch {
30746
+ }
30747
+ }
30748
+ log2.info(`Cleaned up ${toRemove.length} old entity migration file(s)`);
30749
+ }
30750
+ async function executeMigration(options) {
30751
+ const { supabaseDir, supabaseUrl, accessToken } = options;
30752
+ if (!pathExists(supabaseDir)) {
30753
+ throw new Error(`Supabase directory not found: ${supabaseDir}`);
30754
+ }
30755
+ const migrationsDir = joinPath(supabaseDir, "migrations");
30756
+ if (!pathExists(migrationsDir)) {
30757
+ throw new Error(`Migrations directory not found: ${migrationsDir}`);
30758
+ }
30759
+ const sqlFiles = readdirSync3(migrationsDir).filter((f3) => f3.endsWith(".sql")).sort().map((f3) => joinPath(migrationsDir, f3));
30760
+ if (sqlFiles.length === 0) {
30761
+ throw new Error(`No .sql files found in ${migrationsDir}`);
30762
+ }
30763
+ const sql = sqlFiles.map((f3) => asText(readSync(f3))).filter(Boolean).join("\n\n");
30764
+ const projectRef = extractProjectRef(supabaseUrl);
30765
+ const mgmtUrl = `https://api.supabase.com/v1/projects/${projectRef}/database/query`;
30766
+ const response = await fetch(mgmtUrl, {
30767
+ method: "POST",
30768
+ headers: {
30769
+ "Content-Type": "application/json",
30770
+ Authorization: `Bearer ${accessToken}`
30771
+ },
30772
+ body: JSON.stringify({ query: sql })
30773
+ });
30774
+ if (!response.ok) {
30775
+ const body = await response.text();
30776
+ const safe = body.replace(/sbp_[^\s"']*/g, "***").replace(/sb_secret_[^\s"']*/g, "***");
30777
+ throw new Error(
30778
+ `Supabase Management API error (HTTP ${response.status}): ${safe}
30779
+ Ensure SUPABASE_ACCESS_TOKEN is valid. Get one from: https://supabase.com/dashboard/account/tokens`
30780
+ );
30781
+ }
30782
+ log2.info("Migrations executed via Supabase Management API");
30783
+ }
30784
+ async function tableExists(options) {
30785
+ const { supabaseUrl, secretKey, tableName } = options;
30786
+ try {
30787
+ const supabase = createAdminClient(supabaseUrl, secretKey);
30788
+ const { error: error2 } = await supabase.from(tableName).select("*").limit(0);
30789
+ if (error2) {
30790
+ if (error2.message?.includes("does not exist") || error2.code === "42P01" || error2.code === "PGRST116") {
30791
+ return false;
30792
+ }
30793
+ log2.debug(`Error checking table existence: ${error2.message}`);
30794
+ return false;
30795
+ }
30796
+ return true;
30797
+ } catch (error2) {
30798
+ log2.debug(
30799
+ `Error checking if table ${tableName} exists: ${error2 instanceof Error ? error2.message : String(error2)}`
30800
+ );
30801
+ return false;
30802
+ }
30803
+ }
30804
+ async function queryDatabase(projectRef, accessToken, query) {
30805
+ const response = await fetch(
30806
+ `${MGMT_API_BASE}/projects/${projectRef}/database/query`,
30807
+ {
30808
+ method: "POST",
30809
+ headers: {
30810
+ "Content-Type": "application/json",
30811
+ Authorization: `Bearer ${accessToken}`
30812
+ },
30813
+ body: JSON.stringify({ query })
30814
+ }
30815
+ );
30816
+ if (!response.ok) {
30817
+ const body = (await response.text()).replace(/sbp_[^\s"']*/g, "***").replace(/sb_secret_[^\s"']*/g, "***");
30818
+ throw new Error(
30819
+ `Supabase Management API query failed (HTTP ${response.status}): ${body.slice(0, 500)}`
30820
+ );
30821
+ }
30822
+ return await response.json();
30823
+ }
30824
+ async function listEdgeFunctions(projectRef, accessToken) {
30825
+ const url = `${MGMT_API_BASE}/projects/${projectRef}/functions`;
30826
+ const response = await fetch(url, {
30827
+ method: "GET",
30828
+ headers: { Authorization: `Bearer ${accessToken}` }
30829
+ });
30830
+ if (!response.ok) {
30831
+ const body = await response.text();
30832
+ throw new Error(
30833
+ `Failed to list Edge Functions (HTTP ${response.status}): ${body.slice(0, 500)}`
30834
+ );
30835
+ }
30836
+ const functions = await response.json();
30837
+ return functions.map((f3) => f3.slug);
30838
+ }
30839
+ async function deployEdgeFunction(options) {
30840
+ const {
30841
+ projectRef,
30842
+ accessToken,
30843
+ functionName,
30844
+ functionsDir,
30845
+ verifyJwt = false
30846
+ } = options;
30847
+ const buildPath = joinPath(functionsDir, ".build", `${functionName}.js`);
30848
+ if (!pathExists(buildPath)) {
30849
+ throw new Error(
30850
+ `Pre-built edge function not found: ${buildPath}
30851
+ Run \`dn build <app> supabase-functions\` before deploying.`
30852
+ );
30853
+ }
30854
+ const sourceContent = asText(readSync(buildPath, { format: "text" }));
30855
+ if (!sourceContent) {
30856
+ throw new Error(`Empty build output: ${buildPath}`);
30857
+ }
30858
+ const existingSlugs = await listEdgeFunctions(projectRef, accessToken);
30859
+ const exists = existingSlugs.includes(functionName);
30860
+ if (exists) {
30861
+ const url = `${MGMT_API_BASE}/projects/${projectRef}/functions/${functionName}`;
30862
+ const response = await fetch(url, {
30863
+ method: "PATCH",
30864
+ headers: {
30865
+ "Content-Type": "application/json",
30866
+ Authorization: `Bearer ${accessToken}`
30867
+ },
30868
+ body: JSON.stringify({
30869
+ body: sourceContent,
30870
+ verify_jwt: verifyJwt
30871
+ })
30872
+ });
30873
+ if (!response.ok) {
30874
+ const body = await response.text();
30875
+ throw new Error(
30876
+ `Failed to update Edge Function "${functionName}" (HTTP ${response.status}): ${body.slice(0, 500)}`
30877
+ );
30878
+ }
30879
+ } else {
30880
+ const url = `${MGMT_API_BASE}/projects/${projectRef}/functions`;
30881
+ const response = await fetch(url, {
30882
+ method: "POST",
30883
+ headers: {
30884
+ "Content-Type": "application/json",
30885
+ Authorization: `Bearer ${accessToken}`
30886
+ },
30887
+ body: JSON.stringify({
30888
+ slug: functionName,
30889
+ name: functionName,
30890
+ body: sourceContent,
30891
+ verify_jwt: verifyJwt
30892
+ })
30893
+ });
30894
+ if (!response.ok) {
30895
+ const body = await response.text();
30896
+ throw new Error(
30897
+ `Failed to create Edge Function "${functionName}" (HTTP ${response.status}): ${body.slice(0, 500)}`
30898
+ );
30899
+ }
30900
+ }
30901
+ }
30902
+ async function managementRequest(method, path, accessToken, options = {}) {
30903
+ const response = await fetch(`${MGMT_API_BASE}${path}`, {
30904
+ method,
30905
+ headers: {
30906
+ Authorization: `Bearer ${accessToken}`,
30907
+ ...options.body === void 0 ? {} : { "Content-Type": "application/json" }
30908
+ },
30909
+ ...options.body === void 0 ? {} : { body: JSON.stringify(options.body) }
30910
+ });
30911
+ if (response.status === 404 && options.allowNotFound) return null;
30912
+ if (!response.ok) {
30913
+ throw new Error(
30914
+ `Supabase Management API ${method} ${path} failed (HTTP ${response.status}): ${redactSecrets(await response.text(), [accessToken]).slice(0, 500)}`
30915
+ );
30916
+ }
30917
+ return await response.json();
30918
+ }
30919
+ async function requiredRequest(method, path, accessToken, body) {
30920
+ const result = await managementRequest(method, path, accessToken, {
30921
+ body
30922
+ });
30923
+ if (result === null) {
30924
+ throw new Error(
30925
+ `Supabase Management API ${method} ${path} returned no body.`
30926
+ );
30927
+ }
30928
+ return result;
30929
+ }
30930
+ async function getProject(projectRef, accessToken) {
30931
+ return managementRequest(
30932
+ "GET",
30933
+ `/projects/${projectRef}`,
30934
+ accessToken,
30935
+ { allowNotFound: true }
30936
+ );
30937
+ }
30938
+ async function createProject(body, accessToken) {
30939
+ return requiredRequest(
30940
+ "POST",
30941
+ "/projects",
30942
+ accessToken,
30943
+ body
30944
+ );
30945
+ }
30946
+ async function listApiKeys(projectRef, accessToken) {
30947
+ return requiredRequest(
30948
+ "GET",
30949
+ `/projects/${projectRef}/api-keys?reveal=true`,
30950
+ accessToken
30951
+ );
30952
+ }
30953
+ async function getAuthConfig(projectRef, accessToken) {
30954
+ return requiredRequest(
30955
+ "GET",
30956
+ `/projects/${projectRef}/config/auth`,
30957
+ accessToken
30958
+ );
30959
+ }
30960
+ async function updateAuthConfig(projectRef, accessToken, body) {
30961
+ await requiredRequest(
30962
+ "PATCH",
30963
+ `/projects/${projectRef}/config/auth`,
30964
+ accessToken,
30965
+ body
30966
+ );
30967
+ }
30968
+ async function listMigrationHistory(projectRef, accessToken) {
30969
+ return requiredRequest(
30970
+ "GET",
30971
+ `/projects/${projectRef}/database/migrations`,
30972
+ accessToken
30973
+ );
30974
+ }
30975
+ var MGMT_API_BASE, SESSION_POOLER_PORT;
30976
+ var init_supabase_management = __esm({
30977
+ "packages/tooling/src/utils/supabase-management.ts"() {
30978
+ "use strict";
30979
+ init_utils2();
30980
+ init_dist9();
30981
+ init_cli_output();
30982
+ init_pathResolver();
30983
+ init_type_guards();
30984
+ MGMT_API_BASE = "https://api.supabase.com/v1";
30985
+ SESSION_POOLER_PORT = 5432;
30986
+ }
30987
+ });
30988
+
30678
30989
  // node_modules/.bun/extend@3.0.2/node_modules/extend/index.js
30679
30990
  var require_extend = __commonJS({
30680
30991
  "node_modules/.bun/extend@3.0.2/node_modules/extend/index.js"(exports, module) {
@@ -51160,199 +51471,6 @@ var init_app = __esm({
51160
51471
  }
51161
51472
  });
51162
51473
 
51163
- // packages/tooling/src/utils/supabase-management.ts
51164
- var supabase_management_exports = {};
51165
- __export(supabase_management_exports, {
51166
- MGMT_API_BASE: () => MGMT_API_BASE,
51167
- cleanupOldEntityMigrations: () => cleanupOldEntityMigrations,
51168
- deployEdgeFunction: () => deployEdgeFunction,
51169
- executeMigration: () => executeMigration,
51170
- extractProjectRef: () => extractProjectRef,
51171
- listEdgeFunctions: () => listEdgeFunctions,
51172
- tableExists: () => tableExists
51173
- });
51174
- function createAdminClient(supabaseUrl, secretKey) {
51175
- return createClient(supabaseUrl, secretKey, {
51176
- auth: {
51177
- autoRefreshToken: false,
51178
- persistSession: false
51179
- }
51180
- });
51181
- }
51182
- function extractProjectRef(supabaseUrl) {
51183
- const match = supabaseUrl.match(/https?:\/\/([a-z0-9]+)\.supabase\.co/);
51184
- if (!match?.[1]) {
51185
- throw new Error(
51186
- `Cannot extract project ref from URL: ${supabaseUrl}. Expected format: https://<ref>.supabase.co`
51187
- );
51188
- }
51189
- return match[1];
51190
- }
51191
- async function cleanupOldEntityMigrations(supabaseDir, latestFile) {
51192
- const migrationsDir = joinPath(supabaseDir, "migrations");
51193
- if (!pathExists(migrationsDir)) return;
51194
- let oldFiles;
51195
- try {
51196
- oldFiles = await findFiles(migrationsDir, "*_entity_tables.sql");
51197
- } catch {
51198
- return;
51199
- }
51200
- const latestBasename = getBasename(latestFile);
51201
- const toRemove = oldFiles.filter((f3) => getBasename(f3) !== latestBasename);
51202
- if (toRemove.length === 0) return;
51203
- for (const f3 of toRemove) {
51204
- try {
51205
- removeSync(f3);
51206
- } catch {
51207
- }
51208
- }
51209
- log2.info(`Cleaned up ${toRemove.length} old entity migration file(s)`);
51210
- }
51211
- async function executeMigration(options) {
51212
- const { supabaseDir, supabaseUrl, accessToken } = options;
51213
- if (!pathExists(supabaseDir)) {
51214
- throw new Error(`Supabase directory not found: ${supabaseDir}`);
51215
- }
51216
- const migrationsDir = joinPath(supabaseDir, "migrations");
51217
- if (!pathExists(migrationsDir)) {
51218
- throw new Error(`Migrations directory not found: ${migrationsDir}`);
51219
- }
51220
- const sqlFiles = readdirSync3(migrationsDir).filter((f3) => f3.endsWith(".sql")).sort().map((f3) => joinPath(migrationsDir, f3));
51221
- if (sqlFiles.length === 0) {
51222
- throw new Error(`No .sql files found in ${migrationsDir}`);
51223
- }
51224
- const sql = sqlFiles.map((f3) => asText(readSync(f3))).filter(Boolean).join("\n\n");
51225
- const projectRef = extractProjectRef(supabaseUrl);
51226
- const mgmtUrl = `https://api.supabase.com/v1/projects/${projectRef}/database/query`;
51227
- const response = await fetch(mgmtUrl, {
51228
- method: "POST",
51229
- headers: {
51230
- "Content-Type": "application/json",
51231
- Authorization: `Bearer ${accessToken}`
51232
- },
51233
- body: JSON.stringify({ query: sql })
51234
- });
51235
- if (!response.ok) {
51236
- const body = await response.text();
51237
- const safe = body.replace(/sbp_[^\s"']*/g, "***").replace(/sb_secret_[^\s"']*/g, "***");
51238
- throw new Error(
51239
- `Supabase Management API error (HTTP ${response.status}): ${safe}
51240
- Ensure SUPABASE_ACCESS_TOKEN is valid. Get one from: https://supabase.com/dashboard/account/tokens`
51241
- );
51242
- }
51243
- log2.info("Migrations executed via Supabase Management API");
51244
- }
51245
- async function tableExists(options) {
51246
- const { supabaseUrl, secretKey, tableName } = options;
51247
- try {
51248
- const supabase = createAdminClient(supabaseUrl, secretKey);
51249
- const { error: error2 } = await supabase.from(tableName).select("*").limit(0);
51250
- if (error2) {
51251
- if (error2.message?.includes("does not exist") || error2.code === "42P01" || error2.code === "PGRST116") {
51252
- return false;
51253
- }
51254
- log2.debug(`Error checking table existence: ${error2.message}`);
51255
- return false;
51256
- }
51257
- return true;
51258
- } catch (error2) {
51259
- log2.debug(
51260
- `Error checking if table ${tableName} exists: ${error2 instanceof Error ? error2.message : String(error2)}`
51261
- );
51262
- return false;
51263
- }
51264
- }
51265
- async function listEdgeFunctions(projectRef, accessToken) {
51266
- const url = `${MGMT_API_BASE}/projects/${projectRef}/functions`;
51267
- const response = await fetch(url, {
51268
- method: "GET",
51269
- headers: { Authorization: `Bearer ${accessToken}` }
51270
- });
51271
- if (!response.ok) {
51272
- const body = await response.text();
51273
- throw new Error(
51274
- `Failed to list Edge Functions (HTTP ${response.status}): ${body.slice(0, 500)}`
51275
- );
51276
- }
51277
- const functions = await response.json();
51278
- return functions.map((f3) => f3.slug);
51279
- }
51280
- async function deployEdgeFunction(options) {
51281
- const {
51282
- projectRef,
51283
- accessToken,
51284
- functionName,
51285
- functionsDir,
51286
- verifyJwt = false
51287
- } = options;
51288
- const buildPath = joinPath(functionsDir, ".build", `${functionName}.js`);
51289
- if (!pathExists(buildPath)) {
51290
- throw new Error(
51291
- `Pre-built edge function not found: ${buildPath}
51292
- Run \`dn build <app> supabase-functions\` before deploying.`
51293
- );
51294
- }
51295
- const sourceContent = asText(readSync(buildPath, { format: "text" }));
51296
- if (!sourceContent) {
51297
- throw new Error(`Empty build output: ${buildPath}`);
51298
- }
51299
- const existingSlugs = await listEdgeFunctions(projectRef, accessToken);
51300
- const exists = existingSlugs.includes(functionName);
51301
- if (exists) {
51302
- const url = `${MGMT_API_BASE}/projects/${projectRef}/functions/${functionName}`;
51303
- const response = await fetch(url, {
51304
- method: "PATCH",
51305
- headers: {
51306
- "Content-Type": "application/json",
51307
- Authorization: `Bearer ${accessToken}`
51308
- },
51309
- body: JSON.stringify({
51310
- body: sourceContent,
51311
- verify_jwt: verifyJwt
51312
- })
51313
- });
51314
- if (!response.ok) {
51315
- const body = await response.text();
51316
- throw new Error(
51317
- `Failed to update Edge Function "${functionName}" (HTTP ${response.status}): ${body.slice(0, 500)}`
51318
- );
51319
- }
51320
- } else {
51321
- const url = `${MGMT_API_BASE}/projects/${projectRef}/functions`;
51322
- const response = await fetch(url, {
51323
- method: "POST",
51324
- headers: {
51325
- "Content-Type": "application/json",
51326
- Authorization: `Bearer ${accessToken}`
51327
- },
51328
- body: JSON.stringify({
51329
- slug: functionName,
51330
- name: functionName,
51331
- body: sourceContent,
51332
- verify_jwt: verifyJwt
51333
- })
51334
- });
51335
- if (!response.ok) {
51336
- const body = await response.text();
51337
- throw new Error(
51338
- `Failed to create Edge Function "${functionName}" (HTTP ${response.status}): ${body.slice(0, 500)}`
51339
- );
51340
- }
51341
- }
51342
- }
51343
- var MGMT_API_BASE;
51344
- var init_supabase_management = __esm({
51345
- "packages/tooling/src/utils/supabase-management.ts"() {
51346
- "use strict";
51347
- init_utils2();
51348
- init_dist9();
51349
- init_cli_output();
51350
- init_pathResolver();
51351
- init_type_guards();
51352
- MGMT_API_BASE = "https://api.supabase.com/v1";
51353
- }
51354
- });
51355
-
51356
51474
  // packages/tooling/src/cli/setup/supabase.ts
51357
51475
  function isValidSupabaseUrl(url) {
51358
51476
  try {
@@ -51416,6 +51534,100 @@ var init_supabase = __esm({
51416
51534
  }
51417
51535
  });
51418
51536
 
51537
+ // packages/tooling/src/generators/frameworkEntities.ts
51538
+ import { createRequire as createRequire4 } from "node:module";
51539
+ import { pathToFileURL } from "node:url";
51540
+ function valueAt(config, path) {
51541
+ let value = config;
51542
+ for (const key of path) {
51543
+ if (!isRecord(value)) return void 0;
51544
+ value = value[key];
51545
+ }
51546
+ return value;
51547
+ }
51548
+ function isEntityExport(value) {
51549
+ return isObjectLike(value) && typeof value.name === "string" && value.name !== "" && typeof value.collection === "string" && value.collection !== "" && isRecord(value.fields);
51550
+ }
51551
+ async function readAppConfig(appDir) {
51552
+ const file = joinPath(appDir, ...APP_CONFIG_FILE);
51553
+ if (!pathExists(file, true)) return null;
51554
+ const mod3 = await import(pathToFileURL(file).href);
51555
+ const appConfig = isRecord(mod3) ? mod3.appConfig : void 0;
51556
+ if (!isRecord(appConfig)) {
51557
+ throw new DoNotDevError(
51558
+ `${file} does not export an appConfig object (export const appConfig: AppConfig = { \u2026 }).`,
51559
+ DO_NOT_DEV_ERROR_CODES.CONFIGURATION_ERROR
51560
+ );
51561
+ }
51562
+ return appConfig;
51563
+ }
51564
+ function isEnabled(appConfig, feature) {
51565
+ const setting = valueAt(appConfig, feature.configPath);
51566
+ return setting !== void 0 && setting !== null && setting !== false;
51567
+ }
51568
+ async function loadFeatureEntities(appDir, exclude = /* @__PURE__ */ new Set(), features = FRAMEWORK_ENTITY_FEATURES) {
51569
+ if (!appDir) {
51570
+ log2.info("App folder unknown: framework feature entities skipped (pass --app-dir).");
51571
+ return [];
51572
+ }
51573
+ const appConfig = await readAppConfig(appDir);
51574
+ if (!appConfig) {
51575
+ log2.info(
51576
+ `No ${APP_CONFIG_FILE.join("/")} in ${appDir}: framework feature entities skipped.`
51577
+ );
51578
+ return [];
51579
+ }
51580
+ const configFile = joinPath(appDir, ...APP_CONFIG_FILE);
51581
+ const found = [];
51582
+ for (const feature of features) {
51583
+ if (!isEnabled(appConfig, feature)) continue;
51584
+ let resolved;
51585
+ try {
51586
+ resolved = createRequire4(configFile).resolve(feature.module);
51587
+ } catch {
51588
+ log2.warn(
51589
+ `Feature ${feature.name} is on (appConfig.${feature.configPath.join(".")}) but ${feature.packageName} is not installed in ${appDir}: its tables are skipped. Install ${feature.packageName}.`
51590
+ );
51591
+ continue;
51592
+ }
51593
+ const mod3 = await import(pathToFileURL(resolved).href);
51594
+ if (!isRecord(mod3)) continue;
51595
+ const seen = /* @__PURE__ */ new Set();
51596
+ for (const value of Object.values(mod3)) {
51597
+ if (!isEntityExport(value) || seen.has(value.collection)) continue;
51598
+ seen.add(value.collection);
51599
+ if (exclude.has(value.collection)) {
51600
+ log2.info(
51601
+ `${value.collection}: defined by the app's entity files and by feature ${feature.name}; one table.`
51602
+ );
51603
+ continue;
51604
+ }
51605
+ found.push({ entity: value, feature: feature.name, path: resolved });
51606
+ }
51607
+ }
51608
+ return found;
51609
+ }
51610
+ var FRAMEWORK_ENTITY_FEATURES, APP_CONFIG_FILE;
51611
+ var init_frameworkEntities = __esm({
51612
+ "packages/tooling/src/generators/frameworkEntities.ts"() {
51613
+ "use strict";
51614
+ init_utils2();
51615
+ init_cli_output();
51616
+ init_errors();
51617
+ init_pathResolver();
51618
+ init_type_guards();
51619
+ FRAMEWORK_ENTITY_FEATURES = [
51620
+ {
51621
+ name: "chatbot",
51622
+ configPath: ["ai", "chatbot"],
51623
+ module: "@donotdev/ai/entities",
51624
+ packageName: "@donotdev/ai"
51625
+ }
51626
+ ];
51627
+ APP_CONFIG_FILE = ["src", "config", "app.ts"];
51628
+ }
51629
+ });
51630
+
51419
51631
  // node_modules/.bun/firebase-admin@14.5.1+c188cf0323c41673/node_modules/firebase-admin/lib/firestore/error.js
51420
51632
  var require_error4 = __commonJS({
51421
51633
  "node_modules/.bun/firebase-admin@14.5.1+c188cf0323c41673/node_modules/firebase-admin/lib/firestore/error.js"(exports) {
@@ -191717,44 +191929,53 @@ init_create_utils();
191717
191929
  // packages/tooling/src/db/context.ts
191718
191930
  init_utils2();
191719
191931
  init_supabase();
191932
+ init_frameworkEntities();
191720
191933
  init_app_selector();
191721
191934
  init_cli_output();
191722
191935
  init_pathResolver();
191723
191936
  init_secrets_resolver();
191724
191937
  init_type_guards();
191725
- async function loadEntities(projectRoot) {
191938
+ function toLoadedEntity(value) {
191939
+ if (!isObjectLike(value)) return null;
191940
+ if (typeof value.name === "string" && value.name && typeof value.collection === "string" && value.collection && value.fields) {
191941
+ return {
191942
+ name: value.name,
191943
+ collection: value.collection,
191944
+ // why: shape produced by defineEntity() (the app's entities barrel or a framework
191945
+ // feature's entities module); fields/access are validated there, not re-validated here.
191946
+ fields: value.fields,
191947
+ access: value.access
191948
+ };
191949
+ }
191950
+ return null;
191951
+ }
191952
+ async function loadEntities(projectRoot, appDir) {
191953
+ const entities = [];
191726
191954
  const entitiesDir = joinPath(projectRoot, "entities");
191955
+ const indexPath = joinPath(entitiesDir, "index.ts");
191727
191956
  if (!pathExists(entitiesDir)) {
191728
191957
  log2.warn("No entities/ directory found");
191729
- return [];
191730
- }
191731
- const indexPath = joinPath(entitiesDir, "index.ts");
191732
- if (!pathExists(indexPath)) {
191958
+ } else if (!pathExists(indexPath)) {
191733
191959
  log2.warn("No entities/index.ts found");
191734
- return [];
191735
- }
191736
- let entityModule;
191737
- try {
191738
- entityModule = await import(`file://${indexPath}`);
191739
- } catch (err) {
191740
- log2.error(`Failed to import entities:`, err);
191741
- return [];
191742
- }
191743
- const entities = [];
191744
- for (const [key, value] of Object.entries(entityModule)) {
191745
- if (!isObjectLike(value)) continue;
191746
- const candidate = value;
191747
- if (typeof candidate.name === "string" && candidate.name && typeof candidate.collection === "string" && candidate.collection && candidate.fields) {
191748
- entities.push({
191749
- name: candidate.name,
191750
- collection: candidate.collection,
191751
- // why: shape produced by defineEntity() in the app's entities barrel;
191752
- // fields/access are validated there, not re-validated here.
191753
- fields: candidate.fields,
191754
- access: candidate.access
191755
- });
191960
+ } else {
191961
+ try {
191962
+ const entityModule = await import(`file://${indexPath}`);
191963
+ for (const value of Object.values(entityModule)) {
191964
+ const entity = toLoadedEntity(value);
191965
+ if (entity) entities.push(entity);
191966
+ }
191967
+ } catch (err) {
191968
+ log2.error(`Failed to import entities:`, err);
191756
191969
  }
191757
191970
  }
191971
+ const features = await loadFeatureEntities(
191972
+ appDir,
191973
+ new Set(entities.map((entity) => entity.collection))
191974
+ );
191975
+ for (const { entity } of features) {
191976
+ const loaded = toLoadedEntity(entity);
191977
+ if (loaded) entities.push(loaded);
191978
+ }
191758
191979
  return entities;
191759
191980
  }
191760
191981
  function detectProvider(appDir) {
@@ -191951,7 +192172,7 @@ async function createDbContext(options = {}) {
191951
192172
  "Cannot detect database provider. Expected supabase/ or firebase.json in your app directory."
191952
192173
  );
191953
192174
  }
191954
- const entities2 = await loadEntities(projectRoot);
192175
+ const entities2 = await loadEntities(projectRoot, projectRoot);
191955
192176
  if (rootProvider === "firebase") {
191956
192177
  return createFirebaseContext(
191957
192178
  projectRoot,
@@ -191962,7 +192183,7 @@ async function createDbContext(options = {}) {
191962
192183
  }
191963
192184
  return createSupabaseContext(projectRoot, projectRoot, framework, entities2);
191964
192185
  }
191965
- const entities = await loadEntities(projectRoot);
192186
+ const entities = await loadEntities(projectRoot, appDir);
191966
192187
  if (provider === "firebase") {
191967
192188
  return createFirebaseContext(projectRoot, appDir, framework, entities);
191968
192189
  }