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.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
perf(worker): isolate worker package entry points (#8072)
白熱0ee34c290dc0
diff --git a/common/shared/tsdown/configs/umd.ts b/common/shared/tsdown/configs/umd.tsindex 86c0c82cc4..dd2342cb26 100644--- a/common/shared/tsdown/configs/umd.ts+++ b/common/shared/tsdown/configs/umd.ts@@ -1,6 +1,6 @@import type { UserConfig } from 'tsdown';-import type { IEntryConfig } from '../types.ts';import { defineConfig } from 'tsdown';+import type { IEntryConfig } from '../types.ts';import { peerDepsMap } from '../data/peer-deps.ts';import { createCssNoopInputOptions } from '../plugins/css-noop.ts';import { createOutputAliasPlugin } from '../plugins/output-alias.ts';@@ -56,7 +56,8 @@ function resolveUmdGlobal(source: string) {return `${convertLibNameFromPackageName(localeMatch[1])}${convertLibNameFromPackageName(localeMatch[2])}`;}- return convertLibNameFromPackageName(source);+ // Main-thread UMD consumers use the shared APIs exposed by the package's root global.+ return convertLibNameFromPackageName(source.replace(/\/worker$/, ''));}return null;diff --git a/common/shared/tsdown/index.ts b/common/shared/tsdown/index.tsindex 4c3ccd85b1..b2d0053a3b 100644--- a/common/shared/tsdown/index.ts+++ b/common/shared/tsdown/index.ts@@ -1,10 +1,10 @@-import type { TModuleFormat } from './configs/module.ts';-import type { IBuildContext, IBuildOptions } from './types.ts';import { existsSync, rmSync } from 'node:fs';import path from 'node:path';import process from 'node:process';import { pathToFileURL } from 'node:url';import { mergeConfig, build as tsdownBuild } from 'tsdown';+import type { TModuleFormat } from './configs/module.ts';+import type { IBuildContext, IBuildOptions } from './types.ts';import { createModuleConfig } from './configs/module.ts';import { createUmdConfig } from './configs/umd.ts';import { BUILD_OUTPUT_DIRECTORIES, BUILD_OUTPUT_ROOT, CLEANUP_DIRECTORIES } from './constants.ts';@@ -39,8 +39,9 @@ function createBuildContext(packageDir: string, options: IBuildOptions): IBuildC* Expands the package context into all required tsdown configs.*/function createModuleEntryGroups(entries: IBuildContext['entries']) {- const primaryEntries = entries.filter((entry) => entry.type === 'index' || entry.type === 'locale');- const isolatedEntries = entries.filter((entry) => entry.type !== 'index' && entry.type !== 'locale');+ // Share class definitions across public entries to preserve DI token identity.+ const primaryEntries = entries.filter((entry) => entry.type !== 'facade');+ const isolatedEntries = entries.filter((entry) => entry.type === 'facade');return [...(primaryEntries.length > 0 ? [primaryEntries] : []),@@ -72,7 +73,8 @@ export function createConfigs(context: IBuildContext, options: IBuildOptions) {return moduleConfigs;}- const umdConfigs = context.entries.map((entry) => createUmdConfig({+ // Worker entry points are published as ESM/CJS; UMD cannot share their internal modules.+ const umdConfigs = context.entries.filter((entry) => entry.type !== 'worker').map((entry) => createUmdConfig({baseConfig,enableObfuscation,entry,diff --git a/common/shared/tsdown/utils/cleanup-pkg.ts b/common/shared/tsdown/utils/cleanup-pkg.tsindex 68bcdfd8f6..2b03065ec8 100644--- a/common/shared/tsdown/utils/cleanup-pkg.ts+++ b/common/shared/tsdown/utils/cleanup-pkg.ts@@ -1,10 +1,9 @@-import type { IPackageJson } from '../types.ts';import { randomUUID } from 'node:crypto';import fs from 'node:fs';import path from 'node:path';import sortKeys from 'sort-keys';-import * as ts from 'typescript';+import type { IPackageJson } from '../types.ts';import { peerDepsMap } from '../data/peer-deps.ts';type StringMap = Record<string, string>;@@ -360,6 +359,7 @@ function deriveDependencyGroups(packageDir: string, packageJson: IPackageJson):function applyPublishManifest(pkg: CleanupPackageJson, packageDir: string) {const hasLocales = fs.existsSync(path.resolve(packageDir, 'src/locale'));const hasFacade = fs.existsSync(path.resolve(packageDir, 'src/facade/index.ts'));+ const hasWorker = fs.existsSync(path.resolve(packageDir, 'src/worker.ts'));pkg.publishConfig = {access: 'public',@@ -381,6 +381,15 @@ function applyPublishManifest(pkg: CleanupPackageJson, packageDir: string) {pkg.exports ||= {};+ if (hasWorker) {+ pkg.exports['./worker'] = './src/worker.ts';+ pkg.publishConfig.exports['./worker'] = {+ import: './lib/es/worker.js',+ require: './lib/cjs/worker.js',+ types: './lib/types/worker.d.ts',+ };+ }+if (hasLocales) {pkg.exports['./locale/*'] = './src/locale/*.ts';pkg.publishConfig.exports['./locale/*'] = {diff --git a/common/shared/tsdown/utils/entries.ts b/common/shared/tsdown/utils/entries.tsindex a8c9e212f1..547b68fb06 100644--- a/common/shared/tsdown/utils/entries.ts+++ b/common/shared/tsdown/utils/entries.ts@@ -1,6 +1,6 @@-import type { IEntryConfig } from '../types.ts';import { existsSync, readdirSync, statSync } from 'node:fs';import path from 'node:path';+import type { IEntryConfig } from '../types.ts';import { DEFAULT_ENTRY_FILE, FACADE_ENTRY_FILE, LOCALE_DIRECTORY } from '../constants.ts';/**@@ -22,6 +22,15 @@ export function getEntries(packageDir: string): IEntryConfig[] {});}+ const workerEntry = path.join(packageDir, 'src/worker.ts');+ if (existsSync(workerEntry)) {+ entries.push({+ key: 'worker',+ path: workerEntry,+ type: 'worker',+ });+ }+const localeDir = path.join(packageDir, LOCALE_DIRECTORY);if (!existsSync(localeDir)) {return entries;diff --git a/examples/src/docs/worker.ts b/examples/src/docs/worker.tsindex cc61f282fb..e2ad1aa570 100644--- a/examples/src/docs/worker.ts+++ b/examples/src/docs/worker.ts@@ -1,3 +1,5 @@-import { startDocsLayoutWorker } from '@univerjs/docs';+import { Univer } from '@univerjs/core';+import { UniverDocsWorkerPlugin } from '@univerjs/docs/worker';-startDocsLayoutWorker();+const univer = new Univer();+univer.registerPlugin(UniverDocsWorkerPlugin);diff --git a/packages/docs/package.json b/packages/docs/package.jsonindex 1bccf44ad7..1eff25f4df 100644--- a/packages/docs/package.json+++ b/packages/docs/package.json@@ -27,7 +27,8 @@"exports": {".": "./src/index.ts","./*": "./src/*",- "./facade": "./src/facade/index.ts"+ "./facade": "./src/facade/index.ts",+ "./worker": "./src/worker.ts"},"main": "./src/index.ts","types": "./lib/types/index.d.ts",@@ -46,6 +47,11 @@"require": "./lib/cjs/*","types": "./lib/types/index.d.ts"},+ "./worker": {+ "import": "./lib/es/worker.js",+ "require": "./lib/cjs/worker.js",+ "types": "./lib/types/worker.d.ts"+ },"./facade": {"import": "./lib/es/facade.js","require": "./lib/cjs/facade.js",diff --git a/packages/docs/src/config/config.ts b/packages/docs/src/config/config.tsindex cd451e1263..9d198db473 100644--- a/packages/docs/src/config/config.ts+++ b/packages/docs/src/config/config.ts@@ -23,3 +23,9 @@ export interface IUniverDocsConfig {}export const defaultPluginConfig: IUniverDocsConfig = {};++export const DOCS_WORKER_PLUGIN_CONFIG_KEY = 'docs.worker.config';++export interface IUniverDocsWorkerConfig {}++export const defaultPluginWorkerConfig: IUniverDocsWorkerConfig = {};diff --git a/packages/docs/src/index.ts b/packages/docs/src/index.tsindex 9f171e9eef..506e9985cd 100644--- a/packages/docs/src/index.ts+++ b/packages/docs/src/index.ts@@ -67,8 +67,13 @@ export type {IDocsCustomBlockMutationParams,IEmbedDocsCustomBlockData,} from './embed-host-anchor';-export { DocsLayoutWorkerCapabilityError, DocsLayoutWorkerClientService, startDocsLayoutWorker, UniverDocsLayoutWorkerPlugin } from './layout-worker';-export type { IDocsLayoutWorkerCapabilities, IDocsLayoutWorkerFontProbe, IDocsLayoutWorkerRuntime, IUniverDocsLayoutWorkerConfig } from './layout-worker';+export { DocsLayoutWorkerCapabilityError, DocsLayoutWorkerClientService, UniverDocsLayoutWorkerPlugin } from './layout-worker';+export type { IUniverDocsLayoutWorkerConfig } from './layout-worker/config/config';+export type { IDocsLayoutWorkerCapabilities, IDocsLayoutWorkerFontProbe, IDocsLayoutWorkerRuntime } from './layout-worker/protocol';+export {+ /** @deprecated Register UniverDocsWorkerPlugin from '@univerjs/docs/worker' instead. This root export will be removed in the next release. */+ startDocsLayoutWorker,+} from './layout-worker/worker';export { UniverDocsPlugin } from './plugin';export { DocBlockMoveValidatorService } from './services/doc-block-move-validator.service';export type {diff --git a/packages/docs/src/layout-worker/index.ts b/packages/docs/src/layout-worker/index.tsindex ca38450007..3a74a572cd 100644--- a/packages/docs/src/layout-worker/index.ts+++ b/packages/docs/src/layout-worker/index.ts@@ -15,22 +15,38 @@*/import type { IMessageProtocol } from '@univerjs/rpc';-import type { IDocLayoutCancelRequest, IDocLayoutCreateSessionRequest, IDocLayoutDisposeMountRequest, IDocLayoutDisposeSessionRequest, IDocLayoutExecutor, IDocLayoutPageRequest, IDocLayoutPageResult, IDocLayoutPerformanceMetrics, IDocLayoutStartRequest, IDocLayoutStartResult, IDocLayoutStepRequest, IDocLayoutStepResult } from '../services/doc-layout-executor.service';-import type { IDocsLayoutFontFace, IUniverDocsLayoutWorkerConfig } from './config/config';-import type { IDocsLayoutWorkerCapabilities, IDocsLayoutWorkerRuntime } from './protocol';import { DependentOn, Disposable, IConfigService, Inject, Injector, merge, Plugin, Tools } from '@univerjs/core';import { FontCache } from '@univerjs/engine-render';import { ChannelService, toModule } from '@univerjs/rpc';import { Observable, shareReplay } from 'rxjs';+import type {+ IDocLayoutCancelRequest,+ IDocLayoutCreateSessionRequest,+ IDocLayoutDisposeMountRequest,+ IDocLayoutDisposeSessionRequest,+ IDocLayoutExecutor,+ IDocLayoutPageRequest,+ IDocLayoutPageResult,+ IDocLayoutPerformanceMetrics,+ IDocLayoutStartRequest,+ IDocLayoutStartResult,+ IDocLayoutStepRequest,+ IDocLayoutStepResult,+} from '../services/doc-layout-executor.service';+import type { IDocsLayoutFontFace, IUniverDocsLayoutWorkerConfig } from './config/config';+import type { IDocsLayoutWorkerCapabilities, IDocsLayoutWorkerRuntime } from './protocol';import pkg from '../../package.json';import { UniverDocsPlugin } from '../plugin';import { DocLayoutExecutorService, DocLayoutExecutorType } from '../services/doc-layout-executor.service';-import { DEFAULT_DOCS_LAYOUT_WORKER_REQUEST_TIMEOUT_MS, defaultPluginDocsLayoutWorkerConfig, DOCS_LAYOUT_WORKER_PLUGIN_CONFIG_KEY } from './config/config';+import {+ DEFAULT_DOCS_LAYOUT_WORKER_REQUEST_TIMEOUT_MS,+ defaultPluginDocsLayoutWorkerConfig,+ DOCS_LAYOUT_WORKER_PLUGIN_CONFIG_KEY,+} from './config/config';import { collectDocumentFontFamilies, measureDocumentFontFamilies } from './document-font-metrics';import { DocsLayoutFontLoader } from './font-loader';import { DocsLayoutWorkerPerformanceTracker } from './performance-tracker';import { DOCS_LAYOUT_WORKER_CHANNEL, DOCS_LAYOUT_WORKER_PROTOCOL_VERSION } from './protocol';-import { startDocsLayoutWorker } from './worker';const FONT_METRICS_TOLERANCE = 1;@@ -312,7 +328,3 @@ export class UniverDocsLayoutWorkerPlugin extends Plugin {this.disposeWithMe(this._layoutExecutorService.register(client));}}--export type { IUniverDocsLayoutWorkerConfig } from './config/config';-export type { IDocsLayoutWorkerCapabilities, IDocsLayoutWorkerFontProbe, IDocsLayoutWorkerRuntime } from './protocol';-export { startDocsLayoutWorker };diff --git a/packages/docs/src/layout-worker/worker.ts b/packages/docs/src/layout-worker/worker.tsindex b46dcdcba0..6d450558d4 100644--- a/packages/docs/src/layout-worker/worker.ts+++ b/packages/docs/src/layout-worker/worker.ts@@ -17,13 +17,31 @@import type { ICustomRangeForInterceptor } from '@univerjs/core';import type { IDocsCustomBlockRenderViewport } from '@univerjs/engine-render';import type { IMessageProtocol } from '@univerjs/rpc';-import type { IDocLayoutCancelRequest, IDocLayoutCreateSessionRequest, IDocLayoutCustomRangePresentationEntry, IDocLayoutDisposeMountRequest, IDocLayoutDisposeSessionRequest, IDocLayoutMountIdentity, IDocLayoutPageRequest, IDocLayoutPageResult, IDocLayoutPerformanceMetrics, IDocLayoutStartRequest, IDocLayoutStartResult, IDocLayoutStepRequest, IDocLayoutStepResult } from '../services/doc-layout-executor.service';-import type { IDocsLayoutFontFace } from './config/config';-import type { IDocsLayoutWorkerCapabilities, IDocsLayoutWorkerRuntime } from './protocol';import { DocumentDataModel, LocaleService, requestImmediateMacroTask, Tools } from '@univerjs/core';-import { DocumentLayoutSession, FontCache, setDocsCustomBlockRenderViewportProvider } from '@univerjs/engine-render';+import {+ DocumentLayoutSession,+ FontCache,+ setDocsCustomBlockRenderViewportProvider,+} from '@univerjs/engine-render/worker';import { ChannelService, fromModule } from '@univerjs/rpc';import { Observable, shareReplay } from 'rxjs';+import type {+ IDocLayoutCancelRequest,+ IDocLayoutCreateSessionRequest,+ IDocLayoutCustomRangePresentationEntry,+ IDocLayoutDisposeMountRequest,+ IDocLayoutDisposeSessionRequest,+ IDocLayoutMountIdentity,+ IDocLayoutPageRequest,+ IDocLayoutPageResult,+ IDocLayoutPerformanceMetrics,+ IDocLayoutStartRequest,+ IDocLayoutStartResult,+ IDocLayoutStepRequest,+ IDocLayoutStepResult,+} from '../services/doc-layout-executor.service';+import type { IDocsLayoutFontFace } from './config/config';+import type { IDocsLayoutWorkerCapabilities, IDocsLayoutWorkerRuntime } from './protocol';import { DocLayoutExecutorType, DocLayoutSessionStatus } from '../services/doc-layout-executor.service';import { DocsLayoutFontLoader } from './font-loader';import { DocsLayoutWorkerPerformanceTracker } from './performance-tracker';diff --git a/packages/docs/src/worker.ts b/packages/docs/src/worker.tsnew file mode 100644index 0000000000..c71fe07e67--- /dev/null+++ b/packages/docs/src/worker.ts@@ -0,0 +1,41 @@+/**+ * 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 { IConfigService, Inject, Injector, merge, Plugin } from '@univerjs/core';+import type { IUniverDocsWorkerConfig } from './config/config';+import pkg from '../package.json';+import { defaultPluginWorkerConfig, DOCS_WORKER_PLUGIN_CONFIG_KEY } from './config/config';+import { startDocsLayoutWorker } from './layout-worker/worker';++export class UniverDocsWorkerPlugin extends Plugin {+ static override pluginName = 'UNIVER_DOCS_WORKER_PLUGIN';+ static override packageName = pkg.name;+ static override version = pkg.version;++ constructor(+ private readonly _config: IUniverDocsWorkerConfig = defaultPluginWorkerConfig,+ @Inject(Injector) protected override readonly _injector: Injector,+ @IConfigService private readonly _configService: IConfigService+ ) {+ super();+ const { ...rest } = merge({}, defaultPluginWorkerConfig, this._config);+ this._configService.setConfig(DOCS_WORKER_PLUGIN_CONFIG_KEY, rest);+ }++ override onStarting(): void {+ this.disposeWithMe(startDocsLayoutWorker());+ }+}diff --git a/packages/engine-formula/package.json b/packages/engine-formula/package.jsonindex 6586287433..b7465ae655 100644--- a/packages/engine-formula/package.json+++ b/packages/engine-formula/package.json@@ -28,7 +28,8 @@".": "./src/index.ts","./*": "./src/*","./facade": "./src/facade/index.ts",- "./locale/*": "./src/locale/*.ts"+ "./locale/*": "./src/locale/*.ts",+ "./worker": "./src/worker.ts"},"main": "./src/index.ts","types": "./lib/types/index.d.ts",@@ -47,6 +48,11 @@"require": "./lib/cjs/*","types": "./lib/types/index.d.ts"},+ "./worker": {+ "import": "./lib/es/worker.js",+ "require": "./lib/cjs/worker.js",+ "types": "./lib/types/worker.d.ts"+ },"./locale/*": {"import": "./lib/es/locale/*.js","require": "./lib/cjs/locale/*.js",diff --git a/packages/engine-formula/src/worker.ts b/packages/engine-formula/src/worker.tsnew file mode 100644index 0000000000..0dd80396c3--- /dev/null+++ b/packages/engine-formula/src/worker.ts@@ -0,0 +1,17 @@+/**+ * 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.+ */++export { UniverFormulaEnginePlugin } from './plugin';diff --git a/packages/engine-render/package.json b/packages/engine-render/package.jsonindex 4f343f7369..df317b16e8 100644--- a/packages/engine-render/package.json+++ b/packages/engine-render/package.json@@ -26,7 +26,8 @@],"exports": {".": "./src/index.ts",- "./*": "./src/*"+ "./*": "./src/*",+ "./worker": "./src/worker.ts"},"main": "./src/index.ts","types": "./lib/types/index.d.ts",@@ -45,6 +46,11 @@"require": "./lib/cjs/*","types": "./lib/types/index.d.ts"},+ "./worker": {+ "import": "./lib/es/worker.js",+ "require": "./lib/cjs/worker.js",+ "types": "./lib/types/worker.d.ts"+ },"./lib/*": "./lib/*"}},diff --git a/packages/engine-render/src/index.ts b/packages/engine-render/src/index.tsindex dad342587f..20bf9053a6 100644--- a/packages/engine-render/src/index.ts+++ b/packages/engine-render/src/index.ts@@ -149,5 +149,8 @@ export { CanvasColorService, DumbCanvasColorService, ICanvasColorService } fromexport * from './shape';export * from './viewport';-export { DocumentLayoutSession } from './worker-layout';+export {+ /** @deprecated Import from '@univerjs/engine-render/worker' instead. This root export will be removed in the next release. */+ DocumentLayoutSession,+} from './worker';export type { IDocumentLayoutSessionStartOptions, IDocumentLayoutStepResult } from './worker-layout';diff --git a/packages/engine-render/src/worker.ts b/packages/engine-render/src/worker.tsnew file mode 100644index 0000000000..8eb711ad04--- /dev/null+++ b/packages/engine-render/src/worker.ts@@ -0,0 +1,19 @@+/**+ * 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.+ */++export { setDocsCustomBlockRenderViewportProvider } from './components/docs/custom-block-render-viewport';+export { FontCache } from './components/docs/layout/shaping-engine/font-cache';+export { DocumentLayoutSession } from './worker-layout';diff --git a/packages/rpc-node/package.json b/packages/rpc-node/package.jsonindex 76cdd5346f..6fc1cae180 100644--- a/packages/rpc-node/package.json+++ b/packages/rpc-node/package.json@@ -26,7 +26,8 @@],"exports": {".": "./src/index.ts",- "./*": "./src/*"+ "./*": "./src/*",+ "./worker": "./src/worker.ts"},"main": "./src/index.ts","types": "./lib/types/index.d.ts",@@ -45,6 +46,11 @@"require": "./lib/cjs/*","types": "./lib/types/index.d.ts"},+ "./worker": {+ "import": "./lib/es/worker.js",+ "require": "./lib/cjs/worker.js",+ "types": "./lib/types/worker.d.ts"+ },"./lib/*": "./lib/*"}},diff --git a/packages/rpc-node/src/index.ts b/packages/rpc-node/src/index.tsindex 5c37757fee..deadd748ee 100644--- a/packages/rpc-node/src/index.ts+++ b/packages/rpc-node/src/index.ts@@ -14,4 +14,8 @@* limitations under the License.*/-export { UniverRPCNodeMainPlugin, UniverRPCNodeWorkerPlugin } from './plugin';+export { UniverRPCNodeMainPlugin } from './plugin';+export {+ /** @deprecated Import from '@univerjs/rpc-node/worker' instead. This root export will be removed in the next release. */+ UniverRPCNodeWorkerPlugin,+} from './worker';diff --git a/packages/rpc-node/src/plugin.ts b/packages/rpc-node/src/plugin.tsindex ed89f90cdd..67913ecfbb 100644--- a/packages/rpc-node/src/plugin.ts+++ b/packages/rpc-node/src/plugin.ts@@ -17,23 +17,19 @@import type { Dependency } from '@univerjs/core';import type { IMessageProtocol } from '@univerjs/rpc';import type { ChildProcess, Serializable } from 'node:child_process';-import type { IUniverRPCNodeMainConfig, IUniverRPCNodeWorkerThreadConfig } from './config/config';-import { fork } from 'node:child_process';-import process from 'node:process';import { IConfigService, ILogService, Inject, Injector, merge, Plugin } from '@univerjs/core';import {ChannelService,DataSyncPrimaryController,- DataSyncReplicaController,- IRemoteInstanceService,IRemoteSyncService,IRPCChannelService,RemoteSyncPrimaryService,- WebWorkerRemoteInstanceService,} from '@univerjs/rpc';+import { fork } from 'node:child_process';import { Observable, shareReplay } from 'rxjs';+import type { IUniverRPCNodeMainConfig } from './config/config';import pkg from '../package.json';-import { defaultPluginMainThreadConfig, defaultPluginWorkerThreadConfig, PLUGIN_CONFIG_KEY_MAIN_THREAD, PLUGIN_CONFIG_KEY_WORKER_THREAD } from './config/config';+import { defaultPluginMainThreadConfig, PLUGIN_CONFIG_KEY_MAIN_THREAD } from './config/config';export class UniverRPCNodeMainPlugin extends Plugin {static override pluginName = 'UNIVER_RPC_NODE_MAIN_PLUGIN';@@ -68,8 +64,9 @@ export class UniverRPCNodeMainPlugin extends Plugin {const dependencies: Dependency[] = [[IRPCChannelService, {- // eslint-disable-next-line react/no-unnecessary-use-prefix- useFactory: () => new ChannelService(messageProtocol),+ useFactory: function createChannelService() {+ return new ChannelService(messageProtocol);+ },}],[DataSyncPrimaryController],[IRemoteSyncService, { useClass: RemoteSyncPrimaryService }],@@ -95,41 +92,6 @@ export class UniverRPCNodeMainPlugin extends Plugin {}}-export class UniverRPCNodeWorkerPlugin extends Plugin {- static override pluginName = 'UNIVER_RPC_NODE_WORKER_PLUGIN';- static override packageName = pkg.name;- static override version = pkg.version;-- constructor(- private readonly _config: Partial<IUniverRPCNodeWorkerThreadConfig> = defaultPluginWorkerThreadConfig,- @Inject(Injector) protected readonly _injector: Injector,- @IConfigService private readonly _configService: IConfigService- ) {- super();-- // Manage the plugin configuration.- const { ...rest } = merge(- {},- defaultPluginWorkerThreadConfig,- this._config- );- this._configService.setConfig(PLUGIN_CONFIG_KEY_WORKER_THREAD, rest);- }-- override onStarting(): void {- ([- [DataSyncReplicaController],- [IRPCChannelService, {- // eslint-disable-next-line react/no-unnecessary-use-prefix- useFactory: () => new ChannelService(createNodeWorkerMessageProtocol()),- }],- [IRemoteInstanceService, { useClass: WebWorkerRemoteInstanceService }],- ] as Dependency[]).forEach((d) => this._injector.add(d));-- this._injector.get(DataSyncReplicaController);- }-}-function createNodeMessagePortOnMain(injector: Injector, path: string): [IMessageProtocol, ChildProcess] {const logService = injector.get(ILogService);@@ -153,19 +115,3 @@ function createNodeMessagePortOnMain(injector: Injector, path: string): [IMessagreturn [messageProtocol, child];}--function createNodeWorkerMessageProtocol(): IMessageProtocol {- return {- send(message) {- process.send!(message as Serializable);- },- onMessage: new Observable<unknown>((subscriber) => {- const handler = (event: unknown) => {- subscriber.next(event);- };-- process.on('message', handler);- return () => process.off('message', handler);- }).pipe(shareReplay({ bufferSize: 1, refCount: true })),- };-}diff --git a/packages/rpc-node/src/worker.ts b/packages/rpc-node/src/worker.tsnew file mode 100644index 0000000000..8e07f2d94e--- /dev/null+++ b/packages/rpc-node/src/worker.ts@@ -0,0 +1,84 @@+/**+ * 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 type { Dependency } from '@univerjs/core';+import type { IMessageProtocol } from '@univerjs/rpc';+import type { Serializable } from 'node:child_process';+import { IConfigService, Inject, Injector, merge, Plugin } from '@univerjs/core';+import {+ ChannelService,+ DataSyncReplicaController,+ IRemoteInstanceService,+ IRPCChannelService,+ WebWorkerRemoteInstanceService,+} from '@univerjs/rpc';+import process from 'node:process';+import { Observable, shareReplay } from 'rxjs';+import type { IUniverRPCNodeWorkerThreadConfig } from './config/config';+import pkg from '../package.json';+import { defaultPluginWorkerThreadConfig, PLUGIN_CONFIG_KEY_WORKER_THREAD } from './config/config';++export class UniverRPCNodeWorkerPlugin extends Plugin {+ static override pluginName = 'UNIVER_RPC_NODE_WORKER_PLUGIN';+ static override packageName = pkg.name;+ static override version = pkg.version;++ constructor(+ private readonly _config: Partial<IUniverRPCNodeWorkerThreadConfig> = defaultPluginWorkerThreadConfig,+ @Inject(Injector) protected readonly _injector: Injector,+ @IConfigService private readonly _configService: IConfigService+ ) {+ super();++ // Manage the plugin configuration.+ const { ...rest } = merge(+ {},+ defaultPluginWorkerThreadConfig,+ this._config+ );+ this._configService.setConfig(PLUGIN_CONFIG_KEY_WORKER_THREAD, rest);+ }++ override onStarting(): void {+ ([+ [DataSyncReplicaController],+ [IRPCChannelService, {+ useFactory: function createChannelService() {+ return new ChannelService(createNodeWorkerMessageProtocol());+ },+ }],+ [IRemoteInstanceService, { useClass: WebWorkerRemoteInstanceService }],+ ] as Dependency[]).forEach((d) => this._injector.add(d));++ this._injector.get(DataSyncReplicaController);+ }+}++function createNodeWorkerMessageProtocol(): IMessageProtocol {+ return {+ send(message) {+ process.send!(message as Serializable);+ },+ onMessage: new Observable<unknown>((subscriber) => {+ const handler = (event: unknown) => {+ subscriber.next(event);+ };++ process.on('message', handler);+ return () => process.off('message', handler);+ }).pipe(shareReplay({ bufferSize: 1, refCount: true })),+ };+}diff --git a/packages/rpc/package.json b/packages/rpc/package.jsonindex 72948c98c1..1bf2a85ac7 100644--- a/packages/rpc/package.json+++ b/packages/rpc/package.json@@ -26,7 +26,8 @@],"exports": {".": "./src/index.ts",- "./*": "./src/*"+ "./*": "./src/*",+ "./worker": "./src/worker.ts"},"main": "./src/index.ts","types": "./lib/types/index.d.ts",@@ -45,6 +46,11 @@"require": "./lib/cjs/*","types": "./lib/types/index.d.ts"},+ "./worker": {+ "import": "./lib/es/worker.js",+ "require": "./lib/cjs/worker.js",+ "types": "./lib/types/worker.d.ts"+ },"./lib/*": "./lib/*"}},diff --git a/packages/rpc/src/index.ts b/packages/rpc/src/index.tsindex 62ced33114..cfe6dfff46 100644--- a/packages/rpc/src/index.ts+++ b/packages/rpc/src/index.ts@@ -18,10 +18,7 @@ export type { IUniverRPCMainThreadConfig, IUniverRPCWorkerThreadConfig } from '.export { PLUGIN_CONFIG_KEY_MAIN_THREAD, PLUGIN_CONFIG_KEY_WORKER_THREAD } from './config/config';export { DataSyncPrimaryController } from './controllers/data-sync/data-sync-primary.controller';export { DataSyncReplicaController } from './controllers/data-sync/data-sync-replica.controller';-export {- UniverRPCMainThreadPlugin,- UniverRPCWorkerThreadPlugin,-} from './plugin';+export { UniverRPCMainThreadPlugin } from './plugin';export {IRemoteInstanceService,RemoteInstanceServiceName,@@ -33,3 +30,7 @@ export { IRemoteSyncService } from './services/remote-instance/remote-instance.sexport { ChannelService, IRPCChannelService } from './services/rpc/channel.service';export { ChannelClient, ChannelServer, fromModule, toModule } from './services/rpc/rpc.service';export type { IMessageProtocol } from './services/rpc/rpc.service';+export {+ /** @deprecated Import from '@univerjs/rpc/worker' instead. This root export will be removed in the next release. */+ UniverRPCWorkerThreadPlugin,+} from './worker';diff --git a/packages/rpc/src/plugin.ts b/packages/rpc/src/plugin.tsindex 02d0923c9a..1bce7b8b41 100644--- a/packages/rpc/src/plugin.ts+++ b/packages/rpc/src/plugin.ts@@ -15,30 +15,23 @@*/import type { Dependency } from '@univerjs/core';+import { IConfigService, Inject, Injector, merge, Plugin } from '@univerjs/core';import type {IUniverRPCMainThreadConfig,- IUniverRPCWorkerThreadConfig,} from './config/config';-import { IConfigService, Inject, Injector, merge, Plugin } from '@univerjs/core';import pkg from '../package.json';import {defaultPluginMainThreadConfig,- defaultPluginWorkerThreadConfig,PLUGIN_CONFIG_KEY_MAIN_THREAD,- PLUGIN_CONFIG_KEY_WORKER_THREAD,} from './config/config';import { DataSyncPrimaryController } from './controllers/data-sync/data-sync-primary.controller';-import { DataSyncReplicaController } from './controllers/data-sync/data-sync-replica.controller';import {- IRemoteInstanceService,IRemoteSyncService,RemoteSyncPrimaryService,- WebWorkerRemoteInstanceService,} from './services/remote-instance/remote-instance.service';import { ChannelService, IRPCChannelService } from './services/rpc/channel.service';import {createWebWorkerMessagePortOnMain,- createWebWorkerMessagePortOnWorker,} from './services/rpc/implementations/web-worker-rpc.service';/**@@ -91,8 +84,9 @@ export class UniverRPCMainThreadPlugin extends Plugin {[IRPCChannelService,{- // eslint-disable-next-line react/no-unnecessary-use-prefix- useFactory: () => new ChannelService(messageProtocol),+ useFactory: function createChannelService() {+ return new ChannelService(messageProtocol);+ },},],[DataSyncPrimaryController],@@ -105,46 +99,3 @@ export class UniverRPCMainThreadPlugin extends Plugin {this._injector.get(DataSyncPrimaryController);}}--/**- * This plugin is used to register the RPC services on the worker thread.- */-export class UniverRPCWorkerThreadPlugin extends Plugin {- static override pluginName = 'UNIVER_RPC_WORKER_THREAD_PLUGIN';- static override packageName = pkg.name;- static override version = pkg.version;-- constructor(- private readonly _config: Partial<IUniverRPCWorkerThreadConfig> = defaultPluginWorkerThreadConfig,- @Inject(Injector) protected readonly _injector: Injector,- @IConfigService private readonly _configService: IConfigService- ) {- super();-- // Manage the plugin configuration.- const { ...rest } = merge(- {},- defaultPluginWorkerThreadConfig,- this._config- );- this._configService.setConfig(PLUGIN_CONFIG_KEY_WORKER_THREAD, rest);- }-- override onStarting(): void {- (- [- [DataSyncReplicaController],- [- IRPCChannelService,- {- // eslint-disable-next-line react/no-unnecessary-use-prefix- useFactory: () => new ChannelService(createWebWorkerMessagePortOnWorker()),- },- ],- [IRemoteInstanceService, { useClass: WebWorkerRemoteInstanceService }],- ] as Dependency[]- ).forEach((dependency) => this._injector.add(dependency));-- this._injector.get(DataSyncReplicaController);- }-}diff --git a/packages/rpc/src/worker.ts b/packages/rpc/src/worker.tsnew file mode 100644index 0000000000..619438145a--- /dev/null+++ b/packages/rpc/src/worker.ts@@ -0,0 +1,72 @@+/**+ * 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 type { Dependency } from '@univerjs/core';+import { IConfigService, Inject, Injector, merge, Plugin } from '@univerjs/core';+import type { IUniverRPCWorkerThreadConfig } from './config/config';+import pkg from '../package.json';+import { defaultPluginWorkerThreadConfig, PLUGIN_CONFIG_KEY_WORKER_THREAD } from './config/config';+import { DataSyncReplicaController } from './controllers/data-sync/data-sync-replica.controller';+import {+ IRemoteInstanceService,+ WebWorkerRemoteInstanceService,+} from './services/remote-instance/remote-instance.service';+import { ChannelService, IRPCChannelService } from './services/rpc/channel.service';+import { createWebWorkerMessagePortOnWorker } from './services/rpc/implementations/web-worker-rpc.service';++/**+ * This plugin is used to register the RPC services on the worker thread.+ */+export class UniverRPCWorkerThreadPlugin extends Plugin {+ static override pluginName = 'UNIVER_RPC_WORKER_THREAD_PLUGIN';+ static override packageName = pkg.name;+ static override version = pkg.version;++ constructor(+ private readonly _config: Partial<IUniverRPCWorkerThreadConfig> = defaultPluginWorkerThreadConfig,+ @Inject(Injector) protected readonly _injector: Injector,+ @IConfigService private readonly _configService: IConfigService+ ) {+ super();++ // Manage the plugin configuration.+ const { ...rest } = merge(+ {},+ defaultPluginWorkerThreadConfig,+ this._config+ );+ this._configService.setConfig(PLUGIN_CONFIG_KEY_WORKER_THREAD, rest);+ }++ override onStarting(): void {+ (+ [+ [DataSyncReplicaController],+ [+ IRPCChannelService,+ {+ useFactory: function createChannelService() {+ return new ChannelService(createWebWorkerMessagePortOnWorker());+ },+ },+ ],+ [IRemoteInstanceService, { useClass: WebWorkerRemoteInstanceService }],+ ] as Dependency[]+ ).forEach((dependency) => this._injector.add(dependency));++ this._injector.get(DataSyncReplicaController);+ }+}diff --git a/packages/sheets-filter-ui/package.json b/packages/sheets-filter-ui/package.jsonindex 60b2313dd3..3afc4e40f0 100644--- a/packages/sheets-filter-ui/package.json+++ b/packages/sheets-filter-ui/package.json@@ -27,7 +27,8 @@"exports": {".": "./src/index.ts","./*": "./src/*",- "./locale/*": "./src/locale/*.ts"+ "./locale/*": "./src/locale/*.ts",+ "./worker": "./src/worker.ts"},"main": "./src/index.ts","types": "./lib/types/index.d.ts",@@ -46,6 +47,11 @@"require": "./lib/cjs/*","types": "./lib/types/index.d.ts"},+ "./worker": {+ "import": "./lib/es/worker.js",+ "require": "./lib/cjs/worker.js",+ "types": "./lib/types/worker.d.ts"+ },"./locale/*": {"import": "./lib/es/locale/*.js","require": "./lib/cjs/locale/*.js",diff --git a/packages/sheets-filter-ui/src/index.ts b/packages/sheets-filter-ui/src/index.tsindex a83c00410c..83963f2f74 100644--- a/packages/sheets-filter-ui/src/index.ts+++ b/packages/sheets-filter-ui/src/index.ts@@ -22,4 +22,7 @@ export type { IUniverSheetsFilterUIConfig } from './config/config';export { menuSchema as SheetsFilterUIMenuSchema } from './menu/schema';export { UniverSheetsFilterMobileUIPlugin } from './mobile-plugin';export { UniverSheetsFilterUIPlugin } from './plugin';-export { UniverSheetsFilterUIWorkerPlugin } from './worker/plugin';+export {+ /** @deprecated Import from '@univerjs/sheets-filter-ui/worker' instead. This root export will be removed in the next release. */+ UniverSheetsFilterUIWorkerPlugin,+} from './worker';diff --git a/packages/sheets-filter-ui/src/worker.ts b/packages/sheets-filter-ui/src/worker.tsnew file mode 100644index 0000000000..569cd64557--- /dev/null+++ b/packages/sheets-filter-ui/src/worker.ts@@ -0,0 +1,17 @@+/**+ * 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.+ */++export { UniverSheetsFilterUIWorkerPlugin } from './worker/plugin';diff --git a/packages/sheets-filter-ui/src/worker/__tests__/generate-filter-values.service.spec.ts b/packages/sheets-filter-ui/src/worker/__tests__/generate-filter-values.service.spec.tsindex b104961bbd..c82db837e1 100644--- a/packages/sheets-filter-ui/src/worker/__tests__/generate-filter-values.service.spec.ts+++ b/packages/sheets-filter-ui/src/worker/__tests__/generate-filter-values.service.spec.ts@@ -14,23 +14,28 @@* limitations under the License.*/-import { DesktopLogService, ILogService, Injector, IUniverInstanceService, LocaleService } from '@univerjs/core';-import { beforeEach, describe, expect, it } from 'vitest';+import { LocaleService, LocaleType, Univer, UniverInstanceType } from '@univerjs/core';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import enUS from '../../locale/en-US';import { SheetsGenerateFilterValuesService } from '../generate-filter-values.service';describe('SheetsGenerateFilterValuesService', () => {- let service: SheetsGenerateFilterValuesService;+ let univer: Univer;beforeEach(() => {- const injector = new Injector();- injector.add([LocaleService]);- injector.add([ILogService, { useClass: DesktopLogService }]);- injector.add([IUniverInstanceService, { useValue: { getUnit: () => null } as unknown as IUniverInstanceService }]);+ univer = new Univer({ locale: LocaleType.EN_US, locales: { [LocaleType.EN_US]: enUS } });+ const injector = univer.__getInjector();+ injector.get(LocaleService).setDirection('ltr');injector.add([SheetsGenerateFilterValuesService]);- service = injector.get(SheetsGenerateFilterValuesService);+ });++ afterEach(() => {+ univer.dispose();});it('returns no filter value tree when the workbook or worksheet is unavailable', async () => {+ const service = univer.__getInjector().get(SheetsGenerateFilterValuesService);+await expect(service.getFilterValues({unitId: 'missing-book',subUnitId: 'sheet-1',@@ -42,4 +47,38 @@ describe('SheetsGenerateFilterValuesService', () => {alreadyChecked: [],})).resolves.toEqual([]);});++ it('counts matching values while excluding rows filtered by another column', async () => {+ const service = univer.__getInjector().get(SheetsGenerateFilterValuesService);+ univer.createUnit(UniverInstanceType.UNIVER_SHEET, {+ id: 'workbook',+ sheetOrder: ['sheet'],+ sheets: {+ sheet: {+ id: 'sheet',+ name: 'Sales',+ rowCount: 4,+ columnCount: 1,+ cellData: {+ 1: { 0: { v: 'A' } },+ 2: { 0: { v: 'B' } },+ 3: { 0: { v: 'A' } },+ },+ },+ },+ });++ const result = await service.getFilterValues({+ unitId: 'workbook',+ subUnitId: 'sheet',+ filteredOutRowsByOtherColumns: [2],+ filterColumn: null,+ filters: false,+ blankChecked: true,+ iterateRange: { startRow: 1, endRow: 3, startColumn: 0, endColumn: 0 },+ alreadyChecked: [],+ });++ expect(result).toMatchObject({ filterTreeItems: [{ title: 'A', count: 2 }] });+ });});diff --git a/packages/sheets-filter/package.json b/packages/sheets-filter/package.jsonindex f7862ea52c..cae01bef5e 100644--- a/packages/sheets-filter/package.json+++ b/packages/sheets-filter/package.json@@ -28,7 +28,8 @@".": "./src/index.ts","./*": "./src/*","./facade": "./src/facade/index.ts",- "./locale/*": "./src/locale/*.ts"+ "./locale/*": "./src/locale/*.ts",+ "./worker": "./src/worker.ts"},"main": "./src/index.ts","types": "./lib/types/index.d.ts",@@ -47,6 +48,11 @@"require": "./lib/cjs/*","types": "./lib/types/index.d.ts"},+ "./worker": {+ "import": "./lib/es/worker.js",+ "require": "./lib/cjs/worker.js",+ "types": "./lib/types/worker.d.ts"+ },"./locale/*": {"import": "./lib/es/locale/*.js","require": "./lib/cjs/locale/*.js",diff --git a/packages/sheets-filter/src/worker.ts b/packages/sheets-filter/src/worker.tsnew file mode 100644index 0000000000..d7b214a9a6--- /dev/null+++ b/packages/sheets-filter/src/worker.ts@@ -0,0 +1,17 @@+/**+ * 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.+ */++export { UniverSheetsFilterPlugin } from './plugin';diff --git a/packages/sheets-formula/package.json b/packages/sheets-formula/package.jsonindex 74ebb25d0c..f51902eb07 100644--- a/packages/sheets-formula/package.json+++ b/packages/sheets-formula/package.json@@ -28,7 +28,8 @@".": "./src/index.ts","./*": "./src/*","./locale/*": "./src/locale/*.ts",- "./facade": "./src/facade/index.ts"+ "./facade": "./src/facade/index.ts",+ "./worker": "./src/worker.ts"},"main": "./src/index.ts","types": "./lib/types/index.d.ts",@@ -47,6 +48,11 @@"require": "./lib/cjs/*","types": "./lib/types/index.d.ts"},+ "./worker": {+ "import": "./lib/es/worker.js",+ "require": "./lib/cjs/worker.js",+ "types": "./lib/types/worker.d.ts"+ },"./locale/*": {"import": "./lib/es/locale/*.js","require": "./lib/cjs/locale/*.js",diff --git a/packages/sheets-formula/src/controllers/__tests__/array-formula-cell-interceptor.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/array-formula-cell-interceptor.controller.spec.tsindex 3c83862eae..fe21f2da06 100644--- a/packages/sheets-formula/src/controllers/__tests__/array-formula-cell-interceptor.controller.spec.ts+++ b/packages/sheets-formula/src/controllers/__tests__/array-formula-cell-interceptor.controller.spec.ts@@ -14,21 +14,54 @@* limitations under the License.*/-import type { Dependency, IWorkbookData, Workbook, Worksheet } from '@univerjs/core';+import type { Dependency, ICommand, IWorkbookData, Workbook, Worksheet } from '@univerjs/core';+import type { FFormula } from '@univerjs/engine-formula/facade';+import type { IMessageProtocol } from '@univerjs/rpc';import {CellValueType,ICommandService,+ ILogService,+ Inject,+ Injector,InterceptorEffectEnum,+ IUniverInstanceService,+ LocaleService,LocaleType,+ LogLevel,+ Plugin,+ Univer,+ UniverInstanceType,} from '@univerjs/core';+import { FUniver } from '@univerjs/core/facade';import {+ CalculateController,+ ErrorType,FormulaDataModel,SetArrayFormulaDataMutation,+ SetFormulaCalculationNotificationMutation,+ SetFormulaCalculationResultMutation,+ SetFormulaCalculationStartMutation,+ UniverFormulaEnginePlugin,} from '@univerjs/engine-formula';-import { INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import {+ ChannelService,+ DataSyncPrimaryController,+ DataSyncReplicaController,+ IRemoteInstanceService,+ IRemoteSyncService,+ IRPCChannelService,+ RemoteSyncPrimaryService,+ WebWorkerRemoteInstanceService,+} from '@univerjs/rpc';+import { INTERCEPTOR_POINT, SetRangeValuesMutation, SheetInterceptorService, UniverSheetsPlugin } from '@univerjs/sheets';+import { ReplaySubject } from 'rxjs';+import { afterEach, describe, expect, it } from 'vitest';import { createFacadeTestBed } from '../../facade/__tests__/create-test-bed';+import formulaEnUS from '../../locale/en-US';+import { UniverSheetsFormulaPlugin } from '../../plugin';+import { UniverRemoteSheetsFormulaPlugin } from '../../worker';import { ArrayFormulaCellInterceptorController } from '../array-formula-cell-interceptor.controller';+import '@univerjs/engine-formula/facade';function createWorkbookData(): IWorkbookData {return {@@ -88,31 +121,21 @@ function getInterceptedCell(worksheet: Worksheet, workbook: Workbook, row: numbedescribe('ArrayFormulaCellInterceptorController', () => {let testBed: ReturnType<typeof createControllerTestBed>;- let commandService: ICommandService;- let formulaDataModel: FormulaDataModel;- let interceptorService: SheetInterceptorService;- let workbook: Workbook;- let worksheet: Worksheet;-- beforeEach(() => {- testBed = createControllerTestBed();- commandService = testBed.injector.get(ICommandService);- formulaDataModel = testBed.injector.get(FormulaDataModel);- interceptorService = testBed.injector.get(SheetInterceptorService);- workbook = testBed.sheet as Workbook;- worksheet = workbook.getActiveSheet()!;-- commandService.registerCommand(SetArrayFormulaDataMutation);-- testBed.injector.get(ArrayFormulaCellInterceptorController);- });afterEach(() => {- vi.restoreAllMocks();testBed?.univer.dispose();});it('should intercept array formula cells with default values, precision cleanup, raw passthrough and array values', () => {+ testBed = createControllerTestBed();+ const commandService = testBed.injector.get(ICommandService);+ const formulaDataModel = testBed.injector.get(FormulaDataModel);+ const interceptorService = testBed.injector.get(SheetInterceptorService);+ const workbook = testBed.sheet as Workbook;+ const worksheet = workbook.getActiveSheet()!;+ commandService.registerCommand(SetArrayFormulaDataMutation);+ testBed.injector.get(ArrayFormulaCellInterceptorController);+formulaDataModel.setArrayFormulaCellData({test: {sheet1: {@@ -155,3 +178,293 @@ describe('ArrayFormulaCellInterceptorController', () => {expect(getInterceptedCell(worksheet, workbook, 4, 4, interceptorService)).toBeUndefined();});});++const unitId = 'test';+const subUnitId = 'sheet1';++function createPairedMessageProtocols(): [IMessageProtocol, IMessageProtocol] {+ const mainToWorker$ = new ReplaySubject<unknown>(1);+ const workerToMain$ = new ReplaySubject<unknown>(1);++ return [+ {+ send(message: unknown) {+ mainToWorker$.next(message);+ },+ onMessage: workerToMain$.asObservable(),+ },+ {+ send(message: unknown) {+ workerToMain$.next(message);+ },+ onMessage: mainToWorker$.asObservable(),+ },+ ];+}++function waitForMicrotasks(count = 4): Promise<void> {+ let promise = Promise.resolve();+ for (let i = 0; i < count; i++) {+ promise = promise.then(() => undefined);+ }++ return promise;+}++function registerCommand(commandService: ICommandService, command: ICommand) {+ try {+ commandService.registerCommand(command);+ } catch (error) {+ if (!(error instanceof Error) || !error.message.includes('has been registered before')) {+ throw error;+ }+ }+}++async function waitForCondition(condition: () => boolean): Promise<void> {+ for (let i = 0; i < 20; i++) {+ if (condition()) {+ return;+ }++ await new Promise<void>((resolve) => setTimeout(resolve, 0));+ }++ throw new Error('Timed out waiting for condition.');+}++function createWorkerWorkbookData(): IWorkbookData {+ const sourceCellData: NonNullable<IWorkbookData['sheets'][string]['cellData']> = {};++ for (let row = 2; row <= 9; row++) {+ sourceCellData[row] = {};+ for (let column = 2; column <= 6; column++) {+ sourceCellData[row]![column] = {+ v: row + column,+ t: 2,+ };+ }+ }++ return {+ id: unitId,+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: '',+ sheetOrder: [subUnitId],+ styles: {},+ sheets: {+ [subUnitId]: {+ id: subUnitId,+ name: 'Sheet1',+ rowCount: 30,+ columnCount: 20,+ cellData: {+ ...sourceCellData,+ 12: {+ 6: {+ f: '=C3:G10',+ },+ },+ },+ },+ },+ };+}++function createWorkerFormulaTestBed() {+ const [mainProtocol, workerProtocol] = createPairedMessageProtocols();++ class MainRPCPlugin extends Plugin {+ static override pluginName = 'test-main-rpc-plugin';++ constructor(+ _config: undefined,+ @Inject(Injector) override readonly _injector: Injector+ ) {+ super();+ }++ override onStarting(): void {+ this._injector.add([IRPCChannelService, {+ useFactory: function createChannelService() {+ return new ChannelService(mainProtocol);+ },+ }]);+ this._injector.add([DataSyncPrimaryController]);+ this._injector.add([IRemoteSyncService, { useClass: RemoteSyncPrimaryService }]);+ this._injector.get(DataSyncPrimaryController);+ }+ }++ class WorkerRPCPlugin extends Plugin {+ static override pluginName = 'test-worker-rpc-plugin';++ constructor(+ _config: undefined,+ @Inject(Injector) override readonly _injector: Injector+ ) {+ super();+ }++ override onStarting(): void {+ this._injector.add([IRPCChannelService, {+ useFactory: function createChannelService() {+ return new ChannelService(workerProtocol);+ },+ }]);+ this._injector.add([IRemoteInstanceService, { useClass: WebWorkerRemoteInstanceService }]);+ this._injector.add([DataSyncReplicaController]);+ this._injector.get(DataSyncReplicaController);+ }+ }++ const workerUniver = new Univer({+ locale: LocaleType.EN_US,+ locales: {+ [LocaleType.EN_US]: formulaEnUS,+ },+ logLevel: LogLevel.SILENT,+ });+ workerUniver.__getInjector().get(LocaleService).setDirection('ltr');+ workerUniver.registerPlugins([+ [UniverSheetsPlugin, { onlyRegisterFormulaRelatedMutations: true }],+ [UniverFormulaEnginePlugin],+ [WorkerRPCPlugin],+ [UniverRemoteSheetsFormulaPlugin],+ ]);++ const mainUniver = new Univer({+ locale: LocaleType.EN_US,+ locales: {+ [LocaleType.EN_US]: formulaEnUS,+ },+ logLevel: LogLevel.SILENT,+ });+ mainUniver.__getInjector().get(LocaleService).setDirection('ltr');+ mainUniver.registerPlugins([+ [MainRPCPlugin],+ [UniverSheetsPlugin, { notExecuteFormula: true }],+ [UniverFormulaEnginePlugin, { notExecuteFormula: true }],+ [UniverSheetsFormulaPlugin, { notExecuteFormula: true }],+ ]);++ const mainInjector = mainUniver.__getInjector();+ const workerInjector = workerUniver.__getInjector();+ const mainCommandService = mainInjector.get(ICommandService);+ const workerCommandService = workerInjector.get(ICommandService);++ mainInjector.get(ILogService).setLogLevel(LogLevel.SILENT);+ workerInjector.get(ILogService).setLogLevel(LogLevel.SILENT);++ const sheet = mainUniver.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkerWorkbookData());++ return {+ commandService: mainCommandService,+ formulaDataModel: mainInjector.get(FormulaDataModel),+ mainUniver,+ sheet,+ workerCommandService,+ workerFormulaEngine: FUniver.newAPI(workerUniver).getFormula() as FFormula,+ workerInjector,+ workerInstanceService: workerInjector.get(IUniverInstanceService),+ workerUniver,+ };+}++describe('ArrayFormulaCellInterceptorController with remote calculation', () => {+ let testBed: ReturnType<typeof createWorkerFormulaTestBed>;+ let commandService: ICommandService;+ let formulaDataModel: FormulaDataModel;+ let worksheet: Worksheet;++ afterEach(() => {+ testBed.mainUniver.dispose();+ testBed.workerUniver.dispose();+ });++ async function calculateInWorker() {+ await waitForCondition(() => testBed.workerInstanceService.getUnit(unitId) != null);+ [+ SetArrayFormulaDataMutation,+ SetFormulaCalculationNotificationMutation,+ SetFormulaCalculationResultMutation,+ SetFormulaCalculationStartMutation,+ SetRangeValuesMutation,+ ].forEach((command) => {+ registerCommand(commandService, command);+ registerCommand(testBed.workerCommandService, command);+ });+ testBed.workerInjector.get(CalculateController);++ const calculationEnd = new Promise<void>((resolve) => {+ const disposable = testBed.workerFormulaEngine.calculationEnd(() => {+ disposable.dispose();+ resolve();+ });+ });++ // Also wait for the calculation result to be synced back to the main thread.+ const resultSyncedToMain = new Promise<void>((resolve) => {+ const disposable = commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id === SetFormulaCalculationResultMutation.id) {+ disposable.dispose();+ resolve();+ }+ });+ });++ testBed.workerCommandService.syncExecuteCommand(SetFormulaCalculationStartMutation.id, { forceCalculation: true }, { onlyLocal: true });+ await calculationEnd;+ await resultSyncedToMain;+ await waitForMicrotasks(2);+ }++ async function setCell(row: number, column: number, value: number) {+ await commandService.executeCommand(SetRangeValuesMutation.id, {+ unitId,+ subUnitId,+ cellValue: {+ [row]: {+ [column]: {+ v: value,+ t: 2,+ },+ },+ },+ });+ }++ it('should preserve multiple real blockers inside a spilled array reference formula', async () => {+ testBed = createWorkerFormulaTestBed();+ testBed.mainUniver.__getInjector().get(ArrayFormulaCellInterceptorController);+ commandService = testBed.commandService;+ formulaDataModel = testBed.formulaDataModel;+ worksheet = testBed.sheet.getSheetBySheetId(subUnitId) as Worksheet;++ await calculateInWorker();++ expect(formulaDataModel.getArrayFormulaRange()[unitId]?.[subUnitId]?.[12]?.[6]).toEqual({+ startRow: 12,+ startColumn: 6,+ endRow: 19,+ endColumn: 10,+ });++ await setCell(14, 9, 333);+ await calculateInWorker();++ expect(worksheet.getCellRaw(12, 6)?.v).toBe(ErrorType.SPILL);+ expect(worksheet.getCellRaw(14, 9)?.v).toBe(333);+ expect(formulaDataModel.getArrayFormulaCellData()[unitId]?.[subUnitId]?.[14]?.[9]).toBeUndefined();++ await setCell(15, 9, 444);+ await calculateInWorker();++ expect(worksheet.getCellRaw(12, 6)?.v).toBe(ErrorType.SPILL);+ expect(worksheet.getCellRaw(14, 9)?.v).toBe(333);+ expect(worksheet.getCellRaw(15, 9)?.v).toBe(444);+ expect(formulaDataModel.getArrayFormulaCellData()[unitId]?.[subUnitId]?.[14]?.[9]).toBeUndefined();+ expect(formulaDataModel.getArrayFormulaCellData()[unitId]?.[subUnitId]?.[15]?.[9]).toBeUndefined();+ });+});diff --git a/packages/sheets-formula/src/controllers/__tests__/array-formula-spill.worker.spec.ts b/packages/sheets-formula/src/controllers/__tests__/array-formula-spill.worker.spec.tsdeleted file mode 100644index f362cf5490..0000000000--- a/packages/sheets-formula/src/controllers/__tests__/array-formula-spill.worker.spec.ts+++ /dev/null@@ -1,345 +0,0 @@-/**- * 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 type { ICommand, IWorkbookData, Workbook, Worksheet } from '@univerjs/core';-import type { FFormula } from '@univerjs/engine-formula/facade';-import type { IMessageProtocol } from '@univerjs/rpc';-import {- ICommandService,- ILogService,- Inject,- Injector,- IUniverInstanceService,- LocaleType,- LogLevel,- Plugin,- Univer,- UniverInstanceType,-} from '@univerjs/core';-import { FUniver } from '@univerjs/core/facade';-import {- CalculateController,- ErrorType,- FormulaDataModel,- SetArrayFormulaDataMutation,- SetFormulaCalculationNotificationMutation,- SetFormulaCalculationResultMutation,- SetFormulaCalculationStartMutation,- UniverFormulaEnginePlugin,-} from '@univerjs/engine-formula';-import {- ChannelService,- DataSyncPrimaryController,- DataSyncReplicaController,- IRemoteInstanceService,- IRemoteSyncService,- IRPCChannelService,- RemoteSyncPrimaryService,- WebWorkerRemoteInstanceService,-} from '@univerjs/rpc';-import { SetRangeValuesMutation, UniverSheetsPlugin } from '@univerjs/sheets';-import { ReplaySubject } from 'rxjs';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';-import formulaEnUS from '../../locale/en-US';-import { UniverRemoteSheetsFormulaPlugin, UniverSheetsFormulaPlugin } from '../../plugin';-import '@univerjs/engine-formula/facade';--const unitId = 'test';-const subUnitId = 'sheet1';--function createPairedMessageProtocols(): [IMessageProtocol, IMessageProtocol] {- const mainToWorker$ = new ReplaySubject<unknown>(1);- const workerToMain$ = new ReplaySubject<unknown>(1);-- return [- {- send(message: unknown) {- mainToWorker$.next(message);- },- onMessage: workerToMain$.asObservable(),- },- {- send(message: unknown) {- workerToMain$.next(message);- },- onMessage: mainToWorker$.asObservable(),- },- ];-}--function waitForMicrotasks(count = 4): Promise<void> {- let promise = Promise.resolve();- for (let i = 0; i < count; i++) {- promise = promise.then(() => undefined);- }-- return promise;-}--function registerCommand(commandService: ICommandService, command: ICommand) {- try {- commandService.registerCommand(command);- } catch (error) {- if (!(error instanceof Error) || !error.message.includes('has been registered before')) {- throw error;- }- }-}--async function waitForCondition(condition: () => boolean): Promise<void> {- for (let i = 0; i < 20; i++) {- if (condition()) {- return;- }-- await new Promise<void>((resolve) => setTimeout(resolve, 0));- }-- throw new Error('Timed out waiting for condition.');-}--function createWorkbookData(): IWorkbookData {- const sourceCellData: NonNullable<IWorkbookData['sheets'][string]['cellData']> = {};-- for (let row = 2; row <= 9; row++) {- sourceCellData[row] = {};- for (let column = 2; column <= 6; column++) {- sourceCellData[row]![column] = {- v: row + column,- t: 2,- };- }- }-- return {- id: unitId,- appVersion: '3.0.0-alpha',- locale: LocaleType.EN_US,- name: '',- sheetOrder: [subUnitId],- styles: {},- sheets: {- [subUnitId]: {- id: subUnitId,- name: 'Sheet1',- rowCount: 30,- columnCount: 20,- cellData: {- ...sourceCellData,- 12: {- 6: {- f: '=C3:G10',- },- },- },- },- },- };-}--function createWorkerFormulaTestBed() {- const [mainProtocol, workerProtocol] = createPairedMessageProtocols();-- class MainRPCPlugin extends Plugin {- static override pluginName = 'test-main-rpc-plugin';-- constructor(- _config: undefined,- @Inject(Injector) override readonly _injector: Injector- ) {- super();- }-- override onStarting(): void {- this._injector.add([IRPCChannelService, {- // eslint-disable-next-line react/no-unnecessary-use-prefix- useFactory: () => new ChannelService(mainProtocol),- }]);- this._injector.add([DataSyncPrimaryController]);- this._injector.add([IRemoteSyncService, { useClass: RemoteSyncPrimaryService }]);- this._injector.get(DataSyncPrimaryController);- }- }-- class WorkerRPCPlugin extends Plugin {- static override pluginName = 'test-worker-rpc-plugin';-- constructor(- _config: undefined,- @Inject(Injector) override readonly _injector: Injector- ) {- super();- }-- override onStarting(): void {- this._injector.add([IRPCChannelService, {- // eslint-disable-next-line react/no-unnecessary-use-prefix- useFactory: () => new ChannelService(workerProtocol),- }]);- this._injector.add([IRemoteInstanceService, { useClass: WebWorkerRemoteInstanceService }]);- this._injector.add([DataSyncReplicaController]);- this._injector.get(DataSyncReplicaController);- }- }-- const workerUniver = new Univer({- locale: LocaleType.EN_US,- locales: {- [LocaleType.EN_US]: formulaEnUS,- },- logLevel: LogLevel.SILENT,- });- workerUniver.registerPlugins([- [UniverSheetsPlugin, { onlyRegisterFormulaRelatedMutations: true }],- [UniverFormulaEnginePlugin],- [WorkerRPCPlugin],- [UniverRemoteSheetsFormulaPlugin],- ]);-- const mainUniver = new Univer({- locale: LocaleType.EN_US,- locales: {- [LocaleType.EN_US]: formulaEnUS,- },- logLevel: LogLevel.SILENT,- });- mainUniver.registerPlugins([- [MainRPCPlugin],- [UniverSheetsPlugin, { notExecuteFormula: true }],- [UniverFormulaEnginePlugin, { notExecuteFormula: true }],- [UniverSheetsFormulaPlugin, { notExecuteFormula: true }],- ]);-- const mainInjector = mainUniver.__getInjector();- const workerInjector = workerUniver.__getInjector();- const mainCommandService = mainInjector.get(ICommandService);- const workerCommandService = workerInjector.get(ICommandService);-- mainInjector.get(ILogService).setLogLevel(LogLevel.SILENT);- workerInjector.get(ILogService).setLogLevel(LogLevel.SILENT);-- const sheet = mainUniver.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkbookData());-- return {- commandService: mainCommandService,- formulaDataModel: mainInjector.get(FormulaDataModel),- mainUniver,- sheet,- workerCommandService,- workerFormulaEngine: FUniver.newAPI(workerUniver).getFormula() as FFormula,- workerInjector,- workerInstanceService: workerInjector.get(IUniverInstanceService),- workerUniver,- };-}--describe('Array formula SPILL with worker formula calculation', () => {- let testBed: ReturnType<typeof createWorkerFormulaTestBed>;- let commandService: ICommandService;- let formulaDataModel: FormulaDataModel;- let worksheet: Worksheet;-- beforeEach(() => {- testBed = createWorkerFormulaTestBed();- commandService = testBed.commandService;- formulaDataModel = testBed.formulaDataModel;- worksheet = testBed.sheet.getSheetBySheetId(subUnitId) as Worksheet;- });-- afterEach(() => {- testBed.mainUniver.dispose();- testBed.workerUniver.dispose();- });-- async function calculateInWorker() {- await waitForCondition(() => testBed.workerInstanceService.getUnit(unitId) != null);- [- SetArrayFormulaDataMutation,- SetFormulaCalculationNotificationMutation,- SetFormulaCalculationResultMutation,- SetFormulaCalculationStartMutation,- SetRangeValuesMutation,- ].forEach((command) => {- registerCommand(commandService, command);- registerCommand(testBed.workerCommandService, command);- });- testBed.workerInjector.get(CalculateController);-- const calculationEnd = new Promise<void>((resolve) => {- const disposable = testBed.workerFormulaEngine.calculationEnd(() => {- disposable.dispose();- resolve();- });- });-- // Also wait for the calculation result to be synced back to the main thread.- const resultSyncedToMain = new Promise<void>((resolve) => {- const disposable = commandService.onCommandExecuted((commandInfo) => {- if (commandInfo.id === SetFormulaCalculationResultMutation.id) {- disposable.dispose();- resolve();- }- });- });-- testBed.workerCommandService.syncExecuteCommand(SetFormulaCalculationStartMutation.id, { forceCalculation: true }, { onlyLocal: true });- await calculationEnd;- await resultSyncedToMain;- await waitForMicrotasks(2);- }-- async function setCell(row: number, column: number, value: number) {- await commandService.executeCommand(SetRangeValuesMutation.id, {- unitId,- subUnitId,- cellValue: {- [row]: {- [column]: {- v: value,- t: 2,- },- },- },- });- }-- it('should preserve multiple real blockers inside a spilled array reference formula', async () => {- await calculateInWorker();-- expect(formulaDataModel.getArrayFormulaRange()[unitId]?.[subUnitId]?.[12]?.[6]).toEqual({- startRow: 12,- startColumn: 6,- endRow: 19,- endColumn: 10,- });-- await setCell(14, 9, 333);- await calculateInWorker();-- expect(worksheet.getCellRaw(12, 6)?.v).toBe(ErrorType.SPILL);- expect(worksheet.getCellRaw(14, 9)?.v).toBe(333);- expect(formulaDataModel.getArrayFormulaCellData()[unitId]?.[subUnitId]?.[14]?.[9]).toBeUndefined();-- await setCell(15, 9, 444);- await calculateInWorker();-- expect(worksheet.getCellRaw(12, 6)?.v).toBe(ErrorType.SPILL);- expect(worksheet.getCellRaw(14, 9)?.v).toBe(333);- expect(worksheet.getCellRaw(15, 9)?.v).toBe(444);- expect(formulaDataModel.getArrayFormulaCellData()[unitId]?.[subUnitId]?.[14]?.[9]).toBeUndefined();- expect(formulaDataModel.getArrayFormulaCellData()[unitId]?.[subUnitId]?.[15]?.[9]).toBeUndefined();- });-});diff --git a/packages/sheets-formula/src/index.ts b/packages/sheets-formula/src/index.tsindex 3ee102d497..d5f3d398fe 100644--- a/packages/sheets-formula/src/index.ts+++ b/packages/sheets-formula/src/index.ts@@ -25,10 +25,14 @@ export { TriggerCalculationController } from './controllers/trigger-calculation.export { collectUnitQualifierFormulaPatches, UnitQualifierRenameController } from './controllers/unit-qualifier-rename.controller';export { UpdateDefinedNameController } from './controllers/update-defined-name.controller';export { UpdateFormulaController } from './controllers/update-formula.controller';-export { UniverRemoteSheetsFormulaPlugin, UniverSheetsFormulaPlugin } from './plugin';+export { UniverSheetsFormulaPlugin } from './plugin';export { FormulaRefRangeService } from './services/formula-ref-range.service';export {IRemoteRegisterFunctionService,RemoteRegisterFunctionService,} from './services/remote/remote-register-function.service';export { calculateFormula } from './util/calculate';+export {+ /** @deprecated Import from '@univerjs/sheets-formula/worker' instead. This root export will be removed in the next release. */+ UniverRemoteSheetsFormulaPlugin,+} from './worker';diff --git a/packages/sheets-formula/src/plugin.ts b/packages/sheets-formula/src/plugin.tsindex 0d76ffdb0a..c138c9b7af 100644--- a/packages/sheets-formula/src/plugin.ts+++ b/packages/sheets-formula/src/plugin.ts@@ -15,7 +15,6 @@*/import type { Dependency } from '@univerjs/core';-import type { IUniverSheetsFormulaBaseConfig, IUniverSheetsFormulaRemoteConfig } from './config/config';import {DependentOn,IConfigService,@@ -28,15 +27,14 @@ import {UniverInstanceType,} from '@univerjs/core';import { IDescriptionService, UniverFormulaEnginePlugin } from '@univerjs/engine-formula';-import { fromModule, IRPCChannelService, toModule } from '@univerjs/rpc';+import { IRPCChannelService, toModule } from '@univerjs/rpc';import { UniverSheetsPlugin } from '@univerjs/sheets';+import type { IUniverSheetsFormulaBaseConfig } from './config/config';import pkg from '../package.json';import { SHEETS_FORMULA_PLUGIN_NAME } from './common/plugin-name';import {defaultPluginBaseConfig,- defaultPluginRemoteConfig,PLUGIN_CONFIG_KEY_BASE,- PLUGIN_CONFIG_KEY_REMOTE,} from './config/config';import { ActiveDirtyController } from './controllers/active-dirty.controller';import { ArrayFormulaCellInterceptorController } from './controllers/array-formula-cell-interceptor.controller';@@ -56,42 +54,9 @@ import { UpdateFormulaController } from './controllers/update-formula.controllerimport { FormulaRefRangeService } from './services/formula-ref-range.service';import {IRemoteRegisterFunctionService,- RemoteRegisterFunctionService,RemoteRegisterFunctionServiceName,} from './services/remote/remote-register-function.service';-@DependentOn(UniverFormulaEnginePlugin)-export class UniverRemoteSheetsFormulaPlugin extends Plugin {- static override pluginName = 'SHEET_FORMULA_REMOTE_PLUGIN';- static override packageName = pkg.name;- static override version = pkg.version;- static override type = UniverInstanceType.UNIVER_SHEET;-- constructor(- private readonly _config: Partial<IUniverSheetsFormulaRemoteConfig> = defaultPluginRemoteConfig,- @Inject(Injector) override readonly _injector: Injector,- @IConfigService private readonly _configService: IConfigService- ) {- super();-- // Manage the plugin configuration.- const { ...rest } = merge(- {},- defaultPluginRemoteConfig,- this._config- );- this._configService.setConfig(PLUGIN_CONFIG_KEY_REMOTE, rest);- }-- override onStarting(): void {- this._injector.add([RemoteRegisterFunctionService]);- this._injector.get(IRPCChannelService).registerChannel(- RemoteRegisterFunctionServiceName,- fromModule(this._injector.get(RemoteRegisterFunctionService))- );- }-}-@DependentOn(UniverFormulaEnginePlugin, UniverSheetsPlugin)export class UniverSheetsFormulaPlugin extends Plugin {static override pluginName = SHEETS_FORMULA_PLUGIN_NAME;@@ -139,7 +104,9 @@ export class UniverSheetsFormulaPlugin extends Plugin {if (this._config.notExecuteFormula) {const rpcChannelService = j.get(IRPCChannelService);dependencies.push([IRemoteRegisterFunctionService, {- useFactory: () => toModule<IRemoteRegisterFunctionService>(rpcChannelService.requestChannel(RemoteRegisterFunctionServiceName)),+ useFactory: function createChannelService() {+ return toModule<IRemoteRegisterFunctionService>(rpcChannelService.requestChannel(RemoteRegisterFunctionServiceName));+ },}]);}diff --git a/packages/sheets-formula/src/worker.ts b/packages/sheets-formula/src/worker.tsnew file mode 100644index 0000000000..40ae9c7ccf--- /dev/null+++ b/packages/sheets-formula/src/worker.ts@@ -0,0 +1,58 @@+/**+ * 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 { DependentOn, IConfigService, Inject, Injector, merge, Plugin, UniverInstanceType } from '@univerjs/core';+import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula/worker';+import { fromModule, IRPCChannelService } from '@univerjs/rpc';+import type { IUniverSheetsFormulaRemoteConfig } from './config/config';+import pkg from '../package.json';+import { defaultPluginRemoteConfig, PLUGIN_CONFIG_KEY_REMOTE } from './config/config';+import {+ RemoteRegisterFunctionService,+ RemoteRegisterFunctionServiceName,+} from './services/remote/remote-register-function.service';++@DependentOn(UniverFormulaEnginePlugin)+export class UniverRemoteSheetsFormulaPlugin extends Plugin {+ static override pluginName = 'SHEET_FORMULA_REMOTE_PLUGIN';+ static override packageName = pkg.name;+ static override version = pkg.version;+ static override type = UniverInstanceType.UNIVER_SHEET;++ constructor(+ private readonly _config: Partial<IUniverSheetsFormulaRemoteConfig> = defaultPluginRemoteConfig,+ @Inject(Injector) override readonly _injector: Injector,+ @IConfigService private readonly _configService: IConfigService+ ) {+ super();++ // Manage the plugin configuration.+ const { ...rest } = merge(+ {},+ defaultPluginRemoteConfig,+ this._config+ );+ this._configService.setConfig(PLUGIN_CONFIG_KEY_REMOTE, rest);+ }++ override onStarting(): void {+ this._injector.add([RemoteRegisterFunctionService]);+ this._injector.get(IRPCChannelService).registerChannel(+ RemoteRegisterFunctionServiceName,+ fromModule(this._injector.get(RemoteRegisterFunctionService))+ );+ }+}diff --git a/packages/sheets-table/package.json b/packages/sheets-table/package.jsonindex a9f327322e..3387c661e7 100644--- a/packages/sheets-table/package.json+++ b/packages/sheets-table/package.json@@ -28,7 +28,8 @@".": "./src/index.ts","./*": "./src/*","./facade": "./src/facade/index.ts",- "./locale/*": "./src/locale/*.ts"+ "./locale/*": "./src/locale/*.ts",+ "./worker": "./src/worker.ts"},"main": "./src/index.ts","types": "./lib/types/index.d.ts",@@ -47,6 +48,11 @@"require": "./lib/cjs/*","types": "./lib/types/index.d.ts"},+ "./worker": {+ "import": "./lib/es/worker.js",+ "require": "./lib/cjs/worker.js",+ "types": "./lib/types/worker.d.ts"+ },"./locale/*": {"import": "./lib/es/locale/*.js","require": "./lib/cjs/locale/*.js",diff --git a/packages/sheets-table/src/worker.ts b/packages/sheets-table/src/worker.tsnew file mode 100644index 0000000000..6cc4a2cfc3--- /dev/null+++ b/packages/sheets-table/src/worker.ts@@ -0,0 +1,17 @@+/**+ * 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.+ */++export { UniverSheetsTablePlugin } from './plugin';diff --git a/packages/sheets/package.json b/packages/sheets/package.jsonindex d8b4277706..f567764489 100644--- a/packages/sheets/package.json+++ b/packages/sheets/package.json@@ -28,7 +28,8 @@".": "./src/index.ts","./*": "./src/*","./locale/*": "./src/locale/*.ts",- "./facade": "./src/facade/index.ts"+ "./facade": "./src/facade/index.ts",+ "./worker": "./src/worker.ts"},"main": "./src/index.ts","types": "./lib/types/index.d.ts",@@ -47,6 +48,11 @@"require": "./lib/cjs/*","types": "./lib/types/index.d.ts"},+ "./worker": {+ "import": "./lib/es/worker.js",+ "require": "./lib/cjs/worker.js",+ "types": "./lib/types/worker.d.ts"+ },"./locale/*": {"import": "./lib/es/locale/*.js","require": "./lib/cjs/locale/*.js",diff --git a/packages/sheets/src/worker.ts b/packages/sheets/src/worker.tsnew file mode 100644index 0000000000..29ebbed5aa--- /dev/null+++ b/packages/sheets/src/worker.ts@@ -0,0 +1,17 @@+/**+ * 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.+ */++export { UniverSheetsPlugin } from './plugin';diff --git a/presets/packages/preset-sheets-core/src/worker.ts b/presets/packages/preset-sheets-core/src/worker.tsindex 8a0f02b1e1..b08c3526a2 100644--- a/presets/packages/preset-sheets-core/src/worker.ts+++ b/presets/packages/preset-sheets-core/src/worker.ts@@ -15,11 +15,11 @@*/import type { IPreset } from '@univerjs/presets';+import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula/worker';+import { UniverRPCWorkerThreadPlugin } from '@univerjs/rpc/worker';+import { UniverRemoteSheetsFormulaPlugin } from '@univerjs/sheets-formula/worker';+import { UniverSheetsPlugin } from '@univerjs/sheets/worker';import type { IUniverFormulaWorkerConfig } from './types';-import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';-import { UniverRPCWorkerThreadPlugin } from '@univerjs/rpc';-import { UniverSheetsPlugin } from '@univerjs/sheets';-import { UniverRemoteSheetsFormulaPlugin } from '@univerjs/sheets-formula';export interface IUniverSheetsCoreWorkerPresetConfig {/**diff --git a/presets/packages/preset-sheets-filter/src/worker.ts b/presets/packages/preset-sheets-filter/src/worker.tsindex 5801867976..6a6b4d03d0 100644--- a/presets/packages/preset-sheets-filter/src/worker.ts+++ b/presets/packages/preset-sheets-filter/src/worker.ts@@ -15,7 +15,7 @@*/import type { IPreset } from '@univerjs/presets';-import { UniverSheetsFilterPlugin } from '@univerjs/sheets-filter';+import { UniverSheetsFilterPlugin } from '@univerjs/sheets-filter/worker';export function UniverSheetsFilterWorkerPreset(): IPreset {return {