@aglyn/plugins-logic 1.0.0-beta.263 → 1.0.0-beta.266

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.263",
3
+ "version": "1.0.0-beta.266",
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.263",
29
- "@aglyn/shared-data-mdi": "1.0.0-beta.263",
30
- "@aglyn/shared-ui-jsx": "1.0.0-beta.263",
31
- "@aglyn/shared-ui-snackstack": "1.0.0-beta.263",
32
- "@aglyn/shared-util-timestamp": "1.0.0-beta.263",
33
- "@aglyn/tenant-data-admin": "1.0.0-beta.263",
34
- "@aglyn/tenant-feature-instance": "1.0.0-beta.263",
28
+ "@aglyn/aglyn": "1.0.0-beta.266",
29
+ "@aglyn/shared-data-mdi": "1.0.0-beta.266",
30
+ "@aglyn/shared-ui-jsx": "1.0.0-beta.266",
31
+ "@aglyn/shared-ui-snackstack": "1.0.0-beta.266",
32
+ "@aglyn/shared-util-timestamp": "1.0.0-beta.266",
33
+ "@aglyn/tenant-data-admin": "1.0.0-beta.266",
34
+ "@aglyn/tenant-feature-instance": "1.0.0-beta.266",
35
35
  "@swc/helpers": "0.5.23"
36
36
  },
