@aglyn/plugins-logic 1.0.0-beta.285 → 1.0.0-beta.288

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/plugins-logic",
3
- "version": "1.0.0-beta.285",
3
+ "version": "1.0.0-beta.288",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,13 +25,13 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.0.0-beta.285",
29
- "@aglyn/shared-data-mdi": "1.0.0-beta.285",
30
- "@aglyn/shared-ui-jsx": "1.0.0-beta.285",
31
- "@aglyn/shared-ui-snackstack": "1.0.0-beta.285",
32
- "@aglyn/shared-util-timestamp": "1.0.0-beta.285",
33
- "@aglyn/tenant-data-admin": "1.0.0-beta.285",
34
- "@aglyn/tenant-feature-instance": "1.0.0-beta.285",
28
+ "@aglyn/aglyn": "1.0.0-beta.288",
29
+ "@aglyn/shared-data-mdi": "1.0.0-beta.288",
30
+ "@aglyn/shared-ui-jsx": "1.0.0-beta.288",
31
+ "@aglyn/shared-ui-snackstack": "1.0.0-beta.288",
32
+ "@aglyn/shared-util-timestamp": "1.0.0-beta.288",
33
+ "@aglyn/tenant-data-admin": "1.0.0-beta.288",
34
+ "@aglyn/tenant-feature-instance": "1.0.0-beta.288",
35
35
  "@swc/helpers": "0.5.23"
36
36
  },
