UNPKG

3.09 kBJavaScriptView Raw
1import { lazyMethods, logger, objectClear } from '@polkadot/util';
2const l = logger('api/augment');
3function logLength(type, values, and = []) {
4 return values.length
5 ? ` ${values.length} ${type}${and.length ? ' and' : ''}`
6 : '';
7}
8function logValues(type, values) {
9 return values.length
10 ? `\n\t${type.padStart(7)}: ${values.sort().join(', ')}`
11 : '';
12}
13function warn(prefix, type, [added, removed]) {
14 if (added.length || removed.length) {
15 l.warn(`api.${prefix}: Found${logLength('added', added, removed)}${logLength('removed', removed)} ${type}:${logValues('added', added)}${logValues('removed', removed)}`);
16 }
17}
18function findSectionExcludes(a, b) {
19 return a.filter((s) => !b.includes(s));
20}
21function findSectionIncludes(a, b) {
22 return a.filter((s) => b.includes(s));
23}
24function extractSections(src, dst) {
25 const srcSections = Object.keys(src);
26 const dstSections = Object.keys(dst);
27 return [
28 findSectionExcludes(srcSections, dstSections),
29 findSectionExcludes(dstSections, srcSections)
30 ];
31}
32function findMethodExcludes(src, dst) {
33 const srcSections = Object.keys(src);
34 const dstSections = findSectionIncludes(Object.keys(dst), srcSections);
35 const excludes = [];
36 for (let s = 0, scount = dstSections.length; s < scount; s++) {
37 const section = dstSections[s];
38 const srcMethods = Object.keys(src[section]);
39 const dstMethods = Object.keys(dst[section]);
40 for (let d = 0, mcount = dstMethods.length; d < mcount; d++) {
41 const method = dstMethods[d];
42 if (!srcMethods.includes(method)) {
43 excludes.push(`${section}.${method}`);
44 }
45 }
46 }
47 return excludes;
48}
49function extractMethods(src, dst) {
50 return [
51 findMethodExcludes(dst, src),
52 findMethodExcludes(src, dst)
53 ];
54}
55/**
56 * @description Takes a decorated api section (e.g. api.tx) and augment it with the details. It does not override what is
57 * already available, but rather just adds new missing items into the result object.
58 * @internal
59 */
60export function augmentObject(prefix, src, dst, fromEmpty = false) {
61 fromEmpty && objectClear(dst);
62 // NOTE: This part is slightly problematic since it will get the
63 // values for at least all the sections and the names of the methods
64 // (Since methods won't be decorated before lazy, this _may_ be ok)
65 if (prefix && Object.keys(dst).length) {
66 warn(prefix, 'modules', extractSections(src, dst));
67 warn(prefix, 'calls', extractMethods(src, dst));
68 }
69 const sections = Object.keys(src);
70 for (let i = 0, count = sections.length; i < count; i++) {
71 const section = sections[i];
72 const methods = src[section];
73 // We don't set here with a lazy interface, we decorate based
74 // on the top-level structure (this bypasses adding lazy onto lazy)
75 if (!dst[section]) {
76 dst[section] = {};
77 }
78 lazyMethods(dst[section], Object.keys(methods), (m) => methods[m]);
79 }
80 return dst;
81}