The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Implement MutationObserver in the front component worker sandbox (#23489)
Raphaël Bosi7cfb77e4d4b0
diff --git a/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx b/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsxindex f3900ae5f9e..824b1178857 100644--- a/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx+++ b/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx@@ -120,16 +120,9 @@ export const IconPreact: Story = createGalleryStory('preact',);-// KNOWN ISSUE (TDD): base-ui radio internals call MutationObserver.observe,-// shipped as an empty stub class by @remote-dom/polyfill.-const INPUT_EXPECTED_FAILURES = ['Radio', 'RadioGroup', 'CardPicker'];-export const InputReact: Story = createKnownFailureGalleryStory(+export const InputReact: Story = createGalleryStory('twenty-ui-input-gallery');+export const InputPreact: Story = createGalleryStory('twenty-ui-input-gallery',- INPUT_EXPECTED_FAILURES,-);-export const InputPreact: Story = createKnownFailureGalleryStory(- 'twenty-ui-input-gallery',- INPUT_EXPECTED_FAILURES,'preact',);@@ -161,15 +154,11 @@ export const NavigationPreact: Story = createKnownFailureGalleryStory('preact',);-// KNOWN ISSUE (TDD): AppTooltip observes document.body with the stubbed-out-// MutationObserver.-export const SurfacesReact: Story = createKnownFailureGalleryStory(+export const SurfacesReact: Story = createGalleryStory('twenty-ui-surfaces-gallery',- ['AppTooltip'],);-export const SurfacesPreact: Story = createKnownFailureGalleryStory(+export const SurfacesPreact: Story = createGalleryStory('twenty-ui-surfaces-gallery',- ['AppTooltip'],'preact',);diff --git a/packages/twenty-front-component-renderer/src/__stories__/WorkerPlatformApis.stories.tsx b/packages/twenty-front-component-renderer/src/__stories__/WorkerPlatformApis.stories.tsxindex 900834f1f60..c94ae94efa2 100644--- a/packages/twenty-front-component-renderer/src/__stories__/WorkerPlatformApis.stories.tsx+++ b/packages/twenty-front-component-renderer/src/__stories__/WorkerPlatformApis.stories.tsx@@ -1,11 +1,12 @@import { type Meta, type StoryObj } from '@storybook/react-vite';-import { expect, waitFor } from 'storybook/test';+import { expect, userEvent, waitFor, within } from 'storybook/test';import {errorHandler,FRONT_COMPONENT_STORY_DEFAULT_ARGS,resetFrontComponentStoryMocks,} from '@/__stories__/shared/test-utils/createFrontComponentStoryMeta';+import { MOUNT_TIMEOUT } from '@/__stories__/shared/test-utils/timeouts';import { getBuiltStoryComponentPathForRender } from '@/__stories__/utils/getBuiltStoryComponentPathForRender';import { FrontComponentRenderer } from '@/host/components/FrontComponentRenderer';@@ -22,25 +23,49 @@ const meta: Meta<typeof FrontComponentRenderer> = {export default meta;type Story = StoryObj<typeof FrontComponentRenderer>;-// KNOWN ISSUE (TDD) golden test: @remote-dom/polyfill ships MutationObserver-// as an empty class, so observe() throws and crashes the fixture at mount.-// When a real worker-local MutationObserver lands, flip this play to the-// behavior assertions below: click mutation-observer-add, then expect the-// data-observed count on mutation-observer-count to become greater than 0 and-// errorHandler not to have been called — a no-op stub cannot pass that.-const mutationObserverTest: Story['play'] = async () => {- // Matching the message keeps an unrelated worker failure (bundle load,- // import error, ...) from being cataloged as the MutationObserver gap.+const EXPECTED_OBSERVED_MUTATIONS = [+ {+ type: 'childList',+ addedItems: ['item-0'],+ removedItems: [],+ hasPreviousSibling: false,+ hasNextSibling: false,+ },+ {+ type: 'childList',+ addedItems: ['item-1'],+ removedItems: [],+ hasPreviousSibling: true,+ hasNextSibling: false,+ },+];++const mutationObserverTest: Story['play'] = async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ const addItemButton = await canvas.findByTestId(+ 'mutation-observer-add',+ {},+ { timeout: MOUNT_TIMEOUT },+ );++ await userEvent.click(addItemButton);+ await userEvent.click(addItemButton);+await waitFor(() => {- expect(errorHandler).toHaveBeenCalledWith(- expect.objectContaining({- message: expect.stringContaining('observe is not a function'),- }),- );+ expect(+ JSON.parse(+ canvas+ .getByTestId('mutation-observer-status')+ .getAttribute('data-observed-records') ?? '[]',+ ),+ ).toEqual(EXPECTED_OBSERVED_MUTATIONS);},- { timeout: 30000 },+ { timeout: MOUNT_TIMEOUT },);++ expect(errorHandler).not.toHaveBeenCalled();};const createStory = (name: string, runtime?: 'preact'): Story => ({diff --git a/packages/twenty-front-component-renderer/src/__stories__/showcase/mutation-observer-example.front-component.tsx b/packages/twenty-front-component-renderer/src/__stories__/showcase/mutation-observer-example.front-component.tsxindex 08b63292b4c..8cf874ba433 100644--- a/packages/twenty-front-component-renderer/src/__stories__/showcase/mutation-observer-example.front-component.tsx+++ b/packages/twenty-front-component-renderer/src/__stories__/showcase/mutation-observer-example.front-component.tsx@@ -1,11 +1,36 @@import { defineFrontComponent } from 'twenty-sdk/define';import { useEffect, useRef, useState } from 'react';+import { isDefined } from 'twenty-shared/utils';++type ObservedMutationEntry = {+ type: string;+ addedItems: string[];+ removedItems: string[];+ hasPreviousSibling: boolean;+ hasNextSibling: boolean;+};++const readItemName = (node: Node): string | null =>+ node instanceof Element ? node.getAttribute('data-item') : null;++const readItemNames = (nodes: NodeList): string[] =>+ Array.from(nodes).map(readItemName).filter(isDefined);++const toObservedMutationEntry = (+ record: MutationRecord,+): ObservedMutationEntry => ({+ type: record.type,+ addedItems: readItemNames(record.addedNodes),+ removedItems: readItemNames(record.removedNodes),+ hasPreviousSibling: isDefined(record.previousSibling),+ hasNextSibling: isDefined(record.nextSibling),+});-// Exercises real MutationObserver semantics inside the sandbox worker: the-// observer must fire for React-driven insertions into the observed subtree.const MutationObserverComponent = () => {const containerRef = useRef<HTMLDivElement>(null);- const [observedMutationCount, setObservedMutationCount] = useState(0);+ const [observedMutations, setObservedMutations] = useState<+ ObservedMutationEntry[]+ >([]);const [items, setItems] = useState<string[]>([]);useEffect(() => {@@ -16,11 +41,15 @@ const MutationObserverComponent = () => {}const observer = new MutationObserver((records) => {- const childListRecordCount = records.filter(- (record) => record.type === 'childList',- ).length;+ const containerEntries = records+ .filter((record) => record.target === container)+ .map(toObservedMutationEntry);++ if (containerEntries.length === 0) {+ return;+ }- setObservedMutationCount((previous) => previous + childListRecordCount);+ setObservedMutations((previous) => [...previous, ...containerEntries]);});observer.observe(container, { childList: true, subtree: true });@@ -43,14 +72,16 @@ const MutationObserverComponent = () => {</button><div ref={containerRef} data-testid="mutation-observer-container">{items.map((item) => (- <span key={item}>{item} </span>+ <span key={item} data-item={item}>+ {item}{' '}+ </span>))}</div><p- data-testid="mutation-observer-count"- data-observed={observedMutationCount}+ data-testid="mutation-observer-status"+ data-observed-records={JSON.stringify(observedMutations)}>- Mutations observed: {observedMutationCount}+ Mutations observed: {observedMutations.length}</p></div>);diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/constants/MutationObserverHooksUnavailableError.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/constants/MutationObserverHooksUnavailableError.tsnew file mode 100644index 00000000000..b908baa7b0e--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/constants/MutationObserverHooksUnavailableError.ts@@ -0,0 +1,2 @@+export const MUTATION_OBSERVER_HOOKS_UNAVAILABLE_ERROR =+ '[twenty-front-component] The @remote-dom polyfill hooks could not be resolved, so MutationObserver was not installed. The sandbox keeps the @remote-dom stub, which has no observe method, and any component calling observer.observe will throw.';diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/types/MutationObserverRegistration.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/types/MutationObserverRegistration.tsnew file mode 100644index 00000000000..6acc354ee06--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/types/MutationObserverRegistration.ts@@ -0,0 +1,7 @@+import { type MutationRecordSink } from '@/polyfills/dom/types/MutationRecordSink';++export type MutationObserverRegistration = {+ sink: MutationRecordSink;+ options: MutationObserverInit;+ isTransient: boolean;+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/types/MutationObserverRegistry.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/types/MutationObserverRegistry.tsnew file mode 100644index 00000000000..d68f86e0c5d--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/types/MutationObserverRegistry.ts@@ -0,0 +1,24 @@+import { type MutationRecordSink } from '@/polyfills/dom/types/MutationRecordSink';+import { type WorkerMutationRecord } from '@/polyfills/dom/types/WorkerMutationRecord';++export type MutationObserverRegistry = {+ hasObservations: () => boolean;+ registerObservation: (input: {+ target: Node;+ sink: MutationRecordSink;+ options: MutationObserverInit;+ }) => void;+ unregisterObservations: (input: {+ targets: Iterable<Node>;+ sink: MutationRecordSink;+ }) => void;+ registerTransientObservations: (input: {+ detachedNode: Node;+ formerParent: Node;+ }) => void;+ clearTransientObservations: (input: { sink: MutationRecordSink }) => void;+ broadcastMutationRecord: (input: {+ record: WorkerMutationRecord;+ oldValue: string | null;+ }) => void;+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/types/MutationRecordSink.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/types/MutationRecordSink.tsnew file mode 100644index 00000000000..100f121f7ed--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/types/MutationRecordSink.ts@@ -0,0 +1,6 @@+import { type WorkerMutationRecord } from '@/polyfills/dom/types/WorkerMutationRecord';++export type MutationRecordSink = {+ enqueueMutationRecord: (record: WorkerMutationRecord) => void;+ scheduleDelivery: () => void;+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/types/WorkerMutationObserver.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/types/WorkerMutationObserver.tsnew file mode 100644index 00000000000..350e8c98f29--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/types/WorkerMutationObserver.ts@@ -0,0 +1,7 @@+import { type WorkerMutationRecord } from '@/polyfills/dom/types/WorkerMutationRecord';++export type WorkerMutationObserver = {+ observe: (target: Node, options?: MutationObserverInit) => void;+ disconnect: () => void;+ takeRecords: () => WorkerMutationRecord[];+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/types/WorkerMutationObserverCallback.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/types/WorkerMutationObserverCallback.tsnew file mode 100644index 00000000000..37283bb7b43--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/types/WorkerMutationObserverCallback.ts@@ -0,0 +1,7 @@+import { type WorkerMutationObserver } from '@/polyfills/dom/types/WorkerMutationObserver';+import { type WorkerMutationRecord } from '@/polyfills/dom/types/WorkerMutationRecord';++export type WorkerMutationObserverCallback = (+ records: WorkerMutationRecord[],+ observer: WorkerMutationObserver,+) => void;diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/types/WorkerMutationRecord.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/types/WorkerMutationRecord.tsnew file mode 100644index 00000000000..00db0f9312f--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/types/WorkerMutationRecord.ts@@ -0,0 +1,13 @@+import { type WorkerNodeList } from '@/polyfills/dom/types/WorkerNodeList';++export type WorkerMutationRecord = {+ type: MutationRecordType;+ target: Node;+ addedNodes: WorkerNodeList;+ removedNodes: WorkerNodeList;+ previousSibling: Node | null;+ nextSibling: Node | null;+ attributeName: string | null;+ attributeNamespace: string | null;+ oldValue: string | null;+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/types/WorkerNodeList.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/types/WorkerNodeList.tsnew file mode 100644index 00000000000..58114cf8903--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/types/WorkerNodeList.ts@@ -0,0 +1,3 @@+export type WorkerNodeList = Node[] & {+ item: (index: number) => Node | null;+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/createMutationObserverRegistry.test.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/createMutationObserverRegistry.test.tsnew file mode 100644index 00000000000..305b5c8d629--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/createMutationObserverRegistry.test.ts@@ -0,0 +1,188 @@+import { type MutationRecordSink } from '@/polyfills/dom/types/MutationRecordSink';+import { type WorkerMutationRecord } from '@/polyfills/dom/types/WorkerMutationRecord';+import { createMutationObserverRegistry } from '@/polyfills/dom/utils/createMutationObserverRegistry';+import { createMutationRecord } from '@/polyfills/dom/utils/createMutationRecord';++const createFakeNode = (parentNode: Node | null = null) =>+ ({ parentNode }) as unknown as Node;++const createFakeSink = () => {+ const records: WorkerMutationRecord[] = [];+ const scheduleDelivery = jest.fn();++ const sink: MutationRecordSink = {+ enqueueMutationRecord: (record) => {+ records.push(record);+ },+ scheduleDelivery,+ };++ return { sink, records, scheduleDelivery };+};++describe('createMutationObserverRegistry', () => {+ it('registers a transient observation once per detachment batch', () => {+ const registry = createMutationObserverRegistry();+ const { sink, scheduleDelivery } = createFakeSink();++ const formerParent = createFakeNode();+ const detachedNode = createFakeNode();++ registry.registerObservation({+ target: formerParent,+ sink,+ options: { childList: true, subtree: true },+ });++ registry.registerTransientObservations({ detachedNode, formerParent });+ registry.registerTransientObservations({ detachedNode, formerParent });+ registry.registerTransientObservations({ detachedNode, formerParent });++ expect(scheduleDelivery).toHaveBeenCalledTimes(1);+ });++ it('registers a transient observation again after the observer took delivery', () => {+ const registry = createMutationObserverRegistry();+ const { sink, scheduleDelivery } = createFakeSink();++ const formerParent = createFakeNode();+ const detachedNode = createFakeNode();++ registry.registerObservation({+ target: formerParent,+ sink,+ options: { childList: true, subtree: true },+ });++ registry.registerTransientObservations({ detachedNode, formerParent });+ registry.clearTransientObservations({ sink });+ registry.registerTransientObservations({ detachedNode, formerParent });++ expect(scheduleDelivery).toHaveBeenCalledTimes(2);+ });++ it('keeps one transient observation per distinct options object of the same observer', () => {+ const registry = createMutationObserverRegistry();+ const { sink, records } = createFakeSink();++ const root = createFakeNode();+ const formerParent = createFakeNode(root);+ const detachedNode = createFakeNode();++ registry.registerObservation({+ target: root,+ sink,+ options: { childList: true, subtree: true },+ });+ registry.registerObservation({+ target: formerParent,+ sink,+ options: { attributes: true, subtree: true },+ });++ registry.registerTransientObservations({ detachedNode, formerParent });++ registry.broadcastMutationRecord({+ record: createMutationRecord({+ type: 'attributes',+ target: detachedNode,+ attributeName: 'data-open',+ }),+ oldValue: 'true',+ });+ registry.broadcastMutationRecord({+ record: createMutationRecord({+ type: 'childList',+ target: detachedNode,+ addedNodes: [createFakeNode()],+ }),+ oldValue: null,+ });++ expect(records.map((record) => record.type)).toEqual([+ 'attributes',+ 'childList',+ ]);+ });++ it('gives each sink its own added node list', () => {+ const registry = createMutationObserverRegistry();+ const firstSink = createFakeSink();+ const secondSink = createFakeSink();++ const target = createFakeNode();+ const addedNode = createFakeNode();++ registry.registerObservation({+ target,+ sink: firstSink.sink,+ options: { childList: true },+ });+ registry.registerObservation({+ target,+ sink: secondSink.sink,+ options: { childList: true },+ });++ registry.broadcastMutationRecord({+ record: createMutationRecord({+ type: 'childList',+ target,+ addedNodes: [addedNode],+ }),+ oldValue: null,+ });++ expect(firstSink.records[0].addedNodes).not.toBe(+ secondSink.records[0].addedNodes,+ );+ expect(firstSink.records[0].addedNodes).toEqual([addedNode]);+ expect(secondSink.records[0].addedNodes).toEqual([addedNode]);+ });++ it('stops broadcasting after the last observation was unregistered', () => {+ const registry = createMutationObserverRegistry();+ const { sink, records } = createFakeSink();++ const target = createFakeNode();++ registry.registerObservation({+ target,+ sink,+ options: { childList: true },+ });+ registry.unregisterObservations({ targets: [target], sink });++ registry.broadcastMutationRecord({+ record: createMutationRecord({+ type: 'childList',+ target,+ addedNodes: [createFakeNode()],+ }),+ oldValue: null,+ });++ expect(records).toHaveLength(0);+ });++ it('reports whether any observation is registered', () => {+ const registry = createMutationObserverRegistry();+ const { sink } = createFakeSink();++ const target = createFakeNode();++ expect(registry.hasObservations()).toBe(false);++ registry.registerObservation({+ target,+ sink,+ options: { childList: true },+ });++ expect(registry.hasObservations()).toBe(true);++ registry.unregisterObservations({ targets: [target], sink });++ expect(registry.hasObservations()).toBe(false);+ });+});diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/installMutationObserver.test.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/installMutationObserver.test.tsnew file mode 100644index 00000000000..6a9c7c3d894--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/installMutationObserver.test.ts@@ -0,0 +1,851 @@+import { HOOKS, type Hooks, Window } from '@remote-dom/polyfill';++import { MUTATION_OBSERVER_HOOKS_UNAVAILABLE_ERROR } from '@/polyfills/dom/constants/MutationObserverHooksUnavailableError';+import { type WorkerMutationObserver } from '@/polyfills/dom/types/WorkerMutationObserver';+import { type WorkerMutationObserverCallback } from '@/polyfills/dom/types/WorkerMutationObserverCallback';+import { type WorkerMutationRecord } from '@/polyfills/dom/types/WorkerMutationRecord';+import { installMutationObserver } from '@/polyfills/dom/utils/installMutationObserver';++type WorkerMutationObserverConstructor = new (+ callback: WorkerMutationObserverCallback,+) => WorkerMutationObserver;++const createSandbox = (installHooks?: (hooks: Partial<Hooks>) => void) => {+ const polyfillWindow = new Window();+ const globalScope: Record<string, unknown> = { window: polyfillWindow };++ installHooks?.(+ (polyfillWindow as unknown as Record<symbol, Partial<Hooks>>)[HOOKS],+ );++ installMutationObserver({ globalScope });++ return {+ globalScope,+ polyfillWindow: polyfillWindow as unknown as Record<string, unknown>,+ document: polyfillWindow.document as unknown as Document,+ MutationObserver:+ globalScope.MutationObserver as WorkerMutationObserverConstructor,+ };+};++const createRecordCollector = () => {+ const deliveries: WorkerMutationRecord[][] = [];+ const observers: WorkerMutationObserver[] = [];++ const collect: WorkerMutationObserverCallback = (records, observer) => {+ deliveries.push(records);+ observers.push(observer);+ };++ return { collect, deliveries, observers };+};++type ReportedErrorEvent = {+ error: unknown;+ preventDefault: () => void;+};++const collectReportedErrors = (polyfillWindow: Record<string, unknown>) => {+ const reportedErrors: unknown[] = [];++ (+ polyfillWindow.addEventListener as (+ type: string,+ listener: (event: ReportedErrorEvent) => void,+ ) => void+ )('error', (event) => {+ event.preventDefault();+ reportedErrors.push(event.error);+ });++ return reportedErrors;+};++const flushMicrotasks = async () => {+ await Promise.resolve();+ await Promise.resolve();+};++describe('installMutationObserver', () => {+ afterEach(() => {+ jest.restoreAllMocks();+ });++ it('installs the implementation on the global scope and on the polyfill window', () => {+ const { globalScope, polyfillWindow, MutationObserver } = createSandbox();++ expect(typeof MutationObserver).toBe('function');+ expect(polyfillWindow.MutationObserver).toBe(globalScope.MutationObserver);+ });++ it('exposes the spec methods on the prototype', () => {+ const { MutationObserver } = createSandbox();++ expect(typeof MutationObserver.prototype.observe).toBe('function');+ expect(typeof MutationObserver.prototype.disconnect).toBe('function');+ expect(typeof MutationObserver.prototype.takeRecords).toBe('function');+ });++ it('keeps the hooks already installed by remote-dom working', () => {+ const insertChildArguments: unknown[][] = [];+ const setAttributeArguments: unknown[][] = [];+ const { document } = createSandbox((hooks) => {+ hooks.insertChild = (...args) => insertChildArguments.push(args);+ hooks.setAttribute = (...args) => setAttributeArguments.push(args);+ });++ const child = document.createElement('span');+ document.body.appendChild(child);+ child.setAttribute('title', 'hello');++ expect(insertChildArguments).toHaveLength(1);+ expect(insertChildArguments[0][0]).toBe(document.body);+ expect(insertChildArguments[0][1]).toBe(child);+ expect(insertChildArguments[0][2]).toBe(0);++ expect(setAttributeArguments).toHaveLength(1);+ expect(setAttributeArguments[0][0]).toBe(child);+ expect(setAttributeArguments[0][1]).toBe('title');+ expect(setAttributeArguments[0][2]).toBe('hello');+ });++ it('reports childList insertions on the observed target', async () => {+ const { document, MutationObserver } = createSandbox();+ const { collect, deliveries } = createRecordCollector();++ const container = document.createElement('div');+ document.body.appendChild(container);++ new MutationObserver(collect).observe(container, { childList: true });++ const child = document.createElement('span');+ container.appendChild(child);++ await flushMicrotasks();++ expect(deliveries).toHaveLength(1);+ expect(deliveries[0]).toHaveLength(1);++ const [record] = deliveries[0];+ expect(record.type).toBe('childList');+ expect(record.target).toBe(container);+ expect(record.addedNodes).toEqual([child]);+ expect(record.removedNodes).toEqual([]);+ expect(record.previousSibling).toBeNull();+ expect(record.nextSibling).toBeNull();+ expect(record.oldValue).toBeNull();+ });++ it('reports siblings of an inserted node', async () => {+ const { document, MutationObserver } = createSandbox();+ const { collect, deliveries } = createRecordCollector();++ const container = document.createElement('div');+ const firstChild = document.createElement('span');+ const lastChild = document.createElement('span');+ container.appendChild(firstChild);+ container.appendChild(lastChild);++ new MutationObserver(collect).observe(container, { childList: true });++ const insertedChild = document.createElement('span');+ container.insertBefore(insertedChild, lastChild);++ await flushMicrotasks();++ const [record] = deliveries[0];+ expect(record.addedNodes).toEqual([insertedChild]);+ expect(record.previousSibling).toBe(firstChild);+ expect(record.nextSibling).toBe(lastChild);+ });++ it('reports childList removals with the surrounding siblings', async () => {+ const { document, MutationObserver } = createSandbox();+ const { collect, deliveries } = createRecordCollector();++ const container = document.createElement('div');+ const firstChild = document.createElement('span');+ const removedChild = document.createElement('span');+ const lastChild = document.createElement('span');+ container.appendChild(firstChild);+ container.appendChild(removedChild);+ container.appendChild(lastChild);++ new MutationObserver(collect).observe(container, { childList: true });++ container.removeChild(removedChild);++ await flushMicrotasks();++ const [record] = deliveries[0];+ expect(record.type).toBe('childList');+ expect(record.target).toBe(container);+ expect(record.addedNodes).toEqual([]);+ expect(record.removedNodes).toEqual([removedChild]);+ expect(record.previousSibling).toBe(firstChild);+ expect(record.nextSibling).toBe(lastChild);+ });++ it('keeps observing a subtree that was detached earlier in the same batch', async () => {+ const { document, MutationObserver } = createSandbox();+ const { collect, deliveries } = createRecordCollector();++ const container = document.createElement('div');+ const branch = document.createElement('div');+ container.appendChild(branch);++ new MutationObserver(collect).observe(container, {+ childList: true,+ subtree: true,+ });++ container.removeChild(branch);++ const lateChild = document.createElement('span');+ branch.appendChild(lateChild);++ await flushMicrotasks();++ expect(deliveries[0]).toHaveLength(2);+ expect(deliveries[0][0].removedNodes).toEqual([branch]);+ expect(deliveries[0][1].target).toBe(branch);+ expect(deliveries[0][1].addedNodes).toEqual([lateChild]);+ });++ it('stops observing a detached subtree once its records were delivered', async () => {+ const { document, MutationObserver } = createSandbox();+ const { collect, deliveries } = createRecordCollector();++ const container = document.createElement('div');+ const branch = document.createElement('div');+ container.appendChild(branch);++ new MutationObserver(collect).observe(container, {+ childList: true,+ subtree: true,+ });++ container.removeChild(branch);++ await flushMicrotasks();++ branch.appendChild(document.createElement('span'));++ await flushMicrotasks();++ expect(deliveries).toHaveLength(1);+ expect(deliveries[0]).toHaveLength(1);+ });++ it('clears transient registrations even when the removal queued no record', async () => {+ const { document, MutationObserver } = createSandbox();+ const { collect, deliveries } = createRecordCollector();++ const container = document.createElement('div');+ const branch = document.createElement('div');+ container.appendChild(branch);++ new MutationObserver(collect).observe(container, {+ attributes: true,+ subtree: true,+ });++ container.removeChild(branch);+ branch.setAttribute('data-open', 'true');++ await flushMicrotasks();++ expect(deliveries).toHaveLength(1);+ expect(deliveries[0]).toHaveLength(1);+ expect(deliveries[0][0].attributeName).toBe('data-open');++ branch.setAttribute('data-open', 'false');++ await flushMicrotasks();++ expect(deliveries).toHaveLength(1);+ });++ it('delivers a detached subtree mutation only once when the node is reattached', async () => {+ const { document, MutationObserver } = createSandbox();+ const { collect, deliveries } = createRecordCollector();++ const container = document.createElement('div');+ const branch = document.createElement('div');+ container.appendChild(branch);++ new MutationObserver(collect).observe(container, {+ childList: true,+ subtree: true,+ });++ container.removeChild(branch);+ container.appendChild(branch);+ branch.appendChild(document.createElement('span'));++ await flushMicrotasks();++ const childListOnBranch = deliveries[0].filter(+ (record) => record.target === branch,+ );++ expect(childListOnBranch).toHaveLength(1);+ });++ it('ignores descendant mutations unless subtree is requested', async () => {+ const { document, MutationObserver } = createSandbox();+ const { collect, deliveries } = createRecordCollector();++ const container = document.createElement('div');+ const nestedContainer = document.createElement('div');+ container.appendChild(nestedContainer);++ new MutationObserver(collect).observe(container, { childList: true });++ nestedContainer.appendChild(document.createElement('span'));++ await flushMicrotasks();++ expect(deliveries).toHaveLength(0);+ });++ it('reports descendant mutations when subtree is requested', async () => {+ const { document, MutationObserver } = createSandbox();+ const { collect, deliveries } = createRecordCollector();++ const container = document.createElement('div');+ const nestedContainer = document.createElement('div');+ container.appendChild(nestedContainer);++ new MutationObserver(collect).observe(container, {+ childList: true,+ subtree: true,+ });++ const child = document.createElement('span');+ nestedContainer.appendChild(child);++ await flushMicrotasks();++ const [record] = deliveries[0];+ expect(record.type).toBe('childList');+ expect(record.target).toBe(nestedContainer);+ expect(record.addedNodes).toEqual([child]);+ });++ it('reports attribute mutations with their old value', async () => {+ const { document, MutationObserver } = createSandbox();+ const { collect, deliveries } = createRecordCollector();++ const element = document.createElement('div');+ element.setAttribute('title', 'first');++ new MutationObserver(collect).observe(element, {+ attributes: true,+ attributeOldValue: true,+ });++ element.setAttribute('title', 'second');++ await flushMicrotasks();++ const [record] = deliveries[0];+ expect(record.type).toBe('attributes');+ expect(record.target).toBe(element);+ expect(record.attributeName).toBe('title');+ expect(record.attributeNamespace).toBeNull();+ expect(record.oldValue).toBe('first');+ });++ it('omits the old value when it was not requested', async () => {+ const { document, MutationObserver } = createSandbox();+ const { collect, deliveries } = createRecordCollector();++ const element = document.createElement('div');+ element.setAttribute('title', 'first');++ new MutationObserver(collect).observe(element, { attributes: true });++ element.setAttribute('title', 'second');++ await flushMicrotasks();++ expect(deliveries[0][0].oldValue).toBeNull();+ });++ it('reports attribute removals', async () => {+ const { document, MutationObserver } = createSandbox();+ const { collect, deliveries } = createRecordCollector();++ const element = document.createElement('div');+ element.setAttribute('title', 'first');++ new MutationObserver(collect).observe(element, {+ attributes: true,+ attributeOldValue: true,+ });++ element.removeAttribute('title');++ await flushMicrotasks();++ const [record] = deliveries[0];+ expect(record.type).toBe('attributes');+ expect(record.attributeName).toBe('title');+ expect(record.oldValue).toBe('first');+ });++ it('only reports attributes listed in attributeFilter', async () => {+ const { document, MutationObserver } = createSandbox();+ const { collect, deliveries } = createRecordCollector();++ const element = document.createElement('div');++ new MutationObserver(collect).observe(element, {+ attributes: true,+ attributeFilter: ['data-starting-style'],+ });++ element.setAttribute('title', 'ignored');+ element.setAttribute('data-starting-style', '');++ await flushMicrotasks();++ expect(deliveries[0]).toHaveLength(1);+ expect(deliveries[0][0].attributeName).toBe('data-starting-style');+ });++ it('reports character data mutations with their old value', async () => {+ const { document, MutationObserver } = createSandbox();+ const { collect, deliveries } = createRecordCollector();++ const text = document.createTextNode('first');++ new MutationObserver(collect).observe(text, {+ characterData: true,+ characterDataOldValue: true,+ });++ text.data = 'second';++ await flushMicrotasks();++ const [record] = deliveries[0];+ expect(record.type).toBe('characterData');+ expect(record.target).toBe(text);+ expect(record.oldValue).toBe('first');+ });++ it('reports the old value of character data mutated before any observer existed', async () => {+ const { document, MutationObserver } = createSandbox();+ const { collect, deliveries } = createRecordCollector();++ const text = document.createTextNode('first');+ text.data = 'second';++ new MutationObserver(collect).observe(text, {+ characterData: true,+ characterDataOldValue: true,+ });++ text.data = 'third';++ await flushMicrotasks();++ expect(deliveries[0][0].oldValue).toBe('second');+ });++ it('batches every mutation of a microtask into a single callback', async () => {+ const { document, MutationObserver } = createSandbox();+ const { collect, deliveries } = createRecordCollector();++ const container = document.createElement('div');++ new MutationObserver(collect).observe(container, {+ childList: true,+ attributes: true,+ });++ container.appendChild(document.createElement('span'));+ container.appendChild(document.createElement('span'));+ container.setAttribute('title', 'batched');++ await flushMicrotasks();++ expect(deliveries).toHaveLength(1);+ expect(deliveries[0]).toHaveLength(3);+ });++ it('passes the observer as the second callback argument', async () => {+ const { document, MutationObserver } = createSandbox();+ const { collect, observers } = createRecordCollector();++ const container = document.createElement('div');+ const observer = new MutationObserver(collect);+ observer.observe(container, { childList: true });++ container.appendChild(document.createElement('span'));++ await flushMicrotasks();++ expect(observers[0]).toBe(observer);+ });++ it('stops delivering after disconnect', async () => {+ const { document, MutationObserver } = createSandbox();+ const { collect, deliveries } = createRecordCollector();++ const container = document.createElement('div');+ const observer = new MutationObserver(collect);+ observer.observe(container, { childList: true });++ container.appendChild(document.createElement('span'));+ observer.disconnect();++ await flushMicrotasks();++ container.appendChild(document.createElement('span'));++ await flushMicrotasks();++ expect(deliveries).toHaveLength(0);+ });++ it('delivers records again when a target is re-observed after disconnect', async () => {+ const { document, MutationObserver } = createSandbox();+ const { collect, deliveries } = createRecordCollector();++ const container = document.createElement('div');+ const observer = new MutationObserver(collect);+ observer.observe(container, { childList: true });+ observer.disconnect();+ observer.observe(container, { childList: true });++ container.appendChild(document.createElement('span'));++ await flushMicrotasks();++ expect(deliveries).toHaveLength(1);+ });++ it('stops delivering after a disconnect that followed a re-observe of the same target', async () => {+ const { document, MutationObserver } = createSandbox();+ const { collect, deliveries } = createRecordCollector();++ const container = document.createElement('div');+ const observer = new MutationObserver(collect);+ observer.observe(container, { childList: true });+ observer.disconnect();+ observer.observe(container, { childList: true });+ observer.disconnect();++ new MutationObserver(() => {}).observe(container, { childList: true });++ container.appendChild(document.createElement('span'));++ await flushMicrotasks();++ expect(deliveries).toHaveLength(0);+ });++ it('stops delivering to an observer disconnected from another callback', async () => {+ const { document, MutationObserver } = createSandbox();+ const { collect, deliveries } = createRecordCollector();++ const container = document.createElement('div');+ const disconnectedObserver = new MutationObserver(collect);++ new MutationObserver(() => {+ disconnectedObserver.disconnect();+ }).observe(container, { childList: true });+ disconnectedObserver.observe(container, { childList: true });++ container.appendChild(document.createElement('span'));++ await flushMicrotasks();++ expect(deliveries).toHaveLength(0);+ });++ it('drains the queue through takeRecords', async () => {+ const { document, MutationObserver } = createSandbox();+ const { collect, deliveries } = createRecordCollector();++ const container = document.createElement('div');+ const observer = new MutationObserver(collect);+ observer.observe(container, { childList: true });++ container.appendChild(document.createElement('span'));++ expect(observer.takeRecords()).toHaveLength(1);+ expect(observer.takeRecords()).toHaveLength(0);++ await flushMicrotasks();++ expect(deliveries).toHaveLength(0);+ });++ it('replaces the options when the same target is observed twice', async () => {+ const { document, MutationObserver } = createSandbox();+ const { collect, deliveries } = createRecordCollector();++ const container = document.createElement('div');+ const observer = new MutationObserver(collect);+ observer.observe(container, { childList: true, attributes: true });+ observer.observe(container, { attributes: true });++ container.appendChild(document.createElement('span'));++ await flushMicrotasks();++ expect(deliveries).toHaveLength(0);+ });++ it('reports a throwing callback on the polyfill window and keeps other observers alive', async () => {+ const { document, polyfillWindow, MutationObserver } = createSandbox();+ const { collect, deliveries } = createRecordCollector();+ const reportedErrors = collectReportedErrors(polyfillWindow);+ const callbackError = new Error('guest failure');++ const container = document.createElement('div');++ new MutationObserver(() => {+ throw callbackError;+ }).observe(container, { childList: true });+ new MutationObserver(collect).observe(container, { childList: true });++ container.appendChild(document.createElement('span'));++ await flushMicrotasks();++ expect(reportedErrors).toEqual([callbackError]);+ expect(deliveries).toHaveLength(1);+ });++ it('keeps other observers alive when a callback throws an unstringifiable value', async () => {+ const { document, MutationObserver } = createSandbox();+ jest.spyOn(console, 'error').mockImplementation(() => {});+ const { collect, deliveries } = createRecordCollector();++ const container = document.createElement('div');++ new MutationObserver(() => {+ throw Object.create(null);+ }).observe(container, { childList: true });+ new MutationObserver(collect).observe(container, { childList: true });++ container.appendChild(document.createElement('span'));++ await flushMicrotasks();++ expect(deliveries).toHaveLength(1);+ });++ it('rejects a callback that is not a function', () => {+ const { MutationObserver } = createSandbox();++ expect(+ () =>+ new MutationObserver(123 as unknown as WorkerMutationObserverCallback),+ ).toThrow(TypeError);+ });++ it('logs a throwing callback that no error listener handled', async () => {+ const { document, MutationObserver } = createSandbox();+ const consoleErrorSpy = jest+ .spyOn(console, 'error')+ .mockImplementation(() => {});+ const callbackError = new Error('guest failure');++ const container = document.createElement('div');++ new MutationObserver(() => {+ throw callbackError;+ }).observe(container, { childList: true });++ container.appendChild(document.createElement('span'));++ await flushMicrotasks();++ expect(consoleErrorSpy).toHaveBeenCalledWith(+ expect.stringContaining('was not handled'),+ callbackError,+ );+ });++ it('observes document.body the way AppTooltip does', async () => {+ const { document, MutationObserver } = createSandbox();+ const { collect, deliveries } = createRecordCollector();++ new MutationObserver(collect).observe(document.body, {+ childList: true,+ subtree: true,+ attributes: true,+ attributeFilter: ['data-tooltip-id'],+ });++ const anchor = document.createElement('button');+ document.body.appendChild(anchor);+ anchor.setAttribute('data-tooltip-id', 'tooltip');+ anchor.setAttribute('class', 'ignored');++ await flushMicrotasks();++ expect(deliveries[0]).toHaveLength(2);+ expect(deliveries[0][0].type).toBe('childList');+ expect(deliveries[0][0].addedNodes).toEqual([anchor]);+ expect(deliveries[0][1].type).toBe('attributes');+ expect(deliveries[0][1].attributeName).toBe('data-tooltip-id');+ });++ it('rejects an options object that observes nothing', () => {+ const { document, MutationObserver } = createSandbox();++ const observer = new MutationObserver(() => {});++ expect(() => observer.observe(document.body, { subtree: true })).toThrow(+ TypeError,+ );+ });++ it('accepts an options object that switches a refinement off', () => {+ const { document, MutationObserver } = createSandbox();++ const observer = new MutationObserver(() => {});++ expect(() =>+ observer.observe(document.body, {+ childList: true,+ attributes: false,+ attributeOldValue: false,+ }),+ ).not.toThrow();+ });++ it('exposes added and removed nodes as a node list', async () => {+ const { document, MutationObserver } = createSandbox();+ const { collect, deliveries } = createRecordCollector();++ const container = document.createElement('div');++ new MutationObserver(collect).observe(container, { childList: true });++ const child = document.createElement('span');+ container.appendChild(child);++ await flushMicrotasks();++ const [record] = deliveries[0];+ expect(record.addedNodes).toHaveLength(1);+ expect(record.addedNodes.item(0)).toBe(child);+ expect(record.addedNodes.item(1)).toBeNull();+ expect(record.addedNodes.item(-1)).toBeNull();+ expect(record.removedNodes.item(0)).toBeNull();+ });++ it('gives every observer its own record and its own node lists', async () => {+ const { document, MutationObserver } = createSandbox();+ const firstCollector = createRecordCollector();+ const secondCollector = createRecordCollector();++ const container = document.createElement('div');++ new MutationObserver(firstCollector.collect).observe(container, {+ childList: true,+ });+ new MutationObserver(secondCollector.collect).observe(container, {+ childList: true,+ });++ container.appendChild(document.createElement('span'));++ await flushMicrotasks();++ const firstRecord = firstCollector.deliveries[0][0];+ const secondRecord = secondCollector.deliveries[0][0];++ expect(firstRecord).not.toBe(secondRecord);+ expect(firstRecord.addedNodes).not.toBe(secondRecord.addedNodes);++ firstRecord.addedNodes.length = 0;++ expect(secondRecord.addedNodes).toHaveLength(1);+ });++ it('does not leak an observer from one mutation into the next', async () => {+ const { document, MutationObserver } = createSandbox();+ const firstCollector = createRecordCollector();+ const secondCollector = createRecordCollector();++ const firstElement = document.createElement('div');+ const secondElement = document.createElement('div');++ new MutationObserver(firstCollector.collect).observe(firstElement, {+ attributes: true,+ });+ new MutationObserver(secondCollector.collect).observe(secondElement, {+ attributes: true,+ });++ firstElement.setAttribute('title', 'first');+ secondElement.setAttribute('title', 'second');++ await flushMicrotasks();++ expect(firstCollector.deliveries[0]).toHaveLength(1);+ expect(firstCollector.deliveries[0][0].target).toBe(firstElement);+ expect(secondCollector.deliveries[0]).toHaveLength(1);+ expect(secondCollector.deliveries[0][0].target).toBe(secondElement);+ });++ it('reports the old value of a comment node', async () => {+ const { document, MutationObserver } = createSandbox();+ const { collect, deliveries } = createRecordCollector();++ const comment = document.createComment('first');++ new MutationObserver(collect).observe(comment, {+ characterData: true,+ characterDataOldValue: true,+ });++ comment.data = 'second';++ await flushMicrotasks();++ expect(deliveries[0][0].oldValue).toBe('first');+ });++ it('reports null siblings at the edges of the child list', async () => {+ const { document, MutationObserver } = createSandbox();+ const { collect, deliveries } = createRecordCollector();++ const container = document.createElement('div');+ const onlyChild = document.createElement('span');+ container.appendChild(onlyChild);++ new MutationObserver(collect).observe(container, { childList: true });++ container.removeChild(onlyChild);++ await flushMicrotasks();++ expect(deliveries[0][0].previousSibling).toBeNull();+ expect(deliveries[0][0].nextSibling).toBeNull();+ });++ it('reports that it could not install without the polyfill hooks', () => {+ const consoleErrorSpy = jest+ .spyOn(console, 'error')+ .mockImplementation(() => {});+ const globalScope: Record<string, unknown> = {};++ installMutationObserver({ globalScope });++ expect(globalScope.MutationObserver).toBeUndefined();+ expect(consoleErrorSpy).toHaveBeenCalledWith(+ MUTATION_OBSERVER_HOOKS_UNAVAILABLE_ERROR,+ );+ });+});diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/normalizeMutationObserverInit.test.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/normalizeMutationObserverInit.test.tsnew file mode 100644index 00000000000..5abf3f16c62--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/normalizeMutationObserverInit.test.ts@@ -0,0 +1,157 @@+import { normalizeMutationObserverInit } from '@/polyfills/dom/utils/normalizeMutationObserverInit';++describe('normalizeMutationObserverInit', () => {+ it('turns attributes on when only attributeFilter is given', () => {+ expect(+ normalizeMutationObserverInit({ attributeFilter: ['data-open'] }),+ ).toEqual({+ attributes: true,+ characterData: false,+ attributeFilter: ['data-open'],+ });+ });++ it('turns attributes on when only attributeOldValue is given', () => {+ expect(normalizeMutationObserverInit({ attributeOldValue: true })).toEqual({+ attributes: true,+ characterData: false,+ attributeOldValue: true,+ });+ });++ it('turns attributes on when attributeOldValue is present but false', () => {+ expect(normalizeMutationObserverInit({ attributeOldValue: false })).toEqual(+ {+ attributes: true,+ characterData: false,+ attributeOldValue: false,+ },+ );+ });++ it('turns characterData on when characterDataOldValue is present but false', () => {+ expect(+ normalizeMutationObserverInit({ characterDataOldValue: false }),+ ).toEqual({+ attributes: false,+ characterData: true,+ characterDataOldValue: false,+ });+ });++ it('turns characterData on when only characterDataOldValue is given', () => {+ expect(+ normalizeMutationObserverInit({ characterDataOldValue: true }),+ ).toEqual({+ attributes: false,+ characterData: true,+ characterDataOldValue: true,+ });+ });++ it('keeps the options untouched when they are already explicit', () => {+ expect(+ normalizeMutationObserverInit({+ childList: true,+ subtree: true,+ attributes: false,+ characterData: false,+ }),+ ).toEqual({+ childList: true,+ subtree: true,+ attributes: false,+ characterData: false,+ });+ });++ it('rejects attributeFilter when attributes is explicitly off', () => {+ expect(() =>+ normalizeMutationObserverInit({+ childList: true,+ attributes: false,+ attributeFilter: ['data-open'],+ }),+ ).toThrow(TypeError);+ });++ it('rejects attributeOldValue set to true when attributes is explicitly off', () => {+ expect(() =>+ normalizeMutationObserverInit({+ childList: true,+ attributes: false,+ attributeOldValue: true,+ }),+ ).toThrow(TypeError);+ });++ it('rejects characterDataOldValue set to true when characterData is explicitly off', () => {+ expect(() =>+ normalizeMutationObserverInit({+ childList: true,+ characterData: false,+ characterDataOldValue: true,+ }),+ ).toThrow(TypeError);+ });++ it('accepts attributeOldValue set to false when attributes is explicitly off', () => {+ expect(+ normalizeMutationObserverInit({+ childList: true,+ attributes: false,+ attributeOldValue: false,+ }),+ ).toEqual({+ childList: true,+ attributes: false,+ characterData: false,+ attributeOldValue: false,+ });+ });++ it('accepts characterDataOldValue set to false when characterData is explicitly off', () => {+ expect(+ normalizeMutationObserverInit({+ childList: true,+ characterData: false,+ characterDataOldValue: false,+ }),+ ).toEqual({+ childList: true,+ attributes: false,+ characterData: false,+ characterDataOldValue: false,+ });+ });++ it('rejects options that observe nothing', () => {+ expect(() => normalizeMutationObserverInit({})).toThrow(TypeError);+ expect(() => normalizeMutationObserverInit({ subtree: true })).toThrow(+ TypeError,+ );+ });++ it('reports the empty observation before the refinement mismatch', () => {+ expect(() =>+ normalizeMutationObserverInit({+ attributes: false,+ attributeOldValue: true,+ }),+ ).toThrow(/at least one of/);+ });++ it('copies attributeFilter so the caller cannot change it after observe', () => {+ const attributeFilter = ['data-open'];++ const normalizedOptions = normalizeMutationObserverInit({+ attributes: true,+ attributeFilter,+ });++ attributeFilter.push('data-closed');++ expect(normalizedOptions.attributeFilter).toEqual(['data-open']);+ expect(normalizedOptions.attributeFilter).not.toBe(attributeFilter);+ });+});diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/remoteDomPolyfillHooksContract.test.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/remoteDomPolyfillHooksContract.test.tsnew file mode 100644index 00000000000..f4cad2071db--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/__tests__/remoteDomPolyfillHooksContract.test.ts@@ -0,0 +1,147 @@+import { HOOKS, type Hooks, Window } from '@remote-dom/polyfill';++const createHookRecorder = () => {+ const polyfillWindow = new Window();+ const calls: { name: keyof Hooks; args: unknown[] }[] = [];+ const hooks = (polyfillWindow as unknown as Record<symbol, Partial<Hooks>>)[+ HOOKS+ ];++ const recordedHookNames: (keyof Hooks)[] = [+ 'createElement',+ 'createText',+ 'setText',+ 'setAttribute',+ 'removeAttribute',+ 'insertChild',+ 'removeChild',+ ];++ for (const hookName of recordedHookNames) {+ hooks[hookName] = (...args: unknown[]) => {+ calls.push({ name: hookName, args });+ };+ }++ return {+ document: polyfillWindow.document as unknown as Document,+ callsNamed: (hookName: keyof Hooks) =>+ calls.filter((call) => call.name === hookName),+ };+};++describe('@remote-dom/polyfill mutation hooks contract the worker MutationObserver is built on, which a remote-dom upgrade must not silently break', () => {+ it('exports HOOKS as a symbol keying a mutable hooks object', () => {+ const polyfillWindow = new Window();++ expect(typeof HOOKS).toBe('symbol');+ expect(+ typeof (polyfillWindow as unknown as Record<symbol, unknown>)[HOOKS],+ ).toBe('object');+ });++ it('still ships MutationObserver without an observe method', () => {+ const polyfillWindow = new Window();++ expect(+ polyfillWindow.MutationObserver.prototype as unknown as Record<+ string,+ unknown+ >,+ ).not.toHaveProperty('observe');+ });++ it('calls createElement when an element is created', () => {+ const { document, callsNamed } = createHookRecorder();++ const element = document.createElement('div');++ expect(callsNamed('createElement')).toHaveLength(1);+ expect(callsNamed('createElement')[0].args[0]).toBe(element);+ });++ it('calls createText and setText with the text node and its data', () => {+ const { document, callsNamed } = createHookRecorder();++ const text = document.createTextNode('first');+ text.data = 'second';++ expect(callsNamed('createText')[0].args[0]).toBe(text);+ expect(callsNamed('createText')[0].args[1]).toBe('first');+ expect(callsNamed('setText')[0].args[0]).toBe(text);+ expect(callsNamed('setText')[0].args[1]).toBe('second');+ });++ it('calls setAttribute and removeAttribute with the element and attribute name', () => {+ const { document, callsNamed } = createHookRecorder();++ const element = document.createElement('div');+ element.setAttribute('title', 'hello');+ element.removeAttribute('title');++ expect(callsNamed('setAttribute')[0].args[0]).toBe(element);+ expect(callsNamed('setAttribute')[0].args[1]).toBe('title');+ expect(callsNamed('setAttribute')[0].args[2]).toBe('hello');+ expect(callsNamed('removeAttribute')[0].args[0]).toBe(element);+ expect(callsNamed('removeAttribute')[0].args[1]).toBe('title');+ });++ it('calls insertChild and removeChild with the parent, the node and its index', () => {+ const { document, callsNamed } = createHookRecorder();++ const parent = document.createElement('div');+ const firstChild = document.createElement('span');+ const secondChild = document.createElement('span');++ parent.appendChild(firstChild);+ parent.appendChild(secondChild);+ parent.removeChild(secondChild);++ expect(callsNamed('insertChild')[1].args[0]).toBe(parent);+ expect(callsNamed('insertChild')[1].args[1]).toBe(secondChild);+ expect(callsNamed('insertChild')[1].args[2]).toBe(1);+ expect(callsNamed('removeChild')[0].args[0]).toBe(parent);+ expect(callsNamed('removeChild')[0].args[1]).toBe(secondChild);+ expect(callsNamed('removeChild')[0].args[2]).toBe(1);+ });++ it('skips insertChild and removeChild when the parent is not an element node', () => {+ const { document, callsNamed } = createHookRecorder();++ const fragment = document.createDocumentFragment();+ const child = document.createElement('span');++ fragment.appendChild(child);+ fragment.removeChild(child);++ expect(callsNamed('insertChild')).toHaveLength(0);+ expect(callsNamed('removeChild')).toHaveLength(0);+ });++ it('does not call createText for a comment but does call setText when its data changes', () => {+ const { document, callsNamed } = createHookRecorder();++ const comment = document.createComment('first');++ expect(callsNamed('createText')).toHaveLength(0);++ comment.data = 'second';++ expect(callsNamed('setText')).toHaveLength(1);+ expect(callsNamed('setText')[0].args[0]).toBe(comment);+ expect(callsNamed('setText')[0].args[1]).toBe('second');+ });++ it('exposes childNodes as a list whose item returns undefined out of range', () => {+ const { document } = createHookRecorder();++ const parent = document.createElement('div');+ const child = document.createElement('span');++ parent.appendChild(child);++ expect(parent.childNodes.item(0)).toBe(child);+ expect(parent.childNodes.item(-1)).toBeUndefined();+ expect(parent.childNodes.item(1)).toBeUndefined();+ });+});diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/buildAttributeCacheKey.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/buildAttributeCacheKey.tsnew file mode 100644index 00000000000..177b0af5063--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/buildAttributeCacheKey.ts@@ -0,0 +1,12 @@+import { isNonEmptyString } from '@sniptt/guards';++type BuildAttributeCacheKeyInput = {+ name: string;+ namespace?: string | null;+};++export const buildAttributeCacheKey = ({+ name,+ namespace,+}: BuildAttributeCacheKeyInput): string =>+ isNonEmptyString(namespace) ? `${namespace}|${name}` : name;diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/createMutationObserverClass.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/createMutationObserverClass.tsnew file mode 100644index 00000000000..b27dcbd5934--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/createMutationObserverClass.ts@@ -0,0 +1,142 @@+import { isFunction } from '@sniptt/guards';+import { isDefined } from 'twenty-shared/utils';++import { type MutationObserverRegistry } from '@/polyfills/dom/types/MutationObserverRegistry';+import { type MutationRecordSink } from '@/polyfills/dom/types/MutationRecordSink';+import { type WorkerMutationObserver } from '@/polyfills/dom/types/WorkerMutationObserver';+import { type WorkerMutationObserverCallback } from '@/polyfills/dom/types/WorkerMutationObserverCallback';+import { type WorkerMutationRecord } from '@/polyfills/dom/types/WorkerMutationRecord';+import { normalizeMutationObserverInit } from '@/polyfills/dom/utils/normalizeMutationObserverInit';++type CreateMutationObserverClassInput = {+ registry: MutationObserverRegistry;+ reportCallbackError: (error: unknown) => void;+};++export const createMutationObserverClass = ({+ registry,+ reportCallbackError,+}: CreateMutationObserverClassInput) => {+ const pendingDeliveries = new Set<() => void>();+ let isDeliveryScheduled = false;++ const deliverPendingRecords = () => {+ isDeliveryScheduled = false;++ const deliveries = [...pendingDeliveries];+ pendingDeliveries.clear();++ for (const deliverRecords of deliveries) {+ deliverRecords();+ }+ };++ const scheduleDelivery = (deliverRecords: () => void) => {+ pendingDeliveries.add(deliverRecords);++ if (isDeliveryScheduled) {+ return;+ }++ isDeliveryScheduled = true;+ queueMicrotask(deliverPendingRecords);+ };++ return class MutationObserverImplementation implements WorkerMutationObserver {+ #callback: WorkerMutationObserverCallback;+ #records: WorkerMutationRecord[] = [];+ #targetRefs = new Set<WeakRef<Node>>();+ #targetRefByTarget = new WeakMap<Node, WeakRef<Node>>();++ #deliverRecords = () => {+ registry.clearTransientObservations({ sink: this.#sink });++ const records = this.takeRecords();++ if (records.length === 0) {+ return;+ }++ try {+ this.#callback(records, this);+ } catch (error) {+ reportCallbackError(error);+ }+ };++ #sink: MutationRecordSink = {+ enqueueMutationRecord: (record) => {+ this.#records.push(record);+ scheduleDelivery(this.#deliverRecords);+ },+ scheduleDelivery: () => {+ scheduleDelivery(this.#deliverRecords);+ },+ };++ constructor(callback: WorkerMutationObserverCallback) {+ if (!isFunction(callback)) {+ throw new TypeError(+ "Failed to construct 'MutationObserver': parameter 1 is not of type 'Function'.",+ );+ }++ this.#callback = callback;+ }++ #pruneCollectedTargetRefs = () => {+ for (const targetRef of this.#targetRefs) {+ if (!isDefined(targetRef.deref())) {+ this.#targetRefs.delete(targetRef);+ }+ }+ };++ observe(target: Node, options: MutationObserverInit = {}): void {+ const normalizedOptions = normalizeMutationObserverInit(options);++ this.#pruneCollectedTargetRefs();++ const existingTargetRef = this.#targetRefByTarget.get(target);++ if (+ !isDefined(existingTargetRef) ||+ !this.#targetRefs.has(existingTargetRef)+ ) {+ const targetRef = new WeakRef(target);++ this.#targetRefByTarget.set(target, targetRef);+ this.#targetRefs.add(targetRef);+ }++ registry.registerObservation({+ target,+ sink: this.#sink,+ options: normalizedOptions,+ });+ }++ disconnect(): void {+ const liveTargets = [...this.#targetRefs]+ .map((targetRef) => targetRef.deref())+ .filter(isDefined);++ registry.unregisterObservations({+ targets: liveTargets,+ sink: this.#sink,+ });+ registry.clearTransientObservations({ sink: this.#sink });++ this.#targetRefs.clear();+ this.#records = [];+ pendingDeliveries.delete(this.#deliverRecords);+ }++ takeRecords(): WorkerMutationRecord[] {+ const records = this.#records;+ this.#records = [];++ return records;+ }+ };+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/createMutationObserverRegistry.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/createMutationObserverRegistry.tsnew file mode 100644index 00000000000..10eb88f78f8--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/createMutationObserverRegistry.ts@@ -0,0 +1,178 @@+import { isDefined } from 'twenty-shared/utils';++import { type MutationObserverRegistration } from '@/polyfills/dom/types/MutationObserverRegistration';+import { type MutationObserverRegistry } from '@/polyfills/dom/types/MutationObserverRegistry';+import { type MutationRecordSink } from '@/polyfills/dom/types/MutationRecordSink';+import { createWorkerNodeList } from '@/polyfills/dom/utils/createWorkerNodeList';+import { hasTransientRegistrationForObservation } from '@/polyfills/dom/utils/hasTransientRegistrationForObservation';+import { isMutationOldValueRequested } from '@/polyfills/dom/utils/isMutationOldValueRequested';+import { isMutationRecordTypeObserved } from '@/polyfills/dom/utils/isMutationRecordTypeObserved';++const NO_REGISTRATIONS: MutationObserverRegistration[] = [];++export const createMutationObserverRegistry = (): MutationObserverRegistry => {+ const registrationsByTarget = new WeakMap<+ Node,+ MutationObserverRegistration[]+ >();+ const transientTargetsBySink = new Map<MutationRecordSink, Set<Node>>();+ const oldValueRequestedBySink = new Map<MutationRecordSink, boolean>();+ const activeSinks = new Set<MutationRecordSink>();++ return {+ hasObservations: () => activeSinks.size > 0,++ registerObservation: ({ target, sink, options }) => {+ const registrations =+ registrationsByTarget.get(target) ?? NO_REGISTRATIONS;++ registrationsByTarget.set(target, [+ ...registrations.filter((registration) => registration.sink !== sink),+ { sink, options, isTransient: false },+ ]);++ activeSinks.add(sink);+ },++ unregisterObservations: ({ targets, sink }) => {+ activeSinks.delete(sink);++ for (const target of targets) {+ const registrations = registrationsByTarget.get(target);++ if (!isDefined(registrations)) {+ continue;+ }++ registrationsByTarget.set(+ target,+ registrations.filter((registration) => registration.sink !== sink),+ );+ }+ },++ registerTransientObservations: ({ detachedNode, formerParent }) => {+ const nextRegistrations = [+ ...(registrationsByTarget.get(detachedNode) ?? NO_REGISTRATIONS),+ ];+ const addedRegistrations: MutationObserverRegistration[] = [];++ let ancestor: Node | null = formerParent;++ while (isDefined(ancestor)) {+ for (const registration of registrationsByTarget.get(ancestor) ??+ NO_REGISTRATIONS) {+ if (+ registration.options.subtree !== true ||+ hasTransientRegistrationForObservation({+ registrations: nextRegistrations,+ sink: registration.sink,+ options: registration.options,+ })+ ) {+ continue;+ }++ const transientRegistration: MutationObserverRegistration = {+ sink: registration.sink,+ options: registration.options,+ isTransient: true,+ };++ nextRegistrations.push(transientRegistration);+ addedRegistrations.push(transientRegistration);+ }++ ancestor = ancestor.parentNode;+ }++ if (addedRegistrations.length === 0) {+ return;+ }++ registrationsByTarget.set(detachedNode, nextRegistrations);++ for (const { sink } of addedRegistrations) {+ const transientTargets = transientTargetsBySink.get(sink) ?? new Set();++ transientTargets.add(detachedNode);+ transientTargetsBySink.set(sink, transientTargets);++ sink.scheduleDelivery();+ }+ },++ clearTransientObservations: ({ sink }) => {+ const transientTargets = transientTargetsBySink.get(sink);++ if (!isDefined(transientTargets)) {+ return;+ }++ transientTargetsBySink.delete(sink);++ for (const target of transientTargets) {+ const registrations = registrationsByTarget.get(target);++ if (!isDefined(registrations)) {+ continue;+ }++ registrationsByTarget.set(+ target,+ registrations.filter(+ (registration) =>+ !registration.isTransient || registration.sink !== sink,+ ),+ );+ }+ },++ broadcastMutationRecord: ({ record, oldValue }) => {+ oldValueRequestedBySink.clear();++ let observedNode: Node | null = record.target;++ while (isDefined(observedNode)) {+ const isMutationTarget = observedNode === record.target;++ for (const registration of registrationsByTarget.get(observedNode) ??+ NO_REGISTRATIONS) {+ const isObservedFromThisNode =+ isMutationTarget || registration.options.subtree === true;++ if (+ !isObservedFromThisNode ||+ !isMutationRecordTypeObserved({+ options: registration.options,+ recordType: record.type,+ attributeName: record.attributeName,+ })+ ) {+ continue;+ }++ const oldValueRequested =+ (oldValueRequestedBySink.get(registration.sink) ?? false) ||+ isMutationOldValueRequested({+ options: registration.options,+ recordType: record.type,+ });++ oldValueRequestedBySink.set(registration.sink, oldValueRequested);+ }++ observedNode = observedNode.parentNode;+ }++ for (const [sink, oldValueRequested] of oldValueRequestedBySink) {+ sink.enqueueMutationRecord({+ ...record,+ addedNodes: createWorkerNodeList(record.addedNodes),+ removedNodes: createWorkerNodeList(record.removedNodes),+ oldValue: oldValueRequested ? oldValue : null,+ });+ }+ },+ };+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/createMutationRecord.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/createMutationRecord.tsnew file mode 100644index 00000000000..16c138f0f38--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/createMutationRecord.ts@@ -0,0 +1,34 @@+import { type WorkerMutationRecord } from '@/polyfills/dom/types/WorkerMutationRecord';+import { createWorkerNodeList } from '@/polyfills/dom/utils/createWorkerNodeList';++type CreateMutationRecordInput = {+ type: MutationRecordType;+ target: Node;+ addedNodes?: Node[];+ removedNodes?: Node[];+ previousSibling?: Node | null;+ nextSibling?: Node | null;+ attributeName?: string | null;+ attributeNamespace?: string | null;+};++export const createMutationRecord = ({+ type,+ target,+ addedNodes,+ removedNodes,+ previousSibling,+ nextSibling,+ attributeName,+ attributeNamespace,+}: CreateMutationRecordInput): WorkerMutationRecord => ({+ type,+ target,+ addedNodes: createWorkerNodeList(addedNodes ?? []),+ removedNodes: createWorkerNodeList(removedNodes ?? []),+ previousSibling: previousSibling ?? null,+ nextSibling: nextSibling ?? null,+ attributeName: attributeName ?? null,+ attributeNamespace: attributeNamespace ?? null,+ oldValue: null,+});diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/createWorkerNodeList.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/createWorkerNodeList.tsnew file mode 100644index 00000000000..a7475ecda77--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/createWorkerNodeList.ts@@ -0,0 +1,17 @@+import { type WorkerNodeList } from '@/polyfills/dom/types/WorkerNodeList';++class NodeListImplementation extends Array<Node> {+ item(index: number): Node | null {+ return this[index] ?? null;+ }+}++export const createWorkerNodeList = (nodes: Node[]): WorkerNodeList => {+ const nodeList = new NodeListImplementation();++ for (const node of nodes) {+ nodeList.push(node);+ }++ return nodeList;+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/hasTransientRegistrationForObservation.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/hasTransientRegistrationForObservation.tsnew file mode 100644index 00000000000..f42ca029f38--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/hasTransientRegistrationForObservation.ts@@ -0,0 +1,20 @@+import { type MutationObserverRegistration } from '@/polyfills/dom/types/MutationObserverRegistration';+import { type MutationRecordSink } from '@/polyfills/dom/types/MutationRecordSink';++type HasTransientRegistrationForObservationInput = {+ registrations: MutationObserverRegistration[];+ sink: MutationRecordSink;+ options: MutationObserverInit;+};++export const hasTransientRegistrationForObservation = ({+ registrations,+ sink,+ options,+}: HasTransientRegistrationForObservationInput): boolean =>+ registrations.some(+ (registration) =>+ registration.isTransient &&+ registration.sink === sink &&+ registration.options === options,+ );diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/installMutationObserver.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/installMutationObserver.tsnew file mode 100644index 00000000000..afecb2b0a12--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/installMutationObserver.ts@@ -0,0 +1,47 @@+import { isDefined } from 'twenty-shared/utils';++import { MUTATION_OBSERVER_HOOKS_UNAVAILABLE_ERROR } from '@/polyfills/dom/constants/MutationObserverHooksUnavailableError';+import { createMutationObserverClass } from '@/polyfills/dom/utils/createMutationObserverClass';+import { createMutationObserverRegistry } from '@/polyfills/dom/utils/createMutationObserverRegistry';+import { installMutationRecordHooks } from '@/polyfills/dom/utils/installMutationRecordHooks';+import { resolvePolyfillDocument } from '@/polyfills/dom/utils/resolvePolyfillDocument';+import { resolvePolyfillHooks } from '@/polyfills/dom/utils/resolvePolyfillHooks';+import { reportErrorToPolyfillWindow } from '@/polyfills/utils/reportErrorToPolyfillWindow';+import { resolveGlobalScopeInstallTargets } from '@/polyfills/utils/resolveGlobalScopeInstallTargets';+import { resolvePolyfillWindow } from '@/polyfills/utils/resolvePolyfillWindow';++type InstallMutationObserverInput = {+ globalScope: Record<string, unknown>;+};++export const installMutationObserver = ({+ globalScope,+}: InstallMutationObserverInput): void => {+ const installTargets = resolveGlobalScopeInstallTargets(globalScope);+ const hooks = resolvePolyfillHooks(installTargets);++ if (!isDefined(hooks)) {+ console.error(MUTATION_OBSERVER_HOOKS_UNAVAILABLE_ERROR);+ return;+ }++ const registry = createMutationObserverRegistry();++ installMutationRecordHooks({+ hooks,+ registry,+ documentTarget: resolvePolyfillDocument(installTargets),+ });++ const polyfillWindow = resolvePolyfillWindow(globalScope);++ const MutationObserverImplementation = createMutationObserverClass({+ registry,+ reportCallbackError: (error) =>+ reportErrorToPolyfillWindow({ polyfillWindow, error }),+ });++ for (const installTarget of installTargets) {+ installTarget.MutationObserver = MutationObserverImplementation;+ }+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/installMutationRecordHooks.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/installMutationRecordHooks.tsnew file mode 100644index 00000000000..b70386cfe3b--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/installMutationRecordHooks.ts@@ -0,0 +1,170 @@+import { type Hooks } from '@remote-dom/polyfill';+import { isFunction } from '@sniptt/guards';+import { isDefined } from 'twenty-shared/utils';++import { type MutationObserverRegistry } from '@/polyfills/dom/types/MutationObserverRegistry';+import { buildAttributeCacheKey } from '@/polyfills/dom/utils/buildAttributeCacheKey';+import { createMutationRecord } from '@/polyfills/dom/utils/createMutationRecord';+import { resolveChildNodeAtIndex } from '@/polyfills/dom/utils/resolveChildNodeAtIndex';++type InstallMutationRecordHooksInput = {+ hooks: Partial<Hooks>;+ registry: MutationObserverRegistry;+ documentTarget: Record<string, unknown> | null;+};++export const installMutationRecordHooks = ({+ hooks,+ registry,+ documentTarget,+}: InstallMutationRecordHooksInput): void => {+ const attributeValuesByElement = new WeakMap<+ Element,+ Map<string, string | null>+ >();+ const dataByCharacterDataNode = new WeakMap<CharacterData, string>();++ const swapCachedAttributeValue = (+ element: Element,+ cacheKey: string,+ value: string | null,+ ): string | null => {+ const attributeValues = attributeValuesByElement.get(element) ?? new Map();+ const previousValue = attributeValues.get(cacheKey) ?? null;++ attributeValues.set(cacheKey, value);+ attributeValuesByElement.set(element, attributeValues);++ return previousValue;+ };++ const broadcastAttributeMutation = ({+ element,+ name,+ namespace,+ value,+ }: {+ element: Element;+ name: string;+ namespace: string | null | undefined;+ value: string | null;+ }) => {+ const oldValue = swapCachedAttributeValue(+ element,+ buildAttributeCacheKey({ name, namespace }),+ value,+ );++ if (!registry.hasObservations()) {+ return;+ }++ registry.broadcastMutationRecord({+ record: createMutationRecord({+ type: 'attributes',+ target: element,+ attributeName: name,+ attributeNamespace: namespace,+ }),+ oldValue,+ });+ };++ const {+ createText: createTextHook,+ setText: setTextHook,+ setAttribute: setAttributeHook,+ removeAttribute: removeAttributeHook,+ insertChild: insertChildHook,+ removeChild: removeChildHook,+ } = hooks;++ hooks.createText = (text, data) => {+ createTextHook?.(text, data);+ dataByCharacterDataNode.set(text, text.data);+ };++ const createCommentMethod = documentTarget?.createComment;++ if (isDefined(documentTarget) && isFunction(createCommentMethod)) {+ documentTarget.createComment = (data: unknown) => {+ const comment = createCommentMethod.call(+ documentTarget,+ data,+ ) as CharacterData;++ dataByCharacterDataNode.set(comment, comment.data);++ return comment;+ };+ }++ hooks.setText = (text, data) => {+ setTextHook?.(text, data);++ const oldValue = dataByCharacterDataNode.get(text) ?? '';+ dataByCharacterDataNode.set(text, text.data);++ if (!registry.hasObservations()) {+ return;+ }++ registry.broadcastMutationRecord({+ record: createMutationRecord({ type: 'characterData', target: text }),+ oldValue,+ });+ };++ hooks.setAttribute = (element, name, value, namespace) => {+ setAttributeHook?.(element, name, value, namespace);+ broadcastAttributeMutation({ element, name, namespace, value });+ };++ hooks.removeAttribute = (element, name, namespace) => {+ removeAttributeHook?.(element, name, namespace);+ broadcastAttributeMutation({ element, name, namespace, value: null });+ };++ hooks.insertChild = (parent, node, index) => {+ insertChildHook?.(parent, node, index);++ if (!registry.hasObservations()) {+ return;+ }++ registry.broadcastMutationRecord({+ record: createMutationRecord({+ type: 'childList',+ target: parent,+ addedNodes: [node],+ previousSibling: resolveChildNodeAtIndex({ parent, index: index - 1 }),+ nextSibling: resolveChildNodeAtIndex({ parent, index: index + 1 }),+ }),+ oldValue: null,+ });+ };++ hooks.removeChild = (parent, node, index) => {+ removeChildHook?.(parent, node, index);++ if (!registry.hasObservations()) {+ return;+ }++ registry.registerTransientObservations({+ detachedNode: node,+ formerParent: parent,+ });++ registry.broadcastMutationRecord({+ record: createMutationRecord({+ type: 'childList',+ target: parent,+ removedNodes: [node],+ previousSibling: resolveChildNodeAtIndex({ parent, index: index - 1 }),+ nextSibling: resolveChildNodeAtIndex({ parent, index }),+ }),+ oldValue: null,+ });+ };+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/isMutationOldValueRequested.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/isMutationOldValueRequested.tsnew file mode 100644index 00000000000..89db092559a--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/isMutationOldValueRequested.ts@@ -0,0 +1,19 @@+type IsMutationOldValueRequestedInput = {+ options: MutationObserverInit;+ recordType: MutationRecordType;+};++export const isMutationOldValueRequested = ({+ options,+ recordType,+}: IsMutationOldValueRequestedInput): boolean => {+ if (recordType === 'attributes') {+ return options.attributeOldValue === true;+ }++ if (recordType === 'characterData') {+ return options.characterDataOldValue === true;+ }++ return false;+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/isMutationRecordTypeObserved.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/isMutationRecordTypeObserved.tsnew file mode 100644index 00000000000..5a060c62e17--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/isMutationRecordTypeObserved.ts@@ -0,0 +1,36 @@+import { isNonEmptyString } from '@sniptt/guards';+import { isDefined } from 'twenty-shared/utils';++type IsMutationRecordTypeObservedInput = {+ options: MutationObserverInit;+ recordType: MutationRecordType;+ attributeName: string | null;+};++export const isMutationRecordTypeObserved = ({+ options,+ recordType,+ attributeName,+}: IsMutationRecordTypeObservedInput): boolean => {+ if (recordType === 'childList') {+ return options.childList === true;+ }++ if (recordType === 'characterData') {+ return options.characterData === true;+ }++ if (options.attributes !== true) {+ return false;+ }++ const { attributeFilter } = options;++ if (!isDefined(attributeFilter)) {+ return true;+ }++ return (+ isNonEmptyString(attributeName) && attributeFilter.includes(attributeName)+ );+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/normalizeMutationObserverInit.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/normalizeMutationObserverInit.tsnew file mode 100644index 00000000000..8c908dc79c7--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/normalizeMutationObserverInit.ts@@ -0,0 +1,46 @@+import { isDefined } from 'twenty-shared/utils';++export const normalizeMutationObserverInit = (+ options: MutationObserverInit,+): MutationObserverInit => {+ const { attributeFilter } = options;++ const attributes =+ options.attributes ??+ (isDefined(options.attributeOldValue) || isDefined(attributeFilter));+ const characterData =+ options.characterData ?? isDefined(options.characterDataOldValue);++ if (options.childList !== true && !attributes && !characterData) {+ throw new TypeError(+ "MutationObserver.observe: at least one of 'childList', 'attributes' or 'characterData' must be true",+ );+ }++ if (options.attributeOldValue === true && !attributes) {+ throw new TypeError(+ "MutationObserver.observe: 'attributeOldValue' requires 'attributes' to be true",+ );+ }++ if (isDefined(attributeFilter) && !attributes) {+ throw new TypeError(+ "MutationObserver.observe: 'attributeFilter' requires 'attributes' to be true",+ );+ }++ if (options.characterDataOldValue === true && !characterData) {+ throw new TypeError(+ "MutationObserver.observe: 'characterDataOldValue' requires 'characterData' to be true",+ );+ }++ return {+ ...options,+ attributes,+ characterData,+ ...(isDefined(attributeFilter) && {+ attributeFilter: [...attributeFilter],+ }),+ };+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/resolveChildNodeAtIndex.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/resolveChildNodeAtIndex.tsnew file mode 100644index 00000000000..42547f9b5ba--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/resolveChildNodeAtIndex.ts@@ -0,0 +1,17 @@+type ResolveChildNodeAtIndexInput = {+ parent: Node;+ index: number;+};++export const resolveChildNodeAtIndex = ({+ parent,+ index,+}: ResolveChildNodeAtIndexInput): Node | null => {+ const { childNodes } = parent;++ if (index < 0 || index >= childNodes.length) {+ return null;+ }++ return childNodes.item(index) ?? null;+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/resolvePolyfillDocument.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/resolvePolyfillDocument.tsnew file mode 100644index 00000000000..214b1a3727d--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/resolvePolyfillDocument.ts@@ -0,0 +1,15 @@+import { isObject } from '@sniptt/guards';++export const resolvePolyfillDocument = (+ installTargets: Record<string, unknown>[],+): Record<string, unknown> | null => {+ for (const installTarget of installTargets) {+ const documentTarget = installTarget.document;++ if (isObject(documentTarget)) {+ return documentTarget as Record<string, unknown>;+ }+ }++ return null;+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/dom/utils/resolvePolyfillHooks.ts b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/resolvePolyfillHooks.tsnew file mode 100644index 00000000000..72dc12d1142--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/dom/utils/resolvePolyfillHooks.ts@@ -0,0 +1,16 @@+import { HOOKS, type Hooks } from '@remote-dom/polyfill';+import { isObject } from '@sniptt/guards';++export const resolvePolyfillHooks = (+ installTargets: Record<string, unknown>[],+): Partial<Hooks> | null => {+ for (const installTarget of installTargets) {+ const hooks = (installTarget as Record<symbol, unknown>)[HOOKS];++ if (isObject(hooks)) {+ return hooks as Partial<Hooks>;+ }+ }++ return null;+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/installStyleBridge.ts b/packages/twenty-front-component-renderer/src/polyfills/installStyleBridge.tsindex 88b8ea6a9f1..2cd0bc25dd3 100644--- a/packages/twenty-front-component-renderer/src/polyfills/installStyleBridge.ts+++ b/packages/twenty-front-component-renderer/src/polyfills/installStyleBridge.ts@@ -8,7 +8,6 @@ export const installStyleBridge = (remoteRoot: RemoteRootElement): void => {Element,Element & RemoteStyleProperties>();- const styleObserverMap = new WeakMap<Element, { disconnect: () => void }>();const trackStyleElement = (styleElement: Element): void => {if (styleElementMap.has(styleElement)) {@@ -121,25 +120,6 @@ export const installStyleBridge = (remoteRoot: RemoteRootElement): void => {void 0;}- if (typeof MutationObserver === 'function') {- try {- const styleObserver = new MutationObserver(() => {- syncCssFromStyleElement();- });-- if (typeof styleObserver.observe === 'function') {- styleObserver.observe(styleElement, {- subtree: true,- childList: true,- characterData: true,- });- styleObserverMap.set(styleElement, styleObserver);- }- } catch {- void 0;- }- }-const existingContent = styleElement.textContent;if (existingContent) {remoteStyleElement.cssText = existingContent;@@ -149,12 +129,6 @@ export const installStyleBridge = (remoteRoot: RemoteRootElement): void => {};const untrackStyleElement = (styleElement: Element): void => {- const styleObserver = styleObserverMap.get(styleElement);- if (styleObserver) {- styleObserver.disconnect();- styleObserverMap.delete(styleElement);- }-const remoteStyleElement = styleElementMap.get(styleElement);if (remoteStyleElement && remoteStyleElement.parentNode) {diff --git a/packages/twenty-front-component-renderer/src/polyfills/utils/__tests__/reportErrorToPolyfillWindow.test.ts b/packages/twenty-front-component-renderer/src/polyfills/utils/__tests__/reportErrorToPolyfillWindow.test.tsnew file mode 100644index 00000000000..480f71de26d--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/utils/__tests__/reportErrorToPolyfillWindow.test.ts@@ -0,0 +1,111 @@+import { Window } from '@remote-dom/polyfill';++import { reportErrorToPolyfillWindow } from '@/polyfills/utils/reportErrorToPolyfillWindow';++type ReportedErrorEvent = {+ message: string;+ error: unknown;+ cancelable: boolean;+ preventDefault: () => void;+};++const createPolyfillWindow = () =>+ new Window() as unknown as Record<string, unknown>;++const listenForErrorEvents = (+ polyfillWindow: Record<string, unknown>,+ onError: (event: ReportedErrorEvent) => void,+) => {+ (+ polyfillWindow.addEventListener as (+ type: string,+ listener: (event: ReportedErrorEvent) => void,+ ) => void+ )('error', onError);+};++describe('reportErrorToPolyfillWindow', () => {+ afterEach(() => {+ jest.restoreAllMocks();+ });++ it('dispatches a cancelable error event carrying the reported value', () => {+ const polyfillWindow = createPolyfillWindow();+ const errorEvents: ReportedErrorEvent[] = [];+ const error = new Error('guest failure');++ listenForErrorEvents(polyfillWindow, (event) => {+ event.preventDefault();+ errorEvents.push(event);+ });++ reportErrorToPolyfillWindow({ polyfillWindow, error });++ expect(errorEvents).toHaveLength(1);+ expect(errorEvents[0].error).toBe(error);+ expect(errorEvents[0].message).toBe('guest failure');+ expect(errorEvents[0].cancelable).toBe(true);+ });++ it('logs when no listener handled the error event', () => {+ const consoleErrorSpy = jest+ .spyOn(console, 'error')+ .mockImplementation(() => {});+ const polyfillWindow = createPolyfillWindow();+ const error = new Error('guest failure');++ listenForErrorEvents(polyfillWindow, () => {});++ reportErrorToPolyfillWindow({ polyfillWindow, error });++ expect(consoleErrorSpy).toHaveBeenCalledWith(+ expect.stringContaining('was not handled'),+ error,+ );+ });++ it('still returns when a listener throws while handling the error event', () => {+ jest.spyOn(console, 'error').mockImplementation(() => {});+ const polyfillWindow = createPolyfillWindow();+ const error = new Error('guest failure');++ listenForErrorEvents(polyfillWindow, () => {+ throw new Error('listener failure');+ });++ expect(() =>+ reportErrorToPolyfillWindow({ polyfillWindow, error }),+ ).not.toThrow();+ });++ it('reports a value that cannot be converted to a string', () => {+ const polyfillWindow = createPolyfillWindow();+ const errorEvents: ReportedErrorEvent[] = [];+ const error = Object.create(null);++ listenForErrorEvents(polyfillWindow, (event) => {+ event.preventDefault();+ errorEvents.push(event);+ });++ expect(() =>+ reportErrorToPolyfillWindow({ polyfillWindow, error }),+ ).not.toThrow();++ expect(errorEvents).toHaveLength(1);+ expect(errorEvents[0].error).toBe(error);+ expect(errorEvents[0].message).toContain('could not be converted');+ });++ it('logs when there is no polyfill window to report to', () => {+ const consoleErrorSpy = jest+ .spyOn(console, 'error')+ .mockImplementation(() => {});+ const error = new Error('guest failure');++ reportErrorToPolyfillWindow({ polyfillWindow: null, error });+ reportErrorToPolyfillWindow({ polyfillWindow: {}, error });++ expect(consoleErrorSpy).toHaveBeenCalledTimes(2);+ });+});diff --git a/packages/twenty-front-component-renderer/src/polyfills/utils/reportErrorToPolyfillWindow.ts b/packages/twenty-front-component-renderer/src/polyfills/utils/reportErrorToPolyfillWindow.tsnew file mode 100644index 00000000000..72b0039077d--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/utils/reportErrorToPolyfillWindow.ts@@ -0,0 +1,63 @@+import { isFunction } from '@sniptt/guards';+import { isDefined } from 'twenty-shared/utils';++const UNHANDLED_SANDBOX_ERROR_MESSAGE =+ '[twenty-front-component] An error reported inside the front component sandbox was not handled.';++const UNRESOLVABLE_ERROR_MESSAGE =+ '[twenty-front-component] The reported value could not be converted to a message.';++const resolveErrorMessage = (error: unknown): string => {+ try {+ return error instanceof Error ? error.message : String(error);+ } catch {+ return UNRESOLVABLE_ERROR_MESSAGE;+ }+};++type PolyfillErrorEvent = {+ defaultPrevented: boolean;+};++type PolyfillErrorEventConstructor = new (+ type: string,+ eventInitDict: {+ message?: string;+ error?: unknown;+ cancelable?: boolean;+ },+) => PolyfillErrorEvent;++type ReportErrorToPolyfillWindowInput = {+ polyfillWindow: Record<string, unknown> | null;+ error: unknown;+};++export const reportErrorToPolyfillWindow = ({+ polyfillWindow,+ error,+}: ReportErrorToPolyfillWindowInput): void => {+ const ErrorEventConstructor = polyfillWindow?.ErrorEvent;+ const dispatchEvent = polyfillWindow?.dispatchEvent;++ if (+ isDefined(polyfillWindow) &&+ isFunction(ErrorEventConstructor) &&+ isFunction(dispatchEvent)+ ) {+ const errorEvent =+ new (ErrorEventConstructor as PolyfillErrorEventConstructor)('error', {+ message: resolveErrorMessage(error),+ error,+ cancelable: true,+ });++ dispatchEvent.call(polyfillWindow, errorEvent);++ if (errorEvent.defaultPrevented) {+ return;+ }+ }++ console.error(UNHANDLED_SANDBOX_ERROR_MESSAGE, error);+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/utils/resolveGlobalScopeInstallTargets.ts b/packages/twenty-front-component-renderer/src/polyfills/utils/resolveGlobalScopeInstallTargets.tsindex 2792affe5a5..782e2531951 100644--- a/packages/twenty-front-component-renderer/src/polyfills/utils/resolveGlobalScopeInstallTargets.ts+++ b/packages/twenty-front-component-renderer/src/polyfills/utils/resolveGlobalScopeInstallTargets.ts@@ -1,12 +1,14 @@-import { isObject } from '@sniptt/guards';+import { isDefined } from 'twenty-shared/utils';++import { resolvePolyfillWindow } from '@/polyfills/utils/resolvePolyfillWindow';export const resolveGlobalScopeInstallTargets = (globalScope: Record<string, unknown>,): Record<string, unknown>[] => {- const polyfillWindow = globalScope.window;+ const polyfillWindow = resolvePolyfillWindow(globalScope);- if (isObject(polyfillWindow) && polyfillWindow !== globalScope) {- return [globalScope, polyfillWindow as Record<string, unknown>];+ if (isDefined(polyfillWindow)) {+ return [globalScope, polyfillWindow];}return [globalScope];diff --git a/packages/twenty-front-component-renderer/src/polyfills/utils/resolvePolyfillWindow.ts b/packages/twenty-front-component-renderer/src/polyfills/utils/resolvePolyfillWindow.tsnew file mode 100644index 00000000000..7778f4ce9dc--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/utils/resolvePolyfillWindow.ts@@ -0,0 +1,13 @@+import { isObject } from '@sniptt/guards';++export const resolvePolyfillWindow = (+ globalScope: Record<string, unknown>,+): Record<string, unknown> | null => {+ const polyfillWindow = globalScope.window;++ if (!isObject(polyfillWindow) || polyfillWindow === globalScope) {+ return null;+ }++ return polyfillWindow as Record<string, unknown>;+};diff --git a/packages/twenty-front-component-renderer/src/remote/worker/remote-worker.ts b/packages/twenty-front-component-renderer/src/remote/worker/remote-worker.tsindex 63fcaca95d2..c543fb6647d 100644--- a/packages/twenty-front-component-renderer/src/remote/worker/remote-worker.ts+++ b/packages/twenty-front-component-renderer/src/remote/worker/remote-worker.ts@@ -13,6 +13,7 @@ import { installDocumentGetElementById } from '@/polyfills/dom/utils/installDocuimport { installGetComputedStyle } from '@/polyfills/dom/utils/installGetComputedStyle';import { installGetElementsByClassName } from '@/polyfills/dom/utils/installGetElementsByClassName';import { installLocalStyleOnBaseElements } from '@/polyfills/dom/utils/installLocalStyleOnBaseElements';+import { installMutationObserver } from '@/polyfills/dom/utils/installMutationObserver';import { workerGeometryStore } from '@/polyfills/geometry/workerGeometryStore';import { installElementGeometryPolyfill } from '@/polyfills/geometry/utils/installElementGeometryPolyfill';import { installWindowGeometryPolyfill } from '@/polyfills/geometry/utils/installWindowGeometryPolyfill';@@ -40,6 +41,10 @@ installLocalStyleOnBaseElements(Element.prototype);installGetComputedStyle(globalThis as unknown as Record<string, unknown>);+installMutationObserver({+ globalScope: globalThis as unknown as Record<string, unknown>,+});+installElementGeometryPolyfill({elementPrototype: Element.prototype,documentTarget: document,diff --git a/packages/twenty-front-component-renderer/tsconfig.json b/packages/twenty-front-component-renderer/tsconfig.jsonindex 1125cd5a92f..a917c9a0ba1 100644--- a/packages/twenty-front-component-renderer/tsconfig.json+++ b/packages/twenty-front-component-renderer/tsconfig.json@@ -1,6 +1,7 @@{"extends": "../../tsconfig.base.json","compilerOptions": {+ "lib": ["ES2020", "DOM", "ES2021.WeakRef"],"allowJs": false,"esModuleInterop": false,"allowSyntheticDefaultImports": true,