@ones-open/cli 1.0.1-16596.1816 → 1.0.1-8523.1883

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 (42) hide show
  1. package/dist/index.cjs +569 -194
  2. package/dist/index.js +567 -192
  3. package/dist/types/actions/build/index.d.ts.map +1 -1
  4. package/dist/types/actions/install/index.d.ts.map +1 -1
  5. package/dist/types/actions/login/index.d.ts.map +1 -1
  6. package/dist/types/actions/tunnel/hosted-token.d.ts +5 -0
  7. package/dist/types/actions/tunnel/hosted-token.d.ts.map +1 -0
  8. package/dist/types/actions/tunnel/index.d.ts +1 -0
  9. package/dist/types/actions/tunnel/index.d.ts.map +1 -1
  10. package/dist/types/actions/tunnel/tunnel-client.d.ts +20 -0
  11. package/dist/types/actions/tunnel/tunnel-client.d.ts.map +1 -0
  12. package/dist/types/actions/tunnel/tunnel.d.ts +3 -1
  13. package/dist/types/actions/tunnel/tunnel.d.ts.map +1 -1
  14. package/dist/types/actions/whoami/index.d.ts.map +1 -1
  15. package/dist/types/common/config/types.d.ts +1 -0
  16. package/dist/types/common/config/types.d.ts.map +1 -1
  17. package/dist/types/common/config/utils.d.ts.map +1 -1
  18. package/dist/types/common/error/enums.d.ts +3 -1
  19. package/dist/types/common/error/enums.d.ts.map +1 -1
  20. package/dist/types/common/locales/en/index.d.ts +2 -0
  21. package/dist/types/common/locales/en/index.d.ts.map +1 -1
  22. package/dist/types/common/package/schema.d.ts +2 -234
  23. package/dist/types/common/package/schema.d.ts.map +1 -1
  24. package/dist/types/common/package/utils.d.ts +4 -1
  25. package/dist/types/common/package/utils.d.ts.map +1 -1
  26. package/dist/types/common/public/consts.d.ts +2 -0
  27. package/dist/types/common/public/consts.d.ts.map +1 -0
  28. package/dist/types/common/public/index.d.ts +1 -0
  29. package/dist/types/common/public/index.d.ts.map +1 -1
  30. package/dist/types/common/request/consts.d.ts +2 -0
  31. package/dist/types/common/request/consts.d.ts.map +1 -1
  32. package/dist/types/common/request/fetch.d.ts +2 -1
  33. package/dist/types/common/request/fetch.d.ts.map +1 -1
  34. package/dist/types/common/request/types.d.ts +22 -2
  35. package/dist/types/common/request/types.d.ts.map +1 -1
  36. package/dist/types/common/store/schema.d.ts +5 -2
  37. package/dist/types/common/store/schema.d.ts.map +1 -1
  38. package/dist/types/common/store/utils.d.ts +2 -0
  39. package/dist/types/common/store/utils.d.ts.map +1 -1
  40. package/package.json +7 -4
  41. package/public/logo.svg +4 -0
  42. /package/{dist → public}/callback.html +0 -0
package/dist/index.cjs CHANGED
@@ -3,21 +3,26 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const _includesInstanceProperty = require("@babel/runtime-corejs3/core-js-stable/instance/includes");
4
4
  const commander = require("commander");
5
5
  const createOnesApp = require("create-ones-app");
6
- const lodashEs = require("lodash-es");
7
- const process = require("node:process");
8
6
  const node_path = require("node:path");
9
- const node_url = require("node:url");
7
+ const node_child_process = require("node:child_process");
10
8
  const node_fs = require("node:fs");
11
- const zod = require("zod");
9
+ const archiver = require("archiver");
10
+ const lodashEs = require("lodash-es");
11
+ const process$1 = require("node:process");
12
+ const node_url = require("node:url");
13
+ const cosmiconfig = require("cosmiconfig");
12
14
  const fse = require("fs-extra");
13
15
  const envPaths = require("env-paths");
16
+ const zod = require("zod");
17
+ const _defineProperty = require("@babel/runtime-corejs3/helpers/defineProperty");
18
+ const WebSocket = require("ws");
19
+ const axios = require("axios");
20
+ const _reduceInstanceProperty = require("@babel/runtime-corejs3/core-js-stable/instance/reduce");
14
21
  const http = require("node:http");
15
22
  const ora = require("ora");
16
23
  const open = require("open");
17
24
  const getPort = require("get-port");
18
25
  const uuid = require("uuid");
19
- const axios = require("axios");
20
- const _reduceInstanceProperty = require("@babel/runtime-corejs3/core-js-stable/instance/reduce");
21
26
  var _documentCurrentScript = typeof document !== "undefined" ? document.currentScript : null;
