@wix/bex-core 2.402.0 → 2.404.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 (52) hide show
  1. package/dist/cjs/state/CustomFieldModalState.js +5 -1
  2. package/dist/cjs/state/CustomFieldModalState.js.map +1 -1
  3. package/dist/cjs/state/ImportState/ImportState.js +9 -4
  4. package/dist/cjs/state/ImportState/ImportState.js.map +1 -1
  5. package/dist/cjs/state/ImportState/__tests__/ImportState.engine.spec.js +13 -0
  6. package/dist/cjs/state/ImportState/__tests__/ImportState.engine.spec.js.map +1 -1
  7. package/dist/cjs/state/ImportState/detectFieldType.js +37 -16
  8. package/dist/cjs/state/ImportState/detectFieldType.js.map +1 -1
  9. package/dist/cjs/state/ImportState/fieldEdit.js +2 -1
  10. package/dist/cjs/state/ImportState/fieldEdit.js.map +1 -1
  11. package/dist/cjs/state/ImportState/importSampling.js +2 -1
  12. package/dist/cjs/state/ImportState/importSampling.js.map +1 -1
  13. package/dist/cjs/testkit/createInMemorySchemaSource.js +4 -0
  14. package/dist/cjs/testkit/createInMemorySchemaSource.js.map +1 -1
  15. package/dist/cjs/types/FieldTypeDefinition.js.map +1 -1
  16. package/dist/cjs/types/FieldsSource.js.map +1 -1
  17. package/dist/cjs/types/SchemaSource.js +1 -0
  18. package/dist/cjs/types/SchemaSource.js.map +1 -1
  19. package/dist/esm/state/CustomFieldModalState.js +6 -1
  20. package/dist/esm/state/CustomFieldModalState.js.map +1 -1
  21. package/dist/esm/state/ImportState/ImportState.js +19 -8
  22. package/dist/esm/state/ImportState/ImportState.js.map +1 -1
  23. package/dist/esm/state/ImportState/__tests__/ImportState.engine.spec.js +8 -0
  24. package/dist/esm/state/ImportState/__tests__/ImportState.engine.spec.js.map +1 -1
  25. package/dist/esm/state/ImportState/detectFieldType.js +39 -11
  26. package/dist/esm/state/ImportState/detectFieldType.js.map +1 -1
  27. package/dist/esm/state/ImportState/fieldEdit.js +1 -0
  28. package/dist/esm/state/ImportState/fieldEdit.js.map +1 -1
  29. package/dist/esm/state/ImportState/importSampling.js +1 -0
  30. package/dist/esm/state/ImportState/importSampling.js.map +1 -1
  31. package/dist/esm/testkit/createInMemorySchemaSource.js +4 -1
  32. package/dist/esm/testkit/createInMemorySchemaSource.js.map +1 -1
  33. package/dist/esm/types/FieldTypeDefinition.js.map +1 -1
  34. package/dist/esm/types/SchemaSource.js +1 -0
  35. package/dist/esm/types/SchemaSource.js.map +1 -1
  36. package/dist/types/state/CustomFieldModalState.d.ts.map +1 -1
  37. package/dist/types/state/ImportState/ImportState.d.ts +1 -0
  38. package/dist/types/state/ImportState/ImportState.d.ts.map +1 -1
  39. package/dist/types/state/ImportState/detectFieldType.d.ts +2 -2
  40. package/dist/types/state/ImportState/detectFieldType.d.ts.map +1 -1
  41. package/dist/types/state/ImportState/fieldEdit.d.ts.map +1 -1
  42. package/dist/types/state/ImportState/importSampling.d.ts +1 -0
  43. package/dist/types/state/ImportState/importSampling.d.ts.map +1 -1
  44. package/dist/types/testkit/createInMemorySchemaSource.d.ts +2 -0
  45. package/dist/types/testkit/createInMemorySchemaSource.d.ts.map +1 -1
  46. package/dist/types/types/FieldTypeDefinition.d.ts +3 -1
  47. package/dist/types/types/FieldTypeDefinition.d.ts.map +1 -1
  48. package/dist/types/types/FieldsSource.d.ts +3 -1
  49. package/dist/types/types/FieldsSource.d.ts.map +1 -1
  50. package/dist/types/types/SchemaSource.d.ts +4 -0
  51. package/dist/types/types/SchemaSource.d.ts.map +1 -1
  52. package/package.json +4 -4
@@ -22,20 +22,12 @@ var _importSampling = require("./importSampling");
22
22
  // the per-value detector as a parameter so the fields detector reuses this
23
23
  // sampling/majority logic instead of re-implementing it.
24
24
 
25
- // All field types a new column can be detected as. The primitive detector below
26
- // only ever returns the first five; image/video/document/audio come from the
27
- // injected fields detector.
28
-
29
25
  // Infers a column's field type from its values. Injected into `ImportState`.
30
26
 
31
27
  // Infers a single cell's field type.
32
28
 
33
- // Column-detection sampling: look at the first `TYPE_SAMPLE_SIZE` values and
34
- // require a >= `TYPE_MAJORITY` share to agree on a non-text type. We use the same 2/3
35
- // vote as cm-import but a **larger sample** — cm-import's `constants.sampleSize`
36
- // is 6; we deliberately sample more so the inference is steadier on messy
37
- // columns. Exported so callers pass only the head of a column to
38
- // `detectColumnType` instead of copying it whole.
29
+ // Existing-field compatibility keeps a larger, nonempty sample. New-field
30
+ // suggestions use cm-import's six-row sample, including blanks.
39
31
  const TYPE_SAMPLE_SIZE = exports.TYPE_SAMPLE_SIZE = 50;
40
32
 
41
33
  // cm-import `validators/number.js` `validateString`.
@@ -102,9 +94,20 @@ function detectValueType(value) {
102
94
  if (isDate(value)) {
103
95
  return 'date';
104
96
  }
97
+ try {
98
+ const parsed = JSON.parse(value);
99
+ if (Array.isArray(parsed) && parsed.every(item => typeof item === 'string')) {
100
+ return 'multiReference';
101
+ }
102
+ } catch {
103
+ // Only string arrays have a parsed-value detection rule in cm-import.
104
+ }
105
105
  if (isUrl(value)) {
106
106
  return 'url';
107
107
  }
108
+ if (/<\w+\s*[^>]*>/.test(value)) {
109
+ return 'richText';
110
+ }
108
111
  return 'text';
109
112
  }
110
113
 
@@ -123,7 +126,9 @@ const NEW_FIELD_TYPE_TO_DATA_EXTENSION = {
123
126
  image: 'shortText',
124
127
  video: 'shortText',
125
128
  document: 'files',
126
- audio: 'shortText'
129
+ audio: 'shortText',
130
+ richText: 'longText',
131
+ multiReference: 'shortText'
127
132
  };
128
133
 
129
134
  /** Default DataExtension field-type id for a detected `NewFieldType`. */
@@ -141,7 +146,9 @@ const NEW_FIELD_TYPE_TO_PATTERNS = {
141
146
  image: 'IMAGE',
142
147
  video: 'VIDEO',
143
148
  document: 'DOCUMENT',
144
- audio: 'AUDIO'
149
+ audio: 'AUDIO',
150
+ richText: 'RICH_TEXT',
151
+ multiReference: 'MULTI_REFERENCE'
145
152
  };
146
153
 
147
154
  /** Schema `PatternsFieldType` for a detected `NewFieldType`. */
@@ -151,7 +158,7 @@ const toPatternsFieldType = type => NEW_FIELD_TYPE_TO_PATTERNS[type];
151
158
  * Infer a column's field type from its first values: the most common detected
152
159
  * type, but only when it covers at least two-thirds of the samples (otherwise
153
160
  * `text`). Same majority-vote algorithm as cm-import
154
- * `guessFieldConfigFromSamples`, with a larger sample (see `TYPE_SAMPLE_SIZE`).
161
+ * `guessFieldConfigFromSamples`, including date formats and boolean casing.
155
162
  *
156
163
  * `detectValue` defaults to the primitive {@link detectValueType}; the fields
157
164
  * detector passes a media-aware variant so it reuses this sampling/majority
@@ -159,18 +166,32 @@ const toPatternsFieldType = type => NEW_FIELD_TYPE_TO_PATTERNS[type];
159
166
  */
160
167
  exports.toPatternsFieldType = toPatternsFieldType;
