@aglyn/plugins-data 1.0.0-beta.285 → 1.0.0-beta.288

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/model/datasets.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Datasets (AGL-102): tabular data at `orgs/{orgId}/datasets/{id}` with a\n * `records` subcollection, edited in the console Data card and consumed by\n * repeatable components (AGL-103) via `{{item.field}}` bindings.\n */\n\nimport type { ScopeToken } from '@aglyn/aglyn/foundation/definitions/platform.types'\nimport {\n coerceDocumentValues,\n type DatasetModel,\n effectiveDatasetModel,\n validateDocument,\n} from './dataset-models'\nimport { fillRecordAddresses } from '../record-pages/record-pages'\nimport { DATASET_FIELD_PATTERN } from './dataset-model-core'\n\n// The field-id and naming helpers are pure and live with the model's pure\n// half (AGL-3668), which the native apps generate from.\nexport {\n DATASET_FIELD_PATTERN,\n datasetDisplayName,\n defaultDatasetFieldId,\n parseDatasetFieldEntries,\n slugifyDatasetFieldId,\n validateDatasetFieldId,\n} from './dataset-model-core'\n\nexport interface HostDataset {\n $id?: string\n displayName?: string\n /** Column names, in display order (v1; superseded by `model`). */\n fields?: string[]\n /** Typed model (AGL-177); when absent, derive from `fields`. */\n model?: import('./dataset-models').DatasetModel\n /** dod.ts Schema.Name shape (AGL-178). */\n names?: { singular?: string; plural?: string }\n /**\n * Which sites may see this dataset (AGL-1037). Absent = org-wide, until\n * the AGL-1040 backfill stamps it. See `app-utils/scope-tokens`.\n */\n visibleTo?: ScopeToken[]\n}\n\nexport interface HostDatasetRecord {\n $id?: string\n /**\n * Field → value, in storage form per the field's type (see\n * `dataset-models`). Rows written by a form or an automation step before\n * AGL-2773 hold every value as text; readers accept both.\n */\n values?: Record<string, unknown>\n /** Row position in the editor and in repeated output. */\n order?: number\n}\n\n/**\n * Parses a comma/newline separated field list into valid unique names;\n * invalid entries are dropped rather than failing the whole set.\n */\nexport function parseDatasetFields(input: string): string[] {\n const seen = new Set<string>()\n const fields: string[] = []\n for (const raw of input.split(/[,\\n]/)) {\n const name = raw.trim()\n if (!DATASET_FIELD_PATTERN.test(name)) continue\n const key = name.toLowerCase()\n if (seen.has(key)) continue\n seen.add(key)\n fields.push(name)\n }\n return fields\n}\n\n/** Record values restricted to the dataset's declared fields. */\nexport function sanitizeRecordValues(\n fields: string[],\n input: Record<string, unknown> | null | undefined,\n): Record<string, string> {\n const values: Record<string, string> = {}\n for (const field of fields) {\n const value = input?.[field]\n if (value == null) continue\n values[field] = String(value)\n }\n return values\n}\n\n/**\n * The submitted values a dataset write would store, picked by field id and\n * left as they arrived (AGL-556). With a `fieldMap` (submitted key → stable\n * model fieldId), mapped values land under the mapped fieldId — so renamed\n * schema fields keep receiving data — and entries whose fieldId isn't in the\n * model are dropped. Submitted keys without a mapping (and calls without a\n * map) fall back to the legacy name-intersection against the model's field\n * ids, matching `sanitizeRecordValues`.\n */\nexport function pickDatasetRecordInput(\n dataset: { model?: DatasetModel; fields?: string[] },\n input: Record<string, unknown> | null | undefined,\n fieldMap?: Record<string, string> | null,\n): Record<string, unknown> {\n const model = effectiveDatasetModel(dataset)\n const map = fieldMap ?? {}\n const values: Record<string, unknown> = {}\n for (const fieldId of model.order) {\n if (!model.fields[fieldId]) continue\n // A submitted key with an explicit mapping never doubles as a\n // name-match — the mapping decides where it lands.\n if (fieldId in map) continue\n const value = input?.[fieldId]\n if (value == null) continue\n values[fieldId] = value\n }\n for (const [submittedKey, fieldId] of Object.entries(map)) {\n if (typeof fieldId !== 'string' || !model.fields[fieldId]) continue\n const value = input?.[submittedKey]\n if (value == null) continue\n values[fieldId] = value\n }\n return values\n}\n\n/** A dataset record write, checked against the dataset's model. */\nexport interface DatasetRecordWrite {\n /**\n * The model fields this write supplied a value for, before coercion. Empty\n * means nothing submitted matched a field of the dataset.\n */\n matched: string[]\n /**\n * The values to store, in storage form (see `dataset-models`): numbers,\n * booleans, epoch millis and so on per the field's type. For a merge, the\n * existing values with this write's laid over them.\n */\n values: Record<string, unknown>\n /** fieldId → the reason it was refused. Empty when the write may land. */\n errors: Record<string, string>\n}\n\n/**\n * A text field takes what an event payload carries as a number or a boolean\n * as the text it reads as, which is what these writes always stored.\n */\nfunction asTextInput(\n model: DatasetModel,\n picked: Record<string, unknown>,\n): Record<string, unknown> {\n const values: Record<string, unknown> = {}\n for (const [fieldId, value] of Object.entries(picked)) {\n const type = model.fields[fieldId]?.type\n values[fieldId] =\n (type === 'text' || type === 'reference') &&\n (typeof value === 'number' || typeof value === 'boolean')\n ? String(value)\n : value\n }\n return values\n}\n\n/**\n * A record write from a form submission or an automation step, coerced and\n * validated against the dataset's model (AGL-2773, option B).\n *\n * These writes used to store `String(value)` for every field and check\n * nothing, so a form could put `abc` in a number column and skip a required\n * one. They now run the same `coerceDocumentValues` + `validateDocument` pair\n * the console and `/v1` do: a value is stored in its field's type, and a\n * record with any refused field is not written at all. The caller decides\n * what a refusal costs — a form keeps the Inbox submission, a run records a\n * failed step.\n *\n * `existing` makes it a merge (update-or-append's update leg): this write's\n * values are laid over the stored ones, and only the fields THIS write\n * supplied are held to the model. A stored row written as text before this\n * change keeps its text values and is not refused for them — the reads have\n * always rendered them, and a merge that touched `email` must not fail over a\n * legacy `price` of `\"12\"` it never sent.\n *\n * Custom field types validate only once registered: call\n * `ensureDeclaredCustomFieldTypes(model)` before this on a server path.\n */\nexport function prepareDatasetRecordWrite(\n dataset: { model?: DatasetModel; fields?: string[] },\n input: Record<string, unknown> | null | undefined,\n options: {\n fieldMap?: Record<string, string> | null\n existing?: Record<string, unknown> | null\n } = {},\n): DatasetRecordWrite {\n const model = effectiveDatasetModel(dataset)\n const picked = pickDatasetRecordInput(dataset, input, options.fieldMap)\n const matched = Object.keys(picked)\n const coerced = coerceDocumentValues(model, asTextInput(model, picked))\n if (!options.existing) {\n // A page address fills in from its source on the record's first write\n // and is normalized on every one (AGL-3475).\n const values = fillRecordAddresses(model, coerced)\n return {\n matched,\n values,\n errors: validateDocument(model, values),\n }\n }\n const values = fillRecordAddresses(model, { ...options.existing, ...coerced })\n const errors: Record<string, string> = {}\n for (const [fieldId, error] of Object.entries(\n validateDocument(model, values),\n )) {\n if (fieldId in coerced) errors[fieldId] = error\n }\n return { matched, values, errors }\n}\n\n/**\n * A refused write's errors as one line, in the model's field order:\n * `Stars must be a whole number; Email is required`.\n */\nexport function describeDatasetRecordErrors(\n errors: Record<string, string>,\n): string {\n return Object.values(errors).join('; ')\n}\n\n/** Records sorted by their editor order (then id for stability). */\nexport function sortDatasetRecords<T extends HostDatasetRecord>(\n records: T[],\n): T[] {\n return [...records].sort(\n (a, b) =>\n (a.order ?? Number.MAX_SAFE_INTEGER) -\n (b.order ?? Number.MAX_SAFE_INTEGER) ||\n String(a.$id ?? '').localeCompare(String(b.$id ?? '')),\n )\n}\n"],"names":["coerceDocumentValues","effectiveDatasetModel","validateDocument","fillRecordAddresses","DATASET_FIELD_PATTERN","datasetDisplayName","defaultDatasetFieldId","parseDatasetFieldEntries","slugifyDatasetFieldId","validateDatasetFieldId","parseDatasetFields","input","seen","Set","fields","raw","split","name","trim","test","key","toLowerCase","has","add","push","sanitizeRecordValues","values","field","value","String","pickDatasetRecordInput","dataset","fieldMap","model","map","fieldId","order","submittedKey","Object","entries","asTextInput","picked","type","prepareDatasetRecordWrite","options","matched","keys","coerced","existing","errors","error","describeDatasetRecordErrors","join","sortDatasetRecords","records","sort","a","b","Number","MAX_SAFE_INTEGER","$id","localeCompare"],"mappings":"AAA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tE,6CAA6C;QAC7C,MAAMtB,SAASvB,oBAAoB8B,OAAOc;QAC1C,OAAO;YACLF;YACAnB;YACAuB,QAAQ/C,iBAAiB+B,OAAOP;QAClC;IACF;IACA,MAAMA,SAASvB,oBAAoB8B,OAAO,aAAKW,QAAQI,QAAQ,EAAKD;IACpE,MAAME,SAAiC,CAAC;IACxC,KAAK,MAAM,CAACd,SAASe,MAAM,IAAIZ,OAAOC,OAAO,CAC3CrC,iBAAiB+B,OAAOP,SACvB;QACD,IAAIS,WAAWY,SAASE,MAAM,CAACd,QAAQ,GAAGe;IAC5C;IACA,OAAO;QAAEL;QAASnB;QAAQuB;IAAO;AACnC;AAEA;;;CAGC,GACD,OAAO,SAASE,4BACdF,MAA8B;IAE9B,OAAOX,OAAOZ,MAAM,CAACuB,QAAQG,IAAI,CAAC;AACpC;AAEA,kEAAkE,GAClE,OAAO,SAASC,mBACdC,OAAY;IAEZ,OAAO;WAAIA;KAAQ,CAACC,IAAI,CACtB,CAACC,GAAGC;YACDD,UACEC,UACID,QAAkCC;eAFzC,EAACD,WAAAA,EAAEpB,KAAK,YAAPoB,WAAWE,OAAOC,gBAAgB,MAChCF,WAAAA,EAAErB,KAAK,YAAPqB,WAAWC,OAAOC,gBAAgB,KACrC9B,QAAO2B,SAAAA,EAAEI,GAAG,YAALJ,SAAS,IAAIK,aAAa,CAAChC,QAAO4B,SAAAA,EAAEG,GAAG,YAALH,SAAS;;AAExD"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/model/datasets.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Datasets (AGL-102): tabular data at `orgs/{orgId}/datasets/{id}` with a\n * `records` subcollection, edited in the console Data card and consumed by\n * repeatable components (AGL-103) via `{{item.field}}` bindings.\n */\n\nimport type { ScopeToken } from '@aglyn/aglyn/foundation/definitions/platform.types'\nimport {\n coerceDocumentValues,\n type DatasetModel,\n effectiveDatasetModel,\n validateDocument,\n} from './dataset-models'\nimport { fillRecordAddresses } from '../record-pages/record-pages'\nimport { DATASET_FIELD_PATTERN } from './dataset-model-core'\n\n// The field-id and naming helpers are pure and live with the model's pure\n// half (AGL-3668), which the native apps generate from.\nexport {\n DATASET_FIELD_PATTERN,\n datasetDisplayName,\n defaultDatasetFieldId,\n parseDatasetFieldEntries,\n slugifyDatasetFieldId,\n validateDatasetFieldId,\n} from './dataset-model-core'\n\nexport interface HostDataset {\n $id?: string\n displayName?: string\n /** Column names, in display order (v1; superseded by `model`). */\n fields?: string[]\n /** Typed model (AGL-177); when absent, derive from `fields`. */\n model?: import('./dataset-models').DatasetModel\n /** dod.ts Schema.Name shape (AGL-178). */\n names?: { singular?: string; plural?: string }\n /**\n * Which sites may see this dataset (AGL-1037). Absent = org-wide, until\n * the AGL-1040 backfill stamps it. See `app-utils/scope-tokens`.\n */\n visibleTo?: ScopeToken[]\n}\n\nexport interface HostDatasetRecord {\n $id?: string\n /**\n * Field → value, in storage form per the field's type (see\n * `dataset-models`). Rows written by a form or an automation step before\n * AGL-2773 hold every value as text; readers accept both.\n */\n values?: Record<string, unknown>\n /** Row position in the editor and in repeated output. */\n order?: number\n /**\n * A sample a site start seeded for the owner to replace (AGL-4065): the\n * brief gave no entries for the list. Beside the values, so no page reads\n * it; saving the record in Data makes it the owner's.\n */\n sample?: boolean\n}\n\n/** What Data says beside a sample record (AGL-4065). */\nexport const DATASET_SAMPLE_RECORD_NOTE =\n 'A sample row made because your site’s brief gave none. Replace it with your own: saving your changes makes it yours.'\n\n/** Whether a record is a sample to replace (AGL-4065). */\nexport function isSampleDatasetRecord(record: Pick<HostDatasetRecord, 'sample'> | null | undefined): boolean {\n return record?.sample === true\n}\n\n/**\n * Parses a comma/newline separated field list into valid unique names;\n * invalid entries are dropped rather than failing the whole set.\n */\nexport function parseDatasetFields(input: string): string[] {\n const seen = new Set<string>()\n const fields: string[] = []\n for (const raw of input.split(/[,\\n]/)) {\n const name = raw.trim()\n if (!DATASET_FIELD_PATTERN.test(name)) continue\n const key = name.toLowerCase()\n if (seen.has(key)) continue\n seen.add(key)\n fields.push(name)\n }\n return fields\n}\n\n/** Record values restricted to the dataset's declared fields. */\nexport function sanitizeRecordValues(\n fields: string[],\n input: Record<string, unknown> | null | undefined,\n): Record<string, string> {\n const values: Record<string, string> = {}\n for (const field of fields) {\n const value = input?.[field]\n if (value == null) continue\n values[field] = String(value)\n }\n return values\n}\n\n/**\n * The submitted values a dataset write would store, picked by field id and\n * left as they arrived (AGL-556). With a `fieldMap` (submitted key → stable\n * model fieldId), mapped values land under the mapped fieldId — so renamed\n * schema fields keep receiving data — and entries whose fieldId isn't in the\n * model are dropped. Submitted keys without a mapping (and calls without a\n * map) fall back to the legacy name-intersection against the model's field\n * ids, matching `sanitizeRecordValues`.\n */\nexport function pickDatasetRecordInput(\n dataset: { model?: DatasetModel; fields?: string[] },\n input: Record<string, unknown> | null | undefined,\n fieldMap?: Record<string, string> | null,\n): Record<string, unknown> {\n const model = effectiveDatasetModel(dataset)\n const map = fieldMap ?? {}\n const values: Record<string, unknown> = {}\n for (const fieldId of model.order) {\n if (!model.fields[fieldId]) continue\n // A submitted key with an explicit mapping never doubles as a\n // name-match — the mapping decides where it lands.\n if (fieldId in map) continue\n const value = input?.[fieldId]\n if (value == null) continue\n values[fieldId] = value\n }\n for (const [submittedKey, fieldId] of Object.entries(map)) {\n if (typeof fieldId !== 'string' || !model.fields[fieldId]) continue\n const value = input?.[submittedKey]\n if (value == null) continue\n values[fieldId] = value\n }\n return values\n}\n\n/** A dataset record write, checked against the dataset's model. */\nexport interface DatasetRecordWrite {\n /**\n * The model fields this write supplied a value for, before coercion. Empty\n * means nothing submitted matched a field of the dataset.\n */\n matched: string[]\n /**\n * The values to store, in storage form (see `dataset-models`): numbers,\n * booleans, epoch millis and so on per the field's type. For a merge, the\n * existing values with this write's laid over them.\n */\n values: Record<string, unknown>\n /** fieldId → the reason it was refused. Empty when the write may land. */\n errors: Record<string, string>\n}\n\n/**\n * A text field takes what an event payload carries as a number or a boolean\n * as the text it reads as, which is what these writes always stored.\n */\nfunction asTextInput(\n model: DatasetModel,\n picked: Record<string, unknown>,\n): Record<string, unknown> {\n const values: Record<string, unknown> = {}\n for (const [fieldId, value] of Object.entries(picked)) {\n const type = model.fields[fieldId]?.type\n values[fieldId] =\n (type === 'text' || type === 'reference') &&\n (typeof value === 'number' || typeof value === 'boolean')\n ? String(value)\n : value\n }\n return values\n}\n\n/**\n * A record write from a form submission or an automation step, coerced and\n * validated against the dataset's model (AGL-2773, option B).\n *\n * These writes used to store `String(value)` for every field and check\n * nothing, so a form could put `abc` in a number column and skip a required\n * one. They now run the same `coerceDocumentValues` + `validateDocument` pair\n * the console and `/v1` do: a value is stored in its field's type, and a\n * record with any refused field is not written at all. The caller decides\n * what a refusal costs — a form keeps the Inbox submission, a run records a\n * failed step.\n *\n * `existing` makes it a merge (update-or-append's update leg): this write's\n * values are laid over the stored ones, and only the fields THIS write\n * supplied are held to the model. A stored row written as text before this\n * change keeps its text values and is not refused for them — the reads have\n * always rendered them, and a merge that touched `email` must not fail over a\n * legacy `price` of `\"12\"` it never sent.\n *\n * Custom field types validate only once registered: call\n * `ensureDeclaredCustomFieldTypes(model)` before this on a server path.\n */\nexport function prepareDatasetRecordWrite(\n dataset: { model?: DatasetModel; fields?: string[] },\n input: Record<string, unknown> | null | undefined,\n options: {\n fieldMap?: Record<string, string> | null\n existing?: Record<string, unknown> | null\n } = {},\n): DatasetRecordWrite {\n const model = effectiveDatasetModel(dataset)\n const picked = pickDatasetRecordInput(dataset, input, options.fieldMap)\n const matched = Object.keys(picked)\n const coerced = coerceDocumentValues(model, asTextInput(model, picked))\n if (!options.existing) {\n // A page address fills in from its source on the record's first write\n // and is normalized on every one (AGL-3475).\n const values = fillRecordAddresses(model, coerced)\n return {\n matched,\n values,\n errors: validateDocument(model, values),\n }\n }\n const values = fillRecordAddresses(model, { ...options.existing, ...coerced })\n const errors: Record<string, string> = {}\n for (const [fieldId, error] of Object.entries(\n validateDocument(model, values),\n )) {\n if (fieldId in coerced) errors[fieldId] = error\n }\n return { matched, values, errors }\n}\n\n/**\n * A refused write's errors as one line, in the model's field order:\n * `Stars must be a whole number; Email is required`.\n */\nexport function describeDatasetRecordErrors(\n errors: Record<string, string>,\n): string {\n return Object.values(errors).join('; ')\n}\n\n/** Records sorted by their editor order (then id for stability). */\nexport function sortDatasetRecords<T extends HostDatasetRecord>(\n records: T[],\n): T[] {\n return [...records].sort(\n (a, b) =>\n (a.order ?? Number.MAX_SAFE_INTEGER) -\n (b.order ?? Number.MAX_SAFE_INTEGER) ||\n String(a.$id ?? '').localeCompare(String(b.$id ?? '')),\n )\n}\n"],"names":["coerceDocumentValues","effectiveDatasetModel","validateDocument","fillRecordAddresses","DATASET_FIELD_PATTERN","datasetDisplayName","defaultDatasetFieldId","parseDatasetFieldEntries","slugifyDatasetFieldId","validateDatasetFieldId","DATASET_SAMPLE_RECORD_NOTE","isSampleDatasetRecord","record","sample","parseDatasetFields","input","seen","Set","fields","raw","split","name","trim","test","key","toLowerCase","has","add","push","sanitizeRecordValues","values","field","value","String","pickDatasetRecordInput","dataset","fieldMap","model","map","fieldId","order","submittedKey","Object","entries","asTextInput","picked","type","prepareDatasetRecordWrite","options","matched","keys","coerced","existing","errors","error","describeDatasetRecordErrors","join","sortDatasetRecords","records","sort","a","b","Number","MAX_SAFE_INTEGER","$id","localeCompare"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;CAIC;AAGD,SACEA,oBAAoB,EAEpBC,qBAAqB,EACrBC,gBAAgB,QACX,sBAAk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D,IAAI,CAACG,QAAQI,QAAQ,EAAE;QACrB,sEAAsE;QACtE,6CAA6C;QAC7C,MAAMtB,SAAS3B,oBAAoBkC,OAAOc;QAC1C,OAAO;YACLF;YACAnB;YACAuB,QAAQnD,iBAAiBmC,OAAOP;QAClC;IACF;IACA,MAAMA,SAAS3B,oBAAoBkC,OAAO,aAAKW,QAAQI,QAAQ,EAAKD;IACpE,MAAME,SAAiC,CAAC;IACxC,KAAK,MAAM,CAACd,SAASe,MAAM,IAAIZ,OAAOC,OAAO,CAC3CzC,iBAAiBmC,OAAOP,SACvB;QACD,IAAIS,WAAWY,SAASE,MAAM,CAACd,QAAQ,GAAGe;IAC5C;IACA,OAAO;QAAEL;QAASnB;QAAQuB;IAAO;AACnC;AAEA;;;CAGC,GACD,OAAO,SAASE,4BACdF,MAA8B;IAE9B,OAAOX,OAAOZ,MAAM,CAACuB,QAAQG,IAAI,CAAC;AACpC;AAEA,kEAAkE,GAClE,OAAO,SAASC,mBACdC,OAAY;IAEZ,OAAO;WAAIA;KAAQ,CAACC,IAAI,CACtB,CAACC,GAAGC;YACDD,UACEC,UACID,QAAkCC;eAFzC,EAACD,WAAAA,EAAEpB,KAAK,YAAPoB,WAAWE,OAAOC,gBAAgB,MAChCF,WAAAA,EAAErB,KAAK,YAAPqB,WAAWC,OAAOC,gBAAgB,KACrC9B,QAAO2B,SAAAA,EAAEI,GAAG,YAALJ,SAAS,IAAIK,aAAa,CAAChC,QAAO4B,SAAAA,EAAEG,GAAG,YAALH,SAAS;;AAExD"}
@@ -15,7 +15,8 @@ import { _ as _object_without_properties_loose } from "@swc/helpers/_/_object_wi
15
15
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
16
  * See the License for the specific language governing permissions and
