@aglyn/plugins-data 1.13.0 → 1.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/package.json +12 -10
  2. package/src/lib/artifact/dataset-schema-artifact.server.js +10 -4
  3. package/src/lib/artifact/dataset-schema-artifact.server.js.map +1 -1
  4. package/src/lib/components/data-console-page.js +4 -2
  5. package/src/lib/components/data-console-page.js.map +1 -1
  6. package/src/lib/components/dataset-record-dialog.component.d.ts +22 -0
  7. package/src/lib/components/dataset-record-dialog.component.js +77 -54
  8. package/src/lib/components/dataset-record-dialog.component.js.map +1 -1
  9. package/src/lib/components/dataset-schema-dialog.component.js +195 -168
  10. package/src/lib/components/dataset-schema-dialog.component.js.map +1 -1
  11. package/src/lib/components/host-datasets-card.component.d.ts +12 -0
  12. package/src/lib/components/host-datasets-card.component.js +652 -221
  13. package/src/lib/components/host-datasets-card.component.js.map +1 -1
  14. package/src/lib/components/use-dataset-writes-blocked.d.ts +5 -4
  15. package/src/lib/components/use-dataset-writes-blocked.js +11 -12
  16. package/src/lib/components/use-dataset-writes-blocked.js.map +1 -1
  17. package/src/lib/components/use-org-sites.d.ts +27 -0
  18. package/src/lib/components/use-org-sites.js +68 -0
  19. package/src/lib/components/use-org-sites.js.map +1 -0
  20. package/src/lib/model/data-record-routes.js +6 -3
  21. package/src/lib/model/data-record-routes.js.map +1 -1
  22. package/src/lib/model/dataset-model-core.d.ts +22 -0
  23. package/src/lib/model/dataset-model-core.js +34 -0
  24. package/src/lib/model/dataset-model-core.js.map +1 -1
  25. package/src/lib/model/dataset-rail.d.ts +88 -0
  26. package/src/lib/model/dataset-rail.js +123 -0
  27. package/src/lib/model/dataset-rail.js.map +1 -0
  28. package/src/lib/model/dataset-record-list.js +17 -2
  29. package/src/lib/model/dataset-record-list.js.map +1 -1
  30. package/src/lib/model/dataset-record.js +8 -3
  31. package/src/lib/model/dataset-record.js.map +1 -1
  32. package/src/lib/model/datasets.d.ts +14 -0
  33. package/src/lib/model/datasets.js +10 -0
  34. package/src/lib/model/datasets.js.map +1 -1
  35. package/src/lib/plugin.d.ts +5 -1
  36. package/src/lib/plugin.js +8 -3
  37. package/src/lib/plugin.js.map +1 -1
  38. package/src/lib/record-pages/record-template-section.component.js +12 -1
  39. package/src/lib/record-pages/record-template-section.component.js.map +1 -1
  40. package/src/lib/server/api-v1/datasets.js +6 -1
  41. package/src/lib/server/api-v1/datasets.js.map +1 -1
  42. package/src/lib/server/dataset-access.server.d.ts +4 -3
  43. package/src/lib/server/dataset-access.server.js +7 -5
  44. package/src/lib/server/dataset-access.server.js.map +1 -1
  45. package/src/lib/server/dataset-drafts.js +2 -0
  46. package/src/lib/server/dataset-drafts.js.map +1 -1
  47. package/src/lib/server/dataset-site-erasure.d.ts +2 -2
  48. package/src/lib/server/dataset-site-erasure.js +4 -26
  49. package/src/lib/server/dataset-site-erasure.js.map +1 -1
  50. package/src/lib/server/datasets-route.d.ts +2 -0
  51. package/src/lib/server/datasets-route.js +125 -19
  52. package/src/lib/server/datasets-route.js.map +1 -1
  53. package/src/lib/site-bundle/datasets-site-bundle.server.d.ts +4 -2
  54. package/src/lib/site-bundle/datasets-site-bundle.server.js +16 -5
  55. package/src/lib/site-bundle/datasets-site-bundle.server.js.map +1 -1
  56. package/src/lib/transfer/dataset-transfer-access.server.js +3 -3
  57. package/src/lib/transfer/dataset-transfer-access.server.js.map +1 -1
@@ -15,6 +15,7 @@
15
15
  * limitations under the License.
16
16
  */
17
17
  import { type AglynOrgCustomRole, type OrgPermission, resolveOrgPermissions } from '@aglyn/aglyn/app-utils/org-permissions';
18
+ import { type ScopePlaced } from '@aglyn/aglyn/app-utils/site-placement';
18
19
  import type { TransferInstanceImportAnswer, TransferInstanceImportSubject } from '@aglyn/aglyn/plugin-manager/plugin-transfer-resources';
19
20
  /** What the doors read off a membership document. */
