simetra 0.3.0-next.2 → 0.3.0-next.4

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.
@@ -2889,8 +2889,24 @@ const MESSAGES = {
2889
2889
  en: (p) => `Open self sign-up lets anyone from the Internet become a signed-in user: objects open to every signed-in user (${p.objects || "none"}) and the grants of everyUser roles (${p.roles || "none"}) are exposed to them`,
2890
2890
  uk: (p) => `Відкрита самореєстрація дає змогу будь-кому з Інтернету стати дійсним користувачем: йому відкрито об'єкти для кожного користувача (${p.objects || "немає"}) і гранти ролей everyUser (${p.roles || "немає"})`,
2891
2891
  hint: {
2892
- en: "Check that these objects and grants are meant for anyone, or set selfSignUp to false.",
2893
- uk: "Переконайтеся, що ці об'єкти й гранти призначено для будь-кого, або вимкніть selfSignUp."
2892
+ en: "Check that these objects and grants are meant for anyone and list them in selfSignUpAccepted, or set selfSignUp to false.",
2893
+ uk: "Переконайтеся, що ці об'єкти й гранти призначено для будь-кого, і перелічіть їх у selfSignUpAccepted, або вимкніть selfSignUp."
2894
+ }
2895
+ },
2896
+ "project.self-sign-up-role": {
2897
+ en: (p) => `selfSignUpAccepted names ${p.kind} "${p.name}" as the role of a grant, but only a role of the everyUser level gives grants to anyone`,
2898
+ uk: (p) => `selfSignUpAccepted називає ${p.kind} "${p.name}" роллю гранту, але гранти будь-кому дає лише роль рівня everyUser`,
2899
+ hint: {
2900
+ en: "Name a Role with assignedOn everyUser, or remove the entry.",
2901
+ uk: "Назвіть Role з assignedOn everyUser або приберіть запис."
2902
+ }
2903
+ },
2904
+ "project.self-sign-up-stale": {
2905
+ en: (p) => `selfSignUpAccepted accepts ${p.entry}, but nothing open to every signed-in user matches it: the entry would silently accept such openness when it appears`,
2906
+ uk: (p) => `selfSignUpAccepted приймає ${p.entry}, але нічого відкритого кожному користувачу йому не відповідає: запис мовчки прийняв би таку відкритість, коли вона з'явиться`,
2907
+ hint: {
2908
+ en: "Remove the entry (or the actions it no longer matches); accept the openness again when it returns.",
2909
+ uk: "Приберіть запис (чи дії, яким уже нічого не відповідає); прийміть відкритість знову, коли вона повернеться."
2894
2910
  }
2895
2911
  },
2896
2912
  "rights.ownership-target": {
@@ -3282,11 +3298,11 @@ const MESSAGES = {
3282
3298
  }
3283
3299
  },
3284
3300
  "operation.input-invalid": {
3285
- en: (p) => p.scopes !== void 0 ? `The scopes input ${p.scopes === "target" ? "is allowed only with the scopeKinds collection of Project" : p.scopes === "table-unknown" ? `names ${p.table}, which is not a CustomTable of the project` : `names ${p.table}, which already declares its scope: changing a scope is another operation`} (at ${p.at}); nothing was changed` : p.at === void 0 ? "The operation needs metadata that compiles without errors; nothing was changed" : `The operation input must not carry "id" (at ${p.at}): ids are assigned by the operation; nothing was changed`,
3286
- uk: (p) => p.scopes !== void 0 ? `Вхід scopes ${p.scopes === "target" ? "дозволено лише з колекцією scopeKinds проєкту" : p.scopes === "table-unknown" ? `називає ${p.table}, якої немає серед CustomTable проєкту` : `називає ${p.table}, що вже оголошує скоуп: зміна скоупу — інша операція`} (у ${p.at}); нічого не змінено` : p.at === void 0 ? "Операція потребує метаданих, що компілюються без помилок; нічого не змінено" : `Вхід операції не повинен містити "id" (у ${p.at}): id призначає операція; нічого не змінено`,
3301
+ en: (p) => p.objects !== void 0 ? `The objects input is allowed only with the scopeKinds collection of Project (at ${p.at}); nothing was changed` : p.scopes !== void 0 ? `The scopes input ${p.scopes === "target" ? "is allowed only with the scopeKinds collection of Project" : p.scopes === "table-unknown" ? `names ${p.table}, which is not a CustomTable of the project` : `names ${p.table}, which already declares its scope: changing a scope is another operation`} (at ${p.at}); nothing was changed` : p.at === void 0 ? "The operation needs metadata that compiles without errors; nothing was changed" : `The operation input must not carry "id" (at ${p.at}): ids are assigned by the operation; nothing was changed`,
3302
+ uk: (p) => p.objects !== void 0 ? `Вхід objects дозволено лише з колекцією scopeKinds проєкту (у ${p.at}); нічого не змінено` : p.scopes !== void 0 ? `Вхід scopes ${p.scopes === "target" ? "дозволено лише з колекцією scopeKinds проєкту" : p.scopes === "table-unknown" ? `називає ${p.table}, якої немає серед CustomTable проєкту` : `називає ${p.table}, що вже оголошує скоуп: зміна скоупу — інша операція`} (у ${p.at}); нічого не змінено` : p.at === void 0 ? "Операція потребує метаданих, що компілюються без помилок; нічого не змінено" : `Вхід операції не повинен містити "id" (у ${p.at}): id призначає операція; нічого не змінено`,
3287
3303
  hint: {
3288
- en: (p) => p.scopes !== void 0 ? "Use scopes only when adding a scope kind to Project, and name only CustomTables that have no scope yet." : p.at === void 0 ? "Fix the errors reported with this diagnostic (simetra fix handles missing ids and physical names), then repeat the operation." : "Remove the id from the input; a new element gets a fresh id that is never reused.",
3289
- uk: (p) => p.scopes !== void 0 ? "Використовуйте scopes лише при додаванні виду скоупу в проєкт і називайте лише CustomTable без скоупу." : p.at === void 0 ? "Виправте помилки, наведені поряд із цією діагностикою (відсутні id і фізичні імена лагодить simetra fix), і повторіть операцію." : "Приберіть id із входу; новий елемент отримує свіжий id, який ніколи не перевикористовується."
3304
+ en: (p) => p.objects !== void 0 ? "Use objects only when adding a scope kind to Project; create other objects with create." : p.scopes !== void 0 ? "Use scopes only when adding a scope kind to Project, and name only CustomTables that have no scope yet." : p.at === void 0 ? "Fix the errors reported with this diagnostic (simetra fix handles missing ids and physical names), then repeat the operation." : "Remove the id from the input; a new element gets a fresh id that is never reused.",
3305
+ uk: (p) => p.objects !== void 0 ? "Використовуйте objects лише при додаванні виду скоупу в проєкт; інші об'єкти створюйте через create." : p.scopes !== void 0 ? "Використовуйте scopes лише при додаванні виду скоупу в проєкт і називайте лише CustomTable без скоупу." : p.at === void 0 ? "Виправте помилки, наведені поряд із цією діагностикою (відсутні id і фізичні імена лагодить simetra fix), і повторіть операцію." : "Приберіть id із входу; новий елемент отримує свіжий id, який ніколи не перевикористовується."
3290
3306
  }
3291
3307
  },
