sf-plugin-data 0.0.0-stage → 0.1.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.
@@ -0,0 +1,848 @@
1
+ const fieldTypes = [
2
+ 'Number',
3
+ 'Text',
4
+ 'Date',
5
+ 'DateTime',
6
+ 'Url',
7
+ 'Phone',
8
+ 'Email',
9
+ 'Percent',
10
+ 'Boolean',
11
+ 'Currency',
12
+ 'ArrayOfFloats',
13
+ 'ArrayOfTexts',
14
+ ];
15
+ /** Payload-free local contract failure; never interpolate untrusted document values. */
16
+ export class DmoDocumentError extends Error {
17
+ constructor() {
18
+ super('Invalid or unsupported portable DMO document.');
19
+ this.name = 'DmoDocumentError';
20
+ }
21
+ }
22
+ const objectKeys = [
23
+ 'label',
24
+ 'description',
25
+ 'category',
26
+ 'eventDateTimeFieldName',
27
+ 'recordModifiedFieldName',
28
+ 'fields',
29
+ ];
30
+ const fieldKeys = [
31
+ 'name',
32
+ 'label',
33
+ 'description',
34
+ 'category',
35
+ 'dataType',
36
+ 'isPrimaryKey',
37
+ 'isDynamicLookup',
38
+ ];
39
+ const rawObjectConfiguration = ['name', 'dataSpaceName', ...objectKeys, 'creationType'];
40
+ const rawFieldConfiguration = [
41
+ 'category',
42
+ 'name',
43
+ 'label',
44
+ 'description',
45
+ 'type',
46
+ 'isPrimaryKey',
47
+ 'isDynamicLookup',
48
+ 'creationType',
49
+ 'keyQualifierName',
50
+ 'isDistinct',
51
+ 'usageTag',
52
+ ];
53
+ const rawObjectObservations = new Set([
54
+ 'id',
55
+ 'hasExternalDataLakeObjectMappings',
56
+ 'isEditable',
57
+ 'isEnabled',
58
+ 'isSegmentable',
59
+ ]);
60
+ /**
61
+ * Classify documented raw keys only; configuration still needs lossless adapter handling.
62
+ * @param {'object' | 'field'} level Raw response level.
63
+ * @param {string} key Response property name.
64
+ * @returns {'configuration' | 'observation' | 'unknown'} Unknown keys must block export.
65
+ */
66
+ export function classifyDmoRawField(level, key) {
67
+ if ((level === 'object' ? rawObjectConfiguration : rawFieldConfiguration).includes(key))
68
+ return 'configuration';
69
+ if (level === 'object' && rawObjectObservations.has(key))
70
+ return 'observation';
71
+ return 'unknown';
72
+ }
73
+ /**
74
+ * Fail closed with a payload-free diagnostic.
75
+ * @param {unknown} condition Required invariant.
76
+ */
77
+ function requireValid(condition) {
78
+ if (!condition)
79
+ throw new DmoDocumentError();
80
+ }
81
+ /**
82
+ * Check an ordinary JSON record without invoking accessors.
83
+ * @param {unknown} value Candidate record.
84
+ * @param {string[]} allowed Exact permitted keys.
85
+ * @returns {Record<string, unknown>} Checked record.
86
+ */
87
+ function record(value, allowed) {
88
+ requireValid(value && typeof value === 'object' && !Array.isArray(value));
89
+ requireValid(Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
90
+ requireValid(Reflect.ownKeys(value).every((key) => typeof key === 'string' && allowed.includes(key)));
91
+ const descriptors = Object.getOwnPropertyDescriptors(value);
92
+ requireValid(Object.values(descriptors).every((entry) => 'value' in entry && entry.enumerable));
93
+ return value;
94
+ }
95
+ /**
96
+ * Check a nonblank display label.
97
+ * @param {unknown} value Candidate label.
98
+ * @returns {boolean} Whether the label is nonblank.
99
+ */
100
+ function text(value) {
101
+ return typeof value === 'string' && value.trim().length > 0;
102
+ }
103
+ /**
104
+ * Check the initial non-namespaced custom API-name subset.
105
+ * @param {unknown} value Qualified API name.
106
+ * @param {string} suffix Required canonical suffix.
107
+ * @returns {boolean} Whether the name belongs to the supported subset.
108
+ */
109
+ function customName(value, suffix) {
110
+ if (typeof value !== 'string' || !value.endsWith(suffix))
111
+ return false;
112
+ const stem = value.slice(0, -suffix.length);
113
+ return /^[A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)*$/u.test(stem) && !/^ssot/iu.test(stem);
114
+ }
115
+ /**
116
+ * Validate the initial custom-schema subset, without coercion or an API-support claim.
117
+ * @param {unknown} value Parsed JSON document (not a raw org response).
118
+ * @returns {DmoDocument} The validated document; no projection or field removal occurs.
119
+ */
120
+ export function validateDmoDocument(value) {
121
+ const document = record(value, ['schemaVersion', 'kind', 'identity', 'spec']);
122
+ requireValid(document.schemaVersion === 1 && document.kind === 'dmo');
123
+ const identity = record(document.identity, ['dataSpace', 'apiName']);
124
+ requireValid(typeof identity.dataSpace === 'string' && /^[A-Za-z][A-Za-z0-9_]*$/u.test(identity.dataSpace));
125
+ requireValid(customName(identity.apiName, '__dlm'));
126
+ const spec = record(document.spec, objectKeys);
127
+ requireValid(text(spec.label));
128
+ requireValid(!('description' in spec) || typeof spec.description === 'string');
129
+ requireValid(['Profile', 'Other', 'Engagement'].includes(spec.category));
130
+ requireValid(Array.isArray(spec.fields) && spec.fields.length > 0);
131
+ const names = new Set();
132
+ let primaryKeys = 0;
133
+ for (const item of spec.fields) {
134
+ const field = record(item, fieldKeys);
135
+ requireValid(customName(field.name, '__c') && text(field.label));
136
+ requireValid(!('description' in field) || typeof field.description === 'string');
137
+ requireValid(fieldTypes.includes(field.dataType));
138
+ requireValid(!('category' in field) || typeof field.category === 'string');
139
+ requireValid(typeof field.isPrimaryKey === 'boolean' && typeof field.isDynamicLookup === 'boolean');
140
+ requireValid(!names.has(field.name.toLowerCase()));
141
+ names.add(field.name.toLowerCase());
142
+ if (field.isPrimaryKey)
143
+ primaryKeys++;
144
+ }
145
+ requireValid(primaryKeys === 1);
146
+ for (const key of ['eventDateTimeFieldName', 'recordModifiedFieldName']) {
147
+ if (key in spec) {
148
+ requireValid(spec.fields.some((item) => item.name === spec[key] && item.dataType === 'DateTime'));
149
+ }
150
+ }
151
+ requireValid(spec.category !== 'Engagement' || 'eventDateTimeFieldName' in spec);
152
+ return value;
153
+ }
154
+ /**
155
+ * Project custom fields while retaining every raw configuration value in an incomplete result.
156
+ * @param {unknown} value Raw custom DMO detail, not a list or a portable document.
157
+ * @returns {DmoFieldProjection} Diagnostic candidate only; relationship acquisition is still required.
158
+ */
159
+ export function projectDmoRawFields(value) {
160
+ const raw = record(value, [...rawObjectConfiguration, ...rawObjectObservations]);
161
+ requireValid(raw.creationType === 'Custom' && Array.isArray(raw.fields));
162
+ const configuration = {};
163
+ for (const [key, item] of Object.entries(raw)) {
164
+ if (key === 'fields')
165
+ continue;
166
+ requireValid(item === null || ['string', 'boolean'].includes(typeof item));
167
+ if (classifyDmoRawField('object', key) === 'configuration')
168
+ configuration[key] = item;
169
+ }
170
+ const fields = [];
171
+ const retained = [];
172
+ const blockers = ['RELATIONSHIPS_NOT_ACQUIRED'];
173
+ const names = new Set();
174
+ for (const item of raw.fields) {
175
+ const field = record(item, rawFieldConfiguration);
176
+ requireValid(customName(field.name, '__c') && !names.has(field.name.toLowerCase()));
177
+ names.add(field.name.toLowerCase());
178
+ requireValid(Object.values(field).every((entry) => entry === null || ['string', 'boolean'].includes(typeof entry)));
179
+ requireValid(['Custom', 'System'].includes(field.creationType));
180
+ retained.push({ ...field });
181
+ if (field.creationType === 'System') {
182
+ blockers.push('GENERATED_FIELD_REPLAY_UNVERIFIED');
183
+ continue;
184
+ }
185
+ const projected = {};
186
+ for (const key of ['name', 'label', 'description', 'category'])
187
+ if (key in field)
188
+ projected[key] = field[key];
189
+ projected.dataType = field.type;
190
+ // The documented response omits false flags; keep original presence in configuration.
191
+ projected.isPrimaryKey = field.isPrimaryKey ?? false;
192
+ projected.isDynamicLookup = field.isDynamicLookup ?? false;
193
+ requireValid(!('isPrimaryKey' in field) || typeof field.isPrimaryKey === 'boolean');
194
+ requireValid(!('isDynamicLookup' in field) || typeof field.isDynamicLookup === 'boolean');
195
+ fields.push(projected);
196
+ if (['keyQualifierName', 'isDistinct', 'usageTag'].some((key) => key in field))
197
+ blockers.push('FIELD_SEMANTICS_REPLAY_UNVERIFIED');
198
+ }
199
+ configuration.fields = retained;
200
+ const spec = { fields };
201
+ for (const key of objectKeys) {
202
+ if (key !== 'fields' && key in raw)
203
+ spec[key] = raw[key];
204
+ }
205
+ const categories = {
206
+ PROFILE: 'Profile',
207
+ OTHER: 'Other',
208
+ ENGAGEMENT: 'Engagement',
209
+ };
210
+ if (typeof spec.category === 'string' && Object.hasOwn(categories, spec.category))
211
+ spec.category = categories[spec.category];
212
+ const candidate = validateDmoDocument({
213
+ schemaVersion: 1,
214
+ kind: 'dmo',
215
+ identity: { dataSpace: raw.dataSpaceName, apiName: raw.name },
216
+ spec,
217
+ });
218
+ return { status: 'incomplete', blockers: [...new Set(blockers)], candidate, configuration };
219
+ }
220
+ /**
221
+ * Join common field semantics without qualifying object configuration or generated replay.
222
+ * @param {unknown} connectFields Complete Connect field collection.
223
+ * @param {unknown} metadataFields Complete Metadata field collection.
224
+ * @returns {DmoJoinedFields} Authored fields, exact qualifier bindings and unresolved replay semantics.
225
+ */
226
+ export function joinDmoConnectMetadataFields(connectFields, metadataFields) {
227
+ requireValid(Array.isArray(connectFields) && Array.isArray(metadataFields));
228
+ requireValid(connectFields.length === metadataFields.length && connectFields.length > 0);
229
+ const joined = new Map();
230
+ const references = new Map();
231
+ const blockers = new Set();
232
+ for (const item of metadataFields) {
233
+ const field = record(item, [
234
+ 'fullName',
235
+ 'label',
236
+ 'description',
237
+ 'length',
238
+ 'required',
239
+ 'type',
240
+ 'summaryFilterItems',
241
+ 'mktDataModelFieldAttributes',
242
+ ]);
243
+ requireValid(customName(field.fullName, '__c') && !joined.has(field.fullName));
244
+ requireValid(text(field.label) && fieldTypes.includes(field.type));
245
+ requireValid(!('description' in field) || typeof field.description === 'string');
246
+ requireValid(!('required' in field) || typeof field.required === 'boolean');
247
+ if (field.required === true)
248
+ blockers.add('FIELD_REQUIRED_REPLAY_UNVERIFIED');
249
+ if ('length' in field) {
250
+ requireValid(field.type === 'Text' && Number.isSafeInteger(field.length) && Number(field.length) > 0);
251
+ // Retain arbitrary storage lengths; the authored Connect input has no length property.
252
+ blockers.add('FIELD_LENGTH_REPLAY_UNVERIFIED');
253
+ }
254
+ requireValid(!('summaryFilterItems' in field) ||
255
+ (Array.isArray(field.summaryFilterItems) && field.summaryFilterItems.length === 0));
256
+ const detail = record(field.mktDataModelFieldAttributes, [
257
+ 'definitionCreationType',
258
+ 'isDynamicLookup',
259
+ 'labelOverride',
260
+ 'masterLabel',
261
+ 'primaryIndexOrder',
262
+ 'usageTag',
263
+ 'refAttrDeveloperName',
264
+ ]);
265
+ requireValid(['Custom', 'System'].includes(detail.definitionCreationType));
266
+ requireValid(!('isDynamicLookup' in detail) ||
267
+ ['true', 'false'].includes(detail.isDynamicLookup));
268
+ requireValid(!('primaryIndexOrder' in detail) || detail.primaryIndexOrder === '1');
269
+ requireValid(!('labelOverride' in detail) ||
270
+ (text(detail.labelOverride) && detail.labelOverride.length <= 255));
271
+ // Keep base/master agreement as a narrow qualification, independent of display override.
272
+ requireValid(!('masterLabel' in detail) || detail.masterLabel === field.label);
273
+ requireValid(!('usageTag' in detail) || ['None', 'KeyQualifier'].includes(detail.usageTag));
274
+ if ('refAttrDeveloperName' in detail) {
275
+ requireValid(text(detail.refAttrDeveloperName) && !references.has(detail.refAttrDeveloperName));
276
+ requireValid(detail.definitionCreationType === 'System' && detail.usageTag === 'KeyQualifier');
277
+ references.set(detail.refAttrDeveloperName, field.fullName);
278
+ }
279
+ else
280
+ requireValid(detail.usageTag !== 'KeyQualifier');
281
+ joined.set(field.fullName, { field, detail });
282
+ }
283
+ const fields = [];
284
+ const qualifierBindings = [];
285
+ const usedReferences = new Set();
286
+ const names = new Set();
287
+ for (const item of connectFields) {
288
+ const field = record(item, rawFieldConfiguration);
289
+ requireValid(customName(field.name, '__c') && !names.has(field.name.toLowerCase()));
290
+ names.add(field.name.toLowerCase());
291
+ const match = joined.get(field.name);
292
+ requireValid(match);
293
+ joined.delete(field.name);
294
+ const { detail } = match;
295
+ const effectiveLabel = 'labelOverride' in detail ? detail.labelOverride : match.field.label;
296
+ requireValid(field.label === effectiveLabel && field.type === match.field.type);
297
+ requireValid(field.creationType === detail.definitionCreationType);
298
+ requireValid(!('description' in field) || typeof field.description === 'string');
299
+ requireValid(!('category' in field) || typeof field.category === 'string');
300
+ requireValid(!('description' in match.field) || match.field.description === field.description);
301
+ requireValid(!('usageTag' in field) || ['None', 'KeyQualifier'].includes(field.usageTag));
302
+ requireValid(!('usageTag' in field && 'usageTag' in detail) || field.usageTag === detail.usageTag);
303
+ requireValid(!('isDistinct' in field) || typeof field.isDistinct === 'boolean');
304
+ if (field.isDistinct === true)
305
+ blockers.add('FIELD_DISTINCT_REPLAY_UNVERIFIED');
306
+ const primary = detail.primaryIndexOrder === '1';
307
+ requireValid(!('isPrimaryKey' in field) || field.isPrimaryKey === primary);
308
+ requireValid(!('isDynamicLookup' in field) || typeof field.isDynamicLookup === 'boolean');
309
+ requireValid(!('isDynamicLookup' in field && 'isDynamicLookup' in detail) ||
310
+ field.isDynamicLookup === (detail.isDynamicLookup === 'true'));
311
+ // A supplied source may designate dynamic lookup; absence in both is not evidence of false.
312
+ const dynamic = 'isDynamicLookup' in detail ? detail.isDynamicLookup === 'true' : field.isDynamicLookup;
313
+ requireValid(typeof dynamic === 'boolean');
314
+ if (field.creationType === 'System') {
315
+ requireValid(!primary && dynamic === false && !('keyQualifierName' in field));
316
+ if ('refAttrDeveloperName' in detail) {
317
+ requireValid(field.type === 'Text' && field.usageTag === 'KeyQualifier');
318
+ blockers.add('GENERATED_QUALIFIER_REPLAY_UNVERIFIED');
319
+ }
320
+ else {
321
+ requireValid(!('usageTag' in field) || field.usageTag === 'None');
322
+ blockers.add('GENERATED_FIELD_REPLAY_UNVERIFIED');
323
+ }
324
+ if ('description' in field || 'category' in field || field.isDistinct === true)
325
+ blockers.add('GENERATED_FIELD_SEMANTICS_REPLAY_UNVERIFIED');
326
+ continue;
327
+ }
328
+ requireValid(!('refAttrDeveloperName' in detail));
329
+ requireValid(!('usageTag' in field) || field.usageTag === 'None');
330
+ if ('keyQualifierName' in field) {
331
+ requireValid(text(field.keyQualifierName) && !usedReferences.has(field.keyQualifierName));
332
+ const qualifierFieldName = references.get(field.keyQualifierName);
333
+ requireValid(qualifierFieldName);
334
+ usedReferences.add(field.keyQualifierName);
335
+ qualifierBindings.push({ fieldName: field.name, qualifierFieldName });
336
+ }
337
+ fields.push({
338
+ name: field.name,
339
+ label: field.label,
340
+ dataType: field.type,
341
+ ...('description' in field ? { description: field.description } : {}),
342
+ ...('category' in field ? { category: field.category } : {}),
343
+ isPrimaryKey: primary,
344
+ isDynamicLookup: dynamic,
345
+ });
346
+ }
347
+ requireValid(joined.size === 0 && references.size === usedReferences.size);
348
+ requireValid(fields.filter((field) => field.isPrimaryKey).length === 1);
349
+ return {
350
+ fields,
351
+ qualifierBindings,
352
+ blockers: [...blockers],
353
+ expectations: structuredClone({ connect: connectFields, metadata: metadataFields }),
354
+ };
355
+ }
356
+ /**
357
+ * Recognize the evidenced generated recipe, independently of authored collection size.
358
+ * @param {DmoJoinedFields} joined Validated complete field join.
359
+ * @returns {boolean} Whether generated identities, defaults and the primary qualifier match.
360
+ */
361
+ function hasOtherGeneratedRecipe(joined) {
362
+ const primary = joined.fields.find((field) => field.isPrimaryKey);
363
+ if (primary.dataType !== 'Text' || primary.isDynamicLookup)
364
+ return false;
365
+ const reference = `KQ_${primary.name.slice(0, -3)}`;
366
+ const expected = new Map([
367
+ ['DataSource__c', 'Data Source'],
368
+ ['DataSourceObject__c', 'Data Source Object'],
369
+ ['InternalOrganization__c', 'Internal Organization'],
370
+ [`${reference}__c`, `Key Qualifier ${primary.label}`],
371
+ ]);
372
+ if (joined.qualifierBindings.length !== 1 ||
373
+ joined.qualifierBindings[0].fieldName !== primary.name ||
374
+ joined.qualifierBindings[0].qualifierFieldName !== `${reference}__c`)
375
+ return false;
376
+ for (const field of joined.expectations.connect) {
377
+ if (field.creationType !== 'System')
378
+ continue;
379
+ if (expected.get(field.name) !== field.label ||
380
+ field.type !== 'Text' ||
381
+ field.isDistinct !== false ||
382
+ 'description' in field ||
383
+ 'category' in field)
384
+ return false;
385
+ expected.delete(field.name);
386
+ const meta = joined.expectations.metadata.find((item) => item.fullName === field.name);
387
+ const detail = meta.mktDataModelFieldAttributes;
388
+ if (meta.length !== 60 ||
389
+ meta.required !== false ||
390
+ 'description' in meta ||
391
+ detail.isDynamicLookup !== 'false' ||
392
+ detail.labelOverride !== field.label ||
393
+ detail.masterLabel !== field.label ||
394
+ detail.usageTag !== field.usageTag ||
395
+ !Array.isArray(meta.summaryFilterItems) ||
396
+ meta.summaryFilterItems.length > 0 ||
397
+ (field.name === `${reference}__c`
398
+ ? detail.refAttrDeveloperName !== reference || field.usageTag !== 'KeyQualifier'
399
+ : field.usageTag !== 'None'))
400
+ return false;
401
+ }
402
+ return expected.size === 0;
403
+ }
404
+ /**
405
+ * Compose exact common object joins and qualify only evidenced replay semantics.
406
+ * @param {unknown} connect Complete Connect object detail.
407
+ * @param {unknown} metadata Exact matching Metadata CustomObject.
408
+ * @param {unknown} relationships Complete separately acquired relationship inventory.
409
+ * @returns {DmoCommonProjection} Qualified authored candidate or precise incomplete diagnostics.
410
+ */
411
+ export function projectCommonDmoConnectMetadata(connect, metadata, relationships) {
412
+ const raw = record(connect, [...rawObjectConfiguration, ...rawObjectObservations]);
413
+ const collections = [
414
+ 'actionOverrides',
415
+ 'businessProcesses',
416
+ 'compactLayouts',
417
+ 'fieldSets',
418
+ 'indexes',
419
+ 'listViews',
420
+ 'profileSearchLayouts',
421
+ 'recordTypes',
422
+ 'sharingReasons',
423
+ 'sharingRecalculations',
424
+ 'validationRules',
425
+ 'webLinks',
426
+ ];
427
+ const meta = record(metadata, [
428
+ 'fullName',
429
+ 'label',
430
+ 'fields',
431
+ 'mktDataModelAttributes',
432
+ ...collections,
433
+ ]);
434
+ requireValid(customName(raw.name, '__dlm') && meta.fullName === raw.name && meta.label === raw.label);
435
+ requireValid(raw.creationType === 'Custom' && raw.dataSpaceName === 'default');
436
+ requireValid(text(raw.label) && (!('description' in raw) || typeof raw.description === 'string'));
437
+ requireValid(!('id' in raw) || text(raw.id));
438
+ const attributes = record(meta.mktDataModelAttributes, [
439
+ 'creationType',
440
+ 'dataModelTaxonomy',
441
+ 'dataSpaceName',
442
+ 'description',
443
+ 'isEnabled',
444
+ 'isSegmentable',
445
+ 'isUsedForMetrics',
446
+ 'labelOverride',
447
+ 'masterLabel',
448
+ 'objectCategory',
449
+ ]);
450
+ requireValid(attributes.creationType === 'Custom' && attributes.dataSpaceName === raw.dataSpaceName);
451
+ requireValid(attributes.description === raw.description &&
452
+ attributes.labelOverride === raw.label &&
453
+ attributes.masterLabel === raw.label);
454
+ requireValid(text(attributes.dataModelTaxonomy) && text(attributes.objectCategory));
455
+ requireValid(typeof raw.category === 'string' && ['OTHER', 'PROFILE', 'ENGAGEMENT'].includes(raw.category));
456
+ const category = { OTHER: 'Other', PROFILE: 'Profile', ENGAGEMENT: 'Engagement' }[raw.category];
457
+ requireValid(category);
458
+ const blockers = new Set();
459
+ if (attributes.dataModelTaxonomy !== 'Salesforce_SFDCReferenceModel_0_93')
460
+ blockers.add('OBJECT_TAXONOMY_REPLAY_UNVERIFIED');
461
+ if (category !== 'Other' ||
462
+ attributes.objectCategory !== 'Salesforce_SFDCReferenceModel_0_93.Related')
463
+ blockers.add('OBJECT_CATEGORY_TAXONOMY_REPLAY_UNVERIFIED');
464
+ for (const key of ['isEnabled', 'isSegmentable']) {
465
+ requireValid(typeof raw[key] === 'boolean' && ['true', 'false'].includes(attributes[key]));
466
+ requireValid(raw[key] === (attributes[key] === 'true'));
467
+ if (raw[key])
468
+ blockers.add('OBJECT_EXECUTION_REPLAY_UNVERIFIED');
469
+ }
470
+ requireValid(['true', 'false'].includes(attributes.isUsedForMetrics));
471
+ if (attributes.isUsedForMetrics === 'true')
472
+ blockers.add('OBJECT_METRICS_REPLAY_UNVERIFIED');
473
+ requireValid(typeof raw.isEditable === 'boolean' &&
474
+ typeof raw.hasExternalDataLakeObjectMappings === 'boolean');
475
+ if (!raw.isEditable || raw.hasExternalDataLakeObjectMappings)
476
+ blockers.add('OBJECT_MAPPING_REPLAY_UNVERIFIED');
477
+ for (const key of collections) {
478
+ // Only empty auxiliary collections have an established semantics contract.
479
+ requireValid(Array.isArray(meta[key]) && meta[key].length === 0);
480
+ }
481
+ requireValid(Array.isArray(relationships));
482
+ for (const item of relationships) {
483
+ const relation = record(item, [
484
+ 'cardinality',
485
+ 'creationType',
486
+ 'id',
487
+ 'name',
488
+ 'owner',
489
+ 'sourceField',
490
+ 'sourceObject',
491
+ 'status',
492
+ 'targetField',
493
+ 'targetObject',
494
+ ]);
495
+ for (const [key, value] of Object.entries(relation)) {
496
+ if (['sourceObject', 'targetObject', 'sourceField', 'targetField'].includes(key)) {
497
+ const endpoint = record(value, ['name', 'label', 'type', 'keyQualifierField']);
498
+ requireValid(Object.values(endpoint).every((entry) => entry === null || typeof entry === 'string'));
499
+ }
500
+ else
501
+ requireValid(value === null || typeof value === 'string');
502
+ }
503
+ const source = relation.sourceObject;
504
+ const target = relation.targetObject;
505
+ requireValid(text(source?.name) &&
506
+ text(target?.name) &&
507
+ (source?.name === raw.name || target?.name === raw.name));
508
+ }
509
+ if (relationships.length > 0)
510
+ blockers.add('RELATIONSHIP_REPLAY_UNSUPPORTED');
511
+ const joined = joinDmoConnectMetadataFields(raw.fields, meta.fields);
512
+ const recipe = category === 'Other' && hasOtherGeneratedRecipe(joined);
513
+ if (!recipe)
514
+ blockers.add('GENERATED_RECIPE_REPLAY_UNVERIFIED');
515
+ for (const blocker of joined.blockers) {
516
+ if (recipe &&
517
+ [
518
+ 'GENERATED_FIELD_REPLAY_UNVERIFIED',
519
+ 'GENERATED_QUALIFIER_REPLAY_UNVERIFIED',
520
+ 'FIELD_LENGTH_REPLAY_UNVERIFIED',
521
+ ].includes(blocker))
522
+ continue;
523
+ blockers.add(blocker);
524
+ }
525
+ if (recipe &&
526
+ joined.expectations.metadata.some((field) => 'length' in field && field.length !== 60))
527
+ blockers.add('FIELD_LENGTH_REPLAY_UNVERIFIED');
528
+ const spec = { label: raw.label, category, fields: joined.fields };
529
+ if ('description' in raw)
530
+ spec.description = raw.description;
531
+ for (const key of ['eventDateTimeFieldName', 'recordModifiedFieldName']) {
532
+ if (!(key in raw))
533
+ continue;
534
+ requireValid(joined.fields.some((field) => field.name === raw[key] && field.dataType === 'DateTime'));
535
+ spec[key] = raw[key];
536
+ }
537
+ const missingEvent = category === 'Engagement' && !('eventDateTimeFieldName' in spec);
538
+ if (missingEvent)
539
+ blockers.add('ENGAGEMENT_EVENT_DESIGNATION_UNAVAILABLE');
540
+ const candidate = missingEvent
541
+ ? undefined
542
+ : validateDmoDocument({
543
+ schemaVersion: 1,
544
+ kind: 'dmo',
545
+ identity: { dataSpace: raw.dataSpaceName, apiName: raw.name },
546
+ spec,
547
+ });
548
+ return {
549
+ status: blockers.size === 0 ? 'projected' : 'incomplete',
550
+ blockers: [...blockers],
551
+ ...(candidate ? { candidate } : {}),
552
+ createIdentity: { status: 'verified', name: raw.name.slice(0, -5), sourceApiName: raw.name },
553
+ qualifierBindings: joined.qualifierBindings,
554
+ expectations: structuredClone({ connect: raw, metadata: meta, relationships }),
555
+ };
556
+ }
557
+ /**
558
+ * Join the proven relationship-free Other shape and invert its documented custom DMO suffix.
559
+ * @param {unknown} connect Connect DMO detail.
560
+ * @param {unknown} metadata Matching Metadata API CustomObject.
561
+ * @param {unknown} relationships Complete separately acquired relationship inventory.
562
+ * @returns {DmoConnectMetadataProjection} Offline projection, verified create identity and exact readback expectations.
563
+ */
564
+ export function projectDmoConnectMetadata(connect, metadata, relationships) {
565
+ requireValid(Array.isArray(relationships) && relationships.length === 0);
566
+ const raw = record(connect, [...rawObjectConfiguration, ...rawObjectObservations]);
567
+ const emptyCollections = [
568
+ 'actionOverrides',
569
+ 'businessProcesses',
570
+ 'compactLayouts',
571
+ 'fieldSets',
572
+ 'indexes',
573
+ 'listViews',
574
+ 'profileSearchLayouts',
575
+ 'recordTypes',
576
+ 'sharingReasons',
577
+ 'sharingRecalculations',
578
+ 'validationRules',
579
+ 'webLinks',
580
+ ];
581
+ const meta = record(metadata, [
582
+ 'fullName',
583
+ 'fields',
584
+ 'label',
585
+ 'mktDataModelAttributes',
586
+ ...emptyCollections,
587
+ ]);
588
+ requireValid(raw.category === 'OTHER' && raw.creationType === 'Custom');
589
+ requireValid(!('eventDateTimeFieldName' in raw) && !('recordModifiedFieldName' in raw));
590
+ requireValid(meta.fullName === raw.name && meta.label === raw.label);
591
+ for (const key of emptyCollections)
592
+ requireValid(Array.isArray(meta[key]) && meta[key].length === 0);
593
+ const attributes = record(meta.mktDataModelAttributes, [
594
+ 'creationType',
595
+ 'dataModelTaxonomy',
596
+ 'dataSpaceName',
597
+ 'description',
598
+ 'isEnabled',
599
+ 'isSegmentable',
600
+ 'isUsedForMetrics',
601
+ 'labelOverride',
602
+ 'masterLabel',
603
+ 'objectCategory',
604
+ ]);
605
+ requireValid(attributes.creationType === 'Custom' && attributes.dataSpaceName === raw.dataSpaceName);
606
+ requireValid(attributes.description === raw.description);
607
+ requireValid(attributes.labelOverride === raw.label && attributes.masterLabel === raw.label);
608
+ requireValid(attributes.dataModelTaxonomy === 'Salesforce_SFDCReferenceModel_0_93');
609
+ requireValid(attributes.objectCategory === 'Salesforce_SFDCReferenceModel_0_93.Related');
610
+ requireValid(attributes.isUsedForMetrics === 'false');
611
+ for (const key of ['isEnabled', 'isSegmentable'])
612
+ requireValid(raw[key] === false && attributes[key] === 'false');
613
+ requireValid(raw.hasExternalDataLakeObjectMappings === false && raw.isEditable === true);
614
+ requireValid(Array.isArray(raw.fields) && raw.fields.length === 6);
615
+ requireValid(Array.isArray(meta.fields) && meta.fields.length === raw.fields.length);
616
+ const joined = new Map();
617
+ const references = new Map();
618
+ for (const item of meta.fields) {
619
+ const field = record(item, [
620
+ 'fullName',
621
+ 'label',
622
+ 'length',
623
+ 'required',
624
+ 'type',
625
+ 'summaryFilterItems',
626
+ 'mktDataModelFieldAttributes',
627
+ ]);
628
+ requireValid(customName(field.fullName, '__c') && !joined.has(field.fullName));
629
+ requireValid(field.required === false);
630
+ requireValid(Array.isArray(field.summaryFilterItems) && field.summaryFilterItems.length === 0);
631
+ requireValid(field.type === 'Text'
632
+ ? field.length === 60
633
+ : field.type === 'DateTime' && !('length' in field));
634
+ const detail = record(field.mktDataModelFieldAttributes, [
635
+ 'definitionCreationType',
636
+ 'isDynamicLookup',
637
+ 'labelOverride',
638
+ 'masterLabel',
639
+ 'primaryIndexOrder',
640
+ 'usageTag',
641
+ 'refAttrDeveloperName',
642
+ ]);
643
+ requireValid(detail.isDynamicLookup === 'false');
644
+ requireValid(!('primaryIndexOrder' in detail) || detail.primaryIndexOrder === '1');
645
+ requireValid(detail.labelOverride === field.label && detail.masterLabel === field.label);
646
+ if ('refAttrDeveloperName' in detail) {
647
+ requireValid(text(detail.refAttrDeveloperName) && !references.has(detail.refAttrDeveloperName));
648
+ requireValid(detail.definitionCreationType === 'System' && detail.usageTag === 'KeyQualifier');
649
+ references.set(detail.refAttrDeveloperName, field.fullName);
650
+ }
651
+ joined.set(field.fullName, { field, attributes: detail });
652
+ }
653
+ const qualifierBindings = [];
654
+ let generated = 0;
655
+ const checkedFields = raw.fields.map((item) => {
656
+ const field = record(item, rawFieldConfiguration);
657
+ requireValid(typeof field.name === 'string');
658
+ const match = joined.get(field.name);
659
+ requireValid(match);
660
+ joined.delete(field.name);
661
+ requireValid(field.label === match.field.label && field.type === match.field.type);
662
+ requireValid(field.creationType === match.attributes.definitionCreationType);
663
+ requireValid(field.usageTag === match.attributes.usageTag && field.isDistinct === false);
664
+ requireValid(!('description' in field) && !('category' in field));
665
+ const primary = match.attributes.primaryIndexOrder === '1';
666
+ requireValid(!('isPrimaryKey' in field) || field.isPrimaryKey === primary);
667
+ requireValid(!('isDynamicLookup' in field) || field.isDynamicLookup === false);
668
+ if (field.creationType === 'Custom') {
669
+ requireValid(field.usageTag === 'None');
670
+ requireValid(primary ? field.type === 'Text' : field.type === 'DateTime');
671
+ if (primary) {
672
+ requireValid(typeof field.keyQualifierName === 'string');
673
+ const qualifierFieldName = references.get(field.keyQualifierName);
674
+ requireValid(qualifierFieldName);
675
+ qualifierBindings.push({ fieldName: field.name, qualifierFieldName });
676
+ }
677
+ else
678
+ requireValid(!('keyQualifierName' in field));
679
+ requireValid(!('refAttrDeveloperName' in match.attributes));
680
+ }
681
+ else {
682
+ requireValid(field.creationType === 'System' && field.type === 'Text' && !primary);
683
+ requireValid(!('keyQualifierName' in field));
684
+ requireValid(field.usageTag === ('refAttrDeveloperName' in match.attributes ? 'KeyQualifier' : 'None'));
685
+ generated++;
686
+ }
687
+ return { ...field, isPrimaryKey: primary, isDynamicLookup: false };
688
+ });
689
+ requireValid(joined.size === 0 && generated === 4 && references.size === 1 && qualifierBindings.length === 1);
690
+ const { candidate } = projectDmoRawFields({ ...raw, fields: checkedFields });
691
+ requireValid(candidate.spec.fields.length === 2);
692
+ // Validation above admits JSON scalars/records only; retain all presence and generated metadata.
693
+ const expectations = structuredClone({ connect: raw, metadata: meta });
694
+ return {
695
+ status: 'projected',
696
+ blockers: [],
697
+ candidate,
698
+ // Candidate validation proves the non-namespaced base; remove only the terminal suffix.
699
+ createIdentity: {
700
+ status: 'verified',
701
+ name: candidate.identity.apiName.slice(0, -'__dlm'.length),
702
+ sourceApiName: candidate.identity.apiName,
703
+ },
704
+ qualifierBindings,
705
+ expectations,
706
+ };
707
+ }
708
+ /**
709
+ * Map authored custom schema to the documented Connect input, not a raw response.
710
+ * @param {unknown} value Parsed authored document, never a runtime projection.
711
+ * @param {unknown} targetDataSpace Explicit target binding; this slice supports default only.
712
+ * @returns {DmoCreateRequest} Fresh allowlisted request, without a runtime acceptance claim.
713
+ */
714
+ export function buildDmoCreateRequestFromDocument(value, targetDataSpace) {
715
+ const document = validateDmoDocument(value);
716
+ if (document.identity.dataSpace !== 'default')
717
+ throw new Error('Unsupported DMO create mapping: identity.dataSpace must be default.');
718
+ if (targetDataSpace !== 'default')
719
+ throw new Error('Unsupported DMO create mapping: targetDataSpace must be explicit default.');
720
+ const { spec } = document;
721
+ return {
722
+ // Invert only the validated terminal object suffix; preserve authored field names.
723
+ name: document.identity.apiName.slice(0, -'__dlm'.length),
724
+ label: spec.label,
725
+ ...('description' in spec ? { description: spec.description } : {}),
726
+ dataSpaceName: targetDataSpace,
727
+ category: spec.category,
728
+ ...('eventDateTimeFieldName' in spec
729
+ ? { eventDateTimeFieldName: spec.eventDateTimeFieldName }
730
+ : {}),
731
+ ...('recordModifiedFieldName' in spec
732
+ ? { recordModifiedFieldName: spec.recordModifiedFieldName }
733
+ : {}),
734
+ fields: spec.fields.map((field) => ({
735
+ name: field.name,
736
+ label: field.label,
737
+ dataType: field.dataType,
738
+ ...('description' in field ? { description: field.description } : {}),
739
+ ...('category' in field ? { category: field.category } : {}),
740
+ isPrimaryKey: field.isPrimaryKey,
741
+ isDynamicLookup: field.isDynamicLookup,
742
+ })),
743
+ };
744
+ }
745
+ /**
746
+ * Construct only the evidenced default-space Other request, rechecking the complete projection.
747
+ * @param {unknown} value Joined projection, including its independent readback expectations.
748
+ * @param {unknown} targetDataSpace Explicit target binding; only default has replay evidence.
749
+ * @returns {OtherDmoCreateRequest} Fresh authored-only request; no transport or generated-field replay.
750
+ */
751
+ export function buildOtherDmoCreateRequest(value, targetDataSpace) {
752
+ requireValid(targetDataSpace === 'default');
753
+ const projection = record(value, [
754
+ 'status',
755
+ 'blockers',
756
+ 'candidate',
757
+ 'createIdentity',
758
+ 'qualifierBindings',
759
+ 'expectations',
760
+ ]);
761
+ requireValid(projection.status === 'projected');
762
+ requireValid(Array.isArray(projection.blockers) && projection.blockers.length === 0);
763
+ const expectations = record(projection.expectations, ['connect', 'metadata']);
764
+ // Reapply every strict join/profile check; a portable candidate alone is not authority.
765
+ const checked = projectDmoConnectMetadata(expectations.connect, expectations.metadata, []);
766
+ requireValid(checked.candidate.identity.dataSpace === 'default');
767
+ requireValid(serializeDmoDocument(projection.candidate) === serializeDmoDocument(checked.candidate));
768
+ const identity = record(projection.createIdentity, ['status', 'name', 'sourceApiName']);
769
+ for (const key of ['status', 'name', 'sourceApiName'])
770
+ requireValid(identity[key] === checked.createIdentity[key]);
771
+ requireValid(Array.isArray(projection.qualifierBindings) && projection.qualifierBindings.length === 1);
772
+ const binding = record(projection.qualifierBindings[0], ['fieldName', 'qualifierFieldName']);
773
+ requireValid(binding.fieldName === checked.qualifierBindings[0].fieldName);
774
+ requireValid(binding.qualifierFieldName === checked.qualifierBindings[0].qualifierFieldName);
775
+ const { spec } = checked.candidate;
776
+ return {
777
+ name: checked.createIdentity.name,
778
+ label: spec.label,
779
+ ...('description' in spec ? { description: spec.description } : {}),
780
+ dataSpaceName: targetDataSpace,
781
+ category: 'Other',
782
+ // API 65 replay preserves these exact authored __c names; do not invert them.
783
+ fields: spec.fields.map(({ name, label, dataType, isPrimaryKey, isDynamicLookup }) => ({
784
+ name,
785
+ label,
786
+ dataType,
787
+ isPrimaryKey,
788
+ isDynamicLookup,
789
+ })),
790
+ };
791
+ }
792
+ /**
793
+ * Map an authored document independently of internal source-readback expectations.
794
+ * @param {unknown} value Parsed authored document, never a runtime projection.
795
+ * @param {unknown} targetDataSpace Explicit target binding; only default has replay evidence.
796
+ * @returns {OtherDmoCreateRequest} Fresh request for the evidenced two-field Other subset.
797
+ */
798
+ export function buildOtherDmoCreateRequestFromDocument(value, targetDataSpace) {
799
+ const document = validateDmoDocument(value);
800
+ requireValid(document.identity.dataSpace === 'default' && targetDataSpace === 'default');
801
+ const { spec } = document;
802
+ requireValid(spec.category === 'Other' && spec.fields.length === 2);
803
+ requireValid(!('eventDateTimeFieldName' in spec) && !('recordModifiedFieldName' in spec));
804
+ for (const field of spec.fields) {
805
+ requireValid(!('description' in field) && !('category' in field));
806
+ requireValid(field.isDynamicLookup === false);
807
+ requireValid(field.isPrimaryKey ? field.dataType === 'Text' : field.dataType === 'DateTime');
808
+ }
809
+ return {
810
+ // Document validation proves the local base; remove only the terminal suffix.
811
+ name: document.identity.apiName.slice(0, -'__dlm'.length),
812
+ label: spec.label,
813
+ ...('description' in spec ? { description: spec.description } : {}),
814
+ dataSpaceName: targetDataSpace,
815
+ category: 'Other',
816
+ fields: spec.fields.map(({ name, label, dataType, isPrimaryKey, isDynamicLookup }) => ({
817
+ name,
818
+ label,
819
+ dataType,
820
+ isPrimaryKey,
821
+ isDynamicLookup,
822
+ })),
823
+ };
824
+ }
825
+ /**
826
+ * Sort only object keys; all arrays and string contents retain their order.
827
+ * @param {unknown} value Validated JSON value.
828
+ * @returns {unknown} Canonical JSON value.
829
+ */
830
+ function stable(value) {
831
+ if (Array.isArray(value))
832
+ return value.map((item) => stable(item));
833
+ if (value && typeof value === 'object') {
834
+ return Object.fromEntries(Object.entries(value)
835
+ // eslint-disable-next-line unicorn/no-array-sort -- Sort a fresh entries array within the existing TypeScript library target.
836
+ .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
837
+ .map(([key, item]) => [key, stable(item)]));
838
+ }
839
+ return value;
840
+ }
841
+ /**
842
+ * Serialize validated DMO JSON with sorted object keys, original arrays and a final LF.
843
+ * @param {unknown} value Parsed portable document.
844
+ * @returns {string} Deterministic JSON text; UTF-8 encoding belongs to the future writer.
845
+ */
846
+ export function serializeDmoDocument(value) {
847
+ return `${JSON.stringify(stable(validateDmoDocument(value)), undefined, 2)}\n`;
848
+ }