17
17
  * limitations under the License.
18
- */ import { SCREEN_KIND_TEMPLATE, checkEntitlement, hostCollectionKind, hostRoleCanPublish, pluginRequestFromWeb } from "@aglyn/aglyn/server";
18
+ */ import { holdsSiteKey, siteKeyRefusal } from "@aglyn/aglyn/app-utils/host-permissions";
19
+ import { SCREEN_KIND_TEMPLATE, checkEntitlement, hostCollectionKind, pluginRequestFromWeb } from "@aglyn/aglyn/server";
19
20
  import { listPluginSitemapSections } from "@aglyn/aglyn/plugin-manager/plugin-sitemap-sections";
20
21
  import { dropPluginSiteCache } from "@aglyn/aglyn/plugin-manager/plugin-site-cache";
21
22
  import { emailUnverifiedResponse, firebaseAdmin, isImpersonationSession, isServerReleaseFlagOnForOrg, lockdownRefusal } from "@aglyn/tenant-data-admin";
@@ -103,7 +104,6 @@ const text = (value)=>typeof value === 'string' ? value.trim() : '';
103
104
  }
104
105
  try {
105
106
  var _bindings_find;
106
- var _host_memberRoles;
107
107
  const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken);
108
108
  if (!decoded.email_verified && !isImpersonationSession(decoded)) {
109
109
  return emailUnverifiedResponse();
@@ -120,9 +120,9 @@ const text = (value)=>typeof value === 'string' ? value.trim() : '';
120
120
  });
121
121
  }
122
122
  const host = hostSnapshot.data();
