The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
import { isNonEmptyString } from '@sniptt/guards';
import { validate as uuidValidate, version as uuidVersion } from 'uuid';
import {
MINIMUM_UNIVERSAL_IDENTIFIER_UUID_VERSION,
type Manifest,
type PageLayoutManifest,
type PageLayoutTabManifest,
type PageLayoutWidgetManifest,
isValidUniversalIdentifier,
normalizePageLayoutTabManifest,
} from 'twenty-shared/application';
import {
FieldMetadataType,
GRAPH_WIDGET_CONFIGURATION_TYPES,
type GraphWidgetConfigurationType,
type PageLayoutWidgetUniversalConfiguration,
RelationType,
} from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import {
getDuplicateValues,
type ManifestField,
isRelationFieldManifest,
} from '@/app/manifest/utils/manifest-validation-helpers';
import { getFrontComponentWidgetAvailabilityWarnings } from '@/app/manifest/utils/get-front-component-widget-availability-warnings';
import { getPageLayoutDeprecationWarnings } from '@/app/manifest/utils/get-page-layout-deprecation-warnings';
import { getUnresolvedLabelIdentifierWarnings } from '@/app/manifest/utils/get-unresolved-label-identifier-warnings';
import { validateSettingsMenuItemSlugs } from '@/app/manifest/utils/validate-settings-menu-item-slugs';
import { validateTimelineActivityTypes } from '@/app/manifest/utils/validate-timeline-activity-types';
import { validateValidationRules } from '@/app/manifest/utils/validate-validation-rules';
const VALID_RELATION_TYPES: string[] = [
RelationType.MANY_TO_ONE,
RelationType.ONE_TO_MANY,
];
const RAW_AGGREGATE_FIELD_METADATA_ID_KEY = 'aggregateFieldMetadataId';
type GraphPageLayoutWidgetUniversalConfiguration = Extract<
PageLayoutWidgetUniversalConfiguration,
{ configurationType: GraphWidgetConfigurationType }
>;
const isGraphWidgetConfiguration = (
configuration: PageLayoutWidgetUniversalConfiguration | null | undefined,
): configuration is GraphPageLayoutWidgetUniversalConfiguration =>
isDefined(configuration) &&
GRAPH_WIDGET_CONFIGURATION_TYPES.some(
(configurationType) =>
configurationType === configuration.configurationType,
);
const findUniversalIdentifiers = (obj: object): string[] => {
const universalIdentifiers: string[] = [];
if (!obj) {
return [];
}
for (const [key, val] of Object.entries(obj)) {
if (key === 'universalIdentifier' && typeof val === 'string') {
universalIdentifiers.push(val);
}
if (
key === 'postInstallLogicFunction' ||
key === 'preInstallLogicFunction' ||
key === 'uninstallLogicFunction' ||
key === 'healthCheckLogicFunction' ||
key === 'identifyAccountLogicFunction' ||
key === 'authorizeLogicFunction' ||
key === 'callbackLogicFunction' ||
key === 'onConnectLogicFunction' ||
key === 'onDisconnectLogicFunction' ||
key === 'sendMessageLogicFunction' ||
key === 'connectionProvider' ||
key === 'settingsFrontComponent' ||
key === 'input' ||
key === 'expectedBody' ||
key === 'outputSchema' ||
key === 'expectedOutputSchema'
) {
continue;
}
if (typeof val === 'object') {
universalIdentifiers.push(...findUniversalIdentifiers(val));
}
}
return universalIdentifiers;
};
const validateRelationFields = (fields: ManifestField[]): string[] => {
const errors: string[] = [];
for (const field of fields) {
if (!isRelationFieldManifest(field)) {
continue;
}
const settings = field.universalSettings;
if (!settings?.relationType) {
errors.push(
`Relation field "${field.name}" is missing relationType. ` +
`${field.type} fields must declare a relationType (${VALID_RELATION_TYPES.join(' or ')}) in universalSettings.`,
);
continue;
}
if (!VALID_RELATION_TYPES.includes(settings.relationType)) {
errors.push(
`Relation field "${field.name}" has invalid relationType "${settings.relationType}". ` +
`Expected ${VALID_RELATION_TYPES.join(' or ')}.`,
);
continue;
}
if (
settings.relationType === RelationType.MANY_TO_ONE &&
!settings.joinColumnName
) {
errors.push(
`MANY_TO_ONE relation field "${field.name}" is missing joinColumnName. ` +
`MANY_TO_ONE relations must declare a joinColumnName in universalSettings.`,
);
}
}
return errors;
};
const collectPageLayoutWidgets = (
manifest: Pick<
Manifest,
'pageLayouts' | 'pageLayoutTabs' | 'pageLayoutWidgets'
>,
): PageLayoutWidgetManifest[] => {
const widgetsFromPageLayouts = manifest.pageLayouts.flatMap(
(pageLayout) => pageLayout.tabs?.flatMap((tab) => tab.widgets ?? []) ?? [],
);
const widgetsFromStandaloneTabs = manifest.pageLayoutTabs.flatMap(
(tab) => tab.widgets ?? [],
);
return [
...widgetsFromPageLayouts,
...widgetsFromStandaloneTabs,
...(manifest.pageLayoutWidgets ?? []),
];
};
const validateGraphWidgets = (
widgets: PageLayoutWidgetManifest[],
): string[] => {
const errors: string[] = [];
for (const widget of widgets) {
const configuration = widget.configuration;
if (!isGraphWidgetConfiguration(configuration)) {
continue;
}
if (
!isNonEmptyString(configuration.aggregateFieldMetadataUniversalIdentifier)
) {
const usedRawKey = RAW_AGGREGATE_FIELD_METADATA_ID_KEY in configuration;
const hint = usedRawKey
? ` Reference the aggregate field with "aggregateFieldMetadataUniversalIdentifier" (not "${RAW_AGGREGATE_FIELD_METADATA_ID_KEY}").`
: '';
errors.push(
`Graph widget "${widget.title}" is missing aggregateFieldMetadataUniversalIdentifier.${hint}`,
);
}
}
return errors;
};
const validatePageLayoutTab = ({
pageLayoutTab,
pageLayoutType,
}: {
pageLayoutTab: PageLayoutTabManifest;
pageLayoutType: PageLayoutManifest['type'] | undefined;
}): string[] => {
const result = normalizePageLayoutTabManifest({
pageLayoutTabManifest: pageLayoutTab,
pageLayoutType,
});
return result.status === 'fail' ? result.errors : [];
};
const validatePageLayoutTabs = (
manifest: Pick<Manifest, 'pageLayouts' | 'pageLayoutTabs'>,
): string[] => {
const pageLayoutTypeByUniversalIdentifier = new Map(
manifest.pageLayouts.map((pageLayout) => [
pageLayout.universalIdentifier,
pageLayout.type,
]),
);
const nestedTabErrors = manifest.pageLayouts.flatMap((pageLayout) =>
(pageLayout.tabs ?? []).flatMap((pageLayoutTab) =>
validatePageLayoutTab({
pageLayoutTab,
pageLayoutType: pageLayout.type,
}),
),
);
const standaloneTabErrors = manifest.pageLayoutTabs.flatMap((pageLayoutTab) =>
validatePageLayoutTab({
pageLayoutTab,
pageLayoutType: isDefined(pageLayoutTab.pageLayoutUniversalIdentifier)
? pageLayoutTypeByUniversalIdentifier.get(
pageLayoutTab.pageLayoutUniversalIdentifier,
)
: undefined,
}),
);
return [...nestedTabErrors, ...standaloneTabErrors];
};
const invalidUniversalIdentifierVersions = (
identifiers: string[],
): string[] => {
const errors: string[] = [];
const seen = new Set<string>();
for (const identifier of identifiers) {
if (seen.has(identifier)) {
continue;
}
seen.add(identifier);
if (!uuidValidate(identifier)) {
errors.push(`Universal identifier "${identifier}" is not a valid UUID.`);
continue;
}
const version = uuidVersion(identifier);
if (!isValidUniversalIdentifier(identifier)) {
errors.push(
`Universal identifier "${identifier}" is UUID version ${version}. ` +
`Only UUID version ${MINIMUM_UNIVERSAL_IDENTIFIER_UUID_VERSION} or higher is allowed.`,
);
}
}
return errors;
};
export const manifestValidate = (manifest: Manifest) => {
const errors: string[] = [];
const pageLayoutWidgets = collectPageLayoutWidgets(manifest);
const warnings = [
...getPageLayoutDeprecationWarnings(manifest),
...getUnresolvedLabelIdentifierWarnings(manifest),
...getFrontComponentWidgetAvailabilityWarnings({
manifest,
pageLayoutWidgets,
}),
];
const universalIdentifiers = findUniversalIdentifiers(manifest);
const duplicates = getDuplicateValues(
universalIdentifiers.map((identifier) => identifier.toLowerCase()),
);
if (duplicates.length > 0) {
errors.push(`Duplicate universal identifiers: ${duplicates.join(', ')}`);
}
const invalidUniversalIdentifiers =
invalidUniversalIdentifierVersions(universalIdentifiers);
if (invalidUniversalIdentifiers.length > 0) {
errors.push(
`Invalid universal identifiers: ${invalidUniversalIdentifiers.join(', ')}`,
);
}
const allFields: ManifestField[] = [
...manifest.fields,
...manifest.objects.flatMap((object) => object.fields),
];
for (const field of allFields) {
if (
(field.type === FieldMetadataType.SELECT ||
field.type === FieldMetadataType.MULTI_SELECT ||
field.type === FieldMetadataType.RATING) &&
isDefined(field.options)
) {
if (
field.options.some(({ id }) => isDefined(id) && !isNonEmptyString(id))
) {
errors.push(
`Field "${field.name}" has empty option IDs. Set distinct non-empty IDs on these options.`,
);
}
const duplicateIds = getDuplicateValues(
field.options
.map((option) => option.id)
.filter(isDefined)
.map((id) => id.toLowerCase()),
);
if (duplicateIds.length > 0)
errors.push(
`Field "${field.name}" has duplicate option IDs: ${duplicateIds.join(', ')}. Set distinct explicit IDs on these options.`,
);
}
}
errors.push(...validateRelationFields(allFields));
errors.push(...validatePageLayoutTabs(manifest));
errors.push(...validateGraphWidgets(pageLayoutWidgets));
errors.push(...validateTimelineActivityTypes(manifest));
errors.push(...validateValidationRules(manifest));
errors.push(...validateSettingsMenuItemSlugs(manifest));
return { errors, warnings, isValid: errors.length === 0 };
};