@donotdev/cli 0.3.7 → 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.
@@ -10008,11 +10008,19 @@ var init_command_registry = __esm({
10008
10008
  },
10009
10009
  {
10010
10010
  flags: "--output-dir <dir>",
10011
- description: "output directory for migrations (default: supabase/migrations)"
10011
+ description: "output directory for migrations (default: supabase/migrations of the app the command runs for: the nearest folder up with supabase/config.toml, or the only app with one under apps/; fails when none)"
10012
10012
  },
10013
10013
  {
10014
10014
  flags: "--no-single-file",
10015
10015
  description: "emit one migration file per entity"
10016
+ },
10017
+ {
10018
+ flags: "--only <collections...>",
10019
+ description: "emit only these collections into ONE new migration <version>_<first>[_and_more].sql (version: now, or the latest existing + 1 so it sorts last); never touches *_entity_tables.sql (for a live app adding a feature's entities; feature-owned collections accepted)"
10020
+ },
10021
+ {
10022
+ flags: "--app-dir <dir>",
10023
+ description: "app folder whose src/config/app.ts turns framework features on (their entities are included when installed; default: the app of the output dir)"
10016
10024
  }
10017
10025
  ],
10018
10026
  loader: "../generators/sql-generator.ts"
@@ -11881,6 +11889,120 @@ var init_firebase = __esm({
11881
11889
  }
11882
11890
  });
11883
11891
 
11892
+ // packages/tooling/src/generators/frameworkEntities.ts
11893
+ var frameworkEntities_exports = {};
11894
+ __export(frameworkEntities_exports, {
11895
+ APP_CONFIG_FILE: () => APP_CONFIG_FILE,
11896
+ FRAMEWORK_ENTITY_FEATURES: () => FRAMEWORK_ENTITY_FEATURES,
11897
+ appDirOfMigrations: () => appDirOfMigrations,
11898
+ enabledEntityFeatures: () => enabledEntityFeatures,
11899
+ loadFeatureEntities: () => loadFeatureEntities,
11900
+ readAppConfig: () => readAppConfig
11901
+ });
11902
+ import { createRequire as createRequire5 } from "node:module";
11903
+ import { pathToFileURL } from "node:url";
11904
+ function valueAt(config, path) {
11905
+ let value = config;
11906
+ for (const key of path) {
11907
+ if (!isRecord(value)) return void 0;
11908
+ value = value[key];
11909
+ }
11910
+ return value;
11911
+ }
11912
+ function isEntityExport(value) {
11913
+ return isObjectLike(value) && typeof value.name === "string" && value.name !== "" && typeof value.collection === "string" && value.collection !== "" && isRecord(value.fields);
11914
+ }
11915
+ async function readAppConfig(appDir) {
11916
+ const file = joinPath(appDir, ...APP_CONFIG_FILE);
11917
+ if (!pathExists(file, true)) return null;
11918
+ const mod = await import(pathToFileURL(file).href);
11919
+ const appConfig = isRecord(mod) ? mod.appConfig : void 0;
11920
+ if (!isRecord(appConfig)) {
11921
+ throw new DoNotDevError(
11922
+ `${file} does not export an appConfig object (export const appConfig: AppConfig = { \u2026 }).`,
11923
+ DO_NOT_DEV_ERROR_CODES.CONFIGURATION_ERROR
11924
+ );
11925
+ }
11926
+ return appConfig;
11927
+ }
11928
+ function isEnabled(appConfig, feature) {
11929
+ const setting = valueAt(appConfig, feature.configPath);
11930
+ return setting !== void 0 && setting !== null && setting !== false;
11931
+ }
11932
+ async function enabledEntityFeatures(appDir, features = FRAMEWORK_ENTITY_FEATURES) {
11933
+ const appConfig = await readAppConfig(appDir);
11934
+ return appConfig ? features.filter((feature) => isEnabled(appConfig, feature)) : [];
11935
+ }
11936
+ async function loadFeatureEntities(appDir, exclude = /* @__PURE__ */ new Set(), features = FRAMEWORK_ENTITY_FEATURES) {
11937
+ if (!appDir) {
11938
+ log2.info("App folder unknown: framework feature entities skipped (pass --app-dir).");
11939
+ return [];
11940
+ }
11941
+ const appConfig = await readAppConfig(appDir);
11942
+ if (!appConfig) {
11943
+ log2.info(
11944
+ `No ${APP_CONFIG_FILE.join("/")} in ${appDir}: framework feature entities skipped.`
11945
+ );
11946
+ return [];
11947
+ }
11948
+ const configFile = joinPath(appDir, ...APP_CONFIG_FILE);
11949
+ const found = [];
11950
+ for (const feature of features) {
11951
+ if (!isEnabled(appConfig, feature)) continue;
11952
+ let resolved;
11953
+ try {
11954
+ resolved = createRequire5(configFile).resolve(feature.module);
11955
+ } catch {
11956
+ log2.warn(
11957
+ `Feature ${feature.name} is on (appConfig.${feature.configPath.join(".")}) but ${feature.packageName} is not installed in ${appDir}: its tables are skipped. Install ${feature.packageName}.`
11958
+ );
11959
+ continue;
11960
+ }
11961
+ const mod = await import(pathToFileURL(resolved).href);
11962
+ if (!isRecord(mod)) continue;
11963
+ const seen = /* @__PURE__ */ new Set();
11964
+ for (const value of Object.values(mod)) {
11965
+ if (!isEntityExport(value) || seen.has(value.collection)) continue;
11966
+ seen.add(value.collection);
11967
+ if (exclude.has(value.collection)) {
11968
+ log2.info(
11969
+ `${value.collection}: defined by the app's entity files and by feature ${feature.name}; one table.`
11970
+ );
11971
+ continue;
11972
+ }
11973
+ found.push({ entity: value, feature: feature.name, path: resolved });
11974
+ }
11975
+ }
11976
+ return found;
11977
+ }
11978
+ function appDirOfMigrations(migrationsDir) {
11979
+ const parts = migrationsDir.replace(/\\/g, "/").replace(/\/+$/, "").split("/");
11980
+ if (parts.length < 3 || parts.at(-1) !== "migrations" || parts.at(-2) !== "supabase") {
11981
+ return void 0;
11982
+ }
11983
+ return parts.slice(0, -2).join("/") || "/";
11984
+ }
11985
+ var FRAMEWORK_ENTITY_FEATURES, APP_CONFIG_FILE;
11986
+ var init_frameworkEntities = __esm({
11987
+ "packages/tooling/src/generators/frameworkEntities.ts"() {
11988
+ "use strict";
11989
+ init_utils2();
11990
+ init_cli_output();
11991
+ init_errors();
11992
+ init_pathResolver();
11993
+ init_type_guards();
11994
+ FRAMEWORK_ENTITY_FEATURES = [
11995
+ {
11996
+ name: "chatbot",
11997
+ configPath: ["ai", "chatbot"],
11998
+ module: "@donotdev/ai/entities",
11999
+ packageName: "@donotdev/ai"
12000
+ }
12001
+ ];
12002
+ APP_CONFIG_FILE = ["src", "config", "app.ts"];
12003
+ }
12004
+ });
12005
+
11884
12006
  // packages/tooling/src/generators/base-generator.ts
11885
12007
  var __dirname2, BaseGenerator;
