@tachybase/test 1.6.12 → 1.6.13-alpha.3

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,5 +1,4 @@
1
- import TachybaseGlobal from "@tachybase/globals";
2
- import { describe } from "vitest";
1
+ import TachybaseGlobalModule from "@tachybase/globals";
3
2
  import ws from "ws";
4
3
  import { mockDatabase } from "@tachybase/database";
5
4
  import { mockDatabase as mockDatabase2 } from "@tachybase/database";
@@ -8,6 +7,11 @@ import { default as default2 } from "supertest";
8
7
  import { Application, Gateway, AppSupervisor, PluginManager } from "@tego/core";
9
8
  import jwt from "jsonwebtoken";
10
9
  import qs from "qs";
10
+ import fs from "node:fs";
11
+ import { createRequire } from "node:module";
12
+ import os from "node:os";
13
+ import path from "node:path";
14
+ import { pathToFileURL } from "node:url";
11
15
  class MockServer extends Application {
12
16
  async loadAndInstall(options = {}) {
13
17
  await this.load({ method: "install" });
@@ -46,10 +50,11 @@ class MockServer extends Application {
46
50
  get(target, method, receiver) {
47
51
  if (["login", "loginUsingId"].includes(method)) {
48
52
  return (userOrId) => {
53
+ var _a;
49
54
  return proxy.auth(
50
55
  jwt.sign(
51
56
  {
52
- userId: typeof userOrId === "number" ? userOrId : userOrId == null ? void 0 : userOrId.id
57
+ 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
58
  },
54
59
  process.env.APP_KEY,
55
60
  {
@@ -160,10 +165,459 @@ async function createMockServer(options = {}) {
160
165
  if (!skipStart) {
161
166
  await app.runCommandThrowError("start");
162
167
  }
168
+ if (!app.authManager.tokenController) {
169
+ app.authManager.setTokenControlService({
170
+ async getConfig() {
171
+ return {
172
+ tokenExpirationTime: 24 * 60 * 60 * 1e3,
173
+ sessionExpirationTime: 7 * 24 * 60 * 60 * 1e3,
174
+ expiredTokenRenewLimit: 24 * 60 * 60 * 1e3
175
+ };
176
+ },
177
+ async setConfig() {
178
+ },
179
+ async renew() {
180
+ return {
181
+ jti: `test-jti-${Date.now()}-${Math.random().toString(36).slice(2)}`,
182
+ issuedTime: Date.now()
183
+ };
184
+ },
185
+ async add({ userId }) {
186
+ return {
187
+ jti: `test-jti-${Date.now()}-${Math.random().toString(36).slice(2)}`,
188
+ userId,
189
+ issuedTime: Date.now(),
190
+ signInTime: Date.now(),
191
+ renewed: false
192
+ };
193
+ },
194
+ async removeSessionExpiredTokens() {
195
+ }
196
+ });
197
+ }
198
+ if (!app.authManager.userStatusService) {
199
+ app.authManager.setUserStatusService({
200
+ async checkUserStatus() {
201
+ return {
202
+ allowed: true,
203
+ status: "active",
204
+ isExpired: false
205
+ };
206
+ }
207
+ });
208
+ }
163
209
  return app;
164
210
  }
165
- const pgOnly = () => TachybaseGlobal.settings.database.dialect === "postgres" ? describe : describe.skip;
166
- const isPg = () => TachybaseGlobal.settings.database.dialect === "postgres";
211
+ const runtimeRequire = createRequire(path.resolve(process.cwd(), "package.json"));
212
+ const selfRequire = createRequire(require.resolve("@tachybase/test/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() {
237
+ const cores = [];
238
+ try {
239
+ cores.push(selfRequire("@tego/core"));
240
+ } catch (e) {
241
+ if ((e == null ? void 0 : e.code) !== "MODULE_NOT_FOUND") throw e;
242
+ }
243
+ try {
244
+ cores.push(selfRequire("@tego/server"));
245
+ cores.push(createRequire(selfRequire.resolve("@tego/server/package.json"))("@tego/core"));
246
+ } catch (e) {
247
+ if ((e == null ? void 0 : e.code) !== "MODULE_NOT_FOUND") throw e;
248
+ }
249
+ return [...new Set(cores)];
250
+ }
251
+ function createTestDbStorage() {
252
+ const testDbName = `test-${Date.now()}-${Math.random().toString(36).slice(2)}.sqlite`;
253
+ const testDbDir = path.join(os.tmpdir(), "tego-test");
254
+ fs.mkdirSync(testDbDir, { recursive: true });
255
+ return path.join(testDbDir, testDbName);
256
+ }
257
+ function workspacePackageNameByShortName(workspaceRoot, name, map) {
258
+ const normalizedName = workspacePluginNameAliases[name] || name;
259
+ const candidates = [map[name], map[normalizedName], `module-${normalizedName}`, `plugin-${normalizedName}`].filter(
260
+ Boolean
261
+ );
262
+ for (const packageDir of candidates) {
263
+ const packageJsonPath = path.resolve(workspaceRoot, "packages", packageDir, "package.json");
264
+ if (fs.existsSync(packageJsonPath)) {
265
+ const packageJson = runtimeRequire(packageJsonPath);
266
+ return packageJson.name;
267
+ }
268
+ }
269
+ return null;
270
+ }
271
+ function workspacePackageDirByPackageName(workspaceRoot, packageName, map = {}) {
272
+ if (!packageName) {
273
+ return null;
274
+ }
275
+ const mappedPackageDir = Object.values(map).find((packageDir2) => {
276
+ const packageJsonPath2 = path.resolve(workspaceRoot, "packages", packageDir2, "package.json");
277
+ return fs.existsSync(packageJsonPath2) && runtimeRequire(packageJsonPath2).name === packageName;
278
+ });
279
+ if (mappedPackageDir) {
280
+ return mappedPackageDir;
281
+ }
282
+ const packageDir = packageName.replace("@tachybase/", "");
283
+ const packageJsonPath = path.resolve(workspaceRoot, "packages", packageDir, "package.json");
284
+ return fs.existsSync(packageJsonPath) ? packageDir : null;
285
+ }
286
+ function workspaceServerEntry(workspaceRoot, packageDir) {
287
+ const libEntry = path.resolve(workspaceRoot, "packages", packageDir, "lib/server/index.js");
288
+ if (fs.existsSync(libEntry)) {
289
+ return libEntry;
290
+ }
291
+ const distEntry = path.resolve(workspaceRoot, "packages", packageDir, "dist/server/index.js");
292
+ if (fs.existsSync(distEntry)) {
293
+ return distEntry;
294
+ }
295
+ const sourceEntry = path.resolve(workspaceRoot, "packages", packageDir, "src/server/index.ts");
296
+ if (fs.existsSync(sourceEntry)) {
297
+ return sourceEntry;
298
+ }
299
+ return null;
300
+ }
301
+ function getModuleDefault(mod) {
302
+ var _a;
303
+ return ((_a = mod == null ? void 0 : mod.default) == null ? void 0 : _a.default) || (mod == null ? void 0 : mod.default) || mod;
304
+ }
305
+ function getServerTestEnvironmentOptions(core) {
306
+ return core.Plugin.__serverTestEnvironmentOptions;
307
+ }
308
+ function patchPluginRuntime(core, workspaceRoot, packageDirByPluginName) {
309
+ core.Plugin.__serverTestEnvironmentOptions = { workspaceRoot, packageDirByPluginName };
310
+ if (core.Plugin.prototype.__serverTestEnvironmentPatched) {
311
+ return;
312
+ }
313
+ const originalLoadCollections = core.Plugin.prototype.loadCollections;
314
+ core.Plugin.prototype.loadCollections = async function loadWorkspaceCollections() {
315
+ var _a, _b;
316
+ const currentOptions = getServerTestEnvironmentOptions(core);
317
+ const currentWorkspaceRoot = (currentOptions == null ? void 0 : currentOptions.workspaceRoot) || workspaceRoot;
318
+ const currentPackageDirByPluginName = (currentOptions == null ? void 0 : currentOptions.packageDirByPluginName) || packageDirByPluginName;
319
+ const packageDir = ((_a = this.options) == null ? void 0 : _a.workspaceSource) ? workspacePackageDirByPackageName(currentWorkspaceRoot, (_b = this.options) == null ? void 0 : _b.packageName, currentPackageDirByPluginName) : null;
320
+ if (!packageDir) {
321
+ return originalLoadCollections.call(this);
322
+ }
323
+ const sourceDirectory = path.resolve(currentWorkspaceRoot, "packages", packageDir, "src/server/collections");
324
+ const compiledDirectory = path.resolve(currentWorkspaceRoot, "packages", packageDir, "dist/server/collections");
325
+ const directory = fs.existsSync(compiledDirectory) ? compiledDirectory : sourceDirectory;
326
+ if (!fs.existsSync(directory)) {
327
+ return;
328
+ }
329
+ await this.db.import({
330
+ directory,
331
+ from: this.options.packageName
332
+ });
333
+ };
334
+ core.Plugin.prototype.__serverTestEnvironmentPatched = true;
335
+ }
336
+ function getPluginManagerOptions(PluginManager2) {
337
+ return PluginManager2.__serverTestEnvironmentOptions;
338
+ }
339
+ function patchPluginManager(core, options) {
340
+ const PluginManager2 = core.PluginManager;
341
+ PluginManager2.__serverTestEnvironmentOptions = options;
342
+ if (PluginManager2.__serverTestEnvironmentPatchVersion === 2) {
343
+ return;
344
+ }
345
+ const resolvePlugin = (PluginManager2.__serverTestEnvironmentOriginalResolvePlugin || PluginManager2.resolvePlugin).bind(PluginManager2);
346
+ const originalGetPackageName = (PluginManager2.__serverTestEnvironmentOriginalGetPackageName || PluginManager2.getPackageName).bind(PluginManager2);
347
+ const originalAdd = PluginManager2.__serverTestEnvironmentOriginalAdd || PluginManager2.prototype.add;
348
+ const originalEnable = PluginManager2.__serverTestEnvironmentOriginalEnable || PluginManager2.prototype.enable;
349
+ const originalInitRuntimePlugins = PluginManager2.__serverTestEnvironmentOriginalInitRuntimePlugins || PluginManager2.prototype.initRuntimePlugins;
350
+ const originalInitOtherPlugins = PluginManager2.__serverTestEnvironmentOriginalInitOtherPlugins || PluginManager2.prototype.initOtherPlugins;
351
+ PluginManager2.__serverTestEnvironmentOriginalResolvePlugin = resolvePlugin;
352
+ PluginManager2.__serverTestEnvironmentOriginalGetPackageName = originalGetPackageName;
353
+ PluginManager2.__serverTestEnvironmentOriginalAdd = originalAdd;
354
+ PluginManager2.__serverTestEnvironmentOriginalEnable = originalEnable;
355
+ PluginManager2.__serverTestEnvironmentOriginalInitRuntimePlugins = originalInitRuntimePlugins;
356
+ PluginManager2.__serverTestEnvironmentOriginalInitOtherPlugins = originalInitOtherPlugins;
357
+ const workspaceSourcePackages = /* @__PURE__ */ new Set();
358
+ PluginManager2.getPackageName = async (name) => {
359
+ const currentOptions = getPluginManagerOptions(PluginManager2);
360
+ const currentWorkspaceRoot = (currentOptions == null ? void 0 : currentOptions.workspaceRoot) || process.cwd();
361
+ const currentPackageDirByPluginName = (currentOptions == null ? void 0 : currentOptions.packageDirByPluginName) || {};
362
+ const workspacePackageName = workspacePackageNameByShortName(
363
+ currentWorkspaceRoot,
364
+ name,
365
+ currentPackageDirByPluginName
366
+ );
367
+ return workspacePackageName || originalGetPackageName(name);
368
+ };
369
+ PluginManager2.getPackageJson = async (packageName) => {
370
+ const currentOptions = getPluginManagerOptions(PluginManager2);
371
+ const currentWorkspaceRoot = (currentOptions == null ? void 0 : currentOptions.workspaceRoot) || process.cwd();
372
+ const currentPackageDirByPluginName = (currentOptions == null ? void 0 : currentOptions.packageDirByPluginName) || {};
373
+ const packageDir = workspacePackageDirByPackageName(
374
+ currentWorkspaceRoot,
375
+ packageName,
376
+ currentPackageDirByPluginName
377
+ );
378
+ if (packageDir) {
379
+ return runtimeRequire(path.resolve(currentWorkspaceRoot, "packages", packageDir, "package.json"));
380
+ }
381
+ return runtimeRequire(runtimeRequire.resolve(path.join(packageName, "package.json")));
382
+ };
383
+ PluginManager2.resolvePlugin = async (pluginName, isUpgrade = false, isPkg = false) => {
384
+ if (typeof pluginName !== "string") {
385
+ return pluginName;
386
+ }
387
+ const packageName = isPkg ? pluginName : await PluginManager2.getPackageName(pluginName);
388
+ if (workspaceSourcePackages.has(packageName)) {
389
+ const currentOptions = getPluginManagerOptions(PluginManager2);
390
+ const currentWorkspaceRoot = (currentOptions == null ? void 0 : currentOptions.workspaceRoot) || process.cwd();
391
+ const currentPackageDirByPluginName = (currentOptions == null ? void 0 : currentOptions.packageDirByPluginName) || {};
392
+ const packageDir = workspacePackageDirByPackageName(
393
+ currentWorkspaceRoot,
394
+ packageName,
395
+ currentPackageDirByPluginName
396
+ );
397
+ const entry = packageDir ? workspaceServerEntry(currentWorkspaceRoot, packageDir) : null;
398
+ if (entry) {
399
+ const mod = await import(pathToFileURL(entry).href);
400
+ return getModuleDefault(mod);
401
+ }
402
+ return resolvePlugin(packageName, isUpgrade, true);
403
+ }
404
+ return resolvePlugin(pluginName, isUpgrade, isPkg);
405
+ };
406
+ PluginManager2.prototype.initRuntimePlugins = async function initTestRuntimePlugins() {
407
+ const currentOptions = getPluginManagerOptions(PluginManager2);
408
+ if (currentOptions == null ? void 0 : currentOptions.disableRuntimePlugins) {
409
+ this["_initRuntimePlugins"] = true;
410
+ return;
411
+ }
412
+ return originalInitRuntimePlugins.call(this);
413
+ };
414
+ PluginManager2.prototype.initOtherPlugins = async function initTestOtherPlugins() {
415
+ const currentOptions = getPluginManagerOptions(PluginManager2);
416
+ if (currentOptions == null ? void 0 : currentOptions.disableOtherPlugins) {
417
+ this["_initOtherPlugins"] = true;
418
+ return;
419
+ }
420
+ return originalInitOtherPlugins.call(this);
421
+ };
422
+ PluginManager2.prototype.add = async function addWorkspaceSourcePlugin(plugin, pluginOptions = {}, insert = false, isUpgrade = false) {
423
+ if (typeof plugin === "string" && (pluginOptions == null ? void 0 : pluginOptions.workspaceSource) && (pluginOptions == null ? void 0 : pluginOptions.packageName)) {
424
+ const currentOptions = getPluginManagerOptions(PluginManager2);
425
+ const currentWorkspaceRoot = (currentOptions == null ? void 0 : currentOptions.workspaceRoot) || process.cwd();
426
+ const currentPackageDirByPluginName = (currentOptions == null ? void 0 : currentOptions.packageDirByPluginName) || {};
427
+ const packageDir = workspacePackageDirByPackageName(
428
+ currentWorkspaceRoot,
429
+ pluginOptions.packageName,
430
+ currentPackageDirByPluginName
431
+ );
432
+ const entry = packageDir ? workspaceServerEntry(currentWorkspaceRoot, packageDir) : null;
433
+ if (entry) {
434
+ const mod = await import(pathToFileURL(entry).href);
435
+ return originalAdd.call(this, getModuleDefault(mod), pluginOptions, insert, isUpgrade);
436
+ }
437
+ }
438
+ return originalAdd.call(this, plugin, pluginOptions, insert, isUpgrade);
439
+ };
440
+ PluginManager2.prototype.enable = async function enableWorkspacePlugin(name) {
441
+ const normalize = (pluginName) => workspacePluginNameAliases[pluginName] || pluginName;
442
+ const normalizedName = Array.isArray(name) ? name.map(normalize) : normalize(name);
443
+ return originalEnable.call(this, normalizedName);
444
+ };
445
+ PluginManager2.prototype.initPresetPlugins = async function initWorkspacePresetPlugins() {
446
+ var _a, _b;
447
+ if (this["_initPresetPlugins"]) {
448
+ return;
449
+ }
450
+ const addWorkspacePlugin = async (pluginName, pluginOptions = {}) => {
451
+ const normalizedPluginName = typeof pluginName === "string" ? workspacePluginNameAliases[pluginName] || pluginName : pluginName;
452
+ const currentOptions = getPluginManagerOptions(PluginManager2);
453
+ const currentWorkspaceRoot = (currentOptions == null ? void 0 : currentOptions.workspaceRoot) || process.cwd();
454
+ const currentPackageDirByPluginName = (currentOptions == null ? void 0 : currentOptions.packageDirByPluginName) || {};
455
+ const packageName = typeof pluginName === "string" ? workspacePackageNameByShortName(currentWorkspaceRoot, pluginName, currentPackageDirByPluginName) : null;
456
+ if (packageName) {
457
+ workspaceSourcePackages.add(packageName);
458
+ const packageDir = workspacePackageDirByPackageName(
459
+ currentWorkspaceRoot,
460
+ packageName,
461
+ currentPackageDirByPluginName
462
+ );
463
+ const entry = packageDir ? workspaceServerEntry(currentWorkspaceRoot, packageDir) : null;
464
+ if (entry) {
465
+ const mod = await import(pathToFileURL(entry).href);
466
+ const P = getModuleDefault(mod);
467
+ await this.add(P, {
468
+ name: pluginName,
469
+ ...pluginOptions,
470
+ packageName,
471
+ workspaceSource: true
472
+ });
473
+ } else {
474
+ await this.add(normalizedPluginName, {
475
+ name: pluginName,
476
+ ...pluginOptions,
477
+ packageName,
478
+ workspaceSource: true
479
+ });
480
+ }
481
+ } else if (typeof pluginName === "function") {
482
+ await this.add(pluginName, pluginOptions);
483
+ } else {
484
+ await this.add(normalizedPluginName, { name: pluginName, isPreset: true, ...pluginOptions });
485
+ }
486
+ };
487
+ const addTachybasePresetPlugin = async (pluginName, pluginOptions = {}) => {
488
+ if (testUnsafeBuiltinPlugins.has(pluginName)) {
489
+ return;
490
+ }
491
+ await addWorkspacePlugin(pluginName, { enabled: true, ...pluginOptions });
492
+ };
493
+ const addTachybaseExternalPlugin = async (plugin, pluginOptions = {}) => {
494
+ const pluginName = typeof plugin === "string" ? plugin : plugin == null ? void 0 : plugin.name;
495
+ if (!pluginName || testUnsafeBuiltinPlugins.has(pluginName)) {
496
+ return;
497
+ }
498
+ await addWorkspacePlugin(pluginName, { enabled: !!(plugin == null ? void 0 : plugin.enabledByDefault), ...pluginOptions });
499
+ };
500
+ for (const plugin of this.options.plugins || []) {
501
+ const [pluginName, pluginOptions = {}] = Array.isArray(plugin) ? plugin : [plugin];
502
+ if (pluginName === "tachybase") {
503
+ const currentOptions = getPluginManagerOptions(PluginManager2);
504
+ const currentSettings = (currentOptions == null ? void 0 : currentOptions.settings) || options.settings;
505
+ for (const builtinPlugin of ((_a = currentSettings == null ? void 0 : currentSettings.presets) == null ? void 0 : _a.builtinPlugins) || []) {
506
+ await addTachybasePresetPlugin(builtinPlugin, pluginOptions);
507
+ }
508
+ for (const externalPlugin of ((_b = currentSettings == null ? void 0 : currentSettings.presets) == null ? void 0 : _b.externalPlugins) || []) {
509
+ await addTachybaseExternalPlugin(externalPlugin, pluginOptions);
510
+ }
511
+ continue;
512
+ }
513
+ await addWorkspacePlugin(pluginName, { enabled: true, ...pluginOptions });
514
+ }
515
+ this["_initPresetPlugins"] = true;
516
+ };
517
+ PluginManager2.__serverTestEnvironmentPatchVersion = 2;
518
+ PluginManager2.__serverTestEnvironmentPatchOptions = options;
519
+ PluginManager2.findPackagePatched = true;
520
+ }
521
+ function patchAppSupervisor(core, options) {
522
+ const AppSupervisor2 = core.AppSupervisor;
523
+ if (!(AppSupervisor2 == null ? void 0 : AppSupervisor2.getInstance)) {
524
+ return;
525
+ }
526
+ AppSupervisor2.__serverTestEnvironmentOptions = options;
527
+ if (AppSupervisor2.__serverTestEnvironmentPatchVersion === 1) {
528
+ return;
529
+ }
530
+ const supervisor = AppSupervisor2.getInstance();
531
+ const originalAddApp = supervisor.addApp.bind(supervisor);
532
+ supervisor.addApp = (app) => {
533
+ var _a;
534
+ if ((_a = app == null ? void 0 : app.pm) == null ? void 0 : _a.constructor) {
535
+ patchPluginManager(
536
+ {
537
+ PluginManager: app.pm.constructor
538
+ },
539
+ AppSupervisor2.__serverTestEnvironmentOptions
540
+ );
541
+ }
542
+ return originalAddApp(app);
543
+ };
544
+ AppSupervisor2.__serverTestEnvironmentPatchVersion = 1;
545
+ }
546
+ function setupServerTestEnvironment(options = {}) {
547
+ var _a;
548
+ const workspaceRoot = options.workspaceRoot || process.cwd();
549
+ const pluginPaths = options.pluginPaths || [];
550
+ const packageDirByPluginName = options.packageDirByPluginName || {};
551
+ const runtimeRequire2 = createRuntimeRequire(workspaceRoot);
552
+ const TachybaseGlobal = getTachybaseGlobal(runtimeRequire2);
553
+ const settings = runtimeRequire2("tego/presets/settings");
554
+ const testSettings = {
555
+ ...settings,
556
+ env: {
557
+ ...settings.env,
558
+ APP_ENV: "test"
559
+ },
560
+ logger: {
561
+ ...settings.logger,
562
+ level: "error"
563
+ },
564
+ database: {
565
+ dialect: ((_a = settings.database) == null ? void 0 : _a.dialect) || "sqlite",
566
+ ...settings.database,
567
+ storage: createTestDbStorage()
568
+ },
569
+ presets: {
570
+ ...settings.presets,
571
+ runtimePlugins: options.disableRuntimePlugins ? [] : settings.presets.runtimePlugins
572
+ }
573
+ };
574
+ ImportedTachybaseGlobal.settings = testSettings;
575
+ TachybaseGlobal.settings = testSettings;
576
+ ImportedTachybaseGlobal.getInstance().set("PLUGIN_PATHS", pluginPaths);
577
+ TachybaseGlobal.getInstance().set("PLUGIN_PATHS", pluginPaths);
578
+ process.env.TEGO_RUNTIME_HOME = path.join(os.tmpdir(), "test-sqlite");
579
+ process.env.APP_ENV_PATH = process.env.APP_ENV_PATH || ".env.test";
580
+ const coreModules = getCoreModules();
581
+ for (const core of coreModules) {
582
+ patchPluginRuntime(core, workspaceRoot, packageDirByPluginName);
583
+ patchPluginManager(core, {
584
+ ...options,
585
+ workspaceRoot,
586
+ packageDirByPluginName,
587
+ settings: testSettings
588
+ });
589
+ patchAppSupervisor(core, {
590
+ ...options,
591
+ workspaceRoot,
592
+ packageDirByPluginName,
593
+ settings: testSettings
594
+ });
595
+ }
596
+ }
597
+ const noopDescribe = () => {
598
+ };
599
+ function getDescribe() {
600
+ const desc = globalThis.describe;
601
+ if (!desc) {
602
+ throw new Error(
603
+ "globalThis.describe is not available. Ensure your test runner (vitest/jest) provides it globally or configure globals: true."
604
+ );
605
+ }
606
+ return desc;
607
+ }
608
+ const pgOnly = () => {
609
+ var _a, _b;
610
+ const isPostgres = ((_b = (_a = TachybaseGlobalModule.settings) == null ? void 0 : _a.database) == null ? void 0 : _b.dialect) === "postgres";
611
+ const desc = getDescribe();
612
+ if (isPostgres) {
613
+ return desc;
614
+ }
615
+ return desc.skip || noopDescribe;
616
+ };
617
+ const isPg = () => {
618
+ var _a, _b;
619
+ return ((_b = (_a = TachybaseGlobalModule.settings) == null ? void 0 : _a.database) == null ? void 0 : _b.dialect) === "postgres";
620
+ };
167
621
  function randomStr() {
168
622
  return Math.random().toString(36).substring(2);
169
623
  }
@@ -217,6 +671,7 @@ export {
217
671
  mockServer,
218
672
  pgOnly,
219
673
  randomStr,
674
+ setupServerTestEnvironment,
220
675
  startMockServer,
221
676
  startServerWithRandomPort,
222
677
  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;