3292
3308
  "operation.target-not-found": {
@@ -4489,6 +4505,14 @@ const MESSAGES = {
4489
4505
  uk: "Саме підключення вдалося; збій стався під час роботи з базою. Текст помилки драйвера приховано, бо він може нести облікові дані; знайдіть SQLSTATE або повторіть після виправлення бази."
4490
4506
  }
4491
4507
  },
4508
+ "data.scope-unspecified": {
4509
+ en: (p) => `The create of ${p.object} names no ${p.attribute}, and the user is a member of ${p.scopes} scopes of kind "${p.scopeKind}": the scope of the new row is not specified. Nothing was written.`,
4510
+ uk: (p) => `Створення ${p.object} не називає ${p.attribute}, а користувач — учасник ${p.scopes} скоупів виду "${p.scopeKind}": скоуп нового рядка не вказано. Нічого не записано.`,
4511
+ hint: {
4512
+ en: (p) => `Pass values.${p.attribute} with the scope of the new row; it is taken by itself only when the user is a member of exactly one scope of the kind.`,
4513
+ uk: (p) => `Передайте values.${p.attribute} зі скоупом нового рядка; сам він береться лише тоді, коли користувач — учасник рівно одного скоупу виду.`
4514
+ }
4515
+ },
4492
4516
  "roles.create-role-denied": {
4493
4517
  en: (p) => `The connecting role cannot create the platform role ${p.role} on the ${p.server} server: it has neither CREATEROLE nor SUPERUSER`,
4494
4518
  uk: (p) => `Роль підключення не може створити платформну роль ${p.role} на сервері ${p.server === "shadow" ? "тіні" : "цілі"}: у неї немає ні CREATEROLE, ні SUPERUSER`,
@@ -5056,6 +5080,8 @@ const COMPILER_RULES = [
5056
5080
  "rights.adopted-source-writes",
5057
5081
  "rights.scope-kind-unread",
5058
5082
  "project.self-sign-up",
5083
+ "project.self-sign-up-role",
5084
+ "project.self-sign-up-stale",
5059
5085
  "rights.snapshot-source-unknown",
5060
5086
  "rights.snapshot-exempt-writer",
5061
5087
  "rights.signal-source-unknown",
@@ -5257,6 +5283,7 @@ const COMPILER_RULES = [
5257
5283
  "plan.rights-full-access-lost",
5258
5284
  "plan.rights-orphans",
5259
5285
  "database.failed",
5286
+ "data.scope-unspecified",
5260
5287
  "roles.create-role-denied",
5261
5288
  "roles.admin-option-missing",
5262
5289
  "roles.membership-grant-denied",
@@ -5347,6 +5374,7 @@ const WARNING_RULES = /* @__PURE__ */ new Set([
5347
5374
  "rights.adopted-source-writes",
5348
5375
  "rights.scope-kind-unread",
5349
5376
  "project.self-sign-up",
5377
+ "project.self-sign-up-stale",
5350
5378
  "rights.root-creator-no-admin",
5351
5379
  "rights.root-creator-unreachable",
5352
5380
  "sql.debt-session-write",
@@ -6967,7 +6995,6 @@ function derivedSearchColumn(object, style, name) {
6967
6995
  };
6968
6996
  }
6969
6997
  }
6970
- // src/compiler/stages/identity.ts
6971
6998
  /**
6972
6999
  * Ролі, де рядок файлу — логічне ім'я колонки прийнятої таблиці чи цілі її FK.
6973
7000
  * Одна множина для знімка (ім'я → id елемента) і для стадії 3 (id → фізичне
@@ -7200,6 +7227,73 @@ function checkIdentity(objects, brokenNames, project, functionsFiles) {
7200
7227
  role: "storage.scopeKind"
7201
7228
  });
7202
7229
  });
7230
+ const accepted = project?.selfSignUpAccepted;
7231
+ const acceptedTo = (pointer, to) => {
7232
+ references.push({
7233
+ from: {
7234
+ file: PROJECT_FILE,
7235
+ pointer,
7236
+ objectId: ""
7237
+ },
7238
+ to,
7239
+ role: "selfSignUp.accepted"
7240
+ });
7241
+ };
7242
+ const resolveAccepted = (pointer, ref) => {
7243
+ const key = objectKey(ref.kind, ref.name);
7244
+ const target = objectsByName.get(key);
7245
+ if (target === void 0) {
7246
+ if (!brokenNames.has(key)) diagnostics.push(diagnostic("reference.unresolved", PROJECT_FILE, pointer, {
7247
+ kind: ref.kind,
7248
+ name: ref.name
7249
+ }));
7250
+ return;
7251
+ }
7252
+ if (target.id !== void 0) acceptedTo(pointer, {
7253
+ kind: target.kind,
7254
+ id: target.id
7255
+ });
7256
+ return target;
7257
+ };
7258
+ accepted?.objects.forEach((entry, index) => {
7259
+ resolveAccepted(`/selfSignUpAccepted/objects/${index}/object`, entry.object);
7260
+ });
7261
+ accepted?.grants.forEach((grant, index) => {
7262
+ const at = `/selfSignUpAccepted/grants/${index}`;
7263
+ const role = resolveAccepted(`${at}/role`, grant.role);
7264
+ if (role !== void 0 && (role.kind !== "Role" || role.data.assignedOn !== "everyUser")) diagnostics.push(diagnostic("project.self-sign-up-role", PROJECT_FILE, `${at}/role`, {
7265
+ kind: role.kind,
7266
+ name: role.name
7267
+ }));
7268
+ const object = resolveAccepted(`${at}/object`, grant.object);
7269
+ if (object !== void 0) {
7270
+ const standard = KIND_REGISTRY[object.kind].actions(object.data);
7271
+ const custom = customActionsOf(object);
7272
+ grant.actions.forEach((name, i) => {
7273
+ if (standard.some((a) => a.name === name)) return;
7274
+ const id = custom.find((a) => a.name === name)?.id;
7275
+ if (id !== void 0) {
7276
+ acceptedTo(`${at}/actions/${i}`, {
7277
+ kind: "Element",
7278
+ id
7279
+ });
7280
+ return;
7281
+ }
7282
+ diagnostics.push(diagnostic("rights.action-unknown", PROJECT_FILE, `${at}/actions/${i}`, {
7283
+ action: name,
7284
+ object: object.name
7285
+ }));
7286
+ });
7287
+ }
7288
+ if (typeof grant.extent === "object") {
7289
+ const id = projectElements.get("accessDimensions")?.get(grant.extent.dimension)?.id;
7290
+ if (id !== void 0) acceptedTo(`${at}/extent/dimension`, {
7291
+ kind: "Element",
7292
+ id
7293
+ });
7294
+ else diagnostics.push(diagnostic("rights.dimension-unknown", PROJECT_FILE, `${at}/extent/dimension`, { dimension: grant.extent.dimension }));
7295
+ }
7296
+ });
7203
7297
  dimensions.forEach((dimension, index) => {
7204
7298
  resolveDimension(dimension, `/accessDimensions/${index}`, resolveObjectRef, style, references);
7205
7299
  });
@@ -8175,7 +8269,8 @@ function canonicalSnapshot(model) {
8175
8269
  "storageBuckets",
8176
8270
  "accessDimensions",
8177
8271
  "membershipSources",
8178
- "assignmentSources"
8272
+ "assignmentSources",
8273
+ "selfSignUpAccepted"
8179
8274
  ]);
8180
8275
  return {
8181
8276
  project: Object.fromEntries(Object.entries(model.project).filter(([key]) => !unresolved.has(key))),
@@ -22292,7 +22387,7 @@ function systemOf(object) {
22292
22387
  return KIND_REGISTRY[object.kind].rightsSystem?.(object.data);
22293
22388
  }
22294
22389
  /** Рівень системного довідника — його власний скоуп (спека прав §4.6). */
22295
- function catalogLevel(object, references) {
22390
+ function catalogLevel$1(object, references) {
22296
22391
  const scopeKindId = scopeKindOf(object, references);
22297
22392
  return scopeKindId === void 0 ? GLOBAL : {
22298
22393
  level: "scope",
@@ -22373,7 +22468,7 @@ function checkSystemCatalogs(ctx) {
22373
22468
  const first = /* @__PURE__ */ new Map();
22374
22469
  for (const object of catalogs) {
22375
22470
  const system = must$9(systemOf(object));
22376
- const level = catalogLevel(object, ctx.references);
22471
+ const level = catalogLevel$1(object, ctx.references);
22377
22472
  const key = `${system}\u0000${storageKey(level)}`;
22378
22473
  const firstObject = first.get(key);
22379
22474
  if (firstObject === void 0) first.set(key, object);
@@ -22426,7 +22521,7 @@ function checkSystemCatalogs(ctx) {
22426
22521
  }
22427
22522
  }
22428
22523
  for (const object of catalogs) {
22429
- const level = catalogLevel(object, ctx.references);
22524
+ const level = catalogLevel$1(object, ctx.references);
22430
22525
  const source = sourced.get(storageKey(level));
22431
22526
  if (source === void 0 || uncovered.has(storageKey(level))) continue;
22432
22527
  diagnostics.push(diagnostic("rights.system-catalog-parallel", object.file, "/role", {
@@ -22460,7 +22555,7 @@ function rightsCatalogContracts(objects, references, physical) {
22460
22555
  for (const object of objects) {
22461
22556
  const system = systemOf(object);
22462
22557
  if (system === void 0) continue;
22463
- const level = catalogLevel(object, references);
22558
+ const level = catalogLevel$1(object, references);
22464
22559
  const key = storageKey(level);
22465
22560
  byLevel.set(key, {
22466
22561
  level,
@@ -22522,6 +22617,7 @@ const RIGHTS_FUNCTIONS = {
22522
22617
  own: platform$2("rights_own"),
22523
22618
  dim: platform$2("rights_dim"),
22524
22619
  container: platform$2("rights_container"),
22620
+ containerHeld: platform$2("rights_container_held"),
22525
22621
  hasRight: platform$2("has_right"),
22526
22622
  require: platform$2("rights_require"),
22527
22623
  requireScope: platform$2("rights_require_scope"),
@@ -22534,6 +22630,7 @@ const RIGHTS_FUNCTIONS = {
22534
22630
  visibleUsers: platform$2("rights_visible_users"),
22535
22631
  scopesOf: platform$2("rights_scopes_of"),
22536
22632
  detailOf: platform$2("rights_detail_of"),
22633
+ containerHeldOf: platform$2("rights_container_held_of"),
22537
22634
  membersOf: platform$2("rights_members_of"),
22538
22635
  dimensionValuesOf: platform$2("rights_dimension_values_of"),
22539
22636
  scopeSetOf: platform$2("rights_scope_set_of"),
@@ -22696,6 +22793,7 @@ function buildRightsUnits(contracts, physical, attributeCase, provider, module,
22696
22793
  shape: "dispatcher",
22697
22794
  body: snapshotDispatcher(which, snapshotSql, liveSql)
22698
22795
  } : definer(fn, args, returns, current);
22796
+ const heldObject = param(F.containerHeld, "p_object");
22699
22797
  const declarations = [
22700
22798
  data(F.projection, table$1(PROJECTION_COLUMNS), valuesBody(PROJECTION_COLUMNS, projectionRows(contracts))),
22701
22799
  data(F.requires, table$1(REQUIRES_COLUMNS), valuesBody(REQUIRES_COLUMNS, requiresRows(contracts.rights))),
@@ -22722,6 +22820,14 @@ function buildRightsUnits(contracts, physical, attributeCase, provider, module,
22722
22820
  text("p_extent"),
22723
22821
  uuid("p_dimension")
22724
22822
  ], "SETOF uuid", containerBody()),
22823
+ {
22824
+ ...fact(F.containerHeld, [text("p_object")], table$1(HELD_COLUMNS), "rights", containerHeldBody(snapshotInputs(SNAPSHOT_XID), contracts.rights, heldObject), containerHeldBody(liveInputs(contracts, physical, attributeCase, LIVE), contracts.rights, heldObject), containerHeldBody(liveInputs(contracts, physical, attributeCase, CURRENT), contracts.rights, heldObject)),
22825
+ ...snapshot ? { requires: [SNAPSHOT_TABLES.typed, SNAPSHOT_TABLES.containers].map((t) => ({
22826
+ type: "table",
22827
+ ...t
22828
+ })) } : {}
22829
+ },
22830
+ variant(F.containerHeldOf, [text("p_object")], table$1(HELD_COLUMNS), containerHeldBody(liveInputs(contracts, physical, attributeCase, of(F.containerHeldOf)), contracts.rights, param(F.containerHeldOf, "p_object"))),
22725
22831
  definer(F.hasRight, [
22726
22832
  text("p_action"),
22727
22833
  text("p_object"),
@@ -23240,20 +23346,7 @@ function mineBody(user, detail, inputs, pair) {
23240
23346
  return withCtes([
23241
23347
  ["typed", inputs.typed],
23242
23348
  ["containers", inputs.containers],
23243
- ["held", [
23244
- `SELECT t.storage, t.storage_id, t.scope, NULL::uuid AS container, t.custom_role, t.archetype, t.level, t.level_id`,
23245
- `FROM typed t`,
23246
- `WHERE t.level <> 'container'`,
23247
- `UNION ALL`,
23248
- `SELECT t.storage, t.storage_id, t.scope, k.container, t.custom_role, t.archetype, t.level, t.level_id`,
23249
- `FROM typed t`,
23250
- `JOIN containers k`,
23251
- ` ON k.level_id = t.level_id`,
23252
- ` AND k.container = t.container`,
23253
- ` AND k.scope_kind_id IS NOT DISTINCT FROM t.scope_kind_id`,
23254
- ` AND k.scope IS NOT DISTINCT FROM t.scope`,
23255
- `WHERE t.level = 'container'`
23256
- ].join("\n")],
23349
+ ["held", heldCte()],
23257
23350
  [
23258
23351
  "deltas",
23259
23352
  inputs.deltas,
@@ -23304,6 +23397,64 @@ function mineBody(user, detail, inputs, pair) {
23304
23397
  ].join("\n"));
23305
23398
  }
23306
23399
  /**
23400
+ * Дієві призначення актора з їхнім контейнером (CTE `held`).
23401
+ * Контейнер — лише в архетипу контейнерного рівня й лише існуючий
23402
+ * контейнер того самого тенанта (спека прав §4.6): inner join, тож `NULL`,
23403
+ * неіснуючий чи чужий контейнер не дає рядка. Вид скоупу контейнера
23404
+ * зіставлено явно з видом скоупу рядка призначення, а не лише через
23405
+ * рівень зберігання архетипу (`typed`): скоуп без виду нічого не
23406
+ * означає (спека прав §5.1). Вид — колонка `scope_kind_id`, а не `storage_id`:
23407
+ * у рядка джерела там id джерела (спека прав §4.7). Позначка видалення
23408
+ * контейнера прав не відкликає (спека прав §4.6): права зникають із вилученням
23409
+ * контейнера.
23410
+ *
23411
+ * Одне місце для `rights_mine` і `rights_container_held`: критерій
23412
+ * «має контейнерне призначення» не розходиться з призначеннями, з яких
23413
+ * `rights_mine` рахує права контейнера.
23414
+ */
23415
+ function heldCte() {
23416
+ return [
23417
+ `SELECT t.storage, t.storage_id, t.scope, NULL::uuid AS container, t.custom_role, t.archetype, t.level, t.level_id`,
23418
+ `FROM typed t`,
23419
+ `WHERE t.level <> 'container'`,
23420
+ `UNION ALL`,
23421
+ `SELECT t.storage, t.storage_id, t.scope, k.container, t.custom_role, t.archetype, t.level, t.level_id`,
23422
+ `FROM typed t`,
23423
+ `JOIN containers k`,
23424
+ ` ON k.level_id = t.level_id`,
23425
+ ` AND k.container = t.container`,
23426
+ ` AND k.scope_kind_id IS NOT DISTINCT FROM t.scope_kind_id`,
23427
+ ` AND k.scope IS NOT DISTINCT FROM t.scope`,
23428
+ `WHERE t.level = 'container'`
23429
+ ].join("\n");
23430
+ }
23431
+ const HELD_COLUMNS = [["container", "uuid"], ["scope", "uuid"]];
23432
+ const CONTAINER_LABEL_COLUMNS = [["object", "text"], ["level_id", "uuid"]];
23433
+ /**
23434
+ * Контейнери виду з міткою `object`, у яких актор має дієве контейнерне
23435
+ * призначення (спека прав контейнера §1), зі скоупом контейнера. Тіло — над
23436
+ * входами `rights_mine`, а не над її виходом: роль без грантів чи з дельтою
23437
+ * `deny read` рядків прав не дає, а критерій неявного читання — саме
23438
+ * призначення. Мітка зіставляється з id контейнерного об'єкта сталою
23439
+ * генератора: рівень призначення несе id, а не мітку.
23440
+ */
23441
+ function containerHeldBody(inputs, rights, object) {
23442
+ const labels = valuesBody(CONTAINER_LABEL_COLUMNS, rights.filter((c) => c.container === true).map((c) => [c.kindLabel, c.objectId]));
23443
+ return withCtes([
23444
+ ["typed", inputs.typed],
23445
+ ["containers", inputs.containers],
23446
+ ["held", heldCte()]
23447
+ ], [
23448
+ `SELECT DISTINCT h.container, h.scope`,
23449
+ `FROM held h`,
23450
+ `JOIN (`,
23451
+ indent$2(labels),
23452
+ `) o ON o.level_id = h.level_id`,
23453
+ `WHERE h.level = 'container'`,
23454
+ ` AND o.object = ${object}`
23455
+ ].join("\n"));
23456
+ }
23457
+ /**
23307
23458
  * Рядки ролей «кожного користувача» — без призначень і замикання: одне місце
23308
23459
  * для `rights_mine` і для «хто може» (спека прав §5.1).
23309
23460
  */
@@ -32484,8 +32635,21 @@ function rightsPredicates(contract, action, table, main, dml) {
32484
32635
  conditions: [...mine, grant]
32485
32636
  };
32486
32637
  });
32638
+ const asContainer = action === "read" && dml === "select" && contract.container === true && table.schema === contract.table.schema && table.name === contract.table.name ? [{
32639
+ extent: "as_container",
32640
+ conditions: [{
32641
+ kind: "column",
32642
+ column: must$9(rootFamilyKey(table, main)),
32643
+ set: {
32644
+ fn: F.containerHeld,
32645
+ args: [sqlLiteral(contract.kindLabel)],
32646
+ field: "container"
32647
+ },
32648
+ grantDependent: false
32649
+ }]
32650
+ }] : [];
32487
32651
  const binding = contract.binding;
32488
- if (binding === void 0) return atScope;
32652
+ if (binding === void 0) return [...atScope, ...asContainer];
32489
32653
  const bound = column(binding.carrier);
32490
32654
  const inContainer = inners.map(({ extent, carrier, mine }) => ({
32491
32655
  extent: {
@@ -32503,9 +32667,20 @@ function rightsPredicates(contract, action, table, main, dml) {
32503
32667
  grantDependent: true
32504
32668
  }]
32505
32669
  }));
32506
- return [...atScope, ...inContainer];
32670
+ return [
32671
+ ...atScope,
32672
+ ...inContainer,
32673
+ ...asContainer
32674
+ ];
32507
32675
  }
32508
32676
  /**
32677
+ * Чи судить предикат сам рядок, а не грант: неявне читання рядка контейнера
32678
+ * (спека прав контейнера §1). Перевірка без рядка — право без рядка й
32679
+ * `rights_require` без цілі — його не містить. Одне визначення для обох, тож
32680
+ * правило не розійдеться.
32681
+ */
32682
+ const judgedByRow = (predicate) => predicate.extent === "as_container";
32683
+ /**
32509
32684
  * The row-free form of an action's right (P4-B spec §8.3): the grant part of
32510
32685
  * each scope-level predicate of `rightsPredicates` — the scope sets of `any`,
32511
32686
  * `own` and a dimension, or `has_right` with the same extents for an unscoped
@@ -32515,7 +32690,7 @@ function rightsPredicates(contract, action, table, main, dml) {
32515
32690
  function rowFreeGrants(contract, action, main) {
32516
32691
  const grants = /* @__PURE__ */ new Map();
32517
32692
  for (const predicate of rightsPredicates(contract, action, main, main, "select")) {
32518
- if (typeof predicate.extent !== "string" && "container" in predicate.extent) continue;
32693
+ if (judgedByRow(predicate) || typeof predicate.extent !== "string" && "container" in predicate.extent) continue;
32519
32694
  const grant = must$9(predicate.conditions.at(-1));
32520
32695
  grants.set(JSON.stringify(grant), grant);
32521
32696
  }
@@ -32584,7 +32759,7 @@ function carrierColumn(contract, carrier, table, main) {
32584
32759
  function renderCondition(condition, row, published) {
32585
32760
  const at = (column) => row === void 0 ? quoteIdent(column) : `${row}.${quoteIdent(column)}`;
32586
32761
  switch (condition.kind) {
32587
- case "column": return `${at(condition.column)} = ANY (ARRAY(SELECT ${call$1(condition.set.fn, condition.set.args)}))`;
32762
+ case "column": return `${at(condition.column)} = ANY (ARRAY(SELECT ${setQuery(condition.set)}))`;
32588
32763
  case "currentUser": return `${at(condition.column)} = ${CURRENT_USER$1}`;
32589
32764
  case "boolean": return `(SELECT ${condition.expression})`;
32590
32765
  case "rowLiteral": {
@@ -32595,6 +32770,10 @@ function renderCondition(condition, row, published) {
32595
32770
  case "validUser": return `${CURRENT_USER$1} IS NOT NULL`;
32596
32771
  }
32597
32772
  }
32773
+ /** Ціль підзапиту множини: виклик функції чи поле рядка табличної функції. */
32774
+ function setQuery({ fn, args, field }) {
32775
+ return field === void 0 ? call$1(fn, args) : `(${call$1(fn, args)}).${quoteIdent(field)}`;
32776
+ }
32598
32777
  /**
32599
32778
  * «Мій» рядок за носієм власності (спека прав §5.1): мої id учасника — лише свого
32600
32779
  * виду скоупу (спека прав §5.1), бо `id` довідника задає той, хто пише; носій на
@@ -33135,7 +33314,7 @@ function rightsPolicyLabel(contracts) {
33135
33314
  }
33136
33315
  function rightsLabel(predicate, contract, labels) {
33137
33316
  const inner = (extent) => {
33138
- if (extent === "any") return "any";
33317
+ if (extent === "any" || extent === "as_container") return extent;
33139
33318
  if (extent === "own") return contract.ownership.length > 1 ? `own_${must$3(predicate.carrier)}` : "own";
33140
33319
  if ("dimensionId" in extent) return must$3(labels.dimension.get(extent.dimensionId));
33141
33320
  return `in_${must$3(labels.container.get(extent.container))}_${inner(extent.inner)}`;
@@ -33485,6 +33664,50 @@ function triggeredRelationTable(relation, physical, objects) {
33485
33664
  return table;
33486
33665
  }
33487
33666
  // src/compiler/runtime-catalog.ts
33667
+ /** Рівень ролі контракту як його бачить каталог (спека «Споживач поза монорепо» §5.4). */
33668
+ function catalogLevel(level) {
33669
+ switch (level.level) {
33670
+ case "global":
33671
+ case "everyUser": return level.level;
33672
+ case "scope": return { scopeKind: level.scopeKindId };
33673
+ case "container": return { container: level.containerId };
33674
+ }
33675
+ }
33676
+ /**
33677
+ * Розділи `roles` і `rightsSets` спільної частини каталогу: назви архетипів
33678
+ * для екрана призначення. Порядок — за `order`, далі за `name`; у проєкті без
33679
+ * ролей чи наборів поля немає. `title` береться з метаданих, а не з
33680
+ * контракту: контракт у знімок не змінюється.
33681
+ */
33682
+ function rightsDeclarationsOf(model) {
33683
+ const titleOf = (kind) => new Map(model.objects.filter((o) => o.kind === kind).map((o) => [o.id, o.data.title]));
33684
+ const roleTitles = titleOf("Role");
33685
+ const roles = model.contracts.roles.map((r) => {
33686
+ const title = roleTitles.get(r.roleId);
33687
+ return {
33688
+ id: r.roleId,
33689
+ name: r.name,
33690
+ ...title === void 0 ? {} : { title },
33691
+ level: catalogLevel(r.assignedOn),
33692
+ ...r.order === void 0 ? {} : { order: r.order },
33693
+ assignable: r.assignable,
33694
+ fullAccess: r.fullAccess
33695
+ };
33696
+ }).sort((a, b) => (a.order ?? Number.MAX_SAFE_INTEGER) - (b.order ?? Number.MAX_SAFE_INTEGER) || compareStrings(a.name, b.name));
33697
+ const setTitles = titleOf("RightsSet");
33698
+ const rightsSets = model.objects.filter((o) => o.kind === "RightsSet").map((o) => {
33699
+ const title = setTitles.get(o.id);
33700
+ return {
33701
+ id: o.id,
33702
+ name: o.name,
33703
+ ...title === void 0 ? {} : { title }
33704
+ };
33705
+ }).sort((a, b) => compareStrings(a.name, b.name));
33706
+ return {
33707
+ ...roles.length === 0 ? {} : { roles },
33708
+ ...rightsSets.length === 0 ? {} : { rightsSets }
33709
+ };
33710
+ }
33488
33711
  /**
33489
33712
  * Каталог рантайму (спека П4 §6.3) — проєкція скомпільованої моделі: лише
33490
33713
  * довідники з контрактом ядра команд (`CompiledModel.catalogCommands`), у
@@ -33530,6 +33753,7 @@ function buildRuntimeCatalog(model) {
33530
33753
  ...adoptedFactsOf(model)
33531
33754
  } : {},
33532
33755
  ...model.project.selfSignUp ? { selfSignUp: true } : {},
33756
+ ...rightsDeclarationsOf(model),
33533
33757
  objects: model.objects.flatMap((object) => {
33534
33758
  const contract = contracts.get(object.id);
33535
33759
  if (contract === void 0) return [];
@@ -36595,10 +36819,13 @@ function rootCreatorFunction(facts) {
36595
36819
  * (спека П4 §6.6), а літерал не залежить від того, що поставив T3. `dml` —
36596
36820
  * DML функції ядра, як у політики: створення кореня скоупу судить та сама
36597
36821
  * булева форма, що й політика `INSERT` кореня (спека прав §5.2). Один рядок —
36598
- * AND умов одного предиката.
36822
+ * AND умов одного предиката. `rowless` — перевірка без рядка (об'єкт без
36823
+ * носіїв): неявне читання контейнера судить сам рядок (спека прав контейнера
36824
+ * §1), тож його предиката там немає — те саме правило `judgedByRow`, що й у
36825
+ * праві без рядка (`rowFreeGrants`).
36599
36826
  */
36600
- function rightsCheckPredicates(contract, action, main, row, dml) {
36601
- return rightsPredicates(contract, action, main, main, dml).map((predicate) => predicate.conditions.map((c) => renderCondition(c, row)).join(" AND "));
36827
+ function rightsCheckPredicates(contract, action, main, row, dml, rowless = false) {
36828
+ return rightsPredicates(contract, action, main, main, dml).filter((predicate) => !(rowless && judgedByRow(predicate))).map((predicate) => predicate.conditions.map((c) => renderCondition(c, row)).join(" AND "));
36602
36829
  }
36603
36830
  /**
36604
36831
  * Перевірка права ядра — OR предикатів, як OR `PERMISSIVE`-політик. Без
@@ -36606,8 +36833,8 @@ function rightsCheckPredicates(contract, action, main, row, dml) {
36606
36833
  * вживає її лише як `IF (…) IS NOT TRUE`, бо носій `NULL` дає `NULL`, і
36607
36834
  * `IF NOT (…)` пропустив би запис до сирого `42501` RLS.
36608
36835
  */
36609
- function rightsCheck(contract, action, main, row, dml) {
36610
- const predicates = rightsCheckPredicates(contract, action, main, row, dml);
36836
+ function rightsCheck(contract, action, main, row, dml, rowless = false) {
36837
+ const predicates = rightsCheckPredicates(contract, action, main, row, dml, rowless);
36611
36838
  if (predicates.length === 0) return "false";
36612
36839
  return predicates.map((p) => `(${p})`).join(" OR ");
36613
36840
  }
@@ -37810,7 +38037,7 @@ function branchesOf(input) {
37810
38037
  const key = `${form}\0${contract.kindLabel}\0${action.action}`;
37811
38038
  const main = must$9(mainTableOf(input.physical, contract.objectId));
37812
38039
  const access = input.contracts.access.find((a) => a.table.schema === main.schema && a.table.name === main.name);
37813
- const condition = form === "row" ? rowBranch(contract, action.action, input, visibleUsers, must$9(readCallers.get(`${contract.kindLabel}\0${action.action}`))) : form === "scope" ? scopeBranch(contract, action.action, must$9(access)) : rightsCheck(contract, action.action, main, ROW, dmlOf(action.action));
38040
+ const condition = form === "row" ? rowBranch(contract, action.action, input, visibleUsers, must$9(readCallers.get(`${contract.kindLabel}\0${action.action}`))) : form === "scope" ? scopeBranch(contract, action.action, must$9(access)) : rightsCheck(contract, action.action, main, ROW, dmlOf(action.action), true);
37814
38041
  found.set(key, {
37815
38042
  form,
37816
38043
  label: contract.kindLabel,
@@ -38038,7 +38265,10 @@ function explainRows(access, rights, main, { contracts, label, visibleUsers, ses
38038
38265
  });
38039
38266
  if (!everyRow && rights !== void 0 && rights.actions.some((a) => a.action === "read")) {
38040
38267
  const dimensions = new Map(contracts.accessDimensions.map((d) => [uuidLiteral(d.dimensionId), d]));
38041
- for (const predicate of rightsPredicates(rights, "read", main, main, "select")) rows.push(predicateRow(predicate, rights, names.rights(label(predicate, rights)), dimensions, subject));
38268
+ for (const predicate of rightsPredicates(rights, "read", main, main, "select")) {
38269
+ const policy = names.rights(label(predicate, rights));
38270
+ rows.push(predicate.extent === "as_container" ? asContainerRow(predicate, policy, subject) : predicateRow(predicate, rights, policy, dimensions, subject));
38271
+ }
38042
38272
  }
38043
38273
  if (access.publishedRead !== void 0) rows.push({
38044
38274
  policy: names.publishedRead,
@@ -38079,6 +38309,25 @@ function predicateRow(predicate, rights, policy, dimensions, subject) {
38079
38309
  roles: `ARRAY(SELECT DISTINCT x.role FROM ${subject.granted} g CROSS JOIN LATERAL (VALUES (g.role_id), (g.custom_role)) AS x(role) WHERE ${filter} AND x.role IS NOT NULL ORDER BY x.role)`
38080
38310
  };
38081
38311
  }
38312
+ /**
38313
+ * Рядок неявного читання рядка контейнера (спека прав контейнера §1): не
38314
+ * грант, тож без ролей і обсягу; `carrier_match` — рядок серед контейнерів з
38315
+ * дієвим призначенням `subject`: для викликача — функція фактів, як у RLS,
38316
+ * для `p_user` — її живий варіант `rights_container_held_of`.
38317
+ */
38318
+ function asContainerRow(predicate, policy, subject) {
38319
+ const [condition, ...rest] = predicate.conditions;
38320
+ if (condition?.kind !== "column" || rest.length > 0) throw new Error("internal: as_container is one set condition");
38321
+ const { fn, args, field } = condition.set;
38322
+ return {
38323
+ policy,
38324
+ kind: "permissive",
38325
+ extent: null,
38326
+ hasRight: "TRUE",
38327
+ carrierMatch: `EXISTS (SELECT 1 FROM ${subject.sets === "current" ? call$1(fn, args) : call$1(F.containerHeldOf, [subject.user, ...args])} h WHERE h.${quoteIdent(must$9(field))} = ${row(condition.column)})`,
38328
+ roles: NO_ROLES
38329
+ };
38330
+ }
38082
38331
  const isGrant = (condition) => condition.kind === "boolean" || condition.kind === "column" && condition.grantDependent;
38083
38332
  /**
38084
38333
  * Рядки прав `p_user`, що дають грант предиката (спека прав §5.1), — ті самі, що
@@ -38096,6 +38345,7 @@ function grantFilter(predicate, grant, rights) {
38096
38345
  /** Обсяг предиката без контейнера й чи це предикат у контейнері. */
38097
38346
  function extentOf(predicate) {
38098
38347
  const { extent } = predicate;
38348
+ if (extent === "as_container") throw new Error("internal: as_container has no grant extent");
38099
38349
  return typeof extent === "object" && "container" in extent ? {
38100
38350
  inner: extent.inner,
38101
38351
  container: true
@@ -38433,21 +38683,84 @@ function scopeKindUnreadWarnings(contracts, project) {
38433
38683
  * Роль `publicRead` читається зі скомпільованого контракту доступу, а не з
38434
38684
  * рядкової форми метаданих: `anon` теж відкриває `user`, але його бачить і
38435
38685
  * гість, тож самореєстрація до нього нічого не додає.
38686
+ *
38687
+ * Прийняте в `selfSignUpAccepted` (спека публічної частини §5.5) попередження не називає; без
38688
+ * поля воно звучить завжди, з полем — лише коли відкрито щось неприйняте, і
38689
+ * називає тільки його. Ціль прийняття — id з індексу посилань: `rename`
38690
+ * переписує запис, а `delete` прийнятої цілі блокується. Відома межа —
38691
+ * об'єкт-однойменник, створений після ручного видалення теки (повз
38692
+ * `delete`): він резолвиться з того самого запису (спека публічної частини
38693
+ * §5.5). Об'єкт приймається з формою відкритості, грант — з обсягом.
38694
+ *
38695
+ * Запис прийняття, що не покриває жодної наявної відкритості (знятий грант,
38696
+ * об'єкт без `publicRead`), — попередження `project.self-sign-up-stale`:
38697
+ * інакше він мовчки прийняв би майбутню відкритість, якої автор не бачив.
38698
+ * Його звітує й проєкт без `selfSignUp`: прийняття переживає вимкнення.
38436
38699
  */
38437
- function selfSignUpWarnings(contracts, objects, project) {
38438
- if (project.selfSignUp !== true) return [];
38700
+ function selfSignUpWarnings(contracts, objects, project, references) {
38439
38701
  const names = new Map(objects.map(({ id, name }) => [id, name]));
38440
38702
  const nameOf = (objectId) => names.get(objectId) ?? objectId;
38441
- const exposed = [...new Set(contracts.access.filter((a) => publicReadRoleOf(a.publicRead) === "authenticated").map((a) => nameOf(a.objectId)))].sort(compareStrings);
38703
+ const actionNames = new Map(objects.flatMap((o) => customActionsOf(o).map((a) => [a.id, a.name])));
38704
+ const actionOf = (action) => actionNames.get(action) ?? action;
38705
+ const dimensionNames = new Map((project.accessDimensions ?? []).map((d) => [d.id, d.name]));
38706
+ const extentOf = (extent) => typeof extent === "string" ? extent : dimensionNames.get(extent.dimensionId) ?? extent.dimensionId;
38707
+ const accepted = project.selfSignUpAccepted;
38708
+ const target = new Map(references.filter((r) => r.role === "selfSignUp.accepted").map((r) => [r.from.pointer, r.to.id]));
38709
+ const acceptedObjects = new Set((accepted?.objects ?? []).map((entry, i) => `${target.get(`/selfSignUpAccepted/objects/${i}/object`) ?? ""}\0${entry.published === true ? "published" : "all"}`));
38710
+ const objectAccepted = (objectId, published) => acceptedObjects.has(`${objectId}\0all`) || published && acceptedObjects.has(`${objectId}\0published`);
38711
+ const grantKey = (roleId, objectId, action, extent) => JSON.stringify([
38712
+ roleId,
38713
+ objectId,
38714
+ action,
38715
+ typeof extent === "string" ? extent : extent.dimensionId
38716
+ ]);
38717
+ const acceptedGrants = new Set((accepted?.grants ?? []).flatMap((grant, i) => {
38718
+ const at = `/selfSignUpAccepted/grants/${i}`;
38719
+ const extent = typeof grant.extent === "string" ? grant.extent : { dimensionId: target.get(`${at}/extent/dimension`) ?? "" };
38720
+ return grant.actions.map((action, j) => grantKey(target.get(`${at}/role`) ?? "", target.get(`${at}/object`) ?? "", target.get(`${at}/actions/${j}`) ?? action, extent));
38721
+ }));
38722
+ const open = contracts.access.filter((a) => publicReadRoleOf(a.publicRead) === "authenticated");
38442
38723
  const projection = expandedProjection(contracts);
38443
- const roles = contracts.roles.filter((role) => role.assignedOn.level === "everyUser").map((role) => {
38444
- const grants = projection.filter((row) => row.roleId === role.roleId).map((row) => `${nameOf(row.objectId)}.${row.action}`).sort(compareStrings);
38445
- return `${role.name}: ${grants.join(", ")}`;
38446
- }).sort(compareStrings);
38724
+ const everyUser = contracts.roles.filter((role) => role.assignedOn.level === "everyUser");
38725
+ const exposedGrants = new Set(projection.filter((row) => everyUser.some((role) => role.roleId === row.roleId)).map((row) => grantKey(row.roleId, row.objectId, row.action, row.extent)));
38726
+ const stale = staleEntries();
38727
+ if (project.selfSignUp !== true) return stale;
38728
+ const exposed = [...new Set(open.filter((a) => !objectAccepted(a.objectId, a.published !== void 0)).map((a) => `${nameOf(a.objectId)}${a.published === void 0 ? "" : " (published)"}`))].sort(compareStrings);
38729
+ const roles = everyUser.map((role) => ({
38730
+ role,
38731
+ grants: projection.filter((row) => row.roleId === role.roleId).filter((row) => !acceptedGrants.has(grantKey(role.roleId, row.objectId, row.action, row.extent))).map((row) => `${nameOf(row.objectId)}.${actionOf(row.action)} (${extentOf(row.extent)})`).sort(compareStrings)
38732
+ })).filter(({ grants }) => accepted === void 0 || grants.length > 0).map(({ role, grants }) => `${role.name}: ${grants.join(", ")}`).sort(compareStrings);
38733
+ if (accepted !== void 0 && exposed.length === 0 && roles.length === 0) return stale;
38447
38734
  return [diagnostic("project.self-sign-up", PROJECT_FILE, "/selfSignUp", {
38448
38735
  objects: exposed.join(", "),
38449
38736
  roles: roles.join("; ")
38450
- })];
38737
+ }), ...stale];
38738
+ /**
38739
+ * Записи без жодної відкритості, яку вони покривають. Непрорезолвлений
38740
+ * запис уже має помилку стадії 2, тож тут мовчить.
38741
+ */
38742
+ function staleEntries() {
38743
+ const found = [];
38744
+ accepted?.objects.forEach((entry, i) => {
38745
+ const objectId = target.get(`/selfSignUpAccepted/objects/${i}/object`);
38746
+ if (objectId === void 0) return;
38747
+ const forms = open.filter((a) => a.objectId === objectId);
38748
+ if (entry.published === true ? forms.some((a) => a.published !== void 0) : forms.length > 0) return;
38749
+ found.push(diagnostic("project.self-sign-up-stale", PROJECT_FILE, `/selfSignUpAccepted/objects/${i}`, { entry: `${entry.object.name}${entry.published === true ? " (published)" : ""}` }));
38750
+ });
38751
+ accepted?.grants.forEach((grant, i) => {
38752
+ const at = `/selfSignUpAccepted/grants/${i}`;
38753
+ const roleId = target.get(`${at}/role`);
38754
+ const objectId = target.get(`${at}/object`);
38755
+ if (roleId === void 0 || objectId === void 0) return;
38756
+ if (typeof grant.extent === "object" && !target.has(`${at}/extent/dimension`)) return;
38757
+ const extent = typeof grant.extent === "string" ? grant.extent : { dimensionId: target.get(`${at}/extent/dimension`) };
38758
+ const unused = grant.actions.filter((action, j) => !exposedGrants.has(grantKey(roleId, objectId, target.get(`${at}/actions/${j}`) ?? action, extent)));
38759
+ if (unused.length === 0) return;
38760
+ found.push(diagnostic("project.self-sign-up-stale", PROJECT_FILE, at, { entry: `${grant.role.name}: ${unused.map((a) => `${grant.object.name}.${a}`).join(", ")} (${typeof grant.extent === "string" ? grant.extent : grant.extent.dimension})` }));
38761
+ });
38762
+ return found;
38763
+ }
38451
38764
  }
38452
38765
  // src/compiler/author-units.ts
38453
38766
  /** Одна функція авторства на проєкт: тіло не залежить від таблиці. */
@@ -41466,7 +41779,7 @@ async function runStages(stage1, options = {}) {
41466
41779
  rights,
41467
41780
  roles,
41468
41781
  rightsProjection: projection.rows
41469
- }, stage1.objects, stage1.project)
41782
+ }, stage1.objects, stage1.project, stage2.references)
41470
41783
  ]);
41471
41784
  return {
41472
41785
  ok: !hasErrors(final),
@@ -42458,6 +42771,8 @@ function buildClientCatalog(runtime) {
42458
42771
  provider: runtime.provider,
42459
42772
  ...present("rightsSnapshot", runtime.rightsSnapshot),
42460
42773
  ...present("adoptedFacts", runtime.adoptedFacts),
42774
+ ...present("roles", runtime.roles),
42775
+ ...present("rightsSets", runtime.rightsSets),
42461
42776
  objects: runtime.objects.map(entryOf)
42462
42777
  };
42463
42778
  }
@@ -43585,7 +43900,7 @@ function nodeAt$1(root, pointer) {
43585
43900
  * контейнера, тож нова колекція схеми стає доступною без змін тут.
43586
43901
  */
43587
43902
  async function addElement(files, input, o) {
43588
- const supplied = refuseSuppliedId(files, input.element, "element");
43903
+ const supplied = refuseSuppliedId(files, input.element, "element") ?? refuseSuppliedId(files, input.objects ?? [], "objects");
43589
43904
  if (supplied !== void 0) return supplied;
43590
43905
  const clean = await compileInput(files, { repair: true });
43591
43906
  if (!clean.ok) return clean.result;
@@ -43607,6 +43922,26 @@ async function addElement(files, input, o) {
43607
43922
  if (JSON.parse(files.get(object.file)).scope !== void 0) return scopesRefused("table-scoped", table);
43608
43923
  }
43609
43924
  }
43925
+ const created = /* @__PURE__ */ new Map();
43926
+ if (input.objects !== void 0) {
43927
+ if (input.target.kind !== "Project" || input.collection !== "scopeKinds") return refused(files, [diagnostic("operation.input-invalid", "", "", {
43928
+ objects: "target",
43929
+ at: "/objects"
43930
+ })]);
43931
+ for (const object of input.objects) {
43932
+ const path = `${KIND_REGISTRY[object.kind].dir}/${object.name}/${object.name}.meta.json`;
43933
+ const existing = clean.model.objects.find((o) => o.kind === object.kind && o.name === object.name);
43934
+ if (existing !== void 0 || files.has(path) || created.has(path)) return refused(files, [diagnostic("operation.object-exists", existing?.file ?? path, "", {
43935
+ kind: object.kind,
43936
+ name: object.name
43937
+ })]);
43938
+ created.set(path, {
43939
+ ...object.data,
43940
+ kind: object.kind,
43941
+ name: object.name
43942
+ });
43943
+ }
43944
+ }
43610
43945
  const collections = [...namedCollections(container.schema).keys()];
43611
43946
  if (!collections.includes(input.collection)) return refused(files, [diagnostic("operation.collection-unknown", container.file, container.pointer, {
43612
43947
  collection: input.collection,
@@ -43630,6 +43965,10 @@ async function addElement(files, input, o) {
43630
43965
  changed.set(object.file, JSON.stringify(tableRaw));
43631
43966
  only.add(object.file);
43632
43967
  }
43968
+ for (const [path, raw] of created) {
43969
+ changed.set(path, JSON.stringify(raw));
43970
+ only.add(path);
43971
+ }
43633
43972
  const after = await toPlatformFormsAfter(files, changed);
43634
43973
  return completeAndCompile(files, after.files, o, only, clean.accepted, after.diagnostics);
43635
43974
  }
@@ -43859,7 +44198,12 @@ const addElementInput = z.strictObject({
43859
44198
  scopes: z.record(z.string(), z.strictObject({
43860
44199
  scope: z.string().min(1),
43861
44200
  scopeColumn: elementNameSchema.optional()
43862
- })).optional().meta({ description: "Only for collection scopeKinds of Project: declares the scope of adopted CustomTables in the same change, keyed by table name, e.g. { Orders: { scope: \"org\", scopeColumn: \"org\" } }; a table that already has a scope is refused." })
44201
+ })).optional().meta({ description: "Only for collection scopeKinds of Project: declares the scope of adopted CustomTables in the same change, keyed by table name, e.g. { Orders: { scope: \"org\", scopeColumn: \"org\" } }; a table that already has a scope is refused." }),
44202
+ objects: z.array(z.strictObject({
44203
+ kind: metadataKindSchema.meta({ description: void 0 }),
44204
+ name: objectNameSchema.meta({ description: void 0 }),
44205
+ data: z.record(z.string(), z.unknown()).optional()
44206
+ })).optional().meta({ description: "Only for collection scopeKinds of Project: new objects created in the same change, as { kind, name, data } of create, e.g. the scope root and the membership catalog with scope set to the new kind." })
43863
44207
  });
43864
44208
  const renameInput = z.strictObject({
43865
44209
  target: elementTarget,