@super-protocol/sp-cli 0.0.2-beta.1 → 0.0.2-beta.11

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 (47) hide show
  1. package/README.md +135 -321
  2. package/dist/commands/account/info.d.ts +21 -0
  3. package/dist/commands/account/info.js +43 -0
  4. package/dist/commands/auth/login.d.ts +1 -10
  5. package/dist/commands/auth/login.js +15 -84
  6. package/dist/commands/base.d.ts +2 -4
  7. package/dist/commands/base.js +8 -10
  8. package/dist/commands/config/add.js +9 -5
  9. package/dist/commands/config/base.d.ts +4 -3
  10. package/dist/commands/config/base.js +12 -14
  11. package/dist/commands/config/create.js +4 -4
  12. package/dist/commands/config/list.js +2 -2
  13. package/dist/commands/config/use.js +5 -3
  14. package/dist/commands/files/download.d.ts +15 -0
  15. package/dist/commands/files/download.js +53 -0
  16. package/dist/commands/files/upload.d.ts +18 -0
  17. package/dist/commands/files/upload.js +77 -0
  18. package/dist/commands/storage/base.d.ts +5 -0
  19. package/dist/commands/storage/base.js +113 -2
  20. package/dist/commands/storage/create.d.ts +0 -4
  21. package/dist/commands/storage/create.js +0 -116
  22. package/dist/commands/storage/select.js +12 -10
  23. package/dist/commands/storage/update.d.ts +0 -2
  24. package/dist/commands/storage/update.js +35 -87
  25. package/dist/config/config-file.schema.d.ts +4 -4
  26. package/dist/config/config-file.schema.js +1 -1
  27. package/dist/config/config.schema.d.ts +16 -16
  28. package/dist/config/config.schema.js +1 -10
  29. package/dist/config/resource.schema.d.ts +31 -0
  30. package/dist/config/resource.schema.js +14 -0
  31. package/dist/constants.d.ts +1 -0
  32. package/dist/constants.js +1 -0
  33. package/dist/lib/container.d.ts +4 -6
  34. package/dist/lib/container.js +21 -21
  35. package/dist/managers/account-manager.js +13 -3
  36. package/dist/managers/config-file-manager.d.ts +1 -1
  37. package/dist/managers/config-file-manager.js +13 -8
  38. package/dist/services/auth.service.d.ts +24 -0
  39. package/dist/services/auth.service.js +93 -0
  40. package/dist/services/storage.service.d.ts +44 -7
  41. package/dist/services/storage.service.js +207 -12
  42. package/dist/utils/helper.d.ts +5 -0
  43. package/dist/utils/helper.js +22 -0
  44. package/dist/utils/progress.d.ts +8 -0
  45. package/dist/utils/progress.js +27 -0
  46. package/oclif.manifest.json +180 -184
  47. package/package.json +9 -7
@@ -3,7 +3,6 @@ import { ProviderClient } from '@super-protocol/provider-client';
3
3
  import { AccountManager, ConfigFileManager, ConfigManager } from '../managers/index.js';
4
4
  interface RuntimeConfig {
5
5
  configFile?: string;
6
- url?: string;
7
6
  }
