@did-space/core 1.0.10 → 1.0.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.
@@ -1,5 +1,6 @@
1
- import type { Model } from 'sequelize';
1
+ import type { CreationOptional, Model } from 'sequelize';
2
2
  import type { LiteralUnion } from 'type-fest';
3
+ import type { Permissions } from '../configuration';
3
4
  export declare class SpaceRepositoryClass extends Model<SpaceRepositoryClass, SpaceRepositoryClass> {
4
5
  id: string;
5
6
  drive: string;
@@ -17,5 +18,10 @@ export declare class SpaceRepositoryClass extends Model<SpaceRepositoryClass, Sp
17
18
  updateAt: Date | string;
18
19
  expireAt: Date;
19
20
  ownerDid: string;
21
+ props: CreationOptional<{
22
+ usedUnit?: number;
23
+ usedUnitUpdatedAt?: string;
24
+ permissions?: Permissions;
25
+ }>;
20
26
  }
21
27
  export type SpaceRepository = typeof SpaceRepositoryClass;
@@ -2,6 +2,7 @@ import { SpaceConfig } from '../configuration';
2
2
  export interface PermissionOptions {
3
3
  fromAppDid: string;
4
4
  toAppDid: string;
5
+ isFromStorage?: false | true;
5
6
  }
6
7
  export interface SpaceConfigProtocol {
7
8
  createConfig(spaceConfig: SpaceConfig): Promise<void>;
@@ -111,11 +111,13 @@ class GlobalSpace {
111
111
  objectId: hash,
112
112
  };
113
113
  debug('delete.$where', JSON.stringify(where));
114
- const treeRefCount = yield this.treeRepository.count({
114
+ const treeRef = yield this.treeRepository.findOne({
115
115
  where,
116
+ raw: true,
117
+ attributes: ['id'],
116
118
  });
117
- debug('delete.$treeRefCount', treeRefCount);
118
- if (treeRefCount) {
119
+ debug('delete.$treeRef', treeRef);
120
+ if (treeRef) {
119
121
  yield this.objectCollectionRepository.destroy({ where: { id: hash } });
120
122
  return;
121
123
  }
@@ -29,6 +29,7 @@ export declare class ObjectSpace extends EventEmitter implements SpaceProtocol {
29
29
  readonly globalSpace: GlobalSpace;
30
30
  readonly driver: DriverProtocol;
31
31
  static readonly READONLY_OBJECT_KEYS: string[];
32
+ readonly configPath = "/config.yml";
32
33
  constructor(options: ObjectSpaceOptions);
33
34
  createSpace(spaceConfig: SpaceConfig): Promise<void>;
34
35
  isSpaceCreated(): Promise<boolean>;
@@ -90,18 +91,16 @@ export declare class ObjectSpace extends EventEmitter implements SpaceProtocol {
90
91
  getStatusAsOwner(key: string): Promise<KeyStatus>;
91
92
  createConfig(spaceConfig: SpaceConfig): Promise<void>;
92
93
  destroyConfig(): Promise<void>;
93
- set<T = any>(key: string, value: T): Promise<void>;
94
- get<T = any>(key: string, defaultValue?: T): Promise<T>;
94
+ set<T = any>(key: string, value: T, { isFromStorage }?: {
95
+ isFromStorage: false | true;
96
+ }): Promise<void>;
97
+ get<T = any>(key: string, defaultValue?: T, { isFromStorage }?: {
98
+ isFromStorage: false | true;
99
+ }): Promise<T>;
95
100
  private getPermission;
96
101
  /**
97
102
  *
98
103
  * @see https://blog.csdn.net/a1173537204/article/details/89765932
99
- * @private
100
- * @param {PermissionOptions} { fromAppDid, toAppDid }
101
- * @param {number} permission
102
- * @param {boolean} status
103
- * @return {*} {Promise<void>}
104
- * @memberof S3SpaceConfig
105
104
  */
106
105
  private setPermission;
107
106
  /**
@@ -32,6 +32,7 @@ const debug = (0, debug_1.default)('@did-space/core:ObjectSpace');
32
32
  class ObjectSpace extends events_1.default {
33
33
  constructor(options) {
34
34
  super();
35
+ this.configPath = '/config.yml';
35
36
  const { error } = schemas_1.ObjectSpaceOptionsSchema.validate(options, {
36
37
  allowUnknown: true,
37
38
  stripUnknown: true,
@@ -600,8 +601,10 @@ class ObjectSpace extends events_1.default {
600
601
  key,
601
602
  };
602
603
  debug('existsAsOwner.before', JSON.stringify({ where }));
603
- const exists = Boolean(yield this.options.treeRepository.count({
604
+ const exists = Boolean(yield this.options.treeRepository.findOne({
604
605
  where,
606
+ raw: true,
607
+ attributes: ['id'],
605
608
  }));
606
609
  debug('existsAsOwner.after', JSON.stringify({ exists }));
607
610
  return exists;
@@ -650,7 +653,7 @@ class ObjectSpace extends events_1.default {
650
653
  debug('createConfig.$data', data);
651
654
  debug('createConfig.$hash', hash);
652
655
  debug('createConfig.$size', size);
653
- yield this.writeAsOwner('/config.yml', data, {
656
+ yield this.writeAsOwner(this.configPath, data, {
654
657
  hash,
655
658
  size,
656
659
  useGlobal: true,
@@ -658,53 +661,72 @@ class ObjectSpace extends events_1.default {
658
661
  });
659
662
  }
660
663
  destroyConfig() {
661
- return this.deleteAsOwner('/config.yml');
664
+ return this.deleteAsOwner(this.configPath);
662
665
  }
663
- set(key, value) {
666
+ set(key, value, { isFromStorage = false } = { isFromStorage: false }) {
664
667
  return __awaiter(this, void 0, void 0, function* () {
665
- debug('set.before', JSON.stringify({ key, value }));
666
- const configData = yield this.readAsOwner('/config.yml');
667
- const data = js_yaml_1.default.load(yield (0, utils_1.streamToString)(configData));
668
- data[key] = value;
669
- yield this.createConfig(data);
668
+ debug('set.before', JSON.stringify({ key, value, isFromStorage }));
669
+ let data;
670
+ if (isFromStorage) {
671
+ const configData = yield this.readAsOwner(this.configPath);
672
+ data = js_yaml_1.default.load(yield (0, utils_1.streamToString)(configData));
673
+ data[key] = value;
674
+ yield this.writeAsOwner(this.configPath, js_yaml_1.default.dump(data));
675
+ }
676
+ else {
677
+ yield this.options.spaceRepository.update({
678
+ [key]: value,
679
+ }, {
680
+ where: {
681
+ did: this.options.spaceDid,
682
+ },
683
+ });
684
+ }
670
685
  });
671
686
  }
672
- get(key, defaultValue = {}) {
687
+ get(key, defaultValue = {}, { isFromStorage } = { isFromStorage: false }) {
673
688
  var _a;
674
689
  return __awaiter(this, void 0, void 0, function* () {
675
690
  debug('get.before', JSON.stringify({ key }));
676
- const configData = yield this.readAsOwner('/config.yml');
677
- const data = js_yaml_1.default.load(yield (0, utils_1.streamToString)(configData));
691
+ let data;
692
+ if (isFromStorage) {
693
+ const configData = yield this.readAsOwner(this.configPath);
694
+ data = js_yaml_1.default.load(yield (0, utils_1.streamToString)(configData));
695
+ }
696
+ else {
697
+ data = yield this.options.spaceRepository.findOne({
698
+ where: {
699
+ did: this.options.spaceDid,
700
+ },
701
+ });
702
+ }
678
703
  return (_a = data[key]) !== null && _a !== void 0 ? _a : defaultValue;
679
704
  });
680
705
  }
681
- getPermission({ fromAppDid, toAppDid }) {
706
+ getPermission({ fromAppDid, toAppDid, isFromStorage = false }) {
682
707
  var _a;
683
708
  return __awaiter(this, void 0, void 0, function* () {
684
- const permissions = yield this.get('permissions');
709
+ const permissions = yield this.get('permissions', {}, { isFromStorage });
685
710
  return ((_a = permissions === null || permissions === void 0 ? void 0 : permissions[fromAppDid]) === null || _a === void 0 ? void 0 : _a[toAppDid]) || 0;
686
711
  });
687
712
  }
688
713
  /**
689
714
  *
690
715
  * @see https://blog.csdn.net/a1173537204/article/details/89765932
691
- * @private
692
- * @param {PermissionOptions} { fromAppDid, toAppDid }
693
- * @param {number} permission
694
- * @param {boolean} status
695
- * @return {*} {Promise<void>}
696
- * @memberof S3SpaceConfig
697
716
  */
698
- setPermission({ fromAppDid, toAppDid }, permission, status) {
717
+ setPermission({ fromAppDid, toAppDid, isFromStorage = false }, permission, status) {
699
718
  var _a, _b;
700
719
  return __awaiter(this, void 0, void 0, function* () {
701
- const permissions = yield this.get('permissions', {});
720
+ const permissions = yield this.get('permissions', {}, { isFromStorage });
702
721
  // 我想知道原来的权限是啥样的?
703
722
  const oldPermission = ((_a = permissions === null || permissions === void 0 ? void 0 : permissions[fromAppDid]) === null || _a === void 0 ? void 0 : _a[toAppDid]) || 0;
704
723
  permissions[fromAppDid] = Object.assign((_b = permissions === null || permissions === void 0 ? void 0 : permissions[fromAppDid]) !== null && _b !== void 0 ? _b : {}, Object.assign(Object.assign({}, permissions === null || permissions === void 0 ? void 0 : permissions[fromAppDid]), {
705
724
  // eslint-disable-next-line no-bitwise
706
725
  [toAppDid]: status ? oldPermission | permission : oldPermission & ~permission }));
707
- yield this.set('permissions', permissions);
726
+ yield Promise.all([
727
+ this.set('permissions', permissions),
728
+ this.set('permissions', permissions, { isFromStorage: true }),
729
+ ]);
708
730
  });
709
731
  }
710
732
  /**
@@ -17,6 +17,7 @@ const path_1 = require("path");
17
17
  const ipfs_only_hash_1 = require("@arcblock/ipfs-only-hash");
18
18
  const multiformats_1 = require("multiformats");
19
19
  const hasha_1 = __importDefault(require("hasha"));
20
+ const destroy_1 = __importDefault(require("destroy"));
20
21
  const common_1 = require("./common");
21
22
  /**
22
23
  *
@@ -52,16 +53,25 @@ exports.getHashByAlgorithm = getHashByAlgorithm;
52
53
  // eslint-disable-next-line require-await
53
54
  function getHash(data = '', algorithm = 'ipfs') {
54
55
  return __awaiter(this, void 0, void 0, function* () {
55
- if (!['ipfs', 'sha256'].includes(algorithm)) {
56
- throw new Error(`#getHash() Invalid algorithm type: ${algorithm}`);
56
+ try {
57
+ if (!['ipfs', 'sha256'].includes(algorithm)) {
58
+ throw new Error(`#getHash() Invalid algorithm type: ${algorithm}`);
59
+ }
60
+ if (!(0, common_1.isValidData)(data)) {
61
+ throw new Error(`#getHash() Invalid data type: ${data}`);
62
+ }
63
+ if (algorithm === 'ipfs') {
64
+ return yield getHashByIpfs(data);
65
+ }
66
+ return yield getHashByAlgorithm(data, algorithm);
57
67
  }
58
- if (!(0, common_1.isValidData)(data)) {
59
- throw new Error(`#getHash() Invalid data type: ${data}`);
68
+ catch (error) {
69
+ console.error(error);
70
+ throw error;
60
71
  }
61
- if (algorithm === 'ipfs') {
62
- return getHashByIpfs(data);
72
+ finally {
73
+ (0, destroy_1.default)(data);
63
74
  }
64
- return getHashByAlgorithm(data, algorithm);
65
75
  });
66
76
  }
67
77
  exports.getHash = getHash;
@@ -1,5 +1,6 @@
1
- import type { Model } from 'sequelize';
1
+ import type { CreationOptional, Model } from 'sequelize';
2
2
  import type { LiteralUnion } from 'type-fest';
3
+ import type { Permissions } from '../configuration';
3
4
  export declare class SpaceRepositoryClass extends Model<SpaceRepositoryClass, SpaceRepositoryClass> {
4
5
  id: string;
5
6
  drive: string;
@@ -17,5 +18,10 @@ export declare class SpaceRepositoryClass extends Model<SpaceRepositoryClass, Sp
17
18
  updateAt: Date | string;
18
19
  expireAt: Date;
19
20
  ownerDid: string;
21
+ props: CreationOptional<{
22
+ usedUnit?: number;
23
+ usedUnitUpdatedAt?: string;
24
+ permissions?: Permissions;
25
+ }>;
20
26
  }
21
27
  export type SpaceRepository = typeof SpaceRepositoryClass;
@@ -2,6 +2,7 @@ import { SpaceConfig } from '../configuration';
2
2
  export interface PermissionOptions {
3
3
  fromAppDid: string;
4
4
  toAppDid: string;
5
+ isFromStorage?: false | true;
5
6
  }
6
7
  export interface SpaceConfigProtocol {
7
8
  createConfig(spaceConfig: SpaceConfig): Promise<void>;
@@ -100,11 +100,13 @@ export class GlobalSpace {
100
100
  objectId: hash,
101
101
  };
102
102
  debug('delete.$where', JSON.stringify(where));
103
- const treeRefCount = await this.treeRepository.count({
103
+ const treeRef = await this.treeRepository.findOne({
104
104
  where,
105
+ raw: true,
106
+ attributes: ['id'],
105
107
  });
106
- debug('delete.$treeRefCount', treeRefCount);
107
- if (treeRefCount) {
108
+ debug('delete.$treeRef', treeRef);
109
+ if (treeRef) {
108
110
  await this.objectCollectionRepository.destroy({ where: { id: hash } });
109
111
  return;
110
112
  }
@@ -29,6 +29,7 @@ export declare class ObjectSpace extends EventEmitter implements SpaceProtocol {
29
29
  readonly globalSpace: GlobalSpace;
30
30
  readonly driver: DriverProtocol;
31
31
  static readonly READONLY_OBJECT_KEYS: string[];
32
+ readonly configPath = "/config.yml";
32
33
  constructor(options: ObjectSpaceOptions);
33
34
  createSpace(spaceConfig: SpaceConfig): Promise<void>;
34
35
  isSpaceCreated(): Promise<boolean>;
@@ -90,18 +91,16 @@ export declare class ObjectSpace extends EventEmitter implements SpaceProtocol {
90
91
  getStatusAsOwner(key: string): Promise<KeyStatus>;
91
92
  createConfig(spaceConfig: SpaceConfig): Promise<void>;
92
93
  destroyConfig(): Promise<void>;
93
- set<T = any>(key: string, value: T): Promise<void>;
94
- get<T = any>(key: string, defaultValue?: T): Promise<T>;
94
+ set<T = any>(key: string, value: T, { isFromStorage }?: {
95
+ isFromStorage: false | true;
96
+ }): Promise<void>;
97
+ get<T = any>(key: string, defaultValue?: T, { isFromStorage }?: {
98
+ isFromStorage: false | true;
99
+ }): Promise<T>;
95
100
  private getPermission;
96
101
  /**
97
102
  *
98
103
  * @see https://blog.csdn.net/a1173537204/article/details/89765932
99
- * @private
100
- * @param {PermissionOptions} { fromAppDid, toAppDid }
101
- * @param {number} permission
102
- * @param {boolean} status
103
- * @return {*} {Promise<void>}
104
- * @memberof S3SpaceConfig
105
104
  */
106
105
  private setPermission;
107
106
  /**
@@ -19,6 +19,7 @@ export class ObjectSpace extends EventEmitter {
19
19
  globalSpace;
20
20
  driver;
21
21
  static READONLY_OBJECT_KEYS = ['/config.yml'];
22
+ configPath = '/config.yml';
22
23
  constructor(options) {
23
24
  super();
24
25
  const { error } = ObjectSpaceOptionsSchema.validate(options, {
@@ -555,8 +556,10 @@ export class ObjectSpace extends EventEmitter {
555
556
  key,
556
557
  };
557
558
  debug('existsAsOwner.before', JSON.stringify({ where }));
558
- const exists = Boolean(await this.options.treeRepository.count({
559
+ const exists = Boolean(await this.options.treeRepository.findOne({
559
560
  where,
561
+ raw: true,
562
+ attributes: ['id'],
560
563
  }));
561
564
  debug('existsAsOwner.after', JSON.stringify({ exists }));
562
565
  return exists;
@@ -601,44 +604,60 @@ export class ObjectSpace extends EventEmitter {
601
604
  debug('createConfig.$data', data);
602
605
  debug('createConfig.$hash', hash);
603
606
  debug('createConfig.$size', size);
604
- await this.writeAsOwner('/config.yml', data, {
607
+ await this.writeAsOwner(this.configPath, data, {
605
608
  hash,
606
609
  size,
607
610
  useGlobal: true,
608
611
  });
609
612
  }
610
613
  destroyConfig() {
611
- return this.deleteAsOwner('/config.yml');
612
- }
613
- async set(key, value) {
614
- debug('set.before', JSON.stringify({ key, value }));
615
- const configData = await this.readAsOwner('/config.yml');
616
- const data = jsYaml.load(await streamToString(configData));
617
- data[key] = value;
618
- await this.createConfig(data);
614
+ return this.deleteAsOwner(this.configPath);
615
+ }
616
+ async set(key, value, { isFromStorage = false } = { isFromStorage: false }) {
617
+ debug('set.before', JSON.stringify({ key, value, isFromStorage }));
618
+ let data;
619
+ if (isFromStorage) {
620
+ const configData = await this.readAsOwner(this.configPath);
621
+ data = jsYaml.load(await streamToString(configData));
622
+ data[key] = value;
623
+ await this.writeAsOwner(this.configPath, jsYaml.dump(data));
624
+ }
625
+ else {
626
+ await this.options.spaceRepository.update({
627
+ [key]: value,
628
+ }, {
629
+ where: {
630
+ did: this.options.spaceDid,
631
+ },
632
+ });
633
+ }
619
634
  }
620
- async get(key, defaultValue = {}) {
635
+ async get(key, defaultValue = {}, { isFromStorage } = { isFromStorage: false }) {
621
636
  debug('get.before', JSON.stringify({ key }));
622
- const configData = await this.readAsOwner('/config.yml');
623
- const data = jsYaml.load(await streamToString(configData));
637
+ let data;
638
+ if (isFromStorage) {
639
+ const configData = await this.readAsOwner(this.configPath);
640
+ data = jsYaml.load(await streamToString(configData));
641
+ }
642
+ else {
643
+ data = await this.options.spaceRepository.findOne({
644
+ where: {
645
+ did: this.options.spaceDid,
646
+ },
647
+ });
648
+ }
624
649
  return data[key] ?? defaultValue;
625
650
  }
626
- async getPermission({ fromAppDid, toAppDid }) {
627
- const permissions = await this.get('permissions');
651
+ async getPermission({ fromAppDid, toAppDid, isFromStorage = false }) {
652
+ const permissions = await this.get('permissions', {}, { isFromStorage });
628
653
  return permissions?.[fromAppDid]?.[toAppDid] || 0;
629
654
  }
630
655
  /**
631
656
  *
632
657
  * @see https://blog.csdn.net/a1173537204/article/details/89765932
633
- * @private
634
- * @param {PermissionOptions} { fromAppDid, toAppDid }
635
- * @param {number} permission
636
- * @param {boolean} status
637
- * @return {*} {Promise<void>}
638
- * @memberof S3SpaceConfig
639
658
  */
640
- async setPermission({ fromAppDid, toAppDid }, permission, status) {
641
- const permissions = await this.get('permissions', {});
659
+ async setPermission({ fromAppDid, toAppDid, isFromStorage = false }, permission, status) {
660
+ const permissions = await this.get('permissions', {}, { isFromStorage });
642
661
  // 我想知道原来的权限是啥样的?
643
662
  const oldPermission = permissions?.[fromAppDid]?.[toAppDid] || 0;
644
663
  permissions[fromAppDid] = Object.assign(permissions?.[fromAppDid] ?? {}, {
@@ -646,7 +665,10 @@ export class ObjectSpace extends EventEmitter {
646
665
  // eslint-disable-next-line no-bitwise
647
666
  [toAppDid]: status ? oldPermission | permission : oldPermission & ~permission,
648
667
  });
649
- await this.set('permissions', permissions);
668
+ await Promise.all([
669
+ this.set('permissions', permissions),
670
+ this.set('permissions', permissions, { isFromStorage: true }),
671
+ ]);
650
672
  }
651
673
  /**
652
674
  *
@@ -2,6 +2,7 @@ import { join } from 'path';
2
2
  import { onlyHash } from '@arcblock/ipfs-only-hash';
3
3
  import { CID } from 'multiformats';
4
4
  import hasha from 'hasha';
5
+ import destroy from 'destroy';
5
6
  import { isValidData } from './common';
6
7
  /**
7
8
  *
@@ -32,16 +33,25 @@ export function getHashByAlgorithm(data = '', algorithm = 'sha256') {
32
33
  */
33
34
  // eslint-disable-next-line require-await
34
35
  export async function getHash(data = '', algorithm = 'ipfs') {
35
- if (!['ipfs', 'sha256'].includes(algorithm)) {
36
- throw new Error(`#getHash() Invalid algorithm type: ${algorithm}`);
36
+ try {
37
+ if (!['ipfs', 'sha256'].includes(algorithm)) {
38
+ throw new Error(`#getHash() Invalid algorithm type: ${algorithm}`);
39
+ }
40
+ if (!isValidData(data)) {
41
+ throw new Error(`#getHash() Invalid data type: ${data}`);
42
+ }
43
+ if (algorithm === 'ipfs') {
44
+ return await getHashByIpfs(data);
45
+ }
46
+ return await getHashByAlgorithm(data, algorithm);
37
47
  }
38
- if (!isValidData(data)) {
39
- throw new Error(`#getHash() Invalid data type: ${data}`);
48
+ catch (error) {
49
+ console.error(error);
50
+ throw error;
40
51
  }
41
- if (algorithm === 'ipfs') {
42
- return getHashByIpfs(data);
52
+ finally {
53
+ destroy(data);
43
54
  }
44
- return getHashByAlgorithm(data, algorithm);
45
55
  }
46
56
  /**
47
57
  * @description
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@did-space/core",
3
- "version": "1.0.10",
3
+ "version": "1.0.11",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -115,11 +115,12 @@
115
115
  "watch": "npm run build -- -w"
116
116
  },
117
117
  "dependencies": {
118
- "@arcblock/did": "^1.19.6",
118
+ "@arcblock/did": "^1.19.9",
119
119
  "@arcblock/ipfs-only-hash": "^0.0.2",
120
- "@arcblock/validator": "^1.19.6",
120
+ "@arcblock/validator": "^1.19.9",
121
121
  "dayjs": "^1.11.13",
122
122
  "debug": "^4.4.0",
123
+ "destroy": "^1.2.0",
123
124
  "hasha": "^5.2.2",
124
125
  "joi": "^17.13.3",
125
126
  "js-yaml": "^4.1.0",
@@ -134,6 +135,7 @@
134
135
  },
135
136
  "devDependencies": {
136
137
  "@arcblock/eslint-config-ts": "^0.3.3",
138
+ "@types/destroy": "^1.0.3",
137
139
  "@types/jest": "^28.1.8",
138
140
  "@types/node": "18.19.31",
139
141
  "@typescript-eslint/eslint-plugin": "^7.18.0",
@@ -143,8 +145,8 @@
143
145
  "lint-staged": "^13.3.0",
144
146
  "ts-jest": "^28.0.8",
145
147
  "typescript": "^4.9.5",
146
- "vite": "^5.4.11",
147
- "vitest": "^3.0.2"
148
+ "vite": "^5.4.14",
149
+ "vitest": "^3.0.5"
148
150
  },
149
- "gitHead": "bf1e53904f28b786d728648fe0a7d828478551de"
151
+ "gitHead": "a6ef4e989848b33ea26c84fe0d93109587143d34"
150
152
  }