@aglyn/plugins-data 1.13.0 → 1.15.0
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 +12 -10
- package/src/lib/artifact/dataset-schema-artifact.server.js +10 -4
- package/src/lib/artifact/dataset-schema-artifact.server.js.map +1 -1
- package/src/lib/components/data-console-page.js +4 -2
- package/src/lib/components/data-console-page.js.map +1 -1
- package/src/lib/components/dataset-record-dialog.component.d.ts +22 -0
- package/src/lib/components/dataset-record-dialog.component.js +77 -54
- package/src/lib/components/dataset-record-dialog.component.js.map +1 -1
- package/src/lib/components/dataset-schema-dialog.component.js +195 -168
- package/src/lib/components/dataset-schema-dialog.component.js.map +1 -1
- package/src/lib/components/host-datasets-card.component.d.ts +12 -0
- package/src/lib/components/host-datasets-card.component.js +652 -221
- package/src/lib/components/host-datasets-card.component.js.map +1 -1
- package/src/lib/components/use-dataset-writes-blocked.d.ts +5 -4
- package/src/lib/components/use-dataset-writes-blocked.js +11 -12
- package/src/lib/components/use-dataset-writes-blocked.js.map +1 -1
- package/src/lib/components/use-org-sites.d.ts +27 -0
- package/src/lib/components/use-org-sites.js +68 -0
- package/src/lib/components/use-org-sites.js.map +1 -0
- package/src/lib/model/data-record-routes.js +6 -3
- package/src/lib/model/data-record-routes.js.map +1 -1
- package/src/lib/model/dataset-model-core.d.ts +22 -0
- package/src/lib/model/dataset-model-core.js +34 -0
- package/src/lib/model/dataset-model-core.js.map +1 -1
- package/src/lib/model/dataset-rail.d.ts +88 -0
- package/src/lib/model/dataset-rail.js +123 -0
- package/src/lib/model/dataset-rail.js.map +1 -0
- package/src/lib/model/dataset-record-list.js +17 -2
- package/src/lib/model/dataset-record-list.js.map +1 -1
- package/src/lib/model/dataset-record.js +8 -3
- package/src/lib/model/dataset-record.js.map +1 -1
- package/src/lib/model/datasets.d.ts +14 -0
- package/src/lib/model/datasets.js +10 -0
- package/src/lib/model/datasets.js.map +1 -1
- package/src/lib/plugin.d.ts +5 -1
- package/src/lib/plugin.js +8 -3
- package/src/lib/plugin.js.map +1 -1
- package/src/lib/record-pages/record-template-section.component.js +12 -1
- package/src/lib/record-pages/record-template-section.component.js.map +1 -1
- package/src/lib/server/api-v1/datasets.js +6 -1
- package/src/lib/server/api-v1/datasets.js.map +1 -1
- package/src/lib/server/dataset-access.server.d.ts +4 -3
- package/src/lib/server/dataset-access.server.js +7 -5
- package/src/lib/server/dataset-access.server.js.map +1 -1
- package/src/lib/server/dataset-drafts.js +2 -0
- package/src/lib/server/dataset-drafts.js.map +1 -1
- package/src/lib/server/dataset-site-erasure.d.ts +2 -2
- package/src/lib/server/dataset-site-erasure.js +4 -26
- package/src/lib/server/dataset-site-erasure.js.map +1 -1
- package/src/lib/server/datasets-route.d.ts +2 -0
- package/src/lib/server/datasets-route.js +125 -19
- package/src/lib/server/datasets-route.js.map +1 -1
- package/src/lib/site-bundle/datasets-site-bundle.server.d.ts +4 -2
- package/src/lib/site-bundle/datasets-site-bundle.server.js +16 -5
- package/src/lib/site-bundle/datasets-site-bundle.server.js.map +1 -1
- package/src/lib/transfer/dataset-transfer-access.server.js +3 -3
- package/src/lib/transfer/dataset-transfer-access.server.js.map +1 -1
|
@@ -27,6 +27,7 @@ import { collection, limit, query, where } from "firebase/firestore";
|
|
|
27
27
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
|
28
28
|
import { effectiveDatasetModel } from "../model/dataset-models.js";
|
|
29
29
|
import { datasetDisplayName } from "../model/datasets.js";
|
|
30
|
+
import { datasetPickerLabelsOf } from "../model/dataset-rail.js";
|
|
30
31
|
import { isRecordAddressField, recordAddressFieldIds, recordPageBaseRefusal, recordPagePath } from "./record-pages.js";
|
|
31
32
|
import { useRecordPagePreview, useSiteRecordPageBindings } from "./record-page-source.js";
|
|
32
33
|
/** The optional field pickers, in the order the section offers them. */ const FIELD_PICKERS = [
|
|
@@ -99,6 +100,16 @@ const EMPTY_DRAFT = {
|
|
|
99
100
|
const datasets = useMemo(()=>(datasetDocs != null ? datasetDocs : []).filter((dataset)=>!dataset.deletedAt).sort((a, b)=>datasetDisplayName(a).localeCompare(datasetDisplayName(b))), [
|
|
100
101
|
datasetDocs
|
|
101
102
|
]);
|
|
103
|
+
/**
|
|
104
|
+
* Who a dataset is shared with only where two share a name (AGL-4047). Every
|
|
105
|
+
* dataset listed is this site's to see, so one on a single site is on this
|
|
106
|
+
* one, and is called so without reading the site.
|
|
107
|
+
*/ const labels = useMemo(()=>datasetPickerLabelsOf(datasets, {
|
|
108
|
+
[hostId]: 'This site'
|
|
109
|
+
}), [
|
|
110
|
+
datasets,
|
|
111
|
+
hostId
|
|
112
|
+
]);
|
|
102
113
|
const [draft, setDraft] = useState(EMPTY_DRAFT);
|
|
103
114
|
const [sourceField, setSourceField] = useState('');
|
|
104
115
|
const [busy, setBusy] = useState(false);
|
|
@@ -332,7 +343,7 @@ const EMPTY_DRAFT = {
|
|
|
332
343
|
helperText: "Only datasets shared with this site are listed",
|
|
333
344
|
children: datasets.map((one)=>/*#__PURE__*/ _jsx(MenuItem, {
|
|
334
345
|
value: one.$id,
|
|
335
|
-
children: datasetDisplayName(one) || one.$id
|
|
346
|
+
children: labels[one.$id] || datasetDisplayName(one) || one.$id
|
|
336
347
|
}, one.$id))
|
|
337
348
|
}),
|
|
338
349
|
/*#__PURE__*/ _jsx(TextField, {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/record-pages/record-template-section.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\n'use client'\n\nimport { checkEntitlement, scopeTokensForHost } from '@aglyn/aglyn'\nimport type { ConsoleBesignerPagePropertiesZoneProps } from '@aglyn/aglyn/plugin-manager/feature-plugins'\nimport { useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport {\n useFirestore,\n useFirestoreCollection,\n useOrgDataScope,\n useOrgPlan,\n useUser,\n} from '@aglyn/tenant-feature-instance'\nimport {\n Button,\n InputAdornment,\n MenuItem,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport { collection, limit, query, where } from 'firebase/firestore'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { type DatasetModel, effectiveDatasetModel } from '../model/dataset-models'\nimport { type HostDataset, datasetDisplayName } from '../model/datasets'\nimport {\n type DatasetRecordPageBinding,\n isRecordAddressField,\n recordAddressFieldIds,\n recordPageBaseRefusal,\n recordPagePath,\n} from './record-pages'\nimport { useRecordPagePreview, useSiteRecordPageBindings } from './record-page-source'\n\ntype DatasetDoc = HostDataset & { $id: string; deletedAt?: unknown }\n\n/** The optional field pickers, in the order the section offers them. */\nconst FIELD_PICKERS = [\n {\n key: 'titleField',\n label: 'Page name from',\n helper: 'Names each page — its tab title and breadcrumb. Defaults to the first text field.',\n empty: 'First text field',\n },\n {\n key: 'seoTitleField',\n label: 'Search title from',\n helper: 'Used exactly as written. Without one, the page name and the site title are used.',\n empty: 'Page name',\n },\n {\n key: 'seoDescriptionField',\n label: 'Search description from',\n helper: 'Without one, this page’s own description is used.',\n empty: 'This page’s description',\n },\n {\n key: 'seoImageField',\n label: 'Sharing image from',\n helper: 'A media field or an image URL. Without one, this page’s image is used.',\n empty: 'This page’s image',\n },\n] as const\n\ntype Draft = Omit<DatasetRecordPageBinding, 'screenId'>\n\nconst EMPTY_DRAFT: Draft = { datasetId: '', base: '', slugField: '' }\n\n/**\n * Page Properties' \"Record pages\" section (AGL-3475): makes the page in the\n * editor the record template of a dataset, so it is served once per record at\n * `/{base}/{address}`, and picks the record the canvas draws it for.\n *\n * Saving a page that is not yet a template converts it first, through the\n * platform's own route, after saying what that means: it stops answering at\n * its own address and stops counting toward the plan's pages. The binding is\n * then written by the record-pages route, which re-checks everything this\n * section checks and the few things only the server can see.\n */\nexport function RecordTemplateSection(props: ConsoleBesignerPagePropertiesZoneProps) {\n const { hostId, orgId, screenId, screenKind } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n const { org, ready: planReady } = useOrgPlan(hostId)\n const { scope } = useOrgDataScope({ hostId, orgId })\n const { bindings } = useSiteRecordPageBindings(hostId)\n const current = bindings.find((binding) => binding.screenId === screenId)\n const preview = useRecordPagePreview({ hostId, screenId })\n\n // The datasets THIS site may see, which are the ones a record page can\n // render: the same scope the published page's reads apply.\n const { data: datasetDocs } = useFirestoreCollection<DatasetDoc>(\n () =>\n scope\n ? query(\n collection(firestore, scope[0], scope[1], 'datasets'),\n where('visibleTo', 'array-contains-any', scopeTokensForHost(hostId)),\n limit(100),\n )\n : null,\n [firestore, scope, hostId],\n { idField: '$id' },\n )\n const datasets = useMemo(\n () =>\n (datasetDocs ?? [])\n .filter((dataset) => !dataset.deletedAt)\n .sort((a, b) => datasetDisplayName(a).localeCompare(datasetDisplayName(b))),\n [datasetDocs],\n )\n\n const [draft, setDraft] = useState<Draft>(EMPTY_DRAFT)\n const [sourceField, setSourceField] = useState('')\n const [busy, setBusy] = useState(false)\n useEffect(() => {\n if (current) {\n const { screenId: _id, ...stored } = current\n setDraft(stored)\n } else {\n setDraft(EMPTY_DRAFT)\n }\n }, [current])\n\n const dataset = datasets.find((one) => one.$id === draft.datasetId)\n const model: DatasetModel | undefined = dataset ? effectiveDatasetModel(dataset) : undefined\n const addressFields = model ? recordAddressFieldIds(model) : []\n const textFields = model\n ? model.order.filter(\n (fieldId) =>\n model.fields[fieldId]?.type === 'text' && !isRecordAddressField(model.fields[fieldId]),\n )\n : []\n const baseRefusal = draft.base\n ? recordPageBaseRefusal(draft.base, {\n otherBases: bindings\n .filter((binding) => binding.screenId !== screenId)\n .map((binding) => binding.base),\n })\n : null\n\n // A dataset with exactly one address field needs no choice.\n useEffect(() => {\n if (model && !draft.slugField && addressFields.length === 1) {\n setDraft((previous) => ({ ...previous, slugField: addressFields[0] }))\n }\n }, [model, draft.slugField, addressFields])\n\n const post = useCallback(\n async (path: string, body: Record<string, unknown>) => {\n const response = await authorizedFetch(user, path, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n })\n const result = (await response.json().catch(() => ({}))) as Record<string, any>\n if (!response.ok) throw new Error(result?.['error'] ?? 'Something went wrong')\n return result\n },\n [user],\n )\n\n const handleAddAddresses = useCallback(async () => {\n if (!dataset || !sourceField || !orgId) return\n setBusy(true)\n try {\n const result = await post('/api/orgs/datasets', {\n orgId,\n action: 'add-address-field',\n datasetId: dataset.$id,\n sourceField,\n })\n setDraft((previous) => ({ ...previous, slugField: String(result['fieldId'] ?? '') }))\n enqueueSnackbar(\n result['truncated']\n ? `Gave ${result['filled']} records a page address — run it again for the rest`\n : `Gave ${result['filled']} records a page address`,\n { variant: 'success' },\n )\n } catch (error) {\n enqueueSnackbar((error as Error).message, { variant: 'error' })\n } finally {\n setBusy(false)\n }\n }, [dataset, sourceField, orgId, post, enqueueSnackbar])\n\n const handleSave = useCallback(async () => {\n if (screenKind !== 'template') {\n const accepted = await confirm({\n title: 'Make this page a record template?',\n description:\n `Each record gets its own page at ${recordPagePath(draft.base || 'base', 'address')}, ` +\n 'drawn by this design. This page stops answering at its own address and no ' +\n 'longer counts toward your plan’s pages.',\n confirmationText: 'Make it a template',\n })\n // The dialog rejects on cancel.\n .then(() => true)\n .catch(() => false)\n if (!accepted) return\n }\n setBusy(true)\n try {\n if (screenKind !== 'template') {\n await post('/api/hosts/screens', {\n action: 'convert',\n hostId,\n id: screenId,\n kind: 'template',\n })\n }\n await post('/api/hosts/record-pages', { action: 'save', hostId, screenId, ...draft })\n enqueueSnackbar('Record pages saved', { variant: 'success' })\n } catch (error) {\n enqueueSnackbar((error as Error).message, { variant: 'error' })\n } finally {\n setBusy(false)\n }\n }, [screenKind, confirm, draft, post, hostId, screenId, enqueueSnackbar])\n\n const handleRemove = useCallback(async () => {\n const accepted = await confirm({\n title: 'Stop serving record pages?',\n description:\n `Every page under /${current?.base ?? ''}/ stops answering. This page stays a ` +\n 'template, so it doesn’t answer at its own address either.',\n confirmationText: 'Stop serving them',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!accepted) return\n setBusy(true)\n try {\n await post('/api/hosts/record-pages', { action: 'remove', hostId, screenId })\n enqueueSnackbar('Record pages removed', { variant: 'success' })\n } catch (error) {\n enqueueSnackbar((error as Error).message, { variant: 'error' })\n setBusy(false)\n return\n }\n // The page is left a template, which nobody can visit. Making it a page\n // again is offered once, here, and checked against the plan's pages by\n // the platform's convert route, whose refusal names the count.\n const restore = await confirm({\n title: 'Make this a normal page again?',\n description:\n 'It counts toward your plan’s pages and, if it was published, answers at its ' +\n 'own address again right away. Placeholders like {{item.name}} show as plain ' +\n 'text until you edit them out.',\n confirmationText: 'Make it a page',\n cancellationText: 'Keep it hidden',\n })\n .then(() => true)\n .catch(() => false)\n if (restore) {\n try {\n await post('/api/hosts/screens', { action: 'convert', hostId, id: screenId, kind: 'page' })\n enqueueSnackbar('This is a normal page again', { variant: 'success' })\n } catch (error) {\n enqueueSnackbar((error as Error).message, { variant: 'error' })\n }\n }\n setBusy(false)\n }, [confirm, current?.base, post, hostId, screenId, enqueueSnackbar])\n\n if (planReady && !checkEntitlement(org as never, 'dataStore')) {\n return (\n <Stack spacing={1}>\n <Typography variant=\"subtitle2\">{'Record pages'}</Typography>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Serve this page once per record of a dataset — a page for every service or ' +\n 'location. Record pages need a Starter plan or higher.'}\n </Typography>\n </Stack>\n )\n }\n\n const ready = preview.status === 'ready' ? preview : null\n return (\n <Stack spacing={1.5}>\n <Typography variant=\"subtitle2\">{'Record pages'}</Typography>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {current\n ? `This page is the template of every record of ${\n dataset ? datasetDisplayName(dataset) : 'its dataset'\n }, each at /${current.base}/ and its page address. Inside it, ` +\n '{{item.field}} fills in from the record.'\n : 'Serve this page once per record of a dataset, each at its own address — ' +\n '/services/roofing. Inside it, {{item.field}} fills in from the record, as in ' +\n 'a repeat.'}\n </Typography>\n <TextField\n select\n size=\"small\"\n label=\"Dataset\"\n value={draft.datasetId}\n onChange={(event) =>\n setDraft({ ...EMPTY_DRAFT, base: draft.base, datasetId: event.target.value })\n }\n helperText=\"Only datasets shared with this site are listed\"\n >\n {datasets.map((one) => (\n <MenuItem key={one.$id} value={one.$id}>\n {datasetDisplayName(one) || one.$id}\n </MenuItem>\n ))}\n </TextField>\n <TextField\n size=\"small\"\n label=\"Address\"\n value={draft.base}\n onChange={(event) => setDraft({ ...draft, base: event.target.value })}\n error={Boolean(baseRefusal)}\n helperText={\n baseRefusal ??\n (draft.base\n ? `Records are served at /${draft.base.replace(/^\\/+|\\/+$/g, '')}/their-address`\n : 'One or more segments, like services or services/residential')\n }\n slotProps={{\n input: { startAdornment: <InputAdornment position=\"start\">/</InputAdornment> },\n }}\n />\n {model && addressFields.length ? (\n <TextField\n select\n size=\"small\"\n label=\"Page address field\"\n value={draft.slugField}\n onChange={(event) => setDraft({ ...draft, slugField: event.target.value })}\n helperText=\"Each record's own segment of its address\"\n >\n {addressFields.map((fieldId) => (\n <MenuItem key={fieldId} value={fieldId}>\n {model.fields[fieldId]?.name ?? fieldId}\n </MenuItem>\n ))}\n </TextField>\n ) : model ? (\n <Stack spacing={1}>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'This dataset has no Page address field yet. Make one from a text field: ' +\n 'every record gets an address made from its value (Roof Repair → ' +\n 'roof-repair), and new records get one as they are added. A record keeps its ' +\n 'address when it is renamed.'}\n </Typography>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <TextField\n select\n size=\"small\"\n label=\"Make addresses from\"\n value={sourceField}\n onChange={(event) => setSourceField(event.target.value)}\n sx={{ flex: 1 }}\n >\n {textFields.map((fieldId) => (\n <MenuItem key={fieldId} value={fieldId}>\n {model.fields[fieldId]?.name ?? fieldId}\n </MenuItem>\n ))}\n </TextField>\n <Button\n size=\"small\"\n variant=\"outlined\"\n onClick={handleAddAddresses}\n disabled={!sourceField || busy}\n >\n {'Make addresses'}\n </Button>\n </Stack>\n </Stack>\n ) : null}\n {model\n ? FIELD_PICKERS.map((picker) => (\n <TextField\n key={picker.key}\n select\n size=\"small\"\n label={picker.label}\n value={draft[picker.key] ?? ''}\n onChange={(event) =>\n setDraft({ ...draft, [picker.key]: event.target.value || undefined })\n }\n helperText={picker.helper}\n // The empty choice is a real one — \"use the default\" — so it is\n // shown rather than leaving the field looking blank.\n slotProps={{ select: { displayEmpty: true }, inputLabel: { shrink: true } }}\n >\n <MenuItem value=\"\">{picker.empty}</MenuItem>\n {model.order.map((fieldId) => (\n <MenuItem key={fieldId} value={fieldId}>\n {model.fields[fieldId]?.name ?? fieldId}\n </MenuItem>\n ))}\n </TextField>\n ))\n : null}\n {ready ? (\n <TextField\n select\n size=\"small\"\n label=\"Preview with\"\n value={ready.selectedId}\n onChange={(event) => ready.select(event.target.value)}\n helperText={`The canvas draws this page for one of ${ready.choices.length}${\n ready.choices.length >= 100 ? '+' : ''\n } records`}\n >\n {ready.choices.map((choice) => (\n <MenuItem key={choice.id} value={choice.id}>\n {choice.label}\n </MenuItem>\n ))}\n </TextField>\n ) : null}\n <Stack direction=\"row\" spacing={1}>\n <Button\n size=\"small\"\n variant=\"outlined\"\n onClick={handleSave}\n disabled={\n busy || !draft.datasetId || !draft.base || !draft.slugField || Boolean(baseRefusal)\n }\n >\n {current ? 'Save record pages' : 'Serve record pages'}\n </Button>\n {current ? (\n <Button size=\"small\" color=\"error\" onClick={handleRemove} disabled={busy}>\n {'Stop serving'}\n </Button>\n ) : null}\n </Stack>\n </Stack>\n )\n}\n\nexport default RecordTemplateSection\n"],"names":["checkEntitlement","scopeTokensForHost","useConfirmationContext","useSnackbar","authorizedFetch","useFirestore","useFirestoreCollection","useOrgDataScope","useOrgPlan","useUser","Button","InputAdornment","MenuItem","Stack","TextField","Typography","collection","limit","query","where","useCallback","useEffect","useMemo","useState","effectiveDatasetModel","datasetDisplayName","isRecordAddressField","recordAddressFieldIds","recordPageBaseRefusal","recordPagePath","useRecordPagePreview","useSiteRecordPageBindings","FIELD_PICKERS","key","label","helper","empty","EMPTY_DRAFT","datasetId","base","slugField","RecordTemplateSection","props","hostId","orgId","screenId","screenKind","firestore","data","user","enqueueSnackbar","confirm","org","ready","planReady","scope","bindings","current","find","binding","preview","datasetDocs","idField","datasets","filter","dataset","deletedAt","sort","a","b","localeCompare","draft","setDraft","sourceField","setSourceField","busy","setBusy","_id","stored","one","$id","model","undefined","addressFields","textFields","order","fieldId","fields","type","baseRefusal","otherBases","map","length","previous","post","path","body","response","method","headers","JSON","stringify","result","json","catch","ok","Error","handleAddAddresses","action","String","variant","error","message","handleSave","accepted","title","description","confirmationText","then","id","kind","handleRemove","confirmationButtonProps","color","restore","cancellationText","spacing","status","select","size","value","onChange","event","target","helperText","Boolean","replace","slotProps","input","startAdornment","position","name","direction","sx","alignItems","flex","onClick","disabled","picker","displayEmpty","inputLabel","shrink","selectedId","choices","choice"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;AAEA,SAASA,gBAAgB,EAAEC,kBAAkB,QAAQ,eAAc;AAEnE,SAASC,sBAAsB,QAAQ,uBAAsB;AAC7D,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,eAAe,QAAQ,2CAA0C;AAC1E,SACEC,YAAY,EACZC,sBAAsB,EACtBC,eAAe,EACfC,UAAU,EACVC,OAAO,QACF,iCAAgC;AACvC,SACEC,MAA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MAAMhC,IAAI,IAAI,CAACgC,MAAM/B,SAAS,IAAI+F,QAAQ9C;kCAGxEhC,UAAU,sBAAsB;;oBAElCA,wBACC,KAAC/C;wBAAOuH,MAAK;wBAAQN,OAAM;wBAAQuB,SAASzB;wBAAc0B,UAAUxE;kCACjE;yBAED;;;;;AAIZ;AAEA,eAAelC,sBAAqB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/record-pages/record-template-section.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\n'use client'\n\nimport { checkEntitlement, scopeTokensForHost } from '@aglyn/aglyn'\nimport type { ConsoleBesignerPagePropertiesZoneProps } from '@aglyn/aglyn/plugin-manager/feature-plugins'\nimport { useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport {\n useFirestore,\n useFirestoreCollection,\n useOrgDataScope,\n useOrgPlan,\n useUser,\n} from '@aglyn/tenant-feature-instance'\nimport {\n Button,\n InputAdornment,\n MenuItem,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport { collection, limit, query, where } from 'firebase/firestore'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { type DatasetModel, effectiveDatasetModel } from '../model/dataset-models'\nimport { type HostDataset, datasetDisplayName } from '../model/datasets'\nimport { type DatasetRailEntry, datasetPickerLabelsOf } from '../model/dataset-rail'\nimport {\n type DatasetRecordPageBinding,\n isRecordAddressField,\n recordAddressFieldIds,\n recordPageBaseRefusal,\n recordPagePath,\n} from './record-pages'\nimport { useRecordPagePreview, useSiteRecordPageBindings } from './record-page-source'\n\ntype DatasetDoc = HostDataset & { $id: string; deletedAt?: unknown }\n\n/** The optional field pickers, in the order the section offers them. */\nconst FIELD_PICKERS = [\n {\n key: 'titleField',\n label: 'Page name from',\n helper: 'Names each page — its tab title and breadcrumb. Defaults to the first text field.',\n empty: 'First text field',\n },\n {\n key: 'seoTitleField',\n label: 'Search title from',\n helper: 'Used exactly as written. Without one, the page name and the site title are used.',\n empty: 'Page name',\n },\n {\n key: 'seoDescriptionField',\n label: 'Search description from',\n helper: 'Without one, this page’s own description is used.',\n empty: 'This page’s description',\n },\n {\n key: 'seoImageField',\n label: 'Sharing image from',\n helper: 'A media field or an image URL. Without one, this page’s image is used.',\n empty: 'This page’s image',\n },\n] as const\n\ntype Draft = Omit<DatasetRecordPageBinding, 'screenId'>\n\nconst EMPTY_DRAFT: Draft = { datasetId: '', base: '', slugField: '' }\n\n/**\n * Page Properties' \"Record pages\" section (AGL-3475): makes the page in the\n * editor the record template of a dataset, so it is served once per record at\n * `/{base}/{address}`, and picks the record the canvas draws it for.\n *\n * Saving a page that is not yet a template converts it first, through the\n * platform's own route, after saying what that means: it stops answering at\n * its own address and stops counting toward the plan's pages. The binding is\n * then written by the record-pages route, which re-checks everything this\n * section checks and the few things only the server can see.\n */\nexport function RecordTemplateSection(props: ConsoleBesignerPagePropertiesZoneProps) {\n const { hostId, orgId, screenId, screenKind } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n const { org, ready: planReady } = useOrgPlan(hostId)\n const { scope } = useOrgDataScope({ hostId, orgId })\n const { bindings } = useSiteRecordPageBindings(hostId)\n const current = bindings.find((binding) => binding.screenId === screenId)\n const preview = useRecordPagePreview({ hostId, screenId })\n\n // The datasets THIS site may see, which are the ones a record page can\n // render: the same scope the published page's reads apply.\n const { data: datasetDocs } = useFirestoreCollection<DatasetDoc>(\n () =>\n scope\n ? query(\n collection(firestore, scope[0], scope[1], 'datasets'),\n where('visibleTo', 'array-contains-any', scopeTokensForHost(hostId)),\n limit(100),\n )\n : null,\n [firestore, scope, hostId],\n { idField: '$id' },\n )\n const datasets = useMemo(\n () =>\n (datasetDocs ?? [])\n .filter((dataset) => !dataset.deletedAt)\n .sort((a, b) => datasetDisplayName(a).localeCompare(datasetDisplayName(b))),\n [datasetDocs],\n )\n\n /**\n * Who a dataset is shared with only where two share a name (AGL-4047). Every\n * dataset listed is this site's to see, so one on a single site is on this\n * one, and is called so without reading the site.\n */\n const labels = useMemo(\n () => datasetPickerLabelsOf(datasets as DatasetRailEntry[], { [hostId]: 'This site' }),\n [datasets, hostId],\n )\n\n const [draft, setDraft] = useState<Draft>(EMPTY_DRAFT)\n const [sourceField, setSourceField] = useState('')\n const [busy, setBusy] = useState(false)\n useEffect(() => {\n if (current) {\n const { screenId: _id, ...stored } = current\n setDraft(stored)\n } else {\n setDraft(EMPTY_DRAFT)\n }\n }, [current])\n\n const dataset = datasets.find((one) => one.$id === draft.datasetId)\n const model: DatasetModel | undefined = dataset ? effectiveDatasetModel(dataset) : undefined\n const addressFields = model ? recordAddressFieldIds(model) : []\n const textFields = model\n ? model.order.filter(\n (fieldId) =>\n model.fields[fieldId]?.type === 'text' && !isRecordAddressField(model.fields[fieldId]),\n )\n : []\n const baseRefusal = draft.base\n ? recordPageBaseRefusal(draft.base, {\n otherBases: bindings\n .filter((binding) => binding.screenId !== screenId)\n .map((binding) => binding.base),\n })\n : null\n\n // A dataset with exactly one address field needs no choice.\n useEffect(() => {\n if (model && !draft.slugField && addressFields.length === 1) {\n setDraft((previous) => ({ ...previous, slugField: addressFields[0] }))\n }\n }, [model, draft.slugField, addressFields])\n\n const post = useCallback(\n async (path: string, body: Record<string, unknown>) => {\n const response = await authorizedFetch(user, path, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n })\n const result = (await response.json().catch(() => ({}))) as Record<string, any>\n if (!response.ok) throw new Error(result?.['error'] ?? 'Something went wrong')\n return result\n },\n [user],\n )\n\n const handleAddAddresses = useCallback(async () => {\n if (!dataset || !sourceField || !orgId) return\n setBusy(true)\n try {\n const result = await post('/api/orgs/datasets', {\n orgId,\n action: 'add-address-field',\n datasetId: dataset.$id,\n sourceField,\n })\n setDraft((previous) => ({ ...previous, slugField: String(result['fieldId'] ?? '') }))\n enqueueSnackbar(\n result['truncated']\n ? `Gave ${result['filled']} records a page address — run it again for the rest`\n : `Gave ${result['filled']} records a page address`,\n { variant: 'success' },\n )\n } catch (error) {\n enqueueSnackbar((error as Error).message, { variant: 'error' })\n } finally {\n setBusy(false)\n }\n }, [dataset, sourceField, orgId, post, enqueueSnackbar])\n\n const handleSave = useCallback(async () => {\n if (screenKind !== 'template') {\n const accepted = await confirm({\n title: 'Make this page a record template?',\n description:\n `Each record gets its own page at ${recordPagePath(draft.base || 'base', 'address')}, ` +\n 'drawn by this design. This page stops answering at its own address and no ' +\n 'longer counts toward your plan’s pages.',\n confirmationText: 'Make it a template',\n })\n // The dialog rejects on cancel.\n .then(() => true)\n .catch(() => false)\n if (!accepted) return\n }\n setBusy(true)\n try {\n if (screenKind !== 'template') {\n await post('/api/hosts/screens', {\n action: 'convert',\n hostId,\n id: screenId,\n kind: 'template',\n })\n }\n await post('/api/hosts/record-pages', { action: 'save', hostId, screenId, ...draft })\n enqueueSnackbar('Record pages saved', { variant: 'success' })\n } catch (error) {\n enqueueSnackbar((error as Error).message, { variant: 'error' })\n } finally {\n setBusy(false)\n }\n }, [screenKind, confirm, draft, post, hostId, screenId, enqueueSnackbar])\n\n const handleRemove = useCallback(async () => {\n const accepted = await confirm({\n title: 'Stop serving record pages?',\n description:\n `Every page under /${current?.base ?? ''}/ stops answering. This page stays a ` +\n 'template, so it doesn’t answer at its own address either.',\n confirmationText: 'Stop serving them',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!accepted) return\n setBusy(true)\n try {\n await post('/api/hosts/record-pages', { action: 'remove', hostId, screenId })\n enqueueSnackbar('Record pages removed', { variant: 'success' })\n } catch (error) {\n enqueueSnackbar((error as Error).message, { variant: 'error' })\n setBusy(false)\n return\n }\n // The page is left a template, which nobody can visit. Making it a page\n // again is offered once, here, and checked against the plan's pages by\n // the platform's convert route, whose refusal names the count.\n const restore = await confirm({\n title: 'Make this a normal page again?',\n description:\n 'It counts toward your plan’s pages and, if it was published, answers at its ' +\n 'own address again right away. Placeholders like {{item.name}} show as plain ' +\n 'text until you edit them out.',\n confirmationText: 'Make it a page',\n cancellationText: 'Keep it hidden',\n })\n .then(() => true)\n .catch(() => false)\n if (restore) {\n try {\n await post('/api/hosts/screens', { action: 'convert', hostId, id: screenId, kind: 'page' })\n enqueueSnackbar('This is a normal page again', { variant: 'success' })\n } catch (error) {\n enqueueSnackbar((error as Error).message, { variant: 'error' })\n }\n }\n setBusy(false)\n }, [confirm, current?.base, post, hostId, screenId, enqueueSnackbar])\n\n if (planReady && !checkEntitlement(org as never, 'dataStore')) {\n return (\n <Stack spacing={1}>\n <Typography variant=\"subtitle2\">{'Record pages'}</Typography>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Serve this page once per record of a dataset — a page for every service or ' +\n 'location. Record pages need a Starter plan or higher.'}\n </Typography>\n </Stack>\n )\n }\n\n const ready = preview.status === 'ready' ? preview : null\n return (\n <Stack spacing={1.5}>\n <Typography variant=\"subtitle2\">{'Record pages'}</Typography>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {current\n ? `This page is the template of every record of ${\n dataset ? datasetDisplayName(dataset) : 'its dataset'\n }, each at /${current.base}/ and its page address. Inside it, ` +\n '{{item.field}} fills in from the record.'\n : 'Serve this page once per record of a dataset, each at its own address — ' +\n '/services/roofing. Inside it, {{item.field}} fills in from the record, as in ' +\n 'a repeat.'}\n </Typography>\n <TextField\n select\n size=\"small\"\n label=\"Dataset\"\n value={draft.datasetId}\n onChange={(event) =>\n setDraft({ ...EMPTY_DRAFT, base: draft.base, datasetId: event.target.value })\n }\n helperText=\"Only datasets shared with this site are listed\"\n >\n {datasets.map((one) => (\n <MenuItem key={one.$id} value={one.$id}>\n {labels[one.$id] || datasetDisplayName(one) || one.$id}\n </MenuItem>\n ))}\n </TextField>\n <TextField\n size=\"small\"\n label=\"Address\"\n value={draft.base}\n onChange={(event) => setDraft({ ...draft, base: event.target.value })}\n error={Boolean(baseRefusal)}\n helperText={\n baseRefusal ??\n (draft.base\n ? `Records are served at /${draft.base.replace(/^\\/+|\\/+$/g, '')}/their-address`\n : 'One or more segments, like services or services/residential')\n }\n slotProps={{\n input: { startAdornment: <InputAdornment position=\"start\">/</InputAdornment> },\n }}\n />\n {model && addressFields.length ? (\n <TextField\n select\n size=\"small\"\n label=\"Page address field\"\n value={draft.slugField}\n onChange={(event) => setDraft({ ...draft, slugField: event.target.value })}\n helperText=\"Each record's own segment of its address\"\n >\n {addressFields.map((fieldId) => (\n <MenuItem key={fieldId} value={fieldId}>\n {model.fields[fieldId]?.name ?? fieldId}\n </MenuItem>\n ))}\n </TextField>\n ) : model ? (\n <Stack spacing={1}>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'This dataset has no Page address field yet. Make one from a text field: ' +\n 'every record gets an address made from its value (Roof Repair → ' +\n 'roof-repair), and new records get one as they are added. A record keeps its ' +\n 'address when it is renamed.'}\n </Typography>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <TextField\n select\n size=\"small\"\n label=\"Make addresses from\"\n value={sourceField}\n onChange={(event) => setSourceField(event.target.value)}\n sx={{ flex: 1 }}\n >\n {textFields.map((fieldId) => (\n <MenuItem key={fieldId} value={fieldId}>\n {model.fields[fieldId]?.name ?? fieldId}\n </MenuItem>\n ))}\n </TextField>\n <Button\n size=\"small\"\n variant=\"outlined\"\n onClick={handleAddAddresses}\n disabled={!sourceField || busy}\n >\n {'Make addresses'}\n </Button>\n </Stack>\n </Stack>\n ) : null}\n {model\n ? FIELD_PICKERS.map((picker) => (\n <TextField\n key={picker.key}\n select\n size=\"small\"\n label={picker.label}\n value={draft[picker.key] ?? ''}\n onChange={(event) =>\n setDraft({ ...draft, [picker.key]: event.target.value || undefined })\n }\n helperText={picker.helper}\n // The empty choice is a real one — \"use the default\" — so it is\n // shown rather than leaving the field looking blank.\n slotProps={{ select: { displayEmpty: true }, inputLabel: { shrink: true } }}\n >\n <MenuItem value=\"\">{picker.empty}</MenuItem>\n {model.order.map((fieldId) => (\n <MenuItem key={fieldId} value={fieldId}>\n {model.fields[fieldId]?.name ?? fieldId}\n </MenuItem>\n ))}\n </TextField>\n ))\n : null}\n {ready ? (\n <TextField\n select\n size=\"small\"\n label=\"Preview with\"\n value={ready.selectedId}\n onChange={(event) => ready.select(event.target.value)}\n helperText={`The canvas draws this page for one of ${ready.choices.length}${\n ready.choices.length >= 100 ? '+' : ''\n } records`}\n >\n {ready.choices.map((choice) => (\n <MenuItem key={choice.id} value={choice.id}>\n {choice.label}\n </MenuItem>\n ))}\n </TextField>\n ) : null}\n <Stack direction=\"row\" spacing={1}>\n <Button\n size=\"small\"\n variant=\"outlined\"\n onClick={handleSave}\n disabled={\n busy || !draft.datasetId || !draft.base || !draft.slugField || Boolean(baseRefusal)\n }\n >\n {current ? 'Save record pages' : 'Serve record pages'}\n </Button>\n {current ? (\n <Button size=\"small\" color=\"error\" onClick={handleRemove} disabled={busy}>\n {'Stop serving'}\n </Button>\n ) : null}\n </Stack>\n </Stack>\n )\n}\n\nexport default RecordTemplateSection\n"],"names":["checkEntitlement","scopeTokensForHost","useConfirmationContext","useSnackbar","authorizedFetch","useFirestore","useFirestoreCollection","useOrgDataScope","useOrgPlan","useUser","Button","InputAdornment","MenuItem","Stack","TextField","Typography","collection","limit","query","where","useCallback","useEffect","useMemo","useState","effectiveDatasetModel","datasetDisplayName","datasetPickerLabelsOf","isRecordAddressField","recordAddressFieldIds","recordPageBaseRefusal","recordPagePath","useRecordPagePreview","useSiteRecordPageBindings","FIELD_PICKERS","key","label","helper","empty","EMPTY_DRAFT","datasetId","base","slugField","RecordTemplateSection","props","hostId","orgId","screenId","screenKind","firestore","data","user","enqueueSnackbar","confirm","org","ready","planReady","scope","bindings","current","find","binding","preview","datasetDocs","idField","datasets","filter","dataset","deletedAt","sort","a","b","localeCompare","labels","draft","setDraft","sourceField","setSourceField","busy","setBusy","_id","stored","one","$id","model","undefined","addressFields","textFields","order","fieldId","fields","type","baseRefusal","otherBases","map","length","previous","post","path","body","response","method","headers","JSON","stringify","result","json","catch","ok","Error","handleAddAddresses","action","String","variant","error","message","handleSave","accepted","title","description","confirmationText","then","id","kind","handleRemove","confirmationButtonProps","color","restore","cancellationText","spacing","status","select","size","value","onChange","event","target","helperText","Boolean","replace","slotProps","input","startAdornment","position","name","direction","sx","alignItems","flex","onClick","disabled","picker","displayEmpty","inputLabel","shrink","selectedId","choices","choice"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;AAEA,SAASA,gBAAgB,EAAEC,kBAAkB,QAAQ,eAAc;AAEnE,SAASC,sBAAsB,QAAQ,uBAAsB;AAC7D,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,eAAe,QAAQ,2CAA0C;AAC1E,SACEC,YAAY,EACZC,sBAAsB,EACtBC,eAAe,EACfC,UAAU,EACVC,OAAO,QACF,iCAAgC;AACvC,SACEC,MAAM,EACNC,cAAc,EACdC,QAAQ,EACRC,KAAK,EACLC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SAASC,UAAU,EAAEC,KAAK,EAAEC,KAAK,EAAEC,KAAK,QAAQ,qBAAoB;AACpE,SAASC,WAAW,EAAEC,SAAS,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACjE,SAA4BC,qBAAqB,QAAQ,6BAAyB;AAClF,SAA2BC,kBAAkB,QAAQ,uBAAmB;AACxE,SAAgCC,qBAAqB,QAAQ,2BAAuB;AACpF,SAEEC,oBAAoB,EACpBC,qBAA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CACjE;yBAED;;;;;AAIZ;AAEA,eAAenC,sBAAqB"}
|
|
@@ -22,6 +22,7 @@ import { announceDatasetRecords as announceDatasetChange } from "../announce-dat
|
|
|
22
22
|
import { loadCustomFieldTypes } from "../custom-field-types.js";
|
|
23
23
|
import { coerceDocumentValues, datasetIntegrityFields, datasetIntegrityUpdate, effectiveDatasetModel, validateDocument } from "../../model/dataset-models.js";
|
|
24
24
|
import { fillRecordAddresses } from "../../record-pages/record-pages.js";
|
|
25
|
+
import { datasetNameLower } from "../../model/datasets.js";
|
|
25
26
|
/**
|
|
26
27
|
* The organization's datasets on the customer REST API, `/v1/datasets/…`
|
|
27
28
|
* (AGL-2126, AGL-3080): the datasets themselves and the records inside them.
|
|
@@ -176,6 +177,7 @@ const DATASET_FIELDS_MAX = 100;
|
|
|
176
177
|
const id = createResourceUid();
|
|
177
178
|
await collection.doc(id).create(_extends({
|
|
178
179
|
displayName: parsed.values.name,
|
|
180
|
+
nameLower: datasetNameLower(parsed.values.name),
|
|
179
181
|
fields: parsed.values.fields
|
|
180
182
|
}, parsed.values.model ? {
|
|
181
183
|
model: parsed.values.model
|
|
@@ -225,7 +227,10 @@ const DATASET_FIELDS_MAX = 100;
|
|
|
225
227
|
}
|
|
226
228
|
const { name, fields, model } = parsed.values;
|
|
227
229
|
const update = {};
|
|
228
|
-
if (name !== undefined)
|
|
230
|
+
if (name !== undefined) {
|
|
231
|
+
update.displayName = name;
|
|
232
|
+
update.nameLower = datasetNameLower(name);
|
|
233
|
+
}
|
|
229
234
|
if (fields !== undefined) update.fields = fields;
|
|
230
235
|
if (model !== undefined) update.model = model;
|
|
231
236
|
// An empty body is a no-op, answered with the current dataset rather than a
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/plugins/data/src/lib/server/api-v1/datasets.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 {\n checkDatasetQuota,\n checkEntitlement,\n checkQuota,\n createResourceUid,\n defaultScopeForNewResource,\n newResourceScopeFields,\n} from '@aglyn/aglyn/server'\nimport {\n ApiErrors,\n apiJson,\n dataStorageRefusal,\n listResponse,\n} from '@aglyn/tenant-data-admin'\nimport {\n type ApiV1Context,\n claimWrite,\n paginate,\n readJsonBody,\n requireScope,\n serialize,\n} from '@aglyn/tenant-data-admin/server/api-v1-kit'\nimport { FieldValue, Timestamp } from 'firebase-admin/firestore'\nimport { announceDatasetRecords as announceDatasetChange } from '../announce-dataset-records'\nimport { loadCustomFieldTypes } from '../custom-field-types'\nimport { coerceDocumentValues, datasetIntegrityFields, datasetIntegrityUpdate, effectiveDatasetModel, validateDocument } from '../../model/dataset-models'\nimport { fillRecordAddresses } from '../../record-pages/record-pages'\n\n/**\n * The organization's datasets on the customer REST API, `/v1/datasets/…`\n * (AGL-2126, AGL-3080): the datasets themselves and the records inside them.\n * Registered from this plugin's console server declarations; the console's\n * `/v1` router owns the pipeline in front — the key, the plan's API access,\n * the request quota, the rate limit — and hands every request under\n * `/v1/datasets` here.\n */\n\nconst datasetName = (data: FirebaseFirestore.DocumentData): string =>\n (data.displayName as string) ?? (data.name as string) ?? ''\n\nfunction datasetView(doc: FirebaseFirestore.DocumentSnapshot) {\n const data = doc.data() ?? {}\n return {\n id: doc.id,\n object: 'dataset',\n name: datasetName(data),\n fields: data.fields ?? [],\n created: serialize(data.createdAt) ?? null,\n }\n}\n\nfunction recordView(doc: FirebaseFirestore.DocumentSnapshot) {\n const data = doc.data() ?? {}\n return {\n id: doc.id,\n object: 'record',\n values: serialize(data.values ?? {}),\n created: serialize(data.createdAt) ?? null,\n updated: serialize(data.updatedAt) ?? null,\n }\n}\n\nfunction datasetsCollection(ctx: ApiV1Context) {\n return ctx.firestore.collection('orgs').doc(ctx.orgId).collection('datasets')\n}\n\n/** Serialized `model` ceiling, matching the console's create route. */\nconst DATASET_MODEL_MAX_BYTES = 64 * 1024\nconst DATASET_NAME_MAX = 120\nconst DATASET_FIELDS_MAX = 100\n\n/**\n * Validate the writable half of a dataset document (AGL-2126). Returns the\n * cleaned values, or the per-field map `conventions.md` publishes under\n * `validation_failed` — the same shape `validateDocument` produces for a\n * record, so a client branches on one thing across the whole resource.\n *\n * `partial` is what separates PATCH from POST: a create must be told a name\n * and at least one field, an update may send either alone. Absent keys are\n * left alone rather than cleared, because a PATCH that silently emptied\n * `fields` would take a dataset's schema away on a typo'd request body.\n */\nfunction readDatasetInput(\n body: Record<string, unknown>,\n { partial }: { partial: boolean },\n):\n | { values: { name?: string; fields?: string[]; model?: unknown } }\n | { errors: Record<string, string> } {\n const errors: Record<string, string> = {}\n const values: { name?: string; fields?: string[]; model?: unknown } = {}\n\n const hasName = body.name !== undefined\n if (hasName || !partial) {\n const name = String(body.name ?? '').trim().slice(0, DATASET_NAME_MAX)\n if (!name) errors.name = 'Required'\n else values.name = name\n }\n\n const hasFields = body.fields !== undefined\n if (hasFields || !partial) {\n if (!Array.isArray(body.fields)) {\n errors.fields = 'Must be an array of field names'\n } else {\n const fields = (body.fields as unknown[])\n .map((field) => String(field).trim())\n .filter((field) => field.length > 0)\n .slice(0, DATASET_FIELDS_MAX)\n if (fields.length === 0) errors.fields = 'At least one field is required'\n else values.fields = fields\n }\n }\n\n if (body.model !== undefined) {\n if (!body.model || typeof body.model !== 'object') {\n errors.model = 'Must be an object'\n } else if (JSON.stringify(body.model).length > DATASET_MODEL_MAX_BYTES) {\n errors.model = `Must serialize to under ${DATASET_MODEL_MAX_BYTES} bytes`\n } else {\n values.model = body.model\n }\n }\n\n return Object.keys(errors).length ? { errors } : { values }\n}\n\n/**\n * `POST /v1/datasets` (AGL-2126) — the call that lets the API bootstrap itself.\n *\n * Until this shipped, `/v1` could create and edit RECORDS but not the dataset\n * holding them, so an agency provisioning a client workspace, or a developer\n * keeping a schema in source control, had to click a dataset into existence\n * before their first API call could do anything. The console has been able to\n * do this all along (`apps/console/app/api/orgs/datasets`, `create-dataset`).\n *\n * The gates are the console route's, not a looser set. `dataStore` is the\n * entitlement, `checkDatasetQuota` is add-on aware, and — the one that is\n * invisible until it bites — `newResourceScopeFields` stamps `visibleTo`.\n * A dataset created without it matches no `array-contains-any` and therefore\n * renders on NO site at all (AGL-1044): the API would happily create data\n * that never appears anywhere, which is worse than refusing.\n */\nasync function createDataset(\n request: Request,\n ctx: ApiV1Context,\n): Promise<Response> {\n if (!checkEntitlement(ctx.org, 'dataStore')) {\n return ApiErrors.planRequired({\n message: 'Datasets are not included in this organization’s plan',\n code: 'data_store',\n headers: ctx.headers,\n })\n }\n\n const parsed = readDatasetInput(await readJsonBody(request), {\n partial: false,\n })\n if ('errors' in parsed) {\n return ApiErrors.badRequest({\n message: 'Dataset failed validation',\n code: 'validation_failed',\n fields: parsed.errors,\n headers: ctx.headers,\n })\n }\n\n /*\n * CLAIM ABOVE THE QUOTA (AGL-2296), and release on the refusal.\n *\n * This used to check the quota first and claim after, so that a refusal an\n * integrator can act on never consumed their key — a plan refusal is the\n * most retried failure there is, and it clears when somebody buys an\n * add-on. That reasoning is right and is preserved by the `release()`\n * below; the ORDERING it produced was not. A create that consumed the LAST\n * included slot could not be retried at all: the retry re-counts, is now AT\n * the band, and is refused before the claim is ever consulted — so the\n * replay never happens and the integrator cannot tell whether the dataset\n * exists. `conventions.md` publishes the opposite promise.\n *\n * Claiming first and releasing on each refusal gets both properties at\n * once, which is the trade `deleteRecord` already argues for and\n * `createContact` follows. Validation stays above: a deterministic 400 must\n * never take a key at all.\n */\n const collection = datasetsCollection(ctx)\n const claimed = await claimWrite(\n ctx,\n '*',\n request.headers.get('Idempotency-Key'),\n 'datasets',\n )\n if ('replay' in claimed) return claimed.replay\n const { claim } = claimed\n\n try {\n const datasetCount = (await collection.count().get()).data().count\n const quota = checkDatasetQuota(ctx.org, datasetCount)\n if (!quota.allowed) {\n await claim.release()\n return ApiErrors.planRequired({\n message:\n `Dataset limit reached (${quota.limit}). ` +\n (quota.upgradeRequired\n ? 'Upgrade the plan to add more.'\n : `Buy extra datasets for $${quota.addonPriceUsd}/mo each, or upgrade.`),\n code: 'dataset_quota',\n headers: ctx.headers,\n })\n }\n\n const id = createResourceUid()\n await collection.doc(id).create({\n displayName: parsed.values.name,\n fields: parsed.values.fields,\n ...(parsed.values.model ? { model: parsed.values.model } : {}),\n // AGL-1484: the required argument exists so a creator that has not\n // decided cannot compile. No site is in context on an org-scoped API\n // key, so the org's own default is the only honest answer.\n ...newResourceScopeFields(\n defaultScopeForNewResource({\n defaultResourceScope: (\n ctx.org as { defaultResourceScope?: 'org' | 'host' }\n )?.defaultResourceScope,\n hostId: null,\n }),\n ),\n createdAt: Timestamp.now(),\n })\n const view = datasetView(await collection.doc(id).get())\n // Stored as 200 so a replay is distinguishable from the fresh 201 — the\n // rule `conventions.md` publishes and `createRecord` already follows.\n await claim.record(200, view)\n return apiJson(view, { status: 201, headers: ctx.headers })\n } catch (error) {\n // Same direction as every other v1 write: a stranded key is irreversible\n // from outside, a duplicate dataset is one DELETE away.\n await claim.release()\n throw error\n }\n}\n\n/**\n * `PATCH /v1/datasets/{id}` — rename, re-field, or re-model. Takes no\n * `Idempotency-Key` and does not need one, for `updateRecord`'s reason: the\n * same body twice lands the same state AND returns the same `200`.\n */\nasync function updateDataset(\n request: Request,\n ctx: ApiV1Context,\n datasetRef: FirebaseFirestore.DocumentReference,\n): Promise<Response> {\n const snap = await datasetRef.get()\n if (!snap.exists) {\n return ApiErrors.notFound({ message: 'No such dataset', headers: ctx.headers })\n }\n const parsed = readDatasetInput(await readJsonBody(request), { partial: true })\n if ('errors' in parsed) {\n return ApiErrors.badRequest({\n message: 'Dataset failed validation',\n code: 'validation_failed',\n fields: parsed.errors,\n headers: ctx.headers,\n })\n }\n const { name, fields, model } = parsed.values\n const update: Record<string, unknown> = {}\n if (name !== undefined) update.displayName = name\n if (fields !== undefined) update.fields = fields\n if (model !== undefined) update.model = model\n // An empty body is a no-op, answered with the current dataset rather than a\n // 400: a client re-sending an unchanged object should not have to special-\n // case it, and there is no state to disagree about.\n if (Object.keys(update).length > 0) await datasetRef.update(update)\n // The fields and the model decide how every bound page formats and orders\n // this dataset's rows, so a schema change is a change to those pages — and\n // no publish follows a `/v1` write (AGL-3386). A rename alone renders\n // nothing: the display name is the console's label for the dataset. Best\n // effort, like the record writes' announce; the update is already stored.\n if (fields !== undefined || model !== undefined) {\n await announceDatasetChange({\n firestore: ctx.firestore,\n orgId: ctx.orgId,\n datasetId: datasetRef.id,\n })\n }\n return apiJson(datasetView(await datasetRef.get()), { headers: ctx.headers })\n}\n\n/**\n * `DELETE /v1/datasets/{id}` — refuses while records remain.\n *\n * A recursive delete is not something a single REST call should do quietly:\n * the records are the customer's content, and one mistyped id would take all\n * of them with no receipt naming what went. So this answers `409 conflict`\n * with the count, and the integrator deletes the records first — with the\n * same key semantics, through an endpoint that already exists.\n */\nasync function deleteDataset(\n request: Request,\n ctx: ApiV1Context,\n datasetRef: FirebaseFirestore.DocumentReference,\n): Promise<Response> {\n const claimed = await claimWrite(\n ctx,\n datasetRef.id,\n request.headers.get('Idempotency-Key'),\n 'dataset-deletes',\n )\n if ('replay' in claimed) return claimed.replay\n const { claim } = claimed\n\n try {\n const snap = await datasetRef.get()\n if (!snap.exists) {\n // Release: a wrong id is the integrator's to correct and retry with the\n // same key, exactly as `deleteRecord` does.\n await claim.release()\n return ApiErrors.notFound({ message: 'No such dataset', headers: ctx.headers })\n }\n const records = (await datasetRef.collection('records').count().get()).data()\n .count\n if (records > 0) {\n // Release too — this refusal clears once the records are gone, and the\n // retry that should then succeed must not replay the refusal.\n await claim.release()\n return ApiErrors.conflict({\n message: `Dataset still holds ${records} record${\n records === 1 ? '' : 's'\n }. Delete them first.`,\n code: 'dataset_not_empty',\n headers: ctx.headers,\n })\n }\n await datasetRef.delete()\n const view = { id: datasetRef.id, object: 'dataset', deleted: true }\n await claim.record(200, view)\n return apiJson(view, { headers: ctx.headers })\n } catch (error) {\n await claim.release()\n throw error\n }\n}\n\nexport async function handleDatasets(\n request: Request,\n ctx: ApiV1Context,\n segments: string[],\n url: URL,\n): Promise<Response> {\n const [, datasetId, sub, recordId] = segments\n\n // /v1/datasets\n if (!datasetId) {\n if (request.method === 'GET') {\n const denied = requireScope(ctx, 'datasets:read')\n if (denied) return denied\n const { docs, nextCursor } = await paginate(datasetsCollection(ctx), url)\n return listResponse(docs.map(datasetView), nextCursor, ctx.headers)\n }\n if (request.method === 'POST') {\n const denied = requireScope(ctx, 'datasets:write')\n if (denied) return denied\n return createDataset(request, ctx)\n }\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: 'GET, POST' },\n })\n }\n\n const datasetRef = datasetsCollection(ctx).doc(datasetId)\n\n // /v1/datasets/{id}\n if (!sub) {\n if (request.method === 'GET') {\n const denied = requireScope(ctx, 'datasets:read')\n if (denied) return denied\n const snap = await datasetRef.get()\n if (!snap.exists) {\n return ApiErrors.notFound({ message: 'No such dataset', headers: ctx.headers })\n }\n return apiJson(datasetView(snap), { headers: ctx.headers })\n }\n if (request.method === 'PATCH') {\n const denied = requireScope(ctx, 'datasets:write')\n if (denied) return denied\n return updateDataset(request, ctx, datasetRef)\n }\n if (request.method === 'DELETE') {\n const denied = requireScope(ctx, 'datasets:write')\n if (denied) return denied\n return deleteDataset(request, ctx, datasetRef)\n }\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: 'GET, PATCH, DELETE' },\n })\n }\n\n if (sub !== 'records') {\n return ApiErrors.notFound({ message: `Unknown endpoint`, headers: ctx.headers })\n }\n\n const datasetSnap = await datasetRef.get()\n if (!datasetSnap.exists) {\n return ApiErrors.notFound({ message: 'No such dataset', headers: ctx.headers })\n }\n const recordsRef = datasetRef.collection('records')\n\n // /v1/datasets/{id}/records\n if (!recordId) {\n if (request.method === 'GET') {\n const denied = requireScope(ctx, 'datasets:read')\n if (denied) return denied\n const { docs, nextCursor } = await paginate(recordsRef, url)\n return listResponse(docs.map(recordView), nextCursor, ctx.headers)\n }\n if (request.method === 'POST') {\n const denied = requireScope(ctx, 'datasets:write')\n if (denied) return denied\n return createRecord(request, ctx, datasetSnap, recordsRef)\n }\n return ApiErrors.methodNotAllowed({ headers: ctx.headers })\n }\n\n // /v1/datasets/{id}/records/{recordId}\n const recordRef = recordsRef.doc(recordId)\n if (request.method === 'GET') {\n const denied = requireScope(ctx, 'datasets:read')\n if (denied) return denied\n const snap = await recordRef.get()\n if (!snap.exists) return ApiErrors.notFound({ message: 'No such record', headers: ctx.headers })\n return apiJson(recordView(snap), { headers: ctx.headers })\n }\n if (request.method === 'PATCH') {\n const denied = requireScope(ctx, 'datasets:write')\n if (denied) return denied\n return updateRecord(request, ctx, datasetSnap, recordRef)\n }\n if (request.method === 'DELETE') {\n const denied = requireScope(ctx, 'datasets:write')\n if (denied) return denied\n return deleteRecord(request, ctx, datasetSnap.id, recordRef)\n }\n return ApiErrors.methodNotAllowed({ headers: ctx.headers })\n}\n\nasync function createRecord(\n request: Request,\n ctx: ApiV1Context,\n datasetSnap: FirebaseFirestore.DocumentSnapshot,\n recordsRef: FirebaseFirestore.CollectionReference,\n): Promise<Response> {\n const model = effectiveDatasetModel(datasetSnap.data() ?? {})\n // A plugin's field validator only runs once its plugin has registered it.\n await loadCustomFieldTypes(model, ctx.loadPluginSurfaces)\n const body = await readJsonBody(request)\n const coerced = fillRecordAddresses(\n model,\n coerceDocumentValues(model, (body.values as Record<string, unknown>) ?? {}),\n )\n const errors = validateDocument(model, coerced)\n if (Object.keys(errors).length) {\n return ApiErrors.badRequest({\n message: 'Record failed validation',\n headers: ctx.headers,\n code: 'validation_failed',\n // Name the offending fields (AGL-901): validateDocument already\n // produces this map, and a bare 'something is wrong' on a 20-field\n // record leaves an integrator bisecting their payload.\n fields: errors,\n })\n }\n\n /*\n * THE TWO QUOTAS THIS ROUTE DID NOT HAVE (AGL-2253).\n *\n * `POST /v1/datasets/{id}/records` counted rows only to compute `order` and\n * checked nothing: not `recordsPerDataset`, not `dataStorageMbPerOrg`. The\n * console route (`/api/orgs/datasets`) enforces both on the same write, and\n * the tenant form path enforces the rows half — so `/v1` was the one door\n * into `orgs/{id}/datasets/{id}/records` with no cap on it, and a customer\n * could blow a limit through the REST API that the UI refuses.\n *\n * They sit BELOW the idempotency claim (AGL-2296), which is a change from\n * how they shipped. Checking them first protected the key on a refusal —\n * right, and kept by the `release()` calls below — but it made a create\n * that consumed the LAST included row impossible to retry: the retry\n * re-counts, is now AT the band, and is refused before the claim is\n * consulted, so the replay never happens. The bytes leg is worse in\n * practice, because a bulk import crosses the storage band mid-run and\n * every retry from that point on is refused rather than replayed.\n *\n * The row count is reused for `order`, so this adds no read on the rows\n * leg. The bytes leg adds no read either on any plan that meters the\n * overage; see `dataStorageRefusal`.\n */\n // Idempotency: replay a prior create for the same key instead of\n // duplicating. Claimed HERE, below validation, so a deterministic 400 never\n // takes the key at all — an integrator fixes the payload and retries with\n // the same key, exactly as the POS cashier does (AGL-1691).\n const claimed = await claimWrite(\n ctx,\n datasetSnap.id,\n request.headers.get('Idempotency-Key'),\n 'records',\n )\n if ('replay' in claimed) return claimed.replay\n const { claim } = claimed\n\n try {\n const order = (await recordsRef.count().get()).data().count\n const recordQuota = checkQuota(ctx.org, 'recordsPerDataset', order)\n if (!recordQuota.allowed) {\n await claim.release()\n return ApiErrors.planRequired({\n message: `Record limit reached (${recordQuota.limit}). Upgrade the plan to add more.`,\n code: 'record_quota',\n headers: ctx.headers,\n })\n }\n const storageRefusal = await dataStorageRefusal(\n ctx.org,\n ctx.firestore.collection('orgs').doc(ctx.orgId),\n )\n if (storageRefusal) {\n await claim.release()\n return ApiErrors.planRequired({\n message:\n storageRefusal.basis === 'always'\n ? 'Dataset storage is not included in this organization’s plan'\n : `Dataset storage limit reached (${storageRefusal.includedMb} MB). Upgrade the plan to add more.`,\n code: 'data_storage_quota',\n headers: ctx.headers,\n })\n }\n\n const recordId = createResourceUid()\n await recordsRef.doc(recordId).create({\n values: coerced,\n // The integrity index the delete check queries, written on the same\n // write as the values it describes.\n ...datasetIntegrityFields(model, coerced),\n order,\n createdAt: Timestamp.now(),\n updatedAt: Timestamp.now(),\n })\n const created = await recordsRef.doc(recordId).get()\n const view = recordView(created)\n // AGL-2462 recorded that a `/v1` write cannot publish, and the ONLY thing\n // that made it visible was the hour. It announces now (AGL-3113): the\n // pages repeating over this dataset are dropped, on every site it is\n // shared with. Best effort — the record is already stored.\n await announceDatasetChange({\n firestore: ctx.firestore,\n orgId: ctx.orgId,\n datasetId: datasetSnap.id,\n })\n // Recorded as 200, never the 201 this answers: `conventions.md` publishes\n // the status as how a client tells a fresh create from a replay, and that\n // is the contract integrations branch on.\n await claim.record(200, view)\n return apiJson(view, { status: 201, headers: ctx.headers })\n } catch (error) {\n /*\n * Release on EVERY failure, including one whose outcome we cannot know —\n * the deliberate opposite of the refund (AGL-1696, `2dd52f01c`), which\n * strands the key on a throw. Same reasoning, applied where its money term\n * is absent.\n *\n * NOTHING on `/v1` moves money — the write surface is datasets, records,\n * the form-submission `read` flag and contacts (AGL-2276), while orders\n * and products stay read-only precisely because writing them would — so\n * \"a released key costs a second refund\" has no analogue here. The costs invert instead. A duplicate record is visible and\n * reversible BY THE INTEGRATOR with `DELETE /v1/datasets/{id}/records/{id}`\n * — same API, same scope, one extra call. A stranded key is irreversible\n * from outside: keys are documented as never expiring, and an integrator\n * derives them from their own upstream event ids precisely so retries\n * dedupe, so a stranded key means that event can never be written at all.\n *\n * Residual: a process killed between the claim and the record strands the\n * key regardless. `createdAtMs` is written so a sweeper can reap those.\n */\n await claim.release()\n throw error\n }\n}\n\nasync function updateRecord(\n request: Request,\n ctx: ApiV1Context,\n datasetSnap: FirebaseFirestore.DocumentSnapshot,\n recordRef: FirebaseFirestore.DocumentReference,\n): Promise<Response> {\n const snap = await recordRef.get()\n if (!snap.exists) return ApiErrors.notFound({ message: 'No such record', headers: ctx.headers })\n\n const model = effectiveDatasetModel(datasetSnap.data() ?? {})\n // A plugin's field validator only runs once its plugin has registered it.\n await loadCustomFieldTypes(model, ctx.loadPluginSurfaces)\n const body = await readJsonBody(request)\n // PATCH merges the supplied fields over the stored values.\n const merged = fillRecordAddresses(model, {\n ...((snap.get('values') as Record<string, unknown>) ?? {}),\n ...coerceDocumentValues(model, (body.values as Record<string, unknown>) ?? {}),\n })\n const errors = validateDocument(model, merged)\n if (Object.keys(errors).length) {\n return ApiErrors.badRequest({\n message: 'Record failed validation',\n headers: ctx.headers,\n code: 'validation_failed',\n // Name the offending fields (AGL-901): validateDocument already\n // produces this map, and a bare 'something is wrong' on a 20-field\n // record leaves an integrator bisecting their payload.\n fields: errors,\n })\n }\n await recordRef.update({\n values: merged,\n // A PATCH that clears the last reference has to REMOVE the index, not\n // omit it: an update leaves an omitted field standing, and a stale\n // `referencedIds` refuses a delete nothing is holding.\n ...datasetIntegrityUpdate(model, merged, FieldValue.delete()),\n updatedAt: Timestamp.now(),\n })\n const updated = await recordRef.get()\n // An edited row is as stale on a live page as a new one (AGL-3113).\n await announceDatasetChange({\n firestore: ctx.firestore,\n orgId: ctx.orgId,\n datasetId: datasetSnap.id,\n })\n return apiJson(recordView(updated), { headers: ctx.headers })\n}\n\n/**\n * Delete a record, and let a retry of the SAME attempt say so (AGL-1710).\n *\n * This used to read, 404 if absent, then delete. The state after two calls was\n * right and the response was not: an integrator whose first response was lost\n * to a timeout retried, got `404 No such record`, and had no way to separate\n * \"already deleted, you're fine\" from \"that id was wrong and nothing was ever\n * deleted\". Both readings prescribe different actions and the wrong one —\n * escalate, or re-sync the whole dataset — is the one people pick.\n *\n * The obvious fix, `204` (or a `deleted: true` 200) for ANY missing record, is\n * rejected on two counts. It is a BREAKING change: `datasets.md` publishes\n * `404 not_found \"No such record\"` on this path and clients branch on it. And\n * it spends a signal to buy one — a caller that never saw the resource would\n * get a success for a typo'd id, losing the only feedback the API gives that\n * it is asking about the wrong thing. Consistency points the same way: `GET`\n * and `PATCH` on this very path answer 404 for a missing record, and every\n * sibling `DELETE` on `/v1` — the dataset, the form submission, the contact —\n * answers the same way, so there is no convention a 204 would be matching.\n *\n * So the key identifies the ATTEMPT rather than the resource, which is what\n * the shared claim is already for. A retry of the attempt that did the\n * deleting replays its receipt; a wrong id still 404s. That expands the\n * published contract instead of changing it — a caller sending no header sees\n * byte-identical behaviour.\n *\n * The claim is taken ABOVE the existence check, which is the one place this\n * deliberately diverges from `createRecord` (which claims below validation, so\n * a deterministic 400 never burns a key). It has to: the record a retry asks\n * about is precisely the one the first attempt removed, so a claim consulted\n * after the existence check would 404 the retry without ever reaching the\n * replay — the bug verbatim. The cost is taking-and-releasing on a genuine\n * miss, which is the trade the ordering requires.\n */\nasync function deleteRecord(\n request: Request,\n ctx: ApiV1Context,\n datasetId: string,\n recordRef: FirebaseFirestore.DocumentReference,\n): Promise<Response> {\n const claimed = await claimWrite(\n ctx,\n datasetId,\n request.headers.get('Idempotency-Key'),\n 'record-deletes',\n )\n if ('replay' in claimed) return claimed.replay\n const { claim } = claimed\n\n try {\n const snap = await recordRef.get()\n if (!snap.exists) {\n // Release, so the miss does not consume the key: the integrator corrects\n // the id and retries with the same one, exactly as a create's 400 lets\n // them correct the payload. A burned key here would be worse than the\n // 404 — keys never expire, and integrators derive them from upstream\n // event ids, so the corrected delete could never be sent at all.\n await claim.release()\n return ApiErrors.notFound({ message: 'No such record', headers: ctx.headers })\n }\n await recordRef.delete()\n // A row that is gone is the same staleness as a row that changed: the\n // page goes on rendering it until its cache is dropped (AGL-3113).\n await announceDatasetChange({\n firestore: ctx.firestore,\n orgId: ctx.orgId,\n datasetId,\n })\n const view = { id: recordRef.id, object: 'record', deleted: true }\n await claim.record(200, view)\n return apiJson(view, { headers: ctx.headers })\n } catch (error) {\n // Same direction as `createRecord`: a failed attempt gives the key back.\n // Nothing here moves money, and a stranded key is the irreversible failure.\n await claim.release()\n throw error\n }\n}\n"],"names":["checkDatasetQuota","checkEntitlement","checkQuota","createResourceUid","defaultScopeForNewResource","newResourceScopeFields","ApiErrors","apiJson","dataStorageRefusal","listResponse","claimWrite","paginate","readJsonBody","requireScope","serialize","FieldValue","Timestamp","announceDatasetRecords","announceDatasetChange","loadCustomFieldTypes","coerceDocumentValues","datasetIntegrityFields","datasetIntegrityUpdate","effectiveDatasetModel","validateDocument","fillRecordAddresses","datasetName","data","displayName","name","datasetView","doc","id","object","fields","created","createdAt","recordView","values","updated","updatedAt","datasetsCollection","ctx","firestore","collection","orgId","DATASET_MODEL_MAX_BYTES","DATASET_NAME_MAX","DATASET_FIELDS_MAX","readDatasetInput","body","partial","errors","hasName","undefined","String","trim","slice","hasFields","Array","isArray","map","field","filter","length","model","JSON","stringify","Object","keys","createDataset","request","org","planRequired","message","code","headers","parsed","badRequest","claimed","get","replay","claim","datasetCount","count","quota","allowed","release","limit","upgradeRequired","addonPriceUsd","create","defaultResourceScope","hostId","now","view","record","status","error","updateDataset","datasetRef","snap","exists","notFound","update","datasetId","deleteDataset","records","conflict","delete","deleted","handleDatasets","segments","url","sub","recordId","method","denied","docs","nextCursor","methodNotAllowed","Allow","datasetSnap","recordsRef","createRecord","recordRef","updateRecord","deleteRecord","loadPluginSurfaces","coerced","order","recordQuota","storageRefusal","basis","includedMb","merged"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,iBAAiB,EACjBC,gBAAgB,EAChBC,UAAU,EACVC,iBAAiB,EACjBC,0BAA0B,EAC1BC,sBAAsB,QACjB,sBAAqB;AAC5B,SACEC,SAAS,EACTC,OAAO,EACPC,kBAAkB,EAClBC,YAAY,QACP,2BAA0B;AACjC,SAEEC,UAAU,EACVC,QAAQ,EACRC,YAAY,EACZC,YAAY,EACZC,SAAS,QACJ,6CAA4C;AACnD,SAASC,UAAU,EAAEC,SAA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AAMc,MAAM,CAAC,KAAKD;QACxB,OAAOxF,QAAQwF,MAAM;YAAEnB,SAASlC,IAAIkC,OAAO;QAAC;IAC9C,EAAE,OAAOsB,OAAO;QACd,yEAAyE;QACzE,4EAA4E;QAC5E,MAAMhB,MAAMK,OAAO;QACnB,MAAMW;IACR;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/plugins/data/src/lib/server/api-v1/datasets.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 {\n checkDatasetQuota,\n checkEntitlement,\n checkQuota,\n createResourceUid,\n defaultScopeForNewResource,\n newResourceScopeFields,\n} from '@aglyn/aglyn/server'\nimport {\n ApiErrors,\n apiJson,\n dataStorageRefusal,\n listResponse,\n} from '@aglyn/tenant-data-admin'\nimport {\n type ApiV1Context,\n claimWrite,\n paginate,\n readJsonBody,\n requireScope,\n serialize,\n} from '@aglyn/tenant-data-admin/server/api-v1-kit'\nimport { FieldValue, Timestamp } from 'firebase-admin/firestore'\nimport { announceDatasetRecords as announceDatasetChange } from '../announce-dataset-records'\nimport { loadCustomFieldTypes } from '../custom-field-types'\nimport { coerceDocumentValues, datasetIntegrityFields, datasetIntegrityUpdate, effectiveDatasetModel, validateDocument } from '../../model/dataset-models'\nimport { fillRecordAddresses } from '../../record-pages/record-pages'\nimport { datasetNameLower } from '../../model/datasets'\n\n/**\n * The organization's datasets on the customer REST API, `/v1/datasets/…`\n * (AGL-2126, AGL-3080): the datasets themselves and the records inside them.\n * Registered from this plugin's console server declarations; the console's\n * `/v1` router owns the pipeline in front — the key, the plan's API access,\n * the request quota, the rate limit — and hands every request under\n * `/v1/datasets` here.\n */\n\nconst datasetName = (data: FirebaseFirestore.DocumentData): string =>\n (data.displayName as string) ?? (data.name as string) ?? ''\n\nfunction datasetView(doc: FirebaseFirestore.DocumentSnapshot) {\n const data = doc.data() ?? {}\n return {\n id: doc.id,\n object: 'dataset',\n name: datasetName(data),\n fields: data.fields ?? [],\n created: serialize(data.createdAt) ?? null,\n }\n}\n\nfunction recordView(doc: FirebaseFirestore.DocumentSnapshot) {\n const data = doc.data() ?? {}\n return {\n id: doc.id,\n object: 'record',\n values: serialize(data.values ?? {}),\n created: serialize(data.createdAt) ?? null,\n updated: serialize(data.updatedAt) ?? null,\n }\n}\n\nfunction datasetsCollection(ctx: ApiV1Context) {\n return ctx.firestore.collection('orgs').doc(ctx.orgId).collection('datasets')\n}\n\n/** Serialized `model` ceiling, matching the console's create route. */\nconst DATASET_MODEL_MAX_BYTES = 64 * 1024\nconst DATASET_NAME_MAX = 120\nconst DATASET_FIELDS_MAX = 100\n\n/**\n * Validate the writable half of a dataset document (AGL-2126). Returns the\n * cleaned values, or the per-field map `conventions.md` publishes under\n * `validation_failed` — the same shape `validateDocument` produces for a\n * record, so a client branches on one thing across the whole resource.\n *\n * `partial` is what separates PATCH from POST: a create must be told a name\n * and at least one field, an update may send either alone. Absent keys are\n * left alone rather than cleared, because a PATCH that silently emptied\n * `fields` would take a dataset's schema away on a typo'd request body.\n */\nfunction readDatasetInput(\n body: Record<string, unknown>,\n { partial }: { partial: boolean },\n):\n | { values: { name?: string; fields?: string[]; model?: unknown } }\n | { errors: Record<string, string> } {\n const errors: Record<string, string> = {}\n const values: { name?: string; fields?: string[]; model?: unknown } = {}\n\n const hasName = body.name !== undefined\n if (hasName || !partial) {\n const name = String(body.name ?? '').trim().slice(0, DATASET_NAME_MAX)\n if (!name) errors.name = 'Required'\n else values.name = name\n }\n\n const hasFields = body.fields !== undefined\n if (hasFields || !partial) {\n if (!Array.isArray(body.fields)) {\n errors.fields = 'Must be an array of field names'\n } else {\n const fields = (body.fields as unknown[])\n .map((field) => String(field).trim())\n .filter((field) => field.length > 0)\n .slice(0, DATASET_FIELDS_MAX)\n if (fields.length === 0) errors.fields = 'At least one field is required'\n else values.fields = fields\n }\n }\n\n if (body.model !== undefined) {\n if (!body.model || typeof body.model !== 'object') {\n errors.model = 'Must be an object'\n } else if (JSON.stringify(body.model).length > DATASET_MODEL_MAX_BYTES) {\n errors.model = `Must serialize to under ${DATASET_MODEL_MAX_BYTES} bytes`\n } else {\n values.model = body.model\n }\n }\n\n return Object.keys(errors).length ? { errors } : { values }\n}\n\n/**\n * `POST /v1/datasets` (AGL-2126) — the call that lets the API bootstrap itself.\n *\n * Until this shipped, `/v1` could create and edit RECORDS but not the dataset\n * holding them, so an agency provisioning a client workspace, or a developer\n * keeping a schema in source control, had to click a dataset into existence\n * before their first API call could do anything. The console has been able to\n * do this all along (`apps/console/app/api/orgs/datasets`, `create-dataset`).\n *\n * The gates are the console route's, not a looser set. `dataStore` is the\n * entitlement, `checkDatasetQuota` is add-on aware, and — the one that is\n * invisible until it bites — `newResourceScopeFields` stamps `visibleTo`.\n * A dataset created without it matches no `array-contains-any` and therefore\n * renders on NO site at all (AGL-1044): the API would happily create data\n * that never appears anywhere, which is worse than refusing.\n */\nasync function createDataset(\n request: Request,\n ctx: ApiV1Context,\n): Promise<Response> {\n if (!checkEntitlement(ctx.org, 'dataStore')) {\n return ApiErrors.planRequired({\n message: 'Datasets are not included in this organization’s plan',\n code: 'data_store',\n headers: ctx.headers,\n })\n }\n\n const parsed = readDatasetInput(await readJsonBody(request), {\n partial: false,\n })\n if ('errors' in parsed) {\n return ApiErrors.badRequest({\n message: 'Dataset failed validation',\n code: 'validation_failed',\n fields: parsed.errors,\n headers: ctx.headers,\n })\n }\n\n /*\n * CLAIM ABOVE THE QUOTA (AGL-2296), and release on the refusal.\n *\n * This used to check the quota first and claim after, so that a refusal an\n * integrator can act on never consumed their key — a plan refusal is the\n * most retried failure there is, and it clears when somebody buys an\n * add-on. That reasoning is right and is preserved by the `release()`\n * below; the ORDERING it produced was not. A create that consumed the LAST\n * included slot could not be retried at all: the retry re-counts, is now AT\n * the band, and is refused before the claim is ever consulted — so the\n * replay never happens and the integrator cannot tell whether the dataset\n * exists. `conventions.md` publishes the opposite promise.\n *\n * Claiming first and releasing on each refusal gets both properties at\n * once, which is the trade `deleteRecord` already argues for and\n * `createContact` follows. Validation stays above: a deterministic 400 must\n * never take a key at all.\n */\n const collection = datasetsCollection(ctx)\n const claimed = await claimWrite(\n ctx,\n '*',\n request.headers.get('Idempotency-Key'),\n 'datasets',\n )\n if ('replay' in claimed) return claimed.replay\n const { claim } = claimed\n\n try {\n const datasetCount = (await collection.count().get()).data().count\n const quota = checkDatasetQuota(ctx.org, datasetCount)\n if (!quota.allowed) {\n await claim.release()\n return ApiErrors.planRequired({\n message:\n `Dataset limit reached (${quota.limit}). ` +\n (quota.upgradeRequired\n ? 'Upgrade the plan to add more.'\n : `Buy extra datasets for $${quota.addonPriceUsd}/mo each, or upgrade.`),\n code: 'dataset_quota',\n headers: ctx.headers,\n })\n }\n\n const id = createResourceUid()\n await collection.doc(id).create({\n displayName: parsed.values.name,\n nameLower: datasetNameLower(parsed.values.name),\n fields: parsed.values.fields,\n ...(parsed.values.model ? { model: parsed.values.model } : {}),\n // AGL-1484: the required argument exists so a creator that has not\n // decided cannot compile. No site is in context on an org-scoped API\n // key, so the org's own default is the only honest answer.\n ...newResourceScopeFields(\n defaultScopeForNewResource({\n defaultResourceScope: (\n ctx.org as { defaultResourceScope?: 'org' | 'host' }\n )?.defaultResourceScope,\n hostId: null,\n }),\n ),\n createdAt: Timestamp.now(),\n })\n const view = datasetView(await collection.doc(id).get())\n // Stored as 200 so a replay is distinguishable from the fresh 201 — the\n // rule `conventions.md` publishes and `createRecord` already follows.\n await claim.record(200, view)\n return apiJson(view, { status: 201, headers: ctx.headers })\n } catch (error) {\n // Same direction as every other v1 write: a stranded key is irreversible\n // from outside, a duplicate dataset is one DELETE away.\n await claim.release()\n throw error\n }\n}\n\n/**\n * `PATCH /v1/datasets/{id}` — rename, re-field, or re-model. Takes no\n * `Idempotency-Key` and does not need one, for `updateRecord`'s reason: the\n * same body twice lands the same state AND returns the same `200`.\n */\nasync function updateDataset(\n request: Request,\n ctx: ApiV1Context,\n datasetRef: FirebaseFirestore.DocumentReference,\n): Promise<Response> {\n const snap = await datasetRef.get()\n if (!snap.exists) {\n return ApiErrors.notFound({ message: 'No such dataset', headers: ctx.headers })\n }\n const parsed = readDatasetInput(await readJsonBody(request), { partial: true })\n if ('errors' in parsed) {\n return ApiErrors.badRequest({\n message: 'Dataset failed validation',\n code: 'validation_failed',\n fields: parsed.errors,\n headers: ctx.headers,\n })\n }\n const { name, fields, model } = parsed.values\n const update: Record<string, unknown> = {}\n if (name !== undefined) {\n update.displayName = name\n update.nameLower = datasetNameLower(name)\n }\n if (fields !== undefined) update.fields = fields\n if (model !== undefined) update.model = model\n // An empty body is a no-op, answered with the current dataset rather than a\n // 400: a client re-sending an unchanged object should not have to special-\n // case it, and there is no state to disagree about.\n if (Object.keys(update).length > 0) await datasetRef.update(update)\n // The fields and the model decide how every bound page formats and orders\n // this dataset's rows, so a schema change is a change to those pages — and\n // no publish follows a `/v1` write (AGL-3386). A rename alone renders\n // nothing: the display name is the console's label for the dataset. Best\n // effort, like the record writes' announce; the update is already stored.\n if (fields !== undefined || model !== undefined) {\n await announceDatasetChange({\n firestore: ctx.firestore,\n orgId: ctx.orgId,\n datasetId: datasetRef.id,\n })\n }\n return apiJson(datasetView(await datasetRef.get()), { headers: ctx.headers })\n}\n\n/**\n * `DELETE /v1/datasets/{id}` — refuses while records remain.\n *\n * A recursive delete is not something a single REST call should do quietly:\n * the records are the customer's content, and one mistyped id would take all\n * of them with no receipt naming what went. So this answers `409 conflict`\n * with the count, and the integrator deletes the records first — with the\n * same key semantics, through an endpoint that already exists.\n */\nasync function deleteDataset(\n request: Request,\n ctx: ApiV1Context,\n datasetRef: FirebaseFirestore.DocumentReference,\n): Promise<Response> {\n const claimed = await claimWrite(\n ctx,\n datasetRef.id,\n request.headers.get('Idempotency-Key'),\n 'dataset-deletes',\n )\n if ('replay' in claimed) return claimed.replay\n const { claim } = claimed\n\n try {\n const snap = await datasetRef.get()\n if (!snap.exists) {\n // Release: a wrong id is the integrator's to correct and retry with the\n // same key, exactly as `deleteRecord` does.\n await claim.release()\n return ApiErrors.notFound({ message: 'No such dataset', headers: ctx.headers })\n }\n const records = (await datasetRef.collection('records').count().get()).data()\n .count\n if (records > 0) {\n // Release too — this refusal clears once the records are gone, and the\n // retry that should then succeed must not replay the refusal.\n await claim.release()\n return ApiErrors.conflict({\n message: `Dataset still holds ${records} record${\n records === 1 ? '' : 's'\n }. Delete them first.`,\n code: 'dataset_not_empty',\n headers: ctx.headers,\n })\n }\n await datasetRef.delete()\n const view = { id: datasetRef.id, object: 'dataset', deleted: true }\n await claim.record(200, view)\n return apiJson(view, { headers: ctx.headers })\n } catch (error) {\n await claim.release()\n throw error\n }\n}\n\nexport async function handleDatasets(\n request: Request,\n ctx: ApiV1Context,\n segments: string[],\n url: URL,\n): Promise<Response> {\n const [, datasetId, sub, recordId] = segments\n\n // /v1/datasets\n if (!datasetId) {\n if (request.method === 'GET') {\n const denied = requireScope(ctx, 'datasets:read')\n if (denied) return denied\n const { docs, nextCursor } = await paginate(datasetsCollection(ctx), url)\n return listResponse(docs.map(datasetView), nextCursor, ctx.headers)\n }\n if (request.method === 'POST') {\n const denied = requireScope(ctx, 'datasets:write')\n if (denied) return denied\n return createDataset(request, ctx)\n }\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: 'GET, POST' },\n })\n }\n\n const datasetRef = datasetsCollection(ctx).doc(datasetId)\n\n // /v1/datasets/{id}\n if (!sub) {\n if (request.method === 'GET') {\n const denied = requireScope(ctx, 'datasets:read')\n if (denied) return denied\n const snap = await datasetRef.get()\n if (!snap.exists) {\n return ApiErrors.notFound({ message: 'No such dataset', headers: ctx.headers })\n }\n return apiJson(datasetView(snap), { headers: ctx.headers })\n }\n if (request.method === 'PATCH') {\n const denied = requireScope(ctx, 'datasets:write')\n if (denied) return denied\n return updateDataset(request, ctx, datasetRef)\n }\n if (request.method === 'DELETE') {\n const denied = requireScope(ctx, 'datasets:write')\n if (denied) return denied\n return deleteDataset(request, ctx, datasetRef)\n }\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: 'GET, PATCH, DELETE' },\n })\n }\n\n if (sub !== 'records') {\n return ApiErrors.notFound({ message: `Unknown endpoint`, headers: ctx.headers })\n }\n\n const datasetSnap = await datasetRef.get()\n if (!datasetSnap.exists) {\n return ApiErrors.notFound({ message: 'No such dataset', headers: ctx.headers })\n }\n const recordsRef = datasetRef.collection('records')\n\n // /v1/datasets/{id}/records\n if (!recordId) {\n if (request.method === 'GET') {\n const denied = requireScope(ctx, 'datasets:read')\n if (denied) return denied\n const { docs, nextCursor } = await paginate(recordsRef, url)\n return listResponse(docs.map(recordView), nextCursor, ctx.headers)\n }\n if (request.method === 'POST') {\n const denied = requireScope(ctx, 'datasets:write')\n if (denied) return denied\n return createRecord(request, ctx, datasetSnap, recordsRef)\n }\n return ApiErrors.methodNotAllowed({ headers: ctx.headers })\n }\n\n // /v1/datasets/{id}/records/{recordId}\n const recordRef = recordsRef.doc(recordId)\n if (request.method === 'GET') {\n const denied = requireScope(ctx, 'datasets:read')\n if (denied) return denied\n const snap = await recordRef.get()\n if (!snap.exists) return ApiErrors.notFound({ message: 'No such record', headers: ctx.headers })\n return apiJson(recordView(snap), { headers: ctx.headers })\n }\n if (request.method === 'PATCH') {\n const denied = requireScope(ctx, 'datasets:write')\n if (denied) return denied\n return updateRecord(request, ctx, datasetSnap, recordRef)\n }\n if (request.method === 'DELETE') {\n const denied = requireScope(ctx, 'datasets:write')\n if (denied) return denied\n return deleteRecord(request, ctx, datasetSnap.id, recordRef)\n }\n return ApiErrors.methodNotAllowed({ headers: ctx.headers })\n}\n\nasync function createRecord(\n request: Request,\n ctx: ApiV1Context,\n datasetSnap: FirebaseFirestore.DocumentSnapshot,\n recordsRef: FirebaseFirestore.CollectionReference,\n): Promise<Response> {\n const model = effectiveDatasetModel(datasetSnap.data() ?? {})\n // A plugin's field validator only runs once its plugin has registered it.\n await loadCustomFieldTypes(model, ctx.loadPluginSurfaces)\n const body = await readJsonBody(request)\n const coerced = fillRecordAddresses(\n model,\n coerceDocumentValues(model, (body.values as Record<string, unknown>) ?? {}),\n )\n const errors = validateDocument(model, coerced)\n if (Object.keys(errors).length) {\n return ApiErrors.badRequest({\n message: 'Record failed validation',\n headers: ctx.headers,\n code: 'validation_failed',\n // Name the offending fields (AGL-901): validateDocument already\n // produces this map, and a bare 'something is wrong' on a 20-field\n // record leaves an integrator bisecting their payload.\n fields: errors,\n })\n }\n\n /*\n * THE TWO QUOTAS THIS ROUTE DID NOT HAVE (AGL-2253).\n *\n * `POST /v1/datasets/{id}/records` counted rows only to compute `order` and\n * checked nothing: not `recordsPerDataset`, not `dataStorageMbPerOrg`. The\n * console route (`/api/orgs/datasets`) enforces both on the same write, and\n * the tenant form path enforces the rows half — so `/v1` was the one door\n * into `orgs/{id}/datasets/{id}/records` with no cap on it, and a customer\n * could blow a limit through the REST API that the UI refuses.\n *\n * They sit BELOW the idempotency claim (AGL-2296), which is a change from\n * how they shipped. Checking them first protected the key on a refusal —\n * right, and kept by the `release()` calls below — but it made a create\n * that consumed the LAST included row impossible to retry: the retry\n * re-counts, is now AT the band, and is refused before the claim is\n * consulted, so the replay never happens. The bytes leg is worse in\n * practice, because a bulk import crosses the storage band mid-run and\n * every retry from that point on is refused rather than replayed.\n *\n * The row count is reused for `order`, so this adds no read on the rows\n * leg. The bytes leg adds no read either on any plan that meters the\n * overage; see `dataStorageRefusal`.\n */\n // Idempotency: replay a prior create for the same key instead of\n // duplicating. Claimed HERE, below validation, so a deterministic 400 never\n // takes the key at all — an integrator fixes the payload and retries with\n // the same key, exactly as the POS cashier does (AGL-1691).\n const claimed = await claimWrite(\n ctx,\n datasetSnap.id,\n request.headers.get('Idempotency-Key'),\n 'records',\n )\n if ('replay' in claimed) return claimed.replay\n const { claim } = claimed\n\n try {\n const order = (await recordsRef.count().get()).data().count\n const recordQuota = checkQuota(ctx.org, 'recordsPerDataset', order)\n if (!recordQuota.allowed) {\n await claim.release()\n return ApiErrors.planRequired({\n message: `Record limit reached (${recordQuota.limit}). Upgrade the plan to add more.`,\n code: 'record_quota',\n headers: ctx.headers,\n })\n }\n const storageRefusal = await dataStorageRefusal(\n ctx.org,\n ctx.firestore.collection('orgs').doc(ctx.orgId),\n )\n if (storageRefusal) {\n await claim.release()\n return ApiErrors.planRequired({\n message:\n storageRefusal.basis === 'always'\n ? 'Dataset storage is not included in this organization’s plan'\n : `Dataset storage limit reached (${storageRefusal.includedMb} MB). Upgrade the plan to add more.`,\n code: 'data_storage_quota',\n headers: ctx.headers,\n })\n }\n\n const recordId = createResourceUid()\n await recordsRef.doc(recordId).create({\n values: coerced,\n // The integrity index the delete check queries, written on the same\n // write as the values it describes.\n ...datasetIntegrityFields(model, coerced),\n order,\n createdAt: Timestamp.now(),\n updatedAt: Timestamp.now(),\n })\n const created = await recordsRef.doc(recordId).get()\n const view = recordView(created)\n // AGL-2462 recorded that a `/v1` write cannot publish, and the ONLY thing\n // that made it visible was the hour. It announces now (AGL-3113): the\n // pages repeating over this dataset are dropped, on every site it is\n // shared with. Best effort — the record is already stored.\n await announceDatasetChange({\n firestore: ctx.firestore,\n orgId: ctx.orgId,\n datasetId: datasetSnap.id,\n })\n // Recorded as 200, never the 201 this answers: `conventions.md` publishes\n // the status as how a client tells a fresh create from a replay, and that\n // is the contract integrations branch on.\n await claim.record(200, view)\n return apiJson(view, { status: 201, headers: ctx.headers })\n } catch (error) {\n /*\n * Release on EVERY failure, including one whose outcome we cannot know —\n * the deliberate opposite of the refund (AGL-1696, `2dd52f01c`), which\n * strands the key on a throw. Same reasoning, applied where its money term\n * is absent.\n *\n * NOTHING on `/v1` moves money — the write surface is datasets, records,\n * the form-submission `read` flag and contacts (AGL-2276), while orders\n * and products stay read-only precisely because writing them would — so\n * \"a released key costs a second refund\" has no analogue here. The costs invert instead. A duplicate record is visible and\n * reversible BY THE INTEGRATOR with `DELETE /v1/datasets/{id}/records/{id}`\n * — same API, same scope, one extra call. A stranded key is irreversible\n * from outside: keys are documented as never expiring, and an integrator\n * derives them from their own upstream event ids precisely so retries\n * dedupe, so a stranded key means that event can never be written at all.\n *\n * Residual: a process killed between the claim and the record strands the\n * key regardless. `createdAtMs` is written so a sweeper can reap those.\n */\n await claim.release()\n throw error\n }\n}\n\nasync function updateRecord(\n request: Request,\n ctx: ApiV1Context,\n datasetSnap: FirebaseFirestore.DocumentSnapshot,\n recordRef: FirebaseFirestore.DocumentReference,\n): Promise<Response> {\n const snap = await recordRef.get()\n if (!snap.exists) return ApiErrors.notFound({ message: 'No such record', headers: ctx.headers })\n\n const model = effectiveDatasetModel(datasetSnap.data() ?? {})\n // A plugin's field validator only runs once its plugin has registered it.\n await loadCustomFieldTypes(model, ctx.loadPluginSurfaces)\n const body = await readJsonBody(request)\n // PATCH merges the supplied fields over the stored values.\n const merged = fillRecordAddresses(model, {\n ...((snap.get('values') as Record<string, unknown>) ?? {}),\n ...coerceDocumentValues(model, (body.values as Record<string, unknown>) ?? {}),\n })\n const errors = validateDocument(model, merged)\n if (Object.keys(errors).length) {\n return ApiErrors.badRequest({\n message: 'Record failed validation',\n headers: ctx.headers,\n code: 'validation_failed',\n // Name the offending fields (AGL-901): validateDocument already\n // produces this map, and a bare 'something is wrong' on a 20-field\n // record leaves an integrator bisecting their payload.\n fields: errors,\n })\n }\n await recordRef.update({\n values: merged,\n // A PATCH that clears the last reference has to REMOVE the index, not\n // omit it: an update leaves an omitted field standing, and a stale\n // `referencedIds` refuses a delete nothing is holding.\n ...datasetIntegrityUpdate(model, merged, FieldValue.delete()),\n updatedAt: Timestamp.now(),\n })\n const updated = await recordRef.get()\n // An edited row is as stale on a live page as a new one (AGL-3113).\n await announceDatasetChange({\n firestore: ctx.firestore,\n orgId: ctx.orgId,\n datasetId: datasetSnap.id,\n })\n return apiJson(recordView(updated), { headers: ctx.headers })\n}\n\n/**\n * Delete a record, and let a retry of the SAME attempt say so (AGL-1710).\n *\n * This used to read, 404 if absent, then delete. The state after two calls was\n * right and the response was not: an integrator whose first response was lost\n * to a timeout retried, got `404 No such record`, and had no way to separate\n * \"already deleted, you're fine\" from \"that id was wrong and nothing was ever\n * deleted\". Both readings prescribe different actions and the wrong one —\n * escalate, or re-sync the whole dataset — is the one people pick.\n *\n * The obvious fix, `204` (or a `deleted: true` 200) for ANY missing record, is\n * rejected on two counts. It is a BREAKING change: `datasets.md` publishes\n * `404 not_found \"No such record\"` on this path and clients branch on it. And\n * it spends a signal to buy one — a caller that never saw the resource would\n * get a success for a typo'd id, losing the only feedback the API gives that\n * it is asking about the wrong thing. Consistency points the same way: `GET`\n * and `PATCH` on this very path answer 404 for a missing record, and every\n * sibling `DELETE` on `/v1` — the dataset, the form submission, the contact —\n * answers the same way, so there is no convention a 204 would be matching.\n *\n * So the key identifies the ATTEMPT rather than the resource, which is what\n * the shared claim is already for. A retry of the attempt that did the\n * deleting replays its receipt; a wrong id still 404s. That expands the\n * published contract instead of changing it — a caller sending no header sees\n * byte-identical behaviour.\n *\n * The claim is taken ABOVE the existence check, which is the one place this\n * deliberately diverges from `createRecord` (which claims below validation, so\n * a deterministic 400 never burns a key). It has to: the record a retry asks\n * about is precisely the one the first attempt removed, so a claim consulted\n * after the existence check would 404 the retry without ever reaching the\n * replay — the bug verbatim. The cost is taking-and-releasing on a genuine\n * miss, which is the trade the ordering requires.\n */\nasync function deleteRecord(\n request: Request,\n ctx: ApiV1Context,\n datasetId: string,\n recordRef: FirebaseFirestore.DocumentReference,\n): Promise<Response> {\n const claimed = await claimWrite(\n ctx,\n datasetId,\n request.headers.get('Idempotency-Key'),\n 'record-deletes',\n )\n if ('replay' in claimed) return claimed.replay\n const { claim } = claimed\n\n try {\n const snap = await recordRef.get()\n if (!snap.exists) {\n // Release, so the miss does not consume the key: the integrator corrects\n // the id and retries with the same one, exactly as a create's 400 lets\n // them correct the payload. A burned key here would be worse than the\n // 404 — keys never expire, and integrators derive them from upstream\n // event ids, so the corrected delete could never be sent at all.\n await claim.release()\n return ApiErrors.notFound({ message: 'No such record', headers: ctx.headers })\n }\n await recordRef.delete()\n // A row that is gone is the same staleness as a row that changed: the\n // page goes on rendering it until its cache is dropped (AGL-3113).\n await announceDatasetChange({\n firestore: ctx.firestore,\n orgId: ctx.orgId,\n datasetId,\n })\n const view = { id: recordRef.id, object: 'record', deleted: true }\n await claim.record(200, view)\n return apiJson(view, { headers: ctx.headers })\n } catch (error) {\n // Same direction as `createRecord`: a failed attempt gives the key back.\n // Nothing here moves money, and a stranded key is the irreversible failure.\n await claim.release()\n throw error\n }\n}\n"],"names":["checkDatasetQuota","checkEntitlement","checkQuota","createResourceUid","defaultScopeForNewResource","newResourceScopeFields","ApiErrors","apiJson","dataStorageRefusal","listResponse","claimWrite","paginate","readJsonBody","requireScope","serialize","FieldValue","Timestamp","announceDatasetRecords","announceDatasetChange","loadCustomFieldTypes","coerceDocumentValues","datasetIntegrityFields","datasetIntegrityUpdate","effectiveDatasetModel","validateDocument","fillRecordAddresses","datasetNameLower","datasetName","data","displayName","name","datasetView","doc","id","object","fields","created","createdAt","recordView","values","updated","updatedAt","datasetsCollection","ctx","firestore","collection","orgId","DATASET_MODEL_MAX_BYTES","DATASET_NAME_MAX","DATASET_FIELDS_MAX","readDatasetInput","body","partial","errors","hasName","undefined","String","trim","slice","hasFields","Array","isArray","map","field","filter","length","model","JSON","stringify","Object","keys","createDataset","request","org","planRequired","message","code","headers","parsed","badRequest","claimed","get","replay","claim","datasetCount","count","quota","allowed","release","limit","upgradeRequired","addonPriceUsd","create","nameLower","defaultResourceScope","hostId","now","view","record","status","error","updateDataset","datasetRef","snap","exists","notFound","update","datasetId","deleteDataset","records","conflict","delete","deleted","handleDatasets","segments","url","sub","recordId","method","denied","docs","nextCursor","methodNotAllowed","Allow","datasetSnap","recordsRef","createRecord","recordRef","updateRecord","deleteRecord","loadPluginSurfaces","coerced","order","recordQuota","storageRefusal","basis","includedMb","merged"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,iBAAiB,EACjBC,gBAAgB,EAChBC,UAAU,EACVC,iBAAiB,EACjBC,0BAA0B,EAC1BC,sBAAsB,QACjB,sBAAqB;AAC5B,SACEC,SAAS,EACTC,OAAO,EACPC,kBAAkB,EAClBC,YAAY,QACP,2BAA0B;AACjC,SAEEC,UAAU,EACVC,QAAQ,EACRC,YAAY,EACZC,YAAY,EACZC,SAAS,QACJ,6CAA4C;AACnD,SAASC,UAAU,EAAEC,SAAS,QAAQ,2BAA0B;AAChE,SAASC,0BAA0BC,qBAAqB,QAAQ,iCAA6B;AAC7F,SAASC,oBAAoB,QAAQ,2BAAuB;AAC5D,SAASC,oBAAoB,EAAEC,sBAAsB,EAAEC,sBAAsB,EAAEC,qBAAqB,EAAEC,gBAAgB,QAAQ,gCAA4B;AAC1J,SAASC,mBAAmB,QAAQ,qCAAiC;AACrE,SAASC,gBAAgB,QAAQ,0BAAsB;AAEvD;;;;;;;CAOC,GAED,MAAMC,cAAc,CAACC;QACnB,MAACA;YAAD,QAACA,oBAAAA,KAAKC,WAAW,YAAhBD,oBAAgCA,KAAKE,IAAI,YAA1C,OAAyD;;AAE3D,SAASC,YAAYC,GAAuC;QAC7CA,WAKHJ,cACCd;IANX,MAAMc,QAAOI,YAAAA,IAAIJ,IAAI,cAARI,YAAc,CAAC;IAC5B,OAAO;QACLC,IAAID,IAAIC,EAAE;QACVC,QAAQ;QACRJ,MAAMH,YAAYC;QAClBO,MAAM,GAAEP,eAAAA,KAAKO,MAAM,YAAXP,eAAe,EAAE;QACzBQ,OAAO,GAAEtB,aAAAA,UAAUc,KAAKS,SAAS,aAAxBvB,aAA6B;IACxC;AACF;AAEA,SAASwB,WAAWN,GAAuC;QA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,CAAC,oBACpB;IAEF,IAAI,YAAYD,SAAS,OAAOA,QAAQE,MAAM;IAC9C,MAAM,EAAEC,KAAK,EAAE,GAAGH;IAElB,IAAI;QACF,MAAMuB,OAAO,MAAMwB,UAAU9C,GAAG;QAChC,IAAI,CAACsB,KAAKC,MAAM,EAAE;YAChB,yEAAyE;YACzE,uEAAuE;YACvE,sEAAsE;YACtE,qEAAqE;YACrE,iEAAiE;YACjE,MAAMrB,MAAMK,OAAO;YACnB,OAAOlF,UAAUmG,QAAQ,CAAC;gBAAE9B,SAAS;gBAAkBE,SAASlC,IAAIkC,OAAO;YAAC;QAC9E;QACA,MAAMkD,UAAUhB,MAAM;QACtB,sEAAsE;QACtE,mEAAmE;QACnE,MAAM7F,sBAAsB;YAC1B0B,WAAWD,IAAIC,SAAS;YACxBE,OAAOH,IAAIG,KAAK;YAChB6D;QACF;QACA,MAAMV,OAAO;YAAEhE,IAAI8F,UAAU9F,EAAE;YAAEC,QAAQ;YAAU8E,SAAS;QAAK;QACjE,MAAM7B,MAAMe,MAAM,CAAC,KAAKD;QACxB,OAAO1F,QAAQ0F,MAAM;YAAEpB,SAASlC,IAAIkC,OAAO;QAAC;IAC9C,EAAE,OAAOuB,OAAO;QACd,yEAAyE;QACzE,4EAA4E;QAC5E,MAAMjB,MAAMK,OAAO;QACnB,MAAMY;IACR;AACF"}
|
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/
|
|
17
|
+
import type { ScopePlaced } from '@aglyn/aglyn/app-utils/site-placement';
|
|
17
18
|
import type { AglynOrgMember } from '@aglyn/aglyn/foundation/definitions/organization.types';
|
|
18
19
|
/** A dataset act and the two keys that decide it. */
|
|
19
20
|
declare const ACTS: {
|
|
@@ -27,14 +28,14 @@ declare const ACTS: {
|
|
|
27
28
|
};
|
|
28
29
|
};
|
|
29
30
|
/** The key a refusal names: the site's on a one-site dataset, else the workspace's. */
|
|
30
|
-
export declare function datasetRefusalPermission(act: keyof typeof ACTS,
|
|
31
|
-
/** May this member write or delete
|
|
31
|
+
export declare function datasetRefusalPermission(act: keyof typeof ACTS, dataset: ScopePlaced | null | undefined): string;
|
|
32
|
+
/** May this member write or delete this dataset, as its document places it? The routes' `canWriteDatasetOn`. */
|
|
32
33
|
export declare function memberMayActOnDataset(input: {
|
|
33
34
|
firestore: FirebaseFirestore.Firestore;
|
|
34
35
|
orgId: string;
|
|
35
36
|
uid: string;
|
|
36
37
|
member: Partial<AglynOrgMember>;
|
|
37
|
-
|
|
38
|
+
dataset: ScopePlaced | null | undefined;
|
|
38
39
|
act: keyof typeof ACTS;
|
|
39
40
|
}): Promise<boolean>;
|
|
40
41
|
export {};
|
|
@@ -28,15 +28,17 @@ import { DATA_ERASE_PERMISSION, DATA_MANAGE_PERMISSION, DATA_SITE_DELETE_PERMISS
|
|
|
28
28
|
siteKey: DATA_SITE_DELETE_PERMISSION
|
|
29
29
|
}
|
|
30
30
|
};
|
|
31
|
-
/** The key a refusal names: the site's on a one-site dataset, else the workspace's. */ export function datasetRefusalPermission(act,
|
|
32
|
-
return placedRefusalPermission(
|
|
31
|
+
/** The key a refusal names: the site's on a one-site dataset, else the workspace's. */ export function datasetRefusalPermission(act, dataset) {
|
|
32
|
+
return placedRefusalPermission(dataset, ACTS[act].workspaceKey, ACTS[act].siteKey);
|
|
33
33
|
}
|
|
34
|
-
/** May this member write or delete
|
|
35
|
-
const { act } = input, rest = _object_without_properties_loose(input, [
|
|
36
|
-
"act"
|
|
34
|
+
/** May this member write or delete this dataset, as its document places it? The routes' `canWriteDatasetOn`. */ export async function memberMayActOnDataset(input) {
|
|
35
|
+
const { act, dataset } = input, rest = _object_without_properties_loose(input, [
|
|
36
|
+
"act",
|
|
37
|
+
"dataset"
|
|
37
38
|
]);
|
|
38
39
|
const { workspaceKey, siteKey } = ACTS[act];
|
|
39
40
|
return memberMayActOnPlaced(_extends({}, rest, {
|
|
41
|
+
placed: dataset,
|
|
40
42
|
workspace: await memberHasOrgPermission(input.orgId, input.member, workspaceKey),
|
|
41
43
|
workspaceKey,
|
|
42
44
|
siteKey,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/server/dataset-access.server.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 type { AglynOrgMember } from '@aglyn/aglyn/foundation/definitions/organization.types'\nimport { memberHasOrgPermission } from '@aglyn/tenant-data-admin'\nimport { memberMayActOnPlaced, placedRefusalPermission } from '@aglyn/tenant-data-admin/server/placement-access'\nimport {\n DATA_ERASE_PERMISSION,\n DATA_MANAGE_PERMISSION,\n DATA_SITE_DELETE_PERMISSION,\n DATA_SITE_MANAGE_PERMISSION,\n DATA_SITE_ROLE_PRESET,\n} from '../model/dataset-access'\n\n/** A dataset act and the two keys that decide it. */\nconst ACTS = {\n write: { workspaceKey: DATA_MANAGE_PERMISSION, siteKey: DATA_SITE_MANAGE_PERMISSION },\n delete: { workspaceKey: DATA_ERASE_PERMISSION, siteKey: DATA_SITE_DELETE_PERMISSION },\n} as const\n\n/** The key a refusal names: the site's on a one-site dataset, else the workspace's. */\nexport function datasetRefusalPermission(act: keyof typeof ACTS,
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/server/dataset-access.server.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 type { ScopePlaced } from '@aglyn/aglyn/app-utils/site-placement'\nimport type { AglynOrgMember } from '@aglyn/aglyn/foundation/definitions/organization.types'\nimport { memberHasOrgPermission } from '@aglyn/tenant-data-admin'\nimport { memberMayActOnPlaced, placedRefusalPermission } from '@aglyn/tenant-data-admin/server/placement-access'\nimport {\n DATA_ERASE_PERMISSION,\n DATA_MANAGE_PERMISSION,\n DATA_SITE_DELETE_PERMISSION,\n DATA_SITE_MANAGE_PERMISSION,\n DATA_SITE_ROLE_PRESET,\n} from '../model/dataset-access'\n\n/** A dataset act and the two keys that decide it. */\nconst ACTS = {\n write: { workspaceKey: DATA_MANAGE_PERMISSION, siteKey: DATA_SITE_MANAGE_PERMISSION },\n delete: { workspaceKey: DATA_ERASE_PERMISSION, siteKey: DATA_SITE_DELETE_PERMISSION },\n} as const\n\n/** The key a refusal names: the site's on a one-site dataset, else the workspace's. */\nexport function datasetRefusalPermission(act: keyof typeof ACTS, dataset: ScopePlaced | null | undefined): string {\n return placedRefusalPermission(dataset, ACTS[act].workspaceKey, ACTS[act].siteKey)\n}\n\n/** May this member write or delete this dataset, as its document places it? The routes' `canWriteDatasetOn`. */\nexport async function memberMayActOnDataset(input: {\n firestore: FirebaseFirestore.Firestore\n orgId: string\n uid: string\n member: Partial<AglynOrgMember>\n dataset: ScopePlaced | null | undefined\n act: keyof typeof ACTS\n}): Promise<boolean> {\n const { act, dataset, ...rest } = input\n const { workspaceKey, siteKey } = ACTS[act]\n return memberMayActOnPlaced({\n ...rest,\n placed: dataset,\n workspace: await memberHasOrgPermission(input.orgId, input.member, workspaceKey as never),\n workspaceKey,\n siteKey,\n sitePreset: DATA_SITE_ROLE_PRESET,\n })\n}\n"],"names":["memberHasOrgPermission","memberMayActOnPlaced","placedRefusalPermission","DATA_ERASE_PERMISSION","DATA_MANAGE_PERMISSION","DATA_SITE_DELETE_PERMISSION","DATA_SITE_MANAGE_PERMISSION","DATA_SITE_ROLE_PRESET","ACTS","write","workspaceKey","siteKey","delete","datasetRefusalPermission","act","dataset","memberMayActOnDataset","input","rest","placed","workspace","orgId","member","sitePreset"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;;AAID,SAASA,sBAAsB,QAAQ,2BAA0B;AACjE,SAASC,oBAAoB,EAAEC,uBAAuB,QAAQ,mDAAkD;AAChH,SACEC,qBAAqB,EACrBC,sBAAsB,EACtBC,2BAA2B,EAC3BC,2BAA2B,EAC3BC,qBAAqB,QAChB,6BAAyB;AAEhC,mDAAmD,GACnD,MAAMC,OAAO;IACXC,OAAO;QAAEC,cAAcN;QAAwBO,SAASL;IAA4B;IACpFM,QAAQ;QAAEF,cAAcP;QAAuBQ,SAASN;IAA4B;AACtF;AAEA,qFAAqF,GACrF,OAAO,SAASQ,yBAAyBC,GAAsB,EAAEC,OAAuC;IACtG,OAAOb,wBAAwBa,SAASP,IAAI,CAACM,IAAI,CAACJ,YAAY,EAAEF,IAAI,CAACM,IAAI,CAACH,OAAO;AACnF;AAEA,8GAA8G,GAC9G,OAAO,eAAeK,sBAAsBC,KAO3C;IACC,MAAM,EAAEH,GAAG,EAAEC,OAAO,EAAW,GAAGE,OAATC,wCAASD;;;;IAClC,MAAM,EAAEP,YAAY,EAAEC,OAAO,EAAE,GAAGH,IAAI,CAACM,IAAI;IAC3C,OAAOb,qBAAqB,aACvBiB;QACHC,QAAQJ;QACRK,WAAW,MAAMpB,uBAAuBiB,MAAMI,KAAK,EAAEJ,MAAMK,MAAM,EAAEZ;QACnEA;QACAC;QACAY,YAAYhB;;AAEhB"}
|
|
@@ -26,6 +26,7 @@ import { dataStorageRefusal } from "@aglyn/tenant-data-admin/server/data-storage
|
|
|
26
26
|
import { memberHasOrgPermission, resolveOrgIdForHost, resolveOrgMembership } from "@aglyn/tenant-data-admin/server/organizations";
|
|
27
27
|
import { isServerReleaseFlagOnForOrg } from "@aglyn/tenant-data-admin/server/release-flags";
|
|
28
28
|
import { BUNDLE_ID } from "../constants/bundle-common.js";
|
|
29
|
+
import { datasetNameLower } from "../model/datasets.js";
|
|
29
30
|
import { coerceDocumentValues, datasetIntegrityFields, datasetIntegrityUpdate, defaultDatasetFieldId, validateDocument } from "../model/dataset-models.js";
|
|
30
31
|
import { DATASET_IMAGE_FIELD_TYPE, isDatasetImageValue } from "../model/dataset-image-field.js";
|
|
31
32
|
import { DATASET_PAGE_FIELD_TYPE, isDatasetPageValue } from "../model/dataset-page-field.js";
|
|
@@ -449,6 +450,7 @@ export function createDatasetDraftWriter(deps = {}) {
|
|
|
449
450
|
};
|
|
450
451
|
tx.create(datasetRef, _extends({
|
|
451
452
|
displayName: name,
|
|
453
|
+
nameLower: datasetNameLower(name),
|
|
452
454
|
fields: [
|
|
453
455
|
...model.order
|
|
454
456
|
],
|