LSPlugin.caller.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. import Debug from 'debug'
  2. import { Postmate, Model, ParentAPI, ChildAPI } from './postmate'
  3. import EventEmitter from 'eventemitter3'
  4. import { PluginLocal } from './LSPlugin.core'
  5. import { deferred, IS_DEV } from './helpers'
  6. import { LSPluginShadowFrame } from './LSPlugin.shadow'
  7. const debug = Debug('LSPlugin:caller')
  8. type DeferredActor = ReturnType<typeof deferred>
  9. export const FLAG_AWAIT = '#await#response#'
  10. export const LSPMSG = '#lspmsg#'
  11. export const LSPMSG_ERROR_TAG = '#lspmsg#error#'
  12. export const LSPMSG_SETTINGS = '#lspmsg#settings#'
  13. export const LSPMSG_BEFORE_UNLOAD = '#lspmsg#beforeunload#'
  14. export const LSPMSG_SYNC = '#lspmsg#reply#'
  15. export const LSPMSG_READY = '#lspmsg#ready#'
  16. export const LSPMSGFn = (id: string) => `${LSPMSG}${id}`
  17. export const AWAIT_LSPMSGFn = (id: string) => `${FLAG_AWAIT}${id}`
  18. /**
  19. * Call between core and user
  20. */
  21. class LSPluginCaller extends EventEmitter {
  22. private _connected: boolean = false
  23. private _parent?: ParentAPI
  24. private _child?: ChildAPI
  25. private _shadow?: LSPluginShadowFrame
  26. private _status?: 'pending' | 'timeout'
  27. private _userModel: any = {}
  28. private _call?: (
  29. type: string,
  30. payload: any,
  31. actor?: DeferredActor
  32. ) => Promise<any>
  33. private _callUserModel?: (type: string, payload: any) => Promise<any>
  34. private _debugTag = ''
  35. constructor(private _pluginLocal: PluginLocal | null) {
  36. super()
  37. if (_pluginLocal) {
  38. this._debugTag = _pluginLocal.debugTag
  39. }
  40. }
  41. async connectToChild() {
  42. if (this._connected) return
  43. const { shadow } = this._pluginLocal!
  44. if (shadow) {
  45. await this._setupShadowSandbox()
  46. } else {
  47. await this._setupIframeSandbox()
  48. }
  49. }
  50. // run in sandbox
  51. async connectToParent(userModel = {}) {
  52. if (this._connected) return
  53. const caller = this
  54. const isShadowMode = this._pluginLocal != null
  55. let syncGCTimer: any = 0
  56. let syncTag = 0
  57. const syncActors = new Map<number, DeferredActor>()
  58. const readyDeferred = deferred(1000 * 60)
  59. const model: any = this._extendUserModel({
  60. [LSPMSG_READY]: async (baseInfo) => {
  61. // dynamically setup common msg handler
  62. model[LSPMSGFn(baseInfo?.pid)] = ({
  63. type,
  64. payload,
  65. }: {
  66. type: string
  67. payload: any
  68. }) => {
  69. debug(`[host (_call) -> *user] ${this._debugTag}`, type, payload)
  70. // host._call without async
  71. caller.emit(type, payload)
  72. }
  73. await readyDeferred.resolve()
  74. },
  75. [LSPMSG_BEFORE_UNLOAD]: async (e) => {
  76. const actor = deferred(10 * 1000)
  77. caller.emit('beforeunload', Object.assign({ actor }, e))
  78. await actor.promise
  79. },
  80. [LSPMSG_SETTINGS]: async ({ type, payload }) => {
  81. caller.emit('settings:changed', payload)
  82. },
  83. [LSPMSG]: async ({ ns, type, payload }: any) => {
  84. debug(
  85. `[host (async) -> *user] ${this._debugTag} ns=${ns} type=${type}`,
  86. payload
  87. )
  88. if (ns && ns.startsWith('hook')) {
  89. caller.emit(`${ns}:${type}`, payload)
  90. return
  91. }
  92. caller.emit(type, payload)
  93. },
  94. [LSPMSG_SYNC]: ({ _sync, result }: any) => {
  95. debug(`[sync host -> *user] #${_sync}`, result)
  96. if (syncActors.has(_sync)) {
  97. const actor = syncActors.get(_sync)
  98. if (actor) {
  99. if (result?.hasOwnProperty(LSPMSG_ERROR_TAG)) {
  100. actor.reject(result[LSPMSG_ERROR_TAG])
  101. } else {
  102. actor.resolve(result)
  103. }
  104. syncActors.delete(_sync)
  105. }
  106. }
  107. },
  108. ...userModel,
  109. })
  110. if (isShadowMode) {
  111. await readyDeferred.promise
  112. return JSON.parse(JSON.stringify(this._pluginLocal?.toJSON()))
  113. }
  114. const pm = new Model(model)
  115. const handshake = pm.sendHandshakeReply()
  116. this._status = 'pending'
  117. await handshake
  118. .then((refParent: ChildAPI) => {
  119. this._child = refParent
  120. this._connected = true
  121. this._call = async (type, payload = {}, actor) => {
  122. if (actor) {
  123. const tag = ++syncTag
  124. syncActors.set(tag, actor)
  125. payload._sync = tag
  126. actor.setTag(`async call #${tag}`)
  127. debug(`async call #${tag}`)
  128. }
  129. refParent.emit(LSPMSGFn(model.baseInfo.id), { type, payload })
  130. return actor?.promise as Promise<any>
  131. }
  132. this._callUserModel = async (type, payload) => {
  133. try {
  134. model[type](payload)
  135. } catch (e) {
  136. debug(`[model method] #${type} not existed`)
  137. }
  138. }
  139. // actors GC
  140. syncGCTimer = setInterval(() => {
  141. if (syncActors.size > 100) {
  142. for (const [k, v] of syncActors) {
  143. if (v.settled) {
  144. syncActors.delete(k)
  145. }
  146. }
  147. }
  148. }, 1000 * 60 * 30)
  149. })
  150. .finally(() => {
  151. this._status = undefined
  152. })
  153. await readyDeferred.promise
  154. return model.baseInfo
  155. }
  156. async call(type: any, payload: any = {}) {
  157. return this._call?.call(this, type, payload)
  158. }
  159. // only for callable apis for sdk user
  160. async callAsync(type: any, payload: any = {}) {
  161. const actor = deferred(1000 * 10)
  162. return this._call?.call(this, type, payload, actor)
  163. }
  164. async callUserModel(type: string, payload: any = {}) {
  165. return this._callUserModel?.call(this, type, payload)
  166. }
  167. // run in host
  168. async _setupIframeSandbox() {
  169. const pl = this._pluginLocal!
  170. const id = pl.id
  171. const domId = `${id}_lsp_main`
  172. const url = new URL(pl.options.entry!)
  173. url.searchParams.set(
  174. `__v__`,
  175. IS_DEV ? Date.now().toString() : pl.options.version
  176. )
  177. // clear zombie sandbox
  178. const zb = document.querySelector(`#${domId}`)
  179. if (zb) zb.parentElement.removeChild(zb)
  180. const cnt = document.createElement('div')
  181. cnt.classList.add('lsp-iframe-sandbox-container')
  182. cnt.id = domId
  183. cnt.dataset.pid = id
  184. // TODO: apply any container layout data
  185. try {
  186. const mainLayoutInfo = (await this._pluginLocal._loadLayoutsData())?.$$0
  187. if (mainLayoutInfo) {
  188. cnt.dataset.inited_layout = 'true'
  189. const { width, height, left, top } = mainLayoutInfo
  190. Object.assign(cnt.style, {
  191. width: width + 'px',
  192. height: height + 'px',
  193. left: left + 'px',
  194. top: top + 'px',
  195. })
  196. }
  197. } catch (e) {
  198. console.error('[Restore Layout Error]', e)
  199. }
  200. document.body.appendChild(cnt)
  201. const pt = new Postmate({
  202. id: id + '_iframe',
  203. container: cnt,
  204. url: url.href,
  205. classListArray: ['lsp-iframe-sandbox'],
  206. model: { baseInfo: JSON.parse(JSON.stringify(pl.toJSON())) },
  207. })
  208. let handshake = pt.sendHandshake()
  209. this._status = 'pending'
  210. // timeout for handshake
  211. let timer
  212. return new Promise((resolve, reject) => {
  213. timer = setTimeout(() => {
  214. reject(new Error(`handshake Timeout`))
  215. pt.destroy()
  216. }, 4 * 1000) // 4 secs
  217. handshake
  218. .then((refChild: ParentAPI) => {
  219. this._parent = refChild
  220. this._connected = true
  221. this.emit('connected')
  222. refChild.on(LSPMSGFn(pl.id), ({ type, payload }: any) => {
  223. debug(`[user -> *host] `, type, payload)
  224. this._pluginLocal?.emit(type, payload || {})
  225. })
  226. this._call = async (...args: any) => {
  227. // parent all will get message before handshake
  228. await refChild.call(LSPMSGFn(pl.id), {
  229. type: args[0],
  230. payload: Object.assign(args[1] || {}, {
  231. $$pid: pl.id,
  232. }),
  233. })
  234. }
  235. this._callUserModel = async (type, payload: any) => {
  236. if (type.startsWith(FLAG_AWAIT)) {
  237. // TODO: attach payload with method call
  238. return await refChild.get(type.replace(FLAG_AWAIT, ''))
  239. } else {
  240. refChild.call(type, payload)
  241. }
  242. }
  243. resolve(null)
  244. })
  245. .catch((e) => {
  246. reject(e)
  247. })
  248. .finally(() => {
  249. clearTimeout(timer)
  250. })
  251. })
  252. .catch((e) => {
  253. debug('[iframe sandbox] error', e)
  254. throw e
  255. })
  256. .finally(() => {
  257. this._status = undefined
  258. })
  259. }
  260. async _setupShadowSandbox() {
  261. const pl = this._pluginLocal!
  262. const shadow = (this._shadow = new LSPluginShadowFrame(pl))
  263. try {
  264. this._status = 'pending'
  265. await shadow.load()
  266. this._connected = true
  267. this.emit('connected')
  268. this._call = async (type, payload = {}, actor) => {
  269. actor && (payload.actor = actor)
  270. // @ts-ignore Call in same thread
  271. this._pluginLocal?.emit(
  272. type,
  273. Object.assign(payload, {
  274. $$pid: pl.id,
  275. })
  276. )
  277. return actor?.promise
  278. }
  279. this._callUserModel = async (...args: any) => {
  280. let type = args[0] as string
  281. if (type?.startsWith(FLAG_AWAIT)) {
  282. type = type.replace(FLAG_AWAIT, '')
  283. }
  284. const payload = args[1] || {}
  285. const fn = this._userModel[type]
  286. if (typeof fn === 'function') {
  287. await fn.call(null, payload)
  288. }
  289. }
  290. } catch (e) {
  291. debug('[shadow sandbox] error', e)
  292. throw e
  293. } finally {
  294. this._status = undefined
  295. }
  296. }
  297. _extendUserModel(model: any) {
  298. return Object.assign(this._userModel, model)
  299. }
  300. _getSandboxIframeContainer() {
  301. return this._parent?.frame.parentNode as HTMLDivElement
  302. }
  303. _getSandboxShadowContainer() {
  304. return this._shadow?.frame.parentNode as HTMLDivElement
  305. }
  306. _getSandboxIframeRoot() {
  307. return this._parent?.frame
  308. }
  309. _getSandboxShadowRoot() {
  310. return this._shadow?.frame
  311. }
  312. set debugTag(value: string) {
  313. this._debugTag = value
  314. }
  315. async destroy() {
  316. let root: HTMLElement = null
  317. if (this._parent) {
  318. root = this._getSandboxIframeContainer()
  319. await this._parent.destroy()
  320. }
  321. if (this._shadow) {
  322. root = this._getSandboxShadowContainer()
  323. this._shadow.destroy()
  324. }
  325. root?.parentNode.removeChild(root)
  326. }
  327. }
  328. export { LSPluginCaller }