@aglyn/plugins-data 1.14.0 → 1.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/package.json +12 -10
  2. package/src/lib/artifact/dataset-schema-artifact.server.js +4 -1
  3. package/src/lib/artifact/dataset-schema-artifact.server.js.map +1 -1
  4. package/src/lib/components/data-console-page.js +4 -2
  5. package/src/lib/components/data-console-page.js.map +1 -1
  6. package/src/lib/components/dataset-record-dialog.component.d.ts +22 -0
  7. package/src/lib/components/dataset-record-dialog.component.js +77 -54
  8. package/src/lib/components/dataset-record-dialog.component.js.map +1 -1
  9. package/src/lib/components/dataset-schema-dialog.component.js +29 -47
  10. package/src/lib/components/dataset-schema-dialog.component.js.map +1 -1
  11. package/src/lib/components/host-datasets-card.component.d.ts +12 -0
  12. package/src/lib/components/host-datasets-card.component.js +651 -220
  13. package/src/lib/components/host-datasets-card.component.js.map +1 -1
  14. package/src/lib/components/use-org-sites.d.ts +27 -0
  15. package/src/lib/components/use-org-sites.js +68 -0
  16. package/src/lib/components/use-org-sites.js.map +1 -0
  17. package/src/lib/model/data-record-routes.js +6 -3
  18. package/src/lib/model/data-record-routes.js.map +1 -1
  19. package/src/lib/model/dataset-model-core.d.ts +22 -0
  20. package/src/lib/model/dataset-model-core.js +34 -0
  21. package/src/lib/model/dataset-model-core.js.map +1 -1
  22. package/src/lib/model/dataset-rail.d.ts +88 -0
  23. package/src/lib/model/dataset-rail.js +123 -0
  24. package/src/lib/model/dataset-rail.js.map +1 -0
  25. package/src/lib/model/dataset-record-list.js +17 -2
  26. package/src/lib/model/dataset-record-list.js.map +1 -1
  27. package/src/lib/model/datasets.d.ts +14 -0
  28. package/src/lib/model/datasets.js +10 -0
  29. package/src/lib/model/datasets.js.map +1 -1
  30. package/src/lib/plugin.d.ts +5 -1
  31. package/src/lib/plugin.js +8 -3
  32. package/src/lib/plugin.js.map +1 -1
  33. package/src/lib/record-pages/record-template-section.component.js +12 -1
  34. package/src/lib/record-pages/record-template-section.component.js.map +1 -1
  35. package/src/lib/server/api-v1/datasets.js +6 -1
  36. package/src/lib/server/api-v1/datasets.js.map +1 -1
  37. package/src/lib/server/dataset-drafts.js +2 -0
  38. package/src/lib/server/dataset-drafts.js.map +1 -1
  39. package/src/lib/server/datasets-route.js +2 -1
  40. package/src/lib/server/datasets-route.js.map +1 -1
  41. package/src/lib/site-bundle/datasets-site-bundle.server.js +8 -1
  42. package/src/lib/site-bundle/datasets-site-bundle.server.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/plugins/data/src/lib/server/api-v1/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\nimport {\n checkDatasetQuota,\n checkEntitlement,\n checkQuota,\n createResourceUid,\n defaultScopeForNewResource,\n newResourceScopeFields,\n} from '@aglyn/aglyn/server'\nimport {\n ApiErrors,\n apiJson,\n dataStorageRefusal,\n listResponse,\n} from '@aglyn/tenant-data-admin'\nimport {\n type ApiV1Context,\n claimWrite,\n paginate,\n readJsonBody,\n requireScope,\n serialize,\n} from '@aglyn/tenant-data-admin/server/api-v1-kit'\nimport { FieldValue, Timestamp } from 'firebase-admin/firestore'\nimport { announceDatasetRecords as announceDatasetChange } from '../announce-dataset-records'\nimport { loadCustomFieldTypes } from '../custom-field-types'\nimport { coerceDocumentValues, datasetIntegrityFields, datasetIntegrityUpdate, effectiveDatasetModel, validateDocument } from '../../model/dataset-models'\nimport { fillRecordAddresses } from '../../record-pages/record-pages'\n\n/**\n * The organization's datasets on the customer REST API, `/v1/datasets/…`\n * (AGL-2126, AGL-3080): the datasets themselves and the records inside them.\n * Registered from this plugin's console server declarations; the console's\n * `/v1` router owns the pipeline in front — the key, the plan's API access,\n * the request quota, the rate limit — and hands every request under\n * `/v1/datasets` here.\n */\n\nconst datasetName = (data: FirebaseFirestore.DocumentData): string =>\n (data.displayName as string) ?? (data.name as string) ?? ''\n\nfunction datasetView(doc: FirebaseFirestore.DocumentSnapshot) {\n const data = doc.data() ?? {}\n return {\n id: doc.id,\n object: 'dataset',\n name: datasetName(data),\n fields: data.fields ?? [],\n created: serialize(data.createdAt) ?? null,\n }\n}\n\nfunction recordView(doc: FirebaseFirestore.DocumentSnapshot) {\n const data = doc.data() ?? {}\n return {\n id: doc.id,\n object: 'record',\n values: serialize(data.values ?? {}),\n created: serialize(data.createdAt) ?? null,\n updated: serialize(data.updatedAt) ?? null,\n }\n}\n\nfunction datasetsCollection(ctx: ApiV1Context) {\n return ctx.firestore.collection('orgs').doc(ctx.orgId).collection('datasets')\n}\n\n/** Serialized `model` ceiling, matching the console's create route. */\nconst DATASET_MODEL_MAX_BYTES = 64 * 1024\nconst DATASET_NAME_MAX = 120\nconst DATASET_FIELDS_MAX = 100\n\n/**\n * Validate the writable half of a dataset document (AGL-2126). Returns the\n * cleaned values, or the per-field map `conventions.md` publishes under\n * `validation_failed` — the same shape `validateDocument` produces for a\n * record, so a client branches on one thing across the whole resource.\n *\n * `partial` is what separates PATCH from POST: a create must be told a name\n * and at least one field, an update may send either alone. Absent keys are\n * left alone rather than cleared, because a PATCH that silently emptied\n * `fields` would take a dataset's schema away on a typo'd request body.\n */\nfunction readDatasetInput(\n body: Record<string, unknown>,\n { partial }: { partial: boolean },\n):\n | { values: { name?: string; fields?: string[]; model?: unknown } }\n | { errors: Record<string, string> } {\n const errors: Record<string, string> = {}\n const values: { name?: string; fields?: string[]; model?: unknown } = {}\n\n const hasName = body.name !== undefined\n if (hasName || !partial) {\n const name = String(body.name ?? '').trim().slice(0, DATASET_NAME_MAX)\n if (!name) errors.name = 'Required'\n else values.name = name\n }\n\n const hasFields = body.fields !== undefined\n if (hasFields || !partial) {\n if (!Array.isArray(body.fields)) {\n errors.fields = 'Must be an array of field names'\n } else {\n const fields = (body.fields as unknown[])\n .map((field) => String(field).trim())\n .filter((field) => field.length > 0)\n .slice(0, DATASET_FIELDS_MAX)\n if (fields.length === 0) errors.fields = 'At least one field is required'\n else values.fields = fields\n }\n }\n\n if (body.model !== undefined) {\n if (!body.model || typeof body.model !== 'object') {\n errors.model = 'Must be an object'\n } else if (JSON.stringify(body.model).length > DATASET_MODEL_MAX_BYTES) {\n errors.model = `Must serialize to under ${DATASET_MODEL_MAX_BYTES} bytes`\n } else {\n values.model = body.model\n }\n }\n\n return Object.keys(errors).length ? { errors } : { values }\n}\n\n/**\n * `POST /v1/datasets` (AGL-2126) — the call that lets the API bootstrap itself.\n *\n * Until this shipped, `/v1` could create and edit RECORDS but not the dataset\n * holding them, so an agency provisioning a client workspace, or a developer\n * keeping a schema in source control, had to click a dataset into existence\n * before their first API call could do anything. The console has been able to\n * do this all along (`apps/console/app/api/orgs/datasets`, `create-dataset`).\n *\n * The gates are the console route's, not a looser set. `dataStore` is the\n * entitlement, `checkDatasetQuota` is add-on aware, and — the one that is\n * invisible until it bites — `newResourceScopeFields` stamps `visibleTo`.\n * A dataset created without it matches no `array-contains-any` and therefore\n * renders on NO site at all (AGL-1044): the API would happily create data\n * that never appears anywhere, which is worse than refusing.\n */\nasync function createDataset(\n request: Request,\n ctx: ApiV1Context,\n): Promise<Response> {\n if (!checkEntitlement(ctx.org, 'dataStore')) {\n return ApiErrors.planRequired({\n message: 'Datasets are not included in this organization’s plan',\n code: 'data_store',\n headers: ctx.headers,\n })\n }\n\n const parsed = readDatasetInput(await readJsonBody(request), {\n partial: false,\n })\n if ('errors' in parsed) {\n return ApiErrors.badRequest({\n message: 'Dataset failed validation',\n code: 'validation_failed',\n fields: parsed.errors,\n headers: ctx.headers,\n })\n }\n\n /*\n * CLAIM ABOVE THE QUOTA (AGL-2296), and release on the refusal.\n *\n * This used to check the quota first and claim after, so that a refusal an\n * integrator can act on never consumed their key — a plan refusal is the\n * most retried failure there is, and it clears when somebody buys an\n * add-on. That reasoning is right and is preserved by the `release()`\n * below; the ORDERING it produced was not. A create that consumed the LAST\n * included slot could not be retried at all: the retry re-counts, is now AT\n * the band, and is refused before the claim is ever consulted — so the\n * replay never happens and the integrator cannot tell whether the dataset\n * exists. `conventions.md` publishes the opposite promise.\n *\n * Claiming first and releasing on each refusal gets both properties at\n * once, which is the trade `deleteRecord` already argues for and\n * `createContact` follows. Validation stays above: a deterministic 400 must\n * never take a key at all.\n */\n const collection = datasetsCollection(ctx)\n const claimed = await claimWrite(\n ctx,\n '*',\n request.headers.get('Idempotency-Key'),\n 'datasets',\n )\n if ('replay' in claimed) return claimed.replay\n const { claim } = claimed\n\n try {\n const datasetCount = (await collection.count().get()).data().count\n const quota = checkDatasetQuota(ctx.org, datasetCount)\n if (!quota.allowed) {\n await claim.release()\n return ApiErrors.planRequired({\n message:\n `Dataset limit reached (${quota.limit}). ` +\n (quota.upgradeRequired\n ? 'Upgrade the plan to add more.'\n : `Buy extra datasets for $${quota.addonPriceUsd}/mo each, or upgrade.`),\n code: 'dataset_quota',\n headers: ctx.headers,\n })\n }\n\n const id = createResourceUid()\n await collection.doc(id).create({\n displayName: parsed.values.name,\n fields: parsed.values.fields,\n ...(parsed.values.model ? { model: parsed.values.model } : {}),\n // AGL-1484: the required argument exists so a creator that has not\n // decided cannot compile. No site is in context on an org-scoped API\n // key, so the org's own default is the only honest answer.\n ...newResourceScopeFields(\n defaultScopeForNewResource({\n defaultResourceScope: (\n ctx.org as { defaultResourceScope?: 'org' | 'host' }\n )?.defaultResourceScope,\n hostId: null,\n }),\n ),\n createdAt: Timestamp.now(),\n })\n const view = datasetView(await collection.doc(id).get())\n // Stored as 200 so a replay is distinguishable from the fresh 201 — the\n // rule `conventions.md` publishes and `createRecord` already follows.\n await claim.record(200, view)\n return apiJson(view, { status: 201, headers: ctx.headers })\n } catch (error) {\n // Same direction as every other v1 write: a stranded key is irreversible\n // from outside, a duplicate dataset is one DELETE away.\n await claim.release()\n throw error\n }\n}\n\n/**\n * `PATCH /v1/datasets/{id}` — rename, re-field, or re-model. Takes no\n * `Idempotency-Key` and does not need one, for `updateRecord`'s reason: the\n * same body twice lands the same state AND returns the same `200`.\n */\nasync function updateDataset(\n request: Request,\n ctx: ApiV1Context,\n datasetRef: FirebaseFirestore.DocumentReference,\n): Promise<Response> {\n const snap = await datasetRef.get()\n if (!snap.exists) {\n return ApiErrors.notFound({ message: 'No such dataset', headers: ctx.headers })\n }\n const parsed = readDatasetInput(await readJsonBody(request), { partial: true })\n if ('errors' in parsed) {\n return ApiErrors.badRequest({\n message: 'Dataset failed validation',\n code: 'validation_failed',\n fields: parsed.errors,\n headers: ctx.headers,\n })\n }\n const { name, fields, model } = parsed.values\n const update: Record<string, unknown> = {}\n if (name !== undefined) update.displayName = name\n if (fields !== undefined) update.fields = fields\n if (model !== undefined) update.model = model\n // An empty body is a no-op, answered with the current dataset rather than a\n // 400: a client re-sending an unchanged object should not have to special-\n // case it, and there is no state to disagree about.\n if (Object.keys(update).length > 0) await datasetRef.update(update)\n // The fields and the model decide how every bound page formats and orders\n // this dataset's rows, so a schema change is a change to those pages — and\n // no publish follows a `/v1` write (AGL-3386). A rename alone renders\n // nothing: the display name is the console's label for the dataset. Best\n // effort, like the record writes' announce; the update is already stored.\n if (fields !== undefined || model !== undefined) {\n await announceDatasetChange({\n firestore: ctx.firestore,\n orgId: ctx.orgId,\n datasetId: datasetRef.id,\n })\n }\n return apiJson(datasetView(await datasetRef.get()), { headers: ctx.headers })\n}\n\n/**\n * `DELETE /v1/datasets/{id}` — refuses while records remain.\n *\n * A recursive delete is not something a single REST call should do quietly:\n * the records are the customer's content, and one mistyped id would take all\n * of them with no receipt naming what went. So this answers `409 conflict`\n * with the count, and the integrator deletes the records first — with the\n * same key semantics, through an endpoint that already exists.\n */\nasync function deleteDataset(\n request: Request,\n ctx: ApiV1Context,\n datasetRef: FirebaseFirestore.DocumentReference,\n): Promise<Response> {\n const claimed = await claimWrite(\n ctx,\n datasetRef.id,\n request.headers.get('Idempotency-Key'),\n 'dataset-deletes',\n )\n if ('replay' in claimed) return claimed.replay\n const { claim } = claimed\n\n try {\n const snap = await datasetRef.get()\n if (!snap.exists) {\n // Release: a wrong id is the integrator's to correct and retry with the\n // same key, exactly as `deleteRecord` does.\n await claim.release()\n return ApiErrors.notFound({ message: 'No such dataset', headers: ctx.headers })\n }\n const records = (await datasetRef.collection('records').count().get()).data()\n .count\n if (records > 0) {\n // Release too — this refusal clears once the records are gone, and the\n // retry that should then succeed must not replay the refusal.\n await claim.release()\n return ApiErrors.conflict({\n message: `Dataset still holds ${records} record${\n records === 1 ? '' : 's'\n }. Delete them first.`,\n code: 'dataset_not_empty',\n headers: ctx.headers,\n })\n }\n await datasetRef.delete()\n const view = { id: datasetRef.id, object: 'dataset', deleted: true }\n await claim.record(200, view)\n return apiJson(view, { headers: ctx.headers })\n } catch (error) {\n await claim.release()\n throw error\n }\n}\n\nexport async function handleDatasets(\n request: Request,\n ctx: ApiV1Context,\n segments: string[],\n url: URL,\n): Promise<Response> {\n const [, datasetId, sub, recordId] = segments\n\n // /v1/datasets\n if (!datasetId) {\n if (request.method === 'GET') {\n const denied = requireScope(ctx, 'datasets:read')\n if (denied) return denied\n const { docs, nextCursor } = await paginate(datasetsCollection(ctx), url)\n return listResponse(docs.map(datasetView), nextCursor, ctx.headers)\n }\n if (request.method === 'POST') {\n const denied = requireScope(ctx, 'datasets:write')\n if (denied) return denied\n return createDataset(request, ctx)\n }\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: 'GET, POST' },\n })\n }\n\n const datasetRef = datasetsCollection(ctx).doc(datasetId)\n\n // /v1/datasets/{id}\n if (!sub) {\n if (request.method === 'GET') {\n const denied = requireScope(ctx, 'datasets:read')\n if (denied) return denied\n const snap = await datasetRef.get()\n if (!snap.exists) {\n return ApiErrors.notFound({ message: 'No such dataset', headers: ctx.headers })\n }\n return apiJson(datasetView(snap), { headers: ctx.headers })\n }\n if (request.method === 'PATCH') {\n const denied = requireScope(ctx, 'datasets:write')\n if (denied) return denied\n return updateDataset(request, ctx, datasetRef)\n }\n if (request.method === 'DELETE') {\n const denied = requireScope(ctx, 'datasets:write')\n if (denied) return denied\n return deleteDataset(request, ctx, datasetRef)\n }\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: 'GET, PATCH, DELETE' },\n })\n }\n\n if (sub !== 'records') {\n return ApiErrors.notFound({ message: `Unknown endpoint`, headers: ctx.headers })\n }\n\n const datasetSnap = await datasetRef.get()\n if (!datasetSnap.exists) {\n return ApiErrors.notFound({ message: 'No such dataset', headers: ctx.headers })\n }\n const recordsRef = datasetRef.collection('records')\n\n // /v1/datasets/{id}/records\n if (!recordId) {\n if (request.method === 'GET') {\n const denied = requireScope(ctx, 'datasets:read')\n if (denied) return denied\n const { docs, nextCursor } = await paginate(recordsRef, url)\n return listResponse(docs.map(recordView), nextCursor, ctx.headers)\n }\n if (request.method === 'POST') {\n const denied = requireScope(ctx, 'datasets:write')\n if (denied) return denied\n return createRecord(request, ctx, datasetSnap, recordsRef)\n }\n return ApiErrors.methodNotAllowed({ headers: ctx.headers })\n }\n\n // /v1/datasets/{id}/records/{recordId}\n const recordRef = recordsRef.doc(recordId)\n if (request.method === 'GET') {\n const denied = requireScope(ctx, 'datasets:read')\n if (denied) return denied\n const snap = await recordRef.get()\n if (!snap.exists) return ApiErrors.notFound({ message: 'No such record', headers: ctx.headers })\n return apiJson(recordView(snap), { headers: ctx.headers })\n }\n if (request.method === 'PATCH') {\n const denied = requireScope(ctx, 'datasets:write')\n if (denied) return denied\n return updateRecord(request, ctx, datasetSnap, recordRef)\n }\n if (request.method === 'DELETE') {\n const denied = requireScope(ctx, 'datasets:write')\n if (denied) return denied\n return deleteRecord(request, ctx, datasetSnap.id, recordRef)\n }\n return ApiErrors.methodNotAllowed({ headers: ctx.headers })\n}\n\nasync function createRecord(\n request: Request,\n ctx: ApiV1Context,\n datasetSnap: FirebaseFirestore.DocumentSnapshot,\n recordsRef: FirebaseFirestore.CollectionReference,\n): Promise<Response> {\n const model = effectiveDatasetModel(datasetSnap.data() ?? {})\n // A plugin's field validator only runs once its plugin has registered it.\n await loadCustomFieldTypes(model, ctx.loadPluginSurfaces)\n const body = await readJsonBody(request)\n const coerced = fillRecordAddresses(\n model,\n coerceDocumentValues(model, (body.values as Record<string, unknown>) ?? {}),\n )\n const errors = validateDocument(model, coerced)\n if (Object.keys(errors).length) {\n return ApiErrors.badRequest({\n message: 'Record failed validation',\n headers: ctx.headers,\n code: 'validation_failed',\n // Name the offending fields (AGL-901): validateDocument already\n // produces this map, and a bare 'something is wrong' on a 20-field\n // record leaves an integrator bisecting their payload.\n fields: errors,\n })\n }\n\n /*\n * THE TWO QUOTAS THIS ROUTE DID NOT HAVE (AGL-2253).\n *\n * `POST /v1/datasets/{id}/records` counted rows only to compute `order` and\n * checked nothing: not `recordsPerDataset`, not `dataStorageMbPerOrg`. The\n * console route (`/api/orgs/datasets`) enforces both on the same write, and\n * the tenant form path enforces the rows half — so `/v1` was the one door\n * into `orgs/{id}/datasets/{id}/records` with no cap on it, and a customer\n * could blow a limit through the REST API that the UI refuses.\n *\n * They sit BELOW the idempotency claim (AGL-2296), which is a change from\n * how they shipped. Checking them first protected the key on a refusal —\n * right, and kept by the `release()` calls below — but it made a create\n * that consumed the LAST included row impossible to retry: the retry\n * re-counts, is now AT the band, and is refused before the claim is\n * consulted, so the replay never happens. The bytes leg is worse in\n * practice, because a bulk import crosses the storage band mid-run and\n * every retry from that point on is refused rather than replayed.\n *\n * The row count is reused for `order`, so this adds no read on the rows\n * leg. The bytes leg adds no read either on any plan that meters the\n * overage; see `dataStorageRefusal`.\n */\n // Idempotency: replay a prior create for the same key instead of\n // duplicating. Claimed HERE, below validation, so a deterministic 400 never\n // takes the key at all — an integrator fixes the payload and retries with\n // the same key, exactly as the POS cashier does (AGL-1691).\n const claimed = await claimWrite(\n ctx,\n datasetSnap.id,\n request.headers.get('Idempotency-Key'),\n 'records',\n )\n if ('replay' in claimed) return claimed.replay\n const { claim } = claimed\n\n try {\n const order = (await recordsRef.count().get()).data().count\n const recordQuota = checkQuota(ctx.org, 'recordsPerDataset', order)\n if (!recordQuota.allowed) {\n await claim.release()\n return ApiErrors.planRequired({\n message: `Record limit reached (${recordQuota.limit}). Upgrade the plan to add more.`,\n code: 'record_quota',\n headers: ctx.headers,\n })\n }\n const storageRefusal = await dataStorageRefusal(\n ctx.org,\n ctx.firestore.collection('orgs').doc(ctx.orgId),\n )\n if (storageRefusal) {\n await claim.release()\n return ApiErrors.planRequired({\n message:\n storageRefusal.basis === 'always'\n ? 'Dataset storage is not included in this organization’s plan'\n : `Dataset storage limit reached (${storageRefusal.includedMb} MB). Upgrade the plan to add more.`,\n code: 'data_storage_quota',\n headers: ctx.headers,\n })\n }\n\n const recordId = createResourceUid()\n await recordsRef.doc(recordId).create({\n values: coerced,\n // The integrity index the delete check queries, written on the same\n // write as the values it describes.\n ...datasetIntegrityFields(model, coerced),\n order,\n createdAt: Timestamp.now(),\n updatedAt: Timestamp.now(),\n })\n const created = await recordsRef.doc(recordId).get()\n const view = recordView(created)\n // AGL-2462 recorded that a `/v1` write cannot publish, and the ONLY thing\n // that made it visible was the hour. It announces now (AGL-3113): the\n // pages repeating over this dataset are dropped, on every site it is\n // shared with. Best effort — the record is already stored.\n await announceDatasetChange({\n firestore: ctx.firestore,\n orgId: ctx.orgId,\n datasetId: datasetSnap.id,\n })\n // Recorded as 200, never the 201 this answers: `conventions.md` publishes\n // the status as how a client tells a fresh create from a replay, and that\n // is the contract integrations branch on.\n await claim.record(200, view)\n return apiJson(view, { status: 201, headers: ctx.headers })\n } catch (error) {\n /*\n * Release on EVERY failure, including one whose outcome we cannot know —\n * the deliberate opposite of the refund (AGL-1696, `2dd52f01c`), which\n * strands the key on a throw. Same reasoning, applied where its money term\n * is absent.\n *\n * NOTHING on `/v1` moves money — the write surface is datasets, records,\n * the form-submission `read` flag and contacts (AGL-2276), while orders\n * and products stay read-only precisely because writing them would — so\n * \"a released key costs a second refund\" has no analogue here. The costs invert instead. A duplicate record is visible and\n * reversible BY THE INTEGRATOR with `DELETE /v1/datasets/{id}/records/{id}`\n * — same API, same scope, one extra call. A stranded key is irreversible\n * from outside: keys are documented as never expiring, and an integrator\n * derives them from their own upstream event ids precisely so retries\n * dedupe, so a stranded key means that event can never be written at all.\n *\n * Residual: a process killed between the claim and the record strands the\n * key regardless. `createdAtMs` is written so a sweeper can reap those.\n */\n await claim.release()\n throw error\n }\n}\n\nasync function updateRecord(\n request: Request,\n ctx: ApiV1Context,\n datasetSnap: FirebaseFirestore.DocumentSnapshot,\n recordRef: FirebaseFirestore.DocumentReference,\n): Promise<Response> {\n const snap = await recordRef.get()\n if (!snap.exists) return ApiErrors.notFound({ message: 'No such record', headers: ctx.headers })\n\n const model = effectiveDatasetModel(datasetSnap.data() ?? {})\n // A plugin's field validator only runs once its plugin has registered it.\n await loadCustomFieldTypes(model, ctx.loadPluginSurfaces)\n const body = await readJsonBody(request)\n // PATCH merges the supplied fields over the stored values.\n const merged = fillRecordAddresses(model, {\n ...((snap.get('values') as Record<string, unknown>) ?? {}),\n ...coerceDocumentValues(model, (body.values as Record<string, unknown>) ?? {}),\n })\n const errors = validateDocument(model, merged)\n if (Object.keys(errors).length) {\n return ApiErrors.badRequest({\n message: 'Record failed validation',\n headers: ctx.headers,\n code: 'validation_failed',\n // Name the offending fields (AGL-901): validateDocument already\n // produces this map, and a bare 'something is wrong' on a 20-field\n // record leaves an integrator bisecting their payload.\n fields: errors,\n })\n }\n await recordRef.update({\n values: merged,\n // A PATCH that clears the last reference has to REMOVE the index, not\n // omit it: an update leaves an omitted field standing, and a stale\n // `referencedIds` refuses a delete nothing is holding.\n ...datasetIntegrityUpdate(model, merged, FieldValue.delete()),\n updatedAt: Timestamp.now(),\n })\n const updated = await recordRef.get()\n // An edited row is as stale on a live page as a new one (AGL-3113).\n await announceDatasetChange({\n firestore: ctx.firestore,\n orgId: ctx.orgId,\n datasetId: datasetSnap.id,\n })\n return apiJson(recordView(updated), { headers: ctx.headers })\n}\n\n/**\n * Delete a record, and let a retry of the SAME attempt say so (AGL-1710).\n *\n * This used to read, 404 if absent, then delete. The state after two calls was\n * right and the response was not: an integrator whose first response was lost\n * to a timeout retried, got `404 No such record`, and had no way to separate\n * \"already deleted, you're fine\" from \"that id was wrong and nothing was ever\n * deleted\". Both readings prescribe different actions and the wrong one —\n * escalate, or re-sync the whole dataset — is the one people pick.\n *\n * The obvious fix, `204` (or a `deleted: true` 200) for ANY missing record, is\n * rejected on two counts. It is a BREAKING change: `datasets.md` publishes\n * `404 not_found \"No such record\"` on this path and clients branch on it. And\n * it spends a signal to buy one — a caller that never saw the resource would\n * get a success for a typo'd id, losing the only feedback the API gives that\n * it is asking about the wrong thing. Consistency points the same way: `GET`\n * and `PATCH` on this very path answer 404 for a missing record, and every\n * sibling `DELETE` on `/v1` — the dataset, the form submission, the contact —\n * answers the same way, so there is no convention a 204 would be matching.\n *\n * So the key identifies the ATTEMPT rather than the resource, which is what\n * the shared claim is already for. A retry of the attempt that did the\n * deleting replays its receipt; a wrong id still 404s. That expands the\n * published contract instead of changing it — a caller sending no header sees\n * byte-identical behaviour.\n *\n * The claim is taken ABOVE the existence check, which is the one place this\n * deliberately diverges from `createRecord` (which claims below validation, so\n * a deterministic 400 never burns a key). It has to: the record a retry asks\n * about is precisely the one the first attempt removed, so a claim consulted\n * after the existence check would 404 the retry without ever reaching the\n * replay — the bug verbatim. The cost is taking-and-releasing on a genuine\n * miss, which is the trade the ordering requires.\n */\nasync function deleteRecord(\n request: Request,\n ctx: ApiV1Context,\n datasetId: string,\n recordRef: FirebaseFirestore.DocumentReference,\n): Promise<Response> {\n const claimed = await claimWrite(\n ctx,\n datasetId,\n request.headers.get('Idempotency-Key'),\n 'record-deletes',\n )\n if ('replay' in claimed) return claimed.replay\n const { claim } = claimed\n\n try {\n const snap = await recordRef.get()\n if (!snap.exists) {\n // Release, so the miss does not consume the key: the integrator corrects\n // the id and retries with the same one, exactly as a create's 400 lets\n // them correct the payload. A burned key here would be worse than the\n // 404 — keys never expire, and integrators derive them from upstream\n // event ids, so the corrected delete could never be sent at all.\n await claim.release()\n return ApiErrors.notFound({ message: 'No such record', headers: ctx.headers })\n }\n await recordRef.delete()\n // A row that is gone is the same staleness as a row that changed: the\n // page goes on rendering it until its cache is dropped (AGL-3113).\n await announceDatasetChange({\n firestore: ctx.firestore,\n orgId: ctx.orgId,\n datasetId,\n })\n const view = { id: recordRef.id, object: 'record', deleted: true }\n await claim.record(200, view)\n return apiJson(view, { headers: ctx.headers })\n } catch (error) {\n // Same direction as `createRecord`: a failed attempt gives the key back.\n // Nothing here moves money, and a stranded key is the irreversible failure.\n await claim.release()\n throw error\n }\n}\n"],"names":["checkDatasetQuota","checkEntitlement","checkQuota","createResourceUid","defaultScopeForNewResource","newResourceScopeFields","ApiErrors","apiJson","dataStorageRefusal","listResponse","claimWrite","paginate","readJsonBody","requireScope","serialize","FieldValue","Timestamp","announceDatasetRecords","announceDatasetChange","loadCustomFieldTypes","coerceDocumentValues","datasetIntegrityFields","datasetIntegrityUpdate","effectiveDatasetModel","validateDocument","fillRecordAddresses","datasetName","data","displayName","name","datasetView","doc","id","object","fields","created","createdAt","recordView","values","updated","updatedAt","datasetsCollection","ctx","firestore","collection","orgId","DATASET_MODEL_MAX_BYTES","DATASET_NAME_MAX","DATASET_FIELDS_MAX","readDatasetInput","body","partial","errors","hasName","undefined","String","trim","slice","hasFields","Array","isArray","map","field","filter","length","model","JSON","stringify","Object","keys","createDataset","request","org","planRequired","message","code","headers","parsed","badRequest","claimed","get","replay","claim","datasetCount","count","quota","allowed","release","limit","upgradeRequired","addonPriceUsd","create","defaultResourceScope","hostId","now","view","record","status","error","updateDataset","datasetRef","snap","exists","notFound","update","datasetId","deleteDataset","records","conflict","delete","deleted","handleDatasets","segments","url","sub","recordId","method","denied","docs","nextCursor","methodNotAllowed","Allow","datasetSnap","recordsRef","createRecord","recordRef","updateRecord","deleteRecord","loadPluginSurfaces","coerced","order","recordQuota","storageRefusal","basis","includedMb","merged"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,iBAAiB,EACjBC,gBAAgB,EAChBC,UAAU,EACVC,iBAAiB,EACjBC,0BAA0B,EAC1BC,sBAAsB,QACjB,sBAAqB;AAC5B,SACEC,SAAS,EACTC,OAAO,EACPC,kBAAkB,EAClBC,YAAY,QACP,2BAA0B;AACjC,SAEEC,UAAU,EACVC,QAAQ,EACRC,YAAY,EACZC,YAAY,EACZC,SAAS,QACJ,6CAA4C;AACnD,SAASC,UAAU,EAAEC,SAAS,QAAQ,2BAA0B;AAChE,SAASC,0BAA0BC,qBAAqB,QAAQ,iCAA6B;AAC7F,SAASC,oBAAoB,QAAQ,2BAAuB;AAC5D,SAASC,oBAAoB,EAAEC,sBAAsB,EAAEC,sBAAsB,EAAEC,qBAAqB,EAAEC,gBAAgB,QAAQ,gCAA4B;AAC1J,SAASC,mBAAmB,QAAQ,qCAAiC;AAErE;;;;;;;CAOC,GAED,MAAMC,cAAc,CAACC;QACnB,MAACA;YAAD,QAACA,oBAAAA,KAAKC,WAAW,YAAhBD,oBAAgCA,KAAKE,IAAI,YAA1C,OAAyD;;AAE3D,SAASC,YAAYC,GAAuC;QAC7CA,WAKHJ,cACCb;IANX,MAAMa,QAAOI,YAAAA,IAAIJ,IAAI,cAARI,YAAc,CAAC;IAC5B,OAAO;QACLC,IAAID,IAAIC,EAAE;QACVC,QAAQ;QACRJ,MAAMH,YAAYC;QAClBO,MAAM,GAAEP,eAAAA,KAAKO,MAAM,YAAXP,eAAe,EAAE;QACzBQ,OAAO,GAAErB,aAAAA,UAAUa,KAAKS,SAAS,aAAxBtB,aAA6B;IACxC;AACF;AAEA,SAASuB,WAAWN,GAAuC;Q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,MAAMwB,UAAU7C,GAAG;QAChC,IAAI,CAACqB,KAAKC,MAAM,EAAE;YAChB,yEAAyE;YACzE,uEAAuE;YACvE,sEAAsE;YACtE,qEAAqE;YACrE,iEAAiE;YACjE,MAAMpB,MAAMK,OAAO;YACnB,OAAOjF,UAAUiG,QAAQ,CAAC;gBAAE7B,SAAS;gBAAkBE,SAASlC,IAAIkC,OAAO;YAAC;QAC9E;QACA,MAAMiD,UAAUhB,MAAM;QACtB,sEAAsE;QACtE,mEAAmE;QACnE,MAAM3F,sBAAsB;YAC1ByB,WAAWD,IAAIC,SAAS;YACxBE,OAAOH,IAAIG,KAAK;YAChB4D;QACF;QACA,MAAMV,OAAO;YAAE/D,IAAI6F,UAAU7F,EAAE;YAAEC,QAAQ;YAAU6E,SAAS;QAAK;QACjE,MAAM5B,MAAMc,MAAM,CAAC,KAAKD;QACxB,OAAOxF,QAAQwF,MAAM;YAAEnB,SAASlC,IAAIkC,OAAO;QAAC;IAC9C,EAAE,OAAOsB,OAAO;QACd,yEAAyE;QACzE,4EAA4E;QAC5E,MAAMhB,MAAMK,OAAO;QACnB,MAAMW;IACR;AACF"}
1
+ {"version":3,"sources":["../../../../../../../../libs/plugins/data/src/lib/server/api-v1/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\nimport {\n checkDatasetQuota,\n checkEntitlement,\n checkQuota,\n createResourceUid,\n defaultScopeForNewResource,\n newResourceScopeFields,\n} from '@aglyn/aglyn/server'\nimport {\n ApiErrors,\n apiJson,\n dataStorageRefusal,\n listResponse,\n} from '@aglyn/tenant-data-admin'\nimport {\n type ApiV1Context,\n claimWrite,\n paginate,\n readJsonBody,\n requireScope,\n serialize,\n} from '@aglyn/tenant-data-admin/server/api-v1-kit'\nimport { FieldValue, Timestamp } from 'firebase-admin/firestore'\nimport { announceDatasetRecords as announceDatasetChange } from '../announce-dataset-records'\nimport { loadCustomFieldTypes } from '../custom-field-types'\nimport { coerceDocumentValues, datasetIntegrityFields, datasetIntegrityUpdate, effectiveDatasetModel, validateDocument } from '../../model/dataset-models'\nimport { fillRecordAddresses } from '../../record-pages/record-pages'\nimport { datasetNameLower } from '../../model/datasets'\n\n/**\n * The organization's datasets on the customer REST API, `/v1/datasets/…`\n * (AGL-2126, AGL-3080): the datasets themselves and the records inside them.\n * Registered from this plugin's console server declarations; the console's\n * `/v1` router owns the pipeline in front — the key, the plan's API access,\n * the request quota, the rate limit — and hands every request under\n * `/v1/datasets` here.\n */\n\nconst datasetName = (data: FirebaseFirestore.DocumentData): string =>\n (data.displayName as string) ?? (data.name as string) ?? ''\n\nfunction datasetView(doc: FirebaseFirestore.DocumentSnapshot) {\n const data = doc.data() ?? {}\n return {\n id: doc.id,\n object: 'dataset',\n name: datasetName(data),\n fields: data.fields ?? [],\n created: serialize(data.createdAt) ?? null,\n }\n}\n\nfunction recordView(doc: FirebaseFirestore.DocumentSnapshot) {\n const data = doc.data() ?? {}\n return {\n id: doc.id,\n object: 'record',\n values: serialize(data.values ?? {}),\n created: serialize(data.createdAt) ?? null,\n updated: serialize(data.updatedAt) ?? null,\n }\n}\n\nfunction datasetsCollection(ctx: ApiV1Context) {\n return ctx.firestore.collection('orgs').doc(ctx.orgId).collection('datasets')\n}\n\n/** Serialized `model` ceiling, matching the console's create route. */\nconst DATASET_MODEL_MAX_BYTES = 64 * 1024\nconst DATASET_NAME_MAX = 120\nconst DATASET_FIELDS_MAX = 100\n\n/**\n * Validate the writable half of a dataset document (AGL-2126). Returns the\n * cleaned values, or the per-field map `conventions.md` publishes under\n * `validation_failed` — the same shape `validateDocument` produces for a\n * record, so a client branches on one thing across the whole resource.\n *\n * `partial` is what separates PATCH from POST: a create must be told a name\n * and at least one field, an update may send either alone. Absent keys are\n * left alone rather than cleared, because a PATCH that silently emptied\n * `fields` would take a dataset's schema away on a typo'd request body.\n */\nfunction readDatasetInput(\n body: Record<string, unknown>,\n { partial }: { partial: boolean },\n):\n | { values: { name?: string; fields?: string[]; model?: unknown } }\n | { errors: Record<string, string> } {\n const errors: Record<string, string> = {}\n const values: { name?: string; fields?: string[]; model?: unknown } = {}\n\n const hasName = body.name !== undefined\n if (hasName || !partial) {\n const name = String(body.name ?? '').trim().slice(0, DATASET_NAME_MAX)\n if (!name) errors.name = 'Required'\n else values.name = name\n }\n\n const hasFields = body.fields !== undefined\n if (hasFields || !partial) {\n if (!Array.isArray(body.fields)) {\n errors.fields = 'Must be an array of field names'\n } else {\n const fields = (body.fields as unknown[])\n .map((field) => String(field).trim())\n .filter((field) => field.length > 0)\n .slice(0, DATASET_FIELDS_MAX)\n if (fields.length === 0) errors.fields = 'At least one field is required'\n else values.fields = fields\n }\n }\n\n if (body.model !== undefined) {\n if (!body.model || typeof body.model !== 'object') {\n errors.model = 'Must be an object'\n } else if (JSON.stringify(body.model).length > DATASET_MODEL_MAX_BYTES) {\n errors.model = `Must serialize to under ${DATASET_MODEL_MAX_BYTES} bytes`\n } else {\n values.model = body.model\n }\n }\n\n return Object.keys(errors).length ? { errors } : { values }\n}\n\n/**\n * `POST /v1/datasets` (AGL-2126) — the call that lets the API bootstrap itself.\n *\n * Until this shipped, `/v1` could create and edit RECORDS but not the dataset\n * holding them, so an agency provisioning a client workspace, or a developer\n * keeping a schema in source control, had to click a dataset into existence\n * before their first API call could do anything. The console has been able to\n * do this all along (`apps/console/app/api/orgs/datasets`, `create-dataset`).\n *\n * The gates are the console route's, not a looser set. `dataStore` is the\n * entitlement, `checkDatasetQuota` is add-on aware, and — the one that is\n * invisible until it bites — `newResourceScopeFields` stamps `visibleTo`.\n * A dataset created without it matches no `array-contains-any` and therefore\n * renders on NO site at all (AGL-1044): the API would happily create data\n * that never appears anywhere, which is worse than refusing.\n */\nasync function createDataset(\n request: Request,\n ctx: ApiV1Context,\n): Promise<Response> {\n if (!checkEntitlement(ctx.org, 'dataStore')) {\n return ApiErrors.planRequired({\n message: 'Datasets are not included in this organization’s plan',\n code: 'data_store',\n headers: ctx.headers,\n })\n }\n\n const parsed = readDatasetInput(await readJsonBody(request), {\n partial: false,\n })\n if ('errors' in parsed) {\n return ApiErrors.badRequest({\n message: 'Dataset failed validation',\n code: 'validation_failed',\n fields: parsed.errors,\n headers: ctx.headers,\n })\n }\n\n /*\n * CLAIM ABOVE THE QUOTA (AGL-2296), and release on the refusal.\n *\n * This used to check the quota first and claim after, so that a refusal an\n * integrator can act on never consumed their key — a plan refusal is the\n * most retried failure there is, and it clears when somebody buys an\n * add-on. That reasoning is right and is preserved by the `release()`\n * below; the ORDERING it produced was not. A create that consumed the LAST\n * included slot could not be retried at all: the retry re-counts, is now AT\n * the band, and is refused before the claim is ever consulted — so the\n * replay never happens and the integrator cannot tell whether the dataset\n * exists. `conventions.md` publishes the opposite promise.\n *\n * Claiming first and releasing on each refusal gets both properties at\n * once, which is the trade `deleteRecord` already argues for and\n * `createContact` follows. Validation stays above: a deterministic 400 must\n * never take a key at all.\n */\n const collection = datasetsCollection(ctx)\n const claimed = await claimWrite(\n ctx,\n '*',\n request.headers.get('Idempotency-Key'),\n 'datasets',\n )\n if ('replay' in claimed) return claimed.replay\n const { claim } = claimed\n\n try {\n const datasetCount = (await collection.count().get()).data().count\n const quota = checkDatasetQuota(ctx.org, datasetCount)\n if (!quota.allowed) {\n await claim.release()\n return ApiErrors.planRequired({\n message:\n `Dataset limit reached (${quota.limit}). ` +\n (quota.upgradeRequired\n ? 'Upgrade the plan to add more.'\n : `Buy extra datasets for $${quota.addonPriceUsd}/mo each, or upgrade.`),\n code: 'dataset_quota',\n headers: ctx.headers,\n })\n }\n\n const id = createResourceUid()\n await collection.doc(id).create({\n displayName: parsed.values.name,\n nameLower: datasetNameLower(parsed.values.name),\n fields: parsed.values.fields,\n ...(parsed.values.model ? { model: parsed.values.model } : {}),\n // AGL-1484: the required argument exists so a creator that has not\n // decided cannot compile. No site is in context on an org-scoped API\n // key, so the org's own default is the only honest answer.\n ...newResourceScopeFields(\n defaultScopeForNewResource({\n defaultResourceScope: (\n ctx.org as { defaultResourceScope?: 'org' | 'host' }\n )?.defaultResourceScope,\n hostId: null,\n }),\n ),\n createdAt: Timestamp.now(),\n })\n const view = datasetView(await collection.doc(id).get())\n // Stored as 200 so a replay is distinguishable from the fresh 201 — the\n // rule `conventions.md` publishes and `createRecord` already follows.\n await claim.record(200, view)\n return apiJson(view, { status: 201, headers: ctx.headers })\n } catch (error) {\n // Same direction as every other v1 write: a stranded key is irreversible\n // from outside, a duplicate dataset is one DELETE away.\n await claim.release()\n throw error\n }\n}\n\n/**\n * `PATCH /v1/datasets/{id}` — rename, re-field, or re-model. Takes no\n * `Idempotency-Key` and does not need one, for `updateRecord`'s reason: the\n * same body twice lands the same state AND returns the same `200`.\n */\nasync function updateDataset(\n request: Request,\n ctx: ApiV1Context,\n datasetRef: FirebaseFirestore.DocumentReference,\n): Promise<Response> {\n const snap = await datasetRef.get()\n if (!snap.exists) {\n return ApiErrors.notFound({ message: 'No such dataset', headers: ctx.headers })\n }\n const parsed = readDatasetInput(await readJsonBody(request), { partial: true })\n if ('errors' in parsed) {\n return ApiErrors.badRequest({\n message: 'Dataset failed validation',\n code: 'validation_failed',\n fields: parsed.errors,\n headers: ctx.headers,\n })\n }\n const { name, fields, model } = parsed.values\n const update: Record<string, unknown> = {}\n if (name !== undefined) {\n update.displayName = name\n update.nameLower = datasetNameLower(name)\n }\n if (fields !== undefined) update.fields = fields\n if (model !== undefined) update.model = model\n // An empty body is a no-op, answered with the current dataset rather than a\n // 400: a client re-sending an unchanged object should not have to special-\n // case it, and there is no state to disagree about.\n if (Object.keys(update).length > 0) await datasetRef.update(update)\n // The fields and the model decide how every bound page formats and orders\n // this dataset's rows, so a schema change is a change to those pages — and\n // no publish follows a `/v1` write (AGL-3386). A rename alone renders\n // nothing: the display name is the console's label for the dataset. Best\n // effort, like the record writes' announce; the update is already stored.\n if (fields !== undefined || model !== undefined) {\n await announceDatasetChange({\n firestore: ctx.firestore,\n orgId: ctx.orgId,\n datasetId: datasetRef.id,\n })\n }\n return apiJson(datasetView(await datasetRef.get()), { headers: ctx.headers })\n}\n\n/**\n * `DELETE /v1/datasets/{id}` — refuses while records remain.\n *\n * A recursive delete is not something a single REST call should do quietly:\n * the records are the customer's content, and one mistyped id would take all\n * of them with no receipt naming what went. So this answers `409 conflict`\n * with the count, and the integrator deletes the records first — with the\n * same key semantics, through an endpoint that already exists.\n */\nasync function deleteDataset(\n request: Request,\n ctx: ApiV1Context,\n datasetRef: FirebaseFirestore.DocumentReference,\n): Promise<Response> {\n const claimed = await claimWrite(\n ctx,\n datasetRef.id,\n request.headers.get('Idempotency-Key'),\n 'dataset-deletes',\n )\n if ('replay' in claimed) return claimed.replay\n const { claim } = claimed\n\n try {\n const snap = await datasetRef.get()\n if (!snap.exists) {\n // Release: a wrong id is the integrator's to correct and retry with the\n // same key, exactly as `deleteRecord` does.\n await claim.release()\n return ApiErrors.notFound({ message: 'No such dataset', headers: ctx.headers })\n }\n const records = (await datasetRef.collection('records').count().get()).data()\n .count\n if (records > 0) {\n // Release too — this refusal clears once the records are gone, and the\n // retry that should then succeed must not replay the refusal.\n await claim.release()\n return ApiErrors.conflict({\n message: `Dataset still holds ${records} record${\n records === 1 ? '' : 's'\n }. Delete them first.`,\n code: 'dataset_not_empty',\n headers: ctx.headers,\n })\n }\n await datasetRef.delete()\n const view = { id: datasetRef.id, object: 'dataset', deleted: true }\n await claim.record(200, view)\n return apiJson(view, { headers: ctx.headers })\n } catch (error) {\n await claim.release()\n throw error\n }\n}\n\nexport async function handleDatasets(\n request: Request,\n ctx: ApiV1Context,\n segments: string[],\n url: URL,\n): Promise<Response> {\n const [, datasetId, sub, recordId] = segments\n\n // /v1/datasets\n if (!datasetId) {\n if (request.method === 'GET') {\n const denied = requireScope(ctx, 'datasets:read')\n if (denied) return denied\n const { docs, nextCursor } = await paginate(datasetsCollection(ctx), url)\n return listResponse(docs.map(datasetView), nextCursor, ctx.headers)\n }\n if (request.method === 'POST') {\n const denied = requireScope(ctx, 'datasets:write')\n if (denied) return denied\n return createDataset(request, ctx)\n }\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: 'GET, POST' },\n })\n }\n\n const datasetRef = datasetsCollection(ctx).doc(datasetId)\n\n // /v1/datasets/{id}\n if (!sub) {\n if (request.method === 'GET') {\n const denied = requireScope(ctx, 'datasets:read')\n if (denied) return denied\n const snap = await datasetRef.get()\n if (!snap.exists) {\n return ApiErrors.notFound({ message: 'No such dataset', headers: ctx.headers })\n }\n return apiJson(datasetView(snap), { headers: ctx.headers })\n }\n if (request.method === 'PATCH') {\n const denied = requireScope(ctx, 'datasets:write')\n if (denied) return denied\n return updateDataset(request, ctx, datasetRef)\n }\n if (request.method === 'DELETE') {\n const denied = requireScope(ctx, 'datasets:write')\n if (denied) return denied\n return deleteDataset(request, ctx, datasetRef)\n }\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: 'GET, PATCH, DELETE' },\n })\n }\n\n if (sub !== 'records') {\n return ApiErrors.notFound({ message: `Unknown endpoint`, headers: ctx.headers })\n }\n\n const datasetSnap = await datasetRef.get()\n if (!datasetSnap.exists) {\n return ApiErrors.notFound({ message: 'No such dataset', headers: ctx.headers })\n }\n const recordsRef = datasetRef.collection('records')\n\n // /v1/datasets/{id}/records\n if (!recordId) {\n if (request.method === 'GET') {\n const denied = requireScope(ctx, 'datasets:read')\n if (denied) return denied\n const { docs, nextCursor } = await paginate(recordsRef, url)\n return listResponse(docs.map(recordView), nextCursor, ctx.headers)\n }\n if (request.method === 'POST') {\n const denied = requireScope(ctx, 'datasets:write')\n if (denied) return denied\n return createRecord(request, ctx, datasetSnap, recordsRef)\n }\n return ApiErrors.methodNotAllowed({ headers: ctx.headers })\n }\n\n // /v1/datasets/{id}/records/{recordId}\n const recordRef = recordsRef.doc(recordId)\n if (request.method === 'GET') {\n const denied = requireScope(ctx, 'datasets:read')\n if (denied) return denied\n const snap = await recordRef.get()\n if (!snap.exists) return ApiErrors.notFound({ message: 'No such record', headers: ctx.headers })\n return apiJson(recordView(snap), { headers: ctx.headers })\n }\n if (request.method === 'PATCH') {\n const denied = requireScope(ctx, 'datasets:write')\n if (denied) return denied\n return updateRecord(request, ctx, datasetSnap, recordRef)\n }\n if (request.method === 'DELETE') {\n const denied = requireScope(ctx, 'datasets:write')\n if (denied) return denied\n return deleteRecord(request, ctx, datasetSnap.id, recordRef)\n }\n return ApiErrors.methodNotAllowed({ headers: ctx.headers })\n}\n\nasync function createRecord(\n request: Request,\n ctx: ApiV1Context,\n datasetSnap: FirebaseFirestore.DocumentSnapshot,\n recordsRef: FirebaseFirestore.CollectionReference,\n): Promise<Response> {\n const model = effectiveDatasetModel(datasetSnap.data() ?? {})\n // A plugin's field validator only runs once its plugin has registered it.\n await loadCustomFieldTypes(model, ctx.loadPluginSurfaces)\n const body = await readJsonBody(request)\n const coerced = fillRecordAddresses(\n model,\n coerceDocumentValues(model, (body.values as Record<string, unknown>) ?? {}),\n )\n const errors = validateDocument(model, coerced)\n if (Object.keys(errors).length) {\n return ApiErrors.badRequest({\n message: 'Record failed validation',\n headers: ctx.headers,\n code: 'validation_failed',\n // Name the offending fields (AGL-901): validateDocument already\n // produces this map, and a bare 'something is wrong' on a 20-field\n // record leaves an integrator bisecting their payload.\n fields: errors,\n })\n }\n\n /*\n * THE TWO QUOTAS THIS ROUTE DID NOT HAVE (AGL-2253).\n *\n * `POST /v1/datasets/{id}/records` counted rows only to compute `order` and\n * checked nothing: not `recordsPerDataset`, not `dataStorageMbPerOrg`. The\n * console route (`/api/orgs/datasets`) enforces both on the same write, and\n * the tenant form path enforces the rows half — so `/v1` was the one door\n * into `orgs/{id}/datasets/{id}/records` with no cap on it, and a customer\n * could blow a limit through the REST API that the UI refuses.\n *\n * They sit BELOW the idempotency claim (AGL-2296), which is a change from\n * how they shipped. Checking them first protected the key on a refusal —\n * right, and kept by the `release()` calls below — but it made a create\n * that consumed the LAST included row impossible to retry: the retry\n * re-counts, is now AT the band, and is refused before the claim is\n * consulted, so the replay never happens. The bytes leg is worse in\n * practice, because a bulk import crosses the storage band mid-run and\n * every retry from that point on is refused rather than replayed.\n *\n * The row count is reused for `order`, so this adds no read on the rows\n * leg. The bytes leg adds no read either on any plan that meters the\n * overage; see `dataStorageRefusal`.\n */\n // Idempotency: replay a prior create for the same key instead of\n // duplicating. Claimed HERE, below validation, so a deterministic 400 never\n // takes the key at all — an integrator fixes the payload and retries with\n // the same key, exactly as the POS cashier does (AGL-1691).\n const claimed = await claimWrite(\n ctx,\n datasetSnap.id,\n request.headers.get('Idempotency-Key'),\n 'records',\n )\n if ('replay' in claimed) return claimed.replay\n const { claim } = claimed\n\n try {\n const order = (await recordsRef.count().get()).data().count\n const recordQuota = checkQuota(ctx.org, 'recordsPerDataset', order)\n if (!recordQuota.allowed) {\n await claim.release()\n return ApiErrors.planRequired({\n message: `Record limit reached (${recordQuota.limit}). Upgrade the plan to add more.`,\n code: 'record_quota',\n headers: ctx.headers,\n })\n }\n const storageRefusal = await dataStorageRefusal(\n ctx.org,\n ctx.firestore.collection('orgs').doc(ctx.orgId),\n )\n if (storageRefusal) {\n await claim.release()\n return ApiErrors.planRequired({\n message:\n storageRefusal.basis === 'always'\n ? 'Dataset storage is not included in this organization’s plan'\n : `Dataset storage limit reached (${storageRefusal.includedMb} MB). Upgrade the plan to add more.`,\n code: 'data_storage_quota',\n headers: ctx.headers,\n })\n }\n\n const recordId = createResourceUid()\n await recordsRef.doc(recordId).create({\n values: coerced,\n // The integrity index the delete check queries, written on the same\n // write as the values it describes.\n ...datasetIntegrityFields(model, coerced),\n order,\n createdAt: Timestamp.now(),\n updatedAt: Timestamp.now(),\n })\n const created = await recordsRef.doc(recordId).get()\n const view = recordView(created)\n // AGL-2462 recorded that a `/v1` write cannot publish, and the ONLY thing\n // that made it visible was the hour. It announces now (AGL-3113): the\n // pages repeating over this dataset are dropped, on every site it is\n // shared with. Best effort — the record is already stored.\n await announceDatasetChange({\n firestore: ctx.firestore,\n orgId: ctx.orgId,\n datasetId: datasetSnap.id,\n })\n // Recorded as 200, never the 201 this answers: `conventions.md` publishes\n // the status as how a client tells a fresh create from a replay, and that\n // is the contract integrations branch on.\n await claim.record(200, view)\n return apiJson(view, { status: 201, headers: ctx.headers })\n } catch (error) {\n /*\n * Release on EVERY failure, including one whose outcome we cannot know —\n * the deliberate opposite of the refund (AGL-1696, `2dd52f01c`), which\n * strands the key on a throw. Same reasoning, applied where its money term\n * is absent.\n *\n * NOTHING on `/v1` moves money — the write surface is datasets, records,\n * the form-submission `read` flag and contacts (AGL-2276), while orders\n * and products stay read-only precisely because writing them would — so\n * \"a released key costs a second refund\" has no analogue here. The costs invert instead. A duplicate record is visible and\n * reversible BY THE INTEGRATOR with `DELETE /v1/datasets/{id}/records/{id}`\n * — same API, same scope, one extra call. A stranded key is irreversible\n * from outside: keys are documented as never expiring, and an integrator\n * derives them from their own upstream event ids precisely so retries\n * dedupe, so a stranded key means that event can never be written at all.\n *\n * Residual: a process killed between the claim and the record strands the\n * key regardless. `createdAtMs` is written so a sweeper can reap those.\n */\n await claim.release()\n throw error\n }\n}\n\nasync function updateRecord(\n request: Request,\n ctx: ApiV1Context,\n datasetSnap: FirebaseFirestore.DocumentSnapshot,\n recordRef: FirebaseFirestore.DocumentReference,\n): Promise<Response> {\n const snap = await recordRef.get()\n if (!snap.exists) return ApiErrors.notFound({ message: 'No such record', headers: ctx.headers })\n\n const model = effectiveDatasetModel(datasetSnap.data() ?? {})\n // A plugin's field validator only runs once its plugin has registered it.\n await loadCustomFieldTypes(model, ctx.loadPluginSurfaces)\n const body = await readJsonBody(request)\n // PATCH merges the supplied fields over the stored values.\n const merged = fillRecordAddresses(model, {\n ...((snap.get('values') as Record<string, unknown>) ?? {}),\n ...coerceDocumentValues(model, (body.values as Record<string, unknown>) ?? {}),\n })\n const errors = validateDocument(model, merged)\n if (Object.keys(errors).length) {\n return ApiErrors.badRequest({\n message: 'Record failed validation',\n headers: ctx.headers,\n code: 'validation_failed',\n // Name the offending fields (AGL-901): validateDocument already\n // produces this map, and a bare 'something is wrong' on a 20-field\n // record leaves an integrator bisecting their payload.\n fields: errors,\n })\n }\n await recordRef.update({\n values: merged,\n // A PATCH that clears the last reference has to REMOVE the index, not\n // omit it: an update leaves an omitted field standing, and a stale\n // `referencedIds` refuses a delete nothing is holding.\n ...datasetIntegrityUpdate(model, merged, FieldValue.delete()),\n updatedAt: Timestamp.now(),\n })\n const updated = await recordRef.get()\n // An edited row is as stale on a live page as a new one (AGL-3113).\n await announceDatasetChange({\n firestore: ctx.firestore,\n orgId: ctx.orgId,\n datasetId: datasetSnap.id,\n })\n return apiJson(recordView(updated), { headers: ctx.headers })\n}\n\n/**\n * Delete a record, and let a retry of the SAME attempt say so (AGL-1710).\n *\n * This used to read, 404 if absent, then delete. The state after two calls was\n * right and the response was not: an integrator whose first response was lost\n * to a timeout retried, got `404 No such record`, and had no way to separate\n * \"already deleted, you're fine\" from \"that id was wrong and nothing was ever\n * deleted\". Both readings prescribe different actions and the wrong one —\n * escalate, or re-sync the whole dataset — is the one people pick.\n *\n * The obvious fix, `204` (or a `deleted: true` 200) for ANY missing record, is\n * rejected on two counts. It is a BREAKING change: `datasets.md` publishes\n * `404 not_found \"No such record\"` on this path and clients branch on it. And\n * it spends a signal to buy one — a caller that never saw the resource would\n * get a success for a typo'd id, losing the only feedback the API gives that\n * it is asking about the wrong thing. Consistency points the same way: `GET`\n * and `PATCH` on this very path answer 404 for a missing record, and every\n * sibling `DELETE` on `/v1` — the dataset, the form submission, the contact —\n * answers the same way, so there is no convention a 204 would be matching.\n *\n * So the key identifies the ATTEMPT rather than the resource, which is what\n * the shared claim is already for. A retry of the attempt that did the\n * deleting replays its receipt; a wrong id still 404s. That expands the\n * published contract instead of changing it — a caller sending no header sees\n * byte-identical behaviour.\n *\n * The claim is taken ABOVE the existence check, which is the one place this\n * deliberately diverges from `createRecord` (which claims below validation, so\n * a deterministic 400 never burns a key). It has to: the record a retry asks\n * about is precisely the one the first attempt removed, so a claim consulted\n * after the existence check would 404 the retry without ever reaching the\n * replay — the bug verbatim. The cost is taking-and-releasing on a genuine\n * miss, which is the trade the ordering requires.\n */\nasync function deleteRecord(\n request: Request,\n ctx: ApiV1Context,\n datasetId: string,\n recordRef: FirebaseFirestore.DocumentReference,\n): Promise<Response> {\n const claimed = await claimWrite(\n ctx,\n datasetId,\n request.headers.get('Idempotency-Key'),\n 'record-deletes',\n )\n if ('replay' in claimed) return claimed.replay\n const { claim } = claimed\n\n try {\n const snap = await recordRef.get()\n if (!snap.exists) {\n // Release, so the miss does not consume the key: the integrator corrects\n // the id and retries with the same one, exactly as a create's 400 lets\n // them correct the payload. A burned key here would be worse than the\n // 404 — keys never expire, and integrators derive them from upstream\n // event ids, so the corrected delete could never be sent at all.\n await claim.release()\n return ApiErrors.notFound({ message: 'No such record', headers: ctx.headers })\n }\n await recordRef.delete()\n // A row that is gone is the same staleness as a row that changed: the\n // page goes on rendering it until its cache is dropped (AGL-3113).\n await announceDatasetChange({\n firestore: ctx.firestore,\n orgId: ctx.orgId,\n datasetId,\n })\n const view = { id: recordRef.id, object: 'record', deleted: true }\n await claim.record(200, view)\n return apiJson(view, { headers: ctx.headers })\n } catch (error) {\n // Same direction as `createRecord`: a failed attempt gives the key back.\n // Nothing here moves money, and a stranded key is the irreversible failure.\n await claim.release()\n throw error\n }\n}\n"],"names":["checkDatasetQuota","checkEntitlement","checkQuota","createResourceUid","defaultScopeForNewResource","newResourceScopeFields","ApiErrors","apiJson","dataStorageRefusal","listResponse","claimWrite","paginate","readJsonBody","requireScope","serialize","FieldValue","Timestamp","announceDatasetRecords","announceDatasetChange","loadCustomFieldTypes","coerceDocumentValues","datasetIntegrityFields","datasetIntegrityUpdate","effectiveDatasetModel","validateDocument","fillRecordAddresses","datasetNameLower","datasetName","data","displayName","name","datasetView","doc","id","object","fields","created","createdAt","recordView","values","updated","updatedAt","datasetsCollection","ctx","firestore","collection","orgId","DATASET_MODEL_MAX_BYTES","DATASET_NAME_MAX","DATASET_FIELDS_MAX","readDatasetInput","body","partial","errors","hasName","undefined","String","trim","slice","hasFields","Array","isArray","map","field","filter","length","model","JSON","stringify","Object","keys","createDataset","request","org","planRequired","message","code","headers","parsed","badRequest","claimed","get","replay","claim","datasetCount","count","quota","allowed","release","limit","upgradeRequired","addonPriceUsd","create","nameLower","defaultResourceScope","hostId","now","view","record","status","error","updateDataset","datasetRef","snap","exists","notFound","update","datasetId","deleteDataset","records","conflict","delete","deleted","handleDatasets","segments","url","sub","recordId","method","denied","docs","nextCursor","methodNotAllowed","Allow","datasetSnap","recordsRef","createRecord","recordRef","updateRecord","deleteRecord","loadPluginSurfaces","coerced","order","recordQuota","storageRefusal","basis","includedMb","merged"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,iBAAiB,EACjBC,gBAAgB,EAChBC,UAAU,EACVC,iBAAiB,EACjBC,0BAA0B,EAC1BC,sBAAsB,QACjB,sBAAqB;AAC5B,SACEC,SAAS,EACTC,OAAO,EACPC,kBAAkB,EAClBC,YAAY,QACP,2BAA0B;AACjC,SAEEC,UAAU,EACVC,QAAQ,EACRC,YAAY,EACZC,YAAY,EACZC,SAAS,QACJ,6CAA4C;AACnD,SAASC,UAAU,EAAEC,SAAS,QAAQ,2BAA0B;AAChE,SAASC,0BAA0BC,qBAAqB,QAAQ,iCAA6B;AAC7F,SAASC,oBAAoB,QAAQ,2BAAuB;AAC5D,SAASC,oBAAoB,EAAEC,sBAAsB,EAAEC,sBAAsB,EAAEC,qBAAqB,EAAEC,gBAAgB,QAAQ,gCAA4B;AAC1J,SAASC,mBAAmB,QAAQ,qCAAiC;AACrE,SAASC,gBAAgB,QA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IAC9C,EAAE,OAAOuB,OAAO;QACd,yEAAyE;QACzE,4EAA4E;QAC5E,MAAMjB,MAAMK,OAAO;QACnB,MAAMY;IACR;AACF"}
@@ -26,6 +26,7 @@ import { dataStorageRefusal } from "@aglyn/tenant-data-admin/server/data-storage
26
26
  import { memberHasOrgPermission, resolveOrgIdForHost, resolveOrgMembership } from "@aglyn/tenant-data-admin/server/organizations";
27
27
  import { isServerReleaseFlagOnForOrg } from "@aglyn/tenant-data-admin/server/release-flags";
28
28
  import { BUNDLE_ID } from "../constants/bundle-common.js";
29
+ import { datasetNameLower } from "../model/datasets.js";
29
30
  import { coerceDocumentValues, datasetIntegrityFields, datasetIntegrityUpdate, defaultDatasetFieldId, validateDocument } from "../model/dataset-models.js";
30
31
  import { DATASET_IMAGE_FIELD_TYPE, isDatasetImageValue } from "../model/dataset-image-field.js";
31
32
  import { DATASET_PAGE_FIELD_TYPE, isDatasetPageValue } from "../model/dataset-page-field.js";
@@ -449,6 +450,7 @@ export function createDatasetDraftWriter(deps = {}) {
449
450
  };
450
451
  tx.create(datasetRef, _extends({
451
452
  displayName: name,
453
+ nameLower: datasetNameLower(name),
452
454
  fields: [
453
455
  ...model.order
454
456
  ],
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/server/dataset-drafts.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport { permissionRefusalText } from '@aglyn/aglyn/app-utils/org-permissions'\nimport { memberCanSee } from '@aglyn/aglyn/app-utils/organizations'\nimport { checkDatasetQuota, checkEntitlement, checkQuota } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { hostScopeToken, newResourceScopeFields } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport {\n registerPluginResourceDraftWriter,\n type PluginDraftCheck,\n type PluginDraftContext,\n type PluginDraftRecord,\n type PluginDraftRecordsRevise,\n type PluginDraftRefusal,\n type PluginDraftWrite,\n type PluginResourceDraftWriter,\n} from '@aglyn/aglyn/plugin-manager/plugin-resource-drafts'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { dataStorageRefusal } from '@aglyn/tenant-data-admin/server/data-storage-gate'\nimport {\n memberHasOrgPermission,\n resolveOrgIdForHost,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin/server/organizations'\nimport { isServerReleaseFlagOnForOrg } from '@aglyn/tenant-data-admin/server/release-flags'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport {\n coerceDocumentValues,\n datasetIntegrityFields,\n datasetIntegrityUpdate,\n defaultDatasetFieldId,\n validateDocument,\n type DatasetFieldType,\n type DatasetModel,\n} from '../model/dataset-models'\nimport { DATASET_IMAGE_FIELD_TYPE, isDatasetImageValue } from '../model/dataset-image-field'\nimport { DATASET_PAGE_FIELD_TYPE, isDatasetPageValue } from '../model/dataset-page-field'\nimport {\n RECORD_PAGE_ADDRESS_FIELD_TYPE,\n RECORD_PAGE_ADDRESS_MAX,\n uniqueRecordAddresses,\n} from '../record-pages/record-pages'\n\n/**\n * A DATASET ANOTHER PLUGIN ASKS FOR (AGL-3616).\n *\n * The draft writer this plugin registers for the `dataset` resource on the\n * core's resource-drafts seam. Aglyn AI builds a menu, a team, a list of\n * services or a portfolio as a dataset, the way the docs teach a person to,\n * and asks for the writer by name, so every rule is this plugin's:\n *\n * - THE DOCUMENT is the one the Data card's create makes: a display name,\n * the flat `fields` mirror and a typed model, shared with the site it is\n * made for and no other (AGL-4003), and the\n * seeded records, each with the integrity and filter index every record\n * write carries. Where a record page is wanted the model gains a \"Page\n * address\" field that fills from a text field, and every seeded record a\n * unique address (`uniqueRecordAddresses`), so the member's Record pages\n * save has nothing left to fill.\n * - THE ROOM is `datasetsPerOrg` (add-ons included, `checkDatasetQuota`),\n * counted INSIDE the transaction that creates, as the datasets route\n * counts it; the records are held to `recordsPerDataset` and the dataset\n * storage band.\n * - THE PLAN is `dataStore` (Starter and up), THE FLAG `release_data_store`,\n * and THE MEMBER an org member holding \"Manage data\" (`data.manage`,\n * AGL-4047), whose access reaches the site — refused in the route's own\n * words.\n * - THE CHECK holds every record to the model it is written under\n * (`validateDocument`), so what is seeded is what a person could type.\n * - A PHOTO is an `image` field (AGL-3616): text storage riding the\n * \"Image\" custom type, each value an address the site's Image element\n * shows (`isDatasetImageValue`), so a portfolio's pieces or a team keep\n * the photo the page that lists them binds.\n * - A PAGE is a `page` field (AGL-3763): text storage riding the \"Page\"\n * custom type, each value one of the site's pages as `screen:{id}`\n * (`isDatasetPageValue`), which a Button or Link binds.\n * - A SAMPLE is a seeded record the caller marks as one (`samples`,\n * AGL-4065): a site start whose brief gave no entries for a list seeds it\n * with complete-looking samples, and the record carries `sample: true`\n * beside its values, which the Data card shows as a sample to replace\n * and a published page never reads. Saving the record in Data makes it\n * the owner's.\n *\n * Nothing is published. The writer touches the one new dataset and its\n * records; a page shows them only where a person (or a job's draft page)\n * places a repeat over it.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** The resource name this writer is registered under. */\nexport const DATASET_DRAFT_RESOURCE = 'dataset'\n\n/** The longest dataset name, as the datasets route keeps it. */\nexport const DATASET_DRAFT_NAME_MAX = 120\n/** The most fields a drafted dataset is made with, and the longest name. */\nexport const DATASET_DRAFT_FIELDS_MAX = 16\nexport const DATASET_DRAFT_FIELD_NAME_MAX = 60\n/** The most records a draft is seeded with. */\nexport const DATASET_DRAFT_RECORDS_MAX = 24\n/** The longest text value a seeded record keeps. */\nexport const DATASET_DRAFT_VALUE_MAX = 2_000\n/** The most entries a seeded list value keeps. */\nexport const DATASET_DRAFT_LIST_MAX = 12\n\n/**\n * The field types a caller names, in words a person reads, and the type\n * each one is stored as. A date or a time is written as text the way a\n * visitor reads it (\"Saturday 8 November, 7 pm\"): a stored timestamp renders\n * as a number in a repeat's `{{item.<field>}}`. An image is text holding a\n * photo's address, under the \"Image\" custom type (AGL-3616), and a page is\n * text holding a page's reference, under the \"Page\" custom type (AGL-3763).\n */\nexport const DATASET_DRAFT_FIELD_TYPES = {\n text: 'text',\n number: 'float',\n integer: 'int32',\n boolean: 'bool',\n list: 'sorted',\n image: 'text',\n page: 'text',\n} as const satisfies Record<string, DatasetFieldType>\n\nexport type DatasetDraftFieldType = keyof typeof DATASET_DRAFT_FIELD_TYPES\n\nconst DRAFT_TYPES = Object.keys(DATASET_DRAFT_FIELD_TYPES) as DatasetDraftFieldType[]\n\n/** The datasets route's refusals, word for word; the first names the permission, never a role (AGL-4047). */\nexport const DATASET_DRAFT_PERMISSION_REFUSAL = permissionRefusalText('data.manage')\nexport const DATASET_DRAFT_PLAN_REFUSAL = 'Datasets require a Starter plan or higher'\nexport const DATASET_DRAFT_RELEASE_REFUSAL = 'Datasets are not available for this workspace yet'\nexport const DATASET_DRAFT_SCOPE_REFUSAL = 'Your access to this organization does not reach that site'\nexport const DATASET_DRAFT_STORAGE_REFUSAL = 'Dataset storage is full on this plan — upgrade in Billing'\n\n/** The route's refusal at the plan's dataset allowance. */\nexport function datasetDraftLimitRefusal(quota: ReturnType<typeof checkDatasetQuota>): string {\n return quota.upgradeRequired\n ? `Dataset limit reached (${quota.limit}) — upgrade in Billing`\n : `Dataset limit reached (${quota.limit}) — add extra datasets for $${quota.addonPriceUsd}/mo each or upgrade in Billing`\n}\n\n/** The route's refusal at the plan's record allowance. */\nexport function datasetDraftRecordLimitRefusal(limit: number): string {\n return `Record limit reached (${limit}) — upgrade in Billing`\n}\n\n/** One field as a caller names it. */\nexport interface DatasetDraftField {\n name: string\n /** Absent is text. */\n type?: DatasetDraftFieldType\n required?: boolean\n}\n\n/**\n * What a caller sends as `content`. Each record's values are keyed by the\n * field NAME the caller gave, since the caller has no ids yet; the writer\n * mints the ids (`roast_preference` from \"Roast preference\").\n */\nexport interface DatasetDraftContent {\n /** The dataset's name; the request's `name` stands in when absent. */\n name?: string\n fields: DatasetDraftField[]\n records?: Array<Record<string, unknown>>\n /**\n * A text field, by name, a \"Page address\" field fills from (AGL-3475):\n * asked for where a record page will show each record at its own address.\n */\n pageAddressFrom?: string\n /**\n * Which seeded records are samples for the owner to replace, by position\n * as `records` (AGL-4065). Absent, or false, is a record of the owner's.\n */\n samples?: boolean[]\n}\n\n/** What the writer reports about a dataset. */\nexport interface DatasetDraftFacts {\n fields: Array<{ id: string; name: string; type: DatasetFieldType }>\n records: number\n /** The page-address field's id, where the dataset has one. */\n addressField: string | null\n /** The first photo field's id, where the dataset has one (AGL-3616). */\n imageField: string | null\n}\n\n/** The draft as the writer will store it. */\nexport interface DatasetDraftRead {\n name: string\n model: DatasetModel\n /** Each record's values by field id, coerced and addressed. */\n records: Array<Record<string, unknown>>\n addressField: string | null\n /** Which records are samples, by position (AGL-4065); absent where none is. */\n samples?: boolean[]\n}\n\nexport type DatasetDraftContentRead =\n | { ok: true; value: DatasetDraftRead }\n | { ok: false; problems: string[] }\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** Text on one line: controls and runs of space folded to one space. */\nfunction line(value: unknown): string {\n return typeof value === 'string' ? value.replace(/[\\p{Cc}\\s]+/gu, ' ').trim() : ''\n}\n\n/** A value as a seeded record keeps it, before the model coerces it. */\nfunction seedValue(value: unknown): unknown {\n if (typeof value === 'string') return value.replace(/\\r\\n?/g, '\\n').trim().slice(0, DATASET_DRAFT_VALUE_MAX)\n if (Array.isArray(value)) {\n return value\n .map((entry) => (typeof entry === 'string' ? line(entry) : entry))\n .filter((entry) => entry !== '' && entry !== null && entry !== undefined)\n .slice(0, DATASET_DRAFT_LIST_MAX)\n }\n return value\n}\n\n/** The content as the writer reads it, or every problem that stops it. Pure. */\nexport function readDatasetDraftContent(content: Readonly<Record<string, unknown>>): DatasetDraftContentRead {\n const problems: string[] = []\n const name = line(content['name'])\n if (!name) problems.push('The dataset needs a name')\n else if (name.length > DATASET_DRAFT_NAME_MAX) {\n problems.push(`The name is longer than ${DATASET_DRAFT_NAME_MAX} characters`)\n }\n\n const rawFields = content['fields']\n const model: DatasetModel = { fields: {}, order: [] }\n /** Field name, lowercased → id. */\n const byName = new Map<string, string>()\n if (!Array.isArray(rawFields) || !rawFields.length) {\n problems.push('The dataset needs at least one field')\n } else if (rawFields.length > DATASET_DRAFT_FIELDS_MAX) {\n problems.push(`A dataset is made with at most ${DATASET_DRAFT_FIELDS_MAX} fields`)\n } else {\n for (const raw of rawFields) {\n const fieldName = isRecord(raw) ? line(raw['name']) : ''\n const rawType = (isRecord(raw) ? raw['type'] : undefined) ?? 'text'\n if (!fieldName) {\n problems.push('Each field needs a name')\n continue\n }\n if (fieldName.length > DATASET_DRAFT_FIELD_NAME_MAX) {\n problems.push(`The field \"${fieldName.slice(0, 20)}…\" has a name longer than ${DATASET_DRAFT_FIELD_NAME_MAX} characters`)\n continue\n }\n if (!(DRAFT_TYPES as readonly unknown[]).includes(rawType)) {\n problems.push(`The field \"${fieldName}\" is one of ${DRAFT_TYPES.join(', ')}`)\n continue\n }\n if (byName.has(fieldName.toLowerCase())) {\n problems.push(`Two fields are both called \"${fieldName}\"`)\n continue\n }\n const id = defaultDatasetFieldId(fieldName, new Set(model.order))\n if (!id) {\n problems.push(`The field \"${fieldName}\" needs a name with a letter in it`)\n continue\n }\n model.fields[id] = {\n name: fieldName,\n type: DATASET_DRAFT_FIELD_TYPES[rawType as DatasetDraftFieldType],\n ...(rawType === 'image' ? { customType: DATASET_IMAGE_FIELD_TYPE } : {}),\n ...(rawType === 'page' ? { customType: DATASET_PAGE_FIELD_TYPE } : {}),\n ...(isRecord(raw) && raw['required'] === true ? { required: true } : {}),\n }\n model.order.push(id)\n byName.set(fieldName.toLowerCase(), id)\n }\n }\n\n // The page address: a text field the address fills from, once.\n let addressField: string | null = null\n const rawAddress = content['pageAddressFrom']\n if (rawAddress !== undefined && rawAddress !== null && rawAddress !== '') {\n const sourceId = byName.get(line(rawAddress).toLowerCase())\n if (!sourceId || model.fields[sourceId]?.type !== 'text' || model.fields[sourceId]?.customType) {\n problems.push('A page address fills from one of the dataset’s text fields')\n } else {\n addressField = defaultDatasetFieldId('slug', new Set(model.order))\n model.fields[addressField] = {\n name: 'Page address',\n type: 'text',\n customType: RECORD_PAGE_ADDRESS_FIELD_TYPE,\n slugFrom: sourceId,\n }\n model.order.push(addressField)\n }\n }\n\n const rawRecords = content['records'] ?? []\n const records: Array<Record<string, unknown>> = []\n if (!Array.isArray(rawRecords)) {\n problems.push('Records are a list of values by field name')\n } else if (rawRecords.length > DATASET_DRAFT_RECORDS_MAX) {\n problems.push(`A dataset is seeded with at most ${DATASET_DRAFT_RECORDS_MAX} records`)\n } else if (!problems.length) {\n rawRecords.forEach((raw, index) => {\n if (!isRecord(raw)) {\n problems.push(`Record ${index + 1} is not a set of values`)\n return\n }\n const input: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(raw)) {\n const id = byName.get(line(key).toLowerCase())\n if (!id) {\n problems.push(`Record ${index + 1} names \"${line(key).slice(0, 40)}\", which is not a field`)\n continue\n }\n input[id] = seedValue(value)\n }\n const values = coerceDocumentValues(model, input)\n // An empty value is no value: it is not stored, as the card stores none.\n for (const [id, value] of Object.entries(values)) {\n if (value === '' || value === null || value === undefined || (Array.isArray(value) && !value.length)) {\n delete values[id]\n }\n }\n const errors = validateDocument(model, values)\n // A photo is an address the site's Image shows, whether or not the\n // \"Image\" type's check is registered in this process (AGL-3616).\n for (const [id, value] of Object.entries(values)) {\n const field = model.fields[id]\n if (field?.customType === DATASET_IMAGE_FIELD_TYPE && !errors[id] && !isDatasetImageValue(value)) {\n errors[id] = `${field.name} is not a photo from the media library or an https link`\n }\n // …and a page is one of the site's pages, by reference (AGL-3763).\n if (field?.customType === DATASET_PAGE_FIELD_TYPE && !errors[id] && !isDatasetPageValue(value)) {\n errors[id] = `${field.name} is not one of the site’s pages`\n }\n }\n for (const error of Object.values(errors)) problems.push(`Record ${index + 1}: ${error}`)\n if (!Object.keys(values).length) problems.push(`Record ${index + 1} has no values`)\n records.push(values)\n })\n }\n // Which records are samples (AGL-4065): true or false, one a record at most.\n const rawSamples = content['samples']\n if (rawSamples !== undefined && (!Array.isArray(rawSamples) || rawSamples.some((entry) => typeof entry !== 'boolean'))) {\n problems.push('Samples are a list of true or false, one a record')\n } else if (Array.isArray(rawSamples) && rawSamples.length > records.length) {\n problems.push('Samples name more records than the dataset is seeded with')\n }\n const samples = Array.isArray(rawSamples) && rawSamples.some((entry) => entry === true) ? records.map((_values, index) => rawSamples[index] === true) : null\n if (problems.length) return { ok: false, problems: [...new Set(problems)] }\n\n // Every seeded record its own address, unique within the dataset.\n if (addressField) {\n const source = model.fields[addressField]?.slugFrom as string\n const assigned = uniqueRecordAddresses(records.map((values, index) => ({ id: String(index), source: values[source] })))\n records.forEach((values, index) => {\n const address = assigned.get(String(index))\n if (address) values[addressField as string] = address.slice(0, RECORD_PAGE_ADDRESS_MAX)\n })\n }\n return { ok: true, value: { name, model, records, addressField, ...(samples ? { samples } : {}) } }\n}\n\n/** The first photo field of a model, by id. */\nfunction imageFieldOf(model: DatasetModel): string | null {\n return model.order.find((id) => model.fields[id]?.customType === DATASET_IMAGE_FIELD_TYPE) ?? null\n}\n\nfunction factsOf(model: DatasetModel, records: number, addressField: string | null): DatasetDraftFacts {\n return {\n fields: model.order.map((id) => ({ id, name: model.fields[id]?.name ?? id, type: model.fields[id]?.type ?? 'text' })),\n records,\n addressField,\n imageField: imageFieldOf(model),\n }\n}\n\n/** Whether content is a dataset this plugin would store, with what it says about it. Pure. */\nexport function checkDatasetDraftContent(content: Readonly<Record<string, unknown>>): PluginDraftCheck {\n const read = readDatasetDraftContent(content)\n if (read.ok === false) return read\n return {\n ok: true,\n facts: factsOf(read.value.model, read.value.records.length, read.value.addressField) as unknown as Readonly<\n Record<string, unknown>\n >,\n }\n}\n\n/** Who the member is in the org, as the writer asks: whether they hold \"Manage data\". */\nexport interface DatasetDraftMember {\n canManageData: boolean\n /** The membership itself, for whether their access reaches a site. */\n member: Readonly<Record<string, unknown>>\n}\n\nexport interface DatasetDraftWriterDeps {\n /** The Admin SDK handle; specs hand in a double. */\n firestore?: () => Firestore\n /** The org a site belongs to; the platform's lookup otherwise. */\n orgIdForHost?: (hostId: string) => Promise<string | null>\n /** The member, or `null` when they are not one; the platform's otherwise. */\n member?: (uid: string, orgId: string) => Promise<DatasetDraftMember | null>\n /** Whether the data store is released for the org; the platform's flag otherwise. */\n released?: (orgId: string) => Promise<boolean>\n /** Whether dataset bytes may grow; the platform's band otherwise. */\n storageFull?: (org: unknown, orgRef: FirebaseFirestore.DocumentReference) => Promise<boolean>\n}\n\nasync function platformMember(uid: string, orgId: string): Promise<DatasetDraftMember | null> {\n const membership = await resolveOrgMembership(uid, orgId)\n const member = membership?.member\n if (!member) return null\n return {\n canManageData: await memberHasOrgPermission(orgId, member, 'data.manage'),\n member: member as unknown as Readonly<Record<string, unknown>>,\n }\n}\n\nexport function createDatasetDraftWriter(deps: DatasetDraftWriterDeps = {}): PluginResourceDraftWriter {\n const firestore = deps.firestore ?? (() => firebaseAdmin.app().firestore() as unknown as Firestore)\n const orgIdForHost = deps.orgIdForHost ?? ((hostId: string) => resolveOrgIdForHost(hostId))\n const memberOf = deps.member ?? platformMember\n const released = deps.released ?? ((orgId: string) => isServerReleaseFlagOnForOrg('release_data_store', orgId))\n const storageFull =\n deps.storageFull ?? (async (org: unknown, orgRef: FirebaseFirestore.DocumentReference) => Boolean(await dataStorageRefusal(org, orgRef)))\n\n /** Everything but the room: the site is the org's, the member's key, the flag, the plan, the scope. */\n const early = async (context: PluginDraftContext): Promise<PluginDraftRefusal | null> => {\n if ((await orgIdForHost(context.hostId)) !== context.orgId) return { status: 404, error: 'Unknown site' }\n const member = await memberOf(context.uid, context.orgId)\n if (!member?.canManageData) return { status: 403, error: DATASET_DRAFT_PERMISSION_REFUSAL }\n if (!(await released(context.orgId))) return { status: 403, error: DATASET_DRAFT_RELEASE_REFUSAL }\n if (!checkEntitlement(context.org as never, 'dataStore')) return { status: 403, error: DATASET_DRAFT_PLAN_REFUSAL }\n // A member scoped to some sites must be able to see what they create.\n if (!memberCanSee(member.member as never, scopeOf(context))) {\n return { status: 403, error: DATASET_DRAFT_SCOPE_REFUSAL }\n }\n return null\n }\n\n return {\n refusal: async (context) => {\n const refused = await early(context)\n if (refused) return refused\n const used = (await firestore().collection('orgs').doc(context.orgId).collection('datasets').count().get()).data().count\n const quota = checkDatasetQuota(context.org as never, Number(used) || 0)\n return quota.allowed ? null : { status: 403, error: datasetDraftLimitRefusal(quota) }\n },\n\n check: (content) => checkDatasetDraftContent(content),\n\n read: async ({ hostId, id }) => {\n const orgId = await orgIdForHost(hostId)\n if (!orgId) return null\n const dataset = await firestore().collection('orgs').doc(orgId).collection('datasets').doc(id).get()\n return dataset.exists ? recordOf(dataset) : null\n },\n\n // The late photo pass of an AI site start (AGL-3988): a list's covers\n // given photos once its pages are built. Only what a person could type\n // in the record's card is stored, under the same member rules as `write`.\n reviseRecords: async (request): Promise<PluginDraftRecordsRevise> => {\n const refused = await early(request)\n if (refused) return { ok: false, ...refused }\n const orders = [...new Set(request.records.map((record) => record.order))]\n .filter((order) => Number.isInteger(order) && order >= 0)\n .slice(0, DATASET_DRAFT_RECORDS_MAX)\n if (!orders.length) return { ok: true, changed: 0 }\n const db = firestore()\n const datasetRef = db.collection('orgs').doc(request.orgId).collection('datasets').doc(request.id)\n return db.runTransaction(async (tx): Promise<PluginDraftRecordsRevise> => {\n const dataset = await tx.get(datasetRef)\n const model = dataset.get('model') as DatasetModel | undefined\n if (!dataset.exists || !model?.order) return { ok: false, status: 404, error: 'The dataset is no longer there' }\n const rows = await tx.get(datasetRef.collection('records').where('order', 'in', orders))\n let changed = 0\n for (const revision of request.records) {\n const row = rows.docs.find((doc) => doc.get('order') === revision.order)\n if (!row) continue\n const stored = (row.get('values') ?? {}) as Record<string, unknown>\n // A member changed it since: theirs stands.\n if (Object.entries(revision.where ?? {}).some(([id, value]) => stored[id] !== value)) continue\n // Only the list's own fields are changed; a revision naming none of them changes nothing.\n const named = Object.entries(revision.values).filter(([id]) => model.fields[id])\n if (!named.length) continue\n const input: Record<string, unknown> = { ...stored }\n for (const [id, value] of named) input[id] = seedValue(value)\n const values = coerceDocumentValues(model, input)\n for (const [id, value] of Object.entries(values)) {\n if (value === '' || value === null || value === undefined || (Array.isArray(value) && !value.length)) delete values[id]\n }\n const errors = validateDocument(model, values)\n const badPhoto = Object.entries(values).some(\n ([id, value]) => model.fields[id]?.customType === DATASET_IMAGE_FIELD_TYPE && !isDatasetImageValue(value),\n )\n if (Object.keys(errors).length || badPhoto) continue\n tx.update(row.ref, { values, ...datasetIntegrityUpdate(model, values, FieldValue.delete()), updatedAt: request.now })\n changed += 1\n }\n return { ok: true, changed }\n })\n },\n\n write: async (request): Promise<PluginDraftWrite> => {\n // The request's name is the one asked for; the content's stands in.\n const asked = line(request.name)\n const read = readDatasetDraftContent(asked ? { ...request.content, name: asked } : request.content)\n if (read.ok === false) return { ok: false, status: 400, error: read.problems[0] }\n const refused = await early(request)\n if (refused) return { ok: false, ...refused }\n const db = firestore()\n const orgRef = db.collection('orgs').doc(request.orgId)\n const datasets = orgRef.collection('datasets')\n const datasetRef = datasets.doc(request.id)\n const { name, model, records, addressField, samples } = read.value\n const recordQuota = checkQuota(request.org as never, 'recordsPerDataset', Math.max(0, records.length - 1))\n if (records.length && !recordQuota.allowed) {\n return { ok: false, status: 403, error: datasetDraftRecordLimitRefusal(recordQuota.limit) }\n }\n if (records.length && (await storageFull(request.org, orgRef))) {\n return { ok: false, status: 403, error: DATASET_DRAFT_STORAGE_REFUSAL }\n }\n const visibleTo = scopeOf(request)\n // Minted before the transaction, so a retried attempt writes the same rows.\n const recordIds = records.map(() => createResourceUid())\n return db.runTransaction(async (tx): Promise<PluginDraftWrite> => {\n // Every read before any write, which Firestore requires.\n const existing = await tx.get(datasetRef)\n // Asked again under the same id: the dataset it already wrote.\n if (existing.exists) return { ok: true, replayed: true, ...recordOf(existing) }\n const live = (await tx.get(datasets.count())).data().count\n const quota = checkDatasetQuota(request.org as never, Number(live) || 0)\n if (!quota.allowed) return { ok: false, status: 403, error: datasetDraftLimitRefusal(quota) }\n tx.create(datasetRef, {\n displayName: name,\n fields: [...model.order],\n model,\n ...newResourceScopeFields(visibleTo),\n createdAt: request.now,\n createdBy: request.uid,\n })\n records.forEach((values, order) => {\n tx.create(datasetRef.collection('records').doc(recordIds[order]), {\n values,\n ...datasetIntegrityFields(model, values),\n // A sample for the owner to replace (AGL-4065), beside its values: no page reads it.\n ...(samples?.[order] ? { sample: true } : {}),\n order,\n createdAt: request.now,\n updatedAt: request.now,\n })\n })\n return {\n ok: true,\n replayed: false,\n id: request.id,\n name,\n versionId: null,\n facts: factsOf(model, records.length, addressField) as unknown as Readonly<Record<string, unknown>>,\n }\n })\n },\n }\n}\n\n/**\n * The scope a dataset drafted for a site takes: that site alone (AGL-4003).\n *\n * A drafted dataset is the site's own content, made for it by Aglyn AI, so it\n * is shared with that site and no other, whatever the workspace's Default\n * sharing says for the datasets a person makes on the Data page. Deleting the\n * site erases it with its records (`eraseHost`), where a dataset shared with\n * every site outlived its site: 53 did in one workspace. A member can share it\n * with more sites on the Data page.\n */\nfunction scopeOf(context: Pick<PluginDraftContext, 'hostId'>) {\n return [hostScopeToken(context.hostId)]\n}\n\nfunction recordOf(dataset: FirebaseFirestore.DocumentSnapshot): PluginDraftRecord {\n const data = (dataset.data() ?? {}) as { displayName?: unknown; model?: DatasetModel }\n const model: DatasetModel = data.model?.order ? data.model : { fields: {}, order: [] }\n const addressField = model.order.find((id) => model.fields[id]?.customType === RECORD_PAGE_ADDRESS_FIELD_TYPE) ?? null\n return {\n id: dataset.id,\n name: String(data.displayName ?? ''),\n versionId: null,\n // A replay reports the fields; how many records it was seeded with is the first write's to say.\n facts: factsOf(model, 0, addressField) as unknown as Readonly<Record<string, unknown>>,\n }\n}\n\nexport const datasetDraftWriter = createDatasetDraftWriter()\n\n/**\n * Registers the writer; the console surface calls it, since only the console\n * runs AI jobs (AGL-3026). Idempotent: a second call replaces the first.\n */\nexport function registerDatasetDraftWriter(): void {\n registerPluginResourceDraftWriter(DATASET_DRAFT_RESOURCE, datasetDraftWriter, { pluginId: BUNDLE_ID })\n}\n"],"names":["createResourceUid","permissionRefusalText","memberCanSee","checkDatasetQuota","checkEntitlement","checkQuota","hostScopeToken","newResourceScopeFields","registerPluginResourceDraftWriter","firebaseAdmin","FieldValue","dataStorageRefusal","memberHasOrgPermission","resolveOrgIdForHost","resolveOrgMembership","isServerReleaseFlagOnForOrg","BUNDLE_ID","coerceDocumentValues","datasetIntegrityFields","datasetIntegrityUpdate","defaultDatasetFieldId","validateDocument","DATASET_IMAGE_FIELD_TYPE","isDatasetImageValue","DATASET_PAGE_FIELD_TYPE","isDatasetPageValue","RECORD_PAGE_ADDRESS_FIELD_TYPE","RECORD_PAGE_ADDRESS_MAX","uniqueRecordAddresses","DATASET_DRAFT_RESOURCE","DATASET_DRAFT_NAME_MAX","DATASET_DRAFT_FIELDS_MAX","DATASET_DRAFT_FIELD_NAME_MAX","DATASET_DRAFT_RECORDS_MAX","DATASET_DRAFT_VALUE_MAX","DATASET_DRAFT_LIST_MAX","DATASET_DRAFT_FIELD_TYPES","text","number","integer","boolean","list","image","page","DRAFT_TYPES","Object","keys","DATASET_DRAFT_PERMISSION_REFUSAL","DATASET_DRAFT_PLAN_REFUSAL","DATASET_DRAFT_RELEASE_REFUSAL","DATASET_DRAFT_SCOPE_REFUSAL","DATASET_DRAFT_STORAGE_REFUSAL","datasetDraftLimitRefusal","quota","upgradeRequired","limit","addonPriceUsd","datasetDraftRecordLimitRefusal","isRecord","value","Array","isArray","line","replace","trim","seedValue","slice","map","entry","filter","undefined","readDatasetDraftContent","content","problems","name","push","length","rawFields","model","fields","order","byName","Map","raw","fieldName","rawType","includes","join","has","toLowerCase","id","Set","type","customType","required","set","addressField","rawAddress","sourceId","get","slugFrom","rawRecords","records","forEach","index","input","key","entries","values","errors","field","error","rawSamples","some","samples","_values","ok","source","assigned","String","address","imageFieldOf","find","factsOf","imageField","checkDatasetDraftContent","read","facts","platformMember","uid","orgId","membership","member","canManageData","createDatasetDraftWriter","deps","firestore","app","orgIdForHost","hostId","memberOf","released","storageFull","org","orgRef","Boolean","early","context","status","scopeOf","refusal","refused","used","collection","doc","count","data","Number","allowed","check","dataset","exists","recordOf","reviseRecords","request","orders","record","isInteger","changed","db","datasetRef","runTransaction","tx","rows","where","revision","row","docs","stored","named","badPhoto","update","ref","delete","updatedAt","now","write","asked","datasets","recordQuota","Math","max","visibleTo","recordIds","existing","replayed","live","create","displayName","createdAt","createdBy","sample","versionId","datasetDraftWriter","registerDatasetDraftWriter","pluginId"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,qBAAqB,QAAQ,yCAAwC;AAC9E,SAASC,YAAY,QAAQ,uCAAsC;AACnE,SAASC,iBAAiB,EAAEC,gBAAgB,EAAEC,UAAU,QAAQ,2CAA0C;AAC1G,SAASC,cAAc,EAAEC,sBAAsB,QAAQ,sCAAqC;AAC5F,SACEC,iCAAiC,QAQ5B,qDAAoD;AAC3D,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,kBAAkB,QAAQ,oDAAmD;AACtF,SACEC,sBAAsB,EACtBC,mBAAmB,EACnBC,oBAAoB,QACf,gDAA+C;AACtD,SAASC,2BAA2B,QAAQ,gDAA+C;AAC3F,SAASC,SAAS,QAAQ,gCAA4B;AACtD,SACEC,oBAA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F;IACF;AACF;AAEA;;;;;;;;;CASC,GACD,SAASqD,QAAQF,OAA2C;IAC1D,OAAO;QAAC7I,eAAe6I,QAAQR,MAAM;KAAE;AACzC;AAEA,SAASuB,SAASF,OAA2C;QAC7CA,eAEOlF,mBAGN8E;QAJaA;IAD5B,MAAMA,QAAQI,gBAAAA,QAAQJ,IAAI,cAAZI,gBAAkB,CAAC;IACjC,MAAMlF,QAAsB8E,EAAAA,cAAAA,KAAK9E,KAAK,qBAAV8E,YAAY5E,KAAK,IAAG4E,KAAK9E,KAAK,GAAG;QAAEC,QAAQ,CAAC;QAAGC,OAAO,EAAE;IAAC;IACrF,MAAMgB,gBAAelB,oBAAAA,MAAME,KAAK,CAAC0C,IAAI,CAAC,CAAChC;YAAOZ;eAAAA,EAAAA,mBAAAA,MAAMC,MAAM,CAACW,GAAG,qBAAhBZ,iBAAkBe,UAAU,MAAKnE;kBAA1DoD,oBAA6F;IAClH,OAAO;QACLY,IAAIsE,QAAQtE,EAAE;QACdhB,MAAM6C,QAAOqC,oBAAAA,KAAK0C,WAAW,YAAhB1C,oBAAoB;QACjC8C,WAAW;QACX,gGAAgG;QAChG3E,OAAOJ,QAAQ7C,OAAO,GAAGkB;IAC3B;AACF;AAEA,OAAO,MAAM2G,qBAAqBrE,2BAA0B;AAE5D;;;CAGC,GACD,OAAO,SAASsE;IACdpM,kCAAkCqB,wBAAwB8K,oBAAoB;QAAEE,UAAU7L;IAAU;AACtG"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/server/dataset-drafts.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport { permissionRefusalText } from '@aglyn/aglyn/app-utils/org-permissions'\nimport { memberCanSee } from '@aglyn/aglyn/app-utils/organizations'\nimport { checkDatasetQuota, checkEntitlement, checkQuota } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { hostScopeToken, newResourceScopeFields } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport {\n registerPluginResourceDraftWriter,\n type PluginDraftCheck,\n type PluginDraftContext,\n type PluginDraftRecord,\n type PluginDraftRecordsRevise,\n type PluginDraftRefusal,\n type PluginDraftWrite,\n type PluginResourceDraftWriter,\n} from '@aglyn/aglyn/plugin-manager/plugin-resource-drafts'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { dataStorageRefusal } from '@aglyn/tenant-data-admin/server/data-storage-gate'\nimport {\n memberHasOrgPermission,\n resolveOrgIdForHost,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin/server/organizations'\nimport { isServerReleaseFlagOnForOrg } from '@aglyn/tenant-data-admin/server/release-flags'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport { datasetNameLower } from '../model/datasets'\nimport {\n coerceDocumentValues,\n datasetIntegrityFields,\n datasetIntegrityUpdate,\n defaultDatasetFieldId,\n validateDocument,\n type DatasetFieldType,\n type DatasetModel,\n} from '../model/dataset-models'\nimport { DATASET_IMAGE_FIELD_TYPE, isDatasetImageValue } from '../model/dataset-image-field'\nimport { DATASET_PAGE_FIELD_TYPE, isDatasetPageValue } from '../model/dataset-page-field'\nimport {\n RECORD_PAGE_ADDRESS_FIELD_TYPE,\n RECORD_PAGE_ADDRESS_MAX,\n uniqueRecordAddresses,\n} from '../record-pages/record-pages'\n\n/**\n * A DATASET ANOTHER PLUGIN ASKS FOR (AGL-3616).\n *\n * The draft writer this plugin registers for the `dataset` resource on the\n * core's resource-drafts seam. Aglyn AI builds a menu, a team, a list of\n * services or a portfolio as a dataset, the way the docs teach a person to,\n * and asks for the writer by name, so every rule is this plugin's:\n *\n * - THE DOCUMENT is the one the Data card's create makes: a display name,\n * the flat `fields` mirror and a typed model, shared with the site it is\n * made for and no other (AGL-4003), and the\n * seeded records, each with the integrity and filter index every record\n * write carries. Where a record page is wanted the model gains a \"Page\n * address\" field that fills from a text field, and every seeded record a\n * unique address (`uniqueRecordAddresses`), so the member's Record pages\n * save has nothing left to fill.\n * - THE ROOM is `datasetsPerOrg` (add-ons included, `checkDatasetQuota`),\n * counted INSIDE the transaction that creates, as the datasets route\n * counts it; the records are held to `recordsPerDataset` and the dataset\n * storage band.\n * - THE PLAN is `dataStore` (Starter and up), THE FLAG `release_data_store`,\n * and THE MEMBER an org member holding \"Manage data\" (`data.manage`,\n * AGL-4047), whose access reaches the site — refused in the route's own\n * words.\n * - THE CHECK holds every record to the model it is written under\n * (`validateDocument`), so what is seeded is what a person could type.\n * - A PHOTO is an `image` field (AGL-3616): text storage riding the\n * \"Image\" custom type, each value an address the site's Image element\n * shows (`isDatasetImageValue`), so a portfolio's pieces or a team keep\n * the photo the page that lists them binds.\n * - A PAGE is a `page` field (AGL-3763): text storage riding the \"Page\"\n * custom type, each value one of the site's pages as `screen:{id}`\n * (`isDatasetPageValue`), which a Button or Link binds.\n * - A SAMPLE is a seeded record the caller marks as one (`samples`,\n * AGL-4065): a site start whose brief gave no entries for a list seeds it\n * with complete-looking samples, and the record carries `sample: true`\n * beside its values, which the Data card shows as a sample to replace\n * and a published page never reads. Saving the record in Data makes it\n * the owner's.\n *\n * Nothing is published. The writer touches the one new dataset and its\n * records; a page shows them only where a person (or a job's draft page)\n * places a repeat over it.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** The resource name this writer is registered under. */\nexport const DATASET_DRAFT_RESOURCE = 'dataset'\n\n/** The longest dataset name, as the datasets route keeps it. */\nexport const DATASET_DRAFT_NAME_MAX = 120\n/** The most fields a drafted dataset is made with, and the longest name. */\nexport const DATASET_DRAFT_FIELDS_MAX = 16\nexport const DATASET_DRAFT_FIELD_NAME_MAX = 60\n/** The most records a draft is seeded with. */\nexport const DATASET_DRAFT_RECORDS_MAX = 24\n/** The longest text value a seeded record keeps. */\nexport const DATASET_DRAFT_VALUE_MAX = 2_000\n/** The most entries a seeded list value keeps. */\nexport const DATASET_DRAFT_LIST_MAX = 12\n\n/**\n * The field types a caller names, in words a person reads, and the type\n * each one is stored as. A date or a time is written as text the way a\n * visitor reads it (\"Saturday 8 November, 7 pm\"): a stored timestamp renders\n * as a number in a repeat's `{{item.<field>}}`. An image is text holding a\n * photo's address, under the \"Image\" custom type (AGL-3616), and a page is\n * text holding a page's reference, under the \"Page\" custom type (AGL-3763).\n */\nexport const DATASET_DRAFT_FIELD_TYPES = {\n text: 'text',\n number: 'float',\n integer: 'int32',\n boolean: 'bool',\n list: 'sorted',\n image: 'text',\n page: 'text',\n} as const satisfies Record<string, DatasetFieldType>\n\nexport type DatasetDraftFieldType = keyof typeof DATASET_DRAFT_FIELD_TYPES\n\nconst DRAFT_TYPES = Object.keys(DATASET_DRAFT_FIELD_TYPES) as DatasetDraftFieldType[]\n\n/** The datasets route's refusals, word for word; the first names the permission, never a role (AGL-4047). */\nexport const DATASET_DRAFT_PERMISSION_REFUSAL = permissionRefusalText('data.manage')\nexport const DATASET_DRAFT_PLAN_REFUSAL = 'Datasets require a Starter plan or higher'\nexport const DATASET_DRAFT_RELEASE_REFUSAL = 'Datasets are not available for this workspace yet'\nexport const DATASET_DRAFT_SCOPE_REFUSAL = 'Your access to this organization does not reach that site'\nexport const DATASET_DRAFT_STORAGE_REFUSAL = 'Dataset storage is full on this plan — upgrade in Billing'\n\n/** The route's refusal at the plan's dataset allowance. */\nexport function datasetDraftLimitRefusal(quota: ReturnType<typeof checkDatasetQuota>): string {\n return quota.upgradeRequired\n ? `Dataset limit reached (${quota.limit}) — upgrade in Billing`\n : `Dataset limit reached (${quota.limit}) — add extra datasets for $${quota.addonPriceUsd}/mo each or upgrade in Billing`\n}\n\n/** The route's refusal at the plan's record allowance. */\nexport function datasetDraftRecordLimitRefusal(limit: number): string {\n return `Record limit reached (${limit}) — upgrade in Billing`\n}\n\n/** One field as a caller names it. */\nexport interface DatasetDraftField {\n name: string\n /** Absent is text. */\n type?: DatasetDraftFieldType\n required?: boolean\n}\n\n/**\n * What a caller sends as `content`. Each record's values are keyed by the\n * field NAME the caller gave, since the caller has no ids yet; the writer\n * mints the ids (`roast_preference` from \"Roast preference\").\n */\nexport interface DatasetDraftContent {\n /** The dataset's name; the request's `name` stands in when absent. */\n name?: string\n fields: DatasetDraftField[]\n records?: Array<Record<string, unknown>>\n /**\n * A text field, by name, a \"Page address\" field fills from (AGL-3475):\n * asked for where a record page will show each record at its own address.\n */\n pageAddressFrom?: string\n /**\n * Which seeded records are samples for the owner to replace, by position\n * as `records` (AGL-4065). Absent, or false, is a record of the owner's.\n */\n samples?: boolean[]\n}\n\n/** What the writer reports about a dataset. */\nexport interface DatasetDraftFacts {\n fields: Array<{ id: string; name: string; type: DatasetFieldType }>\n records: number\n /** The page-address field's id, where the dataset has one. */\n addressField: string | null\n /** The first photo field's id, where the dataset has one (AGL-3616). */\n imageField: string | null\n}\n\n/** The draft as the writer will store it. */\nexport interface DatasetDraftRead {\n name: string\n model: DatasetModel\n /** Each record's values by field id, coerced and addressed. */\n records: Array<Record<string, unknown>>\n addressField: string | null\n /** Which records are samples, by position (AGL-4065); absent where none is. */\n samples?: boolean[]\n}\n\nexport type DatasetDraftContentRead =\n | { ok: true; value: DatasetDraftRead }\n | { ok: false; problems: string[] }\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** Text on one line: controls and runs of space folded to one space. */\nfunction line(value: unknown): string {\n return typeof value === 'string' ? value.replace(/[\\p{Cc}\\s]+/gu, ' ').trim() : ''\n}\n\n/** A value as a seeded record keeps it, before the model coerces it. */\nfunction seedValue(value: unknown): unknown {\n if (typeof value === 'string') return value.replace(/\\r\\n?/g, '\\n').trim().slice(0, DATASET_DRAFT_VALUE_MAX)\n if (Array.isArray(value)) {\n return value\n .map((entry) => (typeof entry === 'string' ? line(entry) : entry))\n .filter((entry) => entry !== '' && entry !== null && entry !== undefined)\n .slice(0, DATASET_DRAFT_LIST_MAX)\n }\n return value\n}\n\n/** The content as the writer reads it, or every problem that stops it. Pure. */\nexport function readDatasetDraftContent(content: Readonly<Record<string, unknown>>): DatasetDraftContentRead {\n const problems: string[] = []\n const name = line(content['name'])\n if (!name) problems.push('The dataset needs a name')\n else if (name.length > DATASET_DRAFT_NAME_MAX) {\n problems.push(`The name is longer than ${DATASET_DRAFT_NAME_MAX} characters`)\n }\n\n const rawFields = content['fields']\n const model: DatasetModel = { fields: {}, order: [] }\n /** Field name, lowercased → id. */\n const byName = new Map<string, string>()\n if (!Array.isArray(rawFields) || !rawFields.length) {\n problems.push('The dataset needs at least one field')\n } else if (rawFields.length > DATASET_DRAFT_FIELDS_MAX) {\n problems.push(`A dataset is made with at most ${DATASET_DRAFT_FIELDS_MAX} fields`)\n } else {\n for (const raw of rawFields) {\n const fieldName = isRecord(raw) ? line(raw['name']) : ''\n const rawType = (isRecord(raw) ? raw['type'] : undefined) ?? 'text'\n if (!fieldName) {\n problems.push('Each field needs a name')\n continue\n }\n if (fieldName.length > DATASET_DRAFT_FIELD_NAME_MAX) {\n problems.push(`The field \"${fieldName.slice(0, 20)}…\" has a name longer than ${DATASET_DRAFT_FIELD_NAME_MAX} characters`)\n continue\n }\n if (!(DRAFT_TYPES as readonly unknown[]).includes(rawType)) {\n problems.push(`The field \"${fieldName}\" is one of ${DRAFT_TYPES.join(', ')}`)\n continue\n }\n if (byName.has(fieldName.toLowerCase())) {\n problems.push(`Two fields are both called \"${fieldName}\"`)\n continue\n }\n const id = defaultDatasetFieldId(fieldName, new Set(model.order))\n if (!id) {\n problems.push(`The field \"${fieldName}\" needs a name with a letter in it`)\n continue\n }\n model.fields[id] = {\n name: fieldName,\n type: DATASET_DRAFT_FIELD_TYPES[rawType as DatasetDraftFieldType],\n ...(rawType === 'image' ? { customType: DATASET_IMAGE_FIELD_TYPE } : {}),\n ...(rawType === 'page' ? { customType: DATASET_PAGE_FIELD_TYPE } : {}),\n ...(isRecord(raw) && raw['required'] === true ? { required: true } : {}),\n }\n model.order.push(id)\n byName.set(fieldName.toLowerCase(), id)\n }\n }\n\n // The page address: a text field the address fills from, once.\n let addressField: string | null = null\n const rawAddress = content['pageAddressFrom']\n if (rawAddress !== undefined && rawAddress !== null && rawAddress !== '') {\n const sourceId = byName.get(line(rawAddress).toLowerCase())\n if (!sourceId || model.fields[sourceId]?.type !== 'text' || model.fields[sourceId]?.customType) {\n problems.push('A page address fills from one of the dataset’s text fields')\n } else {\n addressField = defaultDatasetFieldId('slug', new Set(model.order))\n model.fields[addressField] = {\n name: 'Page address',\n type: 'text',\n customType: RECORD_PAGE_ADDRESS_FIELD_TYPE,\n slugFrom: sourceId,\n }\n model.order.push(addressField)\n }\n }\n\n const rawRecords = content['records'] ?? []\n const records: Array<Record<string, unknown>> = []\n if (!Array.isArray(rawRecords)) {\n problems.push('Records are a list of values by field name')\n } else if (rawRecords.length > DATASET_DRAFT_RECORDS_MAX) {\n problems.push(`A dataset is seeded with at most ${DATASET_DRAFT_RECORDS_MAX} records`)\n } else if (!problems.length) {\n rawRecords.forEach((raw, index) => {\n if (!isRecord(raw)) {\n problems.push(`Record ${index + 1} is not a set of values`)\n return\n }\n const input: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(raw)) {\n const id = byName.get(line(key).toLowerCase())\n if (!id) {\n problems.push(`Record ${index + 1} names \"${line(key).slice(0, 40)}\", which is not a field`)\n continue\n }\n input[id] = seedValue(value)\n }\n const values = coerceDocumentValues(model, input)\n // An empty value is no value: it is not stored, as the card stores none.\n for (const [id, value] of Object.entries(values)) {\n if (value === '' || value === null || value === undefined || (Array.isArray(value) && !value.length)) {\n delete values[id]\n }\n }\n const errors = validateDocument(model, values)\n // A photo is an address the site's Image shows, whether or not the\n // \"Image\" type's check is registered in this process (AGL-3616).\n for (const [id, value] of Object.entries(values)) {\n const field = model.fields[id]\n if (field?.customType === DATASET_IMAGE_FIELD_TYPE && !errors[id] && !isDatasetImageValue(value)) {\n errors[id] = `${field.name} is not a photo from the media library or an https link`\n }\n // …and a page is one of the site's pages, by reference (AGL-3763).\n if (field?.customType === DATASET_PAGE_FIELD_TYPE && !errors[id] && !isDatasetPageValue(value)) {\n errors[id] = `${field.name} is not one of the site’s pages`\n }\n }\n for (const error of Object.values(errors)) problems.push(`Record ${index + 1}: ${error}`)\n if (!Object.keys(values).length) problems.push(`Record ${index + 1} has no values`)\n records.push(values)\n })\n }\n // Which records are samples (AGL-4065): true or false, one a record at most.\n const rawSamples = content['samples']\n if (rawSamples !== undefined && (!Array.isArray(rawSamples) || rawSamples.some((entry) => typeof entry !== 'boolean'))) {\n problems.push('Samples are a list of true or false, one a record')\n } else if (Array.isArray(rawSamples) && rawSamples.length > records.length) {\n problems.push('Samples name more records than the dataset is seeded with')\n }\n const samples = Array.isArray(rawSamples) && rawSamples.some((entry) => entry === true) ? records.map((_values, index) => rawSamples[index] === true) : null\n if (problems.length) return { ok: false, problems: [...new Set(problems)] }\n\n // Every seeded record its own address, unique within the dataset.\n if (addressField) {\n const source = model.fields[addressField]?.slugFrom as string\n const assigned = uniqueRecordAddresses(records.map((values, index) => ({ id: String(index), source: values[source] })))\n records.forEach((values, index) => {\n const address = assigned.get(String(index))\n if (address) values[addressField as string] = address.slice(0, RECORD_PAGE_ADDRESS_MAX)\n })\n }\n return { ok: true, value: { name, model, records, addressField, ...(samples ? { samples } : {}) } }\n}\n\n/** The first photo field of a model, by id. */\nfunction imageFieldOf(model: DatasetModel): string | null {\n return model.order.find((id) => model.fields[id]?.customType === DATASET_IMAGE_FIELD_TYPE) ?? null\n}\n\nfunction factsOf(model: DatasetModel, records: number, addressField: string | null): DatasetDraftFacts {\n return {\n fields: model.order.map((id) => ({ id, name: model.fields[id]?.name ?? id, type: model.fields[id]?.type ?? 'text' })),\n records,\n addressField,\n imageField: imageFieldOf(model),\n }\n}\n\n/** Whether content is a dataset this plugin would store, with what it says about it. Pure. */\nexport function checkDatasetDraftContent(content: Readonly<Record<string, unknown>>): PluginDraftCheck {\n const read = readDatasetDraftContent(content)\n if (read.ok === false) return read\n return {\n ok: true,\n facts: factsOf(read.value.model, read.value.records.length, read.value.addressField) as unknown as Readonly<\n Record<string, unknown>\n >,\n }\n}\n\n/** Who the member is in the org, as the writer asks: whether they hold \"Manage data\". */\nexport interface DatasetDraftMember {\n canManageData: boolean\n /** The membership itself, for whether their access reaches a site. */\n member: Readonly<Record<string, unknown>>\n}\n\nexport interface DatasetDraftWriterDeps {\n /** The Admin SDK handle; specs hand in a double. */\n firestore?: () => Firestore\n /** The org a site belongs to; the platform's lookup otherwise. */\n orgIdForHost?: (hostId: string) => Promise<string | null>\n /** The member, or `null` when they are not one; the platform's otherwise. */\n member?: (uid: string, orgId: string) => Promise<DatasetDraftMember | null>\n /** Whether the data store is released for the org; the platform's flag otherwise. */\n released?: (orgId: string) => Promise<boolean>\n /** Whether dataset bytes may grow; the platform's band otherwise. */\n storageFull?: (org: unknown, orgRef: FirebaseFirestore.DocumentReference) => Promise<boolean>\n}\n\nasync function platformMember(uid: string, orgId: string): Promise<DatasetDraftMember | null> {\n const membership = await resolveOrgMembership(uid, orgId)\n const member = membership?.member\n if (!member) return null\n return {\n canManageData: await memberHasOrgPermission(orgId, member, 'data.manage'),\n member: member as unknown as Readonly<Record<string, unknown>>,\n }\n}\n\nexport function createDatasetDraftWriter(deps: DatasetDraftWriterDeps = {}): PluginResourceDraftWriter {\n const firestore = deps.firestore ?? (() => firebaseAdmin.app().firestore() as unknown as Firestore)\n const orgIdForHost = deps.orgIdForHost ?? ((hostId: string) => resolveOrgIdForHost(hostId))\n const memberOf = deps.member ?? platformMember\n const released = deps.released ?? ((orgId: string) => isServerReleaseFlagOnForOrg('release_data_store', orgId))\n const storageFull =\n deps.storageFull ?? (async (org: unknown, orgRef: FirebaseFirestore.DocumentReference) => Boolean(await dataStorageRefusal(org, orgRef)))\n\n /** Everything but the room: the site is the org's, the member's key, the flag, the plan, the scope. */\n const early = async (context: PluginDraftContext): Promise<PluginDraftRefusal | null> => {\n if ((await orgIdForHost(context.hostId)) !== context.orgId) return { status: 404, error: 'Unknown site' }\n const member = await memberOf(context.uid, context.orgId)\n if (!member?.canManageData) return { status: 403, error: DATASET_DRAFT_PERMISSION_REFUSAL }\n if (!(await released(context.orgId))) return { status: 403, error: DATASET_DRAFT_RELEASE_REFUSAL }\n if (!checkEntitlement(context.org as never, 'dataStore')) return { status: 403, error: DATASET_DRAFT_PLAN_REFUSAL }\n // A member scoped to some sites must be able to see what they create.\n if (!memberCanSee(member.member as never, scopeOf(context))) {\n return { status: 403, error: DATASET_DRAFT_SCOPE_REFUSAL }\n }\n return null\n }\n\n return {\n refusal: async (context) => {\n const refused = await early(context)\n if (refused) return refused\n const used = (await firestore().collection('orgs').doc(context.orgId).collection('datasets').count().get()).data().count\n const quota = checkDatasetQuota(context.org as never, Number(used) || 0)\n return quota.allowed ? null : { status: 403, error: datasetDraftLimitRefusal(quota) }\n },\n\n check: (content) => checkDatasetDraftContent(content),\n\n read: async ({ hostId, id }) => {\n const orgId = await orgIdForHost(hostId)\n if (!orgId) return null\n const dataset = await firestore().collection('orgs').doc(orgId).collection('datasets').doc(id).get()\n return dataset.exists ? recordOf(dataset) : null\n },\n\n // The late photo pass of an AI site start (AGL-3988): a list's covers\n // given photos once its pages are built. Only what a person could type\n // in the record's card is stored, under the same member rules as `write`.\n reviseRecords: async (request): Promise<PluginDraftRecordsRevise> => {\n const refused = await early(request)\n if (refused) return { ok: false, ...refused }\n const orders = [...new Set(request.records.map((record) => record.order))]\n .filter((order) => Number.isInteger(order) && order >= 0)\n .slice(0, DATASET_DRAFT_RECORDS_MAX)\n if (!orders.length) return { ok: true, changed: 0 }\n const db = firestore()\n const datasetRef = db.collection('orgs').doc(request.orgId).collection('datasets').doc(request.id)\n return db.runTransaction(async (tx): Promise<PluginDraftRecordsRevise> => {\n const dataset = await tx.get(datasetRef)\n const model = dataset.get('model') as DatasetModel | undefined\n if (!dataset.exists || !model?.order) return { ok: false, status: 404, error: 'The dataset is no longer there' }\n const rows = await tx.get(datasetRef.collection('records').where('order', 'in', orders))\n let changed = 0\n for (const revision of request.records) {\n const row = rows.docs.find((doc) => doc.get('order') === revision.order)\n if (!row) continue\n const stored = (row.get('values') ?? {}) as Record<string, unknown>\n // A member changed it since: theirs stands.\n if (Object.entries(revision.where ?? {}).some(([id, value]) => stored[id] !== value)) continue\n // Only the list's own fields are changed; a revision naming none of them changes nothing.\n const named = Object.entries(revision.values).filter(([id]) => model.fields[id])\n if (!named.length) continue\n const input: Record<string, unknown> = { ...stored }\n for (const [id, value] of named) input[id] = seedValue(value)\n const values = coerceDocumentValues(model, input)\n for (const [id, value] of Object.entries(values)) {\n if (value === '' || value === null || value === undefined || (Array.isArray(value) && !value.length)) delete values[id]\n }\n const errors = validateDocument(model, values)\n const badPhoto = Object.entries(values).some(\n ([id, value]) => model.fields[id]?.customType === DATASET_IMAGE_FIELD_TYPE && !isDatasetImageValue(value),\n )\n if (Object.keys(errors).length || badPhoto) continue\n tx.update(row.ref, { values, ...datasetIntegrityUpdate(model, values, FieldValue.delete()), updatedAt: request.now })\n changed += 1\n }\n return { ok: true, changed }\n })\n },\n\n write: async (request): Promise<PluginDraftWrite> => {\n // The request's name is the one asked for; the content's stands in.\n const asked = line(request.name)\n const read = readDatasetDraftContent(asked ? { ...request.content, name: asked } : request.content)\n if (read.ok === false) return { ok: false, status: 400, error: read.problems[0] }\n const refused = await early(request)\n if (refused) return { ok: false, ...refused }\n const db = firestore()\n const orgRef = db.collection('orgs').doc(request.orgId)\n const datasets = orgRef.collection('datasets')\n const datasetRef = datasets.doc(request.id)\n const { name, model, records, addressField, samples } = read.value\n const recordQuota = checkQuota(request.org as never, 'recordsPerDataset', Math.max(0, records.length - 1))\n if (records.length && !recordQuota.allowed) {\n return { ok: false, status: 403, error: datasetDraftRecordLimitRefusal(recordQuota.limit) }\n }\n if (records.length && (await storageFull(request.org, orgRef))) {\n return { ok: false, status: 403, error: DATASET_DRAFT_STORAGE_REFUSAL }\n }\n const visibleTo = scopeOf(request)\n // Minted before the transaction, so a retried attempt writes the same rows.\n const recordIds = records.map(() => createResourceUid())\n return db.runTransaction(async (tx): Promise<PluginDraftWrite> => {\n // Every read before any write, which Firestore requires.\n const existing = await tx.get(datasetRef)\n // Asked again under the same id: the dataset it already wrote.\n if (existing.exists) return { ok: true, replayed: true, ...recordOf(existing) }\n const live = (await tx.get(datasets.count())).data().count\n const quota = checkDatasetQuota(request.org as never, Number(live) || 0)\n if (!quota.allowed) return { ok: false, status: 403, error: datasetDraftLimitRefusal(quota) }\n tx.create(datasetRef, {\n displayName: name,\n nameLower: datasetNameLower(name),\n fields: [...model.order],\n model,\n ...newResourceScopeFields(visibleTo),\n createdAt: request.now,\n createdBy: request.uid,\n })\n records.forEach((values, order) => {\n tx.create(datasetRef.collection('records').doc(recordIds[order]), {\n values,\n ...datasetIntegrityFields(model, values),\n // A sample for the owner to replace (AGL-4065), beside its values: no page reads it.\n ...(samples?.[order] ? { sample: true } : {}),\n order,\n createdAt: request.now,\n updatedAt: request.now,\n })\n })\n return {\n ok: true,\n replayed: false,\n id: request.id,\n name,\n versionId: null,\n facts: factsOf(model, records.length, addressField) as unknown as Readonly<Record<string, unknown>>,\n }\n })\n },\n }\n}\n\n/**\n * The scope a dataset drafted for a site takes: that site alone (AGL-4003).\n *\n * A drafted dataset is the site's own content, made for it by Aglyn AI, so it\n * is shared with that site and no other, whatever the workspace's Default\n * sharing says for the datasets a person makes on the Data page. Deleting the\n * site erases it with its records (`eraseHost`), where a dataset shared with\n * every site outlived its site: 53 did in one workspace. A member can share it\n * with more sites on the Data page.\n */\nfunction scopeOf(context: Pick<PluginDraftContext, 'hostId'>) {\n return [hostScopeToken(context.hostId)]\n}\n\nfunction recordOf(dataset: FirebaseFirestore.DocumentSnapshot): PluginDraftRecord {\n const data = (dataset.data() ?? {}) as { displayName?: unknown; model?: DatasetModel }\n const model: DatasetModel = data.model?.order ? data.model : { fields: {}, order: [] }\n const addressField = model.order.find((id) => model.fields[id]?.customType === RECORD_PAGE_ADDRESS_FIELD_TYPE) ?? null\n return {\n id: dataset.id,\n name: String(data.displayName ?? ''),\n versionId: null,\n // A replay reports the fields; how many records it was seeded with is the first write's to say.\n facts: factsOf(model, 0, addressField) as unknown as Readonly<Record<string, unknown>>,\n }\n}\n\nexport const datasetDraftWriter = createDatasetDraftWriter()\n\n/**\n * Registers the writer; the console surface calls it, since only the console\n * runs AI jobs (AGL-3026). Idempotent: a second call replaces the first.\n */\nexport function registerDatasetDraftWriter(): void {\n registerPluginResourceDraftWriter(DATASET_DRAFT_RESOURCE, datasetDraftWriter, { pluginId: BUNDLE_ID })\n}\n"],"names":["createResourceUid","permissionRefusalText","memberCanSee","checkDatasetQuota","checkEntitlement","checkQuota","hostScopeToken","newResourceScopeFields","registerPluginResourceDraftWriter","firebaseAdmin","FieldValue","dataStorageRefusal","memberHasOrgPermission","resolveOrgIdForHost","resolveOrgMembership","isServerReleaseFlagOnForOrg","BUNDLE_ID","datasetNameLower","coerceDocumentValues","datasetIntegrityFields","datasetIntegrityUpdate","defaultDatasetFieldId","validateDocument","DATASET_IMAGE_FIELD_TYPE","isDatasetImageValue","DATASET_PAGE_FIELD_TYPE","isDatasetPageValue","RECORD_PAGE_ADDRESS_FIELD_TYPE","RECORD_PAGE_ADDRESS_MAX","uniqueRecordAddresses","DATASET_DRAFT_RESOURCE","DATASET_DRAFT_NAME_MAX","DATASET_DRAFT_FIELDS_MAX","DATASET_DRAFT_FIELD_NAME_MAX","DATASET_DRAFT_RECORDS_MAX","DATASET_DRAFT_VALUE_MAX","DATASET_DRAFT_LIST_MAX","DATASET_DRAFT_FIELD_TYPES","text","number","integer","boolean","list","image","page","DRAFT_TYPES","Object","keys","DATASET_DRAFT_PERMISSION_REFUSAL","DATASET_DRAFT_PLAN_REFUSAL","DATASET_DRAFT_RELEASE_REFUSAL","DATASET_DRAFT_SCOPE_REFUSAL","DATASET_DRAFT_STORAGE_REFUSAL","datasetDraftLimitRefusal","quota","upgradeRequired","limit","addonPriceUsd","datasetDraftRecordLimitRefusal","isRecord","value","Array","isArray","line","replace","trim","seedValue","slice","map","entry","filter","undefined","readDatasetDraftContent","content","problems","name","push","length","rawFields","model","fields","order","byName","Map","raw","fieldName","rawType","includes","join","has","toLowerCase","id","Set","type","customType","required","set","addressField","rawAddress","sourceId","get","slugFrom","rawRecords","records","forEach","index","input","key","entries","values","errors","field","error","rawSamples","some","samples","_values","ok","source","assigned","String","address","imageFieldOf","find","factsOf","imageField","checkDatasetDraftContent","read","facts","platformMember","uid","orgId","membership","member","canManageData","createDatasetDraftWriter","deps","firestore","app","orgIdForHost","hostId","memberOf","released","storageFull","org","orgRef","Boolean","early","context","status","scopeOf","refusal","refused","used","collection","doc","count","data","Number","allowed","check","dataset","exists","recordOf","reviseRecords","request","orders","record","isInteger","changed","db","datasetRef","runTransaction","tx","rows","where","revision","row","docs","stored","named","badPhoto","update","ref","delete","updatedAt","now","write","asked","datasets","recordQuota","Math","max","visibleTo","recordIds","existing","replayed","live","create","displayName","nameLower","createdAt","createdBy","sample","versionId","datasetDraftWriter","registerDatasetDraftWriter","pluginId"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,qBAAqB,QAAQ,yCAAwC;AAC9E,SAASC,YAAY,QAAQ,uCAAsC;AACnE,SAASC,iBAAiB,EAAEC,gBAAgB,EAAEC,UAAU,QAAQ,2CAA0C;AAC1G,SAASC,cAAc,EAAEC,sBAAsB,QAAQ,sCAAqC;AAC5F,SACEC,iCAAiC,QAQ5B,qDAAoD;AAC3D,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,UAAU,Q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{ announceDatasetRecords as announceDatasetChange } from "./announce-dataset-records.js";
27
27
  import { datasetRefusalPermission, memberMayActOnDataset } from "./dataset-access.server.js";
28
28
  import { coerceDocumentValues, datasetIntegrityFields, datasetIntegrityUpdate, effectiveDatasetModel, validateDocument } from "../model/dataset-models.js";
29
- import { defaultDatasetFieldId } from "../model/datasets.js";
29
+ import { datasetNameLower, defaultDatasetFieldId } from "../model/datasets.js";
30
30
  import { planReferenceFixups, referencingFieldIds, restrictedDeleteMessage } from "../model/dataset-record-delete-plan.js";
31
31
  import { RECORD_PAGE_ADDRESS_FIELD_TYPE, fillRecordAddresses, isRecordAddressField, recordAddressFieldIds, recordAddressOf, uniqueRecordAddresses } from "../record-pages/record-pages.js";
32
32
  /**
@@ -334,6 +334,7 @@ import { RECORD_PAGE_ADDRESS_FIELD_TYPE, fillRecordAddresses, isRecordAddressFie
334
334
  if (!authoritative.allowed) return overDatasetQuota(authoritative);
335
335
  tx.create(datasetsRef.doc(id), _extends({
336
336
  displayName,
337
+ nameLower: datasetNameLower(displayName),
337
338
  fields
338
339
  }, model ? {
339
340
  model