Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

fix: prevent prototype pollution in drawing and formula maps

白熱a05e826d86b0
diff --git a/packages/drawing/src/services/__tests__/drawing-manager-impl.service.spec.ts b/packages/drawing/src/services/__tests__/drawing-manager-impl.service.spec.ts
index 34f8f70e99..6386bd340c 100644
--- a/packages/drawing/src/services/__tests__/drawing-manager-impl.service.spec.ts
+++ b/packages/drawing/src/services/__tests__/drawing-manager-impl.service.spec.ts
@@ -66,6 +66,37 @@ function createSearch(drawingId: string): IDrawingSearch {
}
describe('UnitDrawingService', () => {
+ it.each(['__proto__', 'constructor', 'prototype'])('rejects unsafe drawing identifiers (%s) before changing state', (key) => {
+ const injector = new Injector([[UnitDrawingService]]);
+ const service = injector.get(UnitDrawingService);
+ const marker = '__drawing_pollution__';
+ try {
+ expect(() => service.applyJson1(key, marker, null)).toThrow();
+ expect(() => service.applyJson1('unit', key, null)).toThrow();
+ expect(Object.getOwnPropertyDescriptor(Object.prototype, marker)).toBeUndefined();
+ expect(service.drawingManagerData).toEqual({});
+ } finally {
+ Reflect.deleteProperty(Object.prototype, marker);
+ Reflect.deleteProperty(Object, marker);
+ injector.dispose();
+ }
+ });
+
+ it('rejects unsafe snapshots and operations without partially initializing the drawing map', () => {
+ const injector = new Injector([[UnitDrawingService]]);
+ const service = injector.get(UnitDrawingService);
+ try {
+ expect(() => service.registerDrawingData('unit', JSON.parse('{"__proto__":{"data":{},"order":[]}}'))).toThrow();
+ expect(() => service.registerDrawingData('__proto__', {})).toThrow();
+ expect(() => service.applyJson1('unit', 'sheet', ['__proto__', 'polluted', { i: true }])).toThrow();
+ expect(() => service.applyJson1('unit', 'sheet', ['missing', 'nested', { i: true }])).toThrow();
+ expect(service.drawingManagerData).toEqual({});
+ expect(service.getDrawingByParam({ unitId: 'constructor', subUnitId: 'prototype', drawingId: 'data' })).toBeUndefined();
+ } finally {
+ injector.dispose();
+ }
+ });
+
let service: UnitDrawingService<IDrawingParam>;
beforeEach(() => {
diff --git a/packages/drawing/src/services/drawing-manager-impl.service.ts b/packages/drawing/src/services/drawing-manager-impl.service.ts
index d74ec562f0..5a779055d4 100644
--- a/packages/drawing/src/services/drawing-manager-impl.service.ts
+++ b/packages/drawing/src/services/drawing-manager-impl.service.ts
@@ -172,6 +172,31 @@ function appendJsonUpdateOps(
}
}
+function assertSafeDrawingKeys(...keys: string[]): void {
+ for (const key of keys) {
+ if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
+ throw new Error('Invalid drawing key');
+ }
+ }
+}
+
+function getOwn<T>(record: Record<string, T> | undefined, key: string): T | undefined {
+ return record != null && Object.prototype.hasOwnProperty.call(record, key) ? record[key] : undefined;
+}
+
+function validateDrawingData<T extends IDrawingParam>(data: IDrawingSubunitMap<T>): void {
+ for (const subUnitId of Object.keys(data)) {
+ assertSafeDrawingKeys(subUnitId);
+ const subUnit = data[subUnitId];
+ if (subUnit?.data) {
+ Object.keys(subUnit.data).forEach((key) => assertSafeDrawingKeys(key));
+ }
+ if (subUnit?.order) {
+ subUnit.order.forEach((key) => assertSafeDrawingKeys(key));
+ }
+ }
+}
+
interface IDrawingRefreshMetadata {
behindText?: unknown;
}
@@ -283,11 +308,11 @@ export class UnitDrawingService<T extends IDrawingParam> implements IUnitDrawing
}
getDrawingDataForUnit(unitId: string) {
- return this.drawingManagerData[unitId] || {};
+ return getOwn(this.drawingManagerData, unitId) || {};
}
removeDrawingDataForUnit(unitId: string) {
- const subUnits = this.drawingManagerData[unitId];
+ const subUnits = getOwn(this.drawingManagerData, unitId);
if (subUnits == null) {
return;
@@ -312,12 +337,14 @@ export class UnitDrawingService<T extends IDrawingParam> implements IUnitDrawing
}
registerDrawingData(unitId: string, data: IDrawingSubunitMap<T>) {
+ assertSafeDrawingKeys(unitId);
+ validateDrawingData(data);
this.drawingManagerData[unitId] = data;
}
initializeNotification(unitId: string) {
const drawings: T[] = [];
- const data = this.drawingManagerData[unitId];
+ const data = getOwn(this.drawingManagerData, unitId);
if (data == null) {
return;
@@ -350,6 +377,9 @@ export class UnitDrawingService<T extends IDrawingParam> implements IUnitDrawing
// Use in doc only.
setDrawingData(unitId: string, subUnitId: string, data: IDrawingMapItemData<T>) {
+ assertSafeDrawingKeys(unitId, subUnitId);
+ Object.keys(data).forEach((key) => assertSafeDrawingKeys(key));
+ this._establishDrawingMap(unitId, subUnitId);
const unitData = this.drawingManagerData[unitId];
const subUnitData = unitData[subUnitId];
// Docs replaces a whole subunit snapshot instead of applying JSON1. Isolate that subunit container so
@@ -702,33 +732,25 @@ export class UnitDrawingService<T extends IDrawingParam> implements IUnitDrawing
}
applyJson1(unitId: string, subUnitId: string, jsonOp: JSONOp) {
- this._establishDrawingMap(unitId, subUnitId);
- // this._fillMissingFields(jsonOp);
- this._oldDrawingManagerData = { ...this.drawingManagerData };
- this.drawingManagerData = JSON1.type.apply(this.drawingManagerData as unknown as JSON1.Doc, jsonOp) as unknown as IDrawingMap<T>;
- }
-
- // private _fillMissingFields(jsonOp: JSONOp) {
- // if (jsonOp == null) {
- // return;
- // }
-
- // let object: { [key: string]: {} } = this.drawingManagerData;
- // for (let i = 0; i < jsonOp.length; i++) {
- // const op = jsonOp[i];
- // if (Array.isArray(op)) {
- // const opKey = op[0] as string;
- // if (!(opKey in object)) {
- // object[opKey] = null as unknown as never;
- // }
- // } else if (typeof op === 'string') {
- // object = object[op];
- // if (object == null) {
- // break;
- // }
- // }
- // }
- // }
+ assertSafeDrawingKeys(unitId, subUnitId);
+ JSON1.type.checkValidOp(jsonOp);
+ const unitData = getOwn(this.drawingManagerData, unitId);
+ // Stage initialization locally so a rejected operation leaves both snapshots unchanged.
+ const data = {
+ ...this.drawingManagerData,
+ [unitId]: {
+ ...unitData,
+ [subUnitId]: getOwn(unitData, subUnitId) ?? { data: {}, order: [] },
+ },
+ };
+ const nextData = JSON1.type.apply(data as unknown as JSON1.Doc, jsonOp) as unknown as IDrawingMap<T>;
+ for (const id of Object.keys(nextData)) {
+ assertSafeDrawingKeys(id);
+ validateDrawingData(nextData[id]);
+ }
+ this._oldDrawingManagerData = this.drawingManagerData;
+ this.drawingManagerData = nextData;
+ }
featurePluginUpdateNotification(updateParams: T[]) {
this._featurePluginUpdate$.next(updateParams);
@@ -807,6 +829,9 @@ export class UnitDrawingService<T extends IDrawingParam> implements IUnitDrawing
// Use in doc only.
setDrawingOrder(unitId: string, subUnitId: string, order: string[]) {
+ assertSafeDrawingKeys(unitId, subUnitId);
+ order.forEach((key) => assertSafeDrawingKeys(key));
+ this._establishDrawingMap(unitId, subUnitId);
this.drawingManagerData[unitId][subUnitId].order = order;
}
@@ -974,7 +999,7 @@ export class UnitDrawingService<T extends IDrawingParam> implements IUnitDrawing
return;
}
const { unitId, subUnitId, drawingId } = searchParam;
- return this.drawingManagerData[unitId]?.[subUnitId]?.data?.[drawingId] as T;
+ return getOwn(getOwn(getOwn(this.drawingManagerData, unitId), subUnitId)?.data, drawingId);
}
private _getOldBySearch(searchParam: Nullable<IDrawingSearch>): Nullable<T> {
@@ -982,15 +1007,19 @@ export class UnitDrawingService<T extends IDrawingParam> implements IUnitDrawing
return;
}
const { unitId, subUnitId, drawingId } = searchParam;
- return this._oldDrawingManagerData[unitId]?.[subUnitId]?.data?.[drawingId] as T;
+ return getOwn(getOwn(getOwn(this._oldDrawingManagerData, unitId), subUnitId)?.data, drawingId);
}
private _establishDrawingMap(unitId: string, subUnitId: string, drawingId?: string) {
- if (!this.drawingManagerData[unitId]) {
+ assertSafeDrawingKeys(unitId, subUnitId);
+ if (drawingId != null) {
+ assertSafeDrawingKeys(drawingId);
+ }
+ if (!getOwn(this.drawingManagerData, unitId)) {
this.drawingManagerData[unitId] = {};
}
- if (!this.drawingManagerData[unitId][subUnitId]) {
+ if (!getOwn(this.drawingManagerData[unitId], subUnitId)) {
this.drawingManagerData[unitId][subUnitId] = {
data: {},
order: [],
@@ -1000,7 +1029,7 @@ export class UnitDrawingService<T extends IDrawingParam> implements IUnitDrawing
if (drawingId == null) {
return null;
}
- return this.drawingManagerData[unitId][subUnitId].data?.[drawingId];
+ return getOwn(this.drawingManagerData[unitId][subUnitId].data, drawingId);
}
private _addByParam(insertParam: T): { op: JSONOp; invertOp: JSONOp } {
@@ -1097,11 +1126,11 @@ export class UnitDrawingService<T extends IDrawingParam> implements IUnitDrawing
}
private _getDrawingData(unitId: string, subUnitId: string) {
- return this.drawingManagerData[unitId]?.[subUnitId]?.data || {};
+ return getOwn(getOwn(this.drawingManagerData, unitId), subUnitId)?.data || {};
}
private _getDrawingOrder(unitId: string, subUnitId: string) {
- return this.drawingManagerData[unitId]?.[subUnitId]?.order || [];
+ return getOwn(getOwn(this.drawingManagerData, unitId), subUnitId)?.order || [];
}
getDrawingVisible() {
diff --git a/packages/engine-formula/src/basics/__tests__/runtime.spec.ts b/packages/engine-formula/src/basics/__tests__/runtime.spec.ts
new file mode 100644
index 0000000000..c312ed8311
--- /dev/null
+++ b/packages/engine-formula/src/basics/__tests__/runtime.spec.ts
@@ -0,0 +1,35 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+import { convertRuntimeToUnitData, convertUnitDataToRuntime } from '../runtime';
+
+describe('formula runtime data', () => {
+ it.each(['__proto__', 'constructor', 'prototype', 'toString'])('round trips special unit and sheet identifiers (%s) without prototype pollution', (key) => {
+ const marker = '__formula_pollution__';
+ const data = JSON.parse(JSON.stringify({ [key]: { [marker]: { 0: { 0: { v: 42 } } } }, normal: { [key]: { 0: { 0: { v: 7 } } } } }));
+ try {
+ const runtime = convertUnitDataToRuntime(data);
+ expect(runtime[key]![marker].getValue(0, 0)).toEqual({ v: 42 });
+ expect(runtime.normal![key].getValue(0, 0)).toEqual({ v: 7 });
+ expect(convertRuntimeToUnitData(runtime)).toEqual(data);
+ expect(Object.getOwnPropertyDescriptor(Object.prototype, marker)).toBeUndefined();
+ } finally {
+ Reflect.deleteProperty(Object.prototype, marker);
+ Reflect.deleteProperty(Object, marker);
+ }
+ });
+});
diff --git a/packages/engine-formula/src/basics/runtime.ts b/packages/engine-formula/src/basics/runtime.ts
index 98c9d77317..ff32b033aa 100644
--- a/packages/engine-formula/src/basics/runtime.ts
+++ b/packages/engine-formula/src/basics/runtime.ts
@@ -19,7 +19,7 @@ import type { IArrayFormulaUnitCellType, IRuntimeUnitDataPrimitiveType, IRuntime
import { ObjectMatrix } from '@univerjs/core';
export function convertUnitDataToRuntime(unitData: IArrayFormulaUnitCellType) {
- const arrayFormulaCellData: IRuntimeUnitDataType = {};
+ const arrayFormulaCellData: IRuntimeUnitDataType = Object.create(null);
Object.keys(unitData).forEach((unitId) => {
const sheetData = unitData[unitId];
@@ -28,7 +28,7 @@ export function convertUnitDataToRuntime(unitData: IArrayFormulaUnitCellType) {
}
if (arrayFormulaCellData[unitId] == null) {
- arrayFormulaCellData[unitId] = {};
+ arrayFormulaCellData[unitId] = Object.create(null);
}
Object.keys(sheetData).forEach((sheetId) => {
@@ -42,33 +42,44 @@ export function convertUnitDataToRuntime(unitData: IArrayFormulaUnitCellType) {
}
export function convertRuntimeToUnitData(unitData: IRuntimeUnitDataType) {
- const unitPrimitiveData: IRuntimeUnitDataPrimitiveType = {};
+ const unitPrimitiveData: IRuntimeUnitDataPrimitiveType = Object.create(null);
- for (const unitId in unitData) {
+ for (const unitId of Object.keys(unitData)) {
const sheetData = unitData[unitId];
if (sheetData == null) {
continue;
}
if (unitPrimitiveData[unitId] == null) {
- unitPrimitiveData[unitId] = {};
+ unitPrimitiveData[unitId] = Object.create(null);
}
- for (const sheetId in sheetData) {
+ for (const sheetId of Object.keys(sheetData)) {
const cellData = sheetData[sheetId];
- const primitiveData: IObjectMatrixPrimitiveType<Nullable<ICellData>> = {};
+ const primitiveData: IObjectMatrixPrimitiveType<Nullable<ICellData>> = Object.create(null);
cellData.forValue((row, column, value) => {
if (primitiveData[row] === undefined) {
- primitiveData[row] = {};
+ primitiveData[row] = Object.create(null);
}
primitiveData[row][column] = value;
});
- unitPrimitiveData[unitId][sheetId] = primitiveData;
+ unitPrimitiveData[unitId]![sheetId] = primitiveData;
}
}
return unitPrimitiveData;
}
+
+/** Copy the unit and sheet dictionaries without retaining inherited identifier keys. */
+export function copyUnitData<T>(data: { [unitId: string]: Nullable<{ [sheetId: string]: T }> }) {
+ const result: { [unitId: string]: { [sheetId: string]: T } } = Object.create(null);
+ for (const unitId of Object.keys(data)) {
+ if (data[unitId] != null) {
+ result[unitId] = Object.assign(Object.create(null), data[unitId]);
+ }
+ }
+ return result;
+}
diff --git a/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts b/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts
index 2ae05def96..8fc7041c09 100644
--- a/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts
+++ b/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts
@@ -204,6 +204,25 @@ describe('Test formula data model', () => {
univer.dispose();
});
+ it.each(['__proto__', 'constructor', 'prototype', 'toString'])('keeps loaded formula dictionaries safe when merging (%s)', (key) => {
+ const marker = '__formula_pollution__';
+ const range = { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 };
+ try {
+ formulaDataModel.setArrayFormulaRange(JSON.parse('{"normal":{}}'));
+ formulaDataModel.mergeArrayFormulaRange({ [key]: { [marker]: { 0: { 0: range } } } });
+ formulaDataModel.mergeArrayFormulaRange({ normal: { [key]: { 0: { 0: range } } } });
+ expect(formulaDataModel.getArrayFormulaRange()[key]?.[marker]?.[0]?.[0]).toEqual(range);
+ expect(formulaDataModel.getArrayFormulaRange().normal?.[key]?.[0]?.[0]).toEqual(range);
+ const data: IFormulaData = {};
+ formulaDataModel.initSheetFormulaData(data, key, marker, new ObjectMatrix({ 0: { 0: { f: '=1' } } }));
+ expect(data[key]?.[marker]?.[0]?.[0]?.f).toBe('=1');
+ expect(Object.getOwnPropertyDescriptor(Object.prototype, marker)).toBeUndefined();
+ } finally {
+ Reflect.deleteProperty(Object.prototype, marker);
+ Reflect.deleteProperty(Object, marker);
+ }
+ });
+
describe('updateFormulaData', () => {
it('skips formula reconstruction for value updates', () => {
const worksheet = get(IUniverInstanceService)
@@ -509,7 +528,7 @@ describe('Test formula data model', () => {
formulaDataModel.updateArrayFormulaRange(unitId, sheetId, cellValue);
const formulaData = formulaDataModel.getArrayFormulaRange();
- expect(formulaData).toStrictEqual(result);
+ expect(JSON.parse(JSON.stringify(formulaData))).toStrictEqual(result);
});
});
describe('updateArrayFormulaCellData', () => {
@@ -569,7 +588,7 @@ describe('Test formula data model', () => {
formulaDataModel.updateArrayFormulaCellData(unitId, sheetId, cellValue);
const formulaData = formulaDataModel.getArrayFormulaCellData();
- expect(formulaData).toStrictEqual(result);
+ expect(JSON.parse(JSON.stringify(formulaData))).toStrictEqual(result);
});
it('should clear only edited array formula cell data when editing a spill cell', () => {
@@ -616,7 +635,7 @@ describe('Test formula data model', () => {
},
});
- expect(formulaDataModel.getArrayFormulaCellData()).toStrictEqual({
+ expect(JSON.parse(JSON.stringify(formulaDataModel.getArrayFormulaCellData()))).toStrictEqual({
[unitId]: {
[sheetId]: {
0: {
@@ -1329,7 +1348,7 @@ describe('Test formula data model', () => {
};
formulaDataModel.initSheetFormulaData(formulaData, unitId, sheetId, cellMatrix);
- expect(formulaData).toStrictEqual(result);
+ expect(JSON.parse(JSON.stringify(formulaData))).toStrictEqual(result);
});
it('preserves Excel shared formula ids with relative offsets', () => {
diff --git a/packages/engine-formula/src/models/formula-data.model.ts b/packages/engine-formula/src/models/formula-data.model.ts
index 258e76cfe5..9cce58ea1e 100644
--- a/packages/engine-formula/src/models/formula-data.model.ts
+++ b/packages/engine-formula/src/models/formula-data.model.ts
@@ -33,6 +33,7 @@ import type {
} from '../basics/common';
import type { IImageFormulaInfo } from '../engine/value-object/primitive-object';
import { BooleanNumber, CellValueType, createBaseFormulaTableNameMap, Disposable, getBaseFormulaTableName, Inject, isFormulaId, isFormulaString, IUniverInstanceService, ObjectMatrix, RANGE_TYPE, Styles, UniverInstanceType } from '@univerjs/core';
+import { copyUnitData } from '../basics/runtime';
import { LexerTreeBuilder } from '../engine/analysis/lexer-tree-builder';
import { deserializeRangeWithSheet } from '../engine/utils/reference';
import { clearArrayFormulaCellDataByCell, updateFormulaDataByCellValue } from './utils/formula-data-util';
@@ -43,13 +44,13 @@ export interface IRangeChange {
}
export class FormulaDataModel extends Disposable {
- private _formulaIdMapData: IFormulaIdMapData = {};
+ private _formulaIdMapData: IFormulaIdMapData = Object.create(null);
- private _arrayFormulaRange: IArrayFormulaRangeType = {};
+ private _arrayFormulaRange: IArrayFormulaRangeType = Object.create(null);
- private _arrayFormulaCellData: IArrayFormulaUnitCellType = {};
+ private _arrayFormulaCellData: IArrayFormulaUnitCellType = Object.create(null);
- private _unitImageFormulaData: IUnitImageFormulaDataType = {};
+ private _unitImageFormulaData: IUnitImageFormulaDataType = Object.create(null);
constructor(
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
@@ -60,10 +61,10 @@ export class FormulaDataModel extends Disposable {
override dispose() {
super.dispose();
- this._formulaIdMapData = {};
- this._arrayFormulaRange = {};
- this._arrayFormulaCellData = {};
- this._unitImageFormulaData = {};
+ this._formulaIdMapData = Object.create(null);
+ this._arrayFormulaRange = Object.create(null);
+ this._arrayFormulaCellData = Object.create(null);
+ this._unitImageFormulaData = Object.create(null);
}
clearPreviousArrayFormulaCellData(clearArrayFormulaCellData: IRuntimeUnitDataType) {
@@ -123,11 +124,11 @@ export class FormulaDataModel extends Disposable {
}
if (this._arrayFormulaRange[unitId] == null) {
- this._arrayFormulaRange[unitId] = {};
+ this._arrayFormulaRange[unitId] = Object.create(null);
}
if (this._arrayFormulaCellData[unitId] == null) {
- this._arrayFormulaCellData[unitId] = {};
+ this._arrayFormulaCellData[unitId] = Object.create(null);
}
Object.keys(sheetData).forEach((sheetId) => {
@@ -168,12 +169,12 @@ export class FormulaDataModel extends Disposable {
}
getFormulaData(): IFormulaData {
- const formulaData: IFormulaData = {};
+ const formulaData: IFormulaData = Object.create(null);
const allSheets = this._univerInstanceService.getAllUnitsForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
for (let i = 0; i < allSheets.length; i++) {
const workbook = allSheets[i];
const unitId = workbook.getUnitId();
- formulaData[unitId] = {};
+ formulaData[unitId] = Object.create(null);
const worksheets = workbook.getSheets();
for (let j = 0; j < worksheets.length; j++) {
@@ -191,13 +192,13 @@ export class FormulaDataModel extends Disposable {
const base = allBases[i];
const snapshot = base.getSnapshot();
const unitId = base.getUnitId();
- formulaData[unitId] = {};
+ formulaData[unitId] = Object.create(null);
const tables = Object.values(snapshot.tables);
const formulaTableNames = createBaseFormulaTableNameMap(snapshot);
for (let j = 0; j < tables.length; j++) {
const table = tables[j];
- const tableFormulaData: Record<number, Record<number, IFormulaDataItem>> = {};
+ const tableFormulaData: Record<number, Record<number, IFormulaDataItem>> = Object.create(null);
const normalizedFormulaByFieldId = new Map<string, string>();
const recordOrder = table.recordOrder;
if (!recordOrder) {
@@ -225,7 +226,7 @@ export class FormulaDataModel extends Disposable {
normalizedFormula = normalizeBaseFormulaForEngine(formula, table, snapshot, formulaTableNames);
normalizedFormulaByFieldId.set(field.id, normalizedFormula);
}
- tableFormulaData[row] ??= {};
+ tableFormulaData[row] ??= Object.create(null);
tableFormulaData[row][col] = {
f: normalizedFormula,
si: field.id,
@@ -248,7 +249,7 @@ export class FormulaDataModel extends Disposable {
const result = buildSheetFormulaData(formulaData, unitId, sheetId, cellMatrix);
if (!this._formulaIdMapData[unitId]) {
- this._formulaIdMapData[unitId] = {};
+ this._formulaIdMapData[unitId] = Object.create(null);
}
this._formulaIdMapData[unitId]![sheetId] = result.formulaIdMap;
@@ -273,13 +274,13 @@ export class FormulaDataModel extends Disposable {
}
getSheetFormulaData(unitId: string, sheetId: string) {
- const formulaData: IFormulaData = {};
+ const formulaData: IFormulaData = Object.create(null);
const workbook = this._univerInstanceService.getUnit<Workbook>(unitId);
if (workbook == null) {
return {};
}
- formulaData[unitId] = {};
+ formulaData[unitId] = Object.create(null);
const worksheet = workbook.getSheetBySheetId(sheetId);
if (worksheet == null) {
@@ -291,7 +292,7 @@ export class FormulaDataModel extends Disposable {
this._initSheetArrayFormulaData(unitId, sheetId, cellMatrix);
this.initSheetFormulaData(formulaData, unitId, sheetId, cellMatrix);
- return formulaData[unitId][sheetId];
+ return formulaData[unitId]![sheetId];
}
getArrayFormulaRange(): IArrayFormulaRangeType {
@@ -299,7 +300,7 @@ export class FormulaDataModel extends Disposable {
}
setArrayFormulaRange(value: IArrayFormulaRangeType) {
- this._arrayFormulaRange = value;
+ this._arrayFormulaRange = copyUnitData(value);
}
getArrayFormulaCellData() {
@@ -307,7 +308,7 @@ export class FormulaDataModel extends Disposable {
}
setArrayFormulaCellData(value: IArrayFormulaUnitCellType) {
- this._arrayFormulaCellData = value;
+ this._arrayFormulaCellData = copyUnitData(value);
}
getUnitImageFormulaData() {
@@ -315,7 +316,7 @@ export class FormulaDataModel extends Disposable {
}
setUnitImageFormulaData(value: IUnitImageFormulaDataType) {
- this._unitImageFormulaData = value;
+ this._unitImageFormulaData = copyUnitData(value);
}
mergeArrayFormulaRange(formulaData: IArrayFormulaRangeType) {
@@ -327,7 +328,7 @@ export class FormulaDataModel extends Disposable {
}
if (!this._arrayFormulaRange[unitId]) {
- this._arrayFormulaRange[unitId] = {};
+ this._arrayFormulaRange[unitId] = Object.create(null);
}
Object.keys(sheetData).forEach((sheetId) => {
@@ -355,7 +356,7 @@ export class FormulaDataModel extends Disposable {
if (!sheetData) continue;
if (!this._unitImageFormulaData[unitId]) {
- this._unitImageFormulaData[unitId] = {};
+ this._unitImageFormulaData[unitId] = Object.create(null);
}
const sheetIds = Object.keys(sheetData);
@@ -366,8 +367,8 @@ export class FormulaDataModel extends Disposable {
const imageFormulaMatrix = sheetData[sheetId];
if (!imageFormulaMatrix) continue;
- if (!this._unitImageFormulaData[unitId][sheetId]) {
- this._unitImageFormulaData[unitId][sheetId] = new ObjectMatrix<Nullable<IImageFormulaInfo>>();
+ if (!this._unitImageFormulaData[unitId]![sheetId]) {
+ this._unitImageFormulaData[unitId]![sheetId] = new ObjectMatrix<Nullable<IImageFormulaInfo>>();
}
imageFormulaMatrix.forValue((r, c, v) => {
@@ -395,13 +396,13 @@ export class FormulaDataModel extends Disposable {
getCalculateData() {
const unitAllSheet = this._univerInstanceService.getAllUnitsForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
- const allUnitData: IUnitData = {};
+ const allUnitData: IUnitData = Object.create(null);
- const unitStylesData: IUnitStylesData = {};
+ const unitStylesData: IUnitStylesData = Object.create(null);
- const unitSheetNameMap: IUnitSheetNameMap = {};
+ const unitSheetNameMap: IUnitSheetNameMap = Object.create(null);
- const unitNameMap: IFormulaUnitNameMap = {};
+ const unitNameMap: IFormulaUnitNameMap = Object.create(null);
for (const workbook of unitAllSheet) {
const unitId = workbook.getUnitId();
@@ -413,9 +414,9 @@ export class FormulaDataModel extends Disposable {
const sheets = workbook.getSheets();
- const sheetData: ISheetData = {};
+ const sheetData: ISheetData = Object.create(null);
- const sheetNameMap: { [sheetName: string]: string } = {};
+ const sheetNameMap: { [sheetName: string]: string } = Object.create(null);
for (const sheet of sheets) {
const sheetId = sheet.getSheetId();
@@ -448,8 +449,8 @@ export class FormulaDataModel extends Disposable {
name: snapshot.name,
unitType: UniverInstanceType.UNIVER_BASE,
};
- const baseData: ISheetData = {};
- const tableNameMap: { [tableName: string]: string } = {};
+ const baseData: ISheetData = Object.create(null);
+ const tableNameMap: { [tableName: string]: string } = Object.create(null);
const formulaTableNames = createBaseFormulaTableNameMap(snapshot);
for (const table of Object.values(snapshot.tables)) {
@@ -483,20 +484,20 @@ export class FormulaDataModel extends Disposable {
*/
getHiddenRowsFiltered() {
const unitAllSheet = this._univerInstanceService.getAllUnitsForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
- const rowData: IUnitRowData = {};
+ const rowData: IUnitRowData = Object.create(null);
for (const workbook of unitAllSheet) {
const unitId = workbook.getUnitId();
const sheets = workbook.getSheets();
- rowData[unitId] = {};
+ rowData[unitId] = Object.create(null);
for (const sheet of sheets) {
const sheetId = sheet.getSheetId();
- rowData[unitId][sheetId] = {};
+ rowData[unitId]![sheetId] = Object.create(null);
const startRow = 0;
const endRow = sheet.getRowCount() - 1;
- const sheetRowData: IObjectArrayPrimitiveType<Partial<IRowData>> = {};
+ const sheetRowData: IObjectArrayPrimitiveType<Partial<IRowData>> = Object.create(null);
for (let i = startRow; i <= endRow; i++) {
if (!sheet.getRowVisible(i)) {
@@ -506,7 +507,7 @@ export class FormulaDataModel extends Disposable {
}
}
- rowData[unitId][sheetId] = sheetRowData;
+ rowData[unitId]![sheetId] = sheetRowData;
}
}
@@ -550,7 +551,7 @@ export class FormulaDataModel extends Disposable {
return newSheetFormulaDataMatrix.getMatrix();
}
- const formulaIdMap: { [formulaId: string]: IFormulaIdMap } = {};
+ const formulaIdMap: { [formulaId: string]: IFormulaIdMap } = Object.create(null);
const sharedFormulaCellMatrix = new ObjectMatrix<Nullable<ICellData>>();
worksheetCellMatrix?.forValue((r, c, cell) => {
const formulaId = cell?.si;
@@ -777,7 +778,7 @@ export class FormulaDataModel extends Disposable {
if (!sheetInstance) continue;
// Object to store continuous cell ranges by column
- const columnRanges: { [column: number]: { startRow: number; endRow: number }[] } = {};
+ const columnRanges: { [column: number]: { startRow: number; endRow: number }[] } = Object.create(null);
for (const rowStr of Object.keys(sheet)) {
const row = Number(rowStr);
@@ -870,10 +871,10 @@ export class FormulaDataModel extends Disposable {
}
if (!this._arrayFormulaRange[unitId]) {
- this._arrayFormulaRange[unitId] = {};
+ this._arrayFormulaRange[unitId] = Object.create(null);
}
if (!this._arrayFormulaCellData[unitId]) {
- this._arrayFormulaCellData[unitId] = {};
+ this._arrayFormulaCellData[unitId] = Object.create(null);
}
arrayFormulaRangeMatrix ??= new ObjectMatrix<IRange>(this._arrayFormulaRange[unitId]?.[sheetId]);
@@ -912,16 +913,17 @@ function buildSheetFormulaData(
sheetId: string,
cellMatrix: ObjectMatrix<Nullable<ICellData>>
) {
- if (!formulaData[unitId]) {
- formulaData[unitId] = {};
- }
-
- if (!formulaData[unitId][sheetId]) {
- formulaData[unitId][sheetId] = {};
+ const unitData = Object.assign(
+ Object.create(null),
+ Object.prototype.hasOwnProperty.call(formulaData, unitId) ? formulaData[unitId] : undefined
+ );
+ Object.defineProperty(formulaData, unitId, { value: unitData, writable: true, configurable: true, enumerable: true });
+ if (!unitData[sheetId]) {
+ unitData[sheetId] = Object.create(null);
}
- const formulaIdMap: Record<string, IFormulaIdMap> = {}; // Connect the formula and ID
- const sheetFormulaDataMatrix = new ObjectMatrix<Nullable<IFormulaDataItem>>(formulaData[unitId][sheetId]);
+ const formulaIdMap: Record<string, IFormulaIdMap> = Object.create(null); // Connect the formula and ID
+ const sheetFormulaDataMatrix = new ObjectMatrix<Nullable<IFormulaDataItem>>(unitData[sheetId]);
cellMatrix.forValue((r, c, cell) => {
const formulaString = cell?.f || '';
diff --git a/packages/engine-formula/src/services/__tests__/defined-names.service.spec.ts b/packages/engine-formula/src/services/__tests__/defined-names.service.spec.ts
index ecfdd56efa..36b204781b 100644
--- a/packages/engine-formula/src/services/__tests__/defined-names.service.spec.ts
+++ b/packages/engine-formula/src/services/__tests__/defined-names.service.spec.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { Injector, IUniverInstanceService } from '@univerjs/core';
+import { ContextService, DesktopLogService, IContextService, ILogService, Injector, IUniverInstanceService, UniverInstanceService } from '@univerjs/core';
import { describe, expect, it } from 'vitest';
import { DefinedNamesService, IDefinedNamesService } from '../defined-names.service';
@@ -40,6 +40,29 @@ function createDefinedNamesService() {
}
describe('DefinedNamesService', () => {
+ it.each(['__proto__', 'constructor', 'prototype', 'toString'])('keeps special identifiers (%s) out of the prototype chain after loading data', (key) => {
+ const injector = new Injector([
+ [DefinedNamesService],
+ [IUniverInstanceService, { useClass: UniverInstanceService }],
+ [IContextService, { useClass: ContextService }],
+ [ILogService, { useClass: DesktopLogService }],
+ ]);
+ const service = injector.get(DefinedNamesService);
+ const marker = '__formula_pollution__';
+ try {
+ service.registerDefinedName(key, { id: marker, name: 'Total', formulaOrRefString: '=1' });
+ service.registerDefinedNames('unit', JSON.parse('{}'));
+ service.registerDefinedName('unit', { id: key, name: key, formulaOrRefString: '=2' });
+ expect(service.getValueById(key, marker)?.formulaOrRefString).toBe('=1');
+ expect(service.getValueByName('unit', key)?.formulaOrRefString).toBe('=2');
+ expect(Object.getOwnPropertyDescriptor(Object.prototype, marker)).toBeUndefined();
+ } finally {
+ Reflect.deleteProperty(Object.prototype, marker);
+ Reflect.deleteProperty(Object, marker);
+ injector.dispose();
+ }
+ });
+
it('should register/query/remove defined names and update cache', () => {
const { service } = createDefinedNamesService();
diff --git a/packages/engine-formula/src/services/__tests__/other-formula-manager.service.spec.ts b/packages/engine-formula/src/services/__tests__/other-formula-manager.service.spec.ts
index dd5da947eb..3166034712 100644
--- a/packages/engine-formula/src/services/__tests__/other-formula-manager.service.spec.ts
+++ b/packages/engine-formula/src/services/__tests__/other-formula-manager.service.spec.ts
@@ -27,6 +27,34 @@ describe('OtherFormulaManagerService', () => {
service = injector.get(IOtherFormulaManagerService);
});
+ it.each(['__proto__', 'constructor', 'prototype', 'toString'])('keeps special identifiers (%s) as ordinary formula data', (key) => {
+ const injector = new Injector([[OtherFormulaManagerService]]);
+ const service = injector.get(OtherFormulaManagerService);
+ const marker = '__formula_pollution__';
+ const item = { f: '=1', ranges: [] };
+ try {
+ for (const search of [
+ { unitId: key, subUnitId: marker, formulaId: marker },
+ { unitId: 'unit', subUnitId: key, formulaId: marker },
+ { unitId: 'unit', subUnitId: 'sheet', formulaId: key },
+ ]) {
+ service.register({ ...search, item });
+ expect(service.get(search)).toBe(item);
+ expect(Object.getOwnPropertyDescriptor(Object.prototype, marker)).toBeUndefined();
+ expect(Object.getOwnPropertyDescriptor(Object, marker)).toBeUndefined();
+ expect(Object.getOwnPropertyDescriptor(Object.prototype.toString, marker)).toBeUndefined();
+ service.remove(search);
+ expect(service.get(search)).toBeUndefined();
+ }
+ expect(Object.getOwnPropertyDescriptor(Object.prototype, marker)).toBeUndefined();
+ } finally {
+ Reflect.deleteProperty(Object.prototype, marker);
+ Reflect.deleteProperty(Object, marker);
+ Reflect.deleteProperty(Object.prototype.toString, marker);
+ injector.dispose();
+ }
+ });
+
it('keeps plugin-owned formula data isolated by unit, sheet and formula id', () => {
const item = { f: '=TABLE()', ranges: [] };
diff --git a/packages/engine-formula/src/services/__tests__/runtime.service.spec.ts b/packages/engine-formula/src/services/__tests__/runtime.service.spec.ts
index 3a05799a37..329a3a8021 100644
--- a/packages/engine-formula/src/services/__tests__/runtime.service.spec.ts
+++ b/packages/engine-formula/src/services/__tests__/runtime.service.spec.ts
@@ -85,6 +85,7 @@ function createRuntimeService() {
const runtime = injector.get(IFormulaRuntimeService) as FormulaRuntimeService;
return {
+ injector,
runtime,
unitDataMatrix,
arrayFormulaCellData: currentConfigService.getArrayFormulaCellData().unit!.sheet!,
@@ -93,6 +94,26 @@ function createRuntimeService() {
}
describe('FormulaRuntimeService', () => {
+ it.each(['__proto__', 'constructor', 'prototype', 'toString'])('isolates runtime writes for special identifiers (%s)', (key) => {
+ const { injector, runtime } = createRuntimeService();
+ const marker = '__formula_pollution__';
+ try {
+ runtime.setCurrent(0, 0, 10, 10, marker, key);
+ runtime.setUnitArrayFormulaEmbeddedMap();
+ runtime.setRuntimeOtherData(marker, 0, 0, NumberValueObject.create(7));
+ expect(runtime.getUnitArrayFormulaEmbeddedMap()[key]?.[marker]?.[0]?.[0]).toBe(true);
+ expect(runtime.getRuntimeOtherData()[key]?.[marker]?.[marker]?.[0]?.[0]?.[0]?.[0]?.v).toBe(7);
+ expect(Object.getOwnPropertyDescriptor(Object.prototype, marker)).toBeUndefined();
+ runtime.reset();
+ runtime.setUnitArrayFormulaEmbeddedMap();
+ expect(runtime.getUnitArrayFormulaEmbeddedMap()[key]?.[marker]?.[0]?.[0]).toBe(true);
+ } finally {
+ Reflect.deleteProperty(Object.prototype, marker);
+ Reflect.deleteProperty(Object, marker);
+ injector.dispose();
+ }
+ });
+
it('should manage state, counters and cycle flags', () => {
const { runtime } = createRuntimeService();
diff --git a/packages/engine-formula/src/services/calculate-formula.service.ts b/packages/engine-formula/src/services/calculate-formula.service.ts
index 6b6b6bdb3d..8633c9374d 100644
--- a/packages/engine-formula/src/services/calculate-formula.service.ts
+++ b/packages/engine-formula/src/services/calculate-formula.service.ts
@@ -207,7 +207,7 @@ export class CalculateFormulaService extends Disposable implements ICalculateFor
runtimeFeatureRange: { [featureId: string]: IFeatureDirtyRangeType }
) {
const dirtyRanges: IUnitRange[] = [];
- const excludedCell: IUnitExcludedCell = {};
+ const excludedCell: IUnitExcludedCell = Object.create(null);
Object.keys(arrayFormulaRange).forEach((unitId) => {
const sheetArrayFormulaRange = arrayFormulaRange[unitId];
@@ -231,7 +231,7 @@ export class CalculateFormulaService extends Disposable implements ICalculateFor
});
if (excludedCell[unitId] == null) {
- excludedCell[unitId] = {};
+ excludedCell[unitId] = Object.create(null);
}
excludedCell[unitId]![sheetId] = newCellData;
@@ -264,7 +264,6 @@ export class CalculateFormulaService extends Disposable implements ICalculateFor
return { dirtyRanges, excludedCell };
}
- // eslint-disable-next-line max-lines-per-function
protected async _apply(isArrayFormulaState = false) {
if (isArrayFormulaState) {
this._runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.START_DEPENDENCY_ARRAY_FORMULA);
@@ -412,13 +411,13 @@ export class CalculateFormulaService extends Disposable implements ICalculateFor
this._runtimeService.reset();
- const result: IFormulaExecuteResultMap = {};
+ const result: IFormulaExecuteResultMap = Object.create(null);
for (const unitId of Object.keys(formulas)) {
const sheetFormulas = formulas[unitId];
if (sheetFormulas == null) continue;
- result[unitId] = {};
+ result[unitId] = Object.create(null);
for (const sheetId of Object.keys(sheetFormulas)) {
const rowFormulas = sheetFormulas[sheetId];
@@ -428,11 +427,11 @@ export class CalculateFormulaService extends Disposable implements ICalculateFor
if (sheetItem == null) continue;
- result[unitId]![sheetId] = {};
+ result[unitId]![sheetId] = Object.create(null);
for (const rowString of Object.keys(rowFormulas)) {
const row = Number.parseInt(rowString);
- result[unitId]![sheetId]![row] = {};
+ result[unitId]![sheetId]![row] = Object.create(null);
const cellData = rowFormulas[row];
if (!cellData) continue;
diff --git a/packages/engine-formula/src/services/current-data.service.ts b/packages/engine-formula/src/services/current-data.service.ts
index 4c2673e6a0..b52e35d3ee 100644
--- a/packages/engine-formula/src/services/current-data.service.ts
+++ b/packages/engine-formula/src/services/current-data.service.ts
@@ -44,7 +44,7 @@ import {
ObjectMatrix,
UniverInstanceType,
} from '@univerjs/core';
-import { convertUnitDataToRuntime } from '../basics/runtime';
+import { convertUnitDataToRuntime, copyUnitData } from '../basics/runtime';
import { FormulaDataModel } from '../models/formula-data.model';
import { ISheetRowFilteredService } from './sheet-row-filtered.service';
@@ -143,43 +143,43 @@ export interface IFormulaCurrentConfigService {
}
export class FormulaCurrentConfigService extends Disposable implements IFormulaCurrentConfigService {
- private _unitData: IUnitData = {};
+ private _unitData: IUnitData = Object.create(null);
- private _unitStylesData: IUnitStylesData = {};
+ private _unitStylesData: IUnitStylesData = Object.create(null);
- private _arrayFormulaCellData: IRuntimeUnitDataType = {};
+ private _arrayFormulaCellData: IRuntimeUnitDataType = Object.create(null);
- private _arrayFormulaRange: IArrayFormulaRangeType = {};
+ private _arrayFormulaRange: IArrayFormulaRangeType = Object.create(null);
- private _formulaData: IFormulaData = {};
+ private _formulaData: IFormulaData = Object.create(null);
- private _sheetNameMap: IUnitSheetNameMap = {};
+ private _sheetNameMap: IUnitSheetNameMap = Object.create(null);
- private _unitNameMap: IFormulaUnitNameMap = {};
+ private _unitNameMap: IFormulaUnitNameMap = Object.create(null);
- private _externalReferences: IFormulaExternalReferences = {};
+ private _externalReferences: IFormulaExternalReferences = Object.create(null);
private _calculationGeneration = 0;
private _forceCalculate: boolean = false;
- private _clearDependencyTreeCache: IDirtyUnitSheetNameMap = {};
+ private _clearDependencyTreeCache: IDirtyUnitSheetNameMap = Object.create(null);
private _dirtyRanges: IUnitRange[] = [];
- private _dirtyNameMap: IDirtyUnitSheetNameMap = {};
+ private _dirtyNameMap: IDirtyUnitSheetNameMap = Object.create(null);
- private _dirtyDefinedNameMap: IDirtyUnitDefinedNameMap = {};
+ private _dirtyDefinedNameMap: IDirtyUnitDefinedNameMap = Object.create(null);
- private _dirtySuperTableMap: IDirtyUnitSuperTableMap = {};
+ private _dirtySuperTableMap: IDirtyUnitSuperTableMap = Object.create(null);
- private _dirtyUnitFeatureMap: IDirtyUnitFeatureMap = {};
+ private _dirtyUnitFeatureMap: IDirtyUnitFeatureMap = Object.create(null);
- private _dirtyUnitOtherFormulaMap: IDirtyUnitOtherFormulaMap = {};
+ private _dirtyUnitOtherFormulaMap: IDirtyUnitOtherFormulaMap = Object.create(null);
private _excludedCell: Nullable<IUnitExcludedCell>;
- private _sheetIdToNameMap: IUnitSheetIdToNameMap = {};
+ private _sheetIdToNameMap: IUnitSheetIdToNameMap = Object.create(null);
private _executeUnitId: Nullable<string> = '';
private _executeSubUnitId: Nullable<string> = '';
@@ -195,23 +195,23 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
override dispose(): void {
super.dispose();
- this._unitData = {};
- this._unitStylesData = {};
- this._arrayFormulaCellData = {};
- this._arrayFormulaRange = {};
- this._formulaData = {};
- this._sheetNameMap = {};
- this._unitNameMap = {};
- this._externalReferences = {};
- this._clearDependencyTreeCache = {};
+ this._unitData = Object.create(null);
+ this._unitStylesData = Object.create(null);
+ this._arrayFormulaCellData = Object.create(null);
+ this._arrayFormulaRange = Object.create(null);
+ this._formulaData = Object.create(null);
+ this._sheetNameMap = Object.create(null);
+ this._unitNameMap = Object.create(null);
+ this._externalReferences = Object.create(null);
+ this._clearDependencyTreeCache = Object.create(null);
this._dirtyRanges = [];
- this._dirtyNameMap = {};
- this._dirtyDefinedNameMap = {};
- this._dirtySuperTableMap = {};
- this._dirtyUnitFeatureMap = {};
- this._dirtyUnitOtherFormulaMap = {};
- this._excludedCell = {};
- this._sheetIdToNameMap = {};
+ this._dirtyNameMap = Object.create(null);
+ this._dirtyDefinedNameMap = Object.create(null);
+ this._dirtySuperTableMap = Object.create(null);
+ this._dirtyUnitFeatureMap = Object.create(null);
+ this._dirtyUnitOtherFormulaMap = Object.create(null);
+ this._excludedCell = Object.create(null);
+ this._sheetIdToNameMap = Object.create(null);
}
getExecuteUnitId() {
@@ -307,7 +307,7 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
}
setSheetNameMap(sheetIdToNameMap: IUnitSheetIdToNameMap) {
- this._sheetIdToNameMap = sheetIdToNameMap;
+ this._sheetIdToNameMap = copyUnitData(sheetIdToNameMap);
}
getClearDependencyTreeCache() {
@@ -372,18 +372,18 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
load(config: IFormulaDatasetConfig) {
this._calculationGeneration++;
if (config.allUnitData && config.unitSheetNameMap && config.unitStylesData) {
- this._unitData = config.allUnitData;
+ this._unitData = copyUnitData(config.allUnitData);
this._unitStylesData = config.unitStylesData;
- this._sheetNameMap = config.unitSheetNameMap;
+ this._sheetNameMap = copyUnitData(config.unitSheetNameMap);
this._unitNameMap = config.unitNameMap || {};
} else {
const { allUnitData, unitNameMap, unitSheetNameMap, unitStylesData } = this._loadSheetData();
- this._unitData = allUnitData;
+ this._unitData = copyUnitData(allUnitData);
this._unitStylesData = unitStylesData;
- this._sheetNameMap = unitSheetNameMap;
+ this._sheetNameMap = copyUnitData(unitSheetNameMap);
this._unitNameMap = unitNameMap;
}
@@ -425,11 +425,11 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
loadDataLite(rowData?: IUnitRowData) {
const { allUnitData, unitNameMap, unitSheetNameMap, unitStylesData } = this._loadSheetData();
- this._unitData = allUnitData;
+ this._unitData = copyUnitData(allUnitData);
this._unitStylesData = unitStylesData;
- this._sheetNameMap = unitSheetNameMap;
+ this._sheetNameMap = copyUnitData(unitSheetNameMap);
this._unitNameMap = unitNameMap;
@@ -463,11 +463,11 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
/**
* Mark dirty for expansion of array formulas, need to clear the worksheet's dirty flag.
*/
- this._dirtyNameMap = {};
+ this._dirtyNameMap = Object.create(null);
}
registerUnitData(unitData: IUnitData) {
- this._unitData = unitData;
+ this._unitData = copyUnitData(unitData);
}
registerFormulaData(formulaData: IFormulaData) {
@@ -475,108 +475,31 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
}
registerSheetNameMap(sheetNameMap: IUnitSheetNameMap) {
- this._sheetNameMap = sheetNameMap;
+ this._sheetNameMap = copyUnitData(sheetNameMap);
}
registerUnitNameMap(unitNameMap: IFormulaUnitNameMap) {
this._unitNameMap = unitNameMap;
}
- // private _loadOtherFormulaData() {
- // const unitAllDoc = this._univerInstanceService.getAllUniverDocsInstance();
-
- // const unitAllSlide = this._univerInstanceService.getAllUniverSlidesInstance();
-
- // const otherFormulaData: IOtherFormulaData = {};
-
- // for (const documentDataModel of unitAllDoc) {
- // const unitId = documentDataModel.getUnitId();
-
- // if (otherFormulaData[unitId] == null) {
- // otherFormulaData[unitId] = {};
- // }
-
- // if (otherFormulaData[unitId][DEFAULT_DOCUMENT_SUB_COMPONENT_ID] == null) {
- // otherFormulaData[unitId][DEFAULT_DOCUMENT_SUB_COMPONENT_ID] = {};
- // }
-
- // const subComponent = otherFormulaData[unitId][DEFAULT_DOCUMENT_SUB_COMPONENT_ID];
-
- // const customRanges = documentDataModel.getBody()?.customRanges;
-
- // if (customRanges == null) {
- // continue;
- // }
-
- // for (const customRange of customRanges) {
- // subComponent[customRange.rangeId] = {
- // f: customRange.endIndex.toString(),
- // };
- // }
- // }
-
- // for (const slide of unitAllSlide) {
- // const unitId = slide.getUnitId();
-
- // if (otherFormulaData[unitId] == null) {
- // otherFormulaData[unitId] = {};
- // }
-
- // if (otherFormulaData[unitId][DEFAULT_DOCUMENT_SUB_COMPONENT_ID] == null) {
- // otherFormulaData[unitId][DEFAULT_DOCUMENT_SUB_COMPONENT_ID] = {};
- // }
-
- // const pages = slide.getPages();
-
- // if (pages == null) {
- // continue;
- // }
-
- // const pageIds = Object.keys(pages);
-
- // for (const pageId of pageIds) {
- // const page = pages[pageId];
-
- // const subComponent = otherFormulaData[unitId][pageId];
-
- // const pageElements = page.pageElements;
-
- // if (pageElements == null) {
- // continue;
- // }
-
- // const pageElementIds = Object.keys(pageElements);
-
- // for (const pageElementId of pageElementIds) {
- // const pageElement = pageElements[pageElementId];
- // subComponent[pageElementId] = {
- // f: pageElement.title,
- // };
- // }
- // }
- // }
-
- // return otherFormulaData;
- // }
-
private _mergeNameMap(unitSheetNameMap: IUnitSheetNameMap, dirtyNameMap: IDirtyUnitSheetNameMap) {
Object.keys(dirtyNameMap).forEach((unitId) => {
if (dirtyNameMap[unitId]) {
Object.keys(dirtyNameMap[unitId]!).forEach((sheetId) => {
if (unitSheetNameMap[unitId] == null) {
- unitSheetNameMap[unitId] = {};
+ unitSheetNameMap[unitId] = Object.create(null);
}
unitSheetNameMap[unitId]![dirtyNameMap[unitId]![sheetId]] = sheetId;
});
}
});
- this._sheetIdToNameMap = {};
+ this._sheetIdToNameMap = Object.create(null);
Object.keys(unitSheetNameMap).forEach((unitId) => {
Object.keys(unitSheetNameMap[unitId]!).forEach((sheetName) => {
if (this._sheetIdToNameMap[unitId] == null) {
- this._sheetIdToNameMap[unitId] = {};
+ this._sheetIdToNameMap[unitId] = Object.create(null);
}
this._sheetIdToNameMap[unitId]![unitSheetNameMap[unitId]![sheetName]] = sheetName;
});
@@ -600,18 +523,18 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
* @param rowData
*/
private _applyUnitRowData(rowData: IUnitRowData) {
- for (const unitId in rowData) {
+ for (const unitId of Object.keys(rowData)) {
if (rowData[unitId] == null) {
continue;
}
- for (const sheetId in rowData[unitId]) {
+ for (const sheetId of Object.keys(rowData[unitId])) {
if (rowData[unitId][sheetId] == null) {
continue;
}
if (this._unitData[unitId] == null) {
- this._unitData[unitId] = {};
+ this._unitData[unitId] = Object.create(null);
}
if (this._unitData[unitId][sheetId] == null) {
diff --git a/packages/engine-formula/src/services/defined-names.service.ts b/packages/engine-formula/src/services/defined-names.service.ts
index b6acb2ac75..915fdeced9 100644
--- a/packages/engine-formula/src/services/defined-names.service.ts
+++ b/packages/engine-formula/src/services/defined-names.service.ts
@@ -90,9 +90,9 @@ export interface IDefinedNamesService {
export class DefinedNamesService extends Disposable implements IDefinedNamesService {
// 18.2.6 definedNames (Defined Names)
- private _definedNameMap: IDefinedNameMap = {};
+ private _definedNameMap: IDefinedNameMap = Object.create(null);
// Cache for name-to-definition mapping, here name key is ignored case sensitivity
- private _nameCacheMap: { [unitId: string]: { [name: string]: IDefinedNamesServiceParam } } = {};
+ private _nameCacheMap: { [unitId: string]: { [name: string]: IDefinedNamesServiceParam } } = Object.create(null);
//
private _definedNamesIsEmpty: boolean = true;
@@ -122,8 +122,8 @@ export class DefinedNamesService extends Disposable implements IDefinedNamesServ
override dispose(): void {
super.dispose();
- this._definedNameMap = {};
- this._nameCacheMap = {};
+ this._definedNameMap = Object.create(null);
+ this._nameCacheMap = Object.create(null);
this._update$.complete();
this._currentRange$.complete();
this._focusRange$.complete();
@@ -157,7 +157,7 @@ export class DefinedNamesService extends Disposable implements IDefinedNamesServ
}
registerDefinedNames(unitId: string, params: IDefinedNameMapItem) {
- this._definedNameMap[unitId] = params;
+ this._definedNameMap[unitId] = Object.assign(Object.create(null), params);
this._updateCache(unitId);
const definedNames = Object.values(params);
@@ -175,7 +175,7 @@ export class DefinedNamesService extends Disposable implements IDefinedNamesServ
registerDefinedName(unitId: string, param: IDefinedNamesServiceParam) {
const unitMap = this._definedNameMap[unitId];
if (unitMap === undefined) {
- this._definedNameMap[unitId] = {};
+ this._definedNameMap[unitId] = Object.create(null);
}
this._definedNameMap[unitId][param.id] = param;
@@ -331,7 +331,7 @@ export class DefinedNamesService extends Disposable implements IDefinedNamesServ
return;
}
- this._nameCacheMap[unitId] = {};
+ this._nameCacheMap[unitId] = Object.create(null);
// Cache all name mappings for this unitId
for (const item of Object.values(nameMap)) {
diff --git a/packages/engine-formula/src/services/other-formula-manager.service.ts b/packages/engine-formula/src/services/other-formula-manager.service.ts
index d8bbc80f1a..58c946b824 100644
--- a/packages/engine-formula/src/services/other-formula-manager.service.ts
+++ b/packages/engine-formula/src/services/other-formula-manager.service.ts
@@ -53,11 +53,11 @@ export interface IOtherFormulaManagerService {
* thereby completing the calculation of the entire dependency tree.
*/
export class OtherFormulaManagerService extends Disposable implements IOtherFormulaManagerService {
- private _otherFormulaData: IOtherFormulaData = {};
+ private _otherFormulaData: IOtherFormulaData = Object.create(null);
override dispose(): void {
super.dispose();
- this._otherFormulaData = {};
+ this._otherFormulaData = Object.create(null);
}
remove(searchParam: IOtherFormulaManagerSearchParam) {
@@ -78,11 +78,11 @@ export class OtherFormulaManagerService extends Disposable implements IOtherForm
register(insertParam: IOtherFormulaManagerInsertParam) {
const { unitId, subUnitId, formulaId, item } = insertParam;
if (!this._otherFormulaData[unitId]) {
- this._otherFormulaData[unitId] = {};
+ this._otherFormulaData[unitId] = Object.create(null);
}
if (!this._otherFormulaData[unitId]![subUnitId]) {
- this._otherFormulaData[unitId]![subUnitId] = {};
+ this._otherFormulaData[unitId]![subUnitId] = Object.create(null);
}
this._otherFormulaData[unitId]![subUnitId]![formulaId] = item;
diff --git a/packages/engine-formula/src/services/runtime.service.ts b/packages/engine-formula/src/services/runtime.service.ts
index 1860a5ca67..59b4739049 100644
--- a/packages/engine-formula/src/services/runtime.service.ts
+++ b/packages/engine-formula/src/services/runtime.service.ts
@@ -224,21 +224,21 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
private _currentSubUnitId: string = '';
private _currentUnitId: string = '';
- private _runtimeData: IRuntimeUnitDataType = {};
+ private _runtimeData: IRuntimeUnitDataType = Object.create(null);
- private _runtimeOtherData: IRuntimeOtherUnitDataType = {}; // Data returned by other businesses through formula calculation, excluding the sheet.
+ private _runtimeOtherData: IRuntimeOtherUnitDataType = Object.create(null); // Data returned by other businesses through formula calculation, excluding the sheet.
- private _unitArrayFormulaRange: IArrayFormulaRangeType = {};
+ private _unitArrayFormulaRange: IArrayFormulaRangeType = Object.create(null);
- private _unitArrayFormulaEmbeddedMap: IArrayFormulaEmbeddedMap = {};
+ private _unitArrayFormulaEmbeddedMap: IArrayFormulaEmbeddedMap = Object.create(null);
- private _runtimeArrayFormulaCellData: IRuntimeUnitDataType = {};
+ private _runtimeArrayFormulaCellData: IRuntimeUnitDataType = Object.create(null);
- private _runtimeClearArrayFormulaCellData: IRuntimeUnitDataType = {};
+ private _runtimeClearArrayFormulaCellData: IRuntimeUnitDataType = Object.create(null);
- private _runtimeFeatureRange: { [featureId: string]: IFeatureDirtyRangeType } = {};
+ private _runtimeFeatureRange: { [featureId: string]: IFeatureDirtyRangeType } = Object.create(null);
- private _runtimeFeatureCellData: { [featureId: string]: IRuntimeUnitDataType } = {};
+ private _runtimeFeatureCellData: { [featureId: string]: IRuntimeUnitDataType } = Object.create(null);
private _runtimeImageFormulaData: IRuntimeImageFormulaDataType[] = [];
@@ -298,8 +298,8 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
super.dispose();
this.reset();
- this._runtimeFeatureCellData = {};
- this._runtimeFeatureRange = {};
+ this._runtimeFeatureCellData = Object.create(null);
+ this._runtimeFeatureRange = Object.create(null);
this.clearReferenceAndNumberformatCache();
}
@@ -391,12 +391,12 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
reset() {
this._formulaExecuteStage = FormulaExecuteStageType.IDLE;
- this._runtimeData = {};
- this._runtimeOtherData = {};
- this._unitArrayFormulaRange = {};
- this._unitArrayFormulaEmbeddedMap = {};
- this._runtimeArrayFormulaCellData = {};
- this._runtimeClearArrayFormulaCellData = {};
+ this._runtimeData = Object.create(null);
+ this._runtimeOtherData = Object.create(null);
+ this._unitArrayFormulaRange = Object.create(null);
+ this._unitArrayFormulaEmbeddedMap = Object.create(null);
+ this._runtimeArrayFormulaCellData = Object.create(null);
+ this._runtimeClearArrayFormulaCellData = Object.create(null);
this._runtimeImageFormulaData = [];
// this._runtimeFeatureCellData = {};
@@ -464,16 +464,16 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
const unitId = this._currentUnitId;
if (this._runtimeOtherData[unitId] === undefined) {
- this._runtimeOtherData[unitId] = {};
+ this._runtimeOtherData[unitId] = Object.create(null);
}
const unitData = this._runtimeOtherData[unitId]!;
if (unitData[subUnitId] === undefined || unitData[subUnitId] === null) {
- unitData[subUnitId] = {};
+ unitData[subUnitId] = Object.create(null);
}
- const subComponentData = unitData[subUnitId];
+ const subComponentData = unitData[subUnitId]!;
let cellDatas: Nullable<ICellData>[][] = [];
@@ -499,18 +499,17 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
}
if (subComponentData[formulaId] === undefined || subComponentData[formulaId] === null) {
- subComponentData[formulaId] = {};
+ subComponentData[formulaId] = Object.create(null);
}
if (subComponentData[formulaId][y] === undefined || subComponentData[formulaId][y] === null) {
- subComponentData[formulaId][y] = {};
+ subComponentData[formulaId][y] = Object.create(null);
}
// x represents the column offset, y represents the row offset
subComponentData[formulaId][y][x] = cellDatas;
}
- // eslint-disable-next-line max-lines-per-function
setRuntimeData(functionVariant: FunctionVariantType) {
const row = this._currentRow;
const column = this._currentColumn;
@@ -521,7 +520,7 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
// Get current sheet data
if (this._runtimeData[unitId] == null) {
- this._runtimeData[unitId] = {};
+ this._runtimeData[unitId] = Object.create(null);
}
const unitData = this._runtimeData[unitId]!;
@@ -534,20 +533,20 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
// Get current sheet array formula range
if (this._unitArrayFormulaRange[unitId] == null) {
- this._unitArrayFormulaRange[unitId] = {};
+ this._unitArrayFormulaRange[unitId] = Object.create(null);
}
const arrayFormulaRange = this._unitArrayFormulaRange[unitId]!;
if (arrayFormulaRange[sheetId] === null || arrayFormulaRange[sheetId] === undefined) {
- arrayFormulaRange[sheetId] = {};
+ arrayFormulaRange[sheetId] = Object.create(null);
}
const arrayData = new ObjectMatrix<IRange>(arrayFormulaRange[sheetId]);
// Get current sheet array formula cell data
if (this._runtimeArrayFormulaCellData[unitId] === undefined) {
- this._runtimeArrayFormulaCellData[unitId] = {};
+ this._runtimeArrayFormulaCellData[unitId] = Object.create(null);
}
const runtimeArrayFormulaCellData = this._runtimeArrayFormulaCellData[unitId]!;
@@ -560,7 +559,7 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
// Get current sheet clear array formula cell data
if (this._runtimeClearArrayFormulaCellData[unitId] === undefined) {
- this._runtimeClearArrayFormulaCellData[unitId] = {};
+ this._runtimeClearArrayFormulaCellData[unitId] = Object.create(null);
}
const clearArrayFormulaCellData = this._runtimeClearArrayFormulaCellData[unitId]!;
@@ -779,18 +778,18 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
const arrayFormulaEmbeddedMap = this._unitArrayFormulaEmbeddedMap;
if (arrayFormulaEmbeddedMap[unitId] == null) {
- arrayFormulaEmbeddedMap[unitId] = {};
+ arrayFormulaEmbeddedMap[unitId] = Object.create(null);
}
- if (arrayFormulaEmbeddedMap[unitId][sheetId] == null) {
- arrayFormulaEmbeddedMap[unitId][sheetId] = {};
+ if (arrayFormulaEmbeddedMap[unitId]![sheetId] == null) {
+ arrayFormulaEmbeddedMap[unitId]![sheetId] = Object.create(null);
}
- if (arrayFormulaEmbeddedMap[unitId][sheetId][rowIndex] == null) {
- arrayFormulaEmbeddedMap[unitId][sheetId][rowIndex] = {};
+ if (arrayFormulaEmbeddedMap[unitId]![sheetId][rowIndex] == null) {
+ arrayFormulaEmbeddedMap[unitId]![sheetId][rowIndex] = Object.create(null);
}
- arrayFormulaEmbeddedMap[unitId][sheetId][rowIndex][columnIndex] = true;
+ arrayFormulaEmbeddedMap[unitId]![sheetId][rowIndex][columnIndex] = true;
}
getRuntimeOtherData() {
@@ -871,7 +870,6 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
FORMULA_REF_TO_ARRAY_CACHE.clear();
}
- // eslint-disable-next-line complexity
private _checkIfArrayFormulaRangeHasData(
formulaUnitId: string,
formulaSheetId: string,
diff --git a/packages/sheets-data-validation/src/services/__tests__/dv-validator.service.spec.ts b/packages/sheets-data-validation/src/services/__tests__/dv-validator.service.spec.ts
index b617a34b07..9fed34efc1 100644
--- a/packages/sheets-data-validation/src/services/__tests__/dv-validator.service.spec.ts
+++ b/packages/sheets-data-validation/src/services/__tests__/dv-validator.service.spec.ts
@@ -17,18 +17,17 @@
import type {
IDataValidationRule,
IRange,
- IUniverInstanceService,
- LifecycleService,
Nullable,
Workbook,
Worksheet,
} from '@univerjs/core';
import type { ISheetLocation } from '@univerjs/sheets';
-import type { SheetDataValidationModel } from '../../models/sheet-data-validation-model';
-import type { DataValidationCacheService } from '../dv-cache.service';
-import { DataValidationStatus, LifecycleStages, ObjectMatrix } from '@univerjs/core';
+import { DataValidationStatus, Injector, IUniverInstanceService, LifecycleService, LifecycleStages, ObjectMatrix } from '@univerjs/core';
import { BehaviorSubject, Subject } from 'rxjs';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createFacadeTestBed } from '../../facade/__tests__/create-test-bed';
+import { SheetDataValidationModel } from '../../models/sheet-data-validation-model';
+import { DataValidationCacheService } from '../dv-cache.service';
import { SheetsDataValidationValidatorService } from '../dv-validator.service';
function createRule(uid: string, ranges: IRange[]): IDataValidationRule {
@@ -86,6 +85,13 @@ function createService() {
stage: LifecycleStages.Rendered,
} as unknown as LifecycleService;
+ const injector = new Injector([
+ [SheetsDataValidationValidatorService],
+ [IUniverInstanceService, { useValue: univerInstanceService }],
+ [SheetDataValidationModel, { useValue: model }],
+ [DataValidationCacheService, { useValue: cacheService }],
+ [LifecycleService, { useValue: lifecycleService }],
+ ]);
return {
dirtyRanges$,
lifecycle$,
@@ -97,11 +103,25 @@ function createService() {
univerInstanceService,
lifecycleService,
getLifecycleSubscribeCount: () => lifecycleSubscribeCount,
- service: new SheetsDataValidationValidatorService(univerInstanceService, model, cacheService, lifecycleService),
+ service: injector.get(SheetsDataValidationValidatorService),
};
}
describe('SheetsDataValidationValidatorService', () => {
+ it('does not pollute prototypes when buffering dirty ranges for an unknown unit', () => {
+ const { univer, injector } = createFacadeTestBed();
+ const marker = '__validation_pollution__';
+ try {
+ injector.get(SheetsDataValidationValidatorService);
+ injector.get(DataValidationCacheService).markRangeDirty('__proto__', marker, []);
+ injector.get(LifecycleService).stage = LifecycleStages.Rendered;
+ expect(Object.getOwnPropertyDescriptor(Object.prototype, marker)).toBeUndefined();
+ } finally {
+ Reflect.deleteProperty(Object.prototype, marker);
+ univer.dispose();
+ }
+ });
+
beforeEach(() => {
vi.useFakeTimers();
vi.stubGlobal('requestIdleCallback', (callback: IdleRequestCallback) => {
diff --git a/packages/sheets-data-validation/src/services/dv-validator.service.ts b/packages/sheets-data-validation/src/services/dv-validator.service.ts
index 59b128da58..bfd56e232d 100644
--- a/packages/sheets-data-validation/src/services/dv-validator.service.ts
+++ b/packages/sheets-data-validation/src/services/dv-validator.service.ts
@@ -40,11 +40,11 @@ export class SheetsDataValidationValidatorService extends Disposable {
const workbook = this._univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);
const worksheet = workbook?.getActiveSheet();
- const map: Record<string, Record<string, IRange[]>> = {};
+ const map: Record<string, Record<string, IRange[]>> = Object.create(null);
ranges.flat().forEach((range) => {
if (!map[range.unitId]) {
- map[range.unitId] = {};
+ map[range.unitId] = Object.create(null);
}
if (!map[range.unitId][range.subUnitId]) {
map[range.unitId][range.subUnitId] = [];
@@ -223,7 +223,7 @@ export class SheetsDataValidationValidatorService extends Disposable {
const sheetIds = this._sheetDataValidationModel.getSubUnitIds(unitId);
const results = await Promise.all(sheetIds.map((id) => this.validatorWorksheet(unitId, id)));
- const map: Record<string, ObjectMatrix<Nullable<DataValidationStatus>>> = {};
+ const map: Record<string, ObjectMatrix<Nullable<DataValidationStatus>>> = Object.create(null);
results.forEach((result, i) => {
map[sheetIds[i]] = result;
diff --git a/packages/sheets-formula/src/controllers/__tests__/active-dirty.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/active-dirty.controller.spec.ts
index 5fc17aea92..7676c6ea21 100644
--- a/packages/sheets-formula/src/controllers/__tests__/active-dirty.controller.spec.ts
+++ b/packages/sheets-formula/src/controllers/__tests__/active-dirty.controller.spec.ts
@@ -92,6 +92,23 @@ describe('ActiveDirtyController', () => {
testBed?.univer.dispose();
});
+ it.each(['__proto__', 'constructor', 'prototype', 'toString'])('keeps dirty sheet names local for special unit identifiers (%s)', (key) => {
+ testBed = createControllerTestBed();
+ testBed.injector.get(ActiveDirtyController);
+ const marker = '__formula_pollution__';
+ try {
+ const data = getDirtyData(testBed, {
+ id: RemoveSheetMutation.id,
+ params: { unitId: key, subUnitId: marker, subUnitName: 'Sheet 1' },
+ });
+ expect(data.dirtyNameMap?.[key]?.[marker]).toBe('Sheet 1');
+ expect(Object.getOwnPropertyDescriptor(Object.prototype, marker)).toBeUndefined();
+ } finally {
+ Reflect.deleteProperty(Object.prototype, marker);
+ Reflect.deleteProperty(Object, marker);
+ }
+ });
+
it('should convert range mutations into dirty ranges and skip style-triggered updates', () => {
testBed = createControllerTestBed();
diff --git a/packages/sheets-formula/src/controllers/active-dirty.controller.ts b/packages/sheets-formula/src/controllers/active-dirty.controller.ts
index 9daed98399..2f50db97f5 100644
--- a/packages/sheets-formula/src/controllers/active-dirty.controller.ts
+++ b/packages/sheets-formula/src/controllers/active-dirty.controller.ts
@@ -428,13 +428,13 @@ export class ActiveDirtyController extends Disposable {
}
private _getRemoveSheetMutation(params: IRemoveSheetMutationParams) {
- const dirtyNameMap: IDirtyUnitSheetNameMap = {};
+ const dirtyNameMap: IDirtyUnitSheetNameMap = Object.create(null);
const { subUnitId: sheetId, unitId, subUnitName } = params;
// const dirtyNameMap: IDirtyUnitSheetNameMap = {};
if (dirtyNameMap[unitId] == null) {
- dirtyNameMap[unitId] = {};
+ dirtyNameMap[unitId] = Object.create(null);
}
dirtyNameMap[unitId]![sheetId] = subUnitName;
@@ -443,11 +443,11 @@ export class ActiveDirtyController extends Disposable {
}
private _getInsertSheetMutation(params: IInsertSheetMutationParams) {
- const dirtyNameMap: IDirtyUnitSheetNameMap = {};
+ const dirtyNameMap: IDirtyUnitSheetNameMap = Object.create(null);
const { sheet, unitId } = params;
if (dirtyNameMap[unitId] == null) {
- dirtyNameMap[unitId] = {};
+ dirtyNameMap[unitId] = Object.create(null);
}
dirtyNameMap[unitId]![sheet.id] = sheet.name;
diff --git a/packages/sheets-formula/src/controllers/image-formula-cell-interceptor.controller.ts b/packages/sheets-formula/src/controllers/image-formula-cell-interceptor.controller.ts
index 54ed03ae9b..a685d39820 100644
--- a/packages/sheets-formula/src/controllers/image-formula-cell-interceptor.controller.ts
+++ b/packages/sheets-formula/src/controllers/image-formula-cell-interceptor.controller.ts
@@ -77,12 +77,12 @@ export class ImageFormulaCellInterceptorController extends Disposable {
})
);
- const unitImageFormulaData: IUnitImageFormulaDataType = {};
+ const unitImageFormulaData: IUnitImageFormulaDataType = Object.create(null);
updateRuntimeImageFormulaData.forEach((imageFormulaInfo) => {
const { unitId, sheetId, row, column, ...imageInfo } = imageFormulaInfo;
if (!unitImageFormulaData[unitId]) {
- unitImageFormulaData[unitId] = {};
+ unitImageFormulaData[unitId] = Object.create(null);
}
if (!unitImageFormulaData[unitId]![sheetId]) {
unitImageFormulaData[unitId]![sheetId] = new ObjectMatrix<Nullable<IImageFormulaInfo>>();
@@ -99,7 +99,6 @@ export class ImageFormulaCellInterceptorController extends Disposable {
);
}
- // eslint-disable-next-line max-lines-per-function
private _initInterceptorCellContent() {
this.disposeWithMe(
this._sheetInterceptorService.intercept(INTERCEPTOR_POINT.CELL_CONTENT, {
diff --git a/packages/sheets-formula/src/controllers/update-formula.controller.ts b/packages/sheets-formula/src/controllers/update-formula.controller.ts
index 48e69ff1ae..42bea8113d 100644
--- a/packages/sheets-formula/src/controllers/update-formula.controller.ts
+++ b/packages/sheets-formula/src/controllers/update-formula.controller.ts
@@ -263,7 +263,7 @@ export class UpdateFormulaController extends Disposable {
}
private _handleWorkbookAdded(unit: Workbook) {
- const formulaData: IFormulaData = {};
+ const formulaData: IFormulaData = Object.create(null);
const unitId = unit.getUnitId();
const newFormulaData: IFormulaData = { [unitId]: {} };
@@ -293,11 +293,11 @@ export class UpdateFormulaController extends Disposable {
// loop all sheets cell data, and get the dirty data
const dirtyRanges: IUnitRange[] = calculationMode === CalculationMode.WHEN_EMPTY ? this._formulaDataModel.getFormulaDirtyRanges() : [];
- const dirtyNameMap: IDirtyUnitSheetNameMap = {};
- const dirtyDefinedNameMap: IDirtyUnitDefinedNameMap = {};
- const dirtyUnitFeatureMap: IDirtyUnitFeatureMap = {};
- const dirtyUnitOtherFormulaMap: IDirtyUnitOtherFormulaMap = {};
- const clearDependencyTreeCache: IDirtyUnitSheetNameMap = {};
+ const dirtyNameMap: IDirtyUnitSheetNameMap = Object.create(null);
+ const dirtyDefinedNameMap: IDirtyUnitDefinedNameMap = Object.create(null);
+ const dirtyUnitFeatureMap: IDirtyUnitFeatureMap = Object.create(null);
+ const dirtyUnitOtherFormulaMap: IDirtyUnitOtherFormulaMap = Object.create(null);
+ const clearDependencyTreeCache: IDirtyUnitSheetNameMap = Object.create(null);
return {
forceCalculation,
@@ -350,7 +350,6 @@ export class UpdateFormulaController extends Disposable {
};
}
- // eslint-disable-next-line max-lines-per-function
private _getFormulaReferenceMoveInfo(
formulaData: IFormulaData,
unitSheetNameMap: IUnitSheetNameMap,
@@ -362,7 +361,7 @@ export class UpdateFormulaController extends Disposable {
if (formulaDataKeys.length === 0) return { newFormulaData: {} };
- const newFormulaData: IFormulaData = {};
+ const newFormulaData: IFormulaData = Object.create(null);
const { unitId: fromUnitId, sheetId: fromSheetId, sheetName: fromSheetName, targetUnitId, targetSheetId, type, from, to } = formulaReferenceMoveParam;
@@ -382,7 +381,7 @@ export class UpdateFormulaController extends Disposable {
const sheetDataKeys = Object.keys(sheetData);
if (!Tools.isDefine(newFormulaData[unitId])) {
- newFormulaData[unitId] = {};
+ newFormulaData[unitId] = Object.create(null);
}
for (const sheetId of sheetDataKeys) {
@@ -390,7 +389,6 @@ export class UpdateFormulaController extends Disposable {
const newFormulaDataItem = new ObjectMatrix<IFormulaDataItem>();
const shouldModifySi: string[] = [];
- // eslint-disable-next-line max-lines-per-function, complexity
matrixData.forValue((row, column, formulaDataItem) => {
if (!formulaDataItem) return true;
@@ -668,11 +666,11 @@ export class UpdateFormulaController extends Disposable {
if (inCrossSheetCutRangeNewFormulas.length > 0 && targetUnitId && targetSheetId) {
if (!newFormulaData[targetUnitId]) {
- newFormulaData[targetUnitId] = {};
+ newFormulaData[targetUnitId] = Object.create(null);
}
- if (!newFormulaData[targetUnitId][targetSheetId]) {
- newFormulaData[targetUnitId][targetSheetId] = {};
+ if (!newFormulaData[targetUnitId]![targetSheetId]) {
+ newFormulaData[targetUnitId]![targetSheetId] = Object.create(null);
}
for (const newFormula of inCrossSheetCutRangeNewFormulas) {
@@ -680,11 +678,11 @@ export class UpdateFormulaController extends Disposable {
const targetRow = fromRow + ((to?.startRow ?? 0) - (from?.startRow ?? 0));
const targetColumn = fromColumn + ((to?.startColumn ?? 0) - (from?.startColumn ?? 0));
- if (!newFormulaData[targetUnitId][targetSheetId][targetRow]) {
- newFormulaData[targetUnitId][targetSheetId][targetRow] = {};
+ if (!newFormulaData[targetUnitId]![targetSheetId]![targetRow]) {
+ newFormulaData[targetUnitId]![targetSheetId]![targetRow] = Object.create(null);
}
- newFormulaData[targetUnitId][targetSheetId][targetRow][targetColumn] = {
+ newFormulaData[targetUnitId]![targetSheetId]![targetRow][targetColumn] = {
f: formulaString,
};
}
diff --git a/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts b/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts
index bbce6a5871..2063aac7f0 100644
--- a/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts
+++ b/packages/sheets-formula/src/controllers/utils/ref-range-formula.ts
@@ -222,8 +222,8 @@ export function getFormulaReferenceRange(oldFormulaData: IFormulaData, newFormul
* @returns
*/
export function refRangeFormula(oldFormulaData: IFormulaData, newFormulaData: IFormulaData, formulaReferenceMoveParam: IFormulaReferenceMoveParam) {
- const redoFormulaData: Record<string, Record<string, IObjectMatrixPrimitiveType<Nullable<ICellData>>>> = {};
- const undoFormulaData: Record<string, Record<string, IObjectMatrixPrimitiveType<Nullable<ICellData>>>> = {};
+ const redoFormulaData: Record<string, Record<string, IObjectMatrixPrimitiveType<Nullable<ICellData>>>> = Object.create(null);
+ const undoFormulaData: Record<string, Record<string, IObjectMatrixPrimitiveType<Nullable<ICellData>>>> = Object.create(null);
const { unitId: fromUnitId, sheetId: fromSheetId } = formulaReferenceMoveParam;
const targetUnitId = formulaReferenceMoveParam.targetUnitId ?? fromUnitId;
@@ -264,10 +264,10 @@ export function refRangeFormula(oldFormulaData: IFormulaData, newFormulaData: IF
const sheetUndoFormulaData = getUndoFormulaData(rangeList, oldFormulaMatrix);
if (!redoFormulaData[unitId]) {
- redoFormulaData[unitId] = {};
+ redoFormulaData[unitId] = Object.create(null);
}
if (!undoFormulaData[unitId]) {
- undoFormulaData[unitId] = {};
+ undoFormulaData[unitId] = Object.create(null);
}
redoFormulaData[unitId][currentSheetId] = {