@tachybase/test 1.6.12 → 1.6.13-alpha.2

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/es/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import TachybaseGlobal from "@tachybase/globals";
1
+ import TachybaseGlobalModule from "@tachybase/globals";
2
2
  import { describe } from "vitest";
3
3
  import ws from "ws";
4
4
  import { mockDatabase } from "@tachybase/database";
@@ -8,6 +8,11 @@ import { default as default2 } from "supertest";
8
8
  import { Application, Gateway, AppSupervisor, PluginManager } from "@tego/core";
9
9
  import jwt from "jsonwebtoken";
10
10
  import qs from "qs";
11
+ import fs from "node:fs";
12
+ import { createRequire } from "node:module";
13
+ import os from "node:os";
14
+ import path from "node:path";
15
+ import { pathToFileURL } from "node:url";
11
16
  class MockServer extends Application {
12
17
  async loadAndInstall(options = {}) {
13
18
  await this.load({ method: "install" });
@@ -46,10 +51,11 @@ class MockServer extends Application {
46
51
  get(target, method, receiver) {
47
52
  if (["login", "loginUsingId"].includes(method)) {
48
53
  return (userOrId) => {
54
+ var _a;
49
55
  return proxy.auth(
50
56
  jwt.sign(
51
57
  {
52
- userId: typeof userOrId === "number" ? userOrId : userOrId == null ? void 0 : userOrId.id
58
+ userId: typeof userOrId === "number" ? userOrId : (userOrId == null ? void 0 : userOrId.id) ?? ((_a = userOrId == null ? void 0 : userOrId.get) == null ? void 0 : _a.call(userOrId, "id"))
53
59
  },
54
60
  process.env.APP_KEY,
55
61
  {
@@ -160,10 +166,449 @@ async function createMockServer(options = {}) {
160
166
  if (!skipStart) {
161
167
  await app.runCommandThrowError("start");
162
168
  }
169
+ if (!app.authManager.tokenController) {
170
+ app.authManager.setTokenControlService({
171
+ async getConfig() {
172
+ return {
173
+ tokenExpirationTime: 24 * 60 * 60 * 1e3,
174
+ sessionExpirationTime: 7 * 24 * 60 * 60 * 1e3,
175
+ expiredTokenRenewLimit: 24 * 60 * 60 * 1e3
176
+ };
177
+ },
178
+ async setConfig() {
179
+ },
180
+ async renew() {
181
+ return {
182
+ jti: `test-jti-${Date.now()}-${Math.random().toString(36).slice(2)}`,
183
+ issuedTime: Date.now()
184
+ };
185
+ },
186
+ async add({ userId }) {
187
+ return {
188
+ jti: `test-jti-${Date.now()}-${Math.random().toString(36).slice(2)}`,
189
+ userId,
190
+ issuedTime: Date.now(),
191
+ signInTime: Date.now(),
192
+ renewed: false
193
+ };
194
+ },
195
+ async removeSessionExpiredTokens() {
196
+ }
197
+ });
198
+ }
199
+ if (!app.authManager.userStatusService) {
200
+ app.authManager.setUserStatusService({
201
+ async checkUserStatus() {
202
+ return {
203
+ allowed: true,
204
+ status: "active",
205
+ isExpired: false
206
+ };
207
+ }
208
+ });
209
+ }
163
210
  return app;
164
211
  }
165
- const pgOnly = () => TachybaseGlobal.settings.database.dialect === "postgres" ? describe : describe.skip;
166
- const isPg = () => TachybaseGlobal.settings.database.dialect === "postgres";
212
+ const runtimeRequire = createRequire(path.resolve(process.cwd(), "package.json"));
213
+ const workspacePluginNameAliases = {
214
+ map: "block-map"
215
+ };
216
+ const ImportedTachybaseGlobal = TachybaseGlobalModule.getInstance ? TachybaseGlobalModule : TachybaseGlobalModule.default;
217
+ const testUnsafeBuiltinPlugins = /* @__PURE__ */ new Set(["event-source", "worker-thread"]);
218
+ function createRuntimeRequire(workspaceRoot) {
219
+ const hostPackageJson = path.resolve(workspaceRoot, "package.json");
220
+ if (fs.existsSync(hostPackageJson)) {
221
+ return createRequire(hostPackageJson);
222
+ }
223
+ return runtimeRequire;
224
+ }
225
+ function getTachybaseGlobal(runtimeRequire2) {
226
+ try {
227
+ const tachybaseGlobalModule = runtimeRequire2("@tachybase/globals");
228
+ return tachybaseGlobalModule.getInstance ? tachybaseGlobalModule : tachybaseGlobalModule.default;
229
+ } catch (error) {
230
+ if (error.code === "MODULE_NOT_FOUND") {
231
+ return ImportedTachybaseGlobal;
232
+ }
233
+ throw error;
234
+ }
235
+ }
236
+ function getCoreModules(runtimeRequire2) {
237
+ const cores = [];
238
+ try {
239
+ cores.push(runtimeRequire2("@tego/core"));
240
+ } catch (error) {
241
+ if (error.code !== "MODULE_NOT_FOUND") {
242
+ throw error;
243
+ }
244
+ }
245
+ try {
246
+ cores.push(runtimeRequire2("@tego/server"));
247
+ const serverRequire = createRequire(runtimeRequire2.resolve("@tego/server/package.json"));
248
+ cores.push(serverRequire("@tego/core"));
249
+ } catch {
250
+ }
251
+ for (const mod of Object.values(runtimeRequire2.cache)) {
252
+ const exports = mod == null ? void 0 : mod.exports;
253
+ if ((exports == null ? void 0 : exports.Plugin) && (exports == null ? void 0 : exports.PluginManager)) {
254
+ cores.push(exports);
255
+ }
256
+ }
257
+ return [...new Set(cores)];
258
+ }
259
+ function createTestDbStorage() {
260
+ const testDbName = `test-${Date.now()}-${Math.random().toString(36).slice(2)}.sqlite`;
261
+ const testDbDir = path.join(os.tmpdir(), "tego-test");
262
+ fs.mkdirSync(testDbDir, { recursive: true });
263
+ return path.join(testDbDir, testDbName);
264
+ }
265
+ function workspacePackageNameByShortName(workspaceRoot, name, map) {
266
+ const normalizedName = workspacePluginNameAliases[name] || name;
267
+ const candidates = [map[name], map[normalizedName], `module-${normalizedName}`, `plugin-${normalizedName}`].filter(
268
+ Boolean
269
+ );
270
+ for (const packageDir of candidates) {
271
+ const packageJsonPath = path.resolve(workspaceRoot, "packages", packageDir, "package.json");
272
+ if (fs.existsSync(packageJsonPath)) {
273
+ const packageJson = runtimeRequire(packageJsonPath);
274
+ return packageJson.name;
275
+ }
276
+ }
277
+ return null;
278
+ }
279
+ function workspacePackageDirByPackageName(workspaceRoot, packageName, map = {}) {
280
+ if (!packageName) {
281
+ return null;
282
+ }
283
+ const mappedPackageDir = Object.values(map).find((packageDir2) => {
284
+ const packageJsonPath2 = path.resolve(workspaceRoot, "packages", packageDir2, "package.json");
285
+ return fs.existsSync(packageJsonPath2) && runtimeRequire(packageJsonPath2).name === packageName;
286
+ });
287
+ if (mappedPackageDir) {
288
+ return mappedPackageDir;
289
+ }
290
+ const packageDir = packageName.replace("@tachybase/", "");
291
+ const packageJsonPath = path.resolve(workspaceRoot, "packages", packageDir, "package.json");
292
+ return fs.existsSync(packageJsonPath) ? packageDir : null;
293
+ }
294
+ function workspaceServerEntry(workspaceRoot, packageDir) {
295
+ const sourceEntry = path.resolve(workspaceRoot, "packages", packageDir, "src/server/index.ts");
296
+ if (fs.existsSync(sourceEntry)) {
297
+ return sourceEntry;
298
+ }
299
+ const compiledEntry = path.resolve(workspaceRoot, "packages", packageDir, "dist/server/index.js");
300
+ return fs.existsSync(compiledEntry) ? compiledEntry : null;
301
+ }
302
+ function getModuleDefault(mod) {
303
+ var _a;
304
+ return ((_a = mod == null ? void 0 : mod.default) == null ? void 0 : _a.default) || (mod == null ? void 0 : mod.default) || mod;
305
+ }
306
+ function getServerTestEnvironmentOptions(core) {
307
+ return core.Plugin.__serverTestEnvironmentOptions;
308
+ }
309
+ function patchPluginRuntime(core, workspaceRoot, packageDirByPluginName) {
310
+ core.Plugin.__serverTestEnvironmentOptions = { workspaceRoot, packageDirByPluginName };
311
+ if (core.Plugin.prototype.__serverTestEnvironmentPatched) {
312
+ return;
313
+ }
314
+ const originalLoadCollections = core.Plugin.prototype.loadCollections;
315
+ core.Plugin.prototype.loadCollections = async function loadWorkspaceCollections() {
316
+ var _a, _b;
317
+ const currentOptions = getServerTestEnvironmentOptions(core);
318
+ const currentWorkspaceRoot = (currentOptions == null ? void 0 : currentOptions.workspaceRoot) || workspaceRoot;
319
+ const currentPackageDirByPluginName = (currentOptions == null ? void 0 : currentOptions.packageDirByPluginName) || packageDirByPluginName;
320
+ const packageDir = ((_a = this.options) == null ? void 0 : _a.workspaceSource) ? workspacePackageDirByPackageName(currentWorkspaceRoot, (_b = this.options) == null ? void 0 : _b.packageName, currentPackageDirByPluginName) : null;
321
+ if (!packageDir) {
322
+ return originalLoadCollections.call(this);
323
+ }
324
+ const sourceDirectory = path.resolve(currentWorkspaceRoot, "packages", packageDir, "src/server/collections");
325
+ const compiledDirectory = path.resolve(currentWorkspaceRoot, "packages", packageDir, "dist/server/collections");
326
+ const directory = fs.existsSync(compiledDirectory) ? compiledDirectory : sourceDirectory;
327
+ if (!fs.existsSync(directory)) {
328
+ return;
329
+ }
330
+ await this.db.import({
331
+ directory,
332
+ from: this.options.packageName
333
+ });
334
+ };
335
+ core.Plugin.prototype.__serverTestEnvironmentPatched = true;
336
+ }
337
+ function getPluginManagerOptions(PluginManager2) {
338
+ return PluginManager2.__serverTestEnvironmentOptions;
339
+ }
340
+ function patchPluginManager(core, options) {
341
+ const PluginManager2 = core.PluginManager;
342
+ PluginManager2.__serverTestEnvironmentOptions = options;
343
+ if (PluginManager2.__serverTestEnvironmentPatchVersion === 2) {
344
+ return;
345
+ }
346
+ const resolvePlugin = (PluginManager2.__serverTestEnvironmentOriginalResolvePlugin || PluginManager2.resolvePlugin).bind(PluginManager2);
347
+ const originalGetPackageName = (PluginManager2.__serverTestEnvironmentOriginalGetPackageName || PluginManager2.getPackageName).bind(PluginManager2);
348
+ const originalAdd = PluginManager2.__serverTestEnvironmentOriginalAdd || PluginManager2.prototype.add;
349
+ const originalEnable = PluginManager2.__serverTestEnvironmentOriginalEnable || PluginManager2.prototype.enable;
350
+ const originalInitRuntimePlugins = PluginManager2.__serverTestEnvironmentOriginalInitRuntimePlugins || PluginManager2.prototype.initRuntimePlugins;
351
+ const originalInitOtherPlugins = PluginManager2.__serverTestEnvironmentOriginalInitOtherPlugins || PluginManager2.prototype.initOtherPlugins;
352
+ PluginManager2.__serverTestEnvironmentOriginalResolvePlugin = resolvePlugin;
353
+ PluginManager2.__serverTestEnvironmentOriginalGetPackageName = originalGetPackageName;
354
+ PluginManager2.__serverTestEnvironmentOriginalAdd = originalAdd;
355
+ PluginManager2.__serverTestEnvironmentOriginalEnable = originalEnable;
356
+ PluginManager2.__serverTestEnvironmentOriginalInitRuntimePlugins = originalInitRuntimePlugins;
357
+ PluginManager2.__serverTestEnvironmentOriginalInitOtherPlugins = originalInitOtherPlugins;
358
+ const workspaceSourcePackages = /* @__PURE__ */ new Set();
359
+ PluginManager2.getPackageName = async (name) => {
360
+ const currentOptions = getPluginManagerOptions(PluginManager2);
361
+ const currentWorkspaceRoot = (currentOptions == null ? void 0 : currentOptions.workspaceRoot) || process.cwd();
362
+ const currentPackageDirByPluginName = (currentOptions == null ? void 0 : currentOptions.packageDirByPluginName) || {};
363
+ const workspacePackageName = workspacePackageNameByShortName(
364
+ currentWorkspaceRoot,
365
+ name,
366
+ currentPackageDirByPluginName
367
+ );
368
+ return workspacePackageName || originalGetPackageName(name);
369
+ };
370
+ PluginManager2.getPackageJson = async (packageName) => {
371
+ const currentOptions = getPluginManagerOptions(PluginManager2);
372
+ const currentWorkspaceRoot = (currentOptions == null ? void 0 : currentOptions.workspaceRoot) || process.cwd();
373
+ const currentPackageDirByPluginName = (currentOptions == null ? void 0 : currentOptions.packageDirByPluginName) || {};
374
+ const packageDir = workspacePackageDirByPackageName(
375
+ currentWorkspaceRoot,
376
+ packageName,
377
+ currentPackageDirByPluginName
378
+ );
379
+ if (packageDir) {
380
+ return runtimeRequire(path.resolve(currentWorkspaceRoot, "packages", packageDir, "package.json"));
381
+ }
382
+ return runtimeRequire(runtimeRequire.resolve(path.join(packageName, "package.json")));
383
+ };
384
+ PluginManager2.resolvePlugin = async (pluginName, isUpgrade = false, isPkg = false) => {
385
+ if (typeof pluginName !== "string") {
386
+ return pluginName;
387
+ }
388
+ const packageName = isPkg ? pluginName : await PluginManager2.getPackageName(pluginName);
389
+ if (workspaceSourcePackages.has(packageName)) {
390
+ const currentOptions = getPluginManagerOptions(PluginManager2);
391
+ const currentWorkspaceRoot = (currentOptions == null ? void 0 : currentOptions.workspaceRoot) || process.cwd();
392
+ const currentPackageDirByPluginName = (currentOptions == null ? void 0 : currentOptions.packageDirByPluginName) || {};
393
+ const packageDir = workspacePackageDirByPackageName(
394
+ currentWorkspaceRoot,
395
+ packageName,
396
+ currentPackageDirByPluginName
397
+ );
398
+ const entry = packageDir ? workspaceServerEntry(currentWorkspaceRoot, packageDir) : null;
399
+ if (entry) {
400
+ const mod = await import(pathToFileURL(entry).href);
401
+ return getModuleDefault(mod);
402
+ }
403
+ return resolvePlugin(packageName, isUpgrade, true);
404
+ }
405
+ return resolvePlugin(pluginName, isUpgrade, isPkg);
406
+ };
407
+ PluginManager2.prototype.initRuntimePlugins = async function initTestRuntimePlugins() {
408
+ const currentOptions = getPluginManagerOptions(PluginManager2);
409
+ if (currentOptions == null ? void 0 : currentOptions.disableRuntimePlugins) {
410
+ this["_initRuntimePlugins"] = true;
411
+ return;
412
+ }
413
+ return originalInitRuntimePlugins.call(this);
414
+ };
415
+ PluginManager2.prototype.initOtherPlugins = async function initTestOtherPlugins() {
416
+ const currentOptions = getPluginManagerOptions(PluginManager2);
417
+ if (currentOptions == null ? void 0 : currentOptions.disableOtherPlugins) {
418
+ this["_initOtherPlugins"] = true;
419
+ return;
420
+ }
421
+ return originalInitOtherPlugins.call(this);
422
+ };
423
+ PluginManager2.prototype.add = async function addWorkspaceSourcePlugin(plugin, pluginOptions = {}, insert = false, isUpgrade = false) {
424
+ if (typeof plugin === "string" && (pluginOptions == null ? void 0 : pluginOptions.workspaceSource) && (pluginOptions == null ? void 0 : pluginOptions.packageName)) {
425
+ const currentOptions = getPluginManagerOptions(PluginManager2);
426
+ const currentWorkspaceRoot = (currentOptions == null ? void 0 : currentOptions.workspaceRoot) || process.cwd();
427
+ const currentPackageDirByPluginName = (currentOptions == null ? void 0 : currentOptions.packageDirByPluginName) || {};
428
+ const packageDir = workspacePackageDirByPackageName(
429
+ currentWorkspaceRoot,
430
+ pluginOptions.packageName,
431
+ currentPackageDirByPluginName
432
+ );
433
+ const entry = packageDir ? workspaceServerEntry(currentWorkspaceRoot, packageDir) : null;
434
+ if (entry) {
435
+ const mod = await import(pathToFileURL(entry).href);
436
+ return originalAdd.call(this, getModuleDefault(mod), pluginOptions, insert, isUpgrade);
437
+ }
438
+ }
439
+ return originalAdd.call(this, plugin, pluginOptions, insert, isUpgrade);
440
+ };
441
+ PluginManager2.prototype.enable = async function enableWorkspacePlugin(name) {
442
+ const normalize = (pluginName) => workspacePluginNameAliases[pluginName] || pluginName;
443
+ const normalizedName = Array.isArray(name) ? name.map(normalize) : normalize(name);
444
+ return originalEnable.call(this, normalizedName);
445
+ };
446
+ PluginManager2.prototype.initPresetPlugins = async function initWorkspacePresetPlugins() {
447
+ var _a, _b;
448
+ if (this["_initPresetPlugins"]) {
449
+ return;
450
+ }
451
+ const addWorkspacePlugin = async (pluginName, pluginOptions = {}) => {
452
+ const normalizedPluginName = typeof pluginName === "string" ? workspacePluginNameAliases[pluginName] || pluginName : pluginName;
453
+ const currentOptions = getPluginManagerOptions(PluginManager2);
454
+ const currentWorkspaceRoot = (currentOptions == null ? void 0 : currentOptions.workspaceRoot) || process.cwd();
455
+ const currentPackageDirByPluginName = (currentOptions == null ? void 0 : currentOptions.packageDirByPluginName) || {};
456
+ const packageName = typeof pluginName === "string" ? workspacePackageNameByShortName(currentWorkspaceRoot, pluginName, currentPackageDirByPluginName) : null;
457
+ if (packageName) {
458
+ workspaceSourcePackages.add(packageName);
459
+ const packageDir = workspacePackageDirByPackageName(
460
+ currentWorkspaceRoot,
461
+ packageName,
462
+ currentPackageDirByPluginName
463
+ );
464
+ const entry = packageDir ? workspaceServerEntry(currentWorkspaceRoot, packageDir) : null;
465
+ if (entry) {
466
+ const mod = await import(pathToFileURL(entry).href);
467
+ const P = getModuleDefault(mod);
468
+ await this.add(P, {
469
+ name: pluginName,
470
+ ...pluginOptions,
471
+ packageName,
472
+ workspaceSource: true
473
+ });
474
+ } else {
475
+ await this.add(normalizedPluginName, {
476
+ name: pluginName,
477
+ ...pluginOptions,
478
+ packageName,
479
+ workspaceSource: true
480
+ });
481
+ }
482
+ } else if (typeof pluginName === "function") {
483
+ await this.add(pluginName, pluginOptions);
484
+ } else {
485
+ await this.add(normalizedPluginName, { name: pluginName, isPreset: true, ...pluginOptions });
486
+ }
487
+ };
488
+ const addTachybasePresetPlugin = async (pluginName, pluginOptions = {}) => {
489
+ if (testUnsafeBuiltinPlugins.has(pluginName)) {
490
+ return;
491
+ }
492
+ await addWorkspacePlugin(pluginName, { enabled: true, ...pluginOptions });
493
+ };
494
+ const addTachybaseExternalPlugin = async (plugin, pluginOptions = {}) => {
495
+ const pluginName = typeof plugin === "string" ? plugin : plugin == null ? void 0 : plugin.name;
496
+ if (!pluginName || testUnsafeBuiltinPlugins.has(pluginName)) {
497
+ return;
498
+ }
499
+ await addWorkspacePlugin(pluginName, { enabled: !!(plugin == null ? void 0 : plugin.enabledByDefault), ...pluginOptions });
500
+ };
501
+ for (const plugin of this.options.plugins || []) {
502
+ const [pluginName, pluginOptions = {}] = Array.isArray(plugin) ? plugin : [plugin];
503
+ if (pluginName === "tachybase") {
504
+ const currentOptions = getPluginManagerOptions(PluginManager2);
505
+ const currentSettings = (currentOptions == null ? void 0 : currentOptions.settings) || options.settings;
506
+ for (const builtinPlugin of ((_a = currentSettings == null ? void 0 : currentSettings.presets) == null ? void 0 : _a.builtinPlugins) || []) {
507
+ await addTachybasePresetPlugin(builtinPlugin, pluginOptions);
508
+ }
509
+ for (const externalPlugin of ((_b = currentSettings == null ? void 0 : currentSettings.presets) == null ? void 0 : _b.externalPlugins) || []) {
510
+ await addTachybaseExternalPlugin(externalPlugin, pluginOptions);
511
+ }
512
+ continue;
513
+ }
514
+ await addWorkspacePlugin(pluginName, { enabled: true, ...pluginOptions });
515
+ }
516
+ this["_initPresetPlugins"] = true;
517
+ };
518
+ PluginManager2.__serverTestEnvironmentPatchVersion = 2;
519
+ PluginManager2.__serverTestEnvironmentPatchOptions = options;
520
+ PluginManager2.findPackagePatched = true;
521
+ }
522
+ function patchAppSupervisor(core, options) {
523
+ const AppSupervisor2 = core.AppSupervisor;
524
+ if (!(AppSupervisor2 == null ? void 0 : AppSupervisor2.getInstance)) {
525
+ return;
526
+ }
527
+ AppSupervisor2.__serverTestEnvironmentOptions = options;
528
+ if (AppSupervisor2.__serverTestEnvironmentPatchVersion === 1) {
529
+ return;
530
+ }
531
+ const supervisor = AppSupervisor2.getInstance();
532
+ const originalAddApp = supervisor.addApp.bind(supervisor);
533
+ supervisor.addApp = (app) => {
534
+ var _a;
535
+ if ((_a = app == null ? void 0 : app.pm) == null ? void 0 : _a.constructor) {
536
+ patchPluginManager(
537
+ {
538
+ PluginManager: app.pm.constructor
539
+ },
540
+ AppSupervisor2.__serverTestEnvironmentOptions
541
+ );
542
+ }
543
+ return originalAddApp(app);
544
+ };
545
+ AppSupervisor2.__serverTestEnvironmentPatchVersion = 1;
546
+ }
547
+ function setupServerTestEnvironment(options = {}) {
548
+ var _a;
549
+ const workspaceRoot = options.workspaceRoot || process.cwd();
550
+ const pluginPaths = options.pluginPaths || [];
551
+ const packageDirByPluginName = options.packageDirByPluginName || {};
552
+ const runtimeRequire2 = createRuntimeRequire(workspaceRoot);
553
+ const TachybaseGlobal = getTachybaseGlobal(runtimeRequire2);
554
+ const settings = runtimeRequire2("tego/presets/settings");
555
+ const testSettings = {
556
+ ...settings,
557
+ env: {
558
+ ...settings.env,
559
+ APP_ENV: "test"
560
+ },
561
+ logger: {
562
+ ...settings.logger,
563
+ level: "error"
564
+ },
565
+ database: {
566
+ dialect: ((_a = settings.database) == null ? void 0 : _a.dialect) || "sqlite",
567
+ ...settings.database,
568
+ storage: createTestDbStorage()
569
+ },
570
+ presets: {
571
+ ...settings.presets,
572
+ runtimePlugins: options.disableRuntimePlugins ? [] : settings.presets.runtimePlugins
573
+ }
574
+ };
575
+ ImportedTachybaseGlobal.settings = testSettings;
576
+ TachybaseGlobal.settings = testSettings;
577
+ ImportedTachybaseGlobal.getInstance().set("PLUGIN_PATHS", pluginPaths);
578
+ TachybaseGlobal.getInstance().set("PLUGIN_PATHS", pluginPaths);
579
+ process.env.TEGO_RUNTIME_HOME = path.join(os.tmpdir(), "test-sqlite");
580
+ process.env.APP_ENV_PATH = process.env.APP_ENV_PATH || ".env.test";
581
+ const coreModules = getCoreModules(runtimeRequire2);
582
+ for (const core of coreModules) {
583
+ patchPluginRuntime(core, workspaceRoot, packageDirByPluginName);
584
+ patchPluginManager(core, {
585
+ ...options,
586
+ workspaceRoot,
587
+ packageDirByPluginName,
588
+ settings: testSettings
589
+ });
590
+ patchAppSupervisor(core, {
591
+ ...options,
592
+ workspaceRoot,
593
+ packageDirByPluginName,
594
+ settings: testSettings
595
+ });
596
+ }
597
+ }
598
+ const noopDescribe = () => {
599
+ };
600
+ const pgOnly = () => {
601
+ var _a, _b;
602
+ const isPostgres = ((_b = (_a = TachybaseGlobalModule.settings) == null ? void 0 : _a.database) == null ? void 0 : _b.dialect) === "postgres";
603
+ if (isPostgres) {
604
+ return describe || noopDescribe;
605
+ }
606
+ return describe.skip || noopDescribe;
607
+ };
608
+ const isPg = () => {
609
+ var _a, _b;
610
+ return ((_b = (_a = TachybaseGlobalModule.settings) == null ? void 0 : _a.database) == null ? void 0 : _b.dialect) === "postgres";
611
+ };
167
612
  function randomStr() {
168
613
  return Math.random().toString(36).substring(2);
169
614
  }
@@ -217,6 +662,7 @@ export {
217
662
  mockServer,
218
663
  pgOnly,
219
664
  randomStr,
665
+ setupServerTestEnvironment,
220
666
  startMockServer,
221
667
  startServerWithRandomPort,
222
668
  default2 as supertest,
@@ -1,6 +1,7 @@
1
1
  export { mockDatabase } from '@tachybase/database';
2
2
  export { default as supertest } from 'supertest';
3
3
  export * from './mockServer';
4
+ export * from './setupTestEnvironment';
4
5
  export declare const pgOnly: () => any;
5
6
  export declare const isPg: () => boolean;
6
7
  export declare function randomStr(): string;
@@ -0,0 +1,8 @@
1
+ export interface ServerTestEnvironmentOptions {
2
+ workspaceRoot?: string;
3
+ pluginPaths?: string[];
4
+ packageDirByPluginName?: Record<string, string>;
5
+ disableRuntimePlugins?: boolean;
6
+ disableOtherPlugins?: boolean;
7
+ }
8
+ export declare function setupServerTestEnvironment(options?: ServerTestEnvironmentOptions): void;
@@ -0,0 +1 @@
1
+ export * from './server/setupTestEnvironment';
package/es/vitest.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ export interface TegoVitestConfigOptions {
2
+ server?: {
3
+ setupFile?: string;
4
+ };
5
+ client?: {
6
+ setupFile?: string;
7
+ };
8
+ }
9
+ export declare function defineTegoVitestConfig(options?: TegoVitestConfigOptions): import("vite").UserConfig & Promise<import("vite").UserConfig> & (import("vitest/config.js").UserConfigFnObject & import("vitest/config.js").UserConfigExport);
10
+ declare const _default: import("vite").UserConfig & Promise<import("vite").UserConfig> & (import("vitest/config.js").UserConfigFnObject & import("vitest/config.js").UserConfigExport);
11
+ export default _default;
package/es/vitest.mjs ADDED
@@ -0,0 +1,137 @@
1
+ import fs from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import path, { resolve } from "node:path";
4
+ import react from "@vitejs/plugin-react";
5
+ import { defineConfig } from "vitest/config";
6
+ const runtimeRequire = createRequire(path.resolve(process.cwd(), "package.json"));
7
+ const packageRoot = fs.existsSync(path.resolve(process.cwd(), "packages/test/package.json")) ? path.resolve(process.cwd(), "packages/test") : path.dirname(runtimeRequire.resolve("@tachybase/test/package.json"));
8
+ const relativePathToAbsolute = (relativePath) => {
9
+ return path.resolve(process.cwd(), relativePath);
10
+ };
11
+ function tsConfigPathsToAlias() {
12
+ var _a;
13
+ const alias = [
14
+ {
15
+ find: "@tachybase/utils/plugin-symlink",
16
+ replacement: "node_modules/@tachybase/utils/plugin-symlink.js"
17
+ },
18
+ {
19
+ find: "@opentelemetry/resources",
20
+ replacement: "node_modules/@opentelemetry/resources/build/src/index.js"
21
+ }
22
+ ];
23
+ try {
24
+ const json = JSON.parse(
25
+ fs.readFileSync(path.resolve(process.cwd(), "./tsconfig.paths.json"), { encoding: "utf8" })
26
+ );
27
+ const paths = ((_a = json.compilerOptions) == null ? void 0 : _a.paths) || {};
28
+ alias.push(
29
+ ...Object.keys(paths).reduce((acc, key) => {
30
+ var _a2;
31
+ if (key !== "@@/*") {
32
+ const value = (_a2 = paths[key]) == null ? void 0 : _a2[0];
33
+ if (value) {
34
+ acc.push({
35
+ find: key,
36
+ replacement: value
37
+ });
38
+ }
39
+ }
40
+ return acc;
41
+ }, [])
42
+ );
43
+ } catch {
44
+ }
45
+ return [
46
+ { find: /^~antd\/(.*)/, replacement: "antd/$1" },
47
+ ...alias.map((item) => {
48
+ return {
49
+ ...item,
50
+ replacement: relativePathToAbsolute(item.replacement)
51
+ };
52
+ })
53
+ ];
54
+ }
55
+ function defineTegoVitestConfig(options = {}) {
56
+ var _a, _b;
57
+ const serverSetupFile = ((_a = options.server) == null ? void 0 : _a.setupFile) || resolve(packageRoot, "./setup/server.ts");
58
+ const clientSetupFiles = [resolve(packageRoot, "./setup/client.ts"), (_b = options.client) == null ? void 0 : _b.setupFile].filter(Boolean);
59
+ return defineConfig({
60
+ test: {
61
+ testTimeout: 6e4,
62
+ hookTimeout: 6e4,
63
+ coverage: {
64
+ provider: "v8",
65
+ reporter: ["text", "json-summary", "json"],
66
+ reportOnFailure: true,
67
+ thresholds: {
68
+ lines: 60,
69
+ branches: 60,
70
+ functions: 80,
71
+ statements: 80
72
+ }
73
+ },
74
+ silent: !!process.env.GITHUB_ACTIONS,
75
+ globals: true,
76
+ alias: tsConfigPathsToAlias(),
77
+ projects: [
78
+ {
79
+ root: process.cwd(),
80
+ resolve: {
81
+ mainFields: ["module"]
82
+ },
83
+ extends: true,
84
+ test: {
85
+ name: "server",
86
+ setupFiles: serverSetupFile,
87
+ include: ["packages/**/__tests__/**/*.test.ts", "apps/**/__tests__/**/*.test.ts"],
88
+ exclude: [
89
+ "**/node_modules/**",
90
+ "**/dist/**",
91
+ "**/lib/**",
92
+ "**/es/**",
93
+ "**/e2e/**",
94
+ "**/__e2e__/**",
95
+ "**/{vitest,commitlint}.config.*",
96
+ "packages/**/{sdk,client,schema,components}/**/__tests__/**/*.{test,spec}.{ts,tsx}"
97
+ ]
98
+ }
99
+ },
100
+ {
101
+ // @ts-ignore
102
+ plugins: [react()],
103
+ resolve: {
104
+ mainFields: ["module"]
105
+ },
106
+ define: {
107
+ "process.env.__TEST__": true,
108
+ "process.env.__E2E__": false
109
+ },
110
+ test: {
111
+ name: "client",
112
+ globals: true,
113
+ setupFiles: clientSetupFiles,
114
+ environment: "jsdom",
115
+ css: false,
116
+ alias: tsConfigPathsToAlias(),
117
+ include: ["packages/**/{sdk,client,schema,components}/**/__tests__/**/*.{test,spec}.{ts,tsx}"],
118
+ exclude: [
119
+ "**/node_modules/**",
120
+ "**/dist/**",
121
+ "**/lib/**",
122
+ "**/es/**",
123
+ "**/e2e/**",
124
+ "**/__e2e__/**",
125
+ "**/{vitest,commitlint}.config.*"
126
+ ]
127
+ }
128
+ }
129
+ ]
130
+ }
131
+ });
132
+ }
133
+ const vitest = defineTegoVitestConfig();
134
+ export {
135
+ vitest as default,
136
+ defineTegoVitestConfig
137
+ };
@@ -1,6 +1,7 @@
1
1
  export { mockDatabase } from '@tachybase/database';
2
2
  export { default as supertest } from 'supertest';
3
3
  export * from './mockServer';
4
+ export * from './setupTestEnvironment';
4
5
  export declare const pgOnly: () => any;
5
6
  export declare const isPg: () => boolean;
6
7
  export declare function randomStr(): string;