161
168
  function detectColumnType(values, detectValue = detectValueType) {
162
- const samples = values.slice(0, TYPE_SAMPLE_SIZE);
169
+ const samples = values.slice(0, _importSampling.NEW_FIELD_SAMPLE_SIZE);
163
170
  if (samples.length === 0) {
164
171
  return 'text';
165
172
  }
166
173
  const counts = new Map();
167
174
  samples.forEach(value => {
175
+ var _counts$get;
168
176
  const type = detectValue(value);
169
- counts.set(type, (counts.get(type) ?? 0) + 1);
177
+ let format = '';
178
+ if (type === 'boolean') {
179
+ format = value === value.toUpperCase() ? 'upper' : /^[A-Z][a-z]+$/.test(value) ? 'sentence' : 'lower';
180
+ } else if (type === 'date' && SLASH_DATE_RE.test(value)) {
181
+ format = Number.isNaN(new Date(value).getTime()) ? 'ddmmyyyy' : 'mmddyyyy';
182
+ }
183
+ const key = `${type}:${format}`;
184
+ counts.set(key, {
185
+ type,
186
+ count: (((_counts$get = counts.get(key)) == null ? void 0 : _counts$get.count) ?? 0) + 1
187
+ });
170
188
  });
171
189
  let best = 'text';
172
190
  let bestCount = 0;
173
- counts.forEach((count, type) => {
191
+ counts.forEach(({
192
+ count,
193
+ type
194
+ }) => {
174
195
  if (count > bestCount) {
175
196
  best = type;
176
197
  bestCount = count;
@@ -1 +1 @@
1
- {"version":3,"names":["_importSampling","require","TYPE_SAMPLE_SIZE","exports","NUMBER_RE","SLASH_DATE_RE","ISO_DATE_RE","WEBSITE_PROTOCOLS","EMAIL_PROTOCOL","PHONE_PROTOCOLS","RELATIVE_PREFIXES","PHONE_RE","EMAIL_RE","startsWithAny","value","prefixes","some","prefix","startsWith","isValidWebsiteUrl","parsed","URL","includes","protocol","isEmailUrl","test","slice","length","isPhoneUrl","isUrl","isDate","Number","isNaN","Date","getTime","swapped","replace","detectValueType","lower","toLowerCase","NEW_FIELD_TYPE_TO_DATA_EXTENSION","text","number","date","boolean","url","image","video","document","audio","toDataExtensionFieldType","type","NEW_FIELD_TYPE_TO_PATTERNS","toPatternsFieldType","detectColumnType","values","detectValue","samples","counts","Map","forEach","set","get","best","bestCount","count","TYPE_MAJORITY"],"sources":["../../../../src/state/ImportState/detectFieldType.ts"],"sourcesContent":["import { TYPE_MAJORITY } from './importSampling';\nimport type { PatternsFieldType } from '../../types/Field';\n\n// Field-type detection for new fields created during CSV import (CAIRO-4131).\n//\n// Ported from cm-import (`wix-data-client/cm-import`):\n// - per-cell rules from `src/field-configuration/detectFieldConfig.js`\n// (`detectPrimitiveType`) and `src/types/validators/{number,url}.js`\n// - the column-level majority vote from\n// `src/field-configuration/guessFieldConfigFromSamples.js`\n//\n// This module owns the shared `NewFieldType` vocabulary and the primitive\n// detector (number / date / boolean / url, else text). Media detection (image /\n// video / document / audio) lives in `@wix/patterns-fields` — it needs the media\n// URI parser, which core must not depend on — and is injected into `ImportState`\n// via `detectColumnType` (see `ImportStateProps`). `detectColumnType` here takes\n// the per-value detector as a parameter so the fields detector reuses this\n// sampling/majority logic instead of re-implementing it.\n\n// All field types a new column can be detected as. The primitive detector below\n// only ever returns the first five; image/video/document/audio come from the\n// injected fields detector.\nexport type NewFieldType =\n | 'text'\n | 'number'\n | 'date'\n | 'boolean'\n | 'url'\n | 'image'\n | 'video'\n | 'document'\n | 'audio';\n\n// Infers a column's field type from its values. Injected into `ImportState`.\nexport type DetectColumnType = (values: string[]) => NewFieldType;\n\n// Infers a single cell's field type.\nexport type DetectValueType = (value: string) => NewFieldType;\n\n// Column-detection sampling: look at the first `TYPE_SAMPLE_SIZE` values and\n// require a >= `TYPE_MAJORITY` share to agree on a non-text type. We use the same 2/3\n// vote as cm-import but a **larger sample** — cm-import's `constants.sampleSize`\n// is 6; we deliberately sample more so the inference is steadier on messy\n// columns. Exported so callers pass only the head of a column to\n// `detectColumnType` instead of copying it whole.\nexport const TYPE_SAMPLE_SIZE = 50;\n\n// cm-import `validators/number.js` `validateString`.\nconst NUMBER_RE = /^[+-]?(?:\\d+\\.?\\d*)?$/;\n\n// cm-import `detectFieldConfig.js` date patterns.\nconst SLASH_DATE_RE = /^\\d{1,2}\\/\\d{1,2}\\/\\d{4}(?: \\d{1,2}:\\d{1,2})?$/;\nconst ISO_DATE_RE = /\\d{4}-\\d{2}-\\d{2}/;\n\n// Approximates cm-import `validators/url.js` (website / email / phone / relative\n// links). cm-import delegates structural validation to `@wix/santa-core-utils`\n// `isValidUrl`/`isValidEmail`, which aren't available here — so website URLs are\n// validated with the platform `URL` parser instead (rejects empty/whitespace/\n// malformed authorities). It's still an approximation: `URL` accepts some\n// odd-but-parseable hosts santa would reject.\nconst WEBSITE_PROTOCOLS = ['http:', 'https:', 'ftp:'];\nconst EMAIL_PROTOCOL = 'mailto:';\nconst PHONE_PROTOCOLS = ['sms:', 'tel:'];\nconst RELATIVE_PREFIXES = ['/', '#', '?'];\nconst PHONE_RE = /^[\\s\\d()+\\-/_]+$/;\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n\nconst startsWithAny = (value: string, prefixes: readonly string[]): boolean =>\n prefixes.some((prefix) => value.startsWith(prefix));\n\nconst isValidWebsiteUrl = (value: string): boolean => {\n let parsed: URL;\n try {\n parsed = new URL(value);\n } catch {\n return false;\n }\n return WEBSITE_PROTOCOLS.includes(parsed.protocol);\n};\n\nconst isEmailUrl = (value: string): boolean =>\n value.startsWith(EMAIL_PROTOCOL) &&\n EMAIL_RE.test(value.slice(EMAIL_PROTOCOL.length));\n\nconst isPhoneUrl = (value: string): boolean =>\n PHONE_PROTOCOLS.some(\n (protocol) =>\n value.startsWith(protocol) && PHONE_RE.test(value.slice(protocol.length)),\n );\n\nconst isUrl = (value: string): boolean =>\n isValidWebsiteUrl(value) ||\n isEmailUrl(value) ||\n isPhoneUrl(value) ||\n startsWithAny(value, RELATIVE_PREFIXES);\n\nconst isDate = (value: string): boolean => {\n if (SLASH_DATE_RE.test(value)) {\n if (!Number.isNaN(new Date(value).getTime())) {\n return true;\n }\n // cm-import also accepts dd/mm/yyyy by swapping day and month.\n const swapped = value.replace(/(\\d{1,2})\\/(\\d{1,2})\\/(\\d{4})/, '$2/$1/$3');\n if (!Number.isNaN(new Date(swapped).getTime())) {\n return true;\n }\n }\n return ISO_DATE_RE.test(value) && !Number.isNaN(new Date(value).getTime());\n};\n\n/**\n * Infer the field type of a single CSV cell, in cm-import's order:\n * empty → number → boolean → date → url, else text.\n */\nexport function detectValueType(value: string): NewFieldType {\n if (value === '') {\n return 'text';\n }\n if (NUMBER_RE.test(value)) {\n return 'number';\n }\n const lower = value.toLowerCase();\n if (lower === 'true' || lower === 'false') {\n return 'boolean';\n }\n if (isDate(value)) {\n return 'date';\n }\n if (isUrl(value)) {\n return 'url';\n }\n return 'text';\n}\n\n// Default DataExtension `CustomFieldType` id for a detected `NewFieldType`, used\n// to seed a new DataExtension field before the user edits it (they can then pick\n// a finer type — e.g. decimal, longText — in the editor). DataExtension has no\n// media types, so image/video/audio fall back to `shortText`; a document column\n// maps to `files`. See the DataExtension creatable-type list in\n// `dataExtensionFieldManagement`.\nconst NEW_FIELD_TYPE_TO_DATA_EXTENSION: Record<NewFieldType, string> = {\n text: 'shortText',\n number: 'integer',\n date: 'date',\n boolean: 'checkbox',\n url: 'url',\n image: 'shortText',\n video: 'shortText',\n document: 'files',\n audio: 'shortText',\n};\n\n/** Default DataExtension field-type id for a detected `NewFieldType`. */\nexport const toDataExtensionFieldType = (type: NewFieldType): string =>\n NEW_FIELD_TYPE_TO_DATA_EXTENSION[type];\n\n// Maps the import flow's `NewFieldType` (lowercase, data-driven detection) to the\n// schema's `PatternsFieldType` (uppercase) used by `Field` / the field editor.\nconst NEW_FIELD_TYPE_TO_PATTERNS: Record<NewFieldType, PatternsFieldType> = {\n text: 'SHORT_TEXT',\n number: 'NUMBER',\n date: 'DATE',\n boolean: 'BOOLEAN',\n url: 'URL',\n image: 'IMAGE',\n video: 'VIDEO',\n document: 'DOCUMENT',\n audio: 'AUDIO',\n};\n\n/** Schema `PatternsFieldType` for a detected `NewFieldType`. */\nexport const toPatternsFieldType = (type: NewFieldType): PatternsFieldType =>\n NEW_FIELD_TYPE_TO_PATTERNS[type];\n\n/**\n * Infer a column's field type from its first values: the most common detected\n * type, but only when it covers at least two-thirds of the samples (otherwise\n * `text`). Same majority-vote algorithm as cm-import\n * `guessFieldConfigFromSamples`, with a larger sample (see `TYPE_SAMPLE_SIZE`).\n *\n * `detectValue` defaults to the primitive {@link detectValueType}; the fields\n * detector passes a media-aware variant so it reuses this sampling/majority\n * logic.\n */\nexport function detectColumnType(\n values: string[],\n detectValue: DetectValueType = detectValueType,\n): NewFieldType {\n const samples = values.slice(0, TYPE_SAMPLE_SIZE);\n if (samples.length === 0) {\n return 'text';\n }\n\n const counts = new Map<NewFieldType, number>();\n samples.forEach((value) => {\n const type = detectValue(value);\n counts.set(type, (counts.get(type) ?? 0) + 1);\n });\n\n let best: NewFieldType = 'text';\n let bestCount = 0;\n counts.forEach((count, type) => {\n if (count > bestCount) {\n best = type;\n bestCount = count;\n }\n });\n\n return bestCount >= samples.length * TYPE_MAJORITY ? best : 'text';\n}\n"],"mappings":";;;;;;;AAAA,IAAAA,eAAA,GAAAC,OAAA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAYA;;AAGA;;AAGA;AACA;AACA;AACA;AACA;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;EAC9CF,OAAO,CAACG,OAAO,CAAE9C,KAAK,IAAK;IACzB,MAAMqC,IAAI,GAAGK,WAAW,CAAC1C,KAAK,CAAC;IAC/B4C,MAAM,CAACG,GAAG,CAACV,IAAI,EAAE,CAACO,MAAM,CAACI,GAAG,CAACX,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;EAC/C,CAAC,CAAC;EAEF,IAAIY,IAAkB,GAAG,MAAM;EAC/B,IAAIC,SAAS,GAAG,CAAC;EACjBN,MAAM,CAACE,OAAO,CAAC,CAACK,KAAK,EAAEd,IAAI,KAAK;IAC9B,IAAIc,KAAK,GAAGD,SAAS,EAAE;MACrBD,IAAI,GAAGZ,IAAI;MACXa,SAAS,GAAGC,KAAK;IACnB;EACF,CAAC,CAAC;EAEF,OAAOD,SAAS,IAAIP,OAAO,CAAC9B,MAAM,GAAGuC,6BAAa,GAAGH,IAAI,GAAG,MAAM;AACpE","ignoreList":[]}
1
+ {"version":3,"names":["_importSampling","require","TYPE_SAMPLE_SIZE","exports","NUMBER_RE","SLASH_DATE_RE","ISO_DATE_RE","WEBSITE_PROTOCOLS","EMAIL_PROTOCOL","PHONE_PROTOCOLS","RELATIVE_PREFIXES","PHONE_RE","EMAIL_RE","startsWithAny","value","prefixes","some","prefix","startsWith","isValidWebsiteUrl","parsed","URL","includes","protocol","isEmailUrl","test","slice","length","isPhoneUrl","isUrl","isDate","Number","isNaN","Date","getTime","swapped","replace","detectValueType","lower","toLowerCase","JSON","parse","Array","isArray","every","item","NEW_FIELD_TYPE_TO_DATA_EXTENSION","text","number","date","boolean","url","image","video","document","audio","richText","multiReference","toDataExtensionFieldType","type","NEW_FIELD_TYPE_TO_PATTERNS","toPatternsFieldType","detectColumnType","values","detectValue","samples","NEW_FIELD_SAMPLE_SIZE","counts","Map","forEach","_counts$get","format","toUpperCase","key","set","count","get","best","bestCount","TYPE_MAJORITY"],"sources":["../../../../src/state/ImportState/detectFieldType.ts"],"sourcesContent":["import { NEW_FIELD_SAMPLE_SIZE, TYPE_MAJORITY } from './importSampling';\nimport type { PatternsFieldType } from '../../types/Field';\n\n// Field-type detection for new fields created during CSV import (CAIRO-4131).\n//\n// Ported from cm-import (`wix-data-client/cm-import`):\n// - per-cell rules from `src/field-configuration/detectFieldConfig.js`\n// (`detectPrimitiveType`) and `src/types/validators/{number,url}.js`\n// - the column-level majority vote from\n// `src/field-configuration/guessFieldConfigFromSamples.js`\n//\n// This module owns the shared `NewFieldType` vocabulary and the primitive\n// detector (number / date / boolean / url, else text). Media detection (image /\n// video / document / audio) lives in `@wix/patterns-fields` — it needs the media\n// URI parser, which core must not depend on — and is injected into `ImportState`\n// via `detectColumnType` (see `ImportStateProps`). `detectColumnType` here takes\n// the per-value detector as a parameter so the fields detector reuses this\n// sampling/majority logic instead of re-implementing it.\n\nexport type NewFieldType =\n | 'text'\n | 'number'\n | 'date'\n | 'boolean'\n | 'url'\n | 'image'\n | 'video'\n | 'document'\n | 'audio'\n | 'richText'\n | 'multiReference';\n\n// Infers a column's field type from its values. Injected into `ImportState`.\nexport type DetectColumnType = (values: string[]) => NewFieldType;\n\n// Infers a single cell's field type.\nexport type DetectValueType = (value: string) => NewFieldType;\n\n// Existing-field compatibility keeps a larger, nonempty sample. New-field\n// suggestions use cm-import's six-row sample, including blanks.\nexport const TYPE_SAMPLE_SIZE = 50;\n\n// cm-import `validators/number.js` `validateString`.\nconst NUMBER_RE = /^[+-]?(?:\\d+\\.?\\d*)?$/;\n\n// cm-import `detectFieldConfig.js` date patterns.\nconst SLASH_DATE_RE = /^\\d{1,2}\\/\\d{1,2}\\/\\d{4}(?: \\d{1,2}:\\d{1,2})?$/;\nconst ISO_DATE_RE = /\\d{4}-\\d{2}-\\d{2}/;\n\n// Approximates cm-import `validators/url.js` (website / email / phone / relative\n// links). cm-import delegates structural validation to `@wix/santa-core-utils`\n// `isValidUrl`/`isValidEmail`, which aren't available here — so website URLs are\n// validated with the platform `URL` parser instead (rejects empty/whitespace/\n// malformed authorities). It's still an approximation: `URL` accepts some\n// odd-but-parseable hosts santa would reject.\nconst WEBSITE_PROTOCOLS = ['http:', 'https:', 'ftp:'];\nconst EMAIL_PROTOCOL = 'mailto:';\nconst PHONE_PROTOCOLS = ['sms:', 'tel:'];\nconst RELATIVE_PREFIXES = ['/', '#', '?'];\nconst PHONE_RE = /^[\\s\\d()+\\-/_]+$/;\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n\nconst startsWithAny = (value: string, prefixes: readonly string[]): boolean =>\n prefixes.some((prefix) => value.startsWith(prefix));\n\nconst isValidWebsiteUrl = (value: string): boolean => {\n let parsed: URL;\n try {\n parsed = new URL(value);\n } catch {\n return false;\n }\n return WEBSITE_PROTOCOLS.includes(parsed.protocol);\n};\n\nconst isEmailUrl = (value: string): boolean =>\n value.startsWith(EMAIL_PROTOCOL) &&\n EMAIL_RE.test(value.slice(EMAIL_PROTOCOL.length));\n\nconst isPhoneUrl = (value: string): boolean =>\n PHONE_PROTOCOLS.some(\n (protocol) =>\n value.startsWith(protocol) && PHONE_RE.test(value.slice(protocol.length)),\n );\n\nconst isUrl = (value: string): boolean =>\n isValidWebsiteUrl(value) ||\n isEmailUrl(value) ||\n isPhoneUrl(value) ||\n startsWithAny(value, RELATIVE_PREFIXES);\n\nconst isDate = (value: string): boolean => {\n if (SLASH_DATE_RE.test(value)) {\n if (!Number.isNaN(new Date(value).getTime())) {\n return true;\n }\n // cm-import also accepts dd/mm/yyyy by swapping day and month.\n const swapped = value.replace(/(\\d{1,2})\\/(\\d{1,2})\\/(\\d{4})/, '$2/$1/$3');\n if (!Number.isNaN(new Date(swapped).getTime())) {\n return true;\n }\n }\n return ISO_DATE_RE.test(value) && !Number.isNaN(new Date(value).getTime());\n};\n\n/**\n * Infer the field type of a single CSV cell, in cm-import's order:\n * empty → number → boolean → date → url, else text.\n */\nexport function detectValueType(value: string): NewFieldType {\n if (value === '') {\n return 'text';\n }\n if (NUMBER_RE.test(value)) {\n return 'number';\n }\n const lower = value.toLowerCase();\n if (lower === 'true' || lower === 'false') {\n return 'boolean';\n }\n if (isDate(value)) {\n return 'date';\n }\n try {\n const parsed: unknown = JSON.parse(value);\n if (\n Array.isArray(parsed) &&\n parsed.every((item) => typeof item === 'string')\n ) {\n return 'multiReference';\n }\n } catch {\n // Only string arrays have a parsed-value detection rule in cm-import.\n }\n if (isUrl(value)) {\n return 'url';\n }\n if (/<\\w+\\s*[^>]*>/.test(value)) {\n return 'richText';\n }\n return 'text';\n}\n\n// Default DataExtension `CustomFieldType` id for a detected `NewFieldType`, used\n// to seed a new DataExtension field before the user edits it (they can then pick\n// a finer type — e.g. decimal, longText — in the editor). DataExtension has no\n// media types, so image/video/audio fall back to `shortText`; a document column\n// maps to `files`. See the DataExtension creatable-type list in\n// `dataExtensionFieldManagement`.\nconst NEW_FIELD_TYPE_TO_DATA_EXTENSION: Record<NewFieldType, string> = {\n text: 'shortText',\n number: 'integer',\n date: 'date',\n boolean: 'checkbox',\n url: 'url',\n image: 'shortText',\n video: 'shortText',\n document: 'files',\n audio: 'shortText',\n richText: 'longText',\n multiReference: 'shortText',\n};\n\n/** Default DataExtension field-type id for a detected `NewFieldType`. */\nexport const toDataExtensionFieldType = (type: NewFieldType): string =>\n NEW_FIELD_TYPE_TO_DATA_EXTENSION[type];\n\n// Maps the import flow's `NewFieldType` (lowercase, data-driven detection) to the\n// schema's `PatternsFieldType` (uppercase) used by `Field` / the field editor.\nconst NEW_FIELD_TYPE_TO_PATTERNS: Record<NewFieldType, PatternsFieldType> = {\n text: 'SHORT_TEXT',\n number: 'NUMBER',\n date: 'DATE',\n boolean: 'BOOLEAN',\n url: 'URL',\n image: 'IMAGE',\n video: 'VIDEO',\n document: 'DOCUMENT',\n audio: 'AUDIO',\n richText: 'RICH_TEXT',\n multiReference: 'MULTI_REFERENCE',\n};\n\n/** Schema `PatternsFieldType` for a detected `NewFieldType`. */\nexport const toPatternsFieldType = (type: NewFieldType): PatternsFieldType =>\n NEW_FIELD_TYPE_TO_PATTERNS[type];\n\n/**\n * Infer a column's field type from its first values: the most common detected\n * type, but only when it covers at least two-thirds of the samples (otherwise\n * `text`). Same majority-vote algorithm as cm-import\n * `guessFieldConfigFromSamples`, including date formats and boolean casing.\n *\n * `detectValue` defaults to the primitive {@link detectValueType}; the fields\n * detector passes a media-aware variant so it reuses this sampling/majority\n * logic.\n */\nexport function detectColumnType(\n values: string[],\n detectValue: DetectValueType = detectValueType,\n): NewFieldType {\n const samples = values.slice(0, NEW_FIELD_SAMPLE_SIZE);\n if (samples.length === 0) {\n return 'text';\n }\n\n const counts = new Map<string, { type: NewFieldType; count: number }>();\n samples.forEach((value) => {\n const type = detectValue(value);\n let format = '';\n if (type === 'boolean') {\n format =\n value === value.toUpperCase()\n ? 'upper'\n : /^[A-Z][a-z]+$/.test(value)\n ? 'sentence'\n : 'lower';\n } else if (type === 'date' && SLASH_DATE_RE.test(value)) {\n format = Number.isNaN(new Date(value).getTime())\n ? 'ddmmyyyy'\n : 'mmddyyyy';\n }\n const key = `${type}:${format}`;\n counts.set(key, { type, count: (counts.get(key)?.count ?? 0) + 1 });\n });\n\n let best: NewFieldType = 'text';\n let bestCount = 0;\n counts.forEach(({ count, type }) => {\n if (count > bestCount) {\n best = type;\n bestCount = count;\n }\n });\n\n return bestCount >= samples.length * TYPE_MAJORITY ? best : 'text';\n}\n"],"mappings":";;;;;;;AAAA,IAAAA,eAAA,GAAAC,OAAA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAeA;;AAGA;;AAGA;AACA;AACO,MAAMC,gBAAgB,GAAAC,OAAA,CAAAD,gBAAA,GAAG,EAAE;;AAElC;AACA,MAAME,SAAS,GAAG,uBAAuB;;AAEzC;AACA,MAAMC,aAAa,GAAG,gDAAgD;AACtE,MAAMC,WAAW,GAAG,mBAAmB;;AAEvC;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,iBAAiB,GAAG,CAAC,OAAO,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EAAE;MACrBD,IAAI,GAAGlB,IAAI;MACXmB,SAAS,GAAGH,KAAK;IACnB;EACF,CAAC,CAAC;EAEF,OAAOG,SAAS,IAAIb,OAAO,CAACtC,MAAM,GAAGoD,6BAAa,GAAGF,IAAI,GAAG,MAAM;AACpE","ignoreList":[]}
@@ -19,7 +19,8 @@ const PATTERNS_TO_NEW_FIELD_TYPE = {
19
19
  IMAGE: 'image',
20
20
  VIDEO: 'video',
21
21
  DOCUMENT: 'document',
22
- AUDIO: 'audio'
22
+ AUDIO: 'audio',
23
+ RICH_TEXT: 'richText'
23
24
  };
24
25
  const toNewFieldType = type => PATTERNS_TO_NEW_FIELD_TYPE[type] ?? 'text';
25
26
 
@@ -1 +1 @@
1
- {"version":3,"names":["PATTERNS_TO_NEW_FIELD_TYPE","SHORT_TEXT","LONG_TEXT","NUMBER","DATE","DATETIME","BOOLEAN","URL","IMAGE","VIDEO","DOCUMENT","AUDIO","toNewFieldType","type","exports","toFieldEdit","field","config","validation","isPii","helpText","fieldType","displayName","Object","keys","length","undefined","DATA_EXTENSION_TO_NEW_FIELD_TYPE","shortText","longText","url","date","dateTime","integer","decimal","checkbox","multiSelect","files","toDataExtensionFieldEdit","draft","permissions","installedApps","defaultRead","readApps","defaultWrite","writeApps","siteVisitors","readUsers","writeUsers","deType","containsPii","name"],"sources":["../../../../src/state/ImportState/fieldEdit.ts"],"sourcesContent":["import type { FieldSpec, PatternsFieldType } from '../../types/Field';\nimport type { FieldDraft, FieldPermissions } from '../../types/FieldsSource';\nimport type { NewFieldType } from './detectFieldType';\nimport type { NewFieldConfig } from './ImportState';\n\n// Reverse of the import detector's vocabulary: maps a schema field type\n// (`PatternsFieldType`, uppercase) back to the import flow's `NewFieldType`. Only\n// the types the field editor can produce need entries; anything else falls back\n// to `text`.\nconst PATTERNS_TO_NEW_FIELD_TYPE: Partial<\n Record<PatternsFieldType, NewFieldType>\n> = {\n SHORT_TEXT: 'text',\n LONG_TEXT: 'text',\n NUMBER: 'number',\n DATE: 'date',\n DATETIME: 'date',\n BOOLEAN: 'boolean',\n URL: 'url',\n IMAGE: 'image',\n VIDEO: 'video',\n DOCUMENT: 'document',\n AUDIO: 'audio',\n};\n\nexport const toNewFieldType = (type: PatternsFieldType): NewFieldType =>\n PATTERNS_TO_NEW_FIELD_TYPE[type] ?? 'text';\n\n// Converts an edited field spec (the field editor's output) into the per-column\n// new-field type + config the import flow stores via `setNewFieldConfig`.\nexport function toFieldEdit(field: FieldSpec): {\n fieldType: NewFieldType;\n displayName: string;\n config?: NewFieldConfig;\n} {\n const config: NewFieldConfig = {\n ...(field.validation && { validation: field.validation }),\n ...(field.isPii && { isPii: true }),\n ...(field.helpText && { helpText: field.helpText }),\n };\n return {\n fieldType: toNewFieldType(field.type),\n displayName: field.displayName,\n config: Object.keys(config).length > 0 ? config : undefined,\n };\n}\n\n// Coarse `NewFieldType` for a DataExtension `CustomFieldType` id — only used for\n// the config-step helper text (\"This will be a new {type} field.\"). The precise\n// DataExtension type the user picked is preserved separately on `config.deType`.\nconst DATA_EXTENSION_TO_NEW_FIELD_TYPE: Record<string, NewFieldType> = {\n shortText: 'text',\n longText: 'text',\n url: 'url',\n date: 'date',\n dateTime: 'date',\n integer: 'number',\n decimal: 'number',\n checkbox: 'boolean',\n multiSelect: 'text',\n files: 'document',\n};\n\n// Converts the DataExtension field editor's output (a source-neutral `FieldDraft`\n// carrying per-audience read/write permissions) into the per-column new-field\n// type + config the import flow stores via `setNewFieldConfig`. The precise\n// DataExtension type is kept on `config.deType`; `_createPendingFields` reads it\n// when building the create-field call.\nexport function toDataExtensionFieldEdit(draft: FieldDraft): {\n fieldType: NewFieldType;\n displayName: string;\n config?: NewFieldConfig;\n} {\n const permissions: FieldPermissions = {\n installedApps: {\n defaultRead: draft.readApps,\n defaultWrite: draft.writeApps,\n },\n siteVisitors: {\n defaultRead: draft.readUsers,\n defaultWrite: draft.writeUsers,\n },\n };\n const config: NewFieldConfig = {\n permissions,\n ...(draft.type && { deType: draft.type }),\n ...(draft.containsPii && { isPii: true }),\n };\n return {\n fieldType: draft.type\n ? DATA_EXTENSION_TO_NEW_FIELD_TYPE[draft.type] ?? 'text'\n : 'text',\n displayName: draft.name,\n config,\n };\n}\n"],"mappings":";;;;;;AAKA;AACA;AACA;AACA;AACA,MAAMA,0BAEL,GAAG;EACFC,UAAU,EAAE,MAAM;EAClBC,SAAS,EAAE,MAAM;EACjBC,MAAM,EAAE,QAAQ;EAChBC,IAAI,EAAE,MAAM;EACZC,QAAQ,EAAE,MAAM;EAChBC,OAAO,EAAE,SAAS;EAClBC,GAAG,EAAE,KAAK;EACVC,KAAK,EAAE,OAAO;EACdC,KAAK,EAAE,OAAO;EACdC,QAAQ,EAAE,UAAU;EACpBC,KAAK,EAAE;AACT,CAAC;AAEM,MAAMC,cAAc,GAAIC,IAAuB,IACpDb,0BAA0B,CAACa,IAAI,CAAC,IAAI,MAAM;;AAE5C;AACA;AAAAC,OAAA,CAAAF,cAAA,GAAAA,cAAA;AACO,SAASG,WAAWA,CAACC,KAAgB,EAI1C;EACA,MAAMC,MAAsB,GAAG;IAC7B,IAAID,KAAK,CAACE,UAAU,IAAI;MAAEA,UAAU,EAAEF,KAAK,CAACE;IAAW,CAAC,CAAC;IACzD,IAAIF,KAAK,CAACG,KAAK,IAAI;MAAEA,KAAK,EAAE;IAAK,CAAC,CAAC;IACnC,IAAIH,KAAK,CAACI,QAAQ,IAAI;MAAEA,QAAQ,EAAEJ,KAAK,CAACI;IAAS,CAAC;EACpD,CAAC;EACD,OAAO;IACLC,SAAS,EAAET,cAAc,CAACI,KAAK,CAACH,IAAI,CAAC;IACrCS,WAAW,EAAEN,KAAK,CAACM,WAAW;IAC9BL,MAAM,EAAEM,MAAM,CAACC,IAAI,CAACP,MAAM,CAAC,CAACQ,MAAM,GAAG,CAAC,GAAGR,MAAM,GAAGS;EACpD,CAAC;AACH;;AAEA;AACA;AACA;AACA,MAAMC,gCAA8D,GAAG;EACrEC,SAAS,EAAE,MAAM;EACjBC,QAAQ,EAAE,MAAM;EAChBC,GAAG,EAAE,KAAK;EACVC,IAAI,EAAE,MAAM;EACZC,QAAQ,EAAE,MAAM;EAChBC,OAAO,EAAE,QAAQ;EACjBC,OAAO,EAAE,QAAQ;EACjBC,QAAQ,EAAE,SAAS;EACnBC,WAAW,EAAE,MAAM;EACnBC,KAAK,EAAE;AACT,CAAC;;AAED;AACA;AACA;AACA;AACA;AACO,SAASC,wBAAwBA,CAACC,KAAiB,EAIxD;EACA,MAAMC,WAA6B,GAAG;IACpCC,aAAa,EAAE;MACbC,WAAW,EAAEH,KAAK,CAACI,QAAQ;MAC3BC,YAAY,EAAEL,KAAK,CAACM;IACtB,CAAC;IACDC,YAAY,EAAE;MACZJ,WAAW,EAAEH,KAAK,CAACQ,SAAS;MAC5BH,YAAY,EAAEL,KAAK,CAACS;IACtB;EACF,CAAC;EACD,MAAM/B,MAAsB,GAAG;IAC7BuB,WAAW;IACX,IAAID,KAAK,CAAC1B,IAAI,IAAI;MAAEoC,MAAM,EAAEV,KAAK,CAAC1B;IAAK,CAAC,CAAC;IACzC,IAAI0B,KAAK,CAACW,WAAW,IAAI;MAAE/B,KAAK,EAAE;IAAK,CAAC;EAC1C,CAAC;EACD,OAAO;IACLE,SAAS,EAAEkB,KAAK,CAAC1B,IAAI,GACjBc,gCAAgC,CAACY,KAAK,CAAC1B,IAAI,CAAC,IAAI,MAAM,GACtD,MAAM;IACVS,WAAW,EAAEiB,KAAK,CAACY,IAAI;IACvBlC;EACF,CAAC;AACH","ignoreList":[]}
1
+ {"version":3,"names":["PATTERNS_TO_NEW_FIELD_TYPE","SHORT_TEXT","LONG_TEXT","NUMBER","DATE","DATETIME","BOOLEAN","URL","IMAGE","VIDEO","DOCUMENT","AUDIO","RICH_TEXT","toNewFieldType","type","exports","toFieldEdit","field","config","validation","isPii","helpText","fieldType","displayName","Object","keys","length","undefined","DATA_EXTENSION_TO_NEW_FIELD_TYPE","shortText","longText","url","date","dateTime","integer","decimal","checkbox","multiSelect","files","toDataExtensionFieldEdit","draft","permissions","installedApps","defaultRead","readApps","defaultWrite","writeApps","siteVisitors","readUsers","writeUsers","deType","containsPii","name"],"sources":["../../../../src/state/ImportState/fieldEdit.ts"],"sourcesContent":["import type { FieldSpec, PatternsFieldType } from '../../types/Field';\nimport type { FieldDraft, FieldPermissions } from '../../types/FieldsSource';\nimport type { NewFieldType } from './detectFieldType';\nimport type { NewFieldConfig } from './ImportState';\n\n// Reverse of the import detector's vocabulary: maps a schema field type\n// (`PatternsFieldType`, uppercase) back to the import flow's `NewFieldType`. Only\n// the types the field editor can produce need entries; anything else falls back\n// to `text`.\nconst PATTERNS_TO_NEW_FIELD_TYPE: Partial<\n Record<PatternsFieldType, NewFieldType>\n> = {\n SHORT_TEXT: 'text',\n LONG_TEXT: 'text',\n NUMBER: 'number',\n DATE: 'date',\n DATETIME: 'date',\n BOOLEAN: 'boolean',\n URL: 'url',\n IMAGE: 'image',\n VIDEO: 'video',\n DOCUMENT: 'document',\n AUDIO: 'audio',\n RICH_TEXT: 'richText',\n};\n\nexport const toNewFieldType = (type: PatternsFieldType): NewFieldType =>\n PATTERNS_TO_NEW_FIELD_TYPE[type] ?? 'text';\n\n// Converts an edited field spec (the field editor's output) into the per-column\n// new-field type + config the import flow stores via `setNewFieldConfig`.\nexport function toFieldEdit(field: FieldSpec): {\n fieldType: NewFieldType;\n displayName: string;\n config?: NewFieldConfig;\n} {\n const config: NewFieldConfig = {\n ...(field.validation && { validation: field.validation }),\n ...(field.isPii && { isPii: true }),\n ...(field.helpText && { helpText: field.helpText }),\n };\n return {\n fieldType: toNewFieldType(field.type),\n displayName: field.displayName,\n config: Object.keys(config).length > 0 ? config : undefined,\n };\n}\n\n// Coarse `NewFieldType` for a DataExtension `CustomFieldType` id — only used for\n// the config-step helper text (\"This will be a new {type} field.\"). The precise\n// DataExtension type the user picked is preserved separately on `config.deType`.\nconst DATA_EXTENSION_TO_NEW_FIELD_TYPE: Record<string, NewFieldType> = {\n shortText: 'text',\n longText: 'text',\n url: 'url',\n date: 'date',\n dateTime: 'date',\n integer: 'number',\n decimal: 'number',\n checkbox: 'boolean',\n multiSelect: 'text',\n files: 'document',\n};\n\n// Converts the DataExtension field editor's output (a source-neutral `FieldDraft`\n// carrying per-audience read/write permissions) into the per-column new-field\n// type + config the import flow stores via `setNewFieldConfig`. The precise\n// DataExtension type is kept on `config.deType`; `_createPendingFields` reads it\n// when building the create-field call.\nexport function toDataExtensionFieldEdit(draft: FieldDraft): {\n fieldType: NewFieldType;\n displayName: string;\n config?: NewFieldConfig;\n} {\n const permissions: FieldPermissions = {\n installedApps: {\n defaultRead: draft.readApps,\n defaultWrite: draft.writeApps,\n },\n siteVisitors: {\n defaultRead: draft.readUsers,\n defaultWrite: draft.writeUsers,\n },\n };\n const config: NewFieldConfig = {\n permissions,\n ...(draft.type && { deType: draft.type }),\n ...(draft.containsPii && { isPii: true }),\n };\n return {\n fieldType: draft.type\n ? DATA_EXTENSION_TO_NEW_FIELD_TYPE[draft.type] ?? 'text'\n : 'text',\n displayName: draft.name,\n config,\n };\n}\n"],"mappings":";;;;;;AAKA;AACA;AACA;AACA;AACA,MAAMA,0BAEL,GAAG;EACFC,UAAU,EAAE,MAAM;EAClBC,SAAS,EAAE,MAAM;EACjBC,MAAM,EAAE,QAAQ;EAChBC,IAAI,EAAE,MAAM;EACZC,QAAQ,EAAE,MAAM;EAChBC,OAAO,EAAE,SAAS;EAClBC,GAAG,EAAE,KAAK;EACVC,KAAK,EAAE,OAAO;EACdC,KAAK,EAAE,OAAO;EACdC,QAAQ,EAAE,UAAU;EACpBC,KAAK,EAAE,OAAO;EACdC,SAAS,EAAE;AACb,CAAC;AAEM,MAAMC,cAAc,GAAIC,IAAuB,IACpDd,0BAA0B,CAACc,IAAI,CAAC,IAAI,MAAM;;AAE5C;AACA;AAAAC,OAAA,CAAAF,cAAA,GAAAA,cAAA;AACO,SAASG,WAAWA,CAACC,KAAgB,EAI1C;EACA,MAAMC,MAAsB,GAAG;IAC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0B,KAAK,CAACW,WAAW,IAAI;MAAE/B,KAAK,EAAE;IAAK,CAAC;EAC1C,CAAC;EACD,OAAO;IACLE,SAAS,EAAEkB,KAAK,CAAC1B,IAAI,GACjBc,gCAAgC,CAACY,KAAK,CAAC1B,IAAI,CAAC,IAAI,MAAM,GACtD,MAAM;IACVS,WAAW,EAAEiB,KAAK,CAACY,IAAI;IACvBlC;EACF,CAAC;AACH","ignoreList":[]}
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
 
3
3
  exports.__esModule = true;
4
- exports.TYPE_MAJORITY = void 0;
4
+ exports.TYPE_MAJORITY = exports.NEW_FIELD_SAMPLE_SIZE = void 0;
5
5
  const TYPE_MAJORITY = exports.TYPE_MAJORITY = 2 / 3;
6
+ const NEW_FIELD_SAMPLE_SIZE = exports.NEW_FIELD_SAMPLE_SIZE = 6;
6
7
  //# sourceMappingURL=importSampling.js.map
@@ -1 +1 @@
1
- {"version":3,"names":["TYPE_MAJORITY","exports"],"sources":["../../../../src/state/ImportState/importSampling.ts"],"sourcesContent":["export const TYPE_MAJORITY = 2 / 3;\n"],"mappings":";;;;AAAO,MAAMA,aAAa,GAAAC,OAAA,CAAAD,aAAA,GAAG,CAAC,GAAG,CAAC","ignoreList":[]}
1
+ {"version":3,"names":["TYPE_MAJORITY","exports","NEW_FIELD_SAMPLE_SIZE"],"sources":["../../../../src/state/ImportState/importSampling.ts"],"sourcesContent":["export const TYPE_MAJORITY = 2 / 3;\nexport const NEW_FIELD_SAMPLE_SIZE = 6;\n"],"mappings":";;;;AAAO,MAAMA,aAAa,GAAAC,OAAA,CAAAD,aAAA,GAAG,CAAC,GAAG,CAAC;AAC3B,MAAME,qBAAqB,GAAAD,OAAA,CAAAC,qBAAA,GAAG,CAAC","ignoreList":[]}
@@ -40,6 +40,7 @@ function createInMemorySchemaSource(config) {
40
40
  displayField = ((_config$fields$ = config.fields[0]) == null ? void 0 : _config$fields$.id) ?? idField,
41
41
  schemaPermissions = ALL_PERMISSIONS,
42
42
  itemPermissions,
43
+ omitBackendMethods = [],
43
44
  fieldModal,
44
45
  fieldTypes,
45
46
  supportsPii = false,
@@ -133,6 +134,9 @@ function createInMemorySchemaSource(config) {
133
134
  };
134
135
  }
135
136
  };
137
+ omitBackendMethods.forEach(method => {
138
+ Reflect.deleteProperty(collectionBackend, method);
139
+ });
136
140
  const fieldActions = {
137
141
  addField: async field => {
138
142
  fields[field.id] = field;
@@ -1 +1 @@
1
- {"version":3,"names":["_SchemaSource","require","_InMemoryBackend","ALL_PERMISSIONS","createField","updateField","deleteField","DEFAULT_FIELD_TYPE_OPTIONS","patternsType","createInMemorySchemaSource","config","_config$fields$","collectionId","idField","displayField","fields","id","schemaPermissions","itemPermissions","fieldModal","fieldTypes","supportsPii","references","getReferencedCollectionSource","getFieldValue","setFieldValue","forEach","field","schema","keyOf","item","String","fieldsSnapshot","seed","items","backend","InMemoryBackend","paginationMode","total","length","createOne","index","itemKey","collectionBackend","find","query","offset","fetchDataSync","hasNext","get","entityId","Error","create","entity","created","map","set","update","delete","bulkDelete","entityIds","bulkInsert","entities","succeeded","failed","fieldActions","addField","addFields","newFields","editField","fieldId","updates","current","Reflect","deleteProperty","renameField","newName","displayName","makePrimary","Object","entries","isPrimary","loadSchema","source","defineSchemaSource","types"],"sources":["../../../src/testkit/createInMemorySchemaSource.ts"],"sourcesContent":["import {\n defineSchemaSource,\n type FieldModalInput,\n type FieldTypeOption,\n type SchemaSource,\n type SchemaSourceInput,\n} from '../types/SchemaSource';\nimport type {\n CollectionBackend,\n FieldActions,\n ItemPermissions,\n LoadedSchema,\n Schema,\n SchemaPermissions,\n} from '../types/Schema';\nimport type { Field } from '../types/Field';\nimport type { FieldTypeDefinition } from '../types/FieldTypeDefinition';\nimport type { OffsetQuery } from '../hooks/paginationModeConfig';\nimport { InMemoryBackend } from '../InMemoryBackend';\n\nconst ALL_PERMISSIONS: SchemaPermissions = {\n createField: true,\n updateField: true,\n deleteField: true,\n};\n\n// The types the add/edit modal offers by default (the ones @wix/data can create).\nconst DEFAULT_FIELD_TYPE_OPTIONS: FieldTypeOption[] = [\n { patternsType: 'SHORT_TEXT' },\n { patternsType: 'NUMBER' },\n { patternsType: 'BOOLEAN' },\n { patternsType: 'DATE' },\n];\n\nexport interface InMemorySchemaSource<T> {\n /** The source to pass anywhere a schema source is accepted. */\n source: SchemaSource<T>;\n /** The in-memory backend holding the rows — read or mutate them directly. */\n backend: InMemoryBackend<T>;\n}\n\nexport interface InMemorySchemaSourceConfig<T> {\n collectionId: string;\n /** The collection's fields (keyed internally by `field.id`). */\n fields: Field[];\n /** Seed rows the backend serves via `find`/`get`. */\n items?: T[];\n /** Defaults to the first field's id, else `idField`. */\n displayField?: string;\n /** Defaults to `_id`. */\n idField?: string;\n /** Defaults to all-true (add/edit/delete allowed). */\n schemaPermissions?: SchemaPermissions;\n itemPermissions?: ItemPermissions;\n /** What the add/edit field modal shows. `types` defaults to\n * text/number/boolean/date. */\n fieldModal?: FieldModalInput;\n /** Consumer-defined field types, resolved by fields with `type: 'CUSTOM'`. */\n fieldTypes?: FieldTypeDefinition[];\n supportsPii?: boolean;\n /** Sources for referenced collections, keyed by referenced collection id. */\n references?: Record<string, SchemaSource<any>>;\n getReferencedCollectionSource?: (\n collectionId: string,\n ) => SchemaSource<any> | undefined;\n /** How a field's value is read from an item. Default: `item[field.id]`. */\n getFieldValue?: SchemaSourceInput<T>['getFieldValue'];\n /** How a field's value is written back. Default: `{ ...item, [field.id]: value }`. */\n setFieldValue?: SchemaSourceInput<T>['setFieldValue'];\n}\n\n/**\n * Builds a real `SchemaSource<T>` backed by in-memory state — no data source (no\n * `@wix/data`, no network). Its backend `find` serves the seeded `items`, and\n * its `fieldActions` mutate the in-memory schema and return the updated fields\n * map, so the create-new-field import flow works end to end (the created column\n * surfaces via the schema-source merge).\n *\n * Returns `{ source, backend }`. Pass `source` anywhere a `SchemaSource` is\n * accepted — a `@wix/patterns/schema` collection hook, or `<Table\n * fieldsSource={...} />` (which the import reads from). Use `backend` to read or\n * assert on the in-memory rows directly.\n */\nexport function createInMemorySchemaSource<\n T extends Record<string, unknown> = Record<string, unknown>,\n>(config: InMemorySchemaSourceConfig<T>): InMemorySchemaSource<T> {\n const {\n collectionId,\n idField = '_id',\n displayField = config.fields[0]?.id ?? idField,\n schemaPermissions = ALL_PERMISSIONS,\n itemPermissions,\n fieldModal,\n fieldTypes,\n supportsPii = false,\n references,\n getReferencedCollectionSource,\n getFieldValue,\n setFieldValue,\n } = config;\n\n // Mutable in-memory state shared by the backend, schema, and field actions.\n const fields: Schema['fields'] = {};\n config.fields.forEach((field) => {\n fields[field.id] = field;\n });\n\n const schema: Schema = {\n id: collectionId,\n fields,\n displayField,\n idField,\n schemaPermissions,\n ...(itemPermissions && { itemPermissions }),\n };\n\n const keyOf = (item: T): string =>\n String((item as Record<string, unknown>)[idField] ?? '');\n // A fresh copy each mutation, so the schema-source merge sees a new map.\n const fieldsSnapshot = (): Schema['fields'] => ({ ...fields });\n\n // The shared `InMemoryBackend` holds the rows and runs the query logic\n // (ordering, filtering, pagination). The `collectionBackend` below adapts it\n // to the source-neutral contract. Mutations write straight to `backend.map`\n // and reads use the synchronous surface, so operations resolve without the\n // util's simulated async delay (which relies on timers the test suite freezes).\n const seed = config.items ?? [];\n const backend = new InMemoryBackend<T>({\n paginationMode: 'offset',\n total: seed.length,\n createOne: (index) => seed[index],\n itemKey: keyOf,\n });\n\n const collectionBackend: CollectionBackend<T> = {\n paginationMode: 'offset',\n find: async (query: OffsetQuery) => {\n const offset = query.offset ?? 0;\n const { items, total = 0 } = backend.fetchDataSync(query);\n return { items, total, hasNext: offset + items.length < total };\n },\n get: async (entityId) => {\n const item = backend.get(entityId);\n if (!item) {\n throw new Error(`Item \"${entityId}\" not found`);\n }\n return item;\n },\n create: async (entity) => {\n const created = { ...entity } as T;\n backend.map.set(keyOf(created), created);\n return created;\n },\n update: async (entity) => {\n backend.map.set(keyOf(entity), entity);\n return entity;\n },\n delete: async (entityId) => {\n backend.map.delete(entityId);\n },\n bulkDelete: async (entityIds) => {\n entityIds.forEach((entityId) => backend.map.delete(entityId));\n },\n bulkInsert: async (entities) => {\n entities.forEach((entity) => {\n const created = { ...entity } as T;\n backend.map.set(keyOf(created), created);\n });\n return { succeeded: entities.length, failed: 0 };\n },\n };\n\n const fieldActions: FieldActions = {\n addField: async (field) => {\n fields[field.id] = field;\n return fieldsSnapshot();\n },\n addFields: async (newFields) => {\n newFields.forEach((field) => {\n fields[field.id] = field;\n });\n return fieldsSnapshot();\n },\n editField: async (fieldId, updates) => {\n const current = fields[fieldId];\n if (current) {\n fields[fieldId] = { ...current, ...updates } as Field;\n }\n return fieldsSnapshot();\n },\n deleteField: async (fieldId) => {\n Reflect.deleteProperty(fields, fieldId);\n return fieldsSnapshot();\n },\n renameField: async (fieldId, newName) => {\n const current = fields[fieldId];\n if (current) {\n fields[fieldId] = { ...current, displayName: newName } as Field;\n }\n },\n makePrimary: async (fieldId) => {\n schema.displayField = fieldId;\n Object.entries(fields).forEach(([id, field]) => {\n if (field) {\n fields[id] = { ...field, isPrimary: id === fieldId } as Field;\n }\n });\n return fieldsSnapshot();\n },\n };\n\n const loadSchema = async (): Promise<LoadedSchema<T>> => ({\n schema,\n backend: collectionBackend,\n fieldActions,\n });\n\n const source = defineSchemaSource<T>({\n collectionId,\n loadSchema,\n fieldModal: {\n ...fieldModal,\n types: fieldModal?.types ?? DEFAULT_FIELD_TYPE_OPTIONS,\n },\n fieldTypes,\n supportsPii,\n ...(references && { references }),\n ...(getReferencedCollectionSource && { getReferencedCollectionSource }),\n ...(getFieldValue && { getFieldValue }),\n ...(setFieldValue && { setFieldValue }),\n });\n\n return { source, backend };\n}\n"],"mappings":";;;;AAAA,IAAAA,aAAA,GAAAC,OAAA;AAkBA,IAAAC,gBAAA,GAAAD,OAAA;AAEA,MAAME,eAAkC,GAAG;EACzCC,WAAW,EAAE,IAAI;EACjBC,WAAW,EAAE,IAAI;EACjBC,WAAW,EAAE;AACf,CAAC;;AAED;A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aAAa,IAAI;MAAEA;IAAc,CAAC,CAAC;IACvC,IAAIC,aAAa,IAAI;MAAEA;IAAc,CAAC;EACxC,CAAC,CAAC;EAEF,OAAO;IAAE0D,MAAM;IAAEhD;EAAQ,CAAC;AAC5B","ignoreList":[]}
1
+ {"version":3,"names":["_SchemaSource","require","_InMemoryBackend","ALL_PERMISSIONS","createField","updateField","deleteField","DEFAULT_FIELD_TYPE_OPTIONS","patternsType","createInMemorySchemaSource","config","_config$fields$","collectionId","idField","displayField","fields","id","schemaPermissions","itemPermissions","omitBackendMethods","fieldModal","fieldTypes","supportsPii","references","getReferencedCollectionSource","getFieldValue","setFieldValue","forEach","field","schema","keyOf","item","String","fieldsSnapshot","seed","items","backend","InMemoryBackend","paginationMode","total","length","createOne","index","itemKey","collectionBackend","find","query","offset","fetchDataSync","hasNext","get","entityId","Error","create","entity","created","map","set","update","delete","bulkDelete","entityIds","bulkInsert","entities","succeeded","failed","method","Reflect","deleteProperty","fieldActions","addField","addFields","newFields","editField","fieldId","updates","current","renameField","newName","displayName","makePrimary","Object","entries","isPrimary","loadSchema","source","defineSchemaSource","types"],"sources":["../../../src/testkit/createInMemorySchemaSource.ts"],"sourcesContent":["import {\n defineSchemaSource,\n type FieldModalInput,\n type FieldTypeOption,\n type SchemaSource,\n type SchemaSourceInput,\n} from '../types/SchemaSource';\nimport type {\n CollectionBackend,\n FieldActions,\n ItemPermissions,\n LoadedSchema,\n Schema,\n SchemaPermissions,\n} from '../types/Schema';\nimport type { Field } from '../types/Field';\nimport type { FieldTypeDefinition } from '../types/FieldTypeDefinition';\nimport type { OffsetQuery } from '../hooks/paginationModeConfig';\nimport { InMemoryBackend } from '../InMemoryBackend';\n\nconst ALL_PERMISSIONS: SchemaPermissions = {\n createField: true,\n updateField: true,\n deleteField: true,\n};\n\n// The types the add/edit modal offers by default (the ones @wix/data can create).\nconst DEFAULT_FIELD_TYPE_OPTIONS: FieldTypeOption[] = [\n { patternsType: 'SHORT_TEXT' },\n { patternsType: 'NUMBER' },\n { patternsType: 'BOOLEAN' },\n { patternsType: 'DATE' },\n];\n\nexport interface InMemorySchemaSource<T> {\n /** The source to pass anywhere a schema source is accepted. */\n source: SchemaSource<T>;\n /** The in-memory backend holding the rows — read or mutate them directly. */\n backend: InMemoryBackend<T>;\n}\n\nexport interface InMemorySchemaSourceConfig<T> {\n collectionId: string;\n /** The collection's fields (keyed internally by `field.id`). */\n fields: Field[];\n /** Seed rows the backend serves via `find`/`get`. */\n items?: T[];\n /** Defaults to the first field's id, else `idField`. */\n displayField?: string;\n /** Defaults to `_id`. */\n idField?: string;\n /** Defaults to all-true (add/edit/delete allowed). */\n schemaPermissions?: SchemaPermissions;\n itemPermissions?: ItemPermissions;\n /** Backend write methods to leave out, as a read-only or partial source does. */\n omitBackendMethods?: (\n | 'create'\n | 'update'\n | 'delete'\n | 'bulkDelete'\n | 'bulkInsert'\n )[];\n /** What the add/edit field modal shows. `types` defaults to\n * text/number/boolean/date. */\n fieldModal?: FieldModalInput;\n /** Consumer-defined field types, resolved by fields with `type: 'CUSTOM'`. */\n fieldTypes?: FieldTypeDefinition[];\n supportsPii?: boolean;\n /** Sources for referenced collections, keyed by referenced collection id. */\n references?: Record<string, SchemaSource<any>>;\n getReferencedCollectionSource?: (\n collectionId: string,\n ) => SchemaSource<any> | undefined;\n /** How a field's value is read from an item. Default: `item[field.id]`. */\n getFieldValue?: SchemaSourceInput<T>['getFieldValue'];\n /** How a field's value is written back. Default: `{ ...item, [field.id]: value }`. */\n setFieldValue?: SchemaSourceInput<T>['setFieldValue'];\n}\n\n/**\n * Builds a real `SchemaSource<T>` backed by in-memory state — no data source (no\n * `@wix/data`, no network). Its backend `find` serves the seeded `items`, and\n * its `fieldActions` mutate the in-memory schema and return the updated fields\n * map, so the create-new-field import flow works end to end (the created column\n * surfaces via the schema-source merge).\n *\n * Returns `{ source, backend }`. Pass `source` anywhere a `SchemaSource` is\n * accepted — a `@wix/patterns/schema` collection hook, or `<Table\n * fieldsSource={...} />` (which the import reads from). Use `backend` to read or\n * assert on the in-memory rows directly.\n */\nexport function createInMemorySchemaSource<\n T extends Record<string, unknown> = Record<string, unknown>,\n>(config: InMemorySchemaSourceConfig<T>): InMemorySchemaSource<T> {\n const {\n collectionId,\n idField = '_id',\n displayField = config.fields[0]?.id ?? idField,\n schemaPermissions = ALL_PERMISSIONS,\n itemPermissions,\n omitBackendMethods = [],\n fieldModal,\n fieldTypes,\n supportsPii = false,\n references,\n getReferencedCollectionSource,\n getFieldValue,\n setFieldValue,\n } = config;\n\n // Mutable in-memory state shared by the backend, schema, and field actions.\n const fields: Schema['fields'] = {};\n config.fields.forEach((field) => {\n fields[field.id] = field;\n });\n\n const schema: Schema = {\n id: collectionId,\n fields,\n displayField,\n idField,\n schemaPermissions,\n ...(itemPermissions && { itemPermissions }),\n };\n\n const keyOf = (item: T): string =>\n String((item as Record<string, unknown>)[idField] ?? '');\n // A fresh copy each mutation, so the schema-source merge sees a new map.\n const fieldsSnapshot = (): Schema['fields'] => ({ ...fields });\n\n // The shared `InMemoryBackend` holds the rows and runs the query logic\n // (ordering, filtering, pagination). The `collectionBackend` below adapts it\n // to the source-neutral contract. Mutations write straight to `backend.map`\n // and reads use the synchronous surface, so operations resolve without the\n // util's simulated async delay (which relies on timers the test suite freezes).\n const seed = config.items ?? [];\n const backend = new InMemoryBackend<T>({\n paginationMode: 'offset',\n total: seed.length,\n createOne: (index) => seed[index],\n itemKey: keyOf,\n });\n\n const collectionBackend: CollectionBackend<T> = {\n paginationMode: 'offset',\n find: async (query: OffsetQuery) => {\n const offset = query.offset ?? 0;\n const { items, total = 0 } = backend.fetchDataSync(query);\n return { items, total, hasNext: offset + items.length < total };\n },\n get: async (entityId) => {\n const item = backend.get(entityId);\n if (!item) {\n throw new Error(`Item \"${entityId}\" not found`);\n }\n return item;\n },\n create: async (entity) => {\n const created = { ...entity } as T;\n backend.map.set(keyOf(created), created);\n return created;\n },\n update: async (entity) => {\n backend.map.set(keyOf(entity), entity);\n return entity;\n },\n delete: async (entityId) => {\n backend.map.delete(entityId);\n },\n bulkDelete: async (entityIds) => {\n entityIds.forEach((entityId) => backend.map.delete(entityId));\n },\n bulkInsert: async (entities) => {\n entities.forEach((entity) => {\n const created = { ...entity } as T;\n backend.map.set(keyOf(created), created);\n });\n return { succeeded: entities.length, failed: 0 };\n },\n };\n\n omitBackendMethods.forEach((method) => {\n Reflect.deleteProperty(collectionBackend, method);\n });\n\n const fieldActions: FieldActions = {\n addField: async (field) => {\n fields[field.id] = field;\n return fieldsSnapshot();\n },\n addFields: async (newFields) => {\n newFields.forEach((field) => {\n fields[field.id] = field;\n });\n return fieldsSnapshot();\n },\n editField: async (fieldId, updates) => {\n const current = fields[fieldId];\n if (current) {\n fields[fieldId] = { ...current, ...updates } as Field;\n }\n return fieldsSnapshot();\n },\n deleteField: async (fieldId) => {\n Reflect.deleteProperty(fields, fieldId);\n return fieldsSnapshot();\n },\n renameField: async (fieldId, newName) => {\n const current = fields[fieldId];\n if (current) {\n fields[fieldId] = { ...current, displayName: newName } as Field;\n }\n },\n makePrimary: async (fieldId) => {\n schema.displayField = fieldId;\n Object.entries(fields).forEach(([id, field]) => {\n if (field) {\n fields[id] = { ...field, isPrimary: id === fieldId } as Field;\n }\n });\n return fieldsSnapshot();\n },\n };\n\n const loadSchema = async (): Promise<LoadedSchema<T>> => ({\n schema,\n backend: collectionBackend,\n fieldActions,\n });\n\n const source = defineSchemaSource<T>({\n collectionId,\n loadSchema,\n fieldModal: {\n ...fieldModal,\n types: fieldModal?.types ?? DEFAULT_FIELD_TYPE_OPTIONS,\n },\n fieldTypes,\n supportsPii,\n ...(references && { references }),\n ...(getReferencedCollectionSource && { getReferencedCollectionSource }),\n ...(getFieldValue && { getFieldValue }),\n ...(setFieldValue && { setFieldValue }),\n });\n\n return { source, backend };\n}\n"],"mappings":";;;;AAAA,IAAAA,aAAA,GAAAC,OAAA;AAkBA,IAAAC,gBAAA,GAAAD,OAAA;AAEA,MAAME,eAAkC,GAAG;EACz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;MACV,GAAGA,UAAU;MACbmE,KAAK,EAAE,CAAAnE,UAAU,oBAAVA,UAAU,CAAEmE,KAAK,KAAIhF;IAC9B,CAAC;IACDc,UAAU;IACVC,WAAW;IACX,IAAIC,UAAU,IAAI;MAAEA;IAAW,CAAC,CAAC;IACjC,IAAIC,6BAA6B,IAAI;MAAEA;IAA8B,CAAC,CAAC;IACvE,IAAIC,aAAa,IAAI;MAAEA;IAAc,CAAC,CAAC;IACvC,IAAIC,aAAa,IAAI;MAAEA;IAAc,CAAC;EACxC,CAAC,CAAC;EAEF,OAAO;IAAE2D,MAAM;IAAEjD;EAAQ,CAAC;AAC5B","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"names":["isFilterTypeConfig","filter","defineFieldType","definition","resolveFieldTypeDefinition","source","field","_source$fieldTypes","type","customType","undefined","fieldTypes","find","def"],"sources":["../../../src/types/FieldTypeDefinition.ts"],"sourcesContent":["import type {\n ComponentType,\n MutableRefObject,\n ReactElement,\n ReactNode,\n} from 'react';\nimport type { Field } from './Field';\nimport type { Filter } from '../model/filter';\nimport type {\n FieldModalCollectionInput,\n FieldPiiWarning,\n FieldSettingsSection,\n FieldsSource,\n} from './FieldsSource';\n\nexport type ValidationRule =\n | { type: 'required'; message: string }\n | { type: 'min' | 'max'; value: number; message: string }\n | { type: 'minLength' | 'maxLength'; value: number; message: string }\n | { type: 'pattern'; value: RegExp; message: string }\n | { type: 'custom'; validate: (value: unknown) => boolean; message: string }\n | {\n type: 'specificValues';\n values: { id: string; value: string }[];\n message: string;\n };\n\nexport interface Focusable {\n focus: () => void;\n}\n\nexport type EditTrigger =\n | { kind: 'type'; key: string }\n | 'enter'\n | 'click'\n | 'doubleClick';\n\nexport interface CellViewProps<V> {\n value: V;\n typeConfig?: unknown;\n validation?: ValidationRule[];\n /** Stable id of the column. Cell components can use it to derive unique DOM ids. */\n columnId: string;\n /** Stable key of the row. Cell components can use it to derive unique DOM ids. */\n rowKey: string;\n /** Whether the cell is editable. Used to conditionally render placeholders (don't show them for read-only cells). */\n isEditable?: boolean;\n /** Whether this is the focused cell, excluding a multi-cell selection. */\n isFocused?: boolean;\n}\n\nexport interface CellEditProps<V> {\n value: V;\n // Method syntax keeps CellEditProps covariant in V (see FieldTypeDefinition).\n onChange(value: V): void;\n onCommit: () => void;\n onCancel: () => void;\n /**\n * Signals that the cell is starting an editing operation that will move focus\n * outside the table (e.g., opening a media manager or a modal). Calling this\n * sets isEditing=true so the table does not clear cell focus while the\n * external UI is open. Pair with onCommit (after the operation succeeds)\n * or onCancel (if the user dismisses without a value change).\n */\n onStartEdit?: () => void;\n /** Ref to the focusable input element. Used for type-to-edit (focusing the input when user starts typing on a focused cell). */\n inputRef?: MutableRefObject<Focusable | undefined | null>;\n typeConfig?: unknown;\n /** How edit mode was triggered. Edit components can use this to customize behavior (e.g., date picker auto-opens on 'type'). */\n editTrigger?: EditTrigger | null;\n /** Column-level validation rules. Edit components can derive UI behavior (e.g., maxLength blocking/tooltip) from these. */\n validation?: ValidationRule[];\n /** Stable id of the column. Cell components can use it to derive unique DOM ids. */\n columnId: string;\n /** Stable key of the row. Cell components can use it to derive unique DOM ids. */\n rowKey: string;\n}\n\n/**\n * Props passed to a cell type's optional `EditWrapper`. The table mounts the\n * wrapper around the cell content and keeps it mounted across the edit↔view\n * transition, so the wrapper can own behavior that must outlive the inline\n * editor (e.g. a reference cell navigating to an overlay and refreshing on\n * return). The wrapper hands anything the editor needs down via its own context.\n */\nexport interface CellEditWrapperProps {\n /** The column's typeConfig (same value handed to the cell's Edit/View). */\n typeConfig?: unknown;\n /** Stable id of the column. */\n columnId: string;\n /** Stable key of the row. */\n rowKey: string;\n /** The cell content (the Edit or View component) to render inside the wrapper. */\n children: ReactNode;\n}\n\nexport type EditableCellContextMenuAction = 'copy' | 'cut' | 'paste' | 'clear';\n\nexport interface EditableCellContextMenuActionContext<V> {\n /** Current cell value, including pending or draft edits. */\n value: V;\n /** Field metadata associated with the column, when available. */\n field?: Field;\n /** Stable key of the row. */\n rowKey: string;\n /** Stable id of the column. */\n columnId: string;\n}\n\nexport interface EditableCellContextMenuActionConfig<V> {\n /** Returning a non-empty string disables the action and shows the tooltip. */\n disabledTooltip(\n context: EditableCellContextMenuActionContext<V>,\n ): string | undefined;\n}\n\n/**\n * The editable-cell slot of a field type definition: how a cell of that type\n * renders, edits, and moves through the clipboard. The definition's key\n * identifies the type and the definition's `value` owns validation, so the\n * slot carries neither.\n *\n * Members that take `V` use method syntax so a definition typed with a\n * concrete value type stays assignable where a loosely typed definition is\n * expected (see `FieldTypeDefinition`).\n */\nexport interface EditableCellConfig<V> {\n /** Render cell in view mode (read-only display). */\n ViewComponent(props: CellViewProps<V>): ReactElement | null;\n /** Render cell in edit mode (inline editor). Optional — omit for view-only cells. */\n EditComponent?(props: CellEditProps<V>): ReactElement | null;\n /** Serialize value to clipboard string. */\n serialize?(value: V): string;\n /** Deserialize clipboard string to value. */\n deserialize?(raw: string): V;\n /** Can this cell type be edited? (default: true) */\n editable?: boolean;\n /** Availability of Cairo's built-in cell context-menu actions. */\n contextMenu?: Partial<\n Record<\n EditableCellContextMenuAction,\n EditableCellContextMenuActionConfig<V>\n >\n >;\n /** Toggle value on single click (e.g., boolean checkbox). Skips focus→edit flow. */\n toggleValue?(value: V): V;\n /** Enter edit mode on single click (e.g., image cell with no value). */\n editOnClick?(value: V): boolean;\n /** Show the EditComponent when the cell is focused, without entering edit mode.\n * Keyboard navigation remains active. Similar to toggleValue but without toggling. */\n showEditWhenFocused?: boolean;\n /** Optional wrapper component the cell type defines to own behavior that must\n * outlive the inline editor. Mounted around the cell content and kept mounted\n * across the edit↔view transition. */\n EditWrapper?: ComponentType<CellEditWrapperProps>;\n /** Cell content can grow past row height when focused, including read-only views. */\n growable?: boolean;\n /** Called on type-to-edit. Return object with cleared value and/or prevent flag.\n * Return undefined to block the key. Return {} to enter edit mode without changing the value. */\n onTypeToEdit?(params: {\n key: string;\n validation?: ValidationRule[];\n }): { value?: V } | undefined;\n /** Optional hook to normalize the committed value (e.g. auto-prepend https://).\n * Called before the edit commits; the value is written back before committing. */\n normalizeOnCommit?(value: V): V;\n /** When true, type-to-edit flushes the edit-mode render synchronously and\n * focuses the input within the same keydown event, then lets the browser's\n * default action deliver the keystroke to the now-focused input naturally.\n * Use for cells that wrap a controlled input whose value can't be seeded via props. */\n nativeTypeToEdit?: boolean;\n}\n\n/** The props the filter builder passes to a definition's toolbar filter\n * component — the same contract the built-in filter elements receive. */\nexport interface FilterTypeComponentProps<V = any> {\n filter: Filter<V>;\n toolbarItemProps?: { label?: ReactNode };\n toolbarTagProps?: { label?: string };\n accordionItemProps?: { label?: string };\n}\n\n/** The filter slot of a field type definition: the filter state registered on\n * the collection query and the toolbar element that renders it. */\nexport interface FilterTypeConfig {\n createFilter: (field: Field) => Filter<any>;\n Component: ComponentType<FilterTypeComponentProps>;\n}\n\n/** Narrows a definition's filter slot to an active filter config. */\nexport function isFilterTypeConfig(\n filter: FieldTypeDefinition['filter'],\n): filter is FilterTypeConfig {\n return 'createFilter' in filter;\n}\n\n/**\n * The read-only table slot of a field type definition: how a cell of that\n * type renders in the table, and the column's layout. Independent of\n * `editableTable` — neither slot falls back to the other.\n */\n/** What a read-only table cell is told about itself. */\nexport interface TableCellProps<V> {\n value: V;\n /** Stable id of the column. Cell components can use it to derive unique DOM ids. */\n columnId: string;\n /** The row this cell belongs to, so a cell can act on its item and not just\n * display it. Typed loosely for the same reason as `FieldsSource.getCellValue`:\n * the row shape belongs to the source, not to Cairo. */\n row: unknown;\n}\n\nexport interface TableCellConfig<V> {\n /** Render the cell. Method syntax keeps the definition assignable to\n * `FieldTypeDefinition<unknown>` (see FieldTypeDefinition). */\n CellComponent(props: TableCellProps<V>): ReactElement | null;\n /** Column width. Required — custom types get no built-in layout default. */\n width: string;\n /** Default: 'start'. */\n align?: 'start' | 'center' | 'end';\n}\n\n/** An extra menu item a field type definition adds to a field's actions menu. */\nexport interface FieldTypeActionItem {\n key: string;\n label: string;\n icon?: ReactNode;\n skin?: 'destructive';\n onClick: (field: Field) => void;\n /** Default: visible. */\n visible?: (field: Field) => boolean;\n /** Returning a string disables the item and shows the tooltip. */\n disabledTooltip?: (field: Field) => string | undefined;\n}\n\n/** The actions slot of a field type definition: extra items for the field's \"more actions\" menu. */\nexport interface FieldActionsConfig {\n items?: FieldTypeActionItem[];\n}\n\n/** Display metadata for a field type: menu label and type icons. */\nexport interface FieldTypeDisplay {\n label: string;\n icons: {\n Small: ComponentType;\n Medium: ComponentType;\n };\n}\n\n/** Value semantics of a field type, independent of any rendering surface.\n * Members use method syntax so a definition typed with a concrete value type\n * stays assignable where a loosely typed definition is expected. */\nexport interface FieldValueBehavior<V> {\n defaultValue?: V;\n isEmpty?(value: V): boolean;\n /** Returns an error message, or null when the value is valid. Every surface\n * that validates a field of this type runs this. */\n validate?(value: V, rules?: ValidationRule[]): string | null;\n}\n\nexport interface FieldCapabilities {\n sortable: boolean;\n}\n\n/** The field-modal slot of a field type definition: opts the type into the\n * add/edit-field modal's type picker and describes its entry there. */\nexport interface FieldModalConfig {\n /** True ⇒ the add-field modal offers this type. */\n creatable: boolean;\n /** Placeholder for the name input. Absent ⇒ the modal's generic placeholder. */\n namePlaceholder?: string;\n /** Fallback field ID base when the name cannot produce a valid ID.\n * Default: the normalized type ID. Numeric suffixes resolve collisions. */\n keyBase?: string;\n /** One-line description under the type in the picker. */\n subtitle?: string;\n /** Group heading this type is listed under in the picker. */\n group?: string;\n /** Whether a field of this type can be marked PII. Absent ⇒ follows the\n * source-wide setting. */\n supportsPii?: boolean;\n /** Warning shown while the PII toggle is on. Read on every render, so it can\n * use data that only exists once the schema has loaded. Default: none. */\n piiWarning?: () => FieldPiiWarning | undefined;\n /** This type's collapsible settings section — the same contract a\n * source-declared type option carries (see `FieldSettingsSection`). */\n settingsSection?: FieldSettingsSection;\n /** Collection picker shown in the main add/edit field form. */\n collectionInput?: FieldModalCollectionInput;\n}\n\n/**\n * Props the entity-page form dispatcher passes to a field type's form\n * component. The dispatcher owns the form wiring (registration, validation\n * from the definition's `value.validate`) and the field UI (label, required\n * marker, error message); the component renders the input: read `value`,\n * report edits through `onChange`, and hand back the focusable control\n * through `inputRef` so a blocked save can reach it.\n */\nexport interface FormFieldComponentProps<V> {\n field: Field;\n value: V;\n // Method syntax keeps FormFieldComponentProps covariant in V (see FieldTypeDefinition).\n onChange(value: V): void;\n /** Call when the input loses focus — marks the field touched, so error\n * timing matches the built-in renderers. */\n onBlur: () => void;\n /** Ref to the focusable input element. Used to focus the field when a\n * blocked save reports an error on it. Absent ⇒ the entity page brings the\n * field into view and focuses the first control it finds inside. */\n inputRef?: MutableRefObject<Focusable | undefined | null>;\n dataHook?: string;\n}\n\n/** The entity-page form slot of a field type definition. */\nexport interface FormTypeConfig<V = unknown> {\n /** Renders the input. Method syntax keeps the definition assignable to\n * `FieldTypeDefinition<unknown>` (see FieldTypeDefinition). */\n Component(props: FormFieldComponentProps<V>): ReactElement | null;\n}\n\n/**\n * A consumer-defined field type. Defined once on the fields source; every\n * entry point that renders the field resolves its slot from here. `V` is the\n * field's value type — `defineFieldType` infers it, and it keeps all the\n * slots consistent with each other.\n *\n * Sources hold definitions of mixed value types in one\n * `FieldTypeDefinition[]` (= `FieldTypeDefinition<unknown>[]`) array. That\n * works because every member that takes `V` is declared with method syntax,\n * which TypeScript checks bivariantly — so `FieldTypeDefinition<number>` is\n * assignable to `FieldTypeDefinition<unknown>` without casts.\n */\nexport interface FieldTypeDefinition<V = unknown> {\n /** Unique key for the type. A built-in type uses its `PatternsFieldType`; a\n * consumer-defined type uses the string its fields reference via `customType`. */\n type: string;\n display: FieldTypeDisplay;\n /** Filter behavior, or an explicit opt-out — never silently absent. */\n filter: FilterTypeConfig | { filterable: false };\n value?: FieldValueBehavior<V>;\n capabilities?: FieldCapabilities;\n /** Absent ⇒ the field renders with the default cell in the read-only table. */\n table?: TableCellConfig<V>;\n /** Absent ⇒ the field renders as a read-only cell in editable surfaces. */\n editableTable?: EditableCellConfig<V>;\n /** Required once a field of this type renders on an entity page:\n * development throws without it; production skips the field. */\n form?: FormTypeConfig<V>;\n /** Extra items for the field's \"more actions\" menu. */\n actions?: FieldActionsConfig;\n /** Absent ⇒ the add/edit field modal never offers this type. Fields of the\n * type created elsewhere still open in the modal for name/PII edits. */\n fieldModal?: FieldModalConfig;\n}\n\n/** Identity factory: infers `V` and keeps the definition's slots type-checked. */\nexport function defineFieldType<V>(\n definition: FieldTypeDefinition<V>,\n): FieldTypeDefinition<V> {\n return definition;\n}\n\n/** Resolves the definition a CUSTOM field references on its source. */\nexport function resolveFieldTypeDefinition(\n source: Pick<FieldsSource, 'fieldTypes'>,\n field: Field,\n) {\n if (field.type !== 'CUSTOM' || !field.customType) {\n return undefined;\n }\n return source.fieldTypes?.find((def) => def.type === field.customType);\n}\n"],"mappings":";;;;;;AA8EA;AACA;AACA;AACA;AACA;AACA;AACA;;AAgCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAgDA;AACA;;AAQA;AACA;;AAMA;AACO,SAASA,kBAAkBA,CAChCC,MAAqC,EACT;EAC5B,OAAO,cAAc,IAAIA,MAAM;AACjC;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAqBA;;AAaA;;AAKA;;AASA;AACA;AACA;;AAaA;AACA;;AA0BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAgBA;;AAOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAwBA;AACO,SAASC,eAAeA,CAC7BC,UAAkC,EACV;EACxB,OAAOA,UAAU;AACnB;;AAEA;AACO,SAASC,0BAA0BA,CACxCC,MAAwC,EACxCC,KAAY,EACZ;EAAA,IAAAC,kBAAA;EACA,IAAID,KAAK,CAACE,IAAI,KAAK,QAAQ,IAAI,CAACF,KAAK,CAACG,UAAU,EAAE;IAChD,OAAOC,SAAS;EAClB;EACA,QAAAH,kBAAA,GAAOF,MAAM,CAACM,UAAU,qBAAjBJ,kBAAA,CAAmBK,IAAI,CAAEC,GAAG,IAAKA,GAAG,CAACL,IAAI,KAAKF,KAAK,CAACG,UAAU,CAAC;AACxE","ignoreList":[]}
1
+ {"version":3,"names":["isFilterTypeConfig","filter","defineFieldType","definition","resolveFieldTypeDefinition","source","field","_source$fieldTypes","type","customType","undefined","fieldTypes","find","def"],"sources":["../../../src/types/FieldTypeDefinition.ts"],"sourcesContent":["import type {\n ComponentType,\n MutableRefObject,\n ReactElement,\n ReactNode,\n} from 'react';\nimport type { Field } from './Field';\nimport type { Filter } from '../model/filter';\nimport type {\n FieldModalCollectionInput,\n FieldPiiWarning,\n FieldSettingsSection,\n FieldsSource,\n LockableFieldProperty,\n} from './FieldsSource';\n\nexport type ValidationRule =\n | { type: 'required'; message: string }\n | { type: 'min' | 'max'; value: number; message: string }\n | { type: 'minLength' | 'maxLength'; value: number; message: string }\n | { type: 'pattern'; value: RegExp; message: string }\n | { type: 'custom'; validate: (value: unknown) => boolean; message: string }\n | {\n type: 'specificValues';\n values: { id: string; value: string }[];\n message: string;\n };\n\nexport interface Focusable {\n focus: () => void;\n}\n\nexport type EditTrigger =\n | { kind: 'type'; key: string }\n | 'enter'\n | 'click'\n | 'doubleClick';\n\nexport interface CellViewProps<V> {\n value: V;\n typeConfig?: unknown;\n validation?: ValidationRule[];\n /** Stable id of the column. Cell components can use it to derive unique DOM ids. */\n columnId: string;\n /** Stable key of the row. Cell components can use it to derive unique DOM ids. */\n rowKey: string;\n /** Whether the cell is editable. Used to conditionally render placeholders (don't show them for read-only cells). */\n isEditable?: boolean;\n /** Whether this is the focused cell, excluding a multi-cell selection. */\n isFocused?: boolean;\n}\n\nexport interface CellEditProps<V> {\n value: V;\n // Method syntax keeps CellEditProps covariant in V (see FieldTypeDefinition).\n onChange(value: V): void;\n onCommit: () => void;\n onCancel: () => void;\n /**\n * Signals that the cell is starting an editing operation that will move focus\n * outside the table (e.g., opening a media manager or a modal). Calling this\n * sets isEditing=true so the table does not clear cell focus while the\n * external UI is open. Pair with onCommit (after the operation succeeds)\n * or onCancel (if the user dismisses without a value change).\n */\n onStartEdit?: () => void;\n /** Ref to the focusable input element. Used for type-to-edit (focusing the input when user starts typing on a focused cell). */\n inputRef?: MutableRefObject<Focusable | undefined | null>;\n typeConfig?: unknown;\n /** How edit mode was triggered. Edit components can use this to customize behavior (e.g., date picker auto-opens on 'type'). */\n editTrigger?: EditTrigger | null;\n /** Column-level validation rules. Edit components can derive UI behavior (e.g., maxLength blocking/tooltip) from these. */\n validation?: ValidationRule[];\n /** Stable id of the column. Cell components can use it to derive unique DOM ids. */\n columnId: string;\n /** Stable key of the row. Cell components can use it to derive unique DOM ids. */\n rowKey: string;\n}\n\n/**\n * Props passed to a cell type's optional `EditWrapper`. The table mounts the\n * wrapper around the cell content and keeps it mounted across the edit↔view\n * transition, so the wrapper can own behavior that must outlive the inline\n * editor (e.g. a reference cell navigating to an overlay and refreshing on\n * return). The wrapper hands anything the editor needs down via its own context.\n */\nexport interface CellEditWrapperProps {\n /** The column's typeConfig (same value handed to the cell's Edit/View). */\n typeConfig?: unknown;\n /** Stable id of the column. */\n columnId: string;\n /** Stable key of the row. */\n rowKey: string;\n /** The cell content (the Edit or View component) to render inside the wrapper. */\n children: ReactNode;\n}\n\nexport type EditableCellContextMenuAction = 'copy' | 'cut' | 'paste' | 'clear';\n\nexport interface EditableCellContextMenuActionContext<V> {\n /** Current cell value, including pending or draft edits. */\n value: V;\n /** Field metadata associated with the column, when available. */\n field?: Field;\n /** Stable key of the row. */\n rowKey: string;\n /** Stable id of the column. */\n columnId: string;\n}\n\nexport interface EditableCellContextMenuActionConfig<V> {\n /** Returning a non-empty string disables the action and shows the tooltip. */\n disabledTooltip(\n context: EditableCellContextMenuActionContext<V>,\n ): string | undefined;\n}\n\n/**\n * The editable-cell slot of a field type definition: how a cell of that type\n * renders, edits, and moves through the clipboard. The definition's key\n * identifies the type and the definition's `value` owns validation, so the\n * slot carries neither.\n *\n * Members that take `V` use method syntax so a definition typed with a\n * concrete value type stays assignable where a loosely typed definition is\n * expected (see `FieldTypeDefinition`).\n */\nexport interface EditableCellConfig<V> {\n /** Render cell in view mode (read-only display). */\n ViewComponent(props: CellViewProps<V>): ReactElement | null;\n /** Render cell in edit mode (inline editor). Optional — omit for view-only cells. */\n EditComponent?(props: CellEditProps<V>): ReactElement | null;\n /** Serialize value to clipboard string. */\n serialize?(value: V): string;\n /** Deserialize clipboard string to value. */\n deserialize?(raw: string): V;\n /** Can this cell type be edited? (default: true) */\n editable?: boolean;\n /** Availability of Cairo's built-in cell context-menu actions. */\n contextMenu?: Partial<\n Record<\n EditableCellContextMenuAction,\n EditableCellContextMenuActionConfig<V>\n >\n >;\n /** Toggle value on single click (e.g., boolean checkbox). Skips focus→edit flow. */\n toggleValue?(value: V): V;\n /** Enter edit mode on single click (e.g., image cell with no value). */\n editOnClick?(value: V): boolean;\n /** Show the EditComponent when the cell is focused, without entering edit mode.\n * Keyboard navigation remains active. Similar to toggleValue but without toggling. */\n showEditWhenFocused?: boolean;\n /** Optional wrapper component the cell type defines to own behavior that must\n * outlive the inline editor. Mounted around the cell content and kept mounted\n * across the edit↔view transition. */\n EditWrapper?: ComponentType<CellEditWrapperProps>;\n /** Cell content can grow past row height when focused, including read-only views. */\n growable?: boolean;\n /** Called on type-to-edit. Return object with cleared value and/or prevent flag.\n * Return undefined to block the key. Return {} to enter edit mode without changing the value. */\n onTypeToEdit?(params: {\n key: string;\n validation?: ValidationRule[];\n }): { value?: V } | undefined;\n /** Optional hook to normalize the committed value (e.g. auto-prepend https://).\n * Called before the edit commits; the value is written back before committing. */\n normalizeOnCommit?(value: V): V;\n /** When true, type-to-edit flushes the edit-mode render synchronously and\n * focuses the input within the same keydown event, then lets the browser's\n * default action deliver the keystroke to the now-focused input naturally.\n * Use for cells that wrap a controlled input whose value can't be seeded via props. */\n nativeTypeToEdit?: boolean;\n}\n\n/** The props the filter builder passes to a definition's toolbar filter\n * component — the same contract the built-in filter elements receive. */\nexport interface FilterTypeComponentProps<V = any> {\n filter: Filter<V>;\n toolbarItemProps?: { label?: ReactNode };\n toolbarTagProps?: { label?: string };\n accordionItemProps?: { label?: string };\n}\n\n/** The filter slot of a field type definition: the filter state registered on\n * the collection query and the toolbar element that renders it. */\nexport interface FilterTypeConfig {\n createFilter: (field: Field) => Filter<any>;\n Component: ComponentType<FilterTypeComponentProps>;\n}\n\n/** Narrows a definition's filter slot to an active filter config. */\nexport function isFilterTypeConfig(\n filter: FieldTypeDefinition['filter'],\n): filter is FilterTypeConfig {\n return 'createFilter' in filter;\n}\n\n/**\n * The read-only table slot of a field type definition: how a cell of that\n * type renders in the table, and the column's layout. Independent of\n * `editableTable` — neither slot falls back to the other.\n */\n/** What a read-only table cell is told about itself. */\nexport interface TableCellProps<V> {\n value: V;\n /** Stable id of the column. Cell components can use it to derive unique DOM ids. */\n columnId: string;\n /** The row this cell belongs to, so a cell can act on its item and not just\n * display it. Typed loosely for the same reason as `FieldsSource.getCellValue`:\n * the row shape belongs to the source, not to Cairo. */\n row: unknown;\n}\n\nexport interface TableCellConfig<V> {\n /** Render the cell. Method syntax keeps the definition assignable to\n * `FieldTypeDefinition<unknown>` (see FieldTypeDefinition). */\n CellComponent(props: TableCellProps<V>): ReactElement | null;\n /** Column width. Required — custom types get no built-in layout default. */\n width: string;\n /** Default: 'start'. */\n align?: 'start' | 'center' | 'end';\n}\n\n/** An extra menu item a field type definition adds to a field's actions menu. */\nexport interface FieldTypeActionItem {\n key: string;\n label: string;\n icon?: ReactNode;\n skin?: 'destructive';\n onClick: (field: Field) => void;\n /** Default: visible. */\n visible?: (field: Field) => boolean;\n /** Returning a string disables the item and shows the tooltip. */\n disabledTooltip?: (field: Field) => string | undefined;\n}\n\n/** The actions slot of a field type definition: extra items for the field's \"more actions\" menu. */\nexport interface FieldActionsConfig {\n items?: FieldTypeActionItem[];\n}\n\n/** Display metadata for a field type: menu label and type icons. */\nexport interface FieldTypeDisplay {\n label: string;\n icons: {\n Small: ComponentType;\n Medium: ComponentType;\n };\n}\n\n/** Value semantics of a field type, independent of any rendering surface.\n * Members use method syntax so a definition typed with a concrete value type\n * stays assignable where a loosely typed definition is expected. */\nexport interface FieldValueBehavior<V> {\n defaultValue?: V;\n isEmpty?(value: V): boolean;\n /** Returns an error message, or null when the value is valid. Every surface\n * that validates a field of this type runs this. */\n validate?(value: V, rules?: ValidationRule[]): string | null;\n}\n\nexport interface FieldCapabilities {\n sortable: boolean;\n}\n\n/** The field-modal slot of a field type definition: opts the type into the\n * add/edit-field modal's type picker and describes its entry there. */\nexport interface FieldModalConfig {\n /** True ⇒ the add-field modal offers this type. */\n creatable: boolean;\n /** Properties kept read-only when editing an existing field of this type. */\n lockedProperties?: readonly LockableFieldProperty[];\n /** Placeholder for the name input. Absent ⇒ the modal's generic placeholder. */\n namePlaceholder?: string;\n /** Fallback field ID base when the name cannot produce a valid ID.\n * Default: the normalized type ID. Numeric suffixes resolve collisions. */\n keyBase?: string;\n /** One-line description under the type in the picker. */\n subtitle?: string;\n /** Group heading this type is listed under in the picker. */\n group?: string;\n /** Whether a field of this type can be marked PII. Absent ⇒ follows the\n * source-wide setting. */\n supportsPii?: boolean;\n /** Warning shown while the PII toggle is on. Read on every render, so it can\n * use data that only exists once the schema has loaded. Default: none. */\n piiWarning?: () => FieldPiiWarning | undefined;\n /** This type's collapsible settings section — the same contract a\n * source-declared type option carries (see `FieldSettingsSection`). */\n settingsSection?: FieldSettingsSection;\n /** Collection picker shown in the main add/edit field form. */\n collectionInput?: FieldModalCollectionInput;\n}\n\n/**\n * Props the entity-page form dispatcher passes to a field type's form\n * component. The dispatcher owns the form wiring (registration, validation\n * from the definition's `value.validate`) and the field UI (label, required\n * marker, error message); the component renders the input: read `value`,\n * report edits through `onChange`, and hand back the focusable control\n * through `inputRef` so a blocked save can reach it.\n */\nexport interface FormFieldComponentProps<V> {\n field: Field;\n value: V;\n // Method syntax keeps FormFieldComponentProps covariant in V (see FieldTypeDefinition).\n onChange(value: V): void;\n /** Call when the input loses focus — marks the field touched, so error\n * timing matches the built-in renderers. */\n onBlur: () => void;\n /** Ref to the focusable input element. Used to focus the field when a\n * blocked save reports an error on it. Absent ⇒ the entity page brings the\n * field into view and focuses the first control it finds inside. */\n inputRef?: MutableRefObject<Focusable | undefined | null>;\n dataHook?: string;\n}\n\n/** The entity-page form slot of a field type definition. */\nexport interface FormTypeConfig<V = unknown> {\n /** Renders the input. Method syntax keeps the definition assignable to\n * `FieldTypeDefinition<unknown>` (see FieldTypeDefinition). */\n Component(props: FormFieldComponentProps<V>): ReactElement | null;\n}\n\n/**\n * A consumer-defined field type. Defined once on the fields source; every\n * entry point that renders the field resolves its slot from here. `V` is the\n * field's value type — `defineFieldType` infers it, and it keeps all the\n * slots consistent with each other.\n *\n * Sources hold definitions of mixed value types in one\n * `FieldTypeDefinition[]` (= `FieldTypeDefinition<unknown>[]`) array. That\n * works because every member that takes `V` is declared with method syntax,\n * which TypeScript checks bivariantly — so `FieldTypeDefinition<number>` is\n * assignable to `FieldTypeDefinition<unknown>` without casts.\n */\nexport interface FieldTypeDefinition<V = unknown> {\n /** Unique key for the type. A built-in type uses its `PatternsFieldType`; a\n * consumer-defined type uses the string its fields reference via `customType`. */\n type: string;\n display: FieldTypeDisplay;\n /** Filter behavior, or an explicit opt-out — never silently absent. */\n filter: FilterTypeConfig | { filterable: false };\n value?: FieldValueBehavior<V>;\n capabilities?: FieldCapabilities;\n /** Absent ⇒ the field renders with the default cell in the read-only table. */\n table?: TableCellConfig<V>;\n /** Absent ⇒ the field renders as a read-only cell in editable surfaces. */\n editableTable?: EditableCellConfig<V>;\n /** Required once a field of this type renders on an entity page:\n * development throws without it; production skips the field. */\n form?: FormTypeConfig<V>;\n /** Extra items for the field's \"more actions\" menu. */\n actions?: FieldActionsConfig;\n /** Absent ⇒ the add/edit field modal never offers this type. Fields of the\n * type created elsewhere still open in the modal for name/PII edits. */\n fieldModal?: FieldModalConfig;\n}\n\n/** Identity factory: infers `V` and keeps the definition's slots type-checked. */\nexport function defineFieldType<V>(\n definition: FieldTypeDefinition<V>,\n): FieldTypeDefinition<V> {\n return definition;\n}\n\n/** Resolves the definition a CUSTOM field references on its source. */\nexport function resolveFieldTypeDefinition(\n source: Pick<FieldsSource, 'fieldTypes'>,\n field: Field,\n) {\n if (field.type !== 'CUSTOM' || !field.customType) {\n return undefined;\n }\n return source.fieldTypes?.find((def) => def.type === field.customType);\n}\n"],"mappings":";;;;;;AA+EA;AACA;AACA;AACA;AACA;AACA;AACA;;AAgCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAgDA;AACA;;AAQA;AACA;;AAMA;AACO,SAASA,kBAAkBA,CAChCC,MAAqC,EACT;EAC5B,OAAO,cAAc,IAAIA,MAAM;AACjC;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAqBA;;AAaA;;AAKA;;AASA;AACA;AACA;;AAaA;AACA;;AA4BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAgBA;;AAOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAwBA;AACO,SAASC,eAAeA,CAC7BC,UAAkC,EACV;EACxB,OAAOA,UAAU;AACnB;;AAEA;AACO,SAASC,0BAA0BA,CACxCC,MAAwC,EACxCC,KAAY,EACZ;EAAA,IAAAC,kBAAA;EACA,IAAID,KAAK,CAACE,IAAI,KAAK,QAAQ,IAAI,CAACF,KAAK,CAACG,UAAU,EAAE;IAChD,OAAOC,SAAS;EAClB;EACA,QAAAH,kBAAA,GAAOF,MAAM,CAACM,UAAU,qBAAjBJ,kBAAA,CAAmBK,IAAI,CAAEC,GAAG,IAAKA,GAAG,CAACL,IAAI,KAAKF,KAAK,CAACG,UAAU,CAAC;AACxE","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"names":[],"sources":["../../../src/types/FieldsSource.ts"],"sourcesContent":["import type { ComponentType } from 'react';\nimport type { Field, PatternsFieldType } from './Field';\nimport type { FieldActions, FieldSettings, Schema } from './Schema';\nimport type {\n FieldTypeDefinition,\n FieldTypeDisplay,\n} from './FieldTypeDefinition';\nimport type { CustomFieldOrigin } from '../services';\n\n/** Presentation for one existing field, without changing its type or behavior. */\nexport interface FieldPresentation {\n typeDisplay?: Partial<FieldTypeDisplay>;\n collectionInputLabel?: string;\n}\n\n/** A field the source has archived. Sources without archiving omit `archive`. */\nexport interface ArchivedFieldItem {\n id: string;\n label: string;\n isPii?: boolean;\n}\n\n/** A `FieldTypeOption` the modal can render: the id and label a source left to\n * the defaults are filled in. */\nexport interface ResolvedFieldTypeOption {\n /** Stored on the draft; the source maps it back to its native type. */\n id: string;\n label: string;\n namePlaceholder?: string;\n /** Fallback field ID base when the name cannot produce a valid ID.\n * Default: the normalized type ID. Numeric suffixes resolve collisions. */\n keyBase?: string;\n subtitle?: string;\n /** Group heading in the type list; types sharing a heading form one group. */\n group?: string;\n /** Whether a field of this type can be marked PII. Absent ⇒ follows the\n * source-wide `supportsPii`. */\n supportsPii?: boolean;\n /** Warning to show while the PII toggle is on. Called on every render.\n * Absent ⇒ none. */\n piiWarning?: () => FieldPiiWarning | undefined;\n /** This type's own part of the collapsible section below the main fields.\n * Absent ⇒ the section holds only what the modal itself puts there. */\n settingsSection?: FieldSettingsSection;\n /** Collection picker shown below the type picker. For built-in reference\n * types, absent copy can use the source's referenceable collection loader. */\n collectionInput?: FieldModalCollectionInput;\n /** Drives the type icon in the modal. */\n patternsType: PatternsFieldType;\n /** Type icons for the picker. Absent ⇒ the icon derives from `patternsType`. */\n icons?: { Small: ComponentType; Medium: ComponentType };\n}\n\n/** Read/write permission defaults a source supports, per audience. */\nexport interface FieldPermissions {\n installedApps?: {\n hide?: boolean;\n defaultRead?: boolean;\n defaultWrite?: boolean;\n };\n siteVisitors?: {\n hide?: boolean;\n defaultRead?: boolean;\n defaultWrite?: boolean;\n };\n}\n\n/** The values the add/edit field modal collects, source-neutral. */\nexport interface FieldDraft {\n type?: string;\n key: string;\n name: string;\n readApps: boolean;\n readUsers: boolean;\n writeApps: boolean;\n writeUsers: boolean;\n containsPii: boolean;\n /** Collection selected by the modal's collection picker, when a type has one. */\n referencedCollectionId?: string;\n /** The field this draft was built from, for the source's settings section to\n * read its own values off. Absent for a new field. */\n field?: Field;\n /** What the source's settings section collected, on its way to that source's\n * `addField`/`editField`. */\n settings?: FieldSettings;\n}\n\n/** The add-modal subtitle: a line of text, an optional second note line, and an\n * optional \"learn more\" link. */\nexport interface FieldModalSubtitle {\n text: string;\n note?: string;\n learnMore?: { label: string; href: string };\n}\n\n/** The text a source supplies for the add/edit field modal. */\nexport interface FieldModalText {\n addTitle: string;\n editTitle: string;\n /** Subtitle for the add modal; omit for none. */\n addSubtitle?: FieldModalSubtitle;\n /** Label of the collapsible section below the main fields. */\n settingsLabel?: string;\n /** Label of the field ID input. Absent ⇒ the standard key label. */\n keyLabel?: string;\n}\n\n/** A warning shown under the PII toggle, with an optional action button. */\nexport interface FieldPiiWarning {\n text: string;\n action?: { label: string; onClick: () => void };\n}\n\nexport interface FieldModalCollectionOption {\n id: string;\n label: string;\n}\n\nexport type FieldModalCollectionOptionsLoader = () => Promise<\n FieldModalCollectionOption[]\n>;\n\nexport interface FieldModalCollectionAction {\n label: string;\n icon?: ComponentType;\n disabled?: boolean;\n /** Return an option to select, or undefined on cancellation. The option may\n * be pending creation; persistence remains the source's responsibility. */\n onClick: () => Promise<FieldModalCollectionOption | undefined>;\n}\n\n/** Extra collection picker a field type can add to the main modal body. */\nexport interface FieldModalCollectionInput {\n label?: string;\n placeholder?: string;\n emptyStateMessage?: string;\n errorMessage?: string;\n required?: boolean;\n loadOptions?: FieldModalCollectionOptionsLoader;\n /** An action below the options, also shown when no options match. */\n dropdownAction?: FieldModalCollectionAction;\n /** Restores the picker value from an existing field. */\n getValue?: (field: Field) => string | undefined;\n /** Adds picker-derived values to the source-owned settings payload. */\n getSettings?: (collectionId: string) => FieldSettings;\n}\n\nexport interface FieldSettingsProps {\n /** The picked field type, or absent before one is picked. */\n fieldType?: string;\n /** Validation rules the section should render as fixed, not user-editable.\n * A section ignores any entry it doesn't recognize. */\n lockedRules?: readonly string[];\n /** When false, hide error styling and messages.\n * `hasError` must still report validity. Omit to show errors immediately. */\n showValidationErrors?: boolean;\n}\n\n/**\n * The collapsible section below the main add/edit field inputs, supplied by the\n * source. The modal renders it, blocks confirm while it has an error, and hands\n * its values to the source's own `addField`/`editField` — it never looks inside.\n */\nexport interface FieldSettingsSection {\n Component: ComponentType<FieldSettingsProps>;\n /** Pure validity check: true blocks confirm even while errors are hidden.\n * The section shows errors according to `showValidationErrors`. */\n hasError(fieldType?: string): boolean;\n /** Passed to the source's field-creation or editing action as-is. */\n getValues(fieldType?: string): FieldSettings;\n /**\n * Fills the inputs when the modal opens: the field being edited, or nothing\n * for a new field. Pushed in rather than read from a prop, so the values are\n * there whether or not the section has been rendered yet.\n */\n setValues(field?: Field): void;\n /** Restores settings saved on a pending new-field draft. */\n setDraftValues?(settings: FieldSettings): void;\n /**\n * Prefills a new field's rules from the caller's requested initial values —\n * there is no backing `Field` yet, so this is separate from `setValues`.\n * Absent ⇒ the section doesn't support prefilling any rule this way, and\n * the modal drops that rule from `lockedProperties` rather than locking a\n * control at a value it could never actually apply.\n */\n setInitialValues?(initial: { required?: boolean }): void;\n}\n\n/** Add/edit/delete capability a source exposes. Present ⇒ field management UI shows. */\nexport interface FieldManagement {\n /** False ⇒ the add-field CTA is hidden entirely. */\n canAddFields: boolean;\n /** True ⇒ the add-field CTA renders but is disabled. */\n addFieldDisabled: boolean;\n /** Hint text shown beneath the add-field CTA while it is disabled. */\n addFieldDisabledHint?: string;\n canEditField(field: Field): boolean;\n /** Allows changing PII on an existing supported field. Default: disabled. */\n canEditFieldPii?(field: Field): boolean;\n /** `origin` is the UI surface the delete was triggered from; used for BI. */\n deleteField(fieldId: string, origin: string): Promise<void>;\n\n /** Everything the add/edit field modal shows: its titles, and the field types\n * it offers with what each one brings to it. */\n fieldModal: {\n /** Whether to show the field ID input. Default: true. */\n showFieldId?: boolean;\n text: FieldModalText;\n /** Default option loader for built-in reference and multi-reference types. */\n loadReferenceableCollectionOptions?: FieldModalCollectionOptionsLoader;\n types: ResolvedFieldTypeOption[];\n /** Defaults for the read/write permissions per audience. Absent ⇒ the modal\n * shows no permissions section. */\n permissions?: FieldPermissions;\n /** Whether a field can be marked PII. A field type option overrides it with\n * its own `supportsPii`. */\n supportsPii?: boolean;\n };\n /** Existing field keys, used by the add modal to reject duplicates. */\n existingFieldKeys: string[];\n /** True when no more fields can be added because a limit is reached. */\n maxReached?: boolean;\n /** Returns the created field's id when the source can identify it, so the\n * modal can report it back to the caller. Absent ⇒ the caller isn't told\n * which field was created. */\n addField(draft: FieldDraft): Promise<string | void>;\n editField(fieldId: string, draft: FieldDraft): Promise<void>;\n /** Current values for an existing field, to prefill the edit modal. */\n getFieldDraft(fieldId: string): FieldDraft | undefined;\n getFieldPresentation?(field: Field): FieldPresentation | undefined;\n}\n\n/** A new-field property `OpenFieldModalOptions` can lock from editing. */\nexport type LockableFieldProperty = 'type' | 'name' | 'required';\n\n/** Options for opening the add/edit field modal. */\nexport interface OpenFieldModalOptions {\n fieldId?: string;\n origin?: CustomFieldOrigin;\n customOrigin?: string;\n /** Fired with the field's id after it's successfully created or edited.\n * Not called for a create when the source can't report which field it\n * created. */\n onSave?: (fieldId: string) => void;\n /** Prefills a new field. Ignored when `fieldId` is set — edit mode prefills\n * from the existing field instead. */\n initialField?: {\n /** Prefilled; locked when included in `lockedProperties`. */\n type?: string;\n /** Prefilled; locked when included in `lockedProperties`. */\n name?: string;\n /** Prefilled; locked when included in `lockedProperties`. Support depends\n * on the picked type's settings section — see `FieldSettingsSection.setInitialValues`. */\n required?: boolean;\n };\n /** Properties the user can't change, on top of being prefilled. A property\n * with no matching `initialField` value is never locked — there is nothing\n * to lock it to. */\n lockedProperties?: readonly LockableFieldProperty[];\n}\n\n/** Archiving capability a source exposes. Present ⇒ archive/restore UI shows. */\nexport interface FieldArchive {\n items: ArchivedFieldItem[];\n shouldDisplay: boolean;\n /** Whether the archived-items panel is currently open. */\n isOpen: boolean;\n openPanel(): void;\n closePanel(): void;\n /** `origin` is the UI surface the action was triggered from; used for BI. */\n archiveField(fieldId: string, origin: string): Promise<void>;\n restoreField(fieldId: string, origin: string): Promise<void>;\n /** Display name for a field, for the confirm-dialog copy. */\n fieldName(fieldId: string): string;\n}\n\n/**\n * The source-neutral fields data a collection reads, implemented by each source\n * adapter. Rendering — field modals, filter elements — is not here; it lives in\n * the collection-page layer.\n */\nexport interface FieldsSource {\n /** Loads the fields (schema/data). The collection runs this once, tracks its\n * status, and shows a retry toast on failure. */\n load(): Promise<void>;\n\n fields: Field[];\n filterableFields: Field[];\n /** The fields the manage-fields panel lists — the source's editable fields. */\n manageableFields: Field[];\n /** Column id for a field. Sources that group fields prefix the group; flat sources use the field key. */\n columnIdForField(field: Field): string;\n /** WQL field path for a filter. Sources that group fields prefix the group; flat sources use the field key. */\n queryFieldId(field: Field): string;\n /** The value to display for a field on a row. */\n getCellValue(row: unknown, field: Field): unknown;\n /** Writes a new value for a field on a row, returning the updated row. Present when cells can be edited in place. */\n setCellValue?(row: unknown, field: Field, value: unknown): unknown;\n\n /** Replaces the source's fields with a freshly-returned map, updating the\n * columns with no refetch. Present when the source holds its fields in a\n * mergeable state (e.g. a loaded schema); used after an import creates fields. */\n mergeFields?(fields: Schema['fields']): void;\n\n /** Field-type definitions the source supports: how a field of that type\n * renders, filters and validates. Built-in types are keyed by their\n * `PatternsFieldType`; consumer-defined types are keyed by the string a field\n * references via `customType`. The add/edit field modal never reads this —\n * see `FieldManagement.fieldModal`. */\n fieldTypes?: FieldTypeDefinition[];\n getFieldPresentation?(field: Field): FieldPresentation | undefined;\n\n /** Present when fields can be added/edited/deleted. */\n fieldManagement?: FieldManagement;\n\n /** The collection's field-mutation actions (delete/makePrimary/duplicate/…),\n * driving the shared FieldActions menu. Absent ⇒ no per-field action menu. */\n fieldActions?: FieldActions;\n\n /** Present when the source supports archiving fields. */\n archive?: FieldArchive;\n\n /** Present when fields are grouped. Absent ⇒ flat list. */\n groups?: {\n all: string[];\n fieldsForGroup(group: string): Field[];\n };\n}\n"],"mappings":"","ignoreList":[]}
1
+ {"version":3,"names":[],"sources":["../../../src/types/FieldsSource.ts"],"sourcesContent":["import type { ComponentType } from 'react';\nimport type { Field, PatternsFieldType } from './Field';\nimport type { FieldActions, FieldSettings, Schema } from './Schema';\nimport type {\n FieldTypeDefinition,\n FieldTypeDisplay,\n} from './FieldTypeDefinition';\nimport type { CustomFieldOrigin } from '../services';\n\n/** Presentation for one existing field, without changing its type or behavior. */\nexport interface FieldPresentation {\n typeDisplay?: Partial<FieldTypeDisplay>;\n collectionInputLabel?: string;\n}\n\n/** A field the source has archived. Sources without archiving omit `archive`. */\nexport interface ArchivedFieldItem {\n id: string;\n label: string;\n isPii?: boolean;\n}\n\n/** A `FieldTypeOption` the modal can render: the id and label a source left to\n * the defaults are filled in. */\nexport interface ResolvedFieldTypeOption {\n /** Stored on the draft; the source maps it back to its native type. */\n id: string;\n label: string;\n namePlaceholder?: string;\n /** Fallback field ID base when the name cannot produce a valid ID.\n * Default: the normalized type ID. Numeric suffixes resolve collisions. */\n keyBase?: string;\n subtitle?: string;\n /** Group heading in the type list; types sharing a heading form one group. */\n group?: string;\n /** Whether a field of this type can be marked PII. Absent ⇒ follows the\n * source-wide `supportsPii`. */\n supportsPii?: boolean;\n /** Warning to show while the PII toggle is on. Called on every render.\n * Absent ⇒ none. */\n piiWarning?: () => FieldPiiWarning | undefined;\n /** This type's own part of the collapsible section below the main fields.\n * Absent ⇒ the section holds only what the modal itself puts there. */\n settingsSection?: FieldSettingsSection;\n /** Collection picker shown below the type picker. For built-in reference\n * types, absent copy can use the source's referenceable collection loader. */\n collectionInput?: FieldModalCollectionInput;\n /** Drives the type icon in the modal. */\n patternsType: PatternsFieldType;\n /** Type icons for the picker. Absent ⇒ the icon derives from `patternsType`. */\n icons?: { Small: ComponentType; Medium: ComponentType };\n}\n\n/** Read/write permission defaults a source supports, per audience. */\nexport interface FieldPermissions {\n installedApps?: {\n hide?: boolean;\n defaultRead?: boolean;\n defaultWrite?: boolean;\n };\n siteVisitors?: {\n hide?: boolean;\n defaultRead?: boolean;\n defaultWrite?: boolean;\n };\n}\n\n/** The values the add/edit field modal collects, source-neutral. */\nexport interface FieldDraft {\n type?: string;\n key: string;\n name: string;\n readApps: boolean;\n readUsers: boolean;\n writeApps: boolean;\n writeUsers: boolean;\n containsPii: boolean;\n /** Collection selected by the modal's collection picker, when a type has one. */\n referencedCollectionId?: string;\n /** The field this draft was built from, for the source's settings section to\n * read its own values off. Absent for a new field. */\n field?: Field;\n /** What the source's settings section collected, on its way to that source's\n * `addField`/`editField`. */\n settings?: FieldSettings;\n}\n\n/** The add-modal subtitle: a line of text, an optional second note line, and an\n * optional \"learn more\" link. */\nexport interface FieldModalSubtitle {\n text: string;\n note?: string;\n learnMore?: { label: string; href: string };\n}\n\n/** The text a source supplies for the add/edit field modal. */\nexport interface FieldModalText {\n addTitle: string;\n editTitle: string;\n /** Subtitle for the add modal; omit for none. */\n addSubtitle?: FieldModalSubtitle;\n /** Label of the collapsible section below the main fields. */\n settingsLabel?: string;\n /** Label of the field ID input. Absent ⇒ the standard key label. */\n keyLabel?: string;\n}\n\n/** A warning shown under the PII toggle, with an optional action button. */\nexport interface FieldPiiWarning {\n text: string;\n action?: { label: string; onClick: () => void };\n}\n\nexport interface FieldModalCollectionOption {\n id: string;\n label: string;\n}\n\nexport type FieldModalCollectionOptionsLoader = () => Promise<\n FieldModalCollectionOption[]\n>;\n\nexport interface FieldModalCollectionAction {\n label: string;\n icon?: ComponentType;\n disabled?: boolean;\n /** Return an option to select, or undefined on cancellation. The option may\n * be pending creation; persistence remains the source's responsibility. */\n onClick: () => Promise<FieldModalCollectionOption | undefined>;\n}\n\n/** Extra collection picker a field type can add to the main modal body. */\nexport interface FieldModalCollectionInput {\n label?: string;\n placeholder?: string;\n emptyStateMessage?: string;\n errorMessage?: string;\n required?: boolean;\n loadOptions?: FieldModalCollectionOptionsLoader;\n /** An action below the options, also shown when no options match. */\n dropdownAction?: FieldModalCollectionAction;\n /** Restores the picker value from an existing field. */\n getValue?: (field: Field) => string | undefined;\n /** Adds picker-derived values to the source-owned settings payload. */\n getSettings?: (collectionId: string) => FieldSettings;\n}\n\nexport interface FieldSettingsProps {\n /** The picked field type, or absent before one is picked. */\n fieldType?: string;\n /** Validation rules the section should render as fixed, not user-editable.\n * A section ignores any entry it doesn't recognize. */\n lockedRules?: readonly string[];\n /** When false, hide error styling and messages.\n * `hasError` must still report validity. Omit to show errors immediately. */\n showValidationErrors?: boolean;\n}\n\n/**\n * The collapsible section below the main add/edit field inputs, supplied by the\n * source. The modal renders it, blocks confirm while it has an error, and hands\n * its values to the source's own `addField`/`editField` — it never looks inside.\n */\nexport interface FieldSettingsSection {\n Component: ComponentType<FieldSettingsProps>;\n /** Pure validity check: true blocks confirm even while errors are hidden.\n * The section shows errors according to `showValidationErrors`. */\n hasError(fieldType?: string): boolean;\n /** Passed to the source's field-creation or editing action as-is. */\n getValues(fieldType?: string): FieldSettings;\n /**\n * Fills the inputs when the modal opens: the field being edited, or nothing\n * for a new field. Pushed in rather than read from a prop, so the values are\n * there whether or not the section has been rendered yet.\n */\n setValues(field?: Field): void;\n /** Restores settings saved on a pending new-field draft. */\n setDraftValues?(settings: FieldSettings): void;\n /**\n * Prefills a new field's rules from the caller's requested initial values —\n * there is no backing `Field` yet, so this is separate from `setValues`.\n * Absent ⇒ the section doesn't support prefilling any rule this way, and\n * the modal drops that rule from `lockedProperties` rather than locking a\n * control at a value it could never actually apply.\n */\n setInitialValues?(initial: { required?: boolean }): void;\n}\n\n/** Add/edit/delete capability a source exposes. Present ⇒ field management UI shows. */\nexport interface FieldManagement {\n /** False ⇒ the add-field CTA is hidden entirely. */\n canAddFields: boolean;\n /** True ⇒ the add-field CTA renders but is disabled. */\n addFieldDisabled: boolean;\n /** Hint text shown beneath the add-field CTA while it is disabled. */\n addFieldDisabledHint?: string;\n canEditField(field: Field): boolean;\n /** Allows changing PII on an existing supported field. Default: disabled. */\n canEditFieldPii?(field: Field): boolean;\n /** `origin` is the UI surface the delete was triggered from; used for BI. */\n deleteField(fieldId: string, origin: string): Promise<void>;\n\n /** Everything the add/edit field modal shows: its titles, and the field types\n * it offers with what each one brings to it. */\n fieldModal: {\n /** Whether to show the field ID input. Default: true. */\n showFieldId?: boolean;\n text: FieldModalText;\n /** Default option loader for built-in reference and multi-reference types. */\n loadReferenceableCollectionOptions?: FieldModalCollectionOptionsLoader;\n types: ResolvedFieldTypeOption[];\n /** Metadata for an existing type that is absent from the add-field picker. */\n getEditFieldType?: (type: string) => ResolvedFieldTypeOption | undefined;\n /** Defaults for the read/write permissions per audience. Absent ⇒ the modal\n * shows no permissions section. */\n permissions?: FieldPermissions;\n /** Whether a field can be marked PII. A field type option overrides it with\n * its own `supportsPii`. */\n supportsPii?: boolean;\n };\n /** Existing field keys, used by the add modal to reject duplicates. */\n existingFieldKeys: string[];\n /** True when no more fields can be added because a limit is reached. */\n maxReached?: boolean;\n /** Returns the created field's id when the source can identify it, so the\n * modal can report it back to the caller. Absent ⇒ the caller isn't told\n * which field was created. */\n addField(draft: FieldDraft): Promise<string | void>;\n editField(fieldId: string, draft: FieldDraft): Promise<void>;\n /** Current values for an existing field, to prefill the edit modal. */\n getFieldDraft(fieldId: string): FieldDraft | undefined;\n getFieldPresentation?(field: Field): FieldPresentation | undefined;\n}\n\n/** A field-modal property that can be locked from editing. */\nexport type LockableFieldProperty = 'type' | 'name' | 'required';\n\n/** Options for opening the add/edit field modal. */\nexport interface OpenFieldModalOptions {\n fieldId?: string;\n origin?: CustomFieldOrigin;\n customOrigin?: string;\n /** Fired with the field's id after it's successfully created or edited.\n * Not called for a create when the source can't report which field it\n * created. */\n onSave?: (fieldId: string) => void;\n /** Prefills a new field. Ignored when `fieldId` is set — edit mode prefills\n * from the existing field instead. */\n initialField?: {\n /** Prefilled; locked when included in `lockedProperties`. */\n type?: string;\n /** Prefilled; locked when included in `lockedProperties`. */\n name?: string;\n /** Prefilled; locked when included in `lockedProperties`. Support depends\n * on the picked type's settings section — see `FieldSettingsSection.setInitialValues`. */\n required?: boolean;\n };\n /** Properties the user can't change, on top of being prefilled. A property\n * with no matching `initialField` value is never locked — there is nothing\n * to lock it to. */\n lockedProperties?: readonly LockableFieldProperty[];\n}\n\n/** Archiving capability a source exposes. Present ⇒ archive/restore UI shows. */\nexport interface FieldArchive {\n items: ArchivedFieldItem[];\n shouldDisplay: boolean;\n /** Whether the archived-items panel is currently open. */\n isOpen: boolean;\n openPanel(): void;\n closePanel(): void;\n /** `origin` is the UI surface the action was triggered from; used for BI. */\n archiveField(fieldId: string, origin: string): Promise<void>;\n restoreField(fieldId: string, origin: string): Promise<void>;\n /** Display name for a field, for the confirm-dialog copy. */\n fieldName(fieldId: string): string;\n}\n\n/**\n * The source-neutral fields data a collection reads, implemented by each source\n * adapter. Rendering — field modals, filter elements — is not here; it lives in\n * the collection-page layer.\n */\nexport interface FieldsSource {\n /** Loads the fields (schema/data). The collection runs this once, tracks its\n * status, and shows a retry toast on failure. */\n load(): Promise<void>;\n\n fields: Field[];\n filterableFields: Field[];\n /** The fields the manage-fields panel lists — the source's editable fields. */\n manageableFields: Field[];\n /** Column id for a field. Sources that group fields prefix the group; flat sources use the field key. */\n columnIdForField(field: Field): string;\n /** WQL field path for a filter. Sources that group fields prefix the group; flat sources use the field key. */\n queryFieldId(field: Field): string;\n /** The value to display for a field on a row. */\n getCellValue(row: unknown, field: Field): unknown;\n /** Writes a new value for a field on a row, returning the updated row. Present when cells can be edited in place. */\n setCellValue?(row: unknown, field: Field, value: unknown): unknown;\n\n /** Replaces the source's fields with a freshly-returned map, updating the\n * columns with no refetch. Present when the source holds its fields in a\n * mergeable state (e.g. a loaded schema); used after an import creates fields. */\n mergeFields?(fields: Schema['fields']): void;\n\n /** Field-type definitions the source supports: how a field of that type\n * renders, filters and validates. Built-in types are keyed by their\n * `PatternsFieldType`; consumer-defined types are keyed by the string a field\n * references via `customType`. The add/edit field modal never reads this —\n * see `FieldManagement.fieldModal`. */\n fieldTypes?: FieldTypeDefinition[];\n getFieldPresentation?(field: Field): FieldPresentation | undefined;\n\n /** Present when fields can be added/edited/deleted. */\n fieldManagement?: FieldManagement;\n\n /** The collection's field-mutation actions (delete/makePrimary/duplicate/…),\n * driving the shared FieldActions menu. Absent ⇒ no per-field action menu. */\n fieldActions?: FieldActions;\n\n /** Present when the source supports archiving fields. */\n archive?: FieldArchive;\n\n /** Present when fields are grouped. Absent ⇒ flat list. */\n groups?: {\n all: string[];\n fieldsForGroup(group: string): Field[];\n };\n}\n"],"mappings":"","ignoreList":[]}
@@ -129,6 +129,7 @@ function defineSchemaSource(input) {
129
129
  canAddFields,
130
130
  canEditField,
131
131
  canDeleteField,
132
+ getFieldActionDisabledReason: input.getFieldActionDisabledReason,
132
133
  canMakePrimary: input.canMakePrimary,
133
134
  getDeleteFieldConfirmation: input.getDeleteFieldConfirmation,
134
135
  fieldPermissions,
@@ -1 +1 @@
1
- {"version":3,"names":["sourceFetchData","source","query","backend","schema","loadSchema","visibleColumns","columns","find","searchableFieldIds","length","defineSchemaSource","input","collectionId","paginationMode","fieldModal","fieldTypes","fieldPermissions","supportsPii","references","getReferencedCollectionSource","loaded","resolved","then","result","catch","error","undefined","setLoadedSchema","Promise","resolve","s","displayField","itemKey","item","_resolved","String","idField","itemName","_resolved2","canAddFields","_s$schemaPermissions","schemaPermissions","createField","isLockedField","field","isSystem","id","canEditField","_s$schemaPermissions2","updateField","canDeleteField","_s$schemaPermissions3","deleteField","getFieldValue","setFieldValue","value","schemaParams","_resolved3","_resolved4","_resolved5","tableId","tableName","name","tableType","type","showFieldId","text","loadReferenceableCollectionOptions","types","getFieldPresentation","canMakePrimary","getDeleteFieldConfirmation","canEditFieldPii"],"sources":["../../../src/types/SchemaSource.ts"],"sourcesContent":["import type { Field, PatternsFieldType } from './Field';\nimport type { FieldTypeDefinition } from './FieldTypeDefinition';\nimport type { Schema, LoadedSchema, FindOptions } from './Schema';\nimport type {\n FieldPresentation,\n FieldModalText,\n FieldModalCollectionInput,\n FieldModalCollectionOptionsLoader,\n FieldPermissions,\n FieldPiiWarning,\n FieldSettingsSection,\n} from './FieldsSource';\nimport type {\n OffsetQuery,\n OffsetQueryResult,\n} from '../hooks/paginationModeConfig';\n\n/** A field type the add/edit field modal offers, with everything that type\n * brings to it. Declare one entry per `patternsType` — the type is the entry's\n * identity. Nothing here reaches the table or the filters; that is `fieldTypes`\n * (`FieldTypeDefinition[]`). */\nexport interface FieldTypeOption {\n patternsType: PatternsFieldType;\n /** Custom display name. Absent ⇒ the UI's standard name for this type. */\n label?: string;\n /** Custom name-input placeholder. Absent ⇒ the UI's standard placeholder. */\n namePlaceholder?: string;\n /** Fallback field ID base when the name cannot produce a valid ID.\n * Default: the normalized type ID. Numeric suffixes resolve collisions. */\n keyBase?: string;\n /** A one-line description shown under the type in the add-field menu. */\n subtitle?: string;\n /** The group heading this type is listed under in the add-field menu, in\n * first-seen order. Types sharing a heading form one group. Absent ⇒\n * ungrouped. */\n group?: string;\n /** Whether a field of this type can be marked PII. Absent ⇒ follows the\n * source's `supportsPii`. */\n supportsPii?: boolean;\n /** Warning shown while the PII toggle is on. Read on every render, so it can\n * use data that only exists once the schema has loaded. Default: none. */\n piiWarning?: () => FieldPiiWarning | undefined;\n /** This type's own part of the collapsible section in the add/edit field\n * modal. Default: none. */\n settingsSection?: FieldSettingsSection;\n /** Collection picker shown in the main add/edit field form. */\n collectionInput?: FieldModalCollectionInput;\n}\n\n/** Everything the add/edit field modal shows for this source. */\nexport interface FieldModalInput {\n /** Whether to show the field ID input. Default: true. */\n showFieldId?: boolean;\n /** Title and subtitle. Default: generic titles. */\n text?: FieldModalText;\n /** Default option loader for reference-like built-in field types. */\n loadReferenceableCollectionOptions?: FieldModalCollectionOptionsLoader;\n /** The types the modal offers, in display order. Default: none. */\n types?: FieldTypeOption[];\n}\n\n/** Copy shown before deleting a field. Strings are translated by the caller. */\nexport interface DeleteFieldConfirmation {\n title: string;\n description: string;\n /** When provided, confirmation requires this checkbox to be checked. */\n confirmationCheckboxLabel?: string;\n}\n\n/** Identifies the collection behind a table on BI events. */\nexport interface SchemaBiParams {\n tableId?: string;\n tableName?: string;\n tableType?: string;\n}\n\n/** What a caller passes. Only `collectionId` and `loadSchema` are required. */\nexport interface SchemaSourceInput<T> {\n collectionId: string;\n loadSchema: () => Promise<LoadedSchema<T>>;\n /** Sources for collections this one references, keyed by the referenced\n * collection id. A renderer resolves a reference field through the matching\n * entry — its `loadSchema` gives the referenced schema and `sourceFetchData`\n * queries the referenced items. Default: none. */\n references?: Record<string, SchemaSource<any>>;\n /** Lazy source lookup for a referenced collection that is not in `references`.\n * Is used when a reference field is created in the add field modal.\n * The returned source owns its own async schema/item loading. */\n getReferencedCollectionSource?: (\n collectionId: string,\n ) => SchemaSource<any> | undefined;\n paginationMode?: 'offset';\n /** Stable row identity. Default: `row[idField]`. */\n itemKey?: (item: T) => string;\n /** Row display label. Default: `row[displayField]`. */\n itemName?: (item: T) => string;\n /** Fields free-text search runs against. Default: `[displayField]`. */\n searchableFieldIds?: (schema: Schema) => string[];\n /** What the add/edit field modal shows. Default: no types, generic titles. */\n fieldModal?: FieldModalInput;\n /** Consumer-defined field types: how a field of that type renders, filters and\n * validates wherever it appears. A field with `type: 'CUSTOM'` resolves its\n * definition here by `customType`. The add/edit field modal never reads this\n * — see `fieldModal`. Default: none. */\n fieldTypes?: FieldTypeDefinition[];\n /** Overrides one existing field's type label, icons and collection-picker\n * label. Does not change its type, values or add-field options. */\n getFieldPresentation?: (field: Field) => FieldPresentation | undefined;\n /** Default: `schemaPermissions.createField`. */\n canAddFields?: (schema: Schema) => boolean;\n /** Default: `schemaPermissions.updateField`, except for system fields and\n * the id field. */\n canEditField?: (field: Field, schema: Schema) => boolean;\n /** Default: `schemaPermissions.deleteField`, except for system fields and\n * the id field. */\n canDeleteField?: (field: Field, schema: Schema) => boolean;\n /** Whether a field can become the primary field. When omitted, only\n * `SHORT_TEXT` and `LONG_TEXT` fields can. When set, its result replaces\n * that rule, so return `false` for non-text fields too. */\n canMakePrimary?: (field: Field, schema: Schema) => boolean;\n /** Resolved when deletion is requested. Undefined keeps the default dialog. */\n getDeleteFieldConfirmation?: (\n field: Field,\n schema: Schema,\n ) => DeleteFieldConfirmation | undefined;\n /** Permission defaults shown in the modal. Absent ⇒ no permissions section. */\n fieldPermissions?: FieldPermissions;\n /** Default: `false`. */\n supportsPii?: boolean;\n /** Allows changing PII on an existing supported field. Default: disabled.\n * Does not override `canEditField` or the field type's PII support. */\n canEditFieldPii?: (field: Field, schema: Schema) => boolean;\n /** The value of a field on an item. Default: `item[field.id]`. */\n getFieldValue?: (item: T, field: Field) => unknown;\n /** Writes a field's value on an item, returning the updated item.\n * Default: `{ ...item, [field.id]: value }`. */\n setFieldValue?: (item: T, field: Field, value: unknown) => T;\n}\n\n/** The resolved source: defaults filled, `loadSchema` memoized. */\nexport interface SchemaSource<T> {\n readonly collectionId: string;\n loadSchema: () => Promise<LoadedSchema<T>>;\n readonly paginationMode: 'offset';\n /** Stable row identity. */\n itemKey: (item: T) => string;\n /** Row display label. */\n itemName: (item: T) => string;\n /** Sources for referenced collections, keyed by referenced collection id. */\n readonly references: Record<string, SchemaSource<any>>;\n getReferencedCollectionSource?: (\n collectionId: string,\n ) => SchemaSource<any> | undefined;\n readonly fieldModal: {\n showFieldId?: boolean;\n text?: FieldModalText;\n loadReferenceableCollectionOptions?: FieldModalCollectionOptionsLoader;\n types: FieldTypeOption[];\n };\n readonly fieldTypes: FieldTypeDefinition[];\n getFieldPresentation?: (field: Field) => FieldPresentation | undefined;\n searchableFieldIds: (schema: Schema) => string[];\n canAddFields: (schema: Schema) => boolean;\n canEditField: (field: Field, schema: Schema) => boolean;\n canDeleteField: (field: Field, schema: Schema) => boolean;\n canMakePrimary?: (field: Field, schema: Schema) => boolean;\n getDeleteFieldConfirmation?: (\n field: Field,\n schema: Schema,\n ) => DeleteFieldConfirmation | undefined;\n readonly fieldPermissions?: FieldPermissions;\n readonly supportsPii: boolean;\n canEditFieldPii?: (field: Field, schema: Schema) => boolean;\n /** The value of a field on an item. */\n getFieldValue: (item: T, field: Field) => unknown;\n /** Writes a field's value on an item, returning the updated item. */\n setFieldValue: (item: T, field: Field, value: unknown) => T;\n schemaParams: () => SchemaBiParams;\n /** Replaces the memoized schema returned by later `loadSchema()` calls.\n * No-op before the first successful load. */\n setLoadedSchema?: (schema: Schema) => void;\n}\n\ntype OffsetFind<T> = (\n query: OffsetQuery,\n options?: FindOptions,\n) => Promise<OffsetQueryResult<T>>;\n\n/** The collection fetch derived from a source: loads once, then queries the\n * backend's `find`.\n *\n * Free-text search covers the columns the page is showing: the table keeps\n * `query.columns` in sync with them, so the scope comes off the query rather\n * than being threaded in. Falls back to the source's own `searchableFieldIds`\n * before any columns are known (or with no table attached). */\nexport function sourceFetchData<T>(\n source: SchemaSource<T>,\n): (query: OffsetQuery) => Promise<OffsetQueryResult<T>> {\n return async (query) => {\n const { backend, schema } = await source.loadSchema();\n // `columns` is the visible-column list; `fields` is the projection, which a\n // source-driven table doesn't set.\n const visibleColumns = query.columns;\n return (backend.find as OffsetFind<T>)(query, {\n searchableFieldIds: visibleColumns?.length\n ? visibleColumns\n : source.searchableFieldIds(schema),\n });\n };\n}\n\n/** Fills source-neutral defaults over `input` and memoizes the load so the collection\n * query and the table columns share a single fetch. */\nexport function defineSchemaSource<T>(\n input: SchemaSourceInput<T>,\n): SchemaSource<T> {\n const {\n collectionId,\n paginationMode = 'offset',\n fieldModal = {},\n fieldTypes = [],\n fieldPermissions,\n supportsPii = false,\n references = {},\n getReferencedCollectionSource,\n } = input;\n\n let loaded: Promise<LoadedSchema<T>> | undefined;\n let resolved: LoadedSchema<T> | undefined;\n\n const loadSchema = () =>\n (loaded ??= input\n .loadSchema()\n .then((result) => {\n resolved = result;\n return result;\n })\n .catch((error) => {\n loaded = undefined;\n throw error;\n }));\n\n const setLoadedSchema = (schema: Schema) => {\n if (!resolved) {\n return;\n }\n resolved = { ...resolved, schema };\n loaded = Promise.resolve(resolved);\n };\n\n const searchableFieldIds =\n input.searchableFieldIds ?? ((s) => [s.displayField]);\n\n const itemKey =\n input.itemKey ??\n ((item) =>\n String(\n (item as Record<string, unknown>)[resolved?.schema.idField ?? '_id'] ??\n '',\n ));\n const itemName =\n input.itemName ??\n ((item) =>\n String(\n (item as Record<string, unknown>)[\n resolved?.schema.displayField ?? '_id'\n ] ?? '',\n ));\n const canAddFields =\n input.canAddFields ?? ((s) => s.schemaPermissions?.createField ?? false);\n const isLockedField = (field: Field, s: Schema) =>\n field.isSystem === true || field.id === s.idField;\n const canEditField =\n input.canEditField ??\n ((field, s) =>\n (s.schemaPermissions?.updateField ?? false) && !isLockedField(field, s));\n const canDeleteField =\n input.canDeleteField ??\n ((field, s) =>\n (s.schemaPermissions?.deleteField ?? false) && !isLockedField(field, s));\n const getFieldValue =\n input.getFieldValue ??\n ((item, field) => (item as Record<string, unknown>)[field.id]);\n const setFieldValue =\n input.setFieldValue ??\n ((item, field, value) => ({ ...item, [field.id]: value } as T));\n\n const schemaParams = (): SchemaBiParams => ({\n tableId: resolved?.schema.id ?? collectionId,\n tableName: resolved?.schema.name,\n tableType: resolved?.schema.type,\n });\n\n return {\n collectionId,\n loadSchema,\n paginationMode,\n itemKey,\n itemName,\n references,\n ...(getReferencedCollectionSource && { getReferencedCollectionSource }),\n fieldModal: {\n showFieldId: fieldModal.showFieldId,\n text: fieldModal.text,\n loadReferenceableCollectionOptions:\n fieldModal.loadReferenceableCollectionOptions,\n types: fieldModal.types ?? [],\n },\n fieldTypes,\n getFieldPresentation: input.getFieldPresentation,\n searchableFieldIds,\n canAddFields,\n canEditField,\n canDeleteField,\n canMakePrimary: input.canMakePrimary,\n getDeleteFieldConfirmation: input.getDeleteFieldConfirmation,\n fieldPermissions,\n supportsPii,\n canEditFieldPii: input.canEditFieldPii,\n getFieldValue,\n setFieldValue,\n schemaParams,\n setLoadedSchema,\n };\n}\n"],"mappings":";;;;;AAiBA;AACA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ACrBC,kCAAkC,EAChCrD,UAAU,CAACqD,kCAAkC;MAC/CC,KAAK,EAAEtD,UAAU,CAACsD,KAAK,IAAI;IAC7B,CAAC;IACDrD,UAAU;IACVsD,oBAAoB,EAAE1D,KAAK,CAAC0D,oBAAoB;IAChD7D,kBAAkB;IAClB+B,YAAY;IACZQ,YAAY;IACZG,cAAc;IACdoB,cAAc,EAAE3D,KAAK,CAAC2D,cAAc;IACpCC,0BAA0B,EAAE5D,KAAK,CAAC4D,0BAA0B;IAC5DvD,gBAAgB;IAChBC,WAAW;IACXuD,eAAe,EAAE7D,KAAK,CAAC6D,eAAe;IACtCnB,aAAa;IACbC,aAAa;IACbE,YAAY;IACZ7B;EACF,CAAC;AACH","ignoreList":[]}
1
+ {"version":3,"names":["sourceFetchData","source","query","backend","schema","loadSchema","visibleColumns","columns","find","searchableFieldIds","length","defineSchemaSource","input","collectionId","paginationMode","fieldModal","fieldTypes","fieldPermissions","supportsPii","references","getReferencedCollectionSource","loaded","resolved","then","result","catch","error","undefined","setLoadedSchema","Promise","resolve","s","displayField","itemKey","item","_resolved","String","idField","itemName","_resolved2","canAddFields","_s$schemaPermissions","schemaPermissions","createField","isLockedField","field","isSystem","id","canEditField","_s$schemaPermissions2","updateField","canDeleteField","_s$schemaPermissions3","deleteField","getFieldValue","setFieldValue","value","schemaParams","_resolved3","_resolved4","_resolved5","tableId","tableName","name","tableType","type","showFieldId","text","loadReferenceableCollectionOptions","types","getFieldPresentation","getFieldActionDisabledReason","canMakePrimary","getDeleteFieldConfirmation","canEditFieldPii"],"sources":["../../../src/types/SchemaSource.ts"],"sourcesContent":["import type { Field, PatternsFieldType } from './Field';\nimport type { FieldTypeDefinition } from './FieldTypeDefinition';\nimport type { Schema, LoadedSchema, FindOptions } from './Schema';\nimport type {\n FieldPresentation,\n FieldModalText,\n FieldModalCollectionInput,\n FieldModalCollectionOptionsLoader,\n FieldPermissions,\n FieldPiiWarning,\n FieldSettingsSection,\n} from './FieldsSource';\nimport type {\n OffsetQuery,\n OffsetQueryResult,\n} from '../hooks/paginationModeConfig';\n\n/** A field type the add/edit field modal offers, with everything that type\n * brings to it. Declare one entry per `patternsType` — the type is the entry's\n * identity. Nothing here reaches the table or the filters; that is `fieldTypes`\n * (`FieldTypeDefinition[]`). */\nexport interface FieldTypeOption {\n patternsType: PatternsFieldType;\n /** Custom display name. Absent ⇒ the UI's standard name for this type. */\n label?: string;\n /** Custom name-input placeholder. Absent ⇒ the UI's standard placeholder. */\n namePlaceholder?: string;\n /** Fallback field ID base when the name cannot produce a valid ID.\n * Default: the normalized type ID. Numeric suffixes resolve collisions. */\n keyBase?: string;\n /** A one-line description shown under the type in the add-field menu. */\n subtitle?: string;\n /** The group heading this type is listed under in the add-field menu, in\n * first-seen order. Types sharing a heading form one group. Absent ⇒\n * ungrouped. */\n group?: string;\n /** Whether a field of this type can be marked PII. Absent ⇒ follows the\n * source's `supportsPii`. */\n supportsPii?: boolean;\n /** Warning shown while the PII toggle is on. Read on every render, so it can\n * use data that only exists once the schema has loaded. Default: none. */\n piiWarning?: () => FieldPiiWarning | undefined;\n /** This type's own part of the collapsible section in the add/edit field\n * modal. Default: none. */\n settingsSection?: FieldSettingsSection;\n /** Collection picker shown in the main add/edit field form. */\n collectionInput?: FieldModalCollectionInput;\n}\n\n/** Everything the add/edit field modal shows for this source. */\nexport interface FieldModalInput {\n /** Whether to show the field ID input. Default: true. */\n showFieldId?: boolean;\n /** Title and subtitle. Default: generic titles. */\n text?: FieldModalText;\n /** Default option loader for reference-like built-in field types. */\n loadReferenceableCollectionOptions?: FieldModalCollectionOptionsLoader;\n /** The types the modal offers, in display order. Default: none. */\n types?: FieldTypeOption[];\n}\n\n/** Copy shown before deleting a field. Strings are translated by the caller. */\nexport interface DeleteFieldConfirmation {\n title: string;\n description: string;\n /** When provided, confirmation requires this checkbox to be checked. */\n confirmationCheckboxLabel?: string;\n}\n\n/** Identifies the collection behind a table on BI events. */\nexport interface SchemaBiParams {\n tableId?: string;\n tableName?: string;\n tableType?: string;\n}\n\n/** What a caller passes. Only `collectionId` and `loadSchema` are required. */\nexport interface SchemaSourceInput<T> {\n collectionId: string;\n loadSchema: () => Promise<LoadedSchema<T>>;\n /** Sources for collections this one references, keyed by the referenced\n * collection id. A renderer resolves a reference field through the matching\n * entry — its `loadSchema` gives the referenced schema and `sourceFetchData`\n * queries the referenced items. Default: none. */\n references?: Record<string, SchemaSource<any>>;\n /** Lazy source lookup for a referenced collection that is not in `references`.\n * Is used when a reference field is created in the add field modal.\n * The returned source owns its own async schema/item loading. */\n getReferencedCollectionSource?: (\n collectionId: string,\n ) => SchemaSource<any> | undefined;\n paginationMode?: 'offset';\n /** Stable row identity. Default: `row[idField]`. */\n itemKey?: (item: T) => string;\n /** Row display label. Default: `row[displayField]`. */\n itemName?: (item: T) => string;\n /** Fields free-text search runs against. Default: `[displayField]`. */\n searchableFieldIds?: (schema: Schema) => string[];\n /** What the add/edit field modal shows. Default: no types, generic titles. */\n fieldModal?: FieldModalInput;\n /** Consumer-defined field types: how a field of that type renders, filters and\n * validates wherever it appears. A field with `type: 'CUSTOM'` resolves its\n * definition here by `customType`. The add/edit field modal never reads this\n * — see `fieldModal`. Default: none. */\n fieldTypes?: FieldTypeDefinition[];\n /** Overrides one existing field's type label, icons and collection-picker\n * label. Does not change its type, values or add-field options. */\n getFieldPresentation?: (field: Field) => FieldPresentation | undefined;\n /** Default: `schemaPermissions.createField`. */\n canAddFields?: (schema: Schema) => boolean;\n /** Default: `schemaPermissions.updateField`, except for system fields and\n * the id field. */\n canEditField?: (field: Field, schema: Schema) => boolean;\n /** Default: `schemaPermissions.deleteField`, except for system fields and\n * the id field. */\n canDeleteField?: (field: Field, schema: Schema) => boolean;\n /** Disables an otherwise available field action with this tooltip.\n * Undefined preserves its default state; denied actions stay hidden. */\n getFieldActionDisabledReason?: (\n field: Field,\n schema: Schema,\n action:\n | 'editField'\n | 'makePrimary'\n | 'duplicateField'\n | 'duplicateFieldWithContent'\n | 'delete',\n ) => string | undefined;\n /** Whether a field can become the primary field. When omitted, only\n * `SHORT_TEXT` and `LONG_TEXT` fields can. When set, its result replaces\n * that rule, so return `false` for non-text fields too. */\n canMakePrimary?: (field: Field, schema: Schema) => boolean;\n /** Resolved when deletion is requested. Undefined keeps the default dialog. */\n getDeleteFieldConfirmation?: (\n field: Field,\n schema: Schema,\n ) => DeleteFieldConfirmation | undefined;\n /** Permission defaults shown in the modal. Absent ⇒ no permissions section. */\n fieldPermissions?: FieldPermissions;\n /** Default: `false`. */\n supportsPii?: boolean;\n /** Allows changing PII on an existing supported field. Default: disabled.\n * Does not override `canEditField` or the field type's PII support. */\n canEditFieldPii?: (field: Field, schema: Schema) => boolean;\n /** The value of a field on an item. Default: `item[field.id]`. */\n getFieldValue?: (item: T, field: Field) => unknown;\n /** Writes a field's value on an item, returning the updated item.\n * Default: `{ ...item, [field.id]: value }`. */\n setFieldValue?: (item: T, field: Field, value: unknown) => T;\n}\n\n/** The resolved source: defaults filled, `loadSchema` memoized. */\nexport interface SchemaSource<T> {\n readonly collectionId: string;\n loadSchema: () => Promise<LoadedSchema<T>>;\n readonly paginationMode: 'offset';\n /** Stable row identity. */\n itemKey: (item: T) => string;\n /** Row display label. */\n itemName: (item: T) => string;\n /** Sources for referenced collections, keyed by referenced collection id. */\n readonly references: Record<string, SchemaSource<any>>;\n getReferencedCollectionSource?: (\n collectionId: string,\n ) => SchemaSource<any> | undefined;\n readonly fieldModal: {\n showFieldId?: boolean;\n text?: FieldModalText;\n loadReferenceableCollectionOptions?: FieldModalCollectionOptionsLoader;\n types: FieldTypeOption[];\n };\n readonly fieldTypes: FieldTypeDefinition[];\n getFieldPresentation?: (field: Field) => FieldPresentation | undefined;\n searchableFieldIds: (schema: Schema) => string[];\n canAddFields: (schema: Schema) => boolean;\n canEditField: (field: Field, schema: Schema) => boolean;\n canDeleteField: (field: Field, schema: Schema) => boolean;\n getFieldActionDisabledReason?: SchemaSourceInput<T>['getFieldActionDisabledReason'];\n canMakePrimary?: (field: Field, schema: Schema) => boolean;\n getDeleteFieldConfirmation?: (\n field: Field,\n schema: Schema,\n ) => DeleteFieldConfirmation | undefined;\n readonly fieldPermissions?: FieldPermissions;\n readonly supportsPii: boolean;\n canEditFieldPii?: (field: Field, schema: Schema) => boolean;\n /** The value of a field on an item. */\n getFieldValue: (item: T, field: Field) => unknown;\n /** Writes a field's value on an item, returning the updated item. */\n setFieldValue: (item: T, field: Field, value: unknown) => T;\n schemaParams: () => SchemaBiParams;\n /** Replaces the memoized schema returned by later `loadSchema()` calls.\n * No-op before the first successful load. */\n setLoadedSchema?: (schema: Schema) => void;\n}\n\ntype OffsetFind<T> = (\n query: OffsetQuery,\n options?: FindOptions,\n) => Promise<OffsetQueryResult<T>>;\n\n/** The collection fetch derived from a source: loads once, then queries the\n * backend's `find`.\n *\n * Free-text search covers the columns the page is showing: the table keeps\n * `query.columns` in sync with them, so the scope comes off the query rather\n * than being threaded in. Falls back to the source's own `searchableFieldIds`\n * before any columns are known (or with no table attached). */\nexport function sourceFetchData<T>(\n source: SchemaSource<T>,\n): (query: OffsetQuery) => Promise<OffsetQueryResult<T>> {\n return async (query) => {\n const { backend, schema } = await source.loadSchema();\n // `columns` is the visible-column list; `fields` is the projection, which a\n // source-driven table doesn't set.\n const visibleColumns = query.columns;\n return (backend.find as OffsetFind<T>)(query, {\n searchableFieldIds: visibleColumns?.length\n ? visibleColumns\n : source.searchableFieldIds(schema),\n });\n };\n}\n\n/** Fills source-neutral defaults over `input` and memoizes the load so the collection\n * query and the table columns share a single fetch. */\nexport function defineSchemaSource<T>(\n input: SchemaSourceInput<T>,\n): SchemaSource<T> {\n const {\n collectionId,\n paginationMode = 'offset',\n fieldModal = {},\n fieldTypes = [],\n fieldPermissions,\n supportsPii = false,\n references = {},\n getReferencedCollectionSource,\n } = input;\n\n let loaded: Promise<LoadedSchema<T>> | undefined;\n let resolved: LoadedSchema<T> | undefined;\n\n const loadSchema = () =>\n (loaded ??= input\n .loadSchema()\n .then((result) => {\n resolved = result;\n return result;\n })\n .catch((error) => {\n loaded = undefined;\n throw error;\n }));\n\n const setLoadedSchema = (schema: Schema) => {\n if (!resolved) {\n return;\n }\n resolved = { ...resolved, schema };\n loaded = Promise.resolve(resolved);\n };\n\n const searchableFieldIds =\n input.searchableFieldIds ?? ((s) => [s.displayField]);\n\n const itemKey =\n input.itemKey ??\n ((item) =>\n String(\n (item as Record<string, unknown>)[resolved?.schema.idField ?? '_id'] ??\n '',\n ));\n const itemName =\n input.itemName ??\n ((item) =>\n String(\n (item as Record<string, unknown>)[\n resolved?.schema.displayField ?? '_id'\n ] ?? '',\n ));\n const canAddFields =\n input.canAddFields ?? ((s) => s.schemaPermissions?.createField ?? false);\n const isLockedField = (field: Field, s: Schema) =>\n field.isSystem === true || field.id === s.idField;\n const canEditField =\n input.canEditField ??\n ((field, s) =>\n (s.schemaPermissions?.updateField ?? false) && !isLockedField(field, s));\n const canDeleteField =\n input.canDeleteField ??\n ((field, s) =>\n (s.schemaPermissions?.deleteField ?? false) && !isLockedField(field, s));\n const getFieldValue =\n input.getFieldValue ??\n ((item, field) => (item as Record<string, unknown>)[field.id]);\n const setFieldValue =\n input.setFieldValue ??\n ((item, field, value) => ({ ...item, [field.id]: value } as T));\n\n const schemaParams = (): SchemaBiParams => ({\n tableId: resolved?.schema.id ?? collectionId,\n tableName: resolved?.schema.name,\n tableType: resolved?.schema.type,\n });\n\n return {\n collectionId,\n loadSchema,\n paginationMode,\n itemKey,\n itemName,\n references,\n ...(getReferencedCollectionSource && { getReferencedCollectionSource }),\n fieldModal: {\n showFieldId: fieldModal.showFieldId,\n text: fieldModal.text,\n loadReferenceableCollectionOptions:\n fieldModal.loadReferenceableCollectionOptions,\n types: fieldModal.types ?? [],\n },\n fieldTypes,\n getFieldPresentation: input.getFieldPresentation,\n searchableFieldIds,\n canAddFields,\n canEditField,\n canDeleteField,\n getFieldActionDisabledReason: input.getFieldActionDisabledReason,\n canMakePrimary: input.canMakePrimary,\n getDeleteFieldConfirmation: input.getDeleteFieldConfirmation,\n fieldPermissions,\n supportsPii,\n canEditFieldPii: input.canEditFieldPii,\n getFieldValue,\n setFieldValue,\n schemaParams,\n setLoadedSchema,\n };\n}\n"],"mappings":";;;;;AAiBA;AACA;AACA;AACA;;AA6BA;;AAYA;;AAQA;;AAOA;;AA2EA;;AAkDA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASA,eAAeA,CAC7BC,MAAuB,EACgC;EACvD,OAAO,MAAOC,KAAK,IAAK;IACtB,MAAM;MAAEC,OAAO;MAAEC;IAAO,CAAC,GAAG,MAAMH,MAAM,CAACI,UAAU,CAAC,CAAC;IACrD;IACA;IACA,MAAMC,cAAc,GAAGJ,KAAK,CAACK,OAAO;IACpC,OAAQJ,OAAO,CAACK,IAAI,CAAmBN,KAAK,EAAE;MAC5CO,kBAAkB,EAAEH,cAAc,YAAdA,cAAc,CAAEI,MAAM,GACtCJ,cAAc,GACdL,MAAM,CAACQ,kBAAkB,CAACL,MAAM;IACtC,CAAC,CAAC;EACJ,CAAC;AACH;;AAEA;AACA;AACO,SAASO,kBAAkBA,CAChCC,KAA2B,EACV;EACjB,MAAM;IACJC,YAAY;IACZC,cAAc,GAAG,QAAQ;IACzBC,UAAU,GAAG,CAAC,CAAC;IACfC,UAAU,GAAG,EAAE;IACfC,gBAAgB;IAChBC,WAAW,GAAG,KAAK;IACnBC,UAAU,GAAG,CAAC,CAAC;IACfC;EACF,CAAC,GAAGR,KAAK;EAET,IAAIS,MAA4C;EAChD,IAAIC,QAAqC;EAEzC,MAAMjB,UAAU,GAAGA,CAAA,KAChBgB,MAAM,KAANA,MAAM,GAAKT,KAAK,CACdP,UAAU,CAAC,CAAC,CACZkB,IAAI,CAAEC,MAAM,IAAK;IAChBF,QAAQ,GAAGE,MAAM;IACjB,OAAOA,MAAM;EACf,CAAC,CAAC,CACDC,KAAK,CAAEC,KAAK,IAAK;IAChBL,MAAM,GAAGM,SAAS;IAClB,MAAMD,KAAK;EACb,CAAC,CAAC,CAA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