@aglyn/plugins-data 1.16.0 → 1.18.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/plugins-data",
3
- "version": "1.16.0",
3
+ "version": "1.18.0",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,16 +25,16 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.16.0",
29
- "@aglyn/shared-data-mdi": "1.16.0",
30
- "@aglyn/shared-ui-jsx": "1.16.0",
31
- "@aglyn/shared-ui-next": "1.16.0",
32
- "@aglyn/shared-ui-snackstack": "1.16.0",
33
- "@aglyn/shared-util-http": "1.16.0",
34
- "@aglyn/shared-util-timestamp": "1.16.0",
35
- "@aglyn/tenant-data-admin": "1.16.0",
36
- "@aglyn/tenant-feature-instance": "1.16.0",
37
- "@aglyn/tenant-runtime": "1.16.0",
28
+ "@aglyn/aglyn": "1.18.0",
29
+ "@aglyn/shared-data-mdi": "1.18.0",
30
+ "@aglyn/shared-ui-jsx": "1.18.0",
31
+ "@aglyn/shared-ui-next": "1.18.0",
32
+ "@aglyn/shared-ui-snackstack": "1.18.0",
33
+ "@aglyn/shared-util-http": "1.18.0",
34
+ "@aglyn/shared-util-timestamp": "1.18.0",
35
+ "@aglyn/tenant-data-admin": "1.18.0",
36
+ "@aglyn/tenant-feature-instance": "1.18.0",
37
+ "@aglyn/tenant-runtime": "1.18.0",
38
38
  "@swc/helpers": "0.5.23"
39
39
  },
40
40
  "peerDependencies": {
@@ -32,7 +32,7 @@ import { useListGridFilter } from "@aglyn/shared-ui-jsx/hooks/use-list-grid-filt
32
32
  import { useSnackbar } from "@aglyn/shared-ui-snackstack";
33
33
  import { Timestamp } from "@aglyn/shared-util-timestamp";
34
34
  import { Alert, Box, Button, Chip, Dialog, DialogActions, DialogContent, DialogTitle, MenuItem, Stack, TextField, Tooltip, Typography } from "@mui/material";
35
- import { collection, deleteDoc, deleteField, doc, documentId, endAt, getCountFromServer, getDoc, getDocs, limit, orderBy, query, startAt, where, setDoc, writeBatch } from "firebase/firestore";
35
+ import { collection, deleteDoc, deleteField, doc, endAt, getCountFromServer, getDoc, getDocs, limit, orderBy, query, startAt, where, setDoc, writeBatch } from "firebase/firestore";
36
36
  import { useRouter } from "next/navigation";
37
37
  import { useCallback, useEffect, useMemo, useState } from "react";
38
38
  import { useListColumnSort } from "@aglyn/shared-ui-jsx/hooks/use-list-column-sort";
@@ -51,7 +51,7 @@ import { datasetListScope } from "../model/dataset-record-list.js";
51
51
  import { DATASETS_EXPORT_REFUSAL, DATASETS_VIEW_RECORDS_REFUSAL, DATASETS_WRITE_REFUSAL, useDatasetWritesBlocked } from "./use-dataset-writes-blocked.js";
52
52
  import { DATASET_SAMPLE_RECORD_NOTE, datasetDisplayName, isSampleDatasetRecord, parseDatasetFieldEntries } from "../model/datasets.js";
53
53
  import { datasetTransferResourceKey } from "../transfer/dataset-transfer-key.js";
54
- import { DATASET_RAIL_GROUP_AT, datasetCreatedLabel, datasetNameMatches, datasetPickerLabelsOf, datasetRailName, datasetRecordTitle, datasetRailSecondary, datasetSharingLabel, datasetSourceLabel, groupDatasetsBySharing, sortDatasetsByName } from "../model/dataset-rail.js";
54
+ import { DATASET_RAIL_GROUP_AT, datasetCreatedLabel, datasetPickerLabelsOf, datasetRailName, datasetRecordTitle, datasetRailSecondary, datasetSharingLabel, datasetSourceLabel, groupDatasetsBySharing, sortDatasetsByName } from "../model/dataset-rail.js";
55
55
  import { useOrgSites } from "./use-org-sites.js";
56
56
  /**
57
57
  * The sentence that says who a NEW dataset is shared with, for the card and
@@ -77,15 +77,6 @@ import { useOrgSites } from "./use-org-sites.js";
77
77
  * check walks. "Show more datasets" loads the next window, so the rail
78
78
  * reaches every dataset however many there are (AGL-4047).
79
79
  */ const DATASET_LIST_WINDOW = 100;
80
- /**
81
- * TODO(AGL-4047): switch to true once the `datasets (visibleTo, nameLower)`
82
- * index is READY and `tools/scripts/backfill-dataset-name-lower.mjs --apply`
83
- * has run in production. Then the rail is ordered by `nameLower` on the query
84
- * and the search asks a `nameLower` prefix of the server, rather than the
85
- * rail walking datasets in document order and matching names among the ones
86
- * it has loaded. Until both are confirmed, ordering on a field a dataset may
87
- * lack would leave that dataset off the rail.
88
- */ const DATASET_NAMES_ON_SERVER = false;
89
80
  /** A dataset read off its document, as the card's rows carry it. */ const datasetRow = (snapshot)=>_extends({
90
81
  $id: snapshot.id
91
82
  }, snapshot.data());
@@ -245,7 +236,7 @@ export function newDatasetSharingNote(siteOnly) {
245
236
  pageHostId,
246
237
  listScope
247
238
  ]);
248
- const serverNameKey = DATASET_NAMES_ON_SERVER ? nameSearchKey(nameSearch) : '';
239
+ /** The search as the stored `nameLower` is normalized, asked of the server as a prefix. */ const serverNameKey = nameSearchKey(nameSearch);
249
240
  const { hostNames, sites: orgSites } = useOrgSites(orgId);
250
241
  const { data: datasetDocs, status: datasetsStatus, /**
251
242
  * The dataset rows are unconfirmed by the server (AGL-1358). The schema
@@ -260,19 +251,19 @@ export function newDatasetSharingNote(siteOnly) {
260
251
  ...railScope
261
252
  ])
262
253
  ] : [], /*
263
- * A walk that reaches every dataset (AGL-4047). The document's
264
- * name is on every dataset, so ordering on it leaves none out,
265
- * and the automatic index serves it beside the scope clause. One
266
- * row past the window says whether there are more.
267
- */ ...DATASET_NAMES_ON_SERVER ? [
268
- orderBy('nameLower'),
269
- ...serverNameKey ? [
270
- startAt(serverNameKey),
271
- endAt(`${serverNameKey}\uf8ff`)
272
- ] : []
273
- ] : [
274
- orderBy(documentId())
275
- ], limit(railWindow + 1)) : null, [
254
+ * The rail in name order, and the search as a `nameLower` prefix
255
+ * asked of the server, so it finds a dataset past the loaded
256
+ * window (AGL-4047). Served by the `datasets (visibleTo CONTAINS,
257
+ * nameLower ASC)` index beside the scope clause. Ordering on a
258
+ * field leaves out a document that lacks it, so every writer
259
+ * stamps `nameLower` through `datasetNameLower`, and
260
+ * `tools/scripts/backfill-dataset-name-lower.mjs` stamped the
261
+ * datasets saved before. One row past the window says whether
262
+ * there are more.
263
+ */ orderBy('nameLower'), ...serverNameKey ? [
264
+ startAt(serverNameKey),
265
+ endAt(`${serverNameKey}\uf8ff`)
266
+ ] : [], limit(railWindow + 1)) : null, [
276
267
  firestore,
277
268
  dataScope,
278
269
  railScope,
@@ -289,16 +280,12 @@ export function newDatasetSharingNote(siteOnly) {
289
280
  railWindow
290
281
  ]);
291
282
  const moreDatasets = ((_ref = datasetDocs == null ? void 0 : datasetDocs.length) != null ? _ref : 0) > railWindow;
292
- /** The rail: the loaded window, narrowed by the search among the names it holds. */ const railDatasets = useMemo(()=>DATASET_NAMES_ON_SERVER ? datasets : datasets.filter((item)=>datasetNameMatches(item, nameSearch)), [
293
- datasets,
294
- nameSearch
295
- ]);
296
283
  /**
297
284
  * Whether the loaded window is short of everything this page lists: a
298
- * filter narrowed it, or there are more. A check that must see every
299
- * dataset — what references a record about to be deleted — reads for
300
- * itself then.
301
- */ const railNarrowed = Boolean(pageHostId) || Boolean(sharedWith) || moreDatasets;
285
+ * filter or the name search narrowed it, or there are more. A check that
286
+ * must see every dataset — what references a record about to be deleted —
287
+ * reads for itself then.
288
+ */ const railNarrowed = Boolean(pageHostId) || Boolean(sharedWith) || Boolean(serverNameKey) || moreDatasets;
302
289
  /**
303
290
  * The open dataset (AGL-4047): the one the address names, or, on the bare
304
291
  * page, none until the page moves to the first. The card is also mounted
@@ -1405,7 +1392,7 @@ export function newDatasetSharingNote(siteOnly) {
1405
1392
  * with a second line that tells two of one name apart. Past
1406
1393
  * {@link DATASET_RAIL_GROUP_AT} the tabs are grouped by who they are shared
1407
1394
  * with, and the organization page offers the Shared with filter.
1408
- */ const grouped = railDatasets.length > DATASET_RAIL_GROUP_AT;
1395
+ */ const grouped = datasets.length > DATASET_RAIL_GROUP_AT;
1409
1396
  const railSections = useMemo(()=>{
1410
1397
  if (!basePath) return [];
1411
1398
  const tab = (item, group)=>_extends({
@@ -1418,11 +1405,11 @@ export function newDatasetSharingNote(siteOnly) {
1418
1405
  }, group ? {
1419
1406
  group
1420
1407
  } : {});
1421
- if (!grouped) return railDatasets.map((item)=>tab(item));
1422
- return groupDatasetsBySharing(railDatasets, hostNames).flatMap((group)=>group.datasets.map((item)=>tab(item, group.label)));
1408
+ if (!grouped) return datasets.map((item)=>tab(item));
1409
+ return groupDatasetsBySharing(datasets, hostNames).flatMap((group)=>group.datasets.map((item)=>tab(item, group.label)));
1423
1410
  }, [
1424
1411
  basePath,
1425
- railDatasets,
1412
+ datasets,
1426
1413
  hostNames,
1427
1414
  grouped
1428
1415
  ]);
@@ -1483,14 +1470,14 @@ export function newDatasetSharingNote(siteOnly) {
1483
1470
  }) : null;