37
37
  "peerDependencies": {
@@ -30,7 +30,8 @@ import { TABLE_PAGE_SIZE_DEFAULT } from "@aglyn/shared-ui-jsx/const/table-pagina
30
30
  import { useSnackbar } from "@aglyn/shared-ui-snackstack";
31
31
  import { Timestamp } from "@aglyn/shared-util-timestamp";
32
32
  import { Alert, Button, Dialog, DialogActions, DialogContent, DialogTitle, Divider, IconButton, MenuItem, Stack, Switch, TextField, Typography } from "@mui/material";
33
- import { collection, doc, getCountFromServer, getDocs, limit, query } from "firebase/firestore";
33
+ import { collection, doc, getDocs, limit, query } from "firebase/firestore";
34
+ import { getLiveCountFromServer } from "@aglyn/aglyn/app-utils/live-document-count.client";
34
35
  import { useCallback, useEffect, useMemo, useState } from "react";
35
36
  import { useFirestore, useFirestoreCollection, useHostResourceApi, useUser, writeGuardedBySeed } from "@aglyn/tenant-feature-instance";
36
37
  import { writeSiteWideChange } from "@aglyn/tenant-feature-instance/hooks/helpers/site-wide-change";
@@ -314,16 +315,16 @@ function emptyDraft() {
314
315
  * on those plans the gate compared 100 against hundreds and could never
315
316
  * refuse, while `api/hosts/resources` counted the collection and did.
316
317
  *
317
- * UNFILTERED, matching that route's plain `collection('functions').count()`
318
- * — soft-deleted functions have always counted server-side, so this is the
319
- * card catching up with the verdict it exists to predict. Only a create
320
- * moves the number, so that is where it is re-read.
318
+ * LIVE functions, as that route counts them (AGL-3918): a deleted
319
+ * function frees its slot. Every document less the tombstones
320
+ * (`getLiveCountFromServer`). A create or a delete moves the number, so
321
+ * both re-read it.
321
322
  */ const [functionCountEpoch, setFunctionCountEpoch] = useState(0);
322
323
  const [serverFunctionCount, setServerFunctionCount] = useState(null);
323
324
  useEffect(()=>{
324
325
  let active = true;
325
- void getCountFromServer(collection(firestore, 'hosts', hostId, 'functions')).then((snapshot)=>{
326
- if (active) setServerFunctionCount(snapshot.data().count);
326
+ void getLiveCountFromServer(collection(firestore, 'hosts', hostId, 'functions')).then((count)=>{
327
+ if (active) setServerFunctionCount(count);
327
328
  }).catch(()=>{
328
329
  // Falls back to the loaded rows — a LOWER bound and the prior
329
330
  // behaviour, never 0, which `checkQuota` would answer as "no usage"
@@ -577,6 +578,8 @@ function emptyDraft() {
577
578
  deletedAt: Timestamp.now()
578
579
  })
579
580
  });
581
+ // Deleting frees the slot (AGL-3918), so the head-count is re-read.
582
+ setFunctionCountEpoch((epoch)=>epoch + 1);
580
583
  enqueueSnackbar('Function deleted', {
581
584
  variant: 'success',
582
585
  persist: false
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/logic/src/lib/components/host-functions-card.component.tsx"],"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'use client'\n\nimport {\n type AglynOrgBilling,\n checkQuota,\n evaluateHostFunction,\n FUNCTION_BUILTIN_NAMES,\n type FunctionComparator,\n functionGlobals,\n functionReferencedNames,\n type FunctionValueType,\n type HostFunction,\n type HostFunctionParameter,\n type HostVariable,\n pluginDocsHelp,\n VARIABLE_NAME_PATTERN,\n} from '@aglyn/aglyn'\n/*\n * The MODULE, not the barrel, for the two PURE helpers — every spec that\n * renders this card mocks `@aglyn/tenant-feature-instance` wholesale to stage\n * its Firestore hooks, and a query builder imported through that barrel\n * disappears under the mock. Neither of these is a hook.\n */\nimport {\n ceilingedWindow,\n collectionCeiling,\n} from '@aglyn/tenant-feature-instance/hooks/host-collection-queries'\nimport { CardDisplay, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport { TABLE_PAGE_SIZE_DEFAULT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { Timestamp } from '@aglyn/shared-util-timestamp'\nimport {\n Alert,\n Button,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n Divider,\n IconButton,\n MenuItem,\n Stack,\n Switch,\n TextField,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n doc,\n getCountFromServer,\n getDocs,\n limit,\n query,\n} from 'firebase/firestore'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport {\n useFirestore,\n useFirestoreCollection,\n useHostResourceApi,\n useUser,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport { writeSiteWideChange } from '@aglyn/tenant-feature-instance/hooks/helpers/site-wide-change'\nimport { ParameterChoicesEditor } from './parameter-choices-editor.component'\nimport WhereUsedDialog from './where-used-dialog.component'\nimport { FormulaBuilderButton } from './formula-builder.component'\nimport { formulaNames } from '../model/formula-names'\nimport { useConsoleWidgetSlot } from '@aglyn/aglyn/app-utils/console-widget-slot-context'\nimport {\n HOST_LOGIC_ZONE,\n LOGIC_FUNCTION_EDITOR_ZONE,\n type LogicProposal,\n} from './logic-zones'\nimport {\n fetchWhereUsed,\n summarizeDependents,\n type WhereUsedResult,\n} from '@aglyn/aglyn/app-utils/where-used'\n\n/**\n * How many functions the card reads.\n *\n * A CEILING, not a page size — see the query, which explains why this list\n * cannot be paged by the server without making the duplicate-name check lie.\n */\nconst FUNCTION_CEILING = 100\n\nexport interface HostFunctionsCardProps {\n hostId: string\n /** Resolved entitlement source for quota checks (AGL-395). */\n org?: Partial<AglynOrgBilling>\n}\n\nconst VALUE_TYPES: { value: FunctionValueType; label: string }[] = [\n { value: 'number', label: 'Number' },\n { value: 'text', label: 'Text' },\n { value: 'boolean', label: 'True/false' },\n]\n\nconst COMPARATORS: FunctionComparator[] = ['==', '!=', '<', '<=', '>', '>=']\n\ninterface FunctionDraft extends HostFunction {\n id: string | null\n}\n\nfunction emptyDraft(): FunctionDraft {\n return {\n id: null,\n name: '',\n parameters: [{ name: 'P1', type: 'number', required: true }],\n variables: [{ name: 'P3', type: 'number' }],\n operations: [\n {\n if: { left: '', comparator: '<=', right: '' },\n then: [{ set: '', expression: '' }],\n otherwise: [],\n },\n ],\n returnValue: '',\n }\n}\n\n/**\n * What a VISITOR meets for one parameter (AGL-3202): the label above the\n * input, what it starts with, and — for a question with fixed answers — the\n * choices, one row each (AGL-3768). Empty fields are dropped from the\n * definition rather than stored as empty strings, so a function nobody has\n * dressed for visitors saves exactly the shape it always did.\n *\n * \"Starts as\" is picked, not typed, wherever there is a list to pick from:\n * the choices when there are any, on or off for a true/false.\n */\nfunction ParameterAudienceFields(props: {\n parameter: HostFunctionParameter\n onChange: (next: HostFunctionParameter) => void\n}) {\n const { parameter, onChange } = props\n const assign = (field: 'label' | 'defaultValue', value: string) => {\n const next = { ...parameter }\n if (value) next[field] = value\n else delete next[field]\n onChange(next)\n }\n const options = parameter.options ?? []\n const startsAsChoices: { value: string; label: string }[] | null =\n parameter.type === 'boolean'\n ? [\n { value: 'true', label: 'On' },\n { value: 'false', label: 'Off' },\n ]\n : options.length\n ? options.map((option) => ({\n value: option.value,\n label: option.label ?? option.value,\n }))\n : null\n return (\n <Stack spacing={1}>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Typography\n variant=\"body2\"\n color=\"text.secondary\"\n sx={{ width: 110, flexShrink: 0 }}\n noWrap\n >\n {parameter.name || '—'}\n </Typography>\n <TextField\n label=\"Label\"\n placeholder={parameter.name}\n value={parameter.label ?? ''}\n onChange={(event) => assign('label', event.target.value.slice(0, 80))}\n size=\"small\"\n sx={{ flex: 2 }}\n />\n {startsAsChoices ? (\n <TextField\n select\n label=\"Starts as\"\n value={\n startsAsChoices.some(\n (choice) => choice.value === parameter.defaultValue,\n )\n ? parameter.defaultValue\n : ''\n }\n onChange={(event) => assign('defaultValue', event.target.value)}\n size=\"small\"\n sx={{ flex: 1 }}\n >\n <MenuItem value=\"\">\n <em>{'Nothing chosen'}</em>\n </MenuItem>\n {startsAsChoices.map((choice) => (\n <MenuItem key={choice.value} value={choice.value}>\n {choice.label}\n </MenuItem>\n ))}\n </TextField>\n ) : (\n <TextField\n label=\"Starts as\"\n value={parameter.defaultValue ?? ''}\n onChange={(event) =>\n assign(\n 'defaultValue',\n parameter.type === 'number'\n ? event.target.value.replace(/[^0-9.-]/g, '')\n : event.target.value.slice(0, 120),\n )\n }\n slotProps={\n parameter.type === 'number'\n ? { htmlInput: { inputMode: 'decimal' } }\n : undefined\n }\n size=\"small\"\n sx={{ flex: 1 }}\n />\n )}\n </Stack>\n {parameter.type === 'boolean' ? null : (\n <ParameterChoicesEditor\n parameterName={parameter.name}\n type={parameter.type}\n options={parameter.options}\n onChange={(nextOptions) => {\n const next = { ...parameter }\n if (nextOptions.length) next.options = nextOptions\n else delete next.options\n // A start that is no longer a choice would preselect nothing.\n if (\n nextOptions.length &&\n next.defaultValue !== undefined &&\n !nextOptions.some((option) => option.value === next.defaultValue)\n ) {\n delete next.defaultValue\n }\n onChange(next)\n }}\n />\n )}\n </Stack>\n )\n}\n\n/** Small labelled row header matching the mockup's section styling. */\nfunction SectionLabel(props: { children: string }) {\n return (\n <Typography variant=\"overline\" color=\"text.secondary\">\n {props.children}\n </Typography>\n )\n}\n\n/**\n * No-code function builder (Component Builder, AGL-92): the mockup's Edit\n * Function dialog — Parameters with required toggles, local Variables,\n * numbered conditional operation cards (If below is TRUE / Then do this /\n * Otherwise do this), a Return value select, and a test-run panel driving\n * the shared evaluator. Definitions persist to `hosts/{hostId}/functions`;\n * prop/event wiring lands with AGL-93.\n */\nexport function HostFunctionsCard(props: HostFunctionsCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const createHostResource = useHostResourceApi()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n const { org } = props\n const {\n data: functionDocs,\n status: functionsStatus,\n /**\n * The rows this editor is seeded from are unconfirmed by the server\n * (AGL-1358). Editing destructures a whole stored function into `draft`\n * and writes `{...definition}` back, so `merge: true` protects nothing —\n * the payload is literally every field of the definition. `parameters`\n * and `operations` are arrays, which a merge replaces wholesale rather\n * than diffing, so a cached seed does not lose one edit: it restores that\n * snapshot's entire logic body and parameter list, and every caller's\n * arguments are positional against the list it just reverted.\n */\n fromCache: functionsFromCache,\n } = useFirestoreCollection<any>(\n /*\n * ORDERED AND CEILINGED, deliberately not paged by the query (AGL-2501) —\n * the same decision as the variables card beside it, for the same two\n * reasons.\n *\n * `limit(100)` alone is answered in DOCUMENT-ID order, so the window is a\n * pseudo-random hundred that the `localeCompare` below dresses up as an\n * alphabetical list, and nothing said the list was bounded.\n *\n * `collectionCeiling` does not change WHICH hundred — document-id order is\n * what the bare cap already returned. What it changes is that the order is\n * NAMED, so the obvious next edit is caught: ordering on `name` would HIDE\n * every function written without one rather than mis-sorting the list, and\n * `/api/hosts/resources` validates no field for presence while\n * `IMPORTABLE_FIELDS.functions` copies one only if the export carried it.\n *\n * The QUERY is not paged because `nameTaken` below tests the draft against\n * these rows: case-insensitive uniqueness is what keeps legacy\n * `{{fn:name(...)}}` resolution unambiguous (AGL-185), and on a ten-row\n * server page that check would compare a new function against a tenth of\n * the site and create the duplicate it exists to prevent.\n */\n () =>\n collectionCeiling(\n collection(firestore, 'hosts', hostId, 'functions'),\n FUNCTION_CEILING,\n ),\n [firestore, hostId],\n { idField: '$id' },\n )\n const { rows: readFunctions, truncated: functionsTruncated } =\n ceilingedWindow<any>(functionDocs, FUNCTION_CEILING)\n // Sorting is safe here in a way it is not on a paged list: these rows are\n // the whole collection below the ceiling, not a slice of one.\n const functions = useMemo(\n () =>\n readFunctions\n .filter((definition: any) => !definition.deletedAt)\n .sort((a: any, b: any) =>\n String(a.name ?? '').localeCompare(String(b.name ?? '')),\n ),\n [readFunctions],\n )\n // The page is a SLICE: the rows are already in hand and `nameTaken` needs\n // all of them.\n const [page, setPage] = useState(0)\n const [pageSize, setPageSize] = useState(TABLE_PAGE_SIZE_DEFAULT)\n const visibleFunctions = useMemo(\n () => functions.slice(page * pageSize, page * pageSize + pageSize),\n [functions, page, pageSize],\n )\n /**\n * The function HEAD-COUNT is a server aggregate, not the length of the\n * capped listener (AGL-1716, the AGL-1706 shape) — the same fix as the\n * variables card beside it, for the same reason.\n *\n * The listener is `limit(100)` and `functions.length` fed\n * `checkQuota(org, 'functionsPerHost', …)`, whose bands are 1 / 10 / 50 /\n * 250 / 500 / 1,000. Everything from Business up sits above the window, so\n * on those plans the gate compared 100 against hundreds and could never\n * refuse, while `api/hosts/resources` counted the collection and did.\n *\n * UNFILTERED, matching that route's plain `collection('functions').count()`\n * — soft-deleted functions have always counted server-side, so this is the\n * card catching up with the verdict it exists to predict. Only a create\n * moves the number, so that is where it is re-read.\n */\n const [functionCountEpoch, setFunctionCountEpoch] = useState(0)\n const [serverFunctionCount, setServerFunctionCount] = useState<number | null>(\n null,\n )\n useEffect(() => {\n let active = true\n void getCountFromServer(collection(firestore, 'hosts', hostId, 'functions'))\n .then((snapshot) => {\n if (active) setServerFunctionCount(snapshot.data().count)\n })\n .catch(() => {\n // Falls back to the loaded rows — a LOWER bound and the prior\n // behaviour, never 0, which `checkQuota` would answer as \"no usage\"\n // on a site that is over its band.\n })\n return () => {\n active = false\n }\n }, [firestore, hostId, functionCountEpoch])\n const functionCount = serverFunctionCount ?? functions.length\n\n const [draft, setDraft] = useState<FunctionDraft | null>(null)\n\n // Where-used dialog (AGL-193).\n const [usage, setUsage] = useState<{\n name: string\n result: WhereUsedResult\n } | null>(null)\n const [usageLoading, setUsageLoading] = useState<string | null>(null)\n\n const [testArgs, setTestArgs] = useState<Record<string, string>>({})\n const [testResult, setTestResult] = useState<string | null>(null)\n\n const patch = useCallback(\n (updater: (previous: FunctionDraft) => FunctionDraft) =>\n setDraft((previous) => (previous ? updater(previous) : previous)),\n [],\n )\n\n /**\n * The shell's zone renderer (AGL-3603), for what other plugins add beside\n * Add function and inside a saved function's editor; `null` outside the\n * console shell.\n */\n const ExtensionZone = useConsoleWidgetSlot()\n /*\n * Opens a function another plugin proposed in this editor, unsaved: a new\n * one as Add function opens one — so the plan's cap is asked first — and a\n * change to a saved one in place of what the editor holds. Save is the\n * only write.\n */\n const propose = useCallback(\n (proposal: LogicProposal) => {\n if (proposal.kind !== 'function') return false\n if (!proposal.functionId) {\n const quota = checkQuota(org, 'functionsPerHost', functionCount)\n if (!quota.allowed) {\n enqueueSnackbar(`Function limit reached (${quota.limit}) — upgrade in Billing`, {\n variant: 'warning',\n persist: false,\n })\n return false\n }\n }\n setTestArgs({})\n setTestResult(null)\n setDraft({ ...proposal.definition, id: proposal.functionId })\n return true\n },\n [org, functionCount, enqueueSnackbar],\n )\n /*\n * The saved function the editor has open, named as it is STORED: a rename\n * being typed is not a different function.\n */\n const storedName = draft?.id\n ? functions.find((row: any) => row.$id === draft.id)?.name ?? draft.name\n : null\n\n const names = [\n ...(draft?.parameters ?? []).map((parameter) => parameter.name),\n ...(draft?.variables ?? []).map((variable) => variable.name),\n ].filter((name) => VARIABLE_NAME_PATTERN.test(name))\n\n /**\n * The site's variables, for the formula builder's value picker\n * (AGL-3757). Read the first time a builder opens, like the test run's\n * read below, so an author who never builds a formula costs nothing.\n */\n const [siteVariables, setSiteVariables] = useState<HostVariable[] | null>(\n null,\n )\n const loadSiteVariables = useCallback(() => {\n if (siteVariables) return\n setSiteVariables([])\n getDocs(query(collection(firestore, 'hosts', hostId, 'variables'), limit(100)))\n .then((snapshot) => {\n const rows: HostVariable[] = []\n snapshot.forEach((row) => {\n const data = row.data() as HostVariable & { deletedAt?: unknown }\n if (data?.name && !data.deletedAt) rows.push(data)\n })\n setSiteVariables(rows)\n })\n .catch((error) => {\n // The builder still offers the function's own names.\n console.error(error)\n })\n }, [siteVariables, firestore, hostId])\n const formulaNameOptions = formulaNames({\n parameters: draft?.parameters ?? [],\n locals: draft?.variables ?? [],\n siteVariables: siteVariables ?? [],\n })\n\n // Case-insensitive uniqueness (AGL-185): function names must stay\n // unambiguous for legacy {{fn:name(...)}} token resolution.\n const nameTaken = Boolean(\n draft &&\n functions.some(\n (definition: any) =>\n String(definition.name ?? '').toLowerCase() ===\n draft.name.trim().toLowerCase() && definition.$id !== draft.id,\n ),\n )\n\n /**\n * A test run sees what a published page sees (AGL-3202): the site\n * variables the draft names. Read on the click, and only when the draft\n * names something outside itself, so opening this card still costs the one\n * functions window and nothing else — a listener here would bill a hundred\n * variable reads to every author who never presses Run.\n */\n const handleTestRun = useCallback(async () => {\n if (!draft) return\n let globals: Record<string, number | string | boolean> = {}\n if (functionReferencedNames(draft).length) {\n try {\n const snapshot = await getDocs(\n query(collection(firestore, 'hosts', hostId, 'variables'), limit(100)),\n )\n const lookup: Record<string, HostVariable> = {}\n snapshot.forEach((row) => {\n const data = row.data() as HostVariable & { deletedAt?: unknown }\n if (data?.name && !data.deletedAt) lookup[row.id] = data\n })\n globals = functionGlobals(draft, lookup)\n } catch (error) {\n // The run still happens: an unreadable variable list reads as the\n // evaluator's own \"Unknown name\", which names what was missing.\n console.error(error)\n }\n }\n const result = evaluateHostFunction(draft, testArgs, { globals })\n setTestResult(\n result.ok === false\n ? `Error: ${result.error}`\n : `Result: ${String(result.value)}`,\n )\n }, [draft, testArgs, firestore, hostId])\n\n const handleSave = useCallback(async () => {\n if (!draft || !draft.name.trim() || nameTaken) return\n const { id: draftId, ...definition } = draft\n const fields = { ...definition, name: draft.name.trim().slice(0, 60) }\n try {\n if (draftId) {\n /**\n * Edit stays client-direct (no quota consumed) — and is refused when\n * its seed was never confirmed by the server (AGL-1358). `fields` is\n * the whole definition spread out of the listener row, so `merge:\n * true` has nothing left to protect.\n *\n * The guard WRAPS the write. An early return is a shape you can keep\n * while losing the protection; here the write is only reachable\n * through the verdict.\n */\n const verdict = await writeGuardedBySeed(\n {\n subject: 'function',\n unreadable: functionsStatus === 'error',\n fromCache: functionsFromCache,\n },\n async () => {\n await writeSiteWideChange({\n firestore,\n user,\n hostId,\n write: (batch) =>\n batch.set(\n doc(firestore, 'hosts', hostId, 'functions', draftId),\n { ...fields, updatedAt: Timestamp.now() },\n { merge: true },\n ),\n })\n },\n )\n // Before `setDraft(null)`, so a refusal keeps the dialog open with\n // the whole edited body and its test run still on screen.\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n } else {\n // New function rides the quota-enforcing resources API (AGL-473).\n await createHostResource({ hostId, resource: 'function', data: fields })\n // A create moves the count; the one-shot aggregate below does not\n // refresh itself the way the listener refreshes the rows.\n setFunctionCountEpoch((epoch) => epoch + 1)\n }\n setDraft(null)\n setTestResult(null)\n enqueueSnackbar('Function saved', { variant: 'success', persist: false })\n } catch (error: any) {\n console.error(error)\n enqueueSnackbar(error?.message ?? 'An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n }, [\n user,\n draft,\n nameTaken,\n firestore,\n hostId,\n createHostResource,\n enqueueSnackbar,\n functionsStatus,\n functionsFromCache,\n ])\n\n const handleShowUsage = useCallback(\n (definition: any) => async () => {\n setUsageLoading(definition.$id)\n const result = await fetchWhereUsed(user as any, {\n hostId,\n kind: 'function',\n id: definition.$id,\n name: definition.name,\n })\n setUsageLoading(null)\n setUsage({ name: definition.name, result })\n },\n [user, hostId],\n )\n\n const handleDelete = useCallback(\n (definition: any) => async () => {\n // Dependents warning (AGL-187): screens/layouts binding the function\n // and workflow steps calling it.\n const scan = await fetchWhereUsed(user as any, {\n hostId,\n kind: 'function',\n id: definition.$id,\n name: definition.name,\n })\n const confirmed = await confirm({\n title: 'Delete this function?',\n description: scan.total\n ? `\"${definition.name}\" is used in ${summarizeDependents(scan)} ` +\n 'and those bindings and workflow steps will stop running.'\n : `\"${definition.name}\" will no longer be runnable.`,\n confirmationText: 'Delete',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n await writeSiteWideChange({\n firestore,\n user,\n hostId,\n write: (batch) =>\n batch.update(\n doc(firestore, 'hosts', hostId, 'functions', definition.$id),\n { deletedAt: Timestamp.now() },\n ),\n })\n enqueueSnackbar('Function deleted', {\n variant: 'success',\n persist: false,\n })\n },\n [user, confirm, firestore, hostId, enqueueSnackbar],\n )\n\n const setRow = (\n section: 'then' | 'otherwise',\n operationIndex: number,\n rowIndex: number,\n key: 'set' | 'expression',\n value: string,\n ) =>\n patch((previous) => {\n const operations = previous.operations.map((operation, index) =>\n index === operationIndex\n ? {\n ...operation,\n [section]: operation[section].map((row, index2) =>\n index2 === rowIndex ? { ...row, [key]: value } : row,\n ),\n }\n : operation,\n )\n return { ...previous, operations }\n })\n\n const renderSetRows = (section: 'then' | 'otherwise', operationIndex: number) => {\n const operation = draft?.operations[operationIndex]\n if (!operation) return null\n return (\n <Stack spacing={1}>\n {operation[section].map((row, rowIndex) => (\n <Stack\n key={rowIndex}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Typography variant=\"caption\">{'SET'}</Typography>\n <TextField\n value={row.set}\n onChange={(event) =>\n setRow(section, operationIndex, rowIndex, 'set', event.target.value)\n }\n size=\"small\"\n select\n sx={{ minWidth: 90 }}\n >\n {names.map((name) => (\n <MenuItem key={name} value={name}>\n {name}\n </MenuItem>\n ))}\n </TextField>\n <Typography variant=\"caption\">{'equal to'}</Typography>\n <TextField\n value={row.expression}\n placeholder=\"P1 + P2\"\n onChange={(event) =>\n setRow(\n section,\n operationIndex,\n rowIndex,\n 'expression',\n event.target.value,\n )\n }\n size=\"small\"\n sx={{ flex: 1 }}\n />\n <FormulaBuilderButton\n current={row.expression}\n names={formulaNameOptions}\n onOpen={loadSiteVariables}\n onUse={(expression) =>\n setRow(section, operationIndex, rowIndex, 'expression', expression)\n }\n />\n <IconButton\n size=\"small\"\n aria-label=\"remove operation row\"\n onClick={() =>\n patch((previous) => ({\n ...previous,\n operations: previous.operations.map((op, index) =>\n index === operationIndex\n ? {\n ...op,\n [section]: op[section].filter(\n (_, index2) => index2 !== rowIndex,\n ),\n }\n : op,\n ),\n }))\n }\n >\n {'×'}\n </IconButton>\n </Stack>\n ))}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() =>\n patch((previous) => ({\n ...previous,\n operations: previous.operations.map((op, index) =>\n index === operationIndex\n ? {\n ...op,\n [section]: [...op[section], { set: '', expression: '' }],\n }\n : op,\n ),\n }))\n }\n >\n {'Add set'}\n </Button>\n </Stack>\n )\n }\n\n return (\n <CardDisplay\n header={'Functions'}\n help={pluginDocsHelp('bindings', { anchor: '#functions-card' })}\n // Another way to start a function (AGL-3603), in the card's header.\n actions={\n ExtensionZone ? (\n <ExtensionZone\n slot={HOST_LOGIC_ZONE.id}\n hostId={hostId}\n orgId={org?.$id}\n kind=\"function\"\n propose={propose}\n />\n ) : null\n }\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1}>\n {functions.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Build no-code logic: parameters in, conditional operations, ' +\n 'a value out. Wire functions into components and workflows ' +\n 'as the builder grows.'}\n </Typography>\n ) : (\n visibleFunctions.map((definition: any) => (\n <Stack\n key={definition.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Stack sx={{ flex: 1, minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {definition.name}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {`${(definition.parameters ?? []).map((p: any) => p.name).join(', ') || 'no parameters'} → ${definition.returnValue || '—'}`}\n </Typography>\n </Stack>\n <Button\n size=\"small\"\n disabled={usageLoading === definition.$id}\n onClick={handleShowUsage(definition)}\n >\n {usageLoading === definition.$id ? 'Scanning…' : 'Usage'}\n </Button>\n <Button\n size=\"small\"\n onClick={() => {\n setTestArgs({})\n setTestResult(null)\n setDraft({\n id: definition.$id,\n name: definition.name ?? '',\n parameters: definition.parameters ?? [],\n variables: definition.variables ?? [],\n operations: definition.operations ?? [],\n returnValue: definition.returnValue ?? '',\n })\n }}\n >\n {'Edit'}\n </Button>\n <Button\n size=\"small\"\n color=\"error\"\n onClick={handleDelete(definition)}\n >\n {'Delete'}\n </Button>\n </Stack>\n ))\n )}\n {functions.length === 0 ? null : (\n <ListPagination\n page={page}\n pageSize={pageSize}\n rowCount={visibleFunctions.length}\n // The functions the card HOLDS. Not `functionCount`, which is the\n // site's total including soft-deleted rows and answers the quota's\n // question rather than the reader's.\n count={functions.length}\n onPageChange={setPage}\n onPageSizeChange={setPageSize}\n />\n )}\n {functionsTruncated ? (\n <Alert severity=\"info\">\n {`Showing ${FUNCTION_CEILING} functions, ordered by id. This site ` +\n 'has more — the duplicate-name check below only covers the ' +\n 'ones listed here, so a name may already be taken by one that ' +\n 'is not.'}\n </Alert>\n ) : null}\n <Button\n size=\"small\"\n color=\"primary\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() => {\n // Plan cap (AGL-99): dark-launch — plan-less workspaces uncapped.\n // The site's functions, not this page of them (AGL-1716).\n const quota = checkQuota(org, 'functionsPerHost', functionCount)\n if (!quota.allowed) {\n return void enqueueSnackbar(\n `Function limit reached (${quota.limit}) — upgrade in Billing`,\n { variant: 'warning', persist: false },\n )\n }\n setTestArgs({})\n setTestResult(null)\n setDraft(emptyDraft())\n }}\n >\n {'Add function'}\n </Button>\n </Stack>\n\n <Dialog\n open={Boolean(draft)}\n onClose={() => setDraft(null)}\n maxWidth=\"sm\"\n fullWidth\n >\n <DialogTitle>\n {draft?.id ? 'Edit Function' : 'Add Function'}\n </DialogTitle>\n <DialogContent\n sx={{ display: 'flex', flexDirection: 'column', gap: 1.5, pt: 1 }}\n >\n {ExtensionZone && draft?.id && storedName != null ? (\n <ExtensionZone\n slot={LOGIC_FUNCTION_EDITOR_ZONE.id}\n hostId={hostId}\n orgId={org?.$id}\n target={{ id: draft.id, name: storedName }}\n propose={propose}\n />\n ) : null}\n <TextField\n label=\"Name\"\n helperText={\n nameTaken\n ? 'A function with this name already exists'\n : 'Used to identify the function'\n }\n error={nameTaken}\n value={draft?.name ?? ''}\n onChange={(event) =>\n patch((previous) => ({ ...previous, name: event.target.value }))\n }\n size=\"small\"\n autoFocus\n sx={{ mt: 1 }}\n />\n\n <SectionLabel>{'Parameters'}</SectionLabel>\n {(draft?.parameters ?? []).map((parameter, index) => (\n <Stack\n key={index}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <TextField\n label=\"Name\"\n value={parameter.name}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n parameters: previous.parameters.map((p, index2) =>\n index2 === index\n ? {\n ...p,\n name: event.target.value.replace(\n /[^a-zA-Z0-9_]/g,\n '',\n ),\n }\n : p,\n ),\n }))\n }\n size=\"small\"\n sx={{ width: 110 }}\n />\n <TextField\n label=\"Type\"\n value={parameter.type}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n parameters: previous.parameters.map((p, index2) =>\n index2 === index\n ? { ...p, type: event.target.value as FunctionValueType }\n : p,\n ),\n }))\n }\n size=\"small\"\n select\n sx={{ width: 130 }}\n >\n {VALUE_TYPES.map((type) => (\n <MenuItem key={type.value} value={type.value}>\n {type.label}\n </MenuItem>\n ))}\n </TextField>\n <Stack\n direction=\"row\"\n spacing={0.5}\n sx={{ alignItems: 'center', flex: 1 }}\n >\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Required'}\n </Typography>\n <Switch\n size=\"small\"\n checked={Boolean(parameter.required)}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n parameters: previous.parameters.map((p, index2) =>\n index2 === index\n ? { ...p, required: event.target.checked }\n : p,\n ),\n }))\n }\n />\n </Stack>\n <IconButton\n size=\"small\"\n aria-label=\"remove parameter\"\n onClick={() =>\n patch((previous) => ({\n ...previous,\n parameters: previous.parameters.filter(\n (_, index2) => index2 !== index,\n ),\n }))\n }\n >\n {'×'}\n </IconButton>\n </Stack>\n ))}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() =>\n patch((previous) => ({\n ...previous,\n parameters: [\n ...previous.parameters,\n {\n name: `P${previous.parameters.length + 1}`,\n type: 'number',\n required: false,\n },\n ],\n }))\n }\n >\n {'Add parameter'}\n </Button>\n\n {(draft?.parameters ?? []).length ? (\n <>\n <SectionLabel>{'What visitors see'}</SectionLabel>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Used by a Function Widget on a page. A parameter with ' +\n 'choices is asked as a list — Add choice gives it one — a ' +\n 'number as a number box and a true/false as a switch.'}\n </Typography>\n {(draft?.parameters ?? []).map((parameter, index) => (\n <ParameterAudienceFields\n // Keyed by position: the name is being edited one row up.\n key={index}\n parameter={parameter}\n onChange={(next) =>\n patch((previous) => ({\n ...previous,\n parameters: previous.parameters.map((p, index2) =>\n index2 === index ? next : p,\n ),\n }))\n }\n />\n ))}\n </>\n ) : null}\n\n <SectionLabel>{'Variables'}</SectionLabel>\n {(draft?.variables ?? []).map((variable, index) => (\n <Stack\n key={index}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <TextField\n label=\"Name\"\n value={variable.name}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n variables: previous.variables.map((v, index2) =>\n index2 === index\n ? {\n ...v,\n name: event.target.value.replace(\n /[^a-zA-Z0-9_]/g,\n '',\n ),\n }\n : v,\n ),\n }))\n }\n size=\"small\"\n sx={{ width: 110 }}\n />\n <TextField\n label=\"Type\"\n value={variable.type}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n variables: previous.variables.map((v, index2) =>\n index2 === index\n ? { ...v, type: event.target.value as FunctionValueType }\n : v,\n ),\n }))\n }\n size=\"small\"\n select\n sx={{ width: 130 }}\n >\n {VALUE_TYPES.map((type) => (\n <MenuItem key={type.value} value={type.value}>\n {type.label}\n </MenuItem>\n ))}\n </TextField>\n <IconButton\n size=\"small\"\n aria-label=\"remove variable\"\n sx={{ ml: 'auto' }}\n onClick={() =>\n patch((previous) => ({\n ...previous,\n variables: previous.variables.filter(\n (_, index2) => index2 !== index,\n ),\n }))\n }\n >\n {'×'}\n </IconButton>\n </Stack>\n ))}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() =>\n patch((previous) => ({\n ...previous,\n variables: [\n ...previous.variables,\n { name: `V${previous.variables.length + 1}`, type: 'number' },\n ],\n }))\n }\n >\n {'Add variable'}\n </Button>\n\n <SectionLabel>{'Operations'}</SectionLabel>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Press ƒx beside a box to build its formula by picking values — ' +\n 'add, smallest of, format as money and more. A box also takes ' +\n 'a formula written out: + − × ÷ and parentheses, any site ' +\n 'variable by its name (a dictionary’s members as ' +\n 'name.member), and ' +\n `${FUNCTION_BUILTIN_NAMES.map((name) => `${name}()`).join(', ')}.`}\n </Typography>\n {(draft?.operations ?? []).map((operation, index) => (\n <Stack\n key={index}\n spacing={1}\n sx={{\n border: 1,\n borderColor: 'divider',\n borderRadius: 1,\n p: 1.5,\n }}\n >\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`${index + 1} · If below is TRUE`}\n </Typography>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <TextField\n value={operation.if.left}\n placeholder=\"P1\"\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n operations: previous.operations.map((op, index2) =>\n index2 === index\n ? { ...op, if: { ...op.if, left: event.target.value } }\n : op,\n ),\n }))\n }\n size=\"small\"\n sx={{ flex: 1 }}\n />\n <FormulaBuilderButton\n current={operation.if.left}\n names={formulaNameOptions}\n onOpen={loadSiteVariables}\n onUse={(expression) =>\n patch((previous) => ({\n ...previous,\n operations: previous.operations.map((op, index2) =>\n index2 === index\n ? { ...op, if: { ...op.if, left: expression } }\n : op,\n ),\n }))\n }\n />\n <TextField\n value={operation.if.comparator}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n operations: previous.operations.map((op, index2) =>\n index2 === index\n ? {\n ...op,\n if: {\n ...op.if,\n comparator: event.target\n .value as FunctionComparator,\n },\n }\n : op,\n ),\n }))\n }\n size=\"small\"\n select\n sx={{ width: 84 }}\n >\n {COMPARATORS.map((comparator) => (\n <MenuItem key={comparator} value={comparator}>\n {comparator}\n </MenuItem>\n ))}\n </TextField>\n <TextField\n value={operation.if.right}\n placeholder=\"P2\"\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n operations: previous.operations.map((op, index2) =>\n index2 === index\n ? { ...op, if: { ...op.if, right: event.target.value } }\n : op,\n ),\n }))\n }\n size=\"small\"\n sx={{ flex: 1 }}\n />\n <FormulaBuilderButton\n current={operation.if.right}\n names={formulaNameOptions}\n onOpen={loadSiteVariables}\n onUse={(expression) =>\n patch((previous) => ({\n ...previous,\n operations: previous.operations.map((op, index2) =>\n index2 === index\n ? { ...op, if: { ...op.if, right: expression } }\n : op,\n ),\n }))\n }\n />\n </Stack>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Then do this'}\n </Typography>\n {renderSetRows('then', index)}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Otherwise do this'}\n </Typography>\n {renderSetRows('otherwise', index)}\n </Stack>\n ))}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() =>\n patch((previous) => ({\n ...previous,\n operations: [\n ...previous.operations,\n {\n if: { left: '', comparator: '<=', right: '' },\n then: [{ set: '', expression: '' }],\n otherwise: [],\n },\n ],\n }))\n }\n >\n {'Add operation'}\n </Button>\n\n <TextField\n label=\"Return value\"\n value={draft?.returnValue ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n returnValue: event.target.value,\n }))\n }\n size=\"small\"\n select\n >\n {names.map((name) => (\n <MenuItem key={name} value={name}>\n {name}\n </MenuItem>\n ))}\n </TextField>\n\n <Divider />\n <SectionLabel>{'Test run'}</SectionLabel>\n <Stack direction=\"row\" spacing={1} sx={{ flexWrap: 'wrap' }}>\n {(draft?.parameters ?? []).map((parameter) => (\n <TextField\n key={parameter.name}\n label={parameter.name}\n value={testArgs[parameter.name] ?? ''}\n onChange={(event) =>\n setTestArgs((previous) => ({\n ...previous,\n [parameter.name]: event.target.value,\n }))\n }\n size=\"small\"\n sx={{ width: 110 }}\n />\n ))}\n <Button size=\"small\" color=\"primary\" onClick={handleTestRun}>\n {'Run'}\n </Button>\n </Stack>\n {testResult ? (\n <Alert\n severity={testResult.startsWith('Error') ? 'warning' : 'success'}\n >\n {testResult}\n </Alert>\n ) : null}\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setDraft(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={!draft?.name.trim() || nameTaken}\n onClick={handleSave}\n >\n {'Done'}\n </Button>\n </DialogActions>\n </Dialog>\n <WhereUsedDialog\n hostId={hostId}\n usage={usage}\n onClose={() => setUsage(null)}\n />\n </CardDisplay>\n )\n}\nHostFunctionsCard.displayName = 'HostFunctionsCard'\n\nexport default HostFunctionsCard\n"],"names":["checkQuota","evaluateHostFunction","FUNCTION_BUILTIN_NAMES","functionGlobals","functionReferencedNames","pluginDocsHelp","VARIABLE_NAME_PATTERN","ceilingedWindow","collectionCeiling","CardDisplay","useConfirmationContext","ListPagination","TABLE_PAGE_SIZE_DEFAULT","useSnackbar","Timestamp","Alert","Button","Dialog","DialogActions","DialogContent","DialogTitle","Divider","IconButton","MenuItem","Stack","Switch","TextField","Typography","collection","doc","getCountFromServer","getDocs","limit","query","useCallback","useEffect","useMemo","useState","useFirestore","useFirestoreCollection","useHostResourceApi","useUser","writeGuardedBySeed","writeSiteWideChange","ParameterChoicesEditor","WhereUsedDialog","FormulaBuilderButton","formulaNames","useConsoleWidgetSlot","HOST_LOGIC_ZONE","LOGIC_FUNCTION_EDITOR_ZONE","fetchWhereUsed","summarizeDependents","FUNCTION_CEILING","VALUE_TYPES","value","label","COMPARATORS","emptyDraft","id","name","parameters","type","required","variables","operations","if","left","comparator","right","then","set","expression","otherwise","returnValue","ParameterAudienceFields","props","parameter","onChange","assign","field","next","options","startsAsChoices","length","map","option","spacing","direction","sx","alignItems","variant","color","width","flexShrink","noWrap","placeholder","event","target","slice","size","flex","select","some","choice","defaultValue","em","replace","slotProps","htmlInput","inputMode","undefined","parameterName","nextOptions","SectionLabel","children","HostFunctionsCard","functions","hostId","firestore","data","user","createHostResource","enqueueSnackbar","confirm","org","functionDocs","status","functionsStatus","fromCache","functionsFromCache","idField","rows","readFunctions","truncated","functionsTruncated","filter","definition","deletedAt","sort","a","b","String","localeCompare","page","setPage","pageSize","setPageSize","visibleFunctions","functionCountEpoch","setFunctionCountEpoch","serverFunctionCount","setServerFunctionCount","active","snapshot","count","catch","functionCount","draft","setDraft","usage","setUsage","usageLoading","setUsageLoading","testArgs","setTestArgs","testResult","setTestResult","patch","updater","previous","ExtensionZone","propose","proposal","kind","functionId","quota","allowed","persist","storedName","find","row","$id","names","variable","test","siteVariables","setSiteVariables","loadSiteVariables","forEach","push","error","console","formulaNameOptions","locals","nameTaken","Boolean","toLowerCase","trim","handleTestRun","globals","lookup","result","ok","handleSave","draftId","fields","verdict","subject","unreadable","write","batch","updatedAt","now","merge","message","resource","epoch","allowDuplicate","handleShowUsage","handleDelete","scan","confirmed","title","description","total","confirmationText","confirmationButtonProps","update","setRow","section","operationIndex","rowIndex","key","operation","index","index2","renderSetRows","minWidth","current","onOpen","onUse","aria-label","onClick","op","_","alignSelf","header","help","anchor","actions","slot","orgId","contentGutterX","contentGutterY","p","join","disabled","rowCount","onPageChange","onPageSizeChange","severity","open","onClose","maxWidth","fullWidth","display","flexDirection","gap","pt","helperText","autoFocus","mt","checked","v","ml","border","borderColor","borderRadius","flexWrap","startsWith","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;;AAEA,SAEEA,UAAU,EACVC,oBAAoB,EACpBC,sBAAsB,EAEtBC,eAAe,EACfC,uBAAuB,EAKvBC,cAAc,EACdC,qBAAqB,QAChB,eAAc;AACrB;;;;;CAKC,GACD,SACEC,eAAe,EACfC,iBAAiB,QACZ,+DAA8D;AACrE,SAASC,WAAW,EAAEC,sBAAsB,QAAQ,uBAAsB;AAC1E,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,SAASC,uBAAuB,QAAQ,8CAA6C;AACrF,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,SAAS,QAAQ,+BAA8B;AACxD,SACEC,KAAK,EACLC,MAAM,EACNC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,OAAO,EACPC,UAAU,EACVC,QAAQ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;gCAAOmO,SAAS,IAAMpF,SAAS;0CAAQ;;0CACxC,KAAC/I;gCACC2E,SAAQ;gCACRC,OAAM;gCACNqK,UAAU,EAACnG,yBAAAA,MAAOlG,IAAI,CAAC0I,IAAI,OAAMH;gCACjCgD,SAASvC;0CAER;;;;;;0BAIP,KAAC/J;gBACCyE,QAAQA;gBACR0C,OAAOA;gBACPuG,SAAS,IAAMtG,SAAS;;;;AAIhC;AACA7C,kBAAkBqK,WAAW,GAAG;AAEhC,eAAerK,kBAAiB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/logic/src/lib/components/host-functions-card.component.tsx"],"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'use client'\n\nimport {\n type AglynOrgBilling,\n checkQuota,\n evaluateHostFunction,\n FUNCTION_BUILTIN_NAMES,\n type FunctionComparator,\n functionGlobals,\n functionReferencedNames,\n type FunctionValueType,\n type HostFunction,\n type HostFunctionParameter,\n type HostVariable,\n pluginDocsHelp,\n VARIABLE_NAME_PATTERN,\n} from '@aglyn/aglyn'\n/*\n * The MODULE, not the barrel, for the two PURE helpers — every spec that\n * renders this card mocks `@aglyn/tenant-feature-instance` wholesale to stage\n * its Firestore hooks, and a query builder imported through that barrel\n * disappears under the mock. Neither of these is a hook.\n */\nimport {\n ceilingedWindow,\n collectionCeiling,\n} from '@aglyn/tenant-feature-instance/hooks/host-collection-queries'\nimport { CardDisplay, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport { TABLE_PAGE_SIZE_DEFAULT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { Timestamp } from '@aglyn/shared-util-timestamp'\nimport {\n Alert,\n Button,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n Divider,\n IconButton,\n MenuItem,\n Stack,\n Switch,\n TextField,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n doc,\n getDocs,\n limit,\n query,\n} from 'firebase/firestore'\nimport { getLiveCountFromServer } from '@aglyn/aglyn/app-utils/live-document-count.client'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport {\n useFirestore,\n useFirestoreCollection,\n useHostResourceApi,\n useUser,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport { writeSiteWideChange } from '@aglyn/tenant-feature-instance/hooks/helpers/site-wide-change'\nimport { ParameterChoicesEditor } from './parameter-choices-editor.component'\nimport WhereUsedDialog from './where-used-dialog.component'\nimport { FormulaBuilderButton } from './formula-builder.component'\nimport { formulaNames } from '../model/formula-names'\nimport { useConsoleWidgetSlot } from '@aglyn/aglyn/app-utils/console-widget-slot-context'\nimport {\n HOST_LOGIC_ZONE,\n LOGIC_FUNCTION_EDITOR_ZONE,\n type LogicProposal,\n} from './logic-zones'\nimport {\n fetchWhereUsed,\n summarizeDependents,\n type WhereUsedResult,\n} from '@aglyn/aglyn/app-utils/where-used'\n\n/**\n * How many functions the card reads.\n *\n * A CEILING, not a page size — see the query, which explains why this list\n * cannot be paged by the server without making the duplicate-name check lie.\n */\nconst FUNCTION_CEILING = 100\n\nexport interface HostFunctionsCardProps {\n hostId: string\n /** Resolved entitlement source for quota checks (AGL-395). */\n org?: Partial<AglynOrgBilling>\n}\n\nconst VALUE_TYPES: { value: FunctionValueType; label: string }[] = [\n { value: 'number', label: 'Number' },\n { value: 'text', label: 'Text' },\n { value: 'boolean', label: 'True/false' },\n]\n\nconst COMPARATORS: FunctionComparator[] = ['==', '!=', '<', '<=', '>', '>=']\n\ninterface FunctionDraft extends HostFunction {\n id: string | null\n}\n\nfunction emptyDraft(): FunctionDraft {\n return {\n id: null,\n name: '',\n parameters: [{ name: 'P1', type: 'number', required: true }],\n variables: [{ name: 'P3', type: 'number' }],\n operations: [\n {\n if: { left: '', comparator: '<=', right: '' },\n then: [{ set: '', expression: '' }],\n otherwise: [],\n },\n ],\n returnValue: '',\n }\n}\n\n/**\n * What a VISITOR meets for one parameter (AGL-3202): the label above the\n * input, what it starts with, and — for a question with fixed answers — the\n * choices, one row each (AGL-3768). Empty fields are dropped from the\n * definition rather than stored as empty strings, so a function nobody has\n * dressed for visitors saves exactly the shape it always did.\n *\n * \"Starts as\" is picked, not typed, wherever there is a list to pick from:\n * the choices when there are any, on or off for a true/false.\n */\nfunction ParameterAudienceFields(props: {\n parameter: HostFunctionParameter\n onChange: (next: HostFunctionParameter) => void\n}) {\n const { parameter, onChange } = props\n const assign = (field: 'label' | 'defaultValue', value: string) => {\n const next = { ...parameter }\n if (value) next[field] = value\n else delete next[field]\n onChange(next)\n }\n const options = parameter.options ?? []\n const startsAsChoices: { value: string; label: string }[] | null =\n parameter.type === 'boolean'\n ? [\n { value: 'true', label: 'On' },\n { value: 'false', label: 'Off' },\n ]\n : options.length\n ? options.map((option) => ({\n value: option.value,\n label: option.label ?? option.value,\n }))\n : null\n return (\n <Stack spacing={1}>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Typography\n variant=\"body2\"\n color=\"text.secondary\"\n sx={{ width: 110, flexShrink: 0 }}\n noWrap\n >\n {parameter.name || '—'}\n </Typography>\n <TextField\n label=\"Label\"\n placeholder={parameter.name}\n value={parameter.label ?? ''}\n onChange={(event) => assign('label', event.target.value.slice(0, 80))}\n size=\"small\"\n sx={{ flex: 2 }}\n />\n {startsAsChoices ? (\n <TextField\n select\n label=\"Starts as\"\n value={\n startsAsChoices.some(\n (choice) => choice.value === parameter.defaultValue,\n )\n ? parameter.defaultValue\n : ''\n }\n onChange={(event) => assign('defaultValue', event.target.value)}\n size=\"small\"\n sx={{ flex: 1 }}\n >\n <MenuItem value=\"\">\n <em>{'Nothing chosen'}</em>\n </MenuItem>\n {startsAsChoices.map((choice) => (\n <MenuItem key={choice.value} value={choice.value}>\n {choice.label}\n </MenuItem>\n ))}\n </TextField>\n ) : (\n <TextField\n label=\"Starts as\"\n value={parameter.defaultValue ?? ''}\n onChange={(event) =>\n assign(\n 'defaultValue',\n parameter.type === 'number'\n ? event.target.value.replace(/[^0-9.-]/g, '')\n : event.target.value.slice(0, 120),\n )\n }\n slotProps={\n parameter.type === 'number'\n ? { htmlInput: { inputMode: 'decimal' } }\n : undefined\n }\n size=\"small\"\n sx={{ flex: 1 }}\n />\n )}\n </Stack>\n {parameter.type === 'boolean' ? null : (\n <ParameterChoicesEditor\n parameterName={parameter.name}\n type={parameter.type}\n options={parameter.options}\n onChange={(nextOptions) => {\n const next = { ...parameter }\n if (nextOptions.length) next.options = nextOptions\n else delete next.options\n // A start that is no longer a choice would preselect nothing.\n if (\n nextOptions.length &&\n next.defaultValue !== undefined &&\n !nextOptions.some((option) => option.value === next.defaultValue)\n ) {\n delete next.defaultValue\n }\n onChange(next)\n }}\n />\n )}\n </Stack>\n )\n}\n\n/** Small labelled row header matching the mockup's section styling. */\nfunction SectionLabel(props: { children: string }) {\n return (\n <Typography variant=\"overline\" color=\"text.secondary\">\n {props.children}\n </Typography>\n )\n}\n\n/**\n * No-code function builder (Component Builder, AGL-92): the mockup's Edit\n * Function dialog — Parameters with required toggles, local Variables,\n * numbered conditional operation cards (If below is TRUE / Then do this /\n * Otherwise do this), a Return value select, and a test-run panel driving\n * the shared evaluator. Definitions persist to `hosts/{hostId}/functions`;\n * prop/event wiring lands with AGL-93.\n */\nexport function HostFunctionsCard(props: HostFunctionsCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const createHostResource = useHostResourceApi()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n const { org } = props\n const {\n data: functionDocs,\n status: functionsStatus,\n /**\n * The rows this editor is seeded from are unconfirmed by the server\n * (AGL-1358). Editing destructures a whole stored function into `draft`\n * and writes `{...definition}` back, so `merge: true` protects nothing —\n * the payload is literally every field of the definition. `parameters`\n * and `operations` are arrays, which a merge replaces wholesale rather\n * than diffing, so a cached seed does not lose one edit: it restores that\n * snapshot's entire logic body and parameter list, and every caller's\n * arguments are positional against the list it just reverted.\n */\n fromCache: functionsFromCache,\n } = useFirestoreCollection<any>(\n /*\n * ORDERED AND CEILINGED, deliberately not paged by the query (AGL-2501) —\n * the same decision as the variables card beside it, for the same two\n * reasons.\n *\n * `limit(100)` alone is answered in DOCUMENT-ID order, so the window is a\n * pseudo-random hundred that the `localeCompare` below dresses up as an\n * alphabetical list, and nothing said the list was bounded.\n *\n * `collectionCeiling` does not change WHICH hundred — document-id order is\n * what the bare cap already returned. What it changes is that the order is\n * NAMED, so the obvious next edit is caught: ordering on `name` would HIDE\n * every function written without one rather than mis-sorting the list, and\n * `/api/hosts/resources` validates no field for presence while\n * `IMPORTABLE_FIELDS.functions` copies one only if the export carried it.\n *\n * The QUERY is not paged because `nameTaken` below tests the draft against\n * these rows: case-insensitive uniqueness is what keeps legacy\n * `{{fn:name(...)}}` resolution unambiguous (AGL-185), and on a ten-row\n * server page that check would compare a new function against a tenth of\n * the site and create the duplicate it exists to prevent.\n */\n () =>\n collectionCeiling(\n collection(firestore, 'hosts', hostId, 'functions'),\n FUNCTION_CEILING,\n ),\n [firestore, hostId],\n { idField: '$id' },\n )\n const { rows: readFunctions, truncated: functionsTruncated } =\n ceilingedWindow<any>(functionDocs, FUNCTION_CEILING)\n // Sorting is safe here in a way it is not on a paged list: these rows are\n // the whole collection below the ceiling, not a slice of one.\n const functions = useMemo(\n () =>\n readFunctions\n .filter((definition: any) => !definition.deletedAt)\n .sort((a: any, b: any) =>\n String(a.name ?? '').localeCompare(String(b.name ?? '')),\n ),\n [readFunctions],\n )\n // The page is a SLICE: the rows are already in hand and `nameTaken` needs\n // all of them.\n const [page, setPage] = useState(0)\n const [pageSize, setPageSize] = useState(TABLE_PAGE_SIZE_DEFAULT)\n const visibleFunctions = useMemo(\n () => functions.slice(page * pageSize, page * pageSize + pageSize),\n [functions, page, pageSize],\n )\n /**\n * The function HEAD-COUNT is a server aggregate, not the length of the\n * capped listener (AGL-1716, the AGL-1706 shape) — the same fix as the\n * variables card beside it, for the same reason.\n *\n * The listener is `limit(100)` and `functions.length` fed\n * `checkQuota(org, 'functionsPerHost', …)`, whose bands are 1 / 10 / 50 /\n * 250 / 500 / 1,000. Everything from Business up sits above the window, so\n * on those plans the gate compared 100 against hundreds and could never\n * refuse, while `api/hosts/resources` counted the collection and did.\n *\n * LIVE functions, as that route counts them (AGL-3918): a deleted\n * function frees its slot. Every document less the tombstones\n * (`getLiveCountFromServer`). A create or a delete moves the number, so\n * both re-read it.\n */\n const [functionCountEpoch, setFunctionCountEpoch] = useState(0)\n const [serverFunctionCount, setServerFunctionCount] = useState<number | null>(\n null,\n )\n useEffect(() => {\n let active = true\n void getLiveCountFromServer(collection(firestore, 'hosts', hostId, 'functions'))\n .then((count) => {\n if (active) setServerFunctionCount(count)\n })\n .catch(() => {\n // Falls back to the loaded rows — a LOWER bound and the prior\n // behaviour, never 0, which `checkQuota` would answer as \"no usage\"\n // on a site that is over its band.\n })\n return () => {\n active = false\n }\n }, [firestore, hostId, functionCountEpoch])\n const functionCount = serverFunctionCount ?? functions.length\n\n const [draft, setDraft] = useState<FunctionDraft | null>(null)\n\n // Where-used dialog (AGL-193).\n const [usage, setUsage] = useState<{\n name: string\n result: WhereUsedResult\n } | null>(null)\n const [usageLoading, setUsageLoading] = useState<string | null>(null)\n\n const [testArgs, setTestArgs] = useState<Record<string, string>>({})\n const [testResult, setTestResult] = useState<string | null>(null)\n\n const patch = useCallback(\n (updater: (previous: FunctionDraft) => FunctionDraft) =>\n setDraft((previous) => (previous ? updater(previous) : previous)),\n [],\n )\n\n /**\n * The shell's zone renderer (AGL-3603), for what other plugins add beside\n * Add function and inside a saved function's editor; `null` outside the\n * console shell.\n */\n const ExtensionZone = useConsoleWidgetSlot()\n /*\n * Opens a function another plugin proposed in this editor, unsaved: a new\n * one as Add function opens one — so the plan's cap is asked first — and a\n * change to a saved one in place of what the editor holds. Save is the\n * only write.\n */\n const propose = useCallback(\n (proposal: LogicProposal) => {\n if (proposal.kind !== 'function') return false\n if (!proposal.functionId) {\n const quota = checkQuota(org, 'functionsPerHost', functionCount)\n if (!quota.allowed) {\n enqueueSnackbar(`Function limit reached (${quota.limit}) — upgrade in Billing`, {\n variant: 'warning',\n persist: false,\n })\n return false\n }\n }\n setTestArgs({})\n setTestResult(null)\n setDraft({ ...proposal.definition, id: proposal.functionId })\n return true\n },\n [org, functionCount, enqueueSnackbar],\n )\n /*\n * The saved function the editor has open, named as it is STORED: a rename\n * being typed is not a different function.\n */\n const storedName = draft?.id\n ? functions.find((row: any) => row.$id === draft.id)?.name ?? draft.name\n : null\n\n const names = [\n ...(draft?.parameters ?? []).map((parameter) => parameter.name),\n ...(draft?.variables ?? []).map((variable) => variable.name),\n ].filter((name) => VARIABLE_NAME_PATTERN.test(name))\n\n /**\n * The site's variables, for the formula builder's value picker\n * (AGL-3757). Read the first time a builder opens, like the test run's\n * read below, so an author who never builds a formula costs nothing.\n */\n const [siteVariables, setSiteVariables] = useState<HostVariable[] | null>(\n null,\n )\n const loadSiteVariables = useCallback(() => {\n if (siteVariables) return\n setSiteVariables([])\n getDocs(query(collection(firestore, 'hosts', hostId, 'variables'), limit(100)))\n .then((snapshot) => {\n const rows: HostVariable[] = []\n snapshot.forEach((row) => {\n const data = row.data() as HostVariable & { deletedAt?: unknown }\n if (data?.name && !data.deletedAt) rows.push(data)\n })\n setSiteVariables(rows)\n })\n .catch((error) => {\n // The builder still offers the function's own names.\n console.error(error)\n })\n }, [siteVariables, firestore, hostId])\n const formulaNameOptions = formulaNames({\n parameters: draft?.parameters ?? [],\n locals: draft?.variables ?? [],\n siteVariables: siteVariables ?? [],\n })\n\n // Case-insensitive uniqueness (AGL-185): function names must stay\n // unambiguous for legacy {{fn:name(...)}} token resolution.\n const nameTaken = Boolean(\n draft &&\n functions.some(\n (definition: any) =>\n String(definition.name ?? '').toLowerCase() ===\n draft.name.trim().toLowerCase() && definition.$id !== draft.id,\n ),\n )\n\n /**\n * A test run sees what a published page sees (AGL-3202): the site\n * variables the draft names. Read on the click, and only when the draft\n * names something outside itself, so opening this card still costs the one\n * functions window and nothing else — a listener here would bill a hundred\n * variable reads to every author who never presses Run.\n */\n const handleTestRun = useCallback(async () => {\n if (!draft) return\n let globals: Record<string, number | string | boolean> = {}\n if (functionReferencedNames(draft).length) {\n try {\n const snapshot = await getDocs(\n query(collection(firestore, 'hosts', hostId, 'variables'), limit(100)),\n )\n const lookup: Record<string, HostVariable> = {}\n snapshot.forEach((row) => {\n const data = row.data() as HostVariable & { deletedAt?: unknown }\n if (data?.name && !data.deletedAt) lookup[row.id] = data\n })\n globals = functionGlobals(draft, lookup)\n } catch (error) {\n // The run still happens: an unreadable variable list reads as the\n // evaluator's own \"Unknown name\", which names what was missing.\n console.error(error)\n }\n }\n const result = evaluateHostFunction(draft, testArgs, { globals })\n setTestResult(\n result.ok === false\n ? `Error: ${result.error}`\n : `Result: ${String(result.value)}`,\n )\n }, [draft, testArgs, firestore, hostId])\n\n const handleSave = useCallback(async () => {\n if (!draft || !draft.name.trim() || nameTaken) return\n const { id: draftId, ...definition } = draft\n const fields = { ...definition, name: draft.name.trim().slice(0, 60) }\n try {\n if (draftId) {\n /**\n * Edit stays client-direct (no quota consumed) — and is refused when\n * its seed was never confirmed by the server (AGL-1358). `fields` is\n * the whole definition spread out of the listener row, so `merge:\n * true` has nothing left to protect.\n *\n * The guard WRAPS the write. An early return is a shape you can keep\n * while losing the protection; here the write is only reachable\n * through the verdict.\n */\n const verdict = await writeGuardedBySeed(\n {\n subject: 'function',\n unreadable: functionsStatus === 'error',\n fromCache: functionsFromCache,\n },\n async () => {\n await writeSiteWideChange({\n firestore,\n user,\n hostId,\n write: (batch) =>\n batch.set(\n doc(firestore, 'hosts', hostId, 'functions', draftId),\n { ...fields, updatedAt: Timestamp.now() },\n { merge: true },\n ),\n })\n },\n )\n // Before `setDraft(null)`, so a refusal keeps the dialog open with\n // the whole edited body and its test run still on screen.\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n } else {\n // New function rides the quota-enforcing resources API (AGL-473).\n await createHostResource({ hostId, resource: 'function', data: fields })\n // A create moves the count; the one-shot aggregate below does not\n // refresh itself the way the listener refreshes the rows.\n setFunctionCountEpoch((epoch) => epoch + 1)\n }\n setDraft(null)\n setTestResult(null)\n enqueueSnackbar('Function saved', { variant: 'success', persist: false })\n } catch (error: any) {\n console.error(error)\n enqueueSnackbar(error?.message ?? 'An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n }, [\n user,\n draft,\n nameTaken,\n firestore,\n hostId,\n createHostResource,\n enqueueSnackbar,\n functionsStatus,\n functionsFromCache,\n ])\n\n const handleShowUsage = useCallback(\n (definition: any) => async () => {\n setUsageLoading(definition.$id)\n const result = await fetchWhereUsed(user as any, {\n hostId,\n kind: 'function',\n id: definition.$id,\n name: definition.name,\n })\n setUsageLoading(null)\n setUsage({ name: definition.name, result })\n },\n [user, hostId],\n )\n\n const handleDelete = useCallback(\n (definition: any) => async () => {\n // Dependents warning (AGL-187): screens/layouts binding the function\n // and workflow steps calling it.\n const scan = await fetchWhereUsed(user as any, {\n hostId,\n kind: 'function',\n id: definition.$id,\n name: definition.name,\n })\n const confirmed = await confirm({\n title: 'Delete this function?',\n description: scan.total\n ? `\"${definition.name}\" is used in ${summarizeDependents(scan)} ` +\n 'and those bindings and workflow steps will stop running.'\n : `\"${definition.name}\" will no longer be runnable.`,\n confirmationText: 'Delete',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n await writeSiteWideChange({\n firestore,\n user,\n hostId,\n write: (batch) =>\n batch.update(\n doc(firestore, 'hosts', hostId, 'functions', definition.$id),\n { deletedAt: Timestamp.now() },\n ),\n })\n // Deleting frees the slot (AGL-3918), so the head-count is re-read.\n setFunctionCountEpoch((epoch) => epoch + 1)\n enqueueSnackbar('Function deleted', {\n variant: 'success',\n persist: false,\n })\n },\n [user, confirm, firestore, hostId, enqueueSnackbar],\n )\n\n const setRow = (\n section: 'then' | 'otherwise',\n operationIndex: number,\n rowIndex: number,\n key: 'set' | 'expression',\n value: string,\n ) =>\n patch((previous) => {\n const operations = previous.operations.map((operation, index) =>\n index === operationIndex\n ? {\n ...operation,\n [section]: operation[section].map((row, index2) =>\n index2 === rowIndex ? { ...row, [key]: value } : row,\n ),\n }\n : operation,\n )\n return { ...previous, operations }\n })\n\n const renderSetRows = (section: 'then' | 'otherwise', operationIndex: number) => {\n const operation = draft?.operations[operationIndex]\n if (!operation) return null\n return (\n <Stack spacing={1}>\n {operation[section].map((row, rowIndex) => (\n <Stack\n key={rowIndex}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Typography variant=\"caption\">{'SET'}</Typography>\n <TextField\n value={row.set}\n onChange={(event) =>\n setRow(section, operationIndex, rowIndex, 'set', event.target.value)\n }\n size=\"small\"\n select\n sx={{ minWidth: 90 }}\n >\n {names.map((name) => (\n <MenuItem key={name} value={name}>\n {name}\n </MenuItem>\n ))}\n </TextField>\n <Typography variant=\"caption\">{'equal to'}</Typography>\n <TextField\n value={row.expression}\n placeholder=\"P1 + P2\"\n onChange={(event) =>\n setRow(\n section,\n operationIndex,\n rowIndex,\n 'expression',\n event.target.value,\n )\n }\n size=\"small\"\n sx={{ flex: 1 }}\n />\n <FormulaBuilderButton\n current={row.expression}\n names={formulaNameOptions}\n onOpen={loadSiteVariables}\n onUse={(expression) =>\n setRow(section, operationIndex, rowIndex, 'expression', expression)\n }\n />\n <IconButton\n size=\"small\"\n aria-label=\"remove operation row\"\n onClick={() =>\n patch((previous) => ({\n ...previous,\n operations: previous.operations.map((op, index) =>\n index === operationIndex\n ? {\n ...op,\n [section]: op[section].filter(\n (_, index2) => index2 !== rowIndex,\n ),\n }\n : op,\n ),\n }))\n }\n >\n {'×'}\n </IconButton>\n </Stack>\n ))}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() =>\n patch((previous) => ({\n ...previous,\n operations: previous.operations.map((op, index) =>\n index === operationIndex\n ? {\n ...op,\n [section]: [...op[section], { set: '', expression: '' }],\n }\n : op,\n ),\n }))\n }\n >\n {'Add set'}\n </Button>\n </Stack>\n )\n }\n\n return (\n <CardDisplay\n header={'Functions'}\n help={pluginDocsHelp('bindings', { anchor: '#functions-card' })}\n // Another way to start a function (AGL-3603), in the card's header.\n actions={\n ExtensionZone ? (\n <ExtensionZone\n slot={HOST_LOGIC_ZONE.id}\n hostId={hostId}\n orgId={org?.$id}\n kind=\"function\"\n propose={propose}\n />\n ) : null\n }\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1}>\n {functions.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Build no-code logic: parameters in, conditional operations, ' +\n 'a value out. Wire functions into components and workflows ' +\n 'as the builder grows.'}\n </Typography>\n ) : (\n visibleFunctions.map((definition: any) => (\n <Stack\n key={definition.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Stack sx={{ flex: 1, minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {definition.name}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {`${(definition.parameters ?? []).map((p: any) => p.name).join(', ') || 'no parameters'} → ${definition.returnValue || '—'}`}\n </Typography>\n </Stack>\n <Button\n size=\"small\"\n disabled={usageLoading === definition.$id}\n onClick={handleShowUsage(definition)}\n >\n {usageLoading === definition.$id ? 'Scanning…' : 'Usage'}\n </Button>\n <Button\n size=\"small\"\n onClick={() => {\n setTestArgs({})\n setTestResult(null)\n setDraft({\n id: definition.$id,\n name: definition.name ?? '',\n parameters: definition.parameters ?? [],\n variables: definition.variables ?? [],\n operations: definition.operations ?? [],\n returnValue: definition.returnValue ?? '',\n })\n }}\n >\n {'Edit'}\n </Button>\n <Button\n size=\"small\"\n color=\"error\"\n onClick={handleDelete(definition)}\n >\n {'Delete'}\n </Button>\n </Stack>\n ))\n )}\n {functions.length === 0 ? null : (\n <ListPagination\n page={page}\n pageSize={pageSize}\n rowCount={visibleFunctions.length}\n // The functions the card HOLDS. Not `functionCount`, which is the\n // site's total including soft-deleted rows and answers the quota's\n // question rather than the reader's.\n count={functions.length}\n onPageChange={setPage}\n onPageSizeChange={setPageSize}\n />\n )}\n {functionsTruncated ? (\n <Alert severity=\"info\">\n {`Showing ${FUNCTION_CEILING} functions, ordered by id. This site ` +\n 'has more — the duplicate-name check below only covers the ' +\n 'ones listed here, so a name may already be taken by one that ' +\n 'is not.'}\n </Alert>\n ) : null}\n <Button\n size=\"small\"\n color=\"primary\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() => {\n // Plan cap (AGL-99): dark-launch — plan-less workspaces uncapped.\n // The site's functions, not this page of them (AGL-1716).\n const quota = checkQuota(org, 'functionsPerHost', functionCount)\n if (!quota.allowed) {\n return void enqueueSnackbar(\n `Function limit reached (${quota.limit}) — upgrade in Billing`,\n { variant: 'warning', persist: false },\n )\n }\n setTestArgs({})\n setTestResult(null)\n setDraft(emptyDraft())\n }}\n >\n {'Add function'}\n </Button>\n </Stack>\n\n <Dialog\n open={Boolean(draft)}\n onClose={() => setDraft(null)}\n maxWidth=\"sm\"\n fullWidth\n >\n <DialogTitle>\n {draft?.id ? 'Edit Function' : 'Add Function'}\n </DialogTitle>\n <DialogContent\n sx={{ display: 'flex', flexDirection: 'column', gap: 1.5, pt: 1 }}\n >\n {ExtensionZone && draft?.id && storedName != null ? (\n <ExtensionZone\n slot={LOGIC_FUNCTION_EDITOR_ZONE.id}\n hostId={hostId}\n orgId={org?.$id}\n target={{ id: draft.id, name: storedName }}\n propose={propose}\n />\n ) : null}\n <TextField\n label=\"Name\"\n helperText={\n nameTaken\n ? 'A function with this name already exists'\n : 'Used to identify the function'\n }\n error={nameTaken}\n value={draft?.name ?? ''}\n onChange={(event) =>\n patch((previous) => ({ ...previous, name: event.target.value }))\n }\n size=\"small\"\n autoFocus\n sx={{ mt: 1 }}\n />\n\n <SectionLabel>{'Parameters'}</SectionLabel>\n {(draft?.parameters ?? []).map((parameter, index) => (\n <Stack\n key={index}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <TextField\n label=\"Name\"\n value={parameter.name}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n parameters: previous.parameters.map((p, index2) =>\n index2 === index\n ? {\n ...p,\n name: event.target.value.replace(\n /[^a-zA-Z0-9_]/g,\n '',\n ),\n }\n : p,\n ),\n }))\n }\n size=\"small\"\n sx={{ width: 110 }}\n />\n <TextField\n label=\"Type\"\n value={parameter.type}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n parameters: previous.parameters.map((p, index2) =>\n index2 === index\n ? { ...p, type: event.target.value as FunctionValueType }\n : p,\n ),\n }))\n }\n size=\"small\"\n select\n sx={{ width: 130 }}\n >\n {VALUE_TYPES.map((type) => (\n <MenuItem key={type.value} value={type.value}>\n {type.label}\n </MenuItem>\n ))}\n </TextField>\n <Stack\n direction=\"row\"\n spacing={0.5}\n sx={{ alignItems: 'center', flex: 1 }}\n >\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Required'}\n </Typography>\n <Switch\n size=\"small\"\n checked={Boolean(parameter.required)}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n parameters: previous.parameters.map((p, index2) =>\n index2 === index\n ? { ...p, required: event.target.checked }\n : p,\n ),\n }))\n }\n />\n </Stack>\n <IconButton\n size=\"small\"\n aria-label=\"remove parameter\"\n onClick={() =>\n patch((previous) => ({\n ...previous,\n parameters: previous.parameters.filter(\n (_, index2) => index2 !== index,\n ),\n }))\n }\n >\n {'×'}\n </IconButton>\n </Stack>\n ))}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() =>\n patch((previous) => ({\n ...previous,\n parameters: [\n ...previous.parameters,\n {\n name: `P${previous.parameters.length + 1}`,\n type: 'number',\n required: false,\n },\n ],\n }))\n }\n >\n {'Add parameter'}\n </Button>\n\n {(draft?.parameters ?? []).length ? (\n <>\n <SectionLabel>{'What visitors see'}</SectionLabel>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Used by a Function Widget on a page. A parameter with ' +\n 'choices is asked as a list — Add choice gives it one — a ' +\n 'number as a number box and a true/false as a switch.'}\n </Typography>\n {(draft?.parameters ?? []).map((parameter, index) => (\n <ParameterAudienceFields\n // Keyed by position: the name is being edited one row up.\n key={index}\n parameter={parameter}\n onChange={(next) =>\n patch((previous) => ({\n ...previous,\n parameters: previous.parameters.map((p, index2) =>\n index2 === index ? next : p,\n ),\n }))\n }\n />\n ))}\n </>\n ) : null}\n\n <SectionLabel>{'Variables'}</SectionLabel>\n {(draft?.variables ?? []).map((variable, index) => (\n <Stack\n key={index}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <TextField\n label=\"Name\"\n value={variable.name}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n variables: previous.variables.map((v, index2) =>\n index2 === index\n ? {\n ...v,\n name: event.target.value.replace(\n /[^a-zA-Z0-9_]/g,\n '',\n ),\n }\n : v,\n ),\n }))\n }\n size=\"small\"\n sx={{ width: 110 }}\n />\n <TextField\n label=\"Type\"\n value={variable.type}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n variables: previous.variables.map((v, index2) =>\n index2 === index\n ? { ...v, type: event.target.value as FunctionValueType }\n : v,\n ),\n }))\n }\n size=\"small\"\n select\n sx={{ width: 130 }}\n >\n {VALUE_TYPES.map((type) => (\n <MenuItem key={type.value} value={type.value}>\n {type.label}\n </MenuItem>\n ))}\n </TextField>\n <IconButton\n size=\"small\"\n aria-label=\"remove variable\"\n sx={{ ml: 'auto' }}\n onClick={() =>\n patch((previous) => ({\n ...previous,\n variables: previous.variables.filter(\n (_, index2) => index2 !== index,\n ),\n }))\n }\n >\n {'×'}\n </IconButton>\n </Stack>\n ))}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() =>\n patch((previous) => ({\n ...previous,\n variables: [\n ...previous.variables,\n { name: `V${previous.variables.length + 1}`, type: 'number' },\n ],\n }))\n }\n >\n {'Add variable'}\n </Button>\n\n <SectionLabel>{'Operations'}</SectionLabel>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Press ƒx beside a box to build its formula by picking values — ' +\n 'add, smallest of, format as money and more. A box also takes ' +\n 'a formula written out: + − × ÷ and parentheses, any site ' +\n 'variable by its name (a dictionary’s members as ' +\n 'name.member), and ' +\n `${FUNCTION_BUILTIN_NAMES.map((name) => `${name}()`).join(', ')}.`}\n </Typography>\n {(draft?.operations ?? []).map((operation, index) => (\n <Stack\n key={index}\n spacing={1}\n sx={{\n border: 1,\n borderColor: 'divider',\n borderRadius: 1,\n p: 1.5,\n }}\n >\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`${index + 1} · If below is TRUE`}\n </Typography>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <TextField\n value={operation.if.left}\n placeholder=\"P1\"\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n operations: previous.operations.map((op, index2) =>\n index2 === index\n ? { ...op, if: { ...op.if, left: event.target.value } }\n : op,\n ),\n }))\n }\n size=\"small\"\n sx={{ flex: 1 }}\n />\n <FormulaBuilderButton\n current={operation.if.left}\n names={formulaNameOptions}\n onOpen={loadSiteVariables}\n onUse={(expression) =>\n patch((previous) => ({\n ...previous,\n operations: previous.operations.map((op, index2) =>\n index2 === index\n ? { ...op, if: { ...op.if, left: expression } }\n : op,\n ),\n }))\n }\n />\n <TextField\n value={operation.if.comparator}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n operations: previous.operations.map((op, index2) =>\n index2 === index\n ? {\n ...op,\n if: {\n ...op.if,\n comparator: event.target\n .value as FunctionComparator,\n },\n }\n : op,\n ),\n }))\n }\n size=\"small\"\n select\n sx={{ width: 84 }}\n >\n {COMPARATORS.map((comparator) => (\n <MenuItem key={comparator} value={comparator}>\n {comparator}\n </MenuItem>\n ))}\n </TextField>\n <TextField\n value={operation.if.right}\n placeholder=\"P2\"\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n operations: previous.operations.map((op, index2) =>\n index2 === index\n ? { ...op, if: { ...op.if, right: event.target.value } }\n : op,\n ),\n }))\n }\n size=\"small\"\n sx={{ flex: 1 }}\n />\n <FormulaBuilderButton\n current={operation.if.right}\n names={formulaNameOptions}\n onOpen={loadSiteVariables}\n onUse={(expression) =>\n patch((previous) => ({\n ...previous,\n operations: previous.operations.map((op, index2) =>\n index2 === index\n ? { ...op, if: { ...op.if, right: expression } }\n : op,\n ),\n }))\n }\n />\n </Stack>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Then do this'}\n </Typography>\n {renderSetRows('then', index)}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Otherwise do this'}\n </Typography>\n {renderSetRows('otherwise', index)}\n </Stack>\n ))}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() =>\n patch((previous) => ({\n ...previous,\n operations: [\n ...previous.operations,\n {\n if: { left: '', comparator: '<=', right: '' },\n then: [{ set: '', expression: '' }],\n otherwise: [],\n },\n ],\n }))\n }\n >\n {'Add operation'}\n </Button>\n\n <TextField\n label=\"Return value\"\n value={draft?.returnValue ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n returnValue: event.target.value,\n }))\n }\n size=\"small\"\n select\n >\n {names.map((name) => (\n <MenuItem key={name} value={name}>\n {name}\n </MenuItem>\n ))}\n </TextField>\n\n <Divider />\n <SectionLabel>{'Test run'}</SectionLabel>\n <Stack direction=\"row\" spacing={1} sx={{ flexWrap: 'wrap' }}>\n {(draft?.parameters ?? []).map((parameter) => (\n <TextField\n key={parameter.name}\n label={parameter.name}\n value={testArgs[parameter.name] ?? ''}\n onChange={(event) =>\n setTestArgs((previous) => ({\n ...previous,\n [parameter.name]: event.target.value,\n }))\n }\n size=\"small\"\n sx={{ width: 110 }}\n />\n ))}\n <Button size=\"small\" color=\"primary\" onClick={handleTestRun}>\n {'Run'}\n </Button>\n </Stack>\n {testResult ? (\n <Alert\n severity={testResult.startsWith('Error') ? 'warning' : 'success'}\n >\n {testResult}\n </Alert>\n ) : null}\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setDraft(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={!draft?.name.trim() || nameTaken}\n onClick={handleSave}\n >\n {'Done'}\n </Button>\n </DialogActions>\n </Dialog>\n <WhereUsedDialog\n hostId={hostId}\n usage={usage}\n onClose={() => setUsage(null)}\n />\n </CardDisplay>\n )\n}\nHostFunctionsCard.displayName = 'HostFunctionsCard'\n\nexport default HostFunctionsCard\n"],"names":["checkQuota","evaluateHostFunction","FUNCTION_BUILTIN_NAMES","functionGlobals","functionReferencedNames","pluginDocsHelp","VARIABLE_NAME_PATTERN","ceilingedWindow","collectionCeiling","CardDisplay","useConfirmationContext","ListPagination","TABLE_PAGE_SIZE_DEFAULT","useSnackbar","Timestamp","Alert","Button","Dialog","DialogActions","DialogContent","DialogTitle","Divider","IconButton","MenuItem","Stack","Switch","TextField","Typography","collection","doc","getDocs","limit","query","getLiveCountFromServer","useCallback","useEffect","useMemo","useState","useFirestore","useFirestoreCollection","useHostResourceApi","useUser","writeGuardedBySeed","writeSiteWideChange","ParameterChoicesEditor","WhereUsedDialog","FormulaBuilderButton","formulaNames","useConsoleWidgetSlot","HOST_LOGIC_ZONE","LOGIC_FUNCTION_EDITOR_ZONE","fetchWhereUsed","summarizeDependents","FUNCTION_CEILING","VALUE_TYPES","value","label","COMPARATORS","emptyDraft","id","name","parameters","type","required","variables","operations","if","left","comparator","right","then","set","expression","otherwise","returnValue","ParameterAudienceFields","props","parameter","onChange","assign","field","next","options","startsAsChoices","length","map","option","spacing","direction","sx","alignItems","variant","color","width","flexShrink","noWrap","placeholder","event","target","slice","size","flex","select","some","choice","defaultValue","em","replace","slotProps","htmlInput","inputMode","undefined","parameterName","nextOptions","SectionLabel","children","HostFunctionsCard","functions","hostId","firestore","data","user","createHostResource","enqueueSnackbar","confirm","org","functionDocs","status","functionsStatus","fromCache","functionsFromCache","idField","rows","readFunctions","truncated","functionsTruncated","filter","definition","deletedAt","sort","a","b","String","localeCompare","page","setPage","pageSize","setPageSize","visibleFunctions","functionCountEpoch","setFunctionCountEpoch","serverFunctionCount","setServerFunctionCount","active","count","catch","functionCount","draft","setDraft","usage","setUsage","usageLoading","setUsageLoading","testArgs","setTestArgs","testResult","setTestResult","patch","updater","previous","ExtensionZone","propose","proposal","kind","functionId","quota","allowed","persist","storedName","find","row","$id","names","variable","test","siteVariables","setSiteVariables","loadSiteVariables","snapshot","forEach","push","error","console","formulaNameOptions","locals","nameTaken","Boolean","toLowerCase","trim","handleTestRun","globals","lookup","result","ok","handleSave","draftId","fields","verdict","subject","unreadable","write","batch","updatedAt","now","merge","message","resource","epoch","allowDuplicate","handleShowUsage","handleDelete","scan","confirmed","title","description","total","confirmationText","confirmationButtonProps","update","setRow","section","operationIndex","rowIndex","key","operation","index","index2","renderSetRows","minWidth","current","onOpen","onUse","aria-label","onClick","op","_","alignSelf","header","help","anchor","actions","slot","orgId","contentGutterX","contentGutterY","p","join","disabled","rowCount","onPageChange","onPageSizeChange","severity","open","onClose","maxWidth","fullWidth","display","flexDirection","gap","pt","helperText","autoFocus","mt","checked","v","ml","border","borderColor","borderRadius","flexWrap","startsWith","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;;AAEA,SAEEA,UAAU,EACVC,oBAAoB,EACpBC,sBAAsB,EAEtBC,eAAe,EACfC,uBAAuB,EAKvBC,cAA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ACtF,UAAUjB,IAAI,CAAC,YAAxBuG,2BAA4B;4CACnCrF,UAAU,CAACmB,QACTmE,YAAY,CAACK,WAAc,aACtBA;wDACH,CAAC5F,UAAUjB,IAAI,CAAC,EAAEqC,MAAMC,MAAM,CAAC3C,KAAK;;4CAGxC6C,MAAK;4CACLX,IAAI;gDAAEI,OAAO;4CAAI;2CAVZhB,UAAUjB,IAAI;;kDAavB,KAAC5C;wCAAOoF,MAAK;wCAAQR,OAAM;wCAAUuJ,SAAS5C;kDAC3C;;;;4BAGJlC,2BACC,KAACtJ;gCACCsP,UAAUhG,WAAWmH,UAAU,CAAC,WAAW,YAAY;0CAEtDnH;iCAED;;;kCAEN,MAACnJ;;0CACC,KAACF;gCAAOmO,SAAS,IAAMrF,SAAS;0CAAQ;;0CACxC,KAAC9I;gCACC2E,SAAQ;gCACRC,OAAM;gCACNqK,UAAU,EAACpG,yBAAAA,MAAOjG,IAAI,CAAC0I,IAAI,OAAMH;gCACjCgD,SAASvC;0CAER;;;;;;0BAIP,KAAC/J;gBACCyE,QAAQA;gBACRyC,OAAOA;gBACPwG,SAAS,IAAMvG,SAAS;;;;AAIhC;AACA5C,kBAAkBqK,WAAW,GAAG;AAEhC,eAAerK,kBAAiB"}
@@ -31,7 +31,8 @@ import { TABLE_PAGE_SIZE_DEFAULT } from "@aglyn/shared-ui-jsx/const/table-pagina
31
31
  import { useSnackbar } from "@aglyn/shared-ui-snackstack";
32
32
  import { Timestamp } from "@aglyn/shared-util-timestamp";
33
33
  import { Alert, Button, Dialog, DialogActions, DialogContent, DialogTitle, MenuItem, Stack, Switch, TextField, Typography } from "@mui/material";
34
- import { collection, doc, getCountFromServer } from "firebase/firestore";
34
+ import { collection, doc } from "firebase/firestore";
35
+ import { getLiveCountFromServer } from "@aglyn/aglyn/app-utils/live-document-count.client";
35
36
  import { lazy, Suspense, useCallback, useEffect, useMemo, useState } from "react";
36
37
  import { useFirestore, useFirestoreCollection, useHostResourceApi, useUser, writeGuardedBySeed } from "@aglyn/tenant-feature-instance";
37
38
  import { writeSiteWideChange } from "@aglyn/tenant-feature-instance/hooks/helpers/site-wide-change";
@@ -257,22 +258,20 @@ const StructuredValueEditor = /*#__PURE__*/ lazy(()=>import("./structured-value-
257
258
  * the collection and did. The card offered headroom that did not exist and
258
259
  * then failed the create.
259
260
  *
260
- * UNFILTERED, matching the enforcing route: it runs a plain
261
- * `collection('variables').count()` for this quota — its `softDeletes`
262
- * branch governs only the flat per-host webhook cap — so a soft-deleted
263
- * variable has always counted toward `variablesPerHost` server-side while
264
- * this card excluded it. The card now asks the route's question in the
261
+ * LIVE variables, as the enforcing route counts them (AGL-3918): a
262
+ * deleted variable frees its slot. Every document less the tombstones
263
+ * (`getLiveCountFromServer`), so the card asks the route's question in the
265
264
  * route's terms, which is the only thing that makes a console gate a
266
265
  * useful prediction of the route's verdict.
267
266
  *
268
- * THE LIST KEEPS ITS CAP. Only a create moves the number (deletes here are
269
- * soft, and the route counts them), so that is where it is re-read.
267
+ * THE LIST KEEPS ITS CAP. A create or a delete moves the number, so both
268
+ * re-read it.
270
269
  */ const [variableCountEpoch, setVariableCountEpoch] = useState(0);
271
270
  const [serverVariableCount, setServerVariableCount] = useState(null);
272
271
  useEffect(()=>{
273
272
  let active = true;
274
- void getCountFromServer(collection(firestore, 'hosts', hostId, 'variables')).then((snapshot)=>{
275
- if (active) setServerVariableCount(snapshot.data().count);
273
+ void getLiveCountFromServer(collection(firestore, 'hosts', hostId, 'variables')).then((count)=>{
274
+ if (active) setServerVariableCount(count);
276
275
  }).catch(()=>{
277
276
  // Falls back to the loaded rows below — a LOWER bound, and this
278
277
  // card's prior behaviour. Deliberately not 0: `checkQuota` answers
@@ -444,6 +443,8 @@ const StructuredValueEditor = /*#__PURE__*/ lazy(()=>import("./structured-value-
444
443
  deletedAt: Timestamp.now()
445
444
  })
446
445
  });
446
+ // Deleting frees the slot (AGL-3918), so the head-count is re-read.
447
+ setVariableCountEpoch((epoch)=>epoch + 1);
447
448
  enqueueSnackbar('Variable deleted', {
448
449
  variant: 'success',
449
450
  persist: false
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/logic/src/lib/components/host-variables-card.component.tsx"],"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'use client'\n\nimport {\n type AglynOrgBilling,\n checkQuota,\n formatVariableValue,\n HOST_VARIABLE_TYPE_LABELS,\n type HostVariable,\n type HostVariableType,\n pluginDocsHelp,\n VARIABLE_NAME_PATTERN,\n} from '@aglyn/aglyn'\n/*\n * The MODULE, not the barrel, for the two PURE helpers. Every spec that renders\n * this card mocks `@aglyn/tenant-feature-instance` wholesale to stage its\n * Firestore hooks, and a query builder imported through that barrel disappears\n * under the mock — which fails as \"not a function\" in the component rather than\n * as anything about the test's subject. Neither of these is a hook.\n */\nimport {\n ceilingedWindow,\n collectionCeiling,\n} from '@aglyn/tenant-feature-instance/hooks/host-collection-queries'\nimport {\n pluginRecordListQuery,\n pluginRecordsFromRows,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-lists'\nimport { CardDisplay, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport { TABLE_PAGE_SIZE_DEFAULT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { Timestamp } from '@aglyn/shared-util-timestamp'\nimport {\n Alert,\n Button,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n MenuItem,\n Stack,\n Switch,\n TextField,\n Typography,\n} from '@mui/material'\nimport { collection, doc, getCountFromServer } from 'firebase/firestore'\nimport { lazy, Suspense, useCallback, useEffect, useMemo, useState } from 'react'\nimport {\n useFirestore,\n useFirestoreCollection,\n useHostResourceApi,\n useUser,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport { writeSiteWideChange } from '@aglyn/tenant-feature-instance/hooks/helpers/site-wide-change'\nimport WhereUsedDialog from './where-used-dialog.component'\nimport { useConsoleWidgetSlot } from '@aglyn/aglyn/app-utils/console-widget-slot-context'\nimport { HOST_LOGIC_ZONE, type LogicProposal } from './logic-zones'\nimport {\n fetchWhereUsed,\n summarizeDependents,\n type WhereUsedResult,\n} from '@aglyn/aglyn/app-utils/where-used'\n\n// The entry/item editor is its own chunk, loaded when a dictionary or list\n// variable is opened (AGL-3757).\nconst StructuredValueEditor = lazy(\n () => import('./structured-value-editor.component'),\n)\n\n/**\n * How many variables the card reads.\n *\n * A CEILING, not a page size — see the query, which explains why this list\n * cannot be paged by the server without making the duplicate-name check lie.\n */\nconst VARIABLE_CEILING = 100\n\n/**\n * How many workflows the computed-variable picker offers.\n *\n * Paid for only while the editor is open, which is what makes a ceiling this\n * size affordable: it is one reader mid-edit rather than every visitor to the\n * page.\n */\nconst WORKFLOW_OPTION_CEILING = 100\n\nexport interface HostVariablesCardProps {\n hostId: string\n /** Resolved entitlement source for quota checks (AGL-395). */\n org?: Partial<AglynOrgBilling>\n}\n\ninterface VariableDraft {\n /** Computed-source workflow doc id (AGL-261); name is the display hint. */\n workflowId: string\n id: string | null\n name: string\n type: HostVariableType\n value: string\n /** Workflow (by name) computing this variable at render (AGL-129). */\n workflowName: string\n}\n\n/** Per-type value editor: mirrors the mockup's type list. */\nfunction VariableValueField(props: {\n draft: VariableDraft\n onChange: (value: string) => void\n}) {\n const { draft, onChange } = props\n switch (draft.type) {\n case 'boolean':\n return (\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Switch\n checked={draft.value === 'true'}\n onChange={(event) =>\n onChange(event.target.checked ? 'true' : 'false')\n }\n />\n <Typography variant=\"body2\">\n {draft.value === 'true' ? 'True' : 'False'}\n </Typography>\n </Stack>\n )\n case 'date':\n case 'time':\n return (\n <TextField\n label=\"Value\"\n type={draft.type}\n value={draft.value}\n onChange={(event) => onChange(event.target.value)}\n size=\"small\"\n slotProps={{ inputLabel: { shrink: true } }}\n />\n )\n case 'number':\n return (\n <TextField\n label=\"Value\"\n value={draft.value}\n onChange={(event) =>\n onChange(event.target.value.replace(/[^0-9.eE+-]/g, ''))\n }\n size=\"small\"\n />\n )\n case 'dictionary':\n case 'collection':\n // Rows, never typed JSON (AGL-3757). Keyed by the draft and type so\n // opening another variable, or switching type, reads its value afresh.\n return (\n <Suspense fallback={null}>\n <StructuredValueEditor\n key={`${draft.id ?? 'new'}:${draft.type}`}\n shape={draft.type}\n value={draft.value}\n onChange={onChange}\n />\n </Suspense>\n )\n default:\n return (\n <TextField\n label=\"Value\"\n value={draft.value}\n onChange={(event) => onChange(event.target.value)}\n size=\"small\"\n multiline\n />\n )\n }\n}\n\n/**\n * Host variables (Component Builder, AGL-91): the mockup's Edit Variable\n * dialog — name + typed value — persisted to `hosts/{hostId}/variables`.\n * Any string prop can reference a variable with `{{name}}`; the org\n * compose pipeline resolves it at render. Soft delete keeps old tokens\n * rendering literally rather than breaking published pages.\n */\nexport function HostVariablesCard(props: HostVariablesCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const createHostResource = useHostResourceApi()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n const { org } = props\n // Where-used dependents dialog (AGL-187).\n const [usage, setUsage] = useState<{\n name: string\n result: WhereUsedResult\n } | null>(null)\n const [usageLoading, setUsageLoading] = useState<string | null>(null)\n const {\n data: variableDocs,\n status: variablesStatus,\n /**\n * The rows this editor is seeded from are unconfirmed by the server\n * (AGL-1358). Editing copies a whole stored variable into `draft` and\n * writes all of it back, so `merge: true` protects nothing — every field\n * is in the payload. `value` is the literal every `{{name}}` binding on\n * every published page resolves to, and `workflowId` is what rebinds a\n * computed variable to its source (AGL-261), so a cached seed can point\n * a live binding back at a value or a workflow the author replaced.\n */\n fromCache: variablesFromCache,\n } = useFirestoreCollection<any>(\n /*\n * ORDERED AND CEILINGED, deliberately not paged by the query (AGL-2501).\n *\n * `limit(100)` alone is answered in DOCUMENT-ID order, so the window is a\n * pseudo-random hundred that the `localeCompare` below arranges into a\n * convincing A-to-Z list. `variablesPerHost` runs to 5,000, so a Scale\n * site with three hundred variables sees a hundred of them and nothing\n * said so.\n *\n * `collectionCeiling` does not change WHICH hundred — document-id order is\n * what the bare cap already returned. What it changes is that the order is\n * NAMED, so the obvious next edit is caught: ordering on `name` would not\n * mis-sort this list, it would HIDE from it every variable written without\n * one, and `/api/hosts/resources` validates no field for presence while\n * `IMPORTABLE_FIELDS.variables` copies a name only if the exported\n * document carried it. The document name cannot be absent.\n *\n * The QUERY is not paged because `nameTaken` below tests the draft against\n * these rows. Case-insensitive uniqueness is what keeps legacy `{{name}}`\n * token resolution unambiguous (AGL-185), and on a ten-row server page\n * that check would compare a new variable against a tenth of the site and\n * cheerfully create the duplicate it exists to prevent.\n *\n * The check is still only as complete as the ceiling, and that is now\n * SAID rather than assumed: the notice under the list appears exactly when\n * the probe finds a variable this card did not read.\n */\n () =>\n collectionCeiling(\n collection(firestore, 'hosts', hostId, 'variables'),\n VARIABLE_CEILING,\n ),\n [firestore, hostId],\n { idField: '$id' },\n )\n const { rows: readVariables, truncated: variablesTruncated } =\n ceilingedWindow<any>(variableDocs, VARIABLE_CEILING)\n const [draft, setDraft] = useState<VariableDraft | null>(null)\n\n /** The shell's zone renderer (AGL-3603); `null` outside the console shell. */\n const ExtensionZone = useConsoleWidgetSlot()\n /**\n * The editor has been opened at least once in this session.\n *\n * A LATCH rather than `draft` itself, because the workflow picker below keys its\n * listeners on it. Tracking the dialog would tear that subscription down\n * on Cancel and pay for them again on the next Edit, so a merchant working\n * through ten variables would buy the same window ten times — worse than\n * the mount-time read this replaces. Latched, a reader who never edits pays\n * nothing and a reader who edits pays once.\n */\n const [editorOpened, setEditorOpened] = useState(false)\n if (draft && !editorOpened) setEditorOpened(true)\n /*\n * Workflow picker options (AGL-261): computed variables reference the\n * workflow by doc id instead of a typed name. The workflows are the\n * workflows plugin's, listed through the source it publishes (AGL-3080).\n *\n * READ WHEN THE EDITOR OPENS, not when the card mounts (AGL-2501). Nothing\n * outside the dialog below touches these rows — the table shows a computed\n * variable's stored `workflowName`, never a name looked up here — so an\n * unconditional listener would charge every visitor to this page for a\n * hundred workflows to fill a select most of them never see.\n *\n * Ceilinged and ordered for the same reason as the variables above: a bare\n * `limit` is answered in document-id order, so the `localeCompare` below\n * would arrange a pseudo-random hundred into a convincing alphabet and a\n * workflow past it could not be picked, with nothing saying why.\n */\n const { data: workflowDocs } = useFirestoreCollection<any>(\n () =>\n editorOpened\n ? pluginRecordListQuery('workflow', firestore, {\n hostId,\n limit: WORKFLOW_OPTION_CEILING + 1,\n })\n : null,\n [firestore, hostId, editorOpened],\n { idField: '$id' },\n )\n const { rows: readWorkflows, truncated: workflowOptionsTruncated } =\n ceilingedWindow<any>(workflowDocs, WORKFLOW_OPTION_CEILING)\n // Sorting the whole ceiling, not a page of it. The workflows plugin answers\n // live, named workflows only.\n const workflowOptions = pluginRecordsFromRows('workflow', readWorkflows)\n .map((workflow) => ({ id: workflow.id, name: workflow.name }))\n .sort((a, b) => a.name.localeCompare(b.name))\n /*\n * Sorting is safe HERE in a way it is not on a paged list: these rows are\n * the whole collection below the ceiling, not a slice of one, so the order\n * on screen is the order of everything the card holds.\n */\n const variables = useMemo(\n () =>\n readVariables\n .filter((variable: any) => !variable.deletedAt)\n .sort((a: any, b: any) =>\n String(a.name ?? '').localeCompare(String(b.name ?? '')),\n ),\n [readVariables],\n )\n // The page is a SLICE, because the rows are already in hand and `nameTaken`\n // needs all of them. What the card lacked was not a cheaper read but a\n // control: a hundred variables rendered as one wall.\n const [page, setPage] = useState(0)\n const [pageSize, setPageSize] = useState(TABLE_PAGE_SIZE_DEFAULT)\n const visibleVariables = useMemo(\n () => variables.slice(page * pageSize, page * pageSize + pageSize),\n [variables, page, pageSize],\n )\n /**\n * The variable HEAD-COUNT is a server aggregate, not the length of the\n * capped listener (AGL-1716, the AGL-1706 shape).\n *\n * The listener is `limit(100)` and `variables.length` was handed to\n * `checkQuota(org, 'variablesPerHost', …)`. The bands are 3 / 25 / 100 /\n * 1,000 / 5,000, so the window ties Pro's 100 and hides Business's 1,000\n * and Scale's 5,000 entirely: on those plans the gate compared 100 against\n * thousands and could never refuse, while `api/hosts/resources` counted\n * the collection and did. The card offered headroom that did not exist and\n * then failed the create.\n *\n * UNFILTERED, matching the enforcing route: it runs a plain\n * `collection('variables').count()` for this quota — its `softDeletes`\n * branch governs only the flat per-host webhook cap — so a soft-deleted\n * variable has always counted toward `variablesPerHost` server-side while\n * this card excluded it. The card now asks the route's question in the\n * route's terms, which is the only thing that makes a console gate a\n * useful prediction of the route's verdict.\n *\n * THE LIST KEEPS ITS CAP. Only a create moves the number (deletes here are\n * soft, and the route counts them), so that is where it is re-read.\n */\n const [variableCountEpoch, setVariableCountEpoch] = useState(0)\n const [serverVariableCount, setServerVariableCount] = useState<number | null>(\n null,\n )\n useEffect(() => {\n let active = true\n void getCountFromServer(collection(firestore, 'hosts', hostId, 'variables'))\n .then((snapshot) => {\n if (active) setServerVariableCount(snapshot.data().count)\n })\n .catch(() => {\n // Falls back to the loaded rows below — a LOWER bound, and this\n // card's prior behaviour. Deliberately not 0: `checkQuota` answers\n // from whatever it is handed, and 0 used is a confident wrong\n // number in the flattering direction.\n })\n return () => {\n active = false\n }\n }, [firestore, hostId, variableCountEpoch])\n const variableCount = serverVariableCount ?? variables.length\n /*\n * Opens a variable another plugin proposed (AGL-3603) as Add variable opens\n * one — the plan's cap asked first — unsaved. Save is the only write.\n */\n const propose = useCallback(\n (proposal: LogicProposal) => {\n if (proposal.kind !== 'variable') return false\n const quota = checkQuota(org, 'variablesPerHost', variableCount)\n if (!quota.allowed) {\n enqueueSnackbar(`Variable limit reached (${quota.limit}) — upgrade in Billing`, {\n variant: 'warning',\n persist: false,\n })\n return false\n }\n setDraft({ id: null, ...proposal.variable, workflowId: '', workflowName: '' })\n return true\n },\n [org, variableCount, enqueueSnackbar],\n )\n\n const validName = VARIABLE_NAME_PATTERN.test(draft?.name ?? '')\n // Case-insensitive (AGL-185): names must stay unambiguous for legacy\n // {{name}} token resolution and picker display.\n const nameTaken = Boolean(\n draft &&\n variables.some(\n (variable: any) =>\n String(variable.name ?? '').toLowerCase() ===\n draft.name.trim().toLowerCase() && variable.$id !== draft.id,\n ),\n )\n\n const handleSave = useCallback(async () => {\n if (!draft || !validName || nameTaken) return\n const fields = {\n name: draft.name,\n type: draft.type,\n value: draft.value,\n workflowId: draft.workflowId.trim(),\n workflowName: draft.workflowName.trim(),\n }\n try {\n if (draft.id) {\n /**\n * Edit stays client-direct (no quota consumed) — and is refused when\n * its seed was never confirmed by the server (AGL-1358). `merge:\n * true` protects nothing here: `fields` is every editable key of the\n * stored row, copied off the listener whether or not it was touched.\n *\n * The guard WRAPS the write. An early return is a shape you can keep\n * while losing the protection; here the write is only reachable\n * through the verdict.\n */\n const verdict = await writeGuardedBySeed(\n {\n subject: 'variable',\n unreadable: variablesStatus === 'error',\n fromCache: variablesFromCache,\n },\n async () => {\n await writeSiteWideChange({\n firestore,\n user,\n hostId,\n write: (batch) =>\n batch.set(\n doc(firestore, 'hosts', hostId, 'variables', draft.id),\n { ...fields, updatedAt: Timestamp.now() },\n { merge: true },\n ),\n })\n },\n )\n // Before `setDraft(null)`, so a refusal keeps the dialog open with\n // what was typed. A save that silently does nothing sends the user\n // back to retype a form that will be refused again just as quietly.\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n } else {\n // New variable rides the quota-enforcing resources API (AGL-473).\n await createHostResource({ hostId, resource: 'variable', data: fields })\n // A create moves the count and the aggregate is a one-shot — the\n // listener refreshes the ROWS for free, the count has to be asked\n // again or the cap drifts stale for the rest of the session.\n setVariableCountEpoch((epoch) => epoch + 1)\n }\n setDraft(null)\n enqueueSnackbar(\n `Saved — use {{${draft.name}}} in any text to bind it`,\n { variant: 'success', persist: false },\n )\n } catch (error: any) {\n console.error(error)\n enqueueSnackbar(error?.message ?? 'An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n }, [\n user,\n draft,\n validName,\n nameTaken,\n firestore,\n hostId,\n createHostResource,\n enqueueSnackbar,\n variablesStatus,\n variablesFromCache,\n ])\n\n const handleShowUsage = useCallback(\n (variable: any) => async () => {\n setUsageLoading(variable.$id)\n const result = await fetchWhereUsed(user as any, {\n hostId,\n kind: 'variable',\n id: variable.$id,\n name: variable.name,\n })\n setUsageLoading(null)\n setUsage({ name: variable.name, result })\n },\n [user, hostId],\n )\n\n const handleDelete = useCallback(\n (variable: any) => async () => {\n // Real dependents warning (AGL-187) instead of the generic copy.\n const scan = await fetchWhereUsed(user as any, {\n hostId,\n kind: 'variable',\n id: variable.$id,\n name: variable.name,\n })\n const confirmed = await confirm({\n title: 'Delete this variable?',\n description: scan.total\n ? `\"${variable.name}\" is used in ${summarizeDependents(scan)}. ` +\n 'Those bindings will render as empty or literal tokens after ' +\n 'the next publish.'\n : `\"${variable.name}\" is not referenced by any published ` +\n 'page, layout, or workflow.',\n confirmationText: 'Delete',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n await writeSiteWideChange({\n firestore,\n user,\n hostId,\n write: (batch) =>\n batch.update(\n doc(firestore, 'hosts', hostId, 'variables', variable.$id),\n { deletedAt: Timestamp.now() },\n ),\n })\n enqueueSnackbar('Variable deleted', {\n variant: 'success',\n persist: false,\n })\n },\n [user, confirm, firestore, hostId, enqueueSnackbar],\n )\n\n return (\n <CardDisplay\n header={'Variables'}\n help={pluginDocsHelp('bindings', { anchor: '#typed-variables' })}\n // Another way to start a variable (AGL-3603), in the card's header.\n actions={\n ExtensionZone ? (\n <ExtensionZone\n slot={HOST_LOGIC_ZONE.id}\n hostId={hostId}\n orgId={org?.$id}\n kind=\"variable\"\n propose={propose}\n />\n ) : null\n }\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1}>\n {variables.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Define typed values once and put them into any text with ' +\n 'Insert data in the Besigner — change the variable, every ' +\n 'page updates on the next publish.'}\n </Typography>\n ) : (\n visibleVariables.map((variable: any) => (\n <Stack\n key={variable.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Stack sx={{ flex: 1, minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {variable.name}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {`${HOST_VARIABLE_TYPE_LABELS[variable.type as HostVariableType] ?? variable.type} · ${\n formatVariableValue(variable as HostVariable) || '—'\n }`}\n </Typography>\n </Stack>\n <Button\n size=\"small\"\n disabled={usageLoading === variable.$id}\n onClick={handleShowUsage(variable)}\n >\n {usageLoading === variable.$id ? 'Scanning…' : 'Usage'}\n </Button>\n <Button\n size=\"small\"\n onClick={() =>\n setDraft({\n id: variable.$id,\n name: variable.name ?? '',\n type: variable.type ?? 'text',\n value: variable.value ?? '',\n workflowId: variable.workflowId ?? '',\n workflowName: variable.workflowName ?? '',\n })\n }\n >\n {'Edit'}\n </Button>\n <Button\n size=\"small\"\n color=\"error\"\n onClick={handleDelete(variable)}\n >\n {'Delete'}\n </Button>\n </Stack>\n ))\n )}\n {variables.length === 0 ? null : (\n <ListPagination\n page={page}\n pageSize={pageSize}\n rowCount={visibleVariables.length}\n // The variables the card HOLDS. Not `variableCount`, which is the\n // site's total including soft-deleted rows and answers the quota's\n // question rather than the reader's.\n count={variables.length}\n onPageChange={setPage}\n onPageSizeChange={setPageSize}\n />\n )}\n {variablesTruncated ? (\n <Alert severity=\"info\">\n {`Showing ${VARIABLE_CEILING} variables, ordered by id. This site ` +\n 'has more — the duplicate-name check below only covers the ' +\n 'ones listed here, so a name may already be taken by one that ' +\n 'is not.'}\n </Alert>\n ) : null}\n <Button\n size=\"small\"\n color=\"primary\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() => {\n // Plan cap (AGL-99): dark-launch — plan-less workspaces uncapped.\n // The site's variables, not this page of them (AGL-1716).\n const quota = checkQuota(org, 'variablesPerHost', variableCount)\n if (!quota.allowed) {\n return void enqueueSnackbar(\n `Variable limit reached (${quota.limit}) — upgrade in Billing`,\n { variant: 'warning', persist: false },\n )\n }\n setDraft({\n id: null,\n name: '',\n type: 'text',\n value: '',\n workflowId: '',\n workflowName: '',\n })\n }}\n >\n {'Add variable'}\n </Button>\n </Stack>\n <Dialog\n open={Boolean(draft)}\n onClose={() => setDraft(null)}\n maxWidth=\"xs\"\n fullWidth\n >\n <DialogTitle>\n {draft?.id ? 'Edit Variable' : 'Add Variable'}\n </DialogTitle>\n <DialogContent\n sx={{ display: 'flex', flexDirection: 'column', gap: 2, pt: 1 }}\n >\n <TextField\n label=\"Name\"\n helperText={\n nameTaken\n ? 'A variable with this name already exists'\n : 'Used to identify the variable'\n }\n error={(Boolean(draft?.name) && !validName) || nameTaken}\n value={draft?.name ?? ''}\n onChange={(event) =>\n setDraft((prev) =>\n prev\n ? {\n ...prev,\n name: event.target.value.replace(\n /[^a-zA-Z0-9_]/g,\n '',\n ),\n }\n : prev,\n )\n }\n size=\"small\"\n autoFocus\n sx={{ mt: 1 }}\n />\n <TextField\n label=\"Type\"\n value={draft?.type ?? 'text'}\n onChange={(event) =>\n setDraft((prev) =>\n prev\n ? {\n ...prev,\n type: event.target.value as HostVariableType,\n value: '',\n }\n : prev,\n )\n }\n size=\"small\"\n select\n >\n {Object.entries(HOST_VARIABLE_TYPE_LABELS).map(\n ([value, label]) => (\n <MenuItem key={value} value={value}>\n {label}\n </MenuItem>\n ),\n )}\n </TextField>\n {draft ? (\n <VariableValueField\n draft={draft}\n onChange={(value) =>\n setDraft((prev) => (prev ? { ...prev, value } : prev))\n }\n />\n ) : null}\n <TextField\n select\n label=\"Computed from workflow (optional)\"\n helperText={\n workflowOptionsTruncated\n ? `Showing ${WORKFLOW_OPTION_CEILING} workflows, ordered by ` +\n 'id. This site has more, so one of them is not offered here.'\n : 'Pick a workflow — its result becomes this ' +\n 'variable\\u2019s value at render; the value above is the ' +\n 'fallback (AGL-129)'\n }\n value={\n draft?.workflowId ||\n workflowOptions.find(\n (option) => option.name === draft?.workflowName,\n )?.id ||\n ''\n }\n onChange={(event) =>\n setDraft((prev) =>\n prev\n ? {\n ...prev,\n workflowId: event.target.value,\n workflowName:\n workflowOptions.find(\n (option) => option.id === event.target.value,\n )?.name ?? '',\n }\n : prev,\n )\n }\n size=\"small\"\n >\n <MenuItem value=\"\">{'None'}</MenuItem>\n {workflowOptions.map((option) => (\n <MenuItem key={option.id} value={option.id}>\n {option.name}\n </MenuItem>\n ))}\n </TextField>\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setDraft(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={!validName || nameTaken}\n onClick={handleSave}\n >\n {'Save variable'}\n </Button>\n </DialogActions>\n </Dialog>\n <WhereUsedDialog\n hostId={hostId}\n usage={usage}\n onClose={() => setUsage(null)}\n />\n </CardDisplay>\n )\n}\nHostVariablesCard.displayName = 'HostVariablesCard'\n\nexport default HostVariablesCard\n"],"names":["checkQuota","formatVariableValue","HOST_VARIABLE_TYPE_LABELS","pluginDocsHelp","VARIABLE_NAME_PATTERN","ceilingedWindow","collectionCeiling","pluginRecordListQuery","pluginRecordsFromRows","CardDisplay","useConfirmationContext","ListPagination","TABLE_PAGE_SIZE_DEFAULT","useSnackbar","Timestamp","Alert","Button","Dialog","DialogActions","DialogContent","DialogTitle","MenuItem","Stack","Switch","TextField","Typography","collection","doc","getCountFromServer","lazy","Suspense","useCallback","useEffect","useMemo","useState","useFirestore","useFirestoreCollection","useHostResourceApi","useUser","writeGuardedBySeed","writeSiteWideChange","WhereUsedDialog","useConsoleWidgetSlot","HOST_LOGIC_ZONE","fetchWhereUsed","summarizeDependents","StructuredValueEditor","VARIABLE_CEILING","WORKFLOW_OPTION_CEILING","VariableValueField","props","draft","onChange","type","direction","spacing","sx","alignItems","checked","value","event","target","variant","label","size","slotProps","inputLabel","shrink","replace","fallback","shape","id","multiline","HostVariablesCard","workflowOptions","hostId","firestore","data","user","createHostResource","enqueueSnackbar","confirm","org","usage","setUsage","usageLoading","setUsageLoading","variableDocs","status","variablesStatus","fromCache","variablesFromCache","idField","rows","readVariables","truncated","variablesTruncated","setDraft","ExtensionZone","editorOpened","setEditorOpened","workflowDocs","limit","readWorkflows","workflowOptionsTruncated","map","workflow","name","sort","a","b","localeCompare","variables","filter","variable","deletedAt","String","page","setPage","pageSize","setPageSize","visibleVariables","slice","variableCountEpoch","setVariableCountEpoch","serverVariableCount","setServerVariableCount","active","then","snapshot","count","catch","variableCount","length","propose","proposal","kind","quota","allowed","persist","workflowId","workflowName","validName","test","nameTaken","Boolean","some","toLowerCase","trim","$id","handleSave","fields","verdict","subject","unreadable","write","batch","set","updatedAt","now","merge","ok","message","resource","epoch","error","console","allowDuplicate","handleShowUsage","result","handleDelete","scan","confirmed","title","description","total","confirmationText","confirmationButtonProps","color","update","header","help","anchor","actions","slot","orgId","contentGutterX","contentGutterY","flex","minWidth","noWrap","disabled","onClick","rowCount","onPageChange","onPageSizeChange","severity","alignSelf","open","onClose","maxWidth","fullWidth","display","flexDirection","gap","pt","helperText","prev","autoFocus","mt","select","Object","entries","find","option","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAEEA,UAAU,EACVC,mBAAmB,EACnBC,yBAAyB,EAGzBC,cAAc,EACdC,qBAAqB,QAChB,eAAc;AACrB;;;;;;CAMC,GACD,SACEC,eAAe,EACfC,iBAAiB,QACZ,+DAA8D;AACrE,SACEC,qBAAqB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gB2I,IAAI,CAClB,CAACC,SAAWA,OAAO/I,EAAE,KAAKX,MAAMC,MAAM,CAACF,KAAK,sBAD9Ce,sBAEGiC,IAAI,mBAAI;6CAEfoG;;gCAGR/I,MAAK;;kDAEL,KAAC3C;wCAASsC,OAAM;kDAAI;;oCACnBe,gBAAgB+B,GAAG,CAAC,CAAC6G,uBACpB,KAACjM;4CAAyBsC,OAAO2J,OAAO/I,EAAE;sDACvC+I,OAAO3G,IAAI;2CADC2G,OAAO/I,EAAE;;;;;kCAM9B,MAACrD;;0CACC,KAACF;gCAAOgL,SAAS,IAAM/F,SAAS;0CAAQ;;0CACxC,KAACjF;gCACC8C,SAAQ;gCACRoH,OAAM;gCACNa,UAAU,CAACjD,aAAaE;gCACxBgD,SAAS1C;0CAER;;;;;;0BAIP,KAAC7G;gBACCkC,QAAQA;gBACRQ,OAAOA;gBACPoH,SAAS,IAAMnH,SAAS;;;;AAIhC;AACAX,kBAAkB8I,WAAW,GAAG;AAEhC,eAAe9I,kBAAiB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/logic/src/lib/components/host-variables-card.component.tsx"],"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'use client'\n\nimport {\n type AglynOrgBilling,\n checkQuota,\n formatVariableValue,\n HOST_VARIABLE_TYPE_LABELS,\n type HostVariable,\n type HostVariableType,\n pluginDocsHelp,\n VARIABLE_NAME_PATTERN,\n} from '@aglyn/aglyn'\n/*\n * The MODULE, not the barrel, for the two PURE helpers. Every spec that renders\n * this card mocks `@aglyn/tenant-feature-instance` wholesale to stage its\n * Firestore hooks, and a query builder imported through that barrel disappears\n * under the mock — which fails as \"not a function\" in the component rather than\n * as anything about the test's subject. Neither of these is a hook.\n */\nimport {\n ceilingedWindow,\n collectionCeiling,\n} from '@aglyn/tenant-feature-instance/hooks/host-collection-queries'\nimport {\n pluginRecordListQuery,\n pluginRecordsFromRows,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-lists'\nimport { CardDisplay, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport { TABLE_PAGE_SIZE_DEFAULT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { Timestamp } from '@aglyn/shared-util-timestamp'\nimport {\n Alert,\n Button,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n MenuItem,\n Stack,\n Switch,\n TextField,\n Typography,\n} from '@mui/material'\nimport { collection, doc } from 'firebase/firestore'\nimport { getLiveCountFromServer } from '@aglyn/aglyn/app-utils/live-document-count.client'\nimport { lazy, Suspense, useCallback, useEffect, useMemo, useState } from 'react'\nimport {\n useFirestore,\n useFirestoreCollection,\n useHostResourceApi,\n useUser,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport { writeSiteWideChange } from '@aglyn/tenant-feature-instance/hooks/helpers/site-wide-change'\nimport WhereUsedDialog from './where-used-dialog.component'\nimport { useConsoleWidgetSlot } from '@aglyn/aglyn/app-utils/console-widget-slot-context'\nimport { HOST_LOGIC_ZONE, type LogicProposal } from './logic-zones'\nimport {\n fetchWhereUsed,\n summarizeDependents,\n type WhereUsedResult,\n} from '@aglyn/aglyn/app-utils/where-used'\n\n// The entry/item editor is its own chunk, loaded when a dictionary or list\n// variable is opened (AGL-3757).\nconst StructuredValueEditor = lazy(\n () => import('./structured-value-editor.component'),\n)\n\n/**\n * How many variables the card reads.\n *\n * A CEILING, not a page size — see the query, which explains why this list\n * cannot be paged by the server without making the duplicate-name check lie.\n */\nconst VARIABLE_CEILING = 100\n\n/**\n * How many workflows the computed-variable picker offers.\n *\n * Paid for only while the editor is open, which is what makes a ceiling this\n * size affordable: it is one reader mid-edit rather than every visitor to the\n * page.\n */\nconst WORKFLOW_OPTION_CEILING = 100\n\nexport interface HostVariablesCardProps {\n hostId: string\n /** Resolved entitlement source for quota checks (AGL-395). */\n org?: Partial<AglynOrgBilling>\n}\n\ninterface VariableDraft {\n /** Computed-source workflow doc id (AGL-261); name is the display hint. */\n workflowId: string\n id: string | null\n name: string\n type: HostVariableType\n value: string\n /** Workflow (by name) computing this variable at render (AGL-129). */\n workflowName: string\n}\n\n/** Per-type value editor: mirrors the mockup's type list. */\nfunction VariableValueField(props: {\n draft: VariableDraft\n onChange: (value: string) => void\n}) {\n const { draft, onChange } = props\n switch (draft.type) {\n case 'boolean':\n return (\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Switch\n checked={draft.value === 'true'}\n onChange={(event) =>\n onChange(event.target.checked ? 'true' : 'false')\n }\n />\n <Typography variant=\"body2\">\n {draft.value === 'true' ? 'True' : 'False'}\n </Typography>\n </Stack>\n )\n case 'date':\n case 'time':\n return (\n <TextField\n label=\"Value\"\n type={draft.type}\n value={draft.value}\n onChange={(event) => onChange(event.target.value)}\n size=\"small\"\n slotProps={{ inputLabel: { shrink: true } }}\n />\n )\n case 'number':\n return (\n <TextField\n label=\"Value\"\n value={draft.value}\n onChange={(event) =>\n onChange(event.target.value.replace(/[^0-9.eE+-]/g, ''))\n }\n size=\"small\"\n />\n )\n case 'dictionary':\n case 'collection':\n // Rows, never typed JSON (AGL-3757). Keyed by the draft and type so\n // opening another variable, or switching type, reads its value afresh.\n return (\n <Suspense fallback={null}>\n <StructuredValueEditor\n key={`${draft.id ?? 'new'}:${draft.type}`}\n shape={draft.type}\n value={draft.value}\n onChange={onChange}\n />\n </Suspense>\n )\n default:\n return (\n <TextField\n label=\"Value\"\n value={draft.value}\n onChange={(event) => onChange(event.target.value)}\n size=\"small\"\n multiline\n />\n )\n }\n}\n\n/**\n * Host variables (Component Builder, AGL-91): the mockup's Edit Variable\n * dialog — name + typed value — persisted to `hosts/{hostId}/variables`.\n * Any string prop can reference a variable with `{{name}}`; the org\n * compose pipeline resolves it at render. Soft delete keeps old tokens\n * rendering literally rather than breaking published pages.\n */\nexport function HostVariablesCard(props: HostVariablesCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const createHostResource = useHostResourceApi()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n const { org } = props\n // Where-used dependents dialog (AGL-187).\n const [usage, setUsage] = useState<{\n name: string\n result: WhereUsedResult\n } | null>(null)\n const [usageLoading, setUsageLoading] = useState<string | null>(null)\n const {\n data: variableDocs,\n status: variablesStatus,\n /**\n * The rows this editor is seeded from are unconfirmed by the server\n * (AGL-1358). Editing copies a whole stored variable into `draft` and\n * writes all of it back, so `merge: true` protects nothing — every field\n * is in the payload. `value` is the literal every `{{name}}` binding on\n * every published page resolves to, and `workflowId` is what rebinds a\n * computed variable to its source (AGL-261), so a cached seed can point\n * a live binding back at a value or a workflow the author replaced.\n */\n fromCache: variablesFromCache,\n } = useFirestoreCollection<any>(\n /*\n * ORDERED AND CEILINGED, deliberately not paged by the query (AGL-2501).\n *\n * `limit(100)` alone is answered in DOCUMENT-ID order, so the window is a\n * pseudo-random hundred that the `localeCompare` below arranges into a\n * convincing A-to-Z list. `variablesPerHost` runs to 5,000, so a Scale\n * site with three hundred variables sees a hundred of them and nothing\n * said so.\n *\n * `collectionCeiling` does not change WHICH hundred — document-id order is\n * what the bare cap already returned. What it changes is that the order is\n * NAMED, so the obvious next edit is caught: ordering on `name` would not\n * mis-sort this list, it would HIDE from it every variable written without\n * one, and `/api/hosts/resources` validates no field for presence while\n * `IMPORTABLE_FIELDS.variables` copies a name only if the exported\n * document carried it. The document name cannot be absent.\n *\n * The QUERY is not paged because `nameTaken` below tests the draft against\n * these rows. Case-insensitive uniqueness is what keeps legacy `{{name}}`\n * token resolution unambiguous (AGL-185), and on a ten-row server page\n * that check would compare a new variable against a tenth of the site and\n * cheerfully create the duplicate it exists to prevent.\n *\n * The check is still only as complete as the ceiling, and that is now\n * SAID rather than assumed: the notice under the list appears exactly when\n * the probe finds a variable this card did not read.\n */\n () =>\n collectionCeiling(\n collection(firestore, 'hosts', hostId, 'variables'),\n VARIABLE_CEILING,\n ),\n [firestore, hostId],\n { idField: '$id' },\n )\n const { rows: readVariables, truncated: variablesTruncated } =\n ceilingedWindow<any>(variableDocs, VARIABLE_CEILING)\n const [draft, setDraft] = useState<VariableDraft | null>(null)\n\n /** The shell's zone renderer (AGL-3603); `null` outside the console shell. */\n const ExtensionZone = useConsoleWidgetSlot()\n /**\n * The editor has been opened at least once in this session.\n *\n * A LATCH rather than `draft` itself, because the workflow picker below keys its\n * listeners on it. Tracking the dialog would tear that subscription down\n * on Cancel and pay for them again on the next Edit, so a merchant working\n * through ten variables would buy the same window ten times — worse than\n * the mount-time read this replaces. Latched, a reader who never edits pays\n * nothing and a reader who edits pays once.\n */\n const [editorOpened, setEditorOpened] = useState(false)\n if (draft && !editorOpened) setEditorOpened(true)\n /*\n * Workflow picker options (AGL-261): computed variables reference the\n * workflow by doc id instead of a typed name. The workflows are the\n * workflows plugin's, listed through the source it publishes (AGL-3080).\n *\n * READ WHEN THE EDITOR OPENS, not when the card mounts (AGL-2501). Nothing\n * outside the dialog below touches these rows — the table shows a computed\n * variable's stored `workflowName`, never a name looked up here — so an\n * unconditional listener would charge every visitor to this page for a\n * hundred workflows to fill a select most of them never see.\n *\n * Ceilinged and ordered for the same reason as the variables above: a bare\n * `limit` is answered in document-id order, so the `localeCompare` below\n * would arrange a pseudo-random hundred into a convincing alphabet and a\n * workflow past it could not be picked, with nothing saying why.\n */\n const { data: workflowDocs } = useFirestoreCollection<any>(\n () =>\n editorOpened\n ? pluginRecordListQuery('workflow', firestore, {\n hostId,\n limit: WORKFLOW_OPTION_CEILING + 1,\n })\n : null,\n [firestore, hostId, editorOpened],\n { idField: '$id' },\n )\n const { rows: readWorkflows, truncated: workflowOptionsTruncated } =\n ceilingedWindow<any>(workflowDocs, WORKFLOW_OPTION_CEILING)\n // Sorting the whole ceiling, not a page of it. The workflows plugin answers\n // live, named workflows only.\n const workflowOptions = pluginRecordsFromRows('workflow', readWorkflows)\n .map((workflow) => ({ id: workflow.id, name: workflow.name }))\n .sort((a, b) => a.name.localeCompare(b.name))\n /*\n * Sorting is safe HERE in a way it is not on a paged list: these rows are\n * the whole collection below the ceiling, not a slice of one, so the order\n * on screen is the order of everything the card holds.\n */\n const variables = useMemo(\n () =>\n readVariables\n .filter((variable: any) => !variable.deletedAt)\n .sort((a: any, b: any) =>\n String(a.name ?? '').localeCompare(String(b.name ?? '')),\n ),\n [readVariables],\n )\n // The page is a SLICE, because the rows are already in hand and `nameTaken`\n // needs all of them. What the card lacked was not a cheaper read but a\n // control: a hundred variables rendered as one wall.\n const [page, setPage] = useState(0)\n const [pageSize, setPageSize] = useState(TABLE_PAGE_SIZE_DEFAULT)\n const visibleVariables = useMemo(\n () => variables.slice(page * pageSize, page * pageSize + pageSize),\n [variables, page, pageSize],\n )\n /**\n * The variable HEAD-COUNT is a server aggregate, not the length of the\n * capped listener (AGL-1716, the AGL-1706 shape).\n *\n * The listener is `limit(100)` and `variables.length` was handed to\n * `checkQuota(org, 'variablesPerHost', …)`. The bands are 3 / 25 / 100 /\n * 1,000 / 5,000, so the window ties Pro's 100 and hides Business's 1,000\n * and Scale's 5,000 entirely: on those plans the gate compared 100 against\n * thousands and could never refuse, while `api/hosts/resources` counted\n * the collection and did. The card offered headroom that did not exist and\n * then failed the create.\n *\n * LIVE variables, as the enforcing route counts them (AGL-3918): a\n * deleted variable frees its slot. Every document less the tombstones\n * (`getLiveCountFromServer`), so the card asks the route's question in the\n * route's terms, which is the only thing that makes a console gate a\n * useful prediction of the route's verdict.\n *\n * THE LIST KEEPS ITS CAP. A create or a delete moves the number, so both\n * re-read it.\n */\n const [variableCountEpoch, setVariableCountEpoch] = useState(0)\n const [serverVariableCount, setServerVariableCount] = useState<number | null>(\n null,\n )\n useEffect(() => {\n let active = true\n void getLiveCountFromServer(collection(firestore, 'hosts', hostId, 'variables'))\n .then((count) => {\n if (active) setServerVariableCount(count)\n })\n .catch(() => {\n // Falls back to the loaded rows below — a LOWER bound, and this\n // card's prior behaviour. Deliberately not 0: `checkQuota` answers\n // from whatever it is handed, and 0 used is a confident wrong\n // number in the flattering direction.\n })\n return () => {\n active = false\n }\n }, [firestore, hostId, variableCountEpoch])\n const variableCount = serverVariableCount ?? variables.length\n /*\n * Opens a variable another plugin proposed (AGL-3603) as Add variable opens\n * one — the plan's cap asked first — unsaved. Save is the only write.\n */\n const propose = useCallback(\n (proposal: LogicProposal) => {\n if (proposal.kind !== 'variable') return false\n const quota = checkQuota(org, 'variablesPerHost', variableCount)\n if (!quota.allowed) {\n enqueueSnackbar(`Variable limit reached (${quota.limit}) — upgrade in Billing`, {\n variant: 'warning',\n persist: false,\n })\n return false\n }\n setDraft({ id: null, ...proposal.variable, workflowId: '', workflowName: '' })\n return true\n },\n [org, variableCount, enqueueSnackbar],\n )\n\n const validName = VARIABLE_NAME_PATTERN.test(draft?.name ?? '')\n // Case-insensitive (AGL-185): names must stay unambiguous for legacy\n // {{name}} token resolution and picker display.\n const nameTaken = Boolean(\n draft &&\n variables.some(\n (variable: any) =>\n String(variable.name ?? '').toLowerCase() ===\n draft.name.trim().toLowerCase() && variable.$id !== draft.id,\n ),\n )\n\n const handleSave = useCallback(async () => {\n if (!draft || !validName || nameTaken) return\n const fields = {\n name: draft.name,\n type: draft.type,\n value: draft.value,\n workflowId: draft.workflowId.trim(),\n workflowName: draft.workflowName.trim(),\n }\n try {\n if (draft.id) {\n /**\n * Edit stays client-direct (no quota consumed) — and is refused when\n * its seed was never confirmed by the server (AGL-1358). `merge:\n * true` protects nothing here: `fields` is every editable key of the\n * stored row, copied off the listener whether or not it was touched.\n *\n * The guard WRAPS the write. An early return is a shape you can keep\n * while losing the protection; here the write is only reachable\n * through the verdict.\n */\n const verdict = await writeGuardedBySeed(\n {\n subject: 'variable',\n unreadable: variablesStatus === 'error',\n fromCache: variablesFromCache,\n },\n async () => {\n await writeSiteWideChange({\n firestore,\n user,\n hostId,\n write: (batch) =>\n batch.set(\n doc(firestore, 'hosts', hostId, 'variables', draft.id),\n { ...fields, updatedAt: Timestamp.now() },\n { merge: true },\n ),\n })\n },\n )\n // Before `setDraft(null)`, so a refusal keeps the dialog open with\n // what was typed. A save that silently does nothing sends the user\n // back to retype a form that will be refused again just as quietly.\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n } else {\n // New variable rides the quota-enforcing resources API (AGL-473).\n await createHostResource({ hostId, resource: 'variable', data: fields })\n // A create moves the count and the aggregate is a one-shot — the\n // listener refreshes the ROWS for free, the count has to be asked\n // again or the cap drifts stale for the rest of the session.\n setVariableCountEpoch((epoch) => epoch + 1)\n }\n setDraft(null)\n enqueueSnackbar(\n `Saved — use {{${draft.name}}} in any text to bind it`,\n { variant: 'success', persist: false },\n )\n } catch (error: any) {\n console.error(error)\n enqueueSnackbar(error?.message ?? 'An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n }, [\n user,\n draft,\n validName,\n nameTaken,\n firestore,\n hostId,\n createHostResource,\n enqueueSnackbar,\n variablesStatus,\n variablesFromCache,\n ])\n\n const handleShowUsage = useCallback(\n (variable: any) => async () => {\n setUsageLoading(variable.$id)\n const result = await fetchWhereUsed(user as any, {\n hostId,\n kind: 'variable',\n id: variable.$id,\n name: variable.name,\n })\n setUsageLoading(null)\n setUsage({ name: variable.name, result })\n },\n [user, hostId],\n )\n\n const handleDelete = useCallback(\n (variable: any) => async () => {\n // Real dependents warning (AGL-187) instead of the generic copy.\n const scan = await fetchWhereUsed(user as any, {\n hostId,\n kind: 'variable',\n id: variable.$id,\n name: variable.name,\n })\n const confirmed = await confirm({\n title: 'Delete this variable?',\n description: scan.total\n ? `\"${variable.name}\" is used in ${summarizeDependents(scan)}. ` +\n 'Those bindings will render as empty or literal tokens after ' +\n 'the next publish.'\n : `\"${variable.name}\" is not referenced by any published ` +\n 'page, layout, or workflow.',\n confirmationText: 'Delete',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n await writeSiteWideChange({\n firestore,\n user,\n hostId,\n write: (batch) =>\n batch.update(\n doc(firestore, 'hosts', hostId, 'variables', variable.$id),\n { deletedAt: Timestamp.now() },\n ),\n })\n // Deleting frees the slot (AGL-3918), so the head-count is re-read.\n setVariableCountEpoch((epoch) => epoch + 1)\n enqueueSnackbar('Variable deleted', {\n variant: 'success',\n persist: false,\n })\n },\n [user, confirm, firestore, hostId, enqueueSnackbar],\n )\n\n return (\n <CardDisplay\n header={'Variables'}\n help={pluginDocsHelp('bindings', { anchor: '#typed-variables' })}\n // Another way to start a variable (AGL-3603), in the card's header.\n actions={\n ExtensionZone ? (\n <ExtensionZone\n slot={HOST_LOGIC_ZONE.id}\n hostId={hostId}\n orgId={org?.$id}\n kind=\"variable\"\n propose={propose}\n />\n ) : null\n }\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1}>\n {variables.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Define typed values once and put them into any text with ' +\n 'Insert data in the Besigner — change the variable, every ' +\n 'page updates on the next publish.'}\n </Typography>\n ) : (\n visibleVariables.map((variable: any) => (\n <Stack\n key={variable.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Stack sx={{ flex: 1, minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {variable.name}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {`${HOST_VARIABLE_TYPE_LABELS[variable.type as HostVariableType] ?? variable.type} · ${\n formatVariableValue(variable as HostVariable) || '—'\n }`}\n </Typography>\n </Stack>\n <Button\n size=\"small\"\n disabled={usageLoading === variable.$id}\n onClick={handleShowUsage(variable)}\n >\n {usageLoading === variable.$id ? 'Scanning…' : 'Usage'}\n </Button>\n <Button\n size=\"small\"\n onClick={() =>\n setDraft({\n id: variable.$id,\n name: variable.name ?? '',\n type: variable.type ?? 'text',\n value: variable.value ?? '',\n workflowId: variable.workflowId ?? '',\n workflowName: variable.workflowName ?? '',\n })\n }\n >\n {'Edit'}\n </Button>\n <Button\n size=\"small\"\n color=\"error\"\n onClick={handleDelete(variable)}\n >\n {'Delete'}\n </Button>\n </Stack>\n ))\n )}\n {variables.length === 0 ? null : (\n <ListPagination\n page={page}\n pageSize={pageSize}\n rowCount={visibleVariables.length}\n // The variables the card HOLDS. Not `variableCount`, which is the\n // site's total including soft-deleted rows and answers the quota's\n // question rather than the reader's.\n count={variables.length}\n onPageChange={setPage}\n onPageSizeChange={setPageSize}\n />\n )}\n {variablesTruncated ? (\n <Alert severity=\"info\">\n {`Showing ${VARIABLE_CEILING} variables, ordered by id. This site ` +\n 'has more — the duplicate-name check below only covers the ' +\n 'ones listed here, so a name may already be taken by one that ' +\n 'is not.'}\n </Alert>\n ) : null}\n <Button\n size=\"small\"\n color=\"primary\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() => {\n // Plan cap (AGL-99): dark-launch — plan-less workspaces uncapped.\n // The site's variables, not this page of them (AGL-1716).\n const quota = checkQuota(org, 'variablesPerHost', variableCount)\n if (!quota.allowed) {\n return void enqueueSnackbar(\n `Variable limit reached (${quota.limit}) — upgrade in Billing`,\n { variant: 'warning', persist: false },\n )\n }\n setDraft({\n id: null,\n name: '',\n type: 'text',\n value: '',\n workflowId: '',\n workflowName: '',\n })\n }}\n >\n {'Add variable'}\n </Button>\n </Stack>\n <Dialog\n open={Boolean(draft)}\n onClose={() => setDraft(null)}\n maxWidth=\"xs\"\n fullWidth\n >\n <DialogTitle>\n {draft?.id ? 'Edit Variable' : 'Add Variable'}\n </DialogTitle>\n <DialogContent\n sx={{ display: 'flex', flexDirection: 'column', gap: 2, pt: 1 }}\n >\n <TextField\n label=\"Name\"\n helperText={\n nameTaken\n ? 'A variable with this name already exists'\n : 'Used to identify the variable'\n }\n error={(Boolean(draft?.name) && !validName) || nameTaken}\n value={draft?.name ?? ''}\n onChange={(event) =>\n setDraft((prev) =>\n prev\n ? {\n ...prev,\n name: event.target.value.replace(\n /[^a-zA-Z0-9_]/g,\n '',\n ),\n }\n : prev,\n )\n }\n size=\"small\"\n autoFocus\n sx={{ mt: 1 }}\n />\n <TextField\n label=\"Type\"\n value={draft?.type ?? 'text'}\n onChange={(event) =>\n setDraft((prev) =>\n prev\n ? {\n ...prev,\n type: event.target.value as HostVariableType,\n value: '',\n }\n : prev,\n )\n }\n size=\"small\"\n select\n >\n {Object.entries(HOST_VARIABLE_TYPE_LABELS).map(\n ([value, label]) => (\n <MenuItem key={value} value={value}>\n {label}\n </MenuItem>\n ),\n )}\n </TextField>\n {draft ? (\n <VariableValueField\n draft={draft}\n onChange={(value) =>\n setDraft((prev) => (prev ? { ...prev, value } : prev))\n }\n />\n ) : null}\n <TextField\n select\n label=\"Computed from workflow (optional)\"\n helperText={\n workflowOptionsTruncated\n ? `Showing ${WORKFLOW_OPTION_CEILING} workflows, ordered by ` +\n 'id. This site has more, so one of them is not offered here.'\n : 'Pick a workflow — its result becomes this ' +\n 'variable\\u2019s value at render; the value above is the ' +\n 'fallback (AGL-129)'\n }\n value={\n draft?.workflowId ||\n workflowOptions.find(\n (option) => option.name === draft?.workflowName,\n )?.id ||\n ''\n }\n onChange={(event) =>\n setDraft((prev) =>\n prev\n ? {\n ...prev,\n workflowId: event.target.value,\n workflowName:\n workflowOptions.find(\n (option) => option.id === event.target.value,\n )?.name ?? '',\n }\n : prev,\n )\n }\n size=\"small\"\n >\n <MenuItem value=\"\">{'None'}</MenuItem>\n {workflowOptions.map((option) => (\n <MenuItem key={option.id} value={option.id}>\n {option.name}\n </MenuItem>\n ))}\n </TextField>\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setDraft(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={!validName || nameTaken}\n onClick={handleSave}\n >\n {'Save variable'}\n </Button>\n </DialogActions>\n </Dialog>\n <WhereUsedDialog\n hostId={hostId}\n usage={usage}\n onClose={() => setUsage(null)}\n />\n </CardDisplay>\n )\n}\nHostVariablesCard.displayName = 'HostVariablesCard'\n\nexport default HostVariablesCard\n"],"names":["checkQuota","formatVariableValue","HOST_VARIABLE_TYPE_LABELS","pluginDocsHelp","VARIABLE_NAME_PATTERN","ceilingedWindow","collectionCeiling","pluginRecordListQuery","pluginRecordsFromRows","CardDisplay","useConfirmationContext","ListPagination","TABLE_PAGE_SIZE_DEFAULT","useSnackbar","Timestamp","Alert","Button","Dialog","DialogActions","DialogContent","DialogTitle","MenuItem","Stack","Switch","TextField","Typography","collection","doc","getLiveCountFromServer","lazy","Suspense","useCallback","useEffect","useMemo","useState","useFirestore","useFirestoreCollection","useHostResourceApi","useUser","writeGuardedBySeed","writeSiteWideChange","WhereUsedDialog","useConsoleWidgetSlot","HOST_LOGIC_ZONE","fetchWhereUsed","summarizeDependents","StructuredValueEditor","VARIABLE_CEILING","WORKFLOW_OPTION_CEILING","VariableValueField","props","draft","onChange","type","direction","spacing","sx","alignItems","checked","value","event","target","variant","label","size","slotProps","inputLabel","shrink","replace","fallback","shape","id","multiline","HostVariablesCard","workflowOptions","hostId","firestore","data","user","createHostResource","enqueueSnackbar","confirm","org","usage","setUsage","usageLoading","setUsageLoading","variableDocs","status","variablesStatus","fromCache","variablesFromCache","idField","rows","readVariables","truncated","variablesTruncated","setDraft","ExtensionZone","editorOpened","setEditorOpened","workflowDocs","limit","readWorkflows","workflowOptionsTruncated","map","workflow","name","sort","a","b","localeCompare","variables","filter","variable","deletedAt","String","page","setPage","pageSize","setPageSize","visibleVariables","slice","variableCountEpoch","setVariableCountEpoch","serverVariableCount","setServerVariableCount","active","then","count","catch","variableCount","length","propose","proposal","kind","quota","allowed","persist","workflowId","workflowName","validName","test","nameTaken","Boolean","some","toLowerCase","trim","$id","handleSave","fields","verdict","subject","unreadable","write","batch","set","updatedAt","now","merge","ok","message","resource","epoch","error","console","allowDuplicate","handleShowUsage","result","handleDelete","scan","confirmed","title","description","total","confirmationText","confirmationButtonProps","color","update","header","help","anchor","actions","slot","orgId","contentGutterX","contentGutterY","flex","minWidth","noWrap","disabled","onClick","rowCount","onPageChange","onPageSizeChange","severity","alignSelf","open","onClose","maxWidth","fullWidth","display","flexDirection","gap","pt","helperText","prev","autoFocus","mt","select","Object","entries","find","option","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAEEA,UAAU,EACVC,mBAAmB,EACnBC,yBAAyB,EAGzBC,cAAc,EACdC,qBAAqB,QAChB,eAAc;AACrB;;;;;;CAMC,GACD,SACEC,eAAe,EACfC,iBAAiB,QACZ,+DAA8D;AACrE,SACEC,qBAAqB,EACrBC,qBAAqB,QAChB,kDAAiD;AACxD,SAASC,WAAW,EAAEC,sBAAsB,QAAQ,uBAAsB;AAC1E,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,SAASC,uBAAuB,QAAQ,8CAA6C;AACrF,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,SAAS,QAAQ,+BAA8B;AACxD,SACEC,KAAK,EACLC,MAAM,EACNC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,QAAQ,EACRC,KAAK,EACLC,MAAM,EACNC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SAASC,UAAU,EAAEC,GAAG,QAAQ,qBAAoB;AACpD,SAASC,sBAAsB,QAAQ,oDAAmD;AAC1F,SAASC,IAAI,EAAEC,QAAQ,EAAEC,WAAW,EAAEC,SAAS,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACjF,SACEC,YAAY,EACZC,sBAAsB,EACtBC,kBAAkB,EAClBC,OAAO,EACPC,kBAAkB,QACb,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W,GAAG;AAEhC,eAAe7I,kBAAiB"}
@@ -16,6 +16,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
16
16
  * limitations under the License.
17
17
  */ import { hostRoleCanWrite } from "@aglyn/aglyn/app-utils/organizations";
18
18
  import { checkQuota } from "@aglyn/aglyn/app-utils/plan-entitlements";
19
+ import { countLiveDocuments, isLiveDocument } from "@aglyn/aglyn/app-utils/live-document-count";
19
20
  import { firebaseAdmin } from "@aglyn/tenant-data-admin";
20
21
  import { checkFunctionDraftContent, checkVariableDraftContent, functionDraftFacts, logicNameKey, readFunctionDraftContent, readVariableDraftContent, variableDraftFacts } from "./logic-draft-content.js";
21
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';
@@ -63,7 +64,7 @@ function createLogicDraftWriter(kind, deps) {
63
64
  };
64
65
  const role = roleRefusal(host, context.uid);
65
66
  if (role) return role;
66
- const used = (await hostRef.collection(kind.collection).count().get()).data().count;
67
+ const used = await countLiveDocuments(hostRef.collection(kind.collection));
67
68
  return roomRefusal(context.org, Number(used) || 0);
68
69
  },
69
70
  check: (content)=>kind.check(content),
@@ -108,10 +109,11 @@ function createLogicDraftWriter(kind, deps) {
108
109
  if (role) return _extends({
109
110
  ok: false
110
111
  }, role);
111
- // One projected read answers both: the route counts every document
112
- // for the allowance, and the cards compare names among the live ones.
112
+ // One projected read answers both: the allowance and the cards'
113
+ // name check each count the live ones, so a deleted record frees
114
+ // its slot and its name (AGL-3918).
113
115
  const rows = (await tx.get(records.select('name', 'deletedAt'))).docs;
114
- const room = roomRefusal(request.org, rows.length);
116
+ const room = roomRefusal(request.org, rows.filter((row)=>isLiveDocument(row.get('deletedAt'))).length);
115
117
  if (room) return _extends({
116
118
  ok: false
117
119
  }, room);
@@ -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 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 hostRef.collection(kind.collection).count().get()).data().count\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 route counts every document\n // for the allowance, and the cards compare names among the live ones.\n const rows = (await tx.get(records.select('name', 'deletedAt'))).docs\n const room = roomRefusal(request.org, rows.length)\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","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","count","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","length","key","taken","some","row","create","createdAt","now","updatedAt","createdBy","createVariableDraftWriter","createFunctionDraftWriter","variableDraftWriter","functionDraftWriter"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,QAAQ,uCAAsC;AACvE,SAASC,UAAU,QAAQ,2CAA0C;AASrE,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,sBAAsB,CAAC;AAC9E;AAiBA,SAASC,YAAYC,IAAwC,EAAEC,GAAW;QAC1DD;IAAd,MAAME,OAAO,EAACF,YAAAA,KAAKG,GAAG,CAAC,0BAATH,YAA2B,CAAC,EAAE,CAACC,IAAI;IACjD,OAAOlB,iBAAiBmB,QAAQ,OAAO;QAAEE,QAAQ;QAAKC,OAAOZ;IAAyB;AACxF;AAEA,SAASa,uBACPC,IAAuB,EACvBC,IAA0B;QAERA;IAAlB,MAAMC,aAAYD,kBAAAA,KAAKC,SAAS,YAAdD,kBAAmB,IAAMvB,cAAcyB,GAAG,GAAGD,SAAS;IACxE,MAAME,cAAc,CAACC,K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;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 { 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,sBAAsB,CAAC;AAC9E;AAiBA,SAASC,Y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