@midwayjs/mock 4.0.0-alpha.1 → 4.0.0-beta.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/README.md CHANGED
@@ -9,4 +9,4 @@ Document: [https://midwayjs.org](https://midwayjs.org)
9
9
 
10
10
  ## License
11
11
 
12
- [MIT]((http://github.com/midwayjs/midway/blob/master/LICENSE))
12
+ [MIT]((https://github.com/midwayjs/midway/blob/master/LICENSE))
@@ -3,4 +3,5 @@ export * from './rabbitMQ';
3
3
  export * from './socketio';
4
4
  export * from './ws.client';
5
5
  export * from './kafka';
6
+ export * from './sse';
6
7
  //# sourceMappingURL=index.d.ts.map
@@ -19,4 +19,5 @@ __exportStar(require("./rabbitMQ"), exports);
19
19
  __exportStar(require("./socketio"), exports);
20
20
  __exportStar(require("./ws.client"), exports);
21
21
  __exportStar(require("./kafka"), exports);
22
+ __exportStar(require("./sse"), exports);
22
23
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,23 @@
1
+ /// <reference types="node" />
2
+ import { EventEmitter } from 'events';
3
+ export interface SSEClientOptions {
4
+ headers?: Record<string, string>;
5
+ timeout?: number;
6
+ reconnectInterval?: number;
7
+ maxReconnectAttempts?: number;
8
+ }
9
+ export declare class SSEClient extends EventEmitter {
10
+ private url;
11
+ private options;
12
+ private request?;
13
+ private reconnectAttempts;
14
+ private shouldReconnect;
15
+ private reconnectTimer?;
16
+ constructor(url: string, options?: SSEClientOptions);
17
+ connect(): Promise<void>;
18
+ private processLine;
19
+ private scheduleReconnect;
20
+ close(): void;
21
+ }
22
+ export declare function createSSEClient(url: string, options?: SSEClientOptions): SSEClient;
23
+ //# sourceMappingURL=sse.d.ts.map
@@ -0,0 +1,140 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createSSEClient = exports.SSEClient = void 0;
4
+ const http = require("http");
5
+ const https = require("https");
6
+ const events_1 = require("events");
7
+ class SSEClient extends events_1.EventEmitter {
8
+ constructor(url, options = {}) {
9
+ super();
10
+ this.url = url;
11
+ this.options = options;
12
+ this.reconnectAttempts = 0;
13
+ this.shouldReconnect = true;
14
+ this.options = {
15
+ timeout: 30000,
16
+ reconnectInterval: 3000,
17
+ maxReconnectAttempts: 5,
18
+ ...options,
19
+ };
20
+ }
21
+ connect() {
22
+ return new Promise((resolve, reject) => {
23
+ const parsedUrl = new URL(this.url);
24
+ const isSecure = parsedUrl.protocol === 'https:';
25
+ const httpModule = isSecure ? https : http;
26
+ const requestOptions = {
27
+ hostname: parsedUrl.hostname,
28
+ port: parsedUrl.port,
29
+ path: parsedUrl.pathname + parsedUrl.search,
30
+ method: 'GET',
31
+ headers: {
32
+ Accept: 'text/event-stream',
33
+ 'Cache-Control': 'no-cache',
34
+ Connection: 'keep-alive',
35
+ ...this.options.headers,
36
+ },
37
+ };
38
+ this.request = httpModule.request(requestOptions, response => {
39
+ if (response.statusCode !== 200) {
40
+ reject(new Error(`SSE connection failed with status: ${response.statusCode}`));
41
+ return;
42
+ }
43
+ this.reconnectAttempts = 0;
44
+ this.emit('connected');
45
+ resolve();
46
+ response.setEncoding('utf8');
47
+ let buffer = '';
48
+ response.on('data', (chunk) => {
49
+ buffer += chunk;
50
+ const lines = buffer.split('\n');
51
+ buffer = lines.pop() || '';
52
+ for (const line of lines) {
53
+ this.processLine(line);
54
+ }
55
+ });
56
+ response.on('end', () => {
57
+ this.emit('disconnected');
58
+ if (this.shouldReconnect &&
59
+ this.reconnectAttempts < (this.options.maxReconnectAttempts || 5)) {
60
+ this.scheduleReconnect();
61
+ }
62
+ });
63
+ response.on('error', error => {
64
+ this.emit('error', error);
65
+ });
66
+ });
67
+ this.request.on('error', error => {
68
+ reject(error);
69
+ if (this.shouldReconnect &&
70
+ this.reconnectAttempts < (this.options.maxReconnectAttempts || 5)) {
71
+ this.scheduleReconnect();
72
+ }
73
+ });
74
+ this.request.on('timeout', () => {
75
+ this.request?.destroy();
76
+ reject(new Error('SSE connection timeout'));
77
+ });
78
+ if (this.options.timeout) {
79
+ this.request.setTimeout(this.options.timeout);
80
+ }
81
+ this.request.end();
82
+ });
83
+ }
84
+ processLine(line) {
85
+ if (line.trim() === '') {
86
+ return;
87
+ }
88
+ if (line.startsWith('data: ')) {
89
+ const data = line.substring(6);
90
+ try {
91
+ const parsed = JSON.parse(data);
92
+ this.emit('message', parsed);
93
+ }
94
+ catch {
95
+ this.emit('message', data);
96
+ }
97
+ }
98
+ else if (line.startsWith('event: ')) {
99
+ const eventType = line.substring(7);
100
+ this.emit('event', eventType);
101
+ }
102
+ else if (line.startsWith('id: ')) {
103
+ const id = line.substring(4);
104
+ this.emit('id', id);
105
+ }
106
+ else if (line.startsWith('retry: ')) {
107
+ const retry = parseInt(line.substring(7), 10);
108
+ if (!isNaN(retry)) {
109
+ this.options.reconnectInterval = retry;
110
+ }
111
+ }
112
+ }
113
+ scheduleReconnect() {
114
+ if (this.reconnectTimer) {
115
+ clearTimeout(this.reconnectTimer);
116
+ }
117
+ this.reconnectAttempts++;
118
+ this.reconnectTimer = setTimeout(() => {
119
+ this.connect().catch(error => {
120
+ this.emit('error', error);
121
+ });
122
+ }, this.options.reconnectInterval);
123
+ }
124
+ close() {
125
+ this.shouldReconnect = false;
126
+ if (this.reconnectTimer) {
127
+ clearTimeout(this.reconnectTimer);
128
+ }
129
+ if (this.request) {
130
+ this.request.destroy();
131
+ }
132
+ this.emit('closed');
133
+ }
134
+ }
135
+ exports.SSEClient = SSEClient;
136
+ function createSSEClient(url, options) {
137
+ return new SSEClient(url, options);
138
+ }
139
+ exports.createSSEClient = createSSEClient;
140
+ //# sourceMappingURL=sse.js.map
package/dist/creator.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { IMidwayApplication, IMidwayFramework } from '@midwayjs/core';
2
- import { ComponentModule, MockAppConfigurationOptions, IBootstrapAppStarter, MockBootstrapOptions } from './interface';
3
- export declare function create<T extends IMidwayFramework<any, any, any, any, any>>(appDir: string | MockAppConfigurationOptions, options?: MockAppConfigurationOptions): Promise<T>;
4
- export declare function createApp<T extends IMidwayFramework<any, any, any, any, any>>(baseDir: string | MockAppConfigurationOptions, options?: MockAppConfigurationOptions): Promise<ReturnType<T['getApplication']>>;
2
+ import { ComponentModule, IBootstrapAppStarter, MockBootstrapOptions } from './interface';
3
+ export declare function create<T extends IMidwayFramework<any, any, any, any, any>>(appDir: string | MockBootstrapOptions, options?: MockBootstrapOptions): Promise<T>;
4
+ export declare function createApp<T extends IMidwayFramework<any, any, any, any, any>>(baseDir: string | MockBootstrapOptions, options?: MockBootstrapOptions): Promise<ReturnType<T['getApplication']>>;
5
5
  export declare function close(app: IMidwayApplication<any> | {
6
6
  close: (...args: any[]) => void;
7
7
  }, options?: {
@@ -9,7 +9,7 @@ export declare function close(app: IMidwayApplication<any> | {
9
9
  cleanTempDir?: boolean;
10
10
  sleep?: number;
11
11
  }): Promise<void>;
12
- export declare function createFunctionApp<T extends IMidwayFramework<any, any, any, any, any>, Y = ReturnType<T['getApplication']>>(baseDir?: string | MockAppConfigurationOptions, options?: MockAppConfigurationOptions, customFrameworkModule?: {
12
+ export declare function createFunctionApp<T extends IMidwayFramework<any, any, any, any, any>, Y = ReturnType<T['getApplication']>>(baseDir?: string | MockBootstrapOptions, options?: MockBootstrapOptions, customFrameworkModule?: {
13
13
  new (...args: any[]): T;
14
14
  } | ComponentModule): Promise<Y>;
15
15
  /**
@@ -17,6 +17,6 @@ export declare function createFunctionApp<T extends IMidwayFramework<any, any, a
17
17
  * @param baseDirOrOptions
18
18
  * @param options
19
19
  */
20
- export declare function createLightApp(baseDirOrOptions: string | MockAppConfigurationOptions, options?: MockAppConfigurationOptions): Promise<IMidwayApplication>;
20
+ export declare function createLightApp(baseDirOrOptions: string | MockBootstrapOptions, options?: MockBootstrapOptions): Promise<IMidwayApplication>;
21
21
  export declare function createBootstrap(entryFile: string, options?: MockBootstrapOptions): Promise<IBootstrapAppStarter>;
22
22
  //# sourceMappingURL=creator.d.ts.map
package/dist/creator.js CHANGED
@@ -9,6 +9,7 @@ const util_1 = require("util");
9
9
  const fs_1 = require("fs");
10
10
  const yaml = require("js-yaml");
11
11
  const getRawBody = require("raw-body");
12
+ const functional_1 = require("@midwayjs/core/functional");
12
13
  const debug = (0, util_1.debuglog)('midway:debug');
13
14
  process.setMaxListeners(0);
14
15
  function formatPath(baseDir, p) {
@@ -23,7 +24,7 @@ function getFileNameWithSuffix(fileName) {
23
24
  return (0, core_1.isTypeScriptEnvironment)() ? `${fileName}.ts` : `${fileName}.js`;
24
25
  }
25
26
  function createMockWrapApplicationContext() {
26
- const container = new core_1.MidwayContainer();
27
+ const container = new core_1.DynamicMidwayContainer();
27
28
  debug(`[mock]: Create mock MidwayContainer, id=${container.id}.`);
28
29
  const bindModuleMap = new WeakMap();
29
30
  container.onBeforeBind(target => {
@@ -155,12 +156,32 @@ async function create(appDir, options = {}) {
155
156
  };
156
157
  options.globalConfig = (0, utils_1.mergeGlobalConfig)(options.globalConfig, sslConfig);
157
158
  }
159
+ const anonymousConfiguration = (0, functional_1.defineConfiguration)({
160
+ namespace: 'anonymous',
161
+ async onReady(...args) {
162
+ return options.onReady?.(...args);
163
+ },
164
+ async onStop(...args) {
165
+ return options.onStop?.(...args);
166
+ },
167
+ async onConfigLoad(...args) {
168
+ return options.onConfigLoad?.(...args);
169
+ },
170
+ async onServerReady(...args) {
171
+ return options.onServerReady?.(...args);
172
+ },
173
+ async onHealthCheck(...args) {
174
+ return options.onHealthCheck?.(...args);
175
+ },
176
+ });
158
177
  const container = createMockWrapApplicationContext();
159
178
  options.applicationContext = container;
179
+ options.imports = options.imports || [];
180
+ options.imports.push(anonymousConfiguration);
160
181
  await (0, core_1.initializeGlobalApplicationContext)({
182
+ loggerFactory: logger_1.loggers,
161
183
  ...options,
162
184
  appDir,
163
- loggerFactory: logger_1.loggers,
164
185
  });
165
186
  const frameworkService = await container.getAsync(core_1.MidwayFrameworkService);
166
187
  const mainFramework = frameworkService.getMainFramework();
@@ -1,12 +1,13 @@
1
- import { IMidwayApplication, IMidwayBootstrapOptions } from '@midwayjs/core';
2
- export interface MockAppConfigurationOptions extends IMidwayBootstrapOptions {
1
+ import { ILifeCycle, IMidwayApplication, IMidwayBootstrapOptions } from '@midwayjs/core';
2
+ export interface MockBootstrapOptions extends IMidwayBootstrapOptions, ILifeCycle {
3
3
  cleanLogsDir?: boolean;
4
4
  cleanTempDir?: boolean;
5
5
  ssl?: boolean;
6
- }
7
- export interface MockBootstrapOptions extends MockAppConfigurationOptions {
6
+ bootstrapTimeout?: number;
7
+ starter?: any;
8
8
  entryFile?: string;
9
9
  bootstrapMode?: 'faas' | 'app';
10
+ initializeMethodName?: string;
10
11
  }
11
12
  export type ComponentModule = {
12
13
  Configuration: new () => any;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@midwayjs/mock",
3
- "version": "4.0.0-alpha.1",
3
+ "version": "4.0.0-beta.2",
4
4
  "description": "create your test app from midway framework",
5
5
  "main": "dist/index.js",
6
6
  "typings": "dist/index.d.ts",
@@ -25,11 +25,11 @@
25
25
  "function.js"
26
26
  ],
27
27
  "engines": {
28
- "node": ">=12"
28
+ "node": ">=20"
29
29
  },
30
30
  "license": "MIT",
31
31
  "devDependencies": {
32
- "@midwayjs/core": "^4.0.0-alpha.1",
32
+ "@midwayjs/core": "^4.0.0-beta.2",
33
33
  "@midwayjs/logger": "^3.0.0",
34
34
  "@types/amqplib": "0.10.6",
35
35
  "amqplib": "0.10.5",
@@ -50,5 +50,5 @@
50
50
  "type": "git",
51
51
  "url": "https://github.com/midwayjs/midway.git"
52
52
  },
53
- "gitHead": "14bb4da91805a1cf52f190c0d37a74b395dd6372"
53
+ "gitHead": "53bfef4c5279da5f09025e4610bdbf64f94f60bd"
54
54
  }