@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.
@@ -30678,6 +30678,314 @@ var init_dist9 = __esm({
30678
30678
  }
30679
30679
  });
30680
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
+
30681
30989
  // node_modules/.bun/extend@3.0.2/node_modules/extend/index.js
30682
30990
  var require_extend = __commonJS({
30683
30991
  "node_modules/.bun/extend@3.0.2/node_modules/extend/index.js"(exports, module) {
@@ -51163,199 +51471,6 @@ var init_app = __esm({
51163
51471
  }
51164
51472
  });
51165
51473
 
51166
- // packages/tooling/src/utils/supabase-management.ts
51167
- var supabase_management_exports = {};
51168
- __export(supabase_management_exports, {
51169
- MGMT_API_BASE: () => MGMT_API_BASE,
51170
- cleanupOldEntityMigrations: () => cleanupOldEntityMigrations,
51171
- deployEdgeFunction: () => deployEdgeFunction,
51172
- executeMigration: () => executeMigration,
51173
- extractProjectRef: () => extractProjectRef,
51174
- listEdgeFunctions: () => listEdgeFunctions,
51175
- tableExists: () => tableExists
51176
- });
51177
- function createAdminClient(supabaseUrl, secretKey) {
51178
- return createClient(supabaseUrl, secretKey, {
51179
- auth: {
51180
- autoRefreshToken: false,
51181
- persistSession: false
51182
- }
51183
- });
51184
- }
51185
- function extractProjectRef(supabaseUrl) {
51186
- const match = supabaseUrl.match(/https?:\/\/([a-z0-9]+)\.supabase\.co/);
51187
- if (!match?.[1]) {
51188
- throw new Error(
51189
- `Cannot extract project ref from URL: ${supabaseUrl}. Expected format: https://<ref>.supabase.co`
51190
- );
51191
- }
51192
- return match[1];
51193
- }
51194
- async function cleanupOldEntityMigrations(supabaseDir, latestFile) {
51195
- const migrationsDir = joinPath(supabaseDir, "migrations");
51196
- if (!pathExists(migrationsDir)) return;
51197
- let oldFiles;
51198
- try {
51199
- oldFiles = await findFiles(migrationsDir, "*_entity_tables.sql");
51200
- } catch {
51201
- return;
51202
- }
51203
- const latestBasename = getBasename(latestFile);
51204
- const toRemove = oldFiles.filter((f3) => getBasename(f3) !== latestBasename);
51205
- if (toRemove.length === 0) return;
51206
- for (const f3 of toRemove) {
51207
- try {
51208
- removeSync(f3);
51209
- } catch {
51210
- }
51211
- }
51212
- log2.info(`Cleaned up ${toRemove.length} old entity migration file(s)`);
51213
- }
51214
- async function executeMigration(options) {
51215
- const { supabaseDir, supabaseUrl, accessToken } = options;
51216
- if (!pathExists(supabaseDir)) {
51217
- throw new Error(`Supabase directory not found: ${supabaseDir}`);
51218
- }
51219
- const migrationsDir = joinPath(supabaseDir, "migrations");
51220
- if (!pathExists(migrationsDir)) {
51221
- throw new Error(`Migrations directory not found: ${migrationsDir}`);
51222
- }
51223
- const sqlFiles = readdirSync3(migrationsDir).filter((f3) => f3.endsWith(".sql")).sort().map((f3) => joinPath(migrationsDir, f3));
51224
- if (sqlFiles.length === 0) {
51225
- throw new Error(`No .sql files found in ${migrationsDir}`);
51226
- }
51227
- const sql = sqlFiles.map((f3) => asText(readSync(f3))).filter(Boolean).join("\n\n");
51228
- const projectRef = extractProjectRef(supabaseUrl);
51229
- const mgmtUrl = `https://api.supabase.com/v1/projects/${projectRef}/database/query`;
51230
- const response = await fetch(mgmtUrl, {
51231
- method: "POST",
51232
- headers: {
51233
- "Content-Type": "application/json",
51234
- Authorization: `Bearer ${accessToken}`
51235
- },
51236
- body: JSON.stringify({ query: sql })
51237
- });
51238
- if (!response.ok) {
51239
- const body = await response.text();
51240
- const safe = body.replace(/sbp_[^\s"']*/g, "***").replace(/sb_secret_[^\s"']*/g, "***");
51241
- throw new Error(
51242
- `Supabase Management API error (HTTP ${response.status}): ${safe}
51243
- Ensure SUPABASE_ACCESS_TOKEN is valid. Get one from: https://supabase.com/dashboard/account/tokens`
51244
- );
51245
- }
51246
- log2.info("Migrations executed via Supabase Management API");
51247
- }
51248
- async function tableExists(options) {
51249
- const { supabaseUrl, secretKey, tableName } = options;
51250
- try {
51251
- const supabase = createAdminClient(supabaseUrl, secretKey);
51252
- const { error: error2 } = await supabase.from(tableName).select("*").limit(0);
51253
- if (error2) {
51254
- if (error2.message?.includes("does not exist") || error2.code === "42P01" || error2.code === "PGRST116") {
51255
- return false;
51256
- }
51257
- log2.debug(`Error checking table existence: ${error2.message}`);
51258
- return false;
51259
- }
51260
- return true;
51261
- } catch (error2) {
51262
- log2.debug(
51263
- `Error checking if table ${tableName} exists: ${error2 instanceof Error ? error2.message : String(error2)}`
51264
- );
51265
- return false;
51266
- }
51267
- }
51268
- async function listEdgeFunctions(projectRef, accessToken) {
51269
- const url = `${MGMT_API_BASE}/projects/${projectRef}/functions`;
51270
- const response = await fetch(url, {
51271
- method: "GET",
51272
- headers: { Authorization: `Bearer ${accessToken}` }
51273
- });
51274
- if (!response.ok) {
51275
- const body = await response.text();
51276
- throw new Error(
51277
- `Failed to list Edge Functions (HTTP ${response.status}): ${body.slice(0, 500)}`
51278
- );
51279
- }
51280
- const functions = await response.json();
51281
- return functions.map((f3) => f3.slug);
51282
- }
51283
- async function deployEdgeFunction(options) {
51284
- const {
51285
- projectRef,
51286
- accessToken,
51287
- functionName,
51288
- functionsDir,
51289
- verifyJwt = false
51290
- } = options;
51291
- const buildPath = joinPath(functionsDir, ".build", `${functionName}.js`);
51292
- if (!pathExists(buildPath)) {
51293
- throw new Error(
51294
- `Pre-built edge function not found: ${buildPath}
51295
- Run \`dn build <app> supabase-functions\` before deploying.`
51296
- );
51297
- }
51298
- const sourceContent = asText(readSync(buildPath, { format: "text" }));
51299
- if (!sourceContent) {
51300
- throw new Error(`Empty build output: ${buildPath}`);
51301
- }
51302
- const existingSlugs = await listEdgeFunctions(projectRef, accessToken);
51303
- const exists = existingSlugs.includes(functionName);
51304
- if (exists) {
51305
- const url = `${MGMT_API_BASE}/projects/${projectRef}/functions/${functionName}`;
51306
- const response = await fetch(url, {
51307
- method: "PATCH",
51308
- headers: {
51309
- "Content-Type": "application/json",
51310
- Authorization: `Bearer ${accessToken}`
51311
- },
51312
- body: JSON.stringify({
51313
- body: sourceContent,
51314
- verify_jwt: verifyJwt
51315
- })
51316
- });
51317
- if (!response.ok) {
51318
- const body = await response.text();
51319
- throw new Error(
51320
- `Failed to update Edge Function "${functionName}" (HTTP ${response.status}): ${body.slice(0, 500)}`
51321
- );
51322
- }
51323
- } else {
51324
- const url = `${MGMT_API_BASE}/projects/${projectRef}/functions`;
51325
- const response = await fetch(url, {
51326
- method: "POST",
51327
- headers: {
51328
- "Content-Type": "application/json",
51329
- Authorization: `Bearer ${accessToken}`
51330
- },
51331
- body: JSON.stringify({
51332
- slug: functionName,
51333
- name: functionName,
51334
- body: sourceContent,
51335
- verify_jwt: verifyJwt
51336
- })
51337
- });
51338
- if (!response.ok) {
51339
- const body = await response.text();
51340
- throw new Error(
51341
- `Failed to create Edge Function "${functionName}" (HTTP ${response.status}): ${body.slice(0, 500)}`
51342
- );
51343
- }
51344
- }
51345
- }
51346
- var MGMT_API_BASE;
51347
- var init_supabase_management = __esm({
51348
- "packages/tooling/src/utils/supabase-management.ts"() {
51349
- "use strict";
51350
- init_utils2();
51351
- init_dist9();
51352
- init_cli_output();
51353
- init_pathResolver();
51354
- init_type_guards();
51355
- MGMT_API_BASE = "https://api.supabase.com/v1";
51356
- }
51357
- });
51358
-
51359
51474
  // packages/tooling/src/cli/setup/supabase.ts
51360
51475
  function isValidSupabaseUrl(url) {
51361
51476
  try {
@@ -51419,6 +51534,100 @@ var init_supabase = __esm({
51419
51534
  }
51420
51535
  });
51421
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
+
51422
51631
  // node_modules/.bun/firebase-admin@14.5.1+c188cf0323c41673/node_modules/firebase-admin/lib/firestore/error.js
51423
51632
  var require_error4 = __commonJS({
51424
51633
  "node_modules/.bun/firebase-admin@14.5.1+c188cf0323c41673/node_modules/firebase-admin/lib/firestore/error.js"(exports) {
@@ -191678,15 +191887,18 @@ var init_firestore = __esm({
191678
191887
  });
191679
191888
 
191680
191889
  // packages/tooling/src/utils/coreSemantics.ts
191681
- import { createRequire as createRequire4 } from "node:module";
191682
- import { pathToFileURL } from "node:url";
191890
+ import { createRequire as createRequire5 } from "node:module";
191891
+ import { pathToFileURL as pathToFileURL2 } from "node:url";
191683
191892
  function isFunction(value) {
191684
191893
  return typeof value === "function";
191685
191894
  }
191895
+ function isStringRecord(value) {
191896
+ return isRecord(value) && Object.values(value).every((entry) => typeof entry === "string");
191897
+ }
191686
191898
  async function loadCoreSemantics(fromFile2) {
191687
191899
  let resolved;
191688
191900
  try {
191689
- resolved = createRequire4(fromFile2).resolve("@donotdev/core/server");
191901
+ resolved = createRequire5(fromFile2).resolve("@donotdev/core/server");
191690
191902
  } catch (error2) {
191691
191903
  throw new DoNotDevError(
191692
191904
  `Cannot resolve @donotdev/core from ${fromFile2}: install it in the app (entities import it).`,
@@ -191694,10 +191906,10 @@ async function loadCoreSemantics(fromFile2) {
191694
191906
  { originalError: error2 instanceof Error ? error2 : void 0 }
191695
191907
  );
191696
191908
  }
191697
- const mod3 = await import(pathToFileURL(resolved).href);
191698
- if (!isRecord(mod3) || !isFunction(mod3.describeEntity) || !isFunction(mod3.createSchemas) || !Array.isArray(mod3.HIDDEN_STATUSES) || typeof mod3.DEFAULT_STATUS_VALUE !== "string") {
191909
+ const mod3 = await import(pathToFileURL2(resolved).href);
191910
+ if (!isRecord(mod3) || !isFunction(mod3.describeEntity) || !isFunction(mod3.createSchemas) || !Array.isArray(mod3.HIDDEN_STATUSES) || typeof mod3.DEFAULT_STATUS_VALUE !== "string" || typeof mod3.REMOVED_STATUS !== "string" || !isStringRecord(mod3.USER_ROLES) || !isStringRecord(mod3.SUBSCRIPTION_TIERS)) {
191699
191911
  throw new DoNotDevError(
191700
- `@donotdev/core at ${resolved} has no describeEntity / createSchemas / HIDDEN_STATUSES / DEFAULT_STATUS_VALUE: upgrade @donotdev/core.`,
191912
+ `@donotdev/core at ${resolved} has no describeEntity / createSchemas / HIDDEN_STATUSES / DEFAULT_STATUS_VALUE / REMOVED_STATUS / USER_ROLES / SUBSCRIPTION_TIERS: upgrade @donotdev/core.`,
191701
191913
  DO_NOT_DEV_ERROR_CODES.CONFIGURATION_ERROR
191702
191914
  );
191703
191915
  }
@@ -191708,7 +191920,11 @@ async function loadCoreSemantics(fromFile2) {
191708
191920
  describeEntity: (entity) => describeEntity(entity),
191709
191921
  createSchemas: (entity) => createSchemas(entity),
191710
191922
  hiddenStatuses: mod3.HIDDEN_STATUSES.map(String),
191711
- defaultStatus: mod3.DEFAULT_STATUS_VALUE
191923
+ defaultStatus: mod3.DEFAULT_STATUS_VALUE,
191924
+ removedStatus: mod3.REMOVED_STATUS,
191925
+ // Live objects, not copies: an override run by the app's modules is seen at SQL build
191926
+ userRoles: mod3.USER_ROLES,
191927
+ subscriptionTiers: mod3.SUBSCRIPTION_TIERS
191712
191928
  };
191713
191929
  }
191714
191930
  function schemaIssues(schema, value) {
@@ -191752,44 +191968,53 @@ init_utils2();
191752
191968
  // packages/tooling/src/db/context.ts
191753
191969
  init_utils2();
191754
191970
  init_supabase();
191971
+ init_frameworkEntities();
191755
191972
  init_app_selector();
191756
191973
  init_cli_output();
191757
191974
  init_pathResolver();
191758
191975
  init_secrets_resolver();
191759
191976
  init_type_guards();
191760
- async function loadEntities(projectRoot) {
191977
+ function toLoadedEntity(value) {
191978
+ if (!isObjectLike(value)) return null;
191979
+ if (typeof value.name === "string" && value.name && typeof value.collection === "string" && value.collection && value.fields) {
191980
+ return {
191981
+ name: value.name,
191982
+ collection: value.collection,
191983
+ // why: shape produced by defineEntity() (the app's entities barrel or a framework
191984
+ // feature's entities module); fields/access are validated there, not re-validated here.
191985
+ fields: value.fields,
191986
+ access: value.access
191987
+ };
191988
+ }
191989
+ return null;
191990
+ }
191991
+ async function loadEntities(projectRoot, appDir) {
191992
+ const entities = [];
191761
191993
  const entitiesDir = joinPath(projectRoot, "entities");
191994
+ const indexPath = joinPath(entitiesDir, "index.ts");
191762
191995
  if (!pathExists(entitiesDir)) {
191763
191996
  log2.warn("No entities/ directory found");
191764
- return [];
191765
- }
191766
- const indexPath = joinPath(entitiesDir, "index.ts");
191767
- if (!pathExists(indexPath)) {
191997
+ } else if (!pathExists(indexPath)) {
191768
191998
  log2.warn("No entities/index.ts found");
191769
- return [];
191770
- }
191771
- let entityModule;
191772
- try {
191773
- entityModule = await import(`file://${indexPath}`);
191774
- } catch (err) {
191775
- log2.error(`Failed to import entities:`, err);
191776
- return [];
191777
- }
191778
- const entities = [];
191779
- for (const [key, value] of Object.entries(entityModule)) {
191780
- if (!isObjectLike(value)) continue;
191781
- const candidate = value;
191782
- if (typeof candidate.name === "string" && candidate.name && typeof candidate.collection === "string" && candidate.collection && candidate.fields) {
191783
- entities.push({
191784
- name: candidate.name,
191785
- collection: candidate.collection,
191786
- // why: shape produced by defineEntity() in the app's entities barrel;
191787
- // fields/access are validated there, not re-validated here.
191788
- fields: candidate.fields,
191789
- access: candidate.access
191790
- });
191999
+ } else {
192000
+ try {
192001
+ const entityModule = await import(`file://${indexPath}`);
192002
+ for (const value of Object.values(entityModule)) {
192003
+ const entity = toLoadedEntity(value);
192004
+ if (entity) entities.push(entity);
192005
+ }
192006
+ } catch (err) {
192007
+ log2.error(`Failed to import entities:`, err);
191791
192008
  }
191792
192009
  }
192010
+ const features = await loadFeatureEntities(
192011
+ appDir,
192012
+ new Set(entities.map((entity) => entity.collection))
192013
+ );
192014
+ for (const { entity } of features) {
192015
+ const loaded = toLoadedEntity(entity);
192016
+ if (loaded) entities.push(loaded);
192017
+ }
191793
192018
  return entities;
191794
192019
  }
191795
192020
  function detectProvider(appDir) {
@@ -191986,7 +192211,7 @@ async function createDbContext(options = {}) {
191986
192211
  "Cannot detect database provider. Expected supabase/ or firebase.json in your app directory."
191987
192212
  );
191988
192213
  }
191989
- const entities2 = await loadEntities(projectRoot);
192214
+ const entities2 = await loadEntities(projectRoot, projectRoot);
191990
192215
  if (rootProvider === "firebase") {
191991
192216
  return createFirebaseContext(
191992
192217
  projectRoot,
@@ -191997,7 +192222,7 @@ async function createDbContext(options = {}) {
191997
192222
  }
191998
192223
  return createSupabaseContext(projectRoot, projectRoot, framework, entities2);
191999
192224
  }
192000
- const entities = await loadEntities(projectRoot);
192225
+ const entities = await loadEntities(projectRoot, appDir);
192001
192226
  if (provider === "firebase") {
192002
192227
  return createFirebaseContext(projectRoot, appDir, framework, entities);
192003
192228
  }