@xiuchang-midscene/shared 2.0.2 → 2.0.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.
Files changed (166) hide show
  1. package/dist/es/oss/index.mjs +1 -1
  2. package/dist/lib/oss/index.js +1 -1
  3. package/package.json +1 -1
  4. package/src/oss/index.ts +1 -1
  5. package/dist/es/baseDB.mjs.bak +0 -109
  6. package/dist/es/build/copy-static.mjs.bak +0 -31
  7. package/dist/es/build/rspack-config.mjs.bak +0 -4
  8. package/dist/es/cli/cli-runner.mjs.bak +0 -140
  9. package/dist/es/cli/index.mjs.bak +0 -2
  10. package/dist/es/common.mjs.bak +0 -37
  11. package/dist/es/constants/example-code.mjs.bak +0 -223
  12. package/dist/es/constants/index.mjs.bak +0 -23
  13. package/dist/es/env/basic.mjs.bak +0 -6
  14. package/dist/es/env/constants.mjs.bak +0 -70
  15. package/dist/es/env/global-config-manager.mjs.bak +0 -94
  16. package/dist/es/env/helper.mjs.bak +0 -43
  17. package/dist/es/env/index.mjs.bak +0 -5
  18. package/dist/es/env/init-debug.mjs.bak +0 -18
  19. package/dist/es/env/model-config-manager.mjs.bak +0 -79
  20. package/dist/es/env/parse-model-config.mjs.bak +0 -132
  21. package/dist/es/env/types.mjs.bak +0 -220
  22. package/dist/es/env/utils.mjs.bak +0 -26
  23. package/dist/es/extractor/constants.mjs.bak +0 -2
  24. package/dist/es/extractor/debug.mjs.bak +0 -6
  25. package/dist/es/extractor/dom-util.mjs.bak +0 -92
  26. package/dist/es/extractor/index.mjs.bak +0 -5
  27. package/dist/es/extractor/locator.mjs.bak +0 -250
  28. package/dist/es/extractor/tree.mjs.bak +0 -78
  29. package/dist/es/extractor/util.mjs.bak +0 -245
  30. package/dist/es/extractor/web-extractor.mjs.bak +0 -303
  31. package/dist/es/img/box-select.mjs.bak +0 -824
  32. package/dist/es/img/canvas-fallback.mjs.bak +0 -238
  33. package/dist/es/img/get-photon.mjs.bak +0 -45
  34. package/dist/es/img/get-sharp.mjs.bak +0 -11
  35. package/dist/es/img/index.mjs.bak +0 -4
  36. package/dist/es/img/info.mjs.bak +0 -29
  37. package/dist/es/img/transform.mjs.bak +0 -295
  38. package/dist/es/index.mjs.bak +0 -4
  39. package/dist/es/logger.mjs.bak +0 -64
  40. package/dist/es/mcp/base-server.mjs.bak +0 -281
  41. package/dist/es/mcp/base-tools.mjs.bak +0 -91
  42. package/dist/es/mcp/chrome-path.mjs.bak +0 -35
  43. package/dist/es/mcp/index.mjs.bak +0 -7
  44. package/dist/es/mcp/inject-report-html-plugin.mjs.bak +0 -53
  45. package/dist/es/mcp/launcher-helper.mjs.bak +0 -52
  46. package/dist/es/mcp/tool-generator.mjs.bak +0 -297
  47. package/dist/es/mcp/types.mjs.bak +0 -3
  48. package/dist/es/node/fs.mjs.bak +0 -44
  49. package/dist/es/node/index.mjs.bak +0 -2
  50. package/dist/es/node/port.mjs.bak +0 -24
  51. package/dist/es/oss/demo.mjs.bak +0 -30
  52. package/dist/es/oss/index.mjs.bak +0 -90
  53. package/dist/es/polyfills/async-hooks.mjs.bak +0 -2
  54. package/dist/es/polyfills/index.mjs.bak +0 -1
  55. package/dist/es/types/index.mjs.bak +0 -3
  56. package/dist/es/us-keyboard-layout.mjs.bak +0 -1414
  57. package/dist/es/utils.mjs.bak +0 -72
  58. package/dist/es/zod-schema-utils.mjs.bak +0 -54
  59. package/dist/lib/baseDB.js.bak +0 -149
  60. package/dist/lib/build/copy-static.js.bak +0 -79
  61. package/dist/lib/build/rspack-config.js.bak +0 -38
  62. package/dist/lib/cli/cli-runner.js.bak +0 -196
  63. package/dist/lib/cli/index.js.bak +0 -48
  64. package/dist/lib/common.js.bak +0 -93
  65. package/dist/lib/constants/example-code.js.bak +0 -260
  66. package/dist/lib/constants/index.js.bak +0 -96
  67. package/dist/lib/env/basic.js.bak +0 -40
  68. package/dist/lib/env/constants.js.bak +0 -113
  69. package/dist/lib/env/global-config-manager.js.bak +0 -128
  70. package/dist/lib/env/helper.js.bak +0 -80
  71. package/dist/lib/env/index.js.bak +0 -90
  72. package/dist/lib/env/init-debug.js.bak +0 -52
  73. package/dist/lib/env/model-config-manager.js.bak +0 -113
  74. package/dist/lib/env/parse-model-config.js.bak +0 -178
  75. package/dist/lib/env/types.js.bak +0 -554
  76. package/dist/lib/env/utils.js.bak +0 -72
  77. package/dist/lib/extractor/constants.js.bak +0 -42
  78. package/dist/lib/extractor/debug.js.bak +0 -12
  79. package/dist/lib/extractor/dom-util.js.bak +0 -153
  80. package/dist/lib/extractor/index.js.bak +0 -81
  81. package/dist/lib/extractor/locator.js.bak +0 -296
  82. package/dist/lib/extractor/tree.js.bak +0 -124
  83. package/dist/lib/extractor/util.js.bak +0 -336
  84. package/dist/lib/extractor/web-extractor.js.bak +0 -349
  85. package/dist/lib/img/box-select.js.bak +0 -875
  86. package/dist/lib/img/canvas-fallback.js.bak +0 -305
  87. package/dist/lib/img/get-photon.js.bak +0 -82
  88. package/dist/lib/img/get-sharp.js.bak +0 -45
  89. package/dist/lib/img/index.js.bak +0 -95
  90. package/dist/lib/img/info.js.bak +0 -83
  91. package/dist/lib/img/transform.js.bak +0 -387
  92. package/dist/lib/index.js.bak +0 -47
  93. package/dist/lib/logger.js.bak +0 -114
  94. package/dist/lib/mcp/base-server.js.bak +0 -331
  95. package/dist/lib/mcp/base-tools.js.bak +0 -125
  96. package/dist/lib/mcp/chrome-path.js.bak +0 -72
  97. package/dist/lib/mcp/index.js.bak +0 -100
  98. package/dist/lib/mcp/inject-report-html-plugin.js.bak +0 -98
  99. package/dist/lib/mcp/launcher-helper.js.bak +0 -86
  100. package/dist/lib/mcp/tool-generator.js.bak +0 -334
  101. package/dist/lib/mcp/types.js.bak +0 -40
  102. package/dist/lib/node/fs.js.bak +0 -97
  103. package/dist/lib/node/index.js.bak +0 -65
  104. package/dist/lib/node/port.js.bak +0 -61
  105. package/dist/lib/oss/demo.js.bak +0 -36
  106. package/dist/lib/oss/index.js.bak +0 -138
  107. package/dist/lib/polyfills/async-hooks.js.bak +0 -36
  108. package/dist/lib/polyfills/index.js.bak +0 -58
  109. package/dist/lib/types/index.js.bak +0 -37
  110. package/dist/lib/us-keyboard-layout.js.bak +0 -1457
  111. package/dist/lib/utils.js.bak +0 -148
  112. package/dist/lib/zod-schema-utils.js.bak +0 -97
  113. package/dist/types/baseDB.d.ts.bak +0 -25
  114. package/dist/types/build/copy-static.d.ts.bak +0 -31
  115. package/dist/types/build/rspack-config.d.ts.bak +0 -8
  116. package/dist/types/cli/cli-runner.d.ts.bak +0 -14
  117. package/dist/types/cli/index.d.ts.bak +0 -2
  118. package/dist/types/common.d.ts.bak +0 -12
  119. package/dist/types/constants/example-code.d.ts.bak +0 -2
  120. package/dist/types/constants/index.d.ts.bak +0 -21
  121. package/dist/types/env/basic.d.ts.bak +0 -6
  122. package/dist/types/env/constants.d.ts.bak +0 -40
  123. package/dist/types/env/global-config-manager.d.ts.bak +0 -32
  124. package/dist/types/env/helper.d.ts.bak +0 -4
  125. package/dist/types/env/index.d.ts.bak +0 -4
  126. package/dist/types/env/init-debug.d.ts.bak +0 -1
  127. package/dist/types/env/model-config-manager.d.ts.bak +0 -25
  128. package/dist/types/env/parse-model-config.d.ts.bak +0 -31
  129. package/dist/types/env/types.d.ts.bak +0 -318
  130. package/dist/types/env/utils.d.ts.bak +0 -38
  131. package/dist/types/extractor/constants.d.ts.bak +0 -1
  132. package/dist/types/extractor/debug.d.ts.bak +0 -1
  133. package/dist/types/extractor/dom-util.d.ts.bak +0 -56
  134. package/dist/types/extractor/index.d.ts.bak +0 -32
  135. package/dist/types/extractor/locator.d.ts.bak +0 -9
  136. package/dist/types/extractor/tree.d.ts.bak +0 -6
  137. package/dist/types/extractor/util.d.ts.bak +0 -47
  138. package/dist/types/extractor/web-extractor.d.ts.bak +0 -19
  139. package/dist/types/img/box-select.d.ts.bak +0 -26
  140. package/dist/types/img/canvas-fallback.d.ts.bak +0 -105
  141. package/dist/types/img/get-photon.d.ts.bak +0 -19
  142. package/dist/types/img/get-sharp.d.ts.bak +0 -3
  143. package/dist/types/img/index.d.ts.bak +0 -3
  144. package/dist/types/img/info.d.ts.bak +0 -29
  145. package/dist/types/img/transform.d.ts.bak +0 -107
  146. package/dist/types/index.d.ts.bak +0 -4
  147. package/dist/types/logger.d.ts.bak +0 -5
  148. package/dist/types/mcp/base-server.d.ts.bak +0 -93
  149. package/dist/types/mcp/base-tools.d.ts.bak +0 -79
  150. package/dist/types/mcp/chrome-path.d.ts.bak +0 -2
  151. package/dist/types/mcp/index.d.ts.bak +0 -7
  152. package/dist/types/mcp/inject-report-html-plugin.d.ts.bak +0 -18
  153. package/dist/types/mcp/launcher-helper.d.ts.bak +0 -94
  154. package/dist/types/mcp/tool-generator.d.ts.bak +0 -10
  155. package/dist/types/mcp/types.d.ts.bak +0 -103
  156. package/dist/types/node/fs.d.ts.bak +0 -15
  157. package/dist/types/node/index.d.ts.bak +0 -2
  158. package/dist/types/node/port.d.ts.bak +0 -8
  159. package/dist/types/oss/demo.d.ts.bak +0 -1
  160. package/dist/types/oss/index.d.ts.bak +0 -34
  161. package/dist/types/polyfills/async-hooks.d.ts.bak +0 -6
  162. package/dist/types/polyfills/index.d.ts.bak +0 -4
  163. package/dist/types/types/index.d.ts.bak +0 -34
  164. package/dist/types/us-keyboard-layout.d.ts.bak +0 -32
  165. package/dist/types/utils.d.ts.bak +0 -34
  166. package/dist/types/zod-schema-utils.d.ts.bak +0 -23