11886
12008
  var init_base_generator = __esm({
@@ -12472,25 +12594,6 @@ var init_base_generator = __esm({
12472
12594
  }
12473
12595
  });
12474
12596
 
12475
- // packages/providers/supabase/src/common/checkConstraints.ts
12476
- function checkConstraintName(table, column, rule) {
12477
- const name = `${table}_${column}_${rule}`;
12478
- if (new TextEncoder().encode(name).length > MAX_IDENTIFIER_LENGTH) {
12479
- throw new Error(
12480
- `CHECK constraint name "${name}" exceeds ${MAX_IDENTIFIER_LENGTH} bytes: shorten the table or column name`
12481
- );
12482
- }
12483
- return name;
12484
- }
12485
- var MAX_IDENTIFIER_LENGTH;
12486
- var init_checkConstraints = __esm({
12487
- "packages/providers/supabase/src/common/checkConstraints.ts"() {
12488
- "use strict";
12489
- init_utils2();
12490
- MAX_IDENTIFIER_LENGTH = 63;
12491
- }
12492
- });
12493
-
12494
12597
  // packages/tooling/src/generators/pgRegex.ts
12495
12598
  function toPostgresRegex(regex) {
12496
12599
  const source = typeof regex === "string" ? regex : regex.source;
@@ -12637,6 +12740,25 @@ var init_pgRegex = __esm({
12637
12740
  }
12638
12741
  });
12639
12742
 
12743
+ // packages/providers/supabase/src/common/checkConstraints.ts
12744
+ function checkConstraintName(table, column, rule) {
12745
+ const name = `${table}_${column}_${rule}`;
12746
+ if (new TextEncoder().encode(name).length > MAX_IDENTIFIER_LENGTH) {
12747
+ throw new Error(
12748
+ `CHECK constraint name "${name}" exceeds ${MAX_IDENTIFIER_LENGTH} bytes: shorten the table or column name`
12749
+ );
12750
+ }
12751
+ return name;
12752
+ }
12753
+ var MAX_IDENTIFIER_LENGTH;
12754
+ var init_checkConstraints = __esm({
12755
+ "packages/providers/supabase/src/common/checkConstraints.ts"() {
12756
+ "use strict";
12757
+ init_utils2();
12758
+ MAX_IDENTIFIER_LENGTH = 63;
12759
+ }
12760
+ });
12761
+
12640
12762
  // packages/tooling/src/generators/sqlChecks.ts
12641
12763
  function camelToSnake(str) {
12642
12764
  return str.replace(/[A-Z]/g, (c3) => `_${c3.toLowerCase()}`);
@@ -12916,16 +13038,154 @@ var init_sqlChecks = __esm({
12916
13038
  }
12917
13039
  });
12918
13040
 
13041
+ // packages/tooling/src/generators/sqlUniqueKeys.ts
13042
+ function camelToSnake2(str) {
13043
+ return str.replace(/[A-Z]/g, (c3) => `_${c3.toLowerCase()}`);
13044
+ }
13045
+ function shortHash(text2) {
13046
+ let hash = 2166136261;
13047
+ for (let i2 = 0; i2 < text2.length; i2++) {
13048
+ hash ^= text2.charCodeAt(i2);
13049
+ hash = Math.imul(hash, 16777619) >>> 0;
13050
+ }
13051
+ return hash.toString(16).padStart(8, "0");
13052
+ }
13053
+ function indexName(table, columns) {
13054
+ const name = `${table}_${columns.join("_")}_unique`;
13055
+ if (name.length <= MAX_IDENTIFIER) return name;
13056
+ return `${name.slice(0, MAX_IDENTIFIER - 9)}_${shortHash(name)}`;
13057
+ }
13058
+ function uniqueKeysOf(entity) {
13059
+ const keys = entity.uniqueKeys;
13060
+ if (keys === void 0) return [];
13061
+ if (!Array.isArray(keys)) {
13062
+ throw new DoNotDevError(
13063
+ `${String(entity.name)}: uniqueKeys must be an array`,
13064
+ DO_NOT_DEV_ERROR_CODES.GENERATION_ERROR
13065
+ );
13066
+ }
13067
+ return keys.map((key, index) => {
13068
+ if (!isRecord(key) || !Array.isArray(key.fields) || key.fields.length === 0 || !key.fields.every((f) => typeof f === "string")) {
13069
+ throw new DoNotDevError(
13070
+ `${String(entity.name)}: uniqueKeys[${index}].fields must be a non-empty list of field names`,
13071
+ DO_NOT_DEV_ERROR_CODES.GENERATION_ERROR
13072
+ );
13073
+ }
13074
+ return { fields: key.fields, skipForDrafts: key.skipForDrafts === true };
13075
+ });
13076
+ }
13077
+ function uniqueIndexesOf(entity, descriptor, removedStatus) {
13078
+ return uniqueKeysOf(entity).map((key) => {
13079
+ const columns = [];
13080
+ const expressions = [];
13081
+ const predicates = [];
13082
+ for (const field of key.fields) {
13083
+ const described = descriptor.fields[field];
13084
+ if (!described) {
13085
+ throw new DoNotDevError(
13086
+ `${String(entity.name)}: uniqueKeys field '${field}' is not a field of the entity`,
13087
+ DO_NOT_DEV_ERROR_CODES.GENERATION_ERROR
13088
+ );
13089
+ }
13090
+ const column = camelToSnake2(field);
13091
+ columns.push(column);
13092
+ if (described.value.kind === "text") {
13093
+ expressions.push(`lower(${column})`);
13094
+ predicates.push(`${column} <> ''`);
13095
+ } else {
13096
+ expressions.push(column);
13097
+ }
13098
+ }
13099
+ const excluded = key.skipForDrafts ? [removedStatus, "draft"] : [removedStatus];
13100
+ predicates.push(
13101
+ excluded.length === 1 ? `status <> ${sqlText(excluded[0])}` : `status NOT IN (${excluded.map(sqlText).join(", ")})`
13102
+ );
13103
+ const where = predicates.join(" AND ");
13104
+ const keyList = expressions.join(", ");
13105
+ return {
13106
+ name: indexName(entity.collection, columns),
13107
+ definition: `(${keyList}) WHERE ${where}`,
13108
+ fields: key.fields,
13109
+ duplicatesQuery: `SELECT ${keyList}, count(*) AS row_count, array_agg(id) AS ids FROM public."${entity.collection}" WHERE ${where} GROUP BY ${keyList} HAVING count(*) > 1;`
13110
+ };
13111
+ });
13112
+ }
13113
+ function uniqueIndexesSql(table, indexes) {
13114
+ const blocks = indexes.map(({ name, definition, fields, duplicatesQuery }) => {
13115
+ const comment = sqlText(`${UNIQUE_INDEX_COMMENT_PREFIX}${definition}`);
13116
+ return `-- Unique key ${name}: ${definition}
13117
+ DO $dndev_unique$
13118
+ DECLARE
13119
+ existing text;
13120
+ BEGIN
13121
+ SELECT coalesce(obj_description(c.oid, 'pg_class'), '') INTO existing
13122
+ FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
13123
+ WHERE n.nspname = 'public' AND c.relname = ${sqlText(name)};
13124
+ IF FOUND THEN
13125
+ IF existing = ${comment} THEN
13126
+ RETURN;
13127
+ ELSIF existing NOT LIKE ${sqlText(`${UNIQUE_INDEX_COMMENT_PREFIX}%`)} THEN
13128
+ RAISE WARNING '%: an index of that name exists and was not generated from uniqueKeys; left as is.', ${sqlText(name)};
13129
+ RETURN;
13130
+ END IF;
13131
+ EXECUTE 'DROP INDEX public.${name}';
13132
+ END IF;
13133
+ BEGIN
13134
+ CREATE UNIQUE INDEX IF NOT EXISTS ${name} ON public."${table}" ${definition};
13135
+ EXCEPTION WHEN unique_violation THEN
13136
+ RAISE EXCEPTION 'Table % has rows sharing the unique key (%) of its entity: unique index % cannot be created. List them with: % Then remove or change the duplicates and re-run this migration.',
13137
+ ${sqlText(table)}, ${sqlText(fields.join(", "))}, ${sqlText(name)}, ${sqlText(duplicatesQuery)}
13138
+ USING ERRCODE = 'unique_violation';
13139
+ END;
13140
+ COMMENT ON INDEX public.${name} IS ${comment};
13141
+ END $dndev_unique$;`;
13142
+ });
13143
+ const kept = indexes.map(({ name }) => sqlText(name)).join(", ");
13144
+ blocks.push(`-- Unique keys no longer declared by ${table}: their framework indexes are dropped (no data change)
13145
+ DO $dndev_unique$
13146
+ DECLARE
13147
+ stale record;
13148
+ BEGIN
13149
+ FOR stale IN
13150
+ SELECT c.relname FROM pg_index i
13151
+ JOIN pg_class c ON c.oid = i.indexrelid
13152
+ JOIN pg_class t ON t.oid = i.indrelid
13153
+ JOIN pg_namespace n ON n.oid = t.relnamespace
13154
+ WHERE n.nspname = 'public' AND t.relname = ${sqlText(table)}
13155
+ AND obj_description(c.oid, 'pg_class') LIKE ${sqlText(`${UNIQUE_INDEX_COMMENT_PREFIX}%`)}
13156
+ AND c.relname <> ALL (ARRAY[${kept}]::text[])
13157
+ LOOP
13158
+ EXECUTE format('DROP INDEX public.%I', stale.relname);
13159
+ END LOOP;
13160
+ END $dndev_unique$;`);
13161
+ return blocks.join("\n\n");
13162
+ }
13163
+ var UNIQUE_INDEX_COMMENT_PREFIX, MAX_IDENTIFIER;
13164
+ var init_sqlUniqueKeys = __esm({
13165
+ "packages/tooling/src/generators/sqlUniqueKeys.ts"() {
13166
+ "use strict";
13167
+ init_utils2();
13168
+ init_sqlChecks();
13169
+ init_errors();
13170
+ init_type_guards();
13171
+ UNIQUE_INDEX_COMMENT_PREFIX = "dndev:unique:";
13172
+ MAX_IDENTIFIER = 63;
13173
+ }
13174
+ });
13175
+
12919
13176
  // packages/tooling/src/utils/coreSemantics.ts
12920
- import { createRequire as createRequire5 } from "node:module";
12921
- import { pathToFileURL } from "node:url";
13177
+ import { createRequire as createRequire6 } from "node:module";
13178
+ import { pathToFileURL as pathToFileURL2 } from "node:url";
12922
13179
  function isFunction(value) {
12923
13180
  return typeof value === "function";
12924
13181
  }
13182
+ function isStringRecord(value) {
13183
+ return isRecord(value) && Object.values(value).every((entry) => typeof entry === "string");
13184
+ }
12925
13185
  async function loadCoreSemantics(fromFile) {
12926
13186
  let resolved;
12927
13187
  try {
12928
- resolved = createRequire5(fromFile).resolve("@donotdev/core/server");
13188
+ resolved = createRequire6(fromFile).resolve("@donotdev/core/server");
12929
13189
  } catch (error2) {
12930
13190
  throw new DoNotDevError(
12931
13191
  `Cannot resolve @donotdev/core from ${fromFile}: install it in the app (entities import it).`,
@@ -12933,10 +13193,10 @@ async function loadCoreSemantics(fromFile) {
12933
13193
  { originalError: error2 instanceof Error ? error2 : void 0 }
12934
13194
  );
12935
13195
  }
12936
- const mod = await import(pathToFileURL(resolved).href);
12937
- if (!isRecord(mod) || !isFunction(mod.describeEntity) || !isFunction(mod.createSchemas) || !Array.isArray(mod.HIDDEN_STATUSES) || typeof mod.DEFAULT_STATUS_VALUE !== "string") {
13196
+ const mod = await import(pathToFileURL2(resolved).href);
13197
+ if (!isRecord(mod) || !isFunction(mod.describeEntity) || !isFunction(mod.createSchemas) || !Array.isArray(mod.HIDDEN_STATUSES) || typeof mod.DEFAULT_STATUS_VALUE !== "string" || typeof mod.REMOVED_STATUS !== "string" || !isStringRecord(mod.USER_ROLES) || !isStringRecord(mod.SUBSCRIPTION_TIERS)) {
12938
13198
  throw new DoNotDevError(
12939
- `@donotdev/core at ${resolved} has no describeEntity / createSchemas / HIDDEN_STATUSES / DEFAULT_STATUS_VALUE: upgrade @donotdev/core.`,
13199
+ `@donotdev/core at ${resolved} has no describeEntity / createSchemas / HIDDEN_STATUSES / DEFAULT_STATUS_VALUE / REMOVED_STATUS / USER_ROLES / SUBSCRIPTION_TIERS: upgrade @donotdev/core.`,
12940
13200
  DO_NOT_DEV_ERROR_CODES.CONFIGURATION_ERROR
12941
13201
  );
12942
13202
  }
@@ -12947,7 +13207,11 @@ async function loadCoreSemantics(fromFile) {
12947
13207
  describeEntity: (entity) => describeEntity(entity),
12948
13208
  createSchemas: (entity) => createSchemas(entity),
12949
13209
  hiddenStatuses: mod.HIDDEN_STATUSES.map(String),
12950
- defaultStatus: mod.DEFAULT_STATUS_VALUE
13210
+ defaultStatus: mod.DEFAULT_STATUS_VALUE,
13211
+ removedStatus: mod.REMOVED_STATUS,
13212
+ // Live objects, not copies: an override run by the app's modules is seen at SQL build
13213
+ userRoles: mod.USER_ROLES,
13214
+ subscriptionTiers: mod.SUBSCRIPTION_TIERS
12951
13215
  };
12952
13216
  }
12953
13217
  var init_coreSemantics = __esm({
@@ -12963,11 +13227,117 @@ var init_coreSemantics = __esm({
12963
13227
  var sql_generator_exports = {};
12964
13228
  __export(sql_generator_exports, {
12965
13229
  SqlGenerator: () => SqlGenerator,
12966
- main: () => main2
13230
+ accessNames: () => accessNames,
13231
+ auditFieldsFunctionSql: () => auditFieldsFunctionSql,
13232
+ createRateLimitFunctionSql: () => createRateLimitFunctionSql,
13233
+ main: () => main2,
13234
+ nextMigrationVersion: () => nextMigrationVersion,
13235
+ resolveMigrationsDir: () => resolveMigrationsDir,
13236
+ rowAudienceFunctionsSql: () => rowAudienceFunctionsSql
12967
13237
  });
12968
13238
  function isSqlEntity(value) {
12969
13239
  return isObjectLike(value) && !!value.name && typeof value.collection === "string" && value.collection !== "";
12970
13240
  }
13241
+ function accessNames(core) {
13242
+ const names = {
13243
+ guestRole: core.userRoles["GUEST"],
13244
+ userRole: core.userRoles["USER"],
13245
+ freeTier: core.subscriptionTiers["FREE"]
13246
+ };
13247
+ for (const [key, value] of Object.entries(names)) {
13248
+ if (typeof value !== "string" || value === "") {
13249
+ throw new DoNotDevError(
13250
+ `@donotdev/core USER_ROLES.GUEST / USER_ROLES.USER / SUBSCRIPTION_TIERS.FREE must be non-empty strings (${key} is ${JSON.stringify(value)})`,
13251
+ DO_NOT_DEV_ERROR_CODES.CONFIGURATION_ERROR
13252
+ );
13253
+ }
13254
+ }
13255
+ return names;
13256
+ }
13257
+ function rowAudienceFunctionsSql(names) {
13258
+ const iso = sqlText(toPostgresRegex(ISO_TIMESTAMP_SOURCE));
13259
+ return `-- Framework row audience: the caller's role and subscription tier from the session claims
13260
+ CREATE OR REPLACE FUNCTION public.dndev_user_role()
13261
+ RETURNS text
13262
+ LANGUAGE sql STABLE
13263
+ SET search_path = ''
13264
+ AS $$
13265
+ SELECT CASE
13266
+ WHEN auth.uid() IS NULL THEN ${sqlText(names.guestRole)}
13267
+ ELSE coalesce(nullif(auth.jwt() -> 'app_metadata' ->> 'role', ''), ${sqlText(names.userRole)})
13268
+ END
13269
+ $$;
13270
+
13271
+ CREATE OR REPLACE FUNCTION public.dndev_subscription_tier()
13272
+ RETURNS text
13273
+ LANGUAGE sql STABLE
13274
+ SET search_path = ''
13275
+ AS $$
13276
+ SELECT CASE
13277
+ WHEN auth.uid() IS NULL OR s IS NULL OR jsonb_typeof(s) = 'null' THEN ${sqlText(names.freeTier)}
13278
+ WHEN jsonb_typeof(s) = 'object'
13279
+ AND jsonb_typeof(s -> 'tier') = 'string'
13280
+ AND jsonb_typeof(s -> 'status') = 'string'
13281
+ AND (jsonb_typeof(s -> 'subscriptionEnd') = 'null'
13282
+ OR (jsonb_typeof(s -> 'subscriptionEnd') = 'string' AND (s ->> 'subscriptionEnd') ~ ${iso}))
13283
+ AND jsonb_typeof(s -> 'updatedAt') = 'string' AND (s ->> 'updatedAt') ~ ${iso}
13284
+ AND (NOT s ? 'isDefault' OR jsonb_typeof(s -> 'isDefault') = 'boolean')
13285
+ AND (NOT s ? 'cancelAtPeriodEnd' OR jsonb_typeof(s -> 'cancelAtPeriodEnd') = 'boolean')
13286
+ AND (NOT s ? 'subscriptionId' OR jsonb_typeof(s -> 'subscriptionId') IN ('string', 'null'))
13287
+ AND (NOT s ? 'customerId' OR jsonb_typeof(s -> 'customerId') IN ('string', 'null'))
13288
+ AND (NOT s ? 'features' OR (jsonb_typeof(s -> 'features') = 'array'
13289
+ AND NOT EXISTS (SELECT 1 FROM jsonb_array_elements(s -> 'features') AS f(v) WHERE jsonb_typeof(f.v) <> 'string')))
13290
+ THEN s ->> 'tier'
13291
+ END
13292
+ FROM (SELECT auth.jwt() -> 'app_metadata' -> 'subscription' AS s) AS claims
13293
+ $$;
13294
+ `;
13295
+ }
13296
+ function createRateLimitFunctionSql() {
13297
+ return `-- Framework create rate limit (Entity.rateLimit.create), through public.rate_limit_check
13298
+ CREATE OR REPLACE FUNCTION public.dndev_create_rate_limit()
13299
+ RETURNS trigger
13300
+ LANGUAGE plpgsql
13301
+ SECURITY DEFINER
13302
+ SET search_path = ''
13303
+ AS $$
13304
+ DECLARE
13305
+ caller uuid;
13306
+ headers json;
13307
+ forwarded text[];
13308
+ client_ip text;
13309
+ limit_result jsonb;
13310
+ BEGIN
13311
+ IF coalesce(current_setting('role', true), 'none') NOT IN ('anon', 'authenticated') THEN
13312
+ RETURN NEW;
13313
+ END IF;
13314
+ caller := auth.uid();
13315
+ IF caller IS NULL THEN
13316
+ headers := nullif(current_setting('request.headers', true), '')::json;
13317
+ forwarded := string_to_array(headers ->> 'x-forwarded-for', ',');
13318
+ client_ip := nullif(btrim(forwarded[cardinality(forwarded)]), '');
13319
+ IF client_ip IS NULL OR client_ip !~ ${CLIENT_IP_PATTERN} THEN
13320
+ client_ip := nullif(btrim(headers ->> 'cf-connecting-ip'), '');
13321
+ IF client_ip IS NULL OR client_ip !~ ${CLIENT_IP_PATTERN} THEN
13322
+ client_ip := 'unknown';
13323
+ END IF;
13324
+ END IF;
13325
+ END IF;
13326
+ limit_result := public.rate_limit_check(
13327
+ TG_TABLE_NAME || ':create:' || CASE WHEN caller IS NOT NULL THEN 'uid:' || caller::text ELSE 'ip:' || client_ip END,
13328
+ TG_ARGV[0]::int + 1,
13329
+ TG_ARGV[1]::bigint * 1000,
13330
+ TG_ARGV[1]::bigint * 1000
13331
+ );
13332
+ IF NOT (limit_result ->> 'allowed')::boolean THEN
13333
+ RAISE EXCEPTION '%_create_rate_limited: at most % creates per % seconds', TG_TABLE_NAME, TG_ARGV[0], TG_ARGV[1]
13334
+ USING ERRCODE = 'PT429';
13335
+ END IF;
13336
+ RETURN NEW;
13337
+ END;
13338
+ $$;
13339
+ `;
13340
+ }
12971
13341
  function roleToSqlCondition(role) {
12972
13342
  switch (role) {
12973
13343
  case "guest":
@@ -12985,7 +13355,80 @@ function roleToSqlCondition(role) {
12985
13355
  return "false";
12986
13356
  }
12987
13357
  }
12988
- function camelToSnake2(str) {
13358
+ function rowAudienceConditions(rowAudience) {
13359
+ if (!rowAudience) return [];
13360
+ const conditions = [];
13361
+ if (rowAudience.role) {
13362
+ conditions.push(`${camelToSnake3(rowAudience.role)} = (SELECT public.dndev_user_role())`);
13363
+ }
13364
+ if (rowAudience.tier) {
13365
+ conditions.push(`${camelToSnake3(rowAudience.tier)} = (SELECT public.dndev_subscription_tier())`);
13366
+ }
13367
+ return conditions;
13368
+ }
13369
+ function usesRowAudience(entities) {
13370
+ return entities.some((entity) => rowAudienceConditions(entity.access?.rowAudience).length > 0);
13371
+ }
13372
+ function usesCreateRateLimit(entities) {
13373
+ return entities.some((entity) => entity.rateLimit?.create !== void 0);
13374
+ }
13375
+ function migrationStamp(now = /* @__PURE__ */ new Date()) {
13376
+ return now.getFullYear() + String(now.getMonth() + 1).padStart(2, "0") + String(now.getDate()).padStart(2, "0") + String(now.getHours()).padStart(2, "0") + String(now.getMinutes()).padStart(2, "0") + String(now.getSeconds()).padStart(2, "0");
13377
+ }
13378
+ function resolveMigrationsDir(startDir) {
13379
+ let dir = normalizePath(startDir);
13380
+ for (; ; ) {
13381
+ if (isSupabaseApp(dir)) return joinPath(dir, "supabase", "migrations");
13382
+ const appsDir = joinPath(dir, "apps");
13383
+ if (pathExists(appsDir, true)) {
13384
+ const apps = readdirSync3(appsDir, { withFileTypes: true }).filter((entry) => entry.isDirectory() && isSupabaseApp(joinPath(appsDir, entry.name))).map((entry) => entry.name).sort();
13385
+ if (apps.length === 1) return joinPath(appsDir, apps[0], "supabase", "migrations");
13386
+ throw new DoNotDevError(
13387
+ apps.length === 0 ? `No Supabase app (apps/<app>/supabase/config.toml) under ${dir}. Run from an app folder or pass --output-dir.` : `Several Supabase apps under ${dir}: ${apps.join(", ")}. Run from the app folder or pass --output-dir.`,
13388
+ DO_NOT_DEV_ERROR_CODES.GENERATION_ERROR
13389
+ );
13390
+ }
13391
+ const parent = getDirname(dir);
13392
+ if (parent === dir) break;
13393
+ dir = parent;
13394
+ }
13395
+ throw new DoNotDevError(
13396
+ `No Supabase app found from ${startDir} (no supabase/config.toml in it or above). Run from the app folder or pass --output-dir.`,
13397
+ DO_NOT_DEV_ERROR_CODES.GENERATION_ERROR
13398
+ );
13399
+ }
13400
+ function nextMigrationVersion(dir, now = /* @__PURE__ */ new Date()) {
13401
+ let latest = BigInt(migrationStamp(now));
13402
+ if (pathExists(dir, true)) {
13403
+ for (const file of readdirSync3(dir)) {
13404
+ const version = /^(\d+)_.*\.sql$/.exec(file)?.[1];
13405
+ if (version && BigInt(version) >= latest) latest = BigInt(version) + 1n;
13406
+ }
13407
+ }
13408
+ return String(latest);
13409
+ }
13410
+ function auditFieldsFunctionSql(functionName) {
13411
+ return `CREATE OR REPLACE FUNCTION ${functionName}()
13412
+ RETURNS TRIGGER AS $$
13413
+ BEGIN
13414
+ IF current_user IN ('anon', 'authenticated') THEN
13415
+ IF TG_OP = 'INSERT' THEN
13416
+ NEW.created_by_id = auth.uid();
13417
+ NEW.created_at = now();
13418
+ ELSE
13419
+ NEW.created_by_id = OLD.created_by_id;
13420
+ NEW.created_at = OLD.created_at;
13421
+ END IF;
13422
+ ELSIF TG_OP = 'INSERT' THEN
13423
+ NEW.created_by_id = COALESCE(NEW.created_by_id, auth.uid());
13424
+ END IF;
13425
+ NEW.updated_by_id = auth.uid();
13426
+ RETURN NEW;
13427
+ END;
13428
+ $$ LANGUAGE plpgsql SECURITY INVOKER;
13429
+ `;
13430
+ }
13431
+ function camelToSnake3(str) {
12989
13432
  return str.replace(/[A-Z]/g, (c3) => `_${c3.toLowerCase()}`);
12990
13433
  }
12991
13434
  async function main2() {
@@ -12998,7 +13441,9 @@ async function main2() {
12998
13441
  overwrite: process.env.OVERWRITE === "true",
12999
13442
  dryRun: process.env.DRY_RUN === "true",
13000
13443
  verbose: process.env.VERBOSE === "true",
13001
- singleFile: process.env.SINGLE_FILE !== "false"
13444
+ singleFile: process.env.SINGLE_FILE !== "false",
13445
+ only: process.env.ONLY ? process.env.ONLY.split(",").filter(Boolean) : void 0,
13446
+ appDir: process.env.APP_DIR || void 0
13002
13447
  };
13003
13448
  const generator = new SqlGenerator(options);
13004
13449
  const result = await generator.run();
@@ -13008,13 +13453,16 @@ async function main2() {
13008
13453
  process.exit(1);
13009
13454
  }
13010
13455
  }
13011
- var HIDDEN_STATUSES, ROLE_LEVEL, KIND_TO_SQL, TECHNICAL_KEYS2, SqlGenerator;
13456
+ var HIDDEN_STATUSES, ROLE_LEVEL, KIND_TO_SQL, TECHNICAL_KEYS2, ANON_BASE_COLUMNS, ISO_TIMESTAMP_SOURCE, CLIENT_IP_PATTERN, isSupabaseApp, SqlGenerator;
13012
13457
  var init_sql_generator = __esm({
13013
13458
  "packages/tooling/src/generators/sql-generator.ts"() {
13014
13459
  "use strict";
13015
13460
  init_utils2();
13016
13461
  init_base_generator();
13462
+ init_frameworkEntities();
13463
+ init_pgRegex();
13017
13464
  init_sqlChecks();
13465
+ init_sqlUniqueKeys();
13018
13466
  init_cli_output();
13019
13467
  init_coreSemantics();
13020
13468
  init_errors();
@@ -13046,18 +13494,40 @@ var init_sql_generator = __esm({
13046
13494
  "updatedById",
13047
13495
  "status"
13048
13496
  ]);
13497
+ ANON_BASE_COLUMNS = ["id", "status", "updated_at"];
13498
+ ISO_TIMESTAMP_SOURCE = "^\\d{4}-(?:0[1-9]|1[0-2])-(?:[12]\\d|0[1-9]|3[01])[T ](?:0\\d|1\\d|2[0-3])(?::[0-5]\\d){2}(?:\\.\\d{1,9})?(?:Z| ?[+-](?:0\\d|1\\d|2[0-3])(?::?[0-5]\\d)?)$";
13499
+ CLIENT_IP_PATTERN = sqlText("^(?:[0-9]{1,3}[.]){3}[0-9]{1,3}$|^[0-9a-fA-F:]{2,45}$");
13500
+ isSupabaseApp = (dir) => pathExists(joinPath(dir, "supabase", "config.toml"), true);
13049
13501
  SqlGenerator = class extends BaseGenerator {
13050
13502
  singleFile;
13503
+ only;
13051
13504
  core;
13505
+ /** Last version handed out (a dry run writes nothing for `nextMigrationVersion` to see). */
13506
+ lastVersion = 0n;
13507
+ /** App folder whose config turns framework features on (see `SqlGeneratorOptions.appDir`). */
13508
+ appDir;
13509
+ features;
13510
+ /** Collections of the app's own entity files seen by `processEntityFile` (per-entity mode). */
13511
+ appCollections = /* @__PURE__ */ new Set();
13052
13512
  constructor(options = {}) {
13053
13513
  super("SQL", {
13054
13514
  entityDirs: options.entityDir ? [options.entityDir] : void 0,
13055
- outputDir: options.outputDir || fromAppRoot("supabase", "migrations"),
13515
+ outputDir: options.outputDir || resolveMigrationsDir(process.cwd()),
13056
13516
  overwrite: options.overwrite,
13057
13517
  dryRun: options.dryRun,
13058
13518
  verbose: options.verbose
13059
13519
  });
13060
- this.singleFile = options.singleFile !== false;
13520
+ this.only = options.only && options.only.length > 0 ? options.only : void 0;
13521
+ this.singleFile = this.only ? true : options.singleFile !== false;
13522
+ this.appDir = options.appDir ?? appDirOfMigrations(this.outputDir);
13523
+ this.features = options.features ?? FRAMEWORK_ENTITY_FEATURES;
13524
+ }
13525
+ /** Version of the next migration file: after the folder's latest and after this run's own. */
13526
+ nextVersion() {
13527
+ let version = BigInt(nextMigrationVersion(this.outputDir));
13528
+ if (version <= this.lastVersion) version = this.lastVersion + 1n;
13529
+ this.lastVersion = version;
13530
+ return String(version);
13061
13531
  }
13062
13532
  /** Entity semantics of the app the entity file belongs to (loaded once). */
13063
13533
  async coreFor(entityFilePath) {
@@ -13079,6 +13549,7 @@ var init_sql_generator = __esm({
13079
13549
  }
13080
13550
  const entityName = isObjectLike(entity) ? entity.name : void 0;
13081
13551
  const resolvedName = typeof entityName === "string" ? entityName : entityFileName;
13552
+ if (isSqlEntity(entity)) this.appCollections.add(entity.collection);
13082
13553
  if (this.singleFile) {
13083
13554
  return resolvedName;
13084
13555
  }
@@ -13134,7 +13605,7 @@ var init_sql_generator = __esm({
13134
13605
  DO_NOT_DEV_ERROR_CODES.GENERATION_ERROR
13135
13606
  );
13136
13607
  }
13137
- const colName = camelToSnake2(key);
13608
+ const colName = camelToSnake3(key);
13138
13609
  columns.push(`${colName} ${KIND_TO_SQL[described.value.kind]}`);
13139
13610
  if (field.i18n === true) {
13140
13611
  columns.push(`${colName}_i18n jsonb NOT NULL DEFAULT '{}'::jsonb`);
@@ -13171,6 +13642,125 @@ ${alterDefaults}`;
13171
13642
  ...checks.map(checkConstraintSql)
13172
13643
  ].join("\n\n");
13173
13644
  }
13645
+ /**
13646
+ * Unique indexes of the entity's `uniqueKeys` (`sqlUniqueKeys.ts`: case-insensitive text,
13647
+ * empty values unchecked, soft-deleted rows out, drafts out with `skipForDrafts`; existing
13648
+ * duplicates fail the migration), plus the drop of the framework unique indexes it no
13649
+ * longer declares.
13650
+ */
13651
+ buildUniqueKeysSql(entity, core) {
13652
+ this.safeTableName(entity.collection);
13653
+ return uniqueIndexesSql(
13654
+ entity.collection,
13655
+ uniqueIndexesOf(entity, core.describeEntity(entity), core.removedStatus)
13656
+ );
13657
+ }
13658
+ /**
13659
+ * Column privileges of `anon` for an entity readable by guests (`access.read` guest).
13660
+ * RLS selects rows only; a guest's direct PostgREST read would return every column of a
13661
+ * visible row. `anon` keeps SELECT on `id`, `status` (the adapter selects both on every
13662
+ * read), `updated_at` (sitemap `lastmod`, read by `SupabasePublicReader`) and the columns
13663
+ * of the fields whose visibility is `guest` (with their `_i18n` companion). Table-level REVOKE drops every column grant too, so a re-run applies
13664
+ * exactly the entity's list. `authenticated` is not restricted: pros and admins share
13665
+ * that role (see {@link warnRestrictedFields}).
13666
+ *
13667
+ * @returns The REVOKE / GRANT statements, or '' when guests cannot read the entity
13668
+ */
13669
+ buildAnonGrantsSql(entity, core) {
13670
+ if ((entity.access?.read ?? "guest") !== "guest") return "";
13671
+ const tableName = this.safeTableName(entity.collection);
13672
+ const descriptor = core.describeEntity(entity);
13673
+ const columns = new Set(ANON_BASE_COLUMNS);
13674
+ for (const [key, field] of Object.entries(descriptor.fields)) {
13675
+ if (field.visibleAt !== "guest") continue;
13676
+ columns.add(camelToSnake3(key));
13677
+ if (field.companion) columns.add(camelToSnake3(field.companion));
13678
+ }
13679
+ return [
13680
+ `-- Guest column privileges for ${entity.collection}: anon reads the guest-visible columns only`,
13681
+ `REVOKE SELECT ON ${tableName} FROM anon;`,
13682
+ `GRANT SELECT (${[...columns].join(", ")}) ON ${tableName} TO anon;`
13683
+ ].join("\n");
13684
+ }
13685
+ /**
13686
+ * Insert privileges of `anon`. Every table: `REVOKE INSERT … FROM anon` (Supabase grants it
13687
+ * by default; only guest-create entities need it). `access.create` guest: `anon` inserts
13688
+ * `id` (the Supabase CRUD adapter mints it, since a guest may not read the row back) and
13689
+ * the columns of the fields a write may set (descriptor `write` other than `never`, with
13690
+ * their `_i18n` companion: `status` included, `created_*` / `updated_*` excluded: the audit
13691
+ * trigger stamps them, `created_by_id` stays NULL for a guest). Which rows, the RLS insert
13692
+ * policy decides. Entity-carried SQL, written after, may grant more.
13693
+ *
13694
+ * @returns The REVOKE (and GRANT) statements
13695
+ */
13696
+ buildAnonInsertGrantsSql(entity, core) {
13697
+ const tableName = this.safeTableName(entity.collection);
13698
+ const revoke = `REVOKE INSERT ON ${tableName} FROM anon;`;
13699
+ if ((entity.access?.create ?? "admin") !== "guest") {
13700
+ return [
13701
+ `-- Guest inserts for ${entity.collection}: none (access.create=${entity.access?.create ?? "admin"})`,
13702
+ revoke
13703
+ ].join("\n");
13704
+ }
13705
+ const columns = /* @__PURE__ */ new Set(["id"]);
13706
+ for (const [key, field] of Object.entries(core.describeEntity(entity).fields)) {
13707
+ if (field.write === "never") continue;
13708
+ columns.add(camelToSnake3(key));
13709
+ if (field.companion) columns.add(camelToSnake3(field.companion));
13710
+ }
13711
+ return [
13712
+ `-- Guest inserts for ${entity.collection}: anon writes the id and the writable columns (RLS decides the rows)`,
13713
+ revoke,
13714
+ `GRANT INSERT (${[...columns].join(", ")}) ON ${tableName} TO anon;`
13715
+ ].join("\n");
13716
+ }
13717
+ /**
13718
+ * Create rate limit trigger of an entity (`rateLimit.create`): `BEFORE INSERT … FOR EACH
13719
+ * ROW` calling {@link createRateLimitFunctionSql}'s function with `max` and `windowSeconds`.
13720
+ * Without a limit the framework-named trigger is dropped (a removed limit is removed from
13721
+ * the database on the next run).
13722
+ *
13723
+ * @returns DROP (and CREATE) TRIGGER statements
13724
+ */
13725
+ buildRateLimitTriggerSql(entity) {
13726
+ const tableName = this.safeTableName(entity.collection);
13727
+ const trigger = `${entity.collection}_create_rate_limit`;
13728
+ const drop = `DROP TRIGGER IF EXISTS ${trigger} ON ${tableName};`;
13729
+ const limit = entity.rateLimit?.create;
13730
+ if (!limit) return drop;
13731
+ for (const [key, value] of Object.entries(limit)) {
13732
+ if (!Number.isSafeInteger(value) || value <= 0) {
13733
+ throw new DoNotDevError(
13734
+ `${String(entity.name)}: rateLimit.create.${key} must be a positive integer, got ${JSON.stringify(value)}`,
13735
+ DO_NOT_DEV_ERROR_CODES.GENERATION_ERROR
13736
+ );
13737
+ }
13738
+ }
13739
+ return `-- Create rate limit for ${entity.collection}: ${limit.max} rows per caller per ${limit.windowSeconds} s
13740
+ ${drop}
13741
+ CREATE TRIGGER ${trigger}
13742
+ BEFORE INSERT ON ${tableName}
13743
+ FOR EACH ROW
13744
+ EXECUTE PROCEDURE public.dndev_create_rate_limit('${limit.max}', '${limit.windowSeconds}');`;
13745
+ }
13746
+ /**
13747
+ * Generation-time warning: app fields whose visibility is above `user` on an entity whose
13748
+ * rows non-admins read (`access.read` guest or user). The database enforces rows (RLS) and,
13749
+ * for `anon`, columns ({@link buildAnonGrantsSql}); an authenticated caller reading the row
13750
+ * through PostgREST gets those columns too. The base fields are the framework's own row
13751
+ * metadata and are not listed.
13752
+ *
13753
+ * @returns The warning text, or null when there is nothing to warn about
13754
+ */
13755
+ warnRestrictedFields(entity, core) {
13756
+ const readLevel = ROLE_LEVEL[entity.access?.read ?? "guest"] ?? 0;
13757
+ if (readLevel >= (ROLE_LEVEL["admin"] ?? 2)) return null;
13758
+ const restricted = Object.entries(core.describeEntity(entity).fields).filter(([key, field]) => !TECHNICAL_KEYS2.has(key) && field.visibleAt !== "guest" && field.visibleAt !== "user").map(([key, field]) => `${key} (${field.visibleAt})`);
13759
+ if (restricted.length === 0) return null;
13760
+ const message = `${String(entity.name)}: ${restricted.join(", ")} readable by row owners via direct API; DB enforces rows only (and guest columns for anon).`;
13761
+ log2.warn(message);
13762
+ return message;
13763
+ }
13174
13764
  buildRlsSql(tableName, access) {
13175
13765
  const quoted = this.safeTableName(tableName);
13176
13766
  const readRole = access?.read ?? "guest";
@@ -13183,21 +13773,33 @@ ${alterDefaults}`;
13183
13773
  const deleteCond = roleToSqlCondition(deleteRole);
13184
13774
  const readLevel = ROLE_LEVEL[readRole] ?? 0;
13185
13775
  const adminLevel = ROLE_LEVEL["admin"] ?? 2;
13776
+ const audience = rowAudienceConditions(access?.rowAudience);
13186
13777
  let selectCond;
13187
13778
  if (readLevel < adminLevel) {
13188
13779
  const statusList = HIDDEN_STATUSES.map((s) => `'${s}'`).join(", ");
13189
13780
  const adminCond = roleToSqlCondition("admin");
13190
- selectCond = readCond === "true" ? `(status NOT IN (${statusList}) OR ${adminCond})` : `(${readCond}) AND (status NOT IN (${statusList}) OR ${adminCond})`;
13781
+ const visible = audience.length === 0 ? `status NOT IN (${statusList})` : `(${[`status NOT IN (${statusList})`, ...audience].join(" AND ")})`;
13782
+ selectCond = readCond === "true" ? `(${visible} OR ${adminCond})` : `(${readCond}) AND (${visible} OR ${adminCond})`;
13191
13783
  } else {
13784
+ if (audience.length > 0) {
13785
+ log2.warn(
13786
+ `${tableName}: access.rowAudience has no effect: only admins read it (access.read=${readRole}), and admins read every row.`
13787
+ );
13788
+ }
13192
13789
  selectCond = readCond;
13193
13790
  }
13791
+ const rowAudience = access?.rowAudience;
13792
+ const audienceNote = rowAudience ? `, rowAudience=${[
13793
+ rowAudience.role ? `role:${camelToSnake3(rowAudience.role)}` : "",
13794
+ rowAudience.tier ? `tier:${camelToSnake3(rowAudience.tier)}` : ""
13795
+ ].filter(Boolean).join(",")}` : "";
13194
13796
  const selectPolicy = `${tableName}_select`;
13195
13797
  const insertPolicy = `${tableName}_insert`;
13196
13798
  const updatePolicy = `${tableName}_update`;
13197
13799
  const deletePolicy = `${tableName}_delete`;
13198
13800
  return `
13199
13801
  -- RLS Policies for ${tableName}
13200
- -- Access rules: read=${readRole}, create=${createRole}, update=${updateRole}, delete=${deleteRole}
13802
+ -- Access rules: read=${readRole}, create=${createRole}, update=${updateRole}, delete=${deleteRole}${audienceNote}
13201
13803
  ALTER TABLE ${quoted} ENABLE ROW LEVEL SECURITY;
13202
13804
 
13203
13805
  -- Drop existing policies if they exist (idempotent re-runs)
@@ -13218,6 +13820,26 @@ CREATE POLICY "${updatePolicy}" ON ${quoted}
13218
13820
 
13219
13821
  CREATE POLICY "${deletePolicy}" ON ${quoted}
13220
13822
  FOR DELETE USING (${deleteCond});
13823
+ `;
13824
+ }
13825
+ /**
13826
+ * Entity-carried SQL (`Entity.sql`): custom policies, functions, grants, views, written
13827
+ * verbatim after the entity's generated SQL, under a header naming the entity.
13828
+ *
13829
+ * @returns The block, or '' when the entity carries no SQL
13830
+ */
13831
+ buildEntitySql(entity) {
13832
+ if (entity.sql === void 0) return "";
13833
+ if (typeof entity.sql !== "string") {
13834
+ throw new DoNotDevError(
13835
+ `${String(entity.name)}: entity.sql must be a string`,
13836
+ DO_NOT_DEV_ERROR_CODES.GENERATION_ERROR
13837
+ );
13838
+ }
13839
+ const body = entity.sql.trim();
13840
+ if (body === "") return "";
13841
+ return `-- Entity SQL: ${String(entity.name)} (${entity.collection})
13842
+ ${body}
13221
13843
  `;
13222
13844
  }
13223
13845
  buildTriggerSql(tableName) {
@@ -13258,17 +13880,7 @@ CREATE TRIGGER ${updatedAtTrigger}
13258
13880
  FOR EACH ROW
13259
13881
  EXECUTE PROCEDURE set_updated_at_${tableName}();
13260
13882
 
13261
- CREATE OR REPLACE FUNCTION set_audit_fields_${tableName}()
13262
- RETURNS TRIGGER AS $$
13263
- BEGIN
13264
- IF TG_OP = 'INSERT' THEN
13265
- NEW.created_by_id = COALESCE(NEW.created_by_id, auth.uid());
13266
- END IF;
13267
- NEW.updated_by_id = auth.uid();
13268
- RETURN NEW;
13269
- END;
13270
- $$ LANGUAGE plpgsql SECURITY DEFINER;
13271
-
13883
+ ${auditFieldsFunctionSql(`set_audit_fields_${tableName}`)}
13272
13884
  DROP TRIGGER IF EXISTS ${auditTrigger} ON ${quoted};
13273
13885
  CREATE TRIGGER ${auditTrigger}
13274
13886
  BEFORE INSERT OR UPDATE ON ${quoted}
@@ -13286,26 +13898,57 @@ CREATE TRIGGER ${auditTrigger}
13286
13898
  const tableName = entity.collection;
13287
13899
  const tableSql = this.buildTableSql(entity, core);
13288
13900
  const checksSql = this.buildChecksSql(entity, core);
13901
+ const uniqueSql = this.buildUniqueKeysSql(entity, core);
13902
+ const audienceSql = usesRowAudience([entity]) ? rowAudienceFunctionsSql(accessNames(core)) : "";
13289
13903
  const rlsSql = this.buildRlsSql(tableName, entity.access);
13904
+ const grantsSql = this.buildAnonGrantsSql(entity, core);
13905
+ const insertGrantsSql = this.buildAnonInsertGrantsSql(entity, core);
13906
+ this.warnRestrictedFields(entity, core);
13290
13907
  const triggerSql = this.buildTriggerSqlPerTable(tableName);
13908
+ const rateLimitSql = [
13909
+ usesCreateRateLimit([entity]) ? createRateLimitFunctionSql() : "",
13910
+ this.buildRateLimitTriggerSql(entity)
13911
+ ].filter(Boolean).join("\n");
13912
+ const entitySql = this.buildEntitySql(entity);
13291
13913
  const content = `-- Auto-generated from entity: ${entity.name} (${entityFileName})
13292
13914
  -- Do not edit by hand; re-run SQL generator to regenerate.
13293
13915
 
13294
13916
  ${tableSql}
13295
13917
  ${checksSql}
13918
+ ${uniqueSql}
13919
+ ${audienceSql}
13296
13920
  ${rlsSql}
13921
+ ${grantsSql}
13922
+ ${insertGrantsSql}
13297
13923
  ${triggerSql}
13298
- `;
13299
- const ts = /* @__PURE__ */ new Date();
13300
- const stamp = ts.getFullYear() + String(ts.getMonth() + 1).padStart(2, "0") + String(ts.getDate()).padStart(2, "0") + String(ts.getHours()).padStart(2, "0") + String(ts.getMinutes()).padStart(2, "0") + String(ts.getSeconds()).padStart(2, "0");
13924
+ ${rateLimitSql}
13925
+ ${entitySql}`;
13301
13926
  const outputFilePath = joinPath(
13302
13927
  this.outputDir,
13303
- `${stamp}_${tableName}.sql`
13928
+ `${this.nextVersion()}_${tableName}.sql`
13304
13929
  );
13305
13930
  await this.writeFile(outputFilePath, content, result);
13306
13931
  }
13932
+ /**
13933
+ * Entities of the framework features the app's config turns on and the app has installed
13934
+ * ({@link loadFeatureEntities}), minus the collections the app's own entity files define.
13935
+ */
13936
+ async featureEntities(appCollections) {
13937
+ const found = await loadFeatureEntities(this.appDir, appCollections, this.features);
13938
+ if (found.length > 0) {
13939
+ log2.info(
13940
+ `Framework feature entities: ${found.map((f) => `${f.entity.collection} (${f.feature})`).join(", ")}`
13941
+ );
13942
+ }
13943
+ return found.filter((f) => isSqlEntity(f.entity)).map((f) => ({ entity: f.entity, fileName: `feature ${f.feature}`, path: f.path }));
13944
+ }
13307
13945
  async generateAdditionalFiles(result) {
13308
- if (!this.singleFile) return;
13946
+ if (!this.singleFile) {
13947
+ for (const { entity, fileName, path } of await this.featureEntities(this.appCollections)) {
13948
+ await this.writeMigrationForEntity(entity, fileName, await this.coreFor(path), result);
13949
+ }
13950
+ return;
13951
+ }
13309
13952
  const entityFiles = await this.findEntityFiles();
13310
13953
  const entities = [];
13311
13954
  for (const entityFilePath of entityFiles) {
@@ -13323,31 +13966,53 @@ ${triggerSql}
13323
13966
  continue;
13324
13967
  }
13325
13968
  }
13326
- if (entities.length === 0) return;
13327
- const core = await this.coreFor(entities[0].path);
13969
+ entities.push(...await this.featureEntities(new Set(entities.map((e) => e.entity.collection))));
13970
+ let selected = entities;
13971
+ if (this.only) {
13972
+ const available = entities.map((e) => e.entity.collection);
13973
+ const unknown = this.only.filter((c3) => !available.includes(c3));
13974
+ if (unknown.length > 0) {
13975
+ throw new DoNotDevError(
13976
+ `Unknown collection(s) for --only: ${unknown.join(", ")}. Available: ${available.join(", ") || "(none)"}`,
13977
+ DO_NOT_DEV_ERROR_CODES.GENERATION_ERROR
13978
+ );
13979
+ }
13980
+ selected = entities.filter((e) => this.only.includes(e.entity.collection));
13981
+ }
13982
+ if (selected.length === 0) return;
13983
+ const core = await this.coreFor(selected[0].path);
13328
13984
  const parts = [
13329
- "-- Auto-generated entity tables (Do not edit by hand; re-run SQL generator.)",
13985
+ this.only ? `-- Auto-generated for entities: ${selected.map((e) => e.entity.collection).join(", ")} (dn generate sql --only; do not edit by hand)` : "-- Auto-generated entity tables (Do not edit by hand; re-run SQL generator.)",
13330
13986
  ""
13331
13987
  ];
13332
- for (const { entity } of entities) {
13988
+ for (const { entity } of selected) {
13333
13989
  parts.push(this.buildTableSql(entity, core));
13334
13990
  parts.push("");
13335
13991
  }
13336
- for (const { entity } of entities) {
13992
+ for (const { entity } of selected) {
13337
13993
  const checksSql = this.buildChecksSql(entity, core);
13338
13994
  if (checksSql) {
13339
13995
  parts.push(checksSql);
13340
13996
  parts.push("");
13341
13997
  }
13998
+ parts.push(this.buildUniqueKeysSql(entity, core), "");
13342
13999
  }
13343
- for (const { entity } of entities) {
14000
+ if (usesRowAudience(selected.map((e) => e.entity))) {
14001
+ parts.push(rowAudienceFunctionsSql(accessNames(core)));
14002
+ }
14003
+ for (const { entity } of selected) {
13344
14004
  parts.push(this.buildRlsSql(entity.collection, entity.access));
13345
14005
  }
14006
+ for (const { entity } of selected) {
14007
+ const grantsSql = this.buildAnonGrantsSql(entity, core);
14008
+ if (grantsSql) parts.push(grantsSql, "");
14009
+ parts.push(this.buildAnonInsertGrantsSql(entity, core), "");
14010
+ this.warnRestrictedFields(entity, core);
14011
+ }
13346
14012
  const triggerFunc = "CREATE OR REPLACE FUNCTION set_updated_at()\nRETURNS TRIGGER AS $$\nBEGIN\n NEW.updated_at = now();\n RETURN NEW;\nEND;\n$$ LANGUAGE plpgsql;\n";
13347
14013
  parts.push(triggerFunc);
13348
- const auditFunc = "CREATE OR REPLACE FUNCTION set_audit_fields()\nRETURNS TRIGGER AS $$\nBEGIN\n IF TG_OP = 'INSERT' THEN\n NEW.created_by_id = COALESCE(NEW.created_by_id, auth.uid());\n END IF;\n NEW.updated_by_id = auth.uid();\n RETURN NEW;\nEND;\n$$ LANGUAGE plpgsql SECURITY DEFINER;\n";
13349
- parts.push(auditFunc);
13350
- for (const { entity } of entities) {
14014
+ parts.push(auditFieldsFunctionSql("set_audit_fields"));
14015
+ for (const { entity } of selected) {
13351
14016
  const tn = entity.collection;
13352
14017
  const q = this.safeTableName(tn);
13353
14018
  parts.push(`
@@ -13364,12 +14029,21 @@ CREATE TRIGGER ${tn}_audit
13364
14029
  EXECUTE PROCEDURE set_audit_fields();
13365
14030
  `);
13366
14031
  }
14032
+ if (usesCreateRateLimit(selected.map((e) => e.entity))) {
14033
+ parts.push(createRateLimitFunctionSql());
14034
+ }
14035
+ for (const { entity } of selected) {
14036
+ parts.push(this.buildRateLimitTriggerSql(entity), "");
14037
+ }
14038
+ for (const { entity } of selected) {
14039
+ const entitySql = this.buildEntitySql(entity);
14040
+ if (entitySql) parts.push(entitySql);
14041
+ }
13367
14042
  const content = parts.join("\n");
13368
- const ts = /* @__PURE__ */ new Date();
13369
- const stamp = ts.getFullYear() + String(ts.getMonth() + 1).padStart(2, "0") + String(ts.getDate()).padStart(2, "0") + String(ts.getHours()).padStart(2, "0") + String(ts.getMinutes()).padStart(2, "0") + String(ts.getSeconds()).padStart(2, "0");
14043
+ const name = this.only ? `${this.only[0]}${this.only.length > 1 ? "_and_more" : ""}` : "entity_tables";
13370
14044
  const outputFilePath = joinPath(
13371
14045
  this.outputDir,
13372
- `${stamp}_entity_tables.sql`
14046
+ `${this.nextVersion()}_${name}.sql`
13373
14047
  );
13374
14048
  await this.writeFile(outputFilePath, content, result);
13375
14049
  }
@@ -13603,7 +14277,8 @@ async function main3(options = {}) {
13603
14277
  return;
13604
14278
  }
13605
14279
  const entitiesDir = joinPath(projectRoot, "entities");
13606
- const hasEntities = pathExists(entitiesDir) && pathExists(joinPath(entitiesDir, "index.ts"));
14280
+ const { enabledEntityFeatures: enabledEntityFeatures2 } = await Promise.resolve().then(() => (init_frameworkEntities(), frameworkEntities_exports));
14281
+ const hasEntities = pathExists(entitiesDir) && pathExists(joinPath(entitiesDir, "index.ts")) || (await enabledEntityFeatures2(appDir)).length > 0;
13607
14282
  let sqlGenerated = false;
13608
14283
  let generatedEntityFile = null;
13609
14284
  if (hasEntities) {
@@ -13618,7 +14293,8 @@ async function main3(options = {}) {
13618
14293
  const generator = new SqlGenerator2({
13619
14294
  entityDir: entitiesDir,
13620
14295
  outputDir: joinPath(supabaseDir, "migrations"),
13621
- singleFile: true
14296
+ singleFile: true,
14297
+ appDir
13622
14298
  });
13623
14299
  const s = spinner();
13624
14300
  s.start("Generating SQL migrations from entities...");
@@ -13641,7 +14317,7 @@ async function main3(options = {}) {
13641
14317
  }
13642
14318
  }
13643
14319
  } else {
13644
- log2.info("No entities directory found. Skipping SQL generation.");
14320
+ log2.info("No entities directory and no framework feature with entities on. Skipping SQL generation.");
13645
14321
  }
13646
14322
  if (sqlGenerated && generatedEntityFile) {
13647
14323
  try {
@@ -13761,7 +14437,8 @@ var init_supabase = __esm({
13761
14437
  message: `${existingConfig.url}`
13762
14438
  });
13763
14439
  const entitiesDir = joinPath(ctx.projectRoot, "entities");
13764
- const hasEntities = pathExists(entitiesDir) && pathExists(joinPath(entitiesDir, "index.ts"));
14440
+ const { enabledEntityFeatures: enabledEntityFeatures2 } = await Promise.resolve().then(() => (init_frameworkEntities(), frameworkEntities_exports));
14441
+ const hasEntities = pathExists(entitiesDir) && pathExists(joinPath(entitiesDir, "index.ts")) || (await enabledEntityFeatures2(ctx.appDir)).length > 0;
13765
14442
  let generatedEntityFile = null;
13766
14443
  if (hasEntities) {
13767
14444
  try {
@@ -13769,7 +14446,8 @@ var init_supabase = __esm({
13769
14446
  const generator = new SqlGenerator2({
13770
14447
  entityDir: entitiesDir,
13771
14448
  outputDir: joinPath(supabaseDir, "migrations"),
13772
- singleFile: true
14449
+ singleFile: true,
14450
+ appDir: ctx.appDir
13773
14451
  });
13774
14452
  const s = spinner();
13775
14453
  s.start("Generating SQL from entities...");
@@ -13801,7 +14479,7 @@ var init_supabase = __esm({
13801
14479
  steps.push({
13802
14480
  name: "SQL generation",
13803
14481
  status: "skipped",
13804
- message: "No entities/ directory"
14482
+ message: "No entities/ directory, no framework feature with entities"
13805
14483
  });
13806
14484
  }
13807
14485
  if (generatedEntityFile) {