@aglyn/plugins-data 1.0.0-beta.264 → 1.0.0-beta.268

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.0.0-beta.264",
3
+ "version": "1.0.0-beta.268",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,20 +25,20 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.0.0-beta.264",
29
- "@aglyn/shared-data-mdi": "1.0.0-beta.264",
30
- "@aglyn/shared-ui-jsx": "1.0.0-beta.264",
31
- "@aglyn/shared-ui-snackstack": "1.0.0-beta.264",
32
- "@aglyn/shared-util-http": "1.0.0-beta.264",
33
- "@aglyn/shared-util-timestamp": "1.0.0-beta.264",
34
- "@aglyn/tenant-data-admin": "1.0.0-beta.264",
35
- "@aglyn/tenant-feature-instance": "1.0.0-beta.264",
36
- "@aglyn/tenant-runtime": "1.0.0-beta.264",
28
+ "@aglyn/aglyn": "1.0.0-beta.268",
29
+ "@aglyn/shared-data-mdi": "1.0.0-beta.268",
30
+ "@aglyn/shared-ui-jsx": "1.0.0-beta.268",
31
+ "@aglyn/shared-ui-snackstack": "1.0.0-beta.268",
32
+ "@aglyn/shared-util-http": "1.0.0-beta.268",
33
+ "@aglyn/shared-util-timestamp": "1.0.0-beta.268",
34
+ "@aglyn/tenant-data-admin": "1.0.0-beta.268",
35
+ "@aglyn/tenant-feature-instance": "1.0.0-beta.268",
36
+ "@aglyn/tenant-runtime": "1.0.0-beta.268",
37
37
  "@swc/helpers": "0.5.23"
38
38
  },
39
39
  "peerDependencies": {
40
40
  "@mui/material": "^9.3.1",
41
- "firebase": "^12.18.0",
41
+ "firebase": "^13.0.0",
42
42
  "firebase-admin": "^14.3.0",
43
43
  "react": "^19.2.8"
44
44
  },
@@ -38,4 +38,26 @@ export declare const DATASET_IMAGE_FIELD_TYPE = "image";
38
38
  export declare const DATASET_IMAGE_VALUE_MAX = 2000;
39
39
  /** Whether a value is a photo address a record may hold. */
40
40
  export declare function isDatasetImageValue(value: unknown): value is string;
41
+ /**
42
+ * The site whose own media library a photo address is in (AGL-3912): the
43
+ * `{hostId}` scope of a site-relative CDN path (`/api/media/cdn/{hostId}/…`)
44
+ * or of a `media:{hostId}/…` reference. `null` for an organization-library
45
+ * photo (`org:…`), which outlives any one site, and for any other address.
46
+ */
47
+ export declare function datasetImageSiteOf(value: unknown): string | null;
48
+ /**
49
+ * The sites a record's photos are in the libraries of (AGL-3912), by host id:
50
+ * every value of the record that is a site-library photo
51
+ * ({@link datasetImageSiteOf}).
52
+ */
53
+ export declare function datasetRecordPhotoSites(record: Readonly<Record<string, unknown>>): string[];
54
+ /**
55
+ * A record without the photos whose site no longer exists (AGL-3912). A
56
+ * site's library goes with the site, so such a photo answers 404 under
57
+ * every address, and a page would draw it broken. The field is left out
58
+ * instead, as a record that never had a photo: a published page prints
59
+ * nothing for it, and a card binding it as its picture leaves the picture
60
+ * out. Returns the record itself when it holds none.
61
+ */
62
+ export declare function datasetRecordWithoutGonePhotos<T extends Readonly<Record<string, unknown>>>(record: T, goneSites: ReadonlySet<string>): T;
41
63
  export declare const DATASET_IMAGE_FIELD: CustomFieldType;
@@ -1,3 +1,4 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
1
2
  /**
2
3
  * @license
3
4
  * Copyright 2026 Aglyn LLC
@@ -13,7 +14,7 @@
13
14
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
15
  * See the License for the specific language governing permissions and
15
16
  * limitations under the License.
16
- */ import { parseMediaRef } from "@aglyn/aglyn/app-utils/media-ref";
17
+ */ import { MEDIA_CDN_ROUTE, mediaRefFromCdnPath, parseMediaRef } from "@aglyn/aglyn/app-utils/media-ref";
17
18
  import { BUNDLE_ID } from "../constants/bundle-common.js";
