@eggjs/tegg-vitest 0.0.0 → 4.0.1-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2017-present Alibaba Group Holding Limited and other contributors.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,11 @@
1
+ import { EggMockApp, TeggVitestAdapterOptions } from "./shared.js";
2
+
3
+ //#region src/index.d.ts
4
+
5
+ /**
6
+ * Configure the custom Vitest runner (used via globalThis.__teggVitestConfig).
7
+ * Call this in a setupFile and set `runner` in vitest.config.ts to use the runner approach.
8
+ */
9
+ declare function configureTeggRunner(options?: TeggVitestAdapterOptions): void;
10
+ //#endregion
11
+ export { type EggMockApp, type TeggVitestAdapterOptions, configureTeggRunner };
package/dist/index.js ADDED
@@ -0,0 +1,16 @@
1
+ import { defaultGetApp } from "./shared.js";
2
+
3
+ //#region src/index.ts
4
+ /**
5
+ * Configure the custom Vitest runner (used via globalThis.__teggVitestConfig).
6
+ * Call this in a setupFile and set `runner` in vitest.config.ts to use the runner approach.
7
+ */
8
+ function configureTeggRunner(options = {}) {
9
+ globalThis.__teggVitestConfig = {
10
+ restoreMocks: options.restoreMocks ?? true,
11
+ getApp: options.getApp ?? defaultGetApp
12
+ };
13
+ }
14
+
15
+ //#endregion
16
+ export { configureTeggRunner };
@@ -0,0 +1,21 @@
1
+ import { VitestTestRunner } from "vitest/runners";
2
+ import { RunnerTask, RunnerTestSuite } from "vitest";
3
+
4
+ //#region src/runner.d.ts
5
+ declare class TeggVitestRunner extends VitestTestRunner {
6
+ private fileScopeMap;
7
+ private taskScopeMap;
8
+ private fileAppMap;
9
+ private warned;
10
+ /**
11
+ * Override importFile to capture per-file config set by configureTeggRunner()
12
+ * and await app.ready() during collection phase.
13
+ */
14
+ importFile(filepath: string, source: Parameters<VitestTestRunner["importFile"]>[1]): Promise<unknown>;
15
+ onBeforeRunSuite(suite: RunnerTestSuite): Promise<void>;
16
+ onAfterRunSuite(suite: RunnerTestSuite): Promise<void>;
17
+ onBeforeTryTask(test: RunnerTask): Promise<void>;
18
+ onAfterRunTask(test: RunnerTask): Promise<void>;
19
+ }
20
+ //#endregion
21
+ export { TeggVitestRunner as default };
package/dist/runner.js ADDED
@@ -0,0 +1,172 @@
1
+ import { debugLog, defaultGetApp, restoreEggMocksIfNeeded } from "./shared.js";
2
+ import { VitestTestRunner } from "vitest/runners";
3
+
4
+ //#region src/runner.ts
5
+ /**
6
+ * Create a held beginModuleScope: starts the scope and waits until init() is
7
+ * complete (the inner fn starts executing), then returns the held scope.
8
+ * The scope stays alive until endScope() is called.
9
+ */
10
+ async function createHeldScope(ctx) {
11
+ let endScope;
12
+ const gate = new Promise((resolve) => {
13
+ endScope = resolve;
14
+ });
15
+ let scopeReady;
16
+ const readyPromise = new Promise((resolve) => {
17
+ scopeReady = resolve;
18
+ });
19
+ const scopePromise = ctx.beginModuleScope(async () => {
20
+ scopeReady();
21
+ await gate;
22
+ });
23
+ await Promise.race([readyPromise, scopePromise]);
24
+ return {
25
+ scopePromise,
26
+ endScope
27
+ };
28
+ }
29
+ async function releaseHeldScope(scope) {
30
+ if (!scope) return;
31
+ scope.endScope();
32
+ await scope.scopePromise;
33
+ }
34
+ function isFileSuite(suite) {
35
+ return !suite.suite && !!suite.filepath;
36
+ }
37
+ function getTaskFilepath(task) {
38
+ return task.file?.filepath;
39
+ }
40
+ var TeggVitestRunner = class extends VitestTestRunner {
41
+ fileScopeMap = /* @__PURE__ */ new Map();
42
+ taskScopeMap = /* @__PURE__ */ new Map();
43
+ fileAppMap = /* @__PURE__ */ new Map();
44
+ warned = false;
45
+ /**
46
+ * Override importFile to capture per-file config set by configureTeggRunner()
47
+ * and await app.ready() during collection phase.
48
+ */
49
+ async importFile(filepath, source) {
50
+ if (source === "collect") {
51
+ this.fileAppMap.delete(filepath);
52
+ this.warned = false;
53
+ }
54
+ delete globalThis.__teggVitestConfig;
55
+ const result = await super.importFile(filepath, source);
56
+ if (source === "collect") {
57
+ const rawConfig = globalThis.__teggVitestConfig;
58
+ if (rawConfig) {
59
+ delete globalThis.__teggVitestConfig;
60
+ const config = {
61
+ restoreMocks: rawConfig.restoreMocks ?? true,
62
+ getApp: rawConfig.getApp ?? defaultGetApp
63
+ };
64
+ debugLog(`captured config for ${filepath}`);
65
+ try {
66
+ const app = await config.getApp();
67
+ if (app) {
68
+ await app.ready();
69
+ this.fileAppMap.set(filepath, {
70
+ app,
71
+ config
72
+ });
73
+ debugLog(`app ready for ${filepath}`);
74
+ }
75
+ } catch (err) {
76
+ if (!this.warned) {
77
+ this.warned = true;
78
+ console.warn("[tegg-vitest] getApp failed, skip context injection.", err);
79
+ }
80
+ }
81
+ }
82
+ }
83
+ return result;
84
+ }
85
+ async onBeforeRunSuite(suite) {
86
+ if (isFileSuite(suite)) {
87
+ const filepath = suite.filepath;
88
+ debugLog(`onBeforeRunSuite (file): ${filepath}`);
89
+ const fileApp = this.fileAppMap.get(filepath);
90
+ if (fileApp) {
91
+ const { app, config } = fileApp;
92
+ if (typeof app.mockContext === "function" && app.ctxStorage) {
93
+ const suiteCtx = app.mockContext(void 0, {
94
+ mockCtxStorage: false,
95
+ reuseCtxStorage: false
96
+ });
97
+ app.ctxStorage.enterWith(suiteCtx);
98
+ let suiteScope = null;
99
+ if (typeof suiteCtx.beginModuleScope === "function") {
100
+ suiteScope = await createHeldScope(suiteCtx);
101
+ debugLog("suite held scope created");
102
+ }
103
+ this.fileScopeMap.set(filepath, {
104
+ app,
105
+ config,
106
+ suiteCtx,
107
+ suiteScope
108
+ });
109
+ debugLog("file suite scope created");
110
+ }
111
+ }
112
+ }
113
+ await super.onBeforeRunSuite(suite);
114
+ }
115
+ async onAfterRunSuite(suite) {
116
+ if (isFileSuite(suite)) {
117
+ const filepath = suite.filepath;
118
+ debugLog(`onAfterRunSuite (file): ${filepath}`);
119
+ const fileState = this.fileScopeMap.get(filepath);
120
+ if (fileState) {
121
+ await releaseHeldScope(fileState.suiteScope);
122
+ this.fileScopeMap.delete(filepath);
123
+ }
124
+ this.fileAppMap.delete(filepath);
125
+ }
126
+ await super.onAfterRunSuite(suite);
127
+ }
128
+ async onBeforeTryTask(test) {
129
+ const filepath = getTaskFilepath(test);
130
+ if (filepath) {
131
+ const fileState = this.fileScopeMap.get(filepath);
132
+ if (fileState) {
133
+ const existing = this.taskScopeMap.get(test.id);
134
+ if (existing) await releaseHeldScope(existing.testScope);
135
+ debugLog(`onBeforeTryTask: ${test.name}`);
136
+ const testCtx = fileState.app.mockContext(void 0, {
137
+ mockCtxStorage: false,
138
+ reuseCtxStorage: false
139
+ });
140
+ fileState.app.ctxStorage.enterWith(testCtx);
141
+ let testScope = null;
142
+ if (typeof testCtx.beginModuleScope === "function") {
143
+ testScope = await createHeldScope(testCtx);
144
+ debugLog("test held scope created");
145
+ }
146
+ this.taskScopeMap.set(test.id, {
147
+ testScope,
148
+ filepath
149
+ });
150
+ }
151
+ }
152
+ await super.onBeforeTryTask(test);
153
+ }
154
+ async onAfterRunTask(test) {
155
+ const taskState = this.taskScopeMap.get(test.id);
156
+ if (taskState) {
157
+ debugLog(`onAfterRunTask: ${test.name}`);
158
+ await releaseHeldScope(taskState.testScope);
159
+ this.taskScopeMap.delete(test.id);
160
+ const fileState = this.fileScopeMap.get(taskState.filepath);
161
+ if (fileState) {
162
+ await restoreEggMocksIfNeeded(fileState.config.restoreMocks);
163
+ fileState.app.ctxStorage.enterWith(fileState.suiteCtx);
164
+ debugLog("restored suite context");
165
+ }
166
+ }
167
+ await super.onAfterRunTask(test);
168
+ }
169
+ };
170
+
171
+ //#endregion
172
+ export { TeggVitestRunner as default };
@@ -0,0 +1,29 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { Application } from "egg";
3
+
4
+ //#region src/shared.d.ts
5
+ type EggMockApp = Application & {
6
+ ctxStorage?: {
7
+ getStore?: () => any;
8
+ enterWith?: (store: any) => void;
9
+ } & AsyncLocalStorage<any>;
10
+ mockContext?: (data?: any, options?: any) => any;
11
+ };
12
+ interface TeggVitestAdapterOptions {
13
+ /**
14
+ * Resolve app instance.
15
+ * Default: import('@eggjs/mock/bootstrap').app
16
+ */
17
+ getApp?: () => Promise<EggMockApp | undefined> | EggMockApp | undefined;
18
+ /**
19
+ * Restore mocks after each test.
20
+ * Default: true (calls @eggjs/mock.restore())
21
+ */
22
+ restoreMocks?: boolean;
23
+ }
24
+ declare const DEBUG_ENABLED: boolean;
25
+ declare function debugLog(message: string, extra?: unknown): void;
26
+ declare function defaultGetApp(): Promise<EggMockApp | undefined>;
27
+ declare function restoreEggMocksIfNeeded(restoreMocks: boolean): Promise<void>;
28
+ //#endregion
29
+ export { DEBUG_ENABLED, EggMockApp, TeggVitestAdapterOptions, debugLog, defaultGetApp, restoreEggMocksIfNeeded };
package/dist/shared.js ADDED
@@ -0,0 +1,22 @@
1
+ //#region src/shared.ts
2
+ const DEBUG_ENABLED = process.env.DEBUG_TEGG_VITEST === "1";
3
+ function debugLog(message, extra) {
4
+ if (!DEBUG_ENABLED) return;
5
+ if (extra === void 0) {
6
+ console.log(`[tegg-vitest] ${message}`);
7
+ return;
8
+ }
9
+ console.log(`[tegg-vitest] ${message}`, extra);
10
+ }
11
+ async function defaultGetApp() {
12
+ return (await import("@eggjs/mock/bootstrap"))?.app;
13
+ }
14
+ async function restoreEggMocksIfNeeded(restoreMocks) {
15
+ if (!restoreMocks) return;
16
+ const eggMock = await import("@eggjs/mock");
17
+ const mm = eggMock?.default || eggMock;
18
+ if (mm?.restore) await mm.restore();
19
+ }
20
+
21
+ //#endregion
22
+ export { DEBUG_ENABLED, debugLog, defaultGetApp, restoreEggMocksIfNeeded };
package/package.json CHANGED
@@ -1,31 +1,59 @@
1
1
  {
2
2
  "name": "@eggjs/tegg-vitest",
3
- "version": "0.0.0",
4
- "description": "egg logger",
3
+ "version": "4.0.1-beta.0",
4
+ "description": "Vitest adapter for tegg context injection",
5
5
  "keywords": [
6
+ "adapter",
6
7
  "egg",
7
- "logger"
8
+ "tegg",
9
+ "test",
10
+ "vitest"
8
11
  ],
9
- "homepage": "https://github.com/eggjs/egg/tree/next/packages/logger",
12
+ "homepage": "https://github.com/eggjs/egg/tree/next/tegg/core/vitest",
10
13
  "bugs": {
11
14
  "url": "https://github.com/eggjs/egg/issues"
12
15
  },
13
16
  "license": "MIT",
14
- "author": "fengmk2 <fengmk2@gmail.com> (https://github.com/fengmk2)",
17
+ "author": "killagu <killa123@126.com>",
15
18
  "repository": {
16
19
  "type": "git",
17
20
  "url": "git+https://github.com/eggjs/egg.git",
18
- "directory": "packages/logger"
21
+ "directory": "tegg/core/vitest"
22
+ },
23
+ "files": [
24
+ "dist"
25
+ ],
26
+ "type": "module",
27
+ "main": "./dist/index.js",
28
+ "module": "./dist/index.js",
29
+ "types": "./dist/index.d.ts",
30
+ "exports": {
31
+ ".": "./dist/index.js",
32
+ "./runner": "./dist/runner.js",
33
+ "./shared": "./dist/shared.js",
34
+ "./package.json": "./package.json"
19
35
  },
20
36
  "publishConfig": {
21
37
  "access": "public"
22
38
  },
23
39
  "dependencies": {
40
+ "@eggjs/mock": "7.0.1-beta.0"
24
41
  },
25
42
  "devDependencies": {
43
+ "@types/node": "^24.10.2",
44
+ "tsx": "4.20.6",
45
+ "typescript": "^5.9.3",
46
+ "vitest": "^4.0.15",
47
+ "@eggjs/core-decorator": "4.0.1-beta.0",
48
+ "egg": "4.1.1-beta.0"
49
+ },
50
+ "peerDependencies": {
51
+ "vitest": "^4.0.15"
26
52
  },
27
53
  "engines": {
28
- "node": ">= 22.18.0"
54
+ "node": ">=22.18.0"
55
+ },
56
+ "scripts": {
57
+ "typecheck": "tsgo --noEmit"
29
58
  }
30
- }
31
-
59
+ }