@@ -46,7 +46,7 @@ async function getOSSConfigFromEnv() {
46
46
  region: process.env.MIDSCENE_OSS_REGION || stsResult.region || 'oss-cn-beijing',
47
47
  bucket: process.env.MIDSCENE_OSS_BUCKET || 'xrayandroid',
48
48
  endpoint: process.env.MIDSCENE_OSS_ENDPOINT,
49
- prefix: process.env.MIDSCENE_OSS_PREFIX || 'midscene-reports/',
49
+ prefix: process.env.MIDSCENE_OSS_PREFIX || 'report/',
50
50
  customDomain: process.env.MIDSCENE_OSS_DOMAIN
51
51
  };
52
52
  }
@@ -86,7 +86,7 @@ async function getOSSConfigFromEnv() {
86
86
  region: process.env.MIDSCENE_OSS_REGION || stsResult.region || 'oss-cn-beijing',
87
87
  bucket: process.env.MIDSCENE_OSS_BUCKET || 'xrayandroid',
88
88
  endpoint: process.env.MIDSCENE_OSS_ENDPOINT,
89
- prefix: process.env.MIDSCENE_OSS_PREFIX || 'midscene-reports/',
89
+ prefix: process.env.MIDSCENE_OSS_PREFIX || 'report/',
90
90
  customDomain: process.env.MIDSCENE_OSS_DOMAIN
91
91
  };