37
37
  "peerDependencies": {
@@ -55,7 +55,8 @@ import type { PluginResourceDraftWriter } from '@aglyn/aglyn/plugin-manager/plug
55
55
  */
56
56
  type Firestore = FirebaseFirestore.Firestore;
57
57
  /** The resources route's refusal for a member who may not write the site. */
58
- export declare const LOGIC_DRAFT_ROLE_REFUSAL = "Editing requires the editor role";
58
+ /** Names "Edit site content" (`site.edit`, AGL-4047), never a role. */
59
+ export declare const LOGIC_DRAFT_ROLE_REFUSAL: string;
59
60
  /** The resources route's refusal at the plan's allowance. */
60
61
  export declare function logicDraftLimitRefusal(noun: 'variable' | 'function', limit: number): string;
61
62
  /** The refusal for a name a live record of the kind already carries. */
@@ -14,12 +14,12 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
14
14
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
15
  * See the License for the specific language governing permissions and
16
16
  * limitations under the License.
17
- */ import { hostRoleCanWrite } from "@aglyn/aglyn/app-utils/organizations";
18
- import { checkQuota } from "@aglyn/aglyn/app-utils/plan-entitlements";
17
+ */ import { checkQuota } from "@aglyn/aglyn/app-utils/plan-entitlements";
18
+ import { holdsSiteKey, siteKeyRefusal } from "@aglyn/aglyn/app-utils/host-permissions";
19
19
  import { countLiveDocuments, isLiveDocument } from "@aglyn/aglyn/app-utils/live-document-count";
20
20
  import { firebaseAdmin } from "@aglyn/tenant-data-admin";
21
21
  import { checkFunctionDraftContent, checkVariableDraftContent, functionDraftFacts, logicNameKey, readFunctionDraftContent, readVariableDraftContent, variableDraftFacts } from "./logic-draft-content.js";
22
- /** The resources route's refusal for a member who may not write the site. */ export const LOGIC_DRAFT_ROLE_REFUSAL = 'Editing requires the editor role';
22
+ /** The resources route's refusal for a member who may not write the site. */ /** Names "Edit site content" (`site.edit`, AGL-4047), never a role. */ export const LOGIC_DRAFT_ROLE_REFUSAL = siteKeyRefusal('site.edit');
23
23
  /** The resources route's refusal at the plan's allowance. */ export function logicDraftLimitRefusal(noun, limit) {
24
24
  return `Your plan includes ${limit} ${limit === 1 ? noun : `${noun}s`} — upgrade in Billing for more`;
25
25
  }
@@ -27,9 +27,7 @@ import { checkFunctionDraftContent, checkVariableDraftContent, functionDraftFact
27
27
  return `This site already has a ${noun} named ${name}. Choose another name.`;
28
28
  }
29
29
  function roleRefusal(host, uid) {
30
- var _host_get;
31
- const role = ((_host_get = host.get('memberRoles')) != null ? _host_get : {})[uid];
32
- return hostRoleCanWrite(role) ? null : {
30
+ return holdsSiteKey(host, uid, 'site.edit') ? null : {
33
31
  status: 403,
34
32
  error: LOGIC_DRAFT_ROLE_REFUSAL
35
33
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/logic/src/lib/server/logic-drafts.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { hostRoleCanWrite } from '@aglyn/aglyn/app-utils/organizations'\nimport { checkQuota } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { countLiveDocuments, isLiveDocument } from '@aglyn/aglyn/app-utils/live-document-count'\nimport type {\n PluginDraftCheck,\n PluginDraftContext,\n PluginDraftRecord,\n PluginDraftRefusal,\n PluginDraftWrite,\n PluginResourceDraftWriter,\n} from '@aglyn/aglyn/plugin-manager/plugin-resource-drafts'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport {\n checkFunctionDraftContent,\n checkVariableDraftContent,\n functionDraftFacts,\n type LogicDraftRead,\n logicNameKey,\n readFunctionDraftContent,\n readVariableDraftContent,\n variableDraftFacts,\n} from './logic-draft-content'\n\n/**\n * A VARIABLE OR A FUNCTION ANOTHER PLUGIN ASKS FOR (AGL-3616).\n *\n * The draft writers this plugin registers for the `variable` and `function`\n * resources on the core's resource-drafts seam. An AI build that sets a site\n * up from a brief asks for one by name and gets this plugin's rules:\n *\n * - THE DOCUMENT is the one the Variables and Functions cards create through\n * `/api/hosts/resources`: the fields the plugin declares for the kind in\n * `plugins.config.json`, stamped `createdAt`, `updatedAt` and `createdBy`.\n * A variable is never computed here (`workflowId` and `workflowName` are\n * empty, as the card writes a plain one).\n * - THE ROLE is a member who may write the site's content, refused in the\n * resources route's words. THE ROOM is `variablesPerHost` or\n * `functionsPerHost`, counted as that route counts it — every document in\n * the collection — inside the transaction that creates. Logic carries no\n * plan feature of its own: the Free plan has three variables and one\n * function.\n * - THE NAME is held to the binding grammar (`logic-draft-content.ts`) and\n * must be free: no LIVE record of the kind on the site carries it, compared\n * case-insensitively as both cards compare it. A taken name is REFUSED,\n * never overwritten and never renumbered — a binding names what it reads,\n * so a variable quietly called `price_2` is one no page asked for.\n *\n * ## Draft by default, without a draft state\n *\n * Neither resource has one: a variable or a function is live the moment it\n * exists. It is still a draft in every sense the seam means, because a NEW,\n * UNREFERENCED variable or function changes nothing a visitor sees. A page\n * shows a variable only where a binding names its id (`{{var:id}}`) and runs\n * a function only where a token or a Function Widget names it, and nothing\n * names a document that did not exist a moment ago. What a person reviews is\n * the record itself, on the Logic page, before anything binds it.\n *\n * Asked again under the same id, the writer reports the record it already\n * wrote and writes nothing. Nothing is published, and the writer touches the\n * one new document.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** The resources route's refusal for a member who may not write the site. */\nexport const LOGIC_DRAFT_ROLE_REFUSAL = 'Editing requires the editor role'\n\n/** The resources route's refusal at the plan's allowance. */\nexport function logicDraftLimitRefusal(noun: 'variable' | 'function', limit: number): string {\n return `Your plan includes ${limit} ${limit === 1 ? noun : `${noun}s`} — upgrade in Billing for more`\n}\n\n/** The refusal for a name a live record of the kind already carries. */\nexport function logicDraftNameTaken(noun: 'variable' | 'function', name: string): string {\n return `This site already has a ${noun} named ${name}. Choose another name.`\n}\n\n/** How one kind differs from the other. */\ninterface LogicDraftKind<T extends { name: string }> {\n noun: 'variable' | 'function'\n collection: 'variables' | 'functions'\n quota: 'variablesPerHost' | 'functionsPerHost'\n read: (content: Readonly<Record<string, unknown>>) => LogicDraftRead<T>\n check: (content: Readonly<Record<string, unknown>>) => PluginDraftCheck\n facts: (document: Partial<T>) => Readonly<Record<string, unknown>>\n}\n\nexport interface LogicDraftWriterDeps {\n /** The Admin SDK handle; specs hand in a double. */\n firestore?: () => Firestore\n}\n\nfunction roleRefusal(host: FirebaseFirestore.DocumentSnapshot, uid: string): PluginDraftRefusal | null {\n const role = (host.get('memberRoles') ?? {})[uid]\n return hostRoleCanWrite(role) ? null : { status: 403, error: LOGIC_DRAFT_ROLE_REFUSAL }\n}\n\nfunction createLogicDraftWriter<T extends { name: string }>(\n kind: LogicDraftKind<T>,\n deps: LogicDraftWriterDeps,\n): PluginResourceDraftWriter {\n const firestore = deps.firestore ?? (() => firebaseAdmin.app().firestore() as unknown as Firestore)\n const roomRefusal = (org: PluginDraftContext['org'], used: number): PluginDraftRefusal | null => {\n const quota = checkQuota(org as never, kind.quota, used)\n return quota.allowed ? null : { status: 403, error: logicDraftLimitRefusal(kind.noun, quota.limit) }\n }\n const recordOf = (snapshot: FirebaseFirestore.DocumentSnapshot): PluginDraftRecord => {\n const data = (snapshot.data() ?? {}) as Partial<T>\n return { id: snapshot.id, name: String(data.name ?? ''), versionId: null, facts: kind.facts(data) }\n }\n return {\n refusal: async (context) => {\n const hostRef = firestore().collection('hosts').doc(context.hostId)\n const host = await hostRef.get()\n if (!host.exists) return { status: 404, error: 'Unknown site' }\n const role = roleRefusal(host, context.uid)\n if (role) return role\n const used = await countLiveDocuments(hostRef.collection(kind.collection))\n return roomRefusal(context.org, Number(used) || 0)\n },\n\n check: (content) => kind.check(content),\n\n read: async ({ hostId, id }) => {\n const snapshot = await firestore().collection('hosts').doc(hostId).collection(kind.collection).doc(id).get()\n return snapshot.exists ? recordOf(snapshot) : null\n },\n\n write: async (request): Promise<PluginDraftWrite> => {\n // The content's name is the one a binding reads; the request's stands\n // in only where the content carries none.\n const named = typeof request.content['name'] === 'string' && request.content['name'].trim()\n const read = kind.read(named ? request.content : { ...request.content, name: request.name })\n if (read.ok === false) return { ok: false, status: 400, error: read.problems[0] }\n const document = read.value\n const db = firestore()\n const hostRef = db.collection('hosts').doc(request.hostId)\n const records = hostRef.collection(kind.collection)\n const ref = records.doc(request.id)\n return db.runTransaction(async (tx): Promise<PluginDraftWrite> => {\n // Every read before any write, which Firestore requires.\n const [host, existing] = await Promise.all([tx.get(hostRef), tx.get(ref)])\n if (!host.exists) return { ok: false, status: 404, error: 'Unknown site' }\n // Asked again under the same id: the record it already wrote.\n if (existing.exists) return { ok: true, replayed: true, ...recordOf(existing) }\n const role = roleRefusal(host, request.uid)\n if (role) return { ok: false, ...role }\n // One projected read answers both: the allowance and the cards'\n // name check each count the live ones, so a deleted record frees\n // its slot and its name (AGL-3918).\n const rows = (await tx.get(records.select('name', 'deletedAt'))).docs\n const room = roomRefusal(\n request.org,\n rows.filter((row) => isLiveDocument(row.get('deletedAt'))).length,\n )\n if (room) return { ok: false, ...room }\n const key = logicNameKey(document.name)\n const taken = rows.some(\n (row) => row.get('deletedAt') == null && logicNameKey(String(row.get('name') ?? '')) === key,\n )\n if (taken) return { ok: false, status: 409, error: logicDraftNameTaken(kind.noun, document.name) }\n tx.create(ref, {\n ...document,\n createdAt: request.now,\n updatedAt: request.now,\n createdBy: request.uid,\n })\n return {\n ok: true,\n replayed: false,\n id: request.id,\n name: document.name,\n versionId: null,\n facts: kind.facts(document),\n }\n })\n },\n }\n}\n\n/** The `variable` writer. */\nexport function createVariableDraftWriter(deps: LogicDraftWriterDeps = {}): PluginResourceDraftWriter {\n return createLogicDraftWriter(\n {\n noun: 'variable',\n collection: 'variables',\n quota: 'variablesPerHost',\n read: readVariableDraftContent,\n check: checkVariableDraftContent,\n facts: variableDraftFacts,\n },\n deps,\n )\n}\n\n/** The `function` writer. */\nexport function createFunctionDraftWriter(deps: LogicDraftWriterDeps = {}): PluginResourceDraftWriter {\n return createLogicDraftWriter(\n {\n noun: 'function',\n collection: 'functions',\n quota: 'functionsPerHost',\n read: readFunctionDraftContent,\n check: checkFunctionDraftContent,\n facts: functionDraftFacts,\n },\n deps,\n )\n}\n\nexport const variableDraftWriter = createVariableDraftWriter()\nexport const functionDraftWriter = createFunctionDraftWriter()\n"],"names":["hostRoleCanWrite","checkQuota","countLiveDocuments","isLiveDocument","firebaseAdmin","checkFunctionDraftContent","checkVariableDraftContent","functionDraftFacts","logicNameKey","readFunctionDraftContent","readVariableDraftContent","variableDraftFacts","LOGIC_DRAFT_ROLE_REFUSAL","logicDraftLimitRefusal","noun","limit","logicDraftNameTaken","name","roleRefusal","host","uid","role","get","status","error","createLogicDraftWriter","kind","deps","firestore","app","roomRefusal","org","used","quota","allowed","recordOf","snapshot","data","id","String","versionId","facts","refusal","context","hostRef","collection","doc","hostId","exists","Number","check","content","read","write","request","named","trim","ok","problems","document","value","db","records","ref","runTransaction","tx","existing","Promise","all","replayed","rows","select","docs","room","filter","row","length","key","taken","some","create","createdAt","now","updatedAt","createdBy","createVariableDraftWriter","createFunctionDraftWriter","variableDraftWriter","functionDraftWriter"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,QAAQ,uCAAsC;AACvE,SAASC,UAAU,QAAQ,2CAA0C;AACrE,SAASC,kBAAkB,EAAEC,cAAc,QAAQ,6CAA4C;AAS/F,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SACEC,yBAAyB,EACzBC,yBAAyB,EACzBC,kBAAkB,EAElBC,YAAY,EACZC,wBAAwB,EACxBC,wBAAwB,EACxBC,kBAAkB,QACb,2BAAuB;AA2C9B,2EAA2E,GAC3E,OAAO,MAAMC,2BAA2B,mCAAkC;AAE1E,2DAA2D,GAC3D,OAAO,SAASC,uBAAuBC,IAA6B,EAAEC,KAAa;IACjF,OAAO,CAAC,mBAAmB,EAAEA,MAAM,CAAC,EAAEA,UAAU,IAAID,OAAO,GAAGA,KAAK,CAAC,CAAC,CAAC,8BAA8B,CAAC;AACvG;AAEA,sEAAsE,GACtE,OAAO,SAASE,oBAAoBF,IAA6B,EAAEG,IAAY;IAC7E,OAAO,CAAC,wBAAwB,EAAEH,KAAK,OAAO,EAAEG,KAAK,sBA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KAAK,CAACkB;gBACpB;YACF;QACF;IACF;AACF;AAEA,2BAA2B,GAC3B,OAAO,SAAS0B,0BAA0B1D,OAA6B,CAAC,CAAC;IACvE,OAAOF,uBACL;QACEX,MAAM;QACN+B,YAAY;QACZZ,OAAO;QACPmB,MAAM1C;QACNwC,OAAO5C;QACPmC,OAAO9B;IACT,GACAgB;AAEJ;AAEA,2BAA2B,GAC3B,OAAO,SAAS2D,0BAA0B3D,OAA6B,CAAC,CAAC;IACvE,OAAOF,uBACL;QACEX,MAAM;QACN+B,YAAY;QACZZ,OAAO;QACPmB,MAAM3C;QACNyC,OAAO7C;QACPoC,OAAOlC;IACT,GACAoB;AAEJ;AAEA,OAAO,MAAM4D,sBAAsBF,4BAA2B;AAC9D,OAAO,MAAMG,sBAAsBF,4BAA2B"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/logic/src/lib/server/logic-drafts.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { checkQuota } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { holdsSiteKey, siteKeyRefusal } from '@aglyn/aglyn/app-utils/host-permissions'\nimport { countLiveDocuments, isLiveDocument } from '@aglyn/aglyn/app-utils/live-document-count'\nimport type {\n PluginDraftCheck,\n PluginDraftContext,\n PluginDraftRecord,\n PluginDraftRefusal,\n PluginDraftWrite,\n PluginResourceDraftWriter,\n} from '@aglyn/aglyn/plugin-manager/plugin-resource-drafts'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport {\n checkFunctionDraftContent,\n checkVariableDraftContent,\n functionDraftFacts,\n type LogicDraftRead,\n logicNameKey,\n readFunctionDraftContent,\n readVariableDraftContent,\n variableDraftFacts,\n} from './logic-draft-content'\n\n/**\n * A VARIABLE OR A FUNCTION ANOTHER PLUGIN ASKS FOR (AGL-3616).\n *\n * The draft writers this plugin registers for the `variable` and `function`\n * resources on the core's resource-drafts seam. An AI build that sets a site\n * up from a brief asks for one by name and gets this plugin's rules:\n *\n * - THE DOCUMENT is the one the Variables and Functions cards create through\n * `/api/hosts/resources`: the fields the plugin declares for the kind in\n * `plugins.config.json`, stamped `createdAt`, `updatedAt` and `createdBy`.\n * A variable is never computed here (`workflowId` and `workflowName` are\n * empty, as the card writes a plain one).\n * - THE ROLE is a member who may write the site's content, refused in the\n * resources route's words. THE ROOM is `variablesPerHost` or\n * `functionsPerHost`, counted as that route counts it — every document in\n * the collection — inside the transaction that creates. Logic carries no\n * plan feature of its own: the Free plan has three variables and one\n * function.\n * - THE NAME is held to the binding grammar (`logic-draft-content.ts`) and\n * must be free: no LIVE record of the kind on the site carries it, compared\n * case-insensitively as both cards compare it. A taken name is REFUSED,\n * never overwritten and never renumbered — a binding names what it reads,\n * so a variable quietly called `price_2` is one no page asked for.\n *\n * ## Draft by default, without a draft state\n *\n * Neither resource has one: a variable or a function is live the moment it\n * exists. It is still a draft in every sense the seam means, because a NEW,\n * UNREFERENCED variable or function changes nothing a visitor sees. A page\n * shows a variable only where a binding names its id (`{{var:id}}`) and runs\n * a function only where a token or a Function Widget names it, and nothing\n * names a document that did not exist a moment ago. What a person reviews is\n * the record itself, on the Logic page, before anything binds it.\n *\n * Asked again under the same id, the writer reports the record it already\n * wrote and writes nothing. Nothing is published, and the writer touches the\n * one new document.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** The resources route's refusal for a member who may not write the site. */\n/** Names \"Edit site content\" (`site.edit`, AGL-4047), never a role. */\nexport const LOGIC_DRAFT_ROLE_REFUSAL = siteKeyRefusal('site.edit')\n\n/** The resources route's refusal at the plan's allowance. */\nexport function logicDraftLimitRefusal(noun: 'variable' | 'function', limit: number): string {\n return `Your plan includes ${limit} ${limit === 1 ? noun : `${noun}s`} — upgrade in Billing for more`\n}\n\n/** The refusal for a name a live record of the kind already carries. */\nexport function logicDraftNameTaken(noun: 'variable' | 'function', name: string): string {\n return `This site already has a ${noun} named ${name}. Choose another name.`\n}\n\n/** How one kind differs from the other. */\ninterface LogicDraftKind<T extends { name: string }> {\n noun: 'variable' | 'function'\n collection: 'variables' | 'functions'\n quota: 'variablesPerHost' | 'functionsPerHost'\n read: (content: Readonly<Record<string, unknown>>) => LogicDraftRead<T>\n check: (content: Readonly<Record<string, unknown>>) => PluginDraftCheck\n facts: (document: Partial<T>) => Readonly<Record<string, unknown>>\n}\n\nexport interface LogicDraftWriterDeps {\n /** The Admin SDK handle; specs hand in a double. */\n firestore?: () => Firestore\n}\n\nfunction roleRefusal(host: FirebaseFirestore.DocumentSnapshot, uid: string): PluginDraftRefusal | null {\n return holdsSiteKey(host, uid, 'site.edit') ? null : { status: 403, error: LOGIC_DRAFT_ROLE_REFUSAL }\n}\n\nfunction createLogicDraftWriter<T extends { name: string }>(\n kind: LogicDraftKind<T>,\n deps: LogicDraftWriterDeps,\n): PluginResourceDraftWriter {\n const firestore = deps.firestore ?? (() => firebaseAdmin.app().firestore() as unknown as Firestore)\n const roomRefusal = (org: PluginDraftContext['org'], used: number): PluginDraftRefusal | null => {\n const quota = checkQuota(org as never, kind.quota, used)\n return quota.allowed ? null : { status: 403, error: logicDraftLimitRefusal(kind.noun, quota.limit) }\n }\n const recordOf = (snapshot: FirebaseFirestore.DocumentSnapshot): PluginDraftRecord => {\n const data = (snapshot.data() ?? {}) as Partial<T>\n return { id: snapshot.id, name: String(data.name ?? ''), versionId: null, facts: kind.facts(data) }\n }\n return {\n refusal: async (context) => {\n const hostRef = firestore().collection('hosts').doc(context.hostId)\n const host = await hostRef.get()\n if (!host.exists) return { status: 404, error: 'Unknown site' }\n const role = roleRefusal(host, context.uid)\n if (role) return role\n const used = await countLiveDocuments(hostRef.collection(kind.collection))\n return roomRefusal(context.org, Number(used) || 0)\n },\n\n check: (content) => kind.check(content),\n\n read: async ({ hostId, id }) => {\n const snapshot = await firestore().collection('hosts').doc(hostId).collection(kind.collection).doc(id).get()\n return snapshot.exists ? recordOf(snapshot) : null\n },\n\n write: async (request): Promise<PluginDraftWrite> => {\n // The content's name is the one a binding reads; the request's stands\n // in only where the content carries none.\n const named = typeof request.content['name'] === 'string' && request.content['name'].trim()\n const read = kind.read(named ? request.content : { ...request.content, name: request.name })\n if (read.ok === false) return { ok: false, status: 400, error: read.problems[0] }\n const document = read.value\n const db = firestore()\n const hostRef = db.collection('hosts').doc(request.hostId)\n const records = hostRef.collection(kind.collection)\n const ref = records.doc(request.id)\n return db.runTransaction(async (tx): Promise<PluginDraftWrite> => {\n // Every read before any write, which Firestore requires.\n const [host, existing] = await Promise.all([tx.get(hostRef), tx.get(ref)])\n if (!host.exists) return { ok: false, status: 404, error: 'Unknown site' }\n // Asked again under the same id: the record it already wrote.\n if (existing.exists) return { ok: true, replayed: true, ...recordOf(existing) }\n const role = roleRefusal(host, request.uid)\n if (role) return { ok: false, ...role }\n // One projected read answers both: the allowance and the cards'\n // name check each count the live ones, so a deleted record frees\n // its slot and its name (AGL-3918).\n const rows = (await tx.get(records.select('name', 'deletedAt'))).docs\n const room = roomRefusal(\n request.org,\n rows.filter((row) => isLiveDocument(row.get('deletedAt'))).length,\n )\n if (room) return { ok: false, ...room }\n const key = logicNameKey(document.name)\n const taken = rows.some(\n (row) => row.get('deletedAt') == null && logicNameKey(String(row.get('name') ?? '')) === key,\n )\n if (taken) return { ok: false, status: 409, error: logicDraftNameTaken(kind.noun, document.name) }\n tx.create(ref, {\n ...document,\n createdAt: request.now,\n updatedAt: request.now,\n createdBy: request.uid,\n })\n return {\n ok: true,\n replayed: false,\n id: request.id,\n name: document.name,\n versionId: null,\n facts: kind.facts(document),\n }\n })\n },\n }\n}\n\n/** The `variable` writer. */\nexport function createVariableDraftWriter(deps: LogicDraftWriterDeps = {}): PluginResourceDraftWriter {\n return createLogicDraftWriter(\n {\n noun: 'variable',\n collection: 'variables',\n quota: 'variablesPerHost',\n read: readVariableDraftContent,\n check: checkVariableDraftContent,\n facts: variableDraftFacts,\n },\n deps,\n )\n}\n\n/** The `function` writer. */\nexport function createFunctionDraftWriter(deps: LogicDraftWriterDeps = {}): PluginResourceDraftWriter {\n return createLogicDraftWriter(\n {\n noun: 'function',\n collection: 'functions',\n quota: 'functionsPerHost',\n read: readFunctionDraftContent,\n check: checkFunctionDraftContent,\n facts: functionDraftFacts,\n },\n deps,\n )\n}\n\nexport const variableDraftWriter = createVariableDraftWriter()\nexport const functionDraftWriter = createFunctionDraftWriter()\n"],"names":["checkQuota","holdsSiteKey","siteKeyRefusal","countLiveDocuments","isLiveDocument","firebaseAdmin","checkFunctionDraftContent","checkVariableDraftContent","functionDraftFacts","logicNameKey","readFunctionDraftContent","readVariableDraftContent","variableDraftFacts","LOGIC_DRAFT_ROLE_REFUSAL","logicDraftLimitRefusal","noun","limit","logicDraftNameTaken","name","roleRefusal","host","uid","status","error","createLogicDraftWriter","kind","deps","firestore","app","roomRefusal","org","used","quota","allowed","recordOf","snapshot","data","id","String","versionId","facts","refusal","context","hostRef","collection","doc","hostId","get","exists","role","Number","check","content","read","write","request","named","trim","ok","problems","document","value","db","records","ref","runTransaction","tx","existing","Promise","all","replayed","rows","select","docs","room","filter","row","length","key","taken","some","create","createdAt","now","updatedAt","createdBy","createVariableDraftWriter","createFunctionDraftWriter","variableDraftWriter","functionDraftWriter"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,QAAQ,2CAA0C;AACrE,SAASC,YAAY,EAAEC,cAAc,QAAQ,0CAAyC;AACtF,SAASC,kBAAkB,EAAEC,cAAc,QAAQ,6CAA4C;AAS/F,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SACEC,yBAAyB,EACzBC,yBAAyB,EACzBC,kBAAk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