@ones-open/cli 0.50.0 → 1.0.1-10001.1957

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 (188) hide show
  1. package/LICENSE +201 -674
  2. package/bin/ones.js +4 -0
  3. package/dist/index.cjs +1589 -0
  4. package/dist/index.js +1588 -0
  5. package/dist/types/actions/build/index.d.ts +4 -0
  6. package/dist/types/actions/build/index.d.ts.map +1 -0
  7. package/dist/types/actions/build/normalize.d.ts +6 -0
  8. package/dist/types/actions/build/normalize.d.ts.map +1 -0
  9. package/dist/types/actions/build/regexp.d.ts +2 -0
  10. package/dist/types/actions/build/regexp.d.ts.map +1 -0
  11. package/dist/types/actions/dev/enums.d.ts +6 -0
  12. package/dist/types/actions/dev/enums.d.ts.map +1 -0
  13. package/dist/types/actions/dev/index.d.ts +4 -0
  14. package/dist/types/actions/dev/index.d.ts.map +1 -0
  15. package/dist/types/actions/dev/normalize.d.ts +6 -0
  16. package/dist/types/actions/dev/normalize.d.ts.map +1 -0
  17. package/dist/types/actions/dev/types.d.ts +10 -0
  18. package/dist/types/actions/dev/types.d.ts.map +1 -0
  19. package/dist/types/actions/disable/index.d.ts +4 -0
  20. package/dist/types/actions/disable/index.d.ts.map +1 -0
  21. package/dist/types/actions/disable/normalize.d.ts +6 -0
  22. package/dist/types/actions/disable/normalize.d.ts.map +1 -0
  23. package/dist/types/actions/enable/index.d.ts +4 -0
  24. package/dist/types/actions/enable/index.d.ts.map +1 -0
  25. package/dist/types/actions/enable/normalize.d.ts +6 -0
  26. package/dist/types/actions/enable/normalize.d.ts.map +1 -0
  27. package/dist/types/actions/index.d.ts +15 -0
  28. package/dist/types/actions/index.d.ts.map +1 -0
  29. package/dist/types/actions/install/index.d.ts +5 -0
  30. package/dist/types/actions/install/index.d.ts.map +1 -0
  31. package/dist/types/actions/install/install.d.ts +3 -0
  32. package/dist/types/actions/install/install.d.ts.map +1 -0
  33. package/dist/types/actions/install/normalize.d.ts +6 -0
  34. package/dist/types/actions/install/normalize.d.ts.map +1 -0
  35. package/dist/types/actions/legacy/index.d.ts +4 -0
  36. package/dist/types/actions/legacy/index.d.ts.map +1 -0
  37. package/dist/types/actions/legacy/normalize.d.ts +6 -0
  38. package/dist/types/actions/legacy/normalize.d.ts.map +1 -0
  39. package/dist/types/actions/login/consts.d.ts +2 -0
  40. package/dist/types/actions/login/consts.d.ts.map +1 -0
  41. package/dist/types/actions/login/index.d.ts +4 -0
  42. package/dist/types/actions/login/index.d.ts.map +1 -0
  43. package/dist/types/actions/login/normalize.d.ts +6 -0
  44. package/dist/types/actions/login/normalize.d.ts.map +1 -0
  45. package/dist/types/actions/login/regexp.d.ts +2 -0
  46. package/dist/types/actions/login/regexp.d.ts.map +1 -0
  47. package/dist/types/actions/logout/index.d.ts +4 -0
  48. package/dist/types/actions/logout/index.d.ts.map +1 -0
  49. package/dist/types/actions/logout/normalize.d.ts +6 -0
  50. package/dist/types/actions/logout/normalize.d.ts.map +1 -0
  51. package/dist/types/actions/tunnel/consts.d.ts +6 -0
  52. package/dist/types/actions/tunnel/consts.d.ts.map +1 -0
  53. package/dist/types/actions/tunnel/index.d.ts +7 -0
  54. package/dist/types/actions/tunnel/index.d.ts.map +1 -0
  55. package/dist/types/actions/tunnel/normalize.d.ts +6 -0
  56. package/dist/types/actions/tunnel/normalize.d.ts.map +1 -0
  57. package/dist/types/actions/tunnel/regexp.d.ts +2 -0
  58. package/dist/types/actions/tunnel/regexp.d.ts.map +1 -0
  59. package/dist/types/actions/tunnel/tunnel-client.d.ts +25 -0
  60. package/dist/types/actions/tunnel/tunnel-client.d.ts.map +1 -0
  61. package/dist/types/actions/tunnel/tunnel.d.ts +3 -0
  62. package/dist/types/actions/tunnel/tunnel.d.ts.map +1 -0
  63. package/dist/types/actions/tunnel/types.d.ts +33 -0
  64. package/dist/types/actions/tunnel/types.d.ts.map +1 -0
  65. package/dist/types/actions/tunnel/utils.d.ts +7 -0
  66. package/dist/types/actions/tunnel/utils.d.ts.map +1 -0
  67. package/dist/types/actions/uninstall/index.d.ts +4 -0
  68. package/dist/types/actions/uninstall/index.d.ts.map +1 -0
  69. package/dist/types/actions/uninstall/normalize.d.ts +6 -0
  70. package/dist/types/actions/uninstall/normalize.d.ts.map +1 -0
  71. package/dist/types/actions/whoami/index.d.ts +4 -0
  72. package/dist/types/actions/whoami/index.d.ts.map +1 -0
  73. package/dist/types/actions/whoami/normalize.d.ts +6 -0
  74. package/dist/types/actions/whoami/normalize.d.ts.map +1 -0
  75. package/dist/types/cli/index.d.ts +2 -0
  76. package/dist/types/cli/index.d.ts.map +1 -0
  77. package/dist/types/command/app/index.d.ts +4 -0
  78. package/dist/types/command/app/index.d.ts.map +1 -0
  79. package/dist/types/command/build/index.d.ts +9 -0
  80. package/dist/types/command/build/index.d.ts.map +1 -0
  81. package/dist/types/command/dev/index.d.ts +10 -0
  82. package/dist/types/command/dev/index.d.ts.map +1 -0
  83. package/dist/types/command/disable/index.d.ts +8 -0
  84. package/dist/types/command/disable/index.d.ts.map +1 -0
  85. package/dist/types/command/enable/index.d.ts +8 -0
  86. package/dist/types/command/enable/index.d.ts.map +1 -0
  87. package/dist/types/command/index.d.ts +16 -0
  88. package/dist/types/command/index.d.ts.map +1 -0
  89. package/dist/types/command/install/index.d.ts +8 -0
  90. package/dist/types/command/install/index.d.ts.map +1 -0
  91. package/dist/types/command/legacy/index.d.ts +8 -0
  92. package/dist/types/command/legacy/index.d.ts.map +1 -0
  93. package/dist/types/command/login/index.d.ts +8 -0
  94. package/dist/types/command/login/index.d.ts.map +1 -0
  95. package/dist/types/command/logout/index.d.ts +8 -0
  96. package/dist/types/command/logout/index.d.ts.map +1 -0
  97. package/dist/types/command/tunnel/index.d.ts +8 -0
  98. package/dist/types/command/tunnel/index.d.ts.map +1 -0
  99. package/dist/types/command/uninstall/index.d.ts +8 -0
  100. package/dist/types/command/uninstall/index.d.ts.map +1 -0
  101. package/dist/types/command/whoami/index.d.ts +8 -0
  102. package/dist/types/command/whoami/index.d.ts.map +1 -0
  103. package/dist/types/common/base/index.d.ts +5 -0
  104. package/dist/types/common/base/index.d.ts.map +1 -0
  105. package/dist/types/common/base/utils.d.ts +7 -0
  106. package/dist/types/common/base/utils.d.ts.map +1 -0
  107. package/dist/types/common/command/index.d.ts +6 -0
  108. package/dist/types/common/command/index.d.ts.map +1 -0
  109. package/dist/types/common/command/types.d.ts +2 -0
  110. package/dist/types/common/command/types.d.ts.map +1 -0
  111. package/dist/types/common/command/utils.d.ts +2 -0
  112. package/dist/types/common/command/utils.d.ts.map +1 -0
  113. package/dist/types/common/config/index.d.ts +6 -0
  114. package/dist/types/common/config/index.d.ts.map +1 -0
  115. package/dist/types/common/config/types.d.ts +8 -0
  116. package/dist/types/common/config/types.d.ts.map +1 -0
  117. package/dist/types/common/config/utils.d.ts +3 -0
  118. package/dist/types/common/config/utils.d.ts.map +1 -0
  119. package/dist/types/common/context/index.d.ts +6 -0
  120. package/dist/types/common/context/index.d.ts.map +1 -0
  121. package/dist/types/common/context/types.d.ts +2 -0
  122. package/dist/types/common/context/types.d.ts.map +1 -0
  123. package/dist/types/common/context/utils.d.ts +2 -0
  124. package/dist/types/common/context/utils.d.ts.map +1 -0
  125. package/dist/types/common/error/enums.d.ts +19 -0
  126. package/dist/types/common/error/enums.d.ts.map +1 -0
  127. package/dist/types/common/error/index.d.ts +7 -0
  128. package/dist/types/common/error/index.d.ts.map +1 -0
  129. package/dist/types/common/error/types.d.ts +2 -0
  130. package/dist/types/common/error/types.d.ts.map +1 -0
  131. package/dist/types/common/error/utils.d.ts +2 -0
  132. package/dist/types/common/error/utils.d.ts.map +1 -0
  133. package/dist/types/common/locales/en/index.d.ts +34 -0
  134. package/dist/types/common/locales/en/index.d.ts.map +1 -0
  135. package/dist/types/common/locales/index.d.ts +6 -0
  136. package/dist/types/common/locales/index.d.ts.map +1 -0
  137. package/dist/types/common/locales/types.d.ts +4 -0
  138. package/dist/types/common/locales/types.d.ts.map +1 -0
  139. package/dist/types/common/locales/utils.d.ts +6 -0
  140. package/dist/types/common/locales/utils.d.ts.map +1 -0
  141. package/dist/types/common/package/index.d.ts +7 -0
  142. package/dist/types/common/package/index.d.ts.map +1 -0
  143. package/dist/types/common/package/schema.d.ts +3 -0
  144. package/dist/types/common/package/schema.d.ts.map +1 -0
  145. package/dist/types/common/package/types.d.ts +2 -0
  146. package/dist/types/common/package/types.d.ts.map +1 -0
  147. package/dist/types/common/package/utils.d.ts +14 -0
  148. package/dist/types/common/package/utils.d.ts.map +1 -0
  149. package/dist/types/common/public/consts.d.ts +2 -0
  150. package/dist/types/common/public/consts.d.ts.map +1 -0
  151. package/dist/types/common/public/index.d.ts +6 -0
  152. package/dist/types/common/public/index.d.ts.map +1 -0
  153. package/dist/types/common/public/utils.d.ts +2 -0
  154. package/dist/types/common/public/utils.d.ts.map +1 -0
  155. package/dist/types/common/request/consts.d.ts +13 -0
  156. package/dist/types/common/request/consts.d.ts.map +1 -0
  157. package/dist/types/common/request/fetch.d.ts +12 -0
  158. package/dist/types/common/request/fetch.d.ts.map +1 -0
  159. package/dist/types/common/request/index.d.ts +8 -0
  160. package/dist/types/common/request/index.d.ts.map +1 -0
  161. package/dist/types/common/request/types.d.ts +92 -0
  162. package/dist/types/common/request/types.d.ts.map +1 -0
  163. package/dist/types/common/request/utils.d.ts +8 -0
  164. package/dist/types/common/request/utils.d.ts.map +1 -0
  165. package/dist/types/common/store/index.d.ts +6 -0
  166. package/dist/types/common/store/index.d.ts.map +1 -0
  167. package/dist/types/common/store/schema.d.ts +25 -0
  168. package/dist/types/common/store/schema.d.ts.map +1 -0
  169. package/dist/types/common/store/utils.d.ts +13 -0
  170. package/dist/types/common/store/utils.d.ts.map +1 -0
  171. package/dist/types/index.d.ts +2 -0
  172. package/dist/types/index.d.ts.map +1 -0
  173. package/index.d.ts +2 -0
  174. package/index.js +2 -0
  175. package/package.json +57 -38
  176. package/public/callback.html +65 -0
  177. package/public/logo.svg +4 -0
  178. package/bin/index.es.js +0 -261
  179. package/bin/types/index.d.ts +0 -2
  180. package/bin/types/index.d.ts.map +0 -1
  181. package/bin/types/lib/create.d.ts +0 -4
  182. package/bin/types/lib/create.d.ts.map +0 -1
  183. package/bin/types/lib/env.d.ts +0 -6
  184. package/bin/types/lib/env.d.ts.map +0 -1
  185. package/template/_prettierignore +0 -13
  186. package/template/_prettierrc +0 -6
  187. package/template/browserslist +0 -4
  188. package/template/package.json +0 -5
