@somewhere-cloud/cli 0.38.93 → 0.38.95

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.
@@ -148,11 +148,18 @@ var require_declared_data_contract = __commonJS({
148
148
  if (value.k === "r" && ["k,roles", "generation,k,roles"].includes(keys)) {
149
149
  return { k: "r", roles: policyRoles(value.roles, label) };
150
150
  }
151
- if (value.k === "p" && keys === "k,p,pk,t,v" && [value.v, value.t, value.pk].every((item) => typeof item === "string" && identifier.test(item))) {
151
+ if (value.k === "p" && (keys === "k,p,pk,t,v" || keys === "a,k,p,pk,t,v" && edges === 0) && [value.v, value.t, value.pk].every((item) => typeof item === "string" && identifier.test(item))) {
152
152
  if (edges + 1 > 4) fail(label);
153
153
  const inherited = policy(value.p, label, edges + 1);
154
154
  if (!["o", "m", "a", "n", "p", "g", "r"].includes(inherited.k)) fail(label);
155
- return { k: "p", v: value.v, t: value.t, pk: value.pk, p: inherited };
155
+ let author;
156
+ if (value.a !== void 0) {
157
+ const a = value.a, order = ["author", "parent"];
158
+ const list = (v) => v === void 0 || Array.isArray(v) && v.length > 0 && v.length <= 2 && v.every((x, i) => order.includes(x) && (i === 0 || order.indexOf(v[i - 1]) < order.indexOf(x)));
159
+ if (inherited.k === "p" || !a || typeof a !== "object" || Array.isArray(a) || typeof a.c !== "string" || !identifier.test(a.c) || Object.keys(a).some((k) => !["c", "u", "d"].includes(k)) || !list(a.u) || !list(a.d)) fail(label);
160
+ author = { c: a.c, ...a.u ? { u: [...a.u] } : {}, ...a.d ? { d: [...a.d] } : {} };
161
+ }
162
+ return { k: "p", v: value.v, t: value.t, pk: value.pk, p: inherited, ...author ? { a: author } : {} };
156
163
  }
157
164
  fail(label);
158
165
  }
@@ -1377,6 +1384,8 @@ interface SomewhereAuthProfileUser extends SomewhereAuthUser {
1377
1384
  locale?: string | null;
1378
1385
  timezone?: string | null;
1379
1386
  agent?: SomewhereJsonObject;
1387
+ /** Present when read with { appRoles: true }: the caller's own app-role names, read fresh. */
1388
+ appRoles?: string[];
1380
1389
  }
1381
1390
  interface SomewhereAuthIssuedSession {
1382
1391
  user: SomewhereAuthSignedInUser;
@@ -1508,6 +1517,8 @@ interface SomewhereAuthRequestOptions {
1508
1517
  on?: string;
1509
1518
  // A platform-issued app-user access token string; never an identity value.
1510
1519
  forwardedToken?: string | null;
1520
+ // true: the user also carries appRoles, the signed-in caller's own app-role names read fresh (a hint).
1521
+ appRoles?: boolean;
1511
1522
  }
1512
1523
  interface SomewhereAuthRequireOptions extends SomewhereAuthRequestOptions { role?: 'admin' }
1513
1524
  interface SomewhereAuthAnonSession { id: string; isAnon: true; expiresAt: number }
@@ -3950,6 +3961,8 @@ interface SomewhereEndpointUser {
3950
3961
  email?: string | null;
3951
3962
  display_name?: string | null;
3952
3963
  role?: string;
3964
+ /** The caller's own app roles, read fresh for this request. Present on an endpoint that declares roles. */
3965
+ appRoles?: string[];
3953
3966
  [key: string]: unknown;
3954
3967
  }
3955
3968
  type __SomewhereEndpointLeaf = 'string' | 'email' | 'number' | 'boolean' | 'array' | 'object';
@@ -3977,6 +3990,9 @@ interface SomewhereEndpointInput<Auth extends SomewhereEndpointAuth, Body> {
3977
3990
  type SomewhereMcpJson = null | boolean | number | string | readonly SomewhereMcpJson[] | { readonly [key: string]: SomewhereMcpJson };
3978
3991
  interface SomewhereEndpointConfig<Auth extends SomewhereEndpointAuth, Schema extends SomewhereEndpointBodySchema | undefined> {
3979
3992
  auth?: Auth;
3993
+ /** App roles (declared in db/schema.ts appRoles), any of which admits the caller. Implies a signed-in
3994
+ * caller (auth 'required' or omitted). Checked fresh before the body is read or the handler runs. */
3995
+ roles?: readonly string[];
3980
3996
  /** Explicit MCP opt-in. Only auth: required endpoints can be tools. */
3981
3997
  mcp?: Auth extends 'required' ? {
3982
3998
  name: string;
@@ -4264,6 +4280,9 @@ var require_schema_types = __commonJS({
4264
4280
  unique?: string[][]; relations?: Record<string, Relation>;
4265
4281
  /** sw.rooms: a room per row; save = a json() column only the room writes, referee = an app function path. */
4266
4282
  rooms?: { save?: Field; referee?: string };
4283
+ /** Column rules. write: a caller write that sets the column also needs one of these app roles (declared in appRoles).
4284
+ * memberOf: the column holds a user id that must be a current member of the row's team (this table's group() column). */
4285
+ columns?: Partial<Record<Field, { write?: string[]; memberOf?: Field }>>;
4267
4286
  }
4268
4287
  }
4269
4288
  `;
@@ -4294,7 +4313,7 @@ function grant(options: { table: string; grantee: string; row?: string; operatio
4294
4313
  function anyOf(owner: SomewhereSchemaDeclaration.OwnerScope, other: SomewhereSchemaDeclaration.GrantScope | SomewhereSchemaDeclaration.MemberScope | SomewhereSchemaDeclaration.GroupScope | SomewhereSchemaDeclaration.AppRoleScope): SomewhereSchemaDeclaration.AnyOfScope;
4295
4314
  function anyOf(other: SomewhereSchemaDeclaration.GrantScope | SomewhereSchemaDeclaration.MemberScope | SomewhereSchemaDeclaration.GroupScope | SomewhereSchemaDeclaration.AppRoleScope, owner: SomewhereSchemaDeclaration.OwnerScope): SomewhereSchemaDeclaration.AnyOfScope;
4296
4315
  function allOf(gate: SomewhereSchemaDeclaration.MemberScope | SomewhereSchemaDeclaration.GroupScope | SomewhereSchemaDeclaration.AppRoleScope, who: SomewhereSchemaDeclaration.OwnerScope | SomewhereSchemaDeclaration.AnyOfScope): SomewhereSchemaDeclaration.Scope;
4297
- function parent(options: { via: string; table?: string }): SomewhereSchemaDeclaration.Scope;
4316
+ function parent(options: { via: string; table?: string; author?: string; update?: Array<'author' | 'parent'>; delete?: Array<'author' | 'parent'> }): SomewhereSchemaDeclaration.Scope;
4298
4317
  function group(options?: { column?: string; roles?: Partial<Record<'read' | 'create' | 'update' | 'delete', string[]>>; read?: string[] }): SomewhereSchemaDeclaration.GroupScope;
4299
4318
  function appRole(options: { roles: Partial<Record<'read' | 'create' | 'update' | 'delete', string[]>>; read?: string[] }): SomewhereSchemaDeclaration.AppRoleScope;
4300
4319
  `;
@@ -4474,8 +4493,8 @@ var require_consumer_contract = __commonJS({
4474
4493
  "worker/containers/compile/consumer-contract.cjs"(exports2, module2) {
4475
4494
  "use strict";
4476
4495
  var CONSUMER_CONTRACT2 = Object.freeze({
4477
- version: 15,
4478
- digest: "1e7d89a9beeb6a433b3e40769a236ea1f716918c257b49f3754d7d1c79d9f528"
4496
+ version: 18,
4497
+ digest: "45b503300f9407ee0ea0efcbc61f5459334c758ba446129f6decc8bdec5d5b79"
4479
4498
  });
4480
4499
  var MEMBERSHIPS = "memberships: table({ id: id(), team_id: text(), member_id: text() }, { scope: owner(), client: { read: true } }),";
4481
4500
  var SHARES = "shares: table({ id: id(), grantee_id: text() }, { scope: owner(), client: { read: true, create: ['grantee_id'], delete: true }, unique: [['user_id', 'grantee_id']] }),";
@@ -5179,6 +5198,40 @@ var COMPILE_UNAVAILABLE_REALERT_MS = 60 * 60 * 1e3;
5179
5198
 
5180
5199
 
5181
5200
  var SAFE_SCOPE_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
5201
+ function bakedChildAuthor(value) {
5202
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
5203
+ const node = value;
5204
+ const declared = Object.prototype.hasOwnProperty.call(node, "column");
5205
+ const column = declared ? node.column : node.c;
5206
+ const keys = Object.keys(node).sort();
5207
+ const allowed = declared ? ["column", "delete", "update"] : ["c", "d", "u"];
5208
+ if (typeof column !== "string" || !SAFE_SCOPE_IDENTIFIER.test(column) || keys.some((k) => !allowed.includes(k))) return null;
5209
+ const list = (v) => {
5210
+ if (v === void 0) return void 0;
5211
+ if (!Array.isArray(v) || v.length === 0 || v.length > 2) return null;
5212
+ const order = ["author", "parent"];
5213
+ if (!v.every((x, i) => order.includes(x) && (i === 0 || order.indexOf(v[i - 1]) < order.indexOf(x)))) return null;
5214
+ return [...v];
5215
+ };
5216
+ const u = list(declared ? node.update : node.u), d = list(declared ? node.delete : node.d);
5217
+ if (u === null || d === null) return null;
5218
+ return { c: column.toLowerCase(), ...u ? { u } : {}, ...d ? { d } : {} };
5219
+ }
5220
+ function validBakedColumnWrite(value, columns, pinned = true) {
5221
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
5222
+ const entries = Object.entries(value);
5223
+ if (entries.length === 0) return false;
5224
+ return entries.every(([column, leaf]) => {
5225
+ if (!columns.some((c) => c.n === column) || !leaf || typeof leaf !== "object" || Array.isArray(leaf)) return false;
5226
+ const node = leaf;
5227
+ if (node.k !== "r" || !(exactKeys(node, ["k", "roles", "generation"]) || exactKeys(node, ["k", "roles", "generation", "d"]))) return false;
5228
+ if (node.d !== void 0 && !validRoleDomainMap(node.d)) return false;
5229
+ if (!validGroupRoles(node.roles)) return false;
5230
+ const roles = node.roles;
5231
+ if (roles.read.length !== 0 || roles.delete.length !== 0 || roles.create.length === 0 || JSON.stringify(roles.create) !== JSON.stringify(roles.update) || roles.create.some((role, i) => i > 0 && roles.create[i - 1] >= role)) return false;
5232
+ return Number.isSafeInteger(node.generation) && (pinned ? node.generation >= 1 : node.generation === 0);
5233
+ });
5234
+ }
5182
5235
  var GROUP_ROLE_NAME = /^[a-z][a-z0-9_]{0,63}$/;
5183
5236
  function validGroupRoles(value) {
5184
5237
  if (!value || typeof value !== "object" || Array.isArray(value)) return false;
@@ -5253,7 +5306,9 @@ function validBakedPolicy(value, root = true, edges = 0) {
5253
5306
  if (root && node.k === "p") {
5254
5307
  if (edges + 1 > MAX_PARENT_EDGES) return false;
5255
5308
  const child = node.p?.k;
5256
- return exactKeys(node, ["k", "v", "t", "pk", "p"]) && ident(node.v) && ident(node.t) && ident(node.pk) && validBakedPolicy(node.p, child === "a" || child === "n" || child === "p" || child === "g" || child === "r", edges + 1);
5309
+ const withAuthor = node.a !== void 0;
5310
+ if (withAuthor && (edges !== 0 || !bakedChildAuthor(node.a) || child === "p")) return false;
5311
+ return exactKeys(node, withAuthor ? ["k", "v", "t", "pk", "p", "a"] : ["k", "v", "t", "pk", "p"]) && ident(node.v) && ident(node.t) && ident(node.pk) && validBakedPolicy(node.p, child === "a" || child === "n" || child === "p" || child === "g" || child === "r", edges + 1);
5257
5312
  }
5258
5313
  if (root && node.k === "g") {
5259
5314
  return exactKeys(node, ["k", "c", "roles", "generation"]) && ident(node.c) && validGroupRoles(node.roles) && Number.isSafeInteger(node.generation) && node.generation >= 1;
@@ -5309,6 +5364,28 @@ function bakedTableSchemaFromDeclared(declaredJson) {
5309
5364
  if (col.helper === "id") primaryKeys.push(entry.n);
5310
5365
  }
5311
5366
  const relations = bakedRelationsFromDeclared(shape.relations);
5367
+ let columnWrite;
5368
+ if (Object.prototype.hasOwnProperty.call(shape, "columnWrite")) {
5369
+ const declared = shape.columnWrite;
5370
+ if (!declared || typeof declared !== "object" || Array.isArray(declared)) return null;
5371
+ columnWrite = {};
5372
+ for (const [column, roles] of Object.entries(declared)) {
5373
+ if (!Array.isArray(roles) || !roles.every((role) => typeof role === "string")) return null;
5374
+ columnWrite[column.toLowerCase()] = { k: "r", roles: { read: [], create: [...roles], update: [...roles], delete: [] }, generation: 0 };
5375
+ }
5376
+ if (!validBakedColumnWrite(columnWrite, out, false)) return null;
5377
+ }
5378
+ let memberOf;
5379
+ if (Object.prototype.hasOwnProperty.call(shape, "columnMemberOf")) {
5380
+ const declared = shape.columnMemberOf;
5381
+ if (!declared || typeof declared !== "object" || Array.isArray(declared)) return null;
5382
+ memberOf = {};
5383
+ for (const [column, team] of Object.entries(declared)) {
5384
+ if (typeof team !== "string" || !SAFE_SCOPE_IDENTIFIER.test(team)) return null;
5385
+ memberOf[column.toLowerCase()] = { k: "g", c: team.toLowerCase(), roles: { read: [], create: [], update: [], delete: [] }, generation: 0 };
5386
+ }
5387
+ }
5388
+ const cw = { ...columnWrite ? { columnWrite } : {}, ...memberOf ? { memberOf } : {} };
5312
5389
  const scope = shape.scope;
5313
5390
  let visitors;
5314
5391
  if (scope !== null && typeof scope === "object" && Object.prototype.hasOwnProperty.call(scope, "visitors")) {
@@ -5337,16 +5414,16 @@ function bakedTableSchemaFromDeclared(declaredJson) {
5337
5414
  if (scope !== null && typeof scope === "object" && scope.kind === "member") {
5338
5415
  const member = bakedMemberFromDeclared(scope);
5339
5416
  if (!member) return null;
5340
- return relations ? { columns: out, member, relations, ...browser } : { columns: out, member, ...browser };
5417
+ return relations ? { columns: out, member, relations, ...browser, ...cw } : { columns: out, member, ...browser, ...cw };
5341
5418
  }
5342
5419
  if (scope !== null && typeof scope === "object" && scope.kind === "policy") {
5343
5420
  const policy = bakedPolicyFromDeclared(scope.policy);
5344
5421
  if (!policy || policy.k !== "a" && policy.k !== "n" && policy.k !== "p" && policy.k !== "g" && policy.k !== "r") return null;
5345
- return relations ? { columns: out, policy, relations, ...browser } : { columns: out, policy, ...browser };
5422
+ return relations ? { columns: out, policy, relations, ...browser, ...cw } : { columns: out, policy, ...browser, ...cw };
5346
5423
  }
5347
5424
  const author = scope !== null && typeof scope === "object" && scope.kind === "shared" ? SHARED_AUTHOR_COLUMN : void 0;
5348
5425
  if (author) out.push({ n: author, t: "text", nul: 1 });
5349
- return { columns: out, ...relations ? { relations } : {}, ...author ? { author } : {}, ...visitors ? { visitors } : {}, ...browser };
5426
+ return { columns: out, ...relations ? { relations } : {}, ...author ? { author } : {}, ...visitors ? { visitors } : {}, ...browser, ...cw };
5350
5427
  }
5351
5428
  function declaredPolicyIdentity(value) {
5352
5429
  if (!value || typeof value !== "object") return {};
@@ -5424,7 +5501,15 @@ function bakedPolicyFromDeclared(value, depth = 0, edges = 0, underParent = fals
5424
5501
  if (node.kind === "parent" && typeof node.via === "string" && SAFE_SCOPE_IDENTIFIER.test(node.via) && typeof node.table === "string" && SAFE_SCOPE_IDENTIFIER.test(node.table) && typeof node.parentKey === "string" && SAFE_SCOPE_IDENTIFIER.test(node.parentKey)) {
5425
5502
  if (depth !== 0 && !underParent || edges + 1 > MAX_PARENT_EDGES) return null;
5426
5503
  const inherited = bakedPolicyFromDeclared(node.policy, depth + 1, edges + 1, true);
5427
- return inherited ? { k: "p", v: node.via.toLowerCase(), t: node.table.toLowerCase(), pk: node.parentKey.toLowerCase(), p: inherited } : null;
5504
+ if (!inherited) return null;
5505
+ const author = node.author;
5506
+ let a;
5507
+ if (author !== void 0) {
5508
+ if (depth !== 0) return null;
5509
+ a = bakedChildAuthor(author) ?? void 0;
5510
+ if (!a) return null;
5511
+ }
5512
+ return { k: "p", v: node.via.toLowerCase(), t: node.table.toLowerCase(), pk: node.parentKey.toLowerCase(), p: inherited, ...a ? { a } : {} };
5428
5513
  }
5429
5514
  return null;
5430
5515
  }
@@ -5880,6 +5965,9 @@ function resolveParentChains(tables, tableByName, privatePolicy, errors) {
5880
5965
  const parentKey = parentKeys.length === 1 ? parentKeys[0] : void 0;
5881
5966
  let inherited = null;
5882
5967
  let edges = 1;
5968
+ if (parentTable && parentTable.scope.kind === "policy" && parentTable.scope.policy.kind === "parent" && parentTable.scope.policy.author) {
5969
+ return fail(`Table "${t.name}" uses parent({ via: '${pending.via}' }), but "${parentTable.name}" declares parent({ author }); a table cannot inherit from a table with authors yet.`);
5970
+ }
5883
5971
  if (parentTable && parentTable.scope.kind === "policy" && parentTable.scope.policy.kind === "parent") {
5884
5972
  const above = resolveParent(parentTable);
5885
5973
  if (above === null) {
@@ -5902,7 +5990,7 @@ function resolveParentChains(tables, tableByName, privatePolicy, errors) {
5902
5990
  if (!compatible) {
5903
5991
  return fail(`Table "${t.name}" uses parent({ via: '${pending.via}' }), but that foreign key does not have the same scalar type as "${parentTable.name}"."${parentKey.name}".`);
5904
5992
  }
5905
- t.scope.policy = { kind: "parent", via: pending.via, table: parentTable.name, parentKey: parentKey.name, policy: inherited };
5993
+ t.scope.policy = { kind: "parent", via: pending.via, table: parentTable.name, parentKey: parentKey.name, policy: inherited, ...pending.author ? { author: pending.author } : {} };
5906
5994
  if (t.client?.create && !t.client.create.includes(pending.via)) {
5907
5995
  errors.push(`Table "${t.name}" uses parent({ via: '${pending.via}' }) and client.create must include "${pending.via}" so every new row explicitly selects an authorized parent.`);
5908
5996
  }
@@ -6725,6 +6813,133 @@ function resolveAppRoleScopes(tables, appRoles, errors) {
6725
6813
  }
6726
6814
 
6727
6815
 
6816
+ var roleLines = new WeakMap();
6817
+ var columnLines = new WeakMap();
6818
+ function readColumnRules(r, tableName, line, fail) {
6819
+ const where = `columns on table "${tableName}"`;
6820
+ r.expectPunct("{", `opening ${where}, which takes { column: { write: ['role'] } } or { column: { memberOf: 'team_column' } }`);
6821
+ const rules = {};
6822
+ const memberOf = {};
6823
+ const seen = new Set();
6824
+ const lines2 = [];
6825
+ const at = {};
6826
+ while (!r.tryPunct("}")) {
6827
+ const column = r.readKey(`for a column in ${where}`);
6828
+ const name = column.name.toLowerCase();
6829
+ if (seen.has(name)) fail(column.line, `${where} lists "${column.name}" twice.`);
6830
+ seen.add(name);
6831
+ r.expectPunct(":", `after "${column.name}" in ${where}`);
6832
+ r.expectPunct("{", `opening the rule for "${column.name}" in ${where}, which takes { write: ['role'] } or { memberOf: 'team_column' }`);
6833
+ let roles = null;
6834
+ let team = null;
6835
+ while (!r.tryPunct("}")) {
6836
+ const key = r.readKey(`for an option of column "${column.name}" in ${where}`);
6837
+ if (key.name === "memberOf") {
6838
+ if (team) fail(key.line, `column "${column.name}" in ${where} declares memberOf twice.`);
6839
+ r.expectPunct(":", `after "memberOf" for column "${column.name}"`);
6840
+ const t = r.next();
6841
+ if (t.kind !== "string" || !/^[A-Za-z_][A-Za-z0-9_]{0,63}$/.test(t.value)) fail(t.line, `columns.${column.name}.memberOf on table "${tableName}" must be the quoted name of the table's team column, such as 'team_id'.`);
6842
+ team = t.value.toLowerCase();
6843
+ if (!r.tryPunct(",")) {
6844
+ r.expectPunct("}", `closing the rule for "${column.name}"`);
6845
+ break;
6846
+ }
6847
+ continue;
6848
+ }
6849
+ if (key.name !== "write") fail(key.line, `column "${column.name}" in ${where} has an unknown option "${key.name}". Allowed: write, memberOf.`);
6850
+ if (roles) fail(key.line, `column "${column.name}" in ${where} declares write twice.`);
6851
+ r.expectPunct(":", `after "write" for column "${column.name}"`);
6852
+ const open = r.next();
6853
+ if (open.kind !== "punct" || open.value !== "[") fail(open.line, `columns.${column.name}.write on table "${tableName}" must be a list of quoted app role names, such as ['staff'].`);
6854
+ const list = [];
6855
+ while (!r.tryPunct("]")) {
6856
+ const t = r.next();
6857
+ if (t.kind !== "string") fail(t.line, `columns.${column.name}.write on table "${tableName}" must list quoted app role names; values must be literal strings.`);
6858
+ if (!/^[a-z][a-z0-9_]{0,63}$/.test(t.value)) fail(t.line, `columns.${column.name}.write on table "${tableName}" names "${t.value}", which is not an app role name (lowercase letters, digits and _, starting with a letter).`);
6859
+ if (list.includes(t.value)) fail(t.line, `columns.${column.name}.write on table "${tableName}" lists "${t.value}" twice.`);
6860
+ list.push(t.value);
6861
+ lines2.push({ column: name, role: t.value, line: t.line });
6862
+ if (!r.tryPunct(",")) {
6863
+ r.expectPunct("]", `closing columns.${column.name}.write`);
6864
+ break;
6865
+ }
6866
+ }
6867
+ if (list.length === 0) fail(open.line, `columns.${column.name}.write on table "${tableName}" is empty, so no caller could ever write "${column.name}". List the app roles that may, or leave the column out of columns.`);
6868
+ roles = [...list].sort();
6869
+ if (!r.tryPunct(",")) {
6870
+ r.expectPunct("}", `closing the rule for "${column.name}"`);
6871
+ break;
6872
+ }
6873
+ }
6874
+ if (!roles && !team) fail(column.line, `column "${column.name}" in ${where} needs write: ['role'] or memberOf: 'team_column'.`);
6875
+ if (roles) rules[name] = roles;
6876
+ if (team) memberOf[name] = team;
6877
+ at[name] = column.line;
6878
+ if (!r.tryPunct(",")) {
6879
+ r.expectPunct("}", `closing ${where}`);
6880
+ break;
6881
+ }
6882
+ }
6883
+ if (seen.size === 0) fail(line, `${where} is empty; leave it out, or list the columns that take a rule.`);
6884
+ const out = {};
6885
+ if (Object.keys(rules).length) {
6886
+ const sorted3 = {};
6887
+ for (const name of Object.keys(rules).sort()) sorted3[name] = rules[name];
6888
+ roleLines.set(sorted3, lines2);
6889
+ columnLines.set(sorted3, at);
6890
+ out.write = sorted3;
6891
+ }
6892
+ if (Object.keys(memberOf).length) {
6893
+ const sorted3 = {};
6894
+ for (const name of Object.keys(memberOf).sort()) sorted3[name] = memberOf[name];
6895
+ columnLines.set(sorted3, at);
6896
+ out.memberOf = sorted3;
6897
+ }
6898
+ return out;
6899
+ }
6900
+ function validateColumnMemberOf(memberOf, input, fail) {
6901
+ const at = columnLines.get(memberOf) ?? {};
6902
+ for (const [column, team] of Object.entries(memberOf)) {
6903
+ const line = at[column] ?? input.nameLine;
6904
+ const label = `columns.${column}.memberOf on table "${input.tableName}"`;
6905
+ const declared = input.columns.find((c) => c.name === column);
6906
+ if (column === input.ownerColumn) fail(line, `${label} names the owner column, which the platform writes; it takes no memberOf rule.`);
6907
+ if (!declared) fail(line, `${label}: "${column}" is not one of its declared columns.`);
6908
+ if (declared.helper !== "text") fail(line, `${label}: "${column}" must be a text() column holding a user id.`);
6909
+ if (declared.hasDefault && declared.default !== null) fail(line, `${label}: "${column}" declares a default user id, which a create that leaves the column out would store without the team check. Remove the default (a nullable column may default to null).`);
6910
+ if (input.accessColumns.includes(column)) fail(line, `${label}: "${column}" is read by the table's access rule, so it takes no memberOf rule.`);
6911
+ if (column === input.roomSave) fail(line, `${label}: "${column}" is the room's save column.`);
6912
+ if (!input.groupColumns.includes(team)) {
6913
+ fail(line, `${label} names "${team}", which is not this table's team column. memberOf names the table's own group() column (group(), anyOf(owner(), group()) or an allOf() group() gate); a team inherited through parent() is not supported yet.`);
6914
+ }
6915
+ }
6916
+ }
6917
+ function validateColumnRules(rules, input, fail) {
6918
+ const at = columnLines.get(rules) ?? {};
6919
+ if (input.serverOnly) fail(input.nameLine, `table "${input.tableName}" is serverOnly(), so no caller writes it; columns write rules apply to caller writes and are not accepted on it.`);
6920
+ for (const column of Object.keys(rules)) {
6921
+ const line = at[column] ?? input.nameLine;
6922
+ const label = `columns.${column} on table "${input.tableName}"`;
6923
+ if (column === input.ownerColumn) fail(line, `${label} names the owner column, which the platform writes; no caller writes it, so it takes no write rule.`);
6924
+ if (!input.declaredColumns.has(column)) fail(line, `${label} names "${column}", which is not one of its declared columns.`);
6925
+ if (input.accessColumns.includes(column)) fail(line, `${label} names "${column}", which the table's access rule reads; who may set it is decided by that rule, so it takes no column write rule.`);
6926
+ if (column === input.roomSave) fail(line, `${label} names "${column}", the column this table's room saves its state to. The room writes it, not a caller, so a write rule on it would not be enforced on room saves; it is not accepted.`);
6927
+ }
6928
+ }
6929
+ function resolveColumnRuleRoles(tables, appRoles, groups, errors) {
6930
+ const vocabulary = new Set((appRoles ?? []).map((role) => role.name));
6931
+ const teamRoles = new Set(["owner", "admin", "member", ...groups?.roles ?? []]);
6932
+ for (const t of tables) {
6933
+ if (!t.columnRules) continue;
6934
+ for (const { column, role, line } of roleLines.get(t.columnRules) ?? []) {
6935
+ if (vocabulary.has(role)) continue;
6936
+ errors.push(teamRoles.has(role) ? `line ${line}: columns.${column}.write on table "${t.name}" names "${role}", a team role. Column write rules take app roles only for now (declared in the schema's appRoles option); a team role cannot restrict a column yet.` : `line ${line}: columns.${column}.write on table "${t.name}" names "${role}", which is not declared in the schema's appRoles option. Column write rules accept only app roles declared there.`);
6937
+ }
6938
+ roleLines.delete(t.columnRules);
6939
+ }
6940
+ }
6941
+
6942
+
6728
6943
  var EMAIL_DOMAIN = EMAIL_DOMAIN_PATTERN;
6729
6944
  var GROUP_KEYS = ["roles", "adminGrantableRoles"];
6730
6945
  var APP_ROLE_KEYS = ["grantableBy", "emailDomain", "assignedBy"];
@@ -6910,9 +7125,17 @@ function declaredScopeIdentityColumns(scope) {
6910
7125
  if (scope.kind === "owner") return [scope.column];
6911
7126
  if (scope.kind === "member") return [...scope.group];
6912
7127
  if (scope.kind !== "policy") return [];
6913
- const collect = (policy) => policy.kind === "owner" ? [policy.column] : policy.kind === "member" ? [...policy.group] : policy.kind === "any_of" ? policy.policies.flatMap(collect) : policy.kind === "all_of" ? [...collect(policy.gate), ...collect(policy.who)] : policy.kind === "group" ? [policy.column] : policy.kind === "app_role" ? [] : [policy.via];
7128
+ const collect = (policy) => policy.kind === "owner" ? [policy.column] : policy.kind === "member" ? [...policy.group] : policy.kind === "any_of" ? policy.policies.flatMap(collect) : policy.kind === "all_of" ? [...collect(policy.gate), ...collect(policy.who)] : policy.kind === "group" ? [policy.column] : policy.kind === "app_role" ? [] : [policy.via, ...policy.author ? [policy.author.column] : []];
6914
7129
  return [...new Set(collect(scope.policy))];
6915
7130
  }
7131
+ function declaredTeamColumns(scope) {
7132
+ if (scope.kind !== "policy") return [];
7133
+ const p = scope.policy;
7134
+ if (p.kind === "group") return [p.column];
7135
+ if (p.kind === "any_of") return p.policies.flatMap((x) => x.kind === "group" ? [x.column] : []);
7136
+ if (p.kind === "all_of") return p.gate.kind === "group" ? [p.gate.column] : [];
7137
+ return [];
7138
+ }
6916
7139
  var ROOM_REFEREE_PATH = /^\/api\/[A-Za-z0-9_\-]+(?:\/[A-Za-z0-9_\-.]+)*$/;
6917
7140
  function readRoomsOption(r, rawName, line) {
6918
7141
  r.expectPunct("{", `opening the rooms option of table "${rawName}", which takes { save?: 'column', referee?: '/api/path' }`);
@@ -7663,17 +7886,56 @@ function readAllOfScope(r, tableName, line) {
7663
7886
  }
7664
7887
  function readParentScope(r, tableName, line) {
7665
7888
  r.expectPunct("(", 'after "parent"');
7666
- const opts = r.readLiteralObject(`in parent() options for table "${tableName}"`);
7889
+ const where = `parent() options for table "${tableName}"`;
7890
+ r.expectPunct("{", `in ${where}`);
7891
+ let via = null;
7892
+ let authorColumn = null;
7893
+ const actions = {};
7894
+ const seen = new Set();
7895
+ while (!r.tryPunct("}")) {
7896
+ const key = r.readKey(`for an option key in ${where}`);
7897
+ if (seen.has(key.name)) throw new SchemaTsError(`line ${key.line}: option "${key.name}" appears twice in ${where}.`);
7898
+ seen.add(key.name);
7899
+ r.expectPunct(":", `after "${key.name}" in ${where}`);
7900
+ if (key.name === "via" || key.name === "author") {
7901
+ const t = r.next();
7902
+ if (t.kind !== "string" || !SAFE_IDENT.test(t.value) || t.value.length > MAX_NAME_LENGTH) {
7903
+ throw new SchemaTsError(key.name === "via" ? `line ${t.line}: parent({ via }) on table "${tableName}" must name a valid declared foreign-key column.` : `line ${t.line}: parent({ author }) on table "${tableName}" must name a declared nullable text() column the platform stamps with the row's creator.`);
7904
+ }
7905
+ if (key.name === "via") via = { value: t.value.toLowerCase(), line: t.line };
7906
+ else authorColumn = { value: t.value.toLowerCase(), line: t.line };
7907
+ } else if (key.name === "update" || key.name === "delete") {
7908
+ const open = r.next();
7909
+ if (open.kind !== "punct" || open.value !== "[") throw new SchemaTsError(`line ${open.line}: parent({ ${key.name} }) on table "${tableName}" lists who may ${key.name} a row: 'author' and/or 'parent', such as ['author', 'parent'].`);
7910
+ const list = [];
7911
+ while (!r.tryPunct("]")) {
7912
+ const t = r.next();
7913
+ if (t.kind !== "string" || t.value !== "author" && t.value !== "parent") throw new SchemaTsError(`line ${t.line}: parent({ ${key.name} }) on table "${tableName}" accepts 'author' (the row's author) and 'parent' (whoever may ${key.name} the parent row).`);
7914
+ if (list.includes(t.value)) throw new SchemaTsError(`line ${t.line}: parent({ ${key.name} }) on table "${tableName}" lists '${t.value}' twice.`);
7915
+ list.push(t.value);
7916
+ if (!r.tryPunct(",")) {
7917
+ r.expectPunct("]", `closing parent({ ${key.name} })`);
7918
+ break;
7919
+ }
7920
+ }
7921
+ if (list.length === 0) throw new SchemaTsError(`line ${open.line}: parent({ ${key.name} }) on table "${tableName}" is empty, so nobody could ${key.name} a row. List 'author' and/or 'parent', or leave it out for today's rule ('parent').`);
7922
+ actions[key.name] = ["author", "parent"].filter((a) => list.includes(a));
7923
+ } else {
7924
+ throw new SchemaTsError(`line ${key.line}: parent() on table "${tableName}" has an unknown option "${key.name}". Allowed: via, author, update, delete.`);
7925
+ }
7926
+ if (!r.tryPunct(",")) {
7927
+ r.expectPunct("}", `closing ${where}`);
7928
+ break;
7929
+ }
7930
+ }
7667
7931
  r.tryPunct(",");
7668
7932
  r.expectPunct(")", "closing parent()");
7669
- if (opts.size !== 1 || !opts.has("via")) {
7670
- throw new SchemaTsError(`line ${line}: parent() on table "${tableName}" needs exactly { via: 'foreign_key' }.`);
7671
- }
7672
- const value = opts.get("via").value;
7673
- if (typeof value !== "string" || !SAFE_IDENT.test(value) || value.length > MAX_NAME_LENGTH) {
7674
- throw new SchemaTsError(`line ${opts.get("via").line}: parent({ via }) on table "${tableName}" must name a valid declared foreign-key column.`);
7675
- }
7676
- const sentinel = { kind: "parent", via: value.toLowerCase(), table: "", parentKey: "", policy: { kind: "owner", column: "" } };
7933
+ if (!via) throw new SchemaTsError(`line ${line}: parent() on table "${tableName}" needs { via: 'foreign_key' }.`);
7934
+ const usesAuthor = [actions.update, actions.delete].some((list) => list?.includes("author"));
7935
+ if (usesAuthor && !authorColumn) throw new SchemaTsError(`line ${line}: parent() on table "${tableName}" lets 'author' act but declares no author column; add author: 'author_id' (a nullable text() column the platform stamps).`);
7936
+ if (!authorColumn && (actions.update || actions.delete)) throw new SchemaTsError(`line ${line}: parent() on table "${tableName}" lists update or delete without an author column; without author, every operation already follows the parent.`);
7937
+ const author = authorColumn ? { column: authorColumn.value, ...actions.update ? { update: actions.update } : {}, ...actions.delete ? { delete: actions.delete } : {} } : void 0;
7938
+ const sentinel = { kind: "parent", via: via.value, table: "", parentKey: "", policy: { kind: "owner", column: "" }, ...author ? { author } : {} };
7677
7939
  rememberParentLine(sentinel, line);
7678
7940
  return { kind: "policy", policy: sentinel };
7679
7941
  }
@@ -7877,6 +8139,7 @@ function readTable(r, rawName, nameLine) {
7877
8139
  let relationsDeclared = false;
7878
8140
  let clientInput;
7879
8141
  let roomsInput;
8142
+ let columnOptions;
7880
8143
  if (r.tryPunct(",")) {
7881
8144
  r.expectPunct("{", `opening the options of table "${rawName}"`);
7882
8145
  while (!r.tryPunct("}")) {
@@ -7904,9 +8167,14 @@ function readTable(r, rawName, nameLine) {
7904
8167
  } else if (key.name === "rooms") {
7905
8168
  if (roomsInput) throw new SchemaTsError(`line ${key.line}: table "${rawName}" declares "rooms" twice.`);
7906
8169
  roomsInput = readRoomsOption(r, rawName, key.line);
8170
+ } else if (key.name === "columns") {
8171
+ if (columnOptions) throw new SchemaTsError(`line ${key.line}: table "${rawName}" declares "columns" twice.`);
8172
+ columnOptions = readColumnRules(r, rawName, key.line, (at, message) => {
8173
+ throw new SchemaTsError(`line ${at}: ${message}`);
8174
+ });
7907
8175
  } else {
7908
8176
  throw new SchemaTsError(
7909
- `line ${key.line}: table "${rawName}" has an unknown option "${key.name}". Allowed: scope, indexes, unique, relations, client, rooms.`
8177
+ `line ${key.line}: table "${rawName}" has an unknown option "${key.name}". Allowed: scope, indexes, unique, relations, client, rooms, columns.`
7910
8178
  );
7911
8179
  }
7912
8180
  if (!r.tryPunct(",")) {
@@ -8034,7 +8302,46 @@ function readTable(r, rawName, nameLine) {
8034
8302
  client = parsed.permissions;
8035
8303
  }
8036
8304
  const rooms = roomsInput ? validateRoomsOption(roomsInput, rawName, nameLine, columns, scope, client, relations) : void 0;
8037
- return { kind: "table", table: { name, scope, relations, columns, indexes, uniques, removedColumns: [...removedColumns].sort(), ...client ? { client } : {}, ...rooms ? { rooms } : {} } };
8305
+ if (scope.kind === "policy" && scope.policy.kind === "parent" && scope.policy.author) {
8306
+ const authorColumn = scope.policy.author.column;
8307
+ const declared = columns.find((c) => c.name === authorColumn);
8308
+ if (!declared || declared.helper !== "text" || !declared.nullable || declared.hasDefault || declared.renamedFrom) {
8309
+ throw new SchemaTsError(`line ${nameLine}: parent({ author: '${authorColumn}' }) on table "${rawName}" must name a declared text({ nullable: true }) column without a default or rename: the platform stamps it with the row's creator, and a row without one grants its author nothing.`);
8310
+ }
8311
+ if (authorColumn === scope.policy.via) throw new SchemaTsError(`line ${nameLine}: parent({ author }) on table "${rawName}" cannot be the parent link "${authorColumn}".`);
8312
+ if (client && ((client.create ?? []).includes(authorColumn) || (client.update ?? []).includes(authorColumn))) {
8313
+ throw new SchemaTsError(`line ${nameLine}: table "${rawName}": "${authorColumn}" is the author the platform stamps, so client.create and client.update cannot list it.`);
8314
+ }
8315
+ }
8316
+ const columnRules = columnOptions?.write;
8317
+ const memberOf = columnOptions?.memberOf;
8318
+ if (memberOf) {
8319
+ validateColumnMemberOf(memberOf, {
8320
+ tableName: rawName,
8321
+ nameLine,
8322
+ columns,
8323
+ ownerColumn: managedOwner?.column ?? null,
8324
+ accessColumns: declaredScopeIdentityColumns(scope),
8325
+ roomSave: rooms?.save ?? null,
8326
+ groupColumns: declaredTeamColumns(scope)
8327
+ }, (at, message) => {
8328
+ throw new SchemaTsError(`line ${at}: ${message}`);
8329
+ });
8330
+ }
8331
+ if (columnRules) {
8332
+ validateColumnRules(columnRules, {
8333
+ tableName: rawName,
8334
+ nameLine,
8335
+ declaredColumns: new Set(columns.map((c) => c.name)),
8336
+ ownerColumn: managedOwner?.column ?? null,
8337
+ accessColumns: declaredScopeIdentityColumns(scope),
8338
+ roomSave: rooms?.save ?? null,
8339
+ serverOnly: scope.kind === "server_only"
8340
+ }, (at, message) => {
8341
+ throw new SchemaTsError(`line ${at}: ${message}`);
8342
+ });
8343
+ }
8344
+ return { kind: "table", table: { name, scope, relations, columns, indexes, uniques, removedColumns: [...removedColumns].sort(), ...client ? { client } : {}, ...rooms ? { rooms } : {}, ...columnRules ? { columnRules } : {}, ...memberOf ? { memberOf } : {} } };
8038
8345
  }
8039
8346
  function extractSchemaTs(source, options = {}) {
8040
8347
  if (typeof source !== "string" || source.trim().length === 0) {
@@ -8138,6 +8445,7 @@ function extractSchemaTs(source, options = {}) {
8138
8445
  return null;
8139
8446
  };
8140
8447
  resolveAppRoleScopes(tables, appRoles, errors);
8448
+ resolveColumnRuleRoles(tables, appRoles, groupRoles, errors);
8141
8449
  resolveGroupsAndParents(tables, tableByName, privatePolicy, groupRoles, errors);
8142
8450
  validateDeclaredMemberships(tables, tableByName, knownColumns, errors);
8143
8451
  validateDeclaredRelations(tables, tableByName, knownColumns, (table) => removedTables.includes(table) ? "removedTable()" : exportedTables.includes(table) ? "exported()" : null, errors);
@@ -8203,6 +8511,10 @@ function canonicalTableShape(t) {
8203
8511
 
8204
8512
  ...t.rooms ? { rooms: t.rooms } : {},
8205
8513
 
8514
+ ...t.columnRules ? { columnWrite: t.columnRules } : {},
8515
+
8516
+ ...t.memberOf ? { columnMemberOf: t.memberOf } : {},
8517
+
8206
8518
 
8207
8519
  ...t.groupRefs && t.groupRefs.length > 0 ? { groupRefs: t.groupRefs } : {},
8208
8520