18
19
  /**
19
20
  * A RECORD'S PHOTO (AGL-3616): the "Image" field type, riding `text` storage.
@@ -40,6 +41,48 @@ import { BUNDLE_ID } from "../constants/bundle-common.js";
40
41
  if (value.startsWith('/')) return !value.startsWith('//');
41
42
  return /^https:\/\/[^/]+/.test(value);
42
43
  }
44
+ /**
45
+ * The site whose own media library a photo address is in (AGL-3912): the
46
+ * `{hostId}` scope of a site-relative CDN path (`/api/media/cdn/{hostId}/…`)
47
+ * or of a `media:{hostId}/…` reference. `null` for an organization-library
48
+ * photo (`org:…`), which outlives any one site, and for any other address.
49
+ */ export function datasetImageSiteOf(value) {
50
+ if (typeof value !== 'string') return null;
51
+ const ref = value.startsWith('media:') ? parseMediaRef(value) : value.startsWith(`${MEDIA_CDN_ROUTE}/`) ? parseMediaRef(mediaRefFromCdnPath(value)) : null;
52
+ return ref && !ref.scope.startsWith('org:') ? ref.scope : null;
53
+ }
54
+ /**
55
+ * The sites a record's photos are in the libraries of (AGL-3912), by host id:
56
+ * every value of the record that is a site-library photo
57
+ * ({@link datasetImageSiteOf}).
58
+ */ export function datasetRecordPhotoSites(record) {
59
+ const sites = new Set();
60
+ for (const value of Object.values(record)){
61
+ const site = datasetImageSiteOf(value);
62
+ if (site) sites.add(site);
63
+ }
64
+ return [
65
+ ...sites
66
+ ];
67
+ }
68
+ /**
69
+ * A record without the photos whose site no longer exists (AGL-3912). A
70
+ * site's library goes with the site, so such a photo answers 404 under
71
+ * every address, and a page would draw it broken. The field is left out
72
+ * instead, as a record that never had a photo: a published page prints
73
+ * nothing for it, and a card binding it as its picture leaves the picture
74
+ * out. Returns the record itself when it holds none.
75
+ */ export function datasetRecordWithoutGonePhotos(record, goneSites) {
76
+ if (!goneSites.size) return record;
77
+ const gone = Object.entries(record).filter(([, value])=>{
78
+ const site = datasetImageSiteOf(value);
79
+ return site !== null && goneSites.has(site);
80
+ });
81
+ if (!gone.length) return record;
82
+ const next = _extends({}, record);
83
+ for (const [key] of gone)delete next[key];
84
+ return next;
85
+ }
43
86
  export const DATASET_IMAGE_FIELD = {
44
87
  name: DATASET_IMAGE_FIELD_TYPE,
45
88
  pluginId: BUNDLE_ID,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/model/dataset-image-field.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 { parseMediaRef } from '@aglyn/aglyn/app-utils/media-ref'\nimport type { CustomFieldType } from '@aglyn/aglyn/plugin-manager/custom-fields'\nimport { BUNDLE_ID } from '../constants/bundle-common'\n\n/**\n * A RECORD'S PHOTO (AGL-3616): the \"Image\" field type, riding `text` storage.\n *\n * A portfolio's pieces, a team, a menu, a studio's classes are lists a\n * visitor looks at before reading, so their records carry a photo, and the\n * page that repeats over them binds it as an Image's `src`\n * (`{{item.<field>}}`). The value is an address the site's own Image element\n * shows: the media library's CDN path (`/api/media/cdn/{scope}/{mediaId}`,\n * the form a picker writes into a product), a `media:` reference, another\n * path on the site, or an https address. Nothing else is a picture a page can\n * draw, so nothing else is stored.\n *\n * A `media:` reference is read by `parseMediaRef`, the grammar that minted\n * it, so a photo from the organization library (`media:org:{orgId}/{id}`,\n * whose scope holds a colon) and a content-pinned one (`…@{hash}`) are the\n * same photo as a site's own (AGL-3763).\n */\n\n/** The custom field type a record's photo rides. Persisted on field definitions — never rename. */\nexport const DATASET_IMAGE_FIELD_TYPE = 'image'\n\n/** The longest photo address kept. */\nexport const DATASET_IMAGE_VALUE_MAX = 2_000\n\n/** Whether a value is a photo address a record may hold. */\nexport function isDatasetImageValue(value: unknown): value is string {\n if (typeof value !== 'string' || !value || value.length > DATASET_IMAGE_VALUE_MAX) return false\n if (/[\\s\"'<>\\\\]/.test(value)) return false\n if (value.startsWith('media:')) return parseMediaRef(value) !== null\n if (value.startsWith('/')) return !value.startsWith('//')\n return /^https:\\/\\/[^/]+/.test(value)\n}\n\nexport const DATASET_IMAGE_FIELD: CustomFieldType = {\n name: DATASET_IMAGE_FIELD_TYPE,\n pluginId: BUNDLE_ID,\n label: 'Image',\n baseType: 'text',\n description: 'A photo from the media library, or an https link to one',\n validate: (value) => (isDatasetImageValue(value) ? null : 'Use a photo from the media library or an https link'),\n}\n"],"names":["parseMediaRef","BUNDLE_ID","DATASET_IMAGE_FIELD_TYPE","DATASET_IMAGE_VALUE_MAX","isDatasetImageValue","value","length","test","startsWith","DATASET_IMAGE_FIELD","name","pluginId","label","baseType","description","validate"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,QAAQ,mCAAkC;AAEhE,SAASC,SAAS,QAAQ,gCAA4B;AAEtD;;;;;;;;;;;;;;;;CAgBC,GAED,iGAAiG,GACjG,OAAO,MAAMC,2BAA2B,QAAO;AAE/C,oCAAoC,GACpC,OAAO,MAAMC,0BAA0B,KAAK;AAE5C,0DAA0D,GAC1D,OAAO,SAASC,oBAAoBC,KAAc;IAChD,IAAI,OAAOA,UAAU,YAAY,CAACA,SAASA,MAAMC,MAAM,GAAGH,yBAAyB,OAAO;IAC1F,IAAI,aAAaI,IAAI,CAACF,QAAQ,OAAO;IACrC,IAAIA,MAAMG,UAAU,CAAC,WAAW,OAAOR,cAAcK,WAAW;IAChE,IAAIA,MAAMG,UAAU,CAAC,MAAM,OAAO,CAACH,MAAMG,UAAU,CAAC;IACpD,OAAO,mBAAmBD,IAAI,CAACF;AACjC;AAEA,OAAO,MAAMI,sBAAuC;IAClDC,MAAMR;IACNS,UAAUV;IACVW,OAAO;IACPC,UAAU;IACVC,aAAa;IACbC,UAAU,CAACV,QAAWD,oBAAoBC,SAAS,OAAO;AAC5D,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/model/dataset-image-field.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 { MEDIA_CDN_ROUTE, mediaRefFromCdnPath, parseMediaRef } from '@aglyn/aglyn/app-utils/media-ref'\nimport type { CustomFieldType } from '@aglyn/aglyn/plugin-manager/custom-fields'\nimport { BUNDLE_ID } from '../constants/bundle-common'\n\n/**\n * A RECORD'S PHOTO (AGL-3616): the \"Image\" field type, riding `text` storage.\n *\n * A portfolio's pieces, a team, a menu, a studio's classes are lists a\n * visitor looks at before reading, so their records carry a photo, and the\n * page that repeats over them binds it as an Image's `src`\n * (`{{item.<field>}}`). The value is an address the site's own Image element\n * shows: the media library's CDN path (`/api/media/cdn/{scope}/{mediaId}`,\n * the form a picker writes into a product), a `media:` reference, another\n * path on the site, or an https address. Nothing else is a picture a page can\n * draw, so nothing else is stored.\n *\n * A `media:` reference is read by `parseMediaRef`, the grammar that minted\n * it, so a photo from the organization library (`media:org:{orgId}/{id}`,\n * whose scope holds a colon) and a content-pinned one (`…@{hash}`) are the\n * same photo as a site's own (AGL-3763).\n */\n\n/** The custom field type a record's photo rides. Persisted on field definitions — never rename. */\nexport const DATASET_IMAGE_FIELD_TYPE = 'image'\n\n/** The longest photo address kept. */\nexport const DATASET_IMAGE_VALUE_MAX = 2_000\n\n/** Whether a value is a photo address a record may hold. */\nexport function isDatasetImageValue(value: unknown): value is string {\n if (typeof value !== 'string' || !value || value.length > DATASET_IMAGE_VALUE_MAX) return false\n if (/[\\s\"'<>\\\\]/.test(value)) return false\n if (value.startsWith('media:')) return parseMediaRef(value) !== null\n if (value.startsWith('/')) return !value.startsWith('//')\n return /^https:\\/\\/[^/]+/.test(value)\n}\n\n/**\n * The site whose own media library a photo address is in (AGL-3912): the\n * `{hostId}` scope of a site-relative CDN path (`/api/media/cdn/{hostId}/…`)\n * or of a `media:{hostId}/…` reference. `null` for an organization-library\n * photo (`org:…`), which outlives any one site, and for any other address.\n */\nexport function datasetImageSiteOf(value: unknown): string | null {\n if (typeof value !== 'string') return null\n const ref = value.startsWith('media:')\n ? parseMediaRef(value)\n : value.startsWith(`${MEDIA_CDN_ROUTE}/`)\n ? parseMediaRef(mediaRefFromCdnPath(value))\n : null\n return ref && !ref.scope.startsWith('org:') ? ref.scope : null\n}\n\n/**\n * The sites a record's photos are in the libraries of (AGL-3912), by host id:\n * every value of the record that is a site-library photo\n * ({@link datasetImageSiteOf}).\n */\nexport function datasetRecordPhotoSites(record: Readonly<Record<string, unknown>>): string[] {\n const sites = new Set<string>()\n for (const value of Object.values(record)) {\n const site = datasetImageSiteOf(value)\n if (site) sites.add(site)\n }\n return [...sites]\n}\n\n/**\n * A record without the photos whose site no longer exists (AGL-3912). A\n * site's library goes with the site, so such a photo answers 404 under\n * every address, and a page would draw it broken. The field is left out\n * instead, as a record that never had a photo: a published page prints\n * nothing for it, and a card binding it as its picture leaves the picture\n * out. Returns the record itself when it holds none.\n */\nexport function datasetRecordWithoutGonePhotos<T extends Readonly<Record<string, unknown>>>(\n record: T,\n goneSites: ReadonlySet<string>,\n): T {\n if (!goneSites.size) return record\n const gone = Object.entries(record).filter(([, value]) => {\n const site = datasetImageSiteOf(value)\n return site !== null && goneSites.has(site)\n })\n if (!gone.length) return record\n const next: Record<string, unknown> = { ...record }\n for (const [key] of gone) delete next[key]\n return next as T\n}\n\nexport const DATASET_IMAGE_FIELD: CustomFieldType = {\n name: DATASET_IMAGE_FIELD_TYPE,\n pluginId: BUNDLE_ID,\n label: 'Image',\n baseType: 'text',\n description: 'A photo from the media library, or an https link to one',\n validate: (value) => (isDatasetImageValue(value) ? null : 'Use a photo from the media library or an https link'),\n}\n"],"names":["MEDIA_CDN_ROUTE","mediaRefFromCdnPath","parseMediaRef","BUNDLE_ID","DATASET_IMAGE_FIELD_TYPE","DATASET_IMAGE_VALUE_MAX","isDatasetImageValue","value","length","test","startsWith","datasetImageSiteOf","ref","scope","datasetRecordPhotoSites","record","sites","Set","Object","values","site","add","datasetRecordWithoutGonePhotos","goneSites","size","gone","entries","filter","has","next","key","DATASET_IMAGE_FIELD","name","pluginId","label","baseType","description","validate"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,eAAe,EAAEC,mBAAmB,EAAEC,aAAa,QAAQ,mCAAkC;AAEtG,SAASC,SAAS,QAAQ,gCAA4B;AAEtD;;;;;;;;;;;;;;;;CAgBC,GAED,iGAAiG,GACjG,OAAO,MAAMC,2BAA2B,QAAO;AAE/C,oCAAoC,GACpC,OAAO,MAAMC,0BAA0B,KAAK;AAE5C,0DAA0D,GAC1D,OAAO,SAASC,oBAAoBC,KAAc;IAChD,IAAI,OAAOA,UAAU,YAAY,CAACA,SAASA,MAAMC,MAAM,GAAGH,yBAAyB,OAAO;IAC1F,IAAI,aAAaI,IAAI,CAACF,QAAQ,OAAO;IACrC,IAAIA,MAAMG,UAAU,CAAC,WAAW,OAAOR,cAAcK,WAAW;IAChE,IAAIA,MAAMG,UAAU,CAAC,MAAM,OAAO,CAACH,MAAMG,UAAU,CAAC;IACpD,OAAO,mBAAmBD,IAAI,CAACF;AACjC;AAEA;;;;;CAKC,GACD,OAAO,SAASI,mBAAmBJ,KAAc;IAC/C,IAAI,OAAOA,UAAU,UAAU,OAAO;IACtC,MAAMK,MAAML,MAAMG,UAAU,CAAC,YACzBR,cAAcK,SACdA,MAAMG,UAAU,CAAC,GAAGV,gBAAgB,CAAC,CAAC,IACpCE,cAAcD,oBAAoBM,UAClC;IACN,OAAOK,OAAO,CAACA,IAAIC,KAAK,CAACH,UAAU,CAAC,UAAUE,IAAIC,KAAK,GAAG;AAC5D;AAEA;;;;CAIC,GACD,OAAO,SAASC,wBAAwBC,MAAyC;IAC/E,MAAMC,QAAQ,IAAIC;IAClB,KAAK,MAAMV,SAASW,OAAOC,MAAM,CAACJ,QAAS;QACzC,MAAMK,OAAOT,mBAAmBJ;QAChC,IAAIa,MAAMJ,MAAMK,GAAG,CAACD;IACtB;IACA,OAAO;WAAIJ;KAAM;AACnB;AAEA;;;;;;;CAOC,GACD,OAAO,SAASM,+BACdP,MAAS,EACTQ,SAA8B;IAE9B,IAAI,CAACA,UAAUC,IAAI,EAAE,OAAOT;IAC5B,MAAMU,OAAOP,OAAOQ,OAAO,CAACX,QAAQY,MAAM,CAAC,CAAC,GAAGpB,MAAM;QACnD,MAAMa,OAAOT,mBAAmBJ;QAChC,OAAOa,SAAS,QAAQG,UAAUK,GAAG,CAACR;IACxC;IACA,IAAI,CAACK,KAAKjB,MAAM,EAAE,OAAOO;IACzB,MAAMc,OAAgC,aAAKd;IAC3C,KAAK,MAAM,CAACe,IAAI,IAAIL,KAAM,OAAOI,IAAI,CAACC,IAAI;IAC1C,OAAOD;AACT;AAEA,OAAO,MAAME,sBAAuC;IAClDC,MAAM5B;IACN6B,UAAU9B;IACV+B,OAAO;IACPC,UAAU;IACVC,aAAa;IACbC,UAAU,CAAC9B,QAAWD,oBAAoBC,SAAS,OAAO;AAC5D,EAAC"}
@@ -19,6 +19,8 @@ import { firebaseAdmin, orgDataQueryForHost } from "@aglyn/tenant-data-admin";
19
19
  import { PUBLISHED_SITE_DATA_TTL_SECONDS, tenantDataTag, withRenderCache } from "@aglyn/tenant-data-admin/render-cache";
20
20
  import { datasetFilterValuePath, effectiveDatasetModel, repeatRowsModelOf } from "../model/dataset-models.js";
21
21
  import { datasetDisplayName, sortDatasetRecords } from "../model/datasets.js";
22
+ import { datasetRecordWithoutGonePhotos } from "../model/dataset-image-field.js";
23
+ import { goneSitesOfRecords } from "../repeat/gone-site-photos.server.js";
22
24
  import { DATASET_RECORD_PAGES_COLLECTION, RECORD_PAGES_MAX_PER_SITE, parseRecordPageBinding, recordAddressOf, referencedRecordIds } from "./record-pages.js";
23
25
  /**
24
26
  * A site's record templates (AGL-3475), read once per render cache window and
@@ -126,9 +128,13 @@ async function readRecordUncached(hostId, binding, address) {
126
128
  $id: doc.id
127
129
  }, doc.data())).filter((record)=>recordAddressOf(record.values, binding.slugField) === address));
128
130
  if (!match) return null;
129
- const record = _extends({}, (_match_values = match.values) != null ? _match_values : {}, {
131
+ // A photo of a site since deleted is left out, never drawn broken (AGL-3912).
132
+ const values = _extends({}, (_match_values = match.values) != null ? _match_values : {}, {
130
133
  $id: match.$id
131
134
  });
135
+ const record = datasetRecordWithoutGonePhotos(values, await goneSitesOfRecords(hostId, [
136
+ values
137
+ ]));
132
138
  return {
133
139
  dataset: {
134
140
  id: dataset.id,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/record-pages/record-page-read.server.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { type RepeatableDataset, visibleToHost } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, orgDataQueryForHost } from '@aglyn/tenant-data-admin'\nimport {\n PUBLISHED_SITE_DATA_TTL_SECONDS,\n tenantDataTag,\n withRenderCache,\n} from '@aglyn/tenant-data-admin/render-cache'\nimport {\n datasetFilterValuePath,\n type DatasetModel,\n effectiveDatasetModel,\n repeatRowsModelOf,\n} from '../model/dataset-models'\nimport {\n datasetDisplayName,\n type HostDataset,\n type HostDatasetRecord,\n sortDatasetRecords,\n} from '../model/datasets'\nimport {\n DATASET_RECORD_PAGES_COLLECTION,\n type DatasetRecordPageBinding,\n RECORD_PAGES_MAX_PER_SITE,\n parseRecordPageBinding,\n recordAddressOf,\n referencedRecordIds,\n} from './record-pages'\n\n/**\n * A site's record templates (AGL-3475), read once per render cache window and\n * dropped with everything else the site caches under `tenant-data:{hostId}`,\n * which every binding change busts.\n *\n * Asked on every request no published page claims, so it is one small cached\n * read, bounded by {@link RECORD_PAGES_MAX_PER_SITE}. A site with none caches\n * the empty list, which is the answer for almost every site.\n */\nexport async function readSiteRecordPageBindings(\n hostId: string,\n): Promise<DatasetRecordPageBinding[]> {\n const read = async () => {\n const snapshot = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection(DATASET_RECORD_PAGES_COLLECTION)\n .limit(RECORD_PAGES_MAX_PER_SITE)\n .get()\n return snapshot.docs\n .map((doc) => parseRecordPageBinding(doc.id, doc.data()))\n .filter((binding): binding is DatasetRecordPageBinding => binding != null)\n }\n try {\n return await withRenderCache({\n key: ['tenant-record-pages', 'v1', hostId],\n revalidate: PUBLISHED_SITE_DATA_TTL_SECONDS,\n tags: [tenantDataTag(hostId)],\n read,\n })\n } catch (error) {\n console.error('record page bindings: cached read failed', error)\n return read()\n }\n}\n\n/** A dataset this site may see, with its model, or `null`. */\nexport interface SiteDataset {\n id: string\n name: string\n model: DatasetModel\n ref: FirebaseFirestore.DocumentReference\n}\n\n/**\n * The dataset a binding names, when THIS site may see it — the rule the\n * published repeat reader applies (`visibleTo`, AGL-1039), checked on the\n * document because a keyed read bypasses the scoped query. A deleted dataset,\n * or one no longer shared with the site, is `null`, and its record pages stop\n * serving rather than serving what the site may no longer show.\n */\nexport async function readSiteDataset(\n hostId: string,\n datasetId: string,\n): Promise<SiteDataset | null> {\n if (!datasetId || datasetId.includes('/')) return null\n const { ref } = await orgDataQueryForHost(hostId, 'datasets')\n const snapshot = await ref.doc(datasetId).get()\n const orgScoped = ref.parent?.parent?.id === 'orgs'\n if (\n !snapshot.exists ||\n snapshot.get('deletedAt') ||\n (orgScoped && !visibleToHost(snapshot.get('visibleTo'), hostId))\n ) {\n return null\n }\n const data = snapshot.data() as HostDataset\n return {\n id: snapshot.id,\n name: datasetDisplayName(data),\n model: effectiveDatasetModel(data),\n ref: snapshot.ref,\n }\n}\n\n/** One routed record, ready for the template: its row and its one hop. */\nexport interface RecordPageRecord {\n dataset: { id: string; name: string; model: DatasetModel }\n /** The record's values, with `$id` inside like a repeated row. */\n record: Record<string, unknown>\n /** The datasets its reference fields point into, for one-hop tokens. */\n datasetsByKey: Record<string, RepeatableDataset>\n /** The record's write time, for the sitemap's and the head's dates. */\n updatedAt?: unknown\n}\n\n/** How many records the indexed lookup reads for one address. */\nconst ADDRESS_LOOKUP_LIMIT = 10\n\n/**\n * The record a binding serves at `address`, or `null` — an unknown address,\n * a dataset the site may not see, a slug field the model no longer has.\n *\n * Found through `filterValues.<slugField>`, the equality index every record\n * write keeps (AGL-3321): a page address is stored normalized, which is\n * exactly the key a plain text value's entry holds, so the lookup needs no\n * index of its own. The candidates are then matched on the stored value\n * itself, and when two records share an address the one first in the\n * dataset's own order serves — the order a repeat lists them in.\n */\nexport async function readRecordPageRecord(\n hostId: string,\n binding: DatasetRecordPageBinding,\n address: string,\n): Promise<RecordPageRecord | null> {\n const read = () => readRecordUncached(hostId, binding, address)\n try {\n // `null` is not cached (the cache stores only a defined answer), so an\n // address that starts existing is found on its next request.\n return (\n (await withRenderCache({\n key: [\n 'tenant-record-page',\n 'v1',\n hostId,\n binding.datasetId,\n binding.slugField,\n address,\n ],\n revalidate: PUBLISHED_SITE_DATA_TTL_SECONDS,\n tags: [tenantDataTag(hostId)],\n read: async () => (await read()) ?? undefined,\n })) ?? null\n )\n } catch (error) {\n console.error('record page: cached read failed', error)\n return read()\n }\n}\n\nasync function readRecordUncached(\n hostId: string,\n binding: DatasetRecordPageBinding,\n address: string,\n): Promise<RecordPageRecord | null> {\n const dataset = await readSiteDataset(hostId, binding.datasetId)\n if (!dataset) return null\n const field = dataset.model.fields[binding.slugField]\n const path = datasetFilterValuePath(binding.slugField)\n if (!field || field.type !== 'text' || !path) return null\n const snapshot = await dataset.ref\n .collection('records')\n .where(path, '==', address)\n .limit(ADDRESS_LOOKUP_LIMIT)\n .get()\n const [match] = sortDatasetRecords(\n snapshot.docs\n .map((doc) => ({ $id: doc.id, ...(doc.data() as HostDatasetRecord) }))\n .filter((record) => recordAddressOf(record.values, binding.slugField) === address),\n )\n if (!match) return null\n const record = { ...(match.values ?? {}), $id: match.$id }\n return {\n dataset: { id: dataset.id, name: dataset.name, model: dataset.model },\n record,\n datasetsByKey: await readReferenceHops(hostId, dataset.model, record),\n updatedAt: (match as { updatedAt?: unknown }).updatedAt,\n }\n}\n\n/**\n * The records a routed record's reference fields point at, keyed by the\n * dataset each lives in — just those records, by id, rather than the first\n * hundred rows a repeat would read. A target the site may not see is left\n * out, and its token stays as written, as in a repeat.\n */\nasync function readReferenceHops(\n hostId: string,\n model: DatasetModel,\n record: Record<string, unknown>,\n): Promise<Record<string, RepeatableDataset>> {\n const wanted = referencedRecordIds(repeatRowsModelOf(model), record)\n const answer: Record<string, RepeatableDataset> = {}\n await Promise.all(\n [...wanted].map(async ([datasetId, ids]) => {\n try {\n const target = await readSiteDataset(hostId, datasetId)\n if (!target) return\n const docs = await Promise.all(\n [...ids].map((id) => target.ref.collection('records').doc(id).get()),\n )\n answer[datasetId] = {\n records: docs\n .filter((doc) => doc.exists)\n .map((doc) => ({\n ...((doc.data() as HostDatasetRecord).values ?? {}),\n $id: doc.id,\n })),\n }\n } catch (error) {\n console.error('record page: reference hop failed', error)\n }\n }),\n )\n return answer\n}\n"],"names":["visibleToHost","firebaseAdmin","orgDataQueryForHost","PUBLISHED_SITE_DATA_TTL_SECONDS","tenantDataTag","withRenderCache","datasetFilterValuePath","effectiveDatasetModel","repeatRowsModelOf","datasetDisplayName","sortDatasetRecords","DATASET_RECORD_PAGES_COLLECTION","RECORD_PAGES_MAX_PER_SITE","parseRecordPageBinding","recordAddressOf","referencedRecordIds","readSiteRecordPageBindings","hostId","read","snapshot","app","firestore","collection","doc","limit","get","docs","map","id","data","filter","binding","key","revalidate","tags","error","console","readSiteDataset","datasetId","ref","includes","orgScoped","parent","exists","name","model","ADDRESS_LOOKUP_LIMIT","readRecordPageRecord","address","readRecordUncached","slugField","undefined","match","dataset","field","fields","path","type","where","$id","record","values","datasetsByKey","readReferenceHops","updatedAt","wanted","answer","Promise","all","ids","target","records"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAAiCA,aAAa,QAAQ,sBAAqB;AAC3E,SAASC,aAAa,EAAEC,mBAAmB,QAAQ,2BAA0B;AAC7E,SACEC,+BAA+B,EAC/BC,aAAa,EACbC,eAAe,QACV,wCAAuC;AAC9C,SACEC,sBAAsB,EAEtBC,qBAAqB,EACrBC,iBAAiB,QACZ,6BAAyB;AAChC,SACEC,kBAAkB,EAGlBC,kBAAkB,QACb,uBAAmB;AAC1B,SACEC,+BAA+B,EAE/BC,yBAAyB,EACzBC,sBAAsB,EACtBC,eAAe,EACfC,mBAAmB,QACd,oBAAgB;AAEvB;;;;;;;;CAQC,GACD,OAAO,eAAeC,2BACpBC,MAAc;IAEd,MAAMC,OAAO;QACX,MAAMC,WAAW,MAAMlB,cACpBmB,GAAG,GACHC,SAAS,GACTC,UAAU,CAAC,SACXC,GAAG,CAACN,QACJK,UAAU,CAACX,iCACXa,KAAK,CAACZ,2BACNa,GAAG;QACN,OAAON,SAASO,IAAI,CACjBC,GAAG,CAAC,CAACJ,MAAQV,uBAAuBU,IAAIK,EAAE,EAAEL,IAAIM,IAAI,KACpDC,MAAM,CAAC,CAACC,UAAiDA,WAAW;IACzE;IACA,IAAI;QACF,OAAO,MAAM1B,gBAAgB;YAC3B2B,KAAK;gBAAC;gBAAuB;gBAAMf;aAAO;YAC1C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C,GACD,eAAeD,kBACb9C,MAAc,EACd4B,KAAmB,EACnBe,MAA+B;IAE/B,MAAMK,SAASlD,oBAAoBP,kBAAkBqC,QAAQe;IAC7D,MAAMM,SAA4C,CAAC;IACnD,MAAMC,QAAQC,GAAG,CACf;WAAIH;KAAO,CAACtC,GAAG,CAAC,OAAO,CAACW,WAAW+B,IAAI;QACrC,IAAI;YACF,MAAMC,SAAS,MAAMjC,gBAAgBpB,QAAQqB;YAC7C,IAAI,CAACgC,QAAQ;YACb,MAAM5C,OAAO,MAAMyC,QAAQC,GAAG,CAC5B;mBAAIC;aAAI,CAAC1C,GAAG,CAAC,CAACC,KAAO0C,OAAO/B,GAAG,CAACjB,UAAU,CAAC,WAAWC,GAAG,CAACK,IAAIH,GAAG;YAEnEyC,MAAM,CAAC5B,UAAU,GAAG;gBAClBiC,SAAS7C,KACNI,MAAM,CAAC,CAACP,MAAQA,IAAIoB,MAAM,EAC1BhB,GAAG,CAAC,CAACJ;wBACA;2BADS,cACT,mBAAA,AAACA,IAAIM,IAAI,GAAyBgC,MAAM,YAAxC,mBAA4C,CAAC;wBACjDF,KAAKpC,IAAIK,EAAE;;;YAEjB;QACF,EAAE,OAAOO,OAAO;YACdC,QAAQD,KAAK,CAAC,qCAAqCA;QACrD;IACF;IAEF,OAAO+B;AACT"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/record-pages/record-page-read.server.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { type RepeatableDataset, visibleToHost } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, orgDataQueryForHost } from '@aglyn/tenant-data-admin'\nimport {\n PUBLISHED_SITE_DATA_TTL_SECONDS,\n tenantDataTag,\n withRenderCache,\n} from '@aglyn/tenant-data-admin/render-cache'\nimport {\n datasetFilterValuePath,\n type DatasetModel,\n effectiveDatasetModel,\n repeatRowsModelOf,\n} from '../model/dataset-models'\nimport {\n datasetDisplayName,\n type HostDataset,\n type HostDatasetRecord,\n sortDatasetRecords,\n} from '../model/datasets'\nimport { datasetRecordWithoutGonePhotos } from '../model/dataset-image-field'\nimport { goneSitesOfRecords } from '../repeat/gone-site-photos.server'\nimport {\n DATASET_RECORD_PAGES_COLLECTION,\n type DatasetRecordPageBinding,\n RECORD_PAGES_MAX_PER_SITE,\n parseRecordPageBinding,\n recordAddressOf,\n referencedRecordIds,\n} from './record-pages'\n\n/**\n * A site's record templates (AGL-3475), read once per render cache window and\n * dropped with everything else the site caches under `tenant-data:{hostId}`,\n * which every binding change busts.\n *\n * Asked on every request no published page claims, so it is one small cached\n * read, bounded by {@link RECORD_PAGES_MAX_PER_SITE}. A site with none caches\n * the empty list, which is the answer for almost every site.\n */\nexport async function readSiteRecordPageBindings(\n hostId: string,\n): Promise<DatasetRecordPageBinding[]> {\n const read = async () => {\n const snapshot = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection(DATASET_RECORD_PAGES_COLLECTION)\n .limit(RECORD_PAGES_MAX_PER_SITE)\n .get()\n return snapshot.docs\n .map((doc) => parseRecordPageBinding(doc.id, doc.data()))\n .filter((binding): binding is DatasetRecordPageBinding => binding != null)\n }\n try {\n return await withRenderCache({\n key: ['tenant-record-pages', 'v1', hostId],\n revalidate: PUBLISHED_SITE_DATA_TTL_SECONDS,\n tags: [tenantDataTag(hostId)],\n read,\n })\n } catch (error) {\n console.error('record page bindings: cached read failed', error)\n return read()\n }\n}\n\n/** A dataset this site may see, with its model, or `null`. */\nexport interface SiteDataset {\n id: string\n name: string\n model: DatasetModel\n ref: FirebaseFirestore.DocumentReference\n}\n\n/**\n * The dataset a binding names, when THIS site may see it — the rule the\n * published repeat reader applies (`visibleTo`, AGL-1039), checked on the\n * document because a keyed read bypasses the scoped query. A deleted dataset,\n * or one no longer shared with the site, is `null`, and its record pages stop\n * serving rather than serving what the site may no longer show.\n */\nexport async function readSiteDataset(\n hostId: string,\n datasetId: string,\n): Promise<SiteDataset | null> {\n if (!datasetId || datasetId.includes('/')) return null\n const { ref } = await orgDataQueryForHost(hostId, 'datasets')\n const snapshot = await ref.doc(datasetId).get()\n const orgScoped = ref.parent?.parent?.id === 'orgs'\n if (\n !snapshot.exists ||\n snapshot.get('deletedAt') ||\n (orgScoped && !visibleToHost(snapshot.get('visibleTo'), hostId))\n ) {\n return null\n }\n const data = snapshot.data() as HostDataset\n return {\n id: snapshot.id,\n name: datasetDisplayName(data),\n model: effectiveDatasetModel(data),\n ref: snapshot.ref,\n }\n}\n\n/** One routed record, ready for the template: its row and its one hop. */\nexport interface RecordPageRecord {\n dataset: { id: string; name: string; model: DatasetModel }\n /** The record's values, with `$id` inside like a repeated row. */\n record: Record<string, unknown>\n /** The datasets its reference fields point into, for one-hop tokens. */\n datasetsByKey: Record<string, RepeatableDataset>\n /** The record's write time, for the sitemap's and the head's dates. */\n updatedAt?: unknown\n}\n\n/** How many records the indexed lookup reads for one address. */\nconst ADDRESS_LOOKUP_LIMIT = 10\n\n/**\n * The record a binding serves at `address`, or `null` — an unknown address,\n * a dataset the site may not see, a slug field the model no longer has.\n *\n * Found through `filterValues.<slugField>`, the equality index every record\n * write keeps (AGL-3321): a page address is stored normalized, which is\n * exactly the key a plain text value's entry holds, so the lookup needs no\n * index of its own. The candidates are then matched on the stored value\n * itself, and when two records share an address the one first in the\n * dataset's own order serves — the order a repeat lists them in.\n */\nexport async function readRecordPageRecord(\n hostId: string,\n binding: DatasetRecordPageBinding,\n address: string,\n): Promise<RecordPageRecord | null> {\n const read = () => readRecordUncached(hostId, binding, address)\n try {\n // `null` is not cached (the cache stores only a defined answer), so an\n // address that starts existing is found on its next request.\n return (\n (await withRenderCache({\n key: [\n 'tenant-record-page',\n 'v1',\n hostId,\n binding.datasetId,\n binding.slugField,\n address,\n ],\n revalidate: PUBLISHED_SITE_DATA_TTL_SECONDS,\n tags: [tenantDataTag(hostId)],\n read: async () => (await read()) ?? undefined,\n })) ?? null\n )\n } catch (error) {\n console.error('record page: cached read failed', error)\n return read()\n }\n}\n\nasync function readRecordUncached(\n hostId: string,\n binding: DatasetRecordPageBinding,\n address: string,\n): Promise<RecordPageRecord | null> {\n const dataset = await readSiteDataset(hostId, binding.datasetId)\n if (!dataset) return null\n const field = dataset.model.fields[binding.slugField]\n const path = datasetFilterValuePath(binding.slugField)\n if (!field || field.type !== 'text' || !path) return null\n const snapshot = await dataset.ref\n .collection('records')\n .where(path, '==', address)\n .limit(ADDRESS_LOOKUP_LIMIT)\n .get()\n const [match] = sortDatasetRecords(\n snapshot.docs\n .map((doc) => ({ $id: doc.id, ...(doc.data() as HostDatasetRecord) }))\n .filter((record) => recordAddressOf(record.values, binding.slugField) === address),\n )\n if (!match) return null\n // A photo of a site since deleted is left out, never drawn broken (AGL-3912).\n const values = { ...(match.values ?? {}), $id: match.$id }\n const record = datasetRecordWithoutGonePhotos(values, await goneSitesOfRecords(hostId, [values]))\n return {\n dataset: { id: dataset.id, name: dataset.name, model: dataset.model },\n record,\n datasetsByKey: await readReferenceHops(hostId, dataset.model, record),\n updatedAt: (match as { updatedAt?: unknown }).updatedAt,\n }\n}\n\n/**\n * The records a routed record's reference fields point at, keyed by the\n * dataset each lives in — just those records, by id, rather than the first\n * hundred rows a repeat would read. A target the site may not see is left\n * out, and its token stays as written, as in a repeat.\n */\nasync function readReferenceHops(\n hostId: string,\n model: DatasetModel,\n record: Record<string, unknown>,\n): Promise<Record<string, RepeatableDataset>> {\n const wanted = referencedRecordIds(repeatRowsModelOf(model), record)\n const answer: Record<string, RepeatableDataset> = {}\n await Promise.all(\n [...wanted].map(async ([datasetId, ids]) => {\n try {\n const target = await readSiteDataset(hostId, datasetId)\n if (!target) return\n const docs = await Promise.all(\n [...ids].map((id) => target.ref.collection('records').doc(id).get()),\n )\n answer[datasetId] = {\n records: docs\n .filter((doc) => doc.exists)\n .map((doc) => ({\n ...((doc.data() as HostDatasetRecord).values ?? {}),\n $id: doc.id,\n })),\n }\n } catch (error) {\n console.error('record page: reference hop failed', error)\n }\n }),\n )\n return answer\n}\n"],"names":["visibleToHost","firebaseAdmin","orgDataQueryForHost","PUBLISHED_SITE_DATA_TTL_SECONDS","tenantDataTag","withRenderCache","datasetFilterValuePath","effectiveDatasetModel","repeatRowsModelOf","datasetDisplayName","sortDatasetRecords","datasetRecordWithoutGonePhotos","goneSitesOfRecords","DATASET_RECORD_PAGES_COLLECTION","RECORD_PAGES_MAX_PER_SITE","parseRecordPageBinding","recordAddressOf","referencedRecordIds","readSiteRecordPageBindings","hostId","read","snapshot","app","firestore","collection","doc","limit","get","docs","map","id","data","filter","binding","key","revalidate","tags","error","console","readSiteDataset","datasetId","ref","includes","orgScoped","parent","exists","name","model","ADDRESS_LOOKUP_LIMIT","readRecordPageRecord","address","readRecordUncached","slugField","undefined","match","dataset","field","fields","path","type","where","$id","record","values","datasetsByKey","readReferenceHops","updatedAt","wanted","answer","Promise","all","ids","target","records"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAAiCA,aAAa,QAAQ,sBAAqB;AAC3E,SAASC,aAAa,EAAEC,mBAAmB,QAAQ,2BAA0B;AAC7E,SACEC,+BAA+B,EAC/BC,aAAa,EACbC,eAAe,QACV,wCAAuC;AAC9C,SACEC,sBAAsB,EAEtBC,qBAAqB,EACrBC,iBAAiB,QACZ,6BAAyB;AAChC,SACEC,kBAAkB,EAGlBC,kBAAkB,QACb,uBAAmB;AAC1B,SAASC,8BAA8B,QAAQ,kCAA8B;AAC7E,SAASC,kBAAkB,QAAQ,uCAAmC;AACtE,SACEC,+BAA+B,EAE/BC,yBAAyB,EACzBC,sBAAsB,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AyBgC,MAAM,YAAxC,mBAA4C,CAAC;wBACjDF,KAAKpC,IAAIK,EAAE;;;YAEjB;QACF,EAAE,OAAOO,OAAO;YACdC,QAAQD,KAAK,CAAC,qCAAqCA;QACrD;IACF;IAEF,OAAO+B;AACT"}
@@ -1,3 +1,4 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
1
2
  /**
2
3
  * @license
3
4
  * Copyright 2026 Aglyn LLC
@@ -17,6 +18,8 @@
17
18
  import { orgDataQueryForHost } from "@aglyn/tenant-data-admin";
18
19
  import { PUBLISHED_SITE_DATA_TTL_SECONDS, tenantDataTag, withRenderCache } from "@aglyn/tenant-data-admin/render-cache";
19
20
  import { repeatRecordsFromPages } from "./repeat-record-pages.js";
21
+ import { goneSitesOfRecords } from "./gone-site-photos.server.js";
22
+ import { datasetRecordWithoutGonePhotos } from "../model/dataset-image-field.js";
20
23
  import { FieldPath } from "firebase-admin/firestore";
21
24
  import { effectiveDatasetModel, repeatRowsModelOf } from "../model/dataset-models.js";
22
25
  import { readSiteRecordPageBindings } from "../record-pages/record-page-read.server.js";
@@ -155,7 +158,32 @@ async function readDatasets(hostId, keys, bindings = []) {
155
158
  } catch (error) {
156
159
  console.error(error);
157
160
  }
158
- return datasets;
161
+ return withoutGonePhotos(hostId, datasets);
162
+ }
163
+ /**
164
+ * The loaded datasets with no photo of a site that no longer exists
165
+ * (AGL-3912): each such field is left out of its record, so the card that
166
+ * binds it draws no broken picture. One dataset loaded under several keys is
167
+ * one object, rewritten once.
168
+ */ async function withoutGonePhotos(hostId, datasets) {
169
+ const loaded = [
170
+ ...new Set(Object.values(datasets))
171
+ ];
172
+ const gone = await goneSitesOfRecords(hostId, loaded.flatMap((dataset)=>dataset.records));
173
+ if (!gone.size) return datasets;
174
+ const rewritten = new Map(loaded.map((dataset)=>[
175
+ dataset,
176
+ _extends({}, dataset, {
177
+ records: dataset.records.map((record)=>datasetRecordWithoutGonePhotos(record, gone))
178
+ })
179
+ ]));
180
+ return Object.fromEntries(Object.entries(datasets).map(([key, dataset])=>{
181
+ var _rewritten_get;
182
+ return [
183
+ key,
184
+ (_rewritten_get = rewritten.get(dataset)) != null ? _rewritten_get : dataset
185
+ ];
186
+ }));
159
187
  }
160
188
  /**
161
189
  * The records a repeat renders, in the order it renders them.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/repeat/dataset-repeat-rows.server.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n REPEAT_MAX_RECORDS,\n type RepeatableDataset,\n visibleToHost,\n} from '@aglyn/aglyn/server'\nimport type {\n RepeatRowsAnswer,\n RepeatRowsRequest,\n} from '@aglyn/aglyn/plugin-manager/repeat-rows'\nimport { orgDataQueryForHost } from '@aglyn/tenant-data-admin'\nimport {\n PUBLISHED_SITE_DATA_TTL_SECONDS,\n tenantDataTag,\n withRenderCache,\n} from '@aglyn/tenant-data-admin/render-cache'\nimport { repeatRecordsFromPages } from './repeat-record-pages'\nimport { FieldPath } from 'firebase-admin/firestore'\nimport { effectiveDatasetModel, repeatRowsModelOf } from '../model/dataset-models'\nimport type { HostDataset, HostDatasetRecord } from '../model/datasets'\nimport { readSiteRecordPageBindings } from '../record-pages/record-page-read.server'\nimport {\n type DatasetRecordPageBinding,\n withRecordPageUrls,\n} from '../record-pages/record-pages'\n\n/**\n * The render path's largest read (AGL-1302): up to two pages of records per\n * dataset a page repeats over. Records are mapped to plain values before\n * return, so the cached shape is what repeatable expansion consumes. Backstop\n * only; the publish path busts the tag — see PUBLISHED_SITE_DATA_TTL_SECONDS.\n */\nconst DATASETS_TTL_SECONDS = PUBLISHED_SITE_DATA_TTL_SECONDS\n\n/**\n * The datasets a published page repeats over, with their records — this\n * plugin's answer to the platform's repeat-rows contract\n * (`plugin-manager/repeat-rows.ts`), registered from\n * `registerDataServerDeclarations` and read by the tenant composition.\n *\n * `keys` are the page's repeat keys (`repeatKeys`), each a dataset id or\n * a display name — editors type the friendly name into the Repeat attribute.\n * The map answers under every key exactly as written, and under every loaded\n * dataset's id, which is how a reference hop (AGL-180) finds its target.\n * Records are editor-ordered and capped at the repeat bound.\n *\n * Only the datasets the page names are read. A site may see thousands of\n * datasets, and a read of \"the site's datasets\" can only ever be a bounded\n * page of them, so a repeat bound to one outside that page rendered its\n * template once with nothing to say why.\n *\n * Fail-open, per key: a key that cannot be read is left out, and its\n * repeatable renders no copies (AGL-3496), without costing the others.\n *\n * Scoped to what THIS host may see (AGL-1039): a display name resolves inside\n * the host's scope, and an id outside it resolves to nothing. The Admin SDK\n * does not evaluate rules, so AGL-1041 does not cover this path; the filter\n * has to live here.\n */\nexport async function readPublishedDatasetRows(\n options: RepeatRowsRequest,\n): Promise<RepeatRowsAnswer> {\n const keys = [\n ...new Set(options.keys.map((key) => key.trim()).filter(Boolean)),\n ].sort()\n if (!keys.length) return {}\n // The site's record templates (AGL-3475), read through their own cache: a\n // row of a dataset that has one carries its page as `url`.\n const bindings = await readSiteRecordPageBindings(options.hostId).catch(\n (error: unknown) => {\n console.error(error)\n return [] as DatasetRecordPageBinding[]\n },\n )\n try {\n return await withRenderCache({\n // `rows-v3`: rows carry their record page's `url` (AGL-3475); `v2`\n // carried the rows' references rather than the whole model (AGL-3080).\n key: ['tenant-datasets', 'rows-v3', options.hostId, ...keys],\n revalidate: DATASETS_TTL_SECONDS,\n tags: [tenantDataTag(options.hostId)],\n read: () => readDatasets(options.hostId, keys, bindings),\n })\n } catch (error) {\n console.error(error)\n return readDatasets(options.hostId, keys, bindings)\n }\n}\n\nasync function readDatasets(\n hostId: string,\n keys: readonly string[],\n bindings: readonly DatasetRecordPageBinding[] = [],\n): Promise<Record<string, RepeatableDataset>> {\n const datasets: Record<string, RepeatableDataset> = {}\n try {\n const { ref, query } = await orgDataQueryForHost(hostId, 'datasets')\n // The same visibility rule `resolveDatasetDoc` applies: a keyed read\n // bypasses the scoped query, so the scope is checked on the document.\n const orgScoped = ref.parent?.parent?.id === 'orgs'\n const usable = (snapshot: FirebaseFirestore.DocumentSnapshot | undefined) =>\n Boolean(snapshot?.exists) &&\n !snapshot?.get('deletedAt') &&\n (!orgScoped || visibleToHost(snapshot?.get('visibleTo'), hostId))\n\n const loads = new Map<string, Promise<RepeatableDataset>>()\n const load = (snapshot: FirebaseFirestore.DocumentSnapshot) => {\n let dataset = loads.get(snapshot.id)\n if (!dataset) {\n const model = effectiveDatasetModel(snapshot.data() as HostDataset)\n const binding = bindings.find((one) => one.datasetId === snapshot.id)\n dataset = readRepeatRecords(snapshot.ref).then((records) => ({\n records: withRecordPageUrls(records, binding, model),\n model: repeatRowsModelOf(model),\n }))\n loads.set(snapshot.id, dataset)\n }\n return dataset\n }\n\n // An id first, then a display name. An id that exists but that this host\n // cannot see does not fall through to the name: that would answer \"which\n // dataset is called X\" for a key that already named a specific one.\n const resolveKey = async (key: string) => {\n if (!key.includes('/')) {\n const byId = await ref.doc(key).get()\n if (byId.exists) return usable(byId) ? byId : undefined\n }\n const byName = await query.where('displayName', '==', key).limit(1).get()\n return byName.docs.find((snapshot) => usable(snapshot))\n }\n\n const resolved = await Promise.all(\n keys.map(async (key) => {\n try {\n const snapshot = await resolveKey(key)\n if (!snapshot) return undefined\n const dataset = await load(snapshot)\n datasets[key] = dataset\n datasets[snapshot.id] = dataset\n return dataset\n } catch (error) {\n console.error(error)\n return undefined\n }\n }),\n )\n\n // One reference hop (AGL-180): `{{item.author.name}}` reads the target's\n // rows by id, so the target has to be loaded even though no repeat names it.\n const targets = new Set<string>()\n for (const dataset of resolved) {\n for (const targetId of Object.values(dataset?.model?.references ?? {})) {\n if (targetId && !targetId.includes('/') && !datasets[targetId]) {\n targets.add(targetId)\n }\n }\n }\n await Promise.all(\n [...targets].map(async (targetId) => {\n try {\n const target = await ref.doc(targetId).get()\n if (usable(target)) datasets[targetId] = await load(target)\n } catch (error) {\n console.error(error)\n }\n }),\n )\n } catch (error) {\n console.error(error)\n }\n return datasets\n}\n\n/**\n * The records a repeat renders, in the order it renders them.\n *\n * `orderBy('order')` reads the first group, and matches only documents that\n * carry the field. When it comes back short, every ordered record is already\n * in hand — so at most that many rows of the first page by document id can be\n * ordered, and the rest of that page is exactly the first unordered records.\n * Two bounded reads, never a walk of the collection; which rows win, and in\n * what order, is {@link repeatRecordsFromPages}, the rule the besigner's\n * canvas preview reads through as well (AGL-3111).\n */\nasync function readRepeatRecords(\n datasetRef: FirebaseFirestore.DocumentReference,\n): Promise<Array<Record<string, unknown>>> {\n const recordsRef = datasetRef.collection('records')\n const page = (snapshot: FirebaseFirestore.QuerySnapshot) =>\n snapshot.docs.map((doc) => ({\n id: doc.id,\n data: doc.data() as HostDatasetRecord,\n }))\n const byOrder = await recordsRef\n .orderBy('order')\n .limit(REPEAT_MAX_RECORDS)\n .get()\n const byId =\n byOrder.docs.length < REPEAT_MAX_RECORDS\n ? await recordsRef\n .orderBy(FieldPath.documentId())\n .limit(REPEAT_MAX_RECORDS)\n .get()\n : undefined\n return repeatRecordsFromPages(page(byOrder), byId ? page(byId) : [])\n}\n"],"names":["REPEAT_MAX_RECORDS","visibleToHost","orgDataQueryForHost","PUBLISHED_SITE_DATA_TTL_SECONDS","tenantDataTag","withRenderCache","repeatRecordsFromPages","FieldPath","effectiveDatasetModel","repeatRowsModelOf","readSiteRecordPageBindings","withRecordPageUrls","DATASETS_TTL_SECONDS","readPublishedDatasetRows","options","keys","Set","map","key","trim","filter","Boolean","sort","length","bindings","hostId","catch","error","console","revalidate","tags","read","readDatasets","datasets","ref","query","orgScoped","parent","id","usable","snapshot","exists","get","loads","Map","load","dataset","model","data","binding","find","one","datasetId","readRepeatRecords","then","records","set","resolveKey","includes","byId","doc","undefined","byName","where","limit","docs","resolved","Promise","all","targets","targetId","Object","values","references","add","target","datasetRef","recordsRef","collection","page","byOrder","orderBy","documentId"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,kBAAkB,EAElBC,aAAa,QACR,sBAAqB;AAK5B,SAASC,mBAAmB,QAAQ,2BAA0B;AAC9D,SACEC,+BAA+B,EAC/BC,aAAa,EACbC,eAAe,QACV,wCAAuC;AAC9C,SAASC,sBAAsB,QAAQ,2BAAuB;AAC9D,SAASC,SAAS,QAAQ,2BAA0B;AACpD,SAASC,qBAAqB,EAAEC,iBAAiB,QAAQ,6BAAyB;AAElF,SAASC,0BAA0B,QAAQ,6CAAyC;AACpF,SAEEC,kBAAkB,QACb,kCAA8B;AAErC;;;;;CAKC,GACD,MAAMC,uBAAuBT;AAE7B;;;;;;;;;;;;;;;;;;;;;;;;CAwBC,GACD,OAAO,eAAeU,yBACpBC,OAA0B;IAE1B,MAAMC,OAAO;WACR,IAAIC,IAAIF,QAAQC,IAAI,CAACE,GAAG,CAAC,CAACC,MAAQA,IAAIC,IAAI,IAAIC,MAAM,CAACC;KACzD,CAACC,IAAI;IACN,IAAI,CAACP,KAAKQ,MAAM,EAAE,OAAO,CAAC;IAC1B,0EAA0E;IAC1E,2DAA2D;IAC3D,MAAMC,WAAW,MAAMd,2BAA2BI,QAAQW,MAAM,EAAEC,KAAK,CACrE,CAACC;QACCC,QAAQD,KAAK,CAACA;QACd,OAAO,EAAE;IACX;IAEF,IAAI;QACF,OAAO,MAAMtB,gBAAgB;YAC3B,mEAAmE;YACnE,uEAAuE;YACvEa,KAAK;gBAAC;gBAAmB;gBAAWJ,QAAQW,MAAM;mBAAKV;aAAK;YAC5Dc,YAAYjB;YACZkB,MAAM;gBAAC1B,cAAcU,QAAQW,MAAM;aAAE;YACrCM,MAAM,IAAMC,aAAalB,QAAQW,MAAM,EAAEV,MAAMS;QACjD;IACF,E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AAS,GAAG,MAAMzB,KAAK8B;YACtD,EAAE,OAAOhD,OAAO;gBACdC,QAAQD,KAAK,CAACA;YAChB;QACF;IAEJ,EAAE,OAAOA,OAAO;QACdC,QAAQD,KAAK,CAACA;IAChB;IACA,OAAOM;AACT;AAEA;;;;;;;;;;CAUC,GACD,eAAeoB,kBACbuB,UAA+C;IAE/C,MAAMC,aAAaD,WAAWE,UAAU,CAAC;IACzC,MAAMC,OAAO,CAACvC,WACZA,SAASyB,IAAI,CAAChD,GAAG,CAAC,CAAC2C,MAAS,CAAA;gBAC1BtB,IAAIsB,IAAItB,EAAE;gBACVU,MAAMY,IAAIZ,IAAI;YAChB,CAAA;IACF,MAAMgC,UAAU,MAAMH,WACnBI,OAAO,CAAC,SACRjB,KAAK,CAAChE,oBACN0C,GAAG;IACN,MAAMiB,OACJqB,QAAQf,IAAI,CAAC1C,MAAM,GAAGvB,qBAClB,MAAM6E,WACHI,OAAO,CAAC1E,UAAU2E,UAAU,IAC5BlB,KAAK,CAAChE,oBACN0C,GAAG,KACNmB;IACN,OAAOvD,uBAAuByE,KAAKC,UAAUrB,OAAOoB,KAAKpB,QAAQ,EAAE;AACrE"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/repeat/dataset-repeat-rows.server.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n REPEAT_MAX_RECORDS,\n type RepeatableDataset,\n visibleToHost,\n} from '@aglyn/aglyn/server'\nimport type {\n RepeatRowsAnswer,\n RepeatRowsRequest,\n} from '@aglyn/aglyn/plugin-manager/repeat-rows'\nimport { orgDataQueryForHost } from '@aglyn/tenant-data-admin'\nimport {\n PUBLISHED_SITE_DATA_TTL_SECONDS,\n tenantDataTag,\n withRenderCache,\n} from '@aglyn/tenant-data-admin/render-cache'\nimport { repeatRecordsFromPages } from './repeat-record-pages'\nimport { goneSitesOfRecords } from './gone-site-photos.server'\nimport { datasetRecordWithoutGonePhotos } from '../model/dataset-image-field'\nimport { FieldPath } from 'firebase-admin/firestore'\nimport { effectiveDatasetModel, repeatRowsModelOf } from '../model/dataset-models'\nimport type { HostDataset, HostDatasetRecord } from '../model/datasets'\nimport { readSiteRecordPageBindings } from '../record-pages/record-page-read.server'\nimport {\n type DatasetRecordPageBinding,\n withRecordPageUrls,\n} from '../record-pages/record-pages'\n\n/**\n * The render path's largest read (AGL-1302): up to two pages of records per\n * dataset a page repeats over. Records are mapped to plain values before\n * return, so the cached shape is what repeatable expansion consumes. Backstop\n * only; the publish path busts the tag — see PUBLISHED_SITE_DATA_TTL_SECONDS.\n */\nconst DATASETS_TTL_SECONDS = PUBLISHED_SITE_DATA_TTL_SECONDS\n\n/**\n * The datasets a published page repeats over, with their records — this\n * plugin's answer to the platform's repeat-rows contract\n * (`plugin-manager/repeat-rows.ts`), registered from\n * `registerDataServerDeclarations` and read by the tenant composition.\n *\n * `keys` are the page's repeat keys (`repeatKeys`), each a dataset id or\n * a display name — editors type the friendly name into the Repeat attribute.\n * The map answers under every key exactly as written, and under every loaded\n * dataset's id, which is how a reference hop (AGL-180) finds its target.\n * Records are editor-ordered and capped at the repeat bound.\n *\n * Only the datasets the page names are read. A site may see thousands of\n * datasets, and a read of \"the site's datasets\" can only ever be a bounded\n * page of them, so a repeat bound to one outside that page rendered its\n * template once with nothing to say why.\n *\n * Fail-open, per key: a key that cannot be read is left out, and its\n * repeatable renders no copies (AGL-3496), without costing the others.\n *\n * Scoped to what THIS host may see (AGL-1039): a display name resolves inside\n * the host's scope, and an id outside it resolves to nothing. The Admin SDK\n * does not evaluate rules, so AGL-1041 does not cover this path; the filter\n * has to live here.\n */\nexport async function readPublishedDatasetRows(\n options: RepeatRowsRequest,\n): Promise<RepeatRowsAnswer> {\n const keys = [\n ...new Set(options.keys.map((key) => key.trim()).filter(Boolean)),\n ].sort()\n if (!keys.length) return {}\n // The site's record templates (AGL-3475), read through their own cache: a\n // row of a dataset that has one carries its page as `url`.\n const bindings = await readSiteRecordPageBindings(options.hostId).catch(\n (error: unknown) => {\n console.error(error)\n return [] as DatasetRecordPageBinding[]\n },\n )\n try {\n return await withRenderCache({\n // `rows-v3`: rows carry their record page's `url` (AGL-3475); `v2`\n // carried the rows' references rather than the whole model (AGL-3080).\n key: ['tenant-datasets', 'rows-v3', options.hostId, ...keys],\n revalidate: DATASETS_TTL_SECONDS,\n tags: [tenantDataTag(options.hostId)],\n read: () => readDatasets(options.hostId, keys, bindings),\n })\n } catch (error) {\n console.error(error)\n return readDatasets(options.hostId, keys, bindings)\n }\n}\n\nasync function readDatasets(\n hostId: string,\n keys: readonly string[],\n bindings: readonly DatasetRecordPageBinding[] = [],\n): Promise<Record<string, RepeatableDataset>> {\n const datasets: Record<string, RepeatableDataset> = {}\n try {\n const { ref, query } = await orgDataQueryForHost(hostId, 'datasets')\n // The same visibility rule `resolveDatasetDoc` applies: a keyed read\n // bypasses the scoped query, so the scope is checked on the document.\n const orgScoped = ref.parent?.parent?.id === 'orgs'\n const usable = (snapshot: FirebaseFirestore.DocumentSnapshot | undefined) =>\n Boolean(snapshot?.exists) &&\n !snapshot?.get('deletedAt') &&\n (!orgScoped || visibleToHost(snapshot?.get('visibleTo'), hostId))\n\n const loads = new Map<string, Promise<RepeatableDataset>>()\n const load = (snapshot: FirebaseFirestore.DocumentSnapshot) => {\n let dataset = loads.get(snapshot.id)\n if (!dataset) {\n const model = effectiveDatasetModel(snapshot.data() as HostDataset)\n const binding = bindings.find((one) => one.datasetId === snapshot.id)\n dataset = readRepeatRecords(snapshot.ref).then((records) => ({\n records: withRecordPageUrls(records, binding, model),\n model: repeatRowsModelOf(model),\n }))\n loads.set(snapshot.id, dataset)\n }\n return dataset\n }\n\n // An id first, then a display name. An id that exists but that this host\n // cannot see does not fall through to the name: that would answer \"which\n // dataset is called X\" for a key that already named a specific one.\n const resolveKey = async (key: string) => {\n if (!key.includes('/')) {\n const byId = await ref.doc(key).get()\n if (byId.exists) return usable(byId) ? byId : undefined\n }\n const byName = await query.where('displayName', '==', key).limit(1).get()\n return byName.docs.find((snapshot) => usable(snapshot))\n }\n\n const resolved = await Promise.all(\n keys.map(async (key) => {\n try {\n const snapshot = await resolveKey(key)\n if (!snapshot) return undefined\n const dataset = await load(snapshot)\n datasets[key] = dataset\n datasets[snapshot.id] = dataset\n return dataset\n } catch (error) {\n console.error(error)\n return undefined\n }\n }),\n )\n\n // One reference hop (AGL-180): `{{item.author.name}}` reads the target's\n // rows by id, so the target has to be loaded even though no repeat names it.\n const targets = new Set<string>()\n for (const dataset of resolved) {\n for (const targetId of Object.values(dataset?.model?.references ?? {})) {\n if (targetId && !targetId.includes('/') && !datasets[targetId]) {\n targets.add(targetId)\n }\n }\n }\n await Promise.all(\n [...targets].map(async (targetId) => {\n try {\n const target = await ref.doc(targetId).get()\n if (usable(target)) datasets[targetId] = await load(target)\n } catch (error) {\n console.error(error)\n }\n }),\n )\n } catch (error) {\n console.error(error)\n }\n return withoutGonePhotos(hostId, datasets)\n}\n\n/**\n * The loaded datasets with no photo of a site that no longer exists\n * (AGL-3912): each such field is left out of its record, so the card that\n * binds it draws no broken picture. One dataset loaded under several keys is\n * one object, rewritten once.\n */\nasync function withoutGonePhotos(\n hostId: string,\n datasets: Record<string, RepeatableDataset>,\n): Promise<Record<string, RepeatableDataset>> {\n const loaded = [...new Set(Object.values(datasets))]\n const gone = await goneSitesOfRecords(\n hostId,\n loaded.flatMap((dataset) => dataset.records),\n )\n if (!gone.size) return datasets\n const rewritten = new Map(\n loaded.map((dataset) => [\n dataset,\n {\n ...dataset,\n records: dataset.records.map((record) =>\n datasetRecordWithoutGonePhotos(record, gone),\n ),\n },\n ]),\n )\n return Object.fromEntries(\n Object.entries(datasets).map(([key, dataset]) => [\n key,\n rewritten.get(dataset) ?? dataset,\n ]),\n )\n}\n\n/**\n * The records a repeat renders, in the order it renders them.\n *\n * `orderBy('order')` reads the first group, and matches only documents that\n * carry the field. When it comes back short, every ordered record is already\n * in hand — so at most that many rows of the first page by document id can be\n * ordered, and the rest of that page is exactly the first unordered records.\n * Two bounded reads, never a walk of the collection; which rows win, and in\n * what order, is {@link repeatRecordsFromPages}, the rule the besigner's\n * canvas preview reads through as well (AGL-3111).\n */\nasync function readRepeatRecords(\n datasetRef: FirebaseFirestore.DocumentReference,\n): Promise<Array<Record<string, unknown>>> {\n const recordsRef = datasetRef.collection('records')\n const page = (snapshot: FirebaseFirestore.QuerySnapshot) =>\n snapshot.docs.map((doc) => ({\n id: doc.id,\n data: doc.data() as HostDatasetRecord,\n }))\n const byOrder = await recordsRef\n .orderBy('order')\n .limit(REPEAT_MAX_RECORDS)\n .get()\n const byId =\n byOrder.docs.length < REPEAT_MAX_RECORDS\n ? await recordsRef\n .orderBy(FieldPath.documentId())\n .limit(REPEAT_MAX_RECORDS)\n .get()\n : undefined\n return repeatRecordsFromPages(page(byOrder), byId ? page(byId) : [])\n}\n"],"names":["REPEAT_MAX_RECORDS","visibleToHost","orgDataQueryForHost","PUBLISHED_SITE_DATA_TTL_SECONDS","tenantDataTag","withRenderCache","repeatRecordsFromPages","goneSitesOfRecords","datasetRecordWithoutGonePhotos","FieldPath","effectiveDatasetModel","repeatRowsModelOf","readSiteRecordPageBindings","withRecordPageUrls","DATASETS_TTL_SECONDS","readPublishedDatasetRows","options","keys","Set","map","key","trim","filter","Boolean","sort","length","bindings","hostId","catch","error","console","revalidate","tags","read","readDatasets","datasets","ref","query","orgScoped","parent","id","usable","snapshot","exists","get","loads","Map","load","dataset","model","data","binding","find","one","datasetId","readRepeatRecords","then","records","set","resolveKey","includes","byId","doc","undefined","byName","where","limit","docs","resolved","Promise","all","targets","targetId","Object","values","references","add","target","withoutGonePhotos","loaded","gone","flatMap","size","rewritten","record","fromEntries","entries","datasetRef","recordsRef","collection","page","byOrder","orderBy","documentId"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,kBAAkB,EAElBC,aAAa,QACR,sBAAqB;AAK5B,SAASC,mBAAmB,QAAQ,2BAA0B;AAC9D,SACEC,+BAA+B,EAC/BC,aAAa,EACbC,eAAe,QACV,wCAAuC;AAC9C,SAASC,sBAAsB,QAAQ,2BAAuB;AAC9D,SAASC,kBAAkB,QAAQ,+BAA2B;AAC9D,SAASC,8BAA8B,QAAQ,kCAA8B;AAC7E,SAASC,SAAS,QAAQ,2BAA0B;AACpD,SAASC,qBAAqB,EAAEC,iBAAiB,QAAQ,6BAAyB;AAElF,SAASC,0BAA0B,QAAQ,6CAAyC;AACpF,SAEEC,kBAAkB,QACb,kCAA8B;AAErC;;;;;CAKC,GACD,MAAMC,uBAAuBX;AAE7B;;;;;;;;;;;;;;;;;;;;;;;;CAwBC,GACD,OAAO,eAAeY,yBACpBC,OAA0B;IAE1B,MAAMC,OAAO;WACR,IAAIC,IAAIF,QAAQC,IAAI,CAACE,GAAG,CAAC,CAACC,MAAQA,IAAIC,IAAI,IAAIC,MAAM,CAACC;KACzD,CAACC,IAAI;IACN,IAAI,CAACP,KAAKQ,MAAM,EAAE,OAAO,CAAC;IAC1B,0EAA0E;IAC1E,2DAA2D;IAC3D,MAAMC,WAAW,MAAMd,2BAA2BI,QAAQW,MAAM,EAAEC,KAAK,CACrE,CAACC;QACCC,QAAQD,KAAK,CAACA;QACd,OAAO,EAAE;IACX;IAEF,IAAI;QACF,OAAO,MAAMxB,gBAAgB;YAC3B,mEAAmE;YACnE,uEAAuE;YACvEe,KAAK;gBAAC;gBAAmB;gBAAWJ,QAAQW,MAAM;mBAAKV;aAAK;YAC5Dc,YAAYjB;YACZkB,MAAM;gBAAC5B,cAAcY,QAAQW,MAAM;aAAE;YACrCM,MAAM,I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iB,OACJ8B,QAAQxB,IAAI,CAAC1C,MAAM,GAAGzB,qBAClB,MAAMwF,WACHI,OAAO,CAACnF,UAAUoF,UAAU,IAC5B3B,KAAK,CAAClE,oBACN4C,GAAG,KACNmB;IACN,OAAOzD,uBAAuBoF,KAAKC,UAAU9B,OAAO6B,KAAK7B,QAAQ,EAAE;AACrE"}
@@ -0,0 +1,28 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ /** How a site's existence is asked: its host document, by id. */
18
+ export type SiteExists = (hostIds: readonly string[]) => Promise<ReadonlySet<string>>;
19
+ /**
20
+ * The sites, among those the records' photos are in the libraries of, that
21
+ * no longer exist (AGL-3912). A dataset belongs to the organization, so a
22
+ * record outlives the site whose library its photo was uploaded to, and that
23
+ * library is deleted with the site: the gym's coaches, written by a start on
24
+ * a site since deleted, showed four broken photos. The site rendering is
25
+ * never asked about, and no read is made when no record holds a photo of
26
+ * another site's. Fail-open: a read that fails answers none gone.
27
+ */
28
+ export declare function goneSitesOfRecords(hostId: string, records: ReadonlyArray<Readonly<Record<string, unknown>>>, exists?: SiteExists): Promise<ReadonlySet<string>>;
@@ -0,0 +1,50 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ import { firebaseAdmin } from "@aglyn/tenant-data-admin";
17
+ import { datasetRecordPhotoSites } from "../model/dataset-image-field.js";
18
+ /** The production answer: one batched read of the named host documents. */ const hostsThatExist = async (hostIds)=>{
19
+ const firestore = firebaseAdmin.app().firestore();
20
+ const snapshots = await firestore.getAll(...hostIds.map((id)=>firestore.collection('hosts').doc(id)));
21
+ return new Set(snapshots.filter((snapshot)=>snapshot.exists).map((snapshot)=>snapshot.id));
22
+ };
23
+ /**
24
+ * The sites, among those the records' photos are in the libraries of, that
25
+ * no longer exist (AGL-3912). A dataset belongs to the organization, so a
26
+ * record outlives the site whose library its photo was uploaded to, and that
27
+ * library is deleted with the site: the gym's coaches, written by a start on
28
+ * a site since deleted, showed four broken photos. The site rendering is
29
+ * never asked about, and no read is made when no record holds a photo of
30
+ * another site's. Fail-open: a read that fails answers none gone.
31
+ */ export async function goneSitesOfRecords(hostId, records, exists = hostsThatExist) {
32
+ const named = new Set();
33
+ for (const record of records){
34
+ for (const site of datasetRecordPhotoSites(record))if (site !== hostId) named.add(site);
35
+ }
36
+ if (!named.size) return new Set();
37
+ try {
38
+ const live = await exists([
39
+ ...named
40
+ ]);
41
+ return new Set([
42
+ ...named
43
+ ].filter((site)=>!live.has(site)));
44
+ } catch (error) {
45
+ console.error('dataset photos: the sites they live in could not be read', error);
46
+ return new Set();
47
+ }
48
+ }
49
+
50
+ //# sourceMappingURL=gone-site-photos.server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/repeat/gone-site-photos.server.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { datasetRecordPhotoSites } from '../model/dataset-image-field'\n\n/** How a site's existence is asked: its host document, by id. */\nexport type SiteExists = (hostIds: readonly string[]) => Promise<ReadonlySet<string>>\n\n/** The production answer: one batched read of the named host documents. */\nconst hostsThatExist: SiteExists = async (hostIds) => {\n const firestore = firebaseAdmin.app().firestore()\n const snapshots = await firestore.getAll(...hostIds.map((id) => firestore.collection('hosts').doc(id)))\n return new Set(snapshots.filter((snapshot) => snapshot.exists).map((snapshot) => snapshot.id))\n}\n\n/**\n * The sites, among those the records' photos are in the libraries of, that\n * no longer exist (AGL-3912). A dataset belongs to the organization, so a\n * record outlives the site whose library its photo was uploaded to, and that\n * library is deleted with the site: the gym's coaches, written by a start on\n * a site since deleted, showed four broken photos. The site rendering is\n * never asked about, and no read is made when no record holds a photo of\n * another site's. Fail-open: a read that fails answers none gone.\n */\nexport async function goneSitesOfRecords(\n hostId: string,\n records: ReadonlyArray<Readonly<Record<string, unknown>>>,\n exists: SiteExists = hostsThatExist,\n): Promise<ReadonlySet<string>> {\n const named = new Set<string>()\n for (const record of records) {\n for (const site of datasetRecordPhotoSites(record)) if (site !== hostId) named.add(site)\n }\n if (!named.size) return new Set()\n try {\n const live = await exists([...named])\n return new Set([...named].filter((site) => !live.has(site)))\n } catch (error) {\n console.error('dataset photos: the sites they live in could not be read', error)\n return new Set()\n }\n}\n"],"names":["firebaseAdmin","datasetRecordPhotoSites","hostsThatExist","hostIds","firestore","app","snapshots","getAll","map","id","collection","doc","Set","filter","snapshot","exists","goneSitesOfRecords","hostId","records","named","record","site","add","size","live","has","error","console"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,QAAQ,2BAA0B;AACxD,SAASC,uBAAuB,QAAQ,kCAA8B;AAKtE,yEAAyE,GACzE,MAAMC,iBAA6B,OAAOC;IACxC,MAAMC,YAAYJ,cAAcK,GAAG,GAAGD,SAAS;IAC/C,MAAME,YAAY,MAAMF,UAAUG,MAAM,IAAIJ,QAAQK,GAAG,CAAC,CAACC,KAAOL,UAAUM,UAAU,CAAC,SAASC,GAAG,CAACF;IAClG,OAAO,IAAIG,IAAIN,UAAUO,MAAM,CAAC,CAACC,WAAaA,SAASC,MAAM,EAAEP,GAAG,CAAC,CAACM,WAAaA,SAASL,EAAE;AAC9F;AAEA;;;;;;;;CAQC,GACD,OAAO,eAAeO,mBACpBC,MAAc,EACdC,OAAyD,EACzDH,SAAqBb,cAAc;IAEnC,MAAMiB,QAAQ,IAAIP;IAClB,KAAK,MAAMQ,UAAUF,QAAS;QAC5B,KAAK,MAAMG,QAAQpB,wBAAwBmB,QAAS,IAAIC,SAASJ,QAAQE,MAAMG,GAAG,CAACD;IACrF;IACA,IAAI,CAACF,MAAMI,IAAI,EAAE,OAAO,IAAIX;IAC5B,IAAI;QACF,MAAMY,OAAO,MAAMT,OAAO;eAAII;SAAM;QACpC,OAAO,IAAIP,IAAI;eAAIO;SAAM,CAACN,MAAM,CAAC,CAACQ,OAAS,CAACG,KAAKC,GAAG,CAACJ;IACvD,EAAE,OAAOK,OAAO;QACdC,QAAQD,KAAK,CAAC,4DAA4DA;QAC1E,OAAO,IAAId;IACb;AACF"}
@@ -31,7 +31,9 @@ import { DATASET_RECORD_PAGES_COLLECTION, RECORD_PAGES_MAX_PER_SITE, parseRecord
31
31
  * out of every answer.
32
32
  *
33
33
  * Each record is `datasetIndexedRecord`'s (`model/dataset-record.ts`): the
34
- * name, the fields and the scope tokens, never a record of the dataset.
34
+ * name, the fields and the scope tokens, never a record of the dataset. One
35
+ * read by `get` also says how many records it holds (`facts.records`,
36
+ * AGL-3912), which a list leaves out so it costs no count per dataset.
35
37
  *
36
38
  * Narrowed to a site, each also says where its records have pages of their
37
39
  * own on THAT site (AGL-3747), as `facts.recordPage`: the template screen,
@@ -67,6 +69,27 @@ import { DATASET_RECORD_PAGES_COLLECTION, RECORD_PAGES_MAX_PER_SITE, parseRecord
67
69
  })
68
70
  });
69
71
  }
72
+ /**
73
+ * A record with how many records the dataset holds, as `facts.records`
74
+ * (AGL-3912), counted by one aggregation; left out where the count fails. A
75
+ * site start reads it to tell a dataset another site filled from one it may
76
+ * fill itself.
77
+ */ async function withRecordCount(record, ref) {
78
+ try {
79
+ const count = Number((await ref.collection('records').count().get()).data().count);
80
+ return Number.isFinite(count) ? _extends({}, record, {
81
+ facts: _extends({}, record.facts, {
82
+ records: count
83
+ })
84
+ }) : record;
85
+ } catch (error) {
86
+ console.error('dataset index: the records could not be counted', {
87
+ id: record.id,
88
+ error
89
+ });
90
+ return record;
91
+ }
92
+ }
70
93
  export const datasetRecordIndex = {
71
94
  async list ({ orgId, hostId, limit }) {
72
95
  if (!orgId || limit <= 0) return {
@@ -92,10 +115,11 @@ export const datasetRecordIndex = {
92
115
  async get ({ orgId, hostId, id }) {
93
116
  if (!orgId || !id) return null;
94
117
  const snapshot = await datasets(orgId).doc(id).get();
95
- const record = snapshot.exists ? datasetIndexedRecord(snapshot.id, snapshot.data()) : null;
96
- if (!record || !hostId) return record;
97
- if (!visibleToHost(record.facts['visibleTo'], hostId)) return null;
98
- return withRecordPage(record, await siteRecordPages(hostId));
118
+ const found = snapshot.exists ? datasetIndexedRecord(snapshot.id, snapshot.data()) : null;
119
+ if (!found) return null;
120
+ if (hostId && !visibleToHost(found.facts['visibleTo'], hostId)) return null;
121
+ const record = await withRecordCount(found, snapshot.ref);
122
+ return hostId ? withRecordPage(record, await siteRecordPages(hostId)) : record;
99
123
  }
100
124
  };
101
125
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/server/dataset-record-index.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 { visibleToHost } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport type {\n PluginIndexedRecord,\n PluginRecordIndex,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-index'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport { scopedToHost } from '@aglyn/tenant-data-admin/server/organizations'\nimport { datasetIndexedRecord } from '../model/dataset-record'\nimport {\n DATASET_RECORD_PAGES_COLLECTION,\n type DatasetRecordPageBinding,\n RECORD_PAGES_MAX_PER_SITE,\n parseRecordPageBinding,\n} from '../record-pages/record-pages'\n\n/**\n * The data plugin's `dataset` index (AGL-3080): the workspace's datasets, as\n * another surface reads them — an AI job drafting an automation that names a\n * dataset, a planner listing what a site already has — without knowing where\n * they are stored or what a deleted one looks like.\n *\n * Datasets belong to the ORGANIZATION (`orgId` required; a scope with none\n * answers nothing). Narrowed to a site (`hostId`), only the datasets shared\n * with it are answered — the site Data page's rule. A deleted dataset is left\n * out of every answer.\n *\n * Each record is `datasetIndexedRecord`'s (`model/dataset-record.ts`): the\n * name, the fields and the scope tokens, never a record of the dataset.\n *\n * Narrowed to a site, each also says where its records have pages of their\n * own on THAT site (AGL-3747), as `facts.recordPage`: the template screen,\n * the base and the address field of the site's record template for it\n * (AGL-3475), `null` where the site keeps none. A planner reads it to link a list's cards to\n * record pages made before its plan; one small read of the site's record\n * templates, bounded by `RECORD_PAGES_MAX_PER_SITE`, per answer.\n */\n\nfunction datasets(orgId: string) {\n return firebaseAdmin.app().firestore().collection('orgs').doc(orgId).collection('datasets')\n}\n\n/** What `facts.recordPage` says of one dataset's record pages on a site. */\nexport interface DatasetIndexedRecordPage {\n screenId: string\n base: string\n slugField: string\n}\n\n/**\n * The site's record templates by the dataset they render, the first in the\n * site's order where a dataset has more than one.\n */\nasync function siteRecordPages(hostId: string): Promise<Map<string, DatasetIndexedRecordPage>> {\n const snapshot = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection(DATASET_RECORD_PAGES_COLLECTION)\n .limit(RECORD_PAGES_MAX_PER_SITE)\n .get()\n const pages = new Map<string, DatasetIndexedRecordPage>()\n for (const doc of snapshot.docs) {\n const binding: DatasetRecordPageBinding | null = parseRecordPageBinding(doc.id, doc.data())\n if (!binding || pages.has(binding.datasetId)) continue\n pages.set(binding.datasetId, { screenId: binding.screenId, base: binding.base, slugField: binding.slugField })\n }\n return pages\n}\n\n/** A record with its record page on the site, where one is kept. */\nfunction withRecordPage(\n record: PluginIndexedRecord,\n pages: ReadonlyMap<string, DatasetIndexedRecordPage>,\n): PluginIndexedRecord {\n return { ...record, facts: { ...record.facts, recordPage: pages.get(record.id) ?? null } }\n}\n\nexport const datasetRecordIndex: PluginRecordIndex = {\n async list({ orgId, hostId, limit }) {\n if (!orgId || limit <= 0) return { records: [], truncated: false }\n const collection = datasets(orgId)\n const query = hostId ? scopedToHost(collection, hostId) : collection\n // One more than asked, so `truncated` is a fact rather than a guess;\n // deleted datasets are filtered after the read.\n const snapshot = await query.limit(limit + 1).get()\n const records = snapshot.docs\n .map((doc) => datasetIndexedRecord(doc.id, doc.data()))\n .filter((record): record is PluginIndexedRecord => record !== null)\n .slice(0, limit)\n if (!hostId || !records.length) return { records, truncated: snapshot.size > limit }\n const pages = await siteRecordPages(hostId)\n return { records: records.map((record) => withRecordPage(record, pages)), truncated: snapshot.size > limit }\n },\n async get({ orgId, hostId, id }) {\n if (!orgId || !id) return null\n const snapshot = await datasets(orgId).doc(id).get()\n const record = snapshot.exists ? datasetIndexedRecord(snapshot.id, snapshot.data()) : null\n if (!record || !hostId) return record\n if (!visibleToHost(record.facts['visibleTo'] as string[], hostId)) return null\n return withRecordPage(record, await siteRecordPages(hostId))\n },\n}\n"],"names":["visibleToHost","firebaseAdmin","scopedToHost","datasetIndexedRecord","DATASET_RECORD_PAGES_COLLECTION","RECORD_PAGES_MAX_PER_SITE","parseRecordPageBinding","datasets","orgId","app","firestore","collection","doc","siteRecordPages","hostId","snapshot","limit","get","pages","Map","docs","binding","id","data","has","datasetId","set","screenId","base","slugField","withRecordPage","record","facts","recordPage","datasetRecordIndex","list","records","truncated","query","map","filter","slice","length","size","exists"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,QAAQ,sCAAqC;AAKnE,SAASC,aAAa,QAAQ,iDAAgD;AAC9E,SAASC,YAAY,QAAQ,gDAA+C;AAC5E,SAASC,oBAAoB,QAAQ,6BAAyB;AAC9D,SACEC,+BAA+B,EAE/BC,yBAAyB,EACzBC,sBAAsB,QACjB,kCAA8B;AAErC;;;;;;;;;;;;;;;;;;;;CAoBC,GAED,SAASC,SAASC,KAAa;IAC7B,OAAOP,cAAcQ,GAAG,GAAGC,SAAS,GAAGC,UAAU,CAAC,QAAQC,GAAG,CAACJ,OAAOG,UAAU,CAAC;AAClF;AASA;;;CAGC,GACD,eAAeE,gBAAgBC,MAAc;IAC3C,MAAMC,WAAW,MAAMd,cACpBQ,GAAG,GACHC,SAAS,GACTC,UAAU,CAAC,SACXC,GAAG,CAACE,QACJH,UAAU,CAACP,iCACXY,KAAK,CAACX,2BACNY,GAAG;IACN,MAAMC,QAAQ,IAAIC;IAClB,KAAK,MAAMP,OAAOG,SAASK,IAAI,CAAE;QAC/B,MAAMC,UAA2Cf,uBAAuBM,IAAIU,EAAE,EAAEV,IAAIW,IAAI;QACxF,IAAI,CAACF,WAAWH,MAAMM,GAAG,CAACH,QAAQI,SAAS,GAAG;QAC9CP,MAAMQ,GAAG,CAACL,QAAQI,SAAS,EAAE;YAAEE,UAAUN,QA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P,WAAW,MAAMR,SAASC,OAAOI,GAAG,CAACU,IAAIL,GAAG;QAClD,MAAMc,SAAShB,SAAS6B,MAAM,GAAGzC,qBAAqBY,SAASO,EAAE,EAAEP,SAASQ,IAAI,MAAM;QACtF,IAAI,CAACQ,UAAU,CAACjB,QAAQ,OAAOiB;QAC/B,IAAI,CAAC/B,cAAc+B,OAAOC,KAAK,CAAC,YAAY,EAAclB,SAAS,OAAO;QAC1E,OAAOgB,eAAeC,QAAQ,MAAMlB,gBAAgBC;IACtD;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/server/dataset-record-index.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 { visibleToHost } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport type {\n PluginIndexedRecord,\n PluginRecordIndex,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-index'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport { scopedToHost } from '@aglyn/tenant-data-admin/server/organizations'\nimport { datasetIndexedRecord } from '../model/dataset-record'\nimport {\n DATASET_RECORD_PAGES_COLLECTION,\n type DatasetRecordPageBinding,\n RECORD_PAGES_MAX_PER_SITE,\n parseRecordPageBinding,\n} from '../record-pages/record-pages'\n\n/**\n * The data plugin's `dataset` index (AGL-3080): the workspace's datasets, as\n * another surface reads them — an AI job drafting an automation that names a\n * dataset, a planner listing what a site already has — without knowing where\n * they are stored or what a deleted one looks like.\n *\n * Datasets belong to the ORGANIZATION (`orgId` required; a scope with none\n * answers nothing). Narrowed to a site (`hostId`), only the datasets shared\n * with it are answered — the site Data page's rule. A deleted dataset is left\n * out of every answer.\n *\n * Each record is `datasetIndexedRecord`'s (`model/dataset-record.ts`): the\n * name, the fields and the scope tokens, never a record of the dataset. One\n * read by `get` also says how many records it holds (`facts.records`,\n * AGL-3912), which a list leaves out so it costs no count per dataset.\n *\n * Narrowed to a site, each also says where its records have pages of their\n * own on THAT site (AGL-3747), as `facts.recordPage`: the template screen,\n * the base and the address field of the site's record template for it\n * (AGL-3475), `null` where the site keeps none. A planner reads it to link a list's cards to\n * record pages made before its plan; one small read of the site's record\n * templates, bounded by `RECORD_PAGES_MAX_PER_SITE`, per answer.\n */\n\nfunction datasets(orgId: string) {\n return firebaseAdmin.app().firestore().collection('orgs').doc(orgId).collection('datasets')\n}\n\n/** What `facts.recordPage` says of one dataset's record pages on a site. */\nexport interface DatasetIndexedRecordPage {\n screenId: string\n base: string\n slugField: string\n}\n\n/**\n * The site's record templates by the dataset they render, the first in the\n * site's order where a dataset has more than one.\n */\nasync function siteRecordPages(hostId: string): Promise<Map<string, DatasetIndexedRecordPage>> {\n const snapshot = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection(DATASET_RECORD_PAGES_COLLECTION)\n .limit(RECORD_PAGES_MAX_PER_SITE)\n .get()\n const pages = new Map<string, DatasetIndexedRecordPage>()\n for (const doc of snapshot.docs) {\n const binding: DatasetRecordPageBinding | null = parseRecordPageBinding(doc.id, doc.data())\n if (!binding || pages.has(binding.datasetId)) continue\n pages.set(binding.datasetId, { screenId: binding.screenId, base: binding.base, slugField: binding.slugField })\n }\n return pages\n}\n\n/** A record with its record page on the site, where one is kept. */\nfunction withRecordPage(\n record: PluginIndexedRecord,\n pages: ReadonlyMap<string, DatasetIndexedRecordPage>,\n): PluginIndexedRecord {\n return { ...record, facts: { ...record.facts, recordPage: pages.get(record.id) ?? null } }\n}\n\n/**\n * A record with how many records the dataset holds, as `facts.records`\n * (AGL-3912), counted by one aggregation; left out where the count fails. A\n * site start reads it to tell a dataset another site filled from one it may\n * fill itself.\n */\nasync function withRecordCount(\n record: PluginIndexedRecord,\n ref: FirebaseFirestore.DocumentReference,\n): Promise<PluginIndexedRecord> {\n try {\n const count = Number((await ref.collection('records').count().get()).data().count)\n return Number.isFinite(count) ? { ...record, facts: { ...record.facts, records: count } } : record\n } catch (error) {\n console.error('dataset index: the records could not be counted', { id: record.id, error })\n return record\n }\n}\n\nexport const datasetRecordIndex: PluginRecordIndex = {\n async list({ orgId, hostId, limit }) {\n if (!orgId || limit <= 0) return { records: [], truncated: false }\n const collection = datasets(orgId)\n const query = hostId ? scopedToHost(collection, hostId) : collection\n // One more than asked, so `truncated` is a fact rather than a guess;\n // deleted datasets are filtered after the read.\n const snapshot = await query.limit(limit + 1).get()\n const records = snapshot.docs\n .map((doc) => datasetIndexedRecord(doc.id, doc.data()))\n .filter((record): record is PluginIndexedRecord => record !== null)\n .slice(0, limit)\n if (!hostId || !records.length) return { records, truncated: snapshot.size > limit }\n const pages = await siteRecordPages(hostId)\n return { records: records.map((record) => withRecordPage(record, pages)), truncated: snapshot.size > limit }\n },\n async get({ orgId, hostId, id }) {\n if (!orgId || !id) return null\n const snapshot = await datasets(orgId).doc(id).get()\n const found = snapshot.exists ? datasetIndexedRecord(snapshot.id, snapshot.data()) : null\n if (!found) return null\n if (hostId && !visibleToHost(found.facts['visibleTo'] as string[], hostId)) return null\n const record = await withRecordCount(found, snapshot.ref)\n return hostId ? withRecordPage(record, await siteRecordPages(hostId)) : record\n },\n}\n"],"names":["visibleToHost","firebaseAdmin","scopedToHost","datasetIndexedRecord","DATASET_RECORD_PAGES_COLLECTION","RECORD_PAGES_MAX_PER_SITE","parseRecordPageBinding","datasets","orgId","app","firestore","collection","doc","siteRecordPages","hostId","snapshot","limit","get","pages","Map","docs","binding","id","data","has","datasetId","set","screenId","base","slugField","withRecordPage","record","facts","recordPage","withRecordCount","ref","count","Number","isFinite","records","error","console","datasetRecordIndex","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