LSPlugin.core.ts 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304
  1. import EventEmitter from 'eventemitter3'
  2. import {
  3. deepMerge,
  4. setupInjectedStyle,
  5. genID,
  6. setupInjectedTheme,
  7. setupInjectedUI,
  8. deferred,
  9. invokeHostExportedApi,
  10. isObject, withFileProtocol,
  11. getSDKPathRoot,
  12. PROTOCOL_FILE, URL_LSP,
  13. safetyPathJoin,
  14. path, safetyPathNormalize
  15. } from './helpers'
  16. import * as pluginHelpers from './helpers'
  17. import Debug from 'debug'
  18. import {
  19. LSPluginCaller,
  20. LSPMSG_READY, LSPMSG_SYNC,
  21. LSPMSG, LSPMSG_SETTINGS,
  22. LSPMSG_ERROR_TAG, LSPMSG_BEFORE_UNLOAD, AWAIT_LSPMSGFn
  23. } from './LSPlugin.caller'
  24. import {
  25. ILSPluginThemeManager,
  26. LSPluginPkgConfig,
  27. StyleOptions,
  28. StyleString,
  29. ThemeOptions, UIContainerAttrs,
  30. UIOptions
  31. } from './LSPlugin'
  32. import { snakeCase } from 'snake-case'
  33. const debug = Debug('LSPlugin:core')
  34. const DIR_PLUGINS = 'plugins'
  35. declare global {
  36. interface Window {
  37. LSPluginCore: LSPluginCore
  38. }
  39. }
  40. type DeferredActor = ReturnType<typeof deferred>
  41. type LSPluginCoreOptions = {
  42. dotConfigRoot: string
  43. }
  44. /**
  45. * User settings
  46. */
  47. class PluginSettings extends EventEmitter<'change'> {
  48. private _settings: Record<string, any> = {
  49. disabled: false
  50. }
  51. constructor (private _userPluginSettings: any) {
  52. super()
  53. Object.assign(this._settings, _userPluginSettings)
  54. }
  55. get<T = any> (k: string): T {
  56. return this._settings[k]
  57. }
  58. set (k: string | Record<string, any>, v?: any) {
  59. const o = deepMerge({}, this._settings)
  60. if (typeof k === 'string') {
  61. if (this._settings[k] == v) return
  62. this._settings[k] = v
  63. } else if (isObject(k)) {
  64. deepMerge(this._settings, k)
  65. } else {
  66. return
  67. }
  68. this.emit('change',
  69. Object.assign({}, this._settings), o)
  70. }
  71. set settings (value: Record<string, any>) {
  72. this._settings = value
  73. }
  74. get settings (): Record<string, any> {
  75. return this._settings
  76. }
  77. toJSON () {
  78. return this._settings
  79. }
  80. }
  81. class PluginLogger extends EventEmitter<'change'> {
  82. private _logs: Array<[type: string, payload: any]> = []
  83. constructor (private _tag: string) {
  84. super()
  85. }
  86. write (type: string, payload: any[]) {
  87. let msg = payload.reduce((ac, it) => {
  88. if (it && it instanceof Error) {
  89. ac += `${it.message} ${it.stack}`
  90. } else {
  91. ac += it.toString()
  92. }
  93. return ac
  94. }, `[${this._tag}][${new Date().toLocaleTimeString()}] `)
  95. this._logs.push([type, msg])
  96. this.emit('change')
  97. }
  98. clear () {
  99. this._logs = []
  100. this.emit('change')
  101. }
  102. info (...args: any[]) {
  103. this.write('INFO', args)
  104. }
  105. error (...args: any[]) {
  106. this.write('ERROR', args)
  107. }
  108. warn (...args: any[]) {
  109. this.write('WARN', args)
  110. }
  111. toJSON () {
  112. return this._logs
  113. }
  114. }
  115. type UserPreferences = {
  116. theme: ThemeOptions
  117. externals: Array<string> // external plugin locations
  118. [key: string]: any
  119. }
  120. type PluginLocalOptions = {
  121. key?: string // Unique from Logseq Plugin Store
  122. entry: string // Plugin main file
  123. url: string // Plugin package absolute fs location
  124. name: string
  125. version: string
  126. mode: 'shadow' | 'iframe'
  127. settings?: PluginSettings
  128. logger?: PluginLogger
  129. effect?: boolean
  130. theme?: boolean
  131. [key: string]: any
  132. }
  133. type PluginLocalUrl = Pick<PluginLocalOptions, 'url'> & { [key: string]: any }
  134. type RegisterPluginOpts = PluginLocalOptions | PluginLocalUrl
  135. type PluginLocalIdentity = string
  136. enum PluginLocalLoadStatus {
  137. LOADING = 'loading',
  138. UNLOADING = 'unloading',
  139. LOADED = 'loaded',
  140. UNLOADED = 'unload',
  141. ERROR = 'error'
  142. }
  143. function initUserSettingsHandlers (pluginLocal: PluginLocal) {
  144. const _ = (label: string): any => `settings:${label}`
  145. pluginLocal.on(_('update'), (attrs) => {
  146. if (!attrs) return
  147. pluginLocal.settings?.set(attrs)
  148. })
  149. }
  150. function initMainUIHandlers (pluginLocal: PluginLocal) {
  151. const _ = (label: string): any => `main-ui:${label}`
  152. pluginLocal.on(_('visible'), ({ visible, toggle, cursor, autoFocus }) => {
  153. const el = pluginLocal.getMainUIContainer()
  154. el?.classList[toggle ? 'toggle' : (visible ? 'add' : 'remove')]('visible')
  155. // pluginLocal.caller!.callUserModel(LSPMSG, { type: _('visible'), payload: visible })
  156. // auto focus frame
  157. if (visible) {
  158. if (!pluginLocal.shadow && el && (autoFocus !== false)) {
  159. (el.querySelector('iframe') as HTMLIFrameElement)?.contentWindow?.focus()
  160. }
  161. }
  162. if (cursor) {
  163. invokeHostExportedApi('restore_editing_cursor')
  164. }
  165. })
  166. pluginLocal.on(_('attrs'), (attrs: Partial<UIContainerAttrs>) => {
  167. const el = pluginLocal.getMainUIContainer()
  168. Object.entries(attrs).forEach(([k, v]) => {
  169. el?.setAttribute(k, v)
  170. if (k === 'draggable' && v) {
  171. pluginLocal._dispose(
  172. pluginLocal._setupDraggableContainer(el, {
  173. title: pluginLocal.options.name,
  174. close: () => {
  175. pluginLocal.caller.call('sys:ui:visible', { toggle: true })
  176. }
  177. }))
  178. }
  179. if (k === 'resizable' && v) {
  180. pluginLocal._dispose(
  181. pluginLocal._setupResizableContainer(el))
  182. }
  183. })
  184. })
  185. pluginLocal.on(_('style'), (style: Record<string, any>) => {
  186. const el = pluginLocal.getMainUIContainer()
  187. const isInitedLayout = !!el.dataset.inited_layout
  188. Object.entries(style).forEach(([k, v]) => {
  189. if (isInitedLayout && [
  190. 'left', 'top', 'bottom', 'right', 'width', 'height'
  191. ].includes(k)) {
  192. return
  193. }
  194. el!.style[k] = v
  195. })
  196. })
  197. }
  198. function initProviderHandlers (pluginLocal: PluginLocal) {
  199. let _ = (label: string): any => `provider:${label}`
  200. let themed = false
  201. pluginLocal.on(_('theme'), (theme: ThemeOptions) => {
  202. pluginLocal.themeMgr.registerTheme(
  203. pluginLocal.id,
  204. theme
  205. )
  206. if (!themed) {
  207. pluginLocal._dispose(() => {
  208. pluginLocal.themeMgr.unregisterTheme(pluginLocal.id)
  209. })
  210. themed = true
  211. }
  212. })
  213. pluginLocal.on(_('style'), (style: StyleString | StyleOptions) => {
  214. let key: string | undefined
  215. if (typeof style !== 'string') {
  216. key = style.key
  217. style = style.style
  218. }
  219. if (!style || !style.trim()) return
  220. pluginLocal._dispose(
  221. setupInjectedStyle(style, {
  222. 'data-injected-style': key ? `${key}-${pluginLocal.id}` : '',
  223. 'data-ref': pluginLocal.id
  224. })
  225. )
  226. })
  227. pluginLocal.on(_('ui'), (ui: UIOptions) => {
  228. pluginLocal._onHostMounted(() => {
  229. pluginLocal._dispose(
  230. setupInjectedUI.call(pluginLocal,
  231. ui, Object.assign({
  232. 'data-ref': pluginLocal.id
  233. }, ui.attrs || {}),
  234. ({ el, float }) => {
  235. if (!float) return
  236. const identity = el.dataset.identity
  237. pluginLocal.layoutCore.move_container_to_top(identity)
  238. }))
  239. })
  240. })
  241. }
  242. function initApiProxyHandlers (pluginLocal: PluginLocal) {
  243. let _ = (label: string): any => `api:${label}`
  244. pluginLocal.on(_('call'), async (payload) => {
  245. let ret: any
  246. try {
  247. ret = await invokeHostExportedApi(payload.method, ...payload.args)
  248. } catch (e) {
  249. ret = {
  250. [LSPMSG_ERROR_TAG]: e,
  251. }
  252. }
  253. const { _sync } = payload
  254. if (pluginLocal.shadow) {
  255. if (payload.actor) {
  256. payload.actor.resolve(ret)
  257. }
  258. return
  259. }
  260. if (_sync != null) {
  261. const reply = (result: any) => {
  262. pluginLocal.caller?.callUserModel(LSPMSG_SYNC, {
  263. result, _sync
  264. })
  265. }
  266. Promise.resolve(ret).then(reply, reply)
  267. }
  268. })
  269. }
  270. function convertToLSPResource (fullUrl: string, dotPluginRoot: string) {
  271. if (
  272. dotPluginRoot &&
  273. fullUrl.startsWith(PROTOCOL_FILE + dotPluginRoot)
  274. ) {
  275. fullUrl = safetyPathJoin(
  276. URL_LSP, fullUrl.substr(PROTOCOL_FILE.length + dotPluginRoot.length))
  277. }
  278. return fullUrl
  279. }
  280. class IllegalPluginPackageError extends Error {
  281. constructor (message: string) {
  282. super(message)
  283. this.name = IllegalPluginPackageError.name
  284. }
  285. }
  286. class ExistedImportedPluginPackageError extends Error {
  287. constructor (message: string) {
  288. super(message)
  289. this.name = ExistedImportedPluginPackageError.name
  290. }
  291. }
  292. /**
  293. * Host plugin for local
  294. */
  295. class PluginLocal
  296. extends EventEmitter<'loaded' | 'unloaded' | 'beforeunload' | 'error'> {
  297. private _disposes: Array<() => Promise<any>> = []
  298. private _id: PluginLocalIdentity
  299. private _status: PluginLocalLoadStatus = PluginLocalLoadStatus.UNLOADED
  300. private _loadErr?: Error
  301. private _localRoot?: string
  302. private _dotSettingsFile?: string
  303. private _caller?: LSPluginCaller
  304. /**
  305. * @param _options
  306. * @param _themeMgr
  307. * @param _ctx
  308. */
  309. constructor (
  310. private _options: PluginLocalOptions,
  311. private _themeMgr: ILSPluginThemeManager,
  312. private _ctx: LSPluginCore
  313. ) {
  314. super()
  315. this._id = _options.key || genID()
  316. initUserSettingsHandlers(this)
  317. initMainUIHandlers(this)
  318. initProviderHandlers(this)
  319. initApiProxyHandlers(this)
  320. }
  321. async _setupUserSettings (
  322. reload?: boolean
  323. ) {
  324. const { _options } = this
  325. const logger = _options.logger = new PluginLogger('Loader')
  326. if (_options.settings && !reload) {
  327. return
  328. }
  329. try {
  330. const loadFreshSettings = () => invokeHostExportedApi('load_plugin_user_settings', this.id)
  331. const [userSettingsFilePath, userSettings] = await loadFreshSettings()
  332. this._dotSettingsFile = userSettingsFilePath
  333. let settings = _options.settings
  334. if (!settings) {
  335. settings = _options.settings = new PluginSettings(userSettings)
  336. }
  337. if (reload) {
  338. settings.settings = userSettings
  339. return
  340. }
  341. const handler = async (a, b) => {
  342. debug('Settings changed', this.debugTag, a)
  343. if (!a.disabled && b.disabled) {
  344. // Enable plugin
  345. const [, freshSettings] = await loadFreshSettings()
  346. freshSettings.disabled = false
  347. a = deepMerge(a, freshSettings)
  348. settings.settings = a
  349. await this.load()
  350. }
  351. if (a.disabled && !b.disabled) {
  352. // Disable plugin
  353. const [, freshSettings] = await loadFreshSettings()
  354. freshSettings.disabled = true
  355. a = deepMerge(a, freshSettings)
  356. await this.unload()
  357. }
  358. if (a) {
  359. invokeHostExportedApi(`save_plugin_user_settings`, this.id, a)
  360. }
  361. }
  362. // observe settings
  363. settings.on('change', handler)
  364. return () => {}
  365. } catch (e) {
  366. debug('[load plugin user settings Error]', e)
  367. logger?.error(e)
  368. }
  369. }
  370. getMainUIContainer (): HTMLElement | undefined {
  371. if (this.shadow) {
  372. return this.caller?._getSandboxShadowContainer()
  373. }
  374. return this.caller?._getSandboxIframeContainer()
  375. }
  376. _resolveResourceFullUrl (filePath: string, localRoot?: string) {
  377. if (!filePath?.trim()) return
  378. localRoot = localRoot || this._localRoot
  379. const reg = /^(http|file)/
  380. if (!reg.test(filePath)) {
  381. const url = path.join(localRoot, filePath)
  382. filePath = reg.test(url) ? url : (PROTOCOL_FILE + url)
  383. }
  384. return (!this.options.effect && this.isInstalledInDotRoot) ?
  385. convertToLSPResource(filePath, this.dotPluginsRoot) : filePath
  386. }
  387. async _preparePackageConfigs () {
  388. const { url } = this._options
  389. let pkg: any
  390. try {
  391. if (!url) {
  392. throw new Error('Can not resolve package config location')
  393. }
  394. debug('prepare package root', url)
  395. pkg = await invokeHostExportedApi('load_plugin_config', url)
  396. if (!pkg || (pkg = JSON.parse(pkg), !pkg)) {
  397. throw new Error(`Parse package config error #${url}/package.json`)
  398. }
  399. } catch (e) {
  400. throw new IllegalPluginPackageError(e.message)
  401. }
  402. const localRoot = this._localRoot = safetyPathNormalize(url)
  403. const logseq: Partial<LSPluginPkgConfig> = pkg.logseq || {}
  404. // Pick legal attrs
  405. ;['name', 'author', 'repository', 'version',
  406. 'description', 'repo', 'title', 'effect', 'sponsors'
  407. ].concat(!this.isInstalledInDotRoot ? ['devEntry'] : []).forEach(k => {
  408. this._options[k] = pkg[k]
  409. })
  410. const validateEntry = (main) => main && /\.(js|html)$/.test(main)
  411. // Entry from main
  412. const entry = logseq.entry || logseq.main || pkg.main
  413. if (validateEntry(entry)) { // Theme has no main
  414. this._options.entry = this._resolveResourceFullUrl(entry, localRoot)
  415. this._options.devEntry = logseq.devEntry
  416. if (logseq.mode) {
  417. this._options.mode = logseq.mode
  418. }
  419. }
  420. const title = logseq.title || pkg.title
  421. const icon = logseq.icon || pkg.icon
  422. this._options.title = title
  423. this._options.icon = icon &&
  424. this._resolveResourceFullUrl(icon)
  425. this._options.theme = Boolean(logseq.theme || !!logseq.themes)
  426. // TODO: strategy for Logseq plugins center
  427. if (this.isInstalledInDotRoot) {
  428. this._id = path.basename(localRoot)
  429. } else {
  430. if (logseq.id) {
  431. this._id = logseq.id
  432. } else {
  433. logseq.id = this.id
  434. try {
  435. await invokeHostExportedApi('save_plugin_config', url, { ...pkg, logseq })
  436. } catch (e) {
  437. debug('[save plugin ID Error] ', e)
  438. }
  439. }
  440. }
  441. // Validate id
  442. const { registeredPlugins, isRegistering } = this._ctx
  443. if (isRegistering && registeredPlugins.has(logseq.id)) {
  444. throw new ExistedImportedPluginPackageError('prepare package Error')
  445. }
  446. return async () => {
  447. try {
  448. // 0. Install Themes
  449. let themes = logseq.themes
  450. if (themes) {
  451. await this._loadConfigThemes(
  452. Array.isArray(themes) ? themes : [themes]
  453. )
  454. }
  455. } catch (e) {
  456. debug('[prepare package effect Error]', e)
  457. }
  458. }
  459. }
  460. async _tryToNormalizeEntry () {
  461. let { entry, settings, devEntry } = this.options
  462. devEntry = devEntry || settings?.get('_devEntry')
  463. if (devEntry) {
  464. this._options.entry = devEntry
  465. return
  466. }
  467. if (!entry.endsWith('.js')) return
  468. let dirPathInstalled = null
  469. let tmp_file_method = 'write_user_tmp_file'
  470. if (this.isInstalledInDotRoot) {
  471. tmp_file_method = 'write_dotdir_file'
  472. dirPathInstalled = this._localRoot.replace(this.dotPluginsRoot, '')
  473. dirPathInstalled = path.join(DIR_PLUGINS, dirPathInstalled)
  474. }
  475. let sdkPathRoot = await getSDKPathRoot()
  476. let entryPath = await invokeHostExportedApi(
  477. tmp_file_method,
  478. `${this._id}_index.html`,
  479. `<!doctype html>
  480. <html lang="en">
  481. <head>
  482. <meta charset="UTF-8">
  483. <title>logseq plugin entry</title>
  484. <script src="${sdkPathRoot}/lsplugin.user.js"></script>
  485. </head>
  486. <body>
  487. <div id="app"></div>
  488. <script src="${entry}"></script>
  489. </body>
  490. </html>`, dirPathInstalled)
  491. entry = convertToLSPResource(
  492. withFileProtocol(path.normalize(entryPath)),
  493. this.dotPluginsRoot
  494. )
  495. this._options.entry = entry
  496. }
  497. async _loadConfigThemes (themes: Array<ThemeOptions>) {
  498. themes.forEach((options) => {
  499. if (!options.url) return
  500. if (!options.url.startsWith('http') && this._localRoot) {
  501. options.url = path.join(this._localRoot, options.url)
  502. // file:// for native
  503. if (!options.url.startsWith('file:')) {
  504. options.url = 'assets://' + options.url
  505. }
  506. }
  507. // @ts-ignore
  508. this.emit('provider:theme', options)
  509. })
  510. }
  511. _persistMainUILayoutData (e: { width: number, height: number, left: number, top: number }) {
  512. const layouts = this.settings.get('layouts') || []
  513. layouts[0] = e
  514. this.settings.set('layout', layouts)
  515. }
  516. _setupDraggableContainer (
  517. el: HTMLElement,
  518. opts: Partial<{ key: string, title: string, close: () => void }> = {}): () => void {
  519. const ds = el.dataset
  520. if (ds.inited_draggable) return
  521. if (!ds.identity) {
  522. ds.identity = 'dd-' + genID()
  523. }
  524. const isInjectedUI = !!opts.key
  525. const handle = document.createElement('div')
  526. handle.classList.add('draggable-handle')
  527. handle.innerHTML = `
  528. <div class="th">
  529. <div class="l"><h3>${opts.title || ''}</h3></div>
  530. <div class="r">
  531. <a class="button x"><i class="ti ti-x"></i></a>
  532. </div>
  533. </div>
  534. `
  535. handle.querySelector('.x')
  536. .addEventListener('click', (e) => {
  537. opts?.close?.()
  538. e.stopPropagation()
  539. }, false)
  540. handle.addEventListener('mousedown', (e) => {
  541. const target = e.target as HTMLElement
  542. if (target?.closest('.r')) {
  543. e.stopPropagation()
  544. e.preventDefault()
  545. return
  546. }
  547. }, false)
  548. el.prepend(handle)
  549. // move to top
  550. el.addEventListener('mousedown', (e) => {
  551. this.layoutCore.move_container_to_top(ds.identity)
  552. }, true)
  553. const setTitle = (title) => {
  554. handle.querySelector('h3').textContent = title
  555. }
  556. const dispose = this.layoutCore.setup_draggable_container_BANG_(el,
  557. !isInjectedUI ? this._persistMainUILayoutData.bind(this) : () => {})
  558. ds.inited_draggable = 'true'
  559. if (opts.title) {
  560. setTitle(opts.title)
  561. }
  562. // click outside
  563. let removeOutsideListener = null
  564. if (ds.close === 'outside') {
  565. const handler = (e) => {
  566. const target = e.target
  567. if (!el.contains(target)) {
  568. opts.close()
  569. }
  570. }
  571. document.addEventListener('click', handler, false)
  572. removeOutsideListener = () => {
  573. document.removeEventListener('click', handler)
  574. }
  575. }
  576. return () => {
  577. dispose()
  578. removeOutsideListener?.()
  579. }
  580. }
  581. _setupResizableContainer (el: HTMLElement, key?: string): () => void {
  582. const ds = el.dataset
  583. if (ds.inited_resizable) return
  584. if (!ds.identity) {
  585. ds.identity = 'dd-' + genID()
  586. }
  587. const handle = document.createElement('div')
  588. handle.classList.add('resizable-handle')
  589. el.prepend(handle)
  590. // @ts-ignore
  591. const layoutCore = window.frontend.modules.layout.core
  592. const dispose = layoutCore.setup_resizable_container_BANG_(el,
  593. !key ? this._persistMainUILayoutData.bind(this) : () => {})
  594. ds.inited_resizable = 'true'
  595. return dispose
  596. }
  597. async load (
  598. opts?: Partial<{
  599. indicator: DeferredActor,
  600. reload: boolean
  601. }>
  602. ) {
  603. if (this.pending) {
  604. return
  605. }
  606. this._status = PluginLocalLoadStatus.LOADING
  607. this._loadErr = undefined
  608. try {
  609. // if (!this.options.entry) { // Themes package no entry field
  610. // }
  611. let installPackageThemes = await this._preparePackageConfigs()
  612. this._dispose(
  613. await this._setupUserSettings(opts?.reload)
  614. )
  615. if (!this.disabled) {
  616. await installPackageThemes.call(null)
  617. }
  618. if (this.disabled || !this.options.entry) {
  619. return
  620. }
  621. await this._tryToNormalizeEntry()
  622. this._caller = new LSPluginCaller(this)
  623. await this._caller.connectToChild()
  624. const readyFn = () => {
  625. this._caller?.callUserModel(LSPMSG_READY, { pid: this.id })
  626. }
  627. if (opts?.indicator) {
  628. opts.indicator.promise.then(readyFn)
  629. } else {
  630. readyFn()
  631. }
  632. this._dispose(async () => {
  633. await this._caller?.destroy()
  634. })
  635. } catch (e) {
  636. debug('[Load Plugin Error] ', e)
  637. this.logger?.error(e)
  638. this._status = PluginLocalLoadStatus.ERROR
  639. this._loadErr = e
  640. } finally {
  641. if (!this._loadErr) {
  642. if (this.disabled) {
  643. this._status = PluginLocalLoadStatus.UNLOADED
  644. } else {
  645. this._status = PluginLocalLoadStatus.LOADED
  646. }
  647. }
  648. }
  649. }
  650. async reload () {
  651. if (this.pending) {
  652. return
  653. }
  654. this._ctx.emit('beforereload', this)
  655. await this.unload()
  656. await this.load({ reload: true })
  657. this._ctx.emit('reloaded', this)
  658. }
  659. /**
  660. * @param unregister If true delete plugin files
  661. */
  662. async unload (unregister: boolean = false) {
  663. if (this.pending) {
  664. return
  665. }
  666. if (unregister) {
  667. await this.unload()
  668. if (this.isInstalledInDotRoot) {
  669. this._ctx.emit('unlink-plugin', this.id)
  670. }
  671. return
  672. }
  673. try {
  674. this._status = PluginLocalLoadStatus.UNLOADING
  675. const eventBeforeUnload = { unregister }
  676. // sync call
  677. try {
  678. await this._caller?.callUserModel(AWAIT_LSPMSGFn(LSPMSG_BEFORE_UNLOAD), eventBeforeUnload)
  679. this.emit('beforeunload', eventBeforeUnload)
  680. } catch (e) {
  681. console.error('[beforeunload Error]', e)
  682. }
  683. await this.dispose()
  684. this.emit('unloaded')
  685. } catch (e) {
  686. debug('[plugin unload Error]', e)
  687. return false
  688. } finally {
  689. this._status = PluginLocalLoadStatus.UNLOADED
  690. }
  691. }
  692. private async dispose () {
  693. for (const fn of this._disposes) {
  694. try {
  695. fn && (await fn())
  696. } catch (e) {
  697. console.error(this.debugTag, 'dispose Error', e)
  698. }
  699. }
  700. // clear
  701. this._disposes = []
  702. }
  703. _dispose (fn: any) {
  704. if (!fn) return
  705. this._disposes.push(fn)
  706. }
  707. _onHostMounted (callback: () => void) {
  708. const actor = this._ctx.hostMountedActor
  709. if (!actor || actor.settled) {
  710. callback()
  711. } else {
  712. actor?.promise.then(callback)
  713. }
  714. }
  715. get layoutCore (): any {
  716. // @ts-ignore
  717. return window.frontend.modules.layout.core
  718. }
  719. get isInstalledInDotRoot () {
  720. const dotRoot = this.dotConfigRoot
  721. const plgRoot = this.localRoot
  722. return dotRoot && plgRoot && plgRoot.startsWith(dotRoot)
  723. }
  724. get loaded () {
  725. return this._status === PluginLocalLoadStatus.LOADED
  726. }
  727. get pending () {
  728. return [PluginLocalLoadStatus.LOADING, PluginLocalLoadStatus.UNLOADING]
  729. .includes(this._status)
  730. }
  731. get status (): PluginLocalLoadStatus {
  732. return this._status
  733. }
  734. get settings () {
  735. return this.options.settings
  736. }
  737. get logger () {
  738. return this.options.logger
  739. }
  740. get disabled () {
  741. return this.settings?.get('disabled')
  742. }
  743. get caller () {
  744. return this._caller
  745. }
  746. get id (): string {
  747. return this._id
  748. }
  749. get shadow (): boolean {
  750. return this.options.mode === 'shadow'
  751. }
  752. get options (): PluginLocalOptions {
  753. return this._options
  754. }
  755. get themeMgr (): ILSPluginThemeManager {
  756. return this._themeMgr
  757. }
  758. get debugTag () {
  759. const name = this._options?.name
  760. return `#${this._id} ${name ?? ''}`
  761. }
  762. get localRoot (): string {
  763. return this._localRoot || this._options.url
  764. }
  765. get loadErr (): Error | undefined {
  766. return this._loadErr
  767. }
  768. get dotConfigRoot () {
  769. return path.normalize(this._ctx.options.dotConfigRoot)
  770. }
  771. get dotSettingsFile (): string | undefined {
  772. return this._dotSettingsFile
  773. }
  774. get dotPluginsRoot () {
  775. return path.join(this.dotConfigRoot, DIR_PLUGINS)
  776. }
  777. toJSON () {
  778. const json = { ...this.options } as any
  779. json.id = this.id
  780. json.err = this.loadErr
  781. json.usf = this.dotSettingsFile
  782. json.iir = this.isInstalledInDotRoot
  783. json.lsr = this._resolveResourceFullUrl('')
  784. return json
  785. }
  786. }
  787. /**
  788. * Host plugin core
  789. */
  790. class LSPluginCore
  791. extends EventEmitter<'beforeenable' | 'enabled' | 'beforedisable' | 'disabled' | 'registered' | 'error' | 'unregistered' |
  792. 'theme-changed' | 'theme-selected' | 'settings-changed' | 'unlink-plugin' | 'beforereload' | 'reloaded'>
  793. implements ILSPluginThemeManager {
  794. private _isRegistering = false
  795. private _readyIndicator?: DeferredActor
  796. private _hostMountedActor: DeferredActor = deferred()
  797. private _userPreferences: Partial<UserPreferences> = {}
  798. private _registeredThemes = new Map<PluginLocalIdentity, Array<ThemeOptions>>()
  799. private _registeredPlugins = new Map<PluginLocalIdentity, PluginLocal>()
  800. private _currentTheme: { dis: () => void, pid: PluginLocalIdentity, opt: ThemeOptions }
  801. /**
  802. * @param _options
  803. */
  804. constructor (private _options: Partial<LSPluginCoreOptions>) {
  805. super()
  806. }
  807. async loadUserPreferences () {
  808. try {
  809. const settings = await invokeHostExportedApi(`load_user_preferences`)
  810. if (settings) {
  811. Object.assign(this._userPreferences, settings)
  812. }
  813. } catch (e) {
  814. debug('[load user preferences Error]', e)
  815. }
  816. }
  817. async saveUserPreferences (settings: Partial<UserPreferences>) {
  818. try {
  819. if (settings) {
  820. Object.assign(this._userPreferences, settings)
  821. }
  822. await invokeHostExportedApi(`save_user_preferences`, this._userPreferences)
  823. } catch (e) {
  824. debug('[save user preferences Error]', e)
  825. }
  826. }
  827. async activateUserPreferences () {
  828. const { theme } = this._userPreferences
  829. // 0. theme
  830. if (theme) {
  831. await this.selectTheme(theme, false)
  832. }
  833. }
  834. /**
  835. * @param plugins
  836. * @param initial
  837. */
  838. async register (
  839. plugins: Array<RegisterPluginOpts> | RegisterPluginOpts,
  840. initial = false
  841. ) {
  842. if (!Array.isArray(plugins)) {
  843. await this.register([plugins])
  844. return
  845. }
  846. const perfTable = new Map<string, { o: PluginLocal, s: number, e: number }>()
  847. const debugPerfInfo = () => {
  848. const data = Array.from(perfTable.values()).reduce((ac, it) => {
  849. const { options, status, disabled } = it.o
  850. ac[it.o.id] = {
  851. name: options.name,
  852. entry: options.entry,
  853. status: status,
  854. enabled: typeof disabled === 'boolean' ? (!disabled ? '🟢' : '⚫️') : '🔴',
  855. perf: !it.e ? it.o.loadErr : `${(it.e - it.s).toFixed(2)}ms`
  856. }
  857. return ac
  858. }, {})
  859. console.table(data)
  860. }
  861. // @ts-ignore
  862. window.__debugPluginsPerfInfo = debugPerfInfo
  863. try {
  864. this._isRegistering = true
  865. const userConfigRoot = this._options.dotConfigRoot
  866. const readyIndicator = this._readyIndicator = deferred()
  867. await this.loadUserPreferences()
  868. const externals = new Set(this._userPreferences.externals || [])
  869. if (initial) {
  870. plugins = plugins.concat([...externals].filter(url => {
  871. return !plugins.length || (plugins as RegisterPluginOpts[]).every((p) => !p.entry && (p.url !== url))
  872. }).map(url => ({ url })))
  873. }
  874. for (const pluginOptions of plugins) {
  875. const { url } = pluginOptions as PluginLocalOptions
  876. const pluginLocal = new PluginLocal(pluginOptions as PluginLocalOptions, this, this)
  877. const perfInfo = { o: pluginLocal, s: performance.now(), e: 0 }
  878. perfTable.set(pluginLocal.id, perfInfo)
  879. await pluginLocal.load({ indicator: readyIndicator })
  880. const { loadErr } = pluginLocal
  881. if (loadErr) {
  882. debug(`[Failed LOAD Plugin] #`, pluginOptions)
  883. this.emit('error', loadErr)
  884. if (
  885. loadErr instanceof IllegalPluginPackageError ||
  886. loadErr instanceof ExistedImportedPluginPackageError) {
  887. // TODO: notify global log system?
  888. continue
  889. }
  890. }
  891. perfInfo.e = performance.now()
  892. pluginLocal.settings?.on('change', (a) => {
  893. this.emit('settings-changed', pluginLocal.id, a)
  894. pluginLocal.caller?.callUserModel(LSPMSG_SETTINGS, { payload: a })
  895. })
  896. this._registeredPlugins.set(pluginLocal.id, pluginLocal)
  897. this.emit('registered', pluginLocal)
  898. // external plugins
  899. if (!pluginLocal.isInstalledInDotRoot) {
  900. externals.add(url)
  901. }
  902. }
  903. await this.saveUserPreferences({ externals: Array.from(externals) })
  904. await this.activateUserPreferences()
  905. readyIndicator.resolve('ready')
  906. } catch (e) {
  907. console.error(e)
  908. } finally {
  909. this._isRegistering = false
  910. debugPerfInfo()
  911. }
  912. }
  913. async reload (plugins: Array<PluginLocalIdentity> | PluginLocalIdentity) {
  914. if (!Array.isArray(plugins)) {
  915. await this.reload([plugins])
  916. return
  917. }
  918. for (const identity of plugins) {
  919. try {
  920. const p = this.ensurePlugin(identity)
  921. await p.reload()
  922. } catch (e) {
  923. debug(e)
  924. }
  925. }
  926. }
  927. async unregister (plugins: Array<PluginLocalIdentity> | PluginLocalIdentity) {
  928. if (!Array.isArray(plugins)) {
  929. await this.unregister([plugins])
  930. return
  931. }
  932. const unregisteredExternals: Array<string> = []
  933. for (const identity of plugins) {
  934. const p = this.ensurePlugin(identity)
  935. if (!p.isInstalledInDotRoot) {
  936. unregisteredExternals.push(p.options.url)
  937. }
  938. await p.unload(true)
  939. this._registeredPlugins.delete(identity)
  940. this.emit('unregistered', identity)
  941. }
  942. let externals = this._userPreferences.externals || []
  943. if (externals.length && unregisteredExternals.length) {
  944. await this.saveUserPreferences({
  945. externals: externals.filter((it) => {
  946. return !unregisteredExternals.includes(it)
  947. })
  948. })
  949. }
  950. }
  951. async enable (plugin: PluginLocalIdentity) {
  952. const p = this.ensurePlugin(plugin)
  953. if (p.pending) return
  954. this.emit('beforeenable')
  955. p.settings?.set('disabled', false)
  956. this.emit('enabled', p.id)
  957. }
  958. async disable (plugin: PluginLocalIdentity) {
  959. const p = this.ensurePlugin(plugin)
  960. if (p.pending) return
  961. this.emit('beforedisable')
  962. p.settings?.set('disabled', true)
  963. this.emit('disabled', p.id)
  964. }
  965. async _hook (ns: string, type: string, payload?: any, pid?: string) {
  966. for (const [_, p] of this._registeredPlugins) {
  967. if (!pid || pid === p.id) {
  968. p.caller?.callUserModel(LSPMSG, {
  969. ns, type: snakeCase(type), payload
  970. })
  971. }
  972. }
  973. }
  974. hookApp (type: string, payload?: any, pid?: string) {
  975. this._hook(`hook:app`, type, payload, pid)
  976. }
  977. hookEditor (type: string, payload?: any, pid?: string) {
  978. this._hook(`hook:editor`, type, payload, pid)
  979. }
  980. _execDirective (tag: string, ...params: any[]) {
  981. }
  982. ensurePlugin (plugin: PluginLocalIdentity | PluginLocal) {
  983. if (plugin instanceof PluginLocal) {
  984. return plugin
  985. }
  986. const p = this._registeredPlugins.get(plugin)
  987. if (!p) {
  988. throw new Error(`plugin #${plugin} not existed.`)
  989. }
  990. return p
  991. }
  992. hostMounted () {
  993. this._hostMountedActor.resolve()
  994. }
  995. get registeredPlugins (): Map<PluginLocalIdentity, PluginLocal> {
  996. return this._registeredPlugins
  997. }
  998. get options () {
  999. return this._options
  1000. }
  1001. get readyIndicator (): DeferredActor | undefined {
  1002. return this._readyIndicator
  1003. }
  1004. get hostMountedActor (): DeferredActor {
  1005. return this._hostMountedActor
  1006. }
  1007. get isRegistering (): boolean {
  1008. return this._isRegistering
  1009. }
  1010. get themes (): Map<PluginLocalIdentity, Array<ThemeOptions>> {
  1011. return this._registeredThemes
  1012. }
  1013. async registerTheme (id: PluginLocalIdentity, opt: ThemeOptions): Promise<void> {
  1014. debug('registered Theme #', id, opt)
  1015. if (!id) return
  1016. let themes: Array<ThemeOptions> = this._registeredThemes.get(id)!
  1017. if (!themes) {
  1018. this._registeredThemes.set(id, themes = [])
  1019. }
  1020. themes.push(opt)
  1021. this.emit('theme-changed', this.themes, { id, ...opt })
  1022. }
  1023. async selectTheme (opt?: ThemeOptions, effect = true): Promise<void> {
  1024. // clear current
  1025. if (this._currentTheme) {
  1026. this._currentTheme.dis?.()
  1027. }
  1028. const disInjectedTheme = setupInjectedTheme(opt?.url)
  1029. this.emit('theme-selected', opt)
  1030. effect && await this.saveUserPreferences({ theme: opt?.url ? opt : null })
  1031. if (opt?.url) {
  1032. this._currentTheme = {
  1033. dis: () => {
  1034. disInjectedTheme()
  1035. effect && this.saveUserPreferences({ theme: null })
  1036. }, opt, pid: opt.pid
  1037. }
  1038. }
  1039. }
  1040. async unregisterTheme (id: PluginLocalIdentity, effect: boolean = true): Promise<void> {
  1041. debug('unregistered Theme #', id)
  1042. if (!this._registeredThemes.has(id)) return
  1043. this._registeredThemes.delete(id)
  1044. this.emit('theme-changed', this.themes, { id })
  1045. if (effect && this._currentTheme?.pid == id) {
  1046. this._currentTheme.dis?.()
  1047. this._currentTheme = null
  1048. // reset current theme
  1049. this.emit('theme-selected', null)
  1050. }
  1051. }
  1052. }
  1053. function setupPluginCore (options: any) {
  1054. const pluginCore = new LSPluginCore(options)
  1055. debug('=== 🔗 Setup Logseq Plugin System 🔗 ===')
  1056. window.LSPluginCore = pluginCore
  1057. }
  1058. export {
  1059. PluginLocal,
  1060. pluginHelpers,
  1061. setupPluginCore
  1062. }