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.

refactor: use redi instead of bundling it into core (#36)

Wenzhao Hue3b020044411
diff --git a/packages/base-sheets/package.json b/packages/base-sheets/package.json
index 966a1e24a8..d90f25e51e 100644
--- a/packages/base-sheets/package.json
+++ b/packages/base-sheets/package.json
@@ -65,6 +65,7 @@
},
"dependencies": {
"@univerjs/base-render": "workspace:^0.0.1",
- "@univerjs/core": "workspace:^0.0.1"
+ "@univerjs/core": "workspace:^0.0.1",
+ "@wendellhu/redi": "^0.8.0"
}
-}
+}
\ No newline at end of file
diff --git a/packages/base-sheets/src/Controller/AntLineController.ts b/packages/base-sheets/src/Controller/AntLineController.ts
index 082f07aa06..4f1a75c445 100644
--- a/packages/base-sheets/src/Controller/AntLineController.ts
+++ b/packages/base-sheets/src/Controller/AntLineController.ts
@@ -1,4 +1,5 @@
-import { Inject, SheetContext, Workbook } from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
+import { SheetContext, Workbook } from '@univerjs/core';
import { Rect, Scene } from '@univerjs/base-render';
import { AntLine, AntLineModel, IAntLineRange } from '../Model/AntLineModel';
@@ -192,4 +193,4 @@ export class AntLineControl {
}
}
}
-}
+}
\ No newline at end of file
diff --git a/packages/base-sheets/src/Controller/HideColumnController.ts b/packages/base-sheets/src/Controller/HideColumnController.ts
index 627d9c08a4..1409314d82 100644
--- a/packages/base-sheets/src/Controller/HideColumnController.ts
+++ b/packages/base-sheets/src/Controller/HideColumnController.ts
@@ -1,4 +1,5 @@
-import { BooleanNumber, ObjectArray, Inject } from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
+import { BooleanNumber, ObjectArray } from '@univerjs/core';
import { IColumnRulerData } from '../Basics/Interfaces/IRulerManager';
import { ColumnRulerManager } from '../Basics/Register/ColumnRegister';
@@ -43,4 +44,4 @@ export class HideColumnController {
this._columnRulerManager.setHidden(sheetId, columnIndex, numColumns);
}
-}
+}
\ No newline at end of file
diff --git a/packages/base-sheets/src/Controller/RightMenuController.ts b/packages/base-sheets/src/Controller/RightMenuController.ts
index da2e9267fe..5ef0155e28 100644
--- a/packages/base-sheets/src/Controller/RightMenuController.ts
+++ b/packages/base-sheets/src/Controller/RightMenuController.ts
@@ -1,4 +1,5 @@
-import { Context, SheetContext, UIObserver, Inject } from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
+import { Context, SheetContext, UIObserver } from '@univerjs/core';
import { SelectionController } from './Selection/SelectionController';
import { SelectionModel } from '../Model/SelectionModel';
import { IGlobalContext, ISelectionManager, ISheetContext } from '../Services/tokens';
@@ -146,4 +147,4 @@ export class RightMenuController {
});
return selections;
}
-}
+}
\ No newline at end of file
diff --git a/packages/base-sheets/src/Controller/Selection/ColumnTitleController.ts b/packages/base-sheets/src/Controller/Selection/ColumnTitleController.ts
index c358248bf0..8fc1db76bc 100644
--- a/packages/base-sheets/src/Controller/Selection/ColumnTitleController.ts
+++ b/packages/base-sheets/src/Controller/Selection/ColumnTitleController.ts
@@ -1,4 +1,5 @@
-import { Inject, Nullable, SheetContext } from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
+import { Nullable, SheetContext } from '@univerjs/core';
import { CURSOR_TYPE, Group, IMouseEvent, IPointerEvent, Rect } from '@univerjs/base-render';
import { DragLineController, DragLineDirection } from './DragLineController';
import { CanvasView } from '../../View';
@@ -193,4 +194,4 @@ export class ColumnTitleController {
this.pointerDown(evt);
});
}
-}
+}
\ No newline at end of file
diff --git a/packages/base-sheets/src/Controller/Selection/DragLineController.ts b/packages/base-sheets/src/Controller/Selection/DragLineController.ts
index 123a752e2c..fbb0745a4b 100644
--- a/packages/base-sheets/src/Controller/Selection/DragLineController.ts
+++ b/packages/base-sheets/src/Controller/Selection/DragLineController.ts
@@ -1,5 +1,6 @@
import { CURSOR_TYPE, Group, IMouseEvent, IPointerEvent, Rect } from '@univerjs/base-render';
-import { Nullable, Observer, Inject } from '@univerjs/core';
+import { Nullable, Observer } from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
import { CanvasView } from '../../View';
enum DRAG_LINE_KEY {
@@ -175,4 +176,4 @@ export class DragLineController {
this._dragUp(distance, e);
this._dragLine.dispose();
}
-}
+}
\ No newline at end of file
diff --git a/packages/base-sheets/src/Controller/Selection/RowTitleController.ts b/packages/base-sheets/src/Controller/Selection/RowTitleController.ts
index d77676f5aa..6d3f46458b 100644
--- a/packages/base-sheets/src/Controller/Selection/RowTitleController.ts
+++ b/packages/base-sheets/src/Controller/Selection/RowTitleController.ts
@@ -1,5 +1,6 @@
import { CURSOR_TYPE, Group, IMouseEvent, IPointerEvent, Rect } from '@univerjs/base-render';
-import { Nullable, SheetContext, Inject } from '@univerjs/core';
+import { Nullable, SheetContext } from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
import { DragLineController, DragLineDirection } from './DragLineController';
import { CanvasView } from '../../View';
import { ISheetContext } from '../../Services/tokens';
@@ -193,4 +194,4 @@ export class RowTitleController {
this.pointerDown(evt);
});
}
-}
+}
\ No newline at end of file
diff --git a/packages/base-sheets/src/Controller/Selection/SelectionControlDragDrop.ts b/packages/base-sheets/src/Controller/Selection/SelectionControlDragDrop.ts
index ed2f2c29d6..e79072591e 100644
--- a/packages/base-sheets/src/Controller/Selection/SelectionControlDragDrop.ts
+++ b/packages/base-sheets/src/Controller/Selection/SelectionControlDragDrop.ts
@@ -1,5 +1,6 @@
import { CURSOR_TYPE, Group, IMouseEvent, IPointerEvent, Rect, ScrollTimer } from '@univerjs/base-render';
-import { Direction, ICellInfo, ISelection, makeCellToSelection, Nullable, Observer, Inject, Injector } from '@univerjs/core';
+import { Inject, Injector } from '@wendellhu/redi';
+import { Direction, ICellInfo, ISelection, makeCellToSelection, Nullable, Observer } from '@univerjs/core';
import { SelectionModel } from '../../Model';
import { DEFAULT_SELECTION_CONFIG, SELECTION_TYPE } from './SelectionController';
import { CanvasView } from '../../View';
@@ -371,4 +372,4 @@ export class SelectionControlDragAndDrop {
const scene = this._canvasView.getSheetView().getScene();
scene.addObject(this._selectionDragShape);
}
-}
+}
\ No newline at end of file
diff --git a/packages/base-sheets/src/Controller/Selection/SelectionController.ts b/packages/base-sheets/src/Controller/Selection/SelectionController.ts
index 81d1853715..7b3134b838 100644
--- a/packages/base-sheets/src/Controller/Selection/SelectionController.ts
+++ b/packages/base-sheets/src/Controller/Selection/SelectionController.ts
@@ -1,5 +1,6 @@
import { Rect, Group } from '@univerjs/base-render';
-import { Nullable, ISelection, ICellInfo, Inject, Injector } from '@univerjs/core';
+import { Inject, Injector } from '@wendellhu/redi';
+import { Nullable, ISelection, ICellInfo } from '@univerjs/core';
import { SelectionModel } from '../../Model/SelectionModel';
import { SelectionControlDragAndDrop } from './SelectionControlDragDrop';
import { SelectionControlFill } from './SelectionControlFill';
@@ -453,4 +454,4 @@ export class SelectionController {
this._selectionControlFill.remove();
}
}
-}
+}
\ No newline at end of file
diff --git a/packages/base-sheets/src/Controller/Selection/SelectionManager.ts b/packages/base-sheets/src/Controller/Selection/SelectionManager.ts
index 9651eec7e5..4805290a7e 100644
--- a/packages/base-sheets/src/Controller/Selection/SelectionManager.ts
+++ b/packages/base-sheets/src/Controller/Selection/SelectionManager.ts
@@ -18,9 +18,9 @@ import {
DEFAULT_CELL,
IGridRange,
SheetContext,
- Inject,
- Injector,
} from '@univerjs/core';
+import { Inject, Injector } from '@wendellhu/redi';
+
import { ACTION_NAMES, ISelectionsConfig } from '../../Basics';
import { ISelectionModelValue, ISetSelectionValueActionData, SetSelectionValueAction } from '../../Model/Action/SetSelectionValueAction';
import { SelectionModel } from '../../Model/SelectionModel';
@@ -1068,4 +1068,4 @@ export class SelectionManager {
this.renderCurrentControls();
});
}
-}
+}
\ No newline at end of file
diff --git a/packages/base-sheets/src/Controller/SheetContainerController.ts b/packages/base-sheets/src/Controller/SheetContainerController.ts
index 4f24a59588..c930a4084d 100644
--- a/packages/base-sheets/src/Controller/SheetContainerController.ts
+++ b/packages/base-sheets/src/Controller/SheetContainerController.ts
@@ -1,7 +1,10 @@
-import { CommandManager, ISheetActionData, SheetActionBase, SheetContext, Inject } from '@univerjs/core';
+import { CommandManager, ISheetActionData, SheetActionBase, SheetContext } from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
+
import { ISelectionManager, ISheetContext } from '../Services/tokens';
import { SelectionManager } from './Selection';
import { CanvasView } from '../View';
+import { warn } from 'console';
// All skins' less file
export class SheetContainerController {
@@ -49,4 +52,4 @@ export class SheetContainerController {
}
});
}
-}
+}
\ No newline at end of file
diff --git a/packages/base-sheets/src/Controller/ToolbarController.ts b/packages/base-sheets/src/Controller/ToolbarController.ts
index f8ffae975a..226e399771 100644
--- a/packages/base-sheets/src/Controller/ToolbarController.ts
+++ b/packages/base-sheets/src/Controller/ToolbarController.ts
@@ -1,4 +1,5 @@
-import { Inject, HorizontalAlign, VerticalAlign, WrapStrategy, BorderType, UIObserver, Context, SheetContext } from '@univerjs/core';
+import { BorderType, Context, HorizontalAlign, SheetContext, UIObserver, VerticalAlign, WrapStrategy } from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
import { SelectionController } from './Selection/SelectionController';
@@ -244,4 +245,4 @@ export class ToolbarController {
});
}
}
-}
+}
\ No newline at end of file
diff --git a/packages/base-sheets/src/Services/tokens.ts b/packages/base-sheets/src/Services/tokens.ts
index 3935129ade..cce6083d4e 100644
--- a/packages/base-sheets/src/Services/tokens.ts
+++ b/packages/base-sheets/src/Services/tokens.ts
@@ -1,4 +1,5 @@
-import { createIdentifier, Context, SheetContext } from '@univerjs/core';
+import { createIdentifier } from '@wendellhu/redi';
+import { Context, SheetContext } from '@univerjs/core';
import { Engine } from '@univerjs/base-render';
@@ -18,4 +19,4 @@ export const ISheetPlugin = createIdentifier<SheetPlugin>('deprecated.univer.she
/** @deprecated temporary solution, we should inject SelectionManager directly */
export const ISelectionManager = createIdentifier<SelectionManager>('deprecated.univer.sheet.selection-manager');
-export const ICanvasView = createIdentifier<CanvasView>('univer.sheet.canvas-view');
+export const ICanvasView = createIdentifier<CanvasView>('univer.sheet.canvas-view');
\ No newline at end of file
diff --git a/packages/base-sheets/src/SheetPlugin.ts b/packages/base-sheets/src/SheetPlugin.ts
index c847ba02b4..a8ff488d67 100644
--- a/packages/base-sheets/src/SheetPlugin.ts
+++ b/packages/base-sheets/src/SheetPlugin.ts
@@ -1,5 +1,6 @@
import { Engine, RenderEngine } from '@univerjs/base-render';
-import { SheetContext, Plugin, PLUGIN_NAMES, DEFAULT_SELECTION, UniverSheet, UIObserver, Injector } from '@univerjs/core';
+import { SheetContext, Plugin, PLUGIN_NAMES, DEFAULT_SELECTION, UniverSheet, UIObserver } from '@univerjs/core';
+import { Injector } from '@wendellhu/redi';
import { SheetPluginObserve, uninstall } from './Basics/Observer';
import { CANVAS_VIEW_KEY } from './View/BaseView';
@@ -308,4 +309,4 @@ export class SheetPlugin extends Plugin<SheetPluginObserve, SheetContext> {
// #endregion Controllers
]);
}
-}
+}
\ No newline at end of file
diff --git a/packages/base-sheets/src/View/CanvasView.ts b/packages/base-sheets/src/View/CanvasView.ts
index 650aaa3042..e1a9db6550 100644
--- a/packages/base-sheets/src/View/CanvasView.ts
+++ b/packages/base-sheets/src/View/CanvasView.ts
@@ -1,4 +1,5 @@
-import { Inject, Injector, EventState, SheetContext, Worksheet } from '@univerjs/core';
+import { Inject, Injector } from '@wendellhu/redi';
+import { EventState, SheetContext, Worksheet } from '@univerjs/core';
import { Engine, EVENT_TYPE, IScrollObserverParam, IWheelEvent, Layer, Scene, ScrollBar, Viewport } from '@univerjs/base-render';
import { BaseView, CANVAS_VIEW_KEY, CanvasViewRegistry } from './BaseView';
@@ -156,4 +157,4 @@ export class CanvasView {
this._views.push(viewFactory.create(scene, this._injector));
});
}
-}
+}
\ No newline at end of file
diff --git a/packages/core/package.json b/packages/core/package.json
index 2db1c5f7bd..425bec98ac 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -56,6 +56,7 @@
"url": "https://github.com/dream-num/univer.git"
},
"dependencies": {
+ "@wendellhu/redi": "^0.8.0",
"dayjs": "^1.11.5",
"es6-proxy-polyfill": "^2.1.1",
"nanoid": "4.0.0",
@@ -75,4 +76,4 @@
"vite": "^3.0.9",
"vite-plugin-external": "1.2.3"
}
-}
+}
\ No newline at end of file
diff --git a/packages/core/src/DI/Accessor.ts b/packages/core/src/DI/Accessor.ts
deleted file mode 100644
index 3ab53a3634..0000000000
--- a/packages/core/src/DI/Accessor.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import { Injector } from './Injector';
-
-export interface Accessor {
- get: Injector['get'];
-}
diff --git a/packages/core/src/DI/Decorators.ts b/packages/core/src/DI/Decorators.ts
deleted file mode 100644
index 657bcccd63..0000000000
--- a/packages/core/src/DI/Decorators.ts
+++ /dev/null
@@ -1,438 +0,0 @@
-import {
- DependencyIdentifier,
- IdentifierDecorator,
- IdentifierDecoratorSymbol,
- prettyPrintIdentifier,
-} from './DependencyIdentifier';
-import { Ctor, LookUp, Quantity } from './Types';
-import { DIError } from './Error';
-
-export interface DependencyItemHooks<T> {
- onInstantiation?: (instance: T) => void;
-}
-
-export interface ClassDependencyItem<T> extends DependencyItemHooks<T> {
- useClass: Ctor<T>;
- lazy?: boolean;
-}
-export function isClassDependencyItem<T>(
- thing: unknown
-): thing is ClassDependencyItem<T> {
- if (thing && typeof (thing as any).useClass !== 'undefined') {
- return true;
- }
-
- return false;
-}
-
-export type FactoryDepModifier =
- | typeof Self
- | typeof SkipSelf
- | typeof Optional
- | typeof Many
- | typeof WithNew;
-export type FactoryDep<T> =
- | [...FactoryDepModifier[], DependencyIdentifier<T>]
- | DependencyIdentifier<T>;
-export interface FactoryDependencyItem<T> extends DependencyItemHooks<T> {
- useFactory: (...deps: any[]) => T;
- dynamic?: true;
- deps?: Array<FactoryDep<any>>;
-}
-export function isFactoryDependencyItem<T>(
- thing: unknown
-): thing is FactoryDependencyItem<T> {
- if (thing && typeof (thing as any).useFactory !== 'undefined') {
- return true;
- }
-
- return false;
-}
-
-export interface ValueDependencyItem<T> extends DependencyItemHooks<T> {
- useValue: T;
-}
-export function isValueDependencyItem<T>(
- thing: unknown
-): thing is ValueDependencyItem<T> {
- if (thing && typeof (thing as any).useValue !== 'undefined') {
- return true;
- }
-
- return false;
-}
-
-export interface AsyncDependencyItem<T> extends DependencyItemHooks<T> {
- useAsync: () => Promise<
- T | Ctor<T> | [DependencyIdentifier<T>, SyncDependencyItem<T>]
- >;
-}
-export function isAsyncDependencyItem<T>(
- thing: unknown
-): thing is AsyncDependencyItem<T> {
- if (thing && typeof (thing as any).useAsync !== 'undefined') {
- return true;
- }
-
- return false;
-}
-export interface AsyncHook<T> {
- whenReady(): Promise<T>;
-}
-export function isAsyncHook<T>(thing: unknown): thing is AsyncHook<T> {
- if (thing && typeof (thing as any).whenReady !== 'undefined') {
- return true;
- }
-
- return false;
-}
-
-export type SyncDependencyItem<T> =
- | ClassDependencyItem<T>
- | FactoryDependencyItem<T>
- | ValueDependencyItem<T>;
-export type DependencyItem<T> = SyncDependencyItem<T> | AsyncDependencyItem<T>;
-
-export interface DependencyDescriptor<T> {
- paramIndex: number;
- identifier: DependencyIdentifier<T>;
- quantity: Quantity;
- lookUp?: LookUp;
- withNew: boolean;
-}
-
-/**
- * describes dependencies of a IDependencyItem
- */
-export interface Dependencies {
- dependencies: Array<DependencyDescriptor<any>>;
-}
-
-export function normalizeFactoryDeps(
- deps?: Array<FactoryDep<any>>
-): Array<DependencyDescriptor<any>> {
- if (!deps) {
- return [];
- }
-
- return deps.map((dep, index) => {
- if (!Array.isArray(dep)) {
- return {
- paramIndex: index,
- identifier: dep,
- quantity: Quantity.REQUIRED,
- withNew: false,
- };
- }
-
- const modifiers = dep.slice(0, dep.length - 1) as FactoryDepModifier[];
- const identifier = dep[dep.length - 1] as DependencyIdentifier<any>;
-
- let lookUp: LookUp | undefined;
- let quantity = Quantity.REQUIRED;
- let withNew = false;
-
- (modifiers as FactoryDepModifier[]).forEach(
- (modifier: FactoryDepModifier) => {
- if (modifier instanceof Self) {
- lookUp = LookUp.SELF;
- } else if (modifier instanceof SkipSelf) {
- lookUp = LookUp.SKIP_SELF;
- } else if (modifier instanceof Optional) {
- quantity = Quantity.OPTIONAL;
- } else if (modifier instanceof Many) {
- quantity = Quantity.MANY;
- } else if (modifier instanceof WithNew) {
- withNew = true;
- } else {
- throw new DIError(`unknown dep modifier ${modifier}.`);
- }
- }
- );
-
- return {
- paramIndex: index,
- identifier: identifier as DependencyIdentifier<any>,
- quantity,
- lookUp,
- withNew,
- };
- });
-}
-
-function changeLookup(target: Ctor<any>, index: number, lookUp: LookUp) {
- const descriptor = getDependencyByIndex(target, index);
- descriptor.lookUp = lookUp;
-}
-
-function lookupDecoratorFactoryProducer(lookUp: LookUp) {
- return function DecoratorFactory<T>(this: any) {
- if (this instanceof DecoratorFactory) {
- return this;
- }
-
- return function d(target: Ctor<T>, _key: string, index: number) {
- changeLookup(target, index, lookUp);
- };
- } as any;
-}
-
-interface SkipSelfDecorator {
- (): any;
- // eslint-disable-next-line @typescript-eslint/no-misused-new
- new (): SkipSelfDecorator;
-}
-/**
- * when resolving this dependency, skip the current injector
- */
-export const SkipSelf: SkipSelfDecorator = lookupDecoratorFactoryProducer(
- LookUp.SKIP_SELF
-);
-
-interface SelfDecorator {
- (): any;
- // eslint-disable-next-line @typescript-eslint/no-misused-new
- new (): SelfDecorator;
-}
-/**
- * when resolving this dependency, only search the current injector
- */
-export const Self: SelfDecorator = lookupDecoratorFactoryProducer(LookUp.SELF);
-
-class QuantityCheckError extends DIError {
- constructor(id: DependencyIdentifier<any>, quantity: Quantity, actual: number) {
- const msg = `Expect "${quantity}" dependency items for id "${prettyPrintIdentifier(
- id
- )}" but get ${actual}.`;
-
- super(msg);
- }
-}
-
-export function checkQuantity(
- id: DependencyIdentifier<any>,
- quantity: Quantity,
- length: number
-): void {
- if (
- (quantity === Quantity.OPTIONAL && length > 1) ||
- (quantity === Quantity.REQUIRED && length !== 1)
- ) {
- throw new QuantityCheckError(id, quantity, length);
- }
-}
-
-export function retrieveQuantity<T>(quantity: Quantity, arr: T[]): T[] | T {
- if (quantity === Quantity.MANY) {
- return arr;
- }
- return arr[0];
-}
-
-function changeQuantity(target: Ctor<any>, index: number, quantity: Quantity) {
- const descriptor = getDependencyByIndex(target, index);
- descriptor.quantity = quantity;
-}
-
-function quantifyDecoratorFactoryProducer(quantity: Quantity) {
- return function decoratorFactory<T>(
- // typescript would remove `this` after transpilation
- // this line just declare the type of `this`
- this: any,
- id?: DependencyIdentifier<T>
- ) {
- if (this instanceof decoratorFactory) {
- return this;
- }
-
- return function d(registerTarget: Ctor<T>, _key: string, index: number) {
- if (id) {
- setDependency(registerTarget, id, index, quantity);
- } else {
- if (quantity === Quantity.REQUIRED) {
- throw new IdentifierUndefinedError(registerTarget, index);
- }
-
- changeQuantity(registerTarget, index, quantity);
- }
- };
- } as any;
-}
-
-interface ManyDecorator {
- (id?: DependencyIdentifier<any>): any;
- // eslint-disable-next-line @typescript-eslint/no-misused-new
- new (): ManyDecorator;
-}
-export const Many: ManyDecorator = quantifyDecoratorFactoryProducer(Quantity.MANY);
-
-interface OptionalDecorator {
- (id?: DependencyIdentifier<any>): any;
- // eslint-disable-next-line @typescript-eslint/no-misused-new
- new (): OptionalDecorator;
-}
-export const Optional: OptionalDecorator = quantifyDecoratorFactoryProducer(
- Quantity.OPTIONAL
-);
-
-interface InjectDecorator {
- (id: DependencyIdentifier<any>): any;
- // eslint-disable-next-line @typescript-eslint/no-misused-new
- new (): InjectDecorator;
-}
-export const Inject: InjectDecorator = quantifyDecoratorFactoryProducer(
- Quantity.REQUIRED
-);
-
-function withNewDecoratorFactoryProducer(withNew: boolean) {
- return function DecoratorFactory<T>(this: any) {
- if (this instanceof DecoratorFactory) {
- return this;
- }
-
- return function d(target: Ctor<T>, _key: string, index: number) {
- changeToSelf(target, index, withNew);
- };
- } as any;
-}
-
-interface ToSelfDecorator {
- (): any;
- // eslint-disable-next-line @typescript-eslint/no-misused-new
- new (): ToSelfDecorator;
-}
-
-/**
- * Always initialize a new instance of that dependency instead of getting the cached instance from the injector.
- */
-export const WithNew: ToSelfDecorator = withNewDecoratorFactoryProducer(true);
-
-class DependencyDescriptorNotFoundError extends DIError {
- constructor(index: number, target: Ctor<any>) {
- const msg = `Could not find dependency registered on the ${
- index + 1
- } parameter of the constructor of "${prettyPrintIdentifier(target)}".`;
-
- super(msg);
- }
-}
-
-class IdentifierUndefinedError extends DIError {
- constructor(target: Ctor<any>, index: number) {
- const msg = `It seems that you register "undefined" as dependency on the ${
- index + 1
- } parameter of "${prettyPrintIdentifier(
- target
- )}". Please make sure that there is not cyclic dependency among your TypeScript files, or consider using "forwardRef".`;
-
- super(msg);
- }
-}
-
-export const TARGET = Symbol('$$TARGET');
-export const DEPENDENCIES = Symbol('$$DEPENDENCIES');
-
-/**
- * get dependencies declared on a class
- *
- * @param registerTarget the class
- * @returns dependencies
- */
-export function getDependencies<T>(
- registerTarget: Ctor<T>
-): Array<DependencyDescriptor<any>> {
- const target = registerTarget as any;
- return target[DEPENDENCIES] || [];
-}
-
-export function getDependencyByIndex<T>(
- registerTarget: Ctor<T>,
- index: number
-): DependencyDescriptor<any> {
- const allDependencies = getDependencies(registerTarget);
- const dep = allDependencies.find(
- (descriptor) => descriptor.paramIndex === index
- );
-
- if (!dep) {
- throw new DependencyDescriptorNotFoundError(index, registerTarget);
- }
-
- return dep;
-}
-
-/**
- * declare dependency relationship on a class
- *
- * if the IDependencyDescriptor already exists, just modify it without creating
- * a new descriptor since differently decorators could be applied on a same
- * constructor property
- *
- * @param registerTarget the class to be registered
- * @param identifier dependency item identifier
- * @param paramIndex index of the decorator constructor parameter
- * @param quantity quantity of the dependency
- * @param lookUp optional lookup
- */
-export function setDependency<T, U>(
- registerTarget: Ctor<U>,
- identifier: DependencyIdentifier<T>,
- paramIndex: number,
- quantity: Quantity = Quantity.REQUIRED,
- lookUp?: LookUp
-): void {
- const descriptor: DependencyDescriptor<T> = {
- paramIndex,
- identifier,
- quantity,
- lookUp,
- withNew: false,
- };
-
- // sometimes identifier could be 'undefined' if user meant to pass in an ES class
- // this is related to how classes are transpiled
- if (typeof identifier === 'undefined') {
- throw new IdentifierUndefinedError(registerTarget, paramIndex);
- }
-
- const target = registerTarget as any;
- // deal with inheritance, subclass need to declare dependencies on its on
- if (target[TARGET] === target) {
- target[DEPENDENCIES].push(descriptor);
- } else {
- target[DEPENDENCIES] = [descriptor];
- target[TARGET] = target;
- }
-}
-
-const knownIdentifiers = new Set<string>();
-export function createIdentifier<T>(id: string): IdentifierDecorator<T> {
- if (knownIdentifiers.has(id)) {
- throw new DIError(`Identifier "${id}" already exists.`);
- } else {
- knownIdentifiers.add(id);
- }
-
- const decorator = function d(
- registerTarget: Ctor<T>,
- _key: string,
- index: number
- ): void {
- setDependency(registerTarget, decorator, index);
- } as unknown as IdentifierDecorator<T>; // decorator as an identifier
-
- decorator.toString = () => id;
- decorator[IdentifierDecoratorSymbol] = true;
-
- return decorator;
-}
-
-/* istanbul ignore next */
-export function TEST_ONLY_clearKnownIdentifiers(): void {
- knownIdentifiers.clear();
-}
-
-function changeToSelf(target: Ctor<any>, index: number, withNew: boolean) {
- const descriptor = getDependencyByIndex(target, index);
- descriptor.withNew = withNew;
-}
diff --git a/packages/core/src/DI/DependencyCollection.ts b/packages/core/src/DI/DependencyCollection.ts
deleted file mode 100644
index 71a7fa9618..0000000000
--- a/packages/core/src/DI/DependencyCollection.ts
+++ /dev/null
@@ -1,196 +0,0 @@
-import { DependencyIdentifier, prettyPrintIdentifier } from './DependencyIdentifier';
-import { IDisposable, isIDisposable } from './Lifecycle';
-import { Ctor, Quantity } from './Types';
-import { DIError } from './Error';
-import { DependencyItem, checkQuantity, retrieveQuantity } from './Decorators';
-
-export type DependencyPair<T> = [DependencyIdentifier<T>, DependencyItem<T>];
-export type DependencyClass<T> = [Ctor<T>];
-export type Dependency<T = any> = DependencyPair<T> | DependencyClass<T>;
-
-export function isBareClassDependency<T>(
- thing: Dependency<T>
-): thing is DependencyClass<T> {
- return thing.length === 1;
-}
-
-export class DependencyNotFoundError extends DIError {
- constructor(id: DependencyIdentifier<any>) {
- const msg = `Cannot find "${prettyPrintIdentifier(
- id
- )}" registered by any injector.`;
-
- super(msg);
- }
-}
-
-/**
- * store unresolved dependencies in an injector
- *
- * @internal
- */
-export class DependencyCollection implements IDisposable {
- private readonly dependencyMap = new Map<
- DependencyIdentifier<any>,
- Array<DependencyItem<any>>
- >();
-
- constructor(dependencies: Dependency[]) {
- this.normalizeDependencies(dependencies).map((pair) =>
- this.add(pair[0], pair[1])
- );
- }
-
- add<T>(ctor: Ctor<T>): void;
- add<T>(id: DependencyIdentifier<T>, val: DependencyItem<T>): void;
- add<T>(
- ctorOrId: Ctor<T> | DependencyIdentifier<T>,
- val?: DependencyItem<T>
- ): void {
- if (typeof val === 'undefined') {
- val = { useClass: ctorOrId as Ctor<T>, lazy: false };
- }
-
- let arr = this.dependencyMap.get(ctorOrId);
- if (typeof arr === 'undefined') {
- arr = [];
- this.dependencyMap.set(ctorOrId, arr);
- }
- arr.push(val);
- }
-
- delete<T>(id: DependencyIdentifier<T>): void {
- this.dependencyMap.delete(id);
- }
-
- get<T>(id: DependencyIdentifier<T>): DependencyItem<T>;
- get<T>(
- id: DependencyIdentifier<T>,
- quantity: Quantity.REQUIRED
- ): DependencyItem<T>;
- get<T>(
- id: DependencyIdentifier<T>,
- quantity: Quantity.MANY
- ): Array<DependencyItem<T>>;
- get<T>(
- id: DependencyIdentifier<T>,
- quantity: Quantity.OPTIONAL
- ): DependencyItem<T> | null;
- get<T>(
- id: DependencyIdentifier<T>,
- quantity: Quantity
- ): DependencyItem<T> | Array<DependencyItem<T>> | null;
- get<T>(
- id: DependencyIdentifier<T>,
- quantity: Quantity = Quantity.REQUIRED
- ): DependencyItem<T> | Array<DependencyItem<T>> | null {
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
- const ret = this.dependencyMap.get(id)!;
-
- checkQuantity(id, quantity, ret.length);
- return retrieveQuantity(quantity, ret);
- }
-
- has<T>(id: DependencyIdentifier<T>): boolean {
- return this.dependencyMap.has(id);
- }
-
- append(dependencies: Array<Dependency<any>>): void {
- this.normalizeDependencies(dependencies).forEach((pair) =>
- this.add(pair[0], pair[1])
- );
- }
-
- dispose(): void {
- this.dependencyMap.clear();
- }
-
- /**
- * normalize dependencies to `DependencyItem`
- */
- private normalizeDependencies(
- dependencies: Dependency[]
- ): Array<DependencyPair<any>> {
- return dependencies.map((dependency) => {
- const id = dependency[0];
- let val: DependencyItem<any>;
- if (isBareClassDependency(dependency)) {
- val = {
- useClass: dependency[0],
- lazy: false,
- };
- } else {
- val = dependency[1];
- }
-
- return [id, val];
- });
- }
-}
-
-/**
- * store resolved dependencies
- *
- * @internal
- */
-export class ResolvedDependencyCollection implements IDisposable {
- private readonly resolvedDependencies = new Map<
- DependencyIdentifier<any>,
- any[]
- >();
-
- add<T>(id: DependencyIdentifier<T>, val: T | null): void {
- let arr = this.resolvedDependencies.get(id);
- if (typeof arr === 'undefined') {
- arr = [];
- this.resolvedDependencies.set(id, arr);
- }
-
- arr.push(val);
- }
-
- has<T>(id: DependencyIdentifier<T>): boolean {
- return this.resolvedDependencies.has(id);
- }
-
- delete<T>(id: DependencyIdentifier<T>): void {
- if (this.resolvedDependencies.has(id)) {
- const things = this.resolvedDependencies.get(id)!;
- things.forEach((t) => (isIDisposable(t) ? t.dispose() : undefined));
- this.resolvedDependencies.delete(id);
- }
- }
-
- get<T>(id: DependencyIdentifier<T>): T;
- get<T>(id: DependencyIdentifier<T>, quantity: Quantity.OPTIONAL): T | null;
- get<T>(id: DependencyIdentifier<T>, quantity: Quantity.REQUIRED): T;
- get<T>(id: DependencyIdentifier<T>, quantity: Quantity.MANY): T[];
- get<T>(id: DependencyIdentifier<T>, quantity: Quantity): T[] | T | null;
- get<T>(
- id: DependencyIdentifier<T>,
- quantity: Quantity = Quantity.REQUIRED
- ): T | T[] | null {
- const ret = this.resolvedDependencies.get(id);
-
- if (!ret) {
- throw new DependencyNotFoundError(id);
- }
-
- checkQuantity(id, quantity, ret.length);
-
- if (quantity === Quantity.MANY) {
- return ret;
- }
- return ret[0];
- }
-
- dispose(): void {
- Array.from(this.resolvedDependencies.values()).forEach((items) => {
- items.forEach((item) =>
- isIDisposable(item) ? item.dispose() : undefined
- );
- });
-
- this.resolvedDependencies.clear();
- }
-}
diff --git a/packages/core/src/DI/DependencyDeclare.ts b/packages/core/src/DI/DependencyDeclare.ts
deleted file mode 100644
index 4a1173fbac..0000000000
--- a/packages/core/src/DI/DependencyDeclare.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-import { FactoryDep, normalizeFactoryDeps, setDependency } from './Decorators';
-import { Ctor } from './Types';
-
-export function setDependencies<U>(
- registerTarget: Ctor<U>,
- deps: Array<FactoryDep<any>>
-): void {
- const normalizedDescriptors = normalizeFactoryDeps(deps);
- normalizedDescriptors.forEach((descriptor) => {
- setDependency(
- registerTarget,
- descriptor.identifier,
- descriptor.paramIndex,
- descriptor.quantity,
- descriptor.lookUp
- );
- });
-}
diff --git a/packages/core/src/DI/DependencyForwardRef.ts b/packages/core/src/DI/DependencyForwardRef.ts
deleted file mode 100644
index 0d02e820ee..0000000000
--- a/packages/core/src/DI/DependencyForwardRef.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import { Ctor } from './Types';
-
-export interface ForwardRef<T> {
- unwrap(): Ctor<T>;
-}
-
-export function forwardRef<T>(wrapper: () => Ctor<T>): ForwardRef<T> {
- return {
- unwrap: wrapper,
- };
-}
-
-export function isForwardRef<T = any>(thing: unknown): thing is ForwardRef<T> {
- return !!thing && typeof (thing as any).unwrap === 'function';
-}
diff --git a/packages/core/src/DI/DependencyIdentifier.ts b/packages/core/src/DI/DependencyIdentifier.ts
deleted file mode 100644
index af7e337a54..0000000000
--- a/packages/core/src/DI/DependencyIdentifier.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { ForwardRef } from './DependencyForwardRef';
-import { Ctor, isCtor } from './Types';
-
-export type IdentifierDecorator<T> = {
- // call signature of an decorator
- (...args: any[]): void;
-
- type: T;
-
- [IdentifierDecoratorSymbol]: true;
-
- // beautify console
- toString(): string;
-};
-
-export type DependencyIdentifier<T> =
- | string
- | Ctor<T>
- | ForwardRef<T>
- | IdentifierDecorator<T>;
-
-export type NormalizedDependencyIdentifier<T> = Exclude<
- DependencyIdentifier<T>,
- ForwardRef<T>
->;
-
-export const IdentifierDecoratorSymbol = Symbol('$$IDENTIFIER_DECORATOR');
-
-export function prettyPrintIdentifier<T>(id: DependencyIdentifier<T>): string {
- if (typeof id === 'undefined') {
- return 'undefined';
- }
-
- return isCtor(id) && !(id as any)[IdentifierDecoratorSymbol]
- ? id.name
- : id.toString();
-}
diff --git a/packages/core/src/DI/DependencySingletons.ts b/packages/core/src/DI/DependencySingletons.ts
deleted file mode 100644
index 4f350c712f..0000000000
--- a/packages/core/src/DI/DependencySingletons.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-import { DIError } from './Error';
-import { DependencyIdentifier, prettyPrintIdentifier } from './DependencyIdentifier';
-import { DependencyItem } from './Decorators';
-
-let singletonFetchedLock = false;
-
-const singletonDependencies: Array<
- [DependencyIdentifier<any>, DependencyItem<any>]
-> = [];
-
-class DuplicatedRegistrationError extends DIError {
- constructor(
- id: DependencyIdentifier<any>,
- item1: DependencyItem<any>,
- item2: DependencyItem<any>
- ) {
- super(
- `Duplicated registration of ${prettyPrintIdentifier(
- id
- )}, 1. ${item1} 2. ${item2}.`
- );
- }
-}
-
-export function registerSingleton<T>(
- id: DependencyIdentifier<T>,
- item: DependencyItem<T>
-): void {
- const index = singletonDependencies.findIndex((r) => r[0] === id);
-
- if (index !== -1) {
- throw new DuplicatedRegistrationError(
- id,
- singletonDependencies[index][1],
- item
- );
- }
-
- singletonDependencies.push([id, item]);
-}
-
-export function getSingletonDependencies(): Array<
- [DependencyIdentifier<any>, DependencyItem<any>]
-> {
- if (singletonFetchedLock) {
- console.warn(
- '[DI]: Singleton dependencies has been fetched before by an other injector. ' +
- 'Please avoid fetching singleton dependencies twice.'
- );
- }
-
- singletonFetchedLock = true;
-
- return singletonDependencies;
-}
-
-/* istanbul ignore next */
-export function TEST_ONLY_clearSingletonDependencies(): void {
- singletonFetchedLock = false;
-
- singletonDependencies.length = 0;
-}
diff --git a/packages/core/src/DI/Error.ts b/packages/core/src/DI/Error.ts
deleted file mode 100644
index 70d1df043d..0000000000
--- a/packages/core/src/DI/Error.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-export class DIError extends Error {
- constructor(message: string) {
- super(`[DI]: ${message}`);
- }
-}
diff --git a/packages/core/src/DI/IdleValue.ts b/packages/core/src/DI/IdleValue.ts
deleted file mode 100644
index 7c2aac76b9..0000000000
--- a/packages/core/src/DI/IdleValue.ts
+++ /dev/null
@@ -1,119 +0,0 @@
-import { IDisposable } from './Lifecycle';
-
-export interface IdleDeadline {
- readonly didTimeout: boolean;
- timeRemaining(): DOMHighResTimeStamp;
-}
-
-export type DisposableCallback = () => void;
-
-/**
- * this run the callback when CPU is idle. Will fallback to setTimeout if
- * the browser doesn't support requestIdleCallback
- */
-// eslint-disable-next-line import/no-mutable-exports
-export let runWhenIdle: (
- callback: (idle?: IdleDeadline) => void,
- timeout?: number
-) => DisposableCallback;
-
-// declare global variables because apparently the type file doesn't have it, for now
-declare function requestIdleCallback(
- callback: (args: IdleDeadline) => void,
- options?: { timeout: number }
-): number;
-declare function cancelIdleCallback(handle: number): void;
-
-// use an IIFE to set up runWhenIdle
-(function patch() {
- if (
- typeof requestIdleCallback !== 'undefined' &&
- typeof cancelIdleCallback !== 'undefined'
- ) {
- // use native requestIdleCallback
- runWhenIdle = (runner, timeout?) => {
- const handle: number = requestIdleCallback(
- runner,
- typeof timeout === 'number' ? { timeout } : undefined
- );
- let disposed = false;
- return () => {
- if (disposed) {
- return;
- }
- disposed = true;
- clearTimeout(handle);
- };
- };
- } else {
- // use setTimeout as hack
- const dummyIdle: IdleDeadline = Object.freeze({
- didTimeout: true,
- timeRemaining() {
- return 15;
- },
- });
-
- runWhenIdle = (runner) => {
- const handle = setTimeout(() => runner(dummyIdle));
- let disposed = false;
- return () => {
- if (disposed) {
- return;
- }
- disposed = true;
- clearTimeout(handle);
- };
- };
- }
-})();
-
-/**
- * a wrapper of a executor so it can be evaluated when it's necessary or the CPU is idle
- *
- * the type of the returned value of the executor would be T
- */
-export class IdleValue<T> implements IDisposable {
- private readonly executor: () => void;
-
- private readonly disposeCallback: () => void;
-
- private didRun = false;
-
- private value?: T;
-
- private error?: Error;
-
- constructor(executor: () => T) {
- this.executor = () => {
- try {
- this.value = executor();
- } catch (err: any) {
- this.error = err;
- } finally {
- this.didRun = true;
- }
- };
- this.disposeCallback = runWhenIdle(() => this.executor());
- }
-
- hasRun(): boolean {
- return this.didRun;
- }
-
- dispose(): void {
- this.disposeCallback();
- }
-
- getValue(): T {
- if (!this.didRun) {
- this.dispose();
- this.executor();
- }
- if (this.error) {
- throw this.error;
- }
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
- return this.value!;
- }
-}
diff --git a/packages/core/src/DI/Injector.ts b/packages/core/src/DI/Injector.ts
deleted file mode 100644
index e6368145b2..0000000000
--- a/packages/core/src/DI/Injector.ts
+++ /dev/null
@@ -1,618 +0,0 @@
-import {
- getDependencies,
- DependencyItem,
- AsyncDependencyItem,
- isClassDependencyItem,
- isFactoryDependencyItem,
- isValueDependencyItem,
- isAsyncDependencyItem,
- ClassDependencyItem,
- FactoryDependencyItem,
- AsyncHook,
- isAsyncHook,
- ValueDependencyItem,
- normalizeFactoryDeps,
-} from './Decorators';
-import {
- Dependency,
- DependencyCollection,
- DependencyNotFoundError,
- ResolvedDependencyCollection,
- DependencyPair,
-} from './DependencyCollection';
-import {
- DependencyIdentifier,
- NormalizedDependencyIdentifier,
- prettyPrintIdentifier,
-} from './DependencyIdentifier';
-import { IdleValue } from './IdleValue';
-import { getSingletonDependencies } from './DependencySingletons';
-import { DIError } from './Error';
-import { Quantity, LookUp, Ctor, isCtor } from './Types';
-import { isICreatable } from './Lifecycle';
-import { isForwardRef } from './DependencyForwardRef';
-
-const MAX_RESOLUTIONS_QUEUED = 300;
-
-const NotInstantiatedSymbol = Symbol('$$NOT_INSTANTIATED_SYMBOL');
-
-class CircularDependencyError<T> extends DIError {
- constructor(id: DependencyIdentifier<T>) {
- super(
- `Detecting cyclic dependency. The last identifier is "${prettyPrintIdentifier(
- id
- )}".`
- );
- }
-}
-
-class InjectorAlreadyDisposedError extends DIError {
- constructor() {
- super('Injector cannot be accessed after it disposes.');
- }
-}
-
-class AsyncItemReturnAsyncItemError<T> extends DIError {
- constructor(id: DependencyIdentifier<T>) {
- super(
- `Async item "${prettyPrintIdentifier(id)}" returns another async item.`
- );
- }
-}
-
-class GetAsyncItemFromSyncApiError<T> extends DIError {
- constructor(id: DependencyIdentifier<T>) {
- super(`Cannot get async item "${prettyPrintIdentifier(id)}" from sync api.`);
- }
-}
-
-function normalizeForwardRef<T>(
- id: DependencyIdentifier<T>
-): NormalizedDependencyIdentifier<T> {
- if (isForwardRef(id)) {
- return id.unwrap();
- }
-
- return id;
-}
-
-export class Injector {
- private readonly dependencyCollection: DependencyCollection;
-
- private readonly resolvedDependencyCollection: ResolvedDependencyCollection;
-
- private readonly parent: Injector | null;
-
- private readonly children: Injector[] = [];
-
- private resolutionOngoing = 0;
-
- private disposed = false;
-
- constructor(collectionOrDependencies?: Dependency[], parent?: Injector) {
- this.dependencyCollection = new DependencyCollection(
- collectionOrDependencies || []
- );
-
- if (!parent) {
- this.parent = null;
- this.dependencyCollection.append(getSingletonDependencies());
- } else {
- this.parent = parent;
- parent.children.push(this);
- }
-
- this.resolvedDependencyCollection = new ResolvedDependencyCollection();
- }
-
- createChild(dependencies?: Dependency[]): Injector {
- this.ensureInjectorNotDisposed();
-
- return new Injector(dependencies, this);
- }
-
- dispose(): void {
- this.dependencyCollection.dispose();
- this.resolvedDependencyCollection.dispose();
- this.deleteThisFromParent();
-
- this.disposed = true;
- }
-
- add<T>(ctor: Ctor<T>): void;
- add<T>(pair: DependencyPair<T>): void;
- add<T>(id: DependencyIdentifier<T>, item: DependencyItem<T> | T): void;
- add<T>(
- dependency: Ctor<T> | DependencyPair<T> | DependencyIdentifier<T>,
- item?: DependencyItem<T> | T
- ): void {
- if (typeof item !== 'undefined' || Array.isArray(dependency)) {
- if (Array.isArray(dependency)) {
- item = dependency[1];
- dependency = dependency[0];
- }
-
- if (
- isAsyncDependencyItem(item) ||
- isClassDependencyItem(item) ||
- isValueDependencyItem(item) ||
- isFactoryDependencyItem(item)
- ) {
- this.dependencyCollection.add(dependency, item as DependencyItem<T>);
- } else {
- this.resolvedDependencyCollection.add(dependency, item as T);
- }
- } else {
- this.dependencyCollection.add(dependency as Ctor<T>);
- }
- }
-
- /**
- * delete a dependency and instantiated values from an injector
- */
- delete<T>(id: DependencyIdentifier<T>): void {
- this.dependencyCollection.delete(id);
- this.resolvedDependencyCollection.delete(id);
- }
-
- /**
- * get a dependency
- */
- get<T>(id: DependencyIdentifier<T>, lookUp?: LookUp): T;
- get<T>(
- id: DependencyIdentifier<T>,
- quantity: Quantity.MANY,
- lookUp?: LookUp
- ): T[];
- get<T>(
- id: DependencyIdentifier<T>,
- quantity: Quantity.OPTIONAL,
- lookUp?: LookUp
- ): T | null;
- get<T>(
- id: DependencyIdentifier<T>,
- quantity: Quantity.REQUIRED,
- lookUp?: LookUp
- ): T;
- get<T>(
- id: DependencyIdentifier<T>,
- quantity?: Quantity,
- lookUp?: LookUp
- ): T[] | T | null;
- get<T>(
- id: DependencyIdentifier<T>,
- quantityOrLookup?: Quantity | LookUp,
- lookUp?: LookUp
- ): T[] | T | null;
- get<T>(
- id: DependencyIdentifier<T>,
- quantityOrLookup?: Quantity | LookUp,
- lookUp?: LookUp
- ): T[] | T | null {
- const newResult = this._get(id, quantityOrLookup, lookUp);
-
- if (
- (Array.isArray(newResult) && newResult.some((r) => isAsyncHook(r))) ||
- isAsyncHook(newResult)
- ) {
- throw new GetAsyncItemFromSyncApiError(id);
- }
-
- return newResult as T | T[] | null;
- }
-
- _get<T>(
- id: DependencyIdentifier<T>,
- quantityOrLookup?: Quantity | LookUp,
- lookUp?: LookUp,
- toSelf?: boolean
- ): T[] | T | AsyncHook<T> | null {
- this.ensureInjectorNotDisposed();
-
- let quantity: Quantity = Quantity.REQUIRED;
- if (
- quantityOrLookup === Quantity.REQUIRED ||
- quantityOrLookup === Quantity.OPTIONAL ||
- quantityOrLookup === Quantity.MANY
- ) {
- quantity = quantityOrLookup as Quantity;
- } else {
- lookUp = quantityOrLookup as LookUp;
- }
-
- if (!toSelf) {
- // see if the dependency is already resolved, return it and check quantity
- const cachedResult = this.getValue(id, quantity, lookUp);
- if (cachedResult !== NotInstantiatedSymbol) {
- return cachedResult;
- }
- }
-
- // see if the dependency can be instantiated by itself or its parent
- return this.createDependency(id, quantity, lookUp, !toSelf) as
- | T[]
- | T
- | AsyncHook<T>
- | null;
- }
-
- /**
- * get a dependency, but in async way
- */
- getAsync<T>(id: DependencyIdentifier<T>): Promise<T> {
- this.ensureInjectorNotDisposed();
-
- const cachedResult = this.getValue(id, Quantity.REQUIRED);
- if (cachedResult !== NotInstantiatedSymbol) {
- return Promise.resolve(cachedResult as T);
- }
-
- const newResult = this.createDependency(id, Quantity.REQUIRED);
- if (!isAsyncHook(newResult)) {
- return Promise.resolve(newResult as T);
- }
-
- return newResult.whenReady();
- }
-
- /**
- * to instantiate a class withing the current injector
- */
- createInstance<T extends unknown[], U extends unknown[], C>(
- ctor: new (...args: [...T, ...U]) => C,
- ...customArgs: T
- ): C {
- this.ensureInjectorNotDisposed();
-
- return this.resolveClass_(ctor as Ctor<C>, ...customArgs);
- }
-
- /**
- * resolve different types of dependencies
- */
- private resolveDependency<T>(
- id: DependencyIdentifier<T>,
- item: DependencyItem<T>,
- shouldCache = true
- ): T | AsyncHook<T> {
- if (isValueDependencyItem(item)) {
- return this.resolveValueDependency(id, item as ValueDependencyItem<T>);
- }
- if (isFactoryDependencyItem(item)) {
- return this.resolveFactory(
- id,
- item as FactoryDependencyItem<T>,
- shouldCache
- );
- }
- if (isClassDependencyItem(item)) {
- return this.resolveClass(
- id,
- item as ClassDependencyItem<T>,
- shouldCache
- );
- }
- return this.resolveAsync(id, item as AsyncDependencyItem<T>);
- }
-
- private resolveValueDependency<T>(
- id: DependencyIdentifier<T>,
- item: ValueDependencyItem<T>
- ): T {
- const thing = item.useValue;
- this.resolvedDependencyCollection.add(id, thing);
- return thing;
- }
-
- private resolveClass<T>(
- id: DependencyIdentifier<T> | null,
- item: ClassDependencyItem<T>,
- shouldCache = true
- ): T {
- const ctor = item.useClass;
- let thing: T;
-
- if (item.lazy) {
- const idle = new IdleValue<T>(() => this.resolveClass_(ctor));
- thing = new Proxy(Object.create(null), {
- get(target: any, key: string | number | symbol): any {
- if (key in target) {
- return target[key]; // such as toString
- }
-
- // hack checking if it's a async loader
- if (key === 'whenReady') {
- return undefined;
- }
-
- const hasInstantiated = idle.hasRun();
- const thing = idle.getValue();
- if (!hasInstantiated) {
- item.onInstantiation?.(thing);
- }
-
- let property = (thing as any)[key];
- if (typeof property !== 'function') {
- return property;
- }
-
- property = property.bind(thing);
- target[key] = property;
-
- return property;
- },
- set(
- _target: any,
- key: string | number | symbol,
- value: any
- ): boolean {
- (idle.getValue() as any)[key] = value;
- return true;
- },
- });
- } else {
- thing = this.resolveClass_(ctor);
- }
-
- if (id && shouldCache) {
- this.resolvedDependencyCollection.add(id, thing);
- }
-
- return thing;
- }
-
- private resolveClass_<T>(CCtor: Ctor<T>, ...extraParams: any[]) {
- this.markNewResolution(CCtor);
-
- const declaredDependencies = getDependencies(CCtor)
- .sort((a, b) => a.paramIndex - b.paramIndex)
- .map((descriptor) => ({
- ...descriptor,
- identifier: normalizeForwardRef(descriptor.identifier),
- }));
-
- const resolvedArgs: any[] = [];
-
- for (const dep of declaredDependencies) {
- // recursive happens here
- const thing = this._get(
- dep.identifier,
- dep.quantity,
- dep.lookUp,
- dep.withNew
- );
- resolvedArgs.push(thing);
- }
-
- let args = [...extraParams];
- const firstDependencyArgIndex =
- declaredDependencies.length > 0
- ? declaredDependencies[0].paramIndex
- : args.length;
-
- if (args.length !== firstDependencyArgIndex) {
- console.warn(
- `[DI]: Expect ${firstDependencyArgIndex} custom parameter(s) but get ${args.length}.`
- );
-
- const delta = firstDependencyArgIndex - args.length;
- if (delta > 0) {
- args = [...args, ...new Array(delta).fill(undefined)];
- } else {
- args = args.slice(0, firstDependencyArgIndex);
- }
- }
-
- const thing = new CCtor(...args, ...resolvedArgs);
-
- this.callOnCreationMethod(thing);
- this.markResolutionCompleted();
-
- return thing;
- }
-
- private callOnCreationMethod(thing: unknown): void {
- if (isICreatable(thing)) {
- thing.onCreate.apply(thing);
- }
- }
-
- private resolveFactory<T>(
- id: DependencyIdentifier<T>,
- item: FactoryDependencyItem<T>,
- shouldCache: boolean
- ): T {
- this.markNewResolution(id);
-
- const declaredDependencies = normalizeFactoryDeps(item.deps);
-
- const resolvedArgs: any[] = [];
- for (const dep of declaredDependencies) {
- const thing = this._get(
- dep.identifier,
- dep.quantity,
- dep.lookUp,
- dep.withNew
- );
- resolvedArgs.push(thing);
- }
-
- const thing = item.useFactory.apply(null, resolvedArgs);
-
- if (shouldCache) {
- this.resolvedDependencyCollection.add(id, thing);
- }
-
- this.markResolutionCompleted();
-
- item?.onInstantiation?.(thing);
-
- return thing;
- }
-
- private resolveAsync<T>(
- id: DependencyIdentifier<T>,
- item: AsyncDependencyItem<T>
- ): AsyncHook<T> {
- const asyncLoader: AsyncHook<T> = {
- whenReady: () => this.resolveAsync_(id, item),
- };
- return asyncLoader;
- }
-
- private resolveAsync_<T>(
- id: DependencyIdentifier<T>,
- item: AsyncDependencyItem<T>
- ): Promise<T> {
- return item.useAsync().then((thing) => {
- // check if another promise has been resolved,
- // do not resolve the async item twice
- const resolvedCheck = this.getValue(id);
- if (resolvedCheck !== NotInstantiatedSymbol) {
- return resolvedCheck as T;
- }
-
- let ret: T;
- if (Array.isArray(thing)) {
- const item = thing[1];
- if (isAsyncDependencyItem(item)) {
- throw new AsyncItemReturnAsyncItemError(id);
- } else {
- ret = this.resolveDependency(id, item) as T;
- }
- } else if (isCtor(thing)) {
- ret = this.resolveClass_(thing);
- } else {
- ret = thing;
- }
-
- this.resolvedDependencyCollection.add(id, ret);
-
- return ret;
- });
- }
-
- /**
- * recursively get a dependency value
- */
- private getValue<T>(
- id: DependencyIdentifier<T>,
- quantity: Quantity = Quantity.REQUIRED,
- lookUp?: LookUp
- ): null | T | T[] | typeof NotInstantiatedSymbol {
- const onSelf = () => {
- if (
- this.dependencyCollection.has(id) &&
- !this.resolvedDependencyCollection.has(id)
- ) {
- return NotInstantiatedSymbol;
- }
-
- return this.resolvedDependencyCollection.get(id, quantity);
- };
-
- const onParent = () => {
- if (this.parent) {
- return this.parent.getValue(id, quantity);
- }
- return NotInstantiatedSymbol;
- };
-
- if (lookUp === LookUp.SKIP_SELF) {
- return onParent();
- }
-
- if (lookUp === LookUp.SELF) {
- return onSelf();
- }
-
- if (
- this.resolvedDependencyCollection.has(id) ||
- this.dependencyCollection.has(id)
- ) {
- return onSelf();
- }
-
- return onParent();
- }
-
- /**
- * create instance on the correct injector
- */
- private createDependency<T>(
- id: DependencyIdentifier<T>,
- quantity: Quantity = Quantity.REQUIRED,
- lookUp?: LookUp,
- shouldCache = true
- ): null | T | T[] | AsyncHook<T> | Array<T | AsyncHook<T>> {
- const onSelf = () => {
- const registrations = this.dependencyCollection.get(id, quantity);
-
- let ret: Array<T | AsyncHook<T>> | T | AsyncHook<T> | null = null;
- if (Array.isArray(registrations)) {
- ret = registrations.map((dependencyItem) =>
- this.resolveDependency(id, dependencyItem, shouldCache)
- );
- } else if (registrations) {
- ret = this.resolveDependency(id, registrations, shouldCache);
- }
-
- return ret;
- };
-
- const onParent = () => {
- if (this.parent) {
- return this.parent.createDependency(
- id,
- quantity,
- undefined,
- shouldCache
- );
- }
- if (quantity === Quantity.OPTIONAL) {
- return null;
- }
-
- throw new DependencyNotFoundError(id);
- };
-
- if (lookUp === LookUp.SKIP_SELF) {
- return onParent();
- }
-
- if ((id as any as Ctor<Injector>) === Injector) {
- return this as any as T;
- }
-
- if (this.dependencyCollection.has(id)) {
- return onSelf();
- }
-
- return onParent();
- }
-
- private markNewResolution<T>(id: DependencyIdentifier<T>): void {
- this.resolutionOngoing += 1;
-
- if (this.resolutionOngoing >= MAX_RESOLUTIONS_QUEUED) {
- throw new CircularDependencyError(id);
- }
- }
-
- private markResolutionCompleted(): void {
- this.resolutionOngoing -= 1;
- }
-
- private ensureInjectorNotDisposed(): void {
- if (this.disposed) {
- throw new InjectorAlreadyDisposedError();
- }
- }
-
- private deleteThisFromParent(): void {
- if (this.parent) {
- const index = this.parent.children.indexOf(this);
- this.parent.children.splice(index, 1);
- }
- }
-}
diff --git a/packages/core/src/DI/Lifecycle.ts b/packages/core/src/DI/Lifecycle.ts
deleted file mode 100644
index 937814dac0..0000000000
--- a/packages/core/src/DI/Lifecycle.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-export interface IDisposable {
- dispose(): void;
-}
-
-export function isIDisposable(thing: unknown): thing is IDisposable {
- return !!thing && typeof (thing as any).dispose === 'function';
-}
-
-export interface ICreatable {
- onCreate(): void;
-}
-
-export function isICreatable(thing: unknown): thing is ICreatable {
- return !!thing && typeof (thing as any).onCreate === 'function';
-}
diff --git a/packages/core/src/DI/Types.ts b/packages/core/src/DI/Types.ts
deleted file mode 100644
index d793293b2d..0000000000
--- a/packages/core/src/DI/Types.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-export enum Quantity {
- MANY = 'many',
- OPTIONAL = 'optional',
- REQUIRED = 'required',
-}
-
-export enum LookUp {
- SELF = 'self',
- SKIP_SELF = 'skipSelf',
-}
-
-export interface Ctor<T> {
- name: string; // constructor function has a name
-
- new (...args: any[]): T;
-}
-export function isCtor<T>(thing: unknown): thing is Ctor<T> {
- return typeof thing === 'function';
-}
diff --git a/packages/core/src/DI/index.ts b/packages/core/src/DI/index.ts
deleted file mode 100644
index b4f5793858..0000000000
--- a/packages/core/src/DI/index.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-export {
- AsyncDependencyItem,
- AsyncHook,
- ClassDependencyItem,
- createIdentifier,
- DependencyItem,
- FactoryDependencyItem,
- Inject,
- isAsyncDependencyItem,
- isAsyncHook,
- isClassDependencyItem,
- isFactoryDependencyItem,
- isValueDependencyItem,
- Many,
- Optional,
- Self,
- SkipSelf,
- SyncDependencyItem,
- ValueDependencyItem,
-} from './Decorators';
-export { Quantity, LookUp, Ctor, isCtor } from './Types';
-export { forwardRef } from './DependencyForwardRef';
-export { Injector } from './Injector';
-export { DependencyPair, Dependency } from './DependencyCollection';
-export { DependencyIdentifier, IdentifierDecorator } from './DependencyIdentifier';
-export { IDisposable, ICreatable } from './Lifecycle';
-export { setDependencies } from './DependencyDeclare';
-export { registerSingleton } from './DependencySingletons';
-export { DIError } from './Error';
-
-const globalObject: any =
- (typeof globalThis !== 'undefined' && globalThis) ||
- (typeof window !== 'undefined' && window) ||
- // @ts-ignore
- (typeof global !== 'undefined' && global);
-
-const __REDI_GLOBAL_LOCK__ = 'REDI_GLOBAL_LOCK';
-
-if (globalObject[__REDI_GLOBAL_LOCK__]) {
- console.error(
- '[DI]: Load scripts of DI more than once! This may cause undesired behavior in your application.'
- );
-} else {
- globalObject[__REDI_GLOBAL_LOCK__] = true;
-}
diff --git a/packages/core/src/Server/ServerSocket.ts b/packages/core/src/Server/ServerSocket.ts
index b2b00d0eae..fca7b35144 100644
--- a/packages/core/src/Server/ServerSocket.ts
+++ b/packages/core/src/Server/ServerSocket.ts
@@ -1,5 +1,5 @@
import { ISheetActionData } from '../Command';
-import { ICreatable, createIdentifier } from '../DI';
+import { ICreatable, createIdentifier } from '@wendellhu/redi';
import { IWorkbookConfig, IWorksheetConfig } from '../Types/Interfaces';
import { IOSocket, IOSocketListenType } from '../Shared';
import { MessageQueue } from './MessageQueue';
@@ -135,4 +135,4 @@ export class ServerSocket extends ServerBase implements ICreatable {
}
return this.status;
}
-}
+}
\ No newline at end of file
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index fc1eb50ae4..fef79bdf80 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -18,7 +18,6 @@ import './Docs/Action';
export * from './Basics';
export * from './Command';
export * from './Types/Const';
-export * from './DI';
export * from './Docs/Domain';
export * from './Types/Enum';
export * from './Types/Interfaces';
@@ -27,4 +26,4 @@ export * from './Plugin';
export * from './Server';
export * from './Shared';
export * from './Sheets';
-export * from './Slides/Domain';
+export * from './Slides/Domain';
\ No newline at end of file
diff --git a/packages/sheets-plugin-numfmt/package.json b/packages/sheets-plugin-numfmt/package.json
index bce541e675..327dafa041 100644
--- a/packages/sheets-plugin-numfmt/package.json
+++ b/packages/sheets-plugin-numfmt/package.json
@@ -64,7 +64,7 @@
"@univerjs/common-plugin-data": "workspace:^0.0.1",
"@univerjs/core": "workspace:^0.0.1",
"@univerjs/ui-plugin-sheets": "workspace:^0.0.1",
- "preact": "^10.12.1",
- "@wendellhu/redi": "^0.6.5"
+ "@wendellhu/redi": "^0.8.0",
+ "preact": "^10.12.1"
}
-}
+}
\ No newline at end of file
diff --git a/packages/sheets-plugin-numfmt/src/NumfmtPlugin.ts b/packages/sheets-plugin-numfmt/src/NumfmtPlugin.ts
index 73c6ef0ef4..15583825c1 100644
--- a/packages/sheets-plugin-numfmt/src/NumfmtPlugin.ts
+++ b/packages/sheets-plugin-numfmt/src/NumfmtPlugin.ts
@@ -1,11 +1,12 @@
-import { SheetContext, IRangeData, ObjectMatrixPrimitiveType, Plugin, PLUGIN_NAMES, Injector } from '@univerjs/core';
import { RenderEngine } from '@univerjs/base-render';
import { IGlobalContext, IRenderingEngine, ISheetContext } from '@univerjs/base-sheets';
-import { NumfmtPluginObserve, install } from './Basics/Observer';
+import { IRangeData, ObjectMatrixPrimitiveType, Plugin, PLUGIN_NAMES, SheetContext } from '@univerjs/core';
+import { Injector } from '@wendellhu/redi';
import { NUMFMT_PLUGIN_NAME } from './Basics/Const/PLUGIN_NAME';
+import { install, NumfmtPluginObserve } from './Basics/Observer';
+import { NumfmtActionExtensionFactory } from './Basics/Register/NumfmtActionExtension';
import { NumfmtController } from './Controller/NumfmtController';
import { NumfmtModalController } from './Controller/NumfmtModalController';
-import { NumfmtActionExtensionFactory } from './Basics/Register/NumfmtActionExtension';
import en from './Locale/en';
import zh from './Locale/zh';
@@ -71,4 +72,4 @@ export class NumfmtPlugin extends Plugin<NumfmtPluginObserve, SheetContext> {
[NumfmtModalController],
]);
}
-}
+}
\ No newline at end of file