simetra 0.3.0-next.7 → 0.3.0-next.9

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.
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- import { ASSIGNED_ONCE, CAST_TYPES, COMMAND_CORE_ERRORS, COMMAND_SETTING, CURRENT_USER_FUNCTION_NAME, DATABASE_PROVIDERS, DEFAULT_MAIN_PRESENTATION, DELETE_EVENTS, FUNCTIONS_FILE_SUFFIX, HEAD_READABLE_SETTINGS, HIERARCHY_ISOLATION_ERROR, KIND_REGISTRY, MAX_PHYSICAL_NAME_BYTES, MEMBERSHIP_SET_FUNCTION, METADATA_KINDS, NO_SCOPE, PINNED_SESSION_SETTINGS, PLATFORM_ACTIONS, PLATFORM_ROLES, PLATFORM_ROLES_NOT_PURPOSES, PLATFORM_SCHEMA, PLATFORM_SETTING_PREFIX, PLATFORM_STATE_TABLES, PROTECTED_SESSION_SETTINGS, PROVIDER_API_ROLES, PROVIDER_EVENT_SOURCES, PROVIDER_EXPRESSION_FUNCTIONS, PROVIDER_FUNCTIONS, PROVIDER_IDENTITY_SOURCES, PROVIDER_LOGIN_ROLES, PROVIDER_OWNER_ROLES, PROVIDER_SCHEMAS, PUBLIC_READ_PURPOSES, RESPONSE_BUDGET_BYTES, RICH_TEXT_PROFILE, RICH_TEXT_WHITESPACE, RIGHTS_CLIENT_SNAPSHOT_FUNCTION_NAME, RIGHTS_COLUMNS, RIGHTS_DELTA_SECTION, RIGHTS_DIMENSION_VALUES_MAX, RIGHTS_MAINTENANCE_SETTING, RIGHTS_REQUIRE_ERROR, SCHEMA_RULES, SESSION_CLAIMS_SETTING, SIGNAL_INVALIDATE_FUNCTION_NAME, SIGNAL_MERGE_MODE, SIGNAL_MODE_SETTING, SIGNAL_NOTIFY_CHANNEL, SIGNAL_OUTBOX, SIGNAL_PAYLOAD_MAX_BYTES, SIGNAL_TOPIC_ALLOWED_FUNCTION_NAME, SQL_DEBT_FILE, SQL_UNIT_CLASSES, STANDARD_ACTIONS, STORAGE_ERRORS, STORAGE_FUNCTIONS, STORAGE_TABLES, STRUCTURAL_PATH_WORDS, TOPIC_UUID_PATTERN, USER_PLATFORM_COLUMNS, UUID_TEXT, ZERO_UUID, acceptInvitationAction, actionRequires, assignPhysicalName, authorColumns, catalogFromSnapshot, chooseConstraintName, clipBytes, closeRequires, defaultMayRepeat, defaultViolatesValueChecks, deletionMarkColumn, diffCatalogModels, effectiveMaxBytes, effectiveSearch, elementNameSchema, expectsKindLabel, filePlatformColumns, formatMetaFile, formatProjectFile, formatSqlDebtFile, formatSqlFunctionsFile, grantEntryForm, isObjectOrigin, isObjectTable, isRecordKeyAt, isScalarDefault, isSqlReservedWord, isTextEncodedType, isUuidColumn, jsonBytes, jsonbBuildObject, keyColumn, kindByDir, lineNumberColumn, logicalElementName, makeObjectName, matchesAttributeCase, metadataKindSchema, monthColumn, namedCollections, objectNameSchema, objectTable, parseExpression, parsePublicRead, parseStandardElementId, pgEnumTypeName, pgTypeOf, postsMovements, predefinedNameColumn, projectSchema, publicationCarriers, publishedColumn, quoteIdent, rowWithoutSearch, searchColumnName, searchPrefixNormalization, serviceDateColumns, singleUuidKeyColumn, singletonColumn, sqlDebtSchema, sqlFunctionDeclarationSchema, sqlFunctionsFileSchema, standardElementId, standardLogicalName, tabularParentColumn, toSnakeCase, truncatedPeriodExpression, userPlatformColumns, versionColumn, walkExpr } from "simetra/model";
2
+ import { ASSIGNED_ONCE, CAST_TYPES, COMMAND_CORE_ERRORS, COMMAND_SETTING, CURRENT_USER_FUNCTION_NAME, DATABASE_PROVIDERS, DEFAULT_MAIN_PRESENTATION, DELETE_EVENTS, FUNCTIONS_FILE_SUFFIX, HEAD_READABLE_SETTINGS, HIERARCHY_ISOLATION_ERROR, INVITATION_ACCEPT_FUNCTION_NAME, KIND_REGISTRY, MAX_PHYSICAL_NAME_BYTES, MEMBERSHIP_SET_FUNCTION, METADATA_KINDS, NO_SCOPE, PINNED_SESSION_SETTINGS, PLATFORM_ACTIONS, PLATFORM_ROLES, PLATFORM_ROLES_NOT_PURPOSES, PLATFORM_SCHEMA, PLATFORM_SETTING_PREFIX, PLATFORM_STATE_TABLES, PROTECTED_SESSION_SETTINGS, PROVIDER_API_ROLES, PROVIDER_EVENT_SOURCES, PROVIDER_EXPRESSION_FUNCTIONS, PROVIDER_FUNCTIONS, PROVIDER_IDENTITY_SOURCES, PROVIDER_LOGIN_ROLES, PROVIDER_OWNER_ROLES, PROVIDER_SCHEMAS, PUBLIC_READ_PURPOSES, RESPONSE_BUDGET_BYTES, RICH_TEXT_PROFILE, RICH_TEXT_WHITESPACE, RIGHTS_CLIENT_SNAPSHOT_FUNCTION_NAME, RIGHTS_COLUMNS, RIGHTS_DELTA_SECTION, RIGHTS_DIMENSION_VALUES_MAX, RIGHTS_MAINTENANCE_SETTING, RIGHTS_MY_SCOPES_FUNCTION_NAME, RIGHTS_REQUIRE_ERROR, SCHEMA_RULES, SESSION_CLAIMS_SETTING, SIGNAL_INVALIDATE_FUNCTION_NAME, SIGNAL_MERGE_MODE, SIGNAL_MODE_SETTING, SIGNAL_NOTIFY_CHANNEL, SIGNAL_OUTBOX, SIGNAL_PAYLOAD_MAX_BYTES, SIGNAL_TOPIC_ALLOWED_FUNCTION_NAME, SQL_DEBT_FILE, SQL_UNIT_CLASSES, STANDARD_ACTIONS, STORAGE_ERRORS, STORAGE_FUNCTIONS, STORAGE_TABLES, STRUCTURAL_PATH_WORDS, TOPIC_UUID_PATTERN, USER_PLATFORM_COLUMNS, UUID_TEXT, ZERO_UUID, acceptInvitationAction, actionRequires, assignPhysicalName, authorColumns, catalogFromSnapshot, chooseConstraintName, clipBytes, closeRequires, defaultMayRepeat, defaultViolatesValueChecks, deletionMarkColumn, diffCatalogModels, effectiveMaxBytes, effectiveSearch, elementNameSchema, expectsKindLabel, filePlatformColumns, formatMetaFile, formatProjectFile, formatSqlDebtFile, formatSqlFunctionsFile, grantEntryForm, isObjectOrigin, isObjectTable, isRecordKeyAt, isScalarDefault, isSqlReservedWord, isTextEncodedType, isUuidColumn, jsonBytes, jsonbBuildObject, keyColumn, kindByDir, lineNumberColumn, logicalElementName, makeObjectName, matchesAttributeCase, metadataKindSchema, monthColumn, namedCollections, objectNameSchema, objectTable, parseExpression, parsePublicRead, parseStandardElementId, pgEnumTypeName, pgTypeOf, postsMovements, predefinedNameColumn, projectSchema, publicationCarriers, publishedColumn, quoteIdent, rowWithoutSearch, searchColumnName, searchPrefixNormalization, serviceDateColumns, singleUuidKeyColumn, singletonColumn, sqlDebtSchema, sqlFunctionDeclarationSchema, sqlFunctionsFileSchema, standardElementId, standardLogicalName, tabularParentColumn, toSnakeCase, truncatedPeriodExpression, userPlatformColumns, versionColumn, walkExpr } from "simetra/model";
3
3
  import { parseTree } from "jsonc-parser";
4
4
  import { loadModule, parseSync } from "libpg-query";
5
5
  import { loadModule as loadModule$1, parsePlPgSQLSync, parseSync as parseSync$1, scanSync } from "@libpg-query/parser";
@@ -5980,8 +5980,8 @@ function readSqlUnits(sources, parse, known) {
5980
5980
  }
5981
5981
  const declared = files.flatMap(({ source, statements }) => statements.flatMap(({ stmt }) => {
5982
5982
  if ("CreateDomainStmt" in stmt) return [qualify$1(strings$4(stmt.CreateDomainStmt.domainname), source.schema)];
5983
- if ("ViewStmt" in stmt) return [relation$5(stmt.ViewStmt.view, source.schema)];
5984
- if ("CreateTableAsStmt" in stmt && stmt.CreateTableAsStmt.objtype === "OBJECT_MATVIEW") return [relation$5(stmt.CreateTableAsStmt.into?.rel, source.schema)];
5983
+ if ("ViewStmt" in stmt) return [relation$6(stmt.ViewStmt.view, source.schema)];
5984
+ if ("CreateTableAsStmt" in stmt && stmt.CreateTableAsStmt.objtype === "OBJECT_MATVIEW") return [relation$6(stmt.CreateTableAsStmt.into?.rel, source.schema)];
5985
5985
  return [];
5986
5986
  }));
5987
5987
  const types = modelTypes([...known, ...declared]);
@@ -6302,7 +6302,7 @@ function classify(stmt, scope) {
6302
6302
  }
