Skip to content

The open alternative to Salesforce, designed for AI.

feat(shared): no unchecked indexed access twenty-shared (#26495)

BOHEUS472fcbf71839
diff --git a/packages/twenty-front/src/modules/object-record/cache/utils/filterRecordOnGqlFields.ts b/packages/twenty-front/src/modules/object-record/cache/utils/filterRecordOnGqlFields.ts
index 92464bcad0e..267ada29252 100644
--- a/packages/twenty-front/src/modules/object-record/cache/utils/filterRecordOnGqlFields.ts
+++ b/packages/twenty-front/src/modules/object-record/cache/utils/filterRecordOnGqlFields.ts
@@ -25,7 +25,7 @@ export const filterRecordOnGqlFields = ({
if (isNonEmptyArray(value)) {
return [
key,
- value.map((item) => {
+ value.map((item: unknown) => {
if (!isDefined(item) || typeof item !== 'object') {
return item;
}
diff --git a/packages/twenty-shared/src/application/normalizePageLayoutTabManifest.ts b/packages/twenty-shared/src/application/normalizePageLayoutTabManifest.ts
index 1814a0f949a..c5aa5aea57e 100644
--- a/packages/twenty-shared/src/application/normalizePageLayoutTabManifest.ts
+++ b/packages/twenty-shared/src/application/normalizePageLayoutTabManifest.ts
@@ -189,16 +189,19 @@ export const normalizePageLayoutTabManifest = ({
);
}
+ const singleViewportWidget =
+ viewportWidgets.length === 1 ? viewportWidgets[0] : undefined;
+
if (
- viewportWidgets.length === 1 &&
+ isDefined(singleViewportWidget) &&
pageLayoutTab.widgets.some(
(widget) =>
- widget !== viewportWidgets[0] &&
+ widget !== singleViewportWidget &&
widget.position.layoutMode ===
PageLayoutTabLayoutMode.VERTICAL_LIST &&
- viewportWidgets[0].position.layoutMode ===
+ singleViewportWidget.position.layoutMode ===
PageLayoutTabLayoutMode.VERTICAL_LIST &&
- widget.position.index >= viewportWidgets[0].position.index,
+ widget.position.index >= singleViewportWidget.position.index,
)
) {
errors.push(
diff --git a/packages/twenty-shared/src/logic-function/__tests__/json-schema-to-input-schema.test.ts b/packages/twenty-shared/src/logic-function/__tests__/json-schema-to-input-schema.test.ts
index 6c520e121b9..93469639e5b 100644
--- a/packages/twenty-shared/src/logic-function/__tests__/json-schema-to-input-schema.test.ts
+++ b/packages/twenty-shared/src/logic-function/__tests__/json-schema-to-input-schema.test.ts
@@ -28,7 +28,7 @@ describe('jsonSchemaToInputSchema', () => {
properties: { count: { type: 'integer' } },
});
- expect(result[0].properties).toEqual({ count: { type: 'number' } });
+ expect(result[0]?.properties).toEqual({ count: { type: 'number' } });
});
it('maps null to unknown', () => {
@@ -37,7 +37,7 @@ describe('jsonSchemaToInputSchema', () => {
properties: { value: { type: 'null' } },
});
- expect(result[0].properties).toEqual({ value: { type: 'unknown' } });
+ expect(result[0]?.properties).toEqual({ value: { type: 'unknown' } });
});
it('preserves array items', () => {
@@ -62,7 +62,7 @@ describe('jsonSchemaToInputSchema', () => {
},
});
- expect(result[0].properties?.color).toEqual({
+ expect(result[0]?.properties?.color).toEqual({
type: 'string',
enum: ['red', 'green', 'blue'],
});
@@ -76,7 +76,7 @@ describe('jsonSchemaToInputSchema', () => {
},
});
- expect(result[0].properties?.mixed).toEqual({
+ expect(result[0]?.properties?.mixed).toEqual({
type: 'string',
enum: ['a', 'b'],
});
@@ -90,7 +90,7 @@ describe('jsonSchemaToInputSchema', () => {
},
});
- expect(result[0].properties?.body).toEqual({
+ expect(result[0]?.properties?.body).toEqual({
type: 'string',
multiline: true,
});
@@ -105,8 +105,8 @@ describe('jsonSchemaToInputSchema', () => {
},
});
- expect(result[0].properties?.title).toEqual({ type: 'string' });
- expect(result[0].properties?.other).toEqual({ type: 'string' });
+ expect(result[0]?.properties?.title).toEqual({ type: 'string' });
+ expect(result[0]?.properties?.other).toEqual({ type: 'string' });
});
it('preserves label on top-level and nested properties', () => {
@@ -125,16 +125,16 @@ describe('jsonSchemaToInputSchema', () => {
},
});
- expect(result[0].label).toBe('Slack Message');
- expect(result[0].properties?.slackChannelId).toEqual({
+ expect(result[0]?.label).toBe('Slack Message');
+ expect(result[0]?.properties?.slackChannelId).toEqual({
type: 'string',
label: 'Channel',
});
- expect(result[0].properties?.messageText).toEqual({
+ expect(result[0]?.properties?.messageText).toEqual({
type: 'string',
label: 'Message text',
});
- expect(result[0].properties?.meta?.properties?.count).toEqual({
+ expect(result[0]?.properties?.meta?.properties?.count).toEqual({
type: 'number',
label: 'Count',
});
@@ -158,11 +158,11 @@ describe('jsonSchemaToInputSchema', () => {
},
});
- expect(result[0].properties?.company).toEqual({
+ expect(result[0]?.properties?.company).toEqual({
type: 'object',
objectUniversalIdentifier: 'company-universal-identifier',
});
- expect(result[0].properties?.people).toEqual({
+ expect(result[0]?.properties?.people).toEqual({
type: 'array',
items: {
type: 'object',
@@ -186,11 +186,11 @@ describe('jsonSchemaToInputSchema', () => {
},
});
- expect(result[0].properties?.company).toEqual({
+ expect(result[0]?.properties?.company).toEqual({
type: 'record',
objectUniversalIdentifier: 'company-universal-identifier',
});
- expect(result[0].properties?.people).toEqual({
+ expect(result[0]?.properties?.people).toEqual({
type: 'records',
objectUniversalIdentifier: 'person-universal-identifier',
});
@@ -205,7 +205,7 @@ describe('jsonSchemaToInputSchema', () => {
},
});
- expect(result[0].properties?.empty).toEqual({ type: 'string' });
- expect(result[0].properties?.missing).toEqual({ type: 'string' });
+ expect(result[0]?.properties?.empty).toEqual({ type: 'string' });
+ expect(result[0]?.properties?.missing).toEqual({ type: 'string' });
});
});
diff --git a/packages/twenty-shared/src/translations/utils/getLocaleTextDirection.ts b/packages/twenty-shared/src/translations/utils/getLocaleTextDirection.ts
index d81e16d8e5e..eb0ca92e022 100644
--- a/packages/twenty-shared/src/translations/utils/getLocaleTextDirection.ts
+++ b/packages/twenty-shared/src/translations/utils/getLocaleTextDirection.ts
@@ -16,4 +16,6 @@ const RIGHT_TO_LEFT_LANGUAGES = [
];
export const getLocaleTextDirection = (locale: string): TextDirection =>
- RIGHT_TO_LEFT_LANGUAGES.includes(locale.split('-')[0]) ? 'rtl' : 'ltr';
+ RIGHT_TO_LEFT_LANGUAGES.includes(locale.split('-')[0] ?? locale)
+ ? 'rtl'
+ : 'ltr';
diff --git a/packages/twenty-shared/src/types/__tests__/apiPathCollisions.spec.ts b/packages/twenty-shared/src/types/__tests__/apiPathCollisions.spec.ts
index da6541b9087..ea02d2a40e4 100644
--- a/packages/twenty-shared/src/types/__tests__/apiPathCollisions.spec.ts
+++ b/packages/twenty-shared/src/types/__tests__/apiPathCollisions.spec.ts
@@ -5,7 +5,7 @@ import { AppPath } from '@/types/AppPath';
const apiPaths = new Set<string>(Object.values(ApiPath));
const getFirstPathSegment = (path: string) =>
- path.replace(/^\//, '').split('/')[0];
+ path.replace(/^\//, '').split('/')[0] ?? '';
const frontRoutes = [...Object.values(AppPath), ...Object.values(AppBasePath)];
diff --git a/packages/twenty-shared/src/utils/applyDiff.ts b/packages/twenty-shared/src/utils/applyDiff.ts
index a5333474831..f8613662f9c 100644
--- a/packages/twenty-shared/src/utils/applyDiff.ts
+++ b/packages/twenty-shared/src/utils/applyDiff.ts
@@ -55,6 +55,10 @@ const applyDiffToPath = (
const pathLength = path.length;
const lastPathElement = path[pathLength - 1];
+ if (!isDefined(lastPathElement)) {
+ throw new Error('Cannot apply diff at an empty path');
+ }
+
const parentContainer = navigateToParent(obj, path);
switch (type) {
@@ -217,8 +221,8 @@ const filterRemoveSymbols = (array: ArrayType): void => {
}
}
- for (let i = indicesToRemove.length - 1; i >= 0; i--) {
- array.splice(indicesToRemove[i], 1);
+ for (const indexToRemove of indicesToRemove.reverse()) {
+ array.splice(indexToRemove, 1);
}
};
diff --git a/packages/twenty-shared/src/utils/array/__tests__/isNonEmptyArray.test.ts b/packages/twenty-shared/src/utils/array/__tests__/isNonEmptyArray.test.ts
new file mode 100644
index 00000000000..65e2b73fdd7
--- /dev/null
+++ b/packages/twenty-shared/src/utils/array/__tests__/isNonEmptyArray.test.ts
@@ -0,0 +1,44 @@
+import { isNonEmptyArray } from '@/utils/array/isNonEmptyArray';
+
+describe('isNonEmptyArray', () => {
+ it('should return false for empty, null and undefined arrays', () => {
+ expect(isNonEmptyArray([])).toBe(false);
+ expect(isNonEmptyArray(null)).toBe(false);
+ expect(isNonEmptyArray(undefined)).toBe(false);
+ });
+
+ it('should return true and expose a defined first element', () => {
+ const values: string[] = ['first', 'second'];
+
+ expect(isNonEmptyArray(values)).toBe(true);
+
+ if (isNonEmptyArray(values)) {
+ const firstValue: string = values[0];
+
+ expect(firstValue).toBe('first');
+ }
+ });
+
+ it('should return false for an array whose first element is a hole', () => {
+ const sparseValues = new Array<string>(2);
+
+ expect(isNonEmptyArray(sparseValues)).toBe(false);
+
+ sparseValues[0] = 'first';
+
+ expect(isNonEmptyArray(sparseValues)).toBe(true);
+ });
+
+ it('should keep a narrowed readonly array readonly', () => {
+ const values: readonly string[] = Object.freeze(['first']);
+
+ if (isNonEmptyArray(values)) {
+ expect(() => {
+ // @ts-expect-error narrowing must not hand out mutators on a readonly array
+ values.push('second');
+ }).toThrow();
+ }
+
+ expect(values).toHaveLength(1);
+ });
+});
diff --git a/packages/twenty-shared/src/utils/array/__tests__/upsertIntoArrayOfObjectsComparingId.test.ts b/packages/twenty-shared/src/utils/array/__tests__/upsertIntoArrayOfObjectsComparingId.test.ts
index 78a4ccec8ec..bda8e1e15b3 100644
--- a/packages/twenty-shared/src/utils/array/__tests__/upsertIntoArrayOfObjectsComparingId.test.ts
+++ b/packages/twenty-shared/src/utils/array/__tests__/upsertIntoArrayOfObjectsComparingId.test.ts
@@ -27,7 +27,7 @@ const mockTestObjects: TestObject[] = [
describe('upsertIntoArrayOfObjectsComparingId', () => {
it('should insert in empty array', () => {
expect(
- upsertIntoArrayOfObjectsComparingId([], mockTestObjects[0]),
+ upsertIntoArrayOfObjectsComparingId([], mockTestObjects[0]!),
).toStrictEqual([mockTestObjects[0]]);
});
diff --git a/packages/twenty-shared/src/utils/array/isNonEmptyArray.ts b/packages/twenty-shared/src/utils/array/isNonEmptyArray.ts
index 210f4d59089..074791f5d3e 100644
--- a/packages/twenty-shared/src/utils/array/isNonEmptyArray.ts
+++ b/packages/twenty-shared/src/utils/array/isNonEmptyArray.ts
@@ -1,12 +1,13 @@
import { isNumber } from '@sniptt/guards';
-export const isNonEmptyArray = <T>(
- probableArray: T[] | readonly T[] | undefined | null,
-): probableArray is NonNullable<T[]> => {
+export const isNonEmptyArray = <TArray extends readonly unknown[]>(
+ probableArray: TArray | undefined | null,
+): probableArray is TArray & { 0: TArray[number] } => {
if (
Array.isArray(probableArray) &&
isNumber(probableArray.length) &&
- probableArray.length > 0
+ probableArray.length > 0 &&
+ 0 in probableArray
) {
return true;
}
diff --git a/packages/twenty-shared/src/utils/callRecording/parseCallRecordingTranscriptEntries.ts b/packages/twenty-shared/src/utils/callRecording/parseCallRecordingTranscriptEntries.ts
index 8ca13e18bec..e8b62cf97e9 100644
--- a/packages/twenty-shared/src/utils/callRecording/parseCallRecordingTranscriptEntries.ts
+++ b/packages/twenty-shared/src/utils/callRecording/parseCallRecordingTranscriptEntries.ts
@@ -66,14 +66,17 @@ const readTranscriptEntry = (
.map(readTranscriptWord)
.filter(isDefined);
- if (words.length === 0) {
+ const firstWord = words[0];
+ const lastWord = words[words.length - 1];
+
+ if (!isDefined(firstWord) || !isDefined(lastWord)) {
return undefined;
}
return {
speakerName: readSpeakerName(asRecord(candidate.participant)),
- startSeconds: words[0].startSeconds,
- endSeconds: words[words.length - 1].endSeconds,
+ startSeconds: firstWord.startSeconds,
+ endSeconds: lastWord.endSeconds,
text: words.map((word) => word.text).join(' '),
words,
};
diff --git a/packages/twenty-shared/src/utils/email/__tests__/formatEmailAddress.test.ts b/packages/twenty-shared/src/utils/email/__tests__/formatEmailAddress.test.ts
index 0f2fa74d2ed..a25778c358f 100644
--- a/packages/twenty-shared/src/utils/email/__tests__/formatEmailAddress.test.ts
+++ b/packages/twenty-shared/src/utils/email/__tests__/formatEmailAddress.test.ts
@@ -46,10 +46,10 @@ describe('formatEmailAddress', () => {
const reparsed = parseEmailAddressList(`${formatted}, [email protected]`);
expect(reparsed).toHaveLength(2);
- expect(reparsed[0].address).toBe('[email protected]');
+ expect(reparsed[0]?.address).toBe('[email protected]');
// addressparser collapses the escaped backslash: containment is the
// contract here, not byte fidelity of exotic display names.
- expect(reparsed[0].name).toBe('x"y');
+ expect(reparsed[0]?.name).toBe('x"y');
expect(reparsed[1]).toEqual({ address: '[email protected]', name: '' });
});
diff --git a/packages/twenty-shared/src/utils/evalFromContext.ts b/packages/twenty-shared/src/utils/evalFromContext.ts
index 60c4ad4cdae..940bcae95aa 100644
--- a/packages/twenty-shared/src/utils/evalFromContext.ts
+++ b/packages/twenty-shared/src/utils/evalFromContext.ts
@@ -30,7 +30,7 @@ const readFirstParam = (expression: string): string | undefined => {
let param = '';
for (let index = 0; index < expression.length; ++index) {
- const character = expression[index];
+ const character = expression.charAt(index);
if (character === '[') {
const closingIndex = expression.indexOf(']', index + 1);
@@ -153,7 +153,7 @@ export const evalFromContext = (
return undefined;
}
- const expression = tokenMatch[1].trim();
+ const expression = tokenMatch[1]?.trim();
if (!isNonEmptyString(expression)) {
return undefined;
@@ -225,15 +225,16 @@ export const evalFromContext = (
return undefined;
}
- if (segments.length === 0) {
+ const firstSegment = segments[0];
+ const lastSegment = segments[segments.length - 1];
+
+ if (!isDefined(firstSegment) || !isDefined(lastSegment)) {
return toJsonValue(context);
}
// A number or a keyword read as a value rather than a key, so a path ending in
// one never resolved. Mid-path they are ordinary keys: `arr.0` is undefined
// but `arr.0.length` is not, and `[0]` works in either position
- const lastSegment = segments[segments.length - 1];
-
if (
!lastSegment.isLiteralSegment &&
(NUMBER_LITERAL_PATTERN.test(lastSegment.value) ||
@@ -246,8 +247,8 @@ export const evalFromContext = (
// only for a bare path: under `@root.` it stayed an ordinary empty-string key
if (
contextPrefix !== '@root.' &&
- segments[0].isLiteralSegment &&
- segments[0].value === ''
+ firstSegment.isLiteralSegment &&
+ firstSegment.value === ''
) {
return toJsonValue(context);
}
diff --git a/packages/twenty-shared/src/utils/filter/__tests__/filterOutInvalidRecordFilters.test.ts b/packages/twenty-shared/src/utils/filter/__tests__/filterOutInvalidRecordFilters.test.ts
index 3bede36c8d2..057151d8cf0 100644
--- a/packages/twenty-shared/src/utils/filter/__tests__/filterOutInvalidRecordFilters.test.ts
+++ b/packages/twenty-shared/src/utils/filter/__tests__/filterOutInvalidRecordFilters.test.ts
@@ -66,7 +66,7 @@ describe('filterOutInvalidRecordFilters', () => {
const result = filterOutInvalidRecordFilters(filters);
expect(result).toEqual(filters);
- expect(result[0].id).toBe('filter-1');
- expect(result[0].fieldMetadataId).toBe('field-1');
+ expect(result[0]?.id).toBe('filter-1');
+ expect(result[0]?.fieldMetadataId).toBe('field-1');
});
});
diff --git a/packages/twenty-shared/src/utils/filter/computeRecordGqlOperationFilter.ts b/packages/twenty-shared/src/utils/filter/computeRecordGqlOperationFilter.ts
index e70b7c42cb9..37d2b6e7a04 100644
--- a/packages/twenty-shared/src/utils/filter/computeRecordGqlOperationFilter.ts
+++ b/packages/twenty-shared/src/utils/filter/computeRecordGqlOperationFilter.ts
@@ -58,12 +58,14 @@ export const computeRecordGqlOperationFilter = ({
advancedRecordGqlOperationFilter,
].filter(isDefined);
- if (recordGqlOperationFilters.length === 0) {
+ const [firstRecordGqlOperationFilter] = recordGqlOperationFilters;
+
+ if (!isDefined(firstRecordGqlOperationFilter)) {
return {};
}
if (recordGqlOperationFilters.length === 1) {
- return recordGqlOperationFilters[0];
+ return firstRecordGqlOperationFilter;
}
const recordGqlOperationFilter = {
diff --git a/packages/twenty-shared/src/utils/filter/utils/combineFilters.ts b/packages/twenty-shared/src/utils/filter/utils/combineFilters.ts
index 1301365fa7a..70093b32a1d 100644
--- a/packages/twenty-shared/src/utils/filter/utils/combineFilters.ts
+++ b/packages/twenty-shared/src/utils/filter/utils/combineFilters.ts
@@ -1,4 +1,5 @@
import { type RecordGqlOperationFilter } from '@/types';
+import { isDefined } from '@/utils/validation';
export const combineFilters = (
filters: RecordGqlOperationFilter[],
@@ -7,12 +8,14 @@ export const combineFilters = (
(filter) => Object.keys(filter).length > 0,
);
- if (nonEmptyFilters.length === 0) {
+ const [firstFilter] = nonEmptyFilters;
+
+ if (!isDefined(firstFilter)) {
return {};
}
if (nonEmptyFilters.length === 1) {
- return nonEmptyFilters[0];
+ return firstFilter;
}
return {
diff --git a/packages/twenty-shared/src/utils/filter/utils/convert-view-filter-operand-to-core-operand.util.ts b/packages/twenty-shared/src/utils/filter/utils/convert-view-filter-operand-to-core-operand.util.ts
index a91202714f3..2bc40d2f557 100644
--- a/packages/twenty-shared/src/utils/filter/utils/convert-view-filter-operand-to-core-operand.util.ts
+++ b/packages/twenty-shared/src/utils/filter/utils/convert-view-filter-operand-to-core-operand.util.ts
@@ -1,6 +1,9 @@
import { ViewFilterOperand, ViewFilterOperandDeprecated } from '@/types';
-const operandMapping: Record<string, ViewFilterOperand> = {
+const operandMapping: Record<
+ ViewFilterOperand | ViewFilterOperandDeprecated,
+ ViewFilterOperand
+> = {
[ViewFilterOperandDeprecated.Is]: ViewFilterOperand.IS,
[ViewFilterOperandDeprecated.IsNotNull]: ViewFilterOperand.IS_NOT_NULL,
[ViewFilterOperandDeprecated.IsNot]: ViewFilterOperand.IS_NOT,
@@ -39,7 +42,7 @@ const operandMapping: Record<string, ViewFilterOperand> = {
};
export const convertViewFilterOperandToCoreOperand = (
- sharedOperand: string,
+ sharedOperand: ViewFilterOperand | ViewFilterOperandDeprecated,
): ViewFilterOperand => {
return operandMapping[sharedOperand];
};
diff --git a/packages/twenty-shared/src/utils/filter/utils/fieldRatingConvertors.ts b/packages/twenty-shared/src/utils/filter/utils/fieldRatingConvertors.ts
index 3e3978799ac..e1009117d26 100644
--- a/packages/twenty-shared/src/utils/filter/utils/fieldRatingConvertors.ts
+++ b/packages/twenty-shared/src/utils/filter/utils/fieldRatingConvertors.ts
@@ -5,14 +5,14 @@ export const convertGreaterThanOrEqualRatingToArrayOfRatingValues = (
greaterThanValue: number,
) =>
RATING_VALUES.filter(
- (ratingValue) => +ratingValue.split('_')[1] >= greaterThanValue,
+ (ratingValue) => Number(ratingValue.split('_')[1]) >= greaterThanValue,
);
export const convertLessThanOrEqualRatingToArrayOfRatingValues = (
lessThanValue: number,
) =>
RATING_VALUES.filter(
- (ratingValue) => +ratingValue.split('_')[1] <= lessThanValue,
+ (ratingValue) => Number(ratingValue.split('_')[1]) <= lessThanValue,
);
export const convertRatingToRatingValue = (rating: number) =>
diff --git a/packages/twenty-shared/src/utils/indexMetadata/__tests__/getUniqueConstraintsFields.test.ts b/packages/twenty-shared/src/utils/indexMetadata/__tests__/getUniqueConstraintsFields.test.ts
index 7b5ed78a86c..d1432bd0038 100644
--- a/packages/twenty-shared/src/utils/indexMetadata/__tests__/getUniqueConstraintsFields.test.ts
+++ b/packages/twenty-shared/src/utils/indexMetadata/__tests__/getUniqueConstraintsFields.test.ts
@@ -108,7 +108,7 @@ describe('getUniqueConstraintsFields', () => {
expect(result).toHaveLength(1);
expect(result[0]).toHaveLength(1);
- expect(result[0][0]).toEqual(mockIdField);
+ expect(result[0]?.[0]).toEqual(mockIdField);
});
it('should return the primary key constraint field and the unique indexes fields if unique indexes are present', () => {
@@ -132,8 +132,8 @@ describe('getUniqueConstraintsFields', () => {
expect(result).toHaveLength(2);
expect(result[0]).toHaveLength(1);
- expect(result[0][0]).toEqual(mockIdField);
+ expect(result[0]?.[0]).toEqual(mockIdField);
expect(result[1]).toHaveLength(1);
- expect(result[1][0]).toEqual(mockEmailField);
+ expect(result[1]?.[0]).toEqual(mockEmailField);
});
});
diff --git a/packages/twenty-shared/src/utils/json/fast-deep-equal.ts b/packages/twenty-shared/src/utils/json/fast-deep-equal.ts
index d7ebb8c9e8e..2d899a631b9 100644
--- a/packages/twenty-shared/src/utils/json/fast-deep-equal.ts
+++ b/packages/twenty-shared/src/utils/json/fast-deep-equal.ts
@@ -88,11 +88,11 @@ export const fastDeepEqual = (
if (firstKeys.length !== secondKeys.length) return false;
for (let index = firstKeys.length; index-- !== 0; ) {
- if (!(firstKeys[index] in secondValue)) return false;
+ if (!(firstKeys[index]! in secondValue)) return false;
}
for (let index = firstKeys.length; index-- !== 0; ) {
- const key = firstKeys[index];
+ const key = firstKeys[index]!;
if (
!fastDeepEqual(
diff --git a/packages/twenty-shared/src/utils/strings/capitalize.ts b/packages/twenty-shared/src/utils/strings/capitalize.ts
index 9953f375173..1374114afdc 100644
--- a/packages/twenty-shared/src/utils/strings/capitalize.ts
+++ b/packages/twenty-shared/src/utils/strings/capitalize.ts
@@ -3,5 +3,7 @@ import { isNonEmptyString } from '@sniptt/guards';
export const capitalize = (stringToCapitalize: string) => {
if (!isNonEmptyString(stringToCapitalize)) return '';
- return stringToCapitalize[0].toUpperCase() + stringToCapitalize.slice(1);
+ return (
+ stringToCapitalize.charAt(0).toUpperCase() + stringToCapitalize.slice(1)
+ );
};
diff --git a/packages/twenty-shared/src/utils/tiptap/__tests__/campaign-variables.test.ts b/packages/twenty-shared/src/utils/tiptap/__tests__/campaign-variables.test.ts
index 783fb664188..3708607aaf6 100644
--- a/packages/twenty-shared/src/utils/tiptap/__tests__/campaign-variables.test.ts
+++ b/packages/twenty-shared/src/utils/tiptap/__tests__/campaign-variables.test.ts
@@ -41,7 +41,7 @@ describe('listCampaignVariablesForFields', () => {
'name.lastName',
]);
- expect(definitions[0].label).toBe('Name · First name');
+ expect(definitions[0]?.label).toBe('Name · First name');
});
it('should skip system, inactive and unsupported fields', () => {
diff --git a/packages/twenty-shared/src/utils/tiptap/__tests__/email-document-schema.test.ts b/packages/twenty-shared/src/utils/tiptap/__tests__/email-document-schema.test.ts
index 1f20bd73283..025047a7c1d 100644
--- a/packages/twenty-shared/src/utils/tiptap/__tests__/email-document-schema.test.ts
+++ b/packages/twenty-shared/src/utils/tiptap/__tests__/email-document-schema.test.ts
@@ -151,7 +151,7 @@ describe('parseEmailDocument', () => {
expect(result.success).toBe(true);
if (result.success) {
- expect(result.document.content?.[0].attrs?.futureAttribute).toBe('kept');
+ expect(result.document.content?.[0]?.attrs?.futureAttribute).toBe('kept');
}
});
diff --git a/packages/twenty-shared/src/utils/tiptap/__tests__/transform-email-document-strings.test.ts b/packages/twenty-shared/src/utils/tiptap/__tests__/transform-email-document-strings.test.ts
index 5201df94a04..403da489a8c 100644
--- a/packages/twenty-shared/src/utils/tiptap/__tests__/transform-email-document-strings.test.ts
+++ b/packages/twenty-shared/src/utils/tiptap/__tests__/transform-email-document-strings.test.ts
@@ -37,24 +37,24 @@ describe('transformEmailDocumentStrings', () => {
},
);
- expect(document.content?.[0].content?.[0].attrs?.variable).toBe(
+ expect(document.content?.[0]?.content?.[0]?.attrs?.variable).toBe(
'[text]{{name}}',
);
expect(
(
- document.content?.[0].content?.[1].marks?.[0] as {
+ document.content?.[0]?.content?.[1]?.marks?.[0] as {
attrs: { href: string };
}
).attrs.href,
).toBe('[url]/people/{{id}}');
- expect(document.content?.[1].attrs).toEqual({
+ expect(document.content?.[1]?.attrs).toEqual({
src: '[url]/images/{{id}}',
href: '[url]/people/{{id}}',
alt: '[text]{{name}}',
title: '[text]{{name}}',
});
- expect(document.content?.[2].attrs?.href).toBe('[url]/people/{{id}}');
- expect(document.content?.[3].attrs?.html).toBe('[html]<p>{{name}}</p>');
+ expect(document.content?.[2]?.attrs?.href).toBe('[url]/people/{{id}}');
+ expect(document.content?.[3]?.attrs?.html).toBe('[html]<p>{{name}}</p>');
expect(contexts).toContain('html');
expect(contexts).toContain('text');
expect(contexts).toContain('url');
diff --git a/packages/twenty-shared/src/utils/tiptap/convert-tiptap-blocks-to-markdown.ts b/packages/twenty-shared/src/utils/tiptap/convert-tiptap-blocks-to-markdown.ts
index 9834de672d9..7ada4e651f4 100644
--- a/packages/twenty-shared/src/utils/tiptap/convert-tiptap-blocks-to-markdown.ts
+++ b/packages/twenty-shared/src/utils/tiptap/convert-tiptap-blocks-to-markdown.ts
@@ -42,7 +42,7 @@ export const convertTipTapBlocksToMarkdown = (
const [firstNode] = nodes;
- return nodes.length === 1 && firstNode.type === TIPTAP_NODE_TYPES.DOCUMENT
+ return nodes.length === 1 && firstNode?.type === TIPTAP_NODE_TYPES.DOCUMENT
? tipTapDocumentToMarkdown(firstNode as TipTapDocument)
: tipTapDocumentToMarkdown({
type: TIPTAP_NODE_TYPES.DOCUMENT,
diff --git a/packages/twenty-shared/src/utils/tiptap/tiptap-document-to-markdown.ts b/packages/twenty-shared/src/utils/tiptap/tiptap-document-to-markdown.ts
index 7153c6a69c2..955beb6a7fd 100644
--- a/packages/twenty-shared/src/utils/tiptap/tiptap-document-to-markdown.ts
+++ b/packages/twenty-shared/src/utils/tiptap/tiptap-document-to-markdown.ts
@@ -31,7 +31,7 @@ const MARKDOWN_DESTINATION_CHARACTER_ESCAPES: Readonly<Record<string, string>> =
const escapeMarkdownDestination = (destination: string): string =>
destination.replace(/[\\()<>\s]/g, (character) =>
character in MARKDOWN_DESTINATION_CHARACTER_ESCAPES
- ? MARKDOWN_DESTINATION_CHARACTER_ESCAPES[character]
+ ? (MARKDOWN_DESTINATION_CHARACTER_ESCAPES[character] ?? character)
: encodeURIComponent(character),
);
diff --git a/packages/twenty-shared/src/utils/upgrade/formatUpgradeCommandName.ts b/packages/twenty-shared/src/utils/upgrade/formatUpgradeCommandName.ts
index eef5b5af74f..433577e6325 100644
--- a/packages/twenty-shared/src/utils/upgrade/formatUpgradeCommandName.ts
+++ b/packages/twenty-shared/src/utils/upgrade/formatUpgradeCommandName.ts
@@ -27,7 +27,7 @@ export const formatUpgradeCommandName = (commandName: string): string => {
const version = commandNameParts[0];
const lastPart = commandNameParts[commandNameParts.length - 1];
- const hasTrailingTimestamp = TRAILING_TIMESTAMP_PATTERN.test(lastPart);
+ const hasTrailingTimestamp = TRAILING_TIMESTAMP_PATTERN.test(lastPart ?? '');
const className = commandNameParts.slice(1, -1).join('_');
const friendlyCommandName = stripCommandSuffix(className);
diff --git a/packages/twenty-shared/src/utils/url/normalizeDomain.ts b/packages/twenty-shared/src/utils/url/normalizeDomain.ts
index dd436e2918e..df200fa1e08 100644
--- a/packages/twenty-shared/src/utils/url/normalizeDomain.ts
+++ b/packages/twenty-shared/src/utils/url/normalizeDomain.ts
@@ -26,11 +26,13 @@ const toPunycodeHost = (host: string): string => {
};
export const normalizeDomain = (rawDomain: string): string => {
+ const [pathlessDomain = ''] = rawDomain
+ .trim()
+ .replace(SCHEME_PREFIX_REGEX, '')
+ .split(PATH_SEPARATOR_REGEX);
+
const host = stripWwwPrefixesAndTrailingDots(
- rawDomain
- .trim()
- .replace(SCHEME_PREFIX_REGEX, '')
- .split(PATH_SEPARATOR_REGEX)[0]
+ pathlessDomain
.replace(USER_INFO_PREFIX_REGEX, '')
.replace(PORT_SUFFIX_REGEX, '')
.toLowerCase(),
diff --git a/packages/twenty-shared/src/utils/validation/normalizeLocale.ts b/packages/twenty-shared/src/utils/validation/normalizeLocale.ts
index 9df7aad2272..bf546042993 100644
--- a/packages/twenty-shared/src/utils/validation/normalizeLocale.ts
+++ b/packages/twenty-shared/src/utils/validation/normalizeLocale.ts
@@ -9,7 +9,7 @@ import { isValidLocale } from '@/utils/validation/isValidLocale';
// Maps language codes to full locale keys in APP_LOCALES
// Example: 'fr' -> 'fr-FR', 'en' -> 'en'
const languageToLocaleMap = Object.keys(APP_LOCALES).reduce((map, locale) => {
- const language = locale.split('-')[0].toLowerCase();
+ const language = (locale.split('-')[0] ?? locale).toLowerCase();
// Only add to the map if not already added or if the current locale is the source locale
// This ensures language codes map to their full locale version (e.g., 'es' -> 'es-ES')
@@ -38,7 +38,9 @@ export const normalizeLocale = (value: string | null): AppLocale => {
}
// Try matching just the language part (e.g., 'fr' -> 'fr-FR')
- const languageCode = value?.trim() ? value.split('-')[0].toLowerCase() : '';
+ const languageCode = value?.trim()
+ ? (value.split('-')[0] ?? value).toLowerCase()
+ : '';
const languageLocale = languageToLocaleMap.get(languageCode);
if (isDefined(languageLocale)) {
diff --git a/packages/twenty-shared/src/workflow/layout/utils/__tests__/compute-workflow-layout.util.test.ts b/packages/twenty-shared/src/workflow/layout/utils/__tests__/compute-workflow-layout.util.test.ts
index e9bec2b1fb9..d7e2318a172 100644
--- a/packages/twenty-shared/src/workflow/layout/utils/__tests__/compute-workflow-layout.util.test.ts
+++ b/packages/twenty-shared/src/workflow/layout/utils/__tests__/compute-workflow-layout.util.test.ts
@@ -49,7 +49,7 @@ describe('computeWorkflowLayout', () => {
edges: [],
});
- expect(positions[0].centerPosition).toEqual({
+ expect(positions[0]?.centerPosition).toEqual({
x: width / 2,
y: height / 2,
});
diff --git a/packages/twenty-shared/src/workflow/validation/utils/extract-variables-from-input.util.ts b/packages/twenty-shared/src/workflow/validation/utils/extract-variables-from-input.util.ts
index 55ce30caf1e..d97f197f16a 100644
--- a/packages/twenty-shared/src/workflow/validation/utils/extract-variables-from-input.util.ts
+++ b/packages/twenty-shared/src/workflow/validation/utils/extract-variables-from-input.util.ts
@@ -1,5 +1,6 @@
import { isObject, isString } from '@sniptt/guards';
+import { isDefined } from '@/utils';
import { CAPTURE_ALL_VARIABLE_TAG_INNER_REGEX } from '@/workflow/constants/CaptureAllVariableTagInnerRegex';
function* resolveVariables(value: unknown): Generator<string> {
@@ -7,7 +8,9 @@ function* resolveVariables(value: unknown): Generator<string> {
for (const [, variablePath] of value.matchAll(
CAPTURE_ALL_VARIABLE_TAG_INNER_REGEX,
)) {
- yield variablePath;
+ if (isDefined(variablePath)) {
+ yield variablePath;
+ }
}
return;
diff --git a/packages/twenty-shared/src/workflow/validation/utils/get-edit-distance.util.ts b/packages/twenty-shared/src/workflow/validation/utils/get-edit-distance.util.ts
index b49eb9f5f34..e20f80ba69e 100644
--- a/packages/twenty-shared/src/workflow/validation/utils/get-edit-distance.util.ts
+++ b/packages/twenty-shared/src/workflow/validation/utils/get-edit-distance.util.ts
@@ -8,25 +8,28 @@ export const getEditDistance = (source: string, target: string): number => {
);
for (let rowIndex = 0; rowIndex < rowCount; rowIndex++) {
- matrix[rowIndex][0] = rowIndex;
+ matrix[rowIndex]![0] = rowIndex;
}
for (let columnIndex = 0; columnIndex < columnCount; columnIndex++) {
- matrix[0][columnIndex] = columnIndex;
+ matrix[0]![columnIndex] = columnIndex;
}
for (let rowIndex = 1; rowIndex < rowCount; rowIndex++) {
+ const previousRow = matrix[rowIndex - 1]!;
+ const currentRow = matrix[rowIndex]!;
+
for (let columnIndex = 1; columnIndex < columnCount; columnIndex++) {
const substitutionCost =
source[rowIndex - 1] === target[columnIndex - 1] ? 0 : 1;
- matrix[rowIndex][columnIndex] = Math.min(
- matrix[rowIndex - 1][columnIndex] + 1,
- matrix[rowIndex][columnIndex - 1] + 1,
- matrix[rowIndex - 1][columnIndex - 1] + substitutionCost,
+ currentRow[columnIndex] = Math.min(
+ previousRow[columnIndex]! + 1,
+ currentRow[columnIndex - 1]! + 1,
+ previousRow[columnIndex - 1]! + substitutionCost,
);
}
}
- return matrix[source.length][target.length];
+ return matrix[source.length]![target.length]!;
};
diff --git a/packages/twenty-shared/src/workflow/validation/utils/validate-workflow-graph.util.ts b/packages/twenty-shared/src/workflow/validation/utils/validate-workflow-graph.util.ts
index c7f9c00ce82..6f5784a0491 100644
--- a/packages/twenty-shared/src/workflow/validation/utils/validate-workflow-graph.util.ts
+++ b/packages/twenty-shared/src/workflow/validation/utils/validate-workflow-graph.util.ts
@@ -1,4 +1,4 @@
-import { isDefined } from '@/utils';
+import { isDefined, isNonEmptyArray } from '@/utils';
import { WorkflowActionType } from '@/workflow/types/WorkflowActionType';
import {
type IfElseStepInput,
@@ -39,7 +39,7 @@ export const validateWorkflowGraph = ({
isDefined,
);
- if (steps.length > 0 && triggerNextStepIds.length === 0) {
+ if (isNonEmptyArray(steps) && triggerNextStepIds.length === 0) {
issues.push({
severity: 'error',
code: 'TRIGGER_HAS_NO_NEXT_STEP',
diff --git a/packages/twenty-shared/src/workflow/workflow-schema/utils/find-output-schema-path-failure.ts b/packages/twenty-shared/src/workflow/workflow-schema/utils/find-output-schema-path-failure.ts
index e76491490ba..800ffc8bb83 100644
--- a/packages/twenty-shared/src/workflow/workflow-schema/utils/find-output-schema-path-failure.ts
+++ b/packages/twenty-shared/src/workflow/workflow-schema/utils/find-output-schema-path-failure.ts
@@ -19,15 +19,20 @@ export const findOutputSchemaPathFailure = ({
let currentSchema: BaseOutputSchemaV2 = schema;
for (let index = 0; index < propertyPath.length; index++) {
+ const segment = propertyPath[index];
+
+ if (!isDefined(segment)) {
+ return undefined;
+ }
+
if (!isObject(currentSchema)) {
return {
validPrefix: propertyPath.slice(0, index),
- failedSegment: propertyPath[index],
+ failedSegment: segment,
availableKeys: [],
};
}
- const segment = propertyPath[index];
const field = currentSchema[segment];
if (!isDefined(field)) {
@@ -39,12 +44,12 @@ export const findOutputSchemaPathFailure = ({
}
if (field.isLeaf) {
- const isLastSegment = index === propertyPath.length - 1;
+ const nextSegment = propertyPath[index + 1];
- if (!isLastSegment) {
+ if (isDefined(nextSegment)) {
return {
validPrefix: propertyPath.slice(0, index + 1),
- failedSegment: propertyPath[index + 1],
+ failedSegment: nextSegment,
availableKeys: [],
};
}
diff --git a/packages/twenty-shared/src/workflow/workflow-schema/utils/resolve-variable-path-in-output-schema.ts b/packages/twenty-shared/src/workflow/workflow-schema/utils/resolve-variable-path-in-output-schema.ts
index e5f44ebf106..fde1da84817 100644
--- a/packages/twenty-shared/src/workflow/workflow-schema/utils/resolve-variable-path-in-output-schema.ts
+++ b/packages/twenty-shared/src/workflow/workflow-schema/utils/resolve-variable-path-in-output-schema.ts
@@ -101,6 +101,11 @@ const resolveInGenericMap = (
segments: string[],
): ResolvedVariable => {
const [segment, ...rest] = segments;
+
+ if (!isDefined(segment)) {
+ return NOT_FOUND;
+ }
+
const field = map[segment];
if (isSchemaField(field)) {
diff --git a/packages/twenty-shared/tsconfig.json b/packages/twenty-shared/tsconfig.json
index fffeed0c92b..148cb33c06f 100644
--- a/packages/twenty-shared/tsconfig.json
+++ b/packages/twenty-shared/tsconfig.json
@@ -5,6 +5,7 @@
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"strictNullChecks": true,
+ "noUncheckedIndexedAccess": true,
"alwaysStrict": true,
"noImplicitAny": true,
"strictBindCallApply": false,