@blocklet/sdk 1.8.68 → 1.8.69-beta-e0666d0d

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,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
4
  };
@@ -25,9 +16,9 @@ const sign = (data) => {
25
16
  const signData = typeof data === 'undefined' ? {} : data;
26
17
  return { 'x-component-sig': wallet.sign((0, json_stable_stringify_1.default)(signData)) };
27
18
  };
28
- const doCall = ({ url, data }) => __awaiter(void 0, void 0, void 0, function* () {
19
+ const doCall = async ({ url, data }) => {
29
20
  try {
30
- const resp = yield axios_1.default.post(url, data, { headers: sign(data), timeout: 60000 });
21
+ const resp = await axios_1.default.post(url, data, { headers: sign(data), timeout: 60000 });
31
22
  config_1.logger.info(`call ${url} api success`);
32
23
  return resp;
33
24
  }
@@ -40,7 +31,7 @@ const doCall = ({ url, data }) => __awaiter(void 0, void 0, void 0, function* ()
40
31
  });
41
32
  throw new Error(`call ${url} api failed`);
42
33
  }
43
- });
34
+ };
44
35
  const parsePorts = () => JSON.parse(process.env.BLOCKLET_WEB_PORTS);
45
36
  const getWebEndpoint = (name) => {
46
37
  const ports = parsePorts();
@@ -68,11 +59,11 @@ const parseMountPoints = () => {
68
59
  });
69
60
  return mountPoints;
70
61
  };
71
- const call = ({ name, path: _path, data }) => __awaiter(void 0, void 0, void 0, function* () {
62
+ const call = async ({ name, path: _path, data }) => {
72
63
  const baseURL = name ? getChildWebEndpoint(name) : getParentWebEndpoint();
73
64
  const url = (0, url_join_1.default)(baseURL, _path);
74
65
  return doCall({ url, data });
75
- });
66
+ };
76
67
  exports.call = call;
77
68
  const getComponentMountPoint = (keyword) => {
78
69
  const mountPoints = parseMountPoints();
@@ -5,11 +5,14 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  const authenticator_1 = require("@did-connect/authenticator");
6
6
  const wallet_1 = __importDefault(require("../wallet"));
7
7
  const check_blocklet_env_1 = __importDefault(require("../util/check-blocklet-env"));
8
- const shared_1 = __importDefault(require("./shared"));
8
+ const shared_1 = require("./shared");
9
9
  class BlockletAuthenticator extends authenticator_1.Authenticator {
10
10
  constructor(options = {}) {
11
11
  (0, check_blocklet_env_1.default)();
12
- super(Object.assign({ wallet: (0, wallet_1.default)() }, (0, shared_1.default)(options)));
12
+ super({
13
+ wallet: (0, wallet_1.default)(),
14
+ ...(0, shared_1.getAuthenticatorProps)(options),
15
+ });
13
16
  }
14
17
  }
15
18
  module.exports = BlockletAuthenticator;
@@ -22,15 +22,6 @@ var __importStar = (this && this.__importStar) || function (mod) {
22
22
  __setModuleDefault(result, mod);
23
23
  return result;
24
24
  };
25
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
- return new (P || (P = Promise))(function (resolve, reject) {
28
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
- step((generator = generator.apply(thisArg, _arguments || [])).next());
32
- });
33
- };
34
25
  var __importDefault = (this && this.__importDefault) || function (mod) {
35
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
36
27
  };
@@ -60,8 +51,8 @@ const createConnectHandlers = ({ authenticator, storage, logger = consoleLogger,
60
51
  socketPathname,
61
52
  });
62
53
  const originCreateHandler = handlers.handleSessionCreate;