1484
1471
  const railFooter = /*#__PURE__*/ _jsxs(_Fragment, {
1485
1472
  children: [
1486
- listAnswered && datasets.length > 0 && railDatasets.length === 0 ? /*#__PURE__*/ _jsx(Typography, {
1473
+ listAnswered && serverNameKey && datasets.length === 0 ? /*#__PURE__*/ _jsx(Typography, {
1487
1474
  variant: "body2",
1488
1475
  color: "text.secondary",
1489
1476
  sx: {
1490
1477
  px: 2,
1491
1478
  py: 1
1492
1479
  },
1493
- children: moreDatasets ? 'None of the loaded datasets match.' : 'No datasets match.'
1480
+ children: 'No datasets match.'
1494
1481
  }) : null,
1495
1482
  moreDatasets ? /*#__PURE__*/ _jsx(Button, {
1496
1483
  size: "small",
@@ -1653,7 +1640,7 @@ export function newDatasetSharingNote(siteOnly) {
1653
1640
  }) : notFound ? /*#__PURE__*/ _jsx(Alert, {
1654
1641
  severity: "info",
1655
1642
  children: 'This dataset doesn’t exist, or you can’t open it.'
1656
- }) : recordPanel ? recordPanel : !selected ? listAnswered && datasets.length === 0 && !sharedWith ? /*#__PURE__*/ _jsx(CardDisplay, {
1643
+ }) : recordPanel ? recordPanel : !selected ? listAnswered && datasets.length === 0 && !sharedWith && !serverNameKey ? /*#__PURE__*/ _jsx(CardDisplay, {
1657
1644
  contentGutterX: true,
1658
1645
  contentGutterY: true,
1659
1646
  children: /*#__PURE__*/ _jsx(Typography, {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/components/host-datasets-card.component.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport type { ScopePlaced } from '@aglyn/aglyn/app-utils/site-placement'\nimport { TransferResumeImport } from '@aglyn/aglyn/app-utils/transfer-resume-import'\nimport {\n type AglynOrgBilling,\n checkDatasetQuota,\n checkEntitlement,\n checkQuota,\n getCustomFieldType,\n PageHeaderActions,\n PageHeaderRecord,\n pluginDocsHelp,\n scopeTokensForHost,\n useTransferLauncher,\n visibleToHost,\n} from '@aglyn/aglyn'\nimport { nameSearchKey } from '@aglyn/aglyn/app-utils/name-search'\nimport { HubSections, type HubSection } from '@aglyn/shared-ui-next/components/hub-tabs'\nimport { AppLink, CardDisplay, MdiIcon, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { mdiArrowLeft } from '@aglyn/shared-data-mdi'\nimport ListFilterChips from '@aglyn/shared-ui-jsx/components/list-filter-chips.component'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport ListQueryNotices, {\n listQueryRefusals,\n} from '@aglyn/shared-ui-jsx/components/list-query-notices.component'\nimport {\n ListTable,\n listActionsColumn,\n} from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport QuotaReadoutComponent from '@aglyn/shared-ui-jsx/components/quota-readout.component'\nimport { listFilterGridColumns } from '@aglyn/shared-ui-jsx/const/list-grid-filter'\nimport { useListGridFilter } from '@aglyn/shared-ui-jsx/hooks/use-list-grid-filter'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { Timestamp } from '@aglyn/shared-util-timestamp'\nimport {\n Alert,\n Box,\n Button,\n Chip,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n MenuItem,\n Stack,\n TextField,\n Tooltip,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n deleteDoc,\n deleteField,\n doc,\n documentId,\n endAt,\n getCountFromServer,\n getDoc,\n getDocs,\n limit,\n orderBy,\n query,\n startAt,\n where,\n setDoc,\n writeBatch,\n} from 'firebase/firestore'\nimport { useRouter } from 'next/navigation'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { useListColumnSort } from '@aglyn/shared-ui-jsx/hooks/use-list-column-sort'\nimport {\n useFirestore,\n useFirestoreCollection,\n useFirestoreDoc,\n useHostActivityLogger,\n useOrgDataScope,\n usePagedCollection,\n useScopeTokens,\n useUser,\n} from '@aglyn/tenant-feature-instance'\nimport { listQueryConstraints } from '@aglyn/tenant-feature-instance/hooks/use-list-query'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport { DatasetSchemaDialog } from './dataset-schema-dialog.component'\nimport { DatasetRecordDialog, DatasetRecordFieldList } from './dataset-record-dialog.component'\nimport { DatasetRecordSiteContext } from './dataset-field-inputs.component'\nimport {\n datasetRecordFilter,\n planRecordQuery,\n recordColumn,\n} from './dataset-record-filter'\nimport { coerceDocumentValues, datasetIntegrityUpdate, datasetValueToInput, effectiveDatasetModel, formatDatasetValue, modelFromFieldEntries, validateDocument } from '../model/dataset-models'\nimport { fillRecordAddresses } from '../record-pages/record-pages'\nimport { planReferenceFixups, referencingFieldIds, restrictedDeleteMessage } from '../model/dataset-record-delete-plan'\nimport { BlockedControl } from '@aglyn/shared-ui-jsx/components/blocked-control.component'\nimport { datasetListScope } from '../model/dataset-record-list'\nimport {\n DATASETS_EXPORT_REFUSAL,\n DATASETS_VIEW_RECORDS_REFUSAL,\n DATASETS_WRITE_REFUSAL,\n useDatasetWritesBlocked,\n} from './use-dataset-writes-blocked'\nimport { DATASET_SAMPLE_RECORD_NOTE, datasetDisplayName, isSampleDatasetRecord, parseDatasetFieldEntries } from '../model/datasets'\nimport { datasetTransferResourceKey } from '../transfer/dataset-transfer-key'\nimport {\n DATASET_RAIL_GROUP_AT,\n type DatasetRailEntry,\n datasetCreatedLabel,\n datasetNameMatches,\n datasetPickerLabelsOf,\n datasetRailName,\n datasetRecordTitle,\n datasetRailSecondary,\n datasetSharingLabel,\n datasetSourceLabel,\n groupDatasetsBySharing,\n sortDatasetsByName,\n} from '../model/dataset-rail'\nimport { useOrgSites } from './use-org-sites'\n\nexport interface HostDatasetsCardProps {\n /** Host context: resolves the owning org and logs host activity. */\n hostId?: string\n /**\n * Direct org scope (AGL-239): the org Data page renders the editor\n * without any host context. Wins over `hostId` resolution when set.\n */\n orgId?: string\n /**\n * The resolved entitlement source (org billing doc). Passed in by both\n * callers (the plugin Data page via the shell, the org Data page via its\n * own resolver) so this relocated card runs entitlement/quota checks\n * without console-app org/session hooks (AGL-395).\n */\n org?: Partial<AglynOrgBilling>\n /**\n * The Data page's own address (AGL-4047): each dataset is a tab of the\n * page's rail, at `<basePath>/<datasetId>`. Handed down by both callers —\n * the site's plugin route and the organization Data page.\n */\n basePath?: string\n /**\n * The path beneath {@link basePath}: `[datasetId]` on a dataset's tab,\n * `[datasetId, 'records', recordId]` on one of its records, and empty on the\n * bare page, which opens the first dataset.\n */\n segments?: readonly string[]\n}\n\n/**\n * The sentence that says who a NEW dataset is shared with, for the card and\n * for the site Data page's banner above it.\n *\n * `siteOnly` is true only on a site's Data page in an org whose Default\n * sharing is \"Only the site they were created in\". Everywhere else a new\n * dataset starts on All sites: the org Data page has no site to limit it to.\n */\n/** The records walk serves no header order: every header sorts the page. */\nconst NO_QUERY_SORTS: never[] = []\n\n/** The grid's own Export and Print, off for a member without \"Export data\" (AGL-4047). */\nconst EXPORT_OFF_TOOLBAR = {\n toolbar: { csvOptions: { disableToolbarButton: true }, printOptions: { disableToolbarButton: true } },\n}\n\n/** Stable, so an empty answer does not re-render the card. */\nconst NO_DATASETS: any[] = []\n\n/**\n * The datasets the rail loads at a time, and the most a delete's reference\n * check walks. \"Show more datasets\" loads the next window, so the rail\n * reaches every dataset however many there are (AGL-4047).\n */\nconst DATASET_LIST_WINDOW = 100\n\n/**\n * TODO(AGL-4047): switch to true once the `datasets (visibleTo, nameLower)`\n * index is READY and `tools/scripts/backfill-dataset-name-lower.mjs --apply`\n * has run in production. Then the rail is ordered by `nameLower` on the query\n * and the search asks a `nameLower` prefix of the server, rather than the\n * rail walking datasets in document order and matching names among the ones\n * it has loaded. Until both are confirmed, ordering on a field a dataset may\n * lack would leave that dataset off the rail.\n */\nconst DATASET_NAMES_ON_SERVER = false\n\n/** A dataset read off its document, as the card's rows carry it. */\nconst datasetRow = (snapshot: { id: string; data(): unknown }) => ({\n $id: snapshot.id,\n ...(snapshot.data() as object),\n})\n\nexport function newDatasetSharingNote(siteOnly: boolean): string {\n return siteOnly\n ? 'Datasets belong to your organization. Your default sharing starts a ' +\n 'new one on this site only — use Schema to share it with more.'\n : 'Datasets belong to your organization. A new one is shared with ' +\n 'every site — use Schema to narrow that.'\n}\n\n/**\n * Datasets editor (AGL-102): org-shared document collections at\n * `orgs/{orgId}/datasets` (AGL-237/239) with a `records` subcollection,\n * consumed by repeatable components (AGL-103) via `{{item.field}}`.\n * Starter+ (`data-store` flag) with per-plan dataset and record caps —\n * dark-launch rule as everywhere (no plan, no gate). The host path is\n * the pre-migration fallback for hosts not yet org-wired.\n */\nexport function HostDatasetsCard(props: HostDatasetsCardProps) {\n const { hostId, basePath, segments } = props\n const router = useRouter()\n // `dataScope` is null until the async org lookup settles (AGL-1061), and\n // for a host with no owning org — there is no host fallback to act on\n // any more (AGL-1050), so every path built from it is guarded rather\n // than redirected.\n const { scope: dataScope, orgId } = useOrgDataScope({\n hostId,\n orgId: props.orgId,\n })\n // Scoped sharing (AGL-1044). Required, not cosmetic: under the AGL-1041\n // rules a scoped member's UNFILTERED list is rejected outright —\n // Firestore fails the whole query if any candidate would fail — so\n // without this the Data page errors rather than showing fewer rows.\n const {\n tokens: scopeTokens,\n orgWide: viewerOrgWide,\n loaded: scopeLoaded,\n } = useScopeTokens(orgId)\n /**\n * The site whose Data page this is, or undefined on the organization Data\n * page. The explicit `orgId` is that page's own scope and already wins over\n * `hostId` when the org is resolved, so it wins here too, even if a caller\n * hands the card both.\n */\n const pageHostId = props.orgId ? undefined : hostId || undefined\n // What the VIEWER reaches: their scope tokens, or no filter for an org-wide\n // member, who reads everything. Every dataset here is an org dataset, and\n // org datasets are all scoped (AGL-1041).\n const reachScope = viewerOrgWide ? null : scopeTokens\n /**\n * What this page lists (AGL-4047): a site's Data page shows that site's and\n * the workspace-wide datasets, whoever is looking, as every other site\n * surface does. It used to ask only the viewer's reach, so an owner, who\n * reaches everything, saw every site's datasets on every site. The\n * organization Data page lists the viewer's reach.\n */\n const listScope = useMemo(\n () => datasetListScope({ hostId: pageHostId, memberScope: reachScope }),\n [pageHostId, reachScope],\n )\n // Two answers must be in before listing: the org path (AGL-1061) and the\n // viewer's scope tokens (AGL-1047). `useScopeTokens` reports org-wide\n // while loading, so without `scopeLoaded` a scoped collaborator's first\n // render sends an UNFILTERED list that the AGL-1041 rules deny per\n // document. It recovers on the next render, which is exactly what makes\n // it easy to miss: the page looks right and logs a denial every mount.\n const scopeReady = Boolean(dataScope) && scopeLoaded\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n const { org } = props\n const logActivity = useHostActivityLogger(hostId)\n const { data: user } = useUser()\n /**\n * The site a dataset created here is created FROM, or undefined on the\n * organization Data page.\n *\n * `/api/orgs/datasets` stamps a new dataset with the org's Default sharing,\n * and that setting can only narrow to a site the request names — so a\n * create that names none lands on All sites whatever the org chose.\n */\n const createdFromHostId = pageHostId\n const createdFrom = useMemo(\n () => (createdFromHostId ? { hostId: createdFromHostId } : {}),\n [createdFromHostId],\n )\n /**\n * The site the record editor's Page field lists pages from (AGL-3763): the\n * site whose Data page this is, and none on the organization Data page,\n * where a dataset is no one site's.\n */\n const recordSite = useMemo(\n () => ({ hostId: createdFromHostId }),\n [createdFromHostId],\n )\n /**\n * Whether a dataset created here starts on this site alone: the org chose\n * \"Only the site they were created in\" and there is a site to limit it to.\n * The caption reads it so it never promises All sites to a create that\n * will not get it.\n */\n const createsSiteOnly =\n Boolean(createdFromHostId) &&\n (org as { defaultResourceScope?: 'org' | 'host' } | undefined)\n ?.defaultResourceScope === 'host'\n\n // Creates go through the console API (AGL-473): rules deny client-side\n // `create` on org datasets/records so quotas are server-enforced.\n // Updates/deletes stay client-direct (they don't consume quota). The\n // legacy host scope (no org resolved) keeps the old client writes.\n const callDatasetApi = useCallback(\n async (payload: Record<string, unknown>) => {\n const response = await authorizedFetch(user, '/api/orgs/datasets', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ orgId, ...payload }),\n })\n const result = await response.json().catch(() => ({}))\n if (!response.ok) {\n throw new Error(result?.error ?? 'Dataset operation failed')\n }\n return result\n },\n [user, orgId],\n )\n\n /**\n * Refresh the live pages showing a dataset after a write the BROWSER made\n * (AGL-3113).\n *\n * Record edits and deletes are client-direct — they consume no quota, so\n * AGL-473 left them out of the server leg — which also left them with\n * nothing to announce from. They make a page listing the rows exactly as\n * stale as a create does, so they take the same trip the create already\n * takes, through the route that already holds the org membership check.\n *\n * BEST EFFORT. The record is stored by the time this runs, and the pages\n * catch up on their own window regardless; a refused cache must never be\n * shown to somebody as a refused save.\n */\n const announceRecords = useCallback(\n async (datasetId: string) => {\n try {\n await callDatasetApi({ action: 'announce-records', datasetId })\n } catch (error) {\n console.error(error)\n }\n },\n [callDatasetApi],\n )\n\n /**\n * The rail's search and its Shared with filter (AGL-4047).\n *\n * The filter is a query clause: one site the reader reaches, asked by that\n * site's scope tokens in place of the page's own, which they sit inside —\n * a site the reader is a member of is one their own tokens already reach,\n * so the narrower query is still one the rules can prove. Offered on the\n * organization Data page only: a site's page already lists that site's.\n */\n const [nameSearch, setNameSearch] = useState('')\n const [sharedWith, setSharedWith] = useState('')\n const [railWindow, setRailWindow] = useState(DATASET_LIST_WINDOW)\n const railScope = useMemo(\n () => (sharedWith && !pageHostId ? scopeTokensForHost(sharedWith) : listScope),\n [sharedWith, pageHostId, listScope],\n )\n const serverNameKey = DATASET_NAMES_ON_SERVER ? nameSearchKey(nameSearch) : ''\n const { hostNames, sites: orgSites } = useOrgSites(orgId)\n\n const {\n data: datasetDocs,\n status: datasetsStatus,\n /**\n * The dataset rows are unconfirmed by the server (AGL-1358). The schema\n * dialog is seeded from one of them and writes the whole `model` plus\n * `visibleTo` back, so the freshness verdict belongs to THIS listener —\n * the dialog has none of its own, which is why it is handed down rather\n * than recomputed there.\n */\n fromCache: datasetsFromCache,\n listen: datasetsListen,\n } = useFirestoreCollection<any>(\n () =>\n // `scopeReady` already implies a non-null `dataScope`; testing it\n // directly is what lets the compiler see that too.\n dataScope && scopeReady\n ? query(\n collection(firestore, dataScope[0], dataScope[1], 'datasets'),\n ...(railScope\n ? [where('visibleTo', 'array-contains-any', [...railScope])]\n : []),\n /*\n * A walk that reaches every dataset (AGL-4047). The document's\n * name is on every dataset, so ordering on it leaves none out,\n * and the automatic index serves it beside the scope clause. One\n * row past the window says whether there are more.\n */\n ...(DATASET_NAMES_ON_SERVER\n ? [\n orderBy('nameLower'),\n ...(serverNameKey ? [startAt(serverNameKey), endAt(`${serverNameKey}\\uf8ff`)] : []),\n ]\n : [orderBy(documentId())]),\n limit(railWindow + 1),\n )\n : null,\n [firestore, dataScope, railScope, scopeReady, railWindow, serverNameKey],\n { idField: '$id' },\n )\n /** The loaded window in name order: what the join dialog and the reference checks read. */\n const datasets = useMemo(\n () => sortDatasetsByName<any>([...(datasetDocs ?? [])].slice(0, railWindow)),\n [datasetDocs, railWindow],\n )\n const moreDatasets = (datasetDocs?.length ?? 0) > railWindow\n /** The rail: the loaded window, narrowed by the search among the names it holds. */\n const railDatasets = useMemo(\n () =>\n DATASET_NAMES_ON_SERVER\n ? datasets\n : datasets.filter((item: DatasetRailEntry) => datasetNameMatches(item, nameSearch)),\n [datasets, nameSearch],\n )\n /**\n * Whether the loaded window is short of everything this page lists: a\n * filter narrowed it, or there are more. A check that must see every\n * dataset — what references a record about to be deleted — reads for\n * itself then.\n */\n const railNarrowed = Boolean(pageHostId) || Boolean(sharedWith) || moreDatasets\n\n /**\n * The open dataset (AGL-4047): the one the address names, or, on the bare\n * page, none until the page moves to the first. The card is also mounted\n * without an address by callers outside the console's routes, which pick\n * one by state.\n */\n const routeDatasetId = basePath ? segments?.[0] : undefined\n /** The record the address opens on its own page (AGL-4047), beneath its dataset's tab. */\n const routeRecordId = basePath && segments?.[1] === 'records' ? segments?.[2] : undefined\n const [selectedId, setSelectedId] = useState<string | null>(null)\n const wantedId = routeDatasetId ?? selectedId ?? undefined\n const listed = wantedId ? datasets.find((item) => item.$id === wantedId) : undefined\n const listAnswered = datasetDocs !== undefined\n /*\n * A dataset the address names that the loaded window does not hold — past\n * the window, outside the filter, or only just created — is read on its\n * own, live, so its tab still opens and a save still seeds from a listener.\n */\n const linkedRead = useFirestoreDoc<any>(\n () =>\n dataScope && scopeReady && wantedId && listAnswered && !listed\n ? doc(firestore, dataScope[0], dataScope[1], 'datasets', wantedId)\n : null,\n [firestore, dataScope, scopeReady, wantedId, listAnswered, Boolean(listed)],\n )\n // Keyed by the id it was read under, as the list's rows are.\n const linked = useMemo(\n () => (!listed && wantedId && linkedRead.data ? { ...linkedRead.data, $id: wantedId } : undefined),\n [listed, wantedId, linkedRead.data],\n )\n /** A site's page refuses a dataset that is not shared with the site (#2341). */\n const notSharedHere = Boolean(\n pageHostId && linked && !visibleToHost((linked as { visibleTo?: string[] }).visibleTo, pageHostId),\n )\n const notFound = Boolean(\n wantedId &&\n listAnswered &&\n !listed &&\n !linked &&\n (linkedRead.status === 'error' || (linkedRead.status !== 'loading' && !linkedRead.fromCache)),\n )\n const selected =\n listed ??\n (linked && !notSharedHere ? linked : undefined) ??\n (wantedId ? undefined : datasets[0])\n /** Which listener the open dataset came from, for the schema dialog's freshness guard. */\n const seed = listed || !linked\n ? { fromCache: datasetsFromCache, unreadable: datasetsStatus === 'error', listen: datasetsListen }\n : { fromCache: linkedRead.fromCache, unreadable: linkedRead.status === 'error', listen: linkedRead.listen }\n /** Opens a dataset: its own address on a routed page, the card's state elsewhere. */\n const openDataset = useCallback(\n (id: string | null) => {\n if (basePath) router.push(id ? `${basePath}/${id}` : basePath)\n else setSelectedId(id)\n },\n [basePath, router],\n )\n // The bare page opens the first dataset, as a hub opens its first section,\n // so the rail always has a tab lit and the address names what is open.\n const landing = basePath && !routeDatasetId && datasets[0] ? `${basePath}/${datasets[0].$id}` : null\n useEffect(() => {\n if (landing) router.replace(landing)\n }, [landing, router])\n const [schemaOpen, setSchemaOpen] = useState(false)\n // What this member may do with THIS dataset (AGL-4047): one placed on one site\n // answers to that site.\n const blocked = useDatasetWritesBlocked(orgId, selected as ScopePlaced | undefined)\n // Typed model (AGL-179): drives headers, cell rendering, and the\n // document form; v1 datasets get a derived all-text model.\n const model = useMemo(\n () => effectiveDatasetModel(selected ?? {}),\n [selected],\n )\n const fields: string[] = useMemo(() => model.order, [model])\n // The records grid's Filters panel, from the dataset's own schema.\n const recordFilter = useMemo(() => datasetRecordFilter(model), [model])\n\n // Guarded on BOTH the scope and a real selection (AGL-1440): with no\n // datasets, `selected` never resolves, and `datasets/-none-/records` is not\n // an empty read for everyone — the AGL-1044 scoped-sharing rules deny it\n // outright for a scoped collaborator, and a permanently denied listen is\n // reopened forever by the refusal loop.\n /**\n * The records table PAGES (AGL-2501). It used to be `limit(500)` with no\n * `orderBy`, every row rendered at once and no control anywhere.\n *\n * That was wrong twice. Five hundred documents were read and billed on\n * every mount of a card nobody had scrolled — and past five hundred the\n * remaining rows were not merely unrendered, they were UNREACHABLE, because\n * nothing showed them and nothing asked for more. Firestore answers an\n * unordered limit in document-id order over auto-ids, so which five hundred\n * a reader got was arbitrary and could differ between two loads of the same\n * dataset; `sortDatasetRecords` then sorted that sample by `order`, which\n * made the table look ordered while being a sample. The export leg\n * (AGL-2335) fixed exactly this shape for the file and left the table.\n *\n * ## Why the walk orders on the document id, and not on a field\n *\n * The usual fix is `orderBy` on the field the rows are sorted by. It cannot\n * be used here: `orderBy` matches only documents that HAVE the field, so\n * ordering on one that any writer omits does not mis-order the list, it\n * hides rows from it — a worse failure than the one being fixed, and a\n * silent one. Every candidate on this collection is omitted by some writer:\n *\n * * `order` — set by `/api/orgs/datasets` and by `POST /v1/datasets/{id}\n * /records`, and NOT by the tenant form-submit leg or by the workflow\n * `appendDataset`/`updateDataset` actions, which write `values` and\n * `createdAt` only. Ordering on it would drop every row a public form or\n * an automation ever produced — the rows a lead dataset is mostly made\n * of.\n * * `createdAt` — written by all four of those, and NOT by a site import:\n * `IMPORTABLE_FIELDS.records` is `['values', 'order']`, so a restored\n * record carries no `createdAt` at all.\n * * `updatedAt` — the mirror image: the import stamps it, the form and\n * automation legs do not.\n *\n * A document's NAME is not a field and cannot be absent, so ordering on it\n * drops nothing and the walk is total: every record is reachable by paging,\n * which is the property the old query lacked. It is not insertion order —\n * ids are random — so the rows are not claimed to be in one. What they are\n * is stable, complete, and the same on every load.\n *\n * `sortDatasetRecords` is deliberately NOT applied to the page. Re-sorting a\n * window of an id-ordered walk by `order` is the same lie the old code told:\n * rows would run in one order within a page and another across pages.\n * For the same reason a header sorts THIS PAGE only, and says so\n * (AGL-3680, `recordColumnSort` below): no stored field could serve it.\n *\n * ## Filtering: every clause and the search word are on the query\n *\n * The grid's Filters panel and quick search are predicates on this same\n * walk (AGL-3321), planned by `planRecordQuery` (`./dataset-record-filter`,\n * over the shared `planListQuery`): equalities ask the record's\n * `filterValues`, and one word-level clause — a text `contains`, a list\n * member, or the search word — asks its `filterKeys`. Firestore's\n * automatic single-field indexes merge them under the same document-name\n * order, so every filter pages through every matching record exactly as\n * the plain walk pages through all of them, with no composite index and\n * no index deploy.\n *\n * Nothing is matched over the rows already loaded. What one query cannot\n * hold is not offered (ranges, negations, empty checks) or is refused by\n * name above the table (a second `contains`, a `contains` beside the\n * search), and a many-word `contains` or search says it asked the first\n * word.\n */\n const gridFilter = useListGridFilter({ selectFields: recordFilter.selectFields })\n // A clause on a field this dataset does not have (the reader switched\n // datasets) narrows nothing and is not shown.\n const recordClauses = useMemo(\n () =>\n gridFilter.clauses.filter((clause) =>\n recordFilter.fields.some((field) => field.column === clause.field),\n ),\n [gridFilter.clauses, recordFilter.fields],\n )\n const recordPlan = useMemo(\n () => planRecordQuery(model, recordFilter, recordClauses, gridFilter.searchWords),\n [model, recordFilter, recordClauses, gridFilter.searchWords],\n )\n // The query's identity: a new plan is a new walk, from page one.\n const recordPlanKey = JSON.stringify({\n filters: recordPlan.plan.filters,\n orderBy: recordPlan.plan.orderBy,\n })\n const {\n rows: records,\n hasMore: hasMoreRecords,\n page: recordPage,\n setPage: setRecordPage,\n pageSize: recordPageSize,\n setPageSize: setRecordPageSize,\n } = usePagedCollection<any>(\n (pageLimit) =>\n // A record's own page shows no table, so it reads none (AGL-4047).\n dataScope && selected?.$id && !blocked.records && !routeRecordId\n ? query(\n collection(\n firestore,\n dataScope[0],\n dataScope[1],\n 'datasets',\n selected.$id,\n 'records',\n ),\n ...listQueryConstraints(recordPlan.plan),\n limit(pageLimit),\n )\n : null,\n [firestore, dataScope, selected?.$id, recordPlanKey, blocked.records, routeRecordId],\n { idField: '$id' },\n )\n /**\n * The record a record's own page opens (AGL-4047), read on its own and live,\n * so a deep link to a record on no loaded page still opens and an edit shows\n * as soon as it lands. Asked only of a member who may view the records.\n */\n const routeRecordRead = useFirestoreDoc<any>(\n () =>\n dataScope && selected?.$id && routeRecordId && !blocked.records\n ? doc(firestore, dataScope[0], dataScope[1], 'datasets', selected.$id, 'records', routeRecordId)\n : null,\n [firestore, dataScope, selected?.$id, routeRecordId, blocked.records],\n )\n // Keyed by the id it was read under, as the table's rows are.\n const routeRecord = useMemo(\n () => (routeRecordId && routeRecordRead.data ? { ...routeRecordRead.data, $id: routeRecordId } : null),\n [routeRecordId, routeRecordRead.data],\n )\n const routeRecordMissing = Boolean(\n routeRecordId &&\n !routeRecord &&\n (routeRecordRead.status === 'error' || (routeRecordRead.status !== 'loading' && !routeRecordRead.fromCache)),\n )\n const recordRefusals = useMemo(\n () =>\n listQueryRefusals(recordPlan.refused, {\n fields: recordFilter.fields,\n headers: recordFilter.headers,\n options: recordFilter.options,\n }),\n [recordPlan.refused, recordFilter],\n )\n const filteringRecords =\n recordClauses.length > 0 || gridFilter.searchWords.some((word) => word.trim())\n /**\n * The two HEAD-COUNTS on this card are server aggregates, not the lengths\n * of the two capped listeners above (AGL-1716, the AGL-1706 shape).\n *\n * Both listeners are capped correctly — 100 datasets in a picker, 500 rows\n * in a table, nobody needs more streamed in. What neither may do is answer\n * \"how many does this org have\", and both did:\n *\n * * `records.length` saturated at 500 and was handed to\n * `checkQuota(org, 'recordsPerDataset', …)`. The bands are 1,000 /\n * 10,000 / 100,000 / 500,000 / 1,000,000, so on EVERY paid plan the\n * check read 500-against-thousands and could never refuse. Worse, the\n * importer computed its room as `limit − records.length`, so an\n * understated count *inflated* the slots it offered.\n * * `datasets.length` saturated at 100 and fed `checkDatasetQuota`, whose\n * bands run to 250 / 500 / 2,000 above that window.\n *\n * `api/orgs/datasets` — the route that actually enforces both — counts with\n * `collection('datasets').count()` and `collection('records').count()` on\n * these exact paths, so this card was offering headroom the API would then\n * refuse. It now asks the same question the same way, and the console\n * billing page and the staff org page already read the dataset count with\n * this identical unscoped aggregate.\n *\n * THE LISTS KEEP THEIR CAPS. The list and the count are different\n * questions; only the count moved. A one-shot goes stale where a listener\n * refreshed for free, so both are re-read after any mutation that can move\n * them — the epochs below.\n *\n * No counting RULE moves: `checkQuota` and `checkDatasetQuota` are\n * untouched entitlement inputs, and nothing here is metered by\n * `report-usage` (it samples record counts server-side for storage, on its\n * own read). Only this card's inputs stopped being saturated.\n */\n const [datasetCountEpoch, setDatasetCountEpoch] = useState(0)\n const [recordCountEpoch, setRecordCountEpoch] = useState(0)\n const [serverDatasetCount, setServerDatasetCount] = useState<number | null>(\n null,\n )\n // TAGGED with the dataset it describes. A bare number would have to be\n // cleared when the selection changes, and clearing state from inside the\n // effect that fills it is a render loop waiting for one unstable dep;\n // tagging answers \"whose count is this?\" without writing state on render.\n const [serverRecordCount, setServerRecordCount] = useState<{\n datasetId: string\n count: number\n } | null>(null)\n useEffect(() => {\n if (!dataScope) return\n let active = true\n // Unscoped, exactly like `api/orgs/datasets` and the billing page: the\n // quota is about the ORG's datasets, not the subset this collaborator\n // can see. A scoped collaborator whom AGL-1044 denies the read falls\n // through to the catch and keeps the visible-rows lower bound.\n void getCountFromServer(\n collection(firestore, dataScope[0], dataScope[1], 'datasets'),\n )\n .then((snapshot) => {\n if (active) setServerDatasetCount(snapshot.data().count)\n })\n .catch(() => {\n // Falls back to the listener length below — a LOWER bound, and this\n // card's prior behaviour. Deliberately not 0: `checkDatasetQuota`\n // answers from whatever it is handed, and 0 used is a confident\n // wrong number in the flattering direction.\n })\n return () => {\n active = false\n }\n }, [firestore, dataScope, datasetCountEpoch])\n // The dataset the counts below belong to. Distinct from `selectedId`\n // above, which is the PICKER value and is null until the user chooses.\n const countedDatasetId: string | undefined = selected?.$id\n useEffect(() => {\n if (!dataScope || !countedDatasetId || blocked.records) return\n let active = true\n void getCountFromServer(\n collection(\n firestore,\n dataScope[0],\n dataScope[1],\n 'datasets',\n countedDatasetId,\n 'records',\n ),\n )\n .then((snapshot) => {\n if (active) {\n setServerRecordCount({\n datasetId: countedDatasetId,\n count: snapshot.data().count,\n })\n }\n })\n .catch(() => {\n // Same fallback, same reason as above.\n })\n return () => {\n active = false\n }\n }, [firestore, dataScope, countedDatasetId, recordCountEpoch, blocked.records])\n // Pending, denied, or answered about the PREVIOUS selection, the loaded\n // rows stand in. They can only UNDERSTATE (same collections, capped),\n // never overstate, so nothing these figures gate fires on a count larger\n // than the truth. Since AGL-2501 the record fallback is one PAGE, so it\n // understates by more — which moves it further in the safe direction and\n // changes nothing about which way it can be wrong.\n const datasetCount = serverDatasetCount ?? datasets.length\n const recordCount =\n serverRecordCount && serverRecordCount.datasetId === countedDatasetId\n ? serverRecordCount.count\n : records.length\n\n // --- Create dataset -----------------------------------------------------\n const [creator, setCreator] = useState<{\n name: string\n fields: string\n } | null>(null)\n const handleOpenCreator = useCallback(() => {\n if (!checkEntitlement(org, 'dataStore')) {\n return enqueueSnackbar(\n 'Datasets require a Starter plan or higher — see Billing',\n { variant: 'warning', persist: false },\n )\n }\n // Addon-aware quota (AGL-132): purchased extra datasets raise the\n // limit up to the plan's hard max; beyond that only an upgrade helps.\n // The ORG's datasets, not the picker's window (AGL-1716).\n const quota = checkDatasetQuota(org as any, datasetCount)\n if (!quota.allowed) {\n return enqueueSnackbar(\n quota.upgradeRequired\n ? `Dataset limit reached (${quota.limit}) — upgrade in Billing`\n : `Dataset limit reached (${quota.limit}) — add extra datasets ` +\n `for $${quota.addonPriceUsd}/mo each or upgrade in Billing`,\n { variant: 'warning', persist: false },\n )\n }\n setCreator({ name: '', fields: '' })\n }, [org, datasetCount, enqueueSnackbar])\n // Entries are human names — \"Roast preference\" → stable id\n // `roast_preference` with the pretty name kept for headers (AGL-558).\n const creatorEntries = parseDatasetFieldEntries(creator?.fields ?? '')\n const creatorFields = creatorEntries.map((entry) => entry.id)\n const handleCreate = useCallback(async () => {\n // No org, no create. The `else` that used to sit below this was the\n // legacy host-scope client write (AGL-1050) — the one path by which a\n // dataset could be created with NO quota check, since /api/orgs/datasets\n // is where AGL-473 enforces it. The rules now deny that path outright;\n // this is the client side of the same closure. The Add button is\n // disabled without a scope, so reaching the guard means a stale closure.\n if (!creator?.name.trim() || creatorFields.length === 0 || !orgId) return\n let id: string\n try {\n const result = await callDatasetApi({\n action: 'create-dataset',\n displayName: creator.name.trim(),\n fields: creatorFields,\n // Typed model from day one (AGL-178); refine in the Schema dialog.\n model: modelFromFieldEntries(creatorEntries),\n ...createdFrom,\n })\n id = String(result.id)\n } catch (error: any) {\n return void enqueueSnackbar(error?.message ?? 'Dataset create failed', {\n variant: 'warning',\n persist: false,\n })\n }\n setCreator(null)\n openDataset(id)\n setDatasetCountEpoch((epoch) => epoch + 1)\n enqueueSnackbar(`Dataset \"${creator.name.trim()}\" created`, {\n variant: 'success',\n persist: false,\n })\n logActivity('Created dataset', {\n type: 'content',\n id,\n name: creator.name.trim(),\n })\n }, [creator, creatorEntries, creatorFields, orgId, createdFrom, callDatasetApi, enqueueSnackbar, logActivity, openDataset])\n\n // Join collection template (AGL-180): extrinsic many-to-many as a\n // visible, editable collection of FKey pairs — no magic.\n const [joiner, setJoiner] = useState<{ a: string; b: string } | null>(null)\n const handleCreateJoin = useCallback(async () => {\n if (!joiner?.a || !joiner?.b || joiner.a === joiner.b) return\n const a = datasets.find((item) => item.$id === joiner.a)\n const b = datasets.find((item) => item.$id === joiner.b)\n // A join collection is a dataset and consumes the same quota, so it\n // takes the same API-only route (AGL-1050) — the host-scope client\n // write that used to stand in for it is gone.\n if (!a || !b || !orgId) return\n const fieldFor = (target: any, fieldId: string) => ({\n name: datasetDisplayName(target) || fieldId,\n type: 'reference' as const,\n required: true,\n reference: {\n datasetId: target.$id as string,\n displayFieldId: effectiveDatasetModel(target).order[0],\n onDelete: 'setNull' as const,\n },\n })\n const payload = {\n displayName: `${datasetDisplayName(a)} ↔ ${datasetDisplayName(b)}`,\n fields: ['aRef', 'bRef'],\n model: {\n order: ['aRef', 'bRef'],\n fields: { aRef: fieldFor(a, 'aRef'), bRef: fieldFor(b, 'bRef') },\n },\n }\n let id: string\n try {\n const result = await callDatasetApi({\n action: 'create-dataset',\n ...payload,\n // A join collection is a dataset, so the same Default sharing applies.\n ...createdFrom,\n })\n id = String(result.id)\n } catch (error: any) {\n return void enqueueSnackbar(error?.message ?? 'Join create failed', {\n variant: 'warning',\n persist: false,\n })\n }\n setJoiner(null)\n openDataset(id)\n // A join collection IS a dataset and consumes the same quota.\n setDatasetCountEpoch((epoch) => epoch + 1)\n enqueueSnackbar('Join collection created', {\n variant: 'success',\n persist: false,\n })\n }, [joiner, datasets, orgId, createdFrom, callDatasetApi, enqueueSnackbar, openDataset])\n\n const handleDeleteDataset = useCallback(async () => {\n if (!selected) return\n const confirmed = await confirm({\n title: 'Delete this dataset?',\n description:\n `\"${datasetDisplayName(selected)}\"` +\n // What is actually being destroyed, not what is loaded (AGL-1716):\n // a 40,000-row dataset used to warn about \"its 500 documents\".\n (recordCount\n ? ` and its ${recordCount.toLocaleString()} record${recordCount === 1 ? '' : 's'}`\n : '') +\n ' will be deleted. Repeatable components and bindings that use it ' +\n 'stop showing its data.',\n confirmationText: 'Delete',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed || !dataScope) return\n // Deleting the dataset doc client-side would strand its `records`\n // subcollection — Firestore doesn't cascade and only the Admin SDK has\n // `recursiveDelete`, so the delete goes through the erase route\n // (AGL-945). Single-record deletes below stay client-direct.\n try {\n const response = await authorizedFetch(user, '/api/resources/erase', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n scope: dataScope[0],\n scopeId: dataScope[1],\n kind: 'datasets',\n id: selected.$id,\n // Names the site this delete was issued from, so the route can\n // refuse to destroy a dataset shared beyond it (AGL-1046). The\n // org Data page passes no host and keeps the org-wide delete.\n hostId,\n }),\n })\n const result = await response.json().catch(() => ({}))\n if (!response.ok) throw new Error(result?.error ?? 'Dataset delete failed')\n } catch (error: any) {\n return void enqueueSnackbar(error?.message ?? 'Dataset delete failed', {\n variant: 'warning',\n persist: false,\n })\n }\n openDataset(null)\n setDatasetCountEpoch((epoch) => epoch + 1)\n enqueueSnackbar('Dataset deleted', { variant: 'success', persist: false })\n logActivity('Deleted dataset', {\n type: 'content',\n id: selected.$id,\n name: datasetDisplayName(selected),\n })\n }, [\n selected,\n recordCount,\n confirm,\n dataScope,\n hostId,\n user,\n enqueueSnackbar,\n logActivity,\n openDataset,\n ])\n\n /**\n * What the selected dataset's references point at beyond this site's list\n * (AGL-4047). A dataset this site sees can name a target another site holds;\n * the schema dialog warns about exactly that, and a cell still labels the\n * row it points at, so the target has to be known even though the site's\n * list does not show it. Read one by one, and only when there is one; a\n * target the viewer may not read stays unknown.\n */\n const [outsideTargets, setOutsideTargets] = useState<any[]>(NO_DATASETS)\n useEffect(() => {\n let active = true\n const missing = railNarrowed\n ? [\n ...new Set(\n model.order\n .map((fieldId) => model.fields[fieldId]?.reference?.datasetId)\n .filter((id): id is string => Boolean(id)),\n ),\n ].filter((id) => !datasets.some((item) => item.$id === id))\n : []\n if (!missing.length || !dataScope) {\n setOutsideTargets(NO_DATASETS)\n return\n }\n void Promise.all(\n missing.map((id) =>\n getDoc(doc(firestore, dataScope[0], dataScope[1], 'datasets', id)).then(\n (snapshot) => (snapshot.exists() ? datasetRow(snapshot) : null),\n () => null,\n ),\n ),\n ).then((rows) => {\n if (active) setOutsideTargets(rows.filter(Boolean))\n })\n return () => {\n active = false\n }\n }, [railNarrowed, model, datasets, firestore, dataScope])\n const knownDatasets = useMemo(\n () => (outsideTargets.length ? [...datasets, ...outsideTargets] : datasets),\n [datasets, outsideTargets],\n )\n\n // Reference pickers (AGL-180): load target-collection rows for every\n // reference field in the model (id -> display label).\n const [refOptions, setRefOptions] = useState<\n Record<string, Array<{ id: string; label: string }>>\n >({})\n useEffect(() => {\n let active = true\n const referenceFields = model.order.filter(\n (fieldId) =>\n model.fields[fieldId]?.type === 'reference' &&\n model.fields[fieldId]?.reference?.datasetId,\n )\n if (!referenceFields.length || !dataScope) {\n setRefOptions({})\n return\n }\n void Promise.all(\n referenceFields.map(async (fieldId) => {\n const reference = model.fields[fieldId].reference as {\n datasetId: string\n displayFieldId?: string\n }\n const target = knownDatasets.find(\n (item) => item.$id === reference.datasetId,\n )\n const displayFieldId =\n reference.displayFieldId ??\n effectiveDatasetModel(target ?? {}).order[0]\n const snapshot = await getDocs(\n query(\n collection(\n firestore,\n dataScope[0],\n dataScope[1],\n 'datasets',\n reference.datasetId,\n 'records',\n ),\n limit(200),\n ),\n ).catch(() => null)\n const options = (snapshot?.docs ?? []).map((docSnapshot) => ({\n id: docSnapshot.id,\n label: String(\n docSnapshot.get('values')?.[displayFieldId ?? ''] ??\n docSnapshot.id,\n ),\n }))\n return [fieldId, options] as const\n }),\n ).then((entries) => {\n if (active) setRefOptions(Object.fromEntries(entries))\n })\n return () => {\n active = false\n }\n }, [model, knownDatasets, firestore, dataScope])\n /**\n * One reference target's label, or `null` when this ID resolves to nothing.\n *\n * The distinction the grid cannot draw. `referenceLabel` below falls back to\n * the raw ID, which is the only thing a cell has room for and is\n * indistinguishable from a resolved label that happens to look like an ID.\n * The record view has room to say which, so it asks the question that has a\n * `null` answer.\n *\n * Unresolvable covers more than a deleted target: `refOptions` loads at most\n * 200 rows per referenced collection, so a live target outside that window\n * reports the same way. Either way the ID is shown and neither is claimed to\n * be a working link.\n */\n const resolveReferenceLabel = useCallback(\n (fieldId: string, id: string): string | null =>\n refOptions[fieldId]?.find((option) => option.id === id)?.label ?? null,\n [refOptions],\n )\n const referenceLabel = useCallback(\n (fieldId: string, value: unknown): string => {\n const ids = Array.isArray(value) ? value : value != null ? [value] : []\n return ids\n .map((id) => resolveReferenceLabel(fieldId, String(id)) ?? String(id))\n .join(', ')\n },\n [resolveReferenceLabel],\n )\n /**\n * The record the viewer is showing, held as an ID and resolved against the\n * page the table already has.\n *\n * Holding the ID rather than the row is what keeps the view live without\n * costing a read: the same listener that draws the table re-resolves it, so\n * an edit landing underneath updates the open dialog. When the row leaves\n * the page — deleted, or paged past — this answers `null` and the dialog\n * closes, which is the honest response to a record no longer in front of\n * this reader. Nothing here queries: `records` is the page (or filter window)\n * query's answer.\n */\n const [viewerId, setViewerId] = useState<string | null>(null)\n /**\n * Opens a record (AGL-4047): on its own page beneath the dataset's tab\n * where the Data page is routed, in the View record dialog elsewhere.\n */\n const datasetHref = basePath && selected?.$id ? `${basePath}/${selected.$id}` : null\n const openRecord = useCallback(\n (id: string) => {\n if (datasetHref) router.push(`${datasetHref}/records/${encodeURIComponent(id)}`)\n else setViewerId(id)\n },\n [datasetHref, router],\n )\n const viewerRecord = useMemo(\n () =>\n viewerId\n ? (records.find((record: any) => record.$id === viewerId) ?? null)\n : null,\n [viewerId, records],\n )\n\n // --- Document editor (null id = new; AGL-179 typed inputs) --------------\n const [editor, setEditor] = useState<{\n id: string | null\n values: Record<string, string>\n errors: Record<string, string>\n /** A sample a site start seeded (AGL-4065): saving it makes it the owner's. */\n sample?: boolean\n } | null>(null)\n const handleOpenRecord = useCallback(\n (record?: any) => () => {\n if (!record) {\n // The dataset's documents, not the loaded window (AGL-1716).\n const quota = checkQuota(org, 'recordsPerDataset', recordCount)\n if (!quota.allowed) {\n return enqueueSnackbar(\n `Record limit reached (${quota.limit}) — see Billing to upgrade`,\n { variant: 'warning', persist: false },\n )\n }\n }\n const values: Record<string, string> = {}\n for (const fieldId of model.order) {\n const field = model.fields[fieldId]\n if (!field) continue\n if (record) {\n values[fieldId] = datasetValueToInput(\n field,\n record.values?.[fieldId],\n )\n } else if (field.default != null) {\n values[fieldId] = String(field.default)\n }\n }\n // Flag non-conforming stored values (AGL-178 policy: type changes\n // never rewrite documents; the editor surfaces the mismatch).\n const errors = record\n ? validateDocument(model, record.values ?? {})\n : {}\n setEditor({ id: record?.$id ?? null, values, errors, ...(isSampleDatasetRecord(record) ? { sample: true } : {}) })\n },\n [org, recordCount, model, enqueueSnackbar],\n )\n const handleSaveRecord = useCallback(async () => {\n if (!editor || !selected || !dataScope) return\n // The editor holds the record's WHOLE values, so an address it already\n // has stays and an empty one fills in from its source (AGL-3475).\n const coerced = fillRecordAddresses(\n model,\n coerceDocumentValues(model, editor.values),\n )\n const errors = validateDocument(model, coerced)\n if (Object.keys(errors).length) {\n return void setEditor((prev) => (prev ? { ...prev, errors } : prev))\n }\n // `values` is replaced wholesale (not merged) so orphaned values from\n // removed fields strip here, lazily, per the documented AGL-178 policy.\n try {\n if (editor.id) {\n // Updates stay client-direct (no quota consumed).\n const recordRef = doc(\n firestore,\n dataScope[0],\n dataScope[1],\n 'datasets',\n selected.$id,\n 'records',\n editor.id,\n )\n await setDoc(\n recordRef,\n {\n values: coerced,\n // The integrity index moves with the values it describes\n // (`datasetIntegrityUpdate`); the merging form, because clearing\n // the last reference has to REMOVE the field rather than omit it.\n ...datasetIntegrityUpdate(model, coerced, deleteField()),\n // A sample saved is the owner's row now (AGL-4065).\n ...(editor.sample ? { sample: deleteField() } : {}),\n updatedAt: Timestamp.now(),\n },\n {\n mergeFields: [\n 'values',\n 'referencedIds',\n 'filterKeys',\n 'filterValues',\n 'updatedAt',\n ...(editor.sample ? ['sample'] : []),\n ],\n },\n )\n await announceRecords(selected.$id)\n } else {\n // Creates go through the quota-enforcing API (AGL-473). The legacy\n // host-scope client write that used to follow this branch is gone\n // (AGL-1050): a non-null `dataScope` is an org scope, so `orgId` is\n // set and there is no third case to fall into.\n await callDatasetApi({\n action: 'create-record',\n datasetId: selected.$id,\n values: coerced,\n })\n }\n } catch (error: any) {\n return void enqueueSnackbar(error?.message ?? 'Record save failed', {\n variant: 'warning',\n persist: false,\n })\n }\n setEditor(null)\n // A create moves the count; an update cannot. Same reason as the\n // importer: the one-shot aggregate does not refresh itself.\n if (!editor.id) setRecordCountEpoch((epoch) => epoch + 1)\n enqueueSnackbar(editor.id ? 'Record saved' : 'Record added', {\n variant: 'success',\n persist: false,\n })\n logActivity(editor.id ? 'Updated record' : 'Added record', {\n type: 'content',\n id: selected.$id,\n name: datasetDisplayName(selected),\n })\n }, [\n editor,\n selected,\n firestore,\n dataScope,\n model,\n callDatasetApi,\n announceRecords,\n enqueueSnackbar,\n logActivity,\n ])\n const handleDeleteRecord = useCallback(\n (record: any, afterDelete?: () => void) => async () => {\n // Datasets whose records this delete rewrites through a reference\n // fixup, beside the one the record belongs to. Each has pages of its\n // own to refresh (AGL-3113).\n const alsoChanged = new Set<string>()\n if (!selected || !dataScope) return\n /**\n * Delete integrity (AGL-180): every collection whose model references\n * this one is asked whether it still points at this record. `restrict`\n * blocks the delete; `setNull` strips the FKey from the holders.\n *\n * The question is a QUERY over the denormalized `referencedIds` index,\n * not a page of records filtered in the browser. A page answers for the\n * rows it happened to fetch — an unordered `limit` is answered in\n * document-id order over auto-ids, so it is an arbitrary sample — and a\n * reference held by a row outside it reads as no reference at all: the\n * delete goes through and `restrict` silently fails to restrict, leaving\n * a document pointing at something that no longer exists. `values`\n * itself cannot be queried (it carries a deliberate index exemption —\n * see `datasetIntegrityFields`), which is why the index exists.\n *\n * The query narrows to the candidates; the per-field test below keeps it\n * EXACT, since `referencedIds` is the union across every reference field\n * and one of them may point at a different collection entirely.\n *\n * ⚠️ FAILS CLOSED. A query that rejects — a missing index, a rules\n * refusal on a collection this member cannot read — refuses the delete\n * rather than treating silence as \"nothing references it\". A check that\n * fails open is worse than no check, because the UI then tells the user\n * the record is safe to remove.\n *\n * ⚠️ Reaches the collections in this viewer's scoped, capped window. A\n * referencing collection shared with no site this member can see is one\n * the client may not read at all, so it is not consulted; only a server\n * route could close that.\n *\n * On a site's Data page that window is NOT the list (AGL-4047). The list\n * is the site's, and a dataset another site holds can reference a row of\n * one shared with both: narrowing what the page shows must not narrow\n * what a delete protects. So the page reads the viewer's reach here, once,\n * at the moment of the delete, and refuses if it cannot.\n */\n let referencing: any[] = datasets\n if (railNarrowed) {\n try {\n const reach = await getDocs(\n query(\n collection(firestore, dataScope[0], dataScope[1], 'datasets'),\n ...(reachScope\n ? [where('visibleTo', 'array-contains-any', [...reachScope])]\n : []),\n limit(DATASET_LIST_WINDOW),\n ),\n )\n referencing = reach.docs.map(datasetRow)\n } catch {\n return void enqueueSnackbar(\n 'Cannot delete: the datasets that may reference this record could ' +\n 'not be checked, so removing it could break them. Nothing was ' +\n 'deleted.',\n { variant: 'error' },\n )\n }\n }\n for (const other of referencing) {\n const otherModel = effectiveDatasetModel(other)\n if (!referencingFieldIds(otherModel, selected.$id).length) continue\n let snapshot\n try {\n snapshot = await getDocs(\n query(\n collection(\n firestore,\n dataScope[0],\n dataScope[1],\n 'datasets',\n other.$id,\n 'records',\n ),\n where('referencedIds', 'array-contains', record.$id),\n ),\n )\n } catch {\n return void enqueueSnackbar(\n `Cannot delete: \"${datasetDisplayName(other)}\" could not be checked for ` +\n 'references, so removing this record could break it. Nothing ' +\n 'was deleted.',\n { variant: 'error' },\n )\n }\n // The verdict is shared with `/api/orgs/datasets` `delete-record`\n // (`planReferenceFixups`): the per-field test keeps the query EXACT,\n // since `referencedIds` is the union across every reference field.\n const plan = planReferenceFixups(\n otherModel,\n selected.$id,\n record.$id,\n snapshot.docs.map((docSnapshot) => ({ id: docSnapshot.id, values: docSnapshot.get('values') })),\n )\n if (plan.kind === 'none') continue\n if (plan.kind === 'restricted') {\n return void enqueueSnackbar(\n restrictedDeleteMessage(plan.holders, datasetDisplayName(other)),\n { variant: 'warning', persist: false },\n )\n }\n // Chunked under Firestore's 500-writes-per-batch cap. The query is no\n // longer bounded by a page size, so the number of holders is whatever\n // the collection really holds.\n for (let start = 0; start < plan.updates.length; start += 400) {\n const batch = writeBatch(firestore)\n for (const update of plan.updates.slice(start, start + 400)) {\n const holder = snapshot.docs.find((docSnapshot) => docSnapshot.id === update.id)\n if (!holder) continue\n batch.update(holder.ref, {\n values: update.values,\n ...datasetIntegrityUpdate(otherModel, update.values, deleteField()),\n })\n }\n await batch.commit()\n }\n // The fixups rewrote rows in ANOTHER dataset, whose own pages are now\n // showing a reference that no longer resolves.\n alsoChanged.add(other.$id)\n }\n await deleteDoc(\n doc(\n firestore,\n dataScope[0],\n dataScope[1],\n 'datasets',\n selected.$id,\n 'records',\n record.$id,\n ),\n )\n setRecordCountEpoch((epoch) => epoch + 1)\n for (const datasetId of [selected.$id, ...alsoChanged]) {\n await announceRecords(datasetId)\n }\n enqueueSnackbar('Record deleted', { variant: 'success', persist: false })\n afterDelete?.()\n },\n [\n selected,\n datasets,\n railNarrowed,\n reachScope,\n firestore,\n dataScope,\n announceRecords,\n enqueueSnackbar,\n ],\n )\n\n /**\n * Import and export (AGL-3530) open the console's import wizard and export\n * dialog on this dataset (`data.dataset:<datasetId>`): the file is read,\n * matched and written on the server, through the same record writes as\n * every other create and update, and the export streams the fields the\n * person picks. Outside the console shell there is no launcher, and no\n * Import or Export to offer. Inside it, Import is on for a member who may\n * write this dataset and switched off with the permission named for one who\n * may not, and Export likewise for \"Export data\", for a member who can see it\n * (AGL-3546, AGL-4047) — the transfer routes' own rule.\n */\n const transfer = useTransferLauncher()\n const transferTarget = selected?.$id\n ? {\n resource: datasetTransferResourceKey(selected.$id),\n scope: 'org' as const,\n // This dataset's own answer once it is known; the workspace's until then.\n ...(blocked.known ? { importAllowed: !blocked.writes } : {}),\n }\n : null\n const canImport = Boolean(transfer && transferTarget && transfer.can('import', transferTarget))\n const canExport = Boolean(transfer && transferTarget && transfer.can('export', transferTarget))\n const handleImport = useCallback(() => {\n if (!transfer || !selected?.$id) return\n const dataset = { id: selected.$id, name: datasetDisplayName(selected) }\n transfer.openImport({\n resource: datasetTransferResourceKey(dataset.id),\n scope: 'org',\n title: dataset.name ? `Import into ${dataset.name}` : 'Import records',\n onFinished: () => {\n // An import moves the record count, and the aggregate is a one-shot.\n setRecordCountEpoch((epoch) => epoch + 1)\n logActivity('Imported records', { type: 'content', id: dataset.id, name: dataset.name })\n },\n })\n }, [transfer, selected, logActivity])\n const handleExport = useCallback(() => {\n if (!transfer || !selected?.$id) return\n const name = datasetDisplayName(selected)\n transfer.openExport({\n resource: datasetTransferResourceKey(selected.$id),\n scope: 'org',\n title: name ? `Export ${name}` : 'Export records',\n // The table's own query, re-planned on the server the way the table\n // plans it, so \"the current filter\" exports what the table shows.\n ...(filteringRecords\n ? {\n filter: {\n label: 'The records the table’s filters and search show',\n value: { clauses: recordClauses, search: gridFilter.searchWords },\n },\n }\n : {}),\n })\n }, [transfer, selected, filteringRecords, recordClauses, gridFilter.searchWords])\n\n /*\n * One column per schema field, filterable as far as `datasetRecordFilter`\n * declares it. The row OPENS the record, read-only (`onOpen`); the actions\n * column holds the keyboard's way in (`View`, a real button) beside Edit\n * and Delete, and a press anywhere in it never opens the row.\n */\n const recordGridColumns = useMemo(\n () =>\n listFilterGridColumns(\n [\n ...fields.map((fieldId, column) => {\n const field = model.fields[fieldId]\n const shown = (row: any) =>\n field?.type === 'reference'\n ? referenceLabel(fieldId, row.values?.[fieldId]) || '--'\n : field\n ? formatDatasetValue(field, row.values?.[fieldId]) || '--'\n : '--'\n return {\n field: recordColumn(fieldId),\n headerName: field?.name ?? fieldId,\n // Field descriptions (AGL-560) surface as header hints.\n description: field?.description,\n flex: 1,\n minWidth: 140,\n renderCell: ({ row }: { row: any }) =>\n // A sample a site start seeded says so beside its first value (AGL-4065).\n column === 0 && isSampleDatasetRecord(row) ? (\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center', height: '100%', minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {shown(row)}\n </Typography>\n <Tooltip title={DATASET_SAMPLE_RECORD_NOTE}>\n <Chip label=\"Sample\" size=\"small\" variant=\"outlined\" color=\"info\" />\n </Tooltip>\n </Stack>\n ) : (\n shown(row)\n ),\n }\n }),\n listActionsColumn(\n (record: any) => (\n <Stack\n direction=\"row\"\n sx={{ height: '100%', alignItems: 'center', justifyContent: 'flex-end' }}\n >\n <Button size=\"small\" onClick={() => openRecord(record.$id)}>\n {'View'}\n </Button>\n <BlockedControl blocked={blocked.writes} reason={blocked.writesReason}>\n <Button size=\"small\" onClick={handleOpenRecord(record)}>\n {'Edit'}\n </Button>\n </BlockedControl>\n <BlockedControl blocked={blocked.writes} reason={blocked.writesReason}>\n <Button\n size=\"small\"\n color=\"error\"\n onClick={handleDeleteRecord(record)}\n >\n {'Delete'}\n </Button>\n </BlockedControl>\n </Stack>\n ),\n { width: 220 },\n ),\n ] as Parameters<typeof listFilterGridColumns>[0],\n recordFilter.fields,\n recordFilter.options,\n recordFilter.headers,\n ),\n [\n fields,\n model,\n referenceLabel,\n handleOpenRecord,\n handleDeleteRecord,\n openRecord,\n recordFilter,\n blocked.writes,\n blocked.writesReason,\n ],\n )\n\n /*\n * EVERY HEADER SORTS — THE PAGE ON SCREEN (AGL-3680). A record's values are\n * per-schema and no field is on every record (see the walk above), so no\n * query can order by one; each value column sorts the loaded page by what\n * it shows (a reference by its label, a number or switch by its value) and\n * the notice says it is this page only.\n */\n const recordPageSorts = useMemo(\n () =>\n Object.fromEntries(\n fields.map((fieldId) => {\n const field = model.fields[fieldId]\n return [\n recordColumn(fieldId),\n (row: any) => {\n const value = row.values?.[fieldId]\n if (field?.type === 'reference') return referenceLabel(fieldId, value) || null\n if (typeof value === 'number' || typeof value === 'boolean') return value\n return field ? formatDatasetValue(field, value) || null : null\n },\n ]\n }),\n ),\n [fields, model, referenceLabel],\n )\n const recordSortHeaders = useMemo(\n () =>\n Object.fromEntries(\n fields.map((fieldId) => [recordColumn(fieldId), model.fields[fieldId]?.name ?? fieldId]),\n ),\n [fields, model],\n )\n const recordColumnSort = useListColumnSort<any>({\n sorts: NO_QUERY_SORTS,\n rows: records,\n pageSorts: recordPageSorts,\n headers: recordSortHeaders,\n })\n\n /**\n * The rail (AGL-4047): one tab per dataset, at the dataset's own address,\n * with a second line that tells two of one name apart. Past\n * {@link DATASET_RAIL_GROUP_AT} the tabs are grouped by who they are shared\n * with, and the organization page offers the Shared with filter.\n */\n const grouped = railDatasets.length > DATASET_RAIL_GROUP_AT\n const railSections = useMemo<HubSection[]>(() => {\n if (!basePath) return []\n const tab = (item: DatasetRailEntry, group?: string): HubSection => ({\n href: `${basePath}/${item.$id}`,\n label: datasetRailName(item),\n secondary: datasetRailSecondary(item, { hostNames, grouped }),\n ...(group ? { group } : {}),\n })\n if (!grouped) return railDatasets.map((item: DatasetRailEntry) => tab(item))\n return groupDatasetsBySharing(railDatasets, hostNames).flatMap((group) =>\n group.datasets.map((item) => tab(item, group.label)),\n )\n }, [basePath, railDatasets, hostNames, grouped])\n /** The join dialog's names, told apart where two match (AGL-4047). */\n const joinLabels = useMemo(() => datasetPickerLabelsOf(datasets, hostNames), [datasets, hostNames])\n const offerSharedWith =\n !pageHostId && orgSites.length > 1 && (datasets.length > DATASET_RAIL_GROUP_AT || Boolean(sharedWith))\n const sitesByName = useMemo(\n () => [...orgSites].sort((a, b) => (hostNames[a.$id] ?? '').localeCompare(hostNames[b.$id] ?? '')),\n [orgSites, hostNames],\n )\n const railHeader =\n datasets.length || nameSearch || sharedWith ? (\n <Stack spacing={1.5} sx={{ mb: 1 }}>\n <TextField\n size=\"small\"\n fullWidth\n placeholder=\"Search datasets by name\"\n value={nameSearch}\n onChange={(event) => setNameSearch(event.target.value)}\n slotProps={{ htmlInput: { 'aria-label': 'Search datasets by name' } }}\n />\n {offerSharedWith ? (\n <TextField\n select\n size=\"small\"\n fullWidth\n label=\"Shared with\"\n value={sharedWith}\n onChange={(event) => {\n setSharedWith(event.target.value)\n setRailWindow(DATASET_LIST_WINDOW)\n }}\n >\n <MenuItem value=\"\">{'Any site'}</MenuItem>\n {sitesByName.map((site) => (\n <MenuItem key={site.$id} value={site.$id}>\n {hostNames[site.$id]}\n </MenuItem>\n ))}\n </TextField>\n ) : null}\n </Stack>\n ) : null\n const railFooter = (\n <>\n {listAnswered && datasets.length > 0 && railDatasets.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\" sx={{ px: 2, py: 1 }}>\n {moreDatasets ? 'None of the loaded datasets match.' : 'No datasets match.'}\n </Typography>\n ) : null}\n {moreDatasets ? (\n <Button size=\"small\" sx={{ mt: 1 }} onClick={() => setRailWindow((window) => window + DATASET_LIST_WINDOW)}>\n {'Show more datasets'}\n </Button>\n ) : null}\n </>\n )\n\n /** The open dataset's facts, under its name. */\n const facts: Array<[string, string]> = selected\n ? [\n ['Shared with', datasetSharingLabel(selected, hostNames)],\n ['Fields', String(fields.length)],\n ['Records', blocked.records ? '--' : recordCount.toLocaleString()],\n ['Source', datasetSourceLabel(selected)],\n ['Created', datasetCreatedLabel(selected)],\n ]\n : []\n\n /** Label-over-value facts, under a heading. */\n const factsRow = (pairs: Array<[string, string]>) => (\n <Stack direction=\"row\" spacing={3} useFlexGap sx={{ flexWrap: 'wrap', mt: 1 }}>\n {pairs.map(([label, value]) => (\n <Box key={label}>\n <Typography variant=\"caption\" color=\"text.secondary\" component=\"div\">\n {label}\n </Typography>\n <Typography variant=\"body2\" color=\"text.primary\" component=\"div\" sx={{ overflowWrap: 'anywhere' }}>\n {value}\n </Typography>\n </Box>\n ))}\n </Stack>\n )\n\n /**\n * A record's own page (AGL-4047): back to its dataset, its fields, and\n * today's record actions with today's gates. It takes the place of the View\n * record dialog where the Data page is routed.\n */\n const recordTitle = routeRecord ? datasetRecordTitle(model, routeRecord.values) : undefined\n const recordPanel =\n selected && routeRecordId ? (\n <CardDisplay\n help={pluginDocsHelp('datasets', { anchor: '#organization-data-page' })}\n header={\n <Stack spacing={1} sx={{ alignItems: 'flex-start' }}>\n {datasetHref ? (\n <Button\n size=\"small\"\n component={AppLink}\n href={datasetHref}\n startIcon={<MdiIcon path={mdiArrowLeft.path} size={0.8} />}\n >\n {datasetRailName(selected)}\n </Button>\n ) : null}\n {recordTitle ? <span>{recordTitle}</span> : null}\n </Stack>\n }\n contentGutterX\n contentGutterY\n contentBordered=\"top\"\n HeaderProps={{\n action: routeRecord ? (\n <Stack direction=\"row\" spacing={1} useFlexGap sx={{ alignItems: 'center', flexWrap: 'wrap', justifyContent: 'flex-end' }}>\n <BlockedControl blocked={blocked.writes} reason={blocked.writesReason}>\n <Button size=\"small\" onClick={handleOpenRecord(routeRecord)}>\n {'Edit record'}\n </Button>\n </BlockedControl>\n <BlockedControl blocked={blocked.writes} reason={blocked.writesReason}>\n <Button\n size=\"small\"\n color=\"error\"\n onClick={handleDeleteRecord(routeRecord, () => {\n if (datasetHref) router.push(datasetHref)\n })}\n >\n {'Delete'}\n </Button>\n </BlockedControl>\n </Stack>\n ) : undefined,\n subheader: factsRow([\n ['Record ID', routeRecordId],\n ['Dataset', `${datasetRailName(selected)} · ${datasetSharingLabel(selected, hostNames)}`],\n ]),\n }}\n >\n <Stack spacing={1.5}>\n {blocked.records ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {DATASETS_VIEW_RECORDS_REFUSAL}\n </Typography>\n ) : routeRecordMissing ? (\n <Alert severity=\"info\">{'This record doesn’t exist, or you can’t open it.'}</Alert>\n ) : routeRecord ? (\n <DatasetRecordFieldList\n record={routeRecord}\n model={model}\n resolveReference={resolveReferenceLabel}\n divided\n />\n ) : null}\n </Stack>\n </CardDisplay>\n ) : null\n\n const panel = notSharedHere ? (\n <Alert severity=\"info\">{'This dataset isn’t shared with this site.'}</Alert>\n ) : notFound ? (\n <Alert severity=\"info\">{'This dataset doesn’t exist, or you can’t open it.'}</Alert>\n ) : recordPanel ? (\n recordPanel\n ) : !selected ? (\n listAnswered && datasets.length === 0 && !sharedWith ? (\n <CardDisplay contentGutterX contentGutterY>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Create a dataset, like Products, then add a repeating section ' +\n 'to any page to show one item per record.'}\n </Typography>\n </CardDisplay>\n ) : null\n ) : (\n <CardDisplay\n header={datasetRailName(selected)}\n help={pluginDocsHelp('datasets', { anchor: '#filter-records' })}\n contentGutterX\n contentGutterY\n contentBordered=\"top\"\n HeaderProps={{\n action: (\n <Stack\n direction=\"row\"\n spacing={1}\n useFlexGap\n sx={{ alignItems: 'center', flexWrap: 'wrap', justifyContent: 'flex-end' }}\n >\n <BlockedControl blocked={blocked.writes} reason={blocked.writesReason}>\n <Button\n size=\"small\"\n color=\"primary\"\n onClick={handleOpenRecord()}\n >\n {'Add record'}\n </Button>\n </BlockedControl>\n <BlockedControl blocked={blocked.writes && !blocked.sharingOnly} reason={blocked.writesReason}>\n <Button size=\"small\" onClick={() => setSchemaOpen(true)}>\n {'Schema'}\n </Button>\n </BlockedControl>\n {/* An import left unfinished, reopened where it stopped (AGL-3549). */}\n {transferTarget ? (\n <TransferResumeImport\n target={transferTarget}\n {...(selected ? { title: `Import into ${datasetDisplayName(selected)}` } : {})}\n onFinished={() => setRecordCountEpoch((epoch) => epoch + 1)}\n />\n ) : null}\n {/* Off with the permission named for a member known not to hold it,\n not hidden. Still absent while the answer is out, and where the\n launcher refuses for another reason than the key. */}\n {canImport || (transfer && transferTarget && blocked.writes) ? (\n <BlockedControl blocked={!canImport} reason={blocked.writesReason}>\n <Button size=\"small\" onClick={handleImport}>\n {'Import'}\n </Button>\n </BlockedControl>\n ) : null}\n {/* The real dataset size, not the loaded window (AGL-2335) —\n the export is a server stream, so a dataset whose first page\n has not landed yet is still exportable. */}\n {(canExport && (recordCount || records.length)) || (transfer && blocked.exports) ? (\n <BlockedControl blocked={blocked.exports} reason={DATASETS_EXPORT_REFUSAL}>\n <Button size=\"small\" onClick={handleExport}>\n {'Export'}\n </Button>\n </BlockedControl>\n ) : null}\n <BlockedControl blocked={blocked.deletes} reason={blocked.deletesReason}>\n <Button size=\"small\" color=\"error\" onClick={handleDeleteDataset}>\n {'Delete'}\n </Button>\n </BlockedControl>\n </Stack>\n ),\n subheader: factsRow(facts),\n }}\n >\n <Stack spacing={1.5}>\n {/* The per-dataset record cap, standing rather than only on refusal\n (AGL-2113). `recordCount` is the dataset's real size — the same\n number `handleOpenRecord` and the importer hand to `checkQuota`,\n not the loaded window (AGL-1716). */}\n {selected ? (\n <QuotaReadoutComponent\n ready={org != null}\n used={recordCount}\n limit={checkQuota(org, 'recordsPerDataset', recordCount).limit}\n noun=\"record\"\n />\n ) : null}\n {selected && blocked.records ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {DATASETS_VIEW_RECORDS_REFUSAL}\n </Typography>\n ) : selected && (records.length > 0 || recordPage > 0 || filteringRecords) ? (\n <>\n <ListFilterChips\n fields={recordFilter.fields}\n headers={recordFilter.headers}\n clauses={recordClauses}\n onChange={gridFilter.setClauses}\n options={recordFilter.options}\n />\n <ListQueryNotices\n refused={recordRefusals}\n notices={[...recordPlan.notices, ...recordColumnSort.notices]}\n />\n <ListTable\n aria-label=\"Records\"\n // Edit and Delete stay in reach when the columns scroll sideways\n // in the panel beside the rail (AGL-4047).\n pinActions\n rows={recordColumnSort.rows}\n columnSort={recordColumnSort}\n columns={recordGridColumns}\n onOpen={(id) => openRecord(id)}\n // One page of the walk, turned by the footer below: the grid\n // neither slices nor filters it.\n hideFooter\n filterMode=\"server\"\n filterModel={gridFilter.filterModel}\n onFilterModelChange={gridFilter.onFilterModelChange}\n quickFilter\n {...(blocked.exports ? { slotProps: EXPORT_OFF_TOOLBAR } : {})}\n noRowsLabel={\n filteringRecords ? 'No records match these filters' : 'No records yet.'\n }\n />\n {/* The count line is the PAGE's, deliberately. `recordCount` is the\n dataset's real size and it already has its own readout above —\n handing it to the footer as `count` would tell MUI the walk is\n that long and leave Next live past the end of it whenever a rule,\n a scope or a filter has narrowed what this reader may list.\n `hasMore` is a fact from the probe row, so the footer answers\n for what it is actually paging. */}\n <ListPagination\n page={recordPage}\n pageSize={recordPageSize}\n rowCount={records.length}\n hasMore={hasMoreRecords}\n onPageChange={setRecordPage}\n onPageSizeChange={setRecordPageSize}\n />\n </>\n ) : selected ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No records yet.'}\n </Typography>\n ) : null}\n </Stack>\n </CardDisplay>\n )\n\n return (\n <>\n {/* The page's own actions, in the page header beside its title. */}\n <PageHeaderActions>\n <Stack direction=\"row\" spacing={1} useFlexGap sx={{ flexWrap: 'wrap' }}>\n <BlockedControl blocked={blocked.creates} reason={DATASETS_WRITE_REFUSAL}>\n <Button variant=\"outlined\" color=\"primary\" onClick={handleOpenCreator}>\n {'Add dataset'}\n </Button>\n </BlockedControl>\n {datasets.length >= 2 ? (\n <BlockedControl blocked={blocked.creates} reason={DATASETS_WRITE_REFUSAL}>\n <Button onClick={() => setJoiner({ a: '', b: '' })}>{'Add join collection'}</Button>\n </BlockedControl>\n ) : null}\n </Stack>\n </PageHeaderActions>\n {/* The open dataset ends the trail; the heading stays the page's. */}\n {/* On a record's page the trail runs dataset, linked, then record. */}\n {routeRecordId && selected && datasetHref ? (\n <PageHeaderRecord\n title={recordTitle}\n keepHeading\n parentTitle={datasetRailName(selected)}\n parentHref={datasetHref}\n />\n ) : (\n <PageHeaderRecord title={selected && routeDatasetId ? datasetRailName(selected) : undefined} keepHeading />\n )}\n <HubSections\n sections={railSections}\n navHeader=\"Datasets\"\n railHeader={railHeader}\n railFooter={railFooter}\n scrollRail\n >\n {panel}\n </HubSections>\n <Dialog\n open={Boolean(creator)}\n onClose={() => setCreator(null)}\n maxWidth=\"xs\"\n fullWidth\n >\n <DialogTitle>{'New dataset'}</DialogTitle>\n <DialogContent\n sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}\n >\n {orgId ? (\n <Typography variant=\"body2\" color=\"text.secondary\" sx={{ mt: 1 }}>\n {/* Ownership and visibility are separate facts (AGL-1044), and\n what a new dataset starts on depends on where it is made. */}\n {newDatasetSharingNote(createsSiteOnly)}\n </Typography>\n ) : null}\n <TextField\n label=\"Name\"\n value={creator?.name ?? ''}\n onChange={(event) =>\n setCreator((prev) =>\n prev ? { ...prev, name: event.target.value } : prev,\n )\n }\n size=\"small\"\n autoFocus\n sx={{ mt: 1 }}\n helperText=\"e.g. Products, Team, FAQ\"\n />\n <TextField\n label=\"Fields\"\n value={creator?.fields ?? ''}\n onChange={(event) =>\n setCreator((prev) =>\n prev ? { ...prev, fields: event.target.value } : prev,\n )\n }\n size=\"small\"\n helperText={\n creatorEntries.length\n ? `Columns: ${creatorEntries\n .map((entry) => entry.name)\n .join(', ')}`\n : 'Comma-separated column names, e.g. Title, Unit price'\n }\n />\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setCreator(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={\n !scopeReady ||\n !creator?.name.trim() ||\n creatorFields.length === 0\n }\n onClick={handleCreate}\n >\n {'Create'}\n </Button>\n </DialogActions>\n </Dialog>\n {/*\n ONE viewer for the table, not one per row. Its record is a prop out of\n the page already in hand, so opening it reads nothing — and mounting\n the table does not open a dialog per row to discover that.\n */}\n <DatasetRecordDialog\n record={viewerRecord}\n model={model}\n resolveReference={resolveReferenceLabel}\n onClose={() => setViewerId(null)}\n // Explicitly separate, and a hand-off rather than a second editor:\n // the viewer closes and the record opens in the dialog that has\n // always owned writing.\n onEdit={() => {\n const record = viewerRecord\n setViewerId(null)\n if (record) handleOpenRecord(record)()\n }}\n />\n <Dialog\n open={Boolean(editor)}\n onClose={() => setEditor(null)}\n maxWidth=\"xs\"\n fullWidth\n >\n <DialogTitle>{editor?.id ? 'Edit record' : 'New record'}</DialogTitle>\n <DialogContent\n sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}\n >\n {editor?.sample ? <Alert severity=\"info\">{DATASET_SAMPLE_RECORD_NOTE}</Alert> : null}\n <DatasetRecordSiteContext.Provider value={recordSite}>\n {fields.map((fieldId, index) => {\n const field = model.fields[fieldId]\n if (!field) return null\n const value = editor?.values[fieldId] ?? ''\n const error = editor?.errors[fieldId]\n const label = field.required ? `${field.name} *` : field.name\n const setValue = (nextValue: string) =>\n setEditor((prev) =>\n prev\n ? {\n ...prev,\n values: { ...prev.values, [fieldId]: nextValue },\n errors: { ...prev.errors, [fieldId]: '' },\n }\n : prev,\n )\n const common = {\n label,\n value,\n size: 'small' as const,\n autoFocus: index === 0,\n error: Boolean(error),\n helperText: error || field.description,\n sx: index === 0 ? { mt: 1 } : undefined,\n onChange: (event: { target: { value: string } }) =>\n setValue(event.target.value),\n }\n // Custom field types (AGL-434): the declaring plugin's Input\n // takes over; values stay in input form (strings) so the\n // existing coerce/validate pipeline is unchanged.\n const customFieldType = getCustomFieldType(field.customType)\n if (customFieldType?.Input) {\n const CustomInput = customFieldType.Input\n return (\n <Stack key={fieldId} sx={index === 0 ? { mt: 1 } : undefined}>\n <CustomInput\n value={value}\n label={common.label}\n onChange={(next) => setValue(String(next ?? ''))}\n />\n {(error || field.description) ? (\n <Typography\n variant=\"caption\"\n color={error ? 'error' : 'text.secondary'}\n >\n {error || field.description}\n </Typography>\n ) : null}\n </Stack>\n )\n }\n // Typed inputs per FT.Tag (AGL-179).\n if (field.type === 'bool') {\n return (\n <TextField key={fieldId} {...common} select>\n <MenuItem value=\"\">{'—'}</MenuItem>\n <MenuItem value=\"true\">{'Yes'}</MenuItem>\n <MenuItem value=\"false\">{'No'}</MenuItem>\n </TextField>\n )\n }\n if (field.type === 'text' && field.validation?.options?.length) {\n return (\n <TextField key={fieldId} {...common} select>\n <MenuItem value=\"\">{'—'}</MenuItem>\n {field.validation.options.map((option) => (\n <MenuItem key={option} value={option}>\n {option}\n </MenuItem>\n ))}\n </TextField>\n )\n }\n if (field.type === 'reference') {\n const options = refOptions[fieldId] ?? []\n const multiple = Boolean(field.reference?.multiple)\n const selectedIds = value\n .split(',')\n .map((part) => part.trim())\n .filter(Boolean)\n return (\n <TextField\n key={fieldId}\n {...common}\n select\n value={multiple ? selectedIds : value}\n slotProps={{\n select: multiple\n ? {\n multiple: true,\n onChange: (event: any) =>\n setValue(\n (event.target.value as string[]).join(', '),\n ),\n }\n : undefined,\n }}\n >\n {multiple ? null : <MenuItem value=\"\">{'—'}</MenuItem>}\n {options.map((option) => (\n <MenuItem key={option.id} value={option.id}>\n {option.label}\n </MenuItem>\n ))}\n </TextField>\n )\n }\n if (\n field.type === 'int32' ||\n field.type === 'int64' ||\n field.type === 'float'\n ) {\n return <TextField key={fieldId} {...common} type=\"number\" />\n }\n if (field.type === 'timestamp') {\n return (\n <TextField\n key={fieldId}\n {...common}\n type=\"datetime-local\"\n slotProps={{ inputLabel: { shrink: true } }}\n />\n )\n }\n if (field.type === 'coordinates') {\n return (\n <TextField\n key={fieldId}\n {...common}\n helperText={error || field.description || 'lat, lon'}\n />\n )\n }\n if (field.type === 'sorted') {\n return (\n <TextField\n key={fieldId}\n {...common}\n helperText={\n error || field.description || 'Comma-separated list'\n }\n />\n )\n }\n return <TextField key={fieldId} {...common} />\n })}\n </DatasetRecordSiteContext.Provider>\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setEditor(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n onClick={handleSaveRecord}\n >\n {editor?.id ? 'Save' : 'Add'}\n </Button>\n </DialogActions>\n </Dialog>\n <Dialog\n open={Boolean(joiner)}\n onClose={() => setJoiner(null)}\n maxWidth=\"xs\"\n fullWidth\n >\n <DialogTitle>{'New join collection'}</DialogTitle>\n <DialogContent\n sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}\n >\n <Typography variant=\"body2\" color=\"text.secondary\" sx={{ mt: 1 }}>\n {'Links two collections many-to-many; each row pairs one ' +\n 'document from each side.'}\n </Typography>\n {(['a', 'b'] as const).map((side) => (\n <TextField\n key={side}\n select\n size=\"small\"\n label={side === 'a' ? 'First collection' : 'Second collection'}\n value={joiner?.[side] ?? ''}\n onChange={(event) =>\n setJoiner((prev) =>\n prev ? { ...prev, [side]: event.target.value } : prev,\n )\n }\n >\n {datasets.map((item) => (\n <MenuItem key={item.$id} value={item.$id}>\n {/* Who it is shared with only where two share a name (AGL-4047). */}\n {joinLabels[item.$id]}\n </MenuItem>\n ))}\n </TextField>\n ))}\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setJoiner(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={\n !scopeReady || !joiner?.a || !joiner?.b || joiner.a === joiner.b\n }\n onClick={handleCreateJoin}\n >\n {'Create'}\n </Button>\n </DialogActions>\n </Dialog>\n <DatasetSchemaDialog\n hostId={hostId}\n orgId={orgId ?? undefined}\n dataset={schemaOpen && selected ? selected : null}\n datasets={knownDatasets}\n // The dataset's documents, not the loaded window (AGL-1716) — the\n // dialog warns \"N documents exist\" before a narrowing type change,\n // and 500 was the cap talking, not the collection.\n recordCount={recordCount}\n seedFromCache={seed.fromCache}\n seedUnreadable={seed.unreadable}\n seedListen={seed.listen}\n canChangeSharing={!blocked.creates}\n {...(blocked.sharingOnly ? { sharingOnlyReason: blocked.writesReason } : {})}\n onClose={() => setSchemaOpen(false)}\n />\n </>\n )\n}\nHostDatasetsCard.displayName = 'HostDatasetsCard'\n\nexport default HostDatasetsCard\n"],"names":["TransferResumeImport","checkDatasetQuota","checkEntitlement","checkQuota","getCustomFieldType","PageHeaderActions","PageHeaderRecord","pluginDocsHelp","scopeTokensForHost","useTransferLauncher","visibleToHost","nameSearchKey","HubSections","AppLink","CardDisplay","MdiIcon","useConfirmationContext","mdiArrowLeft","ListFilterChips","ListPagination","ListQueryNotices","listQueryRefusals","ListTable","listActionsColumn","QuotaReadoutComponent","listFilterGridColumns","useListGridFilter","useSnackbar","Timestamp","Alert","Box","Button","Chip","Dialog","DialogActions","DialogContent","DialogTitle","MenuItem","Stack","TextField","Tooltip","Typography","collection","deleteDoc","deleteField","doc","documentId","endAt","getCountFromServer","getDoc","getDocs","limit","orderBy","query","startAt","where","setDoc","writeBatch","useRouter","useCallback","useEffect","useMemo","useState","useListColumnSort","useFirestore","useFirestoreCollection","useFirestoreDoc","useHostActivityLogger","useOrgDataScope","usePagedCollection","useScopeTokens","useUser","listQueryConstraints","authorizedFetch","DatasetSchemaDialog","DatasetRecordDialog","DatasetRecordFieldList","DatasetRecordSiteContext","datasetRecordFilter","planRecordQuery","recordColumn","coerceDocumentValues","datasetIntegrityUpdate","datasetValueToInput","effectiveDatasetModel","formatDatasetValue","modelFromFieldEntries","validateDocument","fillRecordAddresses","planReferenceFixups","referencingFieldIds","restrictedDeleteMessage","BlockedControl","datasetListScope","DATASETS_EXPORT_REFUSAL","DATASETS_VIEW_RECORDS_REFUSAL","DATASETS_WRITE_REFUSAL","useDatasetWritesBlocked","DATASET_SAMPLE_RECORD_NOTE","datasetDisplayName","isSampleDatasetRecord","parseDatasetFieldEntries","datasetTransferResourceKey","DATASET_RAIL_GROUP_AT","datasetCreatedLabel","datasetNameMatches","datasetPickerLabelsOf","datasetRailName","datasetRecordTitle","datasetRailSecondary","datasetSharingLabel","datasetSourceLabel","groupDatasetsBySharing","sortDatasetsByName","useOrgSites","NO_QUERY_SORTS","EXPORT_OFF_TOOLBAR","toolbar","csvOptions","disableToolbarButton","printOptions","NO_DATASETS","DATASET_LIST_WINDOW","DATASET_NAMES_ON_SERVER","datasetRow","snapshot","$id","id","data","newDatasetSharingNote","siteOnly","HostDatasetsCard","props","routeDatasetId","listed","hostId","basePath","segments","router","scope","dataScope","orgId","tokens","scopeTokens","orgWide","viewerOrgWide","loaded","scopeLoaded","pageHostId","undefined","reachScope","listScope","memberScope","scopeReady","Boolean","firestore","enqueueSnackbar","confirm","org","logActivity","user","createdFromHostId","createdFrom","recordSite","createsSiteOnly","defaultResourceScope","callDatasetApi","payload","response","method","headers","body","JSON","stringify","result","json","catch","ok","Error","error","announceRecords","datasetId","action","console","nameSearch","setNameSearch","sharedWith","setSharedWith","railWindow","setRailWindow","railScope","serverNameKey","hostNames","sites","orgSites","datasetDocs","status","datasetsStatus","fromCache","datasetsFromCache","listen","datasetsListen","idField","datasets","slice","moreDatasets","length","railDatasets","filter","item","railNarrowed","routeRecordId","selectedId","setSelectedId","wantedId","find","listAnswered","linkedRead","linked","notSharedHere","visibleTo","notFound","selected","seed","unreadable","openDataset","push","landing","replace","schemaOpen","setSchemaOpen","blocked","model","fields","order","recordFilter","gridFilter","selectFields","recordClauses","clauses","clause","some","field","column","recordPlan","searchWords","recordPlanKey","filters","plan","rows","records","hasMore","hasMoreRecords","page","recordPage","setPage","setRecordPage","pageSize","recordPageSize","setPageSize","setRecordPageSize","pageLimit","routeRecordRead","routeRecord","routeRecordMissing","recordRefusals","refused","options","filteringRecords","word","trim","datasetCountEpoch","setDatasetCountEpoch","recordCountEpoch","setRecordCountEpoch","serverDatasetCount","setServerDatasetCount","serverRecordCount","setServerRecordCount","active","then","count","countedDatasetId","datasetCount","recordCount","creator","setCreator","handleOpenCreator","variant","persist","quota","allowed","upgradeRequired","addonPriceUsd","name","creatorEntries","creatorFields","map","entry","handleCreate","displayName","String","message","epoch","type","joiner","setJoiner","handleCreateJoin","a","b","fieldFor","target","fieldId","required","reference","displayFieldId","onDelete","aRef","bRef","handleDeleteDataset","confirmed","title","description","toLocaleString","confirmationText","confirmationButtonProps","color","scopeId","kind","outsideTargets","setOutsideTargets","missing","Set","Promise","all","exists","knownDatasets","refOptions","setRefOptions","referenceFields","docs","docSnapshot","label","get","entries","Object","fromEntries","resolveReferenceLabel","option","referenceLabel","value","ids","Array","isArray","join","viewerId","setViewerId","datasetHref","openRecord","encodeURIComponent","viewerRecord","record","editor","setEditor","handleOpenRecord","values","default","errors","sample","handleSaveRecord","coerced","keys","prev","recordRef","updatedAt","now","mergeFields","handleDeleteRecord","afterDelete","alsoChanged","referencing","reach","other","otherModel","holders","start","updates","batch","update","holder","ref","commit","add","transfer","transferTarget","resource","known","importAllowed","writes","canImport","can","canExport","handleImport","dataset","openImport","onFinished","handleExport","openExport","search","recordGridColumns","shown","row","headerName","flex","minWidth","renderCell","direction","spacing","sx","alignItems","height","noWrap","size","justifyContent","onClick","reason","writesReason","width","recordPageSorts","recordSortHeaders","recordColumnSort","sorts","pageSorts","grouped","railSections","tab","group","href","secondary","flatMap","joinLabels","offerSharedWith","sitesByName","sort","localeCompare","railHeader","mb","fullWidth","placeholder","onChange","event","slotProps","htmlInput","select","site","railFooter","px","py","mt","window","facts","factsRow","pairs","useFlexGap","flexWrap","component","overflowWrap","recordTitle","recordPanel","help","anchor","header","startIcon","path","span","contentGutterX","contentGutterY","contentBordered","HeaderProps","subheader","severity","resolveReference","divided","panel","sharingOnly","exports","deletes","deletesReason","ready","used","noun","setClauses","notices","aria-label","pinActions","columnSort","columns","onOpen","hideFooter","filterMode","filterModel","onFilterModelChange","quickFilter","noRowsLabel","rowCount","onPageChange","onPageSizeChange","creates","keepHeading","parentTitle","parentHref","sections","navHeader","scrollRail","open","onClose","maxWidth","display","flexDirection","gap","autoFocus","helperText","disabled","onEdit","Provider","index","setValue","nextValue","common","customFieldType","customType","Input","CustomInput","next","validation","multiple","selectedIds","split","part","inputLabel","shrink","side","seedFromCache","seedUnreadable","seedListen","canChangeSharing","sharingOnlyReason"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAGA,SAASA,oBAAoB,QAAQ,gDAA+C;AACpF,SAEEC,iBAAiB,EACjBC,gBAAgB,EAChBC,UAAU,EACVC,kBAAkB,EAClBC,iBAAiB,EACjBC,gBAAgB,EAChBC,cAAc,EACdC,kBAAkB,EAClBC,mBAAmB,EACnBC,aAAa,QACR,eAAc;AACrB,SAASC,aAAa,QAAQ,qCAAoC;AAClE,SAASC,WAAW,QAAyB,4CAA2C;AACxF,SAASC,OAAO,EAAEC,WAAW,EAAEC,OAAO,EAAEC,sBAAsB,QAAQ,uBAAsB;AAC5F,SAASC,YAAY,QAAQ,yBAAwB;AACrD,OAAOC,qBAAqB,8DAA6D;AACzF,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,OAAOC,oBACLC,iBAAiB,QACZ,+DAA8D;AACrE,SACEC,SAAS,EACTC,iBAAiB,QACZ,uDAAsD;AAC7D,OAAOC,2BAA2B,0DAAyD;AAC3F,SAASC,qBAAqB,QAAQ,8CAA6C;AACnF,SAASC,iBAAiB,QAAQ,kDAAiD;AACnF,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,SAAS,QAAQ,+BAA8B;AACxD,SACEC,KAAK,EACLC,GAAG,EACHC,MAAM,EACNC,IAAI,EACJC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,QAAQ,EACRC,KAAK,EACLC,SAAS,EACTC,OAAO,EACPC,UAAU,QACL,gBAAe;AACtB,SACEC,UAAU,EACVC,SAAS,EACTC,WAAW,EACXC,GAAG,EACHC,UAAU,EACVC,KAAK,EACLC,kBAAkB,EAClB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AEA,gBAAAA,QAASQ;gBAChB8P,SAAS9K,cAAcP,WAAWA,WAAW;gBAC7CnB,UAAUqI;gBACV,kEAAkE;gBAClE,mEAAmE;gBACnE,mDAAmD;gBACnDpD,aAAaA;gBACbkQ,eAAe/T,KAAKzB,SAAS;gBAC7ByV,gBAAgBhU,KAAKC,UAAU;gBAC/BgU,YAAYjU,KAAKvB,MAAM;gBACvByV,kBAAkB,CAAC1T,QAAQoR,OAAO;eAC7BpR,QAAQ6P,WAAW,GAAG;gBAAE8D,mBAAmB3T,QAAQmM,YAAY;YAAC,IAAI,CAAC;gBAC1EyF,SAAS,IAAM7R,cAAc;;;;AAIrC;AACAnG,iBAAiByK,WAAW,GAAG;AAE/B,eAAezK,iBAAgB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/components/host-datasets-card.component.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport type { ScopePlaced } from '@aglyn/aglyn/app-utils/site-placement'\nimport { TransferResumeImport } from '@aglyn/aglyn/app-utils/transfer-resume-import'\nimport {\n type AglynOrgBilling,\n checkDatasetQuota,\n checkEntitlement,\n checkQuota,\n getCustomFieldType,\n PageHeaderActions,\n PageHeaderRecord,\n pluginDocsHelp,\n scopeTokensForHost,\n useTransferLauncher,\n visibleToHost,\n} from '@aglyn/aglyn'\nimport { nameSearchKey } from '@aglyn/aglyn/app-utils/name-search'\nimport { HubSections, type HubSection } from '@aglyn/shared-ui-next/components/hub-tabs'\nimport { AppLink, CardDisplay, MdiIcon, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { mdiArrowLeft } from '@aglyn/shared-data-mdi'\nimport ListFilterChips from '@aglyn/shared-ui-jsx/components/list-filter-chips.component'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport ListQueryNotices, {\n listQueryRefusals,\n} from '@aglyn/shared-ui-jsx/components/list-query-notices.component'\nimport {\n ListTable,\n listActionsColumn,\n} from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport QuotaReadoutComponent from '@aglyn/shared-ui-jsx/components/quota-readout.component'\nimport { listFilterGridColumns } from '@aglyn/shared-ui-jsx/const/list-grid-filter'\nimport { useListGridFilter } from '@aglyn/shared-ui-jsx/hooks/use-list-grid-filter'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { Timestamp } from '@aglyn/shared-util-timestamp'\nimport {\n Alert,\n Box,\n Button,\n Chip,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n MenuItem,\n Stack,\n TextField,\n Tooltip,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n deleteDoc,\n deleteField,\n doc,\n endAt,\n getCountFromServer,\n getDoc,\n getDocs,\n limit,\n orderBy,\n query,\n startAt,\n where,\n setDoc,\n writeBatch,\n} from 'firebase/firestore'\nimport { useRouter } from 'next/navigation'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { useListColumnSort } from '@aglyn/shared-ui-jsx/hooks/use-list-column-sort'\nimport {\n useFirestore,\n useFirestoreCollection,\n useFirestoreDoc,\n useHostActivityLogger,\n useOrgDataScope,\n usePagedCollection,\n useScopeTokens,\n useUser,\n} from '@aglyn/tenant-feature-instance'\nimport { listQueryConstraints } from '@aglyn/tenant-feature-instance/hooks/use-list-query'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport { DatasetSchemaDialog } from './dataset-schema-dialog.component'\nimport { DatasetRecordDialog, DatasetRecordFieldList } from './dataset-record-dialog.component'\nimport { DatasetRecordSiteContext } from './dataset-field-inputs.component'\nimport {\n datasetRecordFilter,\n planRecordQuery,\n recordColumn,\n} from './dataset-record-filter'\nimport { coerceDocumentValues, datasetIntegrityUpdate, datasetValueToInput, effectiveDatasetModel, formatDatasetValue, modelFromFieldEntries, validateDocument } from '../model/dataset-models'\nimport { fillRecordAddresses } from '../record-pages/record-pages'\nimport { planReferenceFixups, referencingFieldIds, restrictedDeleteMessage } from '../model/dataset-record-delete-plan'\nimport { BlockedControl } from '@aglyn/shared-ui-jsx/components/blocked-control.component'\nimport { datasetListScope } from '../model/dataset-record-list'\nimport {\n DATASETS_EXPORT_REFUSAL,\n DATASETS_VIEW_RECORDS_REFUSAL,\n DATASETS_WRITE_REFUSAL,\n useDatasetWritesBlocked,\n} from './use-dataset-writes-blocked'\nimport { DATASET_SAMPLE_RECORD_NOTE, datasetDisplayName, isSampleDatasetRecord, parseDatasetFieldEntries } from '../model/datasets'\nimport { datasetTransferResourceKey } from '../transfer/dataset-transfer-key'\nimport {\n DATASET_RAIL_GROUP_AT,\n type DatasetRailEntry,\n datasetCreatedLabel,\n datasetPickerLabelsOf,\n datasetRailName,\n datasetRecordTitle,\n datasetRailSecondary,\n datasetSharingLabel,\n datasetSourceLabel,\n groupDatasetsBySharing,\n sortDatasetsByName,\n} from '../model/dataset-rail'\nimport { useOrgSites } from './use-org-sites'\n\nexport interface HostDatasetsCardProps {\n /** Host context: resolves the owning org and logs host activity. */\n hostId?: string\n /**\n * Direct org scope (AGL-239): the org Data page renders the editor\n * without any host context. Wins over `hostId` resolution when set.\n */\n orgId?: string\n /**\n * The resolved entitlement source (org billing doc). Passed in by both\n * callers (the plugin Data page via the shell, the org Data page via its\n * own resolver) so this relocated card runs entitlement/quota checks\n * without console-app org/session hooks (AGL-395).\n */\n org?: Partial<AglynOrgBilling>\n /**\n * The Data page's own address (AGL-4047): each dataset is a tab of the\n * page's rail, at `<basePath>/<datasetId>`. Handed down by both callers —\n * the site's plugin route and the organization Data page.\n */\n basePath?: string\n /**\n * The path beneath {@link basePath}: `[datasetId]` on a dataset's tab,\n * `[datasetId, 'records', recordId]` on one of its records, and empty on the\n * bare page, which opens the first dataset.\n */\n segments?: readonly string[]\n}\n\n/**\n * The sentence that says who a NEW dataset is shared with, for the card and\n * for the site Data page's banner above it.\n *\n * `siteOnly` is true only on a site's Data page in an org whose Default\n * sharing is \"Only the site they were created in\". Everywhere else a new\n * dataset starts on All sites: the org Data page has no site to limit it to.\n */\n/** The records walk serves no header order: every header sorts the page. */\nconst NO_QUERY_SORTS: never[] = []\n\n/** The grid's own Export and Print, off for a member without \"Export data\" (AGL-4047). */\nconst EXPORT_OFF_TOOLBAR = {\n toolbar: { csvOptions: { disableToolbarButton: true }, printOptions: { disableToolbarButton: true } },\n}\n\n/** Stable, so an empty answer does not re-render the card. */\nconst NO_DATASETS: any[] = []\n\n/**\n * The datasets the rail loads at a time, and the most a delete's reference\n * check walks. \"Show more datasets\" loads the next window, so the rail\n * reaches every dataset however many there are (AGL-4047).\n */\nconst DATASET_LIST_WINDOW = 100\n\n/** A dataset read off its document, as the card's rows carry it. */\nconst datasetRow = (snapshot: { id: string; data(): unknown }) => ({\n $id: snapshot.id,\n ...(snapshot.data() as object),\n})\n\nexport function newDatasetSharingNote(siteOnly: boolean): string {\n return siteOnly\n ? 'Datasets belong to your organization. Your default sharing starts a ' +\n 'new one on this site only — use Schema to share it with more.'\n : 'Datasets belong to your organization. A new one is shared with ' +\n 'every site — use Schema to narrow that.'\n}\n\n/**\n * Datasets editor (AGL-102): org-shared document collections at\n * `orgs/{orgId}/datasets` (AGL-237/239) with a `records` subcollection,\n * consumed by repeatable components (AGL-103) via `{{item.field}}`.\n * Starter+ (`data-store` flag) with per-plan dataset and record caps —\n * dark-launch rule as everywhere (no plan, no gate). The host path is\n * the pre-migration fallback for hosts not yet org-wired.\n */\nexport function HostDatasetsCard(props: HostDatasetsCardProps) {\n const { hostId, basePath, segments } = props\n const router = useRouter()\n // `dataScope` is null until the async org lookup settles (AGL-1061), and\n // for a host with no owning org — there is no host fallback to act on\n // any more (AGL-1050), so every path built from it is guarded rather\n // than redirected.\n const { scope: dataScope, orgId } = useOrgDataScope({\n hostId,\n orgId: props.orgId,\n })\n // Scoped sharing (AGL-1044). Required, not cosmetic: under the AGL-1041\n // rules a scoped member's UNFILTERED list is rejected outright —\n // Firestore fails the whole query if any candidate would fail — so\n // without this the Data page errors rather than showing fewer rows.\n const {\n tokens: scopeTokens,\n orgWide: viewerOrgWide,\n loaded: scopeLoaded,\n } = useScopeTokens(orgId)\n /**\n * The site whose Data page this is, or undefined on the organization Data\n * page. The explicit `orgId` is that page's own scope and already wins over\n * `hostId` when the org is resolved, so it wins here too, even if a caller\n * hands the card both.\n */\n const pageHostId = props.orgId ? undefined : hostId || undefined\n // What the VIEWER reaches: their scope tokens, or no filter for an org-wide\n // member, who reads everything. Every dataset here is an org dataset, and\n // org datasets are all scoped (AGL-1041).\n const reachScope = viewerOrgWide ? null : scopeTokens\n /**\n * What this page lists (AGL-4047): a site's Data page shows that site's and\n * the workspace-wide datasets, whoever is looking, as every other site\n * surface does. It used to ask only the viewer's reach, so an owner, who\n * reaches everything, saw every site's datasets on every site. The\n * organization Data page lists the viewer's reach.\n */\n const listScope = useMemo(\n () => datasetListScope({ hostId: pageHostId, memberScope: reachScope }),\n [pageHostId, reachScope],\n )\n // Two answers must be in before listing: the org path (AGL-1061) and the\n // viewer's scope tokens (AGL-1047). `useScopeTokens` reports org-wide\n // while loading, so without `scopeLoaded` a scoped collaborator's first\n // render sends an UNFILTERED list that the AGL-1041 rules deny per\n // document. It recovers on the next render, which is exactly what makes\n // it easy to miss: the page looks right and logs a denial every mount.\n const scopeReady = Boolean(dataScope) && scopeLoaded\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n const { org } = props\n const logActivity = useHostActivityLogger(hostId)\n const { data: user } = useUser()\n /**\n * The site a dataset created here is created FROM, or undefined on the\n * organization Data page.\n *\n * `/api/orgs/datasets` stamps a new dataset with the org's Default sharing,\n * and that setting can only narrow to a site the request names — so a\n * create that names none lands on All sites whatever the org chose.\n */\n const createdFromHostId = pageHostId\n const createdFrom = useMemo(\n () => (createdFromHostId ? { hostId: createdFromHostId } : {}),\n [createdFromHostId],\n )\n /**\n * The site the record editor's Page field lists pages from (AGL-3763): the\n * site whose Data page this is, and none on the organization Data page,\n * where a dataset is no one site's.\n */\n const recordSite = useMemo(\n () => ({ hostId: createdFromHostId }),\n [createdFromHostId],\n )\n /**\n * Whether a dataset created here starts on this site alone: the org chose\n * \"Only the site they were created in\" and there is a site to limit it to.\n * The caption reads it so it never promises All sites to a create that\n * will not get it.\n */\n const createsSiteOnly =\n Boolean(createdFromHostId) &&\n (org as { defaultResourceScope?: 'org' | 'host' } | undefined)\n ?.defaultResourceScope === 'host'\n\n // Creates go through the console API (AGL-473): rules deny client-side\n // `create` on org datasets/records so quotas are server-enforced.\n // Updates/deletes stay client-direct (they don't consume quota). The\n // legacy host scope (no org resolved) keeps the old client writes.\n const callDatasetApi = useCallback(\n async (payload: Record<string, unknown>) => {\n const response = await authorizedFetch(user, '/api/orgs/datasets', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ orgId, ...payload }),\n })\n const result = await response.json().catch(() => ({}))\n if (!response.ok) {\n throw new Error(result?.error ?? 'Dataset operation failed')\n }\n return result\n },\n [user, orgId],\n )\n\n /**\n * Refresh the live pages showing a dataset after a write the BROWSER made\n * (AGL-3113).\n *\n * Record edits and deletes are client-direct — they consume no quota, so\n * AGL-473 left them out of the server leg — which also left them with\n * nothing to announce from. They make a page listing the rows exactly as\n * stale as a create does, so they take the same trip the create already\n * takes, through the route that already holds the org membership check.\n *\n * BEST EFFORT. The record is stored by the time this runs, and the pages\n * catch up on their own window regardless; a refused cache must never be\n * shown to somebody as a refused save.\n */\n const announceRecords = useCallback(\n async (datasetId: string) => {\n try {\n await callDatasetApi({ action: 'announce-records', datasetId })\n } catch (error) {\n console.error(error)\n }\n },\n [callDatasetApi],\n )\n\n /**\n * The rail's search and its Shared with filter (AGL-4047).\n *\n * The filter is a query clause: one site the reader reaches, asked by that\n * site's scope tokens in place of the page's own, which they sit inside —\n * a site the reader is a member of is one their own tokens already reach,\n * so the narrower query is still one the rules can prove. Offered on the\n * organization Data page only: a site's page already lists that site's.\n */\n const [nameSearch, setNameSearch] = useState('')\n const [sharedWith, setSharedWith] = useState('')\n const [railWindow, setRailWindow] = useState(DATASET_LIST_WINDOW)\n const railScope = useMemo(\n () => (sharedWith && !pageHostId ? scopeTokensForHost(sharedWith) : listScope),\n [sharedWith, pageHostId, listScope],\n )\n /** The search as the stored `nameLower` is normalized, asked of the server as a prefix. */\n const serverNameKey = nameSearchKey(nameSearch)\n const { hostNames, sites: orgSites } = useOrgSites(orgId)\n\n const {\n data: datasetDocs,\n status: datasetsStatus,\n /**\n * The dataset rows are unconfirmed by the server (AGL-1358). The schema\n * dialog is seeded from one of them and writes the whole `model` plus\n * `visibleTo` back, so the freshness verdict belongs to THIS listener —\n * the dialog has none of its own, which is why it is handed down rather\n * than recomputed there.\n */\n fromCache: datasetsFromCache,\n listen: datasetsListen,\n } = useFirestoreCollection<any>(\n () =>\n // `scopeReady` already implies a non-null `dataScope`; testing it\n // directly is what lets the compiler see that too.\n dataScope && scopeReady\n ? query(\n collection(firestore, dataScope[0], dataScope[1], 'datasets'),\n ...(railScope\n ? [where('visibleTo', 'array-contains-any', [...railScope])]\n : []),\n /*\n * The rail in name order, and the search as a `nameLower` prefix\n * asked of the server, so it finds a dataset past the loaded\n * window (AGL-4047). Served by the `datasets (visibleTo CONTAINS,\n * nameLower ASC)` index beside the scope clause. Ordering on a\n * field leaves out a document that lacks it, so every writer\n * stamps `nameLower` through `datasetNameLower`, and\n * `tools/scripts/backfill-dataset-name-lower.mjs` stamped the\n * datasets saved before. One row past the window says whether\n * there are more.\n */\n orderBy('nameLower'),\n ...(serverNameKey ? [startAt(serverNameKey), endAt(`${serverNameKey}\\uf8ff`)] : []),\n limit(railWindow + 1),\n )\n : null,\n [firestore, dataScope, railScope, scopeReady, railWindow, serverNameKey],\n { idField: '$id' },\n )\n /** The loaded window in name order: what the join dialog and the reference checks read. */\n const datasets = useMemo(\n () => sortDatasetsByName<any>([...(datasetDocs ?? [])].slice(0, railWindow)),\n [datasetDocs, railWindow],\n )\n const moreDatasets = (datasetDocs?.length ?? 0) > railWindow\n /**\n * Whether the loaded window is short of everything this page lists: a\n * filter or the name search narrowed it, or there are more. A check that\n * must see every dataset — what references a record about to be deleted —\n * reads for itself then.\n */\n const railNarrowed =\n Boolean(pageHostId) || Boolean(sharedWith) || Boolean(serverNameKey) || moreDatasets\n\n /**\n * The open dataset (AGL-4047): the one the address names, or, on the bare\n * page, none until the page moves to the first. The card is also mounted\n * without an address by callers outside the console's routes, which pick\n * one by state.\n */\n const routeDatasetId = basePath ? segments?.[0] : undefined\n /** The record the address opens on its own page (AGL-4047), beneath its dataset's tab. */\n const routeRecordId = basePath && segments?.[1] === 'records' ? segments?.[2] : undefined\n const [selectedId, setSelectedId] = useState<string | null>(null)\n const wantedId = routeDatasetId ?? selectedId ?? undefined\n const listed = wantedId ? datasets.find((item) => item.$id === wantedId) : undefined\n const listAnswered = datasetDocs !== undefined\n /*\n * A dataset the address names that the loaded window does not hold — past\n * the window, outside the filter, or only just created — is read on its\n * own, live, so its tab still opens and a save still seeds from a listener.\n */\n const linkedRead = useFirestoreDoc<any>(\n () =>\n dataScope && scopeReady && wantedId && listAnswered && !listed\n ? doc(firestore, dataScope[0], dataScope[1], 'datasets', wantedId)\n : null,\n [firestore, dataScope, scopeReady, wantedId, listAnswered, Boolean(listed)],\n )\n // Keyed by the id it was read under, as the list's rows are.\n const linked = useMemo(\n () => (!listed && wantedId && linkedRead.data ? { ...linkedRead.data, $id: wantedId } : undefined),\n [listed, wantedId, linkedRead.data],\n )\n /** A site's page refuses a dataset that is not shared with the site (#2341). */\n const notSharedHere = Boolean(\n pageHostId && linked && !visibleToHost((linked as { visibleTo?: string[] }).visibleTo, pageHostId),\n )\n const notFound = Boolean(\n wantedId &&\n listAnswered &&\n !listed &&\n !linked &&\n (linkedRead.status === 'error' || (linkedRead.status !== 'loading' && !linkedRead.fromCache)),\n )\n const selected =\n listed ??\n (linked && !notSharedHere ? linked : undefined) ??\n (wantedId ? undefined : datasets[0])\n /** Which listener the open dataset came from, for the schema dialog's freshness guard. */\n const seed = listed || !linked\n ? { fromCache: datasetsFromCache, unreadable: datasetsStatus === 'error', listen: datasetsListen }\n : { fromCache: linkedRead.fromCache, unreadable: linkedRead.status === 'error', listen: linkedRead.listen }\n /** Opens a dataset: its own address on a routed page, the card's state elsewhere. */\n const openDataset = useCallback(\n (id: string | null) => {\n if (basePath) router.push(id ? `${basePath}/${id}` : basePath)\n else setSelectedId(id)\n },\n [basePath, router],\n )\n // The bare page opens the first dataset, as a hub opens its first section,\n // so the rail always has a tab lit and the address names what is open.\n const landing = basePath && !routeDatasetId && datasets[0] ? `${basePath}/${datasets[0].$id}` : null\n useEffect(() => {\n if (landing) router.replace(landing)\n }, [landing, router])\n const [schemaOpen, setSchemaOpen] = useState(false)\n // What this member may do with THIS dataset (AGL-4047): one placed on one site\n // answers to that site.\n const blocked = useDatasetWritesBlocked(orgId, selected as ScopePlaced | undefined)\n // Typed model (AGL-179): drives headers, cell rendering, and the\n // document form; v1 datasets get a derived all-text model.\n const model = useMemo(\n () => effectiveDatasetModel(selected ?? {}),\n [selected],\n )\n const fields: string[] = useMemo(() => model.order, [model])\n // The records grid's Filters panel, from the dataset's own schema.\n const recordFilter = useMemo(() => datasetRecordFilter(model), [model])\n\n // Guarded on BOTH the scope and a real selection (AGL-1440): with no\n // datasets, `selected` never resolves, and `datasets/-none-/records` is not\n // an empty read for everyone — the AGL-1044 scoped-sharing rules deny it\n // outright for a scoped collaborator, and a permanently denied listen is\n // reopened forever by the refusal loop.\n /**\n * The records table PAGES (AGL-2501). It used to be `limit(500)` with no\n * `orderBy`, every row rendered at once and no control anywhere.\n *\n * That was wrong twice. Five hundred documents were read and billed on\n * every mount of a card nobody had scrolled — and past five hundred the\n * remaining rows were not merely unrendered, they were UNREACHABLE, because\n * nothing showed them and nothing asked for more. Firestore answers an\n * unordered limit in document-id order over auto-ids, so which five hundred\n * a reader got was arbitrary and could differ between two loads of the same\n * dataset; `sortDatasetRecords` then sorted that sample by `order`, which\n * made the table look ordered while being a sample. The export leg\n * (AGL-2335) fixed exactly this shape for the file and left the table.\n *\n * ## Why the walk orders on the document id, and not on a field\n *\n * The usual fix is `orderBy` on the field the rows are sorted by. It cannot\n * be used here: `orderBy` matches only documents that HAVE the field, so\n * ordering on one that any writer omits does not mis-order the list, it\n * hides rows from it — a worse failure than the one being fixed, and a\n * silent one. Every candidate on this collection is omitted by some writer:\n *\n * * `order` — set by `/api/orgs/datasets` and by `POST /v1/datasets/{id}\n * /records`, and NOT by the tenant form-submit leg or by the workflow\n * `appendDataset`/`updateDataset` actions, which write `values` and\n * `createdAt` only. Ordering on it would drop every row a public form or\n * an automation ever produced — the rows a lead dataset is mostly made\n * of.\n * * `createdAt` — written by all four of those, and NOT by a site import:\n * `IMPORTABLE_FIELDS.records` is `['values', 'order']`, so a restored\n * record carries no `createdAt` at all.\n * * `updatedAt` — the mirror image: the import stamps it, the form and\n * automation legs do not.\n *\n * A document's NAME is not a field and cannot be absent, so ordering on it\n * drops nothing and the walk is total: every record is reachable by paging,\n * which is the property the old query lacked. It is not insertion order —\n * ids are random — so the rows are not claimed to be in one. What they are\n * is stable, complete, and the same on every load.\n *\n * `sortDatasetRecords` is deliberately NOT applied to the page. Re-sorting a\n * window of an id-ordered walk by `order` is the same lie the old code told:\n * rows would run in one order within a page and another across pages.\n * For the same reason a header sorts THIS PAGE only, and says so\n * (AGL-3680, `recordColumnSort` below): no stored field could serve it.\n *\n * ## Filtering: every clause and the search word are on the query\n *\n * The grid's Filters panel and quick search are predicates on this same\n * walk (AGL-3321), planned by `planRecordQuery` (`./dataset-record-filter`,\n * over the shared `planListQuery`): equalities ask the record's\n * `filterValues`, and one word-level clause — a text `contains`, a list\n * member, or the search word — asks its `filterKeys`. Firestore's\n * automatic single-field indexes merge them under the same document-name\n * order, so every filter pages through every matching record exactly as\n * the plain walk pages through all of them, with no composite index and\n * no index deploy.\n *\n * Nothing is matched over the rows already loaded. What one query cannot\n * hold is not offered (ranges, negations, empty checks) or is refused by\n * name above the table (a second `contains`, a `contains` beside the\n * search), and a many-word `contains` or search says it asked the first\n * word.\n */\n const gridFilter = useListGridFilter({ selectFields: recordFilter.selectFields })\n // A clause on a field this dataset does not have (the reader switched\n // datasets) narrows nothing and is not shown.\n const recordClauses = useMemo(\n () =>\n gridFilter.clauses.filter((clause) =>\n recordFilter.fields.some((field) => field.column === clause.field),\n ),\n [gridFilter.clauses, recordFilter.fields],\n )\n const recordPlan = useMemo(\n () => planRecordQuery(model, recordFilter, recordClauses, gridFilter.searchWords),\n [model, recordFilter, recordClauses, gridFilter.searchWords],\n )\n // The query's identity: a new plan is a new walk, from page one.\n const recordPlanKey = JSON.stringify({\n filters: recordPlan.plan.filters,\n orderBy: recordPlan.plan.orderBy,\n })\n const {\n rows: records,\n hasMore: hasMoreRecords,\n page: recordPage,\n setPage: setRecordPage,\n pageSize: recordPageSize,\n setPageSize: setRecordPageSize,\n } = usePagedCollection<any>(\n (pageLimit) =>\n // A record's own page shows no table, so it reads none (AGL-4047).\n dataScope && selected?.$id && !blocked.records && !routeRecordId\n ? query(\n collection(\n firestore,\n dataScope[0],\n dataScope[1],\n 'datasets',\n selected.$id,\n 'records',\n ),\n ...listQueryConstraints(recordPlan.plan),\n limit(pageLimit),\n )\n : null,\n [firestore, dataScope, selected?.$id, recordPlanKey, blocked.records, routeRecordId],\n { idField: '$id' },\n )\n /**\n * The record a record's own page opens (AGL-4047), read on its own and live,\n * so a deep link to a record on no loaded page still opens and an edit shows\n * as soon as it lands. Asked only of a member who may view the records.\n */\n const routeRecordRead = useFirestoreDoc<any>(\n () =>\n dataScope && selected?.$id && routeRecordId && !blocked.records\n ? doc(firestore, dataScope[0], dataScope[1], 'datasets', selected.$id, 'records', routeRecordId)\n : null,\n [firestore, dataScope, selected?.$id, routeRecordId, blocked.records],\n )\n // Keyed by the id it was read under, as the table's rows are.\n const routeRecord = useMemo(\n () => (routeRecordId && routeRecordRead.data ? { ...routeRecordRead.data, $id: routeRecordId } : null),\n [routeRecordId, routeRecordRead.data],\n )\n const routeRecordMissing = Boolean(\n routeRecordId &&\n !routeRecord &&\n (routeRecordRead.status === 'error' || (routeRecordRead.status !== 'loading' && !routeRecordRead.fromCache)),\n )\n const recordRefusals = useMemo(\n () =>\n listQueryRefusals(recordPlan.refused, {\n fields: recordFilter.fields,\n headers: recordFilter.headers,\n options: recordFilter.options,\n }),\n [recordPlan.refused, recordFilter],\n )\n const filteringRecords =\n recordClauses.length > 0 || gridFilter.searchWords.some((word) => word.trim())\n /**\n * The two HEAD-COUNTS on this card are server aggregates, not the lengths\n * of the two capped listeners above (AGL-1716, the AGL-1706 shape).\n *\n * Both listeners are capped correctly — 100 datasets in a picker, 500 rows\n * in a table, nobody needs more streamed in. What neither may do is answer\n * \"how many does this org have\", and both did:\n *\n * * `records.length` saturated at 500 and was handed to\n * `checkQuota(org, 'recordsPerDataset', …)`. The bands are 1,000 /\n * 10,000 / 100,000 / 500,000 / 1,000,000, so on EVERY paid plan the\n * check read 500-against-thousands and could never refuse. Worse, the\n * importer computed its room as `limit − records.length`, so an\n * understated count *inflated* the slots it offered.\n * * `datasets.length` saturated at 100 and fed `checkDatasetQuota`, whose\n * bands run to 250 / 500 / 2,000 above that window.\n *\n * `api/orgs/datasets` — the route that actually enforces both — counts with\n * `collection('datasets').count()` and `collection('records').count()` on\n * these exact paths, so this card was offering headroom the API would then\n * refuse. It now asks the same question the same way, and the console\n * billing page and the staff org page already read the dataset count with\n * this identical unscoped aggregate.\n *\n * THE LISTS KEEP THEIR CAPS. The list and the count are different\n * questions; only the count moved. A one-shot goes stale where a listener\n * refreshed for free, so both are re-read after any mutation that can move\n * them — the epochs below.\n *\n * No counting RULE moves: `checkQuota` and `checkDatasetQuota` are\n * untouched entitlement inputs, and nothing here is metered by\n * `report-usage` (it samples record counts server-side for storage, on its\n * own read). Only this card's inputs stopped being saturated.\n */\n const [datasetCountEpoch, setDatasetCountEpoch] = useState(0)\n const [recordCountEpoch, setRecordCountEpoch] = useState(0)\n const [serverDatasetCount, setServerDatasetCount] = useState<number | null>(\n null,\n )\n // TAGGED with the dataset it describes. A bare number would have to be\n // cleared when the selection changes, and clearing state from inside the\n // effect that fills it is a render loop waiting for one unstable dep;\n // tagging answers \"whose count is this?\" without writing state on render.\n const [serverRecordCount, setServerRecordCount] = useState<{\n datasetId: string\n count: number\n } | null>(null)\n useEffect(() => {\n if (!dataScope) return\n let active = true\n // Unscoped, exactly like `api/orgs/datasets` and the billing page: the\n // quota is about the ORG's datasets, not the subset this collaborator\n // can see. A scoped collaborator whom AGL-1044 denies the read falls\n // through to the catch and keeps the visible-rows lower bound.\n void getCountFromServer(\n collection(firestore, dataScope[0], dataScope[1], 'datasets'),\n )\n .then((snapshot) => {\n if (active) setServerDatasetCount(snapshot.data().count)\n })\n .catch(() => {\n // Falls back to the listener length below — a LOWER bound, and this\n // card's prior behaviour. Deliberately not 0: `checkDatasetQuota`\n // answers from whatever it is handed, and 0 used is a confident\n // wrong number in the flattering direction.\n })\n return () => {\n active = false\n }\n }, [firestore, dataScope, datasetCountEpoch])\n // The dataset the counts below belong to. Distinct from `selectedId`\n // above, which is the PICKER value and is null until the user chooses.\n const countedDatasetId: string | undefined = selected?.$id\n useEffect(() => {\n if (!dataScope || !countedDatasetId || blocked.records) return\n let active = true\n void getCountFromServer(\n collection(\n firestore,\n dataScope[0],\n dataScope[1],\n 'datasets',\n countedDatasetId,\n 'records',\n ),\n )\n .then((snapshot) => {\n if (active) {\n setServerRecordCount({\n datasetId: countedDatasetId,\n count: snapshot.data().count,\n })\n }\n })\n .catch(() => {\n // Same fallback, same reason as above.\n })\n return () => {\n active = false\n }\n }, [firestore, dataScope, countedDatasetId, recordCountEpoch, blocked.records])\n // Pending, denied, or answered about the PREVIOUS selection, the loaded\n // rows stand in. They can only UNDERSTATE (same collections, capped),\n // never overstate, so nothing these figures gate fires on a count larger\n // than the truth. Since AGL-2501 the record fallback is one PAGE, so it\n // understates by more — which moves it further in the safe direction and\n // changes nothing about which way it can be wrong.\n const datasetCount = serverDatasetCount ?? datasets.length\n const recordCount =\n serverRecordCount && serverRecordCount.datasetId === countedDatasetId\n ? serverRecordCount.count\n : records.length\n\n // --- Create dataset -----------------------------------------------------\n const [creator, setCreator] = useState<{\n name: string\n fields: string\n } | null>(null)\n const handleOpenCreator = useCallback(() => {\n if (!checkEntitlement(org, 'dataStore')) {\n return enqueueSnackbar(\n 'Datasets require a Starter plan or higher — see Billing',\n { variant: 'warning', persist: false },\n )\n }\n // Addon-aware quota (AGL-132): purchased extra datasets raise the\n // limit up to the plan's hard max; beyond that only an upgrade helps.\n // The ORG's datasets, not the picker's window (AGL-1716).\n const quota = checkDatasetQuota(org as any, datasetCount)\n if (!quota.allowed) {\n return enqueueSnackbar(\n quota.upgradeRequired\n ? `Dataset limit reached (${quota.limit}) — upgrade in Billing`\n : `Dataset limit reached (${quota.limit}) — add extra datasets ` +\n `for $${quota.addonPriceUsd}/mo each or upgrade in Billing`,\n { variant: 'warning', persist: false },\n )\n }\n setCreator({ name: '', fields: '' })\n }, [org, datasetCount, enqueueSnackbar])\n // Entries are human names — \"Roast preference\" → stable id\n // `roast_preference` with the pretty name kept for headers (AGL-558).\n const creatorEntries = parseDatasetFieldEntries(creator?.fields ?? '')\n const creatorFields = creatorEntries.map((entry) => entry.id)\n const handleCreate = useCallback(async () => {\n // No org, no create. The `else` that used to sit below this was the\n // legacy host-scope client write (AGL-1050) — the one path by which a\n // dataset could be created with NO quota check, since /api/orgs/datasets\n // is where AGL-473 enforces it. The rules now deny that path outright;\n // this is the client side of the same closure. The Add button is\n // disabled without a scope, so reaching the guard means a stale closure.\n if (!creator?.name.trim() || creatorFields.length === 0 || !orgId) return\n let id: string\n try {\n const result = await callDatasetApi({\n action: 'create-dataset',\n displayName: creator.name.trim(),\n fields: creatorFields,\n // Typed model from day one (AGL-178); refine in the Schema dialog.\n model: modelFromFieldEntries(creatorEntries),\n ...createdFrom,\n })\n id = String(result.id)\n } catch (error: any) {\n return void enqueueSnackbar(error?.message ?? 'Dataset create failed', {\n variant: 'warning',\n persist: false,\n })\n }\n setCreator(null)\n openDataset(id)\n setDatasetCountEpoch((epoch) => epoch + 1)\n enqueueSnackbar(`Dataset \"${creator.name.trim()}\" created`, {\n variant: 'success',\n persist: false,\n })\n logActivity('Created dataset', {\n type: 'content',\n id,\n name: creator.name.trim(),\n })\n }, [creator, creatorEntries, creatorFields, orgId, createdFrom, callDatasetApi, enqueueSnackbar, logActivity, openDataset])\n\n // Join collection template (AGL-180): extrinsic many-to-many as a\n // visible, editable collection of FKey pairs — no magic.\n const [joiner, setJoiner] = useState<{ a: string; b: string } | null>(null)\n const handleCreateJoin = useCallback(async () => {\n if (!joiner?.a || !joiner?.b || joiner.a === joiner.b) return\n const a = datasets.find((item) => item.$id === joiner.a)\n const b = datasets.find((item) => item.$id === joiner.b)\n // A join collection is a dataset and consumes the same quota, so it\n // takes the same API-only route (AGL-1050) — the host-scope client\n // write that used to stand in for it is gone.\n if (!a || !b || !orgId) return\n const fieldFor = (target: any, fieldId: string) => ({\n name: datasetDisplayName(target) || fieldId,\n type: 'reference' as const,\n required: true,\n reference: {\n datasetId: target.$id as string,\n displayFieldId: effectiveDatasetModel(target).order[0],\n onDelete: 'setNull' as const,\n },\n })\n const payload = {\n displayName: `${datasetDisplayName(a)} ↔ ${datasetDisplayName(b)}`,\n fields: ['aRef', 'bRef'],\n model: {\n order: ['aRef', 'bRef'],\n fields: { aRef: fieldFor(a, 'aRef'), bRef: fieldFor(b, 'bRef') },\n },\n }\n let id: string\n try {\n const result = await callDatasetApi({\n action: 'create-dataset',\n ...payload,\n // A join collection is a dataset, so the same Default sharing applies.\n ...createdFrom,\n })\n id = String(result.id)\n } catch (error: any) {\n return void enqueueSnackbar(error?.message ?? 'Join create failed', {\n variant: 'warning',\n persist: false,\n })\n }\n setJoiner(null)\n openDataset(id)\n // A join collection IS a dataset and consumes the same quota.\n setDatasetCountEpoch((epoch) => epoch + 1)\n enqueueSnackbar('Join collection created', {\n variant: 'success',\n persist: false,\n })\n }, [joiner, datasets, orgId, createdFrom, callDatasetApi, enqueueSnackbar, openDataset])\n\n const handleDeleteDataset = useCallback(async () => {\n if (!selected) return\n const confirmed = await confirm({\n title: 'Delete this dataset?',\n description:\n `\"${datasetDisplayName(selected)}\"` +\n // What is actually being destroyed, not what is loaded (AGL-1716):\n // a 40,000-row dataset used to warn about \"its 500 documents\".\n (recordCount\n ? ` and its ${recordCount.toLocaleString()} record${recordCount === 1 ? '' : 's'}`\n : '') +\n ' will be deleted. Repeatable components and bindings that use it ' +\n 'stop showing its data.',\n confirmationText: 'Delete',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed || !dataScope) return\n // Deleting the dataset doc client-side would strand its `records`\n // subcollection — Firestore doesn't cascade and only the Admin SDK has\n // `recursiveDelete`, so the delete goes through the erase route\n // (AGL-945). Single-record deletes below stay client-direct.\n try {\n const response = await authorizedFetch(user, '/api/resources/erase', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n scope: dataScope[0],\n scopeId: dataScope[1],\n kind: 'datasets',\n id: selected.$id,\n // Names the site this delete was issued from, so the route can\n // refuse to destroy a dataset shared beyond it (AGL-1046). The\n // org Data page passes no host and keeps the org-wide delete.\n hostId,\n }),\n })\n const result = await response.json().catch(() => ({}))\n if (!response.ok) throw new Error(result?.error ?? 'Dataset delete failed')\n } catch (error: any) {\n return void enqueueSnackbar(error?.message ?? 'Dataset delete failed', {\n variant: 'warning',\n persist: false,\n })\n }\n openDataset(null)\n setDatasetCountEpoch((epoch) => epoch + 1)\n enqueueSnackbar('Dataset deleted', { variant: 'success', persist: false })\n logActivity('Deleted dataset', {\n type: 'content',\n id: selected.$id,\n name: datasetDisplayName(selected),\n })\n }, [\n selected,\n recordCount,\n confirm,\n dataScope,\n hostId,\n user,\n enqueueSnackbar,\n logActivity,\n openDataset,\n ])\n\n /**\n * What the selected dataset's references point at beyond this site's list\n * (AGL-4047). A dataset this site sees can name a target another site holds;\n * the schema dialog warns about exactly that, and a cell still labels the\n * row it points at, so the target has to be known even though the site's\n * list does not show it. Read one by one, and only when there is one; a\n * target the viewer may not read stays unknown.\n */\n const [outsideTargets, setOutsideTargets] = useState<any[]>(NO_DATASETS)\n useEffect(() => {\n let active = true\n const missing = railNarrowed\n ? [\n ...new Set(\n model.order\n .map((fieldId) => model.fields[fieldId]?.reference?.datasetId)\n .filter((id): id is string => Boolean(id)),\n ),\n ].filter((id) => !datasets.some((item) => item.$id === id))\n : []\n if (!missing.length || !dataScope) {\n setOutsideTargets(NO_DATASETS)\n return\n }\n void Promise.all(\n missing.map((id) =>\n getDoc(doc(firestore, dataScope[0], dataScope[1], 'datasets', id)).then(\n (snapshot) => (snapshot.exists() ? datasetRow(snapshot) : null),\n () => null,\n ),\n ),\n ).then((rows) => {\n if (active) setOutsideTargets(rows.filter(Boolean))\n })\n return () => {\n active = false\n }\n }, [railNarrowed, model, datasets, firestore, dataScope])\n const knownDatasets = useMemo(\n () => (outsideTargets.length ? [...datasets, ...outsideTargets] : datasets),\n [datasets, outsideTargets],\n )\n\n // Reference pickers (AGL-180): load target-collection rows for every\n // reference field in the model (id -> display label).\n const [refOptions, setRefOptions] = useState<\n Record<string, Array<{ id: string; label: string }>>\n >({})\n useEffect(() => {\n let active = true\n const referenceFields = model.order.filter(\n (fieldId) =>\n model.fields[fieldId]?.type === 'reference' &&\n model.fields[fieldId]?.reference?.datasetId,\n )\n if (!referenceFields.length || !dataScope) {\n setRefOptions({})\n return\n }\n void Promise.all(\n referenceFields.map(async (fieldId) => {\n const reference = model.fields[fieldId].reference as {\n datasetId: string\n displayFieldId?: string\n }\n const target = knownDatasets.find(\n (item) => item.$id === reference.datasetId,\n )\n const displayFieldId =\n reference.displayFieldId ??\n effectiveDatasetModel(target ?? {}).order[0]\n const snapshot = await getDocs(\n query(\n collection(\n firestore,\n dataScope[0],\n dataScope[1],\n 'datasets',\n reference.datasetId,\n 'records',\n ),\n limit(200),\n ),\n ).catch(() => null)\n const options = (snapshot?.docs ?? []).map((docSnapshot) => ({\n id: docSnapshot.id,\n label: String(\n docSnapshot.get('values')?.[displayFieldId ?? ''] ??\n docSnapshot.id,\n ),\n }))\n return [fieldId, options] as const\n }),\n ).then((entries) => {\n if (active) setRefOptions(Object.fromEntries(entries))\n })\n return () => {\n active = false\n }\n }, [model, knownDatasets, firestore, dataScope])\n /**\n * One reference target's label, or `null` when this ID resolves to nothing.\n *\n * The distinction the grid cannot draw. `referenceLabel` below falls back to\n * the raw ID, which is the only thing a cell has room for and is\n * indistinguishable from a resolved label that happens to look like an ID.\n * The record view has room to say which, so it asks the question that has a\n * `null` answer.\n *\n * Unresolvable covers more than a deleted target: `refOptions` loads at most\n * 200 rows per referenced collection, so a live target outside that window\n * reports the same way. Either way the ID is shown and neither is claimed to\n * be a working link.\n */\n const resolveReferenceLabel = useCallback(\n (fieldId: string, id: string): string | null =>\n refOptions[fieldId]?.find((option) => option.id === id)?.label ?? null,\n [refOptions],\n )\n const referenceLabel = useCallback(\n (fieldId: string, value: unknown): string => {\n const ids = Array.isArray(value) ? value : value != null ? [value] : []\n return ids\n .map((id) => resolveReferenceLabel(fieldId, String(id)) ?? String(id))\n .join(', ')\n },\n [resolveReferenceLabel],\n )\n /**\n * The record the viewer is showing, held as an ID and resolved against the\n * page the table already has.\n *\n * Holding the ID rather than the row is what keeps the view live without\n * costing a read: the same listener that draws the table re-resolves it, so\n * an edit landing underneath updates the open dialog. When the row leaves\n * the page — deleted, or paged past — this answers `null` and the dialog\n * closes, which is the honest response to a record no longer in front of\n * this reader. Nothing here queries: `records` is the page (or filter window)\n * query's answer.\n */\n const [viewerId, setViewerId] = useState<string | null>(null)\n /**\n * Opens a record (AGL-4047): on its own page beneath the dataset's tab\n * where the Data page is routed, in the View record dialog elsewhere.\n */\n const datasetHref = basePath && selected?.$id ? `${basePath}/${selected.$id}` : null\n const openRecord = useCallback(\n (id: string) => {\n if (datasetHref) router.push(`${datasetHref}/records/${encodeURIComponent(id)}`)\n else setViewerId(id)\n },\n [datasetHref, router],\n )\n const viewerRecord = useMemo(\n () =>\n viewerId\n ? (records.find((record: any) => record.$id === viewerId) ?? null)\n : null,\n [viewerId, records],\n )\n\n // --- Document editor (null id = new; AGL-179 typed inputs) --------------\n const [editor, setEditor] = useState<{\n id: string | null\n values: Record<string, string>\n errors: Record<string, string>\n /** A sample a site start seeded (AGL-4065): saving it makes it the owner's. */\n sample?: boolean\n } | null>(null)\n const handleOpenRecord = useCallback(\n (record?: any) => () => {\n if (!record) {\n // The dataset's documents, not the loaded window (AGL-1716).\n const quota = checkQuota(org, 'recordsPerDataset', recordCount)\n if (!quota.allowed) {\n return enqueueSnackbar(\n `Record limit reached (${quota.limit}) — see Billing to upgrade`,\n { variant: 'warning', persist: false },\n )\n }\n }\n const values: Record<string, string> = {}\n for (const fieldId of model.order) {\n const field = model.fields[fieldId]\n if (!field) continue\n if (record) {\n values[fieldId] = datasetValueToInput(\n field,\n record.values?.[fieldId],\n )\n } else if (field.default != null) {\n values[fieldId] = String(field.default)\n }\n }\n // Flag non-conforming stored values (AGL-178 policy: type changes\n // never rewrite documents; the editor surfaces the mismatch).\n const errors = record\n ? validateDocument(model, record.values ?? {})\n : {}\n setEditor({ id: record?.$id ?? null, values, errors, ...(isSampleDatasetRecord(record) ? { sample: true } : {}) })\n },\n [org, recordCount, model, enqueueSnackbar],\n )\n const handleSaveRecord = useCallback(async () => {\n if (!editor || !selected || !dataScope) return\n // The editor holds the record's WHOLE values, so an address it already\n // has stays and an empty one fills in from its source (AGL-3475).\n const coerced = fillRecordAddresses(\n model,\n coerceDocumentValues(model, editor.values),\n )\n const errors = validateDocument(model, coerced)\n if (Object.keys(errors).length) {\n return void setEditor((prev) => (prev ? { ...prev, errors } : prev))\n }\n // `values` is replaced wholesale (not merged) so orphaned values from\n // removed fields strip here, lazily, per the documented AGL-178 policy.\n try {\n if (editor.id) {\n // Updates stay client-direct (no quota consumed).\n const recordRef = doc(\n firestore,\n dataScope[0],\n dataScope[1],\n 'datasets',\n selected.$id,\n 'records',\n editor.id,\n )\n await setDoc(\n recordRef,\n {\n values: coerced,\n // The integrity index moves with the values it describes\n // (`datasetIntegrityUpdate`); the merging form, because clearing\n // the last reference has to REMOVE the field rather than omit it.\n ...datasetIntegrityUpdate(model, coerced, deleteField()),\n // A sample saved is the owner's row now (AGL-4065).\n ...(editor.sample ? { sample: deleteField() } : {}),\n updatedAt: Timestamp.now(),\n },\n {\n mergeFields: [\n 'values',\n 'referencedIds',\n 'filterKeys',\n 'filterValues',\n 'updatedAt',\n ...(editor.sample ? ['sample'] : []),\n ],\n },\n )\n await announceRecords(selected.$id)\n } else {\n // Creates go through the quota-enforcing API (AGL-473). The legacy\n // host-scope client write that used to follow this branch is gone\n // (AGL-1050): a non-null `dataScope` is an org scope, so `orgId` is\n // set and there is no third case to fall into.\n await callDatasetApi({\n action: 'create-record',\n datasetId: selected.$id,\n values: coerced,\n })\n }\n } catch (error: any) {\n return void enqueueSnackbar(error?.message ?? 'Record save failed', {\n variant: 'warning',\n persist: false,\n })\n }\n setEditor(null)\n // A create moves the count; an update cannot. Same reason as the\n // importer: the one-shot aggregate does not refresh itself.\n if (!editor.id) setRecordCountEpoch((epoch) => epoch + 1)\n enqueueSnackbar(editor.id ? 'Record saved' : 'Record added', {\n variant: 'success',\n persist: false,\n })\n logActivity(editor.id ? 'Updated record' : 'Added record', {\n type: 'content',\n id: selected.$id,\n name: datasetDisplayName(selected),\n })\n }, [\n editor,\n selected,\n firestore,\n dataScope,\n model,\n callDatasetApi,\n announceRecords,\n enqueueSnackbar,\n logActivity,\n ])\n const handleDeleteRecord = useCallback(\n (record: any, afterDelete?: () => void) => async () => {\n // Datasets whose records this delete rewrites through a reference\n // fixup, beside the one the record belongs to. Each has pages of its\n // own to refresh (AGL-3113).\n const alsoChanged = new Set<string>()\n if (!selected || !dataScope) return\n /**\n * Delete integrity (AGL-180): every collection whose model references\n * this one is asked whether it still points at this record. `restrict`\n * blocks the delete; `setNull` strips the FKey from the holders.\n *\n * The question is a QUERY over the denormalized `referencedIds` index,\n * not a page of records filtered in the browser. A page answers for the\n * rows it happened to fetch — an unordered `limit` is answered in\n * document-id order over auto-ids, so it is an arbitrary sample — and a\n * reference held by a row outside it reads as no reference at all: the\n * delete goes through and `restrict` silently fails to restrict, leaving\n * a document pointing at something that no longer exists. `values`\n * itself cannot be queried (it carries a deliberate index exemption —\n * see `datasetIntegrityFields`), which is why the index exists.\n *\n * The query narrows to the candidates; the per-field test below keeps it\n * EXACT, since `referencedIds` is the union across every reference field\n * and one of them may point at a different collection entirely.\n *\n * ⚠️ FAILS CLOSED. A query that rejects — a missing index, a rules\n * refusal on a collection this member cannot read — refuses the delete\n * rather than treating silence as \"nothing references it\". A check that\n * fails open is worse than no check, because the UI then tells the user\n * the record is safe to remove.\n *\n * ⚠️ Reaches the collections in this viewer's scoped, capped window. A\n * referencing collection shared with no site this member can see is one\n * the client may not read at all, so it is not consulted; only a server\n * route could close that.\n *\n * On a site's Data page that window is NOT the list (AGL-4047). The list\n * is the site's, and a dataset another site holds can reference a row of\n * one shared with both: narrowing what the page shows must not narrow\n * what a delete protects. So the page reads the viewer's reach here, once,\n * at the moment of the delete, and refuses if it cannot.\n */\n let referencing: any[] = datasets\n if (railNarrowed) {\n try {\n const reach = await getDocs(\n query(\n collection(firestore, dataScope[0], dataScope[1], 'datasets'),\n ...(reachScope\n ? [where('visibleTo', 'array-contains-any', [...reachScope])]\n : []),\n limit(DATASET_LIST_WINDOW),\n ),\n )\n referencing = reach.docs.map(datasetRow)\n } catch {\n return void enqueueSnackbar(\n 'Cannot delete: the datasets that may reference this record could ' +\n 'not be checked, so removing it could break them. Nothing was ' +\n 'deleted.',\n { variant: 'error' },\n )\n }\n }\n for (const other of referencing) {\n const otherModel = effectiveDatasetModel(other)\n if (!referencingFieldIds(otherModel, selected.$id).length) continue\n let snapshot\n try {\n snapshot = await getDocs(\n query(\n collection(\n firestore,\n dataScope[0],\n dataScope[1],\n 'datasets',\n other.$id,\n 'records',\n ),\n where('referencedIds', 'array-contains', record.$id),\n ),\n )\n } catch {\n return void enqueueSnackbar(\n `Cannot delete: \"${datasetDisplayName(other)}\" could not be checked for ` +\n 'references, so removing this record could break it. Nothing ' +\n 'was deleted.',\n { variant: 'error' },\n )\n }\n // The verdict is shared with `/api/orgs/datasets` `delete-record`\n // (`planReferenceFixups`): the per-field test keeps the query EXACT,\n // since `referencedIds` is the union across every reference field.\n const plan = planReferenceFixups(\n otherModel,\n selected.$id,\n record.$id,\n snapshot.docs.map((docSnapshot) => ({ id: docSnapshot.id, values: docSnapshot.get('values') })),\n )\n if (plan.kind === 'none') continue\n if (plan.kind === 'restricted') {\n return void enqueueSnackbar(\n restrictedDeleteMessage(plan.holders, datasetDisplayName(other)),\n { variant: 'warning', persist: false },\n )\n }\n // Chunked under Firestore's 500-writes-per-batch cap. The query is no\n // longer bounded by a page size, so the number of holders is whatever\n // the collection really holds.\n for (let start = 0; start < plan.updates.length; start += 400) {\n const batch = writeBatch(firestore)\n for (const update of plan.updates.slice(start, start + 400)) {\n const holder = snapshot.docs.find((docSnapshot) => docSnapshot.id === update.id)\n if (!holder) continue\n batch.update(holder.ref, {\n values: update.values,\n ...datasetIntegrityUpdate(otherModel, update.values, deleteField()),\n })\n }\n await batch.commit()\n }\n // The fixups rewrote rows in ANOTHER dataset, whose own pages are now\n // showing a reference that no longer resolves.\n alsoChanged.add(other.$id)\n }\n await deleteDoc(\n doc(\n firestore,\n dataScope[0],\n dataScope[1],\n 'datasets',\n selected.$id,\n 'records',\n record.$id,\n ),\n )\n setRecordCountEpoch((epoch) => epoch + 1)\n for (const datasetId of [selected.$id, ...alsoChanged]) {\n await announceRecords(datasetId)\n }\n enqueueSnackbar('Record deleted', { variant: 'success', persist: false })\n afterDelete?.()\n },\n [\n selected,\n datasets,\n railNarrowed,\n reachScope,\n firestore,\n dataScope,\n announceRecords,\n enqueueSnackbar,\n ],\n )\n\n /**\n * Import and export (AGL-3530) open the console's import wizard and export\n * dialog on this dataset (`data.dataset:<datasetId>`): the file is read,\n * matched and written on the server, through the same record writes as\n * every other create and update, and the export streams the fields the\n * person picks. Outside the console shell there is no launcher, and no\n * Import or Export to offer. Inside it, Import is on for a member who may\n * write this dataset and switched off with the permission named for one who\n * may not, and Export likewise for \"Export data\", for a member who can see it\n * (AGL-3546, AGL-4047) — the transfer routes' own rule.\n */\n const transfer = useTransferLauncher()\n const transferTarget = selected?.$id\n ? {\n resource: datasetTransferResourceKey(selected.$id),\n scope: 'org' as const,\n // This dataset's own answer once it is known; the workspace's until then.\n ...(blocked.known ? { importAllowed: !blocked.writes } : {}),\n }\n : null\n const canImport = Boolean(transfer && transferTarget && transfer.can('import', transferTarget))\n const canExport = Boolean(transfer && transferTarget && transfer.can('export', transferTarget))\n const handleImport = useCallback(() => {\n if (!transfer || !selected?.$id) return\n const dataset = { id: selected.$id, name: datasetDisplayName(selected) }\n transfer.openImport({\n resource: datasetTransferResourceKey(dataset.id),\n scope: 'org',\n title: dataset.name ? `Import into ${dataset.name}` : 'Import records',\n onFinished: () => {\n // An import moves the record count, and the aggregate is a one-shot.\n setRecordCountEpoch((epoch) => epoch + 1)\n logActivity('Imported records', { type: 'content', id: dataset.id, name: dataset.name })\n },\n })\n }, [transfer, selected, logActivity])\n const handleExport = useCallback(() => {\n if (!transfer || !selected?.$id) return\n const name = datasetDisplayName(selected)\n transfer.openExport({\n resource: datasetTransferResourceKey(selected.$id),\n scope: 'org',\n title: name ? `Export ${name}` : 'Export records',\n // The table's own query, re-planned on the server the way the table\n // plans it, so \"the current filter\" exports what the table shows.\n ...(filteringRecords\n ? {\n filter: {\n label: 'The records the table’s filters and search show',\n value: { clauses: recordClauses, search: gridFilter.searchWords },\n },\n }\n : {}),\n })\n }, [transfer, selected, filteringRecords, recordClauses, gridFilter.searchWords])\n\n /*\n * One column per schema field, filterable as far as `datasetRecordFilter`\n * declares it. The row OPENS the record, read-only (`onOpen`); the actions\n * column holds the keyboard's way in (`View`, a real button) beside Edit\n * and Delete, and a press anywhere in it never opens the row.\n */\n const recordGridColumns = useMemo(\n () =>\n listFilterGridColumns(\n [\n ...fields.map((fieldId, column) => {\n const field = model.fields[fieldId]\n const shown = (row: any) =>\n field?.type === 'reference'\n ? referenceLabel(fieldId, row.values?.[fieldId]) || '--'\n : field\n ? formatDatasetValue(field, row.values?.[fieldId]) || '--'\n : '--'\n return {\n field: recordColumn(fieldId),\n headerName: field?.name ?? fieldId,\n // Field descriptions (AGL-560) surface as header hints.\n description: field?.description,\n flex: 1,\n minWidth: 140,\n renderCell: ({ row }: { row: any }) =>\n // A sample a site start seeded says so beside its first value (AGL-4065).\n column === 0 && isSampleDatasetRecord(row) ? (\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center', height: '100%', minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {shown(row)}\n </Typography>\n <Tooltip title={DATASET_SAMPLE_RECORD_NOTE}>\n <Chip label=\"Sample\" size=\"small\" variant=\"outlined\" color=\"info\" />\n </Tooltip>\n </Stack>\n ) : (\n shown(row)\n ),\n }\n }),\n listActionsColumn(\n (record: any) => (\n <Stack\n direction=\"row\"\n sx={{ height: '100%', alignItems: 'center', justifyContent: 'flex-end' }}\n >\n <Button size=\"small\" onClick={() => openRecord(record.$id)}>\n {'View'}\n </Button>\n <BlockedControl blocked={blocked.writes} reason={blocked.writesReason}>\n <Button size=\"small\" onClick={handleOpenRecord(record)}>\n {'Edit'}\n </Button>\n </BlockedControl>\n <BlockedControl blocked={blocked.writes} reason={blocked.writesReason}>\n <Button\n size=\"small\"\n color=\"error\"\n onClick={handleDeleteRecord(record)}\n >\n {'Delete'}\n </Button>\n </BlockedControl>\n </Stack>\n ),\n { width: 220 },\n ),\n ] as Parameters<typeof listFilterGridColumns>[0],\n recordFilter.fields,\n recordFilter.options,\n recordFilter.headers,\n ),\n [\n fields,\n model,\n referenceLabel,\n handleOpenRecord,\n handleDeleteRecord,\n openRecord,\n recordFilter,\n blocked.writes,\n blocked.writesReason,\n ],\n )\n\n /*\n * EVERY HEADER SORTS — THE PAGE ON SCREEN (AGL-3680). A record's values are\n * per-schema and no field is on every record (see the walk above), so no\n * query can order by one; each value column sorts the loaded page by what\n * it shows (a reference by its label, a number or switch by its value) and\n * the notice says it is this page only.\n */\n const recordPageSorts = useMemo(\n () =>\n Object.fromEntries(\n fields.map((fieldId) => {\n const field = model.fields[fieldId]\n return [\n recordColumn(fieldId),\n (row: any) => {\n const value = row.values?.[fieldId]\n if (field?.type === 'reference') return referenceLabel(fieldId, value) || null\n if (typeof value === 'number' || typeof value === 'boolean') return value\n return field ? formatDatasetValue(field, value) || null : null\n },\n ]\n }),\n ),\n [fields, model, referenceLabel],\n )\n const recordSortHeaders = useMemo(\n () =>\n Object.fromEntries(\n fields.map((fieldId) => [recordColumn(fieldId), model.fields[fieldId]?.name ?? fieldId]),\n ),\n [fields, model],\n )\n const recordColumnSort = useListColumnSort<any>({\n sorts: NO_QUERY_SORTS,\n rows: records,\n pageSorts: recordPageSorts,\n headers: recordSortHeaders,\n })\n\n /**\n * The rail (AGL-4047): one tab per dataset, at the dataset's own address,\n * with a second line that tells two of one name apart. Past\n * {@link DATASET_RAIL_GROUP_AT} the tabs are grouped by who they are shared\n * with, and the organization page offers the Shared with filter.\n */\n const grouped = datasets.length > DATASET_RAIL_GROUP_AT\n const railSections = useMemo<HubSection[]>(() => {\n if (!basePath) return []\n const tab = (item: DatasetRailEntry, group?: string): HubSection => ({\n href: `${basePath}/${item.$id}`,\n label: datasetRailName(item),\n secondary: datasetRailSecondary(item, { hostNames, grouped }),\n ...(group ? { group } : {}),\n })\n if (!grouped) return datasets.map((item: DatasetRailEntry) => tab(item))\n return groupDatasetsBySharing(datasets, hostNames).flatMap((group) =>\n group.datasets.map((item) => tab(item, group.label)),\n )\n }, [basePath, datasets, hostNames, grouped])\n /** The join dialog's names, told apart where two match (AGL-4047). */\n const joinLabels = useMemo(() => datasetPickerLabelsOf(datasets, hostNames), [datasets, hostNames])\n const offerSharedWith =\n !pageHostId && orgSites.length > 1 && (datasets.length > DATASET_RAIL_GROUP_AT || Boolean(sharedWith))\n const sitesByName = useMemo(\n () => [...orgSites].sort((a, b) => (hostNames[a.$id] ?? '').localeCompare(hostNames[b.$id] ?? '')),\n [orgSites, hostNames],\n )\n const railHeader =\n datasets.length || nameSearch || sharedWith ? (\n <Stack spacing={1.5} sx={{ mb: 1 }}>\n <TextField\n size=\"small\"\n fullWidth\n placeholder=\"Search datasets by name\"\n value={nameSearch}\n onChange={(event) => setNameSearch(event.target.value)}\n slotProps={{ htmlInput: { 'aria-label': 'Search datasets by name' } }}\n />\n {offerSharedWith ? (\n <TextField\n select\n size=\"small\"\n fullWidth\n label=\"Shared with\"\n value={sharedWith}\n onChange={(event) => {\n setSharedWith(event.target.value)\n setRailWindow(DATASET_LIST_WINDOW)\n }}\n >\n <MenuItem value=\"\">{'Any site'}</MenuItem>\n {sitesByName.map((site) => (\n <MenuItem key={site.$id} value={site.$id}>\n {hostNames[site.$id]}\n </MenuItem>\n ))}\n </TextField>\n ) : null}\n </Stack>\n ) : null\n const railFooter = (\n <>\n {listAnswered && serverNameKey && datasets.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\" sx={{ px: 2, py: 1 }}>\n {'No datasets match.'}\n </Typography>\n ) : null}\n {moreDatasets ? (\n <Button size=\"small\" sx={{ mt: 1 }} onClick={() => setRailWindow((window) => window + DATASET_LIST_WINDOW)}>\n {'Show more datasets'}\n </Button>\n ) : null}\n </>\n )\n\n /** The open dataset's facts, under its name. */\n const facts: Array<[string, string]> = selected\n ? [\n ['Shared with', datasetSharingLabel(selected, hostNames)],\n ['Fields', String(fields.length)],\n ['Records', blocked.records ? '--' : recordCount.toLocaleString()],\n ['Source', datasetSourceLabel(selected)],\n ['Created', datasetCreatedLabel(selected)],\n ]\n : []\n\n /** Label-over-value facts, under a heading. */\n const factsRow = (pairs: Array<[string, string]>) => (\n <Stack direction=\"row\" spacing={3} useFlexGap sx={{ flexWrap: 'wrap', mt: 1 }}>\n {pairs.map(([label, value]) => (\n <Box key={label}>\n <Typography variant=\"caption\" color=\"text.secondary\" component=\"div\">\n {label}\n </Typography>\n <Typography variant=\"body2\" color=\"text.primary\" component=\"div\" sx={{ overflowWrap: 'anywhere' }}>\n {value}\n </Typography>\n </Box>\n ))}\n </Stack>\n )\n\n /**\n * A record's own page (AGL-4047): back to its dataset, its fields, and\n * today's record actions with today's gates. It takes the place of the View\n * record dialog where the Data page is routed.\n */\n const recordTitle = routeRecord ? datasetRecordTitle(model, routeRecord.values) : undefined\n const recordPanel =\n selected && routeRecordId ? (\n <CardDisplay\n help={pluginDocsHelp('datasets', { anchor: '#organization-data-page' })}\n header={\n <Stack spacing={1} sx={{ alignItems: 'flex-start' }}>\n {datasetHref ? (\n <Button\n size=\"small\"\n component={AppLink}\n href={datasetHref}\n startIcon={<MdiIcon path={mdiArrowLeft.path} size={0.8} />}\n >\n {datasetRailName(selected)}\n </Button>\n ) : null}\n {recordTitle ? <span>{recordTitle}</span> : null}\n </Stack>\n }\n contentGutterX\n contentGutterY\n contentBordered=\"top\"\n HeaderProps={{\n action: routeRecord ? (\n <Stack direction=\"row\" spacing={1} useFlexGap sx={{ alignItems: 'center', flexWrap: 'wrap', justifyContent: 'flex-end' }}>\n <BlockedControl blocked={blocked.writes} reason={blocked.writesReason}>\n <Button size=\"small\" onClick={handleOpenRecord(routeRecord)}>\n {'Edit record'}\n </Button>\n </BlockedControl>\n <BlockedControl blocked={blocked.writes} reason={blocked.writesReason}>\n <Button\n size=\"small\"\n color=\"error\"\n onClick={handleDeleteRecord(routeRecord, () => {\n if (datasetHref) router.push(datasetHref)\n })}\n >\n {'Delete'}\n </Button>\n </BlockedControl>\n </Stack>\n ) : undefined,\n subheader: factsRow([\n ['Record ID', routeRecordId],\n ['Dataset', `${datasetRailName(selected)} · ${datasetSharingLabel(selected, hostNames)}`],\n ]),\n }}\n >\n <Stack spacing={1.5}>\n {blocked.records ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {DATASETS_VIEW_RECORDS_REFUSAL}\n </Typography>\n ) : routeRecordMissing ? (\n <Alert severity=\"info\">{'This record doesn’t exist, or you can’t open it.'}</Alert>\n ) : routeRecord ? (\n <DatasetRecordFieldList\n record={routeRecord}\n model={model}\n resolveReference={resolveReferenceLabel}\n divided\n />\n ) : null}\n </Stack>\n </CardDisplay>\n ) : null\n\n const panel = notSharedHere ? (\n <Alert severity=\"info\">{'This dataset isn’t shared with this site.'}</Alert>\n ) : notFound ? (\n <Alert severity=\"info\">{'This dataset doesn’t exist, or you can’t open it.'}</Alert>\n ) : recordPanel ? (\n recordPanel\n ) : !selected ? (\n listAnswered && datasets.length === 0 && !sharedWith && !serverNameKey ? (\n <CardDisplay contentGutterX contentGutterY>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Create a dataset, like Products, then add a repeating section ' +\n 'to any page to show one item per record.'}\n </Typography>\n </CardDisplay>\n ) : null\n ) : (\n <CardDisplay\n header={datasetRailName(selected)}\n help={pluginDocsHelp('datasets', { anchor: '#filter-records' })}\n contentGutterX\n contentGutterY\n contentBordered=\"top\"\n HeaderProps={{\n action: (\n <Stack\n direction=\"row\"\n spacing={1}\n useFlexGap\n sx={{ alignItems: 'center', flexWrap: 'wrap', justifyContent: 'flex-end' }}\n >\n <BlockedControl blocked={blocked.writes} reason={blocked.writesReason}>\n <Button\n size=\"small\"\n color=\"primary\"\n onClick={handleOpenRecord()}\n >\n {'Add record'}\n </Button>\n </BlockedControl>\n <BlockedControl blocked={blocked.writes && !blocked.sharingOnly} reason={blocked.writesReason}>\n <Button size=\"small\" onClick={() => setSchemaOpen(true)}>\n {'Schema'}\n </Button>\n </BlockedControl>\n {/* An import left unfinished, reopened where it stopped (AGL-3549). */}\n {transferTarget ? (\n <TransferResumeImport\n target={transferTarget}\n {...(selected ? { title: `Import into ${datasetDisplayName(selected)}` } : {})}\n onFinished={() => setRecordCountEpoch((epoch) => epoch + 1)}\n />\n ) : null}\n {/* Off with the permission named for a member known not to hold it,\n not hidden. Still absent while the answer is out, and where the\n launcher refuses for another reason than the key. */}\n {canImport || (transfer && transferTarget && blocked.writes) ? (\n <BlockedControl blocked={!canImport} reason={blocked.writesReason}>\n <Button size=\"small\" onClick={handleImport}>\n {'Import'}\n </Button>\n </BlockedControl>\n ) : null}\n {/* The real dataset size, not the loaded window (AGL-2335) —\n the export is a server stream, so a dataset whose first page\n has not landed yet is still exportable. */}\n {(canExport && (recordCount || records.length)) || (transfer && blocked.exports) ? (\n <BlockedControl blocked={blocked.exports} reason={DATASETS_EXPORT_REFUSAL}>\n <Button size=\"small\" onClick={handleExport}>\n {'Export'}\n </Button>\n </BlockedControl>\n ) : null}\n <BlockedControl blocked={blocked.deletes} reason={blocked.deletesReason}>\n <Button size=\"small\" color=\"error\" onClick={handleDeleteDataset}>\n {'Delete'}\n </Button>\n </BlockedControl>\n </Stack>\n ),\n subheader: factsRow(facts),\n }}\n >\n <Stack spacing={1.5}>\n {/* The per-dataset record cap, standing rather than only on refusal\n (AGL-2113). `recordCount` is the dataset's real size — the same\n number `handleOpenRecord` and the importer hand to `checkQuota`,\n not the loaded window (AGL-1716). */}\n {selected ? (\n <QuotaReadoutComponent\n ready={org != null}\n used={recordCount}\n limit={checkQuota(org, 'recordsPerDataset', recordCount).limit}\n noun=\"record\"\n />\n ) : null}\n {selected && blocked.records ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {DATASETS_VIEW_RECORDS_REFUSAL}\n </Typography>\n ) : selected && (records.length > 0 || recordPage > 0 || filteringRecords) ? (\n <>\n <ListFilterChips\n fields={recordFilter.fields}\n headers={recordFilter.headers}\n clauses={recordClauses}\n onChange={gridFilter.setClauses}\n options={recordFilter.options}\n />\n <ListQueryNotices\n refused={recordRefusals}\n notices={[...recordPlan.notices, ...recordColumnSort.notices]}\n />\n <ListTable\n aria-label=\"Records\"\n // Edit and Delete stay in reach when the columns scroll sideways\n // in the panel beside the rail (AGL-4047).\n pinActions\n rows={recordColumnSort.rows}\n columnSort={recordColumnSort}\n columns={recordGridColumns}\n onOpen={(id) => openRecord(id)}\n // One page of the walk, turned by the footer below: the grid\n // neither slices nor filters it.\n hideFooter\n filterMode=\"server\"\n filterModel={gridFilter.filterModel}\n onFilterModelChange={gridFilter.onFilterModelChange}\n quickFilter\n {...(blocked.exports ? { slotProps: EXPORT_OFF_TOOLBAR } : {})}\n noRowsLabel={\n filteringRecords ? 'No records match these filters' : 'No records yet.'\n }\n />\n {/* The count line is the PAGE's, deliberately. `recordCount` is the\n dataset's real size and it already has its own readout above —\n handing it to the footer as `count` would tell MUI the walk is\n that long and leave Next live past the end of it whenever a rule,\n a scope or a filter has narrowed what this reader may list.\n `hasMore` is a fact from the probe row, so the footer answers\n for what it is actually paging. */}\n <ListPagination\n page={recordPage}\n pageSize={recordPageSize}\n rowCount={records.length}\n hasMore={hasMoreRecords}\n onPageChange={setRecordPage}\n onPageSizeChange={setRecordPageSize}\n />\n </>\n ) : selected ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No records yet.'}\n </Typography>\n ) : null}\n </Stack>\n </CardDisplay>\n )\n\n return (\n <>\n {/* The page's own actions, in the page header beside its title. */}\n <PageHeaderActions>\n <Stack direction=\"row\" spacing={1} useFlexGap sx={{ flexWrap: 'wrap' }}>\n <BlockedControl blocked={blocked.creates} reason={DATASETS_WRITE_REFUSAL}>\n <Button variant=\"outlined\" color=\"primary\" onClick={handleOpenCreator}>\n {'Add dataset'}\n </Button>\n </BlockedControl>\n {datasets.length >= 2 ? (\n <BlockedControl blocked={blocked.creates} reason={DATASETS_WRITE_REFUSAL}>\n <Button onClick={() => setJoiner({ a: '', b: '' })}>{'Add join collection'}</Button>\n </BlockedControl>\n ) : null}\n </Stack>\n </PageHeaderActions>\n {/* The open dataset ends the trail; the heading stays the page's. */}\n {/* On a record's page the trail runs dataset, linked, then record. */}\n {routeRecordId && selected && datasetHref ? (\n <PageHeaderRecord\n title={recordTitle}\n keepHeading\n parentTitle={datasetRailName(selected)}\n parentHref={datasetHref}\n />\n ) : (\n <PageHeaderRecord title={selected && routeDatasetId ? datasetRailName(selected) : undefined} keepHeading />\n )}\n <HubSections\n sections={railSections}\n navHeader=\"Datasets\"\n railHeader={railHeader}\n railFooter={railFooter}\n scrollRail\n >\n {panel}\n </HubSections>\n <Dialog\n open={Boolean(creator)}\n onClose={() => setCreator(null)}\n maxWidth=\"xs\"\n fullWidth\n >\n <DialogTitle>{'New dataset'}</DialogTitle>\n <DialogContent\n sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}\n >\n {orgId ? (\n <Typography variant=\"body2\" color=\"text.secondary\" sx={{ mt: 1 }}>\n {/* Ownership and visibility are separate facts (AGL-1044), and\n what a new dataset starts on depends on where it is made. */}\n {newDatasetSharingNote(createsSiteOnly)}\n </Typography>\n ) : null}\n <TextField\n label=\"Name\"\n value={creator?.name ?? ''}\n onChange={(event) =>\n setCreator((prev) =>\n prev ? { ...prev, name: event.target.value } : prev,\n )\n }\n size=\"small\"\n autoFocus\n sx={{ mt: 1 }}\n helperText=\"e.g. Products, Team, FAQ\"\n />\n <TextField\n label=\"Fields\"\n value={creator?.fields ?? ''}\n onChange={(event) =>\n setCreator((prev) =>\n prev ? { ...prev, fields: event.target.value } : prev,\n )\n }\n size=\"small\"\n helperText={\n creatorEntries.length\n ? `Columns: ${creatorEntries\n .map((entry) => entry.name)\n .join(', ')}`\n : 'Comma-separated column names, e.g. Title, Unit price'\n }\n />\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setCreator(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={\n !scopeReady ||\n !creator?.name.trim() ||\n creatorFields.length === 0\n }\n onClick={handleCreate}\n >\n {'Create'}\n </Button>\n </DialogActions>\n </Dialog>\n {/*\n ONE viewer for the table, not one per row. Its record is a prop out of\n the page already in hand, so opening it reads nothing — and mounting\n the table does not open a dialog per row to discover that.\n */}\n <DatasetRecordDialog\n record={viewerRecord}\n model={model}\n resolveReference={resolveReferenceLabel}\n onClose={() => setViewerId(null)}\n // Explicitly separate, and a hand-off rather than a second editor:\n // the viewer closes and the record opens in the dialog that has\n // always owned writing.\n onEdit={() => {\n const record = viewerRecord\n setViewerId(null)\n if (record) handleOpenRecord(record)()\n }}\n />\n <Dialog\n open={Boolean(editor)}\n onClose={() => setEditor(null)}\n maxWidth=\"xs\"\n fullWidth\n >\n <DialogTitle>{editor?.id ? 'Edit record' : 'New record'}</DialogTitle>\n <DialogContent\n sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}\n >\n {editor?.sample ? <Alert severity=\"info\">{DATASET_SAMPLE_RECORD_NOTE}</Alert> : null}\n <DatasetRecordSiteContext.Provider value={recordSite}>\n {fields.map((fieldId, index) => {\n const field = model.fields[fieldId]\n if (!field) return null\n const value = editor?.values[fieldId] ?? ''\n const error = editor?.errors[fieldId]\n const label = field.required ? `${field.name} *` : field.name\n const setValue = (nextValue: string) =>\n setEditor((prev) =>\n prev\n ? {\n ...prev,\n values: { ...prev.values, [fieldId]: nextValue },\n errors: { ...prev.errors, [fieldId]: '' },\n }\n : prev,\n )\n const common = {\n label,\n value,\n size: 'small' as const,\n autoFocus: index === 0,\n error: Boolean(error),\n helperText: error || field.description,\n sx: index === 0 ? { mt: 1 } : undefined,\n onChange: (event: { target: { value: string } }) =>\n setValue(event.target.value),\n }\n // Custom field types (AGL-434): the declaring plugin's Input\n // takes over; values stay in input form (strings) so the\n // existing coerce/validate pipeline is unchanged.\n const customFieldType = getCustomFieldType(field.customType)\n if (customFieldType?.Input) {\n const CustomInput = customFieldType.Input\n return (\n <Stack key={fieldId} sx={index === 0 ? { mt: 1 } : undefined}>\n <CustomInput\n value={value}\n label={common.label}\n onChange={(next) => setValue(String(next ?? ''))}\n />\n {(error || field.description) ? (\n <Typography\n variant=\"caption\"\n color={error ? 'error' : 'text.secondary'}\n >\n {error || field.description}\n </Typography>\n ) : null}\n </Stack>\n )\n }\n // Typed inputs per FT.Tag (AGL-179).\n if (field.type === 'bool') {\n return (\n <TextField key={fieldId} {...common} select>\n <MenuItem value=\"\">{'—'}</MenuItem>\n <MenuItem value=\"true\">{'Yes'}</MenuItem>\n <MenuItem value=\"false\">{'No'}</MenuItem>\n </TextField>\n )\n }\n if (field.type === 'text' && field.validation?.options?.length) {\n return (\n <TextField key={fieldId} {...common} select>\n <MenuItem value=\"\">{'—'}</MenuItem>\n {field.validation.options.map((option) => (\n <MenuItem key={option} value={option}>\n {option}\n </MenuItem>\n ))}\n </TextField>\n )\n }\n if (field.type === 'reference') {\n const options = refOptions[fieldId] ?? []\n const multiple = Boolean(field.reference?.multiple)\n const selectedIds = value\n .split(',')\n .map((part) => part.trim())\n .filter(Boolean)\n return (\n <TextField\n key={fieldId}\n {...common}\n select\n value={multiple ? selectedIds : value}\n slotProps={{\n select: multiple\n ? {\n multiple: true,\n onChange: (event: any) =>\n setValue(\n (event.target.value as string[]).join(', '),\n ),\n }\n : undefined,\n }}\n >\n {multiple ? null : <MenuItem value=\"\">{'—'}</MenuItem>}\n {options.map((option) => (\n <MenuItem key={option.id} value={option.id}>\n {option.label}\n </MenuItem>\n ))}\n </TextField>\n )\n }\n if (\n field.type === 'int32' ||\n field.type === 'int64' ||\n field.type === 'float'\n ) {\n return <TextField key={fieldId} {...common} type=\"number\" />\n }\n if (field.type === 'timestamp') {\n return (\n <TextField\n key={fieldId}\n {...common}\n type=\"datetime-local\"\n slotProps={{ inputLabel: { shrink: true } }}\n />\n )\n }\n if (field.type === 'coordinates') {\n return (\n <TextField\n key={fieldId}\n {...common}\n helperText={error || field.description || 'lat, lon'}\n />\n )\n }\n if (field.type === 'sorted') {\n return (\n <TextField\n key={fieldId}\n {...common}\n helperText={\n error || field.description || 'Comma-separated list'\n }\n />\n )\n }\n return <TextField key={fieldId} {...common} />\n })}\n </DatasetRecordSiteContext.Provider>\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setEditor(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n onClick={handleSaveRecord}\n >\n {editor?.id ? 'Save' : 'Add'}\n </Button>\n </DialogActions>\n </Dialog>\n <Dialog\n open={Boolean(joiner)}\n onClose={() => setJoiner(null)}\n maxWidth=\"xs\"\n fullWidth\n >\n <DialogTitle>{'New join collection'}</DialogTitle>\n <DialogContent\n sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}\n >\n <Typography variant=\"body2\" color=\"text.secondary\" sx={{ mt: 1 }}>\n {'Links two collections many-to-many; each row pairs one ' +\n 'document from each side.'}\n </Typography>\n {(['a', 'b'] as const).map((side) => (\n <TextField\n key={side}\n select\n size=\"small\"\n label={side === 'a' ? 'First collection' : 'Second collection'}\n value={joiner?.[side] ?? ''}\n onChange={(event) =>\n setJoiner((prev) =>\n prev ? { ...prev, [side]: event.target.value } : prev,\n )\n }\n >\n {datasets.map((item) => (\n <MenuItem key={item.$id} value={item.$id}>\n {/* Who it is shared with only where two share a name (AGL-4047). */}\n {joinLabels[item.$id]}\n </MenuItem>\n ))}\n </TextField>\n ))}\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setJoiner(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={\n !scopeReady || !joiner?.a || !joiner?.b || joiner.a === joiner.b\n }\n onClick={handleCreateJoin}\n >\n {'Create'}\n </Button>\n </DialogActions>\n </Dialog>\n <DatasetSchemaDialog\n hostId={hostId}\n orgId={orgId ?? undefined}\n dataset={schemaOpen && selected ? selected : null}\n datasets={knownDatasets}\n // The dataset's documents, not the loaded window (AGL-1716) — the\n // dialog warns \"N documents exist\" before a narrowing type change,\n // and 500 was the cap talking, not the collection.\n recordCount={recordCount}\n seedFromCache={seed.fromCache}\n seedUnreadable={seed.unreadable}\n seedListen={seed.listen}\n canChangeSharing={!blocked.creates}\n {...(blocked.sharingOnly ? { sharingOnlyReason: blocked.writesReason } : {})}\n onClose={() => setSchemaOpen(false)}\n />\n </>\n )\n}\nHostDatasetsCard.displayName = 'HostDatasetsCard'\n\nexport default HostDatasetsCard\n"],"names":["TransferResumeImport","checkDatasetQuota","checkEntitlement","checkQuota","getCustomFieldType","PageHeaderActions","PageHeaderRecord","pluginDocsHelp","scopeTokensForHost","useTransferLauncher","visibleToHost","nameSearchKey","HubSections","AppLink","CardDisplay","MdiIcon","useConfirmationContext","mdiArrowLeft","ListFilterChips","ListPagination","ListQueryNotices","listQueryRefusals","ListTable","listActionsColumn","QuotaReadoutComponent","listFilterGridColumns","useListGridFilter","useSnackbar","Timestamp","Alert","Box","Button","Chip","Dialog","DialogActions","DialogContent","DialogTitle","MenuItem","Stack","TextField","Tooltip","Typography","collection","deleteDoc","deleteField","doc","endAt","getCountFromServer","getDoc","getDocs","limit","orderBy","query","startAt","where","setDoc","writeBatch","useRouter","useCallback","useEffect","useMemo","useState","useListColumnSort","useFirestore","useFirestoreCollection","useFirestoreDoc","useHostActivityLogger","useOrgDataScope","usePagedCollection","useScopeTokens","useUser","listQueryConstraints","authorizedFetch","DatasetSchemaDialog","DatasetRecordDialog","DatasetRecordFieldList","DatasetRecordSiteContext","datasetRecordFilter","planRecordQuery","recordColumn","coerceDocumentValues","datasetIntegrityUpdate","datasetValueToInput","effectiveDatasetModel","formatDatasetValue","modelFromFieldEntries","validateDocument","fillRecordAddresses","planReferenceFixups","referencingFieldIds","restrictedDeleteMessage","BlockedControl","datasetListScope","DATASETS_EXPORT_REFUSAL","DATASETS_VIEW_RECORDS_REFUSAL","DATASETS_WRITE_REFUSAL","useDatasetWritesBlocked","DATASET_SAMPLE_RECORD_NOTE","datasetDisplayName","isSampleDatasetRecord","parseDatasetFieldEntries","datasetTransferResourceKey","DATASET_RAIL_GROUP_AT","datasetCreatedLabel","datasetPickerLabelsOf","datasetRailName","datasetRecordTitle","datasetRailSecondary","datasetSharingLabel","datasetSourceLabel","groupDatasetsBySharing","sortDatasetsByName","useOrgSites","NO_QUERY_SORTS","EXPORT_OFF_TOOLBAR","toolbar","csvOptions","disableToolbarButton","printOptions","NO_DATASETS","DATASET_LIST_WINDOW","datasetRow","snapshot","$id","id","data","newDatasetSharingNote","siteOnly","HostDatasetsCard","props","routeDatasetId","listed","hostId","basePath","segments","router","scope","dataScope","orgId","tokens","scopeTokens","orgWide","viewerOrgWide","loaded","scopeLoaded","pageHostId","undefined","reachScope","listScope","memberScope","scopeReady","Boolean","firestore","enqueueSnackbar","confirm","org","logActivity","user","createdFromHostId","createdFrom","recordSite","createsSiteOnly","defaultResourceScope","callDatasetApi","payload","response","method","headers","body","JSON","stringify","result","json","catch","ok","Error","error","announceRecords","datasetId","action","console","nameSearch","setNameSearch","sharedWith","setSharedWith","railWindow","setRailWindow","railScope","serverNameKey","hostNames","sites","orgSites","datasetDocs","status","datasetsStatus","fromCache","datasetsFromCache","listen","datasetsListen","idField","datasets","slice","moreDatasets","length","railNarrowed","routeRecordId","selectedId","setSelectedId","wantedId","find","item","listAnswered","linkedRead","linked","notSharedHere","visibleTo","notFound","selected","seed","unreadable","openDataset","push","landing","replace","schemaOpen","setSchemaOpen","blocked","model","fields","order","recordFilter","gridFilter","selectFields","recordClauses","clauses","filter","clause","some","field","column","recordPlan","searchWords","recordPlanKey","filters","plan","rows","records","hasMore","hasMoreRecords","page","recordPage","setPage","setRecordPage","pageSize","recordPageSize","setPageSize","setRecordPageSize","pageLimit","routeRecordRead","routeRecord","routeRecordMissing","recordRefusals","refused","options","filteringRecords","word","trim","datasetCountEpoch","setDatasetCountEpoch","recordCountEpoch","setRecordCountEpoch","serverDatasetCount","setServerDatasetCount","serverRecordCount","setServerRecordCount","active","then","count","countedDatasetId","datasetCount","recordCount","creator","setCreator","handleOpenCreator","variant","persist","quota","allowed","upgradeRequired","addonPriceUsd","name","creatorEntries","creatorFields","map","entry","handleCreate","displayName","String","message","epoch","type","joiner","setJoiner","handleCreateJoin","a","b","fieldFor","target","fieldId","required","reference","displayFieldId","onDelete","aRef","bRef","handleDeleteDataset","confirmed","title","description","toLocaleString","confirmationText","confirmationButtonProps","color","scopeId","kind","outsideTargets","setOutsideTargets","missing","Set","Promise","all","exists","knownDatasets","refOptions","setRefOptions","referenceFields","docs","docSnapshot","label","get","entries","Object","fromEntries","resolveReferenceLabel","option","referenceLabel","value","ids","Array","isArray","join","viewerId","setViewerId","datasetHref","openRecord","encodeURIComponent","viewerRecord","record","editor","setEditor","handleOpenRecord","values","default","errors","sample","handleSaveRecord","coerced","keys","prev","recordRef","updatedAt","now","mergeFields","handleDeleteRecord","afterDelete","alsoChanged","referencing","reach","other","otherModel","holders","start","updates","batch","update","holder","ref","commit","add","transfer","transferTarget","resource","known","importAllowed","writes","canImport","can","canExport","handleImport","dataset","openImport","onFinished","handleExport","openExport","search","recordGridColumns","shown","row","headerName","flex","minWidth","renderCell","direction","spacing","sx","alignItems","height","noWrap","size","justifyContent","onClick","reason","writesReason","width","recordPageSorts","recordSortHeaders","recordColumnSort","sorts","pageSorts","grouped","railSections","tab","group","href","secondary","flatMap","joinLabels","offerSharedWith","sitesByName","sort","localeCompare","railHeader","mb","fullWidth","placeholder","onChange","event","slotProps","htmlInput","select","site","railFooter","px","py","mt","window","facts","factsRow","pairs","useFlexGap","flexWrap","component","overflowWrap","recordTitle","recordPanel","help","anchor","header","startIcon","path","span","contentGutterX","contentGutterY","contentBordered","HeaderProps","subheader","severity","resolveReference","divided","panel","sharingOnly","exports","deletes","deletesReason","ready","used","noun","setClauses","notices","aria-label","pinActions","columnSort","columns","onOpen","hideFooter","filterMode","filterModel","onFilterModelChange","quickFilter","noRowsLabel","rowCount","onPageChange","onPageSizeChange","creates","keepHeading","parentTitle","parentHref","sections","navHeader","scrollRail","open","onClose","maxWidth","display","flexDirection","gap","autoFocus","helperText","disabled","onEdit","Provider","index","setValue","nextValue","common","customFieldType","customType","Input","CustomInput","next","validation","multiple","selectedIds","split","part","inputLabel","shrink","side","seedFromCache","seedUnreadable","seedListen","canChangeSharing","sharingOnlyReason"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAGA,SAASA,oBAAoB,QAAQ,gDAA+C;AACpF,SAEEC,iBAAiB,EACjBC,gBAAgB,EAChBC,UAAU,EACVC,kBAAkB,EAClBC,iBAAiB,EACjBC,gBAAgB,EAChBC,cAAc,EACdC,kBAAkB,EAClBC,mBAAmB,EACnBC,aAAa,QACR,eAAc;AACrB,SAASC,aAAa,QAAQ,qCAAoC;AAClE,SAASC,WAAW,QAAyB,4CAA2C;AACxF,SAASC,OAAO,EAAEC,WAAW,EAAEC,OAAO,EAAEC,sBAAsB,QAAQ,uBAAsB;AAC5F,SAASC,YAAY,QAAQ,yBAAwB;AACrD,OAAOC,qBAAqB,8DAA6D;AACzF,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,OAAOC,oBACLC,iBAAiB,QACZ,+DAA8D;AACrE,SACEC,SAAS,EACTC,iBAAiB,QACZ,uDAAsD;AAC7D,OAAOC,2BAA2B,0DAAyD;AAC3F,SAASC,qBAAqB,QAAQ,8CAA6C;AACnF,SAASC,iBAAiB,QAAQ,kDAAiD;AACnF,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,SAAS,QAAQ,+BAA8B;AACxD,SACEC,KAAK,EACLC,GAAG,EACHC,MAAM,EACNC,IAAI,EACJC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,QAAQ,EACRC,KAAK,EACLC,SAAS,EACTC,OAAO,EACPC,UAAU,QACL,gBAAe;AACtB,SACEC,UAAU,EACVC,SAAS,EACTC,WAAW,EACXC,GAAG,EACHC,KAAK,EACLC,kBAAkB,EAClBC,MAAM,EACNC,OAAO,EACPC,KAAK,EACLC,OAAO,EACPC,KAAK,EACLC,OAAO,EACPC,KAAK,EACLC,MAAM,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8D,mBAAmB5T,QAAQoM,YAAY;YAAC,IAAI,CAAC;gBAC1EyF,SAAS,IAAM9R,cAAc;;;;AAIrC;AACAjG,iBAAiBwK,WAAW,GAAG;AAE/B,eAAexK,iBAAgB"}
@@ -55,12 +55,6 @@ export declare function datasetRailSecondary(dataset: DatasetRailEntry, options:
55
55
  export declare function datasetRailName(dataset: DatasetRailEntry): string;
56
56
  /** Datasets in name order, then id, so two of one name keep their places. */
57
57
  export declare function sortDatasetsByName<T extends DatasetRailEntry>(datasets: readonly T[]): T[];
58
- /**
59
- * Whether a dataset's name starts with what was typed, normalized the way the
60
- * stored `nameLower` is, so the loaded-list search and the query that replaces
61
- * it answer alike.
62
- */
63
- export declare function datasetNameMatches(dataset: DatasetRailEntry, typed: string): boolean;
64
58
  /** One group of the rail: its heading, with how many it holds, and its datasets in name order. */
65
59
  export interface DatasetRailGroup {
66
60
  label: string;
@@ -51,14 +51,6 @@ import { datasetDisplayName } from "./datasets.js";
51
51
  ...datasets
52
52
  ].sort((a, b)=>nameSearchKey(datasetRailName(a)).localeCompare(nameSearchKey(datasetRailName(b))) || a.$id.localeCompare(b.$id));
53
53
  }
54
- /**
55
- * Whether a dataset's name starts with what was typed, normalized the way the
56
- * stored `nameLower` is, so the loaded-list search and the query that replaces
57
- * it answer alike.
58
- */ export function datasetNameMatches(dataset, typed) {
59
- const key = nameSearchKey(typed);
60
- return !key || nameSearchKey(datasetDisplayName(dataset)).startsWith(key);
61
- }
62
54
  /**
63
55
  * The rail's groups by who each dataset is shared with: `Bakery only (6)`.
64
56
  * Groups run in heading order, datasets in name order within each.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/model/dataset-rail.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 { nameSearchKey } from '@aglyn/aglyn/app-utils/name-search'\nimport { describeSharing } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport { type DatasetModel, datasetPickerLabels, effectiveDatasetModel, formatDatasetValue } from './dataset-models'\nimport { datasetDisplayName, type HostDataset } from './datasets'\n\n/**\n * The Data page's rail of datasets (AGL-4047): one tab per dataset, a second\n * line that tells same-named ones apart, a search over the names, and groups\n * by sharing once there are many. Pure, so the card and its specs read the\n * same answers.\n */\n\n/** A dataset as the rail reads it: its document, with the facts it shows. */\nexport type DatasetRailEntry = HostDataset & {\n $id: string\n name?: unknown\n source?: { listingId?: unknown; version?: unknown } | null\n createdAt?: unknown\n scopeMode?: unknown\n scopeExcept?: unknown\n}\n\n/** Past this many datasets the rail groups them by who they are shared with, and offers the Shared with filter. */\nexport const DATASET_RAIL_GROUP_AT = 10\n\n/** How many field names the second line names, in a grouped rail. */\nconst RAIL_FIELD_NAMES = 3\n\n/** `1 field`, `5 fields`. */\nexport function datasetFieldCount(dataset: DatasetRailEntry): string {\n const count = effectiveDatasetModel(dataset).order.length\n return `${count} ${count === 1 ? 'field' : 'fields'}`\n}\n\n/** Who a dataset is shared with, named where `hostNames` has the site: `Bakery only`, `All sites`, `3 sites`. */\nexport function datasetSharingLabel(\n dataset: DatasetRailEntry,\n hostNames: Readonly<Record<string, string>>,\n): string {\n return describeSharing(dataset as unknown as Readonly<Record<string, unknown>>, hostNames)\n}\n\n/**\n * The tab's second line. Ungrouped it says who the dataset is shared with and\n * how many fields it has, which is what tells the same name on two sites\n * apart: `Bakery only · 5 fields`. In a group, whose heading already says who\n * it is shared with, it names the first fields instead:\n * `5 fields · Name, Description, Duration`.\n */\nexport function datasetRailSecondary(\n dataset: DatasetRailEntry,\n options: { hostNames: Readonly<Record<string, string>>; grouped: boolean },\n): string {\n const fields = datasetFieldCount(dataset)\n if (!options.grouped) return `${datasetSharingLabel(dataset, options.hostNames)} · ${fields}`\n const model = effectiveDatasetModel(dataset)\n const names = model.order\n .slice(0, RAIL_FIELD_NAMES)\n .map((id) => model.fields[id]?.name ?? id)\n .filter(Boolean)\n return names.length ? `${fields} · ${names.join(', ')}` : fields\n}\n\n/** A dataset's name for the rail and the page: its display name, or a stand-in when it has none. */\nexport function datasetRailName(dataset: DatasetRailEntry): string {\n return datasetDisplayName(dataset) || 'Untitled dataset'\n}\n\n/** Datasets in name order, then id, so two of one name keep their places. */\nexport function sortDatasetsByName<T extends DatasetRailEntry>(datasets: readonly T[]): T[] {\n return [...datasets].sort(\n (a, b) =>\n nameSearchKey(datasetRailName(a)).localeCompare(nameSearchKey(datasetRailName(b))) ||\n a.$id.localeCompare(b.$id),\n )\n}\n\n/**\n * Whether a dataset's name starts with what was typed, normalized the way the\n * stored `nameLower` is, so the loaded-list search and the query that replaces\n * it answer alike.\n */\nexport function datasetNameMatches(dataset: DatasetRailEntry, typed: string): boolean {\n const key = nameSearchKey(typed)\n return !key || nameSearchKey(datasetDisplayName(dataset)).startsWith(key)\n}\n\n/** One group of the rail: its heading, with how many it holds, and its datasets in name order. */\nexport interface DatasetRailGroup {\n label: string\n datasets: DatasetRailEntry[]\n}\n\n/**\n * The rail's groups by who each dataset is shared with: `Bakery only (6)`.\n * Groups run in heading order, datasets in name order within each.\n */\nexport function groupDatasetsBySharing(\n datasets: readonly DatasetRailEntry[],\n hostNames: Readonly<Record<string, string>>,\n): DatasetRailGroup[] {\n const groups = new Map<string, DatasetRailEntry[]>()\n for (const dataset of datasets) {\n const label = datasetSharingLabel(dataset, hostNames)\n groups.set(label, [...(groups.get(label) ?? []), dataset])\n }\n return [...groups.entries()]\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([label, members]) => ({ label: `${label} (${members.length})`, datasets: sortDatasetsByName(members) }))\n}\n\n/** Where a dataset came from: the marketplace listing it was installed from, or `--` for one made here. */\nexport function datasetSourceLabel(dataset: DatasetRailEntry): string {\n if (!dataset.source?.listingId) return '--'\n const version = Number(dataset.source.version)\n return Number.isFinite(version) && version > 0 ? `Marketplace, version ${version}` : 'Marketplace'\n}\n\n/** When a dataset was created, as a date, or `--` where it was never stamped (a site backup restore stamps none). */\nexport function datasetCreatedLabel(dataset: DatasetRailEntry, locale?: string): string {\n const at = dataset.createdAt as { toDate?: () => Date; seconds?: number } | null | undefined\n const date =\n typeof at?.toDate === 'function'\n ? at.toDate()\n : typeof at?.seconds === 'number'\n ? new Date(at.seconds * 1000)\n : null\n if (!date || Number.isNaN(date.getTime())) return '--'\n return date.toLocaleDateString(locale, { month: 'short', day: 'numeric', year: 'numeric' })\n}\n\n/**\n * A record's own page's heading (AGL-4047): the first field, in the model's\n * order, that shows a value — a reference names an id, so it is passed over —\n * or a stand-in when none does.\n */\nexport function datasetRecordTitle(model: DatasetModel, values: Readonly<Record<string, unknown>> | undefined): string {\n for (const fieldId of model.order) {\n const field = model.fields[fieldId]\n if (!field || field.type === 'reference') continue\n const shown = formatDatasetValue(field, values?.[fieldId]).trim()\n if (shown) return shown\n }\n return 'Untitled record'\n}\n\n/**\n * The picker labels for a list of datasets (AGL-4047), through the pure\n * `datasetPickerLabels`: the name alone unless it collides in the list.\n */\nexport function datasetPickerLabelsOf(\n datasets: readonly DatasetRailEntry[],\n hostNames: Readonly<Record<string, string>> = {},\n): Record<string, string> {\n return datasetPickerLabels(\n datasets.map((dataset) => ({\n id: dataset.$id,\n name: datasetRailName(dataset),\n sharing: datasetSharingLabel(dataset, hostNames),\n fields: effectiveDatasetModel(dataset).order.length,\n })),\n )\n}\n"],"names":["nameSearchKey","describeSharing","datasetPickerLabels","effectiveDatasetModel","formatDatasetValue","datasetDisplayName","DATASET_RAIL_GROUP_AT","RAIL_FIELD_NAMES","datasetFieldCount","dataset","count","order","length","datasetSharingLabel","hostNames","datasetRailSecondary","options","fields","grouped","model","names","slice","map","id","name","filter","Boolean","join","datasetRailName","sortDatasetsByName","datasets","sort","a","b","localeCompare","$id","datasetNameMatches","typed","key","startsWith","groupDatasetsBySharing","groups","Map","label","set","get","entries","members","datasetSourceLabel","source","listingId","version","Number","isFinite","datasetCreatedLabel","locale","at","createdAt","date","toDate","seconds","Date","isNaN","getTime","toLocaleDateString","month","day","year","datasetRecordTitle","values","fieldId","field","type","shown","trim","datasetPickerLabelsOf","sharing"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,QAAQ,qCAAoC;AAClE,SAASC,eAAe,QAAQ,sCAAqC;AACrE,SAA4BC,mBAAmB,EAAEC,qBAAqB,EAAEC,kBAAkB,QAAQ,sBAAkB;AACpH,SAASC,kBAAkB,QAA0B,gBAAY;AAmBjE,iHAAiH,GACjH,OAAO,MAAMC,wBAAwB,GAAE;AAEvC,mEAAmE,GACnE,MAAMC,mBAAmB;AAEzB,2BAA2B,GAC3B,OAAO,SAASC,kBAAkBC,OAAyB;IACzD,MAAMC,QAAQP,sBAAsBM,SAASE,KAAK,CAACC,MAAM;IACzD,OAAO,GAAGF,MAAM,CAAC,EAAEA,UAAU,IAAI,UAAU,UAAU;AACvD;AAEA,+GAA+G,GAC/G,OAAO,SAASG,oBACdJ,OAAyB,EACzBK,SAA2C;IAE3C,OAAOb,gBAAgBQ,SAAyDK;AAClF;AAEA;;;;;;CAMC,GACD,OAAO,SAASC,qBACdN,OAAyB,EACzBO,OAA0E;IAE1E,MAAMC,SAAST,kBAAkBC;IACjC,IAAI,CAACO,QAAQE,OAAO,EAAE,OAAO,GAAGL,oBAAoBJ,SAASO,QAAQF,SAAS,EAAE,GAAG,EAAEG,QAAQ;IAC7F,MAAME,QAAQhB,sBAAsBM;IACpC,MAAMW,QAAQD,MAAMR,KAAK,CACtBU,KAAK,CAAC,GAAGd,kBACTe,GAAG,CAAC,CAACC;;YAAOJ;wBAAAA,mBAAAA,MAAMF,MAAM,CAACM,GAAG,qBAAhBJ,iBAAk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oBJ,SAASK;YACtCG,QAAQd,sBAAsBM,SAASE,KAAK,CAACC,MAAM;QACrD,CAAA;AAEJ"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/model/dataset-rail.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 { nameSearchKey } from '@aglyn/aglyn/app-utils/name-search'\nimport { describeSharing } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport { type DatasetModel, datasetPickerLabels, effectiveDatasetModel, formatDatasetValue } from './dataset-models'\nimport { datasetDisplayName, type HostDataset } from './datasets'\n\n/**\n * The Data page's rail of datasets (AGL-4047): one tab per dataset, a second\n * line that tells same-named ones apart, a search over the names, and groups\n * by sharing once there are many. Pure, so the card and its specs read the\n * same answers.\n */\n\n/** A dataset as the rail reads it: its document, with the facts it shows. */\nexport type DatasetRailEntry = HostDataset & {\n $id: string\n name?: unknown\n source?: { listingId?: unknown; version?: unknown } | null\n createdAt?: unknown\n scopeMode?: unknown\n scopeExcept?: unknown\n}\n\n/** Past this many datasets the rail groups them by who they are shared with, and offers the Shared with filter. */\nexport const DATASET_RAIL_GROUP_AT = 10\n\n/** How many field names the second line names, in a grouped rail. */\nconst RAIL_FIELD_NAMES = 3\n\n/** `1 field`, `5 fields`. */\nexport function datasetFieldCount(dataset: DatasetRailEntry): string {\n const count = effectiveDatasetModel(dataset).order.length\n return `${count} ${count === 1 ? 'field' : 'fields'}`\n}\n\n/** Who a dataset is shared with, named where `hostNames` has the site: `Bakery only`, `All sites`, `3 sites`. */\nexport function datasetSharingLabel(\n dataset: DatasetRailEntry,\n hostNames: Readonly<Record<string, string>>,\n): string {\n return describeSharing(dataset as unknown as Readonly<Record<string, unknown>>, hostNames)\n}\n\n/**\n * The tab's second line. Ungrouped it says who the dataset is shared with and\n * how many fields it has, which is what tells the same name on two sites\n * apart: `Bakery only · 5 fields`. In a group, whose heading already says who\n * it is shared with, it names the first fields instead:\n * `5 fields · Name, Description, Duration`.\n */\nexport function datasetRailSecondary(\n dataset: DatasetRailEntry,\n options: { hostNames: Readonly<Record<string, string>>; grouped: boolean },\n): string {\n const fields = datasetFieldCount(dataset)\n if (!options.grouped) return `${datasetSharingLabel(dataset, options.hostNames)} · ${fields}`\n const model = effectiveDatasetModel(dataset)\n const names = model.order\n .slice(0, RAIL_FIELD_NAMES)\n .map((id) => model.fields[id]?.name ?? id)\n .filter(Boolean)\n return names.length ? `${fields} · ${names.join(', ')}` : fields\n}\n\n/** A dataset's name for the rail and the page: its display name, or a stand-in when it has none. */\nexport function datasetRailName(dataset: DatasetRailEntry): string {\n return datasetDisplayName(dataset) || 'Untitled dataset'\n}\n\n/** Datasets in name order, then id, so two of one name keep their places. */\nexport function sortDatasetsByName<T extends DatasetRailEntry>(datasets: readonly T[]): T[] {\n return [...datasets].sort(\n (a, b) =>\n nameSearchKey(datasetRailName(a)).localeCompare(nameSearchKey(datasetRailName(b))) ||\n a.$id.localeCompare(b.$id),\n )\n}\n\n/** One group of the rail: its heading, with how many it holds, and its datasets in name order. */\nexport interface DatasetRailGroup {\n label: string\n datasets: DatasetRailEntry[]\n}\n\n/**\n * The rail's groups by who each dataset is shared with: `Bakery only (6)`.\n * Groups run in heading order, datasets in name order within each.\n */\nexport function groupDatasetsBySharing(\n datasets: readonly DatasetRailEntry[],\n hostNames: Readonly<Record<string, string>>,\n): DatasetRailGroup[] {\n const groups = new Map<string, DatasetRailEntry[]>()\n for (const dataset of datasets) {\n const label = datasetSharingLabel(dataset, hostNames)\n groups.set(label, [...(groups.get(label) ?? []), dataset])\n }\n return [...groups.entries()]\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([label, members]) => ({ label: `${label} (${members.length})`, datasets: sortDatasetsByName(members) }))\n}\n\n/** Where a dataset came from: the marketplace listing it was installed from, or `--` for one made here. */\nexport function datasetSourceLabel(dataset: DatasetRailEntry): string {\n if (!dataset.source?.listingId) return '--'\n const version = Number(dataset.source.version)\n return Number.isFinite(version) && version > 0 ? `Marketplace, version ${version}` : 'Marketplace'\n}\n\n/** When a dataset was created, as a date, or `--` where it was never stamped (a site backup restore stamps none). */\nexport function datasetCreatedLabel(dataset: DatasetRailEntry, locale?: string): string {\n const at = dataset.createdAt as { toDate?: () => Date; seconds?: number } | null | undefined\n const date =\n typeof at?.toDate === 'function'\n ? at.toDate()\n : typeof at?.seconds === 'number'\n ? new Date(at.seconds * 1000)\n : null\n if (!date || Number.isNaN(date.getTime())) return '--'\n return date.toLocaleDateString(locale, { month: 'short', day: 'numeric', year: 'numeric' })\n}\n\n/**\n * A record's own page's heading (AGL-4047): the first field, in the model's\n * order, that shows a value — a reference names an id, so it is passed over —\n * or a stand-in when none does.\n */\nexport function datasetRecordTitle(model: DatasetModel, values: Readonly<Record<string, unknown>> | undefined): string {\n for (const fieldId of model.order) {\n const field = model.fields[fieldId]\n if (!field || field.type === 'reference') continue\n const shown = formatDatasetValue(field, values?.[fieldId]).trim()\n if (shown) return shown\n }\n return 'Untitled record'\n}\n\n/**\n * The picker labels for a list of datasets (AGL-4047), through the pure\n * `datasetPickerLabels`: the name alone unless it collides in the list.\n */\nexport function datasetPickerLabelsOf(\n datasets: readonly DatasetRailEntry[],\n hostNames: Readonly<Record<string, string>> = {},\n): Record<string, string> {\n return datasetPickerLabels(\n datasets.map((dataset) => ({\n id: dataset.$id,\n name: datasetRailName(dataset),\n sharing: datasetSharingLabel(dataset, hostNames),\n fields: effectiveDatasetModel(dataset).order.length,\n })),\n )\n}\n"],"names":["nameSearchKey","describeSharing","datasetPickerLabels","effectiveDatasetModel","formatDatasetValue","datasetDisplayName","DATASET_RAIL_GROUP_AT","RAIL_FIELD_NAMES","datasetFieldCount","dataset","count","order","length","datasetSharingLabel","hostNames","datasetRailSecondary","options","fields","grouped","model","names","slice","map","id","name","filter","Boolean","join","datasetRailName","sortDatasetsByName","datasets","sort","a","b","localeCompare","$id","groupDatasetsBySharing","groups","Map","label","set","get","entries","members","datasetSourceLabel","source","listingId","version","Number","isFinite","datasetCreatedLabel","locale","at","createdAt","date","toDate","seconds","Date","isNaN","getTime","toLocaleDateString","month","day","year","datasetRecordTitle","values","fieldId","field","type","shown","trim","datasetPickerLabelsOf","sharing"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,QAAQ,qCAAoC;AAClE,SAASC,eAAe,QAAQ,sCAAqC;AACrE,SAA4BC,mBAAmB,EAAEC,qBAAqB,EAAEC,kBAAkB,QAAQ,sBAAkB;AACpH,SAASC,kBAAkB,QAA0B,gBAAY;AAmBjE,iHAAiH,GACjH,OAAO,MAAMC,wBAAwB,GAAE;AAEvC,mEAAmE,GACnE,MAAMC,mBAAmB;AAEzB,2BAA2B,GAC3B,OAAO,SAASC,kBAAkBC,OAAyB;IACzD,MAAMC,QAAQP,sBAAsBM,SAASE,KAAK,CAACC,MAAM;IACzD,OAAO,GAAGF,MAAM,CAAC,EAAEA,UAAU,IAAI,UAAU,UAAU;AACvD;AAEA,+GAA+G,GAC/G,OAAO,SAASG,oBACdJ,OAAyB,EACzBK,SAA2C;IAE3C,OAAOb,gBAAgBQ,SAAyDK;AAClF;AAEA;;;;;;CAMC,GACD,OAAO,SAASC,qBACdN,OAAyB,EACzBO,OAA0E;IAE1E,MAAMC,SAAST,kBAAkBC;IACjC,IAAI,CAACO,QAAQE,OAAO,EAAE,OAAO,GAAGL,oBAAoBJ,SAASO,QAAQF,SAAS,EAAE,GAAG,EAAEG,QAAQ;IAC7F,MAAME,QAAQhB,sBAAsBM;IACpC,MAAMW,QAAQD,MAAMR,KAAK,CACtBU,KAAK,CAAC,GAAGd,k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