8
7
  export declare class AppContainer {
9
8
  readonly cwdDir: string;
@@ -17,7 +16,6 @@ export declare class AppContainer {
17
16
  private readonly initQueue;
18
17
  private logger;
19
18
  private runtimeConfigFile?;
20
- private runtimeProviderUrl?;
21
19
  private constructor();
22
20
  static initialize(currentDir: string, config: Config): AppContainer;
23
21
  get accountManager(): AccountManager;
@@ -25,10 +23,10 @@ export declare class AppContainer {
25
23
  get configManager(): ConfigManager;
26
24
  static get container(): AppContainer;
27
25
  get providerClient(): ProviderClient;
28
- build(): Promise<void>;
29
- initAccountManager(): this;
30
- initConfigFileManager(): this;
31
- initConfigManager(): this;
26
+ build(): Promise<this>;
27
+ initAccountManager(rebuild?: boolean): this;
28
+ initConfigFileManager(rebuild?: boolean): this;
29
+ initConfigManager(rebuild?: boolean): this;
32
30
  initProviderClient({ enableAuth, enableCookies, rebuild }?: {
33
31
  enableAuth?: boolean;
34
32
  enableCookies?: boolean;
@@ -17,7 +17,6 @@ export class AppContainer {
17
17
  initQueue = new Map();
18
18
  logger;
19
19
  runtimeConfigFile;
20
- runtimeProviderUrl;
21
20
  constructor(cwdDir, oclifConfig) {
22
21
  this.cwdDir = cwdDir;
23
22
  this.oclifConfig = oclifConfig;
@@ -61,9 +60,10 @@ export class AppContainer {
61
60
  }
62
61
  async build() {
63
62
  await Promise.all(this.initPromises);
63
+ return this;
64
64
  }
65
- initAccountManager() {
66
- this.initConfigManager();
65
+ initAccountManager(rebuild = true) {
66
+ this.initConfigManager(rebuild);
67
67
  return this.queueInit('accountManager', async () => {
68
68
  await this.waitFor('configManager');
69
69
  if (this._accountManager) {
@@ -73,9 +73,9 @@ export class AppContainer {
73
73
  const accountManager = new AccountManager(this.configManager, this.logger);
74
74
  await accountManager.init();
75
75
  this._accountManager = accountManager;
76
- });
76
+ }, rebuild);
77
77
  }
78
- initConfigFileManager() {
78
+ initConfigFileManager(rebuild = false) {
79
79
  return this.queueInit('configFileManager', async () => {
80
80
  if (this._configFileManager) {
81
81
  return;
@@ -85,10 +85,10 @@ export class AppContainer {
85
85
  });
86
86
  await configFileManager.init();
87
87
  this._configFileManager = configFileManager;
88
- });
88
+ }, rebuild);
89
89
  }
90
- initConfigManager() {
91
- this.initConfigFileManager();
90
+ initConfigManager(rebuild = false) {
91
+ this.initConfigFileManager(rebuild);
92
92
  return this.queueInit('configManager', async () => {
93
93
  await this.waitFor('configFileManager');
94
94
  if (this._configManager) {
@@ -102,7 +102,7 @@ export class AppContainer {
102
102
  const configManager = new ConfigManager(configFilePath, this.logger);
103
103
  await configManager.init();
104
104
  this._configManager = configManager;
105
- });
105
+ }, rebuild);
106
106
  }
107
107
  initProviderClient({ enableAuth = true, enableCookies = true, rebuild = false } = {}) {
108
108
  this.initConfigManager();
@@ -111,13 +111,23 @@ export class AppContainer {
111
111
  return;
112
112
  }
113
113
  await this.waitFor('configManager');
114
- const providerUrl = this.runtimeProviderUrl || await this.configManager.get('providerUrl') || PROVIDER_URL;
114
+ const providerUrl = await this.configManager.get('providerUrl') || PROVIDER_URL;
115
115
  this.logger.info('Initializing provider client');
116
116
  const providerClient = createProviderClient({
117
117
  baseUrl: providerUrl,
118
118
  logger: this.logger,
119
119
  middlewares: [requestIdMiddleware, loggerMiddleware],
120
120
  });
121
+ if (enableCookies) {
122
+ this.logger.info('Initializing cookie middleware');
123
+ const cookiesMiddleware = await createCookieMiddleware(this.configManager, this.logger, providerUrl);
124
+ providerClient.use(cookiesMiddleware);
125
+ }
126
+ if (enableAuth) {
127
+ this.logger.info('Initializing auth middleware');
128
+ const authMiddleware = await createAuthMiddleware(this.configManager, providerClient, this.logger);
129
+ providerClient.use(authMiddleware);
130
+ }
121
131
  providerClient.use({
122
132
  onRequest: async ({ request }) => {
123
133
  const req = request.clone();
@@ -128,20 +138,11 @@ export class AppContainer {
128
138
  }
129
139
  this.logger.debug({
130
140
  body,
141
+ token: req.headers.get('Authorization'),
131
142
  url: req.url,
132
143
  }, 'Requesting');
133
144
  },
134
145
  });
135
- if (enableCookies) {
136
- this.logger.info('Initializing cookie middleware');
137
- const cookiesMiddleware = await createCookieMiddleware(this.configManager, this.logger, providerUrl);
138
- providerClient.use(cookiesMiddleware);
139
- }
140
- if (enableAuth) {
141
- this.logger.info('Initializing auth middleware');
142
- const authMiddleware = await createAuthMiddleware(this.configManager, providerClient, this.logger);
143
- providerClient.use(authMiddleware);
144
- }
145
146
  this._providerClient = providerClient;
146
147
  }, rebuild);
147
148
  }
@@ -149,7 +150,6 @@ export class AppContainer {
149
150
  if (this.initQueue.size > 0) {
150
151
  throw new Error('Cannot change runtime config after initialization has started');
151
152
  }
152
- this.runtimeProviderUrl = config.url;
153
153
  if (config.configFile) {
154
154
  this.runtimeConfigFile = path.isAbsolute(config.configFile)
155
155
  ? config.configFile
@@ -4,9 +4,9 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
4
4
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
5
  return c > 3 && r && Object.defineProperty(target, key, r), r;
6
6
  };
7
- import { confirm, password } from '@inquirer/prompts';
7
+ import { confirm, isCancel, password } from '@clack/prompts';
8
8
  import { ux } from '@oclif/core';
9
- import { Value } from '@sinclair/typebox/value';
9
+ import { Value } from 'typebox/value';
10
10
  import { Retryable } from 'typescript-retry-decorator';
11
11
  import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts';
12
12
  import { accountSchema } from '../config/config.schema.js';
@@ -69,6 +69,9 @@ export class AccountManager {
69
69
  const ask = await confirm({
70
70
  message: 'Do you want to create new one?',
71
71
  });
72
+ if (isCancel(ask)) {
73
+ ux.error('Operation cancelled.', { exit: 1 });
74
+ }
72
75
  if (ask) {
73
76
  await this.promptAccount();
74
77
  }
@@ -81,8 +84,15 @@ export class AccountManager {
81
84
  const askPrivateKey = await confirm({
82
85
  message: 'Do you want to input privateKey?',
83
86
  });
87
+ if (isCancel(askPrivateKey)) {
88
+ ux.error('Operation cancelled.', { exit: 1 });
89
+ }
84
90
  if (askPrivateKey) {
85
- const privateKey = await password({ message: 'Please input your privateKey for using in account' });
91
+ const privateKeyInput = await password({ message: 'Please input your privateKey for using in account' });
92
+ if (isCancel(privateKeyInput)) {
93
+ ux.error('Operation cancelled.', { exit: 1 });
94
+ }
95
+ const privateKey = privateKeyInput.trim();
86
96
  try {
87
97
  const account = await this.createFromKey(privateKey);
88
98
  ux.stdout('Your privateKey will be used in config. Keypair created');
@@ -1,4 +1,4 @@
1
- import { confirm, select } from '@inquirer/prompts';
1
+ import { confirm, select } from '@clack/prompts';
2
2
  import { ux } from '@oclif/core';
3
3
  import pino from 'pino';
4
4
  import { CliConfig } from '../config/config.schema.js';
@@ -1,8 +1,8 @@
1
- import { confirm, select } from '@inquirer/prompts';
1
+ import { confirm, isCancel, select } from '@clack/prompts';
2
2
  import { ux } from '@oclif/core';
3
- import { Value } from '@sinclair/typebox/value';
4
3
  import * as fs from 'node:fs';
5
4
  import path from 'node:path';
5
+ import { Value } from 'typebox/value';
6
6
  import { cliConfigSchema } from '../config/config.schema.js';
7
7
  import { DIR_ACCESS_PERMS, FILE_ACCESS_PERMS } from '../constants.js';
8
8
  import { getConfigName } from '../utils/helper.js';
@@ -78,22 +78,27 @@ export class ConfigFileManager {
78
78
  configToDelete = config.file;
79
79
  }
80
80
  else {
81
- configToDelete = await this.selectPrompt({
82
- choices: configs.map(config => ({
83
- name: config.name,
81
+ const selection = await this.selectPrompt({
82
+ message: 'Select configuration to delete:',
83
+ options: configs.map(config => ({
84
+ label: config.name,
84
85
  value: config.file,
85
86
  })),
86
- message: 'Select configuration to delete:',
87
87
  });
88
+ if (isCancel(selection)) {
89
+ this.ux.stdout('Deletion cancelled');
90
+ return;
91
+ }
92
+ configToDelete = selection;
88
93
  }
89
94
  const configToDeleteData = configs.find(c => c.file === configToDelete);
90
95
  const displayName = configToDeleteData?.name || configToDelete;
91
96
  if (!force) {
92
97
  const confirmed = await this.confirmPrompt({
93
- default: false,
98
+ initialValue: false,
94
99
  message: `Are you sure you want to delete configuration "${displayName}"?`,
95
100
  });
96
- if (!confirmed) {
101
+ if (isCancel(confirmed) || !confirmed) {
97
102
  this.ux.stdout('Deletion cancelled');
98
103
  return;
99
104
  }
@@ -0,0 +1,24 @@
1
+ import { ProviderClient } from '@super-protocol/provider-client';
2
+ import pino from 'pino';
3
+ import { AccountManager } from '../managers/account-manager.js';
4
+ import { ConfigManager } from '../managers/config-manager.js';
5
+ export declare class AuthError extends Error {
6
+ }
7
+ export declare class AuthService {
8
+ private readonly accountManager;
9
+ private readonly configManager;
10
+ private readonly providerClient;
11
+ private readonly logger;
12
+ constructor(accountManager: AccountManager, configManager: ConfigManager, providerClient: ProviderClient, logger: pino.BaseLogger);
13
+ auth(): Promise<void>;
14
+ getTokens(nonce: string): Promise<void>;
15
+ getUserNonce(address: string): Promise<{
16
+ error: {
17
+ message: string;
18
+ statusCode: number;
19
+ } | undefined;
20
+ user: {
21
+ nonce?: string;
22
+ } | undefined;
23
+ }>;
24
+ }
@@ -0,0 +1,93 @@
1
+ export class AuthError extends Error {
2
+ }
3
+ export class AuthService {
4
+ accountManager;
5
+ configManager;
6
+ providerClient;
7
+ logger;
8
+ constructor(accountManager, configManager, providerClient, logger) {
9
+ this.accountManager = accountManager;
10
+ this.configManager = configManager;
11
+ this.providerClient = providerClient;
12
+ this.logger = logger;
13
+ }
14
+ async auth() {
15
+ const address = this.accountManager.getAddress();
16
+ const { error: nonceError, user } = await this.getUserNonce(address);
17
+ if (nonceError && nonceError.statusCode === 404) {
18
+ this.logger.debug('Nonce error call sign up');
19
+ const { data: nonceResponse, error: signUpError } = await this.providerClient.POST('/api/auth/sign-up', {
20
+ body: {
21
+ address,
22
+ },
23
+ });
24
+ if (signUpError && signUpError.statusCode === 409) {
25
+ this.logger.debug({ signUpError }, 'Error signing up');
26
+ const { error: nonceError, user } = await this.getUserNonce(address);
27
+ this.logger.debug({ nonceError, user }, 'Requesting nonce again');
28
+ if (user && user.nonce) {
29
+ await this.getTokens(user.nonce);
30
+ }
31
+ else {
32
+ throw new AuthError('User exists but nonce is unavailable. Please try again or contact support.');
33
+ }
34
+ }
35
+ else if (signUpError) {
36
+ this.logger.error({ signUpError }, 'Sign-up failed');
37
+ throw new AuthError('Sign-up failed. Please try again later.');
38
+ }
39
+ else {
40
+ const nonce = nonceResponse?.nonce;
41
+ if (!nonce) {
42
+ this.logger.error({ response: nonceResponse }, 'Unexpected sign-up response');
43
+ throw new AuthError('Provider did not return a nonce.');
44
+ }
45
+ await this.getTokens(nonce);
46
+ }
47
+ }
48
+ else if (user && user.nonce) {
49
+ this.logger.debug({ user }, 'Requesting for existed user');
50
+ await this.getTokens(user.nonce);
51
+ }
52
+ else {
53
+ throw new AuthError('Unable to retrieve authentication nonce. Please try again later or contact support if the issue persists.');
54
+ }
55
+ }
56
+ async getTokens(nonce) {
57
+ const signature = await this.accountManager.createSign(nonce);
58
+ const { data: tokenResponse, error, } = await this.providerClient.POST('/api/auth/token', {
59
+ body: {
60
+ address: this.accountManager.getAddress(),
61
+ provider: 'sp-cli',
62
+ signature,
63
+ },
64
+ });
65
+ if (error) {
66
+ this.logger.error({ err: error }, 'Token exchange failed');
67
+ throw new AuthError(error.message);
68
+ }
69
+ const { accessToken } = tokenResponse || {};
70
+ if (!accessToken) {
71
+ this.logger.error({ response: tokenResponse }, 'Unexpected token response');
72
+ throw new AuthError('Provider returned an unexpected token response.');
73
+ }
74
+ await this.configManager.setCredentials({ accessKey: accessToken });
75
+ }
76
+ async getUserNonce(address) {
77
+ try {
78
+ const { data, error } = await this.providerClient.GET('/api/users/nonce/{address}', {
79
+ params: {
80
+ path: {
81
+ address,
82
+ },
83
+ },
84
+ });
85
+ this.logger.debug({ data, error }, 'Getting user nonce');
86
+ return { error, user: data };
87
+ }
88
+ catch (error) {
89
+ this.logger.error({ err: error }, 'Error request nonce');
90
+ throw new AuthError('Connection failure, please try again later');
91
+ }
92
+ }
93
+ }
@@ -1,22 +1,50 @@
1
+ import { EncryptionWithIV, Resource, RuntimeInputInfo } from '@super-protocol/dto-js';
1
2
  import { AddStorageDto, ProviderClient, StorageResponseDto, UpdateStorageDto } from '@super-protocol/provider-client';
2
3
  import pino from 'pino';
3
- import { IConfigManager } from '../interfaces/config-manager.interface.js';
4
4
  export declare class StorageError extends Error {
5
5
  }
6
- export declare class StoragesEmptyError extends StorageError {
6
+ export declare class StoragesUndefinedError extends StorageError {
7
7
  }
8
8
  export declare class StorageCreateError extends StorageError {
9
9
  }
10
10
  export declare class StorageUpdateError extends StorageError {
11
11
  }
12
+ export declare class StorageGetError extends StorageError {
13
+ }
14
+ type IUploadParams = {
15
+ localPath: string;
16
+ maximumConcurrent?: number;
17
+ metadataPath?: string;
18
+ outputPath?: string;
19
+ remotePath?: string;
20
+ sync?: boolean;
21
+ withEncryption: boolean;
22
+ };
23
+ type IDownloadParams = {
24
+ downloadPath: string;
25
+ maximumConcurrent?: number;
26
+ resourcePath: string;
27
+ };
28
+ export type ResourceFile = Partial<Pick<RuntimeInputInfo, 'args' | 'hardwareContext' | 'hash' | 'signatureKeyHash'>> & {
29
+ encryption?: EncryptionWithIV;
30
+ resource: Resource;
31
+ };
32
+ type ProgressCb = (arg: {
33
+ current: number;
34
+ key: string;
35
+ total: number;
36
+ }) => void;
37
+ export declare const generateExternalId: () => string;
12
38
  export declare class StorageService {
13
- private readonly configManager;
14
39
  private readonly providerClient;
15
40
  private readonly logger;
16
- constructor(configManager: IConfigManager, providerClient: ProviderClient, logger: pino.BaseLogger);
41
+ constructor(providerClient: ProviderClient, logger: pino.BaseLogger);
17
42
  createStorage(storage: AddStorageDto): Promise<StorageResponseDto>;
43
+ download(params: IDownloadParams, progressCb: ProgressCb): Promise<void>;
44
+ getCentralizedStorage(): Promise<StorageResponseDto>;
45
+ getCurrentStorage(): Promise<StorageResponseDto>;
18
46
  hasStorage(): Promise<boolean>;
19
- initStorage(): Promise<{
47
+ initCentralizedStorage(): Promise<{
20
48
  bucket: string;
21
49
  createdAt: string;
22
50
  id: string;
@@ -28,7 +56,16 @@ export declare class StorageService {
28
56
  updatedAt: string;
29
57
  userId: string;
30
58
  }>;
31
- requestStorage(): Promise<StorageResponseDto[]>;
32
- saveStorage(selectedStorage: string): Promise<void>;
59
+ requestStorages(): Promise<StorageResponseDto[]>;
60
+ saveStorage(selectedStorage: string): Promise<{
61
+ activeStorageId: string;
62
+ createdAt: string;
63
+ decentralizedStorageId?: string;
64
+ id: string;
65
+ updatedAt: string;
66
+ userId: string;
67
+ }>;
33
68
  updateStorage(id: string, storage: UpdateStorageDto): Promise<StorageResponseDto>;
69
+ upload(params: IUploadParams, progressCb: ProgressCb): Promise<void>;
34
70
  }
71
+ export {};