63
- handlers.handleSessionCreate = (context) => __awaiter(void 0, void 0, void 0, function* () {
64
- const session = yield originCreateHandler(context);
54
+ handlers.handleSessionCreate = async (context) => {
55
+ const session = await originCreateHandler(context);
65
56
  const connectedDid = getConnectedDid(session);
66
57
  // send notification to wallet to trigger wallet to auto connect
67
58
  if (connectedDid) {
@@ -88,12 +79,12 @@ const createConnectHandlers = ({ authenticator, storage, logger = consoleLogger,
88
79
  }
89
80
  // sendNotificationFn maybe custom function so we need params
90
81
  const sendFn = sendNotificationFn || notification_1.sendToUser.bind(notification_1.default);
91
- sendFn(connectedDid, message, Object.assign(Object.assign({}, context), { session })).catch((err) => {
82
+ sendFn(connectedDid, message, { ...context, session }).catch((err) => {
92
83
  console.error(err);
93
84
  });
94
85
  }
95
86
  return session;
96
- });
87
+ };
97
88
  return handlers;
98
89
  };
99
90
  module.exports = createConnectHandlers;
@@ -1,4 +1,8 @@
1
- declare const connectShared: (options?: {}) => {
1
+ import { WalletObject } from '@ocap/wallet';
2
+ declare const getDelegator: () => WalletObject<string>;
3
+ declare const getDelegatee: () => WalletObject<string>;
4
+ declare const getDelegation: (delegator: WalletObject, delegatee: WalletObject) => string;
5
+ declare const getAuthenticatorProps: (options?: {}) => {
2
6
  appInfo: (...args: any[]) => Promise<{
3
7
  name: string | undefined;
4
8
  description: string | undefined;
@@ -8,6 +12,8 @@ declare const connectShared: (options?: {}) => {
8
12
  subscriptionEndpoint: string;
9
13
  nodeDid: string | undefined;
10
14
  }>;
15
+ delegator: () => WalletObject<string>;
16
+ delegation: () => string;
11
17
  chainInfo: () => Record<string, string>;
12
18
  };
13
- export = connectShared;
19
+ export { getDelegation, getDelegator, getDelegatee, getAuthenticatorProps };
@@ -1,25 +1,81 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
4
  };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getAuthenticatorProps = exports.getDelegatee = exports.getDelegator = exports.getDelegation = void 0;
14
7
  const url_join_1 = __importDefault(require("url-join"));
8
+ const wallet_1 = __importDefault(require("@blocklet/meta/lib/wallet"));
9
+ const jwt_1 = require("@arcblock/jwt");
15
10
  const util_1 = require("@blocklet/meta/lib/util");
16
11
  const constants_1 = require("../util/constants");
17
12
  // wraps value in closure or returns closure
18
13
  const closure = (value) => (typeof value === 'function' ? value : () => value);
19
- const connectShared = (options = {}) => (Object.assign(Object.assign({ chainInfo: () => (0, util_1.getChainInfo)(process.env) }, options), { appInfo: (...args) => __awaiter(void 0, void 0, void 0, function* () {
20
- const info = yield closure(options.appInfo)(...args);
14
+ const getDelegator = () => {
15
+ const { BLOCKLET_APP_SK, BLOCKLET_APP_PSK, BLOCKLET_WALLET_TYPE } = process.env;
16
+ if (BLOCKLET_APP_SK && BLOCKLET_APP_PSK && BLOCKLET_APP_SK !== BLOCKLET_APP_PSK) {
17
+ return (0, wallet_1.default)(BLOCKLET_APP_PSK, undefined, BLOCKLET_WALLET_TYPE);
18
+ }
19
+ return null;
20
+ };
21
+ exports.getDelegator = getDelegator;
22
+ const getDelegatee = () => {
23
+ const { BLOCKLET_APP_SK, BLOCKLET_WALLET_TYPE } = process.env;
24
+ return (0, wallet_1.default)(BLOCKLET_APP_SK, undefined, BLOCKLET_WALLET_TYPE);
25
+ };
26
+ exports.getDelegatee = getDelegatee;
27
+ const getDelegation = (delegator, delegatee) => {
28
+ return (0, jwt_1.signV2)(delegator.address, delegator.secretKey, {
29
+ agentDid: `did:abt:${delegatee.address}`,
30
+ permissions: [
31
+ {
32
+ role: 'DIDConnectAgent',
33
+ claims: [
34
+ 'authPrincipal',
35
+ 'profile',
36
+ 'signature',
37
+ 'prepareTx',
38
+ 'agreement',
39
+ 'verifiableCredential',
40
+ 'asset',
41
+ 'keyPair',
42
+ 'encryptionKey',
43
+ ],
44
+ },
45
+ ],
46
+ exp: Math.floor(new Date().getTime() / 1000) + 60 * 60, // valid for 1 hour
47
+ });
48
+ };
49
+ exports.getDelegation = getDelegation;
50
+ const getAuthenticatorProps = (options = {}) => ({
51
+ chainInfo: () => (0, util_1.getChainInfo)(process.env),
52
+ ...options,
53
+ appInfo: async (...args) => {
54
+ const info = await closure(options.appInfo)(...args);
21
55
  const { request, baseUrl } = args[0];
22
56
  const groupPathPrefix = request.headers['x-group-path-prefix'] || '/';
23
- return Object.assign(Object.assign({ name: process.env.BLOCKLET_APP_NAME, description: process.env.BLOCKLET_APP_DESCRIPTION }, (info || {})), { link: (0, util_1.getConnectAppUrl)(args[0]), icon: (0, url_join_1.default)(baseUrl, constants_1.SERVICE_PREFIX, `/blocklet/logo?v=${process.env.BLOCKLET_APP_VERSION || ''}`), updateSubEndpoint: true, subscriptionEndpoint: (0, url_join_1.default)(groupPathPrefix, constants_1.SERVICE_PREFIX, 'websocket'), nodeDid: process.env.ABT_NODE_DID });
24
- }) }));
25
- module.exports = connectShared;
57
+ return {
58
+ name: process.env.BLOCKLET_APP_NAME,
59
+ description: process.env.BLOCKLET_APP_DESCRIPTION,
60
+ ...(info || {}),
61
+ link: (0, util_1.getConnectAppUrl)(args[0]),
62
+ icon: (0, url_join_1.default)(baseUrl, constants_1.SERVICE_PREFIX, `/blocklet/logo?v=${process.env.BLOCKLET_APP_VERSION || ''}`),
63
+ updateSubEndpoint: true,
64
+ subscriptionEndpoint: (0, url_join_1.default)(groupPathPrefix, constants_1.SERVICE_PREFIX, 'websocket'),
65
+ nodeDid: process.env.ABT_NODE_DID,
66
+ };
67
+ },
68
+ delegator: () => {
69
+ const delegator = getDelegator();
70
+ return delegator;
71
+ },
72
+ delegation: () => {
73
+ const delegator = getDelegator();
74
+ if (delegator) {
75
+ const delegatee = getDelegatee();
76
+ return getDelegation(delegator, delegatee);
77
+ }
78
+ return null;
79
+ },
80
+ });
81
+ exports.getAuthenticatorProps = getAuthenticatorProps;
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
4
  };
@@ -28,27 +19,29 @@ class DataBase extends core_1.DataStore {
28
19
  const DB_DIR = path_1.default.join(process.env.BLOCKLET_DATA_DIR, 'db');
29
20
  fs_extra_1.default.ensureDirSync(DB_DIR);
30
21
  const filename = options.filename || path_1.default.join(DB_DIR, `${name}.db`);
31
- super(Object.assign({ filename, autoload: true, timestampData: true, onload: (err) => {
22
+ super({
23
+ filename,
24
+ autoload: true,
25
+ timestampData: true,
26
+ onload: (err) => {
32
27
  if (err) {
33
28
  console.error(`failed to load disk database ${filename}`, err);
34
29
  }
35
- } }, options));
36
- }
37
- exists(...args) {
38
- return __awaiter(this, void 0, void 0, function* () {
39
- const doc = yield this.findOne(...args);
40
- return !!doc;
30
+ },
31
+ ...options,
41
32
  });
42
33
  }
43
- paginate({ condition = {}, sort = {}, page = 1, size = 100, projection = {} }) {
44
- return __awaiter(this, void 0, void 0, function* () {
45
- return this.cursor(condition)
46
- .sort(sort)
47
- .skip(Math.max(page * size - size, 0))
48
- .limit(Math.max(size, 1))
49
- .projection(projection)
50
- .exec();
51
- });
34
+ async exists(...args) {
35
+ const doc = await this.findOne(...args);
36
+ return !!doc;
37
+ }
38
+ async paginate({ condition = {}, sort = {}, page = 1, size = 100, projection = {} }) {
39
+ return this.cursor(condition)
40
+ .sort(sort)
41
+ .skip(Math.max(page * size - size, 0))
42
+ .limit(Math.max(size, 1))
43
+ .projection(projection)
44
+ .exec();
52
45
  }
53
46
  }
54
47
  module.exports = DataBase;
@@ -0,0 +1,3 @@
1
+ import type { Request, Response } from 'express';
2
+ declare function expressEmbed(req: Request, res: Response): Promise<void>;
3
+ export default expressEmbed;
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const get_embed_1 = __importDefault(require("../get-embed"));
7
+ async function expressEmbed(req, res) {
8
+ const { query = {} } = req;
9
+ const { url = '' } = query;
10
+ const data = await (0, get_embed_1.default)(url);
11
+ res.json(data);
12
+ }
13
+ exports.default = expressEmbed;
@@ -0,0 +1,6 @@
1
+ export default function generateBlockletEmbed(): {
2
+ name: string;
3
+ url: string;
4
+ origin: string;
5
+ embed: any[];
6
+ };
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ function safeJsonParse(input, defaultValue) {
4
+ try {
5
+ return JSON.parse(input);
6
+ }
7
+ catch {
8
+ return defaultValue;
9
+ }
10
+ }
11
+ function generateBlockletEmbed() {
12
+ const { BLOCKLET_APP_NAME, BLOCKLET_APP_URL, BLOCKLET_REAL_NAME } = process.env;
13
+ const BLOCKLET_MOUNT_POINTS = safeJsonParse(process.env.BLOCKLET_MOUNT_POINTS, []);
14
+ let url = '/';
15
+ let name = BLOCKLET_APP_NAME;
16
+ const blockletNames = BLOCKLET_REAL_NAME.split('/');
17
+ const componentBlocklet = BLOCKLET_MOUNT_POINTS.find((blockletItem) => blockletItem.name === blockletNames[blockletNames.length - 1]);
18
+ if (componentBlocklet) {
19
+ // 先假设只有一层 component blocklet
20
+ url = componentBlocklet.mountPoint;
21
+ name = componentBlocklet.title;
22
+ }
23
+ return {
24
+ name,
25
+ url,
26
+ origin: BLOCKLET_APP_URL,
27
+ embed: [],
28
+ };
29
+ }
30
+ exports.default = generateBlockletEmbed;
@@ -0,0 +1 @@
1
+ export default function getEmbedUrlFromUrl(url: string): Promise<string>;
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const slim_1 = require("cheerio/lib/slim");
7
+ const ufo_1 = require("ufo");
8
+ const axios_1 = __importDefault(require("axios"));
9
+ /**
10
+ * 判断 htmlContent 是否为开发环境
11
+ * @param {string} htmlContent
12
+ * @returns boolean
13
+ */
14
+ function checkViteDev(htmlContent) {
15
+ const $ = (0, slim_1.load)(htmlContent);
16
+ const scirptList = $('script[type="module"]');
17
+ return !![...scirptList].find((scriptItem) => {
18
+ if (scriptItem.firstChild?.type === 'text') {
19
+ return scriptItem.firstChild?.data?.includes('window.__vite_plugin_react_preamble_installed__ = true');
20
+ }
21
+ return false;
22
+ });
23
+ }
24
+ async function getEmbedUrlFromUrl(url) {
25
+ try {
26
+ const { data: htmlContent } = await axios_1.default.get(url, {
27
+ headers: {
28
+ accept: 'text/html,application/xhtml+xml,application/xml',
29
+ },
30
+ });
31
+ let prefix = '/';
32
+ let metaUrl = url;
33
+ const $ = (0, slim_1.load)(htmlContent);
34
+ const link = $('link[rel="blocklet-open-embed"]');
35
+ const blockletScript = $('script[src="__blocklet__.js"]');
36
+ if (link && link.length > 0) {
37
+ metaUrl = link.attr('href') || url;
38
+ }
39
+ else {
40
+ return url;
41
+ }
42
+ const isViteDev = checkViteDev(htmlContent);
43
+ if (blockletScript && blockletScript.length > 0) {
44
+ const scriptUrl = new URL('__blocklet__.js?type=json', (0, ufo_1.withTrailingSlash)(url));
45
+ const { data: blockletMeta } = await axios_1.default.get(scriptUrl.href);
46
+ prefix = blockletMeta.prefix;
47
+ }
48
+ // 在 vite 开发模式下,embed-url 指向的地址会自动被增加一个前缀
49
+ return isViteDev ? (0, ufo_1.joinURL)(prefix, metaUrl.replace(prefix, '')) : (0, ufo_1.joinURL)(prefix, metaUrl);
50
+ }
51
+ catch {
52
+ return url;
53
+ }
54
+ }
55
+ exports.default = getEmbedUrlFromUrl;
@@ -0,0 +1 @@
1
+ export default function getBlockletEmbedFromUrl(url: string): Promise<object | null>;
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const path_1 = require("path");
7
+ const lodash_1 = require("lodash");
8
+ const axios_1 = __importDefault(require("axios"));
9
+ const get_embed_url_1 = __importDefault(require("./get-embed-url"));
10
+ async function getBlockletEmbedFromUrl(url) {
11
+ const metaUrl = await (0, get_embed_url_1.default)(url);
12
+ try {
13
+ if (metaUrl) {
14
+ let finalUrl = '';
15
+ if (metaUrl.startsWith('http://') || metaUrl.startsWith('https://')) {
16
+ finalUrl = metaUrl;
17
+ }
18
+ else {
19
+ finalUrl = `${new URL(url).origin}${(0, path_1.join)('/', metaUrl)}`;
20
+ }
21
+ const { data: metaData } = await axios_1.default.get(finalUrl);
22
+ if ((0, lodash_1.isObject)(metaData)) {
23
+ return metaData;
24
+ }
25
+ }
26
+ }
27
+ catch {
28
+ /* empty */
29
+ }
30
+ return null;
31
+ }
32
+ exports.default = getBlockletEmbedFromUrl;
@@ -0,0 +1,10 @@
1
+ import generateBlockletEmbed from './generate';
2
+ import expressEmbed from './adapters/express';
3
+ import getBlockletEmbedFromUrl from './get-embed';
4
+ declare const _default: {
5
+ expressEmbed: typeof expressEmbed;
6
+ generateBlockletEmbed: typeof generateBlockletEmbed;
7
+ getBlockletEmbedFromUrl: typeof getBlockletEmbedFromUrl;
8
+ };
9
+ export default _default;
10
+ export { expressEmbed, generateBlockletEmbed, getBlockletEmbedFromUrl };
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getBlockletEmbedFromUrl = exports.generateBlockletEmbed = exports.expressEmbed = void 0;
7
+ const generate_1 = __importDefault(require("./generate"));
8
+ exports.generateBlockletEmbed = generate_1.default;
9
+ const express_1 = __importDefault(require("./adapters/express"));
10
+ exports.expressEmbed = express_1.default;
11
+ const get_embed_1 = __importDefault(require("./get-embed"));
12
+ exports.getBlockletEmbedFromUrl = get_embed_1.default;
13
+ exports.default = { expressEmbed: express_1.default, generateBlockletEmbed: generate_1.default, getBlockletEmbedFromUrl: get_embed_1.default };
@@ -0,0 +1,26 @@
1
+ type InstanceType = 'client' | 'server';
2
+ type MessageType = string;
3
+ interface Callback {
4
+ (...args: any[]): void;
5
+ }
6
+ declare class Message {
7
+ id: string;
8
+ type: InstanceType;
9
+ private bc;
10
+ private eventMap;
11
+ init: (cb: Callback) => void;
12
+ onInit: (getData: () => any) => void;
13
+ close: () => void;
14
+ constructor(id: string, type?: InstanceType);
15
+ on(type: MessageType, cb: Callback): void;
16
+ off(type: MessageType, cb: Callback): void;
17
+ once(type: MessageType, cb: Callback): void;
18
+ send(type: MessageType, payload: any): void;
19
+ }
20
+ declare function useMessage(id?: string, type?: InstanceType): any;
21
+ declare const _default: {
22
+ useMessage: typeof useMessage;
23
+ Message: typeof Message;
24
+ };
25
+ export default _default;
26
+ export { useMessage, Message };
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Message = exports.useMessage = void 0;
4
+ const INIT = '__init';
5
+ const ON_INIT = '__on-init';
6
+ function checkKey(typeKey) {
7
+ return !typeKey.startsWith(INIT);
8
+ }
9
+ function ensureType(type) {
10
+ if (!checkKey(type)) {
11
+ throw new Error(`Type can't starts with ${INIT}`);
12
+ }
13
+ }
14
+ function notExist() {
15
+ console.error('function not exist');
16
+ }
17
+ class Message {
18
+ constructor(id, type = 'client') {
19
+ this.id = id;
20
+ this.type = type;
21
+ const bc = new BroadcastChannel(this.id);
22
+ this.bc = bc;
23
+ this.eventMap = new Map();
24
+ const onMessage = (event) => {
25
+ const { data } = event;
26
+ const { type: messageType, payload, id: dataId } = data;
27
+ if (dataId === this.id) {
28
+ const cbList = this.eventMap.get(messageType) || [];
29
+ cbList.forEach((cbItem) => {
30
+ cbItem(payload);
31
+ });
32
+ }
33
+ };
34
+ window.addEventListener('message', onMessage, false);
35
+ this.close = () => {
36
+ window.removeEventListener('message', onMessage, false);
37
+ // v1 message
38
+ this.bc.close();
39
+ };
40
+ // v1 message
41
+ bc.onmessage = ({ data }) => {
42
+ const { type: messageType, payload } = data;
43
+ const cbList = this.eventMap.get(messageType) || [];
44
+ cbList.forEach((cbItem) => {
45
+ cbItem(payload);
46
+ });
47
+ };
48
+ this.init = notExist;
49
+ this.onInit = notExist;
50
+ if (type === 'server') {
51
+ this.onInit = (getData = () => null) => {
52
+ this.eventMap.set(INIT, [
53
+ (listenKey) => {
54
+ const initData = getData();
55
+ this.send(listenKey, initData);
56
+ },
57
+ ]);
58
+ };
59
+ }
60
+ if (type === 'client') {
61
+ this.init = (cb) => {
62
+ const uniqueId = String(+new Date());
63
+ const listenKey = `${ON_INIT}_${uniqueId}`;
64
+ this.once(listenKey, cb);
65
+ this.send(INIT, listenKey);
66
+ };
67
+ }
68
+ }
69
+ on(type, cb) {
70
+ ensureType(type);
71
+ const cbList = this.eventMap.get(type) || [];
72
+ cbList.push(cb);
73
+ this.eventMap.set(type, cbList);
74
+ }
75
+ off(type, cb) {
76
+ ensureType(type);
77
+ const cbList = this.eventMap.get(type) || [];
78
+ if (cb) {
79
+ const index = cbList.indexOf(cb);
80
+ if (index !== -1) {
81
+ cbList.splice(index, 1);
82
+ }
83
+ }
84
+ else {
85
+ cbList.length = 0;
86
+ }
87
+ this.eventMap.set(type, cbList);
88
+ }
89
+ once(type, cb) {
90
+ ensureType(type);
91
+ const callback = (...args) => {
92
+ cb(...args);
93
+ this.off(type, callback);
94
+ };
95
+ this.on(type, callback);
96
+ }
97
+ send(type, payload) {
98
+ const data = {
99
+ id: this.id,
100
+ type,
101
+ payload,
102
+ };
103
+ if (this.type === 'server') {
104
+ const iframeList = [...document.querySelectorAll(`iframe[data-id="${this.id}"]`)];
105
+ iframeList.forEach((iframeItem) => {
106
+ iframeItem.contentWindow.postMessage(data, '*');
107
+ });
108
+ }
109
+ else {
110
+ window.parent.postMessage(data, '*');
111
+ }
112
+ // v1 message
113
+ this.bc.postMessage(data);
114
+ }
115
+ }
116
+ exports.Message = Message;
117
+ const messageCache = new Map();
118
+ function useMessage(id, type = 'client') {
119
+ // eslint-disable-next-line @typescript-eslint/naming-convention
120
+ const _id = id || window.frameElement?.dataset.id || window.name;
121
+ if (messageCache.has(_id)) {
122
+ return messageCache.get(_id);
123
+ }
124
+ const isInIframe = window !== window.parent;
125
+ const message = (type === 'server' || isInIframe) && _id ? new Message(_id, type) : null;
126
+ const data = { message };
127
+ messageCache.set(_id, data);
128
+ return data;
129
+ }
130
+ exports.useMessage = useMessage;
131
+ exports.default = {
132
+ useMessage,
133
+ Message,
134
+ };
package/lib/env.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  declare const _default: Readonly<{
2
2
  appId: string;
3
+ appPid: string;
3
4
  appName: string;
4
5
  appDescription: string;
5
6
  appUrl: string;