@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/index.js CHANGED
@@ -25,6 +25,15 @@ var __export = (target, all) => {
25
25
  __defProp(target, name, { get: all[name], enumerable: true });
26
26
  };
27
27
 
28
+ // src/regexp.ts
29
+ function escapeRegExp(s) {
30
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
31
+ }
32
+ var init_regexp = __esm({
33
+ "src/regexp.ts"() {
34
+ }
35
+ });
36
+
28
37
  // src/introspect/catalog-text.ts
29
38
  function tokenize(tree) {
30
39
  const tokens = [];
@@ -154,9 +163,6 @@ function splitTopLevel(expr, separator) {
154
163
  parts.push(expr.slice(from));
155
164
  return parts;
156
165
  }
157
- function escapeRegExp(s) {
158
- return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
159
- }
160
166
  function checkEnumValues(definition, column) {
161
167
  const outer = /^CHECK \((.*)\)(?: NOT VALID)?$/s.exec(definition.trim());
162
168
  if (!outer) return void 0;
@@ -191,6 +197,7 @@ function checkEnumValues(definition, column) {
191
197
  var CAST, LITERAL;
192
198
  var init_catalog_text = __esm({
193
199
  "src/introspect/catalog-text.ts"() {
200
+ init_regexp();
194
201
  CAST = String.raw`::[a-z][a-z ]*(?:\(\d+(?:,\d+)?\))?`;
195
202
  LITERAL = String.raw`'((?:[^']|'')*)'${CAST}`;
196
203
  }
@@ -826,9 +833,9 @@ async function runScaffold(opts, fs) {
826
833
  function joinPath(...parts) {
827
834
  return parts.filter(Boolean).join("/").replace(/\/+/g, "/");
828
835
  }
829
- function dirname(path49) {
830
- const idx = path49.lastIndexOf("/");
831
- return idx === -1 ? "." : path49.slice(0, idx);
836
+ function dirname(path51) {
837
+ const idx = path51.lastIndexOf("/");
838
+ return idx === -1 ? "." : path51.slice(0, idx);
832
839
  }
833
840
  function brandPackageJson(consumer, genesisVersion) {
834
841
  return JSON.stringify(
@@ -1086,8 +1093,8 @@ function routeTags(source) {
1086
1093
  var GUARD = /<((?:[A-Z]\w*)?(?:Admin|Staff)\w*(?:Guard|Route|Only)|RequireAdmin|RequireStaff)>/;
1087
1094
  function wireStudioRoute(source, route, pageImportPath) {
1088
1095
  const tags = routeTags(source);
1089
- const relative14 = route.replace(/^\//, "");
1090
- const existing = tags.find((t) => new RegExp(`path=["'](/?${relative14.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})["']`).test(t.text));
1096
+ const relative15 = route.replace(/^\//, "");
1097
+ const existing = tags.find((t) => new RegExp(`path=["'](/?${relative15.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})["']`).test(t.text));
1091
1098
  if (existing) {
1092
1099
  return { skipped: `Your router already has a page at ${route}. Replace its element with <DataStudioPage /> to use the studio there.` };
1093
1100
  }
@@ -1095,17 +1102,17 @@ function wireStudioRoute(source, route, pageImportPath) {
1095
1102
  const roots = layouts.length ? layouts : tags.filter((t) => !t.selfClosing && t.close !== void 0 && /path=["']\/["']/.test(t.text));
1096
1103
  if (roots.length !== 1) {
1097
1104
  return {
1098
- skipped: roots.length === 0 ? `No layout route found to put the page under. Add <Route path="${route}" element={<DataStudioPage />} /> where your app's other pages are.` : `More than one layout route; add <Route path="${relative14}" element={<DataStudioPage />} /> inside the one your other admin pages use.`
1105
+ skipped: roots.length === 0 ? `No layout route found to put the page under. Add <Route path="${route}" element={<DataStudioPage />} /> where your app's other pages are.` : `More than one layout route; add <Route path="${relative15}" element={<DataStudioPage />} /> inside the one your other admin pages use.`
1099
1106
  };
1100
1107
  }
1101
1108
  const layout = roots[0];
1102
1109
  const base = (/\bpath=["']([^"']*)["']/.exec(layout.text)?.[1] ?? "").replace(/^\/+|\/+$/g, "");
1103
- if (base && !relative14.startsWith(`${base}/`)) {
1110
+ if (base && !relative15.startsWith(`${base}/`)) {
1104
1111
  return {
1105
1112
  skipped: `Your layout route lives at /${base}, outside ${route}. Add <Route path="${route}" element={<DataStudioPage />} /> where your app's other pages are.`
1106
1113
  };
1107
1114
  }
1108
- const childPath = base ? relative14.slice(base.length + 1) : relative14;
1115
+ const childPath = base ? relative15.slice(base.length + 1) : relative15;
1109
1116
  const guard = GUARD.exec(source)?.[1];
1110
1117
  const element = guard ? `<${guard}><DataStudioPage /></${guard}>` : "<DataStudioPage />";
1111
1118
  const before = source.slice(0, layout.close);
@@ -1626,6 +1633,7 @@ function readGenesisConfig(root) {
1626
1633
  }
1627
1634
  if (raw.appFolder !== void 0) out.appFolder = validateAppFolder(raw.appFolder, file);
1628
1635
  if (raw.environments !== void 0) out.environments = validateEnvironments(raw.environments, file);
1636
+ if (raw.client !== void 0) out.client = validateClient(raw.client, file);
1629
1637
  return out;
1630
1638
  }
1631
1639
  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}$/;
@@ -1637,6 +1645,16 @@ function validateAppFolder(raw, source = "config") {
1637
1645
  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)})`);
1638
1646
  return norm;
1639
1647
  }
1648
+ function validateClient(raw, source = "config") {
1649
+ const fail = (msg) => {
1650
+ throw new GenesisConfigError(`${source}: ${msg}`);
1651
+ };
1652
+ if (!isObject(raw)) return fail(`"client" must be { "dir": "<the client layer's folder, e.g. src/client>" }`);
1653
+ for (const key2 of Object.keys(raw)) if (key2 !== "dir" && key2 !== "$comment") fail(`client: unknown setting "${key2}" (known: dir)`);
1654
+ const dir = typeof raw.dir === "string" ? raw.dir.replace(/^\.\//, "").replace(/\/+$/, "") : "";
1655
+ if (!isPlainFolder(dir)) return fail(`client.dir must be a folder inside the app, such as "src/client" (got ${JSON.stringify(raw.dir)})`);
1656
+ return { dir };
1657
+ }
1640
1658
  function validateSupabase(raw, source = "config") {
1641
1659
  const fail = (msg) => {
1642
1660
  throw new GenesisConfigError(`${source}: ${msg}`);
@@ -1900,7 +1918,7 @@ function globToRegExp(glob) {
1900
1918
  }
1901
1919
  function globMatcher(globs) {
1902
1920
  const res = (globs ?? []).filter((g) => g.trim()).map(globToRegExp);
1903
- return (path49) => res.some((re) => re.test(path49));
1921
+ return (path51) => res.some((re) => re.test(path51));
1904
1922
  }
1905
1923
  var GENESIS_PACKAGE = /^@marktiderman\/genesis(-[a-z0-9-]+)?$/;
1906
1924
  var BLOCK_ID = /^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/;
@@ -3462,6 +3480,319 @@ function resolvePlugin(id, configDir) {
3462
3480
  function resolveFrom(id, from) {
3463
3481
  return createRequire(path21.join(from, "noop.js")).resolve(id);
3464
3482
  }
3483
+
3484
+ // src/doctor/js-scan.ts
3485
+ var IDENT_START = /[A-Za-z_$]/;
3486
+ var IDENT = /[\w$]/;
3487
+ var PUNCT3 = ["...", "===", "!==", "**=", "<<=", ">>=", "??=", "&&=", "||="];
3488
+ var PUNCT2 = ["=>", "==", "!=", "<=", ">=", "&&", "||", "??", "?.", "++", "--", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "**", "<<", ">>"];
3489
+ var EXPRESSION_KEYWORDS = /* @__PURE__ */ new Set(["return", "typeof", "case", "do", "else", "in", "new", "delete", "void", "throw", "yield", "await", "instanceof"]);
3490
+ var TYPE_PARAMETERS = /^<\s*[A-Za-z_$][\w$]*\s*(?:,|extends\b)/;
3491
+ function scanCode(code, options = {}) {
3492
+ const jsx = options.jsx ?? true;
3493
+ const tokens = [];
3494
+ const push = (kind, value) => tokens.push({ kind, value, index: tokens.length });
3495
+ const expressionNext = (start) => {
3496
+ if (tokens.length <= start) return true;
3497
+ const t = tokens[tokens.length - 1];
3498
+ if (!t) return true;
3499
+ if (t.kind === "ident") return EXPRESSION_KEYWORDS.has(t.value);
3500
+ if (t.kind === "jsxTag" || t.kind === "literal") return false;
3501
+ return !(t.value === ")" || t.value === "]" || t.value === "}" || t.value === "<>");
3502
+ };
3503
+ const skipString2 = (i2, quote2) => {
3504
+ let j = i2 + 1;
3505
+ while (j < code.length && code[j] !== quote2) {
3506
+ if (code[j] === "\\") j++;
3507
+ else if (code[j] === "\n") return j;
3508
+ j++;
3509
+ }
3510
+ return j + 1;
3511
+ };
3512
+ const skipAttribute = (i2, quote2) => {
3513
+ const end = code.indexOf(quote2, i2 + 1);
3514
+ return end < 0 ? code.length : end + 1;
3515
+ };
3516
+ const skipRegex = (i2) => {
3517
+ let j = i2 + 1;
3518
+ let inClass = false;
3519
+ while (j < code.length && code[j] !== "\n") {
3520
+ const c = code[j];
3521
+ if (c === "\\") j++;
3522
+ else if (c === "[") inClass = true;
3523
+ else if (c === "]") inClass = false;
3524
+ else if (c === "/" && !inClass) {
3525
+ j++;
3526
+ while (j < code.length && IDENT.test(code[j])) j++;
3527
+ return j;
3528
+ }
3529
+ j++;
3530
+ }
3531
+ return j;
3532
+ };
3533
+ const skipTrivia = (i2) => {
3534
+ let j = i2;
3535
+ for (; ; ) {
3536
+ while (j < code.length && /\s/.test(code[j])) j++;
3537
+ if (code.startsWith("//", j)) {
3538
+ const end = code.indexOf("\n", j);
3539
+ j = end < 0 ? code.length : end;
3540
+ } else if (code.startsWith("/*", j)) {
3541
+ const end = code.indexOf("*/", j + 2);
3542
+ j = end < 0 ? code.length : end + 2;
3543
+ } else return j;
3544
+ }
3545
+ };
3546
+ const stack = [{ k: "code", depth: 0, stop: false, start: 0 }];
3547
+ const openCode = () => stack.push({ k: "code", depth: 0, stop: true, start: tokens.length });
3548
+ const openElement = (i2) => {
3549
+ if (code[i2 + 1] === ">") {
3550
+ stack.push({ k: "children" });
3551
+ return i2 + 2;
3552
+ }
3553
+ let j = i2 + 1;
3554
+ while (j < code.length && /[\w$.:-]/.test(code[j])) j++;
3555
+ const name = code.slice(i2 + 1, j);
3556
+ if (name) push("jsxTag", name.split(/[.:]/)[0]);
3557
+ stack.push({ k: "tag" });
3558
+ return j;
3559
+ };
3560
+ const closeElement = () => {
3561
+ stack.pop();
3562
+ push("punct", "<>");
3563
+ };
3564
+ let i = 0;
3565
+ while (i < code.length) {
3566
+ const top = stack[stack.length - 1];
3567
+ if (top.k === "code") {
3568
+ i = skipTrivia(i);
3569
+ if (i >= code.length) break;
3570
+ const c = code[i];
3571
+ if (c === '"' || c === "'") {
3572
+ i = skipString2(i, c);
3573
+ push("literal", "''");
3574
+ } else if (c === "`") {
3575
+ stack.push({ k: "template" });
3576
+ i++;
3577
+ } else if (IDENT_START.test(c)) {
3578
+ let j = i + 1;
3579
+ while (j < code.length && IDENT.test(code[j])) j++;
3580
+ push("ident", code.slice(i, j));
3581
+ i = j;
3582
+ } else if (/\d/.test(c) || c === "." && /\d/.test(code[i + 1] ?? "")) {
3583
+ let j = i + 1;
3584
+ while (j < code.length && /[\w.]/.test(code[j])) j++;
3585
+ push("literal", "0");
3586
+ i = j;
3587
+ } else if (c === "/" && expressionNext(top.start)) {
3588
+ i = skipRegex(i);
3589
+ push("literal", "//");
3590
+ } else if (c === "<" && jsx && expressionNext(top.start) && /[A-Za-z_$>]/.test(code[i + 1] ?? "") && !TYPE_PARAMETERS.test(code.slice(i, i + 200))) {
3591
+ i = openElement(i);
3592
+ } else if (c === "{") {
3593
+ top.depth++;
3594
+ push("punct", "{");
3595
+ i++;
3596
+ } else if (c === "}") {
3597
+ i++;
3598
+ if (top.depth === 0 && top.stop) stack.pop();
3599
+ else {
3600
+ top.depth = Math.max(0, top.depth - 1);
3601
+ push("punct", "}");
3602
+ }
3603
+ } else {
3604
+ const three = code.slice(i, i + 3);
3605
+ const two = code.slice(i, i + 2);
3606
+ const p = PUNCT3.includes(three) ? three : PUNCT2.includes(two) ? two : c;
3607
+ push("punct", p);
3608
+ i += p.length;
3609
+ }
3610
+ } else if (top.k === "template") {
3611
+ const c = code[i];
3612
+ if (c === "\\") i += 2;
3613
+ else if (c === "`") {
3614
+ stack.pop();
3615
+ push("literal", "``");
3616
+ i++;
3617
+ } else if (c === "$" && code[i + 1] === "{") {
3618
+ openCode();
3619
+ i += 2;
3620
+ } else i++;
3621
+ } else if (top.k === "tag") {
3622
+ i = skipTrivia(i);
3623
+ const c = code[i];
3624
+ if (c === void 0) break;
3625
+ if (c === "/" && code[i + 1] === ">") {
3626
+ closeElement();
3627
+ i += 2;
3628
+ } else if (c === ">") {
3629
+ stack[stack.length - 1] = { k: "children" };
3630
+ i++;
3631
+ } else if (c === "{") {
3632
+ openCode();
3633
+ i++;
3634
+ } else if (c === '"' || c === "'") i = skipAttribute(i, c);
3635
+ else if (c === "<") i = openElement(i);
3636
+ else i++;
3637
+ } else {
3638
+ const c = code[i];
3639
+ if (c === "<" && code[i + 1] === "/") {
3640
+ const end = code.indexOf(">", i);
3641
+ i = end < 0 ? code.length : end + 1;
3642
+ closeElement();
3643
+ } else if (c === "<" && /[A-Za-z_$>]/.test(code[i + 1] ?? "")) i = openElement(i);
3644
+ else if (c === "{") {
3645
+ openCode();
3646
+ i++;
3647
+ } else i++;
3648
+ }
3649
+ }
3650
+ return tokens;
3651
+ }
3652
+ function usesAsCode(code, name, options = {}) {
3653
+ const tokens = scanCode(code, options);
3654
+ return tokens.some((t, i) => {
3655
+ if (t.value !== name) return false;
3656
+ if (t.kind === "jsxTag") return true;
3657
+ if (t.kind !== "ident") return false;
3658
+ const before = tokens[i - 1];
3659
+ const after = tokens[i + 1];
3660
+ if (before?.value === "." || before?.value === "?." || before?.value === "as" || before?.value === "import") return false;
3661
+ if (after?.value === ":" && (before?.value === "{" || before?.value === ",")) return false;
3662
+ return true;
3663
+ });
3664
+ }
3665
+ var NOT_METHODS = /* @__PURE__ */ new Set(["if", "for", "while", "switch", "with", "function", "return", "typeof", "await", "new"]);
3666
+ var BEFORE_METHOD = /* @__PURE__ */ new Set(["{", "}", ";", ",", "*", "async", "get", "set", "static", "public", "private", "protected", "readonly", "override", "abstract", "declare", "accessor"]);
3667
+ var TYPE_PARAMETERS_REACH = 200;
3668
+ var OPENS = /* @__PURE__ */ new Set(["(", "[", "{"]);
3669
+ var CLOSES = /* @__PURE__ */ new Set([")", "]", "}"]);
3670
+ function boundNames(list) {
3671
+ const out = [];
3672
+ const params = [[]];
3673
+ let depth = 0;
3674
+ let angles = 0;
3675
+ let inType = false;
3676
+ for (const t of list) {
3677
+ if (OPENS.has(t.value)) depth++;
3678
+ else if (CLOSES.has(t.value)) depth--;
3679
+ else if (depth === 0 && t.value === ":") inType = true;
3680
+ else if (depth === 0 && t.value === "=") inType = false;
3681
+ else if (inType && t.value === "<") angles++;
3682
+ else if (inType && (t.value === ">" || t.value === ">>")) angles = Math.max(0, angles - t.value.length);
3683
+ if (depth === 0 && angles === 0 && t.value === ",") {
3684
+ params.push([]);
3685
+ inType = false;
3686
+ } else params[params.length - 1].push(t);
3687
+ }
3688
+ for (const param of params) {
3689
+ let d = 0;
3690
+ let end = param.length;
3691
+ for (let k = 0; k < param.length; k++) {
3692
+ const v = param[k].value;
3693
+ if (OPENS.has(v)) d++;
3694
+ else if (CLOSES.has(v)) d--;
3695
+ else if (d === 0 && (v === "=" || v === ":" || v === "?")) {
3696
+ end = k;
3697
+ break;
3698
+ }
3699
+ }
3700
+ const pattern = param.slice(0, end);
3701
+ let skipping = -1;
3702
+ d = 0;
3703
+ for (let k = 0; k < pattern.length; k++) {
3704
+ const t = pattern[k];
3705
+ if (t.value === "[" && skipping < 0) {
3706
+ let depth2 = 0;
3707
+ let close = k;
3708
+ for (; close < pattern.length; close++) {
3709
+ const v = pattern[close].value;
3710
+ if (OPENS.has(v)) depth2++;
3711
+ else if (CLOSES.has(v) && --depth2 === 0) break;
3712
+ }
3713
+ if (pattern[close + 1]?.value === ":") {
3714
+ k = close;
3715
+ continue;
3716
+ }
3717
+ }
3718
+ if (OPENS.has(t.value)) d++;
3719
+ else if (CLOSES.has(t.value)) {
3720
+ d--;
3721
+ if (skipping > d) skipping = -1;
3722
+ }
3723
+ if (skipping >= 0) {
3724
+ if (t.value === "," && d === skipping) skipping = -1;
3725
+ continue;
3726
+ }
3727
+ if (t.value === "=") {
3728
+ skipping = d;
3729
+ continue;
3730
+ }
3731
+ if (t.kind === "ident" && pattern[k + 1]?.value !== ":") out.push(t.value);
3732
+ }
3733
+ }
3734
+ return out;
3735
+ }
3736
+ function boundAsParameter(code, name, options = {}) {
3737
+ const tokens = scanCode(code, options);
3738
+ const match = new Int32Array(tokens.length).fill(-1);
3739
+ const open = [];
3740
+ tokens.forEach((t, k) => {
3741
+ if (t.value === "(") open.push(k);
3742
+ else if (t.value === ")" && open.length) match[open.pop()] = k;
3743
+ });
3744
+ const arrowAfter = (end) => {
3745
+ const next = tokens[end + 1];
3746
+ if (next?.value === "=>") return true;
3747
+ if (next?.value !== ":") return false;
3748
+ let depth = 0;
3749
+ for (let k = end + 2; k < Math.min(tokens.length, end + 200); k++) {
3750
+ const v = tokens[k].value;
3751
+ if (v === "(" || v === "{" || v === "[" || v === "<") depth++;
3752
+ else if (v === ")" || v === "}" || v === "]" || v === ">") depth--;
3753
+ if (depth < 0) return false;
3754
+ if (depth === 0 && v === "=>") return true;
3755
+ if (depth === 0 && (v === ";" || v === "," || v === "=")) return false;
3756
+ }
3757
+ return false;
3758
+ };
3759
+ const beforeTypeParameters = (paren) => {
3760
+ let k = paren - 1;
3761
+ if (tokens[k]?.value !== ">" && tokens[k]?.value !== ">>") return k;
3762
+ let depth = 0;
3763
+ for (const stop = Math.max(0, k - TYPE_PARAMETERS_REACH); k >= stop; k--) {
3764
+ const v = tokens[k].value;
3765
+ if (v === ">") depth++;
3766
+ else if (v === ">>") depth += 2;
3767
+ else if (v === "<" && --depth === 0) return k - 1;
3768
+ }
3769
+ return -1;
3770
+ };
3771
+ const isFunction = (paren) => {
3772
+ let k = beforeTypeParameters(paren);
3773
+ if (k < 0) return false;
3774
+ if (tokens[k]?.kind === "ident" && tokens[k].value !== "function") k--;
3775
+ if (tokens[k]?.value === "*") k--;
3776
+ return tokens[k]?.value === "function";
3777
+ };
3778
+ for (let i = 0; i < tokens.length; i++) {
3779
+ const t = tokens[i];
3780
+ if (t.value === "=>" && tokens[i - 1]?.kind === "ident" && tokens[i - 1].value === name && tokens[i - 2]?.value !== ".") return true;
3781
+ if (t.value !== "(") continue;
3782
+ const end = match[i];
3783
+ if (end < 0) continue;
3784
+ const before = tokens[i - 1];
3785
+ const catchClause = before?.value === "catch";
3786
+ const nameAt = beforeTypeParameters(i);
3787
+ const methodName = nameAt >= 0 ? tokens[nameAt] : void 0;
3788
+ const typed = tokens[end + 1]?.value === ":" && !arrowAfter(end);
3789
+ 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)));
3790
+ if ((catchClause || isFunction(i) || method || arrowAfter(end)) && boundNames(tokens.slice(i + 1, end)).includes(name)) return true;
3791
+ }
3792
+ return false;
3793
+ }
3794
+
3795
+ // src/doctor/rules.ts
3465
3796
  var BUILTIN_RULES = [
3466
3797
  "local-primitives",
3467
3798
  // figma (figma/routes.ts; runs when genesis.config.json has a figma block)
@@ -3549,7 +3880,13 @@ var BUILTIN_RULES = [
3549
3880
  // custom views and app parts (custom-views.ts)
3550
3881
  "app-part-colors",
3551
3882
  "app-part-name",
3552
- "custom-view-states"
3883
+ "custom-view-states",
3884
+ // the app's client layer (client-layer.ts)
3885
+ "client/layer",
3886
+ "client/one-view-per-resource",
3887
+ // how the app reaches its database (data-access.ts)
3888
+ "data/declared-access",
3889
+ "data/access-rule-tests"
3553
3890
  ];
3554
3891
  var DEFAULT_LOCAL_PRIMITIVE_DIRS = ["src/components/ui"];
3555
3892
  var STARTER_LEFTOVERS = ["components.json", "src/lib/utils.ts"];
@@ -3688,14 +4025,32 @@ function checkShadowedExports(ctx) {
3688
4025
  const re = /\bexport\s+(?:default\s+)?(?:declare\s+)?(?:async\s+)?(?:function\*?|const|let|var|class)\s+([A-Z][\w$]*)/g;
3689
4026
  for (const file of ctx.files) {
3690
4027
  if (!SCRIPT_EXTS.has(file.ext) || insideOverlayOf(overlays, file, ctx.genesis.uiPackage)) continue;
4028
+ const wrapped = wrappedGenesisNames(file.code, ctx.genesis.uiPackage, { jsx: file.ext !== ".ts" && file.ext !== ".mts" });
3691
4029
  file.code.split("\n").forEach((text, i) => {
3692
4030
  for (const m of text.matchAll(re)) {
3693
4031
  if (!ctx.genesis.values.has(m[1])) continue;
4032
+ if (wrapped.has(m[1])) continue;
3694
4033
  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)` });
3695
4034
  }
3696
4035
  });
3697
4036
  }
3698
4037
  }
4038
+ function wrappedGenesisNames(code, uiPackage, options = {}) {
4039
+ const out = /* @__PURE__ */ new Set();
4040
+ const pkg = uiPackage.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
4041
+ const re = new RegExp(`\\bimport\\s+(?:type\\s+)?\\{([^}]*)\\}\\s*from\\s*["']${pkg}(?:/[^"']*)?["']`, "g");
4042
+ for (const m of code.matchAll(re)) {
4043
+ if (/^import\s+type\b/.test(m[0])) continue;
4044
+ for (const part of m[1].split(",")) {
4045
+ const spec = part.trim();
4046
+ if (!spec || spec.startsWith("type ")) continue;
4047
+ const [imported, local] = spec.split(/\s+as\s+/).map((x) => x.trim());
4048
+ if (!imported || !local || local === imported) continue;
4049
+ if (usesAsCode(code, local, options)) out.add(imported);
4050
+ }
4051
+ }
4052
+ return out;
4053
+ }
3699
4054
  function unusedComponents(ctx) {
3700
4055
  const used = /* @__PURE__ */ new Set();
3701
4056
  const pkg = ctx.genesis.uiPackage.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
@@ -6825,7 +7180,270 @@ function checkAppParts(ctx) {
6825
7180
  }
6826
7181
  }
6827
7182
  }
6828
- var SCRIPT_EXTS6 = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"]);
7183
+ init_regexp();
7184
+ var JSX_EXTS5 = /* @__PURE__ */ new Set([".tsx", ".jsx"]);
7185
+ var SCRIPT_EXTS6 = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts"]);
7186
+ var DEFAULT_CLIENT_DIR = "src/client";
7187
+ function clientLayer(root, files) {
7188
+ let dir = DEFAULT_CLIENT_DIR;
7189
+ try {
7190
+ dir = readGenesisConfig(root)?.client?.dir ?? DEFAULT_CLIENT_DIR;
7191
+ } catch {
7192
+ }
7193
+ const inside2 = `${dir}/`;
7194
+ 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"));
7195
+ 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"));
7196
+ return { dir, present, recordWrapper };
7197
+ }
7198
+ function genesisImports(code, uiPackage) {
7199
+ const out = /* @__PURE__ */ new Map();
7200
+ const escaped = uiPackage.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
7201
+ const re = new RegExp(`import\\s*(?:type\\s+)?\\{([^}]*)\\}\\s*from\\s*["']${escaped}(?:/data)?["']`, "g");
7202
+ for (const m of code.matchAll(re)) {
7203
+ if (/^\s*type\s/.test(m[0].slice(6))) continue;
7204
+ for (const part of m[1].split(",")) {
7205
+ const spec = part.trim().replace(/^type\s+/, "");
7206
+ if (!spec || part.trim().startsWith("type ")) continue;
7207
+ const [imported, local] = spec.split(/\s+as\s+/).map((x) => x.trim());
7208
+ if (imported === "ResourceView" || imported === "RecordView") out.set(local ?? imported, imported);
7209
+ }
7210
+ }
7211
+ return out;
7212
+ }
7213
+ function checkClientLayer(ctx) {
7214
+ const layer = clientLayer(ctx.root, ctx.files);
7215
+ const inside2 = `${layer.dir}/`;
7216
+ if (layer.present) {
7217
+ for (const file of ctx.files) {
7218
+ if (!JSX_EXTS5.has(file.ext) || file.path.startsWith(inside2)) continue;
7219
+ const imported = genesisImports(file.code, ctx.genesis.uiPackage);
7220
+ for (const [local, name] of imported) {
7221
+ if (name === "RecordView" && !layer.recordWrapper) continue;
7222
+ const at = file.code.search(new RegExp(`<${local}\\b`));
7223
+ if (at < 0) continue;
7224
+ ctx.report({
7225
+ rule: "client/layer",
7226
+ level: "warn",
7227
+ file: file.path,
7228
+ line: lineAt(file.code, at),
7229
+ subject: name,
7230
+ 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)`
7231
+ });
7232
+ }
7233
+ }
7234
+ }
7235
+ if (!layer.present) return;
7236
+ const seen = /* @__PURE__ */ new Map();
7237
+ for (const file of ctx.files) {
7238
+ if (!SCRIPT_EXTS6.has(file.ext) || SHOWN_OR_TRIED.test(file.path)) continue;
7239
+ const imports = importedNames(file.path, file.code);
7240
+ 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)) {
7241
+ const base = m[1];
7242
+ const access = m[2].replace(/\s+/g, "").replace(/'|`/g, '"');
7243
+ const imported = imports.get(base);
7244
+ if (!imported && !declaredAtTop(file.code, base)) continue;
7245
+ if (boundAsParameter(file.code, base, { jsx: file.ext !== ".ts" && file.ext !== ".mts" })) continue;
7246
+ const identity = `${imported ?? `${file.path}#${base}`}${access}`;
7247
+ const shown = `${base}${access}`;
7248
+ const line = lineAt(file.code, m.index ?? 0);
7249
+ const first = seen.get(identity);
7250
+ if (!first) {
7251
+ seen.set(identity, { file: file.path, line });
7252
+ continue;
7253
+ }
7254
+ ctx.report({
7255
+ rule: "client/one-view-per-resource",
7256
+ level: "warn",
7257
+ file: file.path,
7258
+ line,
7259
+ subject: shown,
7260
+ 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)`
7261
+ });
7262
+ }
7263
+ }
7264
+ }
7265
+ function declaredAtTop(code, name) {
7266
+ const escaped = escapeRegExp(name);
7267
+ return new RegExp(`^(?:export\\s+)?(?:const|let|var)\\s+${escaped}\\b`, "m").test(code);
7268
+ }
7269
+ var SHOWN_OR_TRIED = /(\.stories\.|\.test\.|\.spec\.|(^|\/)__tests__\/)/;
7270
+ function importedNames(filePath, code) {
7271
+ const out = /* @__PURE__ */ new Map();
7272
+ const dir = path21.posix.dirname(filePath);
7273
+ const where2 = (spec) => spec.startsWith(".") ? path21.posix.normalize(path21.posix.join(dir, spec)).replace(/\.(t|j)sx?$/, "").replace(/\/index$/, "") : spec;
7274
+ for (const m of code.matchAll(/import\s+(?:type\s+)?\{([^}]*)\}\s*from\s*["']([^"']+)["']/g)) {
7275
+ for (const part of m[1].split(",")) {
7276
+ const spec = part.trim().replace(/^type\s+/, "");
7277
+ if (!spec) continue;
7278
+ const [imported, local] = spec.split(/\s+as\s+/).map((x) => x.trim());
7279
+ out.set(local ?? imported, `${where2(m[2])}#${imported}`);
7280
+ }
7281
+ }
7282
+ 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])}#*`);
7283
+ return out;
7284
+ }
7285
+ var SCRIPT_EXTS7 = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"]);
7286
+ var SKIP_DIRS4 = /* @__PURE__ */ new Set(["node_modules", "dist", "build", ".git", ".next", ".output", ".turbo", "coverage", ".expo"]);
7287
+ var TEST_FILE = /(^|\/)(__tests__\/|[^/]+\.(test|spec)\.[cm]?[jt]sx?$)/;
7288
+ var DOCS = "docs/DATA-ACCESS.md";
7289
+ var TABLE_WRITE = /\.from\(\s*(["'`])([\w.]+)\1\s*\)\s*\.\s*(insert|update|upsert|delete)\s*\(/g;
7290
+ var STORAGE_BEFORE = /\bstorage\s*\??\.?\s*$/;
7291
+ function balanced(code, start) {
7292
+ const open = code[start];
7293
+ const close = open === "{" ? "}" : open === "(" ? ")" : open === "[" ? "]" : "";
7294
+ if (!close) return "";
7295
+ const blank = blankStrings(code);
7296
+ let depth = 0;
7297
+ for (let i = start; i < blank.length; i++) {
7298
+ const ch = blank[i];
7299
+ if (ch === "{" || ch === "(" || ch === "[") depth++;
7300
+ else if (ch === "}" || ch === ")" || ch === "]") {
7301
+ depth--;
7302
+ if (depth === 0) return ch === close ? code.slice(start, i + 1) : "";
7303
+ }
7304
+ }
7305
+ return "";
7306
+ }
7307
+ function testFiles(root) {
7308
+ const out = [];
7309
+ const walk3 = (dir) => {
7310
+ let entries;
7311
+ try {
7312
+ entries = readdirSync(dir, { withFileTypes: true });
7313
+ } catch {
7314
+ return;
7315
+ }
7316
+ for (const entry of entries) {
7317
+ if (entry.isDirectory()) {
7318
+ if (!SKIP_DIRS4.has(entry.name) && !entry.name.startsWith(".")) walk3(path21.join(dir, entry.name));
7319
+ continue;
7320
+ }
7321
+ const abs = path21.join(dir, entry.name);
7322
+ const rel = path21.relative(root, abs).split(path21.sep).join("/");
7323
+ if (SCRIPT_EXTS7.has(path21.extname(entry.name)) && TEST_FILE.test(rel)) out.push(abs);
7324
+ }
7325
+ };
7326
+ walk3(root);
7327
+ return out;
7328
+ }
7329
+ function initializer(code, blank, name) {
7330
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
7331
+ const decl = new RegExp(`\\b(const|let|var)\\s+${escaped}(?![\\w$])[^=;]*=\\s*\\{`).exec(blank);
7332
+ if (!decl) return null;
7333
+ const text = balanced(code, decl.index + decl[0].length - 1);
7334
+ return text ? { text, keyword: decl[1], at: decl.index } : null;
7335
+ }
7336
+ function objectDeclares(object) {
7337
+ const blank = blankStrings(object);
7338
+ let depth = 0;
7339
+ let declaredAt = -1;
7340
+ let lastAccess = -1;
7341
+ let lastSpread = -1;
7342
+ for (let i = 0; i < blank.length; i++) {
7343
+ const ch = blank[i];
7344
+ if (ch === "{" || ch === "(" || ch === "[") depth++;
7345
+ else if (ch === "}" || ch === ")" || ch === "]") depth--;
7346
+ else if (depth === 1 && blank.startsWith("...", i)) lastSpread = i;
7347
+ else if (depth === 1 && blank[i] === object[i] && /[\s{,]/.test(blank[i - 1] ?? " ") && /^(["'`]?)access\1\s*:/.test(object.slice(i))) {
7348
+ lastAccess = i;
7349
+ const value = /^(["'`]?)access\1\s*:\s*(["'`])([^"'`]*)\2/.exec(object.slice(i));
7350
+ declaredAt = value?.[3] === "declared" ? i : -1;
7351
+ }
7352
+ }
7353
+ return declaredAt !== -1 && declaredAt === lastAccess && lastSpread < declaredAt;
7354
+ }
7355
+ function inlineDeclares(call) {
7356
+ const blank = blankStrings(call);
7357
+ let depth = 0;
7358
+ for (let i = 0; i < blank.length; i++) {
7359
+ const ch = blank[i];
7360
+ if (ch === "{" && depth === 1 && objectDeclares(balanced(call, i))) return true;
7361
+ if (ch === "{" || ch === "(" || ch === "[") depth++;
7362
+ else if (ch === "}" || ch === ")" || ch === "]") depth--;
7363
+ }
7364
+ return false;
7365
+ }
7366
+ function optionsConstDeclares(code, blank, call) {
7367
+ const args = blankStrings(call).slice(1, -1);
7368
+ for (const [, name] of args.matchAll(/(?:^|,)\s*([A-Za-z_$][\w$]*)\s*(?=,|$)/g)) {
7369
+ const found = initializer(code, blank, name);
7370
+ if (!found || !objectDeclares(found.text)) continue;
7371
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
7372
+ const reassigned = found.keyword !== "const" && new RegExp(`(?<![\\w$.])${escaped}\\s*=(?!=)`, "g").test(blank.slice(found.at + found.keyword.length + 1 + name.length));
7373
+ const changed = new RegExp(
7374
+ `(?<![\\w$.])${escaped}\\s*(?:\\.\\s*access|\\[[^\\]]*\\])\\s*=(?!=)|\\bdelete\\s+${escaped}\\s*(?:\\.\\s*access|\\[)|Object\\.assign\\(\\s*${escaped}(?![\\w$])`
7375
+ ).test(blank);
7376
+ if (!reassigned && !changed) return true;
7377
+ }
7378
+ return false;
7379
+ }
7380
+ function coverageTested(root) {
7381
+ for (const abs of testFiles(root)) {
7382
+ let code;
7383
+ try {
7384
+ code = stripBlockComments(readFileSync(abs, "utf8"), true);
7385
+ } catch {
7386
+ continue;
7387
+ }
7388
+ if (!code.includes("expectAccessRulesCover")) continue;
7389
+ if (/\bexpectAccessRulesCover\s*\(/.test(blankStrings(code))) return true;
7390
+ }
7391
+ return false;
7392
+ }
7393
+ function checkDataAccess(ctx) {
7394
+ for (const file of ctx.files) {
7395
+ if (!SCRIPT_EXTS7.has(file.ext)) continue;
7396
+ const blank = blankStrings(file.code);
7397
+ for (const m of blank.matchAll(/\bcreateSupabaseProvider\s*\(/g)) {
7398
+ const call = balanced(file.code, (m.index ?? 0) + m[0].length - 1);
7399
+ if (inlineDeclares(call) || optionsConstDeclares(file.code, blank, call)) continue;
7400
+ ctx.report({
7401
+ rule: "data/declared-access",
7402
+ level: "warn",
7403
+ file: file.path,
7404
+ line: lineAt(file.code, m.index ?? 0),
7405
+ subject: "createSupabaseProvider",
7406
+ 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})`
7407
+ });
7408
+ }
7409
+ if (file.path.startsWith("supabase/") || file.path.includes("/supabase/functions/")) continue;
7410
+ for (const m of file.code.matchAll(TABLE_WRITE)) {
7411
+ const at = m.index ?? 0;
7412
+ if (blank[at] !== ".") continue;
7413
+ if (STORAGE_BEFORE.test(blank.slice(Math.max(0, at - 40), at))) continue;
7414
+ ctx.report({
7415
+ rule: "data/declared-access",
7416
+ level: "warn",
7417
+ file: file.path,
7418
+ line: lineAt(file.code, at),
7419
+ subject: `${m[2]}.${m[3]}`,
7420
+ 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})`
7421
+ });
7422
+ }
7423
+ }
7424
+ const providers = providerCalls(ctx.files);
7425
+ if (providers.length === 0 || coverageTested(ctx.root)) return;
7426
+ const first = providers[0];
7427
+ ctx.report({
7428
+ rule: "data/access-rule-tests",
7429
+ level: "warn",
7430
+ file: first.file,
7431
+ line: first.line,
7432
+ subject: "expectAccessRulesCover",
7433
+ 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})`
7434
+ });
7435
+ }
7436
+ function providerCalls(files) {
7437
+ const out = [];
7438
+ for (const file of files) {
7439
+ if (!SCRIPT_EXTS7.has(file.ext)) continue;
7440
+ for (const m of blankStrings(file.code).matchAll(/\bcreateSupabaseProvider\s*\(/g)) {
7441
+ out.push({ file: file.path, line: lineAt(file.code, m.index ?? 0) });
7442
+ }
7443
+ }
7444
+ return out;
7445
+ }
7446
+ var SCRIPT_EXTS8 = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"]);
6829
7447
  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;
6830
7448
  var REEXPORT = /\/\*\*((?:(?!\*\/)[\s\S])*)\*\/\s*\nexport\s+(?:type\s+)?\{([^}]*)\}/g;
6831
7449
  function specifierParts(spec) {
@@ -6915,7 +7533,7 @@ function checkStabilityImports(ctx) {
6915
7533
  return cache2.get(pkg);
6916
7534
  };
6917
7535
  for (const file of ctx.files) {
6918
- if (!SCRIPT_EXTS6.has(file.ext)) continue;
7536
+ if (!SCRIPT_EXTS8.has(file.ext)) continue;
6919
7537
  for (const { pkg, specifier, names, line } of genesisNamedImports(file.code)) {
6920
7538
  const tags = tagsOf(pkg);
6921
7539
  if (!tags) continue;
@@ -7374,6 +7992,7 @@ var RULES = [
7374
7992
  "Never copy an older screen as a template. Old screens predate the primitives; the doctor flags what they did.",
7375
7993
  "A list screen is a view (`defineView`) rendered by `ResourceView`; a record view is `RecordView`; on the phone, `NativeResourceView`.",
7376
7994
  "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.",
7995
+ `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.`,
7377
7996
  "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.",
7378
7997
  "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.",
7379
7998
  "Run `genesis doctor` before you finish; it enforces these rules."
@@ -8540,6 +9159,8 @@ function builtinChecks(config, options = {}) {
8540
9159
  { name: "studio-server-imports", check: checkStudioServerImports },
8541
9160
  { name: "removed-scope-names", check: checkRemovedScopeNames },
8542
9161
  { name: "app-parts", check: checkAppParts },
9162
+ { name: "client-layer", check: checkClientLayer },
9163
+ { name: "data-access", check: checkDataAccess },
8543
9164
  { name: "stability-imports", check: checkStabilityImports },
8544
9165
  { name: "agent-guide", check: (ctx) => {
8545
9166
  checkAgentGuide(ctx);