6303
6303
  if ("CreateTrigStmt" in stmt) {
6304
6304
  const node = stmt.CreateTrigStmt;
6305
- const table = relation$5(node.relation, schema);
6305
+ const table = relation$6(node.relation, schema);
6306
6306
  const name = node.trigname ?? "";
6307
6307
  return unit("trigger", {
6308
6308
  schema: table.schema,
@@ -6311,7 +6311,7 @@ function classify(stmt, scope) {
6311
6311
  }
6312
6312
  if ("CreatePolicyStmt" in stmt) {
6313
6313
  const node = stmt.CreatePolicyStmt;
6314
- const table = relation$5(node.table, schema);
6314
+ const table = relation$6(node.table, schema);
6315
6315
  const name = node.policy_name ?? "";
6316
6316
  return unit("policy", {
6317
6317
  schema: table.schema,
@@ -6319,11 +6319,11 @@ function classify(stmt, scope) {
6319
6319
  }, qualifiedName(table.schema, table.name, name));
6320
6320
  }
6321
6321
  if ("ViewStmt" in stmt) {
6322
- const view = relation$5(stmt.ViewStmt.view, schema);
6322
+ const view = relation$6(stmt.ViewStmt.view, schema);
6323
6323
  return unit("view", view, qualifiedName(view.schema, view.name));
6324
6324
  }
6325
6325
  if ("CreateTableAsStmt" in stmt && stmt.CreateTableAsStmt.objtype === "OBJECT_MATVIEW") {
6326
- const view = relation$5(stmt.CreateTableAsStmt.into?.rel, schema);
6326
+ const view = relation$6(stmt.CreateTableAsStmt.into?.rel, schema);
6327
6327
  return unit("materializedView", view, qualifiedName(view.schema, view.name));
6328
6328
  }
6329
6329
  if ("GrantStmt" in stmt) {
@@ -6378,7 +6378,7 @@ function classify(stmt, scope) {
6378
6378
  }, quoteIdent(name));
6379
6379
  }
6380
6380
  if ("CreateSeqStmt" in stmt) {
6381
- const seq = relation$5(stmt.CreateSeqStmt.sequence, schema);
6381
+ const seq = relation$6(stmt.CreateSeqStmt.sequence, schema);
6382
6382
  return unit("sequence", seq, qualifiedName(seq.schema, seq.name));
6383
6383
  }
6384
6384
  if ("AlterSeqStmt" in stmt) {
@@ -6388,7 +6388,7 @@ function classify(stmt, scope) {
6388
6388
  notAllowed: statement,
6389
6389
  detail: "only OWNED BY is allowed"
6390
6390
  };
6391
- const seq = relation$5(node.sequence, schema);
6391
+ const seq = relation$6(node.sequence, schema);
6392
6392
  return unit("sequenceOwnedBy", seq, qualifiedName(seq.schema, seq.name));
6393
6393
  }
6394
6394
  if ("CreateDomainStmt" in stmt) {
@@ -6407,7 +6407,7 @@ function classify(stmt, scope) {
6407
6407
  if (!("PublicationObjSpec" in o)) return "";
6408
6408
  const spec = o.PublicationObjSpec;
6409
6409
  if (spec.pubtable !== void 0) {
6410
- const table = relation$5(spec.pubtable.relation, schema);
6410
+ const table = relation$6(spec.pubtable.relation, schema);
6411
6411
  return qualifiedName(table.schema, table.name);
6412
6412
  }
6413
6413
  return `schema ${quoteIdent(spec.name ?? schema)}`;
@@ -6425,7 +6425,7 @@ function classify(stmt, scope) {
6425
6425
  notAllowed: statement,
6426
6426
  detail: "rowRuleName"
6427
6427
  };
6428
- const table = relation$5(node.relation, schema);
6428
+ const table = relation$6(node.relation, schema);
6429
6429
  return { rowRule: {
6430
6430
  schema: table.schema,
6431
6431
  table: table.name,
@@ -6439,7 +6439,7 @@ function classify(stmt, scope) {
6439
6439
  detail: "only REPLICA IDENTITY is allowed",
6440
6440
  ...subtypes.some((s) => ROW_SECURITY.has(s)) ? { feature: "rowLevelSecurity" } : {}
6441
6441
  };
6442
- const table = relation$5(node.relation, schema);
6442
+ const table = relation$6(node.relation, schema);
6443
6443
  return unit("replicaIdentity", table, qualifiedName(table.schema, table.name));
6444
6444
  }
6445
6445
  if ("AlterFunctionStmt" in stmt) {
@@ -6485,7 +6485,7 @@ function qualify$1(names, schema) {
6485
6485
  name
6486
6486
  };
6487
6487
  }
6488
- function relation$5(rv, schema) {
6488
+ function relation$6(rv, schema) {
6489
6489
  return {
6490
6490
  schema: rv?.schemaname ?? schema,
6491
6491
  name: rv?.relname ?? ""
@@ -6546,7 +6546,7 @@ function targetParts(node) {
6546
6546
  function targetName$1(node, objtype, scope) {
6547
6547
  const { schema } = scope;
6548
6548
  if ("RangeVar" in node) {
6549
- const { schema: s, name } = relation$5(node.RangeVar, schema);
6549
+ const { schema: s, name } = relation$6(node.RangeVar, schema);
6550
6550
  return qualifiedName(s, name);
6551
6551
  }
6552
6552
  if ("ObjectWithArgs" in node) return functionObject(node.ObjectWithArgs, scope);
@@ -10275,6 +10275,21 @@ function bindingValue(hops, index) {
10275
10275
  return index === hops.length - 1 ? direct.column : carrierCopyName(hops[index].column, direct.column);
10276
10276
  }
10277
10277
  /**
10278
+ * Ланцюжкові нащадки кожного виду за id (Р-К1-8): вид лежить на ланцюжку
10279
+ * нащадка вище за його перший крок. Транзитивне замикання вже записане в
10280
+ * кроках ланцюжків стадії 3 — другого обходу графа немає. Контейнер нащадків
10281
+ * не має: ланцюжок кінчається на ньому, тож він лише ціль кроку. Нащадки — у
10282
+ * порядку id: генератор впорядковує їх за міткою сам.
10283
+ */
10284
+ function bindingDescendants(bindings) {
10285
+ const descendants = /* @__PURE__ */ new Map();
10286
+ for (const [id, binding] of [...bindings].sort(([a], [b]) => compareStrings(a, b))) {
10287
+ if (!binding.ok) continue;
10288
+ for (const hop of binding.hops.slice(1)) descendants.set(hop.object, [...descendants.get(hop.object) ?? [], id]);
10289
+ }
10290
+ return descendants;
10291
+ }
10292
+ /**
10278
10293
  * Прив'язка об'єкта в контракті: контейнер — кінцевий, носій — колонка
10279
10294
  * реквізиту, а в ланцюжку — копія зі значенням прив'язки цілі (`via`); з
10280
10295
  * фізичного знімка — лише ім'я основної таблиці цілі. `undefined` — ланцюжок
@@ -12822,22 +12837,32 @@ const DERIVE_LABEL = "simetra_carriers";
12822
12837
  const PROPAGATE_LABEL = "simetra_carriers_out";
12823
12838
  const PROPAGATE_INSERT_LABEL = "simetra_carriers_out_insert";
12824
12839
  /**
12840
+ * Мітка тригера переприв'язування (Р-К1-8): тієї самої довжини, що
12841
+ * `PROPAGATE_LABEL`, тож алгоритм імен обрізає таблицю до того самого
12842
+ * префікса на будь-якій довжині, а `bnd` < `out` — і тригер одного моменту
12843
+ * спрацьовує раніше за поширення (Postgres запускає їх за іменем).
12844
+ */
12845
+ const REBIND_LABEL = "simetra_carriers_bnd";
12846
+ /**
12825
12847
  * Імена тригерів копій носіїв на таблиці: `derive` — на таблиці з копіями,
12826
- * обидва тригери поширення — на таблиці-джерелі. `derive` — рядковий
12827
- * `BEFORE`, тож іде спільним префіксом групи: інакше на довгій назві він
12828
- * спрацював би не між авторством і механікою. Поширення — `AFTER`, на `NEW`
12829
- * не впливає, і лишається на алгоритмі Postgres, що тримає мітку цілою.
12848
+ * обидва тригери поширення й переприв'язування — на таблиці-джерелі.
12849
+ * `derive` — рядковий `BEFORE`, тож іде спільним префіксом групи: інакше на
12850
+ * довгій назві він спрацював би не між авторством і механікою. Поширення й
12851
+ * переприв'язування — `AFTER`, на `NEW` не впливають, і лишаються на
12852
+ * алгоритмі Postgres, що тримає мітку цілою.
12830
12853
  */
12831
12854
  function carrierTriggerNames(table) {
12832
12855
  return {
12833
12856
  derive: platformBeforeTriggerName(table.name, DERIVE_LABEL),
12834
12857
  propagate: makeObjectName(table.name, void 0, PROPAGATE_LABEL),
12835
- propagateInsert: makeObjectName(table.name, void 0, PROPAGATE_INSERT_LABEL)
12858
+ propagateInsert: makeObjectName(table.name, void 0, PROPAGATE_INSERT_LABEL),
12859
+ rebind: makeObjectName(table.name, void 0, REBIND_LABEL)
12836
12860
  };
12837
12861
  }
12838
12862
  /**
12839
12863
  * Функції носіїв у схемі таблиці: виведення — на таблиці з копіями,
12840
- * поширення — одна на джерело для обох його тригерів.
12864
+ * поширення — одна на джерело для обох його тригерів, переприв'язування —
12865
+ * на джерелі ланцюжка.
12841
12866
  */
12842
12867
  function carrierFunctionNames(table) {
12843
12868
  const names = carrierTriggerNames(table);
@@ -12849,6 +12874,10 @@ function carrierFunctionNames(table) {
12849
12874
  propagate: {
12850
12875
  schema: table.schema,
12851
12876
  name: names.propagate
12877
+ },
12878
+ rebind: {
12879
+ schema: table.schema,
12880
+ name: names.rebind
12852
12881
  }
12853
12882
  };
12854
12883
  }
@@ -12903,7 +12932,10 @@ function carrierLinks(physical) {
12903
12932
  }
12904
12933
  /**
12905
12934
  * Функції носіїв знімка — спільні для генератора й перевірки колізій імен
12906
- * функцій стадії 4 (`derivedFunctions`).
12935
+ * функцій стадії 4 (`derivedFunctions`). Переприв'язування — з запасом, на
12936
+ * кожному джерелі: чи має джерело ланцюжкових нащадків, вирішують контракти,
12937
+ * яких перевірка колізій не має, а джерело ланцюжка завжди є джерелом копії.
12938
+ * Як і функція ефектів, зайве ім'я лише резервується.
12907
12939
  */
12908
12940
  function carrierFunctions(physical) {
12909
12941
  const links = carrierLinks(physical);
@@ -12917,14 +12949,18 @@ function carrierFunctions(physical) {
12917
12949
  table,
12918
12950
  fn: carrierFunctionNames(table).derive,
12919
12951
  role: "derive"
12920
- })), ...[...sources.values()].map((table) => ({
12952
+ })), ...[...sources.values()].flatMap((table) => [{
12921
12953
  table,
12922
12954
  fn: carrierFunctionNames(table).propagate,
12923
12955
  role: "propagate"
12924
- }))];
12956
+ }, {
12957
+ table,
12958
+ fn: carrierFunctionNames(table).rebind,
12959
+ role: "rebind"
12960
+ }])];
12925
12961
  }
12926
- const q$11 = quoteIdent;
12927
- const relation$4 = (t) => `${q$11(t.schema)}.${q$11(t.name)}`;
12962
+ const q$12 = quoteIdent;
12963
+ const relation$5 = (t) => `${q$12(t.schema)}.${q$12(t.name)}`;
12928
12964
  /** Функція джерел копій від авторства (спека П4 §6.7). */
12929
12965
  const AUTHOR_CARRIER_SOURCES_FUNCTION = {
12930
12966
  schema: PLATFORM_SCHEMA,
@@ -12983,14 +13019,14 @@ function authorSourcesUnits(physical, attributeCase, provider, module, parse) {
12983
13019
  const sources = authorCarrierSources(physical, attributeCase);
12984
13020
  if (sources === void 0) return [];
12985
13021
  const users = authorSource(authorCarrierLinks(physical, attributeCase));
12986
- const fn = relation$4(sources.fn);
13022
+ const fn = relation$5(sources.fn);
12987
13023
  const body = [
12988
- `SELECT ${sources.columns.map((c) => `s.${q$11(c.name)}`).join(", ")}`,
12989
- `FROM ${relation$4(users)} s`,
12990
- `WHERE s.${q$11(users.key)} = ${CURRENT_USER$1}`
13024
+ `SELECT ${sources.columns.map((c) => `s.${q$12(c.name)}`).join(", ")}`,
13025
+ `FROM ${relation$5(users)} s`,
13026
+ `WHERE s.${q$12(users.key)} = ${CURRENT_USER$1}`
12991
13027
  ].join("\n");
12992
13028
  const tag = dollarTag$1(body);
12993
- const create = `CREATE OR REPLACE FUNCTION ${fn}()\nRETURNS TABLE (${sources.columns.map((c) => `${q$11(c.name)} ${c.type}`).join(", ")})\nLANGUAGE sql STABLE SECURITY DEFINER\nSET search_path = ''\nSET row_security = off\nAS ${tag}\n${body}\n${tag};`;
13029
+ const create = `CREATE OR REPLACE FUNCTION ${fn}()\nRETURNS TABLE (${sources.columns.map((c) => `${q$12(c.name)} ${c.type}`).join(", ")})\nLANGUAGE sql STABLE SECURITY DEFINER\nSET search_path = ''\nSET row_security = off\nAS ${tag}\n${body}\n${tag};`;
12994
13030
  const requires = [{
12995
13031
  type: "table",
12996
13032
  schema: users.schema,
@@ -13045,7 +13081,7 @@ function buildCarrierUnits(physical, attributeCase, provider, module, parse) {
13045
13081
  const table = group[0].table;
13046
13082
  const fn = carrierFunctionNames(table).derive;
13047
13083
  const sources = uniqueTables(group.map((l) => l.source));
13048
- units.push(unit(table, deriveFunction(fn, group), sources.map(tableNode)), ...executeGrants(`${relation$4(fn)}()`, [], provider).map((sql) => unit(table, sql)), unit(table, `CREATE TRIGGER ${q$11(carrierTriggerNames(table).derive)} BEFORE INSERT OR UPDATE ON ${relation$4(table)} FOR EACH ROW EXECUTE FUNCTION ${relation$4(fn)}();`));
13084
+ units.push(unit(table, deriveFunction(fn, group), sources.map(tableNode)), ...executeGrants(`${relation$5(fn)}()`, [], provider).map((sql) => unit(table, sql)), unit(table, `CREATE TRIGGER ${q$12(carrierTriggerNames(table).derive)} BEFORE INSERT OR UPDATE ON ${relation$5(table)} FOR EACH ROW EXECUTE FUNCTION ${relation$5(fn)}();`));
13049
13085
  }
13050
13086
  for (const group of byTable((l) => l.source)) {
13051
13087
  const source = group[0].source;
@@ -13053,9 +13089,9 @@ function buildCarrierUnits(physical, attributeCase, provider, module, parse) {
13053
13089
  const names = carrierTriggerNames(source);
13054
13090
  const dependents = uniqueTables(group.map((l) => l.table));
13055
13091
  const read = new Set(group.flatMap((l) => l.copies.map((c) => c.column)));
13056
- const changed = source.columns.filter((c) => read.has(c.name)).map((c) => `(OLD.${q$11(c.name)} IS DISTINCT FROM NEW.${q$11(c.name)})`).join(" OR ");
13057
- const execute = `EXECUTE FUNCTION ${relation$4(fn)}();`;
13058
- units.push(unit(source, propagateFunction(fn, group), dependents.map(tableNode)), ...executeGrants(`${relation$4(fn)}()`, [], provider).map((sql) => unit(source, sql)), unit(source, `CREATE TRIGGER ${q$11(names.propagate)} AFTER UPDATE ON ${relation$4(source)} FOR EACH ROW WHEN (${changed}) ${execute}`), unit(source, `CREATE TRIGGER ${q$11(names.propagateInsert)} AFTER INSERT ON ${relation$4(source)} FOR EACH ROW ${execute}`));
13092
+ const changed = source.columns.filter((c) => read.has(c.name)).map((c) => `(OLD.${q$12(c.name)} IS DISTINCT FROM NEW.${q$12(c.name)})`).join(" OR ");
13093
+ const execute = `EXECUTE FUNCTION ${relation$5(fn)}();`;
13094
+ units.push(unit(source, propagateFunction(fn, group), dependents.map(tableNode)), ...executeGrants(`${relation$5(fn)}()`, [], provider).map((sql) => unit(source, sql)), unit(source, `CREATE TRIGGER ${q$12(names.propagate)} AFTER UPDATE ON ${relation$5(source)} FOR EACH ROW WHEN (${changed}) ${execute}`), unit(source, `CREATE TRIGGER ${q$12(names.propagateInsert)} AFTER INSERT ON ${relation$5(source)} FOR EACH ROW ${execute}`));
13059
13095
  }
13060
13096
  return units.sort((a, b) => compareStrings(a.identity, b.identity));
13061
13097
  }
@@ -13064,7 +13100,7 @@ function uniqueTables(tables) {
13064
13100
  }
13065
13101
  /** `s.<джерело> = <row>.<локальна> AND …` за колонками FK зв'язку. */
13066
13102
  function sourceRow(link, row) {
13067
- return link.pairs.map((p) => `s.${q$11(p.source)} = ${row}.${q$11(p.local)}`).join(" AND ");
13103
+ return link.pairs.map((p) => `s.${q$12(p.source)} = ${row}.${q$12(p.local)}`).join(" AND ");
13068
13104
  }
13069
13105
  /**
13070
13106
  * Читання всіх копій зв'язку з рядка джерела в `row` — один будівник для
@@ -13075,9 +13111,9 @@ function sourceRow(link, row) {
13075
13111
  */
13076
13112
  function carrierCopyRead(link, row, lock) {
13077
13113
  return [
13078
- `SELECT ${link.copies.map((c) => `s.${q$11(c.column)}`).join(", ")}`,
13079
- ` INTO ${link.copies.map((c) => `${row}.${q$11(c.name)}`).join(", ")}`,
13080
- ` FROM ${relation$4(link.source)} s WHERE ${sourceRow(link, row)}${lock ? "" : ";"}`,
13114
+ `SELECT ${link.copies.map((c) => `s.${q$12(c.column)}`).join(", ")}`,
13115
+ ` INTO ${link.copies.map((c) => `${row}.${q$12(c.name)}`).join(", ")}`,
13116
+ ` FROM ${relation$5(link.source)} s WHERE ${sourceRow(link, row)}${lock ? "" : ";"}`,
13081
13117
  ...lock ? [" FOR SHARE;"] : []
13082
13118
  ].join("\n");
13083
13119
  }
@@ -13092,10 +13128,10 @@ function carrierCopyRead(link, row, lock) {
13092
13128
  function deriveFunction(fn, links) {
13093
13129
  const body = ["BEGIN"];
13094
13130
  for (const link of links) {
13095
- const from = `FROM ${relation$4(link.source)} s WHERE ${sourceRow(link, "NEW")}`;
13096
- const linkChanged = link.pairs.map((p) => `NEW.${q$11(p.local)} IS DISTINCT FROM OLD.${q$11(p.local)}`).join(" OR ");
13131
+ const from = `FROM ${relation$5(link.source)} s WHERE ${sourceRow(link, "NEW")}`;
13132
+ const linkChanged = link.pairs.map((p) => `NEW.${q$12(p.local)} IS DISTINCT FROM OLD.${q$12(p.local)}`).join(" OR ");
13097
13133
  body.push(` IF TG_OP = 'INSERT' OR ${linkChanged} THEN`, ` ${carrierCopyRead(link, "NEW", true)}`, " ELSE");
13098
- for (const copy of link.copies) body.push(` IF NEW.${q$11(copy.name)} IS DISTINCT FROM OLD.${q$11(copy.name)} THEN`, ` SELECT s.${q$11(copy.column)} INTO NEW.${q$11(copy.name)} ${from};`, " END IF;");
13134
+ for (const copy of link.copies) body.push(` IF NEW.${q$12(copy.name)} IS DISTINCT FROM OLD.${q$12(copy.name)} THEN`, ` SELECT s.${q$12(copy.column)} INTO NEW.${q$12(copy.name)} ${from};`, " END IF;");
13099
13135
  body.push(" END IF;");
13100
13136
  }
13101
13137
  body.push(" RETURN NEW;", "END");
@@ -13111,10 +13147,10 @@ function propagateFunction(fn, links) {
13111
13147
  const ordered = [...links].sort((a, b) => compareStrings(tableKey$1(a.table), tableKey$1(b.table)) || compareStrings(a.through, b.through));
13112
13148
  const body = ["BEGIN"];
13113
13149
  for (const link of ordered) {
13114
- const set = link.copies.map((c) => `${q$11(c.name)} = NEW.${q$11(c.column)}`).join(", ");
13115
- const row = link.pairs.map((p) => `d.${q$11(p.local)} = NEW.${q$11(p.source)}`).join(" AND ");
13116
- const differs = link.copies.map((c) => `d.${q$11(c.name)} IS DISTINCT FROM NEW.${q$11(c.column)}`).join(" OR ");
13117
- body.push(` UPDATE ${relation$4(link.table)} d SET ${set}`, ` WHERE ${row} AND (${differs});`);
13150
+ const set = link.copies.map((c) => `${q$12(c.name)} = NEW.${q$12(c.column)}`).join(", ");
13151
+ const row = link.pairs.map((p) => `d.${q$12(p.local)} = NEW.${q$12(p.source)}`).join(" AND ");
13152
+ const differs = link.copies.map((c) => `d.${q$12(c.name)} IS DISTINCT FROM NEW.${q$12(c.column)}`).join(" OR ");
13153
+ body.push(` UPDATE ${relation$5(link.table)} d SET ${set}`, ` WHERE ${row} AND (${differs});`);
13118
13154
  }
13119
13155
  body.push(" RETURN NULL;", "END");
13120
13156
  return definerTrigger(fn, body.join("\n"));
@@ -13178,8 +13214,8 @@ function carrierBackfillStatements(physical, pending) {
13178
13214
  };
13179
13215
  for (const b of backfills) visit(b);
13180
13216
  return ordered.map(({ link, copies }) => {
13181
- const from = `FROM ${relation$4(link.source)} AS s WHERE ` + link.pairs.map((p) => `s.${q$11(p.source)} OPERATOR(pg_catalog.=) d.${q$11(p.local)}`).join(" AND ");
13182
- const differs = copies.map((c) => `d.${q$11(c.name)} IS DISTINCT FROM (SELECT s.${q$11(c.column)} ${from})`).join(" OR ");
13217
+ const from = `FROM ${relation$5(link.source)} AS s WHERE ` + link.pairs.map((p) => `s.${q$12(p.source)} OPERATOR(pg_catalog.=) d.${q$12(p.local)}`).join(" AND ");
13218
+ const differs = copies.map((c) => `d.${q$12(c.name)} IS DISTINCT FROM (SELECT s.${q$12(c.column)} ${from})`).join(" OR ");
13183
13219
  return {
13184
13220
  table: {
13185
13221
  schema: link.table.schema,
@@ -13190,7 +13226,7 @@ function carrierBackfillStatements(physical, pending) {
13190
13226
  name: link.source.name
13191
13227
  },
13192
13228
  columns: copies.map((c) => c.name),
13193
- sql: `UPDATE ${relation$4(link.table)} AS d SET (${copies.map((c) => q$11(c.name)).join(", ")}) = (SELECT ${copies.map((c) => `s.${q$11(c.column)}`).join(", ")} ${from}) WHERE ${differs};`
13229
+ sql: `UPDATE ${relation$5(link.table)} AS d SET (${copies.map((c) => q$12(c.name)).join(", ")}) = (SELECT ${copies.map((c) => `s.${q$12(c.column)}`).join(", ")} ${from}) WHERE ${differs};`
13194
13230
  };
13195
13231
  });
13196
13232
  }
@@ -23246,7 +23282,7 @@ const RIGHTS_FUNCTIONS = {
23246
23282
  domain: platform$2("rights_domain"),
23247
23283
  roles: platform$2("rights_roles"),
23248
23284
  sourceKeys: platform$2("rights_source_keys"),
23249
- myScopes: platform$2("rights_my_scopes"),
23285
+ myScopes: platform$2(RIGHTS_MY_SCOPES_FUNCTION_NAME),
23250
23286
  myScopesLive: platform$2("rights_my_scopes_live"),
23251
23287
  mine: platform$2("rights_mine"),
23252
23288
  minePair: platform$2("rights_mine"),
@@ -31510,8 +31546,8 @@ function hierarchyNames(table) {
31510
31546
  }
31511
31547
  };
31512
31548
  }
31513
- const q$10 = quoteIdent;
31514
- const relation$3 = (t) => `${q$10(t.schema)}.${q$10(t.name)}`;
31549
+ const q$11 = quoteIdent;
31550
+ const relation$4 = (t) => `${q$11(t.schema)}.${q$11(t.name)}`;
31515
31551
  /**
31516
31552
  * Виклик advisory-замка ієрархії таблиці — одне джерело ключа для тригера й
31517
31553
  * ядра команд (спека П4 §6.6): інший вираз ключа в ядрі не серіалізував би його з
@@ -31519,7 +31555,7 @@ const relation$3 = (t) => `${q$10(t.schema)}.${q$10(t.name)}`;
31519
31555
  * стабільний.
31520
31556
  */
31521
31557
  function hierarchyLockSql(table) {
31522
- return `pg_advisory_xact_lock(${HIERARCHY_LOCK_SPACE}, ${sqlLiteral(relation$3(table))}::regclass::oid::int)`;
31558
+ return `pg_advisory_xact_lock(${HIERARCHY_LOCK_SPACE}, ${sqlLiteral(relation$4(table))}::regclass::oid::int)`;
31523
31559
  }
31524
31560
  /**
31525
31561
  * Ієрархічні основні таблиці знімка: колонка батька — стандартна колонка
@@ -31576,8 +31612,8 @@ function buildHierarchyUnits(physical, objects, attributeCase, provider, module,
31576
31612
  name: table.name
31577
31613
  }] } : {}
31578
31614
  });
31579
- const execute = `EXECUTE FUNCTION ${relation$3(names.fn)}();`;
31580
- units.push(unit(definerTrigger(names.fn, hierarchyBody(entry), { rowSecurity: "off" }), true), ...executeGrants(`${relation$3(names.fn)}()`, [], provider).map((sql) => unit(sql)), unit(`CREATE TRIGGER ${q$10(names.insert)} AFTER INSERT ON ${relation$3(table)} FOR EACH ROW WHEN (NEW.${q$10(parent)} IS NOT NULL) ${execute}`), unit(`CREATE TRIGGER ${q$10(names.update)} AFTER UPDATE ON ${relation$3(table)} FOR EACH ROW WHEN (NEW.${q$10(parent)} IS DISTINCT FROM OLD.${q$10(parent)}) ${execute}`));
31615
+ const execute = `EXECUTE FUNCTION ${relation$4(names.fn)}();`;
31616
+ units.push(unit(definerTrigger(names.fn, hierarchyBody(entry), { rowSecurity: "off" }), true), ...executeGrants(`${relation$4(names.fn)}()`, [], provider).map((sql) => unit(sql)), unit(`CREATE TRIGGER ${q$11(names.insert)} AFTER INSERT ON ${relation$4(table)} FOR EACH ROW WHEN (NEW.${q$11(parent)} IS NOT NULL) ${execute}`), unit(`CREATE TRIGGER ${q$11(names.update)} AFTER UPDATE ON ${relation$4(table)} FOR EACH ROW WHEN (NEW.${q$11(parent)} IS DISTINCT FROM OLD.${q$11(parent)}) ${execute}`));
31581
31617
  }
31582
31618
  return units.sort((a, b) => compareStrings(a.identity, b.identity));
31583
31619
  }
@@ -31594,11 +31630,11 @@ function hierarchyBody({ table, parent, key }) {
31594
31630
  " IF current_setting('transaction_isolation') <> 'read committed' THEN",
31595
31631
  ` RAISE EXCEPTION USING ERRCODE = '${HIERARCHY_ISOLATION_ERROR.errcode}', MESSAGE = '${HIERARCHY_ISOLATION_ERROR.message}';`,
31596
31632
  " END IF;",
31597
- ` IF NEW.${q$10(parent)} = NEW.${q$10(key)} THEN`,
31633
+ ` IF NEW.${q$11(parent)} = NEW.${q$11(key)} THEN`,
31598
31634
  ` ${invalid}`,
31599
31635
  " END IF;",
31600
31636
  ` PERFORM ${hierarchyLockSql(table)};`,
31601
- ` IF EXISTS (WITH RECURSIVE up(node) AS (SELECT p.${q$10(parent)} FROM ${relation$3(table)} p WHERE p.${q$10(key)} = NEW.${q$10(parent)} UNION ALL SELECT p.${q$10(parent)} FROM ${relation$3(table)} p JOIN up ON p.${q$10(key)} = up.node) CYCLE node SET looped USING trail SELECT 1 FROM up WHERE up.node = NEW.${q$10(key)}) THEN`,
31637
+ ` IF EXISTS (WITH RECURSIVE up(node) AS (SELECT p.${q$11(parent)} FROM ${relation$4(table)} p WHERE p.${q$11(key)} = NEW.${q$11(parent)} UNION ALL SELECT p.${q$11(parent)} FROM ${relation$4(table)} p JOIN up ON p.${q$11(key)} = up.node) CYCLE node SET looped USING trail SELECT 1 FROM up WHERE up.node = NEW.${q$11(key)}) THEN`,
31602
31638
  ` ${invalid}`,
31603
31639
  " END IF;",
31604
31640
  " RETURN NULL;",
@@ -31670,8 +31706,8 @@ function languageStateTables(physical, objects, attributeCase) {
31670
31706
  }
31671
31707
  return result.sort((a, b) => compareStrings(a.table.schema, b.table.schema) || compareStrings(a.table.name, b.table.name));
31672
31708
  }
31673
- const q$9 = quoteIdent;
31674
- const relation$2 = (t) => `${q$9(t.schema)}.${q$9(t.name)}`;
31709
+ const q$10 = quoteIdent;
31710
+ const relation$3 = (t) => `${q$10(t.schema)}.${q$10(t.name)}`;
31675
31711
  /**
31676
31712
  * Тригер стану мови (Р-B2-4, спека багатомовності §5.2): незмінність основної
31677
31713
  * й коду, переходи стану за матрицею факту ролі, заборона позначки видалення,
@@ -31693,8 +31729,8 @@ function buildLanguageStateUnits(physical, objects, attributeCase, provider, mod
31693
31729
  module,
31694
31730
  generator: "mechanics"
31695
31731
  });
31696
- const execute = `EXECUTE FUNCTION ${relation$2(names.fn)}();`;
31697
- units.push(unit(definerTrigger(names.fn, languageStateBody(entry), { rowSecurity: "off" })), ...executeGrants(`${relation$2(names.fn)}()`, [], provider).map((sql) => unit(sql)), unit(`CREATE TRIGGER ${q$9(names.row)} BEFORE INSERT OR UPDATE OR DELETE ON ${relation$2(table)} FOR EACH ROW ${execute}`), unit(`CREATE TRIGGER ${q$9(names.truncate)} BEFORE TRUNCATE ON ${relation$2(table)} FOR EACH STATEMENT ${execute}`));
31732
+ const execute = `EXECUTE FUNCTION ${relation$3(names.fn)}();`;
31733
+ units.push(unit(definerTrigger(names.fn, languageStateBody(entry), { rowSecurity: "off" })), ...executeGrants(`${relation$3(names.fn)}()`, [], provider).map((sql) => unit(sql)), unit(`CREATE TRIGGER ${q$10(names.row)} BEFORE INSERT OR UPDATE OR DELETE ON ${relation$3(table)} FOR EACH ROW ${execute}`), unit(`CREATE TRIGGER ${q$10(names.truncate)} BEFORE TRUNCATE ON ${relation$3(table)} FOR EACH STATEMENT ${execute}`));
31698
31734
  }
31699
31735
  return units.sort((a, b) => compareStrings(a.identity, b.identity));
31700
31736
  }
@@ -31707,7 +31743,7 @@ function buildLanguageStateUnits(physical, objects, attributeCase, provider, mod
31707
31743
  function languageStateBody({ state, columns }) {
31708
31744
  const E = COMMAND_CORE_ERRORS.invalid;
31709
31745
  const refuse = `RAISE EXCEPTION USING ERRCODE = '${E.errcode}', MESSAGE = '${E.message}', DETAIL = ${sqlLiteral(E.languageState)};`;
31710
- const col = (row, name) => `${row}.${q$9(name)}`;
31746
+ const col = (row, name) => `${row}.${q$10(name)}`;
31711
31747
  const branch = (condition, body, indent = " ") => [
31712
31748
  `${indent}IF ${condition} THEN`,
31713
31749
  ...body.map((line) => `${indent} ${line}`),
@@ -32028,6 +32064,12 @@ function derivedFunctionLabels(object) {
32028
32064
  });
32029
32065
  return labels;
32030
32066
  }
32067
+ /** Опис функції носіїв у діагностиці колізії імен — за її роллю. */
32068
+ const CARRIER_FUNCTION_ROLES = {
32069
+ derive: "carrier copies",
32070
+ propagate: "carrier propagation",
32071
+ rebind: "carrier rebinding check"
32072
+ };
32031
32073
  /**
32032
32074
  * Усі похідні імена функцій, що їх породжує модель, — для перевірки колізій
32033
32075
  * на стадії 4 (спека §7). Обгортки запитів беруться з оголошених
@@ -32048,7 +32090,7 @@ function derivedFunctions(objects, references, physical, wrapperName, scopeKinds
32048
32090
  for (const { table, fn, role } of carrierFunctions(physical)) {
32049
32091
  const object = byId.get(table.origin.objectId);
32050
32092
  if (object === void 0) continue;
32051
- add(object, fn, `${role === "derive" ? "carrier copies" : "carrier propagation"} of ${table.schema}.${table.name}`);
32093
+ add(object, fn, `${CARRIER_FUNCTION_ROLES[role]} of ${table.schema}.${table.name}`);
32052
32094
  }
32053
32095
  for (const { table } of hierarchyTables(physical, objects, attributeCase)) {
32054
32096
  const object = byId.get(table.origin.objectId);
@@ -33174,22 +33216,11 @@ function rightsPredicates(contract, action, table, main, dml) {
33174
33216
  }))
33175
33217
  ];
33176
33218
  const scope = contract.scopeKindId === void 0 ? void 0 : must$9(table.columns.find((c) => c.origin.scopeKindId === contract.scopeKindId)).name;
33177
- const atScope = inners.map(({ extent, carrier, mine }) => {
33178
- const grant = scope === void 0 ? {
33179
- kind: "boolean",
33180
- expression: call$1(F.hasRight, [...head, ...extentArgs(extent)])
33181
- } : {
33182
- kind: "column",
33183
- column: scope,
33184
- set: scopeSet(extent, head),
33185
- grantDependent: true
33186
- };
33187
- return {
33188
- extent,
33189
- ...carrier === void 0 ? {} : { carrier },
33190
- conditions: [...mine, grant]
33191
- };
33192
- });
33219
+ const atScope = inners.map(({ extent, carrier, mine }) => ({
33220
+ extent,
33221
+ ...carrier === void 0 ? {} : { carrier },
33222
+ conditions: [...mine, scopeGrant(extent, head, scope)]
33223
+ }));
33193
33224
  const asContainer = action === "read" && dml === "select" && contract.container === true && table.schema === contract.table.schema && table.name === contract.table.name ? [{
33194
33225
  extent: "as_container",
33195
33226
  conditions: [{
@@ -33212,15 +33243,7 @@ function rightsPredicates(contract, action, table, main, dml) {
33212
33243
  inner: extent
33213
33244
  },
33214
33245
  carrier: carrier ?? bound,
33215
- conditions: [...mine, {
33216
- kind: "column",
33217
- column: bound,
33218
- set: {
33219
- fn: F.container,
33220
- args: [...head, ...extentArgs(extent)]
33221
- },
33222
- grantDependent: true
33223
- }]
33246
+ conditions: [...mine, containerGrant(extent, head, bound)]
33224
33247
  }));
33225
33248
  return [
33226
33249
  ...atScope,
@@ -33360,6 +33383,46 @@ function actionHead(contract, action) {
33360
33383
  function anyScopeSet(contract, action) {
33361
33384
  return scopeSet("any", actionHead(contract, action));
33362
33385
  }
33386
+ /**
33387
+ * Грант рівня скоупу в обсязі: колонка скоупу в множині скоупів з правом, а
33388
+ * нескоуплений об'єкт — булева перевірка `has_right`.
33389
+ */
33390
+ function scopeGrant(extent, head, scope) {
33391
+ return scope === void 0 ? {
33392
+ kind: "boolean",
33393
+ expression: call$1(RIGHTS_FUNCTIONS.hasRight, [...head, ...extentArgs(extent)])
33394
+ } : {
33395
+ kind: "column",
33396
+ column: scope,
33397
+ set: scopeSet(extent, head),
33398
+ grantDependent: true
33399
+ };
33400
+ }
33401
+ /** Грант у контейнері: колонка прив'язки в множині контейнерів з правом. */
33402
+ function containerGrant(extent, head, carrier) {
33403
+ return {
33404
+ kind: "column",
33405
+ column: carrier,
33406
+ set: {
33407
+ fn: RIGHTS_FUNCTIONS.container,
33408
+ args: [...head, ...extentArgs(extent)]
33409
+ },
33410
+ grantDependent: true
33411
+ };
33412
+ }
33413
+ /**
33414
+ * Право дії в обсязі `any` над рядком без його власного носія (спека прав
33415
+ * контейнера §2, переприв'язування): у контейнері `carrier` чи на рівні
33416
+ * скоупу `scope` (нескоуплений об'єкт — `has_right`). Ті самі будівники
33417
+ * грантів, що й політики, тож множини не розійдуться.
33418
+ */
33419
+ function anyGrants(contract, action, carrier, scope) {
33420
+ const head = actionHead(contract, action);
33421
+ return {
33422
+ container: containerGrant("any", head, carrier),
33423
+ scope: scopeGrant("any", head, scope)
33424
+ };
33425
+ }
33363
33426
  /** Скоупи з правом в обсязі: своя функція множини на кожну форму (§5.1). */
33364
33427
  function scopeSet(extent, head) {
33365
33428
  const F = RIGHTS_FUNCTIONS;
@@ -34309,6 +34372,7 @@ function buildRuntimeCatalog(model) {
34309
34372
  ...adoptedFactsOf(model)
34310
34373
  } : {},
34311
34374
  ...model.project.selfSignUp ? { selfSignUp: true } : {},
34375
+ ...model.scopeKinds.some((k) => k.invitations !== void 0) ? { invitations: true } : {},
34312
34376
  ...rightsDeclarationsOf(model),
34313
34377
  objects: model.objects.flatMap((object) => {
34314
34378
  const contract = contracts.get(object.id);
@@ -34527,7 +34591,8 @@ function operationsOf(objectId, contract, model) {
34527
34591
  ...functions.markDeletion === void 0 || actions.markDeletion === void 0 ? {} : { markDeletion: target(functions.markDeletion, actions.markDeletion) },
34528
34592
  ...functions.delete === void 0 || actions.delete === void 0 ? {} : { delete: target(functions.delete, actions.delete) },
34529
34593
  ...functions.publish === void 0 || actions.publish === void 0 ? {} : { publish: target(functions.publish, actions.publish) },
34530
- ...functions.unpublish === void 0 || actions.unpublish === void 0 ? {} : { unpublish: target(functions.unpublish, actions.unpublish) }
34594
+ ...functions.unpublish === void 0 || actions.unpublish === void 0 ? {} : { unpublish: target(functions.unpublish, actions.unpublish) },
34595
+ ...model.scopeKinds.some((k) => k.invitations?.membership === objectId) ? { issueInvitation: target(invitationIssueFunctionName(contract.table), actions.update) } : {}
34531
34596
  };
34532
34597
  }
34533
34598
  /**
@@ -36383,7 +36448,7 @@ function effectiveHolderRows(catalog, contracts, physical, attributeCase) {
36383
36448
  ].filter(Boolean).join("\n");
36384
36449
  }
36385
36450
  // src/compiler/rights/guard-units.ts
36386
- const q$8 = quoteIdent;
36451
+ const q$9 = quoteIdent;
36387
36452
  const platform = (name) => ({
36388
36453
  schema: PLATFORM_SCHEMA,
36389
36454
  name
@@ -36505,17 +36570,17 @@ function journalRelation(table) {
36505
36570
  return `${table.schema}.${table.name}`;
36506
36571
  }
36507
36572
  function scopeSql(config, alias) {
36508
- return [sqlLiteral(config.catalog.level.level === "scope" ? config.catalog.level.scopeKindId : ZERO_UUID) + "::uuid", config.scope === void 0 ? `${sqlLiteral(ZERO_UUID)}::uuid` : `${alias}.${q$8(config.scope)}`];
36573
+ return [sqlLiteral(config.catalog.level.level === "scope" ? config.catalog.level.scopeKindId : ZERO_UUID) + "::uuid", config.scope === void 0 ? `${sqlLiteral(ZERO_UUID)}::uuid` : `${alias}.${q$9(config.scope)}`];
36509
36574
  }
36510
36575
  function transitionSql(config, operation) {
36511
36576
  const old = operation !== "INSERT";
36512
36577
  const next = operation !== "DELETE";
36513
- const source = operation === "INSERT" ? "new_rows n" : operation === "DELETE" ? "old_rows o" : `old_rows o FULL JOIN new_rows n ON n.${q$8(config.key)} = o.${q$8(config.key)}`;
36514
- const key = next && old ? `coalesce(n.${q$8(config.key)}, o.${q$8(config.key)})` : `${next ? "n" : "o"}.${q$8(config.key)}`;
36578
+ const source = operation === "INSERT" ? "new_rows n" : operation === "DELETE" ? "old_rows o" : `old_rows o FULL JOIN new_rows n ON n.${q$9(config.key)} = o.${q$9(config.key)}`;
36579
+ const key = next && old ? `coalesce(n.${q$9(config.key)}, o.${q$9(config.key)})` : `${next ? "n" : "o"}.${q$9(config.key)}`;
36515
36580
  const [scopeKind, oldScope] = scopeSql(config, "o");
36516
36581
  const [, newScope] = scopeSql(config, "n");
36517
36582
  const scope = next && old ? `coalesce(${newScope}, ${oldScope})` : next ? newScope : oldScope;
36518
- const rows = `SELECT ${scopeKind} AS scope_kind_id, ${scope} AS scope, ${key} AS row_id, ${config.parent === void 0 ? "NULL::uuid" : next && old ? `coalesce(n.${q$8(config.parent)}, o.${q$8(config.parent)})` : `${next ? "n" : "o"}.${q$8(config.parent)}`} AS parent_id, ${old ? "to_jsonb(o)" : "NULL::jsonb"} AS before, ${next ? "to_jsonb(n)" : "NULL::jsonb"} AS after FROM ${source}`;
36583
+ const rows = `SELECT ${scopeKind} AS scope_kind_id, ${scope} AS scope, ${key} AS row_id, ${config.parent === void 0 ? "NULL::uuid" : next && old ? `coalesce(n.${q$9(config.parent)}, o.${q$9(config.parent)})` : `${next ? "n" : "o"}.${q$9(config.parent)}`} AS parent_id, ${old ? "to_jsonb(o)" : "NULL::jsonb"} AS before, ${next ? "to_jsonb(n)" : "NULL::jsonb"} AS after FROM ${source}`;
36519
36584
  const versionRows = operation === "UPDATE" ? `SELECT ${scopeKind} AS scope_kind_id, ${oldScope} AS scope FROM old_rows o UNION SELECT ${scopeKind}, ${newScope} FROM new_rows n` : `SELECT ${scopeKind} AS scope_kind_id, ${scope} AS scope FROM ${source}`;
36520
36585
  const relation = journalRelation(config.table);
36521
36586
  const creator = config.kind === "assignment" && operation === "INSERT" ? ` WHEN EXISTS (SELECT 1 FROM ${ref(SNAPSHOT_TABLES.typed)} t WHERE t.xid = txid_current() AND t.provenance = ${sqlLiteral(ROOT_CREATOR_REASON)} AND t.assignment = r.row_id) AND NOT EXISTS (SELECT 1 FROM ${ref(platform("rights_journal"))} j WHERE j.xid = txid_current() AND j.relation = ${sqlLiteral(relation)} AND j.row_id = r.row_id) THEN ${sqlLiteral(ROOT_CREATOR_REASON)}` : "";
@@ -36737,12 +36802,12 @@ function pendingSql(config, operation) {
36737
36802
  const after = operation !== "DELETE";
36738
36803
  const [kind] = scopeSql(config, "r");
36739
36804
  const events = [...before ? [`SELECT o.*, 1 AS image FROM old_rows o`] : [], ...after ? [`SELECT n.*, 0 AS image FROM new_rows n`] : []].join(" UNION ALL ");
36740
- const scope = config.scope === void 0 ? `${sqlLiteral(ZERO_UUID)}::uuid` : `r.${q$8(config.scope)}`;
36741
- const roleKey = config.kind === "delta" ? `r.${q$8(config.parent)}` : `r.${q$8(config.key)}`;
36805
+ const scope = config.scope === void 0 ? `${sqlLiteral(ZERO_UUID)}::uuid` : `r.${q$9(config.scope)}`;
36806
+ const roleKey = config.kind === "delta" ? `r.${q$9(config.parent)}` : `r.${q$9(config.key)}`;
36742
36807
  return pendingInsert([
36743
- `SELECT ${sqlLiteral(config.kind === "assignment" ? "assignment" : "role")}::text AS kind, ${config.kind === "assignment" ? `r.${q$8(config.key)}` : roleKey} AS key, ${kind} AS scope_kind_id, ${scope} AS scope, r.image FROM (${events}) r`,
36744
- ...config.kind === "assignment" ? [`SELECT 'role'::text, r.${q$8(config.customRole)}, ${kind}, ${scope}, r.image FROM (${events}) r WHERE r.${q$8(config.customRole)} IS NOT NULL`] : [],
36745
- ...config.kind === "assignment" && before ? [`SELECT 'holders'::text, ${scope}, ${kind}, ${scope}, 1 FROM old_rows r WHERE r.${q$8(config.customRole)} IS NULL AND EXISTS (SELECT 1 FROM ${ref(RIGHTS_FUNCTIONS.fullAccessRoles)}() f WHERE f.role_id = r.${q$8(config.archetype)} AND f.storage_id IS NOT DISTINCT FROM ${config.catalog.level.level === "scope" ? kind : "NULL::uuid"})`] : [],
36808
+ `SELECT ${sqlLiteral(config.kind === "assignment" ? "assignment" : "role")}::text AS kind, ${config.kind === "assignment" ? `r.${q$9(config.key)}` : roleKey} AS key, ${kind} AS scope_kind_id, ${scope} AS scope, r.image FROM (${events}) r`,
36809
+ ...config.kind === "assignment" ? [`SELECT 'role'::text, r.${q$9(config.customRole)}, ${kind}, ${scope}, r.image FROM (${events}) r WHERE r.${q$9(config.customRole)} IS NOT NULL`] : [],
36810
+ ...config.kind === "assignment" && before ? [`SELECT 'holders'::text, ${scope}, ${kind}, ${scope}, 1 FROM old_rows r WHERE r.${q$9(config.customRole)} IS NULL AND EXISTS (SELECT 1 FROM ${ref(RIGHTS_FUNCTIONS.fullAccessRoles)}() f WHERE f.role_id = r.${q$9(config.archetype)} AND f.storage_id IS NOT DISTINCT FROM ${config.catalog.level.level === "scope" ? kind : "NULL::uuid"})`] : [],
36746
36811
  actorPending()
36747
36812
  ], "v_maintenance");
36748
36813
  }
@@ -36758,7 +36823,7 @@ function pendingSql(config, operation) {
36758
36823
  function stateRows(table, state, match, style) {
36759
36824
  const name = ref(tableName(table));
36760
36825
  const equals = match.any === true ? `= ANY (${match.value})` : `= ${match.value}`;
36761
- const live = `l.${q$8(match.column)} ${equals}`;
36826
+ const live = `l.${q$9(match.column)} ${equals}`;
36762
36827
  if (state === "after") return `SELECT to_jsonb(l) AS doc FROM ${name} l WHERE ${live}`;
36763
36828
  const key = column(table, KEY$1, style);
36764
36829
  const journal = [`${ref(platform("rights_journal"))} j WHERE j.xid = v_pending.xid AND j.reason IN ('command', ${sqlLiteral(ROOT_CREATOR_REASON)})`, `AND j.relation = ${sqlLiteral(journalRelation(table))}`].join(" ");
@@ -36766,7 +36831,7 @@ function stateRows(table, state, match, style) {
36766
36831
  `(SELECT DISTINCT ON (j.row_id) j.before AS doc FROM ${journal}${match.column === key ? ` AND j.row_id ${equals}` : ""} ORDER BY j.row_id, j.seq)`,
36767
36832
  "UNION ALL",
36768
36833
  `SELECT to_jsonb(l) FROM ${name} l WHERE ${live}`,
36769
- ` AND NOT EXISTS (SELECT 1 FROM ${journal} AND j.row_id = l.${q$8(key)})`
36834
+ ` AND NOT EXISTS (SELECT 1 FROM ${journal} AND j.row_id = l.${q$9(key)})`
36770
36835
  ].join("\n");
36771
36836
  }
36772
36837
  /** Звуження за ключем рядка: перевірка судить один рядок черги. */
@@ -36848,7 +36913,7 @@ function rootExists(catalog, physical) {
36848
36913
  return `EXISTS (SELECT 1 FROM ${ref({
36849
36914
  schema: fk.references.schema,
36850
36915
  name: fk.references.table
36851
- })} root WHERE root.${q$8(fk.references.columns[index])} = v_pending.scope)`;
36916
+ })} root WHERE root.${q$9(fk.references.columns[index])} = v_pending.scope)`;
36852
36917
  }
36853
36918
  function assignmentBeforeSet(catalog, physical, style) {
36854
36919
  const table = tableOf$2(physical, catalog.assignments.table);
@@ -36920,15 +36985,15 @@ function escalationSql(after, before, storageKind) {
36920
36985
  function deltaDomainSql(catalog, physical, style) {
36921
36986
  const roles = tableOf$2(physical, catalog.roles.table);
36922
36987
  const delta = tableOf$2(physical, catalog.roles.delta);
36923
- const r = (def) => `r.${q$8(column(roles, def, style))}`;
36924
- const l = (def) => `l.${q$8(column(delta, def, style))}`;
36988
+ const r = (def) => `r.${q$9(column(roles, def, style))}`;
36989
+ const l = (def) => `l.${q$9(column(delta, def, style))}`;
36925
36990
  const roleScope = scopeColumn(roles);
36926
36991
  const deltaScope = scopeColumn(delta);
36927
36992
  const journal = (table) => `${ref(platform("rights_journal"))} j WHERE j.xid = v_pending.xid AND j.relation = ${sqlLiteral(journalRelation(table))}`;
36928
36993
  const storage = catalog.level.level === "scope" ? `m.storage = 'scope' AND m.storage_id = ${sqlLiteral(catalog.level.scopeKindId)}::uuid` : "m.storage = 'global'";
36929
36994
  return [
36930
- `IF EXISTS (SELECT 1 FROM ${ref(catalog.roles.table)} r JOIN ${ref(catalog.roles.delta)} l ON ${l(PARENT)} = ${r(KEY$1)}${deltaScope === void 0 ? "" : ` AND l.${q$8(deltaScope)} = v_pending.scope`}`,
36931
- ` WHERE ${r(KEY$1)} = v_pending.key${roleScope === void 0 ? "" : ` AND r.${q$8(roleScope)} = v_pending.scope`}`,
36995
+ `IF EXISTS (SELECT 1 FROM ${ref(catalog.roles.table)} r JOIN ${ref(catalog.roles.delta)} l ON ${l(PARENT)} = ${r(KEY$1)}${deltaScope === void 0 ? "" : ` AND l.${q$9(deltaScope)} = v_pending.scope`}`,
36996
+ ` WHERE ${r(KEY$1)} = v_pending.key${roleScope === void 0 ? "" : ` AND r.${q$9(roleScope)} = v_pending.scope`}`,
36932
36997
  ` AND (EXISTS (SELECT 1 FROM ${journal(delta)} AND j.row_id = ${l(KEY$1)} AND j.after IS NOT NULL)`,
36933
36998
  ` OR EXISTS (SELECT 1 FROM (SELECT DISTINCT ON (j.row_id) j.before FROM ${journal(roles)} AND j.row_id = v_pending.key ORDER BY j.row_id, j.seq) f WHERE (f.before ->> ${sqlLiteral(column(roles, R.archetype, style))})::uuid IS DISTINCT FROM ${r(R.archetype)}))`,
36934
36999
  ` AND NOT EXISTS (SELECT 1 FROM ${ref(RIGHTS_FUNCTIONS.roles)}() m JOIN ${ref(RIGHTS_FUNCTIONS.domain)}() d ON d.level = m.level AND d.level_id IS NOT DISTINCT FROM m.level_id`,
@@ -36940,17 +37005,17 @@ function catalogCheck(catalog, contracts, physical, style) {
36940
37005
  const roles = tableOf$2(physical, catalog.roles.table);
36941
37006
  const assignments = tableOf$2(physical, catalog.assignments.table);
36942
37007
  const scope = catalog.level.level === "scope" ? `${sqlLiteral(catalog.level.scopeKindId)}::uuid` : `${sqlLiteral(ZERO_UUID)}::uuid`;
36943
- const roleId = `r.${q$8(column(roles, KEY$1, style))}`;
37008
+ const roleId = `r.${q$9(column(roles, KEY$1, style))}`;
36944
37009
  const assignmentScope = scopeColumn(assignments);
36945
37010
  const roleScope = scopeColumn(roles);
36946
- const sameRole = roleScope === void 0 ? "TRUE" : `r.${q$8(roleScope)} = v_pending.scope`;
36947
- const sameAssignment = assignmentScope === void 0 ? "TRUE" : `a.${q$8(assignmentScope)} = v_pending.scope`;
37011
+ const sameRole = roleScope === void 0 ? "TRUE" : `r.${q$9(roleScope)} = v_pending.scope`;
37012
+ const sameAssignment = assignmentScope === void 0 ? "TRUE" : `a.${q$9(assignmentScope)} = v_pending.scope`;
36948
37013
  const root = rootExists(catalog, physical);
36949
37014
  return [
36950
37015
  `IF v_pending.scope_kind_id = ${scope} THEN`,
36951
37016
  " IF v_pending.kind = 'role' THEN",
36952
- ` IF EXISTS (SELECT 1 FROM ${ref(catalog.roles.table)} r WHERE ${roleId} = v_pending.key AND ${sameRole} AND r.${q$8(column(roles, DELETION, style))})`,
36953
- ` AND EXISTS (SELECT 1 FROM ${ref(catalog.assignments.table)} a WHERE a.${q$8(column(assignments, R.customRole, style))} = v_pending.key AND ${sameAssignment} AND NOT a.${q$8(column(assignments, DELETION, style))})`,
37017
+ ` IF EXISTS (SELECT 1 FROM ${ref(catalog.roles.table)} r WHERE ${roleId} = v_pending.key AND ${sameRole} AND r.${q$9(column(roles, DELETION, style))})`,
37018
+ ` AND EXISTS (SELECT 1 FROM ${ref(catalog.assignments.table)} a WHERE a.${q$9(column(assignments, R.customRole, style))} = v_pending.key AND ${sameAssignment} AND NOT a.${q$9(column(assignments, DELETION, style))})`,
36954
37019
  ` THEN ${refusal(COMMAND_CORE_ERRORS.forbidden.roleInUse)} END IF;`,
36955
37020
  ` ${deltaDomainSql(catalog, physical, style)}`,
36956
37021
  ` ${escalationSql(roleGrantSet(catalog, physical, "after", style), roleGrantSet(catalog, physical, "before", style), catalogStorageKind(catalog))}`,
@@ -37072,7 +37137,7 @@ function eventRows(operation, alias, source) {
37072
37137
  }
37073
37138
  function bumpRows(operation, scopeKindId, scope) {
37074
37139
  const rows = [...eventRows(operation, "r", "old"), ...eventRows(operation, "r", "new")].join(" UNION ALL ");
37075
- const value = scope === void 0 ? `${sqlLiteral(ZERO_UUID)}::uuid` : `r.${q$8(scope)}`;
37140
+ const value = scope === void 0 ? `${sqlLiteral(ZERO_UUID)}::uuid` : `r.${q$9(scope)}`;
37076
37141
  return `PERFORM ${ref(RIGHTS_FUNCTIONS.bump)}(${sqlLiteral(scopeKindId)}::uuid, s.scope) FROM (SELECT DISTINCT ${value} AS scope FROM (${rows}) r) s;`;
37077
37142
  }
37078
37143
  /**
@@ -37086,13 +37151,13 @@ function bumpRows(operation, scopeKindId, scope) {
37086
37151
  * ключем рядка: зміну самого ключа тримає row-level тригер `_id`.
37087
37152
  */
37088
37153
  function memberEventBody(member, contracts, physical, operation, provider, style) {
37089
- const key = q$8(member.keyColumn);
37090
- const scope = q$8(member.scopeColumn);
37091
- const user = q$8(member.userColumn);
37154
+ const key = q$9(member.keyColumn);
37155
+ const scope = q$9(member.scopeColumn);
37156
+ const user = q$9(member.userColumn);
37092
37157
  const assignments = contracts.rightsCatalogs.filter((catalog) => catalog.level.level === "scope" && catalog.level.scopeKindId === member.scopeKindId).map((catalog) => {
37093
37158
  const table = catalog.assignments.table;
37094
37159
  const actual = tableOf$2(physical, table);
37095
- return `EXISTS (SELECT 1 FROM ${ref(table)} a WHERE a.${q$8(column(actual, R.subject, style))} = n.${key} AND a.${q$8(scopeColumn(actual))} = n.${scope})`;
37160
+ return `EXISTS (SELECT 1 FROM ${ref(table)} a WHERE a.${q$9(column(actual, R.subject, style))} = n.${key} AND a.${q$9(scopeColumn(actual))} = n.${scope})`;
37096
37161
  });
37097
37162
  const repeated = operation === "INSERT" && assignments.length > 0 ? `IF EXISTS (SELECT 1 FROM new_rows n WHERE ${assignments.join(" OR ")}) THEN ${refusal(COMMAND_CORE_ERRORS.forbidden.rightsContext)} END IF;` : "";
37098
37163
  const changed = operation === "UPDATE" ? [
@@ -37121,13 +37186,13 @@ function memberEventBody(member, contracts, physical, operation, provider, style
37121
37186
  * видалення облікового запису) і режим обслуговування.
37122
37187
  */
37123
37188
  function usersEventBody(users, contracts, physical, operation, attributeCase, provider) {
37124
- const key = q$8(users.keyColumn);
37125
- const invalid = q$8(users.invalidColumn);
37189
+ const key = q$9(users.keyColumn);
37190
+ const invalid = q$9(users.invalidColumn);
37126
37191
  const table = tableOf$2(physical, users.table);
37127
- const kind = q$8(column(table, USER_PLATFORM_COLUMNS.userKind, attributeCase));
37128
- const repeated = operation === "INSERT" ? [...contracts.membership.map((member) => `EXISTS (SELECT 1 FROM ${ref(member.table)} m WHERE m.${q$8(member.userColumn)} = n.${key})`), ...contracts.rightsCatalogs.filter((catalog) => catalog.level.level === "global").map((catalog) => {
37192
+ const kind = q$9(column(table, USER_PLATFORM_COLUMNS.userKind, attributeCase));
37193
+ const repeated = operation === "INSERT" ? [...contracts.membership.map((member) => `EXISTS (SELECT 1 FROM ${ref(member.table)} m WHERE m.${q$9(member.userColumn)} = n.${key})`), ...contracts.rightsCatalogs.filter((catalog) => catalog.level.level === "global").map((catalog) => {
37129
37194
  const assignment = tableOf$2(physical, catalog.assignments.table);
37130
- return `EXISTS (SELECT 1 FROM ${ref(catalog.assignments.table)} a WHERE a.${q$8(column(assignment, R.subject, attributeCase))} = n.${key})`;
37195
+ return `EXISTS (SELECT 1 FROM ${ref(catalog.assignments.table)} a WHERE a.${q$9(column(assignment, R.subject, attributeCase))} = n.${key})`;
37131
37196
  })] : [];
37132
37197
  const update = operation === "UPDATE" ? [
37133
37198
  `IF v_action IS NULL AND NOT v_maintenance AND EXISTS (SELECT 1 FROM old_rows o JOIN new_rows n ON n.${key} = o.${key}`,
@@ -37178,7 +37243,7 @@ function buildRightsGuardUnits(contracts, physical, objects, attributeCase, prov
37178
37243
  const name = tableName(table);
37179
37244
  const fn = functionName(name, labels.truncate);
37180
37245
  addFunction(fn, truncateBody(table), table.origin.objectId);
37181
- add(`CREATE TRIGGER ${q$8(triggerName(name, labels.truncate))} BEFORE TRUNCATE ON ${ref(name)} FOR EACH STATEMENT EXECUTE FUNCTION ${ref(fn)}();`, table.origin.objectId);
37246
+ add(`CREATE TRIGGER ${q$9(triggerName(name, labels.truncate))} BEFORE TRUNCATE ON ${ref(name)} FOR EACH STATEMENT EXECUTE FUNCTION ${ref(fn)}();`, table.origin.objectId);
37182
37247
  };
37183
37248
  for (const { table, facts } of sources.sources) {
37184
37249
  const name = tableName(table);
@@ -37195,7 +37260,7 @@ function buildRightsGuardUnits(contracts, physical, objects, attributeCase, prov
37195
37260
  ...t
37196
37261
  }))
37197
37262
  ]);
37198
- add(`CREATE TRIGGER ${q$8(triggerName(name, labels.snapshot))} BEFORE INSERT OR UPDATE OR DELETE ON ${ref(name)} FOR EACH STATEMENT EXECUTE FUNCTION ${ref(snapshot)}();`, owner);
37263
+ add(`CREATE TRIGGER ${q$9(triggerName(name, labels.snapshot))} BEFORE INSERT OR UPDATE OR DELETE ON ${ref(name)} FOR EACH STATEMENT EXECUTE FUNCTION ${ref(snapshot)}();`, owner);
37199
37264
  }
37200
37265
  for (const config of catalogTables(contracts, physical, attributeCase)) {
37201
37266
  const table = tableName(config.table);
@@ -37220,7 +37285,7 @@ function buildRightsGuardUnits(contracts, physical, objects, attributeCase, prov
37220
37285
  "DELETE"
37221
37286
  ]) {
37222
37287
  const transition = operation === "INSERT" ? "REFERENCING NEW TABLE AS new_rows" : operation === "DELETE" ? "REFERENCING OLD TABLE AS old_rows" : "REFERENCING OLD TABLE AS old_rows NEW TABLE AS new_rows";
37223
- add(`CREATE TRIGGER ${q$8(triggerName(table, `${labels.rights}_${operation.toLowerCase()}`))} AFTER ${operation} ON ${ref(table)} ${transition} FOR EACH STATEMENT EXECUTE FUNCTION ${ref(fn)}();`, owner);
37288
+ add(`CREATE TRIGGER ${q$9(triggerName(table, `${labels.rights}_${operation.toLowerCase()}`))} AFTER ${operation} ON ${ref(table)} ${transition} FOR EACH STATEMENT EXECUTE FUNCTION ${ref(fn)}();`, owner);
37224
37289
  }
37225
37290
  addTruncate(config.table);
37226
37291
  }
@@ -37237,7 +37302,7 @@ function buildRightsGuardUnits(contracts, physical, objects, attributeCase, prov
37237
37302
  const fn = functionName(name, label);
37238
37303
  const transition = operation === "INSERT" ? "REFERENCING NEW TABLE AS new_rows" : operation === "DELETE" ? "REFERENCING OLD TABLE AS old_rows" : "REFERENCING OLD TABLE AS old_rows NEW TABLE AS new_rows";
37239
37304
  addFunction(fn, memberEventBody(member, contracts, physical, operation, provider, attributeCase), owner, [unitNode(COMMAND_FUNCTIONS.current), BUMP_NODE]);
37240
- add(`CREATE TRIGGER ${q$8(triggerName(name, label))} AFTER ${operation} ON ${ref(name)} ${transition} FOR EACH STATEMENT EXECUTE FUNCTION ${ref(fn)}();`, owner);
37305
+ add(`CREATE TRIGGER ${q$9(triggerName(name, label))} AFTER ${operation} ON ${ref(name)} ${transition} FOR EACH STATEMENT EXECUTE FUNCTION ${ref(fn)}();`, owner);
37241
37306
  }
37242
37307
  addTruncate(table);
37243
37308
  }
@@ -37251,7 +37316,7 @@ function buildRightsGuardUnits(contracts, physical, objects, attributeCase, prov
37251
37316
  const fn = functionName(name, label);
37252
37317
  const transition = operation === "INSERT" ? "REFERENCING NEW TABLE AS new_rows" : "REFERENCING OLD TABLE AS old_rows NEW TABLE AS new_rows";
37253
37318
  addFunction(fn, usersEventBody(users, contracts, physical, operation, attributeCase, provider), owner, [unitNode(COMMAND_FUNCTIONS.current), ...operation === "UPDATE" ? [BUMP_NODE] : []]);
37254
- add(`CREATE TRIGGER ${q$8(triggerName(name, label))} AFTER ${operation} ON ${ref(name)} ${transition} FOR EACH STATEMENT EXECUTE FUNCTION ${ref(fn)}();`, owner);
37319
+ add(`CREATE TRIGGER ${q$9(triggerName(name, label))} AFTER ${operation} ON ${ref(name)} ${transition} FOR EACH STATEMENT EXECUTE FUNCTION ${ref(fn)}();`, owner);
37255
37320
  }
37256
37321
  addTruncate(table);
37257
37322
  }
@@ -37285,7 +37350,7 @@ function buildRightsGuardUnits(contracts, physical, objects, attributeCase, prov
37285
37350
  ]) {
37286
37351
  const label = `simetra_rights_relation_${operation.toLowerCase()}`;
37287
37352
  const transition = operation === "INSERT" ? "REFERENCING NEW TABLE AS new_rows" : operation === "DELETE" ? "REFERENCING OLD TABLE AS old_rows" : "REFERENCING OLD TABLE AS old_rows NEW TABLE AS new_rows";
37288
- add(`CREATE TRIGGER ${q$8(triggerName(name, label))} AFTER ${operation} ON ${ref(name)} ${transition} FOR EACH STATEMENT EXECUTE FUNCTION ${ref(fn)}();`, table.origin.objectId);
37353
+ add(`CREATE TRIGGER ${q$9(triggerName(name, label))} AFTER ${operation} ON ${ref(name)} ${transition} FOR EACH STATEMENT EXECUTE FUNCTION ${ref(fn)}();`, table.origin.objectId);
37289
37354
  }
37290
37355
  addTruncate(table);
37291
37356
  }
@@ -37319,17 +37384,17 @@ function buildRightsGuardUnits(contracts, physical, objects, attributeCase, prov
37319
37384
  ...INVITATIONS_TABLE
37320
37385
  }]
37321
37386
  ]);
37322
- add(`CREATE CONSTRAINT TRIGGER ${q$8("rights_tx_pending_check")} AFTER INSERT ON ${ref(platform("rights_tx_pending"))} DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION ${ref(check)}();`);
37387
+ add(`CREATE CONSTRAINT TRIGGER ${q$9("rights_tx_pending_check")} AFTER INSERT ON ${ref(platform("rights_tx_pending"))} DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION ${ref(check)}();`);
37323
37388
  const markerCheck = platform("rights_tx_root_marker_check");
37324
37389
  addFunction(markerCheck, rootMarkerBody(), void 0, [{
37325
37390
  type: "table",
37326
37391
  ...ROOT_MARKER_TABLE
37327
37392
  }]);
37328
- add(`CREATE CONSTRAINT TRIGGER ${q$8(markerCheck.name)} AFTER INSERT ON ${ref(ROOT_MARKER_TABLE)} DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION ${ref(markerCheck)}();`);
37393
+ add(`CREATE CONSTRAINT TRIGGER ${q$9(markerCheck.name)} AFTER INSERT ON ${ref(ROOT_MARKER_TABLE)} DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION ${ref(markerCheck)}();`);
37329
37394
  return units.sort((a, b) => compareStrings(a.identity, b.identity));
37330
37395
  }
37331
37396
  // src/compiler/rights/invitation-put-units.ts
37332
- const q$7 = quoteIdent;
37397
+ const q$8 = quoteIdent;
37333
37398
  /** Функція запису запрошення (спека запрошень §4, крок 3) — одна на проєкт. */
37334
37399
  const INVITATION_PUT_FUNCTION = {
37335
37400
  schema: PLATFORM_SCHEMA,
@@ -37363,8 +37428,8 @@ function scopeOf(table) {
37363
37428
  * рівно ті рядки, які читає звірка.
37364
37429
  */
37365
37430
  function liveAssignments(assignments, style, member, scope) {
37366
- const a = (def) => `a.${q$7(standardColumn(assignments, def, style).name)}`;
37367
- return `${a(RIGHTS_COLUMNS.subject)} = ${member} AND a.${q$7(scopeOf(assignments))} = ${scope} AND NOT ${a(deletionMarkColumn())}`;
37431
+ const a = (def) => `a.${q$8(standardColumn(assignments, def, style).name)}`;
37432
+ return `${a(RIGHTS_COLUMNS.subject)} = ${member} AND a.${q$8(scopeOf(assignments))} = ${scope} AND NOT ${a(deletionMarkColumn())}`;
37368
37433
  }
37369
37434
  /**
37370
37435
  * Набір видачі (спека запрошень §4, крок 3): відсортований за id перелік
@@ -37379,23 +37444,23 @@ function issueSetSql(catalog, physical, style, member, scope) {
37379
37444
  const assignments = tableOf$1(physical, catalog.assignments.table);
37380
37445
  const roles = tableOf$1(physical, catalog.roles.table);
37381
37446
  const delta = tableOf$1(physical, catalog.roles.delta);
37382
- const col = (table, def) => q$7(standardColumn(table, def, style).name);
37447
+ const col = (table, def) => q$8(standardColumn(table, def, style).name);
37383
37448
  const a = (def) => `a.${col(assignments, def)}`;
37384
37449
  const c = (def) => `c.${col(roles, def)}`;
37385
37450
  const d = (def) => `d.${col(delta, def)}`;
37386
37451
  const R = RIGHTS_COLUMNS;
37387
37452
  const KEY = keyColumn(false);
37388
37453
  const VERSION = versionColumn();
37389
- const assignmentScope = `a.${q$7(scopeOf(assignments))}`;
37454
+ const assignmentScope = `a.${q$8(scopeOf(assignments))}`;
37390
37455
  const deltas = [
37391
37456
  `SELECT encode(sha256(convert_to(coalesce(jsonb_agg(to_jsonb(d) ORDER BY ${d(KEY)}), '[]'::jsonb)::text, 'UTF8')), 'hex')`,
37392
37457
  `FROM ${qualified(catalog.roles.delta)} d`,
37393
- `WHERE ${d(tabularParentColumn())} = ${a(R.customRole)} AND d.${q$7(scopeOf(delta))} = ${assignmentScope}`
37458
+ `WHERE ${d(tabularParentColumn())} = ${a(R.customRole)} AND d.${q$8(scopeOf(delta))} = ${assignmentScope}`
37394
37459
  ].join(" ");
37395
37460
  return [
37396
37461
  `SELECT coalesce(jsonb_agg(jsonb_build_object('id', ${a(KEY)}, 'version', ${a(VERSION)}) || CASE WHEN ${a(R.customRole)} IS NULL THEN '{}'::jsonb ELSE jsonb_build_object('customRole', jsonb_build_object('id', ${c(KEY)}, 'version', ${c(VERSION)}, 'deltas', (${deltas}))) END ORDER BY ${a(KEY)}), '[]'::jsonb)`,
37397
37462
  `FROM ${qualified(catalog.assignments.table)} a`,
37398
- `LEFT JOIN ${qualified(catalog.roles.table)} c ON ${c(KEY)} = ${a(R.customRole)} AND c.${q$7(scopeOf(roles))} = ${assignmentScope}`,
37463
+ `LEFT JOIN ${qualified(catalog.roles.table)} c ON ${c(KEY)} = ${a(R.customRole)} AND c.${q$8(scopeOf(roles))} = ${assignmentScope}`,
37399
37464
  `WHERE ${liveAssignments(assignments, style, member, scope)}`
37400
37465
  ].join("\n");
37401
37466
  }
@@ -37410,11 +37475,11 @@ function issueSetSql(catalog, physical, style, member, scope) {
37410
37475
  function issueSetLocks(catalog, physical, style, member, scope) {
37411
37476
  const assignments = tableOf$1(physical, catalog.assignments.table);
37412
37477
  const roles = tableOf$1(physical, catalog.roles.table);
37413
- const col = (table, def) => q$7(standardColumn(table, def, style).name);
37478
+ const col = (table, def) => q$8(standardColumn(table, def, style).name);
37414
37479
  const a = (def) => `a.${col(assignments, def)}`;
37415
37480
  const R = RIGHTS_COLUMNS;
37416
37481
  const live = liveAssignments(assignments, style, member, scope);
37417
- return [`PERFORM 1 FROM ${qualified(catalog.assignments.table)} a WHERE ${live} FOR SHARE;`, `PERFORM 1 FROM ${qualified(catalog.roles.table)} c WHERE c.${q$7(scopeOf(roles))} = ${scope} AND c.${col(roles, keyColumn(false))} IN (SELECT ${a(R.customRole)} FROM ${qualified(catalog.assignments.table)} a WHERE ${live}) FOR SHARE;`];
37482
+ return [`PERFORM 1 FROM ${qualified(catalog.assignments.table)} a WHERE ${live} FOR SHARE;`, `PERFORM 1 FROM ${qualified(catalog.roles.table)} c WHERE c.${q$8(scopeOf(roles))} = ${scope} AND c.${col(roles, keyColumn(false))} IN (SELECT ${a(R.customRole)} FROM ${qualified(catalog.assignments.table)} a WHERE ${live}) FOR SHARE;`];
37418
37483
  }
37419
37484
  /**
37420
37485
  * `simetra.invitation_put(p_member, p_hash)` (спека запрошень §4, кроки 2–4):
@@ -37446,14 +37511,14 @@ function invitationPutFunction(kinds, contracts, physical, style) {
37446
37511
  const m = kind.membership;
37447
37512
  const id = uuidLiteral(kind.kindId);
37448
37513
  const pending = [
37449
- `m.${q$7(m.key)} = p_member`,
37450
- `m.${q$7(m.user)} IS NULL`,
37451
- ...m.deletion === void 0 ? [] : [`NOT m.${q$7(m.deletion)}`]
37514
+ `m.${q$8(m.key)} = p_member`,
37515
+ `m.${q$8(m.user)} IS NULL`,
37516
+ ...m.deletion === void 0 ? [] : [`NOT m.${q$8(m.deletion)}`]
37452
37517
  ].join(" AND ");
37453
37518
  return [
37454
37519
  `IF v_object = ${sqlLiteral(kind.kindLabel)} THEN`,
37455
37520
  ...[
37456
- `SELECT m.${q$7(m.scope)} INTO v_scope FROM ${qualified(m.table)} m WHERE ${pending};`,
37521
+ `SELECT m.${q$8(m.scope)} INTO v_scope FROM ${qualified(m.table)} m WHERE ${pending};`,
37457
37522
  ...ifRefuse("NOT FOUND"),
37458
37523
  ...ifRefuse(`NOT ${scopeAdministerRights(kind.assignmentsLabel, kind.kindId, "v_scope")}`),
37459
37524
  ...ifRefuse(`EXISTS (SELECT 1 FROM ${qualified(INVITATIONS_TABLE)} i WHERE i.member = p_member AND i.scope_kind_id <> ${id})`),
@@ -37498,11 +37563,11 @@ function invitationPutFunction(kinds, contracts, physical, style) {
37498
37563
  return `CREATE OR REPLACE FUNCTION ${qualified(INVITATION_PUT_FUNCTION)}(p_member uuid, p_hash bytea)\nRETURNS timestamp with time zone\nLANGUAGE plpgsql VOLATILE SECURITY DEFINER\nSET search_path = ''\nAS ${tag}\n${body}\n${tag};`;
37499
37564
  }
37500
37565
  // src/compiler/rights/invitation-accept-units.ts
37501
- const q$6 = quoteIdent;
37566
+ const q$7 = quoteIdent;
37502
37567
  /** Функція прийняття запрошення (спека запрошень §5) — одна на проєкт. */
37503
37568
  const INVITATION_ACCEPT_FUNCTION = {
37504
37569
  schema: PLATFORM_SCHEMA,
37505
- name: "invitation_accept"
37570
+ name: INVITATION_ACCEPT_FUNCTION_NAME
37506
37571
  };
37507
37572
  /**
37508
37573
  * Простір ключів advisory-замка спроб прийняття (`SIMI`): поруч із простором
@@ -37555,10 +37620,10 @@ function invitationAcceptFunction(kinds, contracts, physical, style) {
37555
37620
  const m = kind.membership;
37556
37621
  const id = uuidLiteral(kind.kindId);
37557
37622
  const pending = [
37558
- `m.${q$6(m.key)} = v_member`,
37559
- `m.${q$6(m.scope)} = v_scope`,
37560
- `m.${q$6(m.user)} IS NULL`,
37561
- ...m.deletion === void 0 ? [] : [`NOT m.${q$6(m.deletion)}`]
37623
+ `m.${q$7(m.key)} = v_member`,
37624
+ `m.${q$7(m.scope)} = v_scope`,
37625
+ `m.${q$7(m.user)} IS NULL`,
37626
+ ...m.deletion === void 0 ? [] : [`NOT m.${q$7(m.deletion)}`]
37562
37627
  ].join(" AND ");
37563
37628
  const gone = `DELETE FROM ${qualified(INVITATIONS_TABLE)} i WHERE i.member = v_member AND i.scope_kind_id = ${id};`;
37564
37629
  const changed = `(${issueSetSql(kind.catalog, physical, style, "v_member", "v_scope")}) IS DISTINCT FROM v_assignments`;
@@ -37580,14 +37645,14 @@ function invitationAcceptFunction(kinds, contracts, physical, style) {
37580
37645
  ` ${gone}`,
37581
37646
  ...failed("changed", record).map((l) => ` ${l}`),
37582
37647
  "END IF;",
37583
- `IF EXISTS (SELECT 1 FROM ${qualified(m.table)} m WHERE m.${q$6(m.scope)} = v_scope AND m.${q$6(m.user)} = v_actor) THEN`,
37648
+ `IF EXISTS (SELECT 1 FROM ${qualified(m.table)} m WHERE m.${q$7(m.scope)} = v_scope AND m.${q$7(m.user)} = v_actor) THEN`,
37584
37649
  ...failed("already-member", record).map((l) => ` ${l}`),
37585
37650
  "END IF;",
37586
37651
  `v_context := current_setting(${sqlLiteral(COMMAND_SETTING)}, true);`,
37587
37652
  "BEGIN",
37588
37653
  ...[
37589
37654
  `PERFORM set_config(${sqlLiteral(COMMAND_SETTING)}, jsonb_build_object('action', ${sqlLiteral(acceptInvitationAction.name)}, 'object', ${sqlLiteral(kind.kindLabel)}, 'root', v_member)::text, true);`,
37590
- `UPDATE ${qualified(m.table)} m SET ${q$6(m.user)} = v_actor WHERE m.${q$6(m.key)} = v_member;`,
37655
+ `UPDATE ${qualified(m.table)} m SET ${q$7(m.user)} = v_actor WHERE m.${q$7(m.key)} = v_member;`,
37591
37656
  ...ifRefuse(`${header("rights")} OR ${header("scopes")}`),
37592
37657
  `IF ${changed} THEN`,
37593
37658
  ` RAISE EXCEPTION USING ERRCODE = '${CHANGED_STATE}';`,
@@ -37652,7 +37717,7 @@ function invitationAcceptFunction(kinds, contracts, physical, style) {
37652
37717
  return `CREATE OR REPLACE FUNCTION ${qualified(INVITATION_ACCEPT_FUNCTION)}(p_hash bytea)\nRETURNS jsonb\nLANGUAGE plpgsql VOLATILE SECURITY DEFINER\nSET search_path = ''\nSET row_security = off\nAS ${tag}\n${body}\n${tag};`;
37653
37718
  }
37654
37719
  // src/compiler/rights/root-creator-units.ts
37655
- const q$5 = quoteIdent;
37720
+ const q$6 = quoteIdent;
37656
37721
  /**
37657
37722
  * Функція гранту творцю кореня виду скоупу (спека П4 §6.13):
37658
37723
  * `simetra.<вид скоупу>_root_creator`. Ім'я — від фізичного імені виду: воно
@@ -37698,7 +37763,7 @@ function rootCreatorFunction(facts) {
37698
37763
  m.user,
37699
37764
  ...m.columns.map((c) => c.name)
37700
37765
  ])];
37701
- const memberValue = (column) => forced[column] ?? `CASE WHEN p_member ? ${sqlLiteral(column)} THEN v_in.${q$5(column)} ELSE ${m.columns.find((c) => c.name === column).default} END`;
37766
+ const memberValue = (column) => forced[column] ?? `CASE WHEN p_member ? ${sqlLiteral(column)} THEN v_in.${q$6(column)} ELSE ${m.columns.find((c) => c.name === column).default} END`;
37702
37767
  const typed = {
37703
37768
  storage: "'scope'",
37704
37769
  storage_id: kind,
@@ -37728,12 +37793,12 @@ function rootCreatorFunction(facts) {
37728
37793
  `DELETE FROM ${qualified(ROOT_MARKER_TABLE)} m WHERE m.xid = txid_current() AND m.scope_kind_id = ${kind} AND m.root = p_root AND m.actor = ${CURRENT_USER$1};`,
37729
37794
  "GET DIAGNOSTICS v_count = ROW_COUNT;",
37730
37795
  ...ifRefuse("v_count = 0"),
37731
- ...ifRefuse(`EXISTS (SELECT 1 FROM ${qualified(m.table)} r WHERE r.${q$5(m.scope)} = p_root) OR EXISTS (SELECT 1 FROM ${qualified(a.table)} r WHERE r.${q$5(a.scope)} = p_root)`),
37796
+ ...ifRefuse(`EXISTS (SELECT 1 FROM ${qualified(m.table)} r WHERE r.${q$6(m.scope)} = p_root) OR EXISTS (SELECT 1 FROM ${qualified(a.table)} r WHERE r.${q$6(a.scope)} = p_root)`),
37732
37797
  ...ifRefuse(`${qualified(m.check)}(p_member - ARRAY[${Object.keys(forced).map(sqlLiteral).join(", ")}]::text[], p_root) IS NOT NULL`),
37733
37798
  `v_context := current_setting(${sqlLiteral(COMMAND_SETTING)}, true);`,
37734
37799
  context(m.action, m.kindLabel, "p_member_id"),
37735
37800
  `v_in := jsonb_populate_record(NULL::${qualified(m.table)}, p_member);`,
37736
- `INSERT INTO ${qualified(m.table)} (${memberColumns.map(q$5).join(", ")}) VALUES (${memberColumns.map(memberValue).join(", ")});`,
37801
+ `INSERT INTO ${qualified(m.table)} (${memberColumns.map(q$6).join(", ")}) VALUES (${memberColumns.map(memberValue).join(", ")});`,
37737
37802
  ...ifRefuse(`${header("rights")} OR ${header("scopes")}`),
37738
37803
  ...ifRefuse(`EXISTS (SELECT 1 FROM ${qualified(T.start)} s WHERE s.xid = txid_current())`),
37739
37804
  "v_assignment := gen_random_uuid();",
@@ -37746,7 +37811,7 @@ function rootCreatorFunction(facts) {
37746
37811
  a.scope,
37747
37812
  a.subject,
37748
37813
  a.archetype
37749
- ].map(q$5).join(", ")}) VALUES (v_assignment, p_root, p_member_id, ${archetype});`,
37814
+ ].map(q$6).join(", ")}) VALUES (v_assignment, p_root, p_member_id, ${archetype});`,
37750
37815
  `PERFORM set_config(${sqlLiteral(COMMAND_SETTING)}, v_context, true);`
37751
37816
  ].map((line) => ` ${line}`),
37752
37817
  "END"
@@ -37783,7 +37848,7 @@ function rightsCheck(contract, action, main, row, dml, rowless = false) {
37783
37848
  return predicates.map((p) => `(${p})`).join(" OR ");
37784
37849
  }
37785
37850
  // src/compiler/catalog-command/member-check.ts
37786
- const q$4 = quoteIdent;
37851
+ const q$5 = quoteIdent;
37787
37852
  /**
37788
37853
  * Перевірка рядка членства творця кореня (спека П4 §6.12, §6.13):
37789
37854
  * `<членство>_simetra_member_check(p_member jsonb, p_scope uuid) RETURNS text`
@@ -37807,7 +37872,7 @@ function memberCheckFunction(contract, membership) {
37807
37872
  ]);
37808
37873
  const keys = contract.createKeys.filter((c) => !forced.has(c));
37809
37874
  const fail = (detail) => `RETURN ${detail};`;
37810
- const scope = `v_new.${q$4(membership.scopeColumn)}`;
37875
+ const scope = `v_new.${q$5(membership.scopeColumn)}`;
37811
37876
  const references = contract.references.filter((reference) => (reference.form === "single" ? [reference.column] : [reference.typeColumn, reference.idColumn]).every((c) => !forced.has(c)));
37812
37877
  return coreFunction(memberCheckFunctionName(table), "p_member jsonb, p_scope uuid", [
37813
37878
  "v_in record;",
@@ -37823,8 +37888,8 @@ function memberCheckFunction(contract, membership) {
37823
37888
  tabular: false,
37824
37889
  fail
37825
37890
  }),
37826
- `v_new := jsonb_populate_record(NULL::${q$4(table.schema)}.${q$4(table.name)}, ${sqlLiteral("{}")});`,
37827
- ...keys.map((c) => `v_new.${q$4(c)} := CASE WHEN p_member ? ${sqlLiteral(c)} THEN v_in.${q$4(c)} ELSE ${defaultOf(table, c)} END;`),
37891
+ `v_new := jsonb_populate_record(NULL::${q$5(table.schema)}.${q$5(table.name)}, ${sqlLiteral("{}")});`,
37892
+ ...keys.map((c) => `v_new.${q$5(c)} := CASE WHEN p_member ? ${sqlLiteral(c)} THEN v_in.${q$5(c)} ELSE ${defaultOf(table, c)} END;`),
37828
37893
  `${scope} := p_scope;`,
37829
37894
  ...referenceChecks(references, newRow({
37830
37895
  scope,
@@ -37866,8 +37931,8 @@ const SIGNAL_FUNCTIONS = {
37866
37931
  }
37867
37932
  };
37868
37933
  // src/compiler/catalog-command/units.ts
37869
- const q$3 = quoteIdent;
37870
- const relation$1 = (t) => `${q$3(t.schema)}.${q$3(t.name)}`;
37934
+ const q$4 = quoteIdent;
37935
+ const relation$2 = (t) => `${q$4(t.schema)}.${q$4(t.name)}`;
37871
37936
  const E = COMMAND_CORE_ERRORS;
37872
37937
  /** `DETAIL` — SQL-вираз: літерал ключа чи конкатенація з `v_key`. */
37873
37938
  const invalid = (detail) => `RAISE EXCEPTION USING ERRCODE = '${E.invalid.errcode}', MESSAGE = '${E.invalid.message}', DETAIL = ${detail};`;
@@ -37913,8 +37978,8 @@ function buildCatalogCommandUnits(input) {
37913
37978
  const { contracts, provider, parse } = input;
37914
37979
  if (!hasRightsFunctions(contracts, provider)) return [];
37915
37980
  const rightsById = new Map(contracts.rights.map((r) => [r.objectId, r]));
37916
- const accessByTable = new Map(contracts.access.map((a) => [relation$1(a.table), a]));
37917
- const authorLinks = new Set(authorCarrierLinks(input.physical, input.attributeCase).map((l) => `${relation$1(l.table)}\0${l.through}`));
37981
+ const accessByTable = new Map(contracts.access.map((a) => [relation$2(a.table), a]));
37982
+ const authorLinks = new Set(authorCarrierLinks(input.physical, input.attributeCase).map((l) => `${relation$2(l.table)}\0${l.through}`));
37918
37983
  const unitOf = (contract, schema = contract.table.schema) => (sql, requires) => ({
37919
37984
  ...generatedUnit(sql, schema, parse),
37920
37985
  ownerObjectId: contract.objectId,
@@ -37931,10 +37996,10 @@ function buildCatalogCommandUnits(input) {
37931
37996
  const units = contracts.membership.flatMap((membership) => {
37932
37997
  const contract = byObject.get(membership.objectId);
37933
37998
  if (contract === void 0) return [];
37934
- return withGrants(unitOf(contract), `${relation$1(memberCheckFunctionName(contract.table))}(jsonb, uuid)`, memberCheckFunction(contract, membership), input.units);
37999
+ return withGrants(unitOf(contract), `${relation$2(memberCheckFunctionName(contract.table))}(jsonb, uuid)`, memberCheckFunction(contract, membership), input.units);
37935
38000
  });
37936
38001
  const creators = rootCreators(input, byObject);
37937
- for (const { root, facts } of creators.values()) units.push(...withGrants(unitOf(root, PLATFORM_SCHEMA), `${relation$1(facts.fn)}(uuid, uuid, jsonb)`, rootCreatorFunction(facts), [...input.units, ...units]));
38002
+ for (const { root, facts } of creators.values()) units.push(...withGrants(unitOf(root, PLATFORM_SCHEMA), `${relation$2(facts.fn)}(uuid, uuid, jsonb)`, rootCreatorFunction(facts), [...input.units, ...units]));
37938
38003
  const invitations = invitationKinds(input, byObject);
37939
38004
  if (invitations.length > 0) {
37940
38005
  const put = (sql, requires) => ({
@@ -37948,10 +38013,10 @@ function buildCatalogCommandUnits(input) {
37948
38013
  units.push(put(sql, bodyRequires(sql, {
37949
38014
  ...input,
37950
38015
  units: input.units
37951
- })), ...executeGrants(`${relation$1(INVITATION_PUT_FUNCTION)}(uuid, bytea)`, ["command"], provider).map((grant) => put(grant)), put(accept, bodyRequires(accept, {
38016
+ })), ...executeGrants(`${relation$2(INVITATION_PUT_FUNCTION)}(uuid, bytea)`, ["command"], provider).map((grant) => put(grant)), put(accept, bodyRequires(accept, {
37952
38017
  ...input,
37953
38018
  units: input.units
37954
- })), ...executeGrants(`${relation$1(INVITATION_ACCEPT_FUNCTION)}(bytea)`, ["command"], provider).map((grant) => put(grant)));
38019
+ })), ...executeGrants(`${relation$2(INVITATION_ACCEPT_FUNCTION)}(bytea)`, ["command"], provider).map((grant) => put(grant)));
37955
38020
  }
37956
38021
  const known = [...input.units, ...units];
37957
38022
  const signalModel = {
@@ -37961,12 +38026,12 @@ function buildCatalogCommandUnits(input) {
37961
38026
  };
37962
38027
  for (const contract of commands) {
37963
38028
  const rights = rightsById.get(contract.objectId);
37964
- const access = accessByTable.get(relation$1(contract.table));
38029
+ const access = accessByTable.get(relation$2(contract.table));
37965
38030
  const parts = coreParts(contract, {
37966
38031
  rights,
37967
38032
  access,
37968
38033
  attributeCase: input.attributeCase,
37969
- authorLink: (link) => authorLinks.has(`${relation$1(link.table)}\0${link.through}`),
38034
+ authorLink: (link) => authorLinks.has(`${relation$2(link.table)}\0${link.through}`),
37970
38035
  signal: access === void 0 || !isSignalObject(signalModel, contract.objectId) ? void 0 : {
37971
38036
  objectId: contract.objectId,
37972
38037
  scopeKindId: access.scope?.scopeKindId ?? ZERO_UUID,
@@ -38012,7 +38077,7 @@ function buildCatalogCommandUnits(input) {
38012
38077
  args: "uuid, bytea",
38013
38078
  sql: invitationIssueFunction(contract, invitation, parts)
38014
38079
  });
38015
- for (const { fn, args, sql } of functions) units.push(...withGrants(unitOf(contract), `${relation$1(fn)}(${args})`, sql, known));
38080
+ for (const { fn, args, sql } of functions) units.push(...withGrants(unitOf(contract), `${relation$2(fn)}(${args})`, sql, known));
38016
38081
  }
38017
38082
  return units.sort((a, b) => compareStrings(a.identity, b.identity));
38018
38083
  }
@@ -38149,7 +38214,7 @@ function defaultOf(table, column) {
38149
38214
  function textColumns(table, row) {
38150
38215
  const columns = table.columns.filter((c) => isTextEncodedType(c.type));
38151
38216
  if (columns.length === 0) return void 0;
38152
- return jsonbBuildObject(columns.map((c) => `${sqlLiteral(c.name)}, ${row}.${q$3(c.name)}::${c.type.endsWith("[]") ? "text[]" : "text"}`));
38217
+ return jsonbBuildObject(columns.map((c) => `${sqlLiteral(c.name)}, ${row}.${q$4(c.name)}::${c.type.endsWith("[]") ? "text[]" : "text"}`));
38153
38218
  }
38154
38219
  /**
38155
38220
  * Рядок результату ядра: `to_jsonb` без колонок, що не є полями сутності
@@ -38189,9 +38254,9 @@ function referenceViolations(reference, row) {
38189
38254
  const scoped = (target, alias) => {
38190
38255
  if (reference.crossScope === true || row.scope === void 0 || row.scopeKindId === void 0) return "";
38191
38256
  const column = target.columns.find((c) => c.origin.scopeKindId === row.scopeKindId);
38192
- return column === void 0 ? "" : ` AND ${alias}.${q$3(column.name)} = ${row.scope}`;
38257
+ return column === void 0 ? "" : ` AND ${alias}.${q$4(column.name)} = ${row.scope}`;
38193
38258
  };
38194
- const visible = (target, key, value, withScope) => `EXISTS (SELECT 1 FROM ${relation$1(target)} g WHERE g.${q$3(key)} = ${value}${withScope ? scoped(target, "g") : ""})`;
38259
+ const visible = (target, key, value, withScope) => `EXISTS (SELECT 1 FROM ${relation$2(target)} g WHERE g.${q$4(key)} = ${value}${withScope ? scoped(target, "g") : ""})`;
38195
38260
  if (reference.form === "single") {
38196
38261
  const value = row.value(reference.column);
38197
38262
  const old = row.old?.(reference.column);
@@ -38247,29 +38312,29 @@ function coreParts(contract, facts) {
38247
38312
  def,
38248
38313
  column: findStandardColumn(table, def, facts.attributeCase)?.name
38249
38314
  })).filter((a) => a.column !== void 0);
38250
- const copyRead = (link) => facts.authorLink(link) ? `SELECT ${link.copies.map((c) => `s.${q$3(c.column)}`).join(", ")} INTO ${link.copies.map((c) => `v_new.${q$3(c.name)}`).join(", ")} FROM ${relation$1(AUTHOR_CARRIER_SOURCES_FUNCTION)}() s;` : carrierCopyRead(link, "v_new", false);
38315
+ const copyRead = (link) => facts.authorLink(link) ? `SELECT ${link.copies.map((c) => `s.${q$4(c.column)}`).join(", ")} INTO ${link.copies.map((c) => `v_new.${q$4(c.name)}`).join(", ")} FROM ${relation$2(AUTHOR_CARRIER_SOURCES_FUNCTION)}() s;` : carrierCopyRead(link, "v_new", false);
38251
38316
  return {
38252
38317
  facts,
38253
38318
  label,
38254
- scope: contract.scopeColumn === void 0 ? void 0 : `v_new.${q$3(contract.scopeColumn)}`,
38319
+ scope: contract.scopeColumn === void 0 ? void 0 : `v_new.${q$4(contract.scopeColumn)}`,
38255
38320
  ownScopeKind,
38256
38321
  authors: authors.map((a) => a.column),
38257
38322
  updatedBy: authors.find((a) => a.def.logicalName === "updatedBy")?.column,
38258
- context: (action, root) => ifThen(`(SELECT ${relation$1(COMMAND_FUNCTIONS.action)}()) IS DISTINCT FROM ${sqlLiteral(action)} OR (SELECT ${relation$1(COMMAND_FUNCTIONS.root)}(${label})) IS DISTINCT FROM ${root}`, [contextRefused]),
38323
+ context: (action, root) => ifThen(`(SELECT ${relation$2(COMMAND_FUNCTIONS.action)}()) IS DISTINCT FROM ${sqlLiteral(action)} OR (SELECT ${relation$2(COMMAND_FUNCTIONS.root)}(${label})) IS DISTINCT FROM ${root}`, [contextRefused]),
38259
38324
  lock: `PERFORM ${hierarchyLockSql(table)};`,
38260
38325
  copyRead,
38261
- relink: (links) => links.flatMap((link) => ifThen(link.pairs.map((p) => `v_new.${q$3(p.local)} IS DISTINCT FROM v_old.${q$3(p.local)}`).join(" OR "), [copyRead(link)])),
38326
+ relink: (links) => links.flatMap((link) => ifThen(link.pairs.map((p) => `v_new.${q$4(p.local)} IS DISTINCT FROM v_old.${q$4(p.local)}`).join(" OR "), [copyRead(link)])),
38262
38327
  signal: (row, op, version) => {
38263
38328
  const target = facts.signal;
38264
38329
  if (target === void 0) return [];
38265
- const scope = target.carrier === void 0 ? uuidLiteral(ZERO_UUID) : `${row}.${q$3(target.carrier)}`;
38266
- return [`PERFORM ${relation$1(SIGNAL_FUNCTIONS.signal)}(${uuidLiteral(target.objectId)}, ${uuidLiteral(target.scopeKindId)}, ${scope}, jsonb_build_object(${sqlLiteral(key)}, ${row}.${q$3(key)}), ${version}, ${op});`];
38330
+ const scope = target.carrier === void 0 ? uuidLiteral(ZERO_UUID) : `${row}.${q$4(target.carrier)}`;
38331
+ return [`PERFORM ${relation$2(SIGNAL_FUNCTIONS.signal)}(${uuidLiteral(target.objectId)}, ${uuidLiteral(target.scopeKindId)}, ${scope}, jsonb_build_object(${sqlLiteral(key)}, ${row}.${q$4(key)}), ${version}, ${op});`];
38267
38332
  },
38268
38333
  rightsIf: (action, dml, row, reason) => ifThen(`(${rightsCheck(facts.rights, action, table, row, dml)}) IS NOT TRUE`, [forbidden(reason)]),
38269
38334
  lockedOld: (root, strength, byFields = false) => [
38270
- `SELECT * INTO v_old FROM ${relation$1(table)} r WHERE r.${q$3(key)} = ${root} FOR ${strength};`,
38335
+ `SELECT * INTO v_old FROM ${relation$2(table)} r WHERE r.${q$4(key)} = ${root} FOR ${strength};`,
38271
38336
  ...ifThen("NOT FOUND", [noRight]),
38272
- ...ifThen(`${byFields ? "p_expected_values IS NULL AND " : ""}v_old.${q$3(contract.versionColumn)} IS DISTINCT FROM p_expected_version`, [conflict(E.conflict.version, `v_old.${q$3(contract.versionColumn)}::text`)])
38337
+ ...ifThen(`${byFields ? "p_expected_values IS NULL AND " : ""}v_old.${q$4(contract.versionColumn)} IS DISTINCT FROM p_expected_version`, [conflict(E.conflict.version, `v_old.${q$4(contract.versionColumn)}::text`)])
38273
38338
  ]
38274
38339
  };
38275
38340
  }
@@ -38291,7 +38356,7 @@ function createParts(contract, parts, action, root) {
38291
38356
  /** Рядок «після» `v_new` для перевірки посилань: значення й скоуп рядка. */
38292
38357
  function newRow(parts) {
38293
38358
  return {
38294
- value: (c) => `v_new.${q$3(c)}`,
38359
+ value: (c) => `v_new.${q$4(c)}`,
38295
38360
  ...parts.scope === void 0 ? {} : { scope: parts.scope },
38296
38361
  ...parts.ownScopeKind === void 0 ? {} : { scopeKindId: parts.ownScopeKind }
38297
38362
  };
@@ -38300,11 +38365,11 @@ function newRow(parts) {
38300
38365
  function saveFunction(contract, parts) {
38301
38366
  const { key } = contract;
38302
38367
  const { scope, ownScopeKind, updatedBy, lock, rightsIf } = parts;
38303
- const root = `v_in.${q$3(key)}`;
38368
+ const root = `v_in.${q$4(key)}`;
38304
38369
  const context = (action) => parts.context(action, root);
38305
38370
  const references = (old) => referenceChecks(contract.references, {
38306
38371
  ...newRow(parts),
38307
- ...old ? { old: (c) => `v_old.${q$3(c)}` } : {}
38372
+ ...old ? { old: (c) => `v_old.${q$4(c)}` } : {}
38308
38373
  }, invalid);
38309
38374
  const createBranch = contract.actions.create === void 0 ? [invalid(sqlLiteral(E.invalid.create))] : createLines(contract, {
38310
38375
  ...createParts(contract, parts, contract.actions.create, root),
@@ -38318,8 +38383,8 @@ function saveFunction(contract, parts) {
38318
38383
  ...rightsIf(contract.actions.update, "update", "v_old", E.forbidden.noRight),
38319
38384
  ...fieldsCheck(contract),
38320
38385
  "v_new := v_old;",
38321
- ...contract.updateKeys.flatMap((c) => ifThen(`p_item ? ${sqlLiteral(c)}`, [`v_new.${q$3(c)} := v_in.${q$3(c)};`])),
38322
- ...updatedBy === void 0 ? [] : [`v_new.${q$3(updatedBy)} := ${CURRENT_USER$1};`],
38386
+ ...contract.updateKeys.flatMap((c) => ifThen(`p_item ? ${sqlLiteral(c)}`, [`v_new.${q$4(c)} := v_in.${q$4(c)};`])),
38387
+ ...updatedBy === void 0 ? [] : [`v_new.${q$4(updatedBy)} := ${CURRENT_USER$1};`],
38323
38388
  ...references(true),
38324
38389
  ...parts.relink(contract.carrierLinks),
38325
38390
  ...rightsIf(contract.actions.update, "update", "v_new", E.forbidden.newCarrier),
@@ -38352,12 +38417,12 @@ function saveFunction(contract, parts) {
38352
38417
  ...indent$1(updateBranch),
38353
38418
  "END IF;",
38354
38419
  ...tabularLines(contract, scope, ownScopeKind),
38355
- ...parts.signal("v_row", `CASE WHEN p_expected_version IS NULL THEN ${signalOp("create")} ELSE ${signalOp("update")} END`, `v_row.${q$3(contract.versionColumn)}`),
38420
+ ...parts.signal("v_row", `CASE WHEN p_expected_version IS NULL THEN ${signalOp("create")} ELSE ${signalOp("update")} END`, `v_row.${q$4(contract.versionColumn)}`),
38356
38421
  ...resultLines(contract, root, true)
38357
38422
  ]);
38358
38423
  }
38359
38424
  function inputLines(spec) {
38360
- const t = relation$1(spec.table);
38425
+ const t = relation$2(spec.table);
38361
38426
  const p = spec.param;
38362
38427
  const allowed = (keys) => textArray([.../* @__PURE__ */ new Set([...keys, ...spec.tabular ? ["tabular"] : []])]);
38363
38428
  const unknown = (keys) => `SELECT k.k INTO v_key FROM jsonb_object_keys(${p}) AS k(k) WHERE k.k <> ALL (${allowed(keys)}) ORDER BY k.k LIMIT 1;`;
@@ -38383,7 +38448,7 @@ function inputLines(spec) {
38383
38448
  ...indent$1([spec.fail("v_key")]),
38384
38449
  "END;",
38385
38450
  `${spec.target} := jsonb_populate_record(NULL::${t}, ${p});`,
38386
- ...spec.key === void 0 ? [] : ifThen(`${spec.target}.${q$3(spec.key)} IS NULL`, [spec.fail(sqlLiteral(spec.key))])
38451
+ ...spec.key === void 0 ? [] : ifThen(`${spec.target}.${q$4(spec.key)} IS NULL`, [spec.fail(sqlLiteral(spec.key))])
38387
38452
  ];
38388
38453
  }
38389
38454
  const isBranched = (keys) => !Array.isArray(keys);
@@ -38440,28 +38505,28 @@ function fieldsCheck(contract) {
38440
38505
  return ifThen("p_expected_values IS NOT NULL", [
38441
38506
  `v_expected := ${rowJson(table, "v_exp")};`,
38442
38507
  `v_current := ${rowJson(table, "v_old")};`,
38443
- ...ifThen(fieldsDiffer(table, contract.updateKeys), [conflict(E.conflict.fields, `v_old.${q$3(versionColumn)}::text`)])
38508
+ ...ifThen(fieldsDiffer(table, contract.updateKeys), [conflict(E.conflict.fields, `v_old.${q$4(versionColumn)}::text`)])
38444
38509
  ]);
38445
38510
  }
38446
38511
  /** Гілка створення (`p_expected_version IS NULL` у `save`, ядро кореня). */
38447
38512
  function createLines(contract, parts) {
38448
38513
  const { table, key } = contract;
38449
- const t = relation$1(table);
38450
- const exists = `PERFORM 1 FROM ${t} r WHERE r.${q$3(key)} = v_in.${q$3(key)};`;
38514
+ const t = relation$2(table);
38515
+ const exists = `PERFORM 1 FROM ${t} r WHERE r.${q$4(key)} = v_in.${q$4(key)};`;
38451
38516
  const constraints = keyConstraints(table, key);
38452
38517
  return [
38453
38518
  ...parts.context,
38454
38519
  exists,
38455
38520
  ...ifThen("FOUND", [conflict(E.conflict.exists)]),
38456
38521
  `v_new := jsonb_populate_record(NULL::${t}, '{}');`,
38457
- ...contract.createKeys.map((c) => `v_new.${q$3(c)} := CASE WHEN p_item ? ${sqlLiteral(c)} THEN v_in.${q$3(c)} ELSE ${defaultOf(table, c)} END;`),
38458
- ...parts.authors.map((c) => `v_new.${q$3(c)} := ${CURRENT_USER$1};`),
38522
+ ...contract.createKeys.map((c) => `v_new.${q$4(c)} := CASE WHEN p_item ? ${sqlLiteral(c)} THEN v_in.${q$4(c)} ELSE ${defaultOf(table, c)} END;`),
38523
+ ...parts.authors.map((c) => `v_new.${q$4(c)} := ${CURRENT_USER$1};`),
38459
38524
  ...parts.references,
38460
38525
  ...parts.copies,
38461
38526
  ...parts.rights,
38462
- ...contract.hierarchy === void 0 ? [] : contract.hierarchy.lockAlways ? [parts.lock] : ifThen(`v_new.${q$3(contract.hierarchy.parent)} IS NOT NULL`, [parts.lock]),
38527
+ ...contract.hierarchy === void 0 ? [] : contract.hierarchy.lockAlways ? [parts.lock] : ifThen(`v_new.${q$4(contract.hierarchy.parent)} IS NOT NULL`, [parts.lock]),
38463
38528
  "BEGIN",
38464
- ...indent$1([`INSERT INTO ${t} (${contract.createKeys.map(q$3).join(", ")}) VALUES (${contract.createKeys.map((c) => `v_new.${q$3(c)}`).join(", ")})${parts.returning ? " RETURNING * INTO v_row" : ""};`]),
38529
+ ...indent$1([`INSERT INTO ${t} (${contract.createKeys.map(q$4).join(", ")}) VALUES (${contract.createKeys.map((c) => `v_new.${q$4(c)}`).join(", ")})${parts.returning ? " RETURNING * INTO v_row" : ""};`]),
38465
38530
  "EXCEPTION WHEN unique_violation THEN",
38466
38531
  ...indent$1([
38467
38532
  "GET STACKED DIAGNOSTICS v_constraint = CONSTRAINT_NAME;",
@@ -38496,14 +38561,14 @@ function keyColumns(table) {
38496
38561
  * `NO KEY UPDATE` (спека П4 §6.6), сумісний з `KEY SHARE` взаємних RI-перевірок.
38497
38562
  */
38498
38563
  function headerUpdate(contract) {
38499
- if (contract.updateKeys.length === 0) throw new Error(`internal: command core of ${relation$1(contract.table)} has no update keys`);
38564
+ if (contract.updateKeys.length === 0) throw new Error(`internal: command core of ${relation$2(contract.table)} has no update keys`);
38500
38565
  const keys = keyColumns(contract.table);
38501
- const form = (columns) => [`UPDATE ${relation$1(contract.table)} SET ${columns.map((c) => `${q$3(c)} = CASE WHEN p_item ? ${sqlLiteral(c)} THEN v_in.${q$3(c)} ELSE ${q$3(c)} END`).join(", ")} WHERE ${q$3(contract.key)} = v_in.${q$3(contract.key)} RETURNING * INTO v_row;`, "GET DIAGNOSTICS v_count = ROW_COUNT;"];
38566
+ const form = (columns) => [`UPDATE ${relation$2(contract.table)} SET ${columns.map((c) => `${q$4(c)} = CASE WHEN p_item ? ${sqlLiteral(c)} THEN v_in.${q$4(c)} ELSE ${q$4(c)} END`).join(", ")} WHERE ${q$4(contract.key)} = v_in.${q$4(contract.key)} RETURNING * INTO v_row;`, "GET DIAGNOSTICS v_count = ROW_COUNT;"];
38502
38567
  const changed = contract.updateKeys.filter((c) => keys.has(c));
38503
38568
  const rest = contract.updateKeys.filter((c) => !keys.has(c));
38504
38569
  if (changed.length === 0 || rest.length === 0) return form(contract.updateKeys);
38505
38570
  return [
38506
- `IF ${changed.map((c) => `(p_item ? ${sqlLiteral(c)} AND v_in.${q$3(c)} IS DISTINCT FROM v_old.${q$3(c)})`).join(" OR ")} THEN`,
38571
+ `IF ${changed.map((c) => `(p_item ? ${sqlLiteral(c)} AND v_in.${q$4(c)} IS DISTINCT FROM v_old.${q$4(c)})`).join(" OR ")} THEN`,
38507
38572
  ...indent$1(form(contract.updateKeys)),
38508
38573
  "ELSE",
38509
38574
  ...indent$1(form(rest)),
@@ -38522,28 +38587,28 @@ function tabularLines(contract, scope, scopeKindId) {
38522
38587
  ]);
38523
38588
  }
38524
38589
  function sectionLines(contract, section, scope, scopeKindId) {
38525
- const ts = relation$1(section.table);
38590
+ const ts = relation$2(section.table);
38526
38591
  const name = section.table.name;
38527
38592
  const items = `p_item -> 'tabular' -> ${sqlLiteral(name)}`;
38528
38593
  const detail = (suffix) => sqlLiteral(`${E.invalid.tabular}.${name}${suffix === void 0 ? "" : `.${suffix}`}`);
38529
- const root = `v_in.${q$3(contract.key)}`;
38530
- const key = q$3(section.key);
38531
- const parent = q$3(section.parent);
38594
+ const root = `v_in.${q$4(contract.key)}`;
38595
+ const key = q$4(section.key);
38596
+ const parent = q$4(section.parent);
38532
38597
  const elements = `jsonb_array_elements(${items}) WITH ORDINALITY AS x(e, ord) CROSS JOIN LATERAL jsonb_populate_record(NULL::${ts}, x.e) AS v`;
38533
38598
  const constraints = keyConstraints(section.table, section.key);
38534
38599
  const updatable = new Set(section.updateColumns);
38535
38600
  const afterColumns = [...new Set(section.references.flatMap((r) => r.form === "single" ? [r.column] : [r.typeColumn, r.idColumn]))];
38536
38601
  const afterValue = (c) => {
38537
- if (!updatable.has(c)) throw new Error(`internal: tabular reference ${relation$1(section.table)}.${c} is not an update column`);
38538
- return `CASE WHEN x.e ? ${sqlLiteral(c)} THEN v.${q$3(c)} WHEN o.${key} IS NOT NULL THEN o.${q$3(c)} ELSE ${defaultOf(section.table, c)} END AS ${q$3(c)}`;
38602
+ if (!updatable.has(c)) throw new Error(`internal: tabular reference ${relation$2(section.table)}.${c} is not an update column`);
38603
+ return `CASE WHEN x.e ? ${sqlLiteral(c)} THEN v.${q$4(c)} WHEN o.${key} IS NOT NULL THEN o.${q$4(c)} ELSE ${defaultOf(section.table, c)} END AS ${q$4(c)}`;
38539
38604
  };
38540
38605
  const owned = `${elements} LEFT JOIN ${ts} o ON o.${key} = v.${key} AND o.${parent} = ${root}`;
38541
38606
  const afterOf = `CROSS JOIN LATERAL jsonb_populate_record(NULL::${ts}, v_after -> (x.ord - 1)::int) AS n`;
38542
38607
  const materialize = afterColumns.length === 0 ? [] : [`v_after := (SELECT coalesce(jsonb_agg(to_jsonb(n) ORDER BY x.ord), '[]') FROM ${owned} CROSS JOIN LATERAL (SELECT ${afterColumns.map(afterValue).join(", ")}) AS n);`];
38543
38608
  const afterRows = `${owned} ${afterOf}`;
38544
38609
  const references = section.references.flatMap((reference) => referenceViolations(reference, {
38545
- value: (c) => `n.${q$3(c)}`,
38546
- old: (c) => `o.${q$3(c)}`,
38610
+ value: (c) => `n.${q$4(c)}`,
38611
+ old: (c) => `o.${q$4(c)}`,
38547
38612
  ...scope === void 0 ? {} : { scope },
38548
38613
  ...scopeKindId === void 0 ? {} : { scopeKindId }
38549
38614
  }).flatMap(({ column, condition }) => ifThen(`EXISTS (SELECT 1 FROM ${afterRows} WHERE ${condition})`, [invalid(detail(column))])));
@@ -38558,11 +38623,11 @@ function sectionLines(contract, section, scope, scopeKindId) {
38558
38623
  `v.${key}`,
38559
38624
  root,
38560
38625
  "x.ord",
38561
- ...section.scopeColumn === void 0 ? [] : [`v_new.${q$3(must$1(contract.scopeColumn))}`],
38562
- ...section.rowKeys.map((c) => afterColumns.includes(c) ? `n.${q$3(c)}` : `CASE WHEN x.e ? ${sqlLiteral(c)} THEN v.${q$3(c)} ELSE ${defaultOf(section.table, c)} END`)
38626
+ ...section.scopeColumn === void 0 ? [] : [`v_new.${q$4(must$1(contract.scopeColumn))}`],
38627
+ ...section.rowKeys.map((c) => afterColumns.includes(c) ? `n.${q$4(c)}` : `CASE WHEN x.e ? ${sqlLiteral(c)} THEN v.${q$4(c)} ELSE ${defaultOf(section.table, c)} END`)
38563
38628
  ];
38564
38629
  const insertRows = afterColumns.length === 0 ? elements : `${elements} ${afterOf}`;
38565
- const set = [...section.updateColumns.map((c) => `${q$3(c)} = CASE WHEN x.e ? ${sqlLiteral(c)} THEN v.${q$3(c)} ELSE r.${q$3(c)} END`), `${q$3(section.lineNumber)} = x.ord`].join(", ");
38630
+ const set = [...section.updateColumns.map((c) => `${q$4(c)} = CASE WHEN x.e ? ${sqlLiteral(c)} THEN v.${q$4(c)} ELSE r.${q$4(c)} END`), `${q$4(section.lineNumber)} = x.ord`].join(", ");
38566
38631
  return ifThen(`p_item -> 'tabular' ? ${sqlLiteral(name)}`, [
38567
38632
  ...ifThen(`jsonb_typeof(${items}) IS DISTINCT FROM 'array'`, [invalid(detail())]),
38568
38633
  ...ifThen(`EXISTS (SELECT 1 FROM jsonb_array_elements(${items}) AS x(e) WHERE jsonb_typeof(x.e) IS DISTINCT FROM 'object')`, [invalid(detail())]),
@@ -38591,7 +38656,7 @@ function sectionLines(contract, section, scope, scopeKindId) {
38591
38656
  "GET DIAGNOSTICS v_count = ROW_COUNT;",
38592
38657
  ...ifThen("v_count IS DISTINCT FROM v_ts_update", [noRight]),
38593
38658
  "BEGIN",
38594
- ...indent$1([`INSERT INTO ${ts} (${insertColumns.map(q$3).join(", ")}) SELECT ${insertValues.join(", ")} FROM ${insertRows} WHERE NOT EXISTS (SELECT 1 FROM ${ts} r WHERE r.${key} = v.${key} AND r.${parent} = ${root});`]),
38659
+ ...indent$1([`INSERT INTO ${ts} (${insertColumns.map(q$4).join(", ")}) SELECT ${insertValues.join(", ")} FROM ${insertRows} WHERE NOT EXISTS (SELECT 1 FROM ${ts} r WHERE r.${key} = v.${key} AND r.${parent} = ${root});`]),
38595
38660
  "EXCEPTION WHEN unique_violation THEN",
38596
38661
  ...indent$1([
38597
38662
  "GET STACKED DIAGNOSTICS v_constraint = CONSTRAINT_NAME;",
@@ -38614,7 +38679,7 @@ function resultLines(contract, root, tabular) {
38614
38679
  `v_result := ${rowJson(table, "v_row")};`,
38615
38680
  ...!tabular || contract.tabularSections.length === 0 ? [] : ifThen("p_item ? 'tabular'", [
38616
38681
  "v_tabular := '{}';",
38617
- ...contract.tabularSections.flatMap((section) => ifThen(`p_item -> 'tabular' ? ${sqlLiteral(section.table.name)}`, [`v_tabular := v_tabular || jsonb_build_object(${sqlLiteral(section.table.name)}, (SELECT coalesce(jsonb_agg(${rowJson(section.table, "r")} ORDER BY r.${q$3(section.lineNumber)}), '[]') FROM ${relation$1(section.table)} r WHERE r.${q$3(section.parent)} = ${root}));`])),
38682
+ ...contract.tabularSections.flatMap((section) => ifThen(`p_item -> 'tabular' ? ${sqlLiteral(section.table.name)}`, [`v_tabular := v_tabular || jsonb_build_object(${sqlLiteral(section.table.name)}, (SELECT coalesce(jsonb_agg(${rowJson(section.table, "r")} ORDER BY r.${q$4(section.lineNumber)}), '[]') FROM ${relation$2(section.table)} r WHERE r.${q$4(section.parent)} = ${root}));`])),
38618
38683
  "v_result := v_result || jsonb_build_object('tabular', v_tabular);"
38619
38684
  ]),
38620
38685
  "RETURN v_result::text;"
@@ -38638,7 +38703,7 @@ function coreFunction(fn, args, declarations, statements) {
38638
38703
  "END"
38639
38704
  ].join("\n");
38640
38705
  const tag = dollarTag$1(body);
38641
- return `CREATE OR REPLACE FUNCTION ${relation$1(fn)}(${args})\nRETURNS text\nLANGUAGE plpgsql VOLATILE SECURITY INVOKER\nSET search_path = ''\n${pinnedSettingsClause()}\nAS ${tag}\n${body}\n${tag};`;
38706
+ return `CREATE OR REPLACE FUNCTION ${relation$2(fn)}(${args})\nRETURNS text\nLANGUAGE plpgsql VOLATILE SECURITY INVOKER\nSET search_path = ''\n${pinnedSettingsClause()}\nAS ${tag}\n${body}\n${tag};`;
38642
38707
  }
38643
38708
  /**
38644
38709
  * `<корінь>_create_root(p_item jsonb, p_member jsonb, p_member_id uuid)` (спека
@@ -38654,10 +38719,10 @@ function coreFunction(fn, args, declarations, statements) {
38654
38719
  */
38655
38720
  function createRootFunction(contract, fn, action, parts, creator) {
38656
38721
  const { table, key } = contract;
38657
- const root = `v_in.${q$3(key)}`;
38658
- const insertedVersion = (target, into) => `${into} := current_setting(${sqlLiteral(ROW_VERSION_SETTING)} || '${relation$1(target.table)}'::regclass::oid::text, true);`;
38722
+ const root = `v_in.${q$4(key)}`;
38723
+ const insertedVersion = (target, into) => `${into} := current_setting(${sqlLiteral(ROW_VERSION_SETTING)} || '${relation$2(target.table)}'::regclass::oid::text, true);`;
38659
38724
  const visible = (target, row, id, into, version) => [
38660
- `SELECT * INTO ${row} FROM ${relation$1(target.table)} r WHERE r.${q$3(target.key)} = ${id};`,
38725
+ `SELECT * INTO ${row} FROM ${relation$2(target.table)} r WHERE r.${q$4(target.key)} = ${id};`,
38661
38726
  "IF FOUND THEN",
38662
38727
  ` ${into} := ${rowJson(target.table, row)};`,
38663
38728
  "ELSE",
@@ -38690,7 +38755,7 @@ function createRootFunction(contract, fn, action, parts, creator) {
38690
38755
  }),
38691
38756
  ...creator === void 0 ? ifThen("p_member IS NOT NULL OR p_member_id IS NOT NULL", [invalid(sqlLiteral(E.invalid.creatorMember))]) : [
38692
38757
  ...ifThen("p_member IS NULL OR p_member_id IS NULL OR jsonb_typeof(p_member) IS DISTINCT FROM 'object'", [invalid(sqlLiteral(E.invalid.creatorMember))]),
38693
- `v_column := ${relation$1(creator.facts.membership.check)}(p_member, ${root});`,
38758
+ `v_column := ${relation$2(creator.facts.membership.check)}(p_member, ${root});`,
38694
38759
  ...ifThen("v_column IS NOT NULL", [invalid(`${sqlLiteral(`${E.invalid.creatorMember}.`)} || v_column`)])
38695
38760
  ],
38696
38761
  ...createLines(contract, {
@@ -38699,7 +38764,7 @@ function createRootFunction(contract, fn, action, parts, creator) {
38699
38764
  returning: false
38700
38765
  }),
38701
38766
  insertedVersion(contract, "v_root_version"),
38702
- ...creator === void 0 ? [] : [`PERFORM ${relation$1(creator.facts.fn)}(${root}, p_member_id, p_member);`, insertedVersion(creator.member, "v_member_version")],
38767
+ ...creator === void 0 ? [] : [`PERFORM ${relation$2(creator.facts.fn)}(${root}, p_member_id, p_member);`, insertedVersion(creator.member, "v_member_version")],
38703
38768
  ...visible(contract, "v_row", root, "v_result", "v_root_version"),
38704
38769
  ...creator === void 0 ? ["v_member := NULL;"] : visible(creator.member, "v_member_row", "p_member_id", "v_member", "v_member_version"),
38705
38770
  ...creator === void 0 ? [] : parts.signal("v_in", signalOp("create"), "v_root_version::bigint"),
@@ -38715,16 +38780,16 @@ function createRootFunction(contract, fn, action, parts, creator) {
38715
38780
  function markDeletionFunction(contract, fn, action, parts) {
38716
38781
  const { table, key } = contract;
38717
38782
  const root = "p_id";
38718
- const mark = q$3(standardColumn(table, deletionMarkColumn(), parts.facts.attributeCase).name);
38783
+ const mark = q$4(standardColumn(table, deletionMarkColumn(), parts.facts.attributeCase).name);
38719
38784
  const coupled = must$1(parts.facts.rights.actions.find((a) => a.action === action)).coupled;
38720
38785
  const couple = coupled === void 0 ? void 0 : {
38721
- column: q$3(coupled.column),
38786
+ column: q$4(coupled.column),
38722
38787
  value: sqlLiteral(coupled.value)
38723
38788
  };
38724
38789
  const changed = /* @__PURE__ */ new Set([
38725
38790
  mark,
38726
38791
  ...couple === void 0 ? [] : [couple.column],
38727
- ...parts.updatedBy === void 0 ? [] : [q$3(parts.updatedBy)]
38792
+ ...parts.updatedBy === void 0 ? [] : [q$4(parts.updatedBy)]
38728
38793
  ]);
38729
38794
  return coreFunction(fn, "p_id uuid, p_expected_version bigint, p_mark boolean", [
38730
38795
  "v_old record;",
@@ -38742,14 +38807,14 @@ function markDeletionFunction(contract, fn, action, parts) {
38742
38807
  "v_new := v_old;",
38743
38808
  `v_new.${mark} := p_mark;`,
38744
38809
  ...couple === void 0 ? [] : [`v_new.${couple.column} := ${couple.value};`],
38745
- ...parts.updatedBy === void 0 ? [] : [`v_new.${q$3(parts.updatedBy)} := ${CURRENT_USER$1};`],
38746
- ...parts.relink(contract.carrierLinks.filter((link) => link.pairs.some((p) => changed.has(q$3(p.local))))),
38810
+ ...parts.updatedBy === void 0 ? [] : [`v_new.${q$4(parts.updatedBy)} := ${CURRENT_USER$1};`],
38811
+ ...parts.relink(contract.carrierLinks.filter((link) => link.pairs.some((p) => changed.has(q$4(p.local))))),
38747
38812
  ...parts.rightsIf(action, "update", "v_new", E.forbidden.newCarrier),
38748
- ...contract.predefinedColumn === void 0 ? [] : ifThen(`v_old.${q$3(contract.predefinedColumn)} IS NOT NULL`, [invalid(sqlLiteral(E.invalid.predefined))]),
38749
- `UPDATE ${relation$1(table)} SET ${mark} = p_mark${couple === void 0 ? "" : `, ${couple.column} = ${couple.value}`} WHERE ${q$3(key)} = ${root} RETURNING * INTO v_row;`,
38813
+ ...contract.predefinedColumn === void 0 ? [] : ifThen(`v_old.${q$4(contract.predefinedColumn)} IS NOT NULL`, [invalid(sqlLiteral(E.invalid.predefined))]),
38814
+ `UPDATE ${relation$2(table)} SET ${mark} = p_mark${couple === void 0 ? "" : `, ${couple.column} = ${couple.value}`} WHERE ${q$4(key)} = ${root} RETURNING * INTO v_row;`,
38750
38815
  "GET DIAGNOSTICS v_count = ROW_COUNT;",
38751
38816
  ...ifThen("v_count = 0", [noRight]),
38752
- ...parts.signal("v_row", signalOp("markDeletion"), `v_row.${q$3(contract.versionColumn)}`),
38817
+ ...parts.signal("v_row", signalOp("markDeletion"), `v_row.${q$4(contract.versionColumn)}`),
38753
38818
  ...resultLines(contract, root, false)
38754
38819
  ]);
38755
38820
  }
@@ -38766,13 +38831,13 @@ function publicationFunction(contract, fn, action, publish, parts) {
38766
38831
  const { table, key } = contract;
38767
38832
  const root = "p_id";
38768
38833
  const rights = must$1(parts.facts.rights.actions.find((a) => a.action === action));
38769
- const published = q$3(must$1(rights.transition).column);
38834
+ const published = q$4(must$1(rights.transition).column);
38770
38835
  const marked = rights.coupled === void 0 ? void 0 : {
38771
- column: q$3(rights.coupled.column),
38836
+ column: q$4(rights.coupled.column),
38772
38837
  allowed: sqlLiteral(rights.coupled.value)
38773
38838
  };
38774
38839
  const value = sqlLiteral(publish);
38775
- const changed = /* @__PURE__ */ new Set([published, ...parts.updatedBy === void 0 ? [] : [q$3(parts.updatedBy)]]);
38840
+ const changed = /* @__PURE__ */ new Set([published, ...parts.updatedBy === void 0 ? [] : [q$4(parts.updatedBy)]]);
38776
38841
  return coreFunction(fn, "p_id uuid, p_expected_version bigint", [
38777
38842
  "v_old record;",
38778
38843
  "v_new record;",
@@ -38788,13 +38853,13 @@ function publicationFunction(contract, fn, action, publish, parts) {
38788
38853
  ...marked === void 0 ? [] : ifThen(`v_old.${marked.column} IS DISTINCT FROM ${marked.allowed}`, [invalid(sqlLiteral(E.invalid.marked))]),
38789
38854
  "v_new := v_old;",
38790
38855
  `v_new.${published} := ${value};`,
38791
- ...parts.updatedBy === void 0 ? [] : [`v_new.${q$3(parts.updatedBy)} := ${CURRENT_USER$1};`],
38792
- ...parts.relink(contract.carrierLinks.filter((link) => link.pairs.some((p) => changed.has(q$3(p.local))))),
38856
+ ...parts.updatedBy === void 0 ? [] : [`v_new.${q$4(parts.updatedBy)} := ${CURRENT_USER$1};`],
38857
+ ...parts.relink(contract.carrierLinks.filter((link) => link.pairs.some((p) => changed.has(q$4(p.local))))),
38793
38858
  ...parts.rightsIf(action, "update", "v_new", E.forbidden.newCarrier),
38794
- `UPDATE ${relation$1(table)} SET ${published} = ${value} WHERE ${q$3(key)} = ${root} RETURNING * INTO v_row;`,
38859
+ `UPDATE ${relation$2(table)} SET ${published} = ${value} WHERE ${q$4(key)} = ${root} RETURNING * INTO v_row;`,
38795
38860
  "GET DIAGNOSTICS v_count = ROW_COUNT;",
38796
38861
  ...ifThen("v_count = 0", [noRight]),
38797
- ...parts.signal("v_row", signalOp("update"), `v_row.${q$3(contract.versionColumn)}`),
38862
+ ...parts.signal("v_row", signalOp("update"), `v_row.${q$4(contract.versionColumn)}`),
38798
38863
  ...resultLines(contract, root, false)
38799
38864
  ]);
38800
38865
  }
@@ -38809,17 +38874,17 @@ function publicationFunction(contract, fn, action, publish, parts) {
38809
38874
  function deleteFunction(contract, fn, action, parts) {
38810
38875
  const { table, key, scopeColumn } = contract;
38811
38876
  const root = "p_id";
38812
- const scope = scopeColumn === void 0 || scopeColumn === key ? "" : `, ${sqlLiteral(scopeColumn)}, v_old.${q$3(scopeColumn)}`;
38877
+ const scope = scopeColumn === void 0 || scopeColumn === key ? "" : `, ${sqlLiteral(scopeColumn)}, v_old.${q$4(scopeColumn)}`;
38813
38878
  return coreFunction(fn, "p_id uuid, p_expected_version bigint", ["v_old record;", "v_count bigint;"], [
38814
38879
  ...ifThen("p_expected_version IS NULL", [invalid(sqlLiteral(E.invalid.expectedVersion))]),
38815
38880
  ...parts.context(action, root),
38816
38881
  ...parts.lockedOld(root, "UPDATE"),
38817
38882
  ...parts.rightsIf(action, "delete", "v_old", E.forbidden.noRight),
38818
- `DELETE FROM ${relation$1(table)} WHERE ${q$3(key)} = ${root};`,
38883
+ `DELETE FROM ${relation$2(table)} WHERE ${q$4(key)} = ${root};`,
38819
38884
  "GET DIAGNOSTICS v_count = ROW_COUNT;",
38820
38885
  ...ifThen("v_count = 0", [noRight]),
38821
- ...parts.signal("v_old", signalOp("delete"), `v_old.${q$3(contract.versionColumn)}`),
38822
- `RETURN jsonb_build_object(${sqlLiteral(key)}, ${root}, ${sqlLiteral(contract.versionColumn)}, v_old.${q$3(contract.versionColumn)}::text${scope})::text;`
38886
+ ...parts.signal("v_old", signalOp("delete"), `v_old.${q$4(contract.versionColumn)}`),
38887
+ `RETURN jsonb_build_object(${sqlLiteral(key)}, ${root}, ${sqlLiteral(contract.versionColumn)}, v_old.${q$4(contract.versionColumn)}::text${scope})::text;`
38823
38888
  ]);
38824
38889
  }
38825
38890
  /**
@@ -38840,12 +38905,12 @@ function invitationIssueFunction(contract, invitation, parts) {
38840
38905
  const m = invitation.facts.membership;
38841
38906
  const statements = [
38842
38907
  ...parts.context(action, root),
38843
- `SELECT * INTO v_old FROM ${relation$1(table)} r WHERE r.${q$3(key)} = ${root} FOR NO KEY UPDATE;`,
38908
+ `SELECT * INTO v_old FROM ${relation$2(table)} r WHERE r.${q$4(key)} = ${root} FOR NO KEY UPDATE;`,
38844
38909
  ...ifThen("NOT FOUND", [noRight]),
38845
38910
  ...parts.rightsIf(action, "update", "v_old", E.forbidden.noRight),
38846
- ...ifThen([`v_old.${q$3(m.user)} IS NOT NULL`, ...m.deletion === void 0 ? [] : [`v_old.${q$3(m.deletion)}`]].join(" OR "), [`RAISE EXCEPTION USING ERRCODE = '${E.invitationNotPending.errcode}', MESSAGE = '${E.invitationNotPending.message}';`]),
38847
- ...ifThen(`NOT ${scopeAdministerRights(invitation.facts.assignmentsLabel, invitation.facts.kindId, `v_old.${q$3(m.scope)}`)}`, [noRight]),
38848
- `RETURN jsonb_build_object('expiresAt', ${relation$1(INVITATION_PUT_FUNCTION)}(${root}, p_hash))::text;`
38911
+ ...ifThen([`v_old.${q$4(m.user)} IS NOT NULL`, ...m.deletion === void 0 ? [] : [`v_old.${q$4(m.deletion)}`]].join(" OR "), [`RAISE EXCEPTION USING ERRCODE = '${E.invitationNotPending.errcode}', MESSAGE = '${E.invitationNotPending.message}';`]),
38912
+ ...ifThen(`NOT ${scopeAdministerRights(invitation.facts.assignmentsLabel, invitation.facts.kindId, `v_old.${q$4(m.scope)}`)}`, [noRight]),
38913
+ `RETURN jsonb_build_object('expiresAt', ${relation$2(INVITATION_PUT_FUNCTION)}(${root}, p_hash))::text;`
38849
38914
  ];
38850
38915
  return coreFunction(invitationIssueFunctionName(table), "p_member uuid, p_hash bytea", ["v_old record;"], statements);
38851
38916
  }
@@ -39087,10 +39152,19 @@ function branchesOf(input) {
39087
39152
  };
39088
39153
  }
39089
39154
  /**
39155
+ * Відмова права: код, повідомлення й причина з переліку T0, а `hint` — мітка
39156
+ * виду, на якому бракує права (тригер переприв'язування, спека прав
39157
+ * контейнера §2). Один будівник для `rights_require` і тригера, тож форма
39158
+ * відмови не розійдеться. Мітка — не дані рядка (Рт4).
39159
+ */
39160
+ function rightsRefusal(error, detail, hint) {
39161
+ return `RAISE EXCEPTION USING ERRCODE = '${error.errcode}', MESSAGE = '${error.message}', DETAIL = '${detail}'` + (hint === void 0 ? "" : `, HINT = ${sqlLiteral(hint)}`) + ";";
39162
+ }
39163
+ /**
39090
39164
  * Відмова одна: невідома пара, немає права, немає рядка й `NULL` не
39091
39165
  * розрізняються (оракул наявності рядків не відкривається).
39092
39166
  */
39093
- const REFUSAL = `RAISE EXCEPTION USING ERRCODE = '${RIGHTS_REQUIRE_ERROR.errcode}', MESSAGE = '${RIGHTS_REQUIRE_ERROR.message}', DETAIL = '${RIGHTS_REQUIRE_ERROR.noRight}';`;
39167
+ const REFUSAL = rightsRefusal(RIGHTS_REQUIRE_ERROR, RIGHTS_REQUIRE_ERROR.noRight);
39094
39168
  function requireFunction(name, target, branches) {
39095
39169
  const body = [
39096
39170
  "BEGIN",
@@ -40635,7 +40709,7 @@ const ROWS = {
40635
40709
  UPDATE: ["o", "n"],
40636
40710
  DELETE: ["o"]
40637
40711
  };
40638
- const q$2 = quoteIdent;
40712
+ const q$3 = quoteIdent;
40639
40713
  const ZERO = uuidLiteral(ZERO_UUID);
40640
40714
  const KEY = keyColumn(false);
40641
40715
  const nameOf = (table) => ({
@@ -40668,7 +40742,7 @@ function memberUsers(contracts, scopeKindId, from, subject) {
40668
40742
  }))];
40669
40743
  if (members.length === 0) throw new Error(`internal: no members of scope kind ${scopeKindId}`);
40670
40744
  return {
40671
- selects: members.map((m) => `SELECT m.${q$2(m.user)} AS user_id FROM ${from} JOIN ${qualified(m.table)} m ON m.${q$2(m.key)} = ${subject}`),
40745
+ selects: members.map((m) => `SELECT m.${q$3(m.user)} AS user_id FROM ${from} JOIN ${qualified(m.table)} m ON m.${q$3(m.key)} = ${subject}`),
40672
40746
  reads: members.map((m) => m.table)
40673
40747
  };
40674
40748
  }
@@ -40679,7 +40753,7 @@ function definitionShape(table, level) {
40679
40753
  return {
40680
40754
  reads: [],
40681
40755
  channels: (operation) => ({
40682
- scopes: ROWS[operation].map((a) => level.level === "scope" ? `SELECT ${uuidLiteral(level.scopeKindId)} AS scope_kind, ${a}.${q$2(scope)} AS scope FROM ${FROM[a]}` : `SELECT ${ZERO} AS scope_kind, ${ZERO} AS scope FROM ${FROM[a]}`),
40756
+ scopes: ROWS[operation].map((a) => level.level === "scope" ? `SELECT ${uuidLiteral(level.scopeKindId)} AS scope_kind, ${a}.${q$3(scope)} AS scope FROM ${FROM[a]}` : `SELECT ${ZERO} AS scope_kind, ${ZERO} AS scope FROM ${FROM[a]}`),
40683
40757
  users: []
40684
40758
  })
40685
40759
  };
@@ -40706,7 +40780,7 @@ function shapesOf(table, input) {
40706
40780
  channels: (operation) => ({
40707
40781
  scopes: [],
40708
40782
  users: ROWS[operation].flatMap((a) => {
40709
- const found = assignmentUsers(contracts, catalog.level, FROM[a], `${a}.${q$2(subject)}`);
40783
+ const found = assignmentUsers(contracts, catalog.level, FROM[a], `${a}.${q$3(subject)}`);
40710
40784
  reads.push(...found.reads);
40711
40785
  return found.selects;
40712
40786
  })
@@ -40718,14 +40792,14 @@ function shapesOf(table, input) {
40718
40792
  reads: [],
40719
40793
  channels: (operation) => ({
40720
40794
  scopes: [],
40721
- users: ROWS[operation].map((a) => `SELECT ${a}.${q$2(member.userColumn)} AS user_id FROM ${FROM[a]}`)
40795
+ users: ROWS[operation].map((a) => `SELECT ${a}.${q$3(member.userColumn)} AS user_id FROM ${FROM[a]}`)
40722
40796
  })
40723
40797
  });
40724
40798
  const users = contracts.users;
40725
40799
  if (users !== void 0 && same(users.table)) {
40726
- const key = q$2(users.keyColumn);
40727
- const invalid = q$2(users.invalidColumn);
40728
- const kind = q$2(standardColumn(table, USER_PLATFORM_COLUMNS.userKind, attributeCase).name);
40800
+ const key = q$3(users.keyColumn);
40801
+ const invalid = q$3(users.invalidColumn);
40802
+ const kind = q$3(standardColumn(table, USER_PLATFORM_COLUMNS.userKind, attributeCase).name);
40729
40803
  shapes.push({
40730
40804
  reads: [],
40731
40805
  channels: (operation) => ({
@@ -40746,7 +40820,7 @@ function shapesOf(table, input) {
40746
40820
  channels: (operation) => ({
40747
40821
  scopes: [],
40748
40822
  users: ROWS[operation].flatMap((a) => {
40749
- const subject = `${a}.${q$2(relation.subject)}`;
40823
+ const subject = `${a}.${q$3(relation.subject)}`;
40750
40824
  if ("users" in target) return [`SELECT ${subject} AS user_id FROM ${FROM[a]}`];
40751
40825
  const users = memberUsers(contracts, target.membership, FROM[a], subject);
40752
40826
  reads.push(...users.reads);
@@ -40766,13 +40840,13 @@ function shapesOf(table, input) {
40766
40840
  */
40767
40841
  function containerShape(table, scopeKindId, input) {
40768
40842
  const { contracts, physical, attributeCase } = input;
40769
- const key = q$2(standardColumn(table, KEY, attributeCase).name);
40843
+ const key = q$3(standardColumn(table, KEY, attributeCase).name);
40770
40844
  const scope = scopeKindId === void 0 ? void 0 : scopeColumnOf(table);
40771
40845
  const changed = (operation) => {
40772
40846
  if (operation === "INSERT") return `SELECT n.${key} AS container FROM new_rows n`;
40773
40847
  if (operation === "DELETE") return `SELECT o.${key} AS container FROM old_rows o`;
40774
40848
  if (scope === void 0) return void 0;
40775
- return `SELECT n.${key} AS container FROM old_rows o JOIN new_rows n ON n.${key} = o.${key} WHERE o.${q$2(scope)} IS DISTINCT FROM n.${q$2(scope)}`;
40849
+ return `SELECT n.${key} AS container FROM old_rows o JOIN new_rows n ON n.${key} = o.${key} WHERE o.${q$3(scope)} IS DISTINCT FROM n.${q$3(scope)}`;
40776
40850
  };
40777
40851
  const reads = [];
40778
40852
  return {
@@ -40790,7 +40864,7 @@ function containerShape(table, scopeKindId, input) {
40790
40864
  const subject = standardColumn(assignments, RIGHTS_COLUMNS.subject, attributeCase).name;
40791
40865
  const container = standardColumn(assignments, RIGHTS_COLUMNS.container, attributeCase).name;
40792
40866
  reads.push(catalog.assignments.table);
40793
- const users = assignmentUsers(contracts, catalog.level, `(${containers}) c JOIN ${qualified(catalog.assignments.table)} a ON a.${q$2(container)} = c.container`, `a.${q$2(subject)}`);
40867
+ const users = assignmentUsers(contracts, catalog.level, `(${containers}) c JOIN ${qualified(catalog.assignments.table)} a ON a.${q$3(container)} = c.container`, `a.${q$3(subject)}`);
40794
40868
  reads.push(...users.reads);
40795
40869
  return users.selects;
40796
40870
  })
@@ -40886,7 +40960,7 @@ function buildRightsSignalUnits(input) {
40886
40960
  const names = rightsSignalTriggerNames(table);
40887
40961
  for (const { operation } of operations) {
40888
40962
  const trigger = names.find((n) => n.operation === operation).trigger;
40889
- add(`CREATE TRIGGER ${q$2(trigger)} AFTER ${operation} ON ${qualified(nameOf(table))} ${TRANSITION[operation]} FOR EACH STATEMENT EXECUTE FUNCTION ${qualified(fn)}();`, owner);
40963
+ add(`CREATE TRIGGER ${q$3(trigger)} AFTER ${operation} ON ${qualified(nameOf(table))} ${TRANSITION[operation]} FOR EACH STATEMENT EXECUTE FUNCTION ${qualified(fn)}();`, owner);
40890
40964
  }
40891
40965
  }
40892
40966
  return {
@@ -41004,6 +41078,90 @@ function keyFunction(fn) {
41004
41078
  const tag = dollarTag$1(text);
41005
41079
  return `CREATE OR REPLACE FUNCTION ${fn}()\nRETURNS trigger\nLANGUAGE plpgsql SECURITY INVOKER\nSET search_path = ''\nAS ${tag}\n${text}\n${tag};`;
41006
41080
  }
41081
+ // src/compiler/rights/rebind-units.ts
41082
+ const q$2 = quoteIdent;
41083
+ const relation$1 = (t) => `${q$2(t.schema)}.${q$2(t.name)}`;
41084
+ /** Дія, право на яку переприв'язування вимагає на кожен вид-нащадок. */
41085
+ const REBIND_ACTION = "update";
41086
+ /** Вузол `requires` платформної функції за ім'ям і типами аргументів. */
41087
+ const functionNode = (fn, types) => ({
41088
+ type: "unit",
41089
+ identity: keyIdentity("function", functionKey(fn.schema, fn.name, types))
41090
+ });
41091
+ /**
41092
+ * Генератор переприв'язування (спека прав контейнера §2, Р-К1-8): на
41093
+ * основній таблиці кожного виду з ланцюжковими нащадками — `AFTER UPDATE`
41094
+ * тригер, що вимагає права `update` в обсязі `any` на кожен вид-нащадок і в
41095
+ * контейнері «до», і в контейнері «після»: зміна прив'язки рядка переносить
41096
+ * усіх його нащадків. Лише з функціями прав, як і тригер ефектів. Тіло
41097
+ * plpgsql граф не читає, тож функції тіла — явні ребра `requires`.
41098
+ */
41099
+ function buildRebindUnits(input) {
41100
+ const { contracts, physical, provider, module, parse } = input;
41101
+ if (!hasRightsFunctions(contracts, provider)) return [];
41102
+ const rightsById = new Map(contracts.rights.map((c) => [c.objectId, c]));
41103
+ const F = RIGHTS_FUNCTIONS;
41104
+ const units = [];
41105
+ for (const [sourceId, ids] of bindingDescendants(input.bindings)) {
41106
+ const binding = must$9(must$9(rightsById.get(sourceId)).binding);
41107
+ const table = must$9(mainTableOf(physical, sourceId));
41108
+ const descendants = ids.map((id) => must$9(rightsById.get(id))).sort((a, b) => compareStrings(a.kindLabel, b.kindLabel));
41109
+ const unit = (sql, requires) => ({
41110
+ ...generatedUnit(sql, table.schema, parse),
41111
+ ownerObjectId: sourceId,
41112
+ module,
41113
+ generator: "carriers",
41114
+ ...requires === void 0 ? {} : { requires }
41115
+ });
41116
+ const fn = carrierFunctionNames(table).rebind;
41117
+ const requires = [
41118
+ functionNode(COMMAND_FUNCTIONS.current, []),
41119
+ functionNode(F.any, ["text", "text"]),
41120
+ functionNode(F.container, [
41121
+ "text",
41122
+ "text",
41123
+ "text",
41124
+ "uuid"
41125
+ ]),
41126
+ ...descendants.some((d) => d.scopeKindId === void 0) ? [functionNode(F.hasRight, [
41127
+ "text",
41128
+ "text",
41129
+ "text",
41130
+ "uuid"
41131
+ ])] : []
41132
+ ];
41133
+ const when = [.../* @__PURE__ */ new Set([binding.carrier.column, binding.carrier.value])].map((c) => `(OLD.${q$2(c)} IS DISTINCT FROM NEW.${q$2(c)})`).join(" AND ");
41134
+ units.push(unit(definerTrigger(fn, rebindBody(table, binding.carrier.value, descendants)), requires), ...executeGrants(`${relation$1(fn)}()`, [], provider).map((sql) => unit(sql)), unit(`CREATE TRIGGER ${q$2(carrierTriggerNames(table).rebind)} AFTER UPDATE ON ${relation$1(table)} FOR EACH ROW WHEN (${when}) EXECUTE FUNCTION ${relation$1(fn)}();`));
41135
+ }
41136
+ return units.sort((a, b) => compareStrings(a.identity, b.identity));
41137
+ }
41138
+ /**
41139
+ * Тіло переприв'язування. Поза контекстом команди (режим обслуговування,
41140
+ * крок даних плану) не судить — до жодного виклику функцій прав. Сторона —
41141
+ * контейнер рядка з правом чи скоуп рядка з правом рівня скоупу; порожня
41142
+ * прив'язка дає `NULL = ANY(…)`, тож лишається право рівня скоупу, а
41143
+ * `IS NOT TRUE` відмовляє й на `NULL`. Права — початку транзакції: функції
41144
+ * фактів під контекстом читають знімок актора.
41145
+ */
41146
+ function rebindBody(table, carrier, descendants) {
41147
+ const scopeOf = (d) => d.scopeKindId === void 0 ? void 0 : must$9(table.columns.find((c) => c.origin.scopeKindId === d.scopeKindId)).name;
41148
+ const body = [
41149
+ "DECLARE",
41150
+ " v_action text;",
41151
+ "BEGIN",
41152
+ ` SELECT c.action INTO v_action FROM ${relation$1(COMMAND_FUNCTIONS.current)}() AS c;`,
41153
+ " IF v_action IS NULL THEN",
41154
+ " RETURN NULL;",
41155
+ " END IF;"
41156
+ ];
41157
+ for (const descendant of descendants) {
41158
+ const grants = anyGrants(descendant, REBIND_ACTION, carrier, scopeOf(descendant));
41159
+ const side = (row) => `(${renderCondition(grants.container, row)} OR ${renderCondition(grants.scope, row)})`;
41160
+ body.push(` IF (${side("OLD")} AND ${side("NEW")}) IS NOT TRUE THEN`, ` ${rightsRefusal(COMMAND_CORE_ERRORS.forbidden, COMMAND_CORE_ERRORS.forbidden.noRight, descendant.kindLabel)}`, " END IF;");
41161
+ }
41162
+ body.push(" RETURN NULL;", "END");
41163
+ return body.join("\n");
41164
+ }
41007
41165
  // src/compiler/rights/effects-units.ts
41008
41166
  const q$1 = quoteIdent;
41009
41167
  const relation = (t) => `${q$1(t.schema)}.${q$1(t.name)}`;
@@ -42546,6 +42704,19 @@ async function runStages(stage1, options = {}) {
42546
42704
  ...buildLanguageStateUnits(physical, stage1.objects, stage1.project.naming.attributeCase, stage1.project.database.provider, module, parse),
42547
42705
  ...buildSubscriptionUnits(eventSubscriptions, physical, stage1.project.naming.attributeCase, module, parse),
42548
42706
  ...buildCarrierUnits(physical, stage1.project.naming.attributeCase, stage1.project.database.provider, module, parse),
42707
+ ...buildRebindUnits({
42708
+ contracts: {
42709
+ rights,
42710
+ roles,
42711
+ users,
42712
+ membershipSources: sources.membershipSources
42713
+ },
42714
+ bindings: stage3.bindings,
42715
+ physical,
42716
+ provider: stage1.project.database.provider,
42717
+ module,
42718
+ parse
42719
+ }),
42549
42720
  ...buildRightsUnits(rightsInputs, physical, stage1.project.naming.attributeCase, stage1.project.database.provider, module, parse),
42550
42721
  ...buildExplainUnits({
42551
42722
  ...rightsInputs,
@@ -43368,6 +43539,7 @@ function platformTriggers(table) {
43368
43539
  entry("carriers", "carriers", carrierFns.derive, carriers.derive),
43369
43540
  entry("carriers", "carriers", carrierFns.propagate, carriers.propagate),
43370
43541
  entry("carriers", "carriers", carrierFns.propagate, carriers.propagateInsert),
43542
+ entry("carriers", "carriers", carrierFns.rebind, carriers.rebind),
43371
43543
  entry("hierarchy", "mechanics", hierarchy.fn, hierarchy.insert),
43372
43544
  entry("hierarchy", "mechanics", hierarchy.fn, hierarchy.update),
43373
43545
  entry("languageState", "mechanics", language.fn, language.row),
@@ -43829,6 +44001,7 @@ function buildClientCatalog(runtime) {
43829
44001
  snapshotHash: runtime.snapshotHash,
43830
44002
  provider: runtime.provider,
43831
44003
  ...present("rightsSnapshot", runtime.rightsSnapshot),
44004
+ ...present("invitations", runtime.invitations),
43832
44005
  ...present("adoptedFacts", runtime.adoptedFacts),
43833
44006
  ...present("roles", runtime.roles),
43834
44007
  ...present("rightsSets", runtime.rightsSets),