123
- if (!staff && !hostRoleCanPublish((_host_memberRoles = host['memberRoles']) == null ? void 0 : _host_memberRoles[decoded.uid])) {
123
+ if (!staff && !holdsSiteKey(host, decoded.uid, 'site.publish')) {
124
124
  return Response.json({
125
- error: 'Record templates are published routes — this needs the publisher role on the site'
125
+ error: siteKeyRefusal('site.publish')
126
126
  }, {
127
127
  status: 403
128
128
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/record-pages/record-pages-route.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 SCREEN_KIND_TEMPLATE,\n checkEntitlement,\n hostCollectionKind,\n hostRoleCanPublish,\n pluginRequestFromWeb,\n type PluginWebApiHandler,\n} from '@aglyn/aglyn/server'\nimport { listPluginSitemapSections } from '@aglyn/aglyn/plugin-manager/plugin-sitemap-sections'\nimport { dropPluginSiteCache } from '@aglyn/aglyn/plugin-manager/plugin-site-cache'\nimport {\n emailUnverifiedResponse,\n firebaseAdmin,\n isImpersonationSession,\n isServerReleaseFlagOnForOrg,\n lockdownRefusal,\n} from '@aglyn/tenant-data-admin'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { Timestamp } from 'firebase-admin/firestore'\nimport { announceDatasetRecords } from '../server/announce-dataset-records'\nimport { readRecordPageBindingsUncached, recordPagePathsOf } from './record-page-live-paths.server'\nimport { readSiteDataset } from './record-page-read.server'\nimport {\n type DatasetRecordPageBinding,\n RECORD_PAGES_MAX_PER_SITE,\n isRecordAddressField,\n normalizeRecordPageBase,\n recordPageBaseRefusal,\n} from './record-pages'\n\n/** The optional fields a binding may name, each one a field of the dataset. */\nconst OPTIONAL_FIELDS = [\n 'titleField',\n 'seoTitleField',\n 'seoDescriptionField',\n 'seoImageField',\n] as const\n\nconst text = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\n\n/**\n * The first segment of every route another plugin serves pages under on every\n * site, read off the sections they declare for the sitemap — `/products/{slug}`\n * is `products` — so a base cannot shadow a store without this plugin naming\n * one.\n */\nfunction pluginRouteSegments(): string[] {\n return listPluginSitemapSections()\n .map((section) => section.path.split('/').filter(Boolean)[0] ?? '')\n .filter(Boolean)\n}\n\n/**\n * A site's record templates (AGL-3475), saved and removed — the only writer\n * of `hosts/{hostId}/recordPages`, which the rules close to every client.\n *\n * A binding decides which page serves `/{base}/…` for every record of a\n * dataset, so it is a routing decision and needs the PUBLISH role on the\n * site, as a redirect does. Saving checks what a published page would\n * otherwise get wrong with nothing red:\n *\n * - the page is a template (`kind: 'template'`), so its own address cannot\n * serve raw `{{item.*}}` — the console converts it first, through the\n * platform's own route, which is the only writer of `kind`;\n * - the dataset is shared with this site, and its address field is a page\n * address;\n * - the plan includes datasets (Starter and up), and the data store is\n * released for the organization;\n * - the base is free: no reserved address, no other plugin's route, no\n * content collection's slug, no other template's base; and the dataset has\n * no other template on this site, so `{{item.url}}` has one answer.\n *\n * Every save and removal drops the record pages it changes — the ones it\n * stops serving and the ones it starts to, which a crawler may have been told\n * were missing.\n */\nexport const recordPagesHandler: PluginWebApiHandler = async (request) => {\n const { method, body, headers: rawHeaders } = await pluginRequestFromWeb(request)\n const headers = rawHeaders as Partial<Record<string, string>>\n if (method !== 'POST') {\n return Response.json({ error: 'Method not allowed' }, { status: 405 })\n }\n const authorization = headers.authorization ?? ''\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return Response.json({ error: 'Unauthenticated' }, { status: 401 })\n\n const action = text(body?.action)\n const hostId = text(body?.hostId)\n const screenId = text(body?.screenId)\n if (action !== 'save' && action !== 'remove') {\n return Response.json({ error: 'Unknown action' }, { status: 400 })\n }\n if (!hostId || !screenId || hostId.includes('/') || screenId.includes('/')) {\n return Response.json({ error: 'Missing hostId or screenId' }, { status: 400 })\n }\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n if (!decoded.email_verified && !isImpersonationSession(decoded)) {\n return emailUnverifiedResponse()\n }\n const staff = decoded['staff'] === true\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return Response.json({ error: 'Unknown site' }, { status: 404 })\n }\n const host = hostSnapshot.data() as Record<string, unknown>\n if (!staff && !hostRoleCanPublish((host['memberRoles'] as Record<string, unknown>)?.[decoded.uid])) {\n return Response.json(\n { error: 'Record templates are published routes — this needs the publisher role on the site' },\n { status: 403 },\n )\n }\n const orgId = text(host['orgId'])\n const org = orgId\n ? ((await firestore.collection('orgs').doc(orgId).get()).data() as Record<string, unknown> | undefined)\n : undefined\n const locked = await lockdownRefusal({\n request,\n staff,\n uid: decoded.uid,\n org: org as never,\n host: host as never,\n })\n if (locked) return locked\n if (!staff && orgId && !(await isServerReleaseFlagOnForOrg('release_data_store', orgId))) {\n return Response.json({ error: 'Not available' }, { status: 404 })\n }\n\n // Spelled out, not DATASET_RECORD_PAGES_COLLECTION: the media-corpus guard\n // (host-content-media-coverage.spec) finds host collections by literal.\n const bindingsRef = hostRef.collection('recordPages')\n const bindings = await readRecordPageBindingsUncached(hostId)\n const current = bindings.find((binding) => binding.screenId === screenId) ?? null\n\n if (action === 'remove') {\n if (!current) return Response.json({ ok: true, removed: false }, { status: 200 })\n const stale = await recordPagePathsOf(hostId, current).catch(() => ({ paths: [] as string[] }))\n await bindingsRef.doc(screenId).delete()\n await dropRecordPages(hostId, current, stale.paths, 'record template removed')\n return Response.json({ ok: true, removed: true }, { status: 200 })\n }\n\n if (!checkEntitlement(org as never, 'dataStore')) {\n return Response.json(\n { error: 'Record pages need a Starter plan or higher' },\n { status: 403 },\n )\n }\n const screen = (await hostRef.collection('screens').doc(screenId).get()).data() as\n | Record<string, unknown>\n | undefined\n if (!screen || screen['deletedAt']) {\n return Response.json({ error: 'Unknown page' }, { status: 404 })\n }\n if (screen['kind'] !== SCREEN_KIND_TEMPLATE) {\n return Response.json(\n { error: 'Make this page a template first', code: 'not-template' },\n { status: 409 },\n )\n }\n\n const datasetId = text(body?.datasetId)\n const dataset = await readSiteDataset(hostId, datasetId)\n if (!dataset) {\n return Response.json({ error: 'That dataset is not shared with this site' }, { status: 404 })\n }\n const slugField = text(body?.slugField)\n if (!isRecordAddressField(dataset.model.fields[slugField])) {\n return Response.json(\n { error: 'Pick a Page address field of the dataset for the record pages’ addresses' },\n { status: 400 },\n )\n }\n const optional: Partial<DatasetRecordPageBinding> = {}\n for (const key of OPTIONAL_FIELDS) {\n const fieldId = text(body?.[key])\n if (!fieldId) continue\n if (!dataset.model.fields[fieldId]) {\n return Response.json({ error: `The dataset has no field \"${fieldId}\"` }, { status: 400 })\n }\n optional[key] = fieldId\n }\n\n const others = bindings.filter((binding) => binding.screenId !== screenId)\n if (!current && bindings.length >= RECORD_PAGES_MAX_PER_SITE) {\n return Response.json(\n { error: `A site can have up to ${RECORD_PAGES_MAX_PER_SITE} record templates` },\n { status: 403 },\n )\n }\n if (others.some((binding) => binding.datasetId === dataset.id)) {\n return Response.json(\n { error: `${dataset.name || 'This dataset'} already has a record template on this site` },\n { status: 409 },\n )\n }\n const collections = await hostRef.collection('collections').select('slug', 'kind').get()\n const refusal = recordPageBaseRefusal(body?.base, {\n collectionSlugs: collections.docs\n .filter((doc) => hostCollectionKind(doc.data() as never) === 'content')\n .map((doc) => text(doc.get('slug')))\n .filter(Boolean),\n pluginRouteSegments: pluginRouteSegments(),\n otherBases: others.map((binding) => binding.base),\n })\n if (refusal) return Response.json({ error: refusal }, { status: 400 })\n const base = normalizeRecordPageBase(body?.base) as string\n\n const binding: DatasetRecordPageBinding = {\n screenId,\n datasetId: dataset.id,\n base,\n slugField,\n ...optional,\n }\n const { screenId: _id, ...stored } = binding\n await bindingsRef.doc(screenId).set({\n ...stored,\n updatedAt: Timestamp.now(),\n updatedBy: decoded.uid,\n })\n const [before, after] = await Promise.all([\n current ? recordPagePathsOf(hostId, current).catch(() => ({ paths: [] as string[] })) : { paths: [] },\n recordPagePathsOf(hostId, binding).catch(() => ({ paths: [] as string[] })),\n ])\n await dropRecordPages(\n hostId,\n binding,\n [...after.paths, ...(current ? [`/${current.base}`] : []), ...before.paths],\n 'record template saved',\n )\n return Response.json({ ok: true, binding }, { status: 200 })\n } catch (error) {\n if (isRefusedIdToken(error)) {\n return Response.json({ error: 'Unauthenticated' }, { status: 401 })\n }\n console.error(error)\n return Response.json({ error: 'Record template operation failed' }, { status: 500 })\n }\n}\n\n/**\n * Drops what a binding change makes stale. Best effort: the binding is\n * written, and the host's data tag is underneath.\n *\n * - The record pages it starts or stops serving, and its base, which a site\n * often publishes as the listing — and which is always one path, so the\n * drop always reaches the tenant and busts the data tag the bindings are\n * cached under. A drop naming no path is skipped outright.\n * - Every page that repeats over the dataset, on every site sharing it: its\n * rows have gained or lost their `{{item.url}}`.\n */\nasync function dropRecordPages(\n hostId: string,\n binding: DatasetRecordPageBinding,\n paths: string[],\n reason: string,\n): Promise<void> {\n try {\n await dropPluginSiteCache({\n hostIds: [hostId],\n paths: { [hostId]: [...new Set([`/${binding.base}`, ...paths])] },\n reason,\n })\n } catch (error) {\n console.error('[record-pages] cache drop failed', hostId, error)\n }\n try {\n const dataset = await readSiteDataset(hostId, binding.datasetId)\n const orgId = dataset?.ref.parent.parent?.id\n if (dataset && orgId) {\n await announceDatasetRecords({\n firestore: firebaseAdmin.app().firestore(),\n orgId,\n datasetId: dataset.id,\n })\n }\n } catch (error) {\n console.error('[record-pages] dataset announce failed', hostId, error)\n }\n}\n"],"names":["SCREEN_KIND_TEMPLATE","checkEntitlement","hostCollectionKind","hostRoleCanPublish","pluginRequestFromWeb","listPluginSitemapSections","dropPluginSiteCache","emailUnverifiedResponse","firebaseAdmin","isImpersonationSession","isServerReleaseFlagOnForOrg","lockdownRefusal","isRefusedIdToken","Timestamp","announceDatasetRecords","readRecordPageBindingsUncached","recordPagePathsOf","readSiteDataset","RECORD_PAGES_MAX_PER_SITE","isRecordAddressField","normalizeRecordPageBase","recordPageBaseRefusal","OPTIONAL_FIELDS","text","value","trim","pluginRouteSegments","map","section","path","split","filter","Boolean","recordPagesHandler","request","headers","method","body","rawHeaders","Response","json","error","status","authorization","idToken","startsWith","slice","length","undefined","action","hostId","screenId","includes","bindings","host","decoded","app","auth","verifyIdToken","email_verified","staff","firestore","hostRef","collection","doc","hostSnapshot","get","exists","data","uid","orgId","org","locked","bindingsRef","current","find","binding","ok","removed","stale","catch","paths","delete","dropRecordPages","screen","code","datasetId","dataset","slugField","model","fields","optional","key","fieldId","others","some","id","name","collections","select","refusal","base","collectionSlugs","docs","otherBases","_id","stored","set","updatedAt","now","updatedBy","before","after","Promise","all","console","reason","hostIds","Set","ref","parent"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,oBAAoB,EACpBC,gBAAgB,EAChBC,kBAAkB,EAClBC,kBAAkB,EAClBC,oBAAoB,QAEf,sBAAqB;AAC5B,SAASC,yBAAyB,QAAQ,sDAAqD;AAC/F,SAASC,mBAAmB,QAAQ,gDAA+C;AACnF,SACEC,uBAAuB,EACvBC,aAAa,EACbC,sBAAsB,EACtBC,2BAA2B,EAC3BC,eAAe,QACV,2BAA0B;AACjC,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,SAAS,QAAQ,2BAA0B;AACpD,SAASC,sBAAsB,QAAQ,wCAAoC;AAC3E,SAASC,8BAA8B,EAAEC,iBAAiB,QAAQ,qCAAiC;AACnG,SAASC,eAAe,QAAQ,+BAA2B;AAC3D,SAEEC,yBAAyB,EACzBC,oBAAoB,EACpBC,uBAAuB,EACvBC,qBAAqB,QAChB,oBAAgB;AAEvB,6EAA6E,GAC7E,MAAMC,kBAAkB;IACtB;IACA;IACA;IACA;CACD;AAED,MAAMC,OAAO,CAACC,QAA4B,OAAOA,UAAU,WAAWA,MAAMC,IAAI,KAAK;AAErF;;;;;CAKC,GACD,SAASC;IACP,OAAOrB,4BACJsB,GAAG,CAAC,CAACC;YAAYA;gBAAAA,8BAAAA,QAAQC,IAAI,CAACC,KAAK,CAAC,KAAKC,MAAM,CAACC,QAAQ,CAAC,EAAE,YAA1CJ,8BAA8C;OAC/DG,MAAM,CAACC;AACZ;AAEA;;;;;;;;;;;;;;;;;;;;;;;CAuBC,GACD,OAAO,MAAMC,qBAA0C,OAAOC;QAMtCC;IALtB,MAAM,EAAEC,MAAM,EAAEC,IAAI,EAAEF,SAASG,UAAU,EAAE,GAAG,MAAMlC,qBAAqB8B;IACzE,MAAMC,UAAUG;IAChB,IAAIF,WAAW,QAAQ;QACr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AAQ;QAAI;IACpF;AACF,EAAC;AAED;;;;;;;;;;CAUC,GACD,eAAeyC,gBACbjC,MAAc,EACd0B,OAAiC,EACjCK,KAAe,EACfmC,MAAc;IAEd,IAAI;QACF,MAAM9G,oBAAoB;YACxB+G,SAAS;gBAACnE;aAAO;YACjB+B,OAAO;gBAAE,CAAC/B,OAAO,EAAE;uBAAI,IAAIoE,IAAI;wBAAC,CAAC,CAAC,EAAE1C,QAAQyB,IAAI,EAAE;2BAAKpB;qBAAM;iBAAE;YAAC;YAChEmC;QACF;IACF,EAAE,OAAO3E,OAAO;QACd0E,QAAQ1E,KAAK,CAAC,oCAAoCS,QAAQT;IAC5D;IACA,IAAI;YAEY8C;QADd,MAAMA,UAAU,MAAMtE,gBAAgBiC,QAAQ0B,QAAQU,SAAS;QAC/D,MAAMhB,QAAQiB,4BAAAA,6BAAAA,QAASgC,GAAG,CAACC,MAAM,CAACA,MAAM,qBAA1BjC,2BAA4BS,EAAE;QAC5C,IAAIT,WAAWjB,OAAO;YACpB,MAAMxD,uBAAuB;gBAC3B+C,WAAWrD,cAAcgD,GAAG,GAAGK,SAAS;gBACxCS;gBACAgB,WAAWC,QAAQS,EAAE;YACvB;QACF;IACF,EAAE,OAAOvD,OAAO;QACd0E,QAAQ1E,KAAK,CAAC,0CAA0CS,QAAQT;IAClE;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/record-pages/record-pages-route.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 { holdsSiteKey, siteKeyRefusal } from '@aglyn/aglyn/app-utils/host-permissions'\nimport {\n SCREEN_KIND_TEMPLATE,\n checkEntitlement,\n hostCollectionKind,\n pluginRequestFromWeb,\n type PluginWebApiHandler,\n} from '@aglyn/aglyn/server'\nimport { listPluginSitemapSections } from '@aglyn/aglyn/plugin-manager/plugin-sitemap-sections'\nimport { dropPluginSiteCache } from '@aglyn/aglyn/plugin-manager/plugin-site-cache'\nimport {\n emailUnverifiedResponse,\n firebaseAdmin,\n isImpersonationSession,\n isServerReleaseFlagOnForOrg,\n lockdownRefusal,\n} from '@aglyn/tenant-data-admin'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { Timestamp } from 'firebase-admin/firestore'\nimport { announceDatasetRecords } from '../server/announce-dataset-records'\nimport { readRecordPageBindingsUncached, recordPagePathsOf } from './record-page-live-paths.server'\nimport { readSiteDataset } from './record-page-read.server'\nimport {\n type DatasetRecordPageBinding,\n RECORD_PAGES_MAX_PER_SITE,\n isRecordAddressField,\n normalizeRecordPageBase,\n recordPageBaseRefusal,\n} from './record-pages'\n\n/** The optional fields a binding may name, each one a field of the dataset. */\nconst OPTIONAL_FIELDS = [\n 'titleField',\n 'seoTitleField',\n 'seoDescriptionField',\n 'seoImageField',\n] as const\n\nconst text = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\n\n/**\n * The first segment of every route another plugin serves pages under on every\n * site, read off the sections they declare for the sitemap — `/products/{slug}`\n * is `products` — so a base cannot shadow a store without this plugin naming\n * one.\n */\nfunction pluginRouteSegments(): string[] {\n return listPluginSitemapSections()\n .map((section) => section.path.split('/').filter(Boolean)[0] ?? '')\n .filter(Boolean)\n}\n\n/**\n * A site's record templates (AGL-3475), saved and removed — the only writer\n * of `hosts/{hostId}/recordPages`, which the rules close to every client.\n *\n * A binding decides which page serves `/{base}/…` for every record of a\n * dataset, so it is a routing decision and needs the PUBLISH role on the\n * site, as a redirect does. Saving checks what a published page would\n * otherwise get wrong with nothing red:\n *\n * - the page is a template (`kind: 'template'`), so its own address cannot\n * serve raw `{{item.*}}` — the console converts it first, through the\n * platform's own route, which is the only writer of `kind`;\n * - the dataset is shared with this site, and its address field is a page\n * address;\n * - the plan includes datasets (Starter and up), and the data store is\n * released for the organization;\n * - the base is free: no reserved address, no other plugin's route, no\n * content collection's slug, no other template's base; and the dataset has\n * no other template on this site, so `{{item.url}}` has one answer.\n *\n * Every save and removal drops the record pages it changes — the ones it\n * stops serving and the ones it starts to, which a crawler may have been told\n * were missing.\n */\nexport const recordPagesHandler: PluginWebApiHandler = async (request) => {\n const { method, body, headers: rawHeaders } = await pluginRequestFromWeb(request)\n const headers = rawHeaders as Partial<Record<string, string>>\n if (method !== 'POST') {\n return Response.json({ error: 'Method not allowed' }, { status: 405 })\n }\n const authorization = headers.authorization ?? ''\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return Response.json({ error: 'Unauthenticated' }, { status: 401 })\n\n const action = text(body?.action)\n const hostId = text(body?.hostId)\n const screenId = text(body?.screenId)\n if (action !== 'save' && action !== 'remove') {\n return Response.json({ error: 'Unknown action' }, { status: 400 })\n }\n if (!hostId || !screenId || hostId.includes('/') || screenId.includes('/')) {\n return Response.json({ error: 'Missing hostId or screenId' }, { status: 400 })\n }\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n if (!decoded.email_verified && !isImpersonationSession(decoded)) {\n return emailUnverifiedResponse()\n }\n const staff = decoded['staff'] === true\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return Response.json({ error: 'Unknown site' }, { status: 404 })\n }\n const host = hostSnapshot.data() as Record<string, unknown>\n if (!staff && !holdsSiteKey(host, decoded.uid, 'site.publish')) {\n return Response.json(\n { error: siteKeyRefusal('site.publish') },\n { status: 403 },\n )\n }\n const orgId = text(host['orgId'])\n const org = orgId\n ? ((await firestore.collection('orgs').doc(orgId).get()).data() as Record<string, unknown> | undefined)\n : undefined\n const locked = await lockdownRefusal({\n request,\n staff,\n uid: decoded.uid,\n org: org as never,\n host: host as never,\n })\n if (locked) return locked\n if (!staff && orgId && !(await isServerReleaseFlagOnForOrg('release_data_store', orgId))) {\n return Response.json({ error: 'Not available' }, { status: 404 })\n }\n\n // Spelled out, not DATASET_RECORD_PAGES_COLLECTION: the media-corpus guard\n // (host-content-media-coverage.spec) finds host collections by literal.\n const bindingsRef = hostRef.collection('recordPages')\n const bindings = await readRecordPageBindingsUncached(hostId)\n const current = bindings.find((binding) => binding.screenId === screenId) ?? null\n\n if (action === 'remove') {\n if (!current) return Response.json({ ok: true, removed: false }, { status: 200 })\n const stale = await recordPagePathsOf(hostId, current).catch(() => ({ paths: [] as string[] }))\n await bindingsRef.doc(screenId).delete()\n await dropRecordPages(hostId, current, stale.paths, 'record template removed')\n return Response.json({ ok: true, removed: true }, { status: 200 })\n }\n\n if (!checkEntitlement(org as never, 'dataStore')) {\n return Response.json(\n { error: 'Record pages need a Starter plan or higher' },\n { status: 403 },\n )\n }\n const screen = (await hostRef.collection('screens').doc(screenId).get()).data() as\n | Record<string, unknown>\n | undefined\n if (!screen || screen['deletedAt']) {\n return Response.json({ error: 'Unknown page' }, { status: 404 })\n }\n if (screen['kind'] !== SCREEN_KIND_TEMPLATE) {\n return Response.json(\n { error: 'Make this page a template first', code: 'not-template' },\n { status: 409 },\n )\n }\n\n const datasetId = text(body?.datasetId)\n const dataset = await readSiteDataset(hostId, datasetId)\n if (!dataset) {\n return Response.json({ error: 'That dataset is not shared with this site' }, { status: 404 })\n }\n const slugField = text(body?.slugField)\n if (!isRecordAddressField(dataset.model.fields[slugField])) {\n return Response.json(\n { error: 'Pick a Page address field of the dataset for the record pages’ addresses' },\n { status: 400 },\n )\n }\n const optional: Partial<DatasetRecordPageBinding> = {}\n for (const key of OPTIONAL_FIELDS) {\n const fieldId = text(body?.[key])\n if (!fieldId) continue\n if (!dataset.model.fields[fieldId]) {\n return Response.json({ error: `The dataset has no field \"${fieldId}\"` }, { status: 400 })\n }\n optional[key] = fieldId\n }\n\n const others = bindings.filter((binding) => binding.screenId !== screenId)\n if (!current && bindings.length >= RECORD_PAGES_MAX_PER_SITE) {\n return Response.json(\n { error: `A site can have up to ${RECORD_PAGES_MAX_PER_SITE} record templates` },\n { status: 403 },\n )\n }\n if (others.some((binding) => binding.datasetId === dataset.id)) {\n return Response.json(\n { error: `${dataset.name || 'This dataset'} already has a record template on this site` },\n { status: 409 },\n )\n }\n const collections = await hostRef.collection('collections').select('slug', 'kind').get()\n const refusal = recordPageBaseRefusal(body?.base, {\n collectionSlugs: collections.docs\n .filter((doc) => hostCollectionKind(doc.data() as never) === 'content')\n .map((doc) => text(doc.get('slug')))\n .filter(Boolean),\n pluginRouteSegments: pluginRouteSegments(),\n otherBases: others.map((binding) => binding.base),\n })\n if (refusal) return Response.json({ error: refusal }, { status: 400 })\n const base = normalizeRecordPageBase(body?.base) as string\n\n const binding: DatasetRecordPageBinding = {\n screenId,\n datasetId: dataset.id,\n base,\n slugField,\n ...optional,\n }\n const { screenId: _id, ...stored } = binding\n await bindingsRef.doc(screenId).set({\n ...stored,\n updatedAt: Timestamp.now(),\n updatedBy: decoded.uid,\n })\n const [before, after] = await Promise.all([\n current ? recordPagePathsOf(hostId, current).catch(() => ({ paths: [] as string[] })) : { paths: [] },\n recordPagePathsOf(hostId, binding).catch(() => ({ paths: [] as string[] })),\n ])\n await dropRecordPages(\n hostId,\n binding,\n [...after.paths, ...(current ? [`/${current.base}`] : []), ...before.paths],\n 'record template saved',\n )\n return Response.json({ ok: true, binding }, { status: 200 })\n } catch (error) {\n if (isRefusedIdToken(error)) {\n return Response.json({ error: 'Unauthenticated' }, { status: 401 })\n }\n console.error(error)\n return Response.json({ error: 'Record template operation failed' }, { status: 500 })\n }\n}\n\n/**\n * Drops what a binding change makes stale. Best effort: the binding is\n * written, and the host's data tag is underneath.\n *\n * - The record pages it starts or stops serving, and its base, which a site\n * often publishes as the listing — and which is always one path, so the\n * drop always reaches the tenant and busts the data tag the bindings are\n * cached under. A drop naming no path is skipped outright.\n * - Every page that repeats over the dataset, on every site sharing it: its\n * rows have gained or lost their `{{item.url}}`.\n */\nasync function dropRecordPages(\n hostId: string,\n binding: DatasetRecordPageBinding,\n paths: string[],\n reason: string,\n): Promise<void> {\n try {\n await dropPluginSiteCache({\n hostIds: [hostId],\n paths: { [hostId]: [...new Set([`/${binding.base}`, ...paths])] },\n reason,\n })\n } catch (error) {\n console.error('[record-pages] cache drop failed', hostId, error)\n }\n try {\n const dataset = await readSiteDataset(hostId, binding.datasetId)\n const orgId = dataset?.ref.parent.parent?.id\n if (dataset && orgId) {\n await announceDatasetRecords({\n firestore: firebaseAdmin.app().firestore(),\n orgId,\n datasetId: dataset.id,\n })\n }\n } catch (error) {\n console.error('[record-pages] dataset announce failed', hostId, error)\n }\n}\n"],"names":["holdsSiteKey","siteKeyRefusal","SCREEN_KIND_TEMPLATE","checkEntitlement","hostCollectionKind","pluginRequestFromWeb","listPluginSitemapSections","dropPluginSiteCache","emailUnverifiedResponse","firebaseAdmin","isImpersonationSession","isServerReleaseFlagOnForOrg","lockdownRefusal","isRefusedIdToken","Timestamp","announceDatasetRecords","readRecordPageBindingsUncached","recordPagePathsOf","readSiteDataset","RECORD_PAGES_MAX_PER_SITE","isRecordAddressField","normalizeRecordPageBase","recordPageBaseRefusal","OPTIONAL_FIELDS","text","value","trim","pluginRouteSegments","map","section","path","split","filter","Boolean","recordPagesHandler","request","headers","method","body","rawHeaders","Response","json","error","status","authorization","idToken","startsWith","slice","length","undefined","action","hostId","screenId","includes","bindings","decoded","app","auth","verifyIdToken","email_verified","staff","firestore","hostRef","collection","doc","hostSnapshot","get","exists","host","data","uid","orgId","org","locked","bindingsRef","current","find","binding","ok","removed","stale","catch","paths","delete","dropRecordPages","screen","code","datasetId","dataset","slugField","model","fields","optional","key","fieldId","others","some","id","name","collections","select","refusal","base","collectionSlugs","docs","otherBases","_id","stored","set","updatedAt","now","updatedBy","before","after","Promise","all","console","reason","hostIds","Set","ref","parent"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,YAAY,EAAEC,cAAc,QAAQ,0CAAyC;AACtF,SACEC,oBAAoB,EACpBC,gBAAgB,EAChBC,kBAAkB,EAClBC,oBAAoB,QAEf,sBAAqB;AAC5B,SAASC,yBAAyB,QAAQ,sDAAqD;AAC/F,SAASC,mBAAmB,QAAQ,gDAA+C;AACnF,SACEC,uBAAuB,EACvBC,aAAa,EACbC,sBAAsB,EACtBC,2BAA2B,EAC3BC,eAAe,QACV,2BAA0B;AACjC,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,SAAS,QAAQ,2BAA0B;AACpD,SAASC,sBAAsB,QAAQ,wCAAoC;AAC3E,SAASC,8BAA8B,EAAEC,iBAAiB,QAAQ,qCAAiC;AACnG,SAASC,eAAe,QAAQ,+BAA2B;AAC3D,SAEEC,yBAAyB,EACzBC,oBAAoB,EACpBC,uBAAuB,EACvBC,qBAAqB,QAChB,oBAAgB;AAEvB,6EAA6E,GAC7E,MAAMC,kBAAkB;IACtB;IACA;IACA;IACA;CACD;AAED,MAAMC,OAAO,CAACC,QAA4B,OAAOA,UAAU,WAAWA,MAAMC,IAAI,KAAK;AAErF;;;;;CAKC,GACD,SAASC;IACP,OAAOrB,4BACJsB,GAAG,CAAC,CAACC;YAAYA;gBAAAA,8BAAAA,QAAQC,IAAI,CAACC,KAAK,CAAC,KAAKC,MAAM,CAACC,QAAQ,CAAC,EAAE,YAA1CJ,8BAA8C;OAC/DG,MAAM,CAACC;AACZ;AAEA;;;;;;;;;;;;;;;;;;;;;;;CAuBC,GACD,OAAO,MAAMC,qBAA0C,OAAOC;QAMtCC;IALtB,MAAM,EAAEC,MAAM,EAAEC,IAAI,EAAEF,SAASG,UAAU,EAAE,GAAG,MAAMlC,qBAAqB8B;IACzE,MAAMC,UAAUG;IAChB,IAAIF,WAAW,QAAQ;QACrB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CAUC,GACD,eAAeyC,gBACbjC,MAAc,EACd0B,OAAiC,EACjCK,KAAe,EACfmC,MAAc;IAEd,IAAI;QACF,MAAM9G,oBAAoB;YACxB+G,SAAS;gBAACnE;aAAO;YACjB+B,OAAO;gBAAE,CAAC/B,OAAO,EAAE;uBAAI,IAAIoE,IAAI;wBAAC,CAAC,CAAC,EAAE1C,QAAQyB,IAAI,EAAE;2BAAKpB;qBAAM;iBAAE;YAAC;YAChEmC;QACF;IACF,EAAE,OAAO3E,OAAO;QACd0E,QAAQ1E,KAAK,CAAC,oCAAoCS,QAAQT;IAC5D;IACA,IAAI;YAEY8C;QADd,MAAMA,UAAU,MAAMtE,gBAAgBiC,QAAQ0B,QAAQU,SAAS;QAC/D,MAAMhB,QAAQiB,4BAAAA,6BAAAA,QAASgC,GAAG,CAACC,MAAM,CAACA,MAAM,qBAA1BjC,2BAA4BS,EAAE;QAC5C,IAAIT,WAAWjB,OAAO;YACpB,MAAMxD,uBAAuB;gBAC3B8C,WAAWpD,cAAc+C,GAAG,GAAGK,SAAS;gBACxCU;gBACAgB,WAAWC,QAAQS,EAAE;YACvB;QACF;IACF,EAAE,OAAOvD,OAAO;QACd0E,QAAQ1E,KAAK,CAAC,0CAA0CS,QAAQT;IAClE;AACF"}
@@ -50,6 +50,12 @@ import { type DatasetFieldType, type DatasetModel } from '../model/dataset-model
50
50
  * - A PAGE is a `page` field (AGL-3763): text storage riding the "Page"
51
51
  * custom type, each value one of the site's pages as `screen:{id}`
52
52
  * (`isDatasetPageValue`), which a Button or Link binds.
53
+ * - A SAMPLE is a seeded record the caller marks as one (`samples`,
54
+ * AGL-4065): a site start whose brief gave no entries for a list seeds it
55
+ * with complete-looking samples, and the record carries `sample: true`
56
+ * beside its values, which the Data card shows as a sample to replace
57
+ * and a published page never reads. Saving the record in Data makes it
58
+ * the owner's.
53
59
  *
54
60
  * Nothing is published. The writer touches the one new dataset and its
55
61
  * records; a page shows them only where a person (or a job's draft page)
@@ -120,6 +126,11 @@ export interface DatasetDraftContent {
120
126
  * asked for where a record page will show each record at its own address.
121
127
  */
122
128
  pageAddressFrom?: string;
129
+ /**
130
+ * Which seeded records are samples for the owner to replace, by position
131
+ * as `records` (AGL-4065). Absent, or false, is a record of the owner's.
132
+ */
133
+ samples?: boolean[];
123
134
  }
124
135
  /** What the writer reports about a dataset. */
125
136
  export interface DatasetDraftFacts {
@@ -141,6 +152,8 @@ export interface DatasetDraftRead {
141
152
  /** Each record's values by field id, coerced and addressed. */
142
153
  records: Array<Record<string, unknown>>;
143
154
  addressField: string | null;
155
+ /** Which records are samples, by position (AGL-4065); absent where none is. */
156
+ samples?: boolean[];
144
157
  }
145
158
  export type DatasetDraftContentRead = {
146
159
  ok: true;
@@ -201,6 +201,14 @@ function isRecord(value) {
201
201
  records.push(values);
202
202
  });
203
203
  }
204
+ // Which records are samples (AGL-4065): true or false, one a record at most.
205
+ const rawSamples = content['samples'];
206
+ if (rawSamples !== undefined && (!Array.isArray(rawSamples) || rawSamples.some((entry)=>typeof entry !== 'boolean'))) {
207
+ problems.push('Samples are a list of true or false, one a record');
208
+ } else if (Array.isArray(rawSamples) && rawSamples.length > records.length) {
209
+ problems.push('Samples name more records than the dataset is seeded with');
210
+ }
211
+ const samples = Array.isArray(rawSamples) && rawSamples.some((entry)=>entry === true) ? records.map((_values, index)=>rawSamples[index] === true) : null;
204
212
  if (problems.length) return {
205
213
  ok: false,
206
214
  problems: [
@@ -222,12 +230,14 @@ function isRecord(value) {
222
230
  }
223
231
  return {
224
232
  ok: true,
225
- value: {
233
+ value: _extends({
226
234
  name,
227
235
  model,
228
236
  records,
229
237
  addressField
230
- }
238
+ }, samples ? {
239
+ samples
240
+ } : {})
231
241
  };
232
242
  }
233
243
  /** The first photo field of a model, by id. */ function imageFieldOf(model) {
@@ -414,7 +424,7 @@ export function createDatasetDraftWriter(deps = {}) {
414
424
  const orgRef = db.collection('orgs').doc(request.orgId);
415
425
  const datasets = orgRef.collection('datasets');
416
426
  const datasetRef = datasets.doc(request.id);
417
- const { name, model, records, addressField } = read.value;
427
+ const { name, model, records, addressField, samples } = read.value;
418
428
  const recordQuota = checkQuota(request.org, 'recordsPerDataset', Math.max(0, records.length - 1));
419
429
  if (records.length && !recordQuota.allowed) {
420
430
  return {
@@ -461,7 +471,9 @@ export function createDatasetDraftWriter(deps = {}) {
461
471
  records.forEach((values, order)=>{
462
472
  tx.create(datasetRef.collection('records').doc(recordIds[order]), _extends({
463
473
  values
464
- }, datasetIntegrityFields(model, values), {
474
+ }, datasetIntegrityFields(model, values), (samples == null ? void 0 : samples[order]) ? {
475
+ sample: true
476
+ } : {}, {
465
477
  order,
466
478
  createdAt: request.now,
467
479
  updatedAt: request.now
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/server/dataset-drafts.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport { memberCanSee } from '@aglyn/aglyn/app-utils/organizations'\nimport { checkDatasetQuota, checkEntitlement, checkQuota } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { hostScopeToken, newResourceScopeFields } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport {\n registerPluginResourceDraftWriter,\n type PluginDraftCheck,\n type PluginDraftContext,\n type PluginDraftRecord,\n type PluginDraftRecordsRevise,\n type PluginDraftRefusal,\n type PluginDraftWrite,\n type PluginResourceDraftWriter,\n} from '@aglyn/aglyn/plugin-manager/plugin-resource-drafts'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { dataStorageRefusal } from '@aglyn/tenant-data-admin/server/data-storage-gate'\nimport {\n memberHasOrgPermission,\n resolveOrgIdForHost,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin/server/organizations'\nimport { isServerReleaseFlagOnForOrg } from '@aglyn/tenant-data-admin/server/release-flags'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport {\n coerceDocumentValues,\n datasetIntegrityFields,\n datasetIntegrityUpdate,\n defaultDatasetFieldId,\n validateDocument,\n type DatasetFieldType,\n type DatasetModel,\n} from '../model/dataset-models'\nimport { DATASET_IMAGE_FIELD_TYPE, isDatasetImageValue } from '../model/dataset-image-field'\nimport { DATASET_PAGE_FIELD_TYPE, isDatasetPageValue } from '../model/dataset-page-field'\nimport {\n RECORD_PAGE_ADDRESS_FIELD_TYPE,\n RECORD_PAGE_ADDRESS_MAX,\n uniqueRecordAddresses,\n} from '../record-pages/record-pages'\n\n/**\n * A DATASET ANOTHER PLUGIN ASKS FOR (AGL-3616).\n *\n * The draft writer this plugin registers for the `dataset` resource on the\n * core's resource-drafts seam. Aglyn AI builds a menu, a team, a list of\n * services or a portfolio as a dataset, the way the docs teach a person to,\n * and asks for the writer by name, so every rule is this plugin's:\n *\n * - THE DOCUMENT is the one the Data card's create makes: a display name,\n * the flat `fields` mirror and a typed model, shared with the site it is\n * made for and no other (AGL-4003), and the\n * seeded records, each with the integrity and filter index every record\n * write carries. Where a record page is wanted the model gains a \"Page\n * address\" field that fills from a text field, and every seeded record a\n * unique address (`uniqueRecordAddresses`), so the member's Record pages\n * save has nothing left to fill.\n * - THE ROOM is `datasetsPerOrg` (add-ons included, `checkDatasetQuota`),\n * counted INSIDE the transaction that creates, as the datasets route\n * counts it; the records are held to `recordsPerDataset` and the dataset\n * storage band.\n * - THE PLAN is `dataStore` (Starter and up), THE FLAG `release_data_store`,\n * and THE ROLE an org member who may edit org data (owner, admin or\n * editor) with `data.manage`, whose access reaches the site — refused in\n * the route's own words.\n * - THE CHECK holds every record to the model it is written under\n * (`validateDocument`), so what is seeded is what a person could type.\n * - A PHOTO is an `image` field (AGL-3616): text storage riding the\n * \"Image\" custom type, each value an address the site's Image element\n * shows (`isDatasetImageValue`), so a portfolio's pieces or a team keep\n * the photo the page that lists them binds.\n * - A PAGE is a `page` field (AGL-3763): text storage riding the \"Page\"\n * custom type, each value one of the site's pages as `screen:{id}`\n * (`isDatasetPageValue`), which a Button or Link binds.\n *\n * Nothing is published. The writer touches the one new dataset and its\n * records; a page shows them only where a person (or a job's draft page)\n * places a repeat over it.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** The resource name this writer is registered under. */\nexport const DATASET_DRAFT_RESOURCE = 'dataset'\n\n/** The longest dataset name, as the datasets route keeps it. */\nexport const DATASET_DRAFT_NAME_MAX = 120\n/** The most fields a drafted dataset is made with, and the longest name. */\nexport const DATASET_DRAFT_FIELDS_MAX = 16\nexport const DATASET_DRAFT_FIELD_NAME_MAX = 60\n/** The most records a draft is seeded with. */\nexport const DATASET_DRAFT_RECORDS_MAX = 24\n/** The longest text value a seeded record keeps. */\nexport const DATASET_DRAFT_VALUE_MAX = 2_000\n/** The most entries a seeded list value keeps. */\nexport const DATASET_DRAFT_LIST_MAX = 12\n\n/**\n * The field types a caller names, in words a person reads, and the type\n * each one is stored as. A date or a time is written as text the way a\n * visitor reads it (\"Saturday 8 November, 7 pm\"): a stored timestamp renders\n * as a number in a repeat's `{{item.<field>}}`. An image is text holding a\n * photo's address, under the \"Image\" custom type (AGL-3616), and a page is\n * text holding a page's reference, under the \"Page\" custom type (AGL-3763).\n */\nexport const DATASET_DRAFT_FIELD_TYPES = {\n text: 'text',\n number: 'float',\n integer: 'int32',\n boolean: 'bool',\n list: 'sorted',\n image: 'text',\n page: 'text',\n} as const satisfies Record<string, DatasetFieldType>\n\nexport type DatasetDraftFieldType = keyof typeof DATASET_DRAFT_FIELD_TYPES\n\nconst DRAFT_TYPES = Object.keys(DATASET_DRAFT_FIELD_TYPES) as DatasetDraftFieldType[]\n\n/** The datasets route's refusals, word for word. */\nexport const DATASET_DRAFT_ROLE_REFUSAL = 'Editing org data requires the editor role'\nexport const DATASET_DRAFT_PERMISSION_REFUSAL = 'Your organization role does not allow editing organization data'\nexport const DATASET_DRAFT_PLAN_REFUSAL = 'Datasets require a Starter plan or higher'\nexport const DATASET_DRAFT_RELEASE_REFUSAL = 'Datasets are not available for this workspace yet'\nexport const DATASET_DRAFT_SCOPE_REFUSAL = 'Your access to this organization does not reach that site'\nexport const DATASET_DRAFT_STORAGE_REFUSAL = 'Dataset storage is full on this plan — upgrade in Billing'\n\n/** The route's refusal at the plan's dataset allowance. */\nexport function datasetDraftLimitRefusal(quota: ReturnType<typeof checkDatasetQuota>): string {\n return quota.upgradeRequired\n ? `Dataset limit reached (${quota.limit}) — upgrade in Billing`\n : `Dataset limit reached (${quota.limit}) — add extra datasets for $${quota.addonPriceUsd}/mo each or upgrade in Billing`\n}\n\n/** The route's refusal at the plan's record allowance. */\nexport function datasetDraftRecordLimitRefusal(limit: number): string {\n return `Record limit reached (${limit}) — upgrade in Billing`\n}\n\n/** One field as a caller names it. */\nexport interface DatasetDraftField {\n name: string\n /** Absent is text. */\n type?: DatasetDraftFieldType\n required?: boolean\n}\n\n/**\n * What a caller sends as `content`. Each record's values are keyed by the\n * field NAME the caller gave, since the caller has no ids yet; the writer\n * mints the ids (`roast_preference` from \"Roast preference\").\n */\nexport interface DatasetDraftContent {\n /** The dataset's name; the request's `name` stands in when absent. */\n name?: string\n fields: DatasetDraftField[]\n records?: Array<Record<string, unknown>>\n /**\n * A text field, by name, a \"Page address\" field fills from (AGL-3475):\n * asked for where a record page will show each record at its own address.\n */\n pageAddressFrom?: string\n}\n\n/** What the writer reports about a dataset. */\nexport interface DatasetDraftFacts {\n fields: Array<{ id: string; name: string; type: DatasetFieldType }>\n records: number\n /** The page-address field's id, where the dataset has one. */\n addressField: string | null\n /** The first photo field's id, where the dataset has one (AGL-3616). */\n imageField: string | null\n}\n\n/** The draft as the writer will store it. */\nexport interface DatasetDraftRead {\n name: string\n model: DatasetModel\n /** Each record's values by field id, coerced and addressed. */\n records: Array<Record<string, unknown>>\n addressField: string | null\n}\n\nexport type DatasetDraftContentRead =\n | { ok: true; value: DatasetDraftRead }\n | { ok: false; problems: string[] }\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** Text on one line: controls and runs of space folded to one space. */\nfunction line(value: unknown): string {\n return typeof value === 'string' ? value.replace(/[\\p{Cc}\\s]+/gu, ' ').trim() : ''\n}\n\n/** A value as a seeded record keeps it, before the model coerces it. */\nfunction seedValue(value: unknown): unknown {\n if (typeof value === 'string') return value.replace(/\\r\\n?/g, '\\n').trim().slice(0, DATASET_DRAFT_VALUE_MAX)\n if (Array.isArray(value)) {\n return value\n .map((entry) => (typeof entry === 'string' ? line(entry) : entry))\n .filter((entry) => entry !== '' && entry !== null && entry !== undefined)\n .slice(0, DATASET_DRAFT_LIST_MAX)\n }\n return value\n}\n\n/** The content as the writer reads it, or every problem that stops it. Pure. */\nexport function readDatasetDraftContent(content: Readonly<Record<string, unknown>>): DatasetDraftContentRead {\n const problems: string[] = []\n const name = line(content['name'])\n if (!name) problems.push('The dataset needs a name')\n else if (name.length > DATASET_DRAFT_NAME_MAX) {\n problems.push(`The name is longer than ${DATASET_DRAFT_NAME_MAX} characters`)\n }\n\n const rawFields = content['fields']\n const model: DatasetModel = { fields: {}, order: [] }\n /** Field name, lowercased → id. */\n const byName = new Map<string, string>()\n if (!Array.isArray(rawFields) || !rawFields.length) {\n problems.push('The dataset needs at least one field')\n } else if (rawFields.length > DATASET_DRAFT_FIELDS_MAX) {\n problems.push(`A dataset is made with at most ${DATASET_DRAFT_FIELDS_MAX} fields`)\n } else {\n for (const raw of rawFields) {\n const fieldName = isRecord(raw) ? line(raw['name']) : ''\n const rawType = (isRecord(raw) ? raw['type'] : undefined) ?? 'text'\n if (!fieldName) {\n problems.push('Each field needs a name')\n continue\n }\n if (fieldName.length > DATASET_DRAFT_FIELD_NAME_MAX) {\n problems.push(`The field \"${fieldName.slice(0, 20)}…\" has a name longer than ${DATASET_DRAFT_FIELD_NAME_MAX} characters`)\n continue\n }\n if (!(DRAFT_TYPES as readonly unknown[]).includes(rawType)) {\n problems.push(`The field \"${fieldName}\" is one of ${DRAFT_TYPES.join(', ')}`)\n continue\n }\n if (byName.has(fieldName.toLowerCase())) {\n problems.push(`Two fields are both called \"${fieldName}\"`)\n continue\n }\n const id = defaultDatasetFieldId(fieldName, new Set(model.order))\n if (!id) {\n problems.push(`The field \"${fieldName}\" needs a name with a letter in it`)\n continue\n }\n model.fields[id] = {\n name: fieldName,\n type: DATASET_DRAFT_FIELD_TYPES[rawType as DatasetDraftFieldType],\n ...(rawType === 'image' ? { customType: DATASET_IMAGE_FIELD_TYPE } : {}),\n ...(rawType === 'page' ? { customType: DATASET_PAGE_FIELD_TYPE } : {}),\n ...(isRecord(raw) && raw['required'] === true ? { required: true } : {}),\n }\n model.order.push(id)\n byName.set(fieldName.toLowerCase(), id)\n }\n }\n\n // The page address: a text field the address fills from, once.\n let addressField: string | null = null\n const rawAddress = content['pageAddressFrom']\n if (rawAddress !== undefined && rawAddress !== null && rawAddress !== '') {\n const sourceId = byName.get(line(rawAddress).toLowerCase())\n if (!sourceId || model.fields[sourceId]?.type !== 'text' || model.fields[sourceId]?.customType) {\n problems.push('A page address fills from one of the dataset’s text fields')\n } else {\n addressField = defaultDatasetFieldId('slug', new Set(model.order))\n model.fields[addressField] = {\n name: 'Page address',\n type: 'text',\n customType: RECORD_PAGE_ADDRESS_FIELD_TYPE,\n slugFrom: sourceId,\n }\n model.order.push(addressField)\n }\n }\n\n const rawRecords = content['records'] ?? []\n const records: Array<Record<string, unknown>> = []\n if (!Array.isArray(rawRecords)) {\n problems.push('Records are a list of values by field name')\n } else if (rawRecords.length > DATASET_DRAFT_RECORDS_MAX) {\n problems.push(`A dataset is seeded with at most ${DATASET_DRAFT_RECORDS_MAX} records`)\n } else if (!problems.length) {\n rawRecords.forEach((raw, index) => {\n if (!isRecord(raw)) {\n problems.push(`Record ${index + 1} is not a set of values`)\n return\n }\n const input: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(raw)) {\n const id = byName.get(line(key).toLowerCase())\n if (!id) {\n problems.push(`Record ${index + 1} names \"${line(key).slice(0, 40)}\", which is not a field`)\n continue\n }\n input[id] = seedValue(value)\n }\n const values = coerceDocumentValues(model, input)\n // An empty value is no value: it is not stored, as the card stores none.\n for (const [id, value] of Object.entries(values)) {\n if (value === '' || value === null || value === undefined || (Array.isArray(value) && !value.length)) {\n delete values[id]\n }\n }\n const errors = validateDocument(model, values)\n // A photo is an address the site's Image shows, whether or not the\n // \"Image\" type's check is registered in this process (AGL-3616).\n for (const [id, value] of Object.entries(values)) {\n const field = model.fields[id]\n if (field?.customType === DATASET_IMAGE_FIELD_TYPE && !errors[id] && !isDatasetImageValue(value)) {\n errors[id] = `${field.name} is not a photo from the media library or an https link`\n }\n // …and a page is one of the site's pages, by reference (AGL-3763).\n if (field?.customType === DATASET_PAGE_FIELD_TYPE && !errors[id] && !isDatasetPageValue(value)) {\n errors[id] = `${field.name} is not one of the site’s pages`\n }\n }\n for (const error of Object.values(errors)) problems.push(`Record ${index + 1}: ${error}`)\n if (!Object.keys(values).length) problems.push(`Record ${index + 1} has no values`)\n records.push(values)\n })\n }\n if (problems.length) return { ok: false, problems: [...new Set(problems)] }\n\n // Every seeded record its own address, unique within the dataset.\n if (addressField) {\n const source = model.fields[addressField]?.slugFrom as string\n const assigned = uniqueRecordAddresses(records.map((values, index) => ({ id: String(index), source: values[source] })))\n records.forEach((values, index) => {\n const address = assigned.get(String(index))\n if (address) values[addressField as string] = address.slice(0, RECORD_PAGE_ADDRESS_MAX)\n })\n }\n return { ok: true, value: { name, model, records, addressField } }\n}\n\n/** The first photo field of a model, by id. */\nfunction imageFieldOf(model: DatasetModel): string | null {\n return model.order.find((id) => model.fields[id]?.customType === DATASET_IMAGE_FIELD_TYPE) ?? null\n}\n\nfunction factsOf(model: DatasetModel, records: number, addressField: string | null): DatasetDraftFacts {\n return {\n fields: model.order.map((id) => ({ id, name: model.fields[id]?.name ?? id, type: model.fields[id]?.type ?? 'text' })),\n records,\n addressField,\n imageField: imageFieldOf(model),\n }\n}\n\n/** Whether content is a dataset this plugin would store, with what it says about it. Pure. */\nexport function checkDatasetDraftContent(content: Readonly<Record<string, unknown>>): PluginDraftCheck {\n const read = readDatasetDraftContent(content)\n if (read.ok === false) return read\n return {\n ok: true,\n facts: factsOf(read.value.model, read.value.records.length, read.value.addressField) as unknown as Readonly<\n Record<string, unknown>\n >,\n }\n}\n\n/** Who the member is in the org, as the writer asks: their role, and whether they may manage data. */\nexport interface DatasetDraftMember {\n role: string\n canManageData: boolean\n /** The membership itself, for whether their access reaches a site. */\n member: Readonly<Record<string, unknown>>\n}\n\nexport interface DatasetDraftWriterDeps {\n /** The Admin SDK handle; specs hand in a double. */\n firestore?: () => Firestore\n /** The org a site belongs to; the platform's lookup otherwise. */\n orgIdForHost?: (hostId: string) => Promise<string | null>\n /** The member, or `null` when they are not one; the platform's otherwise. */\n member?: (uid: string, orgId: string) => Promise<DatasetDraftMember | null>\n /** Whether the data store is released for the org; the platform's flag otherwise. */\n released?: (orgId: string) => Promise<boolean>\n /** Whether dataset bytes may grow; the platform's band otherwise. */\n storageFull?: (org: unknown, orgRef: FirebaseFirestore.DocumentReference) => Promise<boolean>\n}\n\n/** Roles allowed to create org data — the datasets route's, mirroring the rules' `canWriteOrgData()`. */\nconst WRITER_ROLES = new Set(['owner', 'admin', 'editor'])\n\nasync function platformMember(uid: string, orgId: string): Promise<DatasetDraftMember | null> {\n const membership = await resolveOrgMembership(uid, orgId)\n const member = membership?.member\n if (!member) return null\n return {\n role: String(member.role ?? ''),\n canManageData: await memberHasOrgPermission(orgId, member, 'data.manage'),\n member: member as unknown as Readonly<Record<string, unknown>>,\n }\n}\n\nexport function createDatasetDraftWriter(deps: DatasetDraftWriterDeps = {}): PluginResourceDraftWriter {\n const firestore = deps.firestore ?? (() => firebaseAdmin.app().firestore() as unknown as Firestore)\n const orgIdForHost = deps.orgIdForHost ?? ((hostId: string) => resolveOrgIdForHost(hostId))\n const memberOf = deps.member ?? platformMember\n const released = deps.released ?? ((orgId: string) => isServerReleaseFlagOnForOrg('release_data_store', orgId))\n const storageFull =\n deps.storageFull ?? (async (org: unknown, orgRef: FirebaseFirestore.DocumentReference) => Boolean(await dataStorageRefusal(org, orgRef)))\n\n /** Everything but the room: the site is the org's, the member's role, the flag, the plan, the scope. */\n const early = async (context: PluginDraftContext): Promise<PluginDraftRefusal | null> => {\n if ((await orgIdForHost(context.hostId)) !== context.orgId) return { status: 404, error: 'Unknown site' }\n const member = await memberOf(context.uid, context.orgId)\n if (!member || !WRITER_ROLES.has(member.role)) return { status: 403, error: DATASET_DRAFT_ROLE_REFUSAL }\n if (!member.canManageData) return { status: 403, error: DATASET_DRAFT_PERMISSION_REFUSAL }\n if (!(await released(context.orgId))) return { status: 403, error: DATASET_DRAFT_RELEASE_REFUSAL }\n if (!checkEntitlement(context.org as never, 'dataStore')) return { status: 403, error: DATASET_DRAFT_PLAN_REFUSAL }\n // A member scoped to some sites must be able to see what they create.\n if (!memberCanSee(member.member as never, scopeOf(context))) {\n return { status: 403, error: DATASET_DRAFT_SCOPE_REFUSAL }\n }\n return null\n }\n\n return {\n refusal: async (context) => {\n const refused = await early(context)\n if (refused) return refused\n const used = (await firestore().collection('orgs').doc(context.orgId).collection('datasets').count().get()).data().count\n const quota = checkDatasetQuota(context.org as never, Number(used) || 0)\n return quota.allowed ? null : { status: 403, error: datasetDraftLimitRefusal(quota) }\n },\n\n check: (content) => checkDatasetDraftContent(content),\n\n read: async ({ hostId, id }) => {\n const orgId = await orgIdForHost(hostId)\n if (!orgId) return null\n const dataset = await firestore().collection('orgs').doc(orgId).collection('datasets').doc(id).get()\n return dataset.exists ? recordOf(dataset) : null\n },\n\n // The late photo pass of an AI site start (AGL-3988): a list's covers\n // given photos once its pages are built. Only what a person could type\n // in the record's card is stored, under the same member rules as `write`.\n reviseRecords: async (request): Promise<PluginDraftRecordsRevise> => {\n const refused = await early(request)\n if (refused) return { ok: false, ...refused }\n const orders = [...new Set(request.records.map((record) => record.order))]\n .filter((order) => Number.isInteger(order) && order >= 0)\n .slice(0, DATASET_DRAFT_RECORDS_MAX)\n if (!orders.length) return { ok: true, changed: 0 }\n const db = firestore()\n const datasetRef = db.collection('orgs').doc(request.orgId).collection('datasets').doc(request.id)\n return db.runTransaction(async (tx): Promise<PluginDraftRecordsRevise> => {\n const dataset = await tx.get(datasetRef)\n const model = dataset.get('model') as DatasetModel | undefined\n if (!dataset.exists || !model?.order) return { ok: false, status: 404, error: 'The dataset is no longer there' }\n const rows = await tx.get(datasetRef.collection('records').where('order', 'in', orders))\n let changed = 0\n for (const revision of request.records) {\n const row = rows.docs.find((doc) => doc.get('order') === revision.order)\n if (!row) continue\n const stored = (row.get('values') ?? {}) as Record<string, unknown>\n // A member changed it since: theirs stands.\n if (Object.entries(revision.where ?? {}).some(([id, value]) => stored[id] !== value)) continue\n // Only the list's own fields are changed; a revision naming none of them changes nothing.\n const named = Object.entries(revision.values).filter(([id]) => model.fields[id])\n if (!named.length) continue\n const input: Record<string, unknown> = { ...stored }\n for (const [id, value] of named) input[id] = seedValue(value)\n const values = coerceDocumentValues(model, input)\n for (const [id, value] of Object.entries(values)) {\n if (value === '' || value === null || value === undefined || (Array.isArray(value) && !value.length)) delete values[id]\n }\n const errors = validateDocument(model, values)\n const badPhoto = Object.entries(values).some(\n ([id, value]) => model.fields[id]?.customType === DATASET_IMAGE_FIELD_TYPE && !isDatasetImageValue(value),\n )\n if (Object.keys(errors).length || badPhoto) continue\n tx.update(row.ref, { values, ...datasetIntegrityUpdate(model, values, FieldValue.delete()), updatedAt: request.now })\n changed += 1\n }\n return { ok: true, changed }\n })\n },\n\n write: async (request): Promise<PluginDraftWrite> => {\n // The request's name is the one asked for; the content's stands in.\n const asked = line(request.name)\n const read = readDatasetDraftContent(asked ? { ...request.content, name: asked } : request.content)\n if (read.ok === false) return { ok: false, status: 400, error: read.problems[0] }\n const refused = await early(request)\n if (refused) return { ok: false, ...refused }\n const db = firestore()\n const orgRef = db.collection('orgs').doc(request.orgId)\n const datasets = orgRef.collection('datasets')\n const datasetRef = datasets.doc(request.id)\n const { name, model, records, addressField } = read.value\n const recordQuota = checkQuota(request.org as never, 'recordsPerDataset', Math.max(0, records.length - 1))\n if (records.length && !recordQuota.allowed) {\n return { ok: false, status: 403, error: datasetDraftRecordLimitRefusal(recordQuota.limit) }\n }\n if (records.length && (await storageFull(request.org, orgRef))) {\n return { ok: false, status: 403, error: DATASET_DRAFT_STORAGE_REFUSAL }\n }\n const visibleTo = scopeOf(request)\n // Minted before the transaction, so a retried attempt writes the same rows.\n const recordIds = records.map(() => createResourceUid())\n return db.runTransaction(async (tx): Promise<PluginDraftWrite> => {\n // Every read before any write, which Firestore requires.\n const existing = await tx.get(datasetRef)\n // Asked again under the same id: the dataset it already wrote.\n if (existing.exists) return { ok: true, replayed: true, ...recordOf(existing) }\n const live = (await tx.get(datasets.count())).data().count\n const quota = checkDatasetQuota(request.org as never, Number(live) || 0)\n if (!quota.allowed) return { ok: false, status: 403, error: datasetDraftLimitRefusal(quota) }\n tx.create(datasetRef, {\n displayName: name,\n fields: [...model.order],\n model,\n ...newResourceScopeFields(visibleTo),\n createdAt: request.now,\n createdBy: request.uid,\n })\n records.forEach((values, order) => {\n tx.create(datasetRef.collection('records').doc(recordIds[order]), {\n values,\n ...datasetIntegrityFields(model, values),\n order,\n createdAt: request.now,\n updatedAt: request.now,\n })\n })\n return {\n ok: true,\n replayed: false,\n id: request.id,\n name,\n versionId: null,\n facts: factsOf(model, records.length, addressField) as unknown as Readonly<Record<string, unknown>>,\n }\n })\n },\n }\n}\n\n/**\n * The scope a dataset drafted for a site takes: that site alone (AGL-4003).\n *\n * A drafted dataset is the site's own content, made for it by Aglyn AI, so it\n * is shared with that site and no other, whatever the workspace's Default\n * sharing says for the datasets a person makes on the Data page. Deleting the\n * site erases it with its records (`eraseHost`), where a dataset shared with\n * every site outlived its site: 53 did in one workspace. A member can share it\n * with more sites on the Data page.\n */\nfunction scopeOf(context: Pick<PluginDraftContext, 'hostId'>) {\n return [hostScopeToken(context.hostId)]\n}\n\nfunction recordOf(dataset: FirebaseFirestore.DocumentSnapshot): PluginDraftRecord {\n const data = (dataset.data() ?? {}) as { displayName?: unknown; model?: DatasetModel }\n const model: DatasetModel = data.model?.order ? data.model : { fields: {}, order: [] }\n const addressField = model.order.find((id) => model.fields[id]?.customType === RECORD_PAGE_ADDRESS_FIELD_TYPE) ?? null\n return {\n id: dataset.id,\n name: String(data.displayName ?? ''),\n versionId: null,\n // A replay reports the fields; how many records it was seeded with is the first write's to say.\n facts: factsOf(model, 0, addressField) as unknown as Readonly<Record<string, unknown>>,\n }\n}\n\nexport const datasetDraftWriter = createDatasetDraftWriter()\n\n/**\n * Registers the writer; the console surface calls it, since only the console\n * runs AI jobs (AGL-3026). Idempotent: a second call replaces the first.\n */\nexport function registerDatasetDraftWriter(): void {\n registerPluginResourceDraftWriter(DATASET_DRAFT_RESOURCE, datasetDraftWriter, { pluginId: BUNDLE_ID })\n}\n"],"names":["createResourceUid","memberCanSee","checkDatasetQuota","checkEntitlement","checkQuota","hostScopeToken","newResourceScopeFields","registerPluginResourceDraftWriter","firebaseAdmin","FieldValue","dataStorageRefusal","memberHasOrgPermission","resolveOrgIdForHost","resolveOrgMembership","isServerReleaseFlagOnForOrg","BUNDLE_ID","coerceDocumentValues","datasetIntegrityFields","datasetIntegrityUpdate","defaultDatasetFieldId","validateDocument","DATASET_IMAGE_FIELD_TYPE","isDatasetImageValue","DATASET_PAGE_FIELD_TYPE","isDatasetPageValue","RECORD_PAGE_ADDRESS_FIELD_TYPE","RECORD_PAGE_ADDRESS_MAX","uniqueRecordAddresses","DATASET_DRAFT_RESOURCE","DATASET_DRAFT_NAME_MAX","DATASET_DRAFT_FIELDS_MAX","DATASET_DRAFT_FIELD_NAME_MAX","DATASET_DRAFT_RECORDS_MAX","DATASET_DRAFT_VALUE_MAX","DATASET_DRAFT_LIST_MAX","DATASET_DRAFT_FIELD_TYPES","text","number","integer","boolean","list","image","page","DRAFT_TYPES","Object","keys","DATASET_DRAFT_ROLE_REFUSAL","DATASET_DRAFT_PERMISSION_REFUSAL","DATASET_DRAFT_PLAN_REFUSAL","DATASET_DRAFT_RELEASE_REFUSAL","DATASET_DRAFT_SCOPE_REFUSAL","DATASET_DRAFT_STORAGE_REFUSAL","datasetDraftLimitRefusal","quota","upgradeRequired","limit","addonPriceUsd","datasetDraftRecordLimitRefusal","isRecord","value","Array","isArray","line","replace","trim","seedValue","slice","map","entry","filter","undefined","readDatasetDraftContent","content","problems","name","push","length","rawFields","model","fields","order","byName","Map","raw","fieldName","rawType","includes","join","has","toLowerCase","id","Set","type","customType","required","set","addressField","rawAddress","sourceId","get","slugFrom","rawRecords","records","forEach","index","input","key","entries","values","errors","field","error","ok","source","assigned","String","address","imageFieldOf","find","factsOf","imageField","checkDatasetDraftContent","read","facts","WRITER_ROLES","platformMember","uid","orgId","member","membership","role","canManageData","createDatasetDraftWriter","deps","firestore","app","orgIdForHost","hostId","memberOf","released","storageFull","org","orgRef","Boolean","early","context","status","scopeOf","refusal","refused","used","collection","doc","count","data","Number","allowed","check","dataset","exists","recordOf","reviseRecords","request","orders","record","isInteger","changed","db","datasetRef","runTransaction","tx","rows","where","revision","row","docs","stored","some","named","badPhoto","update","ref","delete","updatedAt","now","write","asked","datasets","recordQuota","Math","max","visibleTo","recordIds","existing","replayed","live","create","displayName","createdAt","createdBy","versionId","datasetDraftWriter","registerDatasetDraftWriter","pluginId"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,YAAY,QAAQ,uCAAsC;AACnE,SAASC,iBAAiB,EAAEC,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YACF;QACF;IACF;AACF;AAEA;;;;;;;;;CASC,GACD,SAASmD,QAAQF,OAA2C;IAC1D,OAAO;QAAC5I,eAAe4I,QAAQR,MAAM;KAAE;AACzC;AAEA,SAASuB,SAASF,OAA2C;QAC7CA,eAEOhF,mBAGN4E;QAJaA;IAD5B,MAAMA,QAAQI,gBAAAA,QAAQJ,IAAI,cAAZI,gBAAkB,CAAC;IACjC,MAAMhF,QAAsB4E,EAAAA,cAAAA,KAAK5E,KAAK,qBAAV4E,YAAY1E,KAAK,IAAG0E,KAAK5E,KAAK,GAAG;QAAEC,QAAQ,CAAC;QAAGC,OAAO,EAAE;IAAC;IACrF,MAAMgB,gBAAelB,oBAAAA,MAAME,KAAK,CAACsC,IAAI,CAAC,CAAC5B;YAAOZ;eAAAA,EAAAA,mBAAAA,MAAMC,MAAM,CAACW,GAAG,qBAAhBZ,iBAAkBe,UAAU,MAAKpE;kBAA1DqD,oBAA6F;IAClH,OAAO;QACLY,IAAIoE,QAAQpE,EAAE;QACdhB,MAAMyC,QAAOuC,oBAAAA,KAAK2C,WAAW,YAAhB3C,oBAAoB;QACjC8C,WAAW;QACX,gGAAgG;QAChG7E,OAAOJ,QAAQzC,OAAO,GAAGkB;IAC3B;AACF;AAEA,OAAO,MAAMyG,qBAAqBrE,2BAA0B;AAE5D;;;CAGC,GACD,OAAO,SAASsE;IACdnM,kCAAkCqB,wBAAwB6K,oBAAoB;QAAEE,UAAU5L;IAAU;AACtG"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/server/dataset-drafts.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport { memberCanSee } from '@aglyn/aglyn/app-utils/organizations'\nimport { checkDatasetQuota, checkEntitlement, checkQuota } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { hostScopeToken, newResourceScopeFields } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport {\n registerPluginResourceDraftWriter,\n type PluginDraftCheck,\n type PluginDraftContext,\n type PluginDraftRecord,\n type PluginDraftRecordsRevise,\n type PluginDraftRefusal,\n type PluginDraftWrite,\n type PluginResourceDraftWriter,\n} from '@aglyn/aglyn/plugin-manager/plugin-resource-drafts'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { dataStorageRefusal } from '@aglyn/tenant-data-admin/server/data-storage-gate'\nimport {\n memberHasOrgPermission,\n resolveOrgIdForHost,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin/server/organizations'\nimport { isServerReleaseFlagOnForOrg } from '@aglyn/tenant-data-admin/server/release-flags'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport {\n coerceDocumentValues,\n datasetIntegrityFields,\n datasetIntegrityUpdate,\n defaultDatasetFieldId,\n validateDocument,\n type DatasetFieldType,\n type DatasetModel,\n} from '../model/dataset-models'\nimport { DATASET_IMAGE_FIELD_TYPE, isDatasetImageValue } from '../model/dataset-image-field'\nimport { DATASET_PAGE_FIELD_TYPE, isDatasetPageValue } from '../model/dataset-page-field'\nimport {\n RECORD_PAGE_ADDRESS_FIELD_TYPE,\n RECORD_PAGE_ADDRESS_MAX,\n uniqueRecordAddresses,\n} from '../record-pages/record-pages'\n\n/**\n * A DATASET ANOTHER PLUGIN ASKS FOR (AGL-3616).\n *\n * The draft writer this plugin registers for the `dataset` resource on the\n * core's resource-drafts seam. Aglyn AI builds a menu, a team, a list of\n * services or a portfolio as a dataset, the way the docs teach a person to,\n * and asks for the writer by name, so every rule is this plugin's:\n *\n * - THE DOCUMENT is the one the Data card's create makes: a display name,\n * the flat `fields` mirror and a typed model, shared with the site it is\n * made for and no other (AGL-4003), and the\n * seeded records, each with the integrity and filter index every record\n * write carries. Where a record page is wanted the model gains a \"Page\n * address\" field that fills from a text field, and every seeded record a\n * unique address (`uniqueRecordAddresses`), so the member's Record pages\n * save has nothing left to fill.\n * - THE ROOM is `datasetsPerOrg` (add-ons included, `checkDatasetQuota`),\n * counted INSIDE the transaction that creates, as the datasets route\n * counts it; the records are held to `recordsPerDataset` and the dataset\n * storage band.\n * - THE PLAN is `dataStore` (Starter and up), THE FLAG `release_data_store`,\n * and THE ROLE an org member who may edit org data (owner, admin or\n * editor) with `data.manage`, whose access reaches the site — refused in\n * the route's own words.\n * - THE CHECK holds every record to the model it is written under\n * (`validateDocument`), so what is seeded is what a person could type.\n * - A PHOTO is an `image` field (AGL-3616): text storage riding the\n * \"Image\" custom type, each value an address the site's Image element\n * shows (`isDatasetImageValue`), so a portfolio's pieces or a team keep\n * the photo the page that lists them binds.\n * - A PAGE is a `page` field (AGL-3763): text storage riding the \"Page\"\n * custom type, each value one of the site's pages as `screen:{id}`\n * (`isDatasetPageValue`), which a Button or Link binds.\n * - A SAMPLE is a seeded record the caller marks as one (`samples`,\n * AGL-4065): a site start whose brief gave no entries for a list seeds it\n * with complete-looking samples, and the record carries `sample: true`\n * beside its values, which the Data card shows as a sample to replace\n * and a published page never reads. Saving the record in Data makes it\n * the owner's.\n *\n * Nothing is published. The writer touches the one new dataset and its\n * records; a page shows them only where a person (or a job's draft page)\n * places a repeat over it.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** The resource name this writer is registered under. */\nexport const DATASET_DRAFT_RESOURCE = 'dataset'\n\n/** The longest dataset name, as the datasets route keeps it. */\nexport const DATASET_DRAFT_NAME_MAX = 120\n/** The most fields a drafted dataset is made with, and the longest name. */\nexport const DATASET_DRAFT_FIELDS_MAX = 16\nexport const DATASET_DRAFT_FIELD_NAME_MAX = 60\n/** The most records a draft is seeded with. */\nexport const DATASET_DRAFT_RECORDS_MAX = 24\n/** The longest text value a seeded record keeps. */\nexport const DATASET_DRAFT_VALUE_MAX = 2_000\n/** The most entries a seeded list value keeps. */\nexport const DATASET_DRAFT_LIST_MAX = 12\n\n/**\n * The field types a caller names, in words a person reads, and the type\n * each one is stored as. A date or a time is written as text the way a\n * visitor reads it (\"Saturday 8 November, 7 pm\"): a stored timestamp renders\n * as a number in a repeat's `{{item.<field>}}`. An image is text holding a\n * photo's address, under the \"Image\" custom type (AGL-3616), and a page is\n * text holding a page's reference, under the \"Page\" custom type (AGL-3763).\n */\nexport const DATASET_DRAFT_FIELD_TYPES = {\n text: 'text',\n number: 'float',\n integer: 'int32',\n boolean: 'bool',\n list: 'sorted',\n image: 'text',\n page: 'text',\n} as const satisfies Record<string, DatasetFieldType>\n\nexport type DatasetDraftFieldType = keyof typeof DATASET_DRAFT_FIELD_TYPES\n\nconst DRAFT_TYPES = Object.keys(DATASET_DRAFT_FIELD_TYPES) as DatasetDraftFieldType[]\n\n/** The datasets route's refusals, word for word. */\nexport const DATASET_DRAFT_ROLE_REFUSAL = 'Editing org data requires the editor role'\nexport const DATASET_DRAFT_PERMISSION_REFUSAL = 'Your organization role does not allow editing organization data'\nexport const DATASET_DRAFT_PLAN_REFUSAL = 'Datasets require a Starter plan or higher'\nexport const DATASET_DRAFT_RELEASE_REFUSAL = 'Datasets are not available for this workspace yet'\nexport const DATASET_DRAFT_SCOPE_REFUSAL = 'Your access to this organization does not reach that site'\nexport const DATASET_DRAFT_STORAGE_REFUSAL = 'Dataset storage is full on this plan — upgrade in Billing'\n\n/** The route's refusal at the plan's dataset allowance. */\nexport function datasetDraftLimitRefusal(quota: ReturnType<typeof checkDatasetQuota>): string {\n return quota.upgradeRequired\n ? `Dataset limit reached (${quota.limit}) — upgrade in Billing`\n : `Dataset limit reached (${quota.limit}) — add extra datasets for $${quota.addonPriceUsd}/mo each or upgrade in Billing`\n}\n\n/** The route's refusal at the plan's record allowance. */\nexport function datasetDraftRecordLimitRefusal(limit: number): string {\n return `Record limit reached (${limit}) — upgrade in Billing`\n}\n\n/** One field as a caller names it. */\nexport interface DatasetDraftField {\n name: string\n /** Absent is text. */\n type?: DatasetDraftFieldType\n required?: boolean\n}\n\n/**\n * What a caller sends as `content`. Each record's values are keyed by the\n * field NAME the caller gave, since the caller has no ids yet; the writer\n * mints the ids (`roast_preference` from \"Roast preference\").\n */\nexport interface DatasetDraftContent {\n /** The dataset's name; the request's `name` stands in when absent. */\n name?: string\n fields: DatasetDraftField[]\n records?: Array<Record<string, unknown>>\n /**\n * A text field, by name, a \"Page address\" field fills from (AGL-3475):\n * asked for where a record page will show each record at its own address.\n */\n pageAddressFrom?: string\n /**\n * Which seeded records are samples for the owner to replace, by position\n * as `records` (AGL-4065). Absent, or false, is a record of the owner's.\n */\n samples?: boolean[]\n}\n\n/** What the writer reports about a dataset. */\nexport interface DatasetDraftFacts {\n fields: Array<{ id: string; name: string; type: DatasetFieldType }>\n records: number\n /** The page-address field's id, where the dataset has one. */\n addressField: string | null\n /** The first photo field's id, where the dataset has one (AGL-3616). */\n imageField: string | null\n}\n\n/** The draft as the writer will store it. */\nexport interface DatasetDraftRead {\n name: string\n model: DatasetModel\n /** Each record's values by field id, coerced and addressed. */\n records: Array<Record<string, unknown>>\n addressField: string | null\n /** Which records are samples, by position (AGL-4065); absent where none is. */\n samples?: boolean[]\n}\n\nexport type DatasetDraftContentRead =\n | { ok: true; value: DatasetDraftRead }\n | { ok: false; problems: string[] }\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** Text on one line: controls and runs of space folded to one space. */\nfunction line(value: unknown): string {\n return typeof value === 'string' ? value.replace(/[\\p{Cc}\\s]+/gu, ' ').trim() : ''\n}\n\n/** A value as a seeded record keeps it, before the model coerces it. */\nfunction seedValue(value: unknown): unknown {\n if (typeof value === 'string') return value.replace(/\\r\\n?/g, '\\n').trim().slice(0, DATASET_DRAFT_VALUE_MAX)\n if (Array.isArray(value)) {\n return value\n .map((entry) => (typeof entry === 'string' ? line(entry) : entry))\n .filter((entry) => entry !== '' && entry !== null && entry !== undefined)\n .slice(0, DATASET_DRAFT_LIST_MAX)\n }\n return value\n}\n\n/** The content as the writer reads it, or every problem that stops it. Pure. */\nexport function readDatasetDraftContent(content: Readonly<Record<string, unknown>>): DatasetDraftContentRead {\n const problems: string[] = []\n const name = line(content['name'])\n if (!name) problems.push('The dataset needs a name')\n else if (name.length > DATASET_DRAFT_NAME_MAX) {\n problems.push(`The name is longer than ${DATASET_DRAFT_NAME_MAX} characters`)\n }\n\n const rawFields = content['fields']\n const model: DatasetModel = { fields: {}, order: [] }\n /** Field name, lowercased → id. */\n const byName = new Map<string, string>()\n if (!Array.isArray(rawFields) || !rawFields.length) {\n problems.push('The dataset needs at least one field')\n } else if (rawFields.length > DATASET_DRAFT_FIELDS_MAX) {\n problems.push(`A dataset is made with at most ${DATASET_DRAFT_FIELDS_MAX} fields`)\n } else {\n for (const raw of rawFields) {\n const fieldName = isRecord(raw) ? line(raw['name']) : ''\n const rawType = (isRecord(raw) ? raw['type'] : undefined) ?? 'text'\n if (!fieldName) {\n problems.push('Each field needs a name')\n continue\n }\n if (fieldName.length > DATASET_DRAFT_FIELD_NAME_MAX) {\n problems.push(`The field \"${fieldName.slice(0, 20)}…\" has a name longer than ${DATASET_DRAFT_FIELD_NAME_MAX} characters`)\n continue\n }\n if (!(DRAFT_TYPES as readonly unknown[]).includes(rawType)) {\n problems.push(`The field \"${fieldName}\" is one of ${DRAFT_TYPES.join(', ')}`)\n continue\n }\n if (byName.has(fieldName.toLowerCase())) {\n problems.push(`Two fields are both called \"${fieldName}\"`)\n continue\n }\n const id = defaultDatasetFieldId(fieldName, new Set(model.order))\n if (!id) {\n problems.push(`The field \"${fieldName}\" needs a name with a letter in it`)\n continue\n }\n model.fields[id] = {\n name: fieldName,\n type: DATASET_DRAFT_FIELD_TYPES[rawType as DatasetDraftFieldType],\n ...(rawType === 'image' ? { customType: DATASET_IMAGE_FIELD_TYPE } : {}),\n ...(rawType === 'page' ? { customType: DATASET_PAGE_FIELD_TYPE } : {}),\n ...(isRecord(raw) && raw['required'] === true ? { required: true } : {}),\n }\n model.order.push(id)\n byName.set(fieldName.toLowerCase(), id)\n }\n }\n\n // The page address: a text field the address fills from, once.\n let addressField: string | null = null\n const rawAddress = content['pageAddressFrom']\n if (rawAddress !== undefined && rawAddress !== null && rawAddress !== '') {\n const sourceId = byName.get(line(rawAddress).toLowerCase())\n if (!sourceId || model.fields[sourceId]?.type !== 'text' || model.fields[sourceId]?.customType) {\n problems.push('A page address fills from one of the dataset’s text fields')\n } else {\n addressField = defaultDatasetFieldId('slug', new Set(model.order))\n model.fields[addressField] = {\n name: 'Page address',\n type: 'text',\n customType: RECORD_PAGE_ADDRESS_FIELD_TYPE,\n slugFrom: sourceId,\n }\n model.order.push(addressField)\n }\n }\n\n const rawRecords = content['records'] ?? []\n const records: Array<Record<string, unknown>> = []\n if (!Array.isArray(rawRecords)) {\n problems.push('Records are a list of values by field name')\n } else if (rawRecords.length > DATASET_DRAFT_RECORDS_MAX) {\n problems.push(`A dataset is seeded with at most ${DATASET_DRAFT_RECORDS_MAX} records`)\n } else if (!problems.length) {\n rawRecords.forEach((raw, index) => {\n if (!isRecord(raw)) {\n problems.push(`Record ${index + 1} is not a set of values`)\n return\n }\n const input: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(raw)) {\n const id = byName.get(line(key).toLowerCase())\n if (!id) {\n problems.push(`Record ${index + 1} names \"${line(key).slice(0, 40)}\", which is not a field`)\n continue\n }\n input[id] = seedValue(value)\n }\n const values = coerceDocumentValues(model, input)\n // An empty value is no value: it is not stored, as the card stores none.\n for (const [id, value] of Object.entries(values)) {\n if (value === '' || value === null || value === undefined || (Array.isArray(value) && !value.length)) {\n delete values[id]\n }\n }\n const errors = validateDocument(model, values)\n // A photo is an address the site's Image shows, whether or not the\n // \"Image\" type's check is registered in this process (AGL-3616).\n for (const [id, value] of Object.entries(values)) {\n const field = model.fields[id]\n if (field?.customType === DATASET_IMAGE_FIELD_TYPE && !errors[id] && !isDatasetImageValue(value)) {\n errors[id] = `${field.name} is not a photo from the media library or an https link`\n }\n // …and a page is one of the site's pages, by reference (AGL-3763).\n if (field?.customType === DATASET_PAGE_FIELD_TYPE && !errors[id] && !isDatasetPageValue(value)) {\n errors[id] = `${field.name} is not one of the site’s pages`\n }\n }\n for (const error of Object.values(errors)) problems.push(`Record ${index + 1}: ${error}`)\n if (!Object.keys(values).length) problems.push(`Record ${index + 1} has no values`)\n records.push(values)\n })\n }\n // Which records are samples (AGL-4065): true or false, one a record at most.\n const rawSamples = content['samples']\n if (rawSamples !== undefined && (!Array.isArray(rawSamples) || rawSamples.some((entry) => typeof entry !== 'boolean'))) {\n problems.push('Samples are a list of true or false, one a record')\n } else if (Array.isArray(rawSamples) && rawSamples.length > records.length) {\n problems.push('Samples name more records than the dataset is seeded with')\n }\n const samples = Array.isArray(rawSamples) && rawSamples.some((entry) => entry === true) ? records.map((_values, index) => rawSamples[index] === true) : null\n if (problems.length) return { ok: false, problems: [...new Set(problems)] }\n\n // Every seeded record its own address, unique within the dataset.\n if (addressField) {\n const source = model.fields[addressField]?.slugFrom as string\n const assigned = uniqueRecordAddresses(records.map((values, index) => ({ id: String(index), source: values[source] })))\n records.forEach((values, index) => {\n const address = assigned.get(String(index))\n if (address) values[addressField as string] = address.slice(0, RECORD_PAGE_ADDRESS_MAX)\n })\n }\n return { ok: true, value: { name, model, records, addressField, ...(samples ? { samples } : {}) } }\n}\n\n/** The first photo field of a model, by id. */\nfunction imageFieldOf(model: DatasetModel): string | null {\n return model.order.find((id) => model.fields[id]?.customType === DATASET_IMAGE_FIELD_TYPE) ?? null\n}\n\nfunction factsOf(model: DatasetModel, records: number, addressField: string | null): DatasetDraftFacts {\n return {\n fields: model.order.map((id) => ({ id, name: model.fields[id]?.name ?? id, type: model.fields[id]?.type ?? 'text' })),\n records,\n addressField,\n imageField: imageFieldOf(model),\n }\n}\n\n/** Whether content is a dataset this plugin would store, with what it says about it. Pure. */\nexport function checkDatasetDraftContent(content: Readonly<Record<string, unknown>>): PluginDraftCheck {\n const read = readDatasetDraftContent(content)\n if (read.ok === false) return read\n return {\n ok: true,\n facts: factsOf(read.value.model, read.value.records.length, read.value.addressField) as unknown as Readonly<\n Record<string, unknown>\n >,\n }\n}\n\n/** Who the member is in the org, as the writer asks: their role, and whether they may manage data. */\nexport interface DatasetDraftMember {\n role: string\n canManageData: boolean\n /** The membership itself, for whether their access reaches a site. */\n member: Readonly<Record<string, unknown>>\n}\n\nexport interface DatasetDraftWriterDeps {\n /** The Admin SDK handle; specs hand in a double. */\n firestore?: () => Firestore\n /** The org a site belongs to; the platform's lookup otherwise. */\n orgIdForHost?: (hostId: string) => Promise<string | null>\n /** The member, or `null` when they are not one; the platform's otherwise. */\n member?: (uid: string, orgId: string) => Promise<DatasetDraftMember | null>\n /** Whether the data store is released for the org; the platform's flag otherwise. */\n released?: (orgId: string) => Promise<boolean>\n /** Whether dataset bytes may grow; the platform's band otherwise. */\n storageFull?: (org: unknown, orgRef: FirebaseFirestore.DocumentReference) => Promise<boolean>\n}\n\n/** Roles allowed to create org data — the datasets route's, mirroring the rules' `canWriteOrgData()`. */\nconst WRITER_ROLES = new Set(['owner', 'admin', 'editor'])\n\nasync function platformMember(uid: string, orgId: string): Promise<DatasetDraftMember | null> {\n const membership = await resolveOrgMembership(uid, orgId)\n const member = membership?.member\n if (!member) return null\n return {\n role: String(member.role ?? ''),\n canManageData: await memberHasOrgPermission(orgId, member, 'data.manage'),\n member: member as unknown as Readonly<Record<string, unknown>>,\n }\n}\n\nexport function createDatasetDraftWriter(deps: DatasetDraftWriterDeps = {}): PluginResourceDraftWriter {\n const firestore = deps.firestore ?? (() => firebaseAdmin.app().firestore() as unknown as Firestore)\n const orgIdForHost = deps.orgIdForHost ?? ((hostId: string) => resolveOrgIdForHost(hostId))\n const memberOf = deps.member ?? platformMember\n const released = deps.released ?? ((orgId: string) => isServerReleaseFlagOnForOrg('release_data_store', orgId))\n const storageFull =\n deps.storageFull ?? (async (org: unknown, orgRef: FirebaseFirestore.DocumentReference) => Boolean(await dataStorageRefusal(org, orgRef)))\n\n /** Everything but the room: the site is the org's, the member's role, the flag, the plan, the scope. */\n const early = async (context: PluginDraftContext): Promise<PluginDraftRefusal | null> => {\n if ((await orgIdForHost(context.hostId)) !== context.orgId) return { status: 404, error: 'Unknown site' }\n const member = await memberOf(context.uid, context.orgId)\n if (!member || !WRITER_ROLES.has(member.role)) return { status: 403, error: DATASET_DRAFT_ROLE_REFUSAL }\n if (!member.canManageData) return { status: 403, error: DATASET_DRAFT_PERMISSION_REFUSAL }\n if (!(await released(context.orgId))) return { status: 403, error: DATASET_DRAFT_RELEASE_REFUSAL }\n if (!checkEntitlement(context.org as never, 'dataStore')) return { status: 403, error: DATASET_DRAFT_PLAN_REFUSAL }\n // A member scoped to some sites must be able to see what they create.\n if (!memberCanSee(member.member as never, scopeOf(context))) {\n return { status: 403, error: DATASET_DRAFT_SCOPE_REFUSAL }\n }\n return null\n }\n\n return {\n refusal: async (context) => {\n const refused = await early(context)\n if (refused) return refused\n const used = (await firestore().collection('orgs').doc(context.orgId).collection('datasets').count().get()).data().count\n const quota = checkDatasetQuota(context.org as never, Number(used) || 0)\n return quota.allowed ? null : { status: 403, error: datasetDraftLimitRefusal(quota) }\n },\n\n check: (content) => checkDatasetDraftContent(content),\n\n read: async ({ hostId, id }) => {\n const orgId = await orgIdForHost(hostId)\n if (!orgId) return null\n const dataset = await firestore().collection('orgs').doc(orgId).collection('datasets').doc(id).get()\n return dataset.exists ? recordOf(dataset) : null\n },\n\n // The late photo pass of an AI site start (AGL-3988): a list's covers\n // given photos once its pages are built. Only what a person could type\n // in the record's card is stored, under the same member rules as `write`.\n reviseRecords: async (request): Promise<PluginDraftRecordsRevise> => {\n const refused = await early(request)\n if (refused) return { ok: false, ...refused }\n const orders = [...new Set(request.records.map((record) => record.order))]\n .filter((order) => Number.isInteger(order) && order >= 0)\n .slice(0, DATASET_DRAFT_RECORDS_MAX)\n if (!orders.length) return { ok: true, changed: 0 }\n const db = firestore()\n const datasetRef = db.collection('orgs').doc(request.orgId).collection('datasets').doc(request.id)\n return db.runTransaction(async (tx): Promise<PluginDraftRecordsRevise> => {\n const dataset = await tx.get(datasetRef)\n const model = dataset.get('model') as DatasetModel | undefined\n if (!dataset.exists || !model?.order) return { ok: false, status: 404, error: 'The dataset is no longer there' }\n const rows = await tx.get(datasetRef.collection('records').where('order', 'in', orders))\n let changed = 0\n for (const revision of request.records) {\n const row = rows.docs.find((doc) => doc.get('order') === revision.order)\n if (!row) continue\n const stored = (row.get('values') ?? {}) as Record<string, unknown>\n // A member changed it since: theirs stands.\n if (Object.entries(revision.where ?? {}).some(([id, value]) => stored[id] !== value)) continue\n // Only the list's own fields are changed; a revision naming none of them changes nothing.\n const named = Object.entries(revision.values).filter(([id]) => model.fields[id])\n if (!named.length) continue\n const input: Record<string, unknown> = { ...stored }\n for (const [id, value] of named) input[id] = seedValue(value)\n const values = coerceDocumentValues(model, input)\n for (const [id, value] of Object.entries(values)) {\n if (value === '' || value === null || value === undefined || (Array.isArray(value) && !value.length)) delete values[id]\n }\n const errors = validateDocument(model, values)\n const badPhoto = Object.entries(values).some(\n ([id, value]) => model.fields[id]?.customType === DATASET_IMAGE_FIELD_TYPE && !isDatasetImageValue(value),\n )\n if (Object.keys(errors).length || badPhoto) continue\n tx.update(row.ref, { values, ...datasetIntegrityUpdate(model, values, FieldValue.delete()), updatedAt: request.now })\n changed += 1\n }\n return { ok: true, changed }\n })\n },\n\n write: async (request): Promise<PluginDraftWrite> => {\n // The request's name is the one asked for; the content's stands in.\n const asked = line(request.name)\n const read = readDatasetDraftContent(asked ? { ...request.content, name: asked } : request.content)\n if (read.ok === false) return { ok: false, status: 400, error: read.problems[0] }\n const refused = await early(request)\n if (refused) return { ok: false, ...refused }\n const db = firestore()\n const orgRef = db.collection('orgs').doc(request.orgId)\n const datasets = orgRef.collection('datasets')\n const datasetRef = datasets.doc(request.id)\n const { name, model, records, addressField, samples } = read.value\n const recordQuota = checkQuota(request.org as never, 'recordsPerDataset', Math.max(0, records.length - 1))\n if (records.length && !recordQuota.allowed) {\n return { ok: false, status: 403, error: datasetDraftRecordLimitRefusal(recordQuota.limit) }\n }\n if (records.length && (await storageFull(request.org, orgRef))) {\n return { ok: false, status: 403, error: DATASET_DRAFT_STORAGE_REFUSAL }\n }\n const visibleTo = scopeOf(request)\n // Minted before the transaction, so a retried attempt writes the same rows.\n const recordIds = records.map(() => createResourceUid())\n return db.runTransaction(async (tx): Promise<PluginDraftWrite> => {\n // Every read before any write, which Firestore requires.\n const existing = await tx.get(datasetRef)\n // Asked again under the same id: the dataset it already wrote.\n if (existing.exists) return { ok: true, replayed: true, ...recordOf(existing) }\n const live = (await tx.get(datasets.count())).data().count\n const quota = checkDatasetQuota(request.org as never, Number(live) || 0)\n if (!quota.allowed) return { ok: false, status: 403, error: datasetDraftLimitRefusal(quota) }\n tx.create(datasetRef, {\n displayName: name,\n fields: [...model.order],\n model,\n ...newResourceScopeFields(visibleTo),\n createdAt: request.now,\n createdBy: request.uid,\n })\n records.forEach((values, order) => {\n tx.create(datasetRef.collection('records').doc(recordIds[order]), {\n values,\n ...datasetIntegrityFields(model, values),\n // A sample for the owner to replace (AGL-4065), beside its values: no page reads it.\n ...(samples?.[order] ? { sample: true } : {}),\n order,\n createdAt: request.now,\n updatedAt: request.now,\n })\n })\n return {\n ok: true,\n replayed: false,\n id: request.id,\n name,\n versionId: null,\n facts: factsOf(model, records.length, addressField) as unknown as Readonly<Record<string, unknown>>,\n }\n })\n },\n }\n}\n\n/**\n * The scope a dataset drafted for a site takes: that site alone (AGL-4003).\n *\n * A drafted dataset is the site's own content, made for it by Aglyn AI, so it\n * is shared with that site and no other, whatever the workspace's Default\n * sharing says for the datasets a person makes on the Data page. Deleting the\n * site erases it with its records (`eraseHost`), where a dataset shared with\n * every site outlived its site: 53 did in one workspace. A member can share it\n * with more sites on the Data page.\n */\nfunction scopeOf(context: Pick<PluginDraftContext, 'hostId'>) {\n return [hostScopeToken(context.hostId)]\n}\n\nfunction recordOf(dataset: FirebaseFirestore.DocumentSnapshot): PluginDraftRecord {\n const data = (dataset.data() ?? {}) as { displayName?: unknown; model?: DatasetModel }\n const model: DatasetModel = data.model?.order ? data.model : { fields: {}, order: [] }\n const addressField = model.order.find((id) => model.fields[id]?.customType === RECORD_PAGE_ADDRESS_FIELD_TYPE) ?? null\n return {\n id: dataset.id,\n name: String(data.displayName ?? ''),\n versionId: null,\n // A replay reports the fields; how many records it was seeded with is the first write's to say.\n facts: factsOf(model, 0, addressField) as unknown as Readonly<Record<string, unknown>>,\n }\n}\n\nexport const datasetDraftWriter = createDatasetDraftWriter()\n\n/**\n * Registers the writer; the console surface calls it, since only the console\n * runs AI jobs (AGL-3026). Idempotent: a second call replaces the first.\n */\nexport function registerDatasetDraftWriter(): void {\n registerPluginResourceDraftWriter(DATASET_DRAFT_RESOURCE, datasetDraftWriter, { pluginId: BUNDLE_ID })\n}\n"],"names":["createResourceUid","memberCanSee","checkDatasetQuota","checkEntitlement","checkQuota","hostScopeToken","newResourceScopeFields","registerPluginResourceDraftWriter","firebaseAdmin","FieldValue","dataStorageRefusal","memberHasOrgPermission","resolveOrgIdForHost","resolveOrgMembership","isServerReleaseFlagOnForOrg","BUNDLE_ID","coerceDocumentValues","datasetIntegrityFields","datasetIntegrityUpdate","defaultDatasetFieldId","validateDocument","DATASET_IMAGE_FIELD_TYPE","isDatasetImageValue","DATASET_PAGE_FIELD_TYPE","isDatasetPageValue","RECORD_PAGE_ADDRESS_FIELD_TYPE","RECORD_PAGE_ADDRESS_MAX","uniqueRecordAddresses","DATASET_DRAFT_RESOURCE","DATASET_DRAFT_NAME_MAX","DATASET_DRAFT_FIELDS_MAX","DATASET_DRAFT_FIELD_NAME_MAX","DATASET_DRAFT_RECORDS_MAX","DATASET_DRAFT_VALUE_MAX","DATASET_DRAFT_LIST_MAX","DATASET_DRAFT_FIELD_TYPES","text","number","integer","boolean","list","image","page","DRAFT_TYPES","Object","keys","DATASET_DRAFT_ROLE_REFUSAL","DATASET_DRAFT_PERMISSION_REFUSAL","DATASET_DRAFT_PLAN_REFUSAL","DATASET_DRAFT_RELEASE_REFUSAL","DATASET_DRAFT_SCOPE_REFUSAL","DATASET_DRAFT_STORAGE_REFUSAL","datasetDraftLimitRefusal","quota","upgradeRequired","limit","addonPriceUsd","datasetDraftRecordLimitRefusal","isRecord","value","Array","isArray","line","replace","trim","seedValue","slice","map","entry","filter","undefined","readDatasetDraftContent","content","problems","name","push","length","rawFields","model","fields","order","byName","Map","raw","fieldName","rawType","includes","join","has","toLowerCase","id","Set","type","customType","required","set","addressField","rawAddress","sourceId","get","slugFrom","rawRecords","records","forEach","index","input","key","entries","values","errors","field","error","rawSamples","some","samples","_values","ok","source","assigned","String","address","imageFieldOf","find","factsOf","imageField","checkDatasetDraftContent","read","facts","WRITER_ROLES","platformMember","uid","orgId","member","membership","role","canManageData","createDatasetDraftWriter","deps","firestore","app","orgIdForHost","hostId","memberOf","released","storageFull","org","orgRef","Boolean","early","context","status","scopeOf","refusal","refused","used","collection","doc","count","data","Number","allowed","check","dataset","exists","recordOf","reviseRecords","request","orders","record","isInteger","changed","db","datasetRef","runTransaction","tx","rows","where","revision","row","docs","stored","named","badPhoto","update","ref","delete","updatedAt","now","write","asked","datasets","recordQuota","Math","max","visibleTo","recordIds","existing","replayed","live","create","displayName","createdAt","createdBy","sample","versionId","datasetDraftWriter","registerDatasetDraftWriter","pluginId"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,YAAY,QAAQ,uCAAsC;AACnE,SAASC,iBAAiB,EAAEC,gBAAgB,EAAEC,UAAU,QAAQ,2CAA0C;AAC1G,SAASC,cAAc,EAAEC,sBAAsB,QA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