22
27
  const en = {
23
28
  "desc.ones": "cli for ones",
@@ -45,7 +50,9 @@ const en = {
45
50
  "error.schema.app.manifest.parseError": "app manifest json parse error",
46
51
  "error.build.scriptNotFound": "build script not found",
47
52
  "error.dev.scriptNotFound": "dev script not found",
48
- "error.store.permission": 'permission denied, please check the file permission with "{filePath}"'
53
+ "error.store.permission": 'permission denied, please check the file permission with "{filePath}"',
54
+ "error.hostedToken.requestFailed": "failed to request hosted token",
55
+ "error.hostedToken.empty": "hosted token is empty"
49
56
  };
50
57
  const map = {
51
58
  en
@@ -87,49 +94,14 @@ var ErrorCode = ((ErrorCode2) => {
87
94
  ErrorCode2["BUILD_SCRIPT_NOT_FOUND"] = "E09";
88
95
  ErrorCode2["DEV_SCRIPT_NOT_FOUND"] = "E10";
89
96
  ErrorCode2["STORE_PERMISSION"] = "E11";
97
+ ErrorCode2["HOSTED_TOKEN_REQUEST_FAILED"] = "E12";
98
+ ErrorCode2["HOSTED_TOKEN_EMPTY"] = "E13";
90
99
  return ErrorCode2;
91
100
  })(ErrorCode || {});
92
- const AppPackageJSONSchema = zod.z.object({
93
- scripts: zod.z.object({
94
- dev: zod.z.string().optional(),
95
- build: zod.z.string().optional()
96
- }).optional()
97
- });
98
- const AppManifestJSONSchema = zod.z.object({
99
- app: zod.z.object({
100
- id: zod.z.string(),
101
- name: zod.z.string(),
102
- version: zod.z.string(),
103
- logo: zod.z.string().optional(),
104
- desc: zod.z.string().optional(),
105
- base_url: zod.z.string().optional(),
106
- auth: zod.z.object({
107
- type: zod.z.literal("jwt")
108
- }),
109
- ones_version: zod.z.object({
110
- min: zod.z.string(),
111
- max: zod.z.string()
112
- }).optional(),
113
- lifecycle_callback: zod.z.object({
114
- install: zod.z.string(),
115
- enabled: zod.z.string().optional(),
116
- disabled: zod.z.string().optional(),
117
- uninstalled: zod.z.string().optional()
118
- }),
119
- oauth: zod.z.object({
120
- type: zod.z.array(zod.z.enum(["app", "user"])).optional(),
121
- scope: zod.z.array(zod.z.string()),
122
- redirect_url: zod.z.string().optional()
123
- }).optional(),
124
- events: zod.z.object({
125
- url: zod.z.string(),
126
- types: zod.z.array(zod.z.object({
127
- eventType: zod.z.string()
128
- }))
129
- }).optional(),
130
- extensions: zod.z.record(zod.z.unknown()).optional()
131
- })
132
- });
101
+ const getPublicPath = () => {
102
+ 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));
103
+ return node_path.join(__dirname, "../public");
104
+ };
133
105
  const getPackageJSONPath = () => {
134
106
  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));
135
107
  return node_path.join(__dirname, "../package.json");
@@ -145,8 +117,11 @@ const getPackageJSON = () => {
145
117
  return {};
146
118
  }
147
119
  };
120
+ const getAppWorkspacePath = () => {
121
+ return node_path.join(process$1.cwd());
122
+ };
148
123
  const getAppPackageJSONPath = () => {
149
- return node_path.join(process.cwd(), "./package.json");
124
+ return node_path.join(process$1.cwd(), "./package.json");
150
125
  };
151
126
  const getAppPackageJSON = () => {
152
127
  const path = getAppPackageJSONPath();
@@ -155,14 +130,14 @@ const getAppPackageJSON = () => {
155
130
  encoding: "utf8"
156
131
  });
157
132
  const json = JSON.parse(string);
158
- return AppPackageJSONSchema.parse(json);
133
+ return createOnesApp.AppPackageJSONSchema.parse(json);
159
134
  } catch (error) {
160
135
  console.error(error);
161
136
  return createOnesApp.throwError(ErrorCode.APP_PACKAGE_JSON_PARSE_ERROR, i18n.t("error.schema.app.package.parseError"));
162
137
  }
163
138
  };
164
139
  const getAppManifestJSONPath = () => {
165
- return node_path.join(process.cwd(), "./opkx.json");
140
+ return node_path.join(process$1.cwd(), createOnesApp.PUBLIC_FILENAME.MANIFEST);
166
141
  };
167
142
  const getAppManifestJSON = () => {
168
143
  const path = getAppManifestJSONPath();
@@ -171,17 +146,54 @@ const getAppManifestJSON = () => {
171
146
  encoding: "utf8"
172
147
  });
173
148
  const json = JSON.parse(string);
174
- return AppManifestJSONSchema.parse(json);
149
+ return createOnesApp.AppManifestJSONSchema.parse(json);
175
150
  } catch (error) {
176
151
  console.error(error);
177
152
  return createOnesApp.throwError(ErrorCode.APP_MANIFEST_JSON_PARSE_ERROR, i18n.t("error.schema.app.manifest.parseError"));
178
153
  }
179
154
  };
155
+ const defaultAppRcJSON = {
156
+ dev: {
157
+ command: ["npm run dev"]
158
+ }
159
+ };
160
+ let storeAppRcJSON = null;
161
+ const getAppRcJSON = async () => {
162
+ if (storeAppRcJSON)
163
+ ;
164
+ else {
165
+ try {
166
+ const path = node_path.join(createOnesApp.getPublicPath(), createOnesApp.PUBLIC_FILENAME.RC);
167
+ const string = node_fs.readFileSync(path, {
168
+ encoding: "utf8"
169
+ });
170
+ const json = JSON.parse(string);
171
+ storeAppRcJSON = createOnesApp.AppRcJSONSchema.parse(json);
172
+ } catch (error) {
173
+ storeAppRcJSON = {};
174
+ }
175
+ }
176
+ const templateAppRcJSON = storeAppRcJSON || {};
177
+ let currentAppRcJSON;
178
+ const explorer = cosmiconfig.cosmiconfig("ones");
179
+ try {
180
+ const result = await explorer.search();
181
+ const json = result === null || result === void 0 ? void 0 : result.config;
182
+ currentAppRcJSON = createOnesApp.AppRcJSONSchema.parse(json);
183
+ } catch (error) {
184
+ currentAppRcJSON = {};
185
+ }
186
+ return {
187
+ ...defaultAppRcJSON,
188
+ ...templateAppRcJSON,
189
+ ...currentAppRcJSON
190
+ };
191
+ };
180
192
  const isOPKXFilename = /\.opkx$/;
