tauri.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright 2019-2021 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. declare global {
  5. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  6. interface Window {
  7. rpc: {
  8. notify: (command: string, args?: { [key: string]: unknown }) => void
  9. }
  10. }
  11. }
  12. function uid(): string {
  13. const length = new Int8Array(1)
  14. window.crypto.getRandomValues(length)
  15. const array = new Uint8Array(Math.max(16, Math.abs(length[0])))
  16. window.crypto.getRandomValues(array)
  17. return array.join('')
  18. }
  19. function transformCallback(
  20. callback?: (response: any) => void,
  21. once = false
  22. ): string {
  23. const identifier = uid()
  24. Object.defineProperty(window, identifier, {
  25. value: (result: any) => {
  26. if (once) {
  27. Reflect.deleteProperty(window, identifier)
  28. }
  29. return callback?.(result)
  30. },
  31. writable: false,
  32. configurable: true
  33. })
  34. return identifier
  35. }
  36. export interface InvokeArgs {
  37. mainThread?: boolean
  38. [key: string]: unknown
  39. }
  40. /**
  41. * Sends a message to the backend.
  42. *
  43. * @param cmd
  44. * @param [args]
  45. * @return A promise resolving or rejecting to the backend response.
  46. */
  47. async function invoke<T>(cmd: string, args: InvokeArgs = {}): Promise<T> {
  48. return new Promise((resolve, reject) => {
  49. const callback = transformCallback((e) => {
  50. resolve(e)
  51. Reflect.deleteProperty(window, error)
  52. }, true)
  53. const error = transformCallback((e) => {
  54. reject(e)
  55. Reflect.deleteProperty(window, callback)
  56. }, true)
  57. window.rpc.notify(cmd, {
  58. callback,
  59. error,
  60. ...args
  61. })
  62. })
  63. }
  64. export { transformCallback, invoke }