@marktiderman/genesis-cli 1.27.0 → 1.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/vite.js CHANGED
@@ -24,6 +24,15 @@ var __export = (target, all) => {
24
24
  __defProp(target, name, { get: all[name], enumerable: true });
25
25
  };
26
26
 
27
+ // src/regexp.ts
28
+ function escapeRegExp(s) {
29
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
30
+ }
31
+ var init_regexp = __esm({
32
+ "src/regexp.ts"() {
33
+ }
34
+ });
35
+
27
36
  // src/introspect/catalog-text.ts
28
37
  function tokenize(tree) {
29
38
  const tokens = [];
@@ -153,9 +162,6 @@ function splitTopLevel(expr, separator) {
153
162
  parts.push(expr.slice(from));
154
163
  return parts;
155
164
  }
156
- function escapeRegExp(s) {
157
- return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
158
- }
159
165
  function checkEnumValues(definition, column) {
160
166
  const outer = /^CHECK \((.*)\)(?: NOT VALID)?$/s.exec(definition.trim());
161
167
  if (!outer) return void 0;
@@ -190,6 +196,7 @@ function checkEnumValues(definition, column) {
190
196
  var CAST, LITERAL;
191
197
  var init_catalog_text = __esm({
192
198
  "src/introspect/catalog-text.ts"() {
199
+ init_regexp();
193
200
  CAST = String.raw`::[a-z][a-z ]*(?:\(\d+(?:,\d+)?\))?`;
194
201
  LITERAL = String.raw`'((?:[^']|'')*)'${CAST}`;
195
202
  }
@@ -938,6 +945,7 @@ function readGenesisConfig(root) {
938
945
  }
939
946
  if (raw.appFolder !== void 0) out.appFolder = validateAppFolder(raw.appFolder, file);
940
947
  if (raw.environments !== void 0) out.environments = validateEnvironments(raw.environments, file);
948
+ if (raw.client !== void 0) out.client = validateClient(raw.client, file);
941
949
  return out;
942
950
  }
943
951
  var PLAIN_FOLDER = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,59}(?:\/[A-Za-z0-9_][A-Za-z0-9_.-]{0,59}){0,7}$/;
@@ -949,6 +957,16 @@ function validateAppFolder(raw, source = "config") {
949
957
  if (!isPlainFolder(norm)) throw new GenesisConfigError(`${source}: "appFolder" must be the app's folder from the repository root, such as "mobile" or "apps/phone" (got ${JSON.stringify(raw)})`);
950
958
  return norm;
951
959
  }
960
+ function validateClient(raw, source = "config") {
961
+ const fail = (msg) => {
962
+ throw new GenesisConfigError(`${source}: ${msg}`);
963
+ };
964
+ if (!isObject(raw)) return fail(`"client" must be { "dir": "<the client layer's folder, e.g. src/client>" }`);
965
+ for (const key2 of Object.keys(raw)) if (key2 !== "dir" && key2 !== "$comment") fail(`client: unknown setting "${key2}" (known: dir)`);
966
+ const dir = typeof raw.dir === "string" ? raw.dir.replace(/^\.\//, "").replace(/\/+$/, "") : "";
967
+ if (!isPlainFolder(dir)) return fail(`client.dir must be a folder inside the app, such as "src/client" (got ${JSON.stringify(raw.dir)})`);
968
+ return { dir };
969
+ }
952
970
  function validateSupabase(raw, source = "config") {
953
971
  const fail = (msg) => {
954
972
  throw new GenesisConfigError(`${source}: ${msg}`);
@@ -1212,7 +1230,7 @@ function globToRegExp(glob) {
1212
1230
  }
1213
1231
  function globMatcher(globs) {
1214
1232
  const res = (globs ?? []).filter((g) => g.trim()).map(globToRegExp);
1215
- return (path50) => res.some((re) => re.test(path50));
1233
+ return (path52) => res.some((re) => re.test(path52));
1216
1234
  }
1217
1235
  var GENESIS_PACKAGE = /^@marktiderman\/genesis(-[a-z0-9-]+)?$/;
1218
1236
  var BLOCK_ID = /^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/;
@@ -2771,6 +2789,319 @@ function resolvePlugin(id, configDir) {
2771
2789
  function resolveFrom(id, from) {
2772
2790
  return createRequire(path21.join(from, "noop.js")).resolve(id);
2773
2791
  }
2792
+
2793
+ // src/doctor/js-scan.ts
2794
+ var IDENT_START = /[A-Za-z_$]/;
2795
+ var IDENT = /[\w$]/;
2796
+ var PUNCT3 = ["...", "===", "!==", "**=", "<<=", ">>=", "??=", "&&=", "||="];
2797
+ var PUNCT2 = ["=>", "==", "!=", "<=", ">=", "&&", "||", "??", "?.", "++", "--", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "**", "<<", ">>"];
2798
+ var EXPRESSION_KEYWORDS = /* @__PURE__ */ new Set(["return", "typeof", "case", "do", "else", "in", "new", "delete", "void", "throw", "yield", "await", "instanceof"]);
2799
+ var TYPE_PARAMETERS = /^<\s*[A-Za-z_$][\w$]*\s*(?:,|extends\b)/;
2800
+ function scanCode(code, options = {}) {
2801
+ const jsx = options.jsx ?? true;
2802
+ const tokens = [];
2803
+ const push = (kind, value) => tokens.push({ kind, value, index: tokens.length });
2804
+ const expressionNext = (start) => {
2805
+ if (tokens.length <= start) return true;
2806
+ const t = tokens[tokens.length - 1];
2807
+ if (!t) return true;
2808
+ if (t.kind === "ident") return EXPRESSION_KEYWORDS.has(t.value);
2809
+ if (t.kind === "jsxTag" || t.kind === "literal") return false;
2810
+ return !(t.value === ")" || t.value === "]" || t.value === "}" || t.value === "<>");
2811
+ };
2812
+ const skipString2 = (i2, quote2) => {
2813
+ let j = i2 + 1;
2814
+ while (j < code.length && code[j] !== quote2) {
2815
+ if (code[j] === "\\") j++;
2816
+ else if (code[j] === "\n") return j;
2817
+ j++;
2818
+ }
2819
+ return j + 1;
2820
+ };
2821
+ const skipAttribute = (i2, quote2) => {
2822
+ const end = code.indexOf(quote2, i2 + 1);
2823
+ return end < 0 ? code.length : end + 1;
2824
+ };
2825
+ const skipRegex = (i2) => {
2826
+ let j = i2 + 1;
2827
+ let inClass = false;
2828
+ while (j < code.length && code[j] !== "\n") {
2829
+ const c = code[j];
2830
+ if (c === "\\") j++;
2831
+ else if (c === "[") inClass = true;
2832
+ else if (c === "]") inClass = false;
2833
+ else if (c === "/" && !inClass) {
2834
+ j++;
2835
+ while (j < code.length && IDENT.test(code[j])) j++;
2836
+ return j;
2837
+ }
2838
+ j++;
2839
+ }
2840
+ return j;
2841
+ };
2842
+ const skipTrivia = (i2) => {
2843
+ let j = i2;
2844
+ for (; ; ) {
2845
+ while (j < code.length && /\s/.test(code[j])) j++;
2846
+ if (code.startsWith("//", j)) {
2847
+ const end = code.indexOf("\n", j);
2848
+ j = end < 0 ? code.length : end;
2849
+ } else if (code.startsWith("/*", j)) {
2850
+ const end = code.indexOf("*/", j + 2);
2851
+ j = end < 0 ? code.length : end + 2;
2852
+ } else return j;
2853
+ }
2854
+ };
2855
+ const stack = [{ k: "code", depth: 0, stop: false, start: 0 }];
2856
+ const openCode = () => stack.push({ k: "code", depth: 0, stop: true, start: tokens.length });
2857
+ const openElement = (i2) => {
2858
+ if (code[i2 + 1] === ">") {
2859
+ stack.push({ k: "children" });
2860
+ return i2 + 2;
2861
+ }
2862
+ let j = i2 + 1;
2863
+ while (j < code.length && /[\w$.:-]/.test(code[j])) j++;
2864
+ const name = code.slice(i2 + 1, j);
2865
+ if (name) push("jsxTag", name.split(/[.:]/)[0]);
2866
+ stack.push({ k: "tag" });
2867
+ return j;
2868
+ };
2869
+ const closeElement = () => {
2870
+ stack.pop();
2871
+ push("punct", "<>");
2872
+ };
2873
+ let i = 0;
2874
+ while (i < code.length) {
2875
+ const top = stack[stack.length - 1];
2876
+ if (top.k === "code") {
2877
+ i = skipTrivia(i);
2878
+ if (i >= code.length) break;
2879
+ const c = code[i];
2880
+ if (c === '"' || c === "'") {
2881
+ i = skipString2(i, c);
2882
+ push("literal", "''");
2883
+ } else if (c === "`") {
2884
+ stack.push({ k: "template" });
2885
+ i++;
2886
+ } else if (IDENT_START.test(c)) {
2887
+ let j = i + 1;
2888
+ while (j < code.length && IDENT.test(code[j])) j++;
2889
+ push("ident", code.slice(i, j));
2890
+ i = j;
2891
+ } else if (/\d/.test(c) || c === "." && /\d/.test(code[i + 1] ?? "")) {
2892
+ let j = i + 1;
2893
+ while (j < code.length && /[\w.]/.test(code[j])) j++;
2894
+ push("literal", "0");
2895
+ i = j;
2896
+ } else if (c === "/" && expressionNext(top.start)) {
2897
+ i = skipRegex(i);
2898
+ push("literal", "//");
2899
+ } else if (c === "<" && jsx && expressionNext(top.start) && /[A-Za-z_$>]/.test(code[i + 1] ?? "") && !TYPE_PARAMETERS.test(code.slice(i, i + 200))) {
2900
+ i = openElement(i);
2901
+ } else if (c === "{") {
2902
+ top.depth++;
2903
+ push("punct", "{");
2904
+ i++;
2905
+ } else if (c === "}") {
2906
+ i++;
2907
+ if (top.depth === 0 && top.stop) stack.pop();
2908
+ else {
2909
+ top.depth = Math.max(0, top.depth - 1);
2910
+ push("punct", "}");
2911
+ }
2912
+ } else {
2913
+ const three = code.slice(i, i + 3);
2914
+ const two = code.slice(i, i + 2);
2915
+ const p = PUNCT3.includes(three) ? three : PUNCT2.includes(two) ? two : c;
2916
+ push("punct", p);
2917
+ i += p.length;
2918
+ }
2919
+ } else if (top.k === "template") {
2920
+ const c = code[i];
2921
+ if (c === "\\") i += 2;
2922
+ else if (c === "`") {
2923
+ stack.pop();
2924
+ push("literal", "``");
2925
+ i++;
2926
+ } else if (c === "$" && code[i + 1] === "{") {
2927
+ openCode();
2928
+ i += 2;
2929
+ } else i++;
2930
+ } else if (top.k === "tag") {
2931
+ i = skipTrivia(i);
2932
+ const c = code[i];
2933
+ if (c === void 0) break;
2934
+ if (c === "/" && code[i + 1] === ">") {
2935
+ closeElement();
2936
+ i += 2;
2937
+ } else if (c === ">") {
2938
+ stack[stack.length - 1] = { k: "children" };
2939
+ i++;
2940
+ } else if (c === "{") {
2941
+ openCode();
2942
+ i++;
2943
+ } else if (c === '"' || c === "'") i = skipAttribute(i, c);
2944
+ else if (c === "<") i = openElement(i);
2945
+ else i++;
2946
+ } else {
2947
+ const c = code[i];
2948
+ if (c === "<" && code[i + 1] === "/") {
2949
+ const end = code.indexOf(">", i);
2950
+ i = end < 0 ? code.length : end + 1;
2951
+ closeElement();
2952
+ } else if (c === "<" && /[A-Za-z_$>]/.test(code[i + 1] ?? "")) i = openElement(i);
2953
+ else if (c === "{") {
2954
+ openCode();
2955
+ i++;
2956
+ } else i++;
2957
+ }
2958
+ }
2959
+ return tokens;
2960
+ }
2961
+ function usesAsCode(code, name, options = {}) {
2962
+ const tokens = scanCode(code, options);
2963
+ return tokens.some((t, i) => {
2964
+ if (t.value !== name) return false;
2965
+ if (t.kind === "jsxTag") return true;
2966
+ if (t.kind !== "ident") return false;
2967
+ const before = tokens[i - 1];
2968
+ const after = tokens[i + 1];
2969
+ if (before?.value === "." || before?.value === "?." || before?.value === "as" || before?.value === "import") return false;
2970
+ if (after?.value === ":" && (before?.value === "{" || before?.value === ",")) return false;
2971
+ return true;
2972
+ });
2973
+ }
2974
+ var NOT_METHODS = /* @__PURE__ */ new Set(["if", "for", "while", "switch", "with", "function", "return", "typeof", "await", "new"]);
2975
+ var BEFORE_METHOD = /* @__PURE__ */ new Set(["{", "}", ";", ",", "*", "async", "get", "set", "static", "public", "private", "protected", "readonly", "override", "abstract", "declare", "accessor"]);
2976
+ var TYPE_PARAMETERS_REACH = 200;
2977
+ var OPENS = /* @__PURE__ */ new Set(["(", "[", "{"]);
2978
+ var CLOSES = /* @__PURE__ */ new Set([")", "]", "}"]);
2979
+ function boundNames(list) {
2980
+ const out = [];
2981
+ const params = [[]];
2982
+ let depth = 0;
2983
+ let angles = 0;
2984
+ let inType = false;
2985
+ for (const t of list) {
2986
+ if (OPENS.has(t.value)) depth++;
2987
+ else if (CLOSES.has(t.value)) depth--;
2988
+ else if (depth === 0 && t.value === ":") inType = true;
2989
+ else if (depth === 0 && t.value === "=") inType = false;
2990
+ else if (inType && t.value === "<") angles++;
2991
+ else if (inType && (t.value === ">" || t.value === ">>")) angles = Math.max(0, angles - t.value.length);
2992
+ if (depth === 0 && angles === 0 && t.value === ",") {
2993
+ params.push([]);
2994
+ inType = false;
2995
+ } else params[params.length - 1].push(t);
2996
+ }
2997
+ for (const param of params) {
2998
+ let d = 0;
2999
+ let end = param.length;
3000
+ for (let k = 0; k < param.length; k++) {
3001
+ const v = param[k].value;
3002
+ if (OPENS.has(v)) d++;
3003
+ else if (CLOSES.has(v)) d--;
3004
+ else if (d === 0 && (v === "=" || v === ":" || v === "?")) {
3005
+ end = k;
3006
+ break;
3007
+ }
3008
+ }
3009
+ const pattern = param.slice(0, end);
3010
+ let skipping = -1;
3011
+ d = 0;
3012
+ for (let k = 0; k < pattern.length; k++) {
3013
+ const t = pattern[k];
3014
+ if (t.value === "[" && skipping < 0) {
3015
+ let depth2 = 0;
3016
+ let close = k;
3017
+ for (; close < pattern.length; close++) {
3018
+ const v = pattern[close].value;
3019
+ if (OPENS.has(v)) depth2++;
3020
+ else if (CLOSES.has(v) && --depth2 === 0) break;
3021
+ }
3022
+ if (pattern[close + 1]?.value === ":") {
3023
+ k = close;
3024
+ continue;
3025
+ }
3026
+ }
3027
+ if (OPENS.has(t.value)) d++;
3028
+ else if (CLOSES.has(t.value)) {
3029
+ d--;
3030
+ if (skipping > d) skipping = -1;
3031
+ }
3032
+ if (skipping >= 0) {
3033
+ if (t.value === "," && d === skipping) skipping = -1;
3034
+ continue;
3035
+ }
3036
+ if (t.value === "=") {
3037
+ skipping = d;
3038
+ continue;
3039
+ }
3040
+ if (t.kind === "ident" && pattern[k + 1]?.value !== ":") out.push(t.value);
3041
+ }
3042
+ }
3043
+ return out;
3044
+ }
3045
+ function boundAsParameter(code, name, options = {}) {
3046
+ const tokens = scanCode(code, options);
3047
+ const match = new Int32Array(tokens.length).fill(-1);
3048
+ const open = [];
3049
+ tokens.forEach((t, k) => {
3050
+ if (t.value === "(") open.push(k);
3051
+ else if (t.value === ")" && open.length) match[open.pop()] = k;
3052
+ });
3053
+ const arrowAfter = (end) => {
3054
+ const next = tokens[end + 1];
3055
+ if (next?.value === "=>") return true;
3056
+ if (next?.value !== ":") return false;
3057
+ let depth = 0;
3058
+ for (let k = end + 2; k < Math.min(tokens.length, end + 200); k++) {
3059
+ const v = tokens[k].value;
3060
+ if (v === "(" || v === "{" || v === "[" || v === "<") depth++;
3061
+ else if (v === ")" || v === "}" || v === "]" || v === ">") depth--;
3062
+ if (depth < 0) return false;
3063
+ if (depth === 0 && v === "=>") return true;
3064
+ if (depth === 0 && (v === ";" || v === "," || v === "=")) return false;
3065
+ }
3066
+ return false;
3067
+ };
3068
+ const beforeTypeParameters = (paren) => {
3069
+ let k = paren - 1;
3070
+ if (tokens[k]?.value !== ">" && tokens[k]?.value !== ">>") return k;
3071
+ let depth = 0;
3072
+ for (const stop = Math.max(0, k - TYPE_PARAMETERS_REACH); k >= stop; k--) {
3073
+ const v = tokens[k].value;
3074
+ if (v === ">") depth++;
3075
+ else if (v === ">>") depth += 2;
3076
+ else if (v === "<" && --depth === 0) return k - 1;
3077
+ }
3078
+ return -1;
3079
+ };
3080
+ const isFunction = (paren) => {
3081
+ let k = beforeTypeParameters(paren);
3082
+ if (k < 0) return false;
3083
+ if (tokens[k]?.kind === "ident" && tokens[k].value !== "function") k--;
3084
+ if (tokens[k]?.value === "*") k--;
3085
+ return tokens[k]?.value === "function";
3086
+ };
3087
+ for (let i = 0; i < tokens.length; i++) {
3088
+ const t = tokens[i];
3089
+ if (t.value === "=>" && tokens[i - 1]?.kind === "ident" && tokens[i - 1].value === name && tokens[i - 2]?.value !== ".") return true;
3090
+ if (t.value !== "(") continue;
3091
+ const end = match[i];
3092
+ if (end < 0) continue;
3093
+ const before = tokens[i - 1];
3094
+ const catchClause = before?.value === "catch";
3095
+ const nameAt = beforeTypeParameters(i);
3096
+ const methodName = nameAt >= 0 ? tokens[nameAt] : void 0;
3097
+ const typed = tokens[end + 1]?.value === ":" && !arrowAfter(end);
3098
+ const method = !catchClause && methodName?.kind === "ident" && !NOT_METHODS.has(methodName.value) && (tokens[end + 1]?.value === "{" || typed && (nameAt === 0 || BEFORE_METHOD.has(tokens[nameAt - 1].value)));
3099
+ if ((catchClause || isFunction(i) || method || arrowAfter(end)) && boundNames(tokens.slice(i + 1, end)).includes(name)) return true;
3100
+ }
3101
+ return false;
3102
+ }
3103
+
3104
+ // src/doctor/rules.ts
2774
3105
  var BUILTIN_RULES = [
2775
3106
  "local-primitives",
2776
3107
  // figma (figma/routes.ts; runs when genesis.config.json has a figma block)
@@ -2858,7 +3189,13 @@ var BUILTIN_RULES = [
2858
3189
  // custom views and app parts (custom-views.ts)
2859
3190
  "app-part-colors",
2860
3191
  "app-part-name",
2861
- "custom-view-states"
3192
+ "custom-view-states",
3193
+ // the app's client layer (client-layer.ts)
3194
+ "client/layer",
3195
+ "client/one-view-per-resource",
3196
+ // how the app reaches its database (data-access.ts)
3197
+ "data/declared-access",
3198
+ "data/access-rule-tests"
2862
3199
  ];
2863
3200
  var DEFAULT_LOCAL_PRIMITIVE_DIRS = ["src/components/ui"];
2864
3201
  var STARTER_LEFTOVERS = ["components.json", "src/lib/utils.ts"];
@@ -2997,14 +3334,32 @@ function checkShadowedExports(ctx) {
2997
3334
  const re = /\bexport\s+(?:default\s+)?(?:declare\s+)?(?:async\s+)?(?:function\*?|const|let|var|class)\s+([A-Z][\w$]*)/g;
2998
3335
  for (const file of ctx.files) {
2999
3336
  if (!SCRIPT_EXTS.has(file.ext) || insideOverlayOf(overlays, file, ctx.genesis.uiPackage)) continue;
3337
+ const wrapped = wrappedGenesisNames(file.code, ctx.genesis.uiPackage, { jsx: file.ext !== ".ts" && file.ext !== ".mts" });
3000
3338
  file.code.split("\n").forEach((text, i) => {
3001
3339
  for (const m of text.matchAll(re)) {
3002
3340
  if (!ctx.genesis.values.has(m[1])) continue;
3341
+ if (wrapped.has(m[1])) continue;
3003
3342
  ctx.report({ rule: "shadowed-export", file: file.path, line: i + 1, subject: m[1], message: `shadows the Genesis export '${m[1]}'; reuse or extend ${m[1]} from ${ctx.genesis.uiPackage} (or rename yours if it's a different thing)` });
3004
3343
  }
3005
3344
  });
3006
3345
  }
3007
3346
  }
3347
+ function wrappedGenesisNames(code, uiPackage, options = {}) {
3348
+ const out = /* @__PURE__ */ new Set();
3349
+ const pkg = uiPackage.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
3350
+ const re = new RegExp(`\\bimport\\s+(?:type\\s+)?\\{([^}]*)\\}\\s*from\\s*["']${pkg}(?:/[^"']*)?["']`, "g");
3351
+ for (const m of code.matchAll(re)) {
3352
+ if (/^import\s+type\b/.test(m[0])) continue;
3353
+ for (const part of m[1].split(",")) {
3354
+ const spec = part.trim();
3355
+ if (!spec || spec.startsWith("type ")) continue;
3356
+ const [imported, local] = spec.split(/\s+as\s+/).map((x) => x.trim());
3357
+ if (!imported || !local || local === imported) continue;
3358
+ if (usesAsCode(code, local, options)) out.add(imported);
3359
+ }
3360
+ }
3361
+ return out;
3362
+ }
3008
3363
  function unusedComponents(ctx) {
3009
3364
  const used = /* @__PURE__ */ new Set();
3010
3365
  const pkg = ctx.genesis.uiPackage.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
@@ -6134,7 +6489,270 @@ function checkAppParts(ctx) {
6134
6489
  }
6135
6490
  }
6136
6491
  }
6137
- var SCRIPT_EXTS6 = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"]);
6492
+ init_regexp();
6493
+ var JSX_EXTS5 = /* @__PURE__ */ new Set([".tsx", ".jsx"]);
6494
+ var SCRIPT_EXTS6 = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts"]);
6495
+ var DEFAULT_CLIENT_DIR = "src/client";
6496
+ function clientLayer(root, files) {
6497
+ let dir = DEFAULT_CLIENT_DIR;
6498
+ try {
6499
+ dir = readGenesisConfig(root)?.client?.dir ?? DEFAULT_CLIENT_DIR;
6500
+ } catch {
6501
+ }
6502
+ const inside2 = `${dir}/`;
6503
+ const present = files.some((f) => f.path.startsWith(inside2) && /(^|\/)resource-view\.(t|j)sx?$/.test(f.path)) || existsSync(path21.join(root, dir, "resource-view.tsx"));
6504
+ const recordWrapper = files.some((f) => f.path.startsWith(inside2) && /(^|\/)record-view\.(t|j)sx?$/.test(f.path)) || existsSync(path21.join(root, dir, "record-view.tsx"));
6505
+ return { dir, present, recordWrapper };
6506
+ }
6507
+ function genesisImports(code, uiPackage) {
6508
+ const out = /* @__PURE__ */ new Map();
6509
+ const escaped = uiPackage.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
6510
+ const re = new RegExp(`import\\s*(?:type\\s+)?\\{([^}]*)\\}\\s*from\\s*["']${escaped}(?:/data)?["']`, "g");
6511
+ for (const m of code.matchAll(re)) {
6512
+ if (/^\s*type\s/.test(m[0].slice(6))) continue;
6513
+ for (const part of m[1].split(",")) {
6514
+ const spec = part.trim().replace(/^type\s+/, "");
6515
+ if (!spec || part.trim().startsWith("type ")) continue;
6516
+ const [imported, local] = spec.split(/\s+as\s+/).map((x) => x.trim());
6517
+ if (imported === "ResourceView" || imported === "RecordView") out.set(local ?? imported, imported);
6518
+ }
6519
+ }
6520
+ return out;
6521
+ }
6522
+ function checkClientLayer(ctx) {
6523
+ const layer = clientLayer(ctx.root, ctx.files);
6524
+ const inside2 = `${layer.dir}/`;
6525
+ if (layer.present) {
6526
+ for (const file of ctx.files) {
6527
+ if (!JSX_EXTS5.has(file.ext) || file.path.startsWith(inside2)) continue;
6528
+ const imported = genesisImports(file.code, ctx.genesis.uiPackage);
6529
+ for (const [local, name] of imported) {
6530
+ if (name === "RecordView" && !layer.recordWrapper) continue;
6531
+ const at = file.code.search(new RegExp(`<${local}\\b`));
6532
+ if (at < 0) continue;
6533
+ ctx.report({
6534
+ rule: "client/layer",
6535
+ level: "warn",
6536
+ file: file.path,
6537
+ line: lineAt(file.code, at),
6538
+ subject: name,
6539
+ message: `renders Genesis's <${name}> directly; the app has a client layer (${layer.dir}), so render its ${name === "ResourceView" ? "ResourceView from resource-view.tsx" : "RecordView from record-view.tsx"}, and its defaults reach this screen too (docs/adr/0020-client-layer.md)`
6540
+ });
6541
+ }
6542
+ }
6543
+ }
6544
+ if (!layer.present) return;
6545
+ const seen = /* @__PURE__ */ new Map();
6546
+ for (const file of ctx.files) {
6547
+ if (!SCRIPT_EXTS6.has(file.ext) || SHOWN_OR_TRIED.test(file.path)) continue;
6548
+ const imports = importedNames(file.path, file.code);
6549
+ for (const m of file.code.matchAll(/\bdefineView\s*(?:<[^>]*>)?\s*\(\s*([A-Za-z_$][\w$]*)((?:\s*(?:\.\s*[A-Za-z_$][\w$]*|\[\s*["'`][^"'`]+["'`]\s*\]))*)\s*[,)]/g)) {
6550
+ const base = m[1];
6551
+ const access = m[2].replace(/\s+/g, "").replace(/'|`/g, '"');
6552
+ const imported = imports.get(base);
6553
+ if (!imported && !declaredAtTop(file.code, base)) continue;
6554
+ if (boundAsParameter(file.code, base, { jsx: file.ext !== ".ts" && file.ext !== ".mts" })) continue;
6555
+ const identity = `${imported ?? `${file.path}#${base}`}${access}`;
6556
+ const shown = `${base}${access}`;
6557
+ const line = lineAt(file.code, m.index ?? 0);
6558
+ const first = seen.get(identity);
6559
+ if (!first) {
6560
+ seen.set(identity, { file: file.path, line });
6561
+ continue;
6562
+ }
6563
+ ctx.report({
6564
+ rule: "client/one-view-per-resource",
6565
+ level: "warn",
6566
+ file: file.path,
6567
+ line,
6568
+ subject: shown,
6569
+ message: `defines a second view over ${shown} (the first is in ${first.file}:${first.line}); keep one view per resource and narrow it on the screen (preset, filter, columns), so its rules can't drift (docs/adr/0020-client-layer.md)`
6570
+ });
6571
+ }
6572
+ }
6573
+ }
6574
+ function declaredAtTop(code, name) {
6575
+ const escaped = escapeRegExp(name);
6576
+ return new RegExp(`^(?:export\\s+)?(?:const|let|var)\\s+${escaped}\\b`, "m").test(code);
6577
+ }
6578
+ var SHOWN_OR_TRIED = /(\.stories\.|\.test\.|\.spec\.|(^|\/)__tests__\/)/;
6579
+ function importedNames(filePath, code) {
6580
+ const out = /* @__PURE__ */ new Map();
6581
+ const dir = path21.posix.dirname(filePath);
6582
+ const where2 = (spec) => spec.startsWith(".") ? path21.posix.normalize(path21.posix.join(dir, spec)).replace(/\.(t|j)sx?$/, "").replace(/\/index$/, "") : spec;
6583
+ for (const m of code.matchAll(/import\s+(?:type\s+)?\{([^}]*)\}\s*from\s*["']([^"']+)["']/g)) {
6584
+ for (const part of m[1].split(",")) {
6585
+ const spec = part.trim().replace(/^type\s+/, "");
6586
+ if (!spec) continue;
6587
+ const [imported, local] = spec.split(/\s+as\s+/).map((x) => x.trim());
6588
+ out.set(local ?? imported, `${where2(m[2])}#${imported}`);
6589
+ }
6590
+ }
6591
+ for (const m of code.matchAll(/import\s+(?:\*\s+as\s+)?([A-Za-z_$][\w$]*)\s+from\s*["']([^"']+)["']/g)) out.set(m[1], `${where2(m[2])}#*`);
6592
+ return out;
6593
+ }
6594
+ var SCRIPT_EXTS7 = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"]);
6595
+ var SKIP_DIRS4 = /* @__PURE__ */ new Set(["node_modules", "dist", "build", ".git", ".next", ".output", ".turbo", "coverage", ".expo"]);
6596
+ var TEST_FILE = /(^|\/)(__tests__\/|[^/]+\.(test|spec)\.[cm]?[jt]sx?$)/;
6597
+ var DOCS = "docs/DATA-ACCESS.md";
6598
+ var TABLE_WRITE = /\.from\(\s*(["'`])([\w.]+)\1\s*\)\s*\.\s*(insert|update|upsert|delete)\s*\(/g;
6599
+ var STORAGE_BEFORE = /\bstorage\s*\??\.?\s*$/;
6600
+ function balanced(code, start) {
6601
+ const open = code[start];
6602
+ const close = open === "{" ? "}" : open === "(" ? ")" : open === "[" ? "]" : "";
6603
+ if (!close) return "";
6604
+ const blank = blankStrings(code);
6605
+ let depth = 0;
6606
+ for (let i = start; i < blank.length; i++) {
6607
+ const ch = blank[i];
6608
+ if (ch === "{" || ch === "(" || ch === "[") depth++;
6609
+ else if (ch === "}" || ch === ")" || ch === "]") {
6610
+ depth--;
6611
+ if (depth === 0) return ch === close ? code.slice(start, i + 1) : "";
6612
+ }
6613
+ }
6614
+ return "";
6615
+ }
6616
+ function testFiles(root) {
6617
+ const out = [];
6618
+ const walk3 = (dir) => {
6619
+ let entries;
6620
+ try {
6621
+ entries = readdirSync(dir, { withFileTypes: true });
6622
+ } catch {
6623
+ return;
6624
+ }
6625
+ for (const entry of entries) {
6626
+ if (entry.isDirectory()) {
6627
+ if (!SKIP_DIRS4.has(entry.name) && !entry.name.startsWith(".")) walk3(path21.join(dir, entry.name));
6628
+ continue;
6629
+ }
6630
+ const abs = path21.join(dir, entry.name);
6631
+ const rel = path21.relative(root, abs).split(path21.sep).join("/");
6632
+ if (SCRIPT_EXTS7.has(path21.extname(entry.name)) && TEST_FILE.test(rel)) out.push(abs);
6633
+ }
6634
+ };
6635
+ walk3(root);
6636
+ return out;
6637
+ }
6638
+ function initializer(code, blank, name) {
6639
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
6640
+ const decl = new RegExp(`\\b(const|let|var)\\s+${escaped}(?![\\w$])[^=;]*=\\s*\\{`).exec(blank);
6641
+ if (!decl) return null;
6642
+ const text = balanced(code, decl.index + decl[0].length - 1);
6643
+ return text ? { text, keyword: decl[1], at: decl.index } : null;
6644
+ }
6645
+ function objectDeclares(object) {
6646
+ const blank = blankStrings(object);
6647
+ let depth = 0;
6648
+ let declaredAt = -1;
6649
+ let lastAccess = -1;
6650
+ let lastSpread = -1;
6651
+ for (let i = 0; i < blank.length; i++) {
6652
+ const ch = blank[i];
6653
+ if (ch === "{" || ch === "(" || ch === "[") depth++;
6654
+ else if (ch === "}" || ch === ")" || ch === "]") depth--;
6655
+ else if (depth === 1 && blank.startsWith("...", i)) lastSpread = i;
6656
+ else if (depth === 1 && blank[i] === object[i] && /[\s{,]/.test(blank[i - 1] ?? " ") && /^(["'`]?)access\1\s*:/.test(object.slice(i))) {
6657
+ lastAccess = i;
6658
+ const value = /^(["'`]?)access\1\s*:\s*(["'`])([^"'`]*)\2/.exec(object.slice(i));
6659
+ declaredAt = value?.[3] === "declared" ? i : -1;
6660
+ }
6661
+ }
6662
+ return declaredAt !== -1 && declaredAt === lastAccess && lastSpread < declaredAt;
6663
+ }
6664
+ function inlineDeclares(call) {
6665
+ const blank = blankStrings(call);
6666
+ let depth = 0;
6667
+ for (let i = 0; i < blank.length; i++) {
6668
+ const ch = blank[i];
6669
+ if (ch === "{" && depth === 1 && objectDeclares(balanced(call, i))) return true;
6670
+ if (ch === "{" || ch === "(" || ch === "[") depth++;
6671
+ else if (ch === "}" || ch === ")" || ch === "]") depth--;
6672
+ }
6673
+ return false;
6674
+ }
6675
+ function optionsConstDeclares(code, blank, call) {
6676
+ const args = blankStrings(call).slice(1, -1);
6677
+ for (const [, name] of args.matchAll(/(?:^|,)\s*([A-Za-z_$][\w$]*)\s*(?=,|$)/g)) {
6678
+ const found = initializer(code, blank, name);
6679
+ if (!found || !objectDeclares(found.text)) continue;
6680
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
6681
+ const reassigned = found.keyword !== "const" && new RegExp(`(?<![\\w$.])${escaped}\\s*=(?!=)`, "g").test(blank.slice(found.at + found.keyword.length + 1 + name.length));
6682
+ const changed = new RegExp(
6683
+ `(?<![\\w$.])${escaped}\\s*(?:\\.\\s*access|\\[[^\\]]*\\])\\s*=(?!=)|\\bdelete\\s+${escaped}\\s*(?:\\.\\s*access|\\[)|Object\\.assign\\(\\s*${escaped}(?![\\w$])`
6684
+ ).test(blank);
6685
+ if (!reassigned && !changed) return true;
6686
+ }
6687
+ return false;
6688
+ }
6689
+ function coverageTested(root) {
6690
+ for (const abs of testFiles(root)) {
6691
+ let code;
6692
+ try {
6693
+ code = stripBlockComments(readFileSync(abs, "utf8"), true);
6694
+ } catch {
6695
+ continue;
6696
+ }
6697
+ if (!code.includes("expectAccessRulesCover")) continue;
6698
+ if (/\bexpectAccessRulesCover\s*\(/.test(blankStrings(code))) return true;
6699
+ }
6700
+ return false;
6701
+ }
6702
+ function checkDataAccess(ctx) {
6703
+ for (const file of ctx.files) {
6704
+ if (!SCRIPT_EXTS7.has(file.ext)) continue;
6705
+ const blank = blankStrings(file.code);
6706
+ for (const m of blank.matchAll(/\bcreateSupabaseProvider\s*\(/g)) {
6707
+ const call = balanced(file.code, (m.index ?? 0) + m[0].length - 1);
6708
+ if (inlineDeclares(call) || optionsConstDeclares(file.code, blank, call)) continue;
6709
+ ctx.report({
6710
+ rule: "data/declared-access",
6711
+ level: "warn",
6712
+ file: file.path,
6713
+ line: lineAt(file.code, m.index ?? 0),
6714
+ subject: "createSupabaseProvider",
6715
+ message: `leaves its resources free to read and write their tables undeclared. Pass access: "declared", give each resource its read (source: a view or a function) and its writes (writes: named database functions), and opt a table in only with table: { \u2026, why } (${DOCS})`
6716
+ });
6717
+ }
6718
+ if (file.path.startsWith("supabase/") || file.path.includes("/supabase/functions/")) continue;
6719
+ for (const m of file.code.matchAll(TABLE_WRITE)) {
6720
+ const at = m.index ?? 0;
6721
+ if (blank[at] !== ".") continue;
6722
+ if (STORAGE_BEFORE.test(blank.slice(Math.max(0, at - 40), at))) continue;
6723
+ ctx.report({
6724
+ rule: "data/declared-access",
6725
+ level: "warn",
6726
+ file: file.path,
6727
+ line: lineAt(file.code, at),
6728
+ subject: `${m[2]}.${m[3]}`,
6729
+ message: `writes the ${m[2]} table directly (${m[3]}). Write through a named database function (the resource's writes, or a call to it), which holds the access rule; a write that must stay on the table is an allow entry for data/declared-access with its reason (${DOCS})`
6730
+ });
6731
+ }
6732
+ }
6733
+ const providers = providerCalls(ctx.files);
6734
+ if (providers.length === 0 || coverageTested(ctx.root)) return;
6735
+ const first = providers[0];
6736
+ ctx.report({
6737
+ rule: "data/access-rule-tests",
6738
+ level: "warn",
6739
+ file: first.file,
6740
+ line: first.line,
6741
+ subject: "expectAccessRulesCover",
6742
+ message: `no test checks that every database function the provider declares has an access-rule test. Add expectAccessRulesCover(providerOptions, [/* each accessRules spec */]) (@marktiderman/genesis-core/testing) to a test file: it fails for each declared function without one (${DOCS})`
6743
+ });
6744
+ }
6745
+ function providerCalls(files) {
6746
+ const out = [];
6747
+ for (const file of files) {
6748
+ if (!SCRIPT_EXTS7.has(file.ext)) continue;
6749
+ for (const m of blankStrings(file.code).matchAll(/\bcreateSupabaseProvider\s*\(/g)) {
6750
+ out.push({ file: file.path, line: lineAt(file.code, m.index ?? 0) });
6751
+ }
6752
+ }
6753
+ return out;
6754
+ }
6755
+ var SCRIPT_EXTS8 = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"]);
6138
6756
  var DECLARATION = /\/\*\*((?:(?!\*\/)[\s\S])*)\*\/\s*\n(?:export\s+)?(?:declare\s+)?(?:abstract\s+)?(?:function|const|let|class|interface|type|enum|namespace)\s+([A-Za-z_$][\w$]*)/g;
6139
6757
  var REEXPORT = /\/\*\*((?:(?!\*\/)[\s\S])*)\*\/\s*\nexport\s+(?:type\s+)?\{([^}]*)\}/g;
6140
6758
  function specifierParts(spec) {
@@ -6224,7 +6842,7 @@ function checkStabilityImports(ctx) {
6224
6842
  return cache2.get(pkg);
6225
6843
  };
6226
6844
  for (const file of ctx.files) {
6227
- if (!SCRIPT_EXTS6.has(file.ext)) continue;
6845
+ if (!SCRIPT_EXTS8.has(file.ext)) continue;
6228
6846
  for (const { pkg, specifier, names, line } of genesisNamedImports(file.code)) {
6229
6847
  const tags = tagsOf(pkg);
6230
6848
  if (!tags) continue;
@@ -6683,6 +7301,7 @@ var RULES = [
6683
7301
  "Never copy an older screen as a template. Old screens predate the primitives; the doctor flags what they did.",
6684
7302
  "A list screen is a view (`defineView`) rendered by `ResourceView`; a record view is `RecordView`; on the phone, `NativeResourceView`.",
6685
7303
  "Screens never call the database client (`supabase.from`, `.rpc`) directly: reads go through a view or a named data function, writes through the resource's provider rules.",
7304
+ `Data access is declared: the Supabase provider runs with \`access: "declared"\`; each resource reads through a view or a function (\`source\`) and writes through named database functions (\`writes\`, \`actions\`) that hold the access rule; a table is touched only with \`table: { \u2026, why }\`. Every declared function gets an access-rule test (\`accessRules\`), and one test (\`expectAccessRulesCover\`) fails for any declared function whose name no spec carries: it compares names only, so give it the same specs the cases are registered from. See ${GENESIS_DOCS}/DATA-ACCESS.md.`,
6686
7305
  "When a Genesis piece is close and does the same job, extend it: a prop, a variant, a slot, or your own component that wraps it. Never build a parallel copy beside it.",
6687
7306
  "When no Genesis piece does the job, invent it in the app: your own screens and components, on Genesis tokens and primitives. Genesis asks for no write-up or approval first (your app's own design review still applies); you may add it to `docs/genesis-upstream.md` if you think Genesis should have it.",
6688
7307
  "Run `genesis doctor` before you finish; it enforces these rules."
@@ -7830,6 +8449,8 @@ function builtinChecks(config, options = {}) {
7830
8449
  { name: "studio-server-imports", check: checkStudioServerImports },
7831
8450
  { name: "removed-scope-names", check: checkRemovedScopeNames },
7832
8451
  { name: "app-parts", check: checkAppParts },
8452
+ { name: "client-layer", check: checkClientLayer },
8453
+ { name: "data-access", check: checkDataAccess },
7833
8454
  { name: "stability-imports", check: checkStabilityImports },
7834
8455
  { name: "agent-guide", check: (ctx) => {
7835
8456
  checkAgentGuide(ctx);