181
193
  const defaultOutputPath = "";
182
194
  const normalize$a = async (options) => {
183
195
  var _options$output;
184
- let output = node_path.resolve(process.cwd(), (_options$output = options.output) !== null && _options$output !== void 0 ? _options$output : defaultOutputPath);
196
+ let output = node_path.resolve(process$1.cwd(), (_options$output = options.output) !== null && _options$output !== void 0 ? _options$output : defaultOutputPath);
185
197
  if (isOPKXFilename.test(output))
186
198
  ;
187
199
  else {
@@ -194,7 +206,7 @@ const normalize$a = async (options) => {
194
206
  };
195
207
  };
196
208
  const build = async function() {
197
- var _appPackageJSON$scrip;
209
+ var _appPackageJSON$scrip, _appRcJSON$build$comp, _appRcJSON$build;
198
210
  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
199
211
  args[_key] = arguments[_key];
200
212
  }
@@ -202,16 +214,55 @@ const build = async function() {
202
214
  options
203
215
  } = createOnesApp.getCommandOptions(args, buildCommandArguments);
204
216
  const normalizedOptions = await normalize$a(options);
205
- console.log("build", normalizedOptions);
206
217
  const appPackageJSON = getAppPackageJSON();
207
- console.log("appPackageJSON", appPackageJSON);
208
218
  const appManifestJSON = getAppManifestJSON();
209
- console.log("appManifestJSON", appManifestJSON);
210
- if ((_appPackageJSON$scrip = appPackageJSON.scripts) !== null && _appPackageJSON$scrip !== void 0 && _appPackageJSON$scrip.build)
211
- ;
212
- else {
219
+ const appRcJSON = await getAppRcJSON();
220
+ appManifestJSON.app.name;
221
+ if ((_appPackageJSON$scrip = appPackageJSON.scripts) !== null && _appPackageJSON$scrip !== void 0 && _appPackageJSON$scrip.build) {
222
+ node_child_process.spawnSync("npm", ["run", "build"], {
223
+ cwd: getAppWorkspacePath(),
224
+ stdio: "inherit"
225
+ });
226
+ } else {
213
227
  return createOnesApp.throwError(ErrorCode.BUILD_SCRIPT_NOT_FOUND, i18n.t("error.build.scriptNotFound"));
214
228
  }
229
+ const archive = archiver("zip", {
230
+ zlib: {
231
+ level: 9
232
+ }
233
+ });
234
+ archive.on("error", (err) => {
235
+ throw err;
236
+ });
237
+ archive.on("warning", (err) => {
238
+ throw err;
239
+ });
240
+ archive.on("progress", (progress) => {
241
+ const {
242
+ entries,
243
+ fs
244
+ } = progress;
245
+ const entriesStr = entries.total > 0 ? ` ${entries.processed}/${entries.total} files` : "";
246
+ const bytesStr = fs.totalBytes > 0 ? ` ${(fs.processedBytes / 1024).toFixed(1)}/${(fs.totalBytes / 1024).toFixed(1)} KB` : "";
247
+ process.stdout.write(`\rCompressing:${entriesStr}${bytesStr} `);
248
+ });
249
+ archive.on("finish", () => {
250
+ process.stdout.write("\n");
251
+ console.log(`Output file: ${normalizedOptions.output}`);
252
+ console.log(`OPKX "${node_path.basename(normalizedOptions.output)}" created successfully!`);
253
+ });
254
+ const outputStream = node_fs.createWriteStream(normalizedOptions.output);
255
+ archive.pipe(outputStream);
256
+ 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 : [];
257
+ files.forEach((file) => {
258
+ archive.glob(file, {
259
+ cwd: getAppWorkspacePath()
260
+ });
261
+ });
262
+ archive.file(createOnesApp.PUBLIC_FILENAME.MANIFEST, {
263
+ name: createOnesApp.PUBLIC_FILENAME.MANIFEST
264
+ });
265
+ archive.finalize();
215
266
  };
216
267
  var InstallOptions = /* @__PURE__ */ ((InstallOptions2) => {
217
268
  InstallOptions2["AUTO"] = "auto";
@@ -288,7 +339,8 @@ const StoreJSONSchema = zod.z.object({
288
339
  timestamp: zod.z.number().optional(),
289
340
  base_url: zod.z.string().optional(),
290
341
  region_url: zod.z.string().optional(),
291
- ones_token: zod.z.string().optional()
342
+ ones_token: zod.z.string().optional(),
343
+ host_token: zod.z.string().optional()
292
344
  });
293
345
  const {
294
346
  ensureFile,
@@ -353,6 +405,11 @@ const mergeStore = async (store) => {
353
405
  ...store
354
406
  });
355
407
  };
408
+ const getBaseURL = async () => {
409
+ var _store$base_url;
410
+ const store = await getStore();
411
+ return (_store$base_url = store.base_url) !== null && _store$base_url !== void 0 ? _store$base_url : "";
412
+ };
356
413
  const setBaseURL = async (baseURL) => {
357
414
  return mergeStore({
358
415
  base_url: baseURL
@@ -378,14 +435,415 @@ const setONESToken = async (token) => {
378
435
  ones_token: token
379
436
  });
380
437
  };
381
- const invokeTunnel = async (port) => {
382
- console.log("invokeTunnel", port);
438
+ class TunnelClient {
439
+ constructor(localPort, baseUrl, appID, hostedToken) {
440
+ _defineProperty(this, "ws", null);
441
+ this.localPort = localPort;
442
+ this.baseUrl = baseUrl;
443
+ this.appID = appID;
444
+ this.hostedToken = hostedToken;
445
+ }
446
+ async connect() {
447
+ const proxyUrl = this.buildProxyUrl();
448
+ this.ws = new WebSocket(proxyUrl, {
449
+ headers: {
450
+ Authorization: `Bearer ${this.hostedToken}`
451
+ }
452
+ });
453
+ this.ws.on("message", async (data) => {
454
+ const message = this.parseMessage(data);
455
+ if (!message) {
456
+ return;
457
+ }
458
+ await this.handleMessage(message);
459
+ });
460
+ this.ws.on("ping", (data) => {
461
+ var _this$ws;
462
+ (_this$ws = this.ws) === null || _this$ws === void 0 || _this$ws.pong(data);
463
+ });
464
+ this.ws.on("error", (error) => {
465
+ console.error("WebSocket error:", error);
466
+ });
467
+ return new Promise((resolve, reject) => {
468
+ var _this$ws2, _this$ws3;
469
+ (_this$ws2 = this.ws) === null || _this$ws2 === void 0 || _this$ws2.on("open", () => resolve());
470
+ (_this$ws3 = this.ws) === null || _this$ws3 === void 0 || _this$ws3.on("error", reject);
471
+ });
472
+ }
473
+ close() {
474
+ var _this$ws4;
475
+ (_this$ws4 = this.ws) === null || _this$ws4 === void 0 || _this$ws4.close();
476
+ }
477
+ buildProxyUrl() {
478
+ const url = new URL("/platform/app/relay/", this.baseUrl);
479
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
480
+ url.searchParams.set("app_id", this.appID);
481
+ return url.toString();
482
+ }
483
+ parseMessage(data) {
484
+ const payload = data.toString();
485
+ try {
486
+ const message = JSON.parse(payload);
487
+ if (!message) {
488
+ return null;
489
+ }
490
+ return message;
491
+ } catch (error) {
492
+ console.error("Invalid tunnel message:", error);
493
+ return null;
494
+ }
495
+ }
496
+ async handleMessage(message) {
497
+ const request = this.getRequestPayload(message);
498
+ if (!request) {
499
+ return;
500
+ }
501
+ if (request.path === ONES_CLI_MANIFEST_PATH) {
502
+ var _this$ws5;
503
+ const appManifest = getAppManifestJSON().app;
504
+ const baseURL = await buildTunnelUrl();
505
+ const reply = {
506
+ id: message.id,
507
+ payload: {
508
+ status: 200,
509
+ headers: {
510
+ "content-type": ["application/json"]
511
+ },
512
+ body: {
513
+ ...appManifest,
514
+ base_url: baseURL
515
+ }
516
+ }
517
+ };
518
+ (_this$ws5 = this.ws) === null || _this$ws5 === void 0 || _this$ws5.send(JSON.stringify(reply));
519
+ return;
520
+ }
521
+ try {
522
+ var _this$ws6;
523
+ const response = await this.forwardRequest(request);
524
+ const reply = {
525
+ id: message.id,
526
+ payload: response
527
+ };
528
+ (_this$ws6 = this.ws) === null || _this$ws6 === void 0 || _this$ws6.send(JSON.stringify(reply));
529
+ } catch (error) {
530
+ var _this$ws7;
531
+ const reply = {
532
+ id: message.id,
533
+ payload: {
534
+ status: 500,
535
+ headers: {
536
+ "x-agent-error": [error instanceof Error ? error.message : "Unknown error"]
537
+ },
538
+ body: "agent request error"
539
+ }
540
+ };
541
+ (_this$ws7 = this.ws) === null || _this$ws7 === void 0 || _this$ws7.send(JSON.stringify(reply));
542
+ }
543
+ }
544
+ getRequestPayload(message) {
545
+ const payload = message.payload;
546
+ if (!(payload !== null && payload !== void 0 && payload.method) || !(payload !== null && payload !== void 0 && payload.path)) {
547
+ return null;
548
+ }
549
+ return payload;
550
+ }
551
+ async forwardRequest(payload) {
552
+ const url = new URL(payload.path, `http://127.0.0.1:${this.localPort}`);
553
+ if (payload.query) {
554
+ Object.entries(payload.query).forEach((_ref) => {
555
+ let [key, value] = _ref;
556
+ url.searchParams.set(key, value);
557
+ });
558
+ }
559
+ const headers = this.normalizeHeaders(payload.headers);
560
+ const body = this.normalizeBody(payload.body);
561
+ const response = await axios.request({
562
+ url: url.toString(),
563
+ method: payload.method,
564
+ headers,
565
+ data: body,
566
+ responseType: "text",
567
+ validateStatus: () => true
568
+ });
569
+ return {
570
+ status: response.status,
571
+ headers: this.collectHeaders(response.headers),
572
+ body: this.normalizeResponseBody(response.data)
573
+ };
574
+ }
575
+ normalizeHeaders(headers) {
576
+ if (!headers) {
577
+ return void 0;
578
+ }
579
+ const normalized = {};
580
+ Object.entries(headers).forEach((_ref2) => {
581
+ let [key, values] = _ref2;
582
+ if (!values || values.length === 0) {
583
+ return;
584
+ }
585
+ normalized[key] = values.join(",");
586
+ });
587
+ return normalized;
588
+ }
589
+ collectHeaders(headers) {
590
+ const collected = {};
591
+ Object.entries(headers).forEach((_ref3) => {
592
+ let [key, value] = _ref3;
593
+ if (Array.isArray(value)) {
594
+ collected[key] = value.map((item) => String(item));
595
+ return;
596
+ }
597
+ if (value !== void 0 && value !== null) {
598
+ collected[key] = [String(value)];
599
+ }
600
+ });
601
+ return collected;
602
+ }
603
+ normalizeBody(body) {
604
+ if (body === void 0 || body === null) {
605
+ return void 0;
606
+ }
607
+ if (typeof body === "string") {
608
+ return body;
609
+ }
610
+ return JSON.stringify(body);
611
+ }
612
+ normalizeResponseBody(body) {
613
+ if (!body) {
614
+ return void 0;
615
+ }
616
+ try {
617
+ return JSON.parse(body);
618
+ } catch {
619
+ return body;
620
+ }
621
+ }
622
+ }
623
+ const getPath = (path, map2) => {
624
+ var _context;
625
+ return _reduceInstanceProperty(_context = path.split("/")).call(_context, (base, part) => {
626
+ if (/^:/.test(part)) {
627
+ return `${base}/${map2[part.slice(1)]}`;
628
+ }
629
+ return `${base}/${part}`;
630
+ }, "").slice(1);
631
+ };
632
+ const consoleUnauthorizedMessage = () => {
633
+ console.log("Not logged in");
634
+ console.log('Login with "ones login" command');
635
+ };
636
+ const getURL = async (path, pathMap, queryMap) => {
637
+ const base = await getRegionURL();
638
+ if (base) {
639
+ const query = new URLSearchParams(queryMap !== null && queryMap !== void 0 ? queryMap : {}).toString();
640
+ return `${base}${getPath(path, pathMap !== null && pathMap !== void 0 ? pathMap : {})}${query ? `?${query}` : ""}`;
641
+ }
642
+ consoleUnauthorizedMessage();
643
+ process$1.exit(1);
644
+ };
645
+ const getHeaders = async (value) => {
646
+ const token = await getONESToken();
647
+ if (token) {
648
+ return lodashEs.merge({
649
+ Authorization: `Bearer ${token}`
650
+ }, value);
651
+ }
652
+ consoleUnauthorizedMessage();
653
+ process$1.exit(1);
654
+ };
655
+ const handleError = (error) => {
656
+ var _error$response;
657
+ if (((_error$response = error.response) === null || _error$response === void 0 ? void 0 : _error$response.status) === 401) {
658
+ console.log(error.response.statusText);
659
+ consoleUnauthorizedMessage();
660
+ } else {
661
+ console.error(error);
662
+ }
663
+ return {};
664
+ };
665
+ const API = {
666
+ TOKEN_INFO: "/project/api/project/auth/token_info",
667
+ HOSTED_TOKEN: "/platform/runtime_manager/hosted_token",
668
+ APP_LIST: "/platform/api/app/list",
669
+ APP_INSTALL: "/platform/api/app/install",
670
+ APP_UPGRADE: "/platform/api/app/upgrade",
671
+ APP_UNINSTALL: "/platform/api/app/:installation_id/uninstall",
672
+ APP_ENABLE: "/platform/api/app/:installation_id/enable",
673
+ APP_DISABLE: "/platform/api/app/:installation_id/disable"
674
+ };
675
+ const isRecord = (value) => {
676
+ return typeof value === "object" && value !== null;
677
+ };
678
+ const getHostedTokenScopes = (ones2) => {
679
+ const storage = ones2 === null || ones2 === void 0 ? void 0 : ones2.storage;
680
+ if (!storage) {
681
+ return [];
682
+ }
683
+ const scopes = /* @__PURE__ */ new Set();
684
+ if (Array.isArray(storage.entities) && storage.entities.length > 0) {
685
+ scopes.add(createOnesApp.HostedTokenScope.STORAGE_ENTITY);
686
+ }
687
+ if (storage.object !== void 0 && storage.object !== null && storage.object !== false) {
688
+ scopes.add(createOnesApp.HostedTokenScope.STORAGE_OBJECT);
689
+ }
690
+ return Array.from(scopes);
691
+ };
692
+ const getRelayScope = () => {
693
+ return createOnesApp.HostedTokenScope.RELAY;
694
+ };
695
+ const getHostToken = async (baseUrl, userToken, appID, scopes) => {
696
+ const url = `${baseUrl.replace(/\/$/, "")}${API.HOSTED_TOKEN}`;
697
+ return axios.post(url, {
698
+ app_id: appID,
699
+ scopes
700
+ }, {
701
+ headers: {
702
+ Authorization: `Bearer ${userToken}`
703
+ }
704
+ }).then((resp) => {
705
+ const data = resp === null || resp === void 0 ? void 0 : resp.data;
706
+ const tokenFromData = (value) => {
707
+ if (isRecord(value) && isRecord(value.data)) {
708
+ const hosted_token = value.data.hosted_token;
709
+ if (typeof hosted_token === "string" && hosted_token.length > 0) {
710
+ return hosted_token;
711
+ }
712
+ }
713
+ return null;
714
+ };
715
+ const token = tokenFromData(data);
716
+ if (token) {
717
+ return token;
718
+ }
719
+ return createOnesApp.throwError(ErrorCode.HOSTED_TOKEN_EMPTY, i18n.t("error.hostedToken.empty"));
720
+ }).catch((error) => {
721
+ handleError(error);
722
+ return createOnesApp.throwError(ErrorCode.HOSTED_TOKEN_REQUEST_FAILED, i18n.t("error.hostedToken.requestFailed"));
723
+ });
724
+ };
725
+ const fetchAppBase = async (params) => {
726
+ var _params$url;
727
+ const url = await getURL((_params$url = params.url) !== null && _params$url !== void 0 ? _params$url : "", params.pathMap, params.queryMap);
728
+ const headers = await getHeaders(params.headers);
729
+ const response = await axios({
730
+ ...params,
731
+ url,
732
+ headers
733
+ });
734
+ return response.data;
735
+ };
736
+ const fetchAppList = async (appID) => {
737
+ return await fetchAppBase({
738
+ url: API.APP_LIST,
739
+ method: "GET",
740
+ queryMap: {
741
+ app_id: appID
742
+ }
743
+ }).catch(handleError);
744
+ };
745
+ const fetchTokenInfo = async () => {
746
+ return await fetchAppBase({
747
+ url: API.TOKEN_INFO,
748
+ method: "GET"
749
+ }).catch(handleError);
750
+ };
751
+ const fetchAppInstall = async (data) => {
752
+ var _appList$data$0$insta, _appList$data;
753
+ const appID = getAppManifestJSON().app.id;
754
+ const appList = await fetchAppList(appID);
755
+ 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 : "";
756
+ const url = installationID ? API.APP_UPGRADE : API.APP_INSTALL;
757
+ return await fetchAppBase({
758
+ url,
759
+ method: "POST",
760
+ data
761
+ }).catch(handleError);
762
+ };
763
+ const fetchAppUninstall = async () => {
764
+ var _appList$data$0$insta2, _appList$data2;
765
+ const appID = getAppManifestJSON().app.id;
766
+ const appList = await fetchAppList(appID);
767
+ 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 : "";
768
+ return await fetchAppBase({
769
+ url: API.APP_UNINSTALL,
770
+ method: "POST",
771
+ pathMap: {
772
+ installation_id: installationID
773
+ }
774
+ }).catch(handleError);
775
+ };
776
+ const fetchAppEnable = async () => {
777
+ var _appList$data$0$insta3, _appList$data3;
778
+ const appID = getAppManifestJSON().app.id;
779
+ const appList = await fetchAppList(appID);
780
+ 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 : "";
781
+ return await fetchAppBase({
782
+ url: API.APP_ENABLE,
783
+ method: "POST",
784
+ pathMap: {
785
+ installation_id: installationID
786
+ }
787
+ }).catch(handleError);
788
+ };
789
+ const fetchAppDisable = async () => {
790
+ var _appList$data$0$insta4, _appList$data4;
791
+ const appID = getAppManifestJSON().app.id;
792
+ const appList = await fetchAppList(appID);
793
+ 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 : "";
794
+ return await fetchAppBase({
795
+ url: API.APP_DISABLE,
796
+ method: "POST",
797
+ pathMap: {
798
+ installation_id: installationID
799
+ }
800
+ }).catch(handleError);
801
+ };
802
+ const ONES_CLI_MANIFEST_PATH = "/__ones_cli_manifest__";
803
+ const buildTunnelContext = async () => {
804
+ var _appManifestJSON$app$, _appManifestJSON$app;
383
805
  const appManifestJSON = getAppManifestJSON();
384
- console.log("appManifestJSON", appManifestJSON);
806
+ 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$ : "";
807
+ if (!appID) {
808
+ throw new Error("app id is empty");
809
+ }
385
810
  const regionURL = await getRegionURL();
811
+ if (!regionURL) {
812
+ throw new Error("region url is empty");
813
+ }
814
+ return {
815
+ appManifestJSON,
816
+ appID,
817
+ regionURL
818
+ };
819
+ };
820
+ const buildTunnelUrl = async () => {
821
+ const {
822
+ appID,
823
+ regionURL
824
+ } = await buildTunnelContext();
825
+ const url = new URL(regionURL);
826
+ return `${url.protocol}//${url.host}/platform/app/relay/dispatch/${appID}`;
827
+ };
828
+ const invokeTunnel = async (port) => {
829
+ const {
830
+ appManifestJSON,
831
+ appID,
832
+ regionURL
833
+ } = await buildTunnelContext();
386
834
  const onesToken = await getONESToken();
387
- console.log("regionURL", regionURL);
388
- console.log("onesToken", onesToken);
835
+ if (!onesToken) {
836
+ consoleUnauthorizedMessage();
837
+ process$1.exit(1);
838
+ }
839
+ const storageScopes = getHostedTokenScopes(appManifestJSON.ones);
840
+ const scopes = Array.from(/* @__PURE__ */ new Set([...storageScopes, getRelayScope()]));
841
+ const hostedToken = await getHostToken(regionURL, onesToken, appID, scopes);
842
+ process.env.ONES_HOSTED_TOKEN = hostedToken;
843
+ const client = new TunnelClient(port, regionURL, appID, hostedToken);
844
+ await client.connect();
845
+ const runnelUrl = await buildTunnelUrl();
846
+ console.log(`Relay endpoint: ${runnelUrl}`);
389
847
  };
390
848
  const tunnel = async function() {
391
849
  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
@@ -395,18 +853,15 @@ const tunnel = async function() {
395
853
  options
396
854
  } = createOnesApp.getCommandOptions(args, tunnelCommandArguments);
397
855
  const normalizedOptions = await normalize$8(options);
398
- await invokeTunnel(normalizedOptions.port);
856
+ await invokeTunnel(Number(normalizedOptions.port));
399
857
  };
400
858
  const config = {
401
859
  defaultPort: {
402
- login: 8200
860
+ login: 8200,
861
+ tunnel: 8201
403
862
  }
404
863
  };
405
864
  const getConfig = () => config;
406
- const getPublicPath = () => {
407
- 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));
408
- return node_path.join(__dirname, "../public");
409
- };
410
865
  function createPromise() {
411
866
  let resolve;
412
867
  let reject;
@@ -482,6 +937,10 @@ const login = async function() {
482
937
  const html = node_fs.readFileSync(htmlPath, {
483
938
  encoding: "utf-8"
484
939
  });
940
+ const logoPath = node_path.join(publicPath, "logo.svg");
941
+ const logo = node_fs.readFileSync(logoPath, {
942
+ encoding: "utf-8"
943
+ });
485
944
  const {
486
945
  promise,
487
946
  resolve
@@ -490,6 +949,21 @@ const login = async function() {
490
949
  var _req$url$split$, _req$url, _search2$get, _search2$get2;
491
950
  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$ : "");
492
951
  const state = search2.get("state");
952
+ if (state === "logo") {
953
+ res.writeHead(200, {
954
+ "Content-Type": "image/svg+xml"
955
+ });
956
+ res.end(logo);
957
+ return;
958
+ }
959
+ if (state === "cancel") {
960
+ res.writeHead(200, {
961
+ "Content-Type": "image/svg+xml"
962
+ });
963
+ res.end(logo);
964
+ resolve(null);
965
+ return;
966
+ }
493
967
  const token = (_search2$get = search2.get("access_token")) !== null && _search2$get !== void 0 ? _search2$get : "";
494
968
  const region = (_search2$get2 = search2.get("region_url")) !== null && _search2$get2 !== void 0 ? _search2$get2 : "";
495
969
  if (state === uuid$1 && token && region) {
@@ -498,22 +972,31 @@ const login = async function() {
498
972
  ones_token: token,
499
973
  region_url: region
500
974
  });
975
+ res.writeHead(200, {
976
+ "Content-Type": "text/html"
977
+ });
978
+ res.end(html);
979
+ return;
501
980
  }
502
981
  res.writeHead(200, {
503
982
  "Content-Type": "text/html"
504
983
  });
505
- res.end(html);
984
+ res.end("Invalid state error, please try again!");
506
985
  });
507
986
  server.listen(port);
508
987
  promise.then(async (store) => {
509
- var _store$base_url, _store$ones_token, _store$region_url;
510
988
  await sleep(100);
511
989
  server.closeAllConnections();
512
- await setBaseURL((_store$base_url = store.base_url) !== null && _store$base_url !== void 0 ? _store$base_url : "");
513
- await setONESToken((_store$ones_token = store.ones_token) !== null && _store$ones_token !== void 0 ? _store$ones_token : "");
514
- await setRegionURL((_store$region_url = store.region_url) !== null && _store$region_url !== void 0 ? _store$region_url : "");
515
- console.log("Logged in successfully!");
516
- process.exit(0);
990
+ if (store) {
991
+ var _store$base_url, _store$ones_token, _store$region_url;
992
+ await setBaseURL((_store$base_url = store.base_url) !== null && _store$base_url !== void 0 ? _store$base_url : "");
993
+ await setONESToken((_store$ones_token = store.ones_token) !== null && _store$ones_token !== void 0 ? _store$ones_token : "");
994
+ await setRegionURL((_store$region_url = store.region_url) !== null && _store$region_url !== void 0 ? _store$region_url : "");
995
+ console.log("Logged in successfully!");
996
+ } else {
997
+ console.log("Login canceled!");
998
+ }
999
+ process$1.exit(0);
517
1000
  });
518
1001
  console.log("Logging into your ONES account...");
519
1002
  console.log(`Opening ${url}`);
@@ -536,120 +1019,6 @@ const logout = async function() {
536
1019
  await setStore({});
537
1020
  console.log("Logged out successfully!");
538
1021
  };
539
- const API = {
540
- TOKEN_INFO: "/project/api/project/auth/token_info",
541
- APP_LIST: "/platform/api/app/list",
542
- APP_INSTALL: "/app/install",
543
- APP_UNINSTALL: "/app/uninstall",
544
- APP_ENABLE: "/platform/api/app/:installation_id/enable",
545
- APP_DISABLE: "/platform/api/app/:installation_id/disable"
546
- };
547
- const getPath = (path, map2) => {
548
- var _context;
549
- return _reduceInstanceProperty(_context = path.split("/")).call(_context, (base, part) => {
550
- if (/^:/.test(part)) {
551
- return `${base}/${map2[part.slice(1)]}`;
552
- }
553
- return `${base}/${part}`;
554
- }, "").slice(1);
555
- };
556
- const consoleUnauthorizedMessage = () => {
557
- console.log("Not logged in");
558
- console.log('Login with "ones login" command');
559
- };
560
- const getURL = async (path, pathMap, queryMap) => {
561
- const base = await getRegionURL();
562
- if (base) {
563
- const query = new URLSearchParams(queryMap !== null && queryMap !== void 0 ? queryMap : {}).toString();
564
- return `${base}${getPath(path, pathMap !== null && pathMap !== void 0 ? pathMap : {})}${query ? `?${query}` : ""}`;
565
- }
566
- consoleUnauthorizedMessage();
567
- process.exit(1);
568
- };
569
- const getHeaders = async (value) => {
570
- const token = await getONESToken();
571
- if (token) {
572
- return lodashEs.merge({
573
- Authorization: `Bearer ${token}`
574
- }, value);
575
- }
576
- consoleUnauthorizedMessage();
577
- process.exit(1);
578
- };
579
- const handleError = (error) => {
580
- var _error$response;
581
- if (((_error$response = error.response) === null || _error$response === void 0 ? void 0 : _error$response.status) === 401) {
582
- console.log(error.response.statusText);
583
- consoleUnauthorizedMessage();
584
- } else {
585
- console.error(error);
586
- }
587
- return {};
588
- };
589
- const fetchAppBase = async (params) => {
590
- var _params$url;
591
- const url = await getURL((_params$url = params.url) !== null && _params$url !== void 0 ? _params$url : "", params.pathMap, params.queryMap);
592
- const headers = await getHeaders(params.headers);
593
- const response = await axios({
594
- ...params,
595
- url,
596
- headers
597
- });
598
- return response.data;
599
- };
600
- const fetchAppList = async (appID) => {
601
- return await fetchAppBase({
602
- url: API.APP_LIST,
603
- method: "GET",
604
- queryMap: {
605
- app_id: appID
606
- }
607
- }).catch(handleError);
608
- };
609
- const fetchTokenInfo = async () => {
610
- return await fetchAppBase({
611
- url: API.TOKEN_INFO,
612
- method: "GET"
613
- }).catch(handleError);
614
- };
615
- const fetchAppInstall = async () => {
616
- return await fetchAppBase({
617
- url: API.APP_INSTALL,
618
- method: "POST"
619
- }).catch(handleError);
620
- };
621
- const fetchAppUninstall = async () => {
622
- return await fetchAppBase({
623
- url: API.APP_UNINSTALL,
624
- method: "POST"
625
- }).catch(handleError);
626
- };
627
- const fetchAppEnable = async () => {
628
- var _appList$data$0$insta, _appList$data;
629
- const appID = getAppManifestJSON().app.id;
630
- const appList = await fetchAppList(appID);
631
- 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 : "";
632
- return await fetchAppBase({
633
- url: API.APP_ENABLE,
634
- method: "POST",
635
- pathMap: {
636
- installation_id: installationID
637
- }
638
- }).catch(handleError);
639
- };
640
- const fetchAppDisable = async () => {
641
- var _appList$data$0$insta2, _appList$data2;
642
- const appID = getAppManifestJSON().app.id;
643
- const appList = await fetchAppList(appID);
644
- 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 : "";
645
- return await fetchAppBase({
646
- url: API.APP_DISABLE,
647
- method: "POST",
648
- pathMap: {
649
- installation_id: installationID
650
- }
651
- }).catch(handleError);
652
- };
653
1022
  const normalize$5 = async (options) => {
654
1023
  lodashEs.noop(options);
655
1024
  return {};
@@ -664,11 +1033,13 @@ const whoami = async function() {
664
1033
  } = createOnesApp.getCommandOptions(args, whoamiCommandArguments);
665
1034
  const normalizedOptions = await normalize$5(options);
666
1035
  lodashEs.noop(normalizedOptions);
1036
+ const baseURL = await getBaseURL();
667
1037
  const tokenInfo = await fetchTokenInfo();
668
1038
  const name2 = (_tokenInfo$user = tokenInfo.user) === null || _tokenInfo$user === void 0 ? void 0 : _tokenInfo$user.name;
669
1039
  const email = (_tokenInfo$user2 = tokenInfo.user) === null || _tokenInfo$user2 === void 0 ? void 0 : _tokenInfo$user2.email;
670
1040
  if (name2 && email) {
671
1041
  console.log(`${name2} <${email}>`);
1042
+ console.log(`ONES: ${baseURL}`);
672
1043
  } else {
673
1044
  consoleUnauthorizedMessage();
674
1045
  }
@@ -686,7 +1057,11 @@ const install = async function() {
686
1057
  } = createOnesApp.getCommandOptions(args, installCommandArguments);
687
1058
  const normalizedOptions = await normalize$4(options);
688
1059
  lodashEs.noop(normalizedOptions);
689
- const result = await fetchAppInstall();
1060
+ await invokeTunnel(getConfig().defaultPort.tunnel);
1061
+ const runnelUrl = await buildTunnelUrl();
1062
+ const result = await fetchAppInstall({
1063
+ manifest_url: `${runnelUrl}${ONES_CLI_MANIFEST_PATH}`
1064
+ });
690
1065
  if (result.code === "OK") {
691
1066
  console.log("App installed successfully!");
692
1067
  } else {