package/dist/index.cjs ADDED
@@ -0,0 +1,1589 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const _includesInstanceProperty = require("@babel/runtime-corejs3/core-js-stable/instance/includes");
4
+ const commander = require("commander");
5
+ const createOnesApp = require("create-ones-app");
6
+ const node_path = require("node:path");
7
+ const node_child_process = require("node:child_process");
8
+ const node_fs = require("node:fs");
9
+ const fse = require("fs-extra");
10
+ const archiver = require("archiver");
11
+ const lodashEs = require("lodash-es");
12
+ const process$1 = require("node:process");
13
+ const node_url = require("node:url");
14
+ const cosmiconfig = require("cosmiconfig");
15
+ const getPort = require("get-port");
16
+ const envPaths = require("env-paths");
17
+ const zod = require("zod");
18
+ const axios = require("axios");
19
+ const _reduceInstanceProperty = require("@babel/runtime-corejs3/core-js-stable/instance/reduce");
20
+ const WebSocket = require("ws");
21
+ const http = require("node:http");
22
+ const ora = require("ora");
23
+ const open = require("open");
24
+ const uuid = require("uuid");
25
+ var _documentCurrentScript = typeof document !== "undefined" ? document.currentScript : null;
26
+ const en = {
27
+ "desc.ones": "ONES CLI/{env}",
28
+ "desc.build": "Build your ONES App",
29
+ "desc.build.output": "Specify the output file path",
30
+ "desc.dev": "Start your local development server and connect to ONES",
31
+ "desc.dev.install": "Install your ONES App after the server is ready",
32
+ "desc.dev.command": "Specify the dev command",
33
+ "desc.tunnel": "Start a tunnel to connect your local server with ONES",
34
+ "desc.tunnel.port": "Specify the port number for tunnel",
35
+ "desc.login": "Log in to your ONES account",
36
+ "desc.login.baseUrl": "Specify the ONES URL for login",
37
+ "desc.logout": "Log out of your ONES account",
38
+ "desc.whoami": "Display the account information of the logged in user",
39
+ "desc.app": "Manage app installations",
40
+ "desc.install": "Install your ONES App",
41
+ "desc.enable": "Enable your ONES App",
42
+ "desc.disable": "Disable your ONES App",
43
+ "desc.uninstall": "Uninstall your ONES App",
44
+ "desc.legacy": "Legacy command",
45
+ "error.login.missingBaseURL": "Missing base URL",
46
+ "error.login.incorrectBaseURL": "Incorrect base URL",
47
+ "error.tunnel.missingPort": "Missing port",
48
+ "error.tunnel.incorrectPort": "Incorrect port",
49
+ "error.schema.app.package.parseError": "App package JSON parse error",
50
+ "error.schema.app.manifest.parseError": 'App "opkx.json" JSON parse error',
51
+ "error.build.scriptNotFound": 'Npm "build" script not found',
52
+ "error.dev.scriptNotFound": 'Npm "dev" script not found',
53
+ "error.dev.incorrectCommand": "Incorrect dev command",
54
+ "error.store.permission": 'Permission denied, please check the file permission with "{filePath}"',
55
+ "error.hostedToken.requestFailed": "Failed to request hosted token",
56
+ "error.hostedToken.empty": "Hosted token is empty"
57
+ };
58
+ const map = {
59
+ en
60
+ };
61
+ const getCurrentLanguageList = () => {
62
+ return ["en"];
63
+ };
64
+ const translate = (key, params) => {
65
+ const list = getCurrentLanguageList();
66
+ for (let index = 0; index < list.length; index++) {
67
+ const language = list[index];
68
+ let value = lodashEs.get(map[language], key);
69
+ if (value) {
70
+ if (params && typeof value === "string") {
71
+ value = value.replace(/\{(\w+)\}/g, (match, paramKey) => {
72
+ var _params$paramKey;
73
+ const result = (_params$paramKey = params === null || params === void 0 ? void 0 : params[paramKey]) !== null && _params$paramKey !== void 0 ? _params$paramKey : match;
74
+ return String(result);
75
+ });
76
+ }
77
+ return value;
78
+ }
79
+ }
80
+ return key;
81
+ };
82
+ const i18n = {
83
+ t: translate
84
+ };
85
+ var ErrorCode = ((ErrorCode2) => {
86
+ ErrorCode2[ErrorCode2["UNKNOWN_ERROR"] = createOnesApp.ErrorCode.UNKNOWN_ERROR] = "UNKNOWN_ERROR";
87
+ ErrorCode2[ErrorCode2["COMMAND_ERROR"] = createOnesApp.ErrorCode.COMMAND_ERROR] = "COMMAND_ERROR";
88
+ ErrorCode2[ErrorCode2["TEMPLATE_NOT_FOUND"] = createOnesApp.ErrorCode.TEMPLATE_NOT_FOUND] = "TEMPLATE_NOT_FOUND";
89
+ ErrorCode2[ErrorCode2["MISSING_PROJECT_PATH"] = createOnesApp.ErrorCode.MISSING_PROJECT_PATH] = "MISSING_PROJECT_PATH";
90
+ ErrorCode2["MISSING_BASE_URL"] = "E04";
91
+ ErrorCode2["MISSING_PORT"] = "E05";
92
+ ErrorCode2["INCORRECT_BASE_URL"] = "E06";
93
+ ErrorCode2["INCORRECT_PORT"] = "E07";
94
+ ErrorCode2["APP_PACKAGE_JSON_PARSE_ERROR"] = "E08";
95
+ ErrorCode2["APP_MANIFEST_JSON_PARSE_ERROR"] = "E09";
96
+ ErrorCode2["BUILD_SCRIPT_NOT_FOUND"] = "E10";
97
+ ErrorCode2["DEV_SCRIPT_NOT_FOUND"] = "E11";
98
+ ErrorCode2["STORE_PERMISSION"] = "E12";
99
+ ErrorCode2["HOSTED_TOKEN_REQUEST_FAILED"] = "E13";
100
+ ErrorCode2["HOSTED_TOKEN_EMPTY"] = "E14";
101
+ ErrorCode2["INCORRECT_DEV_COMMAND"] = "E15";
102
+ return ErrorCode2;
103
+ })(ErrorCode || {});
104
+ const getPublicPath = () => {
105
+ const __dirname = node_path.dirname(node_url.fileURLToPath(typeof document === "undefined" ? require("url").pathToFileURL(__filename).href : _documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === "SCRIPT" && _documentCurrentScript.src || new URL("index.cjs", document.baseURI).href));
106
+ return node_path.join(__dirname, "../public");
107
+ };
108
+ const getPackageJSONPath = () => {
109
+ const __dirname = node_path.dirname(node_url.fileURLToPath(typeof document === "undefined" ? require("url").pathToFileURL(__filename).href : _documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === "SCRIPT" && _documentCurrentScript.src || new URL("index.cjs", document.baseURI).href));
110
+ return node_path.join(__dirname, "../package.json");
111
+ };
112
+ const getPackageJSON = () => {
113
+ const path = getPackageJSONPath();
114
+ try {
115
+ const string = node_fs.readFileSync(path, {
116
+ encoding: "utf8"
117
+ });
118
+ return JSON.parse(string);
119
+ } catch (error) {
120
+ return {};
121
+ }
122
+ };
123
+ const getAppWorkspacePath = () => {
124
+ return node_path.join(process$1.cwd());
125
+ };
126
+ const getAppPackageJSONPath = () => {
127
+ return node_path.join(process$1.cwd(), "./package.json");
128
+ };
129
+ const getAppPackageJSON = () => {
130
+ const path = getAppPackageJSONPath();
131
+ try {
132
+ const string = node_fs.readFileSync(path, {
133
+ encoding: "utf8"
134
+ });
135
+ const json = JSON.parse(string);
136
+ return createOnesApp.AppPackageJSONSchema.parse(json);
137
+ } catch (error) {
138
+ const details = error instanceof Error ? error.message : String(error);
139
+ return createOnesApp.throwError(ErrorCode.APP_PACKAGE_JSON_PARSE_ERROR, `${i18n.t("error.schema.app.package.parseError")}: ${details}`);
140
+ }
141
+ };
142
+ const getAppManifestJSONPath = () => {
143
+ return node_path.join(process$1.cwd(), createOnesApp.PUBLIC_FILENAME.MANIFEST);
144
+ };
145
+ const getAppManifestJSON = () => {
146
+ const path = getAppManifestJSONPath();
147
+ try {
148
+ const string = node_fs.readFileSync(path, {
149
+ encoding: "utf8"
150
+ });
151
+ const json = JSON.parse(string);
152
+ return createOnesApp.AppManifestJSONSchema.parse(json);
153
+ } catch (error) {
154
+ const details = error instanceof Error ? error.message : String(error);
155
+ return createOnesApp.throwError(ErrorCode.APP_MANIFEST_JSON_PARSE_ERROR, `${i18n.t("error.schema.app.manifest.parseError")}: ${details}`);
156
+ }
157
+ };
158
+ const defaultDevCommand = ["npm", "run", "dev"];
159
+ const defaultAppRcJSON = {
160
+ dev: {
161
+ command: defaultDevCommand
162
+ }
163
+ };
164
+ let storeAppRcJSON = null;
165
+ const getAppRcJSON = async () => {
166
+ if (storeAppRcJSON)
167
+ ;
168
+ else {
169
+ try {
170
+ const path = node_path.join(createOnesApp.getPublicPath(), createOnesApp.PUBLIC_FILENAME.RC);
171
+ const string = node_fs.readFileSync(path, {
172
+ encoding: "utf8"
173
+ });
174
+ const json = JSON.parse(string);
175
+ storeAppRcJSON = createOnesApp.AppRcJSONSchema.parse(json);
176
+ } catch (error) {
177
+ storeAppRcJSON = {};
178
+ }
179
+ }
180
+ const templateAppRcJSON = storeAppRcJSON || {};
181
+ let currentAppRcJSON;
182
+ const explorer = cosmiconfig.cosmiconfig("ones");
183
+ try {
184
+ const result = await explorer.search();
185
+ const json = result === null || result === void 0 ? void 0 : result.config;
186
+ currentAppRcJSON = createOnesApp.AppRcJSONSchema.parse(json);
187
+ } catch (error) {
188
+ currentAppRcJSON = {};
189
+ }
190
+ return {
191
+ ...defaultAppRcJSON,
192
+ ...templateAppRcJSON,
193
+ ...currentAppRcJSON
194
+ };
195
+ };
196
+ const isOPKXFilename = /\.opkx$/;
197
+ const defaultOutputPath = "";
198
+ const normalize$a = async (options) => {
199
+ var _options$output;
200
+ let output = node_path.resolve(process$1.cwd(), (_options$output = options.output) !== null && _options$output !== void 0 ? _options$output : defaultOutputPath);
201
+ if (isOPKXFilename.test(output))
202
+ ;
203
+ else {
204
+ const appManifestJSON = getAppManifestJSON();
205
+ const defaultOutputFilename = `${appManifestJSON.app.name}.opkx`;
206
+ output = node_path.resolve(output, defaultOutputFilename);
207
+ }
208
+ return {
209
+ output
210
+ };
211
+ };
212
+ const {
213
+ existsSync,
214
+ ensureDirSync
215
+ } = fse;
216
+ const build = async function() {
217
+ var _appRcJSON$build$comp, _appRcJSON$build;
218
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
219
+ args[_key] = arguments[_key];
220
+ }
221
+ const {
222
+ options
223
+ } = createOnesApp.getCommandOptions(args, buildCommandArguments);
224
+ const normalizedOptions = await normalize$a(options);
225
+ const appManifestJSON = getAppManifestJSON();
226
+ const appRcJSON = await getAppRcJSON();
227
+ const appPackageJSONPath = getAppPackageJSONPath();
228
+ const isExists = existsSync(appPackageJSONPath);
229
+ if (isExists) {
230
+ var _appPackageJSON$scrip;
231
+ const appPackageJSON = getAppPackageJSON();
232
+ if ((_appPackageJSON$scrip = appPackageJSON.scripts) !== null && _appPackageJSON$scrip !== void 0 && _appPackageJSON$scrip.build) {
233
+ const buildResult = node_child_process.spawnSync("npm", ["run", "build"], {
234
+ cwd: getAppWorkspacePath(),
235
+ stdio: "inherit",
236
+ env: {
237
+ ...process.env,
238
+ NODE_ENV: "production"
239
+ }
240
+ });
241
+ if (buildResult.status !== 0 || buildResult.signal) {
242
+ var _buildResult$status;
243
+ process.exit((_buildResult$status = buildResult.status) !== null && _buildResult$status !== void 0 ? _buildResult$status : 1);
244
+ }
245
+ } else {
246
+ return createOnesApp.throwError(ErrorCode.BUILD_SCRIPT_NOT_FOUND, i18n.t("error.build.scriptNotFound"));
247
+ }
248
+ }
249
+ const appName = appManifestJSON.app.name;
250
+ const outputPath = normalizedOptions.output;
251
+ const outputDir = node_path.dirname(outputPath);
252
+ const outputFilename = node_path.basename(outputPath);
253
+ ensureDirSync(outputDir);
254
+ const outputStream = node_fs.createWriteStream(outputPath);
255
+ const files = (_appRcJSON$build$comp = (_appRcJSON$build = appRcJSON.build) === null || _appRcJSON$build === void 0 || (_appRcJSON$build = _appRcJSON$build.compress) === null || _appRcJSON$build === void 0 ? void 0 : _appRcJSON$build.files) !== null && _appRcJSON$build$comp !== void 0 ? _appRcJSON$build$comp : [];
256
+ const archive = archiver("zip", {
257
+ zlib: {
258
+ level: 9
259
+ }
260
+ });
261
+ archive.on("error", (err) => {
262
+ throw err;
263
+ });
264
+ archive.on("warning", (err) => {
265
+ throw err;
266
+ });
267
+ archive.on("progress", (progress) => {
268
+ const {
269
+ entries,
270
+ fs
271
+ } = progress;
272
+ const entriesStr = entries.total > 0 ? ` ${entries.processed}/${entries.total} files` : "";
273
+ const bytesStr = fs.totalBytes > 0 ? ` ${(fs.processedBytes / 1024).toFixed(1)}/${(fs.totalBytes / 1024).toFixed(1)} KB` : "";
274
+ process.stdout.write(`\rCompressing:${entriesStr}${bytesStr} `);
275
+ });
276
+ archive.on("finish", () => {
277
+ process.stdout.write("\n");
278
+ console.log("");
279
+ console.log("Files in archive: ", createOnesApp.PUBLIC_FILENAME.MANIFEST, files);
280
+ console.log(`App "${appName}" built successfully!`);
281
+ console.log(`OPKX "${outputFilename}" created successfully!`);
282
+ console.log(`Output file: ${outputPath}`);
283
+ });
284
+ archive.pipe(outputStream);
285
+ files.forEach((file) => {
286
+ archive.glob(file, {
287
+ cwd: getAppWorkspacePath()
288
+ });
289
+ });
290
+ archive.file(createOnesApp.PUBLIC_FILENAME.MANIFEST, {
291
+ name: createOnesApp.PUBLIC_FILENAME.MANIFEST
292
+ });
293
+ archive.finalize();
294
+ };
295
+ const config = {
296
+ defaultPort: {
297
+ login: 8200,
298
+ hosted: 8201,
299
+ devWebServer: 8202
300
+ }
301
+ };
302
+ const getConfig = () => config;
303
+ const StoreJSONSchema = zod.z.object({
304
+ version: zod.z.string().optional(),
305
+ timestamp: zod.z.number().optional(),
306
+ base_url: zod.z.string().optional(),
307
+ region_url: zod.z.string().optional(),
308
+ ones_token: zod.z.string().optional(),
309
+ host_token: zod.z.string().optional()
310
+ });
311
+ const {
312
+ ensureFile,
313
+ readJSON,
314
+ writeJSON
315
+ } = fse;
316
+ const name = "@ones-open/cli";
317
+ const paths = envPaths(name);
318
+ const storeDir = paths.config;
319
+ const storePath = node_path.join(storeDir, "config.json");
320
+ const getStore = async () => {
321
+ let json = {};
322
+ try {
323
+ await ensureFile(storePath);
324
+ json = await readJSON(storePath, {
325
+ encoding: "utf8"
326
+ });
327
+ } catch (error) {
328
+ const $error = error;
329
+ if ($error.code === "EPERM" || $error.code === "EACCES") {
330
+ return createOnesApp.throwError(ErrorCode.STORE_PERMISSION, i18n.t("error.store.permission", {
331
+ filePath: storePath
332
+ }));
333
+ }
334
+ if ($error instanceof SyntaxError) {
335
+ return {};
336
+ }
337
+ throw error;
338
+ }
339
+ try {
340
+ return StoreJSONSchema.parse(json);
341
+ } catch (error) {
342
+ return {};
343
+ }
344
+ };
345
+ const setStore = async (store) => {
346
+ try {
347
+ await ensureFile(storePath);
348
+ const version2 = `${getPackageJSON().version}`;
349
+ const timestamp = Date.now();
350
+ return await writeJSON(storePath, {
351
+ ...store,
352
+ version: version2,
353
+ timestamp
354
+ }, {
355
+ encoding: "utf8"
356
+ });
357
+ } catch (error) {
358
+ const $error = error;
359
+ if ($error.code === "EPERM" || $error.code === "EACCES") {
360
+ return createOnesApp.throwError(ErrorCode.STORE_PERMISSION, i18n.t("error.store.permission", {
361
+ filePath: storePath
362
+ }));
363
+ }
364
+ throw error;
365
+ }
366
+ };
367
+ const mergeStore = async (store) => {
368
+ const currentStore = await getStore();
369
+ return setStore({
370
+ ...currentStore,
371
+ ...store
372
+ });
373
+ };
374
+ const getBaseURL = async () => {
375
+ var _store$base_url;
376
+ const store = await getStore();
377
+ return (_store$base_url = store.base_url) !== null && _store$base_url !== void 0 ? _store$base_url : "";
378
+ };
379
+ const setBaseURL = async (baseURL) => {
380
+ return mergeStore({
381
+ base_url: baseURL
382
+ });
383
+ };
384
+ const getRegionURL = async () => {
385
+ var _store$region_url;
386
+ const store = await getStore();
387
+ return (_store$region_url = store.region_url) !== null && _store$region_url !== void 0 ? _store$region_url : "";
388
+ };
389
+ const setRegionURL = async (regionURL) => {
390
+ return mergeStore({
391
+ region_url: regionURL
392
+ });
393
+ };
394
+ const getONESToken = async () => {
395
+ var _store$ones_token;
396
+ const store = await getStore();
397
+ return (_store$ones_token = store.ones_token) !== null && _store$ones_token !== void 0 ? _store$ones_token : "";
398
+ };
399
+ const setONESToken = async (token) => {
400
+ return mergeStore({
401
+ ones_token: token
402
+ });
403
+ };
404
+ const getHostToken = async () => {
405
+ var _store$host_token;
406
+ const store = await getStore();
407
+ return (_store$host_token = store.host_token) !== null && _store$host_token !== void 0 ? _store$host_token : "";
408
+ };
409
+ const setHostToken = async (token) => {
410
+ return mergeStore({
411
+ host_token: token
412
+ });
413
+ };
414
+ const API = {
415
+ TOKEN_INFO: "/project/api/project/auth/token_info",
416
+ HOSTED_TOKEN: "/platform/runtime_manager/hosted_token",
417
+ HOSTED_ABILITY_STORAGE_DEV_DECLARE: "/platform/runtime_manager/hosted_ability/storage/dev_declare",
418
+ APP_LIST: "/platform/api/app/list",
419
+ APP_INSTALL: "/platform/api/app/install",
420
+ APP_UPGRADE: "/platform/api/app/upgrade",
421
+ APP_UNINSTALL: "/platform/api/app/:installation_id/uninstall",
422
+ APP_ENABLE: "/platform/api/app/:installation_id/enable",
423
+ APP_DISABLE: "/platform/api/app/:installation_id/disable"
424
+ };
425
+ const REQUEST_TIMEOUT = 1e4;
426
+ const getPath = (path, map2) => {
427
+ var _context;
428
+ return _reduceInstanceProperty(_context = path.split("/")).call(_context, (base, part) => {
429
+ if (/^:/.test(part)) {
430
+ return `${base}/${map2[part.slice(1)]}`;
431
+ }
432
+ return `${base}/${part}`;
433
+ }, "").slice(1);
434
+ };
435
+ const consoleUnauthorizedMessage = () => {
436
+ console.log("Not logged in");
437
+ console.log('Login with "ones login" command');
438
+ process.exit(1);
439
+ };
440
+ const consoleAppNotInstalledMessage = () => {
441
+ console.log("App not installed");
442
+ process.exit(1);
443
+ };
444
+ const getURL = async (path, pathMap, queryMap) => {
445
+ const base = await getRegionURL();
446
+ if (base) {
447
+ const query = new URLSearchParams(queryMap !== null && queryMap !== void 0 ? queryMap : {}).toString();
448
+ return `${base}${getPath(path, pathMap !== null && pathMap !== void 0 ? pathMap : {})}${query ? `?${query}` : ""}`;
449
+ }
450
+ consoleUnauthorizedMessage();
451
+ };
452
+ const getHeaders = async (value) => {
453
+ const token = await getONESToken();
454
+ if (token) {
455
+ return lodashEs.merge({
456
+ Authorization: `Bearer ${token}`
457
+ }, value);
458
+ }
459
+ consoleUnauthorizedMessage();
460
+ process.exit(1);
461
+ };
462
+ const handleError = (error) => {
463
+ var _error$response, _error$response2;
464
+ if (((_error$response = error.response) === null || _error$response === void 0 ? void 0 : _error$response.status) === 401) {
465
+ console.log(error.response.statusText);
466
+ consoleUnauthorizedMessage();
467
+ process.exit(1);
468
+ }
469
+ if ((_error$response2 = error.response) !== null && _error$response2 !== void 0 && _error$response2.data) {
470
+ try {
471
+ const message = JSON.stringify(error.response.data, null, 2);
472
+ console.error(message);
473
+ process.exit(1);
474
+ } catch (error2) {
475
+ }
476
+ }
477
+ console.error(error);
478
+ return {};
479
+ };
480
+ const fetchAppBase = async (params) => {
481
+ var _params$url;
482
+ const url = await getURL((_params$url = params.url) !== null && _params$url !== void 0 ? _params$url : "", params.pathMap, params.queryMap);
483
+ const headers = await getHeaders(params.headers);
484
+ const response = await axios({
485
+ ...params,
486
+ url,
487
+ headers,
488
+ timeout: REQUEST_TIMEOUT
489
+ });
490
+ return response.data;
491
+ };
492
+ const fetchAppList = async (appID) => {
493
+ return await fetchAppBase({
494
+ url: API.APP_LIST,
495
+ method: "GET",
496
+ queryMap: {
497
+ app_id: appID
498
+ }
499
+ }).catch(handleError);
500
+ };
501
+ const fetchTokenInfo = async () => {
502
+ return await fetchAppBase({
503
+ url: API.TOKEN_INFO,
504
+ method: "GET"
505
+ }).catch(handleError);
506
+ };
507
+ const fetchHostedToken = async (data) => {
508
+ return await fetchAppBase({
509
+ url: API.HOSTED_TOKEN,
510
+ method: "POST",
511
+ data
512
+ }).catch(handleError);
513
+ };
514
+ const fetchHostedAbilityStorageDevDeclare = async (data) => {
515
+ return await fetchAppBase({
516
+ url: API.HOSTED_ABILITY_STORAGE_DEV_DECLARE,
517
+ method: "POST",
518
+ data
519
+ }).catch(handleError);
520
+ };
521
+ const fetchAppInstall = async (data) => {
522
+ var _appList$data$0$insta, _appList$data;
523
+ const appID = getAppManifestJSON().app.id;
524
+ const appList = await fetchAppList(appID);
525
+ const installationID = (_appList$data$0$insta = (_appList$data = appList.data) === null || _appList$data === void 0 || (_appList$data = _appList$data[0]) === null || _appList$data === void 0 ? void 0 : _appList$data.installation_id) !== null && _appList$data$0$insta !== void 0 ? _appList$data$0$insta : "";
526
+ const url = installationID ? API.APP_UPGRADE : API.APP_INSTALL;
527
+ return await fetchAppBase({
528
+ url,
529
+ method: "POST",
530
+ data
531
+ }).catch(handleError);
532
+ };
533
+ const fetchAppUninstall = async () => {
534
+ var _appList$data$0$insta2, _appList$data2;
535
+ const appID = getAppManifestJSON().app.id;
536
+ const appList = await fetchAppList(appID);
537
+ const installationID = (_appList$data$0$insta2 = (_appList$data2 = appList.data) === null || _appList$data2 === void 0 || (_appList$data2 = _appList$data2[0]) === null || _appList$data2 === void 0 ? void 0 : _appList$data2.installation_id) !== null && _appList$data$0$insta2 !== void 0 ? _appList$data$0$insta2 : "";
538
+ if (installationID) {
539
+ return await fetchAppBase({
540
+ url: API.APP_UNINSTALL,
541
+ method: "POST",
542
+ pathMap: {
543
+ installation_id: installationID
544
+ }
545
+ }).catch(handleError);
546
+ }
547
+ consoleAppNotInstalledMessage();
548
+ process.exit(1);
549
+ };
550
+ const fetchAppEnable = async () => {
551
+ var _appList$data$0$insta3, _appList$data3;
552
+ const appID = getAppManifestJSON().app.id;
553
+ const appList = await fetchAppList(appID);
554
+ const installationID = (_appList$data$0$insta3 = (_appList$data3 = appList.data) === null || _appList$data3 === void 0 || (_appList$data3 = _appList$data3[0]) === null || _appList$data3 === void 0 ? void 0 : _appList$data3.installation_id) !== null && _appList$data$0$insta3 !== void 0 ? _appList$data$0$insta3 : "";
555
+ if (installationID) {
556
+ return await fetchAppBase({
557
+ url: API.APP_ENABLE,
558
+ method: "POST",
559
+ pathMap: {
560
+ installation_id: installationID
561
+ }
562
+ }).catch(handleError);
563
+ }
564
+ consoleAppNotInstalledMessage();
565
+ process.exit(1);
566
+ };
567
+ const fetchAppDisable = async () => {
568
+ var _appList$data$0$insta4, _appList$data4;
569
+ const appID = getAppManifestJSON().app.id;
570
+ const appList = await fetchAppList(appID);
571
+ const installationID = (_appList$data$0$insta4 = (_appList$data4 = appList.data) === null || _appList$data4 === void 0 || (_appList$data4 = _appList$data4[0]) === null || _appList$data4 === void 0 ? void 0 : _appList$data4.installation_id) !== null && _appList$data$0$insta4 !== void 0 ? _appList$data$0$insta4 : "";
572
+ if (installationID) {
573
+ return await fetchAppBase({
574
+ url: API.APP_DISABLE,
575
+ method: "POST",
576
+ pathMap: {
577
+ installation_id: installationID
578
+ }
579
+ }).catch(handleError);
580
+ }
581
+ consoleAppNotInstalledMessage();
582
+ process.exit(1);
583
+ };
584
+ const checkTokenInfo = async () => {
585
+ var _store$ones_token, _store$region_url;
586
+ let boolean = true;
587
+ const store = await getStore();
588
+ const token = (_store$ones_token = store.ones_token) !== null && _store$ones_token !== void 0 ? _store$ones_token : "";
589
+ const regionURL = (_store$region_url = store.region_url) !== null && _store$region_url !== void 0 ? _store$region_url : "";
590
+ if (token && regionURL) {
591
+ await fetchAppBase({
592
+ url: API.TOKEN_INFO,
593
+ method: "GET"
594
+ }).catch(() => {
595
+ boolean = false;
596
+ });
597
+ } else {
598
+ boolean = false;
599
+ }
600
+ return boolean;
601
+ };
602
+ const isPortNumber = /^[1-9]\d{0,4}$/;
603
+ const minPortNumber = 1;
604
+ const maxPortNumber = 65535;
605
+ const MANIFEST_PATH = "/manifest";
606
+ const ONES_CLI_INTERNAL_MANIFEST_PATH = "/__ones_cli_internal_manifest__";
607
+ const MAX_RELAY_BODY_BYTES = 64 * 1024 * 1024;
608
+ const normalize$9 = async (options) => {
609
+ const portInput = options.port;
610
+ if (portInput)
611
+ ;
612
+ else {
613
+ return createOnesApp.throwError(ErrorCode.MISSING_PORT, i18n.t("error.tunnel.missingPort"));
614
+ }
615
+ const portString = String(portInput);
616
+ const portNumber = Number(portString);
617
+ if (isPortNumber.test(portString))
618
+ ;
619
+ else {
620
+ return createOnesApp.throwError(ErrorCode.INCORRECT_PORT, i18n.t("error.tunnel.incorrectPort"));
621
+ }
622
+ if (portNumber < minPortNumber || portNumber > maxPortNumber) {
623
+ return createOnesApp.throwError(ErrorCode.INCORRECT_PORT, i18n.t("error.tunnel.incorrectPort"));
624
+ }
625
+ const port = portString;
626
+ return {
627
+ port
628
+ };
629
+ };
630
+ const getTunnelContext = async () => {
631
+ var _appManifestJSON$app$, _appManifestJSON$app, _store$region_url, _store$ones_token;
632
+ const appManifestJSON = getAppManifestJSON();
633
+ const appID = (_appManifestJSON$app$ = (_appManifestJSON$app = appManifestJSON.app) === null || _appManifestJSON$app === void 0 ? void 0 : _appManifestJSON$app.id) !== null && _appManifestJSON$app$ !== void 0 ? _appManifestJSON$app$ : "";
634
+ const store = await getStore();
635
+ const regionURL = (_store$region_url = store.region_url) !== null && _store$region_url !== void 0 ? _store$region_url : "";
636
+ const onesToken = (_store$ones_token = store.ones_token) !== null && _store$ones_token !== void 0 ? _store$ones_token : "";
637
+ if (appID && regionURL && onesToken) {
638
+ return {
639
+ appID,
640
+ regionURL,
641
+ onesToken,
642
+ store,
643
+ appManifestJSON
644
+ };
645
+ }
646
+ consoleUnauthorizedMessage();
647
+ process.exit(1);
648
+ };
649
+ const getHostedTokenScopes = (ones2) => {
650
+ const storage = ones2 === null || ones2 === void 0 ? void 0 : ones2.storage;
651
+ if (!storage) {
652
+ return [];
653
+ }
654
+ const scopes = /* @__PURE__ */ new Set();
655
+ if (Array.isArray(storage.entities) && storage.entities.length > 0) {
656
+ scopes.add(createOnesApp.HostedTokenScope.STORAGE_ENTITY);
657
+ }
658
+ if (storage.object !== void 0 && storage.object !== null && storage.object !== false) {
659
+ scopes.add(createOnesApp.HostedTokenScope.STORAGE_OBJECT);
660
+ }
661
+ return Array.from(scopes);
662
+ };
663
+ const getRelayScope = () => {
664
+ return createOnesApp.HostedTokenScope.RELAY;
665
+ };
666
+ const buildTunnelUrl = async () => {
667
+ const {
668
+ appID,
669
+ regionURL
670
+ } = await getTunnelContext();
671
+ const url = new URL(regionURL);
672
+ url.pathname = `/platform/app/relay/dispatch/${appID}`;
673
+ return url.toString();
674
+ };
675
+ class TunnelClient {
676
+ constructor(localPort, baseUrl, appID, hostedToken) {
677
+ let enableInternalManifestRoute = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : true;
678
+ let replaceExisting = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : true;
679
+ this.ws = null;
680
+ this.localPort = localPort;
681
+ this.baseUrl = baseUrl;
682
+ this.appID = appID;
683
+ this.hostedToken = hostedToken;
684
+ this.enableInternalManifestRoute = enableInternalManifestRoute;
685
+ this.replaceExisting = replaceExisting;
686
+ }
687
+ async connect() {
688
+ const proxyUrl = this.buildProxyUrl();
689
+ this.ws = new WebSocket(proxyUrl, {
690
+ headers: {
691
+ Authorization: `Bearer ${this.hostedToken}`
692
+ },
693
+ maxPayload: MAX_RELAY_BODY_BYTES
694
+ });
695
+ this.ws.on("message", async (data) => {
696
+ const message = this.parseMessage(data);
697
+ if (!message) {
698
+ return;
699
+ }
700
+ await this.handleMessage(message);
701
+ });
702
+ this.ws.on("ping", (data) => {
703
+ var _this$ws;
704
+ (_this$ws = this.ws) === null || _this$ws === void 0 || _this$ws.pong(data);
705
+ });
706
+ this.ws.on("error", (error) => {
707
+ console.error("WebSocket error:", error);
708
+ });
709
+ return new Promise((resolve, reject) => {
710
+ var _this$ws2, _this$ws3;
711
+ (_this$ws2 = this.ws) === null || _this$ws2 === void 0 || _this$ws2.on("open", () => resolve());
712
+ (_this$ws3 = this.ws) === null || _this$ws3 === void 0 || _this$ws3.on("error", reject);
713
+ });
714
+ }
715
+ close() {
716
+ var _this$ws4;
717
+ (_this$ws4 = this.ws) === null || _this$ws4 === void 0 || _this$ws4.close();
718
+ }
719
+ buildProxyUrl() {
720
+ const url = new URL("/platform/app/relay/", this.baseUrl);
721
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
722
+ url.searchParams.set("app_id", this.appID);
723
+ url.searchParams.set("replace_existing", String(this.replaceExisting));
724
+ return url.toString();
725
+ }
726
+ parseMessage(data) {
727
+ const buffer = this.toBuffer(data);
728
+ if (!buffer) {
729
+ return null;
730
+ }
731
+ if (buffer.length >= 4) {
732
+ const binary = this.parseBinaryEnvelope(buffer);
733
+ if (binary) {
734
+ return binary;
735
+ }
736
+ }
737
+ return this.parseJSONEnvelope(buffer.toString());
738
+ }
739
+ async handleMessage(message) {
740
+ const request = this.getRequestPayload(message);
741
+ if (!request) {
742
+ return;
743
+ }
744
+ if (this.enableInternalManifestRoute && request.path === ONES_CLI_INTERNAL_MANIFEST_PATH) {
745
+ const appManifest = getAppManifestJSON().app;
746
+ const baseURL = await buildTunnelUrl();
747
+ const reply = {
748
+ id: message.id,
749
+ payload: {
750
+ status: 200,
751
+ headers: {
752
+ "content-type": ["application/json"]
753
+ },
754
+ body: {
755
+ ...appManifest,
756
+ base_url: baseURL
757
+ }
758
+ }
759
+ };
760
+ this.sendBinaryEnvelope(reply);
761
+ return;
762
+ }
763
+ try {
764
+ const response = await this.forwardRequest(request);
765
+ const reply = {
766
+ id: message.id,
767
+ payload: response
768
+ };
769
+ this.sendBinaryEnvelope(reply);
770
+ } catch (error) {
771
+ const reply = {
772
+ id: message.id,
773
+ payload: {
774
+ status: 500,
775
+ headers: {
776
+ "x-agent-error": [error instanceof Error ? error.message : "Unknown error"]
777
+ },
778
+ body: "agent request error"
779
+ }
780
+ };
781
+ this.sendBinaryEnvelope(reply);
782
+ }
783
+ }
784
+ getRequestPayload(message) {
785
+ const payload = message.payload;
786
+ if (!(payload !== null && payload !== void 0 && payload.method) || !(payload !== null && payload !== void 0 && payload.path)) {
787
+ return null;
788
+ }
789
+ return payload;
790
+ }
791
+ async forwardRequest(payload) {
792
+ const url = new URL(payload.path, `http://127.0.0.1:${this.localPort}`);
793
+ if (payload.query) {
794
+ Object.entries(payload.query).forEach((_ref) => {
795
+ let [key, value] = _ref;
796
+ if (Array.isArray(value)) {
797
+ value.forEach((item) => {
798
+ url.searchParams.append(key, item);
799
+ });
800
+ return;
801
+ }
802
+ url.searchParams.append(key, value);
803
+ });
804
+ }
805
+ const response = await axios.request({
806
+ url: url.toString(),
807
+ method: payload.method,
808
+ headers: payload.headers,
809
+ data: payload.body,
810
+ responseType: "arraybuffer",
811
+ validateStatus: () => true,
812
+ maxBodyLength: MAX_RELAY_BODY_BYTES,
813
+ maxContentLength: MAX_RELAY_BODY_BYTES
814
+ });
815
+ const responseBytes = Buffer.from(response.data);
816
+ return {
817
+ status: response.status,
818
+ headers: this.collectHeaders(response.headers),
819
+ body: responseBytes
820
+ };
821
+ }
822
+ collectHeaders(headers) {
823
+ const collected = {};
824
+ Object.entries(headers).forEach((_ref2) => {
825
+ let [key, value] = _ref2;
826
+ if (Array.isArray(value)) {
827
+ collected[key] = value.map((item) => String(item));
828
+ return;
829
+ }
830
+ if (value !== void 0 && value !== null) {
831
+ collected[key] = [String(value)];
832
+ }
833
+ });
834
+ return collected;
835
+ }
836
+ sendBinaryEnvelope(envelope) {
837
+ var _this$ws5;
838
+ const encoded = this.encodeBinaryEnvelope(envelope);
839
+ (_this$ws5 = this.ws) === null || _this$ws5 === void 0 || _this$ws5.send(encoded);
840
+ }
841
+ encodeBinaryEnvelope(envelope) {
842
+ var _envelope$payload;
843
+ const payload = (_envelope$payload = envelope.payload) !== null && _envelope$payload !== void 0 ? _envelope$payload : {};
844
+ const body = this.toBodyBuffer(payload.body);
845
+ if (body.length > MAX_RELAY_BODY_BYTES) {
846
+ throw new Error("relay body too large");
847
+ }
848
+ const metaPayload = {
849
+ ...payload
850
+ };
851
+ delete metaPayload.body;
852
+ const meta = Buffer.from(JSON.stringify({
853
+ id: envelope.id,
854
+ payload: metaPayload
855
+ }), "utf8");
856
+ const header = Buffer.allocUnsafe(4);
857
+ header.writeUInt32BE(meta.length, 0);
858
+ return Buffer.concat([header, meta, body]);
859
+ }
860
+ toBodyBuffer(body) {
861
+ if (body === void 0 || body === null) {
862
+ return Buffer.alloc(0);
863
+ }
864
+ if (Buffer.isBuffer(body)) {
865
+ return body;
866
+ }
867
+ if (body instanceof ArrayBuffer) {
868
+ return Buffer.from(body);
869
+ }
870
+ if (ArrayBuffer.isView(body)) {
871
+ return Buffer.from(body.buffer, body.byteOffset, body.byteLength);
872
+ }
873
+ if (typeof body === "string") {
874
+ return Buffer.from(body, "utf8");
875
+ }
876
+ return Buffer.from(JSON.stringify(body), "utf8");
877
+ }
878
+ parseBinaryEnvelope(buffer) {
879
+ const metaLength = buffer.readUInt32BE(0);
880
+ if (metaLength <= 0 || 4 + metaLength > buffer.length) {
881
+ return null;
882
+ }
883
+ const metaRaw = buffer.subarray(4, 4 + metaLength).toString("utf8");
884
+ try {
885
+ const envelope = JSON.parse(metaRaw);
886
+ if (!(envelope !== null && envelope !== void 0 && envelope.payload)) {
887
+ return envelope;
888
+ }
889
+ const body = buffer.subarray(4 + metaLength);
890
+ if (body.length > MAX_RELAY_BODY_BYTES) {
891
+ console.error("Binary tunnel body exceeds size limit");
892
+ return null;
893
+ }
894
+ const payload = envelope.payload;
895
+ payload.body = body;
896
+ return envelope;
897
+ } catch (error) {
898
+ console.error("Invalid binary tunnel message:", error);
899
+ return null;
900
+ }
901
+ }
902
+ parseJSONEnvelope(payload) {
903
+ try {
904
+ const message = JSON.parse(payload);
905
+ if (!message) {
906
+ return null;
907
+ }
908
+ return message;
909
+ } catch (error) {
910
+ console.error("Invalid tunnel message:", error);
911
+ return null;
912
+ }
913
+ }
914
+ toBuffer(data) {
915
+ if (Buffer.isBuffer(data)) {
916
+ return data;
917
+ }
918
+ if (Array.isArray(data)) {
919
+ return Buffer.concat(data);
920
+ }
921
+ if (data instanceof ArrayBuffer) {
922
+ return Buffer.from(data);
923
+ }
924
+ return null;
925
+ }
926
+ }
927
+ const invokeTunnel = async function(port) {
928
+ var _options$rebuildWhenE, _options$enableIntern, _hostedTokenResponse$;
929
+ let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
930
+ const {
931
+ appManifestJSON,
932
+ appID,
933
+ regionURL
934
+ } = await getTunnelContext();
935
+ const rebuildWhenExists = (_options$rebuildWhenE = options.rebuildWhenExists) !== null && _options$rebuildWhenE !== void 0 ? _options$rebuildWhenE : true;
936
+ const enableInternalManifestRoute = (_options$enableIntern = options.enableInternalManifestRoute) !== null && _options$enableIntern !== void 0 ? _options$enableIntern : true;
937
+ const storageScopes = getHostedTokenScopes(appManifestJSON.ones);
938
+ const scopes = Array.from(/* @__PURE__ */ new Set([...storageScopes, getRelayScope()]));
939
+ const hostedTokenResponse = await fetchHostedToken({
940
+ app_id: appID,
941
+ scopes
942
+ });
943
+ const hostedToken = hostedTokenResponse === null || hostedTokenResponse === void 0 || (_hostedTokenResponse$ = hostedTokenResponse.data) === null || _hostedTokenResponse$ === void 0 ? void 0 : _hostedTokenResponse$.hosted_token;
944
+ if (!hostedToken) {
945
+ return createOnesApp.throwError(ErrorCode.HOSTED_TOKEN_EMPTY, i18n.t("error.hostedToken.empty"));
946
+ }
947
+ await setHostToken(hostedToken);
948
+ const client = new TunnelClient(port, regionURL, appID, hostedToken, enableInternalManifestRoute, rebuildWhenExists);
949
+ await client.connect();
950
+ };
951
+ const tunnel = async function() {
952
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
953
+ args[_key] = arguments[_key];
954
+ }
955
+ const {
956
+ options
957
+ } = createOnesApp.getCommandOptions(args, tunnelCommandArguments);
958
+ const normalizedOptions = await normalize$9(options);
959
+ const port = Number(normalizedOptions.port);
960
+ await invokeTunnel(port, {
961
+ enableInternalManifestRoute: false,
962
+ rebuildWhenExists: true
963
+ });
964
+ const runnelUrl = await buildTunnelUrl();
965
+ console.log(`Relay endpoint: ${runnelUrl}`);
966
+ };
967
+ const normalize$8 = async (options) => {
968
+ lodashEs.noop(options);
969
+ return {};
970
+ };
971
+ const displayAppDetail = async (installationID) => {
972
+ var _tokenInfo$org$uuid, _tokenInfo$org, _tokenInfo$teams$0$uu, _tokenInfo$teams, _tokenInfo$org$visibi, _tokenInfo$org2;
973
+ const tokenInfo = await fetchTokenInfo();
974
+ const orgUUID = (_tokenInfo$org$uuid = (_tokenInfo$org = tokenInfo.org) === null || _tokenInfo$org === void 0 ? void 0 : _tokenInfo$org.uuid) !== null && _tokenInfo$org$uuid !== void 0 ? _tokenInfo$org$uuid : "";
975
+ const teamUUID = (_tokenInfo$teams$0$uu = (_tokenInfo$teams = tokenInfo.teams) === null || _tokenInfo$teams === void 0 || (_tokenInfo$teams = _tokenInfo$teams[0]) === null || _tokenInfo$teams === void 0 ? void 0 : _tokenInfo$teams.uuid) !== null && _tokenInfo$teams$0$uu !== void 0 ? _tokenInfo$teams$0$uu : "";
976
+ const isOrgVisible = (_tokenInfo$org$visibi = (_tokenInfo$org2 = tokenInfo.org) === null || _tokenInfo$org2 === void 0 ? void 0 : _tokenInfo$org2.visibility) !== null && _tokenInfo$org$visibi !== void 0 ? _tokenInfo$org$visibi : false;
977
+ const baseURL = await getBaseURL();
978
+ if (isOrgVisible && orgUUID) {
979
+ const url = `${baseURL}project/#/org/${orgUUID}/setting/app_manager/platform_app/${installationID}`;
980
+ console.log(`See App detail: ${url}`);
981
+ }
982
+ if (!isOrgVisible && teamUUID) {
983
+ const url = `${baseURL}project/#/team/${teamUUID}/team_setting/app_manager/platform_app/${installationID}`;
984
+ console.log(`See App detail: ${url}`);
985
+ }
986
+ };
987
+ const invokeInstall = async (manifestUrl) => {
988
+ const {
989
+ app
990
+ } = getAppManifestJSON();
991
+ const appName = app.name;
992
+ const appID = app.id;
993
+ const result = await fetchAppInstall({
994
+ manifest_url: manifestUrl,
995
+ options: {
996
+ enable: true
997
+ }
998
+ });
999
+ if (result.code === "OK") {
1000
+ var _appList$data$0$insta, _appList$data;
1001
+ console.log(`App "${appName}" installed successfully!`);
1002
+ const appList = await fetchAppList(appID);
1003
+ const installationID = (_appList$data$0$insta = (_appList$data = appList.data) === null || _appList$data === void 0 || (_appList$data = _appList$data[0]) === null || _appList$data === void 0 ? void 0 : _appList$data.installation_id) !== null && _appList$data$0$insta !== void 0 ? _appList$data$0$insta : "";
1004
+ if (installationID) {
1005
+ await displayAppDetail(installationID);
1006
+ }
1007
+ } else {
1008
+ console.log(`App "${appName}" installed failed!`);
1009
+ console.error(JSON.stringify(result, null, 2));
1010
+ }
1011
+ };
1012
+ const getManifestUrl = async () => {
1013
+ const runnelUrl = await buildTunnelUrl();
1014
+ const customManifestUrl = `${runnelUrl}${MANIFEST_PATH}`;
1015
+ const internalManifestUrl = `${runnelUrl}${ONES_CLI_INTERNAL_MANIFEST_PATH}`;
1016
+ const internalResult = await axios.get(internalManifestUrl).then((response) => {
1017
+ if (response.status === 200) {
1018
+ return internalManifestUrl;
1019
+ }
1020
+ return null;
1021
+ }).catch(lodashEs.noop);
1022
+ if (internalResult) {
1023
+ return internalResult;
1024
+ }
1025
+ const customResult = await axios.get(customManifestUrl).then((response) => {
1026
+ if (response.status === 200) {
1027
+ return customManifestUrl;
1028
+ }
1029
+ return null;
1030
+ }).catch(lodashEs.noop);
1031
+ if (customResult) {
1032
+ return customResult;
1033
+ }
1034
+ return null;
1035
+ };
1036
+ const install = async function() {
1037
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1038
+ args[_key] = arguments[_key];
1039
+ }
1040
+ const {
1041
+ options
1042
+ } = createOnesApp.getCommandOptions(args, installCommandArguments);
1043
+ const normalizedOptions = await normalize$8(options);
1044
+ lodashEs.noop(normalizedOptions);
1045
+ const {
1046
+ app
1047
+ } = getAppManifestJSON();
1048
+ const appName = app.name;
1049
+ const manifestUrl = await getManifestUrl();
1050
+ if (!manifestUrl) {
1051
+ console.log(`App "${appName}" server not available!`);
1052
+ console.log('Use "ones dev" command or "ones tunnel" command to start the server first');
1053
+ process.exit(1);
1054
+ }
1055
+ await invokeInstall(manifestUrl);
1056
+ };
1057
+ var InstallOptions = /* @__PURE__ */ ((InstallOptions2) => {
1058
+ InstallOptions2["AUTO"] = "auto";
1059
+ InstallOptions2["TRUE"] = "true";
1060
+ InstallOptions2["FALSE"] = "false";
1061
+ return InstallOptions2;
1062
+ })(InstallOptions || {});
1063
+ const defaultInstall = InstallOptions.AUTO;
1064
+ const normalize$7 = async (options) => {
1065
+ var _options$install, _options$command;
1066
+ let install2 = (_options$install = options.install) !== null && _options$install !== void 0 ? _options$install : defaultInstall;
1067
+ const command = (_options$command = options.command) !== null && _options$command !== void 0 ? _options$command : "";
1068
+ switch (true) {
1069
+ case install2 === InstallOptions.AUTO:
1070
+ break;
1071
+ case Boolean(install2):
1072
+ install2 = InstallOptions.TRUE;
1073
+ break;
1074
+ default:
1075
+ install2 = InstallOptions.FALSE;
1076
+ break;
1077
+ }
1078
+ return {
1079
+ install: install2,
1080
+ command
1081
+ };
1082
+ };
1083
+ const IDLE_MS = 2e3;
1084
+ function createReadyStatusPipes(onReady) {
1085
+ let readyTimer = null;
1086
+ let summaryPrinted = false;
1087
+ const scheduleReady = () => {
1088
+ if (summaryPrinted)
1089
+ return;
1090
+ if (readyTimer)
1091
+ clearTimeout(readyTimer);
1092
+ readyTimer = setTimeout(() => {
1093
+ readyTimer = null;
1094
+ if (!summaryPrinted) {
1095
+ summaryPrinted = true;
1096
+ onReady();
1097
+ }
1098
+ }, IDLE_MS);
1099
+ };
1100
+ const pipe = (stream, isStderr) => {
1101
+ const write = (chunk) => {
1102
+ if (isStderr)
1103
+ process.stderr.write(chunk);
1104
+ else
1105
+ process.stdout.write(chunk);
1106
+ };
1107
+ stream.on("data", (chunk) => {
1108
+ const str = typeof chunk === "string" ? chunk : chunk.toString();
1109
+ write(str);
1110
+ if (str.startsWith("[backend]") || str.startsWith("[web]")) {
1111
+ scheduleReady();
1112
+ }
1113
+ });
1114
+ };
1115
+ return pipe;
1116
+ }
1117
+ const dev = async function() {
1118
+ var _appRcJSON$dev, _defaultAppRcJSON$dev, _appRcJSON$dev$comman, _appRcJSON$dev2;
1119
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1120
+ args[_key] = arguments[_key];
1121
+ }
1122
+ const {
1123
+ options
1124
+ } = createOnesApp.getCommandOptions(args, devCommandArguments);
1125
+ const normalizedOptions = await normalize$7(options);
1126
+ const appRcJSON = await getAppRcJSON();
1127
+ const appPackageJSON = getAppPackageJSON();
1128
+ const firstCommand = normalizedOptions.command || ((_appRcJSON$dev = appRcJSON.dev) === null || _appRcJSON$dev === void 0 || (_appRcJSON$dev = _appRcJSON$dev.command) === null || _appRcJSON$dev === void 0 ? void 0 : _appRcJSON$dev[0]) || ((_defaultAppRcJSON$dev = defaultAppRcJSON.dev) === null || _defaultAppRcJSON$dev === void 0 || (_defaultAppRcJSON$dev = _defaultAppRcJSON$dev.command) === null || _defaultAppRcJSON$dev === void 0 ? void 0 : _defaultAppRcJSON$dev[0]) || "";
1129
+ if (!firstCommand) {
1130
+ return createOnesApp.throwError(ErrorCode.INCORRECT_DEV_COMMAND, i18n.t("error.dev.incorrectCommand"));
1131
+ }
1132
+ const currentCommand = normalizedOptions.command ? normalizedOptions.command.split(" ") : (_appRcJSON$dev$comman = (_appRcJSON$dev2 = appRcJSON.dev) === null || _appRcJSON$dev2 === void 0 ? void 0 : _appRcJSON$dev2.command) !== null && _appRcJSON$dev$comman !== void 0 ? _appRcJSON$dev$comman : [];
1133
+ const currentCommandString = currentCommand.join(" ");
1134
+ const defaultDevCommandString = defaultDevCommand.join(" ");
1135
+ if (currentCommandString === defaultDevCommandString) {
1136
+ var _appPackageJSON$scrip;
1137
+ if (!((_appPackageJSON$scrip = appPackageJSON.scripts) !== null && _appPackageJSON$scrip !== void 0 && _appPackageJSON$scrip.dev)) {
1138
+ return createOnesApp.throwError(ErrorCode.DEV_SCRIPT_NOT_FOUND, i18n.t("error.dev.scriptNotFound"));
1139
+ }
1140
+ }
1141
+ let enableTunnel = true;
1142
+ if (normalizedOptions.install === InstallOptions.TRUE)
1143
+ ;
1144
+ else {
1145
+ enableTunnel = await checkTokenInfo();
1146
+ }
1147
+ const appManifestJSON = getAppManifestJSON();
1148
+ const {
1149
+ app,
1150
+ ones: ones2
1151
+ } = appManifestJSON;
1152
+ const appID = app.id;
1153
+ const config2 = getConfig();
1154
+ const ONES_HOSTED_PORT = await getPort({
1155
+ port: config2.defaultPort.hosted
1156
+ });
1157
+ const ONES_DEV_WEB_SERVER_PORT = await getPort({
1158
+ port: config2.defaultPort.devWebServer
1159
+ });
1160
+ const env2 = {
1161
+ ...process.env,
1162
+ NODE_ENV: "development",
1163
+ ONES_HOSTED_PORT: `${ONES_HOSTED_PORT}`,
1164
+ ONES_DEV_WEB_SERVER_PORT: `${ONES_DEV_WEB_SERVER_PORT}`,
1165
+ ONES_HOSTED_TOKEN: "",
1166
+ ONES_HOSTED_APP_ID: "",
1167
+ ONES_HOSTED_BASE_URL: ""
1168
+ };
1169
+ if (enableTunnel) {
1170
+ var _ones$storage$entitie, _ones$storage;
1171
+ await invokeTunnel(ONES_HOSTED_PORT, {
1172
+ enableInternalManifestRoute: true,
1173
+ rebuildWhenExists: true
1174
+ });
1175
+ const regionURL = await getRegionURL();
1176
+ const ONES_HOSTED_TOKEN = await getHostToken();
1177
+ const ONES_HOSTED_APP_ID = appID;
1178
+ const ONES_HOSTED_BASE_URL = `${regionURL}/platform/runtime_manager`;
1179
+ env2.ONES_HOSTED_TOKEN = ONES_HOSTED_TOKEN;
1180
+ env2.ONES_HOSTED_APP_ID = ONES_HOSTED_APP_ID;
1181
+ env2.ONES_HOSTED_BASE_URL = ONES_HOSTED_BASE_URL;
1182
+ const entities = (_ones$storage$entitie = ones2 === null || ones2 === void 0 || (_ones$storage = ones2.storage) === null || _ones$storage === void 0 ? void 0 : _ones$storage.entities) !== null && _ones$storage$entitie !== void 0 ? _ones$storage$entitie : [];
1183
+ if (entities.length > 0) {
1184
+ await fetchHostedAbilityStorageDevDeclare({
1185
+ app_id: appID,
1186
+ cleanup_legacy: false,
1187
+ opkx_content: appManifestJSON
1188
+ });
1189
+ }
1190
+ }
1191
+ const onReady = async () => {
1192
+ const appName = app.name;
1193
+ let manifestUrl = "";
1194
+ console.log("");
1195
+ console.log(`Local: http://localhost:${ONES_HOSTED_PORT}`);
1196
+ if (enableTunnel) {
1197
+ const runnelUrl = await buildTunnelUrl();
1198
+ console.log(`URL: ${runnelUrl}`);
1199
+ manifestUrl = `${runnelUrl}${ONES_CLI_INTERNAL_MANIFEST_PATH}`;
1200
+ }
1201
+ console.log("Docs site: https://open.ones.com/");
1202
+ console.log(`App "${appName}" server is ready!`);
1203
+ console.log("");
1204
+ if (enableTunnel) {
1205
+ switch (normalizedOptions.install) {
1206
+ case InstallOptions.TRUE:
1207
+ await invokeInstall(manifestUrl);
1208
+ break;
1209
+ case InstallOptions.AUTO:
1210
+ {
1211
+ var _appList$data$0$insta, _appList$data;
1212
+ const appList = await fetchAppList(appID);
1213
+ const installationID = (_appList$data$0$insta = (_appList$data = appList.data) === null || _appList$data === void 0 || (_appList$data = _appList$data[0]) === null || _appList$data === void 0 ? void 0 : _appList$data.installation_id) !== null && _appList$data$0$insta !== void 0 ? _appList$data$0$insta : "";
1214
+ if (installationID) {
1215
+ await displayAppDetail(installationID);
1216
+ } else {
1217
+ await invokeInstall(manifestUrl);
1218
+ }
1219
+ }
1220
+ break;
1221
+ case InstallOptions.FALSE:
1222
+ break;
1223
+ }
1224
+ }
1225
+ };
1226
+ const cwd = getAppWorkspacePath();
1227
+ const child = node_child_process.spawn(firstCommand, currentCommand.slice(1), {
1228
+ cwd,
1229
+ stdio: ["inherit", "pipe", "pipe"],
1230
+ env: env2,
1231
+ shell: true
1232
+ });
1233
+ const pipe = createReadyStatusPipes(onReady);
1234
+ if (child.stdout)
1235
+ pipe(child.stdout, false);
1236
+ if (child.stderr)
1237
+ pipe(child.stderr, true);
1238
+ const cleanup = () => {
1239
+ child.kill();
1240
+ };
1241
+ const onSignal = () => {
1242
+ cleanup();
1243
+ process.exit(128 + 2);
1244
+ };
1245
+ process.on("SIGINT", onSignal);
1246
+ process.on("SIGTERM", onSignal);
1247
+ await new Promise((resolve) => {
1248
+ child.on("exit", () => {
1249
+ cleanup();
1250
+ process.off("SIGINT", onSignal);
1251
+ process.off("SIGTERM", onSignal);
1252
+ resolve();
1253
+ });
1254
+ });
1255
+ };
1256
+ function createPromise() {
1257
+ let resolve;
1258
+ let reject;
1259
+ const promise = new Promise((res, rej) => {
1260
+ resolve = res;
1261
+ reject = rej;
1262
+ });
1263
+ return {
1264
+ promise,
1265
+ resolve,
1266
+ reject
1267
+ };
1268
+ }
1269
+ const sleep = (number) => {
1270
+ return new Promise((resolve) => {
1271
+ setTimeout(resolve, number);
1272
+ });
1273
+ };
1274
+ const isURL = /^https?:\/\//;
1275
+ const HostBlackList = ["ones.cn", "www.ones.cn", "ones.com", "www.ones.com"];
1276
+ const normalize$6 = async (options) => {
1277
+ const baseURLInput = options.baseURL;
1278
+ if (baseURLInput)
1279
+ ;
1280
+ else {
1281
+ return createOnesApp.throwError(ErrorCode.MISSING_BASE_URL, i18n.t("error.login.missingBaseURL"));
1282
+ }
1283
+ if (isURL.test(baseURLInput))
1284
+ ;
1285
+ else {
1286
+ return createOnesApp.throwError(ErrorCode.INCORRECT_BASE_URL, i18n.t("error.login.incorrectBaseURL"));
1287
+ }
1288
+ let baseURL = "";
1289
+ try {
1290
+ const url = new URL(baseURLInput);
1291
+ const host = url.hostname;
1292
+ if (_includesInstanceProperty(HostBlackList).call(HostBlackList, host)) {
1293
+ return createOnesApp.throwError(ErrorCode.INCORRECT_BASE_URL, i18n.t("error.login.incorrectBaseURL"));
1294
+ }
1295
+ url.pathname = "";
1296
+ url.search = "";
1297
+ url.hash = "";
1298
+ baseURL = url.toString();
1299
+ } catch (error) {
1300
+ return createOnesApp.throwError(ErrorCode.INCORRECT_BASE_URL, i18n.t("error.login.incorrectBaseURL"));
1301
+ }
1302
+ return {
1303
+ baseURL
1304
+ };
1305
+ };
1306
+ const login = async function() {
1307
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1308
+ args[_key] = arguments[_key];
1309
+ }
1310
+ const {
1311
+ options
1312
+ } = createOnesApp.getCommandOptions(args, loginCommandArguments);
1313
+ const normalizedOptions = await normalize$6(options);
1314
+ const base = normalizedOptions.baseURL;
1315
+ const path = "project/oauth2.html";
1316
+ const config2 = getConfig();
1317
+ const port = await getPort({
1318
+ port: config2.defaultPort.login
1319
+ });
1320
+ const uuid$1 = uuid.v4();
1321
+ const search = new URLSearchParams();
1322
+ search.set("redirect_path", "/developer/cli");
1323
+ search.set("redirect_url", `http://localhost:${port}`);
1324
+ search.set("state", uuid$1);
1325
+ const url = `${base}${path}?${search}`;
1326
+ const publicPath = getPublicPath();
1327
+ const htmlPath = node_path.join(publicPath, "callback.html");
1328
+ const html = node_fs.readFileSync(htmlPath, {
1329
+ encoding: "utf-8"
1330
+ });
1331
+ const logoPath = node_path.join(publicPath, "logo.svg");
1332
+ const logo = node_fs.readFileSync(logoPath, {
1333
+ encoding: "utf-8"
1334
+ });
1335
+ const {
1336
+ promise,
1337
+ resolve
1338
+ } = createPromise();
1339
+ const server = http.createServer((req, res) => {
1340
+ var _req$url$split$, _req$url, _search2$get, _search2$get2;
1341
+ const search2 = new URLSearchParams((_req$url$split$ = (_req$url = req.url) === null || _req$url === void 0 ? void 0 : _req$url.split("?")[1]) !== null && _req$url$split$ !== void 0 ? _req$url$split$ : "");
1342
+ const state = search2.get("state");
1343
+ if (state === "logo") {
1344
+ res.writeHead(200, {
1345
+ "Content-Type": "image/svg+xml"
1346
+ });
1347
+ res.end(logo);
1348
+ return;
1349
+ }
1350
+ if (state === "cancel") {
1351
+ res.writeHead(200, {
1352
+ "Content-Type": "image/svg+xml"
1353
+ });
1354
+ res.end(logo);
1355
+ resolve(null);
1356
+ return;
1357
+ }
1358
+ const token = (_search2$get = search2.get("access_token")) !== null && _search2$get !== void 0 ? _search2$get : "";
1359
+ const region = (_search2$get2 = search2.get("region_url")) !== null && _search2$get2 !== void 0 ? _search2$get2 : "";
1360
+ if (state === uuid$1 && token && region) {
1361
+ resolve({
1362
+ base_url: base,
1363
+ ones_token: token,
1364
+ region_url: region
1365
+ });
1366
+ res.writeHead(200, {
1367
+ "Content-Type": "text/html"
1368
+ });
1369
+ res.end(html);
1370
+ return;
1371
+ }
1372
+ res.writeHead(200, {
1373
+ "Content-Type": "text/html"
1374
+ });
1375
+ res.end("Invalid state error, please try again!");
1376
+ });
1377
+ server.listen(port);
1378
+ promise.then(async (store) => {
1379
+ await sleep(100);
1380
+ server.closeAllConnections();
1381
+ if (store) {
1382
+ var _store$base_url, _store$ones_token, _store$region_url;
1383
+ await setBaseURL((_store$base_url = store.base_url) !== null && _store$base_url !== void 0 ? _store$base_url : "");
1384
+ await setONESToken((_store$ones_token = store.ones_token) !== null && _store$ones_token !== void 0 ? _store$ones_token : "");
1385
+ await setRegionURL((_store$region_url = store.region_url) !== null && _store$region_url !== void 0 ? _store$region_url : "");
1386
+ console.log("Logged in successfully!");
1387
+ } else {
1388
+ console.log("Login canceled!");
1389
+ }
1390
+ process$1.exit(0);
1391
+ });
1392
+ console.log("Logging into your ONES account...");
1393
+ console.log(`Opening ${url}`);
1394
+ ora("Waiting for authorization...").start();
1395
+ await open(url);
1396
+ };
1397
+ const normalize$5 = async (options) => {
1398
+ lodashEs.noop(options);
1399
+ return {};
1400
+ };
1401
+ const logout = async function() {
1402
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1403
+ args[_key] = arguments[_key];
1404
+ }
1405
+ const {
1406
+ options
1407
+ } = createOnesApp.getCommandOptions(args, logoutCommandArguments);
1408
+ const normalizedOptions = await normalize$5(options);
1409
+ lodashEs.noop(normalizedOptions);
1410
+ await setStore({});
1411
+ console.log("Logged out successfully!");
1412
+ };
1413
+ const normalize$4 = async (options) => {
1414
+ lodashEs.noop(options);
1415
+ return {};
1416
+ };
1417
+ const whoami = async function() {
1418
+ var _tokenInfo$user, _tokenInfo$user2;
1419
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1420
+ args[_key] = arguments[_key];
1421
+ }
1422
+ const {
1423
+ options
1424
+ } = createOnesApp.getCommandOptions(args, whoamiCommandArguments);
1425
+ const normalizedOptions = await normalize$4(options);
1426
+ lodashEs.noop(normalizedOptions);
1427
+ const baseURL = await getBaseURL();
1428
+ const tokenInfo = await fetchTokenInfo();
1429
+ const name2 = (_tokenInfo$user = tokenInfo.user) === null || _tokenInfo$user === void 0 ? void 0 : _tokenInfo$user.name;
1430
+ const email = (_tokenInfo$user2 = tokenInfo.user) === null || _tokenInfo$user2 === void 0 ? void 0 : _tokenInfo$user2.email;
1431
+ if (name2 && email) {
1432
+ console.log(`User: ${name2}`);
1433
+ console.log(`Email: ${email}`);
1434
+ console.log(`ONES: ${baseURL}`);
1435
+ } else {
1436
+ consoleUnauthorizedMessage();
1437
+ }
1438
+ };
1439
+ const normalize$3 = async (options) => {
1440
+ lodashEs.noop(options);
1441
+ return {};
1442
+ };
1443
+ const enable = async function() {
1444
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1445
+ args[_key] = arguments[_key];
1446
+ }
1447
+ const {
1448
+ options
1449
+ } = createOnesApp.getCommandOptions(args, enableCommandArguments);
1450
+ const normalizedOptions = await normalize$3(options);
1451
+ lodashEs.noop(normalizedOptions);
1452
+ const appName = getAppManifestJSON().app.name;
1453
+ const result = await fetchAppEnable();
1454
+ if (result.code === "OK") {
1455
+ console.log(`App "${appName}" enabled successfully!`);
1456
+ } else {
1457
+ console.log(`App "${appName}" enabled failed!`);
1458
+ console.error(JSON.stringify(result, null, 2));
1459
+ }
1460
+ };
1461
+ const normalize$2 = async (options) => {
1462
+ lodashEs.noop(options);
1463
+ return {};
1464
+ };
1465
+ const disable = async function() {
1466
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1467
+ args[_key] = arguments[_key];
1468
+ }
1469
+ const {
1470
+ options
1471
+ } = createOnesApp.getCommandOptions(args, disableCommandArguments);
1472
+ const normalizedOptions = await normalize$2(options);
1473
+ lodashEs.noop(normalizedOptions);
1474
+ const appName = getAppManifestJSON().app.name;
1475
+ const result = await fetchAppDisable();
1476
+ if (result.code === "OK") {
1477
+ console.log(`App "${appName}" disabled successfully!`);
1478
+ } else {
1479
+ console.log(`App "${appName}" disabled failed!`);
1480
+ console.error(JSON.stringify(result, null, 2));
1481
+ }
1482
+ };
1483
+ const normalize$1 = async (options) => {
1484
+ lodashEs.noop(options);
1485
+ return {};
1486
+ };
1487
+ const uninstall = async function() {
1488
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1489
+ args[_key] = arguments[_key];
1490
+ }
1491
+ const {
1492
+ options
1493
+ } = createOnesApp.getCommandOptions(args, uninstallCommandArguments);
1494
+ const normalizedOptions = await normalize$1(options);
1495
+ lodashEs.noop(normalizedOptions);
1496
+ const appName = getAppManifestJSON().app.name;
1497
+ const result = await fetchAppUninstall();
1498
+ if (result.code === "OK") {
1499
+ console.log(`App "${appName}" uninstalled successfully!`);
1500
+ } else {
1501
+ console.log(`App "${appName}" uninstalled failed!`);
1502
+ console.error(JSON.stringify(result, null, 2));
1503
+ }
1504
+ };
1505
+ const normalize = async (options) => {
1506
+ lodashEs.noop(options);
1507
+ return {};
1508
+ };
1509
+ const legacy = async function() {
1510
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1511
+ args[_key] = arguments[_key];
1512
+ }
1513
+ const {
1514
+ options
1515
+ } = createOnesApp.getCommandOptions(args, legacyCommandArguments);
1516
+ const normalizedOptions = await normalize(options);
1517
+ console.log("legacy", normalizedOptions);
1518
+ };
1519
+ const buildCommandArguments = [];
1520
+ const $build = new commander.Command("build").description(i18n.t("desc.build")).option("-o, --output [file-path]", i18n.t("desc.build.output")).action(build);
1521
+ createOnesApp.addCommandUsage($build);
1522
+ createOnesApp.addCommandOutput($build);
1523
+ const devCommandArguments = [];
1524
+ const $dev = new commander.Command("dev").description(i18n.t("desc.dev")).option("-i, --install [boolean]", i18n.t("desc.dev.install")).option("-c, --command [string]", i18n.t("desc.dev.command")).action(dev);
1525
+ createOnesApp.addCommandUsage($dev);
1526
+ createOnesApp.addCommandOutput($dev);
1527
+ const tunnelCommandArguments = ["port"];
1528
+ const $tunnel = new commander.Command("tunnel").description(i18n.t("desc.tunnel")).argument("<port>", i18n.t("desc.tunnel.port")).action(tunnel);
1529
+ createOnesApp.addCommandUsage($tunnel);
1530
+ createOnesApp.addCommandOutput($tunnel);
1531
+ const loginCommandArguments = ["baseURL"];
1532
+ const $login = new commander.Command("login").description(i18n.t("desc.login")).argument("<base-url>", i18n.t("desc.login.baseUrl")).action(login);
1533
+ createOnesApp.addCommandUsage($login);
1534
+ createOnesApp.addCommandOutput($login);
1535
+ const logoutCommandArguments = [];
1536
+ const $logout = new commander.Command("logout").description(i18n.t("desc.logout")).action(logout);
1537
+ createOnesApp.addCommandUsage($logout);
1538
+ createOnesApp.addCommandOutput($logout);
1539
+ const whoamiCommandArguments = [];
1540
+ const $whoami = new commander.Command("whoami").description(i18n.t("desc.whoami")).action(whoami);
1541
+ createOnesApp.addCommandUsage($whoami);
1542
+ createOnesApp.addCommandOutput($whoami);
1543
+ const installCommandArguments = [];
1544
+ const $install = new commander.Command("install").description(i18n.t("desc.install")).action(install);
1545
+ createOnesApp.addCommandUsage($install);
1546
+ createOnesApp.addCommandOutput($install);
1547
+ const enableCommandArguments = [];
1548
+ const $enable = new commander.Command("enable").description(i18n.t("desc.enable")).action(enable);
1549
+ createOnesApp.addCommandUsage($enable);
1550
+ createOnesApp.addCommandOutput($enable);
1551
+ const disableCommandArguments = [];
1552
+ const $disable = new commander.Command("disable").description(i18n.t("desc.disable")).action(disable);
1553
+ createOnesApp.addCommandUsage($disable);
1554
+ createOnesApp.addCommandOutput($disable);
1555
+ const uninstallCommandArguments = [];
1556
+ const $uninstall = new commander.Command("uninstall").description(i18n.t("desc.uninstall")).action(uninstall);
1557
+ createOnesApp.addCommandUsage($uninstall);
1558
+ createOnesApp.addCommandOutput($uninstall);
1559
+ const $app = new commander.Command("app").description(i18n.t("desc.app"));
1560
+ $app.addCommand($install).addCommand($enable).addCommand($disable).addCommand($uninstall);
1561
+ createOnesApp.addCommandUsage($app);
1562
+ createOnesApp.addCommandOutput($app);
1563
+ const legacyCommandArguments = [];
1564
+ const $legacy = new commander.Command("legacy").description(i18n.t("desc.legacy")).action(legacy);
1565
+ createOnesApp.addCommandUsage($legacy);
1566
+ createOnesApp.addCommandOutput($legacy);
1567
+ const ones = new commander.Command("ones");
1568
+ const version = `${getPackageJSON().version}`;
1569
+ const env = `${version} Node/${process.version}`;
1570
+ ones.description(i18n.t("desc.ones", {
1571
+ env
1572
+ })).addCommand(createOnesApp.$create).addCommand($build).addCommand($dev).addCommand($tunnel).addCommand($app).addCommand($login).addCommand($logout).addCommand($whoami).addCommand($legacy).configureHelp({
1573
+ visibleCommands: (cmd) => {
1574
+ const blackList = ["legacy"];
1575
+ return cmd.commands.filter((command) => !_includesInstanceProperty(blackList).call(blackList, command.name()));
1576
+ },
1577
+ subcommandTerm: (subcommand) => {
1578
+ return `${subcommand.name()} ${subcommand.usage()}`.trim();
1579
+ }
1580
+ });
1581
+ createOnesApp.addCommandOutput(ones);
1582
+ const runCommandONES = async () => {
1583
+ const command = ones;
1584
+ createOnesApp.setContext("command", command);
1585
+ const version2 = `${getPackageJSON().version}`;
1586
+ command.version(version2, "-v, --version");
1587
+ await command.parse();
1588
+ };
1589
+ exports.runCommandONES = runCommandONES;