@aglyn/plugins-data 1.0.0-beta.233 → 1.0.0-beta.235
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +10 -10
- package/src/lib/components/dataset-record-filter.d.ts +10 -1
- package/src/lib/components/dataset-record-filter.js +12 -1
- package/src/lib/components/dataset-record-filter.js.map +1 -1
- package/src/lib/components/dataset-schema-dialog.component.js +2 -11
- package/src/lib/components/dataset-schema-dialog.component.js.map +1 -1
- package/src/lib/components/host-datasets-card.component.js +19 -32
- package/src/lib/components/host-datasets-card.component.js.map +1 -1
- package/src/lib/model/dataset-model-core.d.ts +299 -0
- package/src/lib/model/dataset-model-core.js +511 -0
- package/src/lib/model/dataset-model-core.js.map +1 -0
- package/src/lib/model/dataset-models.d.ts +2 -231
- package/src/lib/model/dataset-models.js +16 -392
- package/src/lib/model/dataset-models.js.map +1 -1
- package/src/lib/model/dataset-record-delete-plan.d.ts +60 -0
- package/src/lib/model/dataset-record-delete-plan.js +82 -0
- package/src/lib/model/dataset-record-delete-plan.js.map +1 -0
- package/src/lib/model/datasets.d.ts +2 -39
- package/src/lib/model/datasets.js +5 -77
- package/src/lib/model/datasets.js.map +1 -1
- package/src/lib/server/datasets-route.d.ts +3 -0
- package/src/lib/server/datasets-route.js +146 -3
- package/src/lib/server/datasets-route.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/model/dataset-models.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { RepeatRowsModel } from '@aglyn/aglyn/app-utils/expand-repeatables'\nimport { validateCustomFieldValue } from '@aglyn/aglyn/plugin-manager/custom-fields'\n\n/**\n * Dataset models (AGL-177): the runtime promotion of the type-level\n * blueprint in `libs/shared/data/types/src/lib/dod.ts` (kept as the\n * referenced design doc — this module is the single runtime source of\n * truth). A model lives on the dataset doc\n * (`orgs/{orgId}/datasets/{id}.model`) and drives the typed editor, import\n * and site-restore validation, and every record write — the console, `/v1`,\n * a bound form's submission and an automation step — through the shared\n * `validateDocument`/`coerceDocumentValues` pair so they can't disagree. The\n * form and the automation step reach the pair through\n * `prepareDatasetRecordWrite` (AGL-2773).\n *\n * Storage conventions (Firestore-safe): timestamps as epoch millis\n * numbers, coordinates as `{ latitude, longitude }`, `sorted` as arrays,\n * `map` as plain objects, references as target-document id strings.\n */\n\n/**\n * A human field entry from the quick creator: the stable id plus the\n * display name shown in table headers and bindings pickers (AGL-558).\n */\nexport interface DatasetFieldEntry {\n id: string\n name: string\n}\n\n/** Display fallback for raw ids: \"roast_preference\" → \"Roast preference\". */\nexport function humanizeDatasetFieldId(id: string): string {\n const words = id.replace(/_/g, ' ').trim()\n return words ? words.charAt(0).toUpperCase() + words.slice(1) : id\n}\n\n/** dod.ts `FT.Tag` vocabulary plus `reference` (AGL-180 builds on it). */\nexport type DatasetFieldType =\n | 'bool'\n | 'bytes'\n | 'timestamp'\n | 'float'\n | 'int32'\n | 'int64'\n | 'nil'\n | 'text'\n | 'coordinates'\n | 'map'\n | 'sorted'\n | 'reference'\n\nexport const DATASET_FIELD_TYPES: DatasetFieldType[] = [\n 'text',\n 'bool',\n 'int32',\n 'int64',\n 'float',\n 'timestamp',\n 'coordinates',\n 'map',\n 'sorted',\n 'bytes',\n 'nil',\n 'reference',\n]\n\n/** Display names, mirroring dod.ts `lbl`. */\nexport const DATASET_FIELD_TYPE_LABELS: Record<DatasetFieldType, string> = {\n text: 'Text',\n bool: 'Boolean',\n int32: 'Integer',\n int64: 'Big integer',\n float: 'Number',\n timestamp: 'Date & time',\n coordinates: 'Coordinates',\n map: 'Map',\n sorted: 'List',\n bytes: 'Bytes',\n nil: 'Null',\n reference: 'Reference',\n}\n\n/**\n * Plain-JSON validation vocabulary (the dod.ts `Eval` shape, extended\n * with min/max and options, serialized flat instead of enum-keyed).\n */\nexport interface DatasetFieldValidation {\n required?: boolean\n /** Source of a RegExp applied to text values. */\n regex?: string\n /** Numbers/timestamps: value bound. Text: length bound. */\n min?: number\n max?: number\n /** Enum: value must be one of these (text fields). */\n options?: string[]\n}\n\nexport interface DatasetFieldDefinition {\n /**\n * Human-facing display label only. The stable reference id is the KEY in\n * `DatasetModel.fields` (and `order`), NOT this name — bindings resolve\n * `{{item.<fieldId>}}` against that key. The default id is derived from\n * this name once at creation but is user-overridable (AGL-578); renaming\n * the label afterwards never changes the id.\n */\n name: string\n type: DatasetFieldType\n /**\n * Plugin-declared custom type riding this base type (AGL-434) — see\n * plugin-manager/custom-fields. Unknown names degrade to the base type.\n */\n customType?: string\n /**\n * A page-address field's source (AGL-3475): the field an EMPTY address\n * fills in from, once — see `fillRecordAddresses` in `record-pages`.\n * Meaningful only on a field of the page-address custom type.\n */\n slugFrom?: string\n description?: string\n required?: boolean\n /** Default applied by editors when creating documents; never coerced. */\n default?: unknown\n validation?: DatasetFieldValidation\n /**\n * Reference fields (AGL-180): target collection + display field id.\n * `multiple` stores a `sorted` array of FKeys (small-cardinality\n * many-to-many per the dod.ts guidance); `onDelete` is the referenced-\n * document delete policy (default `setNull` — never cascade in v2).\n */\n reference?: {\n datasetId: string\n displayFieldId?: string\n multiple?: boolean\n onDelete?: 'restrict' | 'setNull'\n }\n}\n\nexport interface DatasetModel {\n fields: Record<string, DatasetFieldDefinition>\n /** Field ids in display order. */\n order: string[]\n}\n\n/**\n * Migration shim (v1 → v2): datasets created before models carry flat\n * `fields: string[]` — derive a model where every column is an optional\n * text field whose id is the column name, so the editor and AGL-103\n * bindings keep working on unmigrated docs during rollout.\n */\nexport function deriveModelFromFields(fields: string[]): DatasetModel {\n const model: DatasetModel = { fields: {}, order: [] }\n for (const name of fields) {\n // Raw snake_case ids read as titles in table headers and pickers;\n // the id stays the stable key (AGL-558).\n model.fields[name] = { name: humanizeDatasetFieldId(name), type: 'text' }\n model.order.push(name)\n }\n return model\n}\n\n/**\n * Model from quick-creator entries (AGL-558): stable slug ids with the\n * human display names preserved — \"Roast preference\" → id\n * `roast_preference`, name \"Roast preference\".\n */\nexport function modelFromFieldEntries(\n entries: readonly DatasetFieldEntry[],\n): DatasetModel {\n const model: DatasetModel = { fields: {}, order: [] }\n for (const entry of entries) {\n model.fields[entry.id] = { name: entry.name, type: 'text' }\n model.order.push(entry.id)\n }\n return model\n}\n\n/**\n * The part of a dataset's model a repeat reads (AGL-180): each reference\n * field, by the id of the dataset it points into, which is a key the rows map\n * answers under. Every field the model declares, in `order` or not — a hop\n * resolves wherever its target's rows were loaded.\n */\nexport function repeatRowsModelOf(model: DatasetModel): RepeatRowsModel {\n const references: Record<string, string> = {}\n for (const [fieldId, field] of Object.entries(model.fields)) {\n const target = field?.type === 'reference' ? field.reference?.datasetId : undefined\n if (target) references[fieldId] = target\n }\n return { references }\n}\n\n/** The dataset's model, deriving one from v1 `fields` when absent. */\nexport function effectiveDatasetModel(dataset: {\n model?: DatasetModel\n fields?: string[]\n}): DatasetModel {\n if (dataset.model?.fields && dataset.model.order?.length) {\n return dataset.model\n }\n return deriveModelFromFields(dataset.fields ?? [])\n}\n\nconst isFiniteNumber = (value: unknown): value is number =>\n typeof value === 'number' && Number.isFinite(value)\n\n/**\n * Validates a document's values against a model, returning fieldId →\n * human-readable error (empty object = valid). Values are expected in\n * storage form (see the module doc); use `coerceDocumentValues` first\n * when starting from user input strings.\n */\nexport function validateDocument(\n model: DatasetModel,\n values: Record<string, unknown>,\n): Record<string, string> {\n const errors: Record<string, string> = {}\n for (const fieldId of model.order) {\n const field = model.fields[fieldId]\n if (!field) continue\n const value = values[fieldId]\n const required = field.required || field.validation?.required\n // An empty list holds nothing, so it answers \"required\" as an empty\n // string does: `,,` typed into a list field coerces to `[]` (AGL-3496).\n const empty =\n value == null ||\n value === '' ||\n (Array.isArray(value) && !value.length && isListField(field))\n if (empty) {\n if (required) errors[fieldId] = `${field.name} is required`\n continue\n }\n const rules = field.validation ?? {}\n switch (field.type) {\n case 'text': {\n if (typeof value !== 'string') {\n errors[fieldId] = `${field.name} must be text`\n break\n }\n if (rules.min != null && value.length < rules.min) {\n errors[fieldId] = `${field.name} must be at least ${rules.min} characters`\n } else if (rules.max != null && value.length > rules.max) {\n errors[fieldId] = `${field.name} must be at most ${rules.max} characters`\n } else if (rules.regex) {\n try {\n if (!new RegExp(rules.regex).test(value)) {\n errors[fieldId] = `${field.name} has an invalid format`\n }\n } catch {\n // Broken pattern in the model never blocks writes.\n }\n }\n if (\n !errors[fieldId] &&\n rules.options?.length &&\n !rules.options.includes(value)\n ) {\n errors[fieldId] = `${field.name} must be one of: ${rules.options.join(', ')}`\n }\n break\n }\n case 'bool':\n if (typeof value !== 'boolean') {\n errors[fieldId] = `${field.name} must be true or false`\n }\n break\n case 'int32':\n case 'int64':\n if (!isFiniteNumber(value) || !Number.isInteger(value)) {\n errors[fieldId] = `${field.name} must be a whole number`\n break\n }\n if (rules.min != null && value < rules.min) {\n errors[fieldId] = `${field.name} must be ≥ ${rules.min}`\n } else if (rules.max != null && value > rules.max) {\n errors[fieldId] = `${field.name} must be ≤ ${rules.max}`\n }\n break\n case 'float':\n case 'timestamp':\n if (!isFiniteNumber(value)) {\n errors[fieldId] =\n field.type === 'timestamp'\n ? `${field.name} must be a date`\n : `${field.name} must be a number`\n break\n }\n if (rules.min != null && value < rules.min) {\n errors[fieldId] = `${field.name} must be ≥ ${rules.min}`\n } else if (rules.max != null && value > rules.max) {\n errors[fieldId] = `${field.name} must be ≤ ${rules.max}`\n }\n break\n case 'coordinates': {\n const coordinates = value as { latitude?: unknown; longitude?: unknown }\n if (\n !isFiniteNumber(coordinates?.latitude) ||\n !isFiniteNumber(coordinates?.longitude) ||\n Math.abs(coordinates.latitude) > 90 ||\n Math.abs(coordinates.longitude) > 180\n ) {\n errors[fieldId] = `${field.name} must be valid coordinates`\n }\n break\n }\n case 'sorted':\n // A list of values: an entry that is itself an object or a list is\n // not one, and `coerceListValue` leaves it here to be refused.\n if (\n !Array.isArray(value) ||\n value.some((entry) => entry !== null && typeof entry === 'object')\n ) {\n errors[fieldId] = `${field.name} must be a list`\n }\n break\n case 'map':\n if (typeof value !== 'object' || Array.isArray(value)) {\n errors[fieldId] = `${field.name} must be a map`\n }\n break\n case 'reference':\n if (field.reference?.multiple) {\n if (\n !Array.isArray(value) ||\n value.some((entry) => typeof entry !== 'string' || !entry)\n ) {\n errors[fieldId] = `${field.name} must reference documents`\n }\n } else if (typeof value !== 'string' || !value) {\n errors[fieldId] = `${field.name} must reference a document`\n }\n break\n case 'bytes':\n case 'nil':\n break\n }\n }\n // Custom field types (AGL-434): plugin validators run after the base\n // checks, only on fields that passed them.\n for (const fieldId of model.order) {\n const field = model.fields[fieldId]\n if (!field?.customType || errors[fieldId]) continue\n const customError = validateCustomFieldValue(\n field.customType,\n values[fieldId],\n )\n if (customError) errors[fieldId] = `${field.name}: ${customError}`\n }\n return errors\n}\n\n/** Storage value → grid display string (AGL-179). */\nexport function formatDatasetValue(\n field: DatasetFieldDefinition,\n value: unknown,\n): string {\n if (value == null || value === '') return ''\n switch (field.type) {\n case 'bool':\n return value === true ? '✓' : value === false ? '—' : String(value)\n case 'timestamp':\n return isFiniteNumber(value)\n ? new Date(value).toISOString().slice(0, 16).replace('T', ' ')\n : String(value)\n case 'coordinates': {\n const coordinates = value as { latitude?: number; longitude?: number }\n return isFiniteNumber(coordinates?.latitude) &&\n isFiniteNumber(coordinates?.longitude)\n ? `${coordinates.latitude}, ${coordinates.longitude}`\n : String(value)\n }\n case 'sorted':\n return Array.isArray(value) ? value.join(', ') : String(value)\n case 'map':\n try {\n return JSON.stringify(value)\n } catch {\n return String(value)\n }\n default:\n return String(value)\n }\n}\n\n/**\n * Storage value → form-input string (AGL-179): the inverse of\n * `coerceDocumentValues` for populating type-appropriate inputs\n * (timestamps as `datetime-local` values, coordinates as \"lat, lon\").\n */\nexport function datasetValueToInput(\n field: DatasetFieldDefinition,\n value: unknown,\n): string {\n if (value == null) return ''\n if (field.type === 'timestamp' && isFiniteNumber(value)) {\n return new Date(value).toISOString().slice(0, 16)\n }\n if (field.type === 'bool') {\n return value === true ? 'true' : value === false ? 'false' : String(value)\n }\n if (field.type === 'coordinates' || field.type === 'sorted') {\n return formatDatasetValue(field, value)\n }\n if (field.type === 'map') return formatDatasetValue(field, value)\n return String(value)\n}\n\n/**\n * Whether a field stores a list: `sorted`, and a `reference` that may point at\n * more than one record. Both go through {@link coerceListValue}.\n */\nexport function isListField(field: DatasetFieldDefinition): boolean {\n return (\n field.type === 'sorted' ||\n (field.type === 'reference' && Boolean(field.reference?.multiple))\n )\n}\n\n/**\n * The entries of a list given as an array, each a trimmed string with the\n * empty ones dropped — or `null` when an entry is not a scalar (an object, a\n * nested list), which is not a list of values and is left for\n * `validateDocument` to refuse rather than flattened into `[object Object]`.\n */\nfunction listEntries(input: readonly unknown[]): string[] | null {\n const entries: string[] = []\n for (const entry of input) {\n if (entry == null) continue\n if (\n typeof entry !== 'string' &&\n typeof entry !== 'number' &&\n typeof entry !== 'boolean'\n ) {\n return null\n }\n const text = String(entry).trim()\n if (text) entries.push(text)\n }\n return entries\n}\n\n/**\n * A list field's value in storage form (AGL-3496) — the ONE coercion every\n * writer of a `sorted` or multiple-`reference` field reaches through\n * {@link coerceDocumentValues}: the console's record form and its CSV/JSON\n * import, `/api/orgs/datasets`, `/v1` record create and update, form\n * submissions and workflow steps (`prepareDatasetRecordWrite`).\n *\n * - An array is taken as the list: entries stringified and trimmed, empty\n * ones dropped.\n * - A string that parses as a JSON array of scalars is that array. A JSON\n * import hands a list cell over as `[\"Residential\",\"Commercial\"]`, and so\n * does any API client that serialized one; split on commas, it was stored\n * as `[\"[\\\"Residential\\\"\", \"\\\"Commercial\\\"]\"]` and no filter matched it.\n * The console form round-trips such a record too: it shows the stored\n * fragments joined, which reads back as the JSON array, so re-saving a\n * record written that way repairs it.\n * - Any other string is comma-separated, as typed into the form.\n * - Anything else (a number, an object, an array holding objects) passes\n * through untouched for `validateDocument` to refuse.\n */\nexport function coerceListValue(raw: unknown): unknown {\n if (Array.isArray(raw)) return listEntries(raw) ?? raw\n if (typeof raw !== 'string') return raw\n const text = raw.trim()\n if (text.startsWith('[') && text.endsWith(']')) {\n try {\n const parsed: unknown = JSON.parse(text)\n const entries = Array.isArray(parsed) ? listEntries(parsed) : null\n if (entries) return entries\n } catch {\n // Bracketed but not JSON — `[draft], final` — is a comma list.\n }\n }\n return text\n .split(',')\n .map((part) => part.trim())\n .filter(Boolean)\n}\n\nconst BOOL_TRUE_WORDS = new Set(['true', 'yes', 'on', '1'])\nconst BOOL_FALSE_WORDS = new Set(['false', 'no', 'off', '0'])\n\n/**\n * Coerces user-input strings (form fields, CSV cells) into storage form\n * per the field type. Unparseable input is passed through untouched so\n * `validateDocument` reports it instead of silently mangling it.\n *\n * A list field is coerced whatever shape it arrives in — array or string —\n * through {@link coerceListValue}; every other non-string value is already\n * in storage form and passes through.\n */\nexport function coerceDocumentValues(\n model: DatasetModel,\n input: Record<string, unknown>,\n): Record<string, unknown> {\n const values: Record<string, unknown> = {}\n for (const fieldId of model.order) {\n const field = model.fields[fieldId]\n const raw = input[fieldId]\n if (!field || raw == null || raw === '') continue\n if (isListField(field)) {\n values[fieldId] = coerceListValue(raw)\n continue\n }\n if (typeof raw !== 'string') {\n values[fieldId] = raw\n continue\n }\n switch (field.type) {\n case 'bool': {\n // The words a form control or a CSV cell says yes and no with: a\n // lone checkbox posts `on`, a spreadsheet exports `TRUE` or `1`.\n const word = raw.trim().toLowerCase()\n values[fieldId] = BOOL_TRUE_WORDS.has(word)\n ? true\n : BOOL_FALSE_WORDS.has(word)\n ? false\n : raw\n break\n }\n case 'int32':\n case 'int64': {\n const parsed = Number(raw)\n values[fieldId] = Number.isInteger(parsed) ? parsed : raw\n break\n }\n case 'float': {\n const parsed = Number(raw)\n values[fieldId] = Number.isFinite(parsed) ? parsed : raw\n break\n }\n case 'timestamp': {\n const millis = Date.parse(raw)\n values[fieldId] = Number.isFinite(millis) ? millis : raw\n break\n }\n case 'coordinates': {\n const [latitude, longitude] = raw.split(',').map((part) => Number(part.trim()))\n values[fieldId] =\n Number.isFinite(latitude) && Number.isFinite(longitude)\n ? { latitude, longitude }\n : raw\n break\n }\n case 'map':\n try {\n values[fieldId] = JSON.parse(raw)\n } catch {\n values[fieldId] = raw\n }\n break\n default:\n values[fieldId] = raw\n }\n }\n return values\n}\n\n/**\n * Every reference id a record holds, flattened out of its `reference` fields\n * into one de-duplicated list.\n *\n * A reference field stores either a single target id or — when\n * `reference.multiple` is set — an array of them, and a model may declare\n * several. Both shapes flatten into the same list because the question asked\n * of it is never \"which field\", it is \"does this record still point at that\n * document\".\n *\n * Fields are read from `order` UNIONED with the keys of `fields`. Every other\n * pass over a model walks `order` alone, which is right for anything the user\n * sees — but a reference declared without a display slot still holds a real\n * FKey, and an integrity index that skipped it would under-report.\n */\nexport function datasetReferencedIds(\n model: DatasetModel,\n values: Record<string, unknown> | undefined,\n): string[] {\n const ids = new Set<string>()\n const fieldIds = new Set([\n ...(model.order ?? []),\n ...Object.keys(model.fields ?? {}),\n ])\n for (const fieldId of fieldIds) {\n if (model.fields?.[fieldId]?.type !== 'reference') continue\n const stored = values?.[fieldId]\n for (const entry of Array.isArray(stored) ? stored : [stored]) {\n const id = typeof entry === 'string' ? entry.trim() : ''\n if (id) ids.add(id)\n }\n }\n return [...ids]\n}\n\n/**\n * The integrity index a record write carries, so referential integrity can be\n * decided by a QUERY rather than by the rows a listener happened to fetch.\n *\n * Deleting a record has to answer \"is anything still pointing at this?\", and\n * `restrict` refuses the delete on a yes while `setNull` strips the FKey. That\n * question cannot be asked where the answer is stored: dataset fields are\n * user-defined, so `records.values` carries a deliberate index exemption in\n * `cloud/firebase-firestore.indexes.json` — auto-indexing an unbounded map\n * blows Firestore's per-document index-entry limit — and\n * `where('values.<fieldId>', '==', id)` is therefore FAILED_PRECONDITION.\n * Reading a page of records and filtering them in the browser answers only for\n * the rows in that page, which is a browse window standing in for a\n * correctness check: a reference held outside it reads as no reference at all,\n * the delete proceeds, and `restrict` silently fails to restrict.\n *\n * `referencedIds` is that same reference, denormalized to a top-level array\n * Firestore will index, so one `array-contains` reaches every record.\n *\n * ⚠️ OMITTED when a record references nothing, rather than written as `[]`.\n * `isNotEmpty` is served as `!= null` and an empty array is not null, so a\n * record stamped `[]` answers \"holds a reference\" for a dataset that holds\n * none.\n *\n * ⚠️ Spread this at EVERY write that sets a record's `values`. A write that\n * sets values without it leaves the index describing the PREVIOUS values, and\n * a stale integrity index is the exact failure it exists to prevent — with the\n * UI reporting the record as safe to delete. On a merging write use\n * `datasetIntegrityUpdate` instead: omission leaves a stale array in place\n * where clearing the last reference has to remove the field.\n */\nexport function datasetIntegrityFields(\n model: DatasetModel,\n values: Record<string, unknown> | undefined,\n): {\n referencedIds?: string[]\n filterKeys?: string[]\n filterValues?: DatasetFilterValues\n} {\n const referencedIds = datasetReferencedIds(model, values)\n // The records table's filter fields (`datasetFilterKeys`,\n // `datasetFilterValues`) travel on the same writes for the same reason: a\n // record written without them is invisible to every filter the query\n // serves. Omitted when empty, like `referencedIds`.\n const filterKeys = datasetFilterKeys(model, values)\n const filterValues = datasetFilterValues(model, values)\n return {\n ...(referencedIds.length ? { referencedIds } : {}),\n ...(filterKeys.length ? { filterKeys } : {}),\n ...(Object.keys(filterValues).length ? { filterValues } : {}),\n }\n}\n\n/**\n * `datasetIntegrityFields` for a MERGING write (`update`, `set` with\n * `mergeFields`), where leaving the field out preserves what is stored\n * rather than clearing it.\n *\n * A record whose last reference is cleared has to have the field REMOVED, or\n * it goes on answering the `array-contains` for a document it no longer points\n * at — a `restrict` that refuses a delete nothing is holding. `clear` is the\n * caller's delete sentinel: `deleteField()` in the web SDK,\n * `FieldValue.delete()` in the Admin SDK. It is passed in rather than imported\n * because this module is shared by both and must stay SDK-free. The filter\n * fields are cleared the same way, so a record emptied of every filterable\n * value stops answering the filters its old values did.\n *\n * ⚠️ `filterValues` is a MAP, and it is written WHOLE: `update` and\n * `mergeFields` replace a field outright, so a value cleared since the last\n * write leaves the map with it. `set(…, { merge: true })` does NOT — it merges\n * maps key by key and would keep the cleared value answering its old\n * equality — so a record write never uses it; list the fields in\n * `mergeFields` instead.\n */\nexport function datasetIntegrityUpdate<TClear>(\n model: DatasetModel,\n values: Record<string, unknown> | undefined,\n clear: TClear,\n): {\n referencedIds: string[] | TClear\n filterKeys: string[] | TClear\n filterValues: DatasetFilterValues | TClear\n} {\n const referencedIds = datasetReferencedIds(model, values)\n const filterKeys = datasetFilterKeys(model, values)\n const filterValues = datasetFilterValues(model, values)\n return {\n referencedIds: referencedIds.length ? referencedIds : clear,\n filterKeys: filterKeys.length ? filterKeys : clear,\n filterValues: Object.keys(filterValues).length ? filterValues : clear,\n }\n}\n\n/**\n * A dataset record's FILTER TOKENS: every word-level question the records\n * table can ask of a record, flattened into one array of strings Firestore\n * indexes on its own. Its twin, {@link datasetFilterValues}, holds the\n * equalities.\n *\n * ## Why these fields, and not the values\n *\n * A record's fields live under `values`, a user-defined, unbounded map that\n * the index configuration exempts from indexing — auto-indexing it can exceed\n * Firestore's per-document index-entry limit — so `where('values.<field>', …)`\n * is refused. A composite index per dataset would need an admin call per\n * dataset, runs into the project's composite-index cap, and is deleted by the\n * next `firestore:indexes` deploy of a file that does not list it.\n *\n * `filterKeys` and `filterValues` need none of that. Firestore's AUTOMATIC\n * single-field indexes serve `where('filterKeys', 'array-contains', token)`\n * and `where('filterValues.<field>', '==', value)`, and every automatic index\n * ends in the document name — so any number of those equalities and ONE\n * `array-contains`, under `orderBy(documentId())`, compose by index merging,\n * with no composite index and no index deploy, on any dataset of any project\n * (AGL-3321).\n *\n * ## The token grammar\n *\n * `f:<fieldId>=<value>` a field equals a value. Enum (a text field with\n * `validation.options`) values are kept exactly;\n * plain text is lower-cased, trimmed and clipped to\n * {@link DATASET_FILTER_VALUE_MAX} characters;\n * booleans are `true`/`false`; numbers are\n * `String(number)`; a `sorted` list contributes one\n * token per member.\n * `f:<fieldId>^<prefix>` a word of a plain text field starts with this.\n * `s:<prefix>` a word of ANY text value (enums and list members\n * included) starts with this — the quick search.\n *\n * Timestamps, references, maps, bytes, coordinates and nil fields carry no\n * field tokens: a timestamp is asked in ranges, which one token cannot serve,\n * and the rest are not asked about by value.\n *\n * The array is sorted, de-duplicated and capped at\n * {@link DATASET_FILTER_KEYS_MAX}. Past the cap, the `=` tokens are kept\n * first, then the per-field word prefixes, then the search prefixes, so a\n * very long record loses search reach before it loses exact matches.\n */\nexport const DATASET_FILTER_KEYS_MAX = 500\n\n/** Plain text values are clipped to this many characters in an `=` token. */\nexport const DATASET_FILTER_VALUE_MAX = 64\n/** Word prefixes run from 1 to this many characters. */\nexport const DATASET_FILTER_PREFIX_MAX = 12\n/** Only the first this-many words of a value contribute prefixes. */\nexport const DATASET_FILTER_WORDS_MAX = 40\n\n/** One clause of the records table's filter: `{ field, op, value }`. */\nexport interface DatasetFilterClause {\n field: string\n op: string\n value: string\n}\n\n/**\n * The words of a text value: split on anything that is not a letter or a\n * digit, lower-cased, at most {@link DATASET_FILTER_WORDS_MAX} of them.\n */\nexport function datasetFilterWords(text: string): string[] {\n return String(text)\n .toLowerCase()\n .split(/[^\\p{L}\\p{N}]+/u)\n .filter(Boolean)\n .slice(0, DATASET_FILTER_WORDS_MAX)\n}\n\n/** A word's prefixes, 1 to {@link DATASET_FILTER_PREFIX_MAX} characters. */\nfunction prefixes(word: string): string[] {\n const chars = Array.from(word).slice(0, DATASET_FILTER_PREFIX_MAX)\n return chars.map((_char, at) => chars.slice(0, at + 1).join(''))\n}\n\n/** A word clipped the way its stored prefixes are. */\nfunction clipWord(word: string): string {\n return Array.from(word).slice(0, DATASET_FILTER_PREFIX_MAX).join('')\n}\n\nconst isEnum = (field: DatasetFieldDefinition): boolean =>\n field.type === 'text' && (field.validation?.options?.length ?? 0) > 0\n\nconst isNumeric = (field: DatasetFieldDefinition): boolean =>\n field.type === 'int32' || field.type === 'int64' || field.type === 'float'\n\n/**\n * A stored value as text, or null. Numbers are accepted because a form or an\n * automation stores every value as text and an import may do the reverse.\n */\nfunction asText(value: unknown): string | null {\n if (typeof value === 'string') return value\n if (typeof value === 'number' && Number.isFinite(value)) return String(value)\n return null\n}\n\n/**\n * Plain text as its stored key — its `=` token's value and its\n * `filterValues` entry: lower-cased, trimmed, clipped to\n * {@link DATASET_FILTER_VALUE_MAX} characters. What the records table asks a\n * typed value to equal.\n */\nexport function datasetFilterTextKey(value: string): string {\n return Array.from(value.trim().toLowerCase())\n .slice(0, DATASET_FILTER_VALUE_MAX)\n .join('')\n}\nconst textKey = datasetFilterTextKey\n\n/** A stored number (or its text form) as its `=` token's value. */\nfunction numberKey(value: unknown): string | null {\n const number =\n typeof value === 'number'\n ? value\n : typeof value === 'string' && value.trim() !== ''\n ? Number(value)\n : Number.NaN\n return Number.isFinite(number) ? String(number) : null\n}\n\n/** A stored boolean (or its text form) as its `=` token's value. */\nfunction boolKey(value: unknown): string | null {\n if (typeof value === 'boolean') return String(value)\n if (value === 'true' || value === 'false') return value\n return null\n}\n\n/** Every field a model declares, in display order and then the rest. */\nfunction modelFieldIds(model: DatasetModel): string[] {\n return [...new Set([...(model.order ?? []), ...Object.keys(model.fields ?? {})])]\n}\n\n/** The tokens described in {@link DATASET_FILTER_KEYS_MAX}'s comment. */\nexport function datasetFilterKeys(\n model: DatasetModel,\n values: Record<string, unknown> | undefined,\n): string[] {\n const exact: string[] = []\n const fieldWords: string[] = []\n const search: string[] = []\n const searchable = (text: string) => {\n for (const word of datasetFilterWords(text)) {\n for (const prefix of prefixes(word)) search.push(`s:${prefix}`)\n }\n }\n for (const fieldId of modelFieldIds(model)) {\n const field = model.fields?.[fieldId]\n const stored = values?.[fieldId]\n if (!field || stored == null) continue\n if (field.type === 'text') {\n const text = asText(stored)\n if (text == null || !text.trim()) continue\n if (isEnum(field)) {\n exact.push(`f:${fieldId}=${text}`)\n } else {\n exact.push(`f:${fieldId}=${textKey(text)}`)\n for (const word of datasetFilterWords(text)) {\n for (const prefix of prefixes(word)) {\n fieldWords.push(`f:${fieldId}^${prefix}`)\n }\n }\n }\n searchable(text)\n } else if (field.type === 'bool') {\n const key = boolKey(stored)\n if (key) exact.push(`f:${fieldId}=${key}`)\n } else if (isNumeric(field)) {\n const key = numberKey(stored)\n if (key) exact.push(`f:${fieldId}=${key}`)\n } else if (field.type === 'sorted') {\n for (const member of Array.isArray(stored) ? stored : [stored]) {\n const text = asText(member)?.trim()\n if (!text) continue\n exact.push(`f:${fieldId}=${text}`)\n searchable(text)\n }\n }\n }\n const kept = [...new Set([...exact, ...fieldWords, ...search])].slice(\n 0,\n DATASET_FILTER_KEYS_MAX,\n )\n return kept.sort()\n}\n\n/** A record's `filterValues`: field id → the value an equality asks for. */\nexport type DatasetFilterValues = Record<string, string | number | boolean>\n\n/**\n * Field ids a query can name as `filterValues.<id>`. A path string splits on\n * `.`, and the SDKs refuse `~ * / [ ]` in one; the model editor allows only\n * letters, digits and underscores, but a v1 dataset's column names were\n * never checked. Backticks are refused too, as the escape a path would need.\n */\nconst FILTER_VALUE_ID = /^[^.~*/[\\]`]+$/\n\n/**\n * The query path of a field's `filterValues` entry, or null for a field id\n * no path can name — such a field is stamped no entry, and the records table\n * offers it no equality (its `contains`, served by `filterKeys`, stands).\n */\nexport function datasetFilterValuePath(fieldId: string): string | null {\n return FILTER_VALUE_ID.test(fieldId) && !/^__.*__$/.test(fieldId)\n ? `filterValues.${fieldId}`\n : null\n}\n\n/**\n * A dataset record's FILTER VALUES: `{ [fieldId]: value }`, one scalar per\n * field an equality can be asked of, so the records table puts every\n * equality on its query (AGL-3321).\n *\n * enum text (`validation.options`) the value exactly, as its `=` token;\n * plain text {@link datasetFilterTextKey};\n * bool a boolean;\n * int32 / int64 / float a number.\n *\n * A form or an automation stores every value as text, so `'19.50'` is the\n * number 19.5 and `'true'` the boolean, as in {@link datasetFilterKeys}.\n * Fields with no value, and timestamps, lists, references, maps, bytes,\n * coordinates and nil fields, carry no entry: a list is asked by member\n * (`f:<id>=<member>` in `filterKeys`), and the rest are not asked about by\n * value.\n *\n * ## What it costs\n *\n * Unlike `values`, this map is NOT exempt from indexing — that is its whole\n * point. Each entry is a scalar and costs two automatic index entries\n * (ascending, descending), so a record costs at most two per model field —\n * bounded by the model's field count (the `/v1` API caps a model at 100\n * fields), far inside Firestore's 40,000 entries per document, where\n * `values` was unbounded because a `map` or `sorted` value may hold anything.\n */\nexport function datasetFilterValues(\n model: DatasetModel,\n values: Record<string, unknown> | undefined,\n): DatasetFilterValues {\n const out: DatasetFilterValues = {}\n for (const fieldId of modelFieldIds(model)) {\n const field = model.fields?.[fieldId]\n const stored = values?.[fieldId]\n if (!field || stored == null || !datasetFilterValuePath(fieldId)) continue\n if (field.type === 'text') {\n const text = asText(stored)\n if (text == null || !text.trim()) continue\n out[fieldId] = isEnum(field) ? text : textKey(text)\n } else if (field.type === 'bool') {\n const key = boolKey(stored)\n if (key) out[fieldId] = key === 'true'\n } else if (isNumeric(field)) {\n const key = numberKey(stored)\n if (key) out[fieldId] = Number(key)\n }\n }\n return out\n}\n\n/**\n * The `filterKeys` token a word-level clause asks for, or null when it is\n * not one:\n *\n * - plain text `contains` → the `^` token of the value's FIRST word, so a\n * `contains` is a word-prefix match, not a mid-string one, and one word\n * of several is asked (the records table says so);\n * - list `contains` (and `equals`) → the member's `=` token;\n * - enum, boolean, number and plain text `equals` → the `=` token of the\n * value. The records table asks these of `filterValues` instead, which\n * composes with a `contains`; the token remains what the quick search and\n * older readers match.\n * - everything else — ranges, dates, `isEmpty`, `isAnyOf`, negations — null.\n *\n * `clause.field` is the field id. The operator names are the grid's: a\n * select's `equals`, a number's `=`, a boolean's `is`, a list's `contains`.\n */\nexport function datasetFilterToken(\n model: DatasetModel,\n clause: DatasetFilterClause,\n): string | null {\n const field = model.fields?.[clause.field]\n if (!field) return null\n const { op } = clause\n const value = String(clause.value ?? '')\n if (!value.trim()) return null\n const equals = op === 'equals' || op === '=' || op === 'is'\n if (field.type === 'text') {\n if (isEnum(field)) return equals ? `f:${clause.field}=${value}` : null\n if (equals) return `f:${clause.field}=${textKey(value)}`\n if (op === 'contains') {\n const [first] = datasetFilterWords(value)\n return first ? `f:${clause.field}^${clipWord(first)}` : null\n }\n return null\n }\n if (field.type === 'bool') {\n const key = boolKey(value.trim())\n return equals && key ? `f:${clause.field}=${key}` : null\n }\n if (isNumeric(field)) {\n const key = numberKey(value)\n return equals && key ? `f:${clause.field}=${key}` : null\n }\n if (field.type === 'sorted') {\n return equals || op === 'contains' ? `f:${clause.field}=${value.trim()}` : null\n }\n return null\n}\n\n/**\n * The quick-search token for one typed word, or null for a word with no\n * letters or digits. A word with punctuation inside it is asked by its first\n * run — split the search text with {@link datasetFilterWords} to ask for\n * every run.\n */\nexport function datasetSearchToken(word: string): string | null {\n const [first] = datasetFilterWords(word)\n return first ? `s:${clipWord(first)}` : null\n}\n"],"names":["validateCustomFieldValue","humanizeDatasetFieldId","id","words","replace","trim","charAt","toUpperCase","slice","DATASET_FIELD_TYPES","DATASET_FIELD_TYPE_LABELS","text","bool","int32","int64","float","timestamp","coordinates","map","sorted","bytes","nil","reference","deriveModelFromFields","fields","model","order","name","type","push","modelFromFieldEntries","entries","entry","repeatRowsModelOf","references","fieldId","field","Object","target","datasetId","undefined","effectiveDatasetModel","dataset","length","isFiniteNumber","value","Number","isFinite","validateDocument","values","errors","required","validation","empty","Array","isArray","isListField","rules","min","max","regex","RegExp","test","options","includes","join","isInteger","latitude","longitude","Math","abs","some","multiple","customType","customError","formatDatasetValue","String","Date","toISOString","JSON","stringify","datasetValueToInput","Boolean","listEntries","input","coerceListValue","raw","startsWith","endsWith","parsed","parse","split","part","filter","BOOL_TRUE_WORDS","Set","BOOL_FALSE_WORDS","coerceDocumentValues","word","toLowerCase","has","millis","datasetReferencedIds","ids","fieldIds","keys","stored","add","datasetIntegrityFields","referencedIds","filterKeys","datasetFilterKeys","filterValues","datasetFilterValues","datasetIntegrityUpdate","clear","DATASET_FILTER_KEYS_MAX","DATASET_FILTER_VALUE_MAX","DATASET_FILTER_PREFIX_MAX","DATASET_FILTER_WORDS_MAX","datasetFilterWords","prefixes","chars","from","_char","at","clipWord","isEnum","isNumeric","asText","datasetFilterTextKey","textKey","numberKey","number","NaN","boolKey","modelFieldIds","exact","fieldWords","search","searchable","prefix","key","member","kept","sort","FILTER_VALUE_ID","datasetFilterValuePath","out","datasetFilterToken","clause","op","equals","first","datasetSearchToken"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,wBAAwB,QAAQ,4CAA2C;AA4BpF,2EAA2E,GAC3E,OAAO,SAASC,uBAAuBC,EAAU;IAC/C,MAAMC,QAAQD,GAAGE,OAAO,CAAC,MAAM,KAAKC,IAAI;IACxC,OAAOF,QAAQA,MAAMG,MAAM,CAAC,GAAGC,WAAW,KAAKJ,MAAMK,KAAK,CAAC,KAAKN;AAClE;AAiBA,OAAO,MAAMO,sBAA0C;IACrD;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAA;AAED,2CAA2C,GAC3C,OAAO,MAAMC,4BAA8D;IACzEC,MAAM;IACNC,MAAM;IACNC,OAAO;IACPC,OAAO;IACPC,OAAO;IACPC,WAAW;IACXC,aAAa;IACbC,KAAK;IACLC,QAAQ;IACRC,OAAO;IACPC,KAAK;IACLC,WAAW;AACb,EAAC;AA+DD;;;;;CAKC,GACD,OAAO,SAASC,sBAAsBC,MAAgB;IACpD,MAAMC,QAAsB;QAAED,QAAQ,CAAC;QAAGE,OAAO,EAAE;IAAC;IACpD,KAAK,MAAMC,QAAQH,OAAQ;QACzB,kEAAkE;QAClE,yCAAyC;QACzCC,MAAMD,MAAM,CAACG,KAAK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M,GAAGjC,mBAAmB3E;YACnC,OAAO4G,QAAQ,CAAC,EAAE,EAAEH,OAAOlH,KAAK,CAAC,CAAC,EAAE0F,SAAS2B,QAAQ,GAAG;QAC1D;QACA,OAAO;IACT;IACA,IAAIrH,MAAMR,IAAI,KAAK,QAAQ;QACzB,MAAMkH,MAAMP,QAAQ1F,MAAMxC,IAAI;QAC9B,OAAOmJ,UAAUV,MAAM,CAAC,EAAE,EAAEQ,OAAOlH,KAAK,CAAC,CAAC,EAAE0G,KAAK,GAAG;IACtD;IACA,IAAId,UAAU5F,QAAQ;QACpB,MAAM0G,MAAMV,UAAUvF;QACtB,OAAO2G,UAAUV,MAAM,CAAC,EAAE,EAAEQ,OAAOlH,KAAK,CAAC,CAAC,EAAE0G,KAAK,GAAG;IACtD;IACA,IAAI1G,MAAMR,IAAI,KAAK,UAAU;QAC3B,OAAO4H,UAAUD,OAAO,aAAa,CAAC,EAAE,EAAED,OAAOlH,KAAK,CAAC,CAAC,EAAES,MAAMxC,IAAI,IAAI,GAAG;IAC7E;IACA,OAAO;AACT;AAEA;;;;;CAKC,GACD,OAAO,SAASqJ,mBAAmBxD,IAAY;IAC7C,MAAM,CAACuD,MAAM,GAAGjC,mBAAmBtB;IACnC,OAAOuD,QAAQ,CAAC,EAAE,EAAE3B,SAAS2B,QAAQ,GAAG;AAC1C"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/model/dataset-models.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { RepeatRowsModel } from '@aglyn/aglyn/app-utils/expand-repeatables'\nimport { validateCustomFieldValue } from '@aglyn/aglyn/plugin-manager/custom-fields'\n\nimport {\n type DatasetFieldDefinition,\n type DatasetFilterValues,\n type DatasetModel,\n datasetFilterKeys,\n datasetFilterValues,\n} from './dataset-model-core'\n\n/**\n * Dataset models (AGL-177): the runtime promotion of the type-level\n * blueprint in `libs/shared/data/types/src/lib/dod.ts` (kept as the\n * referenced design doc — this module is the single runtime source of\n * truth). A model lives on the dataset doc\n * (`orgs/{orgId}/datasets/{id}.model`) and drives the typed editor, import\n * and site-restore validation, and every record write — the console, `/v1`,\n * a bound form's submission and an automation step — through the shared\n * `validateDocument`/`coerceDocumentValues` pair so they can't disagree. The\n * form and the automation step reach the pair through\n * `prepareDatasetRecordWrite` (AGL-2773).\n *\n * Storage conventions (Firestore-safe): timestamps as epoch millis\n * numbers, coordinates as `{ latitude, longitude }`, `sorted` as arrays,\n * `map` as plain objects, references as target-document id strings.\n */\n\nexport * from './dataset-model-core'\n\n/**\n * The part of a dataset's model a repeat reads (AGL-180): each reference\n * field, by the id of the dataset it points into, which is a key the rows map\n * answers under. Every field the model declares, in `order` or not — a hop\n * resolves wherever its target's rows were loaded.\n */\nexport function repeatRowsModelOf(model: DatasetModel): RepeatRowsModel {\n const references: Record<string, string> = {}\n for (const [fieldId, field] of Object.entries(model.fields)) {\n const target = field?.type === 'reference' ? field.reference?.datasetId : undefined\n if (target) references[fieldId] = target\n }\n return { references }\n}\nconst isFiniteNumber = (value: unknown): value is number =>\n typeof value === 'number' && Number.isFinite(value)\n\n/**\n * Validates a document's values against a model, returning fieldId →\n * human-readable error (empty object = valid). Values are expected in\n * storage form (see the module doc); use `coerceDocumentValues` first\n * when starting from user input strings.\n */\nexport function validateDocument(\n model: DatasetModel,\n values: Record<string, unknown>,\n): Record<string, string> {\n const errors: Record<string, string> = {}\n for (const fieldId of model.order) {\n const field = model.fields[fieldId]\n if (!field) continue\n const value = values[fieldId]\n const required = field.required || field.validation?.required\n // An empty list holds nothing, so it answers \"required\" as an empty\n // string does: `,,` typed into a list field coerces to `[]` (AGL-3496).\n const empty =\n value == null ||\n value === '' ||\n (Array.isArray(value) && !value.length && isListField(field))\n if (empty) {\n if (required) errors[fieldId] = `${field.name} is required`\n continue\n }\n const rules = field.validation ?? {}\n switch (field.type) {\n case 'text': {\n if (typeof value !== 'string') {\n errors[fieldId] = `${field.name} must be text`\n break\n }\n if (rules.min != null && value.length < rules.min) {\n errors[fieldId] = `${field.name} must be at least ${rules.min} characters`\n } else if (rules.max != null && value.length > rules.max) {\n errors[fieldId] = `${field.name} must be at most ${rules.max} characters`\n } else if (rules.regex) {\n try {\n if (!new RegExp(rules.regex).test(value)) {\n errors[fieldId] = `${field.name} has an invalid format`\n }\n } catch {\n // Broken pattern in the model never blocks writes.\n }\n }\n if (\n !errors[fieldId] &&\n rules.options?.length &&\n !rules.options.includes(value)\n ) {\n errors[fieldId] = `${field.name} must be one of: ${rules.options.join(', ')}`\n }\n break\n }\n case 'bool':\n if (typeof value !== 'boolean') {\n errors[fieldId] = `${field.name} must be true or false`\n }\n break\n case 'int32':\n case 'int64':\n if (!isFiniteNumber(value) || !Number.isInteger(value)) {\n errors[fieldId] = `${field.name} must be a whole number`\n break\n }\n if (rules.min != null && value < rules.min) {\n errors[fieldId] = `${field.name} must be ≥ ${rules.min}`\n } else if (rules.max != null && value > rules.max) {\n errors[fieldId] = `${field.name} must be ≤ ${rules.max}`\n }\n break\n case 'float':\n case 'timestamp':\n if (!isFiniteNumber(value)) {\n errors[fieldId] =\n field.type === 'timestamp'\n ? `${field.name} must be a date`\n : `${field.name} must be a number`\n break\n }\n if (rules.min != null && value < rules.min) {\n errors[fieldId] = `${field.name} must be ≥ ${rules.min}`\n } else if (rules.max != null && value > rules.max) {\n errors[fieldId] = `${field.name} must be ≤ ${rules.max}`\n }\n break\n case 'coordinates': {\n const coordinates = value as { latitude?: unknown; longitude?: unknown }\n if (\n !isFiniteNumber(coordinates?.latitude) ||\n !isFiniteNumber(coordinates?.longitude) ||\n Math.abs(coordinates.latitude) > 90 ||\n Math.abs(coordinates.longitude) > 180\n ) {\n errors[fieldId] = `${field.name} must be valid coordinates`\n }\n break\n }\n case 'sorted':\n // A list of values: an entry that is itself an object or a list is\n // not one, and `coerceListValue` leaves it here to be refused.\n if (\n !Array.isArray(value) ||\n value.some((entry) => entry !== null && typeof entry === 'object')\n ) {\n errors[fieldId] = `${field.name} must be a list`\n }\n break\n case 'map':\n if (typeof value !== 'object' || Array.isArray(value)) {\n errors[fieldId] = `${field.name} must be a map`\n }\n break\n case 'reference':\n if (field.reference?.multiple) {\n if (\n !Array.isArray(value) ||\n value.some((entry) => typeof entry !== 'string' || !entry)\n ) {\n errors[fieldId] = `${field.name} must reference documents`\n }\n } else if (typeof value !== 'string' || !value) {\n errors[fieldId] = `${field.name} must reference a document`\n }\n break\n case 'bytes':\n case 'nil':\n break\n }\n }\n // Custom field types (AGL-434): plugin validators run after the base\n // checks, only on fields that passed them.\n for (const fieldId of model.order) {\n const field = model.fields[fieldId]\n if (!field?.customType || errors[fieldId]) continue\n const customError = validateCustomFieldValue(\n field.customType,\n values[fieldId],\n )\n if (customError) errors[fieldId] = `${field.name}: ${customError}`\n }\n return errors\n}\n/**\n * Whether a field stores a list: `sorted`, and a `reference` that may point at\n * more than one record. Both go through {@link coerceListValue}.\n */\nexport function isListField(field: DatasetFieldDefinition): boolean {\n return (\n field.type === 'sorted' ||\n (field.type === 'reference' && Boolean(field.reference?.multiple))\n )\n}\n\n/**\n * The entries of a list given as an array, each a trimmed string with the\n * empty ones dropped — or `null` when an entry is not a scalar (an object, a\n * nested list), which is not a list of values and is left for\n * `validateDocument` to refuse rather than flattened into `[object Object]`.\n */\nfunction listEntries(input: readonly unknown[]): string[] | null {\n const entries: string[] = []\n for (const entry of input) {\n if (entry == null) continue\n if (\n typeof entry !== 'string' &&\n typeof entry !== 'number' &&\n typeof entry !== 'boolean'\n ) {\n return null\n }\n const text = String(entry).trim()\n if (text) entries.push(text)\n }\n return entries\n}\n\n/**\n * A list field's value in storage form (AGL-3496) — the ONE coercion every\n * writer of a `sorted` or multiple-`reference` field reaches through\n * {@link coerceDocumentValues}: the console's record form and its CSV/JSON\n * import, `/api/orgs/datasets`, `/v1` record create and update, form\n * submissions and workflow steps (`prepareDatasetRecordWrite`).\n *\n * - An array is taken as the list: entries stringified and trimmed, empty\n * ones dropped.\n * - A string that parses as a JSON array of scalars is that array. A JSON\n * import hands a list cell over as `[\"Residential\",\"Commercial\"]`, and so\n * does any API client that serialized one; split on commas, it was stored\n * as `[\"[\\\"Residential\\\"\", \"\\\"Commercial\\\"]\"]` and no filter matched it.\n * The console form round-trips such a record too: it shows the stored\n * fragments joined, which reads back as the JSON array, so re-saving a\n * record written that way repairs it.\n * - Any other string is comma-separated, as typed into the form.\n * - Anything else (a number, an object, an array holding objects) passes\n * through untouched for `validateDocument` to refuse.\n */\nexport function coerceListValue(raw: unknown): unknown {\n if (Array.isArray(raw)) return listEntries(raw) ?? raw\n if (typeof raw !== 'string') return raw\n const text = raw.trim()\n if (text.startsWith('[') && text.endsWith(']')) {\n try {\n const parsed: unknown = JSON.parse(text)\n const entries = Array.isArray(parsed) ? listEntries(parsed) : null\n if (entries) return entries\n } catch {\n // Bracketed but not JSON — `[draft], final` — is a comma list.\n }\n }\n return text\n .split(',')\n .map((part) => part.trim())\n .filter(Boolean)\n}\n\nconst BOOL_TRUE_WORDS = new Set(['true', 'yes', 'on', '1'])\nconst BOOL_FALSE_WORDS = new Set(['false', 'no', 'off', '0'])\n\n/**\n * Coerces user-input strings (form fields, CSV cells) into storage form\n * per the field type. Unparseable input is passed through untouched so\n * `validateDocument` reports it instead of silently mangling it.\n *\n * A list field is coerced whatever shape it arrives in — array or string —\n * through {@link coerceListValue}; every other non-string value is already\n * in storage form and passes through.\n */\nexport function coerceDocumentValues(\n model: DatasetModel,\n input: Record<string, unknown>,\n): Record<string, unknown> {\n const values: Record<string, unknown> = {}\n for (const fieldId of model.order) {\n const field = model.fields[fieldId]\n const raw = input[fieldId]\n if (!field || raw == null || raw === '') continue\n if (isListField(field)) {\n values[fieldId] = coerceListValue(raw)\n continue\n }\n if (typeof raw !== 'string') {\n values[fieldId] = raw\n continue\n }\n switch (field.type) {\n case 'bool': {\n // The words a form control or a CSV cell says yes and no with: a\n // lone checkbox posts `on`, a spreadsheet exports `TRUE` or `1`.\n const word = raw.trim().toLowerCase()\n values[fieldId] = BOOL_TRUE_WORDS.has(word)\n ? true\n : BOOL_FALSE_WORDS.has(word)\n ? false\n : raw\n break\n }\n case 'int32':\n case 'int64': {\n const parsed = Number(raw)\n values[fieldId] = Number.isInteger(parsed) ? parsed : raw\n break\n }\n case 'float': {\n const parsed = Number(raw)\n values[fieldId] = Number.isFinite(parsed) ? parsed : raw\n break\n }\n case 'timestamp': {\n const millis = Date.parse(raw)\n values[fieldId] = Number.isFinite(millis) ? millis : raw\n break\n }\n case 'coordinates': {\n const [latitude, longitude] = raw.split(',').map((part) => Number(part.trim()))\n values[fieldId] =\n Number.isFinite(latitude) && Number.isFinite(longitude)\n ? { latitude, longitude }\n : raw\n break\n }\n case 'map':\n try {\n values[fieldId] = JSON.parse(raw)\n } catch {\n values[fieldId] = raw\n }\n break\n default:\n values[fieldId] = raw\n }\n }\n return values\n}\n\n/**\n * Every reference id a record holds, flattened out of its `reference` fields\n * into one de-duplicated list.\n *\n * A reference field stores either a single target id or — when\n * `reference.multiple` is set — an array of them, and a model may declare\n * several. Both shapes flatten into the same list because the question asked\n * of it is never \"which field\", it is \"does this record still point at that\n * document\".\n *\n * Fields are read from `order` UNIONED with the keys of `fields`. Every other\n * pass over a model walks `order` alone, which is right for anything the user\n * sees — but a reference declared without a display slot still holds a real\n * FKey, and an integrity index that skipped it would under-report.\n */\nexport function datasetReferencedIds(\n model: DatasetModel,\n values: Record<string, unknown> | undefined,\n): string[] {\n const ids = new Set<string>()\n const fieldIds = new Set([\n ...(model.order ?? []),\n ...Object.keys(model.fields ?? {}),\n ])\n for (const fieldId of fieldIds) {\n if (model.fields?.[fieldId]?.type !== 'reference') continue\n const stored = values?.[fieldId]\n for (const entry of Array.isArray(stored) ? stored : [stored]) {\n const id = typeof entry === 'string' ? entry.trim() : ''\n if (id) ids.add(id)\n }\n }\n return [...ids]\n}\n\n/**\n * The integrity index a record write carries, so referential integrity can be\n * decided by a QUERY rather than by the rows a listener happened to fetch.\n *\n * Deleting a record has to answer \"is anything still pointing at this?\", and\n * `restrict` refuses the delete on a yes while `setNull` strips the FKey. That\n * question cannot be asked where the answer is stored: dataset fields are\n * user-defined, so `records.values` carries a deliberate index exemption in\n * `cloud/firebase-firestore.indexes.json` — auto-indexing an unbounded map\n * blows Firestore's per-document index-entry limit — and\n * `where('values.<fieldId>', '==', id)` is therefore FAILED_PRECONDITION.\n * Reading a page of records and filtering them in the browser answers only for\n * the rows in that page, which is a browse window standing in for a\n * correctness check: a reference held outside it reads as no reference at all,\n * the delete proceeds, and `restrict` silently fails to restrict.\n *\n * `referencedIds` is that same reference, denormalized to a top-level array\n * Firestore will index, so one `array-contains` reaches every record.\n *\n * ⚠️ OMITTED when a record references nothing, rather than written as `[]`.\n * `isNotEmpty` is served as `!= null` and an empty array is not null, so a\n * record stamped `[]` answers \"holds a reference\" for a dataset that holds\n * none.\n *\n * ⚠️ Spread this at EVERY write that sets a record's `values`. A write that\n * sets values without it leaves the index describing the PREVIOUS values, and\n * a stale integrity index is the exact failure it exists to prevent — with the\n * UI reporting the record as safe to delete. On a merging write use\n * `datasetIntegrityUpdate` instead: omission leaves a stale array in place\n * where clearing the last reference has to remove the field.\n */\nexport function datasetIntegrityFields(\n model: DatasetModel,\n values: Record<string, unknown> | undefined,\n): {\n referencedIds?: string[]\n filterKeys?: string[]\n filterValues?: DatasetFilterValues\n} {\n const referencedIds = datasetReferencedIds(model, values)\n // The records table's filter fields (`datasetFilterKeys`,\n // `datasetFilterValues`) travel on the same writes for the same reason: a\n // record written without them is invisible to every filter the query\n // serves. Omitted when empty, like `referencedIds`.\n const filterKeys = datasetFilterKeys(model, values)\n const filterValues = datasetFilterValues(model, values)\n return {\n ...(referencedIds.length ? { referencedIds } : {}),\n ...(filterKeys.length ? { filterKeys } : {}),\n ...(Object.keys(filterValues).length ? { filterValues } : {}),\n }\n}\n\n/**\n * `datasetIntegrityFields` for a MERGING write (`update`, `set` with\n * `mergeFields`), where leaving the field out preserves what is stored\n * rather than clearing it.\n *\n * A record whose last reference is cleared has to have the field REMOVED, or\n * it goes on answering the `array-contains` for a document it no longer points\n * at — a `restrict` that refuses a delete nothing is holding. `clear` is the\n * caller's delete sentinel: `deleteField()` in the web SDK,\n * `FieldValue.delete()` in the Admin SDK. It is passed in rather than imported\n * because this module is shared by both and must stay SDK-free. The filter\n * fields are cleared the same way, so a record emptied of every filterable\n * value stops answering the filters its old values did.\n *\n * ⚠️ `filterValues` is a MAP, and it is written WHOLE: `update` and\n * `mergeFields` replace a field outright, so a value cleared since the last\n * write leaves the map with it. `set(…, { merge: true })` does NOT — it merges\n * maps key by key and would keep the cleared value answering its old\n * equality — so a record write never uses it; list the fields in\n * `mergeFields` instead.\n */\nexport function datasetIntegrityUpdate<TClear>(\n model: DatasetModel,\n values: Record<string, unknown> | undefined,\n clear: TClear,\n): {\n referencedIds: string[] | TClear\n filterKeys: string[] | TClear\n filterValues: DatasetFilterValues | TClear\n} {\n const referencedIds = datasetReferencedIds(model, values)\n const filterKeys = datasetFilterKeys(model, values)\n const filterValues = datasetFilterValues(model, values)\n return {\n referencedIds: referencedIds.length ? referencedIds : clear,\n filterKeys: filterKeys.length ? filterKeys : clear,\n filterValues: Object.keys(filterValues).length ? filterValues : clear,\n }\n}\n"],"names":["validateCustomFieldValue","datasetFilterKeys","datasetFilterValues","repeatRowsModelOf","model","references","fieldId","field","Object","entries","fields","target","type","reference","datasetId","undefined","isFiniteNumber","value","Number","isFinite","validateDocument","values","errors","order","required","validation","empty","Array","isArray","length","isListField","name","rules","min","max","regex","RegExp","test","options","includes","join","isInteger","coordinates","latitude","longitude","Math","abs","some","entry","multiple","customType","customError","Boolean","listEntries","input","text","String","trim","push","coerceListValue","raw","startsWith","endsWith","parsed","JSON","parse","split","map","part","filter","BOOL_TRUE_WORDS","Set","BOOL_FALSE_WORDS","coerceDocumentValues","word","toLowerCase","has","millis","Date","datasetReferencedIds","ids","fieldIds","keys","stored","id","add","datasetIntegrityFields","referencedIds","filterKeys","filterValues","datasetIntegrityUpdate","clear"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,wBAAwB,QAAQ,4CAA2C;AAEpF,SAIEC,iBAAiB,EACjBC,mBAAmB,QACd,0BAAsB;AAE7B;;;;;;;;;;;;;;;CAeC,GAED,cAAc,0BAAsB;AAEpC;;;;;CAKC,GACD,OAAO,SAASC,kBAAkBC,KAAmB;IACnD,MAAMC,aAAqC,CAAC;IAC5C,KAAK,MAAM,CAACC,SAASC,MAAM,IAAIC,OAAOC,OAAO,CAACL,MAAMM,MAAM,EAAG;YACdH;QAA7C,MAAMI,SAASJ,CAAAA,yBAAAA,MAAOK,IAAI,MAAK,eAAcL,mBAAAA,MAAMM,SAAS,qBAAfN,iBAAiBO,SAAS,GAAGC;QAC1E,IAAIJ,QAAQN,UAAU,CAACC,QAAQ,GAAGK;IACpC;IACA,OAAO;QAAEN;IAAW;AACtB;AACA,MAAMW,iBAAiB,CAACC,QACtB,OAAOA,UAAU,YAAYC,OAAOC,QAAQ,CAACF;AAE/C;;;;;CAKC,GACD,OAAO,SAASG,iBACdhB,KAAmB,EACnBiB,MAA+B;IAE/B,MAAMC,SAAiC,CAAC;IACxC,KAAK,MAAMhB,WAAWF,MAAMmB,KAAK,CAAE;YAenBhB;YAXqBA;QAHnC,MAAMA,QAAQH,MAAMM,MAAM,CAACJ,QAAQ;QACnC,IAAI,CAACC,OAAO;QACZ,MAAMU,QAAQI,MAAM,CAACf,QAAQ;QAC7B,MAAMkB,WAAWjB,MAAMiB,QAAQ,MAAIjB,qBAAAA,MAAMkB,UAAU,qBAAhBlB,mBAAkBiB,QA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jF,OAAO0E,IAAI,CAACO,cAAc5D,MAAM,GAAG4D,eAAeE;IAClE;AACF"}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
import type { DatasetModel } from './dataset-model-core';
|
|
18
|
+
/**
|
|
19
|
+
* What deleting one record does to the datasets that reference it (AGL-180),
|
|
20
|
+
* decided once for both writers: the console's Data card, which applies it as
|
|
21
|
+
* a browser batch, and `/api/orgs/datasets` `delete-record`, which the native
|
|
22
|
+
* apps call (AGL-3668). SDK-free: each writer runs the queries and the writes
|
|
23
|
+
* with its own SDK, and asks this what they are.
|
|
24
|
+
*/
|
|
25
|
+
/** The fields of `model` that point into `datasetId`. */
|
|
26
|
+
export declare function referencingFieldIds(model: DatasetModel, datasetId: string): string[];
|
|
27
|
+
/** One record of a referencing dataset, as its `referencedIds` query returned it. */
|
|
28
|
+
export interface ReferenceHolder {
|
|
29
|
+
id: string;
|
|
30
|
+
values: Record<string, unknown> | undefined;
|
|
31
|
+
}
|
|
32
|
+
/** The verdict for one referencing dataset. */
|
|
33
|
+
export type ReferenceFixupPlan =
|
|
34
|
+
/** Nothing in it points at the record. */
|
|
35
|
+
{
|
|
36
|
+
kind: 'none';
|
|
37
|
+
}
|
|
38
|
+
/** A `restrict` field holds it: the delete is refused, and nothing is written. */
|
|
39
|
+
| {
|
|
40
|
+
kind: 'restricted';
|
|
41
|
+
holders: number;
|
|
42
|
+
}
|
|
43
|
+
/** `setNull`: each holder's values with the record stripped out. */
|
|
44
|
+
| {
|
|
45
|
+
kind: 'strip';
|
|
46
|
+
updates: Array<{
|
|
47
|
+
id: string;
|
|
48
|
+
values: Record<string, unknown>;
|
|
49
|
+
}>;
|
|
50
|
+
};
|
|
51
|
+
/**
|
|
52
|
+
* The verdict for `holders` (the referencing dataset's records whose
|
|
53
|
+
* `referencedIds` contain `recordId`) when `recordId` is deleted from
|
|
54
|
+
* `datasetId`. `referencedIds` is the union across every reference field, so
|
|
55
|
+
* a holder counts only when one of the fields that point into `datasetId`
|
|
56
|
+
* holds the id.
|
|
57
|
+
*/
|
|
58
|
+
export declare function planReferenceFixups(model: DatasetModel, datasetId: string, recordId: string, holders: readonly ReferenceHolder[]): ReferenceFixupPlan;
|
|
59
|
+
/** The refusal a `restrict` reference gives, in the card's words. */
|
|
60
|
+
export declare function restrictedDeleteMessage(holders: number, datasetName: string): string;
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
17
|
+
/**
|
|
18
|
+
* What deleting one record does to the datasets that reference it (AGL-180),
|
|
19
|
+
* decided once for both writers: the console's Data card, which applies it as
|
|
20
|
+
* a browser batch, and `/api/orgs/datasets` `delete-record`, which the native
|
|
21
|
+
* apps call (AGL-3668). SDK-free: each writer runs the queries and the writes
|
|
22
|
+
* with its own SDK, and asks this what they are.
|
|
23
|
+
*/ /** The fields of `model` that point into `datasetId`. */ export function referencingFieldIds(model, datasetId) {
|
|
24
|
+
var _model_order;
|
|
25
|
+
return ((_model_order = model.order) != null ? _model_order : []).filter((fieldId)=>{
|
|
26
|
+
var _model_fields_fieldId, _model_fields, _model_fields_fieldId_reference, _model_fields_fieldId1, _model_fields1;
|
|
27
|
+
return ((_model_fields = model.fields) == null ? void 0 : (_model_fields_fieldId = _model_fields[fieldId]) == null ? void 0 : _model_fields_fieldId.type) === 'reference' && ((_model_fields1 = model.fields) == null ? void 0 : (_model_fields_fieldId1 = _model_fields1[fieldId]) == null ? void 0 : (_model_fields_fieldId_reference = _model_fields_fieldId1.reference) == null ? void 0 : _model_fields_fieldId_reference.datasetId) === datasetId;
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* The verdict for `holders` (the referencing dataset's records whose
|
|
32
|
+
* `referencedIds` contain `recordId`) when `recordId` is deleted from
|
|
33
|
+
* `datasetId`. `referencedIds` is the union across every reference field, so
|
|
34
|
+
* a holder counts only when one of the fields that point into `datasetId`
|
|
35
|
+
* holds the id.
|
|
36
|
+
*/ export function planReferenceFixups(model, datasetId, recordId, holders) {
|
|
37
|
+
const fields = referencingFieldIds(model, datasetId);
|
|
38
|
+
if (!fields.length) return {
|
|
39
|
+
kind: 'none'
|
|
40
|
+
};
|
|
41
|
+
const hits = holders.filter((holder)=>fields.some((fieldId)=>{
|
|
42
|
+
var _holder_values;
|
|
43
|
+
const stored = (_holder_values = holder.values) == null ? void 0 : _holder_values[fieldId];
|
|
44
|
+
return Array.isArray(stored) ? stored.includes(recordId) : stored === recordId;
|
|
45
|
+
}));
|
|
46
|
+
if (!hits.length) return {
|
|
47
|
+
kind: 'none'
|
|
48
|
+
};
|
|
49
|
+
if (fields.some((fieldId)=>{
|
|
50
|
+
var _model_fields_fieldId_reference, _model_fields_fieldId, _model_fields;
|
|
51
|
+
return ((_model_fields = model.fields) == null ? void 0 : (_model_fields_fieldId = _model_fields[fieldId]) == null ? void 0 : (_model_fields_fieldId_reference = _model_fields_fieldId.reference) == null ? void 0 : _model_fields_fieldId_reference.onDelete) === 'restrict';
|
|
52
|
+
})) {
|
|
53
|
+
return {
|
|
54
|
+
kind: 'restricted',
|
|
55
|
+
holders: hits.length
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
return {
|
|
59
|
+
kind: 'strip',
|
|
60
|
+
updates: hits.map((hit)=>{
|
|
61
|
+
var _hit_values;
|
|
62
|
+
const values = _extends({}, (_hit_values = hit.values) != null ? _hit_values : {});
|
|
63
|
+
for (const fieldId of fields){
|
|
64
|
+
const stored = values[fieldId];
|
|
65
|
+
if (Array.isArray(stored)) {
|
|
66
|
+
values[fieldId] = stored.filter((id)=>id !== recordId);
|
|
67
|
+
} else if (stored === recordId) {
|
|
68
|
+
delete values[fieldId];
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return {
|
|
72
|
+
id: hit.id,
|
|
73
|
+
values
|
|
74
|
+
};
|
|
75
|
+
})
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/** The refusal a `restrict` reference gives, in the card's words. */ export function restrictedDeleteMessage(holders, datasetName) {
|
|
79
|
+
return `Cannot delete: referenced by ${holders} document${holders === 1 ? '' : 's'} in "${datasetName}"`;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
//# sourceMappingURL=dataset-record-delete-plan.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/model/dataset-record-delete-plan.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { DatasetModel } from './dataset-model-core'\n\n/**\n * What deleting one record does to the datasets that reference it (AGL-180),\n * decided once for both writers: the console's Data card, which applies it as\n * a browser batch, and `/api/orgs/datasets` `delete-record`, which the native\n * apps call (AGL-3668). SDK-free: each writer runs the queries and the writes\n * with its own SDK, and asks this what they are.\n */\n\n/** The fields of `model` that point into `datasetId`. */\nexport function referencingFieldIds(model: DatasetModel, datasetId: string): string[] {\n return (model.order ?? []).filter(\n (fieldId) =>\n model.fields?.[fieldId]?.type === 'reference' &&\n model.fields?.[fieldId]?.reference?.datasetId === datasetId,\n )\n}\n\n/** One record of a referencing dataset, as its `referencedIds` query returned it. */\nexport interface ReferenceHolder {\n id: string\n values: Record<string, unknown> | undefined\n}\n\n/** The verdict for one referencing dataset. */\nexport type ReferenceFixupPlan =\n /** Nothing in it points at the record. */\n | { kind: 'none' }\n /** A `restrict` field holds it: the delete is refused, and nothing is written. */\n | { kind: 'restricted'; holders: number }\n /** `setNull`: each holder's values with the record stripped out. */\n | { kind: 'strip'; updates: Array<{ id: string; values: Record<string, unknown> }> }\n\n/**\n * The verdict for `holders` (the referencing dataset's records whose\n * `referencedIds` contain `recordId`) when `recordId` is deleted from\n * `datasetId`. `referencedIds` is the union across every reference field, so\n * a holder counts only when one of the fields that point into `datasetId`\n * holds the id.\n */\nexport function planReferenceFixups(\n model: DatasetModel,\n datasetId: string,\n recordId: string,\n holders: readonly ReferenceHolder[],\n): ReferenceFixupPlan {\n const fields = referencingFieldIds(model, datasetId)\n if (!fields.length) return { kind: 'none' }\n const hits = holders.filter((holder) =>\n fields.some((fieldId) => {\n const stored = holder.values?.[fieldId]\n return Array.isArray(stored) ? stored.includes(recordId) : stored === recordId\n }),\n )\n if (!hits.length) return { kind: 'none' }\n if (fields.some((fieldId) => model.fields?.[fieldId]?.reference?.onDelete === 'restrict')) {\n return { kind: 'restricted', holders: hits.length }\n }\n return {\n kind: 'strip',\n updates: hits.map((hit) => {\n const values = { ...(hit.values ?? {}) }\n for (const fieldId of fields) {\n const stored = values[fieldId]\n if (Array.isArray(stored)) {\n values[fieldId] = stored.filter((id: unknown) => id !== recordId)\n } else if (stored === recordId) {\n delete values[fieldId]\n }\n }\n return { id: hit.id, values }\n }),\n }\n}\n\n/** The refusal a `restrict` reference gives, in the card's words. */\nexport function restrictedDeleteMessage(holders: number, datasetName: string): string {\n return `Cannot delete: referenced by ${holders} document${holders === 1 ? '' : 's'} in \"${datasetName}\"`\n}\n"],"names":["referencingFieldIds","model","datasetId","order","filter","fieldId","fields","type","reference","planReferenceFixups","recordId","holders","length","kind","hits","holder","some","stored","values","Array","isArray","includes","onDelete","updates","map","hit","id","restrictedDeleteMessage","datasetName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAID;;;;;;CAMC,GAED,uDAAuD,GACvD,OAAO,SAASA,oBAAoBC,KAAmB,EAAEC,SAAiB;QAChED;IAAR,OAAO,EAACA,eAAAA,MAAME,KAAK,YAAXF,eAAe,EAAE,EAAEG,MAAM,CAC/B,CAACC;YACCJ,uBAAAA,eACAA,iCAAAA,wBAAAA;eADAA,EAAAA,gBAAAA,MAAMK,MAAM,sBAAZL,wBAAAA,aAAc,CAACI,QAAQ,qBAAvBJ,sBAAyBM,IAAI,MAAK,eAClCN,EAAAA,iBAAAA,MAAMK,MAAM,sBAAZL,yBAAAA,cAAc,CAACI,QAAQ,sBAAvBJ,kCAAAA,uBAAyBO,SAAS,qBAAlCP,gCAAoCC,SAAS,MAAKA;;AAExD;AAiBA;;;;;;CAMC,GACD,OAAO,SAASO,oBACdR,KAAmB,EACnBC,SAAiB,EACj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EiB,WAAmB;IAC1E,OAAO,CAAC,6BAA6B,EAAEjB,QAAQ,SAAS,EAAEA,YAAY,IAAI,KAAK,IAAI,KAAK,EAAEiB,YAAY,CAAC,CAAC;AAC1G"}
|
|
@@ -20,9 +20,8 @@
|
|
|
20
20
|
* repeatable components (AGL-103) via `{{item.field}}` bindings.
|
|
21
21
|
*/
|
|
22
22
|
import type { ScopeToken } from '@aglyn/aglyn/foundation/definitions/platform.types';
|
|
23
|
-
import { type
|
|
24
|
-
|
|
25
|
-
export declare const DATASET_FIELD_PATTERN: RegExp;
|
|
23
|
+
import { type DatasetModel } from './dataset-models';
|
|
24
|
+
export { DATASET_FIELD_PATTERN, datasetDisplayName, defaultDatasetFieldId, parseDatasetFieldEntries, slugifyDatasetFieldId, validateDatasetFieldId, } from './dataset-model-core';
|
|
26
25
|
export interface HostDataset {
|
|
27
26
|
$id?: string;
|
|
28
27
|
displayName?: string;
|
|
@@ -52,33 +51,6 @@ export interface HostDatasetRecord {
|
|
|
52
51
|
/** Row position in the editor and in repeated output. */
|
|
53
52
|
order?: number;
|
|
54
53
|
}
|
|
55
|
-
/**
|
|
56
|
-
* Stable field id from a human name: "Roast preference" → "roast_preference".
|
|
57
|
-
* Mirrors DATASET_FIELD_PATTERN; returns '' when nothing salvageable.
|
|
58
|
-
*/
|
|
59
|
-
export declare function slugifyDatasetFieldId(name: string): string;
|
|
60
|
-
/**
|
|
61
|
-
* Default reference id for a new field (AGL-578): the `slugifyDatasetFieldId`
|
|
62
|
-
* slug, suffixed (`_2`, `_3`, …) to stay unique within the dataset. `taken`
|
|
63
|
-
* holds the ids already in use (compared case-insensitively). Returns '' when
|
|
64
|
-
* the name yields nothing valid. The user can override the result.
|
|
65
|
-
*/
|
|
66
|
-
export declare function defaultDatasetFieldId(name: string, taken: ReadonlySet<string>): string;
|
|
67
|
-
/**
|
|
68
|
-
* Validate a user-entered reference id (AGL-578): non-empty, matches
|
|
69
|
-
* `DATASET_FIELD_PATTERN`, and unique within the dataset (`taken` = ids already
|
|
70
|
-
* used, compared case-insensitively). Returns an error message, or null when
|
|
71
|
-
* the id is usable.
|
|
72
|
-
*/
|
|
73
|
-
export declare function validateDatasetFieldId(id: string, taken: ReadonlySet<string>): string | null;
|
|
74
|
-
/**
|
|
75
|
-
* Parses a comma/newline separated list of HUMAN field names into
|
|
76
|
-
* {id, name} entries — "Roast preference" keeps its pretty name and gets
|
|
77
|
-
* the stable id `roast_preference` (AGL-558). Plain snake_case keys
|
|
78
|
-
* still work and pick up a humanized display name. Duplicate ids and
|
|
79
|
-
* unsalvageable entries are dropped rather than failing the set.
|
|
80
|
-
*/
|
|
81
|
-
export declare function parseDatasetFieldEntries(input: string): DatasetFieldEntry[];
|
|
82
54
|
/**
|
|
83
55
|
* Parses a comma/newline separated field list into valid unique names;
|
|
84
56
|
* invalid entries are dropped rather than failing the whole set.
|
|
@@ -149,14 +121,5 @@ export declare function prepareDatasetRecordWrite(dataset: {
|
|
|
149
121
|
* `Stars must be a whole number; Email is required`.
|
|
150
122
|
*/
|
|
151
123
|
export declare function describeDatasetRecordErrors(errors: Record<string, string>): string;
|
|
152
|
-
/**
|
|
153
|
-
* The name a dataset is shown under: `displayName`, which is what every create
|
|
154
|
-
* path writes (AGL-536), then the pre-migration `name`. Blank when the document
|
|
155
|
-
* carries neither.
|
|
156
|
-
*/
|
|
157
|
-
export declare function datasetDisplayName(dataset: {
|
|
158
|
-
displayName?: unknown;
|
|
159
|
-
name?: unknown;
|
|
160
|
-
} | null | undefined): string;
|
|
161
124
|
/** Records sorted by their editor order (then id for stability). */
|
|
162
125
|
export declare function sortDatasetRecords<T extends HostDatasetRecord>(records: T[]): T[];
|
|
@@ -18,69 +18,12 @@
|
|
|
18
18
|
* `records` subcollection, edited in the console Data card and consumed by
|
|
19
19
|
* repeatable components (AGL-103) via `{{item.field}}` bindings.
|
|
20
20
|
*/ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
21
|
-
import { coerceDocumentValues, effectiveDatasetModel,
|
|
21
|
+
import { coerceDocumentValues, effectiveDatasetModel, validateDocument } from "./dataset-models.js";
|
|
22
22
|
import { fillRecordAddresses } from "../record-pages/record-pages.js";
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
*/ export function slugifyDatasetFieldId(name) {
|
|
28
|
-
const slug = name.trim().toLowerCase().replace(/[\s-]+/g, '_').replace(/[^a-z0-9_]/g, '').replace(/^[0-9_]+/, '').replace(/_+$/, '');
|
|
29
|
-
return DATASET_FIELD_PATTERN.test(slug) ? slug : '';
|
|
30
|
-
}
|
|
31
|
-
/**
|
|
32
|
-
* Default reference id for a new field (AGL-578): the `slugifyDatasetFieldId`
|
|
33
|
-
* slug, suffixed (`_2`, `_3`, …) to stay unique within the dataset. `taken`
|
|
34
|
-
* holds the ids already in use (compared case-insensitively). Returns '' when
|
|
35
|
-
* the name yields nothing valid. The user can override the result.
|
|
36
|
-
*/ export function defaultDatasetFieldId(name, taken) {
|
|
37
|
-
const base = slugifyDatasetFieldId(name);
|
|
38
|
-
if (!base) return '';
|
|
39
|
-
const used = new Set([
|
|
40
|
-
...taken
|
|
41
|
-
].map((id)=>id.toLowerCase()));
|
|
42
|
-
let candidate = base;
|
|
43
|
-
let suffix = 2;
|
|
44
|
-
while(used.has(candidate.toLowerCase()))candidate = `${base}_${suffix++}`;
|
|
45
|
-
return candidate;
|
|
46
|
-
}
|
|
47
|
-
/**
|
|
48
|
-
* Validate a user-entered reference id (AGL-578): non-empty, matches
|
|
49
|
-
* `DATASET_FIELD_PATTERN`, and unique within the dataset (`taken` = ids already
|
|
50
|
-
* used, compared case-insensitively). Returns an error message, or null when
|
|
51
|
-
* the id is usable.
|
|
52
|
-
*/ export function validateDatasetFieldId(id, taken) {
|
|
53
|
-
const trimmed = id.trim();
|
|
54
|
-
if (!trimmed) return 'A reference ID is required';
|
|
55
|
-
if (!DATASET_FIELD_PATTERN.test(trimmed)) return 'Start with a letter; use only letters, numbers, and underscores';
|
|
56
|
-
const used = new Set([
|
|
57
|
-
...taken
|
|
58
|
-
].map((existing)=>existing.toLowerCase()));
|
|
59
|
-
if (used.has(trimmed.toLowerCase())) return 'Another field already uses this reference ID';
|
|
60
|
-
return null;
|
|
61
|
-
}
|
|
62
|
-
/**
|
|
63
|
-
* Parses a comma/newline separated list of HUMAN field names into
|
|
64
|
-
* {id, name} entries — "Roast preference" keeps its pretty name and gets
|
|
65
|
-
* the stable id `roast_preference` (AGL-558). Plain snake_case keys
|
|
66
|
-
* still work and pick up a humanized display name. Duplicate ids and
|
|
67
|
-
* unsalvageable entries are dropped rather than failing the set.
|
|
68
|
-
*/ export function parseDatasetFieldEntries(input) {
|
|
69
|
-
const seen = new Set();
|
|
70
|
-
const entries = [];
|
|
71
|
-
for (const raw of input.split(/[,\n]/)){
|
|
72
|
-
const trimmed = raw.trim();
|
|
73
|
-
if (!trimmed) continue;
|
|
74
|
-
const id = slugifyDatasetFieldId(trimmed);
|
|
75
|
-
if (!id || seen.has(id)) continue;
|
|
76
|
-
seen.add(id);
|
|
77
|
-
entries.push({
|
|
78
|
-
id,
|
|
79
|
-
name: DATASET_FIELD_PATTERN.test(trimmed) ? humanizeDatasetFieldId(trimmed) : trimmed
|
|
80
|
-
});
|
|
81
|
-
}
|
|
82
|
-
return entries;
|
|
83
|
-
}
|
|
23
|
+
import { DATASET_FIELD_PATTERN } from "./dataset-model-core.js";
|
|
24
|
+
// The field-id and naming helpers are pure and live with the model's pure
|
|
25
|
+
// half (AGL-3668), which the native apps generate from.
|
|
26
|
+
export { DATASET_FIELD_PATTERN, datasetDisplayName, defaultDatasetFieldId, parseDatasetFieldEntries, slugifyDatasetFieldId, validateDatasetFieldId } from "./dataset-model-core.js";
|
|
84
27
|
/**
|
|
85
28
|
* Parses a comma/newline separated field list into valid unique names;
|
|
86
29
|
* invalid entries are dropped rather than failing the whole set.
|
|
@@ -200,21 +143,6 @@ import { fillRecordAddresses } from "../record-pages/record-pages.js";
|
|
|
200
143
|
*/ export function describeDatasetRecordErrors(errors) {
|
|
201
144
|
return Object.values(errors).join('; ');
|
|
202
145
|
}
|
|
203
|
-
/**
|
|
204
|
-
* The name a dataset is shown under: `displayName`, which is what every create
|
|
205
|
-
* path writes (AGL-536), then the pre-migration `name`. Blank when the document
|
|
206
|
-
* carries neither.
|
|
207
|
-
*/ export function datasetDisplayName(dataset) {
|
|
208
|
-
for (const candidate of [
|
|
209
|
-
dataset == null ? void 0 : dataset.displayName,
|
|
210
|
-
dataset == null ? void 0 : dataset.name
|
|
211
|
-
]){
|
|
212
|
-
if (typeof candidate === 'string' && candidate.trim()) {
|
|
213
|
-
return candidate.trim();
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
return '';
|
|
217
|
-
}
|
|
218
146
|
/** Records sorted by their editor order (then id for stability). */ export function sortDatasetRecords(records) {
|
|
219
147
|
return [
|
|
220
148
|
...records
|
|
@@ -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 DatasetFieldEntry,\n type DatasetModel,\n effectiveDatasetModel,\n humanizeDatasetFieldId,\n validateDocument,\n} from './dataset-models'\nimport { fillRecordAddresses } from '../record-pages/record-pages'\n\n/** Dataset field name: starts with a letter; letters/digits/underscores. */\nexport const DATASET_FIELD_PATTERN = /^[A-Za-z][A-Za-z0-9_]*$/\n\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/**\n * Stable field id from a human name: \"Roast preference\" → \"roast_preference\".\n * Mirrors DATASET_FIELD_PATTERN; returns '' when nothing salvageable.\n */\nexport function slugifyDatasetFieldId(name: string): string {\n const slug = name\n .trim()\n .toLowerCase()\n .replace(/[\\s-]+/g, '_')\n .replace(/[^a-z0-9_]/g, '')\n .replace(/^[0-9_]+/, '')\n .replace(/_+$/, '')\n return DATASET_FIELD_PATTERN.test(slug) ? slug : ''\n}\n\n/**\n * Default reference id for a new field (AGL-578): the `slugifyDatasetFieldId`\n * slug, suffixed (`_2`, `_3`, …) to stay unique within the dataset. `taken`\n * holds the ids already in use (compared case-insensitively). Returns '' when\n * the name yields nothing valid. The user can override the result.\n */\nexport function defaultDatasetFieldId(\n name: string,\n taken: ReadonlySet<string>,\n): string {\n const base = slugifyDatasetFieldId(name)\n if (!base) return ''\n const used = new Set([...taken].map((id) => id.toLowerCase()))\n let candidate = base\n let suffix = 2\n while (used.has(candidate.toLowerCase())) candidate = `${base}_${suffix++}`\n return candidate\n}\n\n/**\n * Validate a user-entered reference id (AGL-578): non-empty, matches\n * `DATASET_FIELD_PATTERN`, and unique within the dataset (`taken` = ids already\n * used, compared case-insensitively). Returns an error message, or null when\n * the id is usable.\n */\nexport function validateDatasetFieldId(\n id: string,\n taken: ReadonlySet<string>,\n): string | null {\n const trimmed = id.trim()\n if (!trimmed) return 'A reference ID is required'\n if (!DATASET_FIELD_PATTERN.test(trimmed))\n return 'Start with a letter; use only letters, numbers, and underscores'\n const used = new Set([...taken].map((existing) => existing.toLowerCase()))\n if (used.has(trimmed.toLowerCase()))\n return 'Another field already uses this reference ID'\n return null\n}\n\n\n/**\n * Parses a comma/newline separated list of HUMAN field names into\n * {id, name} entries — \"Roast preference\" keeps its pretty name and gets\n * the stable id `roast_preference` (AGL-558). Plain snake_case keys\n * still work and pick up a humanized display name. Duplicate ids and\n * unsalvageable entries are dropped rather than failing the set.\n */\nexport function parseDatasetFieldEntries(input: string): DatasetFieldEntry[] {\n const seen = new Set<string>()\n const entries: DatasetFieldEntry[] = []\n for (const raw of input.split(/[,\\n]/)) {\n const trimmed = raw.trim()\n if (!trimmed) continue\n const id = slugifyDatasetFieldId(trimmed)\n if (!id || seen.has(id)) continue\n seen.add(id)\n entries.push({\n id,\n name: DATASET_FIELD_PATTERN.test(trimmed)\n ? humanizeDatasetFieldId(trimmed)\n : trimmed,\n })\n }\n return entries\n}\n\n/**\n * 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/**\n * The name a dataset is shown under: `displayName`, which is what every create\n * path writes (AGL-536), then the pre-migration `name`. Blank when the document\n * carries neither.\n */\nexport function datasetDisplayName(\n dataset: { displayName?: unknown; name?: unknown } | null | undefined,\n): string {\n for (const candidate of [dataset?.displayName, dataset?.name]) {\n if (typeof candidate === 'string' && candidate.trim()) {\n return candidate.trim()\n }\n }\n return ''\n}\n\n/** 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","humanizeDatasetFieldId","validateDocument","fillRecordAddresses","DATASET_FIELD_PATTERN","slugifyDatasetFieldId","name","slug","trim","toLowerCase","replace","test","defaultDatasetFieldId","taken","base","used","Set","map","id","candidate","suffix","has","validateDatasetFieldId","trimmed","existing","parseDatasetFieldEntries","input","seen","entries","raw","split","add","push","parseDatasetFields","fields","key","sanitizeRecordValues","values","field","value","String","pickDatasetRecordInput","dataset","fieldMap","model","fieldId","order","submittedKey","Object","asTextInput","picked","type","prepareDatasetRecordWrite","options","matched","keys","coerced","errors","error","describeDatasetRecordErrors","join","datasetDisplayName","displayName","sortDatasetRecords","records","sort","a","b","Number","MAX_SAFE_INTEGER","$id","localeCompare"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;CAIC;AAGD,SACEA,oBAAoB,EAGpBC,qBAAqB,EACrBC,sBAAsB,EACtBC,gBAAgB,QACX,sBAAkB;AACzB,SAASC,mBAAmB,QAAQ,kCAA8B;AAElE,0EAA0E,GAC1E,OAAO,MAAMC,wBAAwB,0BAAyB;AA+B9D;;;CAGC,GACD,OAAO,SAASC,sBAAsBC,IAAY;IAChD,MAAMC,OAAOD,KACVE,IAAI,GACJC,WAAW,GACXC,OAAO,CAAC,WAAW,KACnBA,OAAO,CAAC,e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iBAAiB0C,OAAOP,SACvB;QACD,IAAIQ,WAAWW,SAASC,MAAM,CAACZ,QAAQ,GAAGa;IAC5C;IACA,OAAO;QAAEJ;QAASjB;QAAQoB;IAAO;AACnC;AAEA;;;CAGC,GACD,OAAO,SAASE,4BACdF,MAA8B;IAE9B,OAAOT,OAAOX,MAAM,CAACoB,QAAQG,IAAI,CAAC;AACpC;AAEA;;;;CAIC,GACD,OAAO,SAASC,mBACdnB,OAAqE;IAErE,KAAK,MAAMvB,aAAa;QAACuB,2BAAAA,QAASoB,WAAW;QAAEpB,2BAAAA,QAASpC,IAAI;KAAC,CAAE;QAC7D,IAAI,OAAOa,cAAc,YAAYA,UAAUX,IAAI,IAAI;YACrD,OAAOW,UAAUX,IAAI;QACvB;IACF;IACA,OAAO;AACT;AAEA,kEAAkE,GAClE,OAAO,SAASuD,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,KACrC7B,QAAO0B,SAAAA,EAAEI,GAAG,YAALJ,SAAS,IAAIK,aAAa,CAAC/B,QAAO2B,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\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":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;CAIC;AAGD,SACEA,oBAAoB,EAEpBC,qBAAqB,EACrBC,gBAAgB,QACX,sBAAkB;AACzB,SAASC,mBAAmB,QAAQ,kCAA8B;AAClE,SAASC,qBAAqB,QAAQ,0BAAsB;AAE5D,0EAA0E;AAC1E,wDAAwD;AACxD,SACEA,qBAAqB,EACrBC,kBAAkB,EAClBC,qBAAqB,EACrBC,wBAAwB,EACxBC,qBAAqB,EACrBC,sBAAsB,QACjB,0BAAsB;AA8B7B;;;CAGC,GACD,OAAO,SAASC,mBAAmBC,KAAa;IAC9C,MAAMC,OAAO,IAAIC;IACjB,MAAMC,SAAmB,EAAE;IAC3B,KAAK,MAAMC,OAAOJ,MAAMK,KAAK,CAAC,SAAU;QACtC,MAAMC,OA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