20
21
  type DatasetWriter = NonNullable<Parameters<typeof resolveOrgPermissions>[0]> & {
@@ -60,12 +61,12 @@ export interface DatasetAccessBlocked {
60
61
  exports: boolean;
61
62
  }
62
63
  /**
63
- * The verdict for a member and a dataset placed at `visibleTo`, as the rule's
64
+ * The verdict for a member and a dataset, as its document places it, as the rule's
64
65
  * `canWriteDatasetOn` and the routes' `memberMayActOnDataset` give it, resolved
65
66
  * from what the site's stamp is written from. `customRole` is the member's custom
66
67
  * role when they carry one and it was read.
67
68
  */
68
- export declare function datasetAccessBlocked(member: DatasetWriter, visibleTo: unknown, customRole?: AglynOrgCustomRole | null): DatasetAccessBlocked;
69
+ export declare function datasetAccessBlocked(member: DatasetWriter, placed: ScopePlaced | null | undefined, customRole?: AglynOrgCustomRole | null): DatasetAccessBlocked;
69
70
  /**
70
71
  * Importing into one dataset, for the Import & export hub's row (AGL-4047): the
71
72
  * same verdict the Data page's Import reads, and the transfer routes' `importAccess`.
@@ -73,12 +74,12 @@ export declare function datasetAccessBlocked(member: DatasetWriter, visibleTo: u
73
74
  export declare function datasetInstanceImportAccess(subject: TransferInstanceImportSubject): TransferInstanceImportAnswer;
74
75
  /**
75
76
  * Which dataset controls switch off with the reason named rather than failing on
76
- * save, for the dataset placed at `visibleTo`. Nothing is blocked until the reads
77
+ * save, for this dataset, as its document places it. Nothing is blocked until the reads
77
78
  * land, nor for a reader with no membership, who is staff. Not a security
78
79
  * boundary: the rules and routes refuse regardless.
79
80
  *
80
81
  * Costs the membership the page already reads, and one read of a custom role
81
82
  * only for a member of the whole workspace whom the site decides.
82
83
  */
83
- export declare function useDatasetWritesBlocked(orgId: string | null | undefined, visibleTo?: unknown): DatasetAccessBlocked;
84
+ export declare function useDatasetWritesBlocked(orgId: string | null | undefined, placed?: ScopePlaced | null): DatasetAccessBlocked;
84
85
  export {};
@@ -50,26 +50,26 @@ const NOTHING_BLOCKED = {
50
50
  exports: false
51
51
  };
52
52
  /**
53
- * The verdict for a member and a dataset placed at `visibleTo`, as the rule's
53
+ * The verdict for a member and a dataset, as its document places it, as the rule's
54
54
  * `canWriteDatasetOn` and the routes' `memberMayActOnDataset` give it, resolved
55
55
  * from what the site's stamp is written from. `customRole` is the member's custom
56
56
  * role when they carry one and it was read.
57
- */ export function datasetAccessBlocked(member, visibleTo, customRole) {
57
+ */ export function datasetAccessBlocked(member, placed, customRole) {
58
58
  const seat = member;
59
- const site = oneSitePlacement(visibleTo);
59
+ const site = oneSitePlacement(placed);
60
60
  const writes = placementVerdict({
61
61
  member: seat,
62
- visibleTo,
62
+ placed,
63
63
  workspace: holdsDatasetPermission(member, DATA_MANAGE_PERMISSION),
64
64
  site: (hostId)=>resolvedPlacementKey(seat, hostId, DATA_SITE_MANAGE_PERMISSION, customRole)
65
65
  });
66
66
  const deletes = placementVerdict({
67
67
  member: seat,
68
- visibleTo,
68
+ placed,
69
69
  workspace: holdsDatasetPermission(member, DATA_ERASE_PERMISSION),
70
70
  site: (hostId)=>resolvedPlacementKey(seat, hostId, DATA_SITE_DELETE_PERMISSION, customRole)
71
71
  });
72
- const beyond = deleteBeyondReach(seat, visibleTo);
72
+ const beyond = deleteBeyondReach(seat, placed);
73
73
  const holdsManage = holdsDatasetPermission(member, DATA_MANAGE_PERMISSION);
74
74
  return {
75
75
  known: true,
@@ -87,8 +87,7 @@ const NOTHING_BLOCKED = {
87
87
  * Importing into one dataset, for the Import & export hub's row (AGL-4047): the
88
88
  * same verdict the Data page's Import reads, and the transfer routes' `importAccess`.
89
89
  */ export function datasetInstanceImportAccess(subject) {
90
- var _subject_record_facts;
91
- const blocked = datasetAccessBlocked(subject.member, (_subject_record_facts = subject.record.facts) == null ? void 0 : _subject_record_facts['visibleTo'], subject.customRole);
90
+ const blocked = datasetAccessBlocked(subject.member, subject.record.facts, subject.customRole);
92
91
  return {
93
92
  allowed: !blocked.writes,
94
93
  reason: blocked.writesReason
@@ -96,13 +95,13 @@ const NOTHING_BLOCKED = {
96
95
  }
97
96
  /**
98
97
  * Which dataset controls switch off with the reason named rather than failing on
99
- * save, for the dataset placed at `visibleTo`. Nothing is blocked until the reads
98
+ * save, for this dataset, as its document places it. Nothing is blocked until the reads
100
99
  * land, nor for a reader with no membership, who is staff. Not a security
101
100
  * boundary: the rules and routes refuse regardless.
102
101
  *
103
102
  * Costs the membership the page already reads, and one read of a custom role
104
103
  * only for a member of the whole workspace whom the site decides.
105
- */ export function useDatasetWritesBlocked(orgId, visibleTo) {
104
+ */ export function useDatasetWritesBlocked(orgId, placed) {
106
105
  var _ref, _role_data;
107
106
  const firestore = useFirestore();
108
107
  const { data: user } = useUser();
@@ -113,7 +112,7 @@ const NOTHING_BLOCKED = {
113
112
  uid
114
113
  ]);
115
114
  const seat = status === 'success' ? member : null;
116
- const site = oneSitePlacement(visibleTo);
115
+ const site = oneSitePlacement(placed);
117
116
  // Only someone the site decides: narrowed on it, or on a role wider or narrower here.
118
117
  const siteDecides = Boolean(seat && site) && isOrgWideMember(seat) && (Boolean(siteMayNarrow(seat, site)) || !holdsDatasetPermission(seat, DATA_MANAGE_PERMISSION));
119
118
  const roleId = siteDecides && typeof (seat == null ? void 0 : seat.roleId) === 'string' ? seat.roleId : '';
@@ -123,7 +122,7 @@ const NOTHING_BLOCKED = {
123
122
  roleId
124
123
  ]);
125
124
  if (!seat || roleId && role.status === 'loading') return NOTHING_BLOCKED;
126
- return datasetAccessBlocked(seat, visibleTo, roleId && role.status === 'success' ? (_role_data = role.data) != null ? _role_data : null : null);
125
+ return datasetAccessBlocked(seat, placed, roleId && role.status === 'success' ? (_role_data = role.data) != null ? _role_data : null : null);
127
126
  }
128
127
 
129
128
  //# sourceMappingURL=use-dataset-writes-blocked.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/components/use-dataset-writes-blocked.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 type AglynOrgCustomRole,\n type OrgPermission,\n permissionRefusalText,\n resolveOrgPermissions,\n} from '@aglyn/aglyn/app-utils/org-permissions'\nimport { siteMayNarrow } from '@aglyn/aglyn/app-utils/host-permissions'\nimport { isOrgWideMember } from '@aglyn/aglyn/app-utils/organizations'\nimport {\n deleteBeyondReach,\n deleteBeyondReachRefusal,\n oneSitePlacement,\n placementVerdict,\n resolvedPlacementKey,\n} from '@aglyn/aglyn/app-utils/site-placement'\nimport type { AglynOrgMember } from '@aglyn/aglyn/foundation/definitions/organization.types'\nimport type {\n TransferInstanceImportAnswer,\n TransferInstanceImportSubject,\n} from '@aglyn/aglyn/plugin-manager/plugin-transfer-resources'\nimport { useFirestore, useFirestoreDoc, useUser } from '@aglyn/tenant-feature-instance'\nimport { doc } from 'firebase/firestore'\nimport {\n DATA_ERASE_PERMISSION,\n DATA_EXPORT_PERMISSION,\n DATA_MANAGE_PERMISSION,\n DATA_SITE_DELETE_PERMISSION,\n DATA_SITE_MANAGE_PERMISSION,\n DATA_VIEW_RECORDS_PERMISSION,\n dataPermissionRefusal,\n} from '../model/dataset-access'\n\n/** What the doors read off a membership document. */\ntype DatasetWriter = NonNullable<Parameters<typeof resolveOrgPermissions>[0]> & {\n resolvedPermissions?: Readonly<Record<string, unknown>>\n permissions?: Readonly<Record<string, unknown>>\n}\n\n/** Creating, editing and sharing datasets, and every record write. */\nexport const DATASETS_WRITE_PERMISSION: OrgPermission = DATA_MANAGE_PERMISSION\n/** Deleting a whole dataset, which the erase route asks. */\nexport const DATASETS_DELETE_PERMISSION: OrgPermission = DATA_ERASE_PERMISSION\n\nexport const DATASETS_WRITE_REFUSAL = permissionRefusalText(DATASETS_WRITE_PERMISSION)\nexport const DATASETS_DELETE_REFUSAL = permissionRefusalText(DATASETS_DELETE_PERMISSION)\nexport const DATASETS_VIEW_RECORDS_REFUSAL = dataPermissionRefusal(DATA_VIEW_RECORDS_PERMISSION)\nexport const DATASETS_EXPORT_REFUSAL = dataPermissionRefusal(DATA_EXPORT_PERMISSION)\n\n/**\n * A member's answer for a dataset key (AGL-4047), as the rules' `memberKeyOrOverride`\n * and the routes' `memberHasOrgPermission` read it: the decision written on\n * `resolvedPermissions`, or, for a member the projection never stamped, on their\n * own `permissions`; else their workspace role's default.\n */\nexport function holdsDatasetPermission(member: DatasetWriter, permission: OrgPermission): boolean {\n const stamped = (member.resolvedPermissions ?? member.permissions)?.[permission]\n if (typeof stamped === 'boolean') return stamped\n return resolveOrgPermissions(member)[permission] === true\n}\n\n/** What the signed-in member is known not to be able to do with a dataset, and why. */\nexport interface DatasetAccessBlocked {\n /** Whether these answers rest on the member's reads, rather than on their not having landed. */\n known: boolean\n /** Making a new dataset: \"Manage data\". */\n creates: boolean\n /** Changing this dataset's schema or records, or importing into it. */\n writes: boolean\n writesReason: string\n /**\n * The writes are off, and changing who it is shared with stays this member's:\n * they hold \"Manage data\" across every site, and a site narrows them on the one\n * this dataset sits on. Sharing is not among what a narrowing takes.\n */\n sharingOnly: boolean\n /** Deleting this dataset. */\n deletes: boolean\n deletesReason: string\n /** Reading this dataset's records. */\n records: boolean\n /** Taking this dataset's records out as a file. */\n exports: boolean\n}\n\nconst NOTHING_BLOCKED: DatasetAccessBlocked = {\n known: false,\n creates: false,\n writes: false,\n writesReason: DATASETS_WRITE_REFUSAL,\n sharingOnly: false,\n deletes: false,\n deletesReason: DATASETS_DELETE_REFUSAL,\n records: false,\n exports: false,\n}\n\n/**\n * The verdict for a member and a dataset placed at `visibleTo`, as the rule's\n * `canWriteDatasetOn` and the routes' `memberMayActOnDataset` give it, resolved\n * from what the site's stamp is written from. `customRole` is the member's custom\n * role when they carry one and it was read.\n */\nexport function datasetAccessBlocked(\n member: DatasetWriter,\n visibleTo: unknown,\n customRole?: AglynOrgCustomRole | null,\n): DatasetAccessBlocked {\n const seat = member as Partial<AglynOrgMember>\n const site = oneSitePlacement(visibleTo)\n const writes = placementVerdict<boolean>({\n member: seat,\n visibleTo,\n workspace: holdsDatasetPermission(member, DATA_MANAGE_PERMISSION),\n site: (hostId) => resolvedPlacementKey(seat, hostId, DATA_SITE_MANAGE_PERMISSION, customRole),\n })\n const deletes = placementVerdict<boolean>({\n member: seat,\n visibleTo,\n workspace: holdsDatasetPermission(member, DATA_ERASE_PERMISSION),\n site: (hostId) => resolvedPlacementKey(seat, hostId, DATA_SITE_DELETE_PERMISSION, customRole),\n })\n const beyond = deleteBeyondReach(seat, visibleTo)\n const holdsManage = holdsDatasetPermission(member, DATA_MANAGE_PERMISSION)\n return {\n known: true,\n creates: !holdsManage,\n writes: !writes,\n sharingOnly: !writes && holdsManage && isOrgWideMember(seat),\n writesReason: site ? dataPermissionRefusal(DATA_SITE_MANAGE_PERMISSION) : DATASETS_WRITE_REFUSAL,\n deletes: beyond || !deletes,\n deletesReason: beyond\n ? deleteBeyondReachRefusal('dataset')\n : site\n ? dataPermissionRefusal(DATA_SITE_DELETE_PERMISSION)\n : DATASETS_DELETE_REFUSAL,\n records: !holdsDatasetPermission(member, DATA_VIEW_RECORDS_PERMISSION),\n exports: !holdsDatasetPermission(member, DATA_EXPORT_PERMISSION),\n }\n}\n\n/**\n * Importing into one dataset, for the Import & export hub's row (AGL-4047): the\n * same verdict the Data page's Import reads, and the transfer routes' `importAccess`.\n */\nexport function datasetInstanceImportAccess(subject: TransferInstanceImportSubject): TransferInstanceImportAnswer {\n const blocked = datasetAccessBlocked(\n subject.member as DatasetWriter,\n subject.record.facts?.['visibleTo'],\n subject.customRole as AglynOrgCustomRole | null,\n )\n return { allowed: !blocked.writes, reason: blocked.writesReason }\n}\n\n/**\n * Which dataset controls switch off with the reason named rather than failing on\n * save, for the dataset placed at `visibleTo`. Nothing is blocked until the reads\n * land, nor for a reader with no membership, who is staff. Not a security\n * boundary: the rules and routes refuse regardless.\n *\n * Costs the membership the page already reads, and one read of a custom role\n * only for a member of the whole workspace whom the site decides.\n */\nexport function useDatasetWritesBlocked(\n orgId: string | null | undefined,\n visibleTo?: unknown,\n): DatasetAccessBlocked {\n const firestore = useFirestore()\n const { data: user } = useUser()\n const uid = (user as { uid?: string } | undefined)?.uid ?? ''\n const { data: member, status } = useFirestoreDoc<DatasetWriter>(\n () => (orgId && uid ? doc(firestore, 'orgs', orgId, 'members', uid) : null),\n [firestore, orgId, uid],\n )\n const seat = (status === 'success' ? member : null) as (DatasetWriter & { roleId?: unknown }) | null | undefined\n const site = oneSitePlacement(visibleTo)\n // Only someone the site decides: narrowed on it, or on a role wider or narrower here.\n const siteDecides =\n Boolean(seat && site) &&\n isOrgWideMember(seat as Partial<AglynOrgMember>) &&\n (Boolean(siteMayNarrow(seat as Partial<AglynOrgMember>, site)) || !holdsDatasetPermission(seat as DatasetWriter, DATA_MANAGE_PERMISSION))\n const roleId = siteDecides && typeof seat?.roleId === 'string' ? seat.roleId : ''\n const role = useFirestoreDoc<AglynOrgCustomRole>(\n () => (orgId && roleId ? doc(firestore, 'orgs', orgId, 'roles', roleId) : null),\n [firestore, orgId, roleId],\n )\n if (!seat || (roleId && role.status === 'loading')) return NOTHING_BLOCKED\n return datasetAccessBlocked(seat, visibleTo, roleId && role.status === 'success' ? (role.data ?? null) : null)\n}\n"],"names":["permissionRefusalText","resolveOrgPermissions","siteMayNarrow","isOrgWideMember","deleteBeyondReach","deleteBeyondReachRefusal","oneSitePlacement","placementVerdict","resolvedPlacementKey","useFirestore","useFirestoreDoc","useUser","doc","DATA_ERASE_PERMISSION","DATA_EXPORT_PERMISSION","DATA_MANAGE_PERMISSION","DATA_SITE_DELETE_PERMISSION","DATA_SITE_MANAGE_PERMISSION","DATA_VIEW_RECORDS_PERMISSION","dataPermissionRefusal","DATASETS_WRITE_PERMISSION","DATASETS_DELETE_PERMISSION","DATASETS_WRITE_REFUSAL","DATASETS_DELETE_REFUSAL","DATASETS_VIEW_RECORDS_REFUSAL","DATASETS_EXPORT_REFUSAL","holdsDatasetPermission","member","permission","stamped","resolvedPermissions","permissions","NOTHING_BLOCKED","known","creates","writes","writesReason","sharingOnly","deletes","deletesReason","records","exports","datasetAccessBlocked","visibleTo","customRole","seat","site","workspace","hostId","beyond","holdsManage","datasetInstanceImportAccess","subject","blocked","record","facts","allowed","reason","useDatasetWritesBlocked","orgId","role","firestore","data","user","uid","status","siteDecides","Boolean","roleId"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAGEA,qBAAqB,EACrBC,qBAAqB,QAChB,yCAAwC;AAC/C,SAASC,aAAa,QAAQ,0CAAyC;AACvE,SAASC,eAAe,QAAQ,uCAAsC;AACtE,SACEC,iBAAiB,EACjBC,wBAAwB,EACxBC,gBAAgB,EAChBC,gBAAgB,EAChBC,oBAAoB,QACf,wCAAuC;AAM9C,SAASC,YAAY,EAAEC,eAAe,EAAEC,OAAO,QAAQ,iCAAgC;AACvF,SAASC,GAAG,QAAQ,qBAAoB;AACxC,SACEC,qBAAqB,EACrBC,sBAAsB,EACtBC,sBAAsB,EACtBC,2BAA2B,EAC3BC,2BAA2B,EAC3BC,4BAA4B,EAC5BC,qBAAqB,QAChB,6BAAyB;AAQhC,oEAAoE,GACpE,OAAO,MAAMC,4BAA2CL,uBAAsB;AAC9E,0DAA0D,GAC1D,OAAO,MAAMM,6BAA4CR,sBAAqB;AAE9E,OAAO,MAAMS,yBAAyBtB,sBAAsBoB,2BAA0B;AACtF,OAAO,MAAMG,0BAA0BvB,sBAAsBqB,4BAA2B;AACxF,OAAO,MAAMG,gCAAgCL,sBAAsBD,8BAA6B;AAChG,OAAO,MAAMO,0BAA0BN,sBAAsBL,wBAAuB;AAEpF;;;;;CAKC,GACD,OAAO,SAASY,uBAAuBC,MAAqB,EAAEC,UAAyB;QACpED;QAAAA;IAAjB,MAAME,WAAWF,SAAAA,8BAAAA,OAAOG,mBAAmB,YAA1BH,8BAA8BA,OAAOI,WAAW,qBAAjD,AAACJ,KA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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 type AglynOrgCustomRole,\n type OrgPermission,\n permissionRefusalText,\n resolveOrgPermissions,\n} from '@aglyn/aglyn/app-utils/org-permissions'\nimport { siteMayNarrow } from '@aglyn/aglyn/app-utils/host-permissions'\nimport { isOrgWideMember } from '@aglyn/aglyn/app-utils/organizations'\nimport {\n deleteBeyondReach,\n deleteBeyondReachRefusal,\n oneSitePlacement,\n placementVerdict,\n resolvedPlacementKey,\n type ScopePlaced,\n} from '@aglyn/aglyn/app-utils/site-placement'\nimport type { AglynOrgMember } from '@aglyn/aglyn/foundation/definitions/organization.types'\nimport type {\n TransferInstanceImportAnswer,\n TransferInstanceImportSubject,\n} from '@aglyn/aglyn/plugin-manager/plugin-transfer-resources'\nimport { useFirestore, useFirestoreDoc, useUser } from '@aglyn/tenant-feature-instance'\nimport { doc } from 'firebase/firestore'\nimport {\n DATA_ERASE_PERMISSION,\n DATA_EXPORT_PERMISSION,\n DATA_MANAGE_PERMISSION,\n DATA_SITE_DELETE_PERMISSION,\n DATA_SITE_MANAGE_PERMISSION,\n DATA_VIEW_RECORDS_PERMISSION,\n dataPermissionRefusal,\n} from '../model/dataset-access'\n\n/** What the doors read off a membership document. */\ntype DatasetWriter = NonNullable<Parameters<typeof resolveOrgPermissions>[0]> & {\n resolvedPermissions?: Readonly<Record<string, unknown>>\n permissions?: Readonly<Record<string, unknown>>\n}\n\n/** Creating, editing and sharing datasets, and every record write. */\nexport const DATASETS_WRITE_PERMISSION: OrgPermission = DATA_MANAGE_PERMISSION\n/** Deleting a whole dataset, which the erase route asks. */\nexport const DATASETS_DELETE_PERMISSION: OrgPermission = DATA_ERASE_PERMISSION\n\nexport const DATASETS_WRITE_REFUSAL = permissionRefusalText(DATASETS_WRITE_PERMISSION)\nexport const DATASETS_DELETE_REFUSAL = permissionRefusalText(DATASETS_DELETE_PERMISSION)\nexport const DATASETS_VIEW_RECORDS_REFUSAL = dataPermissionRefusal(DATA_VIEW_RECORDS_PERMISSION)\nexport const DATASETS_EXPORT_REFUSAL = dataPermissionRefusal(DATA_EXPORT_PERMISSION)\n\n/**\n * A member's answer for a dataset key (AGL-4047), as the rules' `memberKeyOrOverride`\n * and the routes' `memberHasOrgPermission` read it: the decision written on\n * `resolvedPermissions`, or, for a member the projection never stamped, on their\n * own `permissions`; else their workspace role's default.\n */\nexport function holdsDatasetPermission(member: DatasetWriter, permission: OrgPermission): boolean {\n const stamped = (member.resolvedPermissions ?? member.permissions)?.[permission]\n if (typeof stamped === 'boolean') return stamped\n return resolveOrgPermissions(member)[permission] === true\n}\n\n/** What the signed-in member is known not to be able to do with a dataset, and why. */\nexport interface DatasetAccessBlocked {\n /** Whether these answers rest on the member's reads, rather than on their not having landed. */\n known: boolean\n /** Making a new dataset: \"Manage data\". */\n creates: boolean\n /** Changing this dataset's schema or records, or importing into it. */\n writes: boolean\n writesReason: string\n /**\n * The writes are off, and changing who it is shared with stays this member's:\n * they hold \"Manage data\" across every site, and a site narrows them on the one\n * this dataset sits on. Sharing is not among what a narrowing takes.\n */\n sharingOnly: boolean\n /** Deleting this dataset. */\n deletes: boolean\n deletesReason: string\n /** Reading this dataset's records. */\n records: boolean\n /** Taking this dataset's records out as a file. */\n exports: boolean\n}\n\nconst NOTHING_BLOCKED: DatasetAccessBlocked = {\n known: false,\n creates: false,\n writes: false,\n writesReason: DATASETS_WRITE_REFUSAL,\n sharingOnly: false,\n deletes: false,\n deletesReason: DATASETS_DELETE_REFUSAL,\n records: false,\n exports: false,\n}\n\n/**\n * The verdict for a member and a dataset, as its document places it, as the rule's\n * `canWriteDatasetOn` and the routes' `memberMayActOnDataset` give it, resolved\n * from what the site's stamp is written from. `customRole` is the member's custom\n * role when they carry one and it was read.\n */\nexport function datasetAccessBlocked(\n member: DatasetWriter,\n placed: ScopePlaced | null | undefined,\n customRole?: AglynOrgCustomRole | null,\n): DatasetAccessBlocked {\n const seat = member as Partial<AglynOrgMember>\n const site = oneSitePlacement(placed)\n const writes = placementVerdict<boolean>({\n member: seat,\n placed,\n workspace: holdsDatasetPermission(member, DATA_MANAGE_PERMISSION),\n site: (hostId) => resolvedPlacementKey(seat, hostId, DATA_SITE_MANAGE_PERMISSION, customRole),\n })\n const deletes = placementVerdict<boolean>({\n member: seat,\n placed,\n workspace: holdsDatasetPermission(member, DATA_ERASE_PERMISSION),\n site: (hostId) => resolvedPlacementKey(seat, hostId, DATA_SITE_DELETE_PERMISSION, customRole),\n })\n const beyond = deleteBeyondReach(seat, placed)\n const holdsManage = holdsDatasetPermission(member, DATA_MANAGE_PERMISSION)\n return {\n known: true,\n creates: !holdsManage,\n writes: !writes,\n sharingOnly: !writes && holdsManage && isOrgWideMember(seat),\n writesReason: site ? dataPermissionRefusal(DATA_SITE_MANAGE_PERMISSION) : DATASETS_WRITE_REFUSAL,\n deletes: beyond || !deletes,\n deletesReason: beyond\n ? deleteBeyondReachRefusal('dataset')\n : site\n ? dataPermissionRefusal(DATA_SITE_DELETE_PERMISSION)\n : DATASETS_DELETE_REFUSAL,\n records: !holdsDatasetPermission(member, DATA_VIEW_RECORDS_PERMISSION),\n exports: !holdsDatasetPermission(member, DATA_EXPORT_PERMISSION),\n }\n}\n\n/**\n * Importing into one dataset, for the Import & export hub's row (AGL-4047): the\n * same verdict the Data page's Import reads, and the transfer routes' `importAccess`.\n */\nexport function datasetInstanceImportAccess(subject: TransferInstanceImportSubject): TransferInstanceImportAnswer {\n const blocked = datasetAccessBlocked(\n subject.member as DatasetWriter,\n subject.record.facts,\n subject.customRole as AglynOrgCustomRole | null,\n )\n return { allowed: !blocked.writes, reason: blocked.writesReason }\n}\n\n/**\n * Which dataset controls switch off with the reason named rather than failing on\n * save, for this dataset, as its document places it. Nothing is blocked until the reads\n * land, nor for a reader with no membership, who is staff. Not a security\n * boundary: the rules and routes refuse regardless.\n *\n * Costs the membership the page already reads, and one read of a custom role\n * only for a member of the whole workspace whom the site decides.\n */\nexport function useDatasetWritesBlocked(\n orgId: string | null | undefined,\n placed?: ScopePlaced | null,\n): DatasetAccessBlocked {\n const firestore = useFirestore()\n const { data: user } = useUser()\n const uid = (user as { uid?: string } | undefined)?.uid ?? ''\n const { data: member, status } = useFirestoreDoc<DatasetWriter>(\n () => (orgId && uid ? doc(firestore, 'orgs', orgId, 'members', uid) : null),\n [firestore, orgId, uid],\n )\n const seat = (status === 'success' ? member : null) as (DatasetWriter & { roleId?: unknown }) | null | undefined\n const site = oneSitePlacement(placed)\n // Only someone the site decides: narrowed on it, or on a role wider or narrower here.\n const siteDecides =\n Boolean(seat && site) &&\n isOrgWideMember(seat as Partial<AglynOrgMember>) &&\n (Boolean(siteMayNarrow(seat as Partial<AglynOrgMember>, site)) || !holdsDatasetPermission(seat as DatasetWriter, DATA_MANAGE_PERMISSION))\n const roleId = siteDecides && typeof seat?.roleId === 'string' ? seat.roleId : ''\n const role = useFirestoreDoc<AglynOrgCustomRole>(\n () => (orgId && roleId ? doc(firestore, 'orgs', orgId, 'roles', roleId) : null),\n [firestore, orgId, roleId],\n )\n if (!seat || (roleId && role.status === 'loading')) return NOTHING_BLOCKED\n return datasetAccessBlocked(seat, placed, roleId && role.status === 'success' ? (role.data ?? null) : null)\n}\n"],"names":["permissionRefusalText","resolveOrgPermissions","siteMayNarrow","isOrgWideMember","deleteBeyondReach","deleteBeyondReachRefusal","oneSitePlacement","placementVerdict","resolvedPlacementKey","useFirestore","useFirestoreDoc","useUser","doc","DATA_ERASE_PERMISSION","DATA_EXPORT_PERMISSION","DATA_MANAGE_PERMISSION","DATA_SITE_DELETE_PERMISSION","DATA_SITE_MANAGE_PERMISSION","DATA_VIEW_RECORDS_PERMISSION","dataPermissionRefusal","DATASETS_WRITE_PERMISSION","DATASETS_DELETE_PERMISSION","DATASETS_WRITE_REFUSAL","DATASETS_DELETE_REFUSAL","DATASETS_VIEW_RECORDS_REFUSAL","DATASETS_EXPORT_REFUSAL","holdsDatasetPermission","member","permission","stamped","resolvedPermissions","permissions","NOTHING_BLOCKED","known","creates","writes","writesReason","sharingOnly","deletes","deletesReason","records","exports","datasetAccessBlocked","placed","customRole","seat","site","workspace","hostId","beyond","holdsManage","datasetInstanceImportAccess","subject","blocked","record","facts","allowed","reason","useDatasetWritesBlocked","orgId","role","firestore","data","user","uid","status","siteDecides","Boolean","roleId"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAGEA,qBAAqB,EACrBC,qBAAqB,QAChB,yCAAwC;AAC/C,SAASC,aAAa,QAAQ,0CAAyC;AACvE,SAASC,eAAe,QAAQ,uCAAsC;AACtE,SACEC,iBAAiB,EACjBC,wBAAwB,EACxBC,gBAAgB,EAChBC,gBAAgB,EAChBC,oBAAoB,QAEf,wCAAuC;AAM9C,SAASC,YAAY,EAAEC,eAAe,EAAEC,OAAO,QAAQ,iCAAgC;AACvF,SAASC,GAAG,QAAQ,qBAAoB;AACxC,SACEC,qBAAqB,EACrBC,sBAAsB,EACtBC,sBAAsB,EACtBC,2BAA2B,EAC3BC,2BAA2B,EAC3BC,4BAA4B,EAC5BC,qBAAqB,QAChB,6BAAyB;AAQhC,oEAAoE,GACpE,OAAO,MAAMC,4BAA2CL,uBAAsB;AAC9E,0DAA0D,GAC1D,OAAO,MAAMM,6BAA4CR,sBAAqB;AAE9E,OAAO,MAAMS,yBAAyBtB,sBAAsBoB,2BAA0B;AACtF,OAAO,MAAMG,0BAA0BvB,sBAAsBqB,4BAA2B;AACxF,OAAO,MAAMG,gCAAgCL,sBAAsBD,8BAA6B;AAChG,OAAO,MAAMO,0BAA0BN,sBAAsBL,wBAAuB;AAEpF;;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,KAAK,aAAaL,aAAAA,KAAKE,IAAI,YAATF,aAAa,OAAQ;AACxG"}
@@ -0,0 +1,27 @@
1
+ /** A site of the workspace the reader is a member of, as the Data page names it. */
2
+ export interface OrgSite {
3
+ $id: string;
4
+ name?: string;
5
+ subdomain?: string;
6
+ }
7
+ /**
8
+ * The workspace's sites this reader is a member of, for naming who a dataset
9
+ * is shared with (AGL-1145, AGL-4047).
10
+ *
11
+ * Queried here rather than via the console's `useOrgHosts`, because this
12
+ * plugin is a lib and cannot import from an app, so it repeats that hook's
13
+ * membership filter. `/hosts/{hostId}` is gated per document on
14
+ * `memberRoles.{uid}`, and Firestore evaluates a LIST against the QUERY rather
15
+ * than its results: filtering on `orgId` alone is a flat denial for every
16
+ * non-staff reader (cloud/hosts-list-constraint.spec.mjs).
17
+ *
18
+ * ONE query, word for word, for the Data card and its Schema dialog: the SDK
19
+ * serves two listeners of the same query from one target, so naming the
20
+ * sites in the rail costs no read the dialog was not already making.
21
+ */
22
+ export declare function useOrgSites(orgId: string | null | undefined): {
23
+ sites: OrgSite[];
24
+ /** Site id → the name the console shows for it. */
25
+ hostNames: Readonly<Record<string, string>>;
26
+ ready: boolean;
27
+ };
@@ -0,0 +1,68 @@
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
+ */ 'use client';
17
+ import { HOST_ACCESS_ROLES } from "@aglyn/aglyn";
18
+ import { useFirestore, useFirestoreCollection, useUser } from "@aglyn/tenant-feature-instance";
19
+ import { collection, limit, query, where } from "firebase/firestore";
20
+ import { useMemo } from "react";
21
+ const NO_SITES = [];
22
+ /**
23
+ * The workspace's sites this reader is a member of, for naming who a dataset
24
+ * is shared with (AGL-1145, AGL-4047).
25
+ *
26
+ * Queried here rather than via the console's `useOrgHosts`, because this
27
+ * plugin is a lib and cannot import from an app, so it repeats that hook's
28
+ * membership filter. `/hosts/{hostId}` is gated per document on
29
+ * `memberRoles.{uid}`, and Firestore evaluates a LIST against the QUERY rather
30
+ * than its results: filtering on `orgId` alone is a flat denial for every
31
+ * non-staff reader (cloud/hosts-list-constraint.spec.mjs).
32
+ *
33
+ * ONE query, word for word, for the Data card and its Schema dialog: the SDK
34
+ * serves two listeners of the same query from one target, so naming the
35
+ * sites in the rail costs no read the dialog was not already making.
36
+ */ export function useOrgSites(orgId) {
37
+ const firestore = useFirestore();
38
+ const { data: user } = useUser();
39
+ const uid = user == null ? void 0 : user.uid;
40
+ const { data } = useFirestoreCollection(// Held rather than substituted while the uid resolves: a placeholder is
41
+ // still a question asked of the server, and here one that is denied.
42
+ ()=>uid && orgId ? query(collection(firestore, 'hosts'), where(`memberRoles.${uid}`, 'in', HOST_ACCESS_ROLES), where('orgId', '==', orgId), limit(200)) : null, [
43
+ firestore,
44
+ orgId,
45
+ uid
46
+ ], {
47
+ idField: '$id'
48
+ });
49
+ const sites = useMemo(()=>data != null ? data : NO_SITES, [
50
+ data
51
+ ]);
52
+ const hostNames = useMemo(()=>Object.fromEntries(sites.map((site)=>{
53
+ var _ref, _site_name;
54
+ return [
55
+ site.$id,
56
+ (_ref = (_site_name = site.name) != null ? _site_name : site.subdomain) != null ? _ref : site.$id
57
+ ];
58
+ })), [
59
+ sites
60
+ ]);
61
+ return {
62
+ sites,
63
+ hostNames,
64
+ ready: Array.isArray(data)
65
+ };
66
+ }
67
+
68
+ //# sourceMappingURL=use-org-sites.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/components/use-org-sites.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'use client'\n\nimport { HOST_ACCESS_ROLES } from '@aglyn/aglyn'\nimport { useFirestore, useFirestoreCollection, useUser } from '@aglyn/tenant-feature-instance'\nimport { collection, limit, query, where } from 'firebase/firestore'\nimport { useMemo } from 'react'\n\n/** A site of the workspace the reader is a member of, as the Data page names it. */\nexport interface OrgSite {\n $id: string\n name?: string\n subdomain?: string\n}\n\nconst NO_SITES: OrgSite[] = []\n\n/**\n * The workspace's sites this reader is a member of, for naming who a dataset\n * is shared with (AGL-1145, AGL-4047).\n *\n * Queried here rather than via the console's `useOrgHosts`, because this\n * plugin is a lib and cannot import from an app, so it repeats that hook's\n * membership filter. `/hosts/{hostId}` is gated per document on\n * `memberRoles.{uid}`, and Firestore evaluates a LIST against the QUERY rather\n * than its results: filtering on `orgId` alone is a flat denial for every\n * non-staff reader (cloud/hosts-list-constraint.spec.mjs).\n *\n * ONE query, word for word, for the Data card and its Schema dialog: the SDK\n * serves two listeners of the same query from one target, so naming the\n * sites in the rail costs no read the dialog was not already making.\n */\nexport function useOrgSites(orgId: string | null | undefined): {\n sites: OrgSite[]\n /** Site id → the name the console shows for it. */\n hostNames: Readonly<Record<string, string>>\n ready: boolean\n} {\n const firestore = useFirestore()\n const { data: user } = useUser()\n const uid = (user as { uid?: string } | undefined)?.uid\n const { data } = useFirestoreCollection<OrgSite>(\n // Held rather than substituted while the uid resolves: a placeholder is\n // still a question asked of the server, and here one that is denied.\n () =>\n uid && orgId\n ? query(\n collection(firestore, 'hosts'),\n where(`memberRoles.${uid}`, 'in', HOST_ACCESS_ROLES),\n where('orgId', '==', orgId),\n limit(200),\n )\n : null,\n [firestore, orgId, uid],\n { idField: '$id' },\n )\n const sites = useMemo(() => data ?? NO_SITES, [data])\n const hostNames = useMemo(\n () => Object.fromEntries(sites.map((site) => [site.$id, site.name ?? site.subdomain ?? site.$id])),\n [sites],\n )\n return { sites, hostNames, ready: Array.isArray(data) }\n}\n"],"names":["HOST_ACCESS_ROLES","useFirestore","useFirestoreCollection","useUser","collection","limit","query","where","useMemo","NO_SITES","useOrgSites","orgId","firestore","data","user","uid","idField","sites","hostNames","Object","fromEntries","map","site","$id","name","subdomain","ready","Array","isArray"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;AAEA,SAASA,iBAAiB,QAAQ,eAAc;AAChD,SAASC,YAAY,EAAEC,sBAAsB,EAAEC,OAAO,QAAQ,iCAAgC;AAC9F,SAASC,UAAU,EAAEC,KAAK,EAAEC,KAAK,EAAEC,KAAK,QAAQ,qBAAoB;AACpE,SAASC,OAAO,QAAQ,QAAO;AAS/B,MAAMC,WAAsB,EAAE;AAE9B;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASC,YAAYC,KAAgC;IAM1D,MAAMC,YAAYX;IAClB,MAAM,EAAEY,MAAMC,IAAI,EAAE,GAAGX;IACvB,MAAMY,MAAOD,wBAAD,AAACA,KAAuCC,GAAG;IACvD,MAAM,EAAEF,IAAI,EAAE,GAAGX,uBACf,wEAAwE;IACxE,qEAAqE;IACrE,IACEa,OAAOJ,QACHL,MACEF,WAAWQ,WAAW,UACtBL,MAAM,CAAC,YAAY,EAAEQ,KAAK,EAAE,MAAMf,oBAClCO,MAAM,SAAS,MAAMI,QACrBN,MAAM,QAER,MACN;QAACO;QAAWD;QAAOI;KAAI,EACvB;QAAEC,SAAS;IAAM;IAEnB,MAAMC,QAAQT,QAAQ,IAAMK,eAAAA,OAAQJ,UAAU;QAACI;KAAK;IACpD,MAAMK,YAAYV,QAChB,IAAMW,OAAOC,WAAW,CAACH,MAAMI,GAAG,CAAC,CAACC;gBAAoBA,MAAAA;mBAAX;gBAACA,KAAKC,GAAG;iBAAED,QAAAA,aAAAA,KAAKE,IAAI,YAATF,aAAaA,KAAKG,SAAS,YAA3BH,OAA+BA,KAAKC,GAAG;aAAC;aAChG;QAACN;KAAM;IAET,OAAO;QAAEA;QAAOC;QAAWQ,OAAOC,MAAMC,OAAO,CAACf;IAAM;AACxD"}
@@ -24,8 +24,8 @@ import { BUNDLE_ID } from "../constants/bundle-common.js";
24
24
  * for `dataset` rather than spelling this plugin's nav slug, and gets `null`
25
25
  * (text instead of a link) where it is not loaded. A dataset belongs to the
26
26
  * organization and is shared with sites: a site's Data page lists the ones it
27
- * can see, and the organization's lists them all. Neither has a page of one
28
- * dataset, so a record opens the list.
27
+ * can see, and the organization's lists them all. Each dataset is a tab of
28
+ * those pages at `/data/<datasetId>` (AGL-4047), so a record opens its tab.
29
29
  */ /** The nav slug the shell resolves this plugin's site page by. */ const DATA_SLUG = 'data';
30
30
  function list({ orgSlug, host }) {
31
31
  if (!orgSlug) return null;
@@ -44,7 +44,10 @@ function list({ orgSlug, host }) {
44
44
  */ export function registerDataRecordRoutes() {
45
45
  registerPluginRecordRoute('dataset', {
46
46
  list,
47
- record: (context)=>list(context)
47
+ record: (context, id)=>{
48
+ const page = list(context);
49
+ return page && id ? `${page}/${encodeURIComponent(id)}` : page;
50
+ }
48
51
  }, {
49
52
  pluginId: BUNDLE_ID
50
53
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/model/data-record-routes.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 { buildRoute, Route } from '@aglyn/aglyn/app-utils/console-routes'\nimport {\n registerPluginRecordRoute,\n type PluginRecordRouteContext,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-routes'\nimport { BUNDLE_ID } from '../constants/bundle-common'\n\n/**\n * Where a dataset is read, published for every other surface (AGL-3616).\n *\n * An assistant job that made a menu or a team as a dataset opens it on the\n * Data page, which is this plugin's — so it asks the record-route registry\n * for `dataset` rather than spelling this plugin's nav slug, and gets `null`\n * (text instead of a link) where it is not loaded. A dataset belongs to the\n * organization and is shared with sites: a site's Data page lists the ones it\n * can see, and the organization's lists them all. Neither has a page of one\n * dataset, so a record opens the list.\n */\n\n/** The nav slug the shell resolves this plugin's site page by. */\nconst DATA_SLUG = 'data'\n\nfunction list({ orgSlug, host }: PluginRecordRouteContext): string | null {\n if (!orgSlug) return null\n return host ? buildRoute(Route.HOST_PLUGIN, { orgSlug, host, pluginSlug: DATA_SLUG }) : buildRoute(Route.ORG_DATA, { orgSlug })\n}\n\n/**\n * Called from the console registrar. The owner is named rather than read off\n * the loader's marker, so the route registers the same way under a spec that\n * calls the registrar directly.\n */\nexport function registerDataRecordRoutes(): void {\n registerPluginRecordRoute('dataset', { list, record: (context) => list(context) }, { pluginId: BUNDLE_ID })\n}\n"],"names":["buildRoute","Route","registerPluginRecordRoute","BUNDLE_ID","DATA_SLUG","list","orgSlug","host","HOST_PLUGIN","pluginSlug","ORG_DATA","registerDataRecordRoutes","record","context","pluginId"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,EAAEC,KAAK,QAAQ,wCAAuC;AACzE,SACEC,yBAAyB,QAEpB,mDAAkD;AACzD,SAASC,SAAS,QAAQ,gCAA4B;AAEtD;;;;;;;;;;CAUC,GAED,gEAAgE,GAChE,MAAMC,YAAY;AAElB,SAASC,KAAK,EAAEC,OAAO,EAAEC,IAAI,EAA4B;IACvD,IAAI,CAACD,SAAS,OAAO;IACrB,OAAOC,OAAOP,WAAWC,MAAMO,WAAW,EAAE;QAAEF;QAASC;QAAME,YAAYL;IAAU,KAAKJ,WAAWC,MAAMS,QAAQ,EAAE;QAAEJ;IAAQ;AAC/H;AAEA;;;;CAIC,GACD,OAAO,SAASK;IACdT,0BAA0B,WAAW;QAAEG;QAAMO,QAAQ,CAACC,UAAYR,KAAKQ;IAAS,GAAG;QAAEC,UAAUX;IAAU;AAC3G"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/model/data-record-routes.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 { buildRoute, Route } from '@aglyn/aglyn/app-utils/console-routes'\nimport {\n registerPluginRecordRoute,\n type PluginRecordRouteContext,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-routes'\nimport { BUNDLE_ID } from '../constants/bundle-common'\n\n/**\n * Where a dataset is read, published for every other surface (AGL-3616).\n *\n * An assistant job that made a menu or a team as a dataset opens it on the\n * Data page, which is this plugin's — so it asks the record-route registry\n * for `dataset` rather than spelling this plugin's nav slug, and gets `null`\n * (text instead of a link) where it is not loaded. A dataset belongs to the\n * organization and is shared with sites: a site's Data page lists the ones it\n * can see, and the organization's lists them all. Each dataset is a tab of\n * those pages at `/data/<datasetId>` (AGL-4047), so a record opens its tab.\n */\n\n/** The nav slug the shell resolves this plugin's site page by. */\nconst DATA_SLUG = 'data'\n\nfunction list({ orgSlug, host }: PluginRecordRouteContext): string | null {\n if (!orgSlug) return null\n return host ? buildRoute(Route.HOST_PLUGIN, { orgSlug, host, pluginSlug: DATA_SLUG }) : buildRoute(Route.ORG_DATA, { orgSlug })\n}\n\n/**\n * Called from the console registrar. The owner is named rather than read off\n * the loader's marker, so the route registers the same way under a spec that\n * calls the registrar directly.\n */\nexport function registerDataRecordRoutes(): void {\n registerPluginRecordRoute(\n 'dataset',\n {\n list,\n record: (context, id) => {\n const page = list(context)\n return page && id ? `${page}/${encodeURIComponent(id)}` : page\n },\n },\n { pluginId: BUNDLE_ID },\n )\n}\n"],"names":["buildRoute","Route","registerPluginRecordRoute","BUNDLE_ID","DATA_SLUG","list","orgSlug","host","HOST_PLUGIN","pluginSlug","ORG_DATA","registerDataRecordRoutes","record","context","id","page","encodeURIComponent","pluginId"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,EAAEC,KAAK,QAAQ,wCAAuC;AACzE,SACEC,yBAAyB,QAEpB,mDAAkD;AACzD,SAASC,SAAS,QAAQ,gCAA4B;AAEtD;;;;;;;;;;CAUC,GAED,gEAAgE,GAChE,MAAMC,YAAY;AAElB,SAASC,KAAK,EAAEC,OAAO,EAAEC,IAAI,EAA4B;IACvD,IAAI,CAACD,SAAS,OAAO;IACrB,OAAOC,OAAOP,WAAWC,MAAMO,WAAW,EAAE;QAAEF;QAASC;QAAME,YAAYL;IAAU,KAAKJ,WAAWC,MAAMS,QAAQ,EAAE;QAAEJ;IAAQ;AAC/H;AAEA;;;;CAIC,GACD,OAAO,SAASK;IACdT,0BACE,WACA;QACEG;QACAO,QAAQ,CAACC,SAASC;YAChB,MAAMC,OAAOV,KAAKQ;YAClB,OAAOE,QAAQD,KAAK,GAAGC,KAAK,CAAC,EAAEC,mBAAmBF,KAAK,GAAGC;QAC5D;IACF,GACA;QAAEE,UAAUd;IAAU;AAE1B"}
@@ -297,3 +297,25 @@ export declare function datasetDisplayName(dataset: {
297
297
  displayName?: unknown;
298
298
  name?: unknown;
299
299
  } | null | undefined): string;
300
+ /** One dataset as a picker offers it: what tells it apart from another of its name. */
301
+ export interface DatasetPickerEntry {
302
+ id: string;
303
+ /** The name the Data page shows. */
304
+ name: string;
305
+ /** Who it is shared with, as the console says it: `Bakery only`, `All sites`. */
306
+ sharing: string;
307
+ /** How many fields its model has. */
308
+ fields: number;
309
+ }
310
+ /**
311
+ * What each dataset is called in a picker (AGL-4047): its name alone, unless
312
+ * another in the same list has that name too. Then who it is shared with
313
+ * follows (`Services · Bakery only`), and where that still matches another,
314
+ * its field count (`Services · Bakery only · 5 fields`). Names are compared
315
+ * the way the stored search key is: trimmed, spaces collapsed, any case.
316
+ *
317
+ * A site start makes the same names on every site, shared with that site
318
+ * alone, so who it is shared with is what tells most of them apart. No imports,
319
+ * so the native apps can generate from it.
320
+ */
321
+ export declare function datasetPickerLabels(entries: readonly DatasetPickerEntry[]): Record<string, string>;
@@ -507,5 +507,39 @@ const textKey = datasetFilterTextKey;
507
507
  }
508
508
  return '';
509
509
  }
510
+ /**
511
+ * What each dataset is called in a picker (AGL-4047): its name alone, unless
512
+ * another in the same list has that name too. Then who it is shared with
513
+ * follows (`Services · Bakery only`), and where that still matches another,
514
+ * its field count (`Services · Bakery only · 5 fields`). Names are compared
515
+ * the way the stored search key is: trimmed, spaces collapsed, any case.
516
+ *
517
+ * A site start makes the same names on every site, shared with that site
518
+ * alone, so who it is shared with is what tells most of them apart. No imports,
519
+ * so the native apps can generate from it.
520
+ */ export function datasetPickerLabels(entries) {
521
+ const key = (text)=>text.trim().replace(/\s+/g, ' ').toLowerCase();
522
+ const count = (keys)=>{
523
+ var _counts_get;
524
+ const counts = new Map();
525
+ for (const each of keys)counts.set(each, ((_counts_get = counts.get(each)) != null ? _counts_get : 0) + 1);
526
+ return counts;
527
+ };
528
+ const names = count(entries.map((entry)=>key(entry.name)));
529
+ const shared = (entry)=>`${key(entry.name)}\u0000${key(entry.sharing)}`;
530
+ const sharings = count(entries.map(shared));
531
+ const labels = {};
532
+ for (const entry of entries){
533
+ var _names_get, _sharings_get;
534
+ if (((_names_get = names.get(key(entry.name))) != null ? _names_get : 0) < 2) {
535
+ labels[entry.id] = entry.name;
536
+ } else if (((_sharings_get = sharings.get(shared(entry))) != null ? _sharings_get : 0) < 2) {
537
+ labels[entry.id] = `${entry.name} · ${entry.sharing}`;
538
+ } else {
539
+ labels[entry.id] = `${entry.name} · ${entry.sharing} · ${entry.fields} ${entry.fields === 1 ? 'field' : 'fields'}`;
540
+ }
541
+ }
542
+ return labels;
543
+ }
510
544
 
511
545
  //# sourceMappingURL=dataset-model-core.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/model/dataset-model-core.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\n/**\n * The pure half of the dataset model (AGL-3668): the model and field types,\n * the v1 shim, the display and input forms of a stored value, and the\n * records table filter grammar (`filterKeys`/`filterValues` and the tokens a\n * clause or a search word asks for). No imports, so the native apps generate\n * from it (tools/scripts/mobile-pure-modules.json) and replay its answers.\n * `dataset-models.ts` re-exports all of it beside the validation and\n * coercion that reach the plugin registry.\n */\n\n/**\n * A human field entry from the quick creator: the stable id plus the\n * display name shown in table headers and bindings pickers (AGL-558).\n */\nexport interface DatasetFieldEntry {\n id: string\n name: string\n}\n\n/** Display fallback for raw ids: \"roast_preference\" → \"Roast preference\". */\nexport function humanizeDatasetFieldId(id: string): string {\n const words = id.replace(/_/g, ' ').trim()\n return words ? words.charAt(0).toUpperCase() + words.slice(1) : id\n}\n\n/** dod.ts `FT.Tag` vocabulary plus `reference` (AGL-180 builds on it). */\nexport type DatasetFieldType =\n | 'bool'\n | 'bytes'\n | 'timestamp'\n | 'float'\n | 'int32'\n | 'int64'\n | 'nil'\n | 'text'\n | 'coordinates'\n | 'map'\n | 'sorted'\n | 'reference'\n\nexport const DATASET_FIELD_TYPES: DatasetFieldType[] = [\n 'text',\n 'bool',\n 'int32',\n 'int64',\n 'float',\n 'timestamp',\n 'coordinates',\n 'map',\n 'sorted',\n 'bytes',\n 'nil',\n 'reference',\n]\n\n/**\n * The types a person picks for a new field in the Schema dialog; the rest\n * exist for compatibility and stay editable on a field that already has one.\n */\nexport const DATASET_AUTHORABLE_FIELD_TYPES: DatasetFieldType[] = [\n 'text',\n 'bool',\n 'int32',\n 'float',\n 'timestamp',\n 'coordinates',\n 'sorted',\n 'reference',\n]\n\n/** Display names, mirroring dod.ts `lbl`. */\nexport const DATASET_FIELD_TYPE_LABELS: Record<DatasetFieldType, string> = {\n text: 'Text',\n bool: 'Boolean',\n int32: 'Integer',\n int64: 'Big integer',\n float: 'Number',\n timestamp: 'Date & time',\n coordinates: 'Coordinates',\n map: 'Map',\n sorted: 'List',\n bytes: 'Bytes',\n nil: 'Null',\n reference: 'Reference',\n}\n\n/**\n * Plain-JSON validation vocabulary (the dod.ts `Eval` shape, extended\n * with min/max and options, serialized flat instead of enum-keyed).\n */\nexport interface DatasetFieldValidation {\n required?: boolean\n /** Source of a RegExp applied to text values. */\n regex?: string\n /** Numbers/timestamps: value bound. Text: length bound. */\n min?: number\n max?: number\n /** Enum: value must be one of these (text fields). */\n options?: string[]\n}\n\nexport interface DatasetFieldDefinition {\n /**\n * Human-facing display label only. The stable reference id is the KEY in\n * `DatasetModel.fields` (and `order`), NOT this name — bindings resolve\n * `{{item.<fieldId>}}` against that key. The default id is derived from\n * this name once at creation but is user-overridable (AGL-578); renaming\n * the label afterwards never changes the id.\n */\n name: string\n type: DatasetFieldType\n /**\n * Plugin-declared custom type riding this base type (AGL-434) — see\n * plugin-manager/custom-fields. Unknown names degrade to the base type.\n */\n customType?: string\n /**\n * A page-address field's source (AGL-3475): the field an EMPTY address\n * fills in from, once — see `fillRecordAddresses` in `record-pages`.\n * Meaningful only on a field of the page-address custom type.\n */\n slugFrom?: string\n description?: string\n required?: boolean\n /** Default applied by editors when creating documents; never coerced. */\n default?: unknown\n validation?: DatasetFieldValidation\n /**\n * Reference fields (AGL-180): target collection + display field id.\n * `multiple` stores a `sorted` array of FKeys (small-cardinality\n * many-to-many per the dod.ts guidance); `onDelete` is the referenced-\n * document delete policy (default `setNull` — never cascade in v2).\n */\n reference?: {\n datasetId: string\n displayFieldId?: string\n multiple?: boolean\n onDelete?: 'restrict' | 'setNull'\n }\n}\n\nexport interface DatasetModel {\n fields: Record<string, DatasetFieldDefinition>\n /** Field ids in display order. */\n order: string[]\n}\n\n/**\n * Migration shim (v1 → v2): datasets created before models carry flat\n * `fields: string[]` — derive a model where every column is an optional\n * text field whose id is the column name, so the editor and AGL-103\n * bindings keep working on unmigrated docs during rollout.\n */\nexport function deriveModelFromFields(fields: string[]): DatasetModel {\n const model: DatasetModel = { fields: {}, order: [] }\n for (const name of fields) {\n // Raw snake_case ids read as titles in table headers and pickers;\n // the id stays the stable key (AGL-558).\n model.fields[name] = { name: humanizeDatasetFieldId(name), type: 'text' }\n model.order.push(name)\n }\n return model\n}\n\n/**\n * Model from quick-creator entries (AGL-558): stable slug ids with the\n * human display names preserved — \"Roast preference\" → id\n * `roast_preference`, name \"Roast preference\".\n */\nexport function modelFromFieldEntries(\n entries: readonly DatasetFieldEntry[],\n): DatasetModel {\n const model: DatasetModel = { fields: {}, order: [] }\n for (const entry of entries) {\n model.fields[entry.id] = { name: entry.name, type: 'text' }\n model.order.push(entry.id)\n }\n return model\n}\n\n/** The dataset's model, deriving one from v1 `fields` when absent. */\nexport function effectiveDatasetModel(dataset: {\n model?: DatasetModel\n fields?: string[]\n}): DatasetModel {\n if (dataset.model?.fields && dataset.model.order?.length) {\n return dataset.model\n }\n return deriveModelFromFields(dataset.fields ?? [])\n}\n\nconst isFiniteNumber = (value: unknown): value is number =>\n typeof value === 'number' && Number.isFinite(value)\n\n\n\n/** Storage value → grid display string (AGL-179). */\nexport function formatDatasetValue(\n field: DatasetFieldDefinition,\n value: unknown,\n): string {\n if (value == null || value === '') return ''\n switch (field.type) {\n case 'bool':\n return value === true ? '✓' : value === false ? '—' : String(value)\n case 'timestamp':\n return isFiniteNumber(value)\n ? new Date(value).toISOString().slice(0, 16).replace('T', ' ')\n : String(value)\n case 'coordinates': {\n const coordinates = value as { latitude?: number; longitude?: number }\n return isFiniteNumber(coordinates?.latitude) &&\n isFiniteNumber(coordinates?.longitude)\n ? `${coordinates.latitude}, ${coordinates.longitude}`\n : String(value)\n }\n case 'sorted':\n return Array.isArray(value) ? value.join(', ') : String(value)\n case 'map':\n try {\n return JSON.stringify(value)\n } catch {\n return String(value)\n }\n default:\n return String(value)\n }\n}\n\n/**\n * Storage value → form-input string (AGL-179): the inverse of\n * `coerceDocumentValues` for populating type-appropriate inputs\n * (timestamps as `datetime-local` values, coordinates as \"lat, lon\").\n */\nexport function datasetValueToInput(\n field: DatasetFieldDefinition,\n value: unknown,\n): string {\n if (value == null) return ''\n if (field.type === 'timestamp' && isFiniteNumber(value)) {\n return new Date(value).toISOString().slice(0, 16)\n }\n if (field.type === 'bool') {\n return value === true ? 'true' : value === false ? 'false' : String(value)\n }\n if (field.type === 'coordinates' || field.type === 'sorted') {\n return formatDatasetValue(field, value)\n }\n if (field.type === 'map') return formatDatasetValue(field, value)\n return String(value)\n}\n\n/**\n * A dataset record's FILTER TOKENS: every word-level question the records\n * table can ask of a record, flattened into one array of strings Firestore\n * indexes on its own. Its twin, {@link datasetFilterValues}, holds the\n * equalities.\n *\n * ## Why these fields, and not the values\n *\n * A record's fields live under `values`, a user-defined, unbounded map that\n * the index configuration exempts from indexing — auto-indexing it can exceed\n * Firestore's per-document index-entry limit — so `where('values.<field>', …)`\n * is refused. A composite index per dataset would need an admin call per\n * dataset, runs into the project's composite-index cap, and is deleted by the\n * next `firestore:indexes` deploy of a file that does not list it.\n *\n * `filterKeys` and `filterValues` need none of that. Firestore's AUTOMATIC\n * single-field indexes serve `where('filterKeys', 'array-contains', token)`\n * and `where('filterValues.<field>', '==', value)`, and every automatic index\n * ends in the document name — so any number of those equalities and ONE\n * `array-contains`, under `orderBy(documentId())`, compose by index merging,\n * with no composite index and no index deploy, on any dataset of any project\n * (AGL-3321).\n *\n * ## The token grammar\n *\n * `f:<fieldId>=<value>` a field equals a value. Enum (a text field with\n * `validation.options`) values are kept exactly;\n * plain text is lower-cased, trimmed and clipped to\n * {@link DATASET_FILTER_VALUE_MAX} characters;\n * booleans are `true`/`false`; numbers are\n * `String(number)`; a `sorted` list contributes one\n * token per member.\n * `f:<fieldId>^<prefix>` a word of a plain text field starts with this.\n * `s:<prefix>` a word of ANY text value (enums and list members\n * included) starts with this — the quick search.\n *\n * Timestamps, references, maps, bytes, coordinates and nil fields carry no\n * field tokens: a timestamp is asked in ranges, which one token cannot serve,\n * and the rest are not asked about by value.\n *\n * The array is sorted, de-duplicated and capped at\n * {@link DATASET_FILTER_KEYS_MAX}. Past the cap, the `=` tokens are kept\n * first, then the per-field word prefixes, then the search prefixes, so a\n * very long record loses search reach before it loses exact matches.\n */\nexport const DATASET_FILTER_KEYS_MAX = 500\n\n/** Plain text values are clipped to this many characters in an `=` token. */\nexport const DATASET_FILTER_VALUE_MAX = 64\n/** Word prefixes run from 1 to this many characters. */\nexport const DATASET_FILTER_PREFIX_MAX = 12\n/** Only the first this-many words of a value contribute prefixes. */\nexport const DATASET_FILTER_WORDS_MAX = 40\n\n/** One clause of the records table's filter: `{ field, op, value }`. */\nexport interface DatasetFilterClause {\n field: string\n op: string\n value: string\n}\n\n/**\n * The words of a text value: split on anything that is not a letter or a\n * digit, lower-cased, at most {@link DATASET_FILTER_WORDS_MAX} of them.\n */\nexport function datasetFilterWords(text: string): string[] {\n return String(text)\n .toLowerCase()\n .split(/[^\\p{L}\\p{N}]+/u)\n .filter(Boolean)\n .slice(0, DATASET_FILTER_WORDS_MAX)\n}\n\n/** A word's prefixes, 1 to {@link DATASET_FILTER_PREFIX_MAX} characters. */\nfunction prefixes(word: string): string[] {\n const chars = Array.from(word).slice(0, DATASET_FILTER_PREFIX_MAX)\n return chars.map((_char, at) => chars.slice(0, at + 1).join(''))\n}\n\n/** A word clipped the way its stored prefixes are. */\nfunction clipWord(word: string): string {\n return Array.from(word).slice(0, DATASET_FILTER_PREFIX_MAX).join('')\n}\n\nconst isEnum = (field: DatasetFieldDefinition): boolean =>\n field.type === 'text' && (field.validation?.options?.length ?? 0) > 0\n\nconst isNumeric = (field: DatasetFieldDefinition): boolean =>\n field.type === 'int32' || field.type === 'int64' || field.type === 'float'\n\n/**\n * A stored value as text, or null. Numbers are accepted because a form or an\n * automation stores every value as text and an import may do the reverse.\n */\nfunction asText(value: unknown): string | null {\n if (typeof value === 'string') return value\n if (typeof value === 'number' && Number.isFinite(value)) return String(value)\n return null\n}\n\n/**\n * Plain text as its stored key — its `=` token's value and its\n * `filterValues` entry: lower-cased, trimmed, clipped to\n * {@link DATASET_FILTER_VALUE_MAX} characters. What the records table asks a\n * typed value to equal.\n */\nexport function datasetFilterTextKey(value: string): string {\n return Array.from(value.trim().toLowerCase())\n .slice(0, DATASET_FILTER_VALUE_MAX)\n .join('')\n}\nconst textKey = datasetFilterTextKey\n\n/** A stored number (or its text form) as its `=` token's value. */\nfunction numberKey(value: unknown): string | null {\n const number =\n typeof value === 'number'\n ? value\n : typeof value === 'string' && value.trim() !== ''\n ? Number(value)\n : Number.NaN\n return Number.isFinite(number) ? String(number) : null\n}\n\n/** A stored boolean (or its text form) as its `=` token's value. */\nfunction boolKey(value: unknown): string | null {\n if (typeof value === 'boolean') return String(value)\n if (value === 'true' || value === 'false') return value\n return null\n}\n\n/** Every field a model declares, in display order and then the rest. */\nfunction modelFieldIds(model: DatasetModel): string[] {\n return [...new Set([...(model.order ?? []), ...Object.keys(model.fields ?? {})])]\n}\n\n/** The tokens described in {@link DATASET_FILTER_KEYS_MAX}'s comment. */\nexport function datasetFilterKeys(\n model: DatasetModel,\n values: Record<string, unknown> | undefined,\n): string[] {\n const exact: string[] = []\n const fieldWords: string[] = []\n const search: string[] = []\n const searchable = (text: string) => {\n for (const word of datasetFilterWords(text)) {\n for (const prefix of prefixes(word)) search.push(`s:${prefix}`)\n }\n }\n for (const fieldId of modelFieldIds(model)) {\n const field = model.fields?.[fieldId]\n const stored = values?.[fieldId]\n if (!field || stored == null) continue\n if (field.type === 'text') {\n const text = asText(stored)\n if (text == null || !text.trim()) continue\n if (isEnum(field)) {\n exact.push(`f:${fieldId}=${text}`)\n } else {\n exact.push(`f:${fieldId}=${textKey(text)}`)\n for (const word of datasetFilterWords(text)) {\n for (const prefix of prefixes(word)) {\n fieldWords.push(`f:${fieldId}^${prefix}`)\n }\n }\n }\n searchable(text)\n } else if (field.type === 'bool') {\n const key = boolKey(stored)\n if (key) exact.push(`f:${fieldId}=${key}`)\n } else if (isNumeric(field)) {\n const key = numberKey(stored)\n if (key) exact.push(`f:${fieldId}=${key}`)\n } else if (field.type === 'sorted') {\n for (const member of Array.isArray(stored) ? stored : [stored]) {\n const text = asText(member)?.trim()\n if (!text) continue\n exact.push(`f:${fieldId}=${text}`)\n searchable(text)\n }\n }\n }\n const kept = [...new Set([...exact, ...fieldWords, ...search])].slice(\n 0,\n DATASET_FILTER_KEYS_MAX,\n )\n return kept.sort()\n}\n\n/** A record's `filterValues`: field id → the value an equality asks for. */\nexport type DatasetFilterValues = Record<string, string | number | boolean>\n\n/**\n * Field ids a query can name as `filterValues.<id>`. A path string splits on\n * `.`, and the SDKs refuse `~ * / [ ]` in one; the model editor allows only\n * letters, digits and underscores, but a v1 dataset's column names were\n * never checked. Backticks are refused too, as the escape a path would need.\n */\nconst FILTER_VALUE_ID = /^[^.~*/[\\]`]+$/\n\n/**\n * The query path of a field's `filterValues` entry, or null for a field id\n * no path can name — such a field is stamped no entry, and the records table\n * offers it no equality (its `contains`, served by `filterKeys`, stands).\n */\nexport function datasetFilterValuePath(fieldId: string): string | null {\n return FILTER_VALUE_ID.test(fieldId) && !/^__.*__$/.test(fieldId)\n ? `filterValues.${fieldId}`\n : null\n}\n\n/**\n * A dataset record's FILTER VALUES: `{ [fieldId]: value }`, one scalar per\n * field an equality can be asked of, so the records table puts every\n * equality on its query (AGL-3321).\n *\n * enum text (`validation.options`) the value exactly, as its `=` token;\n * plain text {@link datasetFilterTextKey};\n * bool a boolean;\n * int32 / int64 / float a number.\n *\n * A form or an automation stores every value as text, so `'19.50'` is the\n * number 19.5 and `'true'` the boolean, as in {@link datasetFilterKeys}.\n * Fields with no value, and timestamps, lists, references, maps, bytes,\n * coordinates and nil fields, carry no entry: a list is asked by member\n * (`f:<id>=<member>` in `filterKeys`), and the rest are not asked about by\n * value.\n *\n * ## What it costs\n *\n * Unlike `values`, this map is NOT exempt from indexing — that is its whole\n * point. Each entry is a scalar and costs two automatic index entries\n * (ascending, descending), so a record costs at most two per model field —\n * bounded by the model's field count (the `/v1` API caps a model at 100\n * fields), far inside Firestore's 40,000 entries per document, where\n * `values` was unbounded because a `map` or `sorted` value may hold anything.\n */\nexport function datasetFilterValues(\n model: DatasetModel,\n values: Record<string, unknown> | undefined,\n): DatasetFilterValues {\n const out: DatasetFilterValues = {}\n for (const fieldId of modelFieldIds(model)) {\n const field = model.fields?.[fieldId]\n const stored = values?.[fieldId]\n if (!field || stored == null || !datasetFilterValuePath(fieldId)) continue\n if (field.type === 'text') {\n const text = asText(stored)\n if (text == null || !text.trim()) continue\n out[fieldId] = isEnum(field) ? text : textKey(text)\n } else if (field.type === 'bool') {\n const key = boolKey(stored)\n if (key) out[fieldId] = key === 'true'\n } else if (isNumeric(field)) {\n const key = numberKey(stored)\n if (key) out[fieldId] = Number(key)\n }\n }\n return out\n}\n\n/**\n * The `filterKeys` token a word-level clause asks for, or null when it is\n * not one:\n *\n * - plain text `contains` → the `^` token of the value's FIRST word, so a\n * `contains` is a word-prefix match, not a mid-string one, and one word\n * of several is asked (the records table says so);\n * - list `contains` (and `equals`) → the member's `=` token;\n * - enum, boolean, number and plain text `equals` → the `=` token of the\n * value. The records table asks these of `filterValues` instead, which\n * composes with a `contains`; the token remains what the quick search and\n * older readers match.\n * - everything else — ranges, dates, `isEmpty`, `isAnyOf`, negations — null.\n *\n * `clause.field` is the field id. The operator names are the grid's: a\n * select's `equals`, a number's `=`, a boolean's `is`, a list's `contains`.\n */\nexport function datasetFilterToken(\n model: DatasetModel,\n clause: DatasetFilterClause,\n): string | null {\n const field = model.fields?.[clause.field]\n if (!field) return null\n const { op } = clause\n const value = String(clause.value ?? '')\n if (!value.trim()) return null\n const equals = op === 'equals' || op === '=' || op === 'is'\n if (field.type === 'text') {\n if (isEnum(field)) return equals ? `f:${clause.field}=${value}` : null\n if (equals) return `f:${clause.field}=${textKey(value)}`\n if (op === 'contains') {\n const [first] = datasetFilterWords(value)\n return first ? `f:${clause.field}^${clipWord(first)}` : null\n }\n return null\n }\n if (field.type === 'bool') {\n const key = boolKey(value.trim())\n return equals && key ? `f:${clause.field}=${key}` : null\n }\n if (isNumeric(field)) {\n const key = numberKey(value)\n return equals && key ? `f:${clause.field}=${key}` : null\n }\n if (field.type === 'sorted') {\n return equals || op === 'contains' ? `f:${clause.field}=${value.trim()}` : null\n }\n return null\n}\n\n/**\n * The quick-search token for one typed word, or null for a word with no\n * letters or digits. A word with punctuation inside it is asked by its first\n * run — split the search text with {@link datasetFilterWords} to ask for\n * every run.\n */\nexport function datasetSearchToken(word: string): string | null {\n const [first] = datasetFilterWords(word)\n return first ? `s:${clipWord(first)}` : null\n}\n\n/** Dataset field name: starts with a letter; letters/digits/underscores. */\nexport const DATASET_FIELD_PATTERN = /^[A-Za-z][A-Za-z0-9_]*$/\n\n\n/**\n * Stable field id from a human name: \"Roast preference\" → \"roast_preference\".\n * Mirrors DATASET_FIELD_PATTERN; returns '' when nothing salvageable.\n */\nexport function slugifyDatasetFieldId(name: string): string {\n const slug = name\n .trim()\n .toLowerCase()\n .replace(/[\\s-]+/g, '_')\n .replace(/[^a-z0-9_]/g, '')\n .replace(/^[0-9_]+/, '')\n .replace(/_+$/, '')\n return DATASET_FIELD_PATTERN.test(slug) ? slug : ''\n}\n\n/**\n * Default reference id for a new field (AGL-578): the `slugifyDatasetFieldId`\n * slug, suffixed (`_2`, `_3`, …) to stay unique within the dataset. `taken`\n * holds the ids already in use (compared case-insensitively). Returns '' when\n * the name yields nothing valid. The user can override the result.\n */\nexport function defaultDatasetFieldId(\n name: string,\n taken: ReadonlySet<string>,\n): string {\n const base = slugifyDatasetFieldId(name)\n if (!base) return ''\n const used = new Set([...taken].map((id) => id.toLowerCase()))\n let candidate = base\n let suffix = 2\n while (used.has(candidate.toLowerCase())) candidate = `${base}_${suffix++}`\n return candidate\n}\n\n/**\n * Validate a user-entered reference id (AGL-578): non-empty, matches\n * `DATASET_FIELD_PATTERN`, and unique within the dataset (`taken` = ids already\n * used, compared case-insensitively). Returns an error message, or null when\n * the id is usable.\n */\nexport function validateDatasetFieldId(\n id: string,\n taken: ReadonlySet<string>,\n): string | null {\n const trimmed = id.trim()\n if (!trimmed) return 'A reference ID is required'\n if (!DATASET_FIELD_PATTERN.test(trimmed))\n return 'Start with a letter; use only letters, numbers, and underscores'\n const used = new Set([...taken].map((existing) => existing.toLowerCase()))\n if (used.has(trimmed.toLowerCase()))\n return 'Another field already uses this reference ID'\n return null\n}\n\n\n/**\n * Parses a comma/newline separated list of HUMAN field names into\n * {id, name} entries — \"Roast preference\" keeps its pretty name and gets\n * the stable id `roast_preference` (AGL-558). Plain snake_case keys\n * still work and pick up a humanized display name. Duplicate ids and\n * unsalvageable entries are dropped rather than failing the set.\n */\nexport function parseDatasetFieldEntries(input: string): DatasetFieldEntry[] {\n const seen = new Set<string>()\n const entries: DatasetFieldEntry[] = []\n for (const raw of input.split(/[,\\n]/)) {\n const trimmed = raw.trim()\n if (!trimmed) continue\n const id = slugifyDatasetFieldId(trimmed)\n if (!id || seen.has(id)) continue\n seen.add(id)\n entries.push({\n id,\n name: DATASET_FIELD_PATTERN.test(trimmed)\n ? humanizeDatasetFieldId(trimmed)\n : trimmed,\n })\n }\n return entries\n}\n\n/**\n * The name a dataset is shown under: `displayName`, which is what every create\n * path writes (AGL-536), then the pre-migration `name`. Blank when the document\n * carries neither.\n */\nexport function datasetDisplayName(\n dataset: { displayName?: unknown; name?: unknown } | null | undefined,\n): string {\n for (const candidate of [dataset?.displayName, dataset?.name]) {\n if (typeof candidate === 'string' && candidate.trim()) {\n return candidate.trim()\n }\n }\n return ''\n}\n"],"names":["humanizeDatasetFieldId","id","words","replace","trim","charAt","toUpperCase","slice","DATASET_FIELD_TYPES","DATASET_AUTHORABLE_FIELD_TYPES","DATASET_FIELD_TYPE_LABELS","text","bool","int32","int64","float","timestamp","coordinates","map","sorted","bytes","nil","reference","deriveModelFromFields","fields","model","order","name","type","push","modelFromFieldEntries","entries","entry","effectiveDatasetModel","dataset","length","isFiniteNumber","value","Number","isFinite","formatDatasetValue","field","String","Date","toISOString","latitude","longitude","Array","isArray","join","JSON","stringify","datasetValueToInput","DATASET_FILTER_KEYS_MAX","DATASET_FILTER_VALUE_MAX","DATASET_FILTER_PREFIX_MAX","DATASET_FILTER_WORDS_MAX","datasetFilterWords","toLowerCase","split","filter","Boolean","prefixes","word","chars","from","_char","at","clipWord","isEnum","validation","options","isNumeric","asText","datasetFilterTextKey","textKey","numberKey","number","NaN","boolKey","modelFieldIds","Set","Object","keys","datasetFilterKeys","values","exact","fieldWords","search","searchable","prefix","fieldId","stored","key","member","kept","sort","FILTER_VALUE_ID","datasetFilterValuePath","test","datasetFilterValues","out","datasetFilterToken","clause","op","equals","first","datasetSearchToken","DATASET_FIELD_PATTERN","slugifyDatasetFieldId","slug","defaultDatasetFieldId","taken","base","used","candidate","suffix","has","validateDatasetFieldId","trimmed","existing","parseDatasetFieldEntries","input","seen","raw","add","datasetDisplayName","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;CAQC,GAED;;;CAGC,GAMD,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YAAYA,UAAU/G,IAAI,IAAI;YACrD,OAAO+G,UAAU/G,IAAI;QACvB;IACF;IACA,OAAO;AACT"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/model/dataset-model-core.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\n/**\n * The pure half of the dataset model (AGL-3668): the model and field types,\n * the v1 shim, the display and input forms of a stored value, and the\n * records table filter grammar (`filterKeys`/`filterValues` and the tokens a\n * clause or a search word asks for). No imports, so the native apps generate\n * from it (tools/scripts/mobile-pure-modules.json) and replay its answers.\n * `dataset-models.ts` re-exports all of it beside the validation and\n * coercion that reach the plugin registry.\n */\n\n/**\n * A human field entry from the quick creator: the stable id plus the\n * display name shown in table headers and bindings pickers (AGL-558).\n */\nexport interface DatasetFieldEntry {\n id: string\n name: string\n}\n\n/** Display fallback for raw ids: \"roast_preference\" → \"Roast preference\". */\nexport function humanizeDatasetFieldId(id: string): string {\n const words = id.replace(/_/g, ' ').trim()\n return words ? words.charAt(0).toUpperCase() + words.slice(1) : id\n}\n\n/** dod.ts `FT.Tag` vocabulary plus `reference` (AGL-180 builds on it). */\nexport type DatasetFieldType =\n | 'bool'\n | 'bytes'\n | 'timestamp'\n | 'float'\n | 'int32'\n | 'int64'\n | 'nil'\n | 'text'\n | 'coordinates'\n | 'map'\n | 'sorted'\n | 'reference'\n\nexport const DATASET_FIELD_TYPES: DatasetFieldType[] = [\n 'text',\n 'bool',\n 'int32',\n 'int64',\n 'float',\n 'timestamp',\n 'coordinates',\n 'map',\n 'sorted',\n 'bytes',\n 'nil',\n 'reference',\n]\n\n/**\n * The types a person picks for a new field in the Schema dialog; the rest\n * exist for compatibility and stay editable on a field that already has one.\n */\nexport const DATASET_AUTHORABLE_FIELD_TYPES: DatasetFieldType[] = [\n 'text',\n 'bool',\n 'int32',\n 'float',\n 'timestamp',\n 'coordinates',\n 'sorted',\n 'reference',\n]\n\n/** Display names, mirroring dod.ts `lbl`. */\nexport const DATASET_FIELD_TYPE_LABELS: Record<DatasetFieldType, string> = {\n text: 'Text',\n bool: 'Boolean',\n int32: 'Integer',\n int64: 'Big integer',\n float: 'Number',\n timestamp: 'Date & time',\n coordinates: 'Coordinates',\n map: 'Map',\n sorted: 'List',\n bytes: 'Bytes',\n nil: 'Null',\n reference: 'Reference',\n}\n\n/**\n * Plain-JSON validation vocabulary (the dod.ts `Eval` shape, extended\n * with min/max and options, serialized flat instead of enum-keyed).\n */\nexport interface DatasetFieldValidation {\n required?: boolean\n /** Source of a RegExp applied to text values. */\n regex?: string\n /** Numbers/timestamps: value bound. Text: length bound. */\n min?: number\n max?: number\n /** Enum: value must be one of these (text fields). */\n options?: string[]\n}\n\nexport interface DatasetFieldDefinition {\n /**\n * Human-facing display label only. The stable reference id is the KEY in\n * `DatasetModel.fields` (and `order`), NOT this name — bindings resolve\n * `{{item.<fieldId>}}` against that key. The default id is derived from\n * this name once at creation but is user-overridable (AGL-578); renaming\n * the label afterwards never changes the id.\n */\n name: string\n type: DatasetFieldType\n /**\n * Plugin-declared custom type riding this base type (AGL-434) — see\n * plugin-manager/custom-fields. Unknown names degrade to the base type.\n */\n customType?: string\n /**\n * A page-address field's source (AGL-3475): the field an EMPTY address\n * fills in from, once — see `fillRecordAddresses` in `record-pages`.\n * Meaningful only on a field of the page-address custom type.\n */\n slugFrom?: string\n description?: string\n required?: boolean\n /** Default applied by editors when creating documents; never coerced. */\n default?: unknown\n validation?: DatasetFieldValidation\n /**\n * Reference fields (AGL-180): target collection + display field id.\n * `multiple` stores a `sorted` array of FKeys (small-cardinality\n * many-to-many per the dod.ts guidance); `onDelete` is the referenced-\n * document delete policy (default `setNull` — never cascade in v2).\n */\n reference?: {\n datasetId: string\n displayFieldId?: string\n multiple?: boolean\n onDelete?: 'restrict' | 'setNull'\n }\n}\n\nexport interface DatasetModel {\n fields: Record<string, DatasetFieldDefinition>\n /** Field ids in display order. */\n order: string[]\n}\n\n/**\n * Migration shim (v1 → v2): datasets created before models carry flat\n * `fields: string[]` — derive a model where every column is an optional\n * text field whose id is the column name, so the editor and AGL-103\n * bindings keep working on unmigrated docs during rollout.\n */\nexport function deriveModelFromFields(fields: string[]): DatasetModel {\n const model: DatasetModel = { fields: {}, order: [] }\n for (const name of fields) {\n // Raw snake_case ids read as titles in table headers and pickers;\n // the id stays the stable key (AGL-558).\n model.fields[name] = { name: humanizeDatasetFieldId(name), type: 'text' }\n model.order.push(name)\n }\n return model\n}\n\n/**\n * Model from quick-creator entries (AGL-558): stable slug ids with the\n * human display names preserved — \"Roast preference\" → id\n * `roast_preference`, name \"Roast preference\".\n */\nexport function modelFromFieldEntries(\n entries: readonly DatasetFieldEntry[],\n): DatasetModel {\n const model: DatasetModel = { fields: {}, order: [] }\n for (const entry of entries) {\n model.fields[entry.id] = { name: entry.name, type: 'text' }\n model.order.push(entry.id)\n }\n return model\n}\n\n/** The dataset's model, deriving one from v1 `fields` when absent. */\nexport function effectiveDatasetModel(dataset: {\n model?: DatasetModel\n fields?: string[]\n}): DatasetModel {\n if (dataset.model?.fields && dataset.model.order?.length) {\n return dataset.model\n }\n return deriveModelFromFields(dataset.fields ?? [])\n}\n\nconst isFiniteNumber = (value: unknown): value is number =>\n typeof value === 'number' && Number.isFinite(value)\n\n\n\n/** Storage value → grid display string (AGL-179). */\nexport function formatDatasetValue(\n field: DatasetFieldDefinition,\n value: unknown,\n): string {\n if (value == null || value === '') return ''\n switch (field.type) {\n case 'bool':\n return value === true ? '✓' : value === false ? '—' : String(value)\n case 'timestamp':\n return isFiniteNumber(value)\n ? new Date(value).toISOString().slice(0, 16).replace('T', ' ')\n : String(value)\n case 'coordinates': {\n const coordinates = value as { latitude?: number; longitude?: number }\n return isFiniteNumber(coordinates?.latitude) &&\n isFiniteNumber(coordinates?.longitude)\n ? `${coordinates.latitude}, ${coordinates.longitude}`\n : String(value)\n }\n case 'sorted':\n return Array.isArray(value) ? value.join(', ') : String(value)\n case 'map':\n try {\n return JSON.stringify(value)\n } catch {\n return String(value)\n }\n default:\n return String(value)\n }\n}\n\n/**\n * Storage value → form-input string (AGL-179): the inverse of\n * `coerceDocumentValues` for populating type-appropriate inputs\n * (timestamps as `datetime-local` values, coordinates as \"lat, lon\").\n */\nexport function datasetValueToInput(\n field: DatasetFieldDefinition,\n value: unknown,\n): string {\n if (value == null) return ''\n if (field.type === 'timestamp' && isFiniteNumber(value)) {\n return new Date(value).toISOString().slice(0, 16)\n }\n if (field.type === 'bool') {\n return value === true ? 'true' : value === false ? 'false' : String(value)\n }\n if (field.type === 'coordinates' || field.type === 'sorted') {\n return formatDatasetValue(field, value)\n }\n if (field.type === 'map') return formatDatasetValue(field, value)\n return String(value)\n}\n\n/**\n * A dataset record's FILTER TOKENS: every word-level question the records\n * table can ask of a record, flattened into one array of strings Firestore\n * indexes on its own. Its twin, {@link datasetFilterValues}, holds the\n * equalities.\n *\n * ## Why these fields, and not the values\n *\n * A record's fields live under `values`, a user-defined, unbounded map that\n * the index configuration exempts from indexing — auto-indexing it can exceed\n * Firestore's per-document index-entry limit — so `where('values.<field>', …)`\n * is refused. A composite index per dataset would need an admin call per\n * dataset, runs into the project's composite-index cap, and is deleted by the\n * next `firestore:indexes` deploy of a file that does not list it.\n *\n * `filterKeys` and `filterValues` need none of that. Firestore's AUTOMATIC\n * single-field indexes serve `where('filterKeys', 'array-contains', token)`\n * and `where('filterValues.<field>', '==', value)`, and every automatic index\n * ends in the document name — so any number of those equalities and ONE\n * `array-contains`, under `orderBy(documentId())`, compose by index merging,\n * with no composite index and no index deploy, on any dataset of any project\n * (AGL-3321).\n *\n * ## The token grammar\n *\n * `f:<fieldId>=<value>` a field equals a value. Enum (a text field with\n * `validation.options`) values are kept exactly;\n * plain text is lower-cased, trimmed and clipped to\n * {@link DATASET_FILTER_VALUE_MAX} characters;\n * booleans are `true`/`false`; numbers are\n * `String(number)`; a `sorted` list contributes one\n * token per member.\n * `f:<fieldId>^<prefix>` a word of a plain text field starts with this.\n * `s:<prefix>` a word of ANY text value (enums and list members\n * included) starts with this — the quick search.\n *\n * Timestamps, references, maps, bytes, coordinates and nil fields carry no\n * field tokens: a timestamp is asked in ranges, which one token cannot serve,\n * and the rest are not asked about by value.\n *\n * The array is sorted, de-duplicated and capped at\n * {@link DATASET_FILTER_KEYS_MAX}. Past the cap, the `=` tokens are kept\n * first, then the per-field word prefixes, then the search prefixes, so a\n * very long record loses search reach before it loses exact matches.\n */\nexport const DATASET_FILTER_KEYS_MAX = 500\n\n/** Plain text values are clipped to this many characters in an `=` token. */\nexport const DATASET_FILTER_VALUE_MAX = 64\n/** Word prefixes run from 1 to this many characters. */\nexport const DATASET_FILTER_PREFIX_MAX = 12\n/** Only the first this-many words of a value contribute prefixes. */\nexport const DATASET_FILTER_WORDS_MAX = 40\n\n/** One clause of the records table's filter: `{ field, op, value }`. */\nexport interface DatasetFilterClause {\n field: string\n op: string\n value: string\n}\n\n/**\n * The words of a text value: split on anything that is not a letter or a\n * digit, lower-cased, at most {@link DATASET_FILTER_WORDS_MAX} of them.\n */\nexport function datasetFilterWords(text: string): string[] {\n return String(text)\n .toLowerCase()\n .split(/[^\\p{L}\\p{N}]+/u)\n .filter(Boolean)\n .slice(0, DATASET_FILTER_WORDS_MAX)\n}\n\n/** A word's prefixes, 1 to {@link DATASET_FILTER_PREFIX_MAX} characters. */\nfunction prefixes(word: string): string[] {\n const chars = Array.from(word).slice(0, DATASET_FILTER_PREFIX_MAX)\n return chars.map((_char, at) => chars.slice(0, at + 1).join(''))\n}\n\n/** A word clipped the way its stored prefixes are. */\nfunction clipWord(word: string): string {\n return Array.from(word).slice(0, DATASET_FILTER_PREFIX_MAX).join('')\n}\n\nconst isEnum = (field: DatasetFieldDefinition): boolean =>\n field.type === 'text' && (field.validation?.options?.length ?? 0) > 0\n\nconst isNumeric = (field: DatasetFieldDefinition): boolean =>\n field.type === 'int32' || field.type === 'int64' || field.type === 'float'\n\n/**\n * A stored value as text, or null. Numbers are accepted because a form or an\n * automation stores every value as text and an import may do the reverse.\n */\nfunction asText(value: unknown): string | null {\n if (typeof value === 'string') return value\n if (typeof value === 'number' && Number.isFinite(value)) return String(value)\n return null\n}\n\n/**\n * Plain text as its stored key — its `=` token's value and its\n * `filterValues` entry: lower-cased, trimmed, clipped to\n * {@link DATASET_FILTER_VALUE_MAX} characters. What the records table asks a\n * typed value to equal.\n */\nexport function datasetFilterTextKey(value: string): string {\n return Array.from(value.trim().toLowerCase())\n .slice(0, DATASET_FILTER_VALUE_MAX)\n .join('')\n}\nconst textKey = datasetFilterTextKey\n\n/** A stored number (or its text form) as its `=` token's value. */\nfunction numberKey(value: unknown): string | null {\n const number =\n typeof value === 'number'\n ? value\n : typeof value === 'string' && value.trim() !== ''\n ? Number(value)\n : Number.NaN\n return Number.isFinite(number) ? String(number) : null\n}\n\n/** A stored boolean (or its text form) as its `=` token's value. */\nfunction boolKey(value: unknown): string | null {\n if (typeof value === 'boolean') return String(value)\n if (value === 'true' || value === 'false') return value\n return null\n}\n\n/** Every field a model declares, in display order and then the rest. */\nfunction modelFieldIds(model: DatasetModel): string[] {\n return [...new Set([...(model.order ?? []), ...Object.keys(model.fields ?? {})])]\n}\n\n/** The tokens described in {@link DATASET_FILTER_KEYS_MAX}'s comment. */\nexport function datasetFilterKeys(\n model: DatasetModel,\n values: Record<string, unknown> | undefined,\n): string[] {\n const exact: string[] = []\n const fieldWords: string[] = []\n const search: string[] = []\n const searchable = (text: string) => {\n for (const word of datasetFilterWords(text)) {\n for (const prefix of prefixes(word)) search.push(`s:${prefix}`)\n }\n }\n for (const fieldId of modelFieldIds(model)) {\n const field = model.fields?.[fieldId]\n const stored = values?.[fieldId]\n if (!field || stored == null) continue\n if (field.type === 'text') {\n const text = asText(stored)\n if (text == null || !text.trim()) continue\n if (isEnum(field)) {\n exact.push(`f:${fieldId}=${text}`)\n } else {\n exact.push(`f:${fieldId}=${textKey(text)}`)\n for (const word of datasetFilterWords(text)) {\n for (const prefix of prefixes(word)) {\n fieldWords.push(`f:${fieldId}^${prefix}`)\n }\n }\n }\n searchable(text)\n } else if (field.type === 'bool') {\n const key = boolKey(stored)\n if (key) exact.push(`f:${fieldId}=${key}`)\n } else if (isNumeric(field)) {\n const key = numberKey(stored)\n if (key) exact.push(`f:${fieldId}=${key}`)\n } else if (field.type === 'sorted') {\n for (const member of Array.isArray(stored) ? stored : [stored]) {\n const text = asText(member)?.trim()\n if (!text) continue\n exact.push(`f:${fieldId}=${text}`)\n searchable(text)\n }\n }\n }\n const kept = [...new Set([...exact, ...fieldWords, ...search])].slice(\n 0,\n DATASET_FILTER_KEYS_MAX,\n )\n return kept.sort()\n}\n\n/** A record's `filterValues`: field id → the value an equality asks for. */\nexport type DatasetFilterValues = Record<string, string | number | boolean>\n\n/**\n * Field ids a query can name as `filterValues.<id>`. A path string splits on\n * `.`, and the SDKs refuse `~ * / [ ]` in one; the model editor allows only\n * letters, digits and underscores, but a v1 dataset's column names were\n * never checked. Backticks are refused too, as the escape a path would need.\n */\nconst FILTER_VALUE_ID = /^[^.~*/[\\]`]+$/\n\n/**\n * The query path of a field's `filterValues` entry, or null for a field id\n * no path can name — such a field is stamped no entry, and the records table\n * offers it no equality (its `contains`, served by `filterKeys`, stands).\n */\nexport function datasetFilterValuePath(fieldId: string): string | null {\n return FILTER_VALUE_ID.test(fieldId) && !/^__.*__$/.test(fieldId)\n ? `filterValues.${fieldId}`\n : null\n}\n\n/**\n * A dataset record's FILTER VALUES: `{ [fieldId]: value }`, one scalar per\n * field an equality can be asked of, so the records table puts every\n * equality on its query (AGL-3321).\n *\n * enum text (`validation.options`) the value exactly, as its `=` token;\n * plain text {@link datasetFilterTextKey};\n * bool a boolean;\n * int32 / int64 / float a number.\n *\n * A form or an automation stores every value as text, so `'19.50'` is the\n * number 19.5 and `'true'` the boolean, as in {@link datasetFilterKeys}.\n * Fields with no value, and timestamps, lists, references, maps, bytes,\n * coordinates and nil fields, carry no entry: a list is asked by member\n * (`f:<id>=<member>` in `filterKeys`), and the rest are not asked about by\n * value.\n *\n * ## What it costs\n *\n * Unlike `values`, this map is NOT exempt from indexing — that is its whole\n * point. Each entry is a scalar and costs two automatic index entries\n * (ascending, descending), so a record costs at most two per model field —\n * bounded by the model's field count (the `/v1` API caps a model at 100\n * fields), far inside Firestore's 40,000 entries per document, where\n * `values` was unbounded because a `map` or `sorted` value may hold anything.\n */\nexport function datasetFilterValues(\n model: DatasetModel,\n values: Record<string, unknown> | undefined,\n): DatasetFilterValues {\n const out: DatasetFilterValues = {}\n for (const fieldId of modelFieldIds(model)) {\n const field = model.fields?.[fieldId]\n const stored = values?.[fieldId]\n if (!field || stored == null || !datasetFilterValuePath(fieldId)) continue\n if (field.type === 'text') {\n const text = asText(stored)\n if (text == null || !text.trim()) continue\n out[fieldId] = isEnum(field) ? text : textKey(text)\n } else if (field.type === 'bool') {\n const key = boolKey(stored)\n if (key) out[fieldId] = key === 'true'\n } else if (isNumeric(field)) {\n const key = numberKey(stored)\n if (key) out[fieldId] = Number(key)\n }\n }\n return out\n}\n\n/**\n * The `filterKeys` token a word-level clause asks for, or null when it is\n * not one:\n *\n * - plain text `contains` → the `^` token of the value's FIRST word, so a\n * `contains` is a word-prefix match, not a mid-string one, and one word\n * of several is asked (the records table says so);\n * - list `contains` (and `equals`) → the member's `=` token;\n * - enum, boolean, number and plain text `equals` → the `=` token of the\n * value. The records table asks these of `filterValues` instead, which\n * composes with a `contains`; the token remains what the quick search and\n * older readers match.\n * - everything else — ranges, dates, `isEmpty`, `isAnyOf`, negations — null.\n *\n * `clause.field` is the field id. The operator names are the grid's: a\n * select's `equals`, a number's `=`, a boolean's `is`, a list's `contains`.\n */\nexport function datasetFilterToken(\n model: DatasetModel,\n clause: DatasetFilterClause,\n): string | null {\n const field = model.fields?.[clause.field]\n if (!field) return null\n const { op } = clause\n const value = String(clause.value ?? '')\n if (!value.trim()) return null\n const equals = op === 'equals' || op === '=' || op === 'is'\n if (field.type === 'text') {\n if (isEnum(field)) return equals ? `f:${clause.field}=${value}` : null\n if (equals) return `f:${clause.field}=${textKey(value)}`\n if (op === 'contains') {\n const [first] = datasetFilterWords(value)\n return first ? `f:${clause.field}^${clipWord(first)}` : null\n }\n return null\n }\n if (field.type === 'bool') {\n const key = boolKey(value.trim())\n return equals && key ? `f:${clause.field}=${key}` : null\n }\n if (isNumeric(field)) {\n const key = numberKey(value)\n return equals && key ? `f:${clause.field}=${key}` : null\n }\n if (field.type === 'sorted') {\n return equals || op === 'contains' ? `f:${clause.field}=${value.trim()}` : null\n }\n return null\n}\n\n/**\n * The quick-search token for one typed word, or null for a word with no\n * letters or digits. A word with punctuation inside it is asked by its first\n * run — split the search text with {@link datasetFilterWords} to ask for\n * every run.\n */\nexport function datasetSearchToken(word: string): string | null {\n const [first] = datasetFilterWords(word)\n return first ? `s:${clipWord(first)}` : null\n}\n\n/** Dataset field name: starts with a letter; letters/digits/underscores. */\nexport const DATASET_FIELD_PATTERN = /^[A-Za-z][A-Za-z0-9_]*$/\n\n\n/**\n * Stable field id from a human name: \"Roast preference\" → \"roast_preference\".\n * Mirrors DATASET_FIELD_PATTERN; returns '' when nothing salvageable.\n */\nexport function slugifyDatasetFieldId(name: string): string {\n const slug = name\n .trim()\n .toLowerCase()\n .replace(/[\\s-]+/g, '_')\n .replace(/[^a-z0-9_]/g, '')\n .replace(/^[0-9_]+/, '')\n .replace(/_+$/, '')\n return DATASET_FIELD_PATTERN.test(slug) ? slug : ''\n}\n\n/**\n * Default reference id for a new field (AGL-578): the `slugifyDatasetFieldId`\n * slug, suffixed (`_2`, `_3`, …) to stay unique within the dataset. `taken`\n * holds the ids already in use (compared case-insensitively). Returns '' when\n * the name yields nothing valid. The user can override the result.\n */\nexport function defaultDatasetFieldId(\n name: string,\n taken: ReadonlySet<string>,\n): string {\n const base = slugifyDatasetFieldId(name)\n if (!base) return ''\n const used = new Set([...taken].map((id) => id.toLowerCase()))\n let candidate = base\n let suffix = 2\n while (used.has(candidate.toLowerCase())) candidate = `${base}_${suffix++}`\n return candidate\n}\n\n/**\n * Validate a user-entered reference id (AGL-578): non-empty, matches\n * `DATASET_FIELD_PATTERN`, and unique within the dataset (`taken` = ids already\n * used, compared case-insensitively). Returns an error message, or null when\n * the id is usable.\n */\nexport function validateDatasetFieldId(\n id: string,\n taken: ReadonlySet<string>,\n): string | null {\n const trimmed = id.trim()\n if (!trimmed) return 'A reference ID is required'\n if (!DATASET_FIELD_PATTERN.test(trimmed))\n return 'Start with a letter; use only letters, numbers, and underscores'\n const used = new Set([...taken].map((existing) => existing.toLowerCase()))\n if (used.has(trimmed.toLowerCase()))\n return 'Another field already uses this reference ID'\n return null\n}\n\n\n/**\n * Parses a comma/newline separated list of HUMAN field names into\n * {id, name} entries — \"Roast preference\" keeps its pretty name and gets\n * the stable id `roast_preference` (AGL-558). Plain snake_case keys\n * still work and pick up a humanized display name. Duplicate ids and\n * unsalvageable entries are dropped rather than failing the set.\n */\nexport function parseDatasetFieldEntries(input: string): DatasetFieldEntry[] {\n const seen = new Set<string>()\n const entries: DatasetFieldEntry[] = []\n for (const raw of input.split(/[,\\n]/)) {\n const trimmed = raw.trim()\n if (!trimmed) continue\n const id = slugifyDatasetFieldId(trimmed)\n if (!id || seen.has(id)) continue\n seen.add(id)\n entries.push({\n id,\n name: DATASET_FIELD_PATTERN.test(trimmed)\n ? humanizeDatasetFieldId(trimmed)\n : trimmed,\n })\n }\n return entries\n}\n\n/**\n * The name a dataset is shown under: `displayName`, which is what every create\n * path writes (AGL-536), then the pre-migration `name`. Blank when the document\n * carries neither.\n */\nexport function datasetDisplayName(\n dataset: { displayName?: unknown; name?: unknown } | null | undefined,\n): string {\n for (const candidate of [dataset?.displayName, dataset?.name]) {\n if (typeof candidate === 'string' && candidate.trim()) {\n return candidate.trim()\n }\n }\n return ''\n}\n\n/** One dataset as a picker offers it: what tells it apart from another of its name. */\nexport interface DatasetPickerEntry {\n id: string\n /** The name the Data page shows. */\n name: string\n /** Who it is shared with, as the console says it: `Bakery only`, `All sites`. */\n sharing: string\n /** How many fields its model has. */\n fields: number\n}\n\n/**\n * What each dataset is called in a picker (AGL-4047): its name alone, unless\n * another in the same list has that name too. Then who it is shared with\n * follows (`Services · Bakery only`), and where that still matches another,\n * its field count (`Services · Bakery only · 5 fields`). Names are compared\n * the way the stored search key is: trimmed, spaces collapsed, any case.\n *\n * A site start makes the same names on every site, shared with that site\n * alone, so who it is shared with is what tells most of them apart. No imports,\n * so the native apps can generate from it.\n */\nexport function datasetPickerLabels(entries: readonly DatasetPickerEntry[]): Record<string, string> {\n const key = (text: string) => text.trim().replace(/\\s+/g, ' ').toLowerCase()\n const count = (keys: readonly string[]) => {\n const counts = new Map<string, number>()\n for (const each of keys) counts.set(each, (counts.get(each) ?? 0) + 1)\n return counts\n }\n const names = count(entries.map((entry) => key(entry.name)))\n const shared = (entry: DatasetPickerEntry) => `${key(entry.name)}\\u0000${key(entry.sharing)}`\n const sharings = count(entries.map(shared))\n const labels: Record<string, string> = {}\n for (const entry of entries) {\n if ((names.get(key(entry.name)) ?? 0) < 2) {\n labels[entry.id] = entry.name\n } else if ((sharings.get(shared(entry)) ?? 0) < 2) {\n labels[entry.id] = `${entry.name} · ${entry.sharing}`\n } else {\n labels[entry.id] = `${entry.name} · ${entry.sharing} · ${entry.fields} ${entry.fields === 1 ? 'field' : 'fields'}`\n }\n }\n return labels\n}\n"],"names":["humanizeDatasetFieldId","id","words","replace","trim","charAt","toUpperCase","slice","DATASET_FIELD_TYPES","DATASET_AUTHORABLE_FIELD_TYPES","DATASET_FIELD_TYPE_LABELS","text","bool","int32","int64","float","timestamp","coordinates","map","sorted","bytes","nil","reference","deriveModelFromFields","fields","model","order","name","type","push","modelFromFieldEntries","entries","entry","effectiveDatasetModel","dataset","length","isFiniteNumber","value","Number","isFinite","formatDatasetValue","field","String","Date","toISOString","latitude","longitude","Array","isArray","join","JSON","stringify","datasetValueToInput","DATASET_FILTER_KEYS_MAX","DATASET_FILTER_VALUE_MAX","DATASET_FILTER_PREFIX_MAX","DATASET_FILTER_WORDS_MAX","datasetFilterWords","toLowerCase","split","filter","Boolean","prefixes","word","chars","from","_char","at","clipWord","isEnum","validation","options","isNumeric","asText","datasetFilterTextKey","textKey","numberKey","number","NaN","boolKey","modelFieldIds","Set","Object","keys","datasetFilterKeys","values","exact","fieldWords","search","searchable","prefix","fieldId","stored","key","member","kept","sort","FILTER_VALUE_ID","datasetFilterValuePath","test","datasetFilterValues","out","datasetFilterToken","clause","op","equals","first","datasetSearchToken","DATASET_FIELD_PATTERN","slugifyDatasetFieldId","slug","defaultDatasetFieldId","taken","base","used","candidate","suffix","has","validateDatasetFieldId","trimmed","existing","parseDatasetFieldEntries","input","seen","raw","add","datasetDisplayName","displayName","datasetPickerLabels","count","counts","Map","each","set","get","names","shared","sharing","sharings","labels"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;CAQC,GAED;;;CAGC,GAMD,2EAA2E,GAC3E,OAAO,SAASA,uBAAuBC,EAAU;IAC/C,MAAMC,QAAQD,GAAGE,OAAO,CAAC,MAAM,KAAKC,IAAI;IACxC,OAAOF,QAAQA,MAAMG,MAAM,CAAC,GAAGC,WAAW,KAAKJ,MAAMK,KAAK,CAAC,KAAKN;AAClE;AAiBA,OAAO,MAAMO,sBAA0C;IACrD;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAA;AAED;;;CAGC,GACD,OAAO,MAAMC,iCAAqD;IAChE;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAA;AAED,2CAA2C,GAC3C,OAAO,MAAMC,4BAA8D;IACzEC,MAAM;IACNC,MAAM;IACNC,OAAO;IAC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