@metamask/snaps-controllers 4.1.0 → 5.0.1

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.
Files changed (145) hide show
  1. package/CHANGELOG.md +27 -1
  2. package/dist/cjs/cronjob/CronjobController.js +3 -3
  3. package/dist/cjs/cronjob/CronjobController.js.map +1 -1
  4. package/dist/cjs/index.js +1 -0
  5. package/dist/cjs/index.js.map +1 -1
  6. package/dist/cjs/interface/SnapInterfaceController.js +166 -0
  7. package/dist/cjs/interface/SnapInterfaceController.js.map +1 -0
  8. package/dist/cjs/interface/index.js +20 -0
  9. package/dist/cjs/interface/index.js.map +1 -0
  10. package/dist/cjs/interface/utils.js +59 -0
  11. package/dist/cjs/interface/utils.js.map +1 -0
  12. package/dist/cjs/services/browser.js +1 -0
  13. package/dist/cjs/services/browser.js.map +1 -1
  14. package/dist/cjs/services/index.js +1 -0
  15. package/dist/cjs/services/index.js.map +1 -1
  16. package/dist/cjs/services/webview/WebViewExecutionService.js +99 -0
  17. package/dist/cjs/services/webview/WebViewExecutionService.js.map +1 -0
  18. package/dist/cjs/services/webview/WebViewMessageStream.js +127 -0
  19. package/dist/cjs/services/webview/WebViewMessageStream.js.map +1 -0
  20. package/dist/cjs/services/webview/index.js +20 -0
  21. package/dist/cjs/services/webview/index.js.map +1 -0
  22. package/dist/cjs/snaps/SnapController.js +111 -51
  23. package/dist/cjs/snaps/SnapController.js.map +1 -1
  24. package/dist/cjs/snaps/constants.js +25 -0
  25. package/dist/cjs/snaps/constants.js.map +1 -0
  26. package/dist/cjs/snaps/index.js +0 -2
  27. package/dist/cjs/snaps/index.js.map +1 -1
  28. package/dist/cjs/snaps/location/npm.js +13 -2
  29. package/dist/cjs/snaps/location/npm.js.map +1 -1
  30. package/dist/cjs/snaps/registry/json.js +10 -5
  31. package/dist/cjs/snaps/registry/json.js.map +1 -1
  32. package/dist/esm/cronjob/CronjobController.js +2 -2
  33. package/dist/esm/cronjob/CronjobController.js.map +1 -1
  34. package/dist/esm/index.js +1 -0
  35. package/dist/esm/index.js.map +1 -1
  36. package/dist/esm/interface/SnapInterfaceController.js +158 -0
  37. package/dist/esm/interface/SnapInterfaceController.js.map +1 -0
  38. package/dist/esm/interface/index.js +3 -0
  39. package/dist/esm/interface/index.js.map +1 -0
  40. package/dist/esm/interface/utils.js +62 -0
  41. package/dist/esm/interface/utils.js.map +1 -0
  42. package/dist/esm/services/browser.js +1 -0
  43. package/dist/esm/services/browser.js.map +1 -1
  44. package/dist/esm/services/index.js +1 -0
  45. package/dist/esm/services/index.js.map +1 -1
  46. package/dist/esm/services/webview/WebViewExecutionService.js +89 -0
  47. package/dist/esm/services/webview/WebViewExecutionService.js.map +1 -0
  48. package/dist/esm/services/webview/WebViewMessageStream.js +119 -0
  49. package/dist/esm/services/webview/WebViewMessageStream.js.map +1 -0
  50. package/dist/esm/services/webview/index.js +3 -0
  51. package/dist/esm/services/webview/index.js.map +1 -0
  52. package/dist/esm/snaps/SnapController.js +105 -45
  53. package/dist/esm/snaps/SnapController.js.map +1 -1
  54. package/dist/esm/snaps/constants.js +16 -0
  55. package/dist/esm/snaps/constants.js.map +1 -0
  56. package/dist/esm/snaps/index.js +0 -2
  57. package/dist/esm/snaps/index.js.map +1 -1
  58. package/dist/esm/snaps/location/npm.js +13 -2
  59. package/dist/esm/snaps/location/npm.js.map +1 -1
  60. package/dist/esm/snaps/registry/json.js +10 -5
  61. package/dist/esm/snaps/registry/json.js.map +1 -1
  62. package/dist/types/index.d.ts +1 -0
  63. package/dist/types/interface/SnapInterfaceController.d.ts +85 -0
  64. package/dist/types/interface/index.d.ts +1 -0
  65. package/dist/types/interface/utils.d.ts +36 -0
  66. package/dist/types/services/browser.d.ts +1 -0
  67. package/dist/types/services/index.d.ts +1 -0
  68. package/dist/types/services/webview/WebViewExecutionService.d.ts +20 -0
  69. package/dist/types/services/webview/WebViewMessageStream.d.ts +32 -0
  70. package/dist/types/services/webview/index.d.ts +1 -0
  71. package/dist/types/snaps/SnapController.d.ts +7 -4
  72. package/dist/types/snaps/constants.d.ts +1 -0
  73. package/dist/types/snaps/index.d.ts +0 -2
  74. package/dist/types/utils.d.ts +33 -13
  75. package/package.json +12 -12
  76. package/dist/cjs/snaps/endowments/cronjob.js +0 -100
  77. package/dist/cjs/snaps/endowments/cronjob.js.map +0 -1
  78. package/dist/cjs/snaps/endowments/enum.js +0 -26
  79. package/dist/cjs/snaps/endowments/enum.js.map +0 -1
  80. package/dist/cjs/snaps/endowments/ethereum-provider.js +0 -43
  81. package/dist/cjs/snaps/endowments/ethereum-provider.js.map +0 -1
  82. package/dist/cjs/snaps/endowments/home-page.js +0 -37
  83. package/dist/cjs/snaps/endowments/home-page.js.map +0 -1
  84. package/dist/cjs/snaps/endowments/index.js +0 -107
  85. package/dist/cjs/snaps/endowments/index.js.map +0 -1
  86. package/dist/cjs/snaps/endowments/keyring.js +0 -100
  87. package/dist/cjs/snaps/endowments/keyring.js.map +0 -1
  88. package/dist/cjs/snaps/endowments/lifecycle-hooks.js +0 -37
  89. package/dist/cjs/snaps/endowments/lifecycle-hooks.js.map +0 -1
  90. package/dist/cjs/snaps/endowments/name-lookup.js +0 -106
  91. package/dist/cjs/snaps/endowments/name-lookup.js.map +0 -1
  92. package/dist/cjs/snaps/endowments/network-access.js +0 -44
  93. package/dist/cjs/snaps/endowments/network-access.js.map +0 -1
  94. package/dist/cjs/snaps/endowments/rpc.js +0 -99
  95. package/dist/cjs/snaps/endowments/rpc.js.map +0 -1
  96. package/dist/cjs/snaps/endowments/signature-insight.js +0 -106
  97. package/dist/cjs/snaps/endowments/signature-insight.js.map +0 -1
  98. package/dist/cjs/snaps/endowments/transaction-insight.js +0 -106
  99. package/dist/cjs/snaps/endowments/transaction-insight.js.map +0 -1
  100. package/dist/cjs/snaps/endowments/web-assembly.js +0 -42
  101. package/dist/cjs/snaps/endowments/web-assembly.js.map +0 -1
  102. package/dist/cjs/snaps/permissions.js +0 -61
  103. package/dist/cjs/snaps/permissions.js.map +0 -1
  104. package/dist/esm/snaps/endowments/cronjob.js +0 -99
  105. package/dist/esm/snaps/endowments/cronjob.js.map +0 -1
  106. package/dist/esm/snaps/endowments/enum.js +0 -16
  107. package/dist/esm/snaps/endowments/enum.js.map +0 -1
  108. package/dist/esm/snaps/endowments/ethereum-provider.js +0 -33
  109. package/dist/esm/snaps/endowments/ethereum-provider.js.map +0 -1
  110. package/dist/esm/snaps/endowments/home-page.js +0 -27
  111. package/dist/esm/snaps/endowments/home-page.js.map +0 -1
  112. package/dist/esm/snaps/endowments/index.js +0 -60
  113. package/dist/esm/snaps/endowments/index.js.map +0 -1
  114. package/dist/esm/snaps/endowments/keyring.js +0 -91
  115. package/dist/esm/snaps/endowments/keyring.js.map +0 -1
  116. package/dist/esm/snaps/endowments/lifecycle-hooks.js +0 -27
  117. package/dist/esm/snaps/endowments/lifecycle-hooks.js.map +0 -1
  118. package/dist/esm/snaps/endowments/name-lookup.js +0 -98
  119. package/dist/esm/snaps/endowments/name-lookup.js.map +0 -1
  120. package/dist/esm/snaps/endowments/network-access.js +0 -34
  121. package/dist/esm/snaps/endowments/network-access.js.map +0 -1
  122. package/dist/esm/snaps/endowments/rpc.js +0 -88
  123. package/dist/esm/snaps/endowments/rpc.js.map +0 -1
  124. package/dist/esm/snaps/endowments/signature-insight.js +0 -99
  125. package/dist/esm/snaps/endowments/signature-insight.js.map +0 -1
  126. package/dist/esm/snaps/endowments/transaction-insight.js +0 -99
  127. package/dist/esm/snaps/endowments/transaction-insight.js.map +0 -1
  128. package/dist/esm/snaps/endowments/web-assembly.js +0 -32
  129. package/dist/esm/snaps/endowments/web-assembly.js.map +0 -1
  130. package/dist/esm/snaps/permissions.js +0 -50
  131. package/dist/esm/snaps/permissions.js.map +0 -1
  132. package/dist/types/snaps/endowments/cronjob.d.ts +0 -51
  133. package/dist/types/snaps/endowments/enum.d.ts +0 -13
  134. package/dist/types/snaps/endowments/ethereum-provider.d.ts +0 -14
  135. package/dist/types/snaps/endowments/home-page.d.ts +0 -15
  136. package/dist/types/snaps/endowments/index.d.ts +0 -127
  137. package/dist/types/snaps/endowments/keyring.d.ts +0 -39
  138. package/dist/types/snaps/endowments/lifecycle-hooks.d.ts +0 -15
  139. package/dist/types/snaps/endowments/name-lookup.d.ts +0 -38
  140. package/dist/types/snaps/endowments/network-access.d.ts +0 -14
  141. package/dist/types/snaps/endowments/rpc.d.ts +0 -38
  142. package/dist/types/snaps/endowments/signature-insight.d.ts +0 -39
  143. package/dist/types/snaps/endowments/transaction-insight.d.ts +0 -39
  144. package/dist/types/snaps/endowments/web-assembly.d.ts +0 -14
  145. package/dist/types/snaps/permissions.d.ts +0 -16
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/interface/SnapInterfaceController.ts"],"sourcesContent":["import type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type {\n MaybeUpdateState,\n TestOrigin,\n} from '@metamask/phishing-controller';\nimport type { Component, InterfaceState, SnapId } from '@metamask/snaps-sdk';\nimport { validateComponentLinks } from '@metamask/snaps-utils';\nimport { assert } from '@metamask/utils';\nimport { nanoid } from 'nanoid';\n\nimport { constructState } from './utils';\n\nconst controllerName = 'SnapInterfaceController';\n\nexport type CreateInterface = {\n type: `${typeof controllerName}:createInterface`;\n handler: SnapInterfaceController['createInterface'];\n};\n\nexport type GetInterface = {\n type: `${typeof controllerName}:getInterface`;\n handler: SnapInterfaceController['getInterface'];\n};\n\nexport type UpdateInterface = {\n type: `${typeof controllerName}:updateInterface`;\n handler: SnapInterfaceController['updateInterface'];\n};\n\nexport type DeleteInterface = {\n type: `${typeof controllerName}:deleteInterface`;\n handler: SnapInterfaceController['deleteInterface'];\n};\n\nexport type UpdateInterfaceState = {\n type: `${typeof controllerName}:updateInterfaceState`;\n handler: SnapInterfaceController['updateInterfaceState'];\n};\n\nexport type SnapInterfaceControllerAllowedActions =\n | TestOrigin\n | MaybeUpdateState;\n\nexport type SnapInterfaceControllerActions =\n | CreateInterface\n | GetInterface\n | UpdateInterface\n | DeleteInterface\n | UpdateInterfaceState;\n\nexport type SnapInterfaceControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n SnapInterfaceControllerActions | SnapInterfaceControllerAllowedActions,\n never,\n SnapInterfaceControllerAllowedActions['type'],\n never\n>;\n\nexport type StoredInterface = {\n snapId: SnapId;\n content: Component;\n state: InterfaceState;\n};\n\nexport type SnapInterfaceControllerState = {\n interfaces: Record<string, StoredInterface>;\n};\n\nexport type SnapInterfaceControllerArgs = {\n messenger: SnapInterfaceControllerMessenger;\n state?: SnapInterfaceControllerState;\n};\n\n/**\n * Use this controller to manage snaps UI interfaces using RPC method hooks.\n */\nexport class SnapInterfaceController extends BaseController<\n typeof controllerName,\n SnapInterfaceControllerState,\n SnapInterfaceControllerMessenger\n> {\n constructor({ messenger, state }: SnapInterfaceControllerArgs) {\n super({\n messenger,\n metadata: {\n interfaces: { persist: false, anonymous: false },\n },\n name: controllerName,\n state: { interfaces: {}, ...state },\n });\n\n this.#registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers() {\n this.messagingSystem.registerActionHandler(\n `${controllerName}:createInterface`,\n this.createInterface.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:getInterface`,\n this.getInterface.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:updateInterface`,\n this.updateInterface.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:deleteInterface`,\n this.deleteInterface.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:updateInterfaceState`,\n this.updateInterfaceState.bind(this),\n );\n }\n\n /**\n * Create an interface in the controller state with the associated data.\n *\n * @param snapId - The snap id that created the interface.\n * @param content - The interface content.\n * @returns The newly interface id.\n */\n async createInterface(snapId: SnapId, content: Component) {\n await this.#validateContent(content);\n\n const id = nanoid();\n\n const componentState = constructState({}, content);\n\n this.update((draftState) => {\n draftState.interfaces[id] = {\n snapId,\n content,\n state: componentState,\n };\n });\n\n return id;\n }\n\n /**\n * Get the data of a given interface id.\n *\n * @param snapId - The snap id requesting the interface data.\n * @param id - The interface id.\n * @returns The interface state.\n */\n getInterface(snapId: SnapId, id: string) {\n this.#validateArgs(snapId, id);\n\n return this.state.interfaces[id];\n }\n\n /**\n * Update the interface with the given content.\n *\n * @param snapId - The snap id requesting the update.\n * @param id - The interface id.\n * @param content - The new content.\n */\n async updateInterface(snapId: SnapId, id: string, content: Component) {\n this.#validateArgs(snapId, id);\n await this.#validateContent(content);\n\n const oldState = this.state.interfaces[id].state;\n\n const newState = constructState(oldState, content);\n\n this.update((draftState) => {\n draftState.interfaces[id].state = newState;\n draftState.interfaces[id].content = content;\n });\n }\n\n /**\n * Delete an interface from state.\n *\n * @param id - The interface id.\n */\n deleteInterface(id: string) {\n this.update((draftState) => {\n delete draftState.interfaces[id];\n });\n }\n\n /**\n * Update the interface state.\n *\n * @param id - The interface id.\n * @param state - The new state.\n */\n updateInterfaceState(id: string, state: InterfaceState) {\n this.update((draftState) => {\n draftState.interfaces[id].state = state;\n });\n }\n\n /**\n * Utility function to validate the args passed to the other methods.\n *\n * @param snapId - The snap id.\n * @param id - The interface id.\n */\n #validateArgs(snapId: SnapId, id: string) {\n const existingInterface = this.state.interfaces[id];\n\n assert(\n existingInterface !== undefined,\n `Interface with id '${id}' not found.`,\n );\n assert(\n existingInterface.snapId === snapId,\n `Interface not created by ${snapId}.`,\n );\n }\n\n /**\n * Trigger a Phishing list update if needed.\n */\n async #triggerPhishingListUpdate() {\n await this.messagingSystem.call('PhishingController:maybeUpdateState');\n }\n\n /**\n * Check an origin against the phishing list.\n *\n * @param origin - The origin to check.\n * @returns True if the origin is on the phishing list, otherwise false.\n */\n #checkPhishingList(origin: string) {\n return this.messagingSystem.call('PhishingController:testOrigin', origin)\n .result;\n }\n\n /**\n * Utility function to validate the components of an interface.\n * Throws if something is invalid.\n *\n * Right now this only checks links against the phighing list.\n *\n * @param content - The components to verify.\n */\n async #validateContent(content: Component) {\n await this.#triggerPhishingListUpdate();\n\n validateComponentLinks(content, this.#checkPhishingList.bind(this));\n }\n}\n"],"names":["BaseController","validateComponentLinks","assert","nanoid","constructState","controllerName","SnapInterfaceController","createInterface","snapId","content","validateContent","id","componentState","update","draftState","interfaces","state","getInterface","validateArgs","updateInterface","oldState","newState","deleteInterface","updateInterfaceState","constructor","messenger","metadata","persist","anonymous","name","registerMessageHandlers","messagingSystem","registerActionHandler","bind","existingInterface","undefined","call","origin","result","triggerPhishingListUpdate","checkPhishingList"],"mappings":"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"}
@@ -0,0 +1,3 @@
1
+ export * from './SnapInterfaceController';
2
+
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/interface/index.ts"],"sourcesContent":["export * from './SnapInterfaceController';\n"],"names":[],"mappings":"AAAA,cAAc,4BAA4B"}
@@ -0,0 +1,62 @@
1
+ import { NodeType, assert } from '@metamask/snaps-sdk';
2
+ /**
3
+ * Construct the state for a stray input (not enclosed in a form).
4
+ *
5
+ * @param state - The interface state.
6
+ * @param component - The Input component.
7
+ * @returns The input state.
8
+ */ export const constructInputState = (state, component)=>{
9
+ return component.value ?? state[component.name] ?? null;
10
+ };
11
+ /**
12
+ * Construct the state for a form input.
13
+ *
14
+ * Sets the state to either the specified component value, the previous value from the old state or null.
15
+ *
16
+ * @param state - The interface state.
17
+ * @param component - The Input component.
18
+ * @param form - The parent form name of the input.
19
+ * @returns The input state.
20
+ */ export const constructFormInputState = (state, component, form)=>{
21
+ const oldFormState = state[form];
22
+ const oldInputState = oldFormState?.[component.name];
23
+ return component.value ?? oldInputState ?? null;
24
+ };
25
+ /**
26
+ * Assert that the component name is unique in state.
27
+ *
28
+ * @param state - The interface state to verify against.
29
+ * @param name - The component name to verify.
30
+ */ export const assertNameIsUnique = (state, name)=>{
31
+ assert(state[name] === undefined, `Duplicate component names are not allowed, found multiple instances of: "${name}".`);
32
+ };
33
+ /**
34
+ * Construct the interface state for a given component tree while preserving values for matching stateful components in the old state.
35
+ *
36
+ * @param oldState - The previous state.
37
+ * @param component - The UI component to construct state from.
38
+ * @param newState - The state that is being constructed.
39
+ * @returns The interface state of the passed component.
40
+ */ export const constructState = (oldState, component, newState = {})=>{
41
+ const { type } = component;
42
+ if (type === NodeType.Panel) {
43
+ return component.children.reduce((acc, node)=>constructState(oldState, node, acc), newState);
44
+ }
45
+ if (type === NodeType.Form) {
46
+ assertNameIsUnique(newState, component.name);
47
+ newState[component.name] = component.children.reduce((acc, node)=>{
48
+ if (node.type === NodeType.Input) {
49
+ assertNameIsUnique(acc, node.name);
50
+ acc[node.name] = constructFormInputState(oldState, node, component.name);
51
+ }
52
+ return acc;
53
+ }, {});
54
+ }
55
+ if (type === NodeType.Input) {
56
+ assertNameIsUnique(newState, component.name);
57
+ newState[component.name] = constructInputState(oldState, component);
58
+ }
59
+ return newState;
60
+ };
61
+
62
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/interface/utils.ts"],"sourcesContent":["import { NodeType, assert } from '@metamask/snaps-sdk';\nimport type {\n Component,\n Input,\n FormState,\n InterfaceState,\n} from '@metamask/snaps-sdk';\n\n/**\n * Construct the state for a stray input (not enclosed in a form).\n *\n * @param state - The interface state.\n * @param component - The Input component.\n * @returns The input state.\n */\nexport const constructInputState = (\n state: InterfaceState,\n component: Input,\n) => {\n return component.value ?? state[component.name] ?? null;\n};\n\n/**\n * Construct the state for a form input.\n *\n * Sets the state to either the specified component value, the previous value from the old state or null.\n *\n * @param state - The interface state.\n * @param component - The Input component.\n * @param form - The parent form name of the input.\n * @returns The input state.\n */\nexport const constructFormInputState = (\n state: InterfaceState,\n component: Input,\n form: string,\n) => {\n const oldFormState = state[form] as FormState;\n const oldInputState = oldFormState?.[component.name];\n return component.value ?? oldInputState ?? null;\n};\n\n/**\n * Assert that the component name is unique in state.\n *\n * @param state - The interface state to verify against.\n * @param name - The component name to verify.\n */\nexport const assertNameIsUnique = (state: InterfaceState, name: string) => {\n assert(\n state[name] === undefined,\n `Duplicate component names are not allowed, found multiple instances of: \"${name}\".`,\n );\n};\n\n/**\n * Construct the interface state for a given component tree while preserving values for matching stateful components in the old state.\n *\n * @param oldState - The previous state.\n * @param component - The UI component to construct state from.\n * @param newState - The state that is being constructed.\n * @returns The interface state of the passed component.\n */\nexport const constructState = (\n oldState: InterfaceState,\n component: Component,\n newState: InterfaceState = {},\n): InterfaceState => {\n const { type } = component;\n if (type === NodeType.Panel) {\n return component.children.reduce(\n (acc, node) => constructState(oldState, node, acc),\n newState,\n );\n }\n\n if (type === NodeType.Form) {\n assertNameIsUnique(newState, component.name);\n newState[component.name] = component.children.reduce<FormState>(\n (acc, node) => {\n if (node.type === NodeType.Input) {\n assertNameIsUnique(acc, node.name);\n acc[node.name] = constructFormInputState(\n oldState,\n node,\n component.name,\n );\n }\n\n return acc;\n },\n {},\n );\n }\n\n if (type === NodeType.Input) {\n assertNameIsUnique(newState, component.name);\n newState[component.name] = constructInputState(oldState, component);\n }\n\n return newState;\n};\n"],"names":["NodeType","assert","constructInputState","state","component","value","name","constructFormInputState","form","oldFormState","oldInputState","assertNameIsUnique","undefined","constructState","oldState","newState","type","Panel","children","reduce","acc","node","Form","Input"],"mappings":"AAAA,SAASA,QAAQ,EAAEC,MAAM,QAAQ,sBAAsB;AAQvD;;;;;;CAMC,GACD,OAAO,MAAMC,sBAAsB,CACjCC,OACAC;IAEA,OAAOA,UAAUC,KAAK,IAAIF,KAAK,CAACC,UAAUE,IAAI,CAAC,IAAI;AACrD,EAAE;AAEF;;;;;;;;;CASC,GACD,OAAO,MAAMC,0BAA0B,CACrCJ,OACAC,WACAI;IAEA,MAAMC,eAAeN,KAAK,CAACK,KAAK;IAChC,MAAME,gBAAgBD,cAAc,CAACL,UAAUE,IAAI,CAAC;IACpD,OAAOF,UAAUC,KAAK,IAAIK,iBAAiB;AAC7C,EAAE;AAEF;;;;;CAKC,GACD,OAAO,MAAMC,qBAAqB,CAACR,OAAuBG;IACxDL,OACEE,KAAK,CAACG,KAAK,KAAKM,WAChB,CAAC,yEAAyE,EAAEN,KAAK,EAAE,CAAC;AAExF,EAAE;AAEF;;;;;;;CAOC,GACD,OAAO,MAAMO,iBAAiB,CAC5BC,UACAV,WACAW,WAA2B,CAAC,CAAC;IAE7B,MAAM,EAAEC,IAAI,EAAE,GAAGZ;IACjB,IAAIY,SAAShB,SAASiB,KAAK,EAAE;QAC3B,OAAOb,UAAUc,QAAQ,CAACC,MAAM,CAC9B,CAACC,KAAKC,OAASR,eAAeC,UAAUO,MAAMD,MAC9CL;IAEJ;IAEA,IAAIC,SAAShB,SAASsB,IAAI,EAAE;QAC1BX,mBAAmBI,UAAUX,UAAUE,IAAI;QAC3CS,QAAQ,CAACX,UAAUE,IAAI,CAAC,GAAGF,UAAUc,QAAQ,CAACC,MAAM,CAClD,CAACC,KAAKC;YACJ,IAAIA,KAAKL,IAAI,KAAKhB,SAASuB,KAAK,EAAE;gBAChCZ,mBAAmBS,KAAKC,KAAKf,IAAI;gBACjCc,GAAG,CAACC,KAAKf,IAAI,CAAC,GAAGC,wBACfO,UACAO,MACAjB,UAAUE,IAAI;YAElB;YAEA,OAAOc;QACT,GACA,CAAC;IAEL;IAEA,IAAIJ,SAAShB,SAASuB,KAAK,EAAE;QAC3BZ,mBAAmBI,UAAUX,UAAUE,IAAI;QAC3CS,QAAQ,CAACX,UAAUE,IAAI,CAAC,GAAGJ,oBAAoBY,UAAUV;IAC3D;IAEA,OAAOW;AACT,EAAE"}
@@ -4,6 +4,7 @@ export * from './ExecutionService';
4
4
  export * from './ProxyPostMessageStream';
5
5
  export * from './iframe';
6
6
  export * from './offscreen';
7
+ export * from './webview';
7
8
  export { WebWorkerExecutionService } from './webworker';
8
9
 
9
10
  //# sourceMappingURL=browser.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/services/browser.ts"],"sourcesContent":["// Subset of exports meant for browser environments, omits Node.js services\nexport * from './AbstractExecutionService';\nexport * from './ExecutionService';\nexport * from './ProxyPostMessageStream';\nexport * from './iframe';\nexport * from './offscreen';\nexport { WebWorkerExecutionService } from './webworker';\n"],"names":["WebWorkerExecutionService"],"mappings":"AAAA,2EAA2E;AAC3E,cAAc,6BAA6B;AAC3C,cAAc,qBAAqB;AACnC,cAAc,2BAA2B;AACzC,cAAc,WAAW;AACzB,cAAc,cAAc;AAC5B,SAASA,yBAAyB,QAAQ,cAAc"}
1
+ {"version":3,"sources":["../../../src/services/browser.ts"],"sourcesContent":["// Subset of exports meant for browser environments, omits Node.js services\nexport * from './AbstractExecutionService';\nexport * from './ExecutionService';\nexport * from './ProxyPostMessageStream';\nexport * from './iframe';\nexport * from './offscreen';\nexport * from './webview';\nexport { WebWorkerExecutionService } from './webworker';\n"],"names":["WebWorkerExecutionService"],"mappings":"AAAA,2EAA2E;AAC3E,cAAc,6BAA6B;AAC3C,cAAc,qBAAqB;AACnC,cAAc,2BAA2B;AACzC,cAAc,WAAW;AACzB,cAAc,cAAc;AAC5B,cAAc,YAAY;AAC1B,SAASA,yBAAyB,QAAQ,cAAc"}
@@ -4,6 +4,7 @@ export * from './ProxyPostMessageStream';
4
4
  export * from './iframe';
5
5
  export * from './node';
6
6
  export * from './offscreen';
7
+ export * from './webview';
7
8
  export { WebWorkerExecutionService } from './webworker';
8
9
 
9
10
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/services/index.ts"],"sourcesContent":["export * from './AbstractExecutionService';\nexport * from './ExecutionService';\nexport * from './ProxyPostMessageStream';\nexport * from './iframe';\nexport * from './node';\nexport * from './offscreen';\nexport { WebWorkerExecutionService } from './webworker';\n"],"names":["WebWorkerExecutionService"],"mappings":"AAAA,cAAc,6BAA6B;AAC3C,cAAc,qBAAqB;AACnC,cAAc,2BAA2B;AACzC,cAAc,WAAW;AACzB,cAAc,SAAS;AACvB,cAAc,cAAc;AAC5B,SAASA,yBAAyB,QAAQ,cAAc"}
1
+ {"version":3,"sources":["../../../src/services/index.ts"],"sourcesContent":["export * from './AbstractExecutionService';\nexport * from './ExecutionService';\nexport * from './ProxyPostMessageStream';\nexport * from './iframe';\nexport * from './node';\nexport * from './offscreen';\nexport * from './webview';\nexport { WebWorkerExecutionService } from './webworker';\n"],"names":["WebWorkerExecutionService"],"mappings":"AAAA,cAAc,6BAA6B;AAC3C,cAAc,qBAAqB;AACnC,cAAc,2BAA2B;AACzC,cAAc,WAAW;AACzB,cAAc,SAAS;AACvB,cAAc,cAAc;AAC5B,cAAc,YAAY;AAC1B,SAASA,yBAAyB,QAAQ,cAAc"}
@@ -0,0 +1,89 @@
1
+ function _check_private_redeclaration(obj, privateCollection) {
2
+ if (privateCollection.has(obj)) {
3
+ throw new TypeError("Cannot initialize the same private elements twice on an object");
4
+ }
5
+ }
6
+ function _class_apply_descriptor_get(receiver, descriptor) {
7
+ if (descriptor.get) {
8
+ return descriptor.get.call(receiver);
9
+ }
10
+ return descriptor.value;
11
+ }
12
+ function _class_apply_descriptor_set(receiver, descriptor, value) {
13
+ if (descriptor.set) {
14
+ descriptor.set.call(receiver, value);
15
+ } else {
16
+ if (!descriptor.writable) {
17
+ throw new TypeError("attempted to set read only private field");
18
+ }
19
+ descriptor.value = value;
20
+ }
21
+ }
22
+ function _class_extract_field_descriptor(receiver, privateMap, action) {
23
+ if (!privateMap.has(receiver)) {
24
+ throw new TypeError("attempted to " + action + " private field on non-instance");
25
+ }
26
+ return privateMap.get(receiver);
27
+ }
28
+ function _class_private_field_get(receiver, privateMap) {
29
+ var descriptor = _class_extract_field_descriptor(receiver, privateMap, "get");
30
+ return _class_apply_descriptor_get(receiver, descriptor);
31
+ }
32
+ function _class_private_field_init(obj, privateMap, value) {
33
+ _check_private_redeclaration(obj, privateMap);
34
+ privateMap.set(obj, value);
35
+ }
36
+ function _class_private_field_set(receiver, privateMap, value) {
37
+ var descriptor = _class_extract_field_descriptor(receiver, privateMap, "set");
38
+ _class_apply_descriptor_set(receiver, descriptor, value);
39
+ return value;
40
+ }
41
+ function _class_private_method_get(receiver, privateSet, fn) {
42
+ if (!privateSet.has(receiver)) {
43
+ throw new TypeError("attempted to get private field on non-instance");
44
+ }
45
+ return fn;
46
+ }
47
+ function _class_private_method_init(obj, privateSet) {
48
+ _check_private_redeclaration(obj, privateSet);
49
+ privateSet.add(obj);
50
+ }
51
+ import { ProxyExecutionService } from '../proxy/ProxyExecutionService';
52
+ import { WebViewMessageStream } from './WebViewMessageStream';
53
+ var _getWebView = /*#__PURE__*/ new WeakMap(), _ensureWebViewLoaded = /*#__PURE__*/ new WeakSet();
54
+ export class WebViewExecutionService extends ProxyExecutionService {
55
+ /**
56
+ * Create a new stream for the specified job. This wraps the runtime stream
57
+ * in a stream specific to the job.
58
+ *
59
+ * @param jobId - The job ID.
60
+ */ async initEnvStream(jobId) {
61
+ // Ensure that the WebView has been loaded before we proceed.
62
+ await _class_private_method_get(this, _ensureWebViewLoaded, ensureWebViewLoaded).call(this);
63
+ return super.initEnvStream(jobId);
64
+ }
65
+ constructor({ messenger, setupSnapProvider, getWebView }){
66
+ super({
67
+ messenger,
68
+ setupSnapProvider,
69
+ stream: new WebViewMessageStream({
70
+ name: 'parent',
71
+ target: 'child',
72
+ getWebView
73
+ })
74
+ });
75
+ /**
76
+ * Ensure that the WebView has been loaded by awaiting the getWebView promise.
77
+ */ _class_private_method_init(this, _ensureWebViewLoaded);
78
+ _class_private_field_init(this, _getWebView, {
79
+ writable: true,
80
+ value: void 0
81
+ });
82
+ _class_private_field_set(this, _getWebView, getWebView);
83
+ }
84
+ }
85
+ async function ensureWebViewLoaded() {
86
+ await _class_private_field_get(this, _getWebView).call(this);
87
+ }
88
+
89
+ //# sourceMappingURL=WebViewExecutionService.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/services/webview/WebViewExecutionService.ts"],"sourcesContent":["import type { ExecutionServiceArgs } from '../AbstractExecutionService';\nimport { ProxyExecutionService } from '../proxy/ProxyExecutionService';\nimport type { WebViewInterface } from './WebViewMessageStream';\nimport { WebViewMessageStream } from './WebViewMessageStream';\n\nexport type WebViewExecutionServiceArgs = ExecutionServiceArgs & {\n getWebView: () => Promise<WebViewInterface>;\n};\n\nexport class WebViewExecutionService extends ProxyExecutionService {\n #getWebView;\n\n constructor({\n messenger,\n setupSnapProvider,\n getWebView,\n }: WebViewExecutionServiceArgs) {\n super({\n messenger,\n setupSnapProvider,\n stream: new WebViewMessageStream({\n name: 'parent',\n target: 'child',\n getWebView,\n }),\n });\n this.#getWebView = getWebView;\n }\n\n /**\n * Create a new stream for the specified job. This wraps the runtime stream\n * in a stream specific to the job.\n *\n * @param jobId - The job ID.\n */\n protected async initEnvStream(jobId: string) {\n // Ensure that the WebView has been loaded before we proceed.\n await this.#ensureWebViewLoaded();\n\n return super.initEnvStream(jobId);\n }\n\n /**\n * Ensure that the WebView has been loaded by awaiting the getWebView promise.\n */\n async #ensureWebViewLoaded() {\n await this.#getWebView();\n }\n}\n"],"names":["ProxyExecutionService","WebViewMessageStream","WebViewExecutionService","initEnvStream","jobId","ensureWebViewLoaded","constructor","messenger","setupSnapProvider","getWebView","stream","name","target"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAASA,qBAAqB,QAAQ,iCAAiC;AAEvE,SAASC,oBAAoB,QAAQ,yBAAyB;IAO5D,2CAmCM;AApCR,OAAO,MAAMC,gCAAgCF;IAoB3C;;;;;GAKC,GACD,MAAgBG,cAAcC,KAAa,EAAE;QAC3C,6DAA6D;QAC7D,MAAM,0BAAA,IAAI,EAAEC,sBAAAA,0BAAN,IAAI;QAEV,OAAO,KAAK,CAACF,cAAcC;IAC7B;IA5BAE,YAAY,EACVC,SAAS,EACTC,iBAAiB,EACjBC,UAAU,EACkB,CAAE;QAC9B,KAAK,CAAC;YACJF;YACAC;YACAE,QAAQ,IAAIT,qBAAqB;gBAC/BU,MAAM;gBACNC,QAAQ;gBACRH;YACF;QACF;QAiBF;;GAEC,GACD,iCAAM;QAnCN,gCAAA;;mBAAA,KAAA;;uCAgBQA,aAAaA;IACrB;AAqBF;AAHE,eAAA;IACE,MAAM,yBAAA,IAAI,EAAEA,kBAAN,IAAI;AACZ"}
@@ -0,0 +1,119 @@
1
+ function _check_private_redeclaration(obj, privateCollection) {
2
+ if (privateCollection.has(obj)) {
3
+ throw new TypeError("Cannot initialize the same private elements twice on an object");
4
+ }
5
+ }
6
+ function _class_apply_descriptor_get(receiver, descriptor) {
7
+ if (descriptor.get) {
8
+ return descriptor.get.call(receiver);
9
+ }
10
+ return descriptor.value;
11
+ }
12
+ function _class_apply_descriptor_set(receiver, descriptor, value) {
13
+ if (descriptor.set) {
14
+ descriptor.set.call(receiver, value);
15
+ } else {
16
+ if (!descriptor.writable) {
17
+ throw new TypeError("attempted to set read only private field");
18
+ }
19
+ descriptor.value = value;
20
+ }
21
+ }
22
+ function _class_extract_field_descriptor(receiver, privateMap, action) {
23
+ if (!privateMap.has(receiver)) {
24
+ throw new TypeError("attempted to " + action + " private field on non-instance");
25
+ }
26
+ return privateMap.get(receiver);
27
+ }
28
+ function _class_private_field_get(receiver, privateMap) {
29
+ var descriptor = _class_extract_field_descriptor(receiver, privateMap, "get");
30
+ return _class_apply_descriptor_get(receiver, descriptor);
31
+ }
32
+ function _class_private_field_init(obj, privateMap, value) {
33
+ _check_private_redeclaration(obj, privateMap);
34
+ privateMap.set(obj, value);
35
+ }
36
+ function _class_private_field_set(receiver, privateMap, value) {
37
+ var descriptor = _class_extract_field_descriptor(receiver, privateMap, "set");
38
+ _class_apply_descriptor_set(receiver, descriptor, value);
39
+ return value;
40
+ }
41
+ import { BasePostMessageStream } from '@metamask/post-message-stream';
42
+ import { isValidStreamMessage } from '@metamask/post-message-stream/dist/utils';
43
+ import { logError } from '@metamask/snaps-utils';
44
+ import { assert, bytesToBase64, stringToBytes } from '@metamask/utils';
45
+ var _name = /*#__PURE__*/ new WeakMap(), _target = /*#__PURE__*/ new WeakMap(), _webView = /*#__PURE__*/ new WeakMap();
46
+ /**
47
+ * A special postMessage stream used to interface with a WebView.
48
+ */ export class WebViewMessageStream extends BasePostMessageStream {
49
+ _postMessage(data) {
50
+ assert(_class_private_field_get(this, _webView));
51
+ const json = JSON.stringify({
52
+ target: _class_private_field_get(this, _target),
53
+ data
54
+ });
55
+ // To prevent XSS, we base64 encode the message before injecting it.
56
+ // This adds significant performance overhead.
57
+ // TODO: Should we use mobile native base64 here?
58
+ const bytes = stringToBytes(json);
59
+ const base64 = bytesToBase64(bytes);
60
+ _class_private_field_get(this, _webView).injectJavaScript(`window.postMessage('${base64}')`);
61
+ }
62
+ _onMessage(event) {
63
+ if (typeof event.data !== 'string') {
64
+ return;
65
+ }
66
+ const message = JSON.parse(event.data);
67
+ // Notice that we don't check targetWindow or targetOrigin here.
68
+ // This doesn't seem possible to do in RN.
69
+ if (!isValidStreamMessage(message) || message.target !== _class_private_field_get(this, _name)) {
70
+ return;
71
+ }
72
+ this._onData(message.data);
73
+ }
74
+ _destroy() {
75
+ assert(_class_private_field_get(this, _webView));
76
+ // This method is already bound.
77
+ // eslint-disable-next-line @typescript-eslint/unbound-method
78
+ _class_private_field_get(this, _webView).unregisterMessageListener(this._onMessage);
79
+ }
80
+ /**
81
+ * Creates a stream for communicating with other streams inside a WebView.
82
+ *
83
+ * @param args - Options bag.
84
+ * @param args.name - The name of the stream. Used to differentiate between
85
+ * multiple streams sharing the same window object.
86
+ * @param args.target - The name of the stream to exchange messages with.
87
+ * @param args.getWebView - A asynchronous getter for the webview.
88
+ */ constructor({ name, target, getWebView }){
89
+ super();
90
+ _class_private_field_init(this, _name, {
91
+ writable: true,
92
+ value: void 0
93
+ });
94
+ _class_private_field_init(this, _target, {
95
+ writable: true,
96
+ value: void 0
97
+ });
98
+ _class_private_field_init(this, _webView, {
99
+ writable: true,
100
+ value: void 0
101
+ });
102
+ _class_private_field_set(this, _name, name);
103
+ _class_private_field_set(this, _target, target);
104
+ this._onMessage = this._onMessage.bind(this);
105
+ // This is a bit atypical from other post-message streams.
106
+ // We have to wait for the WebView to fully load before we can continue using the stream.
107
+ getWebView().then((webView)=>{
108
+ _class_private_field_set(this, _webView, webView);
109
+ // This method is already bound.
110
+ // eslint-disable-next-line @typescript-eslint/unbound-method
111
+ webView.registerMessageListener(this._onMessage);
112
+ this._handshake();
113
+ }).catch((error)=>{
114
+ logError(error);
115
+ });
116
+ }
117
+ }
118
+
119
+ //# sourceMappingURL=WebViewMessageStream.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/services/webview/WebViewMessageStream.ts"],"sourcesContent":["import type { PostMessageEvent } from '@metamask/post-message-stream';\nimport { BasePostMessageStream } from '@metamask/post-message-stream';\nimport { isValidStreamMessage } from '@metamask/post-message-stream/dist/utils';\nimport { logError } from '@metamask/snaps-utils';\nimport { assert, bytesToBase64, stringToBytes } from '@metamask/utils';\n\nexport type WebViewInterface = {\n injectJavaScript(js: string): void;\n registerMessageListener(listener: (event: PostMessageEvent) => void): void;\n unregisterMessageListener(listener: (event: PostMessageEvent) => void): void;\n};\n\ntype WebViewStreamArgs = {\n name: string;\n target: string;\n getWebView: () => Promise<WebViewInterface>;\n};\n\n/**\n * A special postMessage stream used to interface with a WebView.\n */\n\nexport class WebViewMessageStream extends BasePostMessageStream {\n #name;\n\n #target;\n\n #webView: WebViewInterface | undefined;\n\n /**\n * Creates a stream for communicating with other streams inside a WebView.\n *\n * @param args - Options bag.\n * @param args.name - The name of the stream. Used to differentiate between\n * multiple streams sharing the same window object.\n * @param args.target - The name of the stream to exchange messages with.\n * @param args.getWebView - A asynchronous getter for the webview.\n */\n constructor({ name, target, getWebView }: WebViewStreamArgs) {\n super();\n\n this.#name = name;\n this.#target = target;\n\n this._onMessage = this._onMessage.bind(this);\n\n // This is a bit atypical from other post-message streams.\n // We have to wait for the WebView to fully load before we can continue using the stream.\n getWebView()\n .then((webView) => {\n this.#webView = webView;\n // This method is already bound.\n // eslint-disable-next-line @typescript-eslint/unbound-method\n webView.registerMessageListener(this._onMessage);\n this._handshake();\n })\n .catch((error) => {\n logError(error);\n });\n }\n\n protected _postMessage(data: unknown): void {\n assert(this.#webView);\n const json = JSON.stringify({\n target: this.#target,\n data,\n });\n\n // To prevent XSS, we base64 encode the message before injecting it.\n // This adds significant performance overhead.\n // TODO: Should we use mobile native base64 here?\n const bytes = stringToBytes(json);\n const base64 = bytesToBase64(bytes);\n this.#webView.injectJavaScript(`window.postMessage('${base64}')`);\n }\n\n private _onMessage(event: PostMessageEvent): void {\n if (typeof event.data !== 'string') {\n return;\n }\n\n const message = JSON.parse(event.data);\n\n // Notice that we don't check targetWindow or targetOrigin here.\n // This doesn't seem possible to do in RN.\n if (!isValidStreamMessage(message) || message.target !== this.#name) {\n return;\n }\n\n this._onData(message.data);\n }\n\n _destroy() {\n assert(this.#webView);\n // This method is already bound.\n // eslint-disable-next-line @typescript-eslint/unbound-method\n this.#webView.unregisterMessageListener(this._onMessage);\n }\n}\n"],"names":["BasePostMessageStream","isValidStreamMessage","logError","assert","bytesToBase64","stringToBytes","WebViewMessageStream","_postMessage","data","webView","json","JSON","stringify","target","bytes","base64","injectJavaScript","_onMessage","event","message","parse","name","_onData","_destroy","unregisterMessageListener","constructor","getWebView","bind","then","registerMessageListener","_handshake","catch","error"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAASA,qBAAqB,QAAQ,gCAAgC;AACtE,SAASC,oBAAoB,QAAQ,2CAA2C;AAChF,SAASC,QAAQ,QAAQ,wBAAwB;AACjD,SAASC,MAAM,EAAEC,aAAa,EAAEC,aAAa,QAAQ,kBAAkB;IAmBrE,qCAEA,uCAEA;AATF;;CAEC,GAED,OAAO,MAAMC,6BAA6BN;IAuC9BO,aAAaC,IAAa,EAAQ;QAC1CL,gCAAO,IAAI,EAAEM;QACb,MAAMC,OAAOC,KAAKC,SAAS,CAAC;YAC1BC,MAAM,2BAAE,IAAI,EAAEA;YACdL;QACF;QAEA,oEAAoE;QACpE,8CAA8C;QAC9C,iDAAiD;QACjD,MAAMM,QAAQT,cAAcK;QAC5B,MAAMK,SAASX,cAAcU;QAC7B,yBAAA,IAAI,EAAEL,UAAQO,gBAAgB,CAAC,CAAC,oBAAoB,EAAED,OAAO,EAAE,CAAC;IAClE;IAEQE,WAAWC,KAAuB,EAAQ;QAChD,IAAI,OAAOA,MAAMV,IAAI,KAAK,UAAU;YAClC;QACF;QAEA,MAAMW,UAAUR,KAAKS,KAAK,CAACF,MAAMV,IAAI;QAErC,gEAAgE;QAChE,0CAA0C;QAC1C,IAAI,CAACP,qBAAqBkB,YAAYA,QAAQN,MAAM,8BAAK,IAAI,EAAEQ,QAAM;YACnE;QACF;QAEA,IAAI,CAACC,OAAO,CAACH,QAAQX,IAAI;IAC3B;IAEAe,WAAW;QACTpB,gCAAO,IAAI,EAAEM;QACb,gCAAgC;QAChC,6DAA6D;QAC7D,yBAAA,IAAI,EAAEA,UAAQe,yBAAyB,CAAC,IAAI,CAACP,UAAU;IACzD;IApEA;;;;;;;;GAQC,GACDQ,YAAY,EAAEJ,IAAI,EAAER,MAAM,EAAEa,UAAU,EAAqB,CAAE;QAC3D,KAAK;QAhBP,gCAAA;;mBAAA,KAAA;;QAEA,gCAAA;;mBAAA,KAAA;;QAEA,gCAAA;;mBAAA,KAAA;;uCAcQL,OAAOA;uCACPR,SAASA;QAEf,IAAI,CAACI,UAAU,GAAG,IAAI,CAACA,UAAU,CAACU,IAAI,CAAC,IAAI;QAE3C,0DAA0D;QAC1D,yFAAyF;QACzFD,aACGE,IAAI,CAAC,CAACnB;2CACCA,UAAUA;YAChB,gCAAgC;YAChC,6DAA6D;YAC7DA,QAAQoB,uBAAuB,CAAC,IAAI,CAACZ,UAAU;YAC/C,IAAI,CAACa,UAAU;QACjB,GACCC,KAAK,CAAC,CAACC;YACN9B,SAAS8B;QACX;IACJ;AAuCF"}
@@ -0,0 +1,3 @@
1
+ export * from './WebViewExecutionService';
2
+
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/services/webview/index.ts"],"sourcesContent":["export * from './WebViewExecutionService';\n"],"names":[],"mappings":"AAAA,cAAc,4BAA4B"}