92
92
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xiuchang-midscene/shared",
3
- "version": "2.0.2",
3
+ "version": "2.0.3",
4
4
  "repository": "https://github.com/web-infra-dev/midscene",
5
5
  "homepage": "https://midscenejs.com/",
6
6
  "types": "./dist/types/index.d.ts",
package/src/oss/index.ts CHANGED
@@ -118,7 +118,7 @@ export async function getOSSConfigFromEnv(): Promise<OSSUploadConfig | null> {
118
118
  process.env.MIDSCENE_OSS_REGION || stsResult.region || 'oss-cn-beijing',
119
119
  bucket: process.env.MIDSCENE_OSS_BUCKET || 'xrayandroid',
120
120
  endpoint: process.env.MIDSCENE_OSS_ENDPOINT,
121
- prefix: process.env.MIDSCENE_OSS_PREFIX || 'midscene-reports/',
121
+ prefix: process.env.MIDSCENE_OSS_PREFIX || 'report/',
122
122
  customDomain: process.env.MIDSCENE_OSS_DOMAIN,
123
123
  };
124
124
  }
@@ -1,109 +0,0 @@
1
- function _define_property(obj, key, value) {
2
- if (key in obj) Object.defineProperty(obj, key, {
3
- value: value,
4
- enumerable: true,
5
- configurable: true,
6
- writable: true
7
- });
8
- else obj[key] = value;
9
- return obj;
10
- }
11
- class IndexedDBManager {
12
- initDB() {
13
- return new Promise((resolve, reject)=>{
14
- const request = indexedDB.open(this.dbName, this.version);
15
- request.onerror = ()=>reject(request.error);
16
- request.onsuccess = ()=>resolve(request.result);
17
- request.onupgradeneeded = (event)=>{
18
- const db = event.target.result;
19
- this.storeConfigs.forEach(({ name, keyPath })=>{
20
- if (!db.objectStoreNames.contains(name)) {
21
- const store = db.createObjectStore(name, {
22
- keyPath
23
- });
24
- store.createIndex('timestamp', 'timestamp', {
25
- unique: false
26
- });
27
- }
28
- });
29
- };
30
- });
31
- }
32
- async withTransaction(storeNames, mode, operation) {
33
- const db = await this.dbPromise;
34
- const transaction = db.transaction(storeNames, mode);
35
- const stores = Array.isArray(storeNames) ? storeNames.map((name)=>transaction.objectStore(name)) : transaction.objectStore(storeNames);
36
- return operation(stores);
37
- }
38
- promisifyRequest(request) {
39
- return new Promise((resolve, reject)=>{
40
- request.onsuccess = ()=>resolve(request.result);
41
- request.onerror = ()=>reject(request.error);
42
- });
43
- }
44
- async put(storeName, data) {
45
- await this.withTransaction(storeName, 'readwrite', async (store)=>{
46
- await this.promisifyRequest(store.put(data));
47
- });
48
- }
49
- async get(storeName, key) {
50
- return this.withTransaction(storeName, 'readonly', async (store)=>this.promisifyRequest(store.get(key)));
51
- }
52
- async getAll(storeName, sortByTimestamp = true) {
53
- return this.withTransaction(storeName, 'readonly', async (store)=>{
54
- const objectStore = store;
55
- const results = sortByTimestamp ? await this.promisifyRequest(objectStore.index('timestamp').getAll()) : await this.promisifyRequest(objectStore.getAll());
56
- return sortByTimestamp ? results.sort((a, b)=>a.timestamp - b.timestamp) : results;
57
- });
58
- }
59
- async clear(storeName) {
60
- await this.withTransaction(storeName, 'readwrite', async (store)=>{
61
- await this.promisifyRequest(store.clear());
62
- });
63
- }
64
- async delete(storeName, key) {
65
- await this.withTransaction(storeName, 'readwrite', async (store)=>{
66
- await this.promisifyRequest(store.delete(key));
67
- });
68
- }
69
- async count(storeName) {
70
- return this.withTransaction(storeName, 'readonly', async (store)=>this.promisifyRequest(store.count()));
71
- }
72
- getDBPromise() {
73
- return this.dbPromise;
74
- }
75
- constructor(dbName, version, storeConfigs){
76
- _define_property(this, "dbPromise", void 0);
77
- _define_property(this, "dbName", void 0);
78
- _define_property(this, "version", void 0);
79
- _define_property(this, "storeConfigs", void 0);
80
- this.dbName = dbName;
81
- this.version = version;
82
- this.storeConfigs = storeConfigs;
83
- this.dbPromise = this.initDB();
84
- }
85
- }
86
- const withErrorHandling = async (operation, errorMessage, defaultValue, onQuotaExceeded)=>{
87
- try {
88
- return await operation();
89
- } catch (e) {
90
- console.error(errorMessage, e);
91
- if (e instanceof Error && 'QuotaExceededError' === e.name && onQuotaExceeded) {
92
- console.log('Storage quota exceeded, running cleanup...');
93
- await onQuotaExceeded();
94
- }
95
- return defaultValue;
96
- }
97
- };
98
- const createCleanupFunction = (dbManager, storeName, maxItems)=>async ()=>{
99
- try {
100
- const results = await dbManager.getAll(storeName);
101
- if (results.length > maxItems) {
102
- const toDelete = results.sort((a, b)=>a.timestamp - b.timestamp).slice(0, results.length - maxItems);
103
- await Promise.all(toDelete.map((item)=>dbManager.delete(storeName, item.id)));
104
- }
105
- } catch (e) {
106
- console.error(`Failed to cleanup ${storeName}:`, e);
107
- }
108
- };
109
- export { IndexedDBManager, createCleanupFunction, withErrorHandling };
@@ -1,31 +0,0 @@
1
- import node_fs from "node:fs";
2
- import node_path from "node:path";
3
- const createCopyStaticPlugin = (options)=>({
4
- name: options.pluginName || 'copy-static',
5
- setup (api) {
6
- api.onAfterBuild(async ()=>{
7
- const { srcDir, destDir, faviconPath } = options;
8
- const stat = await node_fs.promises.lstat(destDir).catch(()=>null);
9
- if (stat?.isSymbolicLink()) await node_fs.promises.unlink(destDir);
10
- await node_fs.promises.mkdir(destDir, {
11
- recursive: true
12
- });
13
- await node_fs.promises.cp(srcDir, destDir, {
14
- recursive: true
15
- });
16
- console.log(`Copied build artifacts from ${srcDir} to ${destDir}`);
17
- if (faviconPath) {
18
- const faviconDest = node_path.join(destDir, 'favicon.ico');
19
- await node_fs.promises.copyFile(faviconPath, faviconDest);
20
- console.log(`Copied favicon from ${faviconPath} to ${faviconDest}`);
21
- }
22
- });
23
- }
24
- });
25
- const createPlaygroundCopyPlugin = (srcDir, destDir, pluginName, faviconSrc)=>createCopyStaticPlugin({
26
- srcDir,
27
- destDir,
28
- faviconPath: faviconSrc,
29
- pluginName
30
- });
31
- export { createCopyStaticPlugin, createPlaygroundCopyPlugin };
@@ -1,4 +0,0 @@
1
- const commonIgnoreWarnings = [
2
- /Critical dependency: the request of a dependency is an expression/
3
- ];
4
- export { commonIgnoreWarnings };
@@ -1,140 +0,0 @@
1
- import { existsSync, writeFileSync } from "node:fs";
2
- import { tmpdir } from "node:os";
3
- import { join } from "node:path";
4
- import dotenv from "dotenv";
5
- import { getDebug } from "../logger.mjs";
6
- function _define_property(obj, key, value) {
7
- if (key in obj) Object.defineProperty(obj, key, {
8
- value: value,
9
- enumerable: true,
10
- configurable: true,
11
- writable: true
12
- });
13
- else obj[key] = value;
14
- return obj;
15
- }
16
- const debug = getDebug('cli-runner');
17
- class CLIError extends Error {
18
- constructor(message, exitCode = 1){
19
- super(message), _define_property(this, "exitCode", void 0), this.exitCode = exitCode;
20
- }
21
- }
22
- function parseValue(raw) {
23
- if (raw.startsWith('{') || raw.startsWith('[')) try {
24
- return JSON.parse(raw);
25
- } catch {}
26
- if (/^-?\d+(\.\d+)?$/.test(raw)) return Number(raw);
27
- return raw;
28
- }
29
- function parseCliArgs(args) {
30
- const result = {};
31
- for(let i = 0; i < args.length; i++){
32
- const arg = args[i];
33
- if (!arg.startsWith('--')) continue;
34
- const body = arg.slice(2);
35
- const eqIdx = body.indexOf('=');
36
- if (eqIdx >= 0) result[body.slice(0, eqIdx)] = parseValue(body.slice(eqIdx + 1));
37
- else if (args[i + 1] && !args[i + 1].startsWith('--')) {
38
- i++;
39
- result[body] = parseValue(args[i]);
40
- } else result[body] = true;
41
- }
42
- return result;
43
- }
44
- function outputContentItem(item, isError) {
45
- switch(item.type){
46
- case 'text':
47
- if (isError) console.error(item.text);
48
- else console.log(item.text);
49
- break;
50
- case 'image':
51
- {
52
- const filename = `screenshot-${Date.now()}.png`;
53
- const filepath = join(tmpdir(), filename);
54
- writeFileSync(filepath, Buffer.from(item.data, 'base64'));
55
- console.log(`Screenshot saved: ${filepath}`);
56
- break;
57
- }
58
- default:
59
- console.log(`[${item.type} content not displayed in CLI]`);
60
- }
61
- }
62
- function outputResult(result) {
63
- for (const item of result.content)outputContentItem(item, result.isError ?? false);
64
- }
65
- function removePrefix(name, prefix) {
66
- if (prefix && name.startsWith(prefix)) return name.slice(prefix.length);
67
- return name;
68
- }
69
- function printCommandHelp(scriptName, cmd) {
70
- const { def } = cmd;
71
- console.log(`\nUsage: ${scriptName} ${cmd.name} [options]\n`);
72
- console.log(def.description);
73
- const schemaEntries = Object.entries(def.schema);
74
- if (schemaEntries.length > 0) {
75
- console.log('\nOptions:');
76
- for (const [key, zodType] of schemaEntries){
77
- const desc = zodType.description ?? '';
78
- console.log(` --${key.padEnd(20)} ${desc}`);
79
- }
80
- }
81
- }
82
- function printVersion(scriptName, version) {
83
- console.log(`${scriptName} v${version}`);
84
- }
85
- function printHelp(scriptName, commands, version) {
86
- if (version) {
87
- printVersion(scriptName, version);
88
- console.log('');
89
- }
90
- console.log(`\nUsage: ${scriptName} <command> [options]\n`);
91
- console.log('Commands:');
92
- for (const { name, def } of commands)console.log(` ${name.padEnd(30)} ${def.description}`);
93
- console.log(` ${'version'.padEnd(30)} Show CLI version`);
94
- console.log(`\nRun "${scriptName} <command> --help" for more info.`);
95
- }
96
- async function runToolsCLI(tools, scriptName, options) {
97
- const rawArgs = options?.argv ?? process.argv.slice(2);
98
- debug('CLI invoked: %s %s', scriptName, rawArgs.join(' '));
99
- const envFile = join(process.cwd(), '.env');
100
- if (existsSync(envFile)) dotenv.config({
101
- path: envFile
102
- });
103
- await tools.initTools();
104
- const commands = tools.getToolDefinitions().map((def)=>({
105
- name: removePrefix(def.name, options?.stripPrefix).toLowerCase(),
106
- def
107
- }));
108
- const cliVersion = options?.version;
109
- const [commandName, ...restArgs] = rawArgs;
110
- if (!commandName || '--help' === commandName || '-h' === commandName) {
111
- debug('showing help (no command or --help flag)');
112
- printHelp(scriptName, commands, cliVersion);
113
- return;
114
- }
115
- if ('--version' === commandName || '-v' === commandName || 'version' === commandName.toLowerCase()) {
116
- if (!cliVersion) throw new CLIError('Failed to determine CLI version');
117
- printVersion(scriptName, cliVersion);
118
- return;
119
- }
120
- const match = commands.find((c)=>c.name.toLowerCase() === commandName.toLowerCase());
121
- if (!match) {
122
- debug('unknown command: %s', commandName);
123
- console.error(`Unknown command: ${commandName}`);
124
- printHelp(scriptName, commands, cliVersion);
125
- throw new CLIError(`Unknown command: ${commandName}`);
126
- }
127
- const parsedArgs = parseCliArgs(restArgs);
128
- debug('command: %s, args: %s', match.name, JSON.stringify(parsedArgs));
129
- if (true === parsedArgs.help) {
130
- debug('showing command help for: %s', match.name);
131
- printCommandHelp(scriptName, match);
132
- return;
133
- }
134
- const result = await match.def.handler(parsedArgs);
135
- debug('command %s completed, isError: %s', match.name, result.isError ?? false);
136
- outputResult(result);
137
- await tools.destroy();
138
- if (result.isError) throw new CLIError('Command failed', 1);
139
- }
140
- export { CLIError, parseCliArgs, parseValue, removePrefix, runToolsCLI };
@@ -1,2 +0,0 @@
1
- import { CLIError, parseCliArgs, parseValue, removePrefix, runToolsCLI } from "./cli-runner.mjs";
2
- export { CLIError, parseCliArgs, parseValue, removePrefix, runToolsCLI };
@@ -1,37 +0,0 @@
1
- import { existsSync, mkdirSync } from "node:fs";
2
- import { tmpdir } from "node:os";
3
- import node_path from "node:path";
4
- import { getBasicEnvValue } from "./env/basic.mjs";
5
- import { MIDSCENE_RUN_DIR } from "./env/types.mjs";
6
- import { ifInNode } from "./utils.mjs";
7
- const defaultRunDirName = 'midscene_run';
8
- const getMidsceneRunDir = ()=>{
9
- if (!ifInNode) return '';
10
- return getBasicEnvValue(MIDSCENE_RUN_DIR) || defaultRunDirName;
11
- };
12
- const getMidsceneRunBaseDir = ()=>{
13
- if (!ifInNode) return '';
14
- let basePath = node_path.resolve(process.cwd(), getMidsceneRunDir());
15
- if (!existsSync(basePath)) try {
16
- mkdirSync(basePath, {
17
- recursive: true
18
- });
19
- } catch (error) {
20
- basePath = node_path.join(tmpdir(), defaultRunDirName);
21
- mkdirSync(basePath, {
22
- recursive: true
23
- });
24
- }
25
- return basePath;
26
- };
27
- const getMidsceneRunSubDir = (subdir)=>{
28
- if (!ifInNode) return '';
29
- const basePath = getMidsceneRunBaseDir();
30
- const logPath = node_path.join(basePath, subdir);
31
- if (!existsSync(logPath)) mkdirSync(logPath, {
32
- recursive: true
33
- });
34
- return logPath;
35
- };
36
- const ERROR_CODE_NOT_IMPLEMENTED_AS_DESIGNED = 'NOT_IMPLEMENTED_AS_DESIGNED';
37
- export { ERROR_CODE_NOT_IMPLEMENTED_AS_DESIGNED, defaultRunDirName, getMidsceneRunBaseDir, getMidsceneRunDir, getMidsceneRunSubDir };
@@ -1,223 +0,0 @@
1
- const PLAYWRIGHT_EXAMPLE_CODE = `
2
- // Reference the following code to generate Midscene test cases
3
- // The following is test code for Midscene AI, for reference
4
- // The following is Playwright syntax, you can use Playwright to assist in test generation
5
- IMPORTANT: Follow these exact type signatures for AI functions:
6
-
7
- // Type signatures for AI functions:
8
- aiAct(prompt: string, options?: { cacheable?: boolean, deepThink?: 'unset' | true | false }): Promise<void>
9
- aiInput(text: string, locate: string, options?: { deepLocate?: boolean, xpath?: string, cacheable?: boolean }): Promise<void>
10
- aiTap(locate: string, options?: { deepLocate?: boolean, xpath?: string, cacheable?: boolean }): Promise<void>
11
- aiHover(locate: string, options?: { deepLocate?: boolean, xpath?: string, cacheable?: boolean }): Promise<void>
12
- aiDoubleClick(locate: string, options?: { deepLocate?: boolean, xpath?: string, cacheable?: boolean }): Promise<void>
13
- aiKeyboardPress(key: string, locate?: string, options?: { deepLocate?: boolean, xpath?: string, cacheable?: boolean }): Promise<void>
14
- aiScroll(locate: string | undefined, options: {
15
- direction?: 'up' | 'down' | 'left' | 'right',
16
- scrollType?: 'singleAction' | 'scrollToBottom' | 'scrollToTop' | 'scrollToRight' | 'scrollToLeft',
17
- distance?: number | null,
18
- deepLocate?: boolean,
19
- xpath?: string,
20
- cacheable?: boolean
21
- }): Promise<void>
22
- aiAssert(assertion: string, options?: { errorMessage?: string }): Promise<void>
23
- aiWaitFor(prompt: string, options?: { timeout?: number }): Promise<void>
24
- aiQuery<T>(queryObject: Record<string, string>): Promise<T> // Extracts data from page based on descriptions
25
-
26
- // examples:
27
- // Reference the following code to generate Midscene test cases
28
- // The following is test code for Midscene AI, for reference
29
- // The following is Playwright syntax, you can use Playwright to assist in test generation
30
- import { test as base } from '@playwright/test';
31
- import type { PlayWrightAiFixtureType } from '@midscene/web/playwright';
32
- import { PlaywrightAiFixture } from '@midscene/web/playwright';
33
-
34
- const test = base.extend<PlayWrightAiFixtureType>(PlaywrightAiFixture({
35
- waitForNetworkIdleTimeout: 2000, // optional, the timeout for waiting for network idle between each action, default is 2000ms
36
- }));
37
-
38
-
39
- test.beforeEach(async ({ page }) => {
40
- await page.goto('https://www.xxx.com/');
41
- await page.setViewportSize({ width: 1920, height: 1080 });
42
- });
43
-
44
- test('ai shop', async ({
45
- aiAct,
46
- aiInput,
47
- aiAssert,
48
- aiQuery,
49
- aiKeyboardPress,
50
- aiHover,
51
- aiTap,
52
- aiWaitFor,
53
- agentForPage,
54
- page,
55
- }) => {
56
- // login
57
- await aiAssert('The page shows the login interface');
58
- await aiInput('user_name', 'in user name input');
59
- await aiInput('password', 'in password input');
60
- await aiKeyboardPress('Enter', 'Login Button');
61
-
62
- // check the login success
63
- await aiWaitFor('The page shows that the loading is complete');
64
- await aiAssert('The current page shows the product detail page');
65
-
66
- // check the product info
67
- const dataA = await aiQuery({
68
- userInfo: 'User information in the format {name: string}',
69
- theFirstProductInfo: 'The first product info in the format {name: string, price: number}',
70
- });
71
- expect(dataA.theFirstProductInfo.name).toBe('xxx');
72
- expect(dataA.theFirstProductInfo.price).toBe(100);
73
-
74
-
75
- // add to cart
76
- await aiTap('click add to cart button');
77
-
78
- await aiTap('click right top cart icon');
79
- await aiAssert('The cart icon shows the number 1');
80
- });
81
- `;
82
- const YAML_EXAMPLE_CODE = `
83
- 1. Format:
84
-
85
- web:
86
- url: "starting_url"
87
- viewportWidth: 1280
88
- viewportHeight: 960
89
-
90
- tasks:
91
- - name: "descriptive task name"
92
- flow:
93
- - aiTap: "element description"
94
- - aiInput: 'text value'
95
- locate: 'input field description'
96
- - aiScroll:
97
- direction: down/up
98
- scrollType: scrollToBottom/scrollToTop/singleAction
99
- - aiAssert: "expected state"
100
- - sleep: milliseconds
101
-
102
- 2. Action Types:
103
- - aiTap: for clicks (natural language targeting)
104
- - aiInput: for text input with 'locate' field
105
- - aiScroll: with direction and scrollType
106
- - aiAssert: for validations
107
- - sleep: for delays (milliseconds)
108
-
109
- 3. Best Practices:
110
- - Group related actions into logical tasks
111
- - Use natural language descriptions
112
- - Add deepLocate: true for complex interactions
113
- - Keep task names concise but descriptive
114
-
115
- 4. CRITICAL - YAML Indentation Rules:
116
- - For actions with additional parameters (aiScroll, aiInput, aiKeyboardPress), the parameters must be SIBLING keys, NOT nested children
117
- - Parameters like direction, scrollType, locate must align with the action key, not indented further
118
- - CORRECT indentation example:
119
- - aiScroll:
120
- direction: down
121
- scrollType: singleAction
122
- - WRONG indentation (DO NOT do this):
123
- - aiScroll:
124
- direction: down
125
- scrollType: singleAction
126
-
127
-
128
-
129
- YAML type
130
- tasks:
131
- - name: <name>
132
- continueOnError: <boolean> # Optional, whether to continue to the next task on error, defaults to false.
133
- flow:
134
- # Auto Planning (.ai)
135
- # ----------------
136
-
137
- # Perform an interaction. \`ai\` is a shorthand for \`aiAct\`.
138
- - ai: <prompt>
139
- cacheable: <boolean> # Optional, whether to cache the result of this API call when the [caching feature](./caching.mdx) is enabled. Defaults to True.
140
-
141
- # This usage is the same as \`ai\`.
142
- - aiAct: <prompt>
143
- cacheable: <boolean> # Optional, whether to cache the result of this API call when the [caching feature](./caching.mdx) is enabled. Defaults to True.
144
-
145
- # Instant Action (.aiTap, .aiDoubleClick, .aiHover, .aiInput, .aiKeyboardPress, .aiScroll)
146
- # ----------------
147
-
148
- # Tap an element described by a prompt.
149
- - aiTap: <prompt>
150
- deepLocate: <boolean> # Optional, whether to use deepLocate to precisely locate the element. Defaults to False.
151
- xpath: <xpath> # Optional, the xpath of the target element for the operation. If provided, Midscene will prioritize this xpath to find the element before using the cache and the AI model. Defaults to empty.
152
- cacheable: <boolean> # Optional, whether to cache the result of this API call when the [caching feature](./caching.mdx) is enabled. Defaults to True.
153
-
154
- # Double click an element described by a prompt.
155
- - aiDoubleClick: <prompt>
156
- deepLocate: <boolean> # Optional, whether to use deepLocate to precisely locate the element. Defaults to False.
157
- xpath: <xpath> # Optional, the xpath of the target element for the operation. If provided, Midscene will prioritize this xpath to find the element before using the cache and the AI model. Defaults to empty.
158
- cacheable: <boolean> # Optional, whether to cache the result of this API call when the [caching feature](./caching.mdx) is enabled. Defaults to True.
159
-
160
- # Hover over an element described by a prompt.
161
- - aiHover: <prompt>
162
- deepLocate: <boolean> # Optional, whether to use deepLocate to precisely locate the element. Defaults to False.
163
- xpath: <xpath> # Optional, the xpath of the target element for the operation. If provided, Midscene will prioritize this xpath to find the element before using the cache and the AI model. Defaults to empty.
164
- cacheable: <boolean> # Optional, whether to cache the result of this API call when the [caching feature](./caching.mdx) is enabled. Defaults to True.
165
-
166
- # Input text into an element described by a prompt.
167
- - aiInput: <final text content of the input>
168
- locate: <prompt>
169
- deepLocate: <boolean> # Optional, whether to use deepLocate to precisely locate the element. Defaults to False.
170
- xpath: <xpath> # Optional, the xpath of the target element for the operation. If provided, Midscene will prioritize this xpath to find the element before using the cache and the AI model. Defaults to empty.
171
- cacheable: <boolean> # Optional, whether to cache the result of this API call when the [caching feature](./caching.mdx) is enabled. Defaults to True.
172
-
173
- # Press a key (e.g., Enter, Tab, Escape) on an element described by a prompt.
174
- - aiKeyboardPress: <key>
175
- locate: <prompt>
176
- deepLocate: <boolean> # Optional, whether to use deepLocate to precisely locate the element. Defaults to False.
177
- xpath: <xpath> # Optional, the xpath of the target element for the operation. If provided, Midscene will prioritize this xpath to find the element before using the cache and the AI model. Defaults to empty.
178
- cacheable: <boolean> # Optional, whether to cache the result of this API call when the [caching feature](./caching.mdx) is enabled. Defaults to True.
179
-
180
- # Scroll globally or on an element described by a prompt.
181
- - aiScroll:
182
- direction: 'up' # or 'down' | 'left' | 'right'
183
- scrollType: 'singleAction' # or 'scrollToTop' | 'scrollToBottom' | 'scrollToLeft' | 'scrollToRight'
184
- distance: <number> # Optional, the scroll distance in pixels.
185
- locate: <prompt> # Optional, the element to scroll on.
186
- deepLocate: <boolean> # Optional, whether to use deepLocate to precisely locate the element. Defaults to False.
187
- xpath: <xpath> # Optional, the xpath of the target element for the operation. If provided, Midscene will prioritize this xpath to find the element before using the cache and the AI model. Defaults to empty.
188
- cacheable: <boolean> # Optional, whether to cache the result of this API call when the [caching feature](./caching.mdx) is enabled. Defaults to True.
189
-
190
- # Record the current screenshot with a description in the report file.
191
- - recordToReport: <title> # Optional, the title of the screenshot. If not provided, the title will be 'untitled'.
192
- content: <content> # Optional, the description of the screenshot.
193
-
194
- # Data Extraction
195
- # ----------------
196
-
197
- # Perform a query that returns a JSON object.
198
- - aiQuery: <prompt> # Remember to describe the format of the result in the prompt.
199
- name: <name> # The key for the query result in the JSON output.
200
-
201
- # More APIs
202
- # ----------------
203
-
204
- # Wait for a condition to be met, with a timeout (in ms, optional, defaults to 30000).
205
- - aiWaitFor: <prompt>
206
- timeout: <ms>
207
-
208
- # Perform an assertion.
209
- - aiAssert: <prompt>
210
- errorMessage: <error-message> # Optional, the error message to print if the assertion fails.
211
-
212
- # Wait for a specified amount of time.
213
- - sleep: <ms>
214
-
215
- # Execute a piece of JavaScript code in the web page context.
216
- - javascript: <javascript>
217
- name: <name> # Optional, assign a name to the return value, which will be used as a key in the JSON output.
218
-
219
- - name: <name>
220
- flow:
221
- # ...
222
- `;
223
- export { PLAYWRIGHT_EXAMPLE_CODE, YAML_EXAMPLE_CODE };
@@ -1,23 +0,0 @@
1
- import { PLAYWRIGHT_EXAMPLE_CODE, YAML_EXAMPLE_CODE } from "./example-code.mjs";
2
- const TEXT_SIZE_THRESHOLD = 9;
3
- const TEXT_MAX_SIZE = 40;
4
- const CONTAINER_MINI_HEIGHT = 3;
5
- const CONTAINER_MINI_WIDTH = 3;
6
- var constants_NodeType = /*#__PURE__*/ function(NodeType) {
7
- NodeType["CONTAINER"] = "CONTAINER Node";
8
- NodeType["FORM_ITEM"] = "FORM_ITEM Node";
9
- NodeType["BUTTON"] = "BUTTON Node";
10
- NodeType["A"] = "Anchor Node";
11
- NodeType["IMG"] = "IMG Node";
12
- NodeType["TEXT"] = "TEXT Node";
13
- NodeType["POSITION"] = "POSITION Node";
14
- return NodeType;
15
- }({});
16
- const PLAYGROUND_SERVER_PORT = 5800;
17
- const SCRCPY_SERVER_PORT = 5700;
18
- const WEBDRIVER_ELEMENT_ID_KEY = 'element-6066-11e4-a52e-4f735466cecf';
19
- const DEFAULT_WDA_PORT = 8100;
20
- const DEFAULT_WAIT_FOR_NAVIGATION_TIMEOUT = 5000;
21
- const DEFAULT_WAIT_FOR_NETWORK_IDLE_TIMEOUT = 2000;
22
- const DEFAULT_WAIT_FOR_NETWORK_IDLE_CONCURRENCY = 2;
23
- export { CONTAINER_MINI_HEIGHT, CONTAINER_MINI_WIDTH, DEFAULT_WAIT_FOR_NAVIGATION_TIMEOUT, DEFAULT_WAIT_FOR_NETWORK_IDLE_CONCURRENCY, DEFAULT_WAIT_FOR_NETWORK_IDLE_TIMEOUT, DEFAULT_WDA_PORT, constants_NodeType as NodeType, PLAYGROUND_SERVER_PORT, PLAYWRIGHT_EXAMPLE_CODE, SCRCPY_SERVER_PORT, TEXT_MAX_SIZE, TEXT_SIZE_THRESHOLD, WEBDRIVER_ELEMENT_ID_KEY, YAML_EXAMPLE_CODE };
@@ -1,6 +0,0 @@
1
- import { BASIC_ENV_KEYS } from "./types.mjs";
2
- const getBasicEnvValue = (key)=>{
3
- if (!BASIC_ENV_KEYS.includes(key)) throw new Error(`getBasicEnvValue with key ${key} is not supported.`);
4
- return process.env[key];
5
- };
6
- export { getBasicEnvValue };