@dxos/plugin-script 0.6.13-staging.1e988a3 → 0.6.14-main.7bd9c89

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 (202) hide show
  1. package/README.md +1 -1
  2. package/dist/lib/browser/AutomationPanel-LJD3HE2U.mjs +78 -0
  3. package/dist/lib/browser/AutomationPanel-LJD3HE2U.mjs.map +7 -0
  4. package/dist/lib/browser/ScriptContainer-B3CPWXRE.mjs +423 -0
  5. package/dist/lib/browser/ScriptContainer-B3CPWXRE.mjs.map +7 -0
  6. package/dist/lib/browser/chunk-G66MXS4T.mjs +248 -0
  7. package/dist/lib/browser/chunk-G66MXS4T.mjs.map +7 -0
  8. package/dist/lib/browser/{chunk-RHEZ5LUU.mjs → chunk-G6H56WFS.mjs} +51 -2
  9. package/dist/lib/browser/{chunk-RHEZ5LUU.mjs.map → chunk-G6H56WFS.mjs.map} +4 -4
  10. package/dist/lib/browser/{chunk-DL5XQRQM.mjs → chunk-KHNN3F7J.mjs} +18 -6
  11. package/dist/lib/browser/chunk-KHNN3F7J.mjs.map +7 -0
  12. package/dist/lib/browser/{chunk-O4LWBX6A.mjs → chunk-KXVQPS4Y.mjs} +2 -2
  13. package/dist/lib/browser/{chunk-O4LWBX6A.mjs.map → chunk-KXVQPS4Y.mjs.map} +2 -2
  14. package/dist/lib/browser/chunk-SGQHRB4P.mjs +17 -0
  15. package/dist/lib/browser/chunk-SGQHRB4P.mjs.map +7 -0
  16. package/dist/lib/browser/edge/index.mjs +5 -1
  17. package/dist/lib/browser/index.mjs +86 -61
  18. package/dist/lib/browser/index.mjs.map +4 -4
  19. package/dist/lib/browser/meta.json +1 -1
  20. package/dist/lib/browser/meta.mjs +1 -1
  21. package/dist/lib/browser/types/index.mjs +2 -2
  22. package/dist/lib/node/AutomationPanel-2U3LW3J4.cjs +100 -0
  23. package/dist/lib/node/AutomationPanel-2U3LW3J4.cjs.map +7 -0
  24. package/dist/lib/node/ScriptContainer-BV7HMUY5.cjs +425 -0
  25. package/dist/lib/node/ScriptContainer-BV7HMUY5.cjs.map +7 -0
  26. package/dist/lib/node/{chunk-5RBVXKXT.cjs → chunk-25PQE7FL.cjs} +6 -6
  27. package/dist/lib/node/{chunk-5RBVXKXT.cjs.map → chunk-25PQE7FL.cjs.map} +2 -2
  28. package/dist/lib/node/{chunk-4GTXIELQ.cjs → chunk-ACLCRWDB.cjs} +44 -6
  29. package/dist/lib/node/chunk-ACLCRWDB.cjs.map +7 -0
  30. package/dist/lib/node/{TypescriptEditor-M3WWFIP2.cjs → chunk-EJC55SDD.cjs} +18 -8
  31. package/dist/lib/node/chunk-EJC55SDD.cjs.map +7 -0
  32. package/dist/lib/node/{chunk-PFH3ROEH.cjs → chunk-FY5KKL5N.cjs} +22 -8
  33. package/dist/lib/node/chunk-FY5KKL5N.cjs.map +7 -0
  34. package/dist/lib/node/chunk-JWKMTYYH.cjs +277 -0
  35. package/dist/lib/node/chunk-JWKMTYYH.cjs.map +7 -0
  36. package/dist/lib/node/edge/index.cjs +12 -8
  37. package/dist/lib/node/edge/index.cjs.map +2 -2
  38. package/dist/lib/node/index.cjs +103 -82
  39. package/dist/lib/node/index.cjs.map +4 -4
  40. package/dist/lib/node/meta.cjs +3 -3
  41. package/dist/lib/node/meta.cjs.map +1 -1
  42. package/dist/lib/node/meta.json +1 -1
  43. package/dist/lib/node/types/index.cjs +5 -5
  44. package/dist/lib/node/types/index.cjs.map +1 -1
  45. package/dist/lib/node-esm/AutomationPanel-FS47OF3I.mjs +79 -0
  46. package/dist/lib/node-esm/AutomationPanel-FS47OF3I.mjs.map +7 -0
  47. package/dist/lib/node-esm/ScriptContainer-HSIOGVP3.mjs +424 -0
  48. package/dist/lib/node-esm/ScriptContainer-HSIOGVP3.mjs.map +7 -0
  49. package/dist/lib/node-esm/chunk-3QHVR4VV.mjs +249 -0
  50. package/dist/lib/node-esm/chunk-3QHVR4VV.mjs.map +7 -0
  51. package/dist/lib/node-esm/chunk-7EDYDVQH.mjs +47 -0
  52. package/dist/lib/node-esm/chunk-7EDYDVQH.mjs.map +7 -0
  53. package/dist/lib/node-esm/chunk-GO7HYFM5.mjs +19 -0
  54. package/dist/lib/node-esm/chunk-GO7HYFM5.mjs.map +7 -0
  55. package/dist/lib/node-esm/chunk-LDLNTVAK.mjs +280 -0
  56. package/dist/lib/node-esm/chunk-LDLNTVAK.mjs.map +7 -0
  57. package/dist/lib/node-esm/chunk-QMTTZYLF.mjs +255 -0
  58. package/dist/lib/node-esm/chunk-QMTTZYLF.mjs.map +7 -0
  59. package/dist/lib/node-esm/edge/index.mjs +24 -0
  60. package/dist/lib/node-esm/index.mjs +317 -0
  61. package/dist/lib/node-esm/index.mjs.map +7 -0
  62. package/dist/lib/node-esm/meta.json +1 -0
  63. package/dist/lib/node-esm/meta.mjs +10 -0
  64. package/dist/lib/node-esm/meta.mjs.map +7 -0
  65. package/dist/lib/node-esm/types/index.mjs +13 -0
  66. package/dist/lib/node-esm/types/index.mjs.map +7 -0
  67. package/dist/types/src/ScriptPlugin.d.ts.map +1 -1
  68. package/dist/types/src/components/AutomationPanel/AutomationPanel.d.ts +17 -0
  69. package/dist/types/src/components/AutomationPanel/AutomationPanel.d.ts.map +1 -0
  70. package/dist/types/src/components/AutomationPanel/index.d.ts +4 -0
  71. package/dist/types/src/components/AutomationPanel/index.d.ts.map +1 -0
  72. package/dist/types/src/components/{DebugPanel.d.ts → DebugPanel/DebugPanel.d.ts} +2 -1
  73. package/dist/types/src/components/DebugPanel/DebugPanel.d.ts.map +1 -0
  74. package/dist/types/src/components/DebugPanel/index.d.ts +2 -0
  75. package/dist/types/src/components/DebugPanel/index.d.ts.map +1 -0
  76. package/dist/types/src/components/{ScriptBlock/FrameContainer → FrameContainer}/FrameContainer.d.ts +1 -1
  77. package/dist/types/src/components/FrameContainer/FrameContainer.d.ts.map +1 -0
  78. package/dist/types/src/components/FrameContainer/frame.d.ts.map +1 -0
  79. package/dist/types/src/components/FrameContainer/index.d.ts.map +1 -0
  80. package/dist/types/src/components/ScriptBlock/ScriptBlock.d.ts +1 -3
  81. package/dist/types/src/components/ScriptBlock/ScriptBlock.d.ts.map +1 -1
  82. package/dist/types/src/components/ScriptBlock/ScriptBlock.stories.d.ts +3 -8
  83. package/dist/types/src/components/ScriptBlock/ScriptBlock.stories.d.ts.map +1 -1
  84. package/dist/types/src/components/ScriptContainer.d.ts +5 -0
  85. package/dist/types/src/components/ScriptContainer.d.ts.map +1 -0
  86. package/dist/types/src/components/ScriptEditor.d.ts +4 -5
  87. package/dist/types/src/components/ScriptEditor.d.ts.map +1 -1
  88. package/dist/types/src/components/ScriptSettings/ScriptSettings.d.ts +6 -0
  89. package/dist/types/src/components/ScriptSettings/ScriptSettings.d.ts.map +1 -0
  90. package/dist/types/src/components/ScriptSettings/index.d.ts +2 -0
  91. package/dist/types/src/components/ScriptSettings/index.d.ts.map +1 -0
  92. package/dist/types/src/components/Toolbar/Toolbar.d.ts +23 -0
  93. package/dist/types/src/components/Toolbar/Toolbar.d.ts.map +1 -0
  94. package/dist/types/src/components/Toolbar/Toolbar.stories.d.ts +14 -0
  95. package/dist/types/src/components/Toolbar/Toolbar.stories.d.ts.map +1 -0
  96. package/dist/types/src/components/Toolbar/index.d.ts +2 -0
  97. package/dist/types/src/components/Toolbar/index.d.ts.map +1 -0
  98. package/dist/types/src/components/{TypescriptEditor.d.ts → TypescriptEditor/TypescriptEditor.d.ts} +1 -2
  99. package/dist/types/src/components/TypescriptEditor/TypescriptEditor.d.ts.map +1 -0
  100. package/dist/types/src/components/TypescriptEditor/TypescriptEditor.stories.d.ts +6 -0
  101. package/dist/types/src/components/TypescriptEditor/TypescriptEditor.stories.d.ts.map +1 -0
  102. package/dist/types/src/components/TypescriptEditor/index.d.ts +2 -0
  103. package/dist/types/src/components/TypescriptEditor/index.d.ts.map +1 -0
  104. package/dist/types/src/components/index.d.ts +3 -3
  105. package/dist/types/src/components/index.d.ts.map +1 -1
  106. package/dist/types/src/edge/functions.d.ts +7 -0
  107. package/dist/types/src/edge/functions.d.ts.map +1 -1
  108. package/dist/types/src/meta.d.ts +4 -9
  109. package/dist/types/src/meta.d.ts.map +1 -1
  110. package/dist/types/src/templates/chat.d.ts +6 -0
  111. package/dist/types/src/templates/chat.d.ts.map +1 -0
  112. package/dist/types/src/templates/chess.d.ts +6 -0
  113. package/dist/types/src/templates/chess.d.ts.map +1 -0
  114. package/dist/types/src/templates/echo.d.ts +6 -0
  115. package/dist/types/src/templates/echo.d.ts.map +1 -0
  116. package/dist/types/src/templates/email.d.ts +6 -0
  117. package/dist/types/src/templates/email.d.ts.map +1 -0
  118. package/dist/types/src/templates/forex.d.ts +6 -0
  119. package/dist/types/src/templates/forex.d.ts.map +1 -0
  120. package/dist/types/src/templates.d.ts +8 -0
  121. package/dist/types/src/templates.d.ts.map +1 -0
  122. package/dist/types/src/translations.d.ts +2 -0
  123. package/dist/types/src/translations.d.ts.map +1 -1
  124. package/dist/types/src/types/script.d.ts +4 -4
  125. package/dist/types/src/types/types.d.ts +4 -3
  126. package/dist/types/src/types/types.d.ts.map +1 -1
  127. package/package.json +61 -55
  128. package/src/ScriptPlugin.tsx +26 -39
  129. package/src/bundler/bundler.test.ts +12 -2
  130. package/src/components/AutomationPanel/AutomationPanel.tsx +101 -0
  131. package/src/components/AutomationPanel/index.ts +9 -0
  132. package/src/components/{DebugPanel.tsx → DebugPanel/DebugPanel.tsx} +83 -78
  133. package/src/components/DebugPanel/index.ts +5 -0
  134. package/src/components/{ScriptBlock/FrameContainer → FrameContainer}/FrameContainer.tsx +1 -1
  135. package/src/components/ScriptBlock/ScriptBlock.stories.tsx +14 -13
  136. package/src/components/ScriptBlock/ScriptBlock.tsx +23 -51
  137. package/src/components/ScriptContainer.tsx +22 -0
  138. package/src/components/ScriptEditor.tsx +58 -55
  139. package/src/components/ScriptSettings/ScriptSettings.tsx +47 -0
  140. package/src/components/ScriptSettings/index.ts +5 -0
  141. package/src/components/Toolbar/Toolbar.stories.tsx +30 -0
  142. package/src/components/Toolbar/Toolbar.tsx +177 -0
  143. package/src/components/{ScriptBlock/Splitter → Toolbar}/index.ts +1 -1
  144. package/src/components/{TypescriptEditor.stories.tsx → TypescriptEditor/TypescriptEditor.stories.tsx} +17 -35
  145. package/src/components/{TypescriptEditor.tsx → TypescriptEditor/TypescriptEditor.tsx} +1 -3
  146. package/src/components/TypescriptEditor/index.ts +5 -0
  147. package/src/components/index.ts +5 -3
  148. package/src/edge/functions.ts +19 -0
  149. package/src/meta.ts +15 -0
  150. package/src/templates/chat.ts +102 -0
  151. package/src/templates/chess.ts +41 -0
  152. package/src/templates/echo.ts +15 -0
  153. package/src/templates/email.ts +38 -0
  154. package/src/templates/forex.ts +21 -0
  155. package/src/templates.ts +54 -0
  156. package/src/translations.ts +2 -0
  157. package/src/types/types.ts +9 -5
  158. package/dist/lib/browser/ScriptEditor-5Y3EROG3.mjs +0 -513
  159. package/dist/lib/browser/ScriptEditor-5Y3EROG3.mjs.map +0 -7
  160. package/dist/lib/browser/TypescriptEditor-GPE72Y6I.mjs +0 -9
  161. package/dist/lib/browser/chunk-DL5XQRQM.mjs.map +0 -7
  162. package/dist/lib/browser/chunk-JBACGDOJ.mjs +0 -21
  163. package/dist/lib/browser/chunk-JBACGDOJ.mjs.map +0 -7
  164. package/dist/lib/browser/chunk-MRGOT5RF.mjs +0 -78
  165. package/dist/lib/browser/chunk-MRGOT5RF.mjs.map +0 -7
  166. package/dist/lib/node/ScriptEditor-YCUQFWQM.cjs +0 -526
  167. package/dist/lib/node/ScriptEditor-YCUQFWQM.cjs.map +0 -7
  168. package/dist/lib/node/TypescriptEditor-M3WWFIP2.cjs.map +0 -7
  169. package/dist/lib/node/chunk-4GTXIELQ.cjs.map +0 -7
  170. package/dist/lib/node/chunk-4VMNBXWU.cjs +0 -54
  171. package/dist/lib/node/chunk-4VMNBXWU.cjs.map +0 -7
  172. package/dist/lib/node/chunk-IMLDKD5Y.cjs +0 -111
  173. package/dist/lib/node/chunk-IMLDKD5Y.cjs.map +0 -7
  174. package/dist/lib/node/chunk-PFH3ROEH.cjs.map +0 -7
  175. package/dist/types/src/components/DebugPanel.d.ts.map +0 -1
  176. package/dist/types/src/components/ScriptBlock/FrameContainer/FrameContainer.d.ts.map +0 -1
  177. package/dist/types/src/components/ScriptBlock/FrameContainer/frame.d.ts.map +0 -1
  178. package/dist/types/src/components/ScriptBlock/FrameContainer/index.d.ts.map +0 -1
  179. package/dist/types/src/components/ScriptBlock/Splitter/Splitter.d.ts +0 -15
  180. package/dist/types/src/components/ScriptBlock/Splitter/Splitter.d.ts.map +0 -1
  181. package/dist/types/src/components/ScriptBlock/Splitter/Splitter.stories.d.ts +0 -13
  182. package/dist/types/src/components/ScriptBlock/Splitter/Splitter.stories.d.ts.map +0 -1
  183. package/dist/types/src/components/ScriptBlock/Splitter/index.d.ts +0 -2
  184. package/dist/types/src/components/ScriptBlock/Splitter/index.d.ts.map +0 -1
  185. package/dist/types/src/components/Toolbar.d.ts +0 -13
  186. package/dist/types/src/components/Toolbar.d.ts.map +0 -1
  187. package/dist/types/src/components/Toolbar.stories.d.ts +0 -14
  188. package/dist/types/src/components/Toolbar.stories.d.ts.map +0 -1
  189. package/dist/types/src/components/TypescriptEditor.d.ts.map +0 -1
  190. package/dist/types/src/components/TypescriptEditor.stories.d.ts +0 -10
  191. package/dist/types/src/components/TypescriptEditor.stories.d.ts.map +0 -1
  192. package/src/components/ScriptBlock/Splitter/Splitter.stories.tsx +0 -37
  193. package/src/components/ScriptBlock/Splitter/Splitter.tsx +0 -52
  194. package/src/components/Toolbar.stories.tsx +0 -17
  195. package/src/components/Toolbar.tsx +0 -147
  196. package/src/meta.tsx +0 -19
  197. /package/dist/lib/{browser/TypescriptEditor-GPE72Y6I.mjs.map → node-esm/edge/index.mjs.map} +0 -0
  198. /package/dist/types/src/components/{ScriptBlock/FrameContainer → FrameContainer}/frame.d.ts +0 -0
  199. /package/dist/types/src/components/{ScriptBlock/FrameContainer → FrameContainer}/index.d.ts +0 -0
  200. /package/src/components/{ScriptBlock/FrameContainer → FrameContainer}/frame.html +0 -0
  201. /package/src/components/{ScriptBlock/FrameContainer → FrameContainer}/frame.tsx +0 -0
  202. /package/src/components/{ScriptBlock/FrameContainer → FrameContainer}/index.ts +0 -0
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/types/script.ts", "../../../src/types/types.ts"],
4
- "sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { ref, S, TypedObject } from '@dxos/echo-schema';\nimport { TextType } from '@dxos/plugin-markdown/types';\n\n// TODO(burdon): Which is the outer type? I.e., in the navbar?\n\n/**\n * Source script.\n */\nexport class ScriptType extends TypedObject({ typename: 'dxos.org/type/Script', version: '0.1.0' })({\n // TODO(burdon): Change to URI?\n name: S.optional(S.String),\n description: S.optional(S.String),\n source: ref(TextType),\n // TODO(burdon): Change to has of deployed content.\n // Whether source has changed since last deploy.\n changed: S.optional(S.Boolean),\n}) {}\n\n/**\n * Function deployment.\n */\nexport class FunctionType extends TypedObject({ typename: 'dxos.org/type/Function', version: '0.1.0' })({\n name: S.optional(S.String),\n version: S.Number,\n // Local binding to a function name.\n // TODO(burdon): Move binding to inner type.\n binding: S.optional(S.String),\n // Reference to a source script if it exists within ECHO.\n source: S.optional(ref(ScriptType)),\n}) {}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport type {\n GraphBuilderProvides,\n IntentResolverProvides,\n MetadataRecordsProvides,\n SurfaceProvides,\n TranslationsProvides,\n} from '@dxos/app-framework';\nimport { type SchemaProvides } from '@dxos/plugin-client';\nimport { type StackProvides } from '@dxos/plugin-stack';\n\nimport { SCRIPT_PLUGIN } from '../meta';\n\nexport enum ScriptAction {\n CREATE = `${SCRIPT_PLUGIN}/create`,\n}\n\nexport type ScriptPluginProvides = SurfaceProvides &\n IntentResolverProvides &\n GraphBuilderProvides &\n MetadataRecordsProvides &\n TranslationsProvides &\n SchemaProvides &\n StackProvides;\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,yBAAoC;AACpC,mBAAyB;AAOlB,IAAMA,aAAN,kBAAyBC,gCAAY;EAAEC,UAAU;EAAwBC,SAAS;AAAQ,CAAA,EAAG;;EAElGC,MAAMC,qBAAEC,SAASD,qBAAEE,MAAM;EACzBC,aAAaH,qBAAEC,SAASD,qBAAEE,MAAM;EAChCE,YAAQC,wBAAIC,qBAAAA;;;EAGZC,SAASP,qBAAEC,SAASD,qBAAEQ,OAAO;AAC/B,CAAA,EAAA;AAAI;AAKG,IAAMC,eAAN,kBAA2Bb,gCAAY;EAAEC,UAAU;EAA0BC,SAAS;AAAQ,CAAA,EAAG;EACtGC,MAAMC,qBAAEC,SAASD,qBAAEE,MAAM;EACzBJ,SAASE,qBAAEU;;;EAGXC,SAASX,qBAAEC,SAASD,qBAAEE,MAAM;;EAE5BE,QAAQJ,qBAAEC,aAASI,wBAAIV,UAAAA,CAAAA;AACzB,CAAA,EAAA;AAAI;;UCjBQiB,eAAAA;0CACD,GAAGC,mCAAAA,SAAsB,IAAA;GADxBD,iBAAAA,eAAAA,CAAAA,EAAAA;",
4
+ "sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { ref, S, TypedObject } from '@dxos/echo-schema';\nimport { TextType } from '@dxos/plugin-markdown/types';\n\n// TODO(burdon): Which is the outer type? I.e., in the navbar?\n\n/**\n * Source script.\n */\nexport class ScriptType extends TypedObject({ typename: 'dxos.org/type/Script', version: '0.1.0' })({\n // TODO(burdon): Change to URI?\n name: S.optional(S.String),\n description: S.optional(S.String),\n source: ref(TextType),\n // TODO(burdon): Change to has of deployed content.\n // Whether source has changed since last deploy.\n changed: S.optional(S.Boolean),\n}) {}\n\n/**\n * Function deployment.\n */\nexport class FunctionType extends TypedObject({ typename: 'dxos.org/type/Function', version: '0.1.0' })({\n name: S.optional(S.String),\n version: S.Number,\n // Local binding to a function name.\n // TODO(burdon): Move binding to inner type.\n binding: S.optional(S.String),\n // Reference to a source script if it exists within ECHO.\n source: S.optional(ref(ScriptType)),\n}) {}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport type {\n GraphBuilderProvides,\n IntentResolverProvides,\n MetadataRecordsProvides,\n SettingsProvides,\n SurfaceProvides,\n TranslationsProvides,\n} from '@dxos/app-framework';\nimport { type SchemaProvides } from '@dxos/plugin-client';\nimport { type SpaceInitProvides } from '@dxos/plugin-space';\n\nimport { SCRIPT_PLUGIN } from '../meta';\n\nexport enum ScriptAction {\n CREATE = `${SCRIPT_PLUGIN}/create`,\n}\n\nexport type ScriptSettingsProps = {};\n\nexport type ScriptPluginProvides = GraphBuilderProvides &\n IntentResolverProvides &\n MetadataRecordsProvides &\n SchemaProvides &\n SettingsProvides<ScriptSettingsProps> &\n SpaceInitProvides &\n SurfaceProvides &\n TranslationsProvides;\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,yBAAoC;AACpC,mBAAyB;AAOlB,IAAMA,aAAN,kBAAyBC,gCAAY;EAAEC,UAAU;EAAwBC,SAAS;AAAQ,CAAA,EAAG;;EAElGC,MAAMC,qBAAEC,SAASD,qBAAEE,MAAM;EACzBC,aAAaH,qBAAEC,SAASD,qBAAEE,MAAM;EAChCE,YAAQC,wBAAIC,qBAAAA;;;EAGZC,SAASP,qBAAEC,SAASD,qBAAEQ,OAAO;AAC/B,CAAA,EAAA;AAAI;AAKG,IAAMC,eAAN,kBAA2Bb,gCAAY;EAAEC,UAAU;EAA0BC,SAAS;AAAQ,CAAA,EAAG;EACtGC,MAAMC,qBAAEC,SAASD,qBAAEE,MAAM;EACzBJ,SAASE,qBAAEU;;;EAGXC,SAASX,qBAAEC,SAASD,qBAAEE,MAAM;;EAE5BE,QAAQJ,qBAAEC,aAASI,wBAAIV,UAAAA,CAAAA;AACzB,CAAA,EAAA;AAAI;;UChBQiB,eAAAA;0CACD,GAAGC,mCAAAA,SAAsB,IAAA;GADxBD,iBAAAA,eAAAA,CAAAA,EAAAA;",
6
6
  "names": ["ScriptType", "TypedObject", "typename", "version", "name", "S", "optional", "String", "description", "source", "ref", "TextType", "changed", "Boolean", "FunctionType", "Number", "binding", "ScriptAction", "SCRIPT_PLUGIN"]
7
7
  }
@@ -16,12 +16,13 @@ var __copyProps = (to, from, except, desc) => {
16
16
  return to;
17
17
  };
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var chunk_4GTXIELQ_exports = {};
20
- __export(chunk_4GTXIELQ_exports, {
19
+ var chunk_ACLCRWDB_exports = {};
20
+ __export(chunk_ACLCRWDB_exports, {
21
21
  Bundler: () => Bundler,
22
- initializeBundler: () => initializeBundler
22
+ initializeBundler: () => initializeBundler,
23
+ templates: () => templates
23
24
  });
24
- module.exports = __toCommonJS(chunk_4GTXIELQ_exports);
25
+ module.exports = __toCommonJS(chunk_ACLCRWDB_exports);
25
26
  var import_esbuild_wasm = require("esbuild-wasm");
26
27
  var import_crypto = require("@dxos/crypto");
27
28
  var import_invariant = require("@dxos/invariant");
@@ -244,9 +245,46 @@ var httpPlugin = {
244
245
  });
245
246
  }
246
247
  };
248
+ var chat_default = "//\n// Copyright 2024 DXOS.org\n//\n\n// @ts-ignore\nimport { transformServerSentEvents } from 'https://esm.sh/@dxos/script-toolbox';\n\n/**\n * Chatbot that answers questions based on the context data.\n */\nexport default async ({\n event: {\n data: { request },\n },\n context: { space, ai },\n}: any) => {\n const textBody = await request.text();\n let parsedRequest: any;\n try {\n parsedRequest = JSON.parse(textBody);\n } catch (err) {\n const answer = await ai.run('@cf/meta/llama-3.1-8b-instruct', {\n stream: true,\n prompt: `\n Using only the context data below to answer the user's question.\n If you cannot answer the question from the provided content, then reply with \"I don't know.\"\n\n CONTEXT:\n ${await getContext({ space })}\n\n QUESTION:\n ${textBody}\n `,\n });\n return new Response(transformServerSentEvents(answer));\n }\n\n const promptId = parsedRequest.trigger.promptId;\n const promptObject = await space.crud.query({ id: promptId }).first();\n\n if (parsedRequest.data.objects.length !== 1) {\n return new Response('Message batches not supported.');\n }\n\n const messageId = parsedRequest.data.objects[0];\n let message;\n try {\n message = await space.crud.query({ id: messageId }).first();\n } catch (err) {\n return new Response('Message not replicated yet.', { status: 409 });\n }\n\n if (message.text.includes('--------')) {\n return new Response('Message was already processed.');\n }\n\n let prompt = promptObject.template;\n for (const input of promptObject.inputs) {\n let value: string | null = null;\n if (input.type === ChainInputType.VALUE) {\n value = String(input.value);\n } else if (input.type === ChainInputType.RETRIEVER) {\n value = await getContext({ space });\n } else if (input.type === ChainInputType.PASS_THROUGH) {\n value = message.text;\n }\n if (value) {\n prompt = prompt.replaceAll(`{${input.name}}`, value);\n }\n }\n\n const answer = await ai.run('@cf/meta/llama-3.1-8b-instruct', {\n stream: false,\n prompt,\n });\n const response = { response: answer.response, prompt, message };\n const textWithAnswer = message.text + '\\n--------\\n\\n' + answer.response;\n await space.crud.update({ id: messageId }, { text: textWithAnswer });\n\n return new Response(JSON.stringify(response));\n};\n\nconst getContext = async ({ space }: any) => {\n let context = '';\n const { objects: docs } = await space.crud.query({ __typename: 'dxos.org/type/Document' }).run();\n for (const doc of docs) {\n const { content } = await space.crud.query({ id: doc.content }).first();\n context += content + '\\n\\n';\n }\n return context;\n};\n\nenum ChainInputType {\n VALUE = 0,\n PASS_THROUGH = 1,\n RETRIEVER = 2,\n FUNCTION = 3,\n QUERY = 4,\n RESOLVER = 5,\n CONTEXT = 6,\n SCHEMA = 7,\n}\n";
249
+ var chess_default = "//\n// Copyright 2024 DXOS.org\n//\n\n// @ts-ignore\nimport { Chess } from 'https://esm.sh/chess.js@0.13.1';\n\n/**\n * Plays a random move in a chess game.\n */\nexport default async ({\n event: {\n data: { request },\n },\n context: { space },\n}: any) => {\n const {\n data: {\n objects: [gameId],\n player = 'b',\n },\n } = await request.json();\n\n const { pgn } = await space.crud.query({ id: gameId }).first();\n const game = new Chess();\n game.load_pgn(pgn);\n if (game.turn() !== player) {\n return new Response('Invalid turn', { status: 409 });\n }\n\n const moves = game.moves();\n const move = moves[Math.floor(Math.random() * moves.length)];\n if (!move) {\n return new Response('No legal moves', { status: 406 });\n }\n\n game.move(move);\n const newPgn = game.pgn();\n await space.crud.update({ id: gameId }, { pgn: newPgn });\n return new Response(game.ascii());\n};\n";
250
+ var echo_default = "//\n// Copyright 2024 DXOS.org\n//\n\n/**\n * Echos the request data.\n */\nexport default async ({\n event: {\n data: { request },\n },\n}: any) => {\n const data = await request.json();\n return new Response(JSON.stringify(data ?? {}), { headers: { 'Content-Type': 'application/json' } });\n};\n";
251
+ var email_default = "//\n// Copyright 2024 DXOS.org\n//\n\n/**\n * Stores a message into ECHO Mailbox object.\n */\nexport default async ({\n event: {\n data: { request },\n },\n context: { space },\n}: any) => {\n const {\n data: {\n objects: [message],\n },\n } = await request.json();\n\n const mailbox = await space.crud.query({ __typename: 'dxos.org/type/MailboxType' }).first();\n if (!mailbox) {\n return new Response('Mailbox not found.', { status: 500 });\n }\n\n await space.crud.push(\n { id: mailbox.id },\n {\n sender: { email: message.from },\n timestamp: new Date(message.created).toISOString(),\n text: message.body,\n properties: {\n subject: message.subject,\n to: [{ email: message.to }],\n },\n },\n );\n return new Response(JSON.stringify(message));\n};\n";
252
+ var forex_default = "//\n// Copyright 2024 DXOS.org\n//\n\n/**\n * Returns the exchange rate between two currencies.\n */\nexport default async ({\n event: {\n data: { request },\n },\n}: any) => {\n const { args: [from = 'EUR', to = 'USD'] = [] } = await request.json();\n\n const res = await fetch(`https://free.ratesdb.com/v1/rates?from=${from}&to=${to}`);\n const {\n data: { rates },\n } = await res.json();\n\n return new Response(rates[to].toString());\n};\n";
253
+ var removeHeader = (str) => str.split("\n").slice(4).join("\n");
254
+ var templates = [
255
+ {
256
+ id: "dxos.org/script/echo",
257
+ name: "Echo",
258
+ source: removeHeader(echo_default)
259
+ },
260
+ {
261
+ id: "dxos.org/script/forex",
262
+ name: "Forex",
263
+ source: removeHeader(forex_default)
264
+ },
265
+ {
266
+ id: "dxos.org/script/gpt",
267
+ name: "Gpt",
268
+ source: removeHeader(chat_default),
269
+ presetId: "dxos.org/function/gpt"
270
+ },
271
+ {
272
+ id: "dxos.org/script/chess",
273
+ name: "Chess",
274
+ source: removeHeader(chess_default),
275
+ presetId: "dxos.org/function/chess"
276
+ },
277
+ {
278
+ id: "dxos.org/script/email",
279
+ name: "Email",
280
+ source: removeHeader(email_default),
281
+ presetId: "dxos.org/function/email"
282
+ }
283
+ ];
247
284
  // Annotate the CommonJS export names for ESM import in node:
248
285
  0 && (module.exports = {
249
286
  Bundler,
250
- initializeBundler
287
+ initializeBundler,
288
+ templates
251
289
  });
252
- //# sourceMappingURL=chunk-4GTXIELQ.cjs.map
290
+ //# sourceMappingURL=chunk-ACLCRWDB.cjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/bundler/bundler.ts", "raw-loader:./templates/chat.ts?raw", "raw-loader:./templates/chess.ts?raw", "raw-loader:./templates/echo.ts?raw", "raw-loader:./templates/email.ts?raw", "raw-loader:./templates/forex.ts?raw", "../../../src/templates.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport { type BuildOptions } from 'esbuild';\nimport { build, initialize, type BuildResult, type Plugin } from 'esbuild-wasm';\n\nimport { subtleCrypto } from '@dxos/crypto';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\n\nexport type Import = {\n moduleUrl: string;\n defaultImport: boolean;\n namedImports: string[];\n};\n\nexport type BundlerResult = {\n timestamp: number;\n sourceHash: Buffer;\n imports?: Import[];\n bundle?: string;\n error?: any;\n};\n\nexport type BundlerOptions = {\n platform: BuildOptions['platform'];\n sandboxedModules: string[];\n remoteModules: Record<string, string>;\n};\n\nlet initialized: Promise<void>;\nexport const initializeBundler = async (options: { wasmUrl: string }) => {\n await (initialized ??= initialize({\n wasmURL: options.wasmUrl,\n }));\n};\n\n/**\n * ESBuild bundler.\n */\nexport class Bundler {\n constructor(private readonly _options: BundlerOptions) {}\n\n async bundle(source: string): Promise<BundlerResult> {\n const { sandboxedModules: providedModules, ...options } = this._options;\n\n const createResult = async (result?: Partial<BundlerResult>) => {\n return {\n timestamp: Date.now(),\n sourceHash: Buffer.from(await subtleCrypto.digest('SHA-256', Buffer.from(source))),\n ...result,\n };\n };\n\n if (this._options.platform === 'browser') {\n invariant(initialized, 'Compiler not initialized.');\n await initialized;\n }\n\n const imports = analyzeSourceFileImports(source);\n\n // https://esbuild.github.io/api/#build\n try {\n const result = await build({\n platform: options.platform,\n conditions: ['workerd', 'browser'],\n metafile: true,\n write: false,\n entryPoints: ['memory:main.tsx'],\n bundle: true,\n format: 'esm',\n plugins: [\n {\n name: 'memory',\n setup: (build) => {\n build.onResolve({ filter: /^\\.\\/runtime\\.js$/ }, ({ path }) => {\n return { path, external: true };\n });\n\n build.onResolve({ filter: /^memory:/ }, ({ path }) => {\n return { path: path.split(':')[1], namespace: 'memory' };\n });\n\n build.onLoad({ filter: /.*/, namespace: 'memory' }, ({ path }) => {\n if (path === 'main.tsx') {\n return {\n contents: source,\n loader: 'tsx',\n };\n }\n });\n\n for (const module of providedModules) {\n build.onResolve({ filter: new RegExp(`^${module}$`) }, ({ path }) => {\n return { path, namespace: 'injected-module' };\n });\n }\n\n build.onLoad({ filter: /.*/, namespace: 'injected-module' }, ({ path }) => {\n const namedImports = imports.find((entry) => entry.moduleIdentifier === path)?.namedImports ?? [];\n return {\n contents: `\n const { ${namedImports.join(',')} } = window.__DXOS_SANDBOX_MODULES__[${JSON.stringify(path)}];\n export { ${namedImports.join(',')} };\n export default window.__DXOS_SANDBOX_MODULES__[${JSON.stringify(path)}].default;\n `,\n loader: 'tsx',\n };\n });\n },\n },\n httpPlugin,\n ],\n });\n\n log('compile complete', result.metafile);\n\n return await createResult({\n imports: this.analyzeImports(result),\n bundle: result.outputFiles![0].text,\n });\n } catch (err) {\n return await createResult({ error: err });\n }\n }\n\n // TODO(dmaretskyi): In the future we can replace the compiler with SWC with plugins running in WASM.\n analyzeImports(result: BuildResult): Import[] {\n invariant(result.outputFiles);\n\n // TODO(dmaretskyi): Support import aliases and wildcard imports.\n const parsedImports = allMatches(IMPORT_REGEX, result.outputFiles[0].text);\n return Object.values(result.metafile!.outputs)[0].imports.map((entry): Import => {\n const namedImports: string[] = [];\n\n const parsedImport = parsedImports.find((capture) => capture?.[4] === entry.path);\n if (parsedImport?.[2]) {\n NAMED_IMPORTS_REGEX.lastIndex = 0;\n const namedImportsMatch = NAMED_IMPORTS_REGEX.exec(parsedImport[2]);\n if (namedImportsMatch) {\n namedImportsMatch[1].split(',').forEach((importName) => {\n namedImports.push(importName.trim());\n });\n }\n }\n\n return {\n moduleUrl: entry.path,\n defaultImport: !!parsedImport?.[1],\n namedImports,\n };\n });\n }\n\n analyzeSourceFileImports(code: string) {\n // TODO(dmaretskyi): Support import aliases and wildcard imports.\n const parsedImports = allMatches(IMPORT_REGEX, code);\n return parsedImports.map((capture) => {\n return {\n defaultImportName: capture[1],\n namedImports: capture[2]?.split(',').map((importName) => importName.trim()),\n wildcardImportName: capture[3],\n moduleIdentifier: capture[4],\n quotes: capture[5],\n };\n });\n }\n}\n\n// https://regex101.com/r/FEN5ks/1\n// https://stackoverflow.com/a/73265022\n// $1 = default import name (can be non-existent)\n// $2 = destructured exports (can be non-existent)\n// $3 = wildcard import name (can be non-existent)\n// $4 = module identifier\n// $5 = quotes used (either ' or \")\nconst IMPORT_REGEX =\n /import(?:(?:(?:[ \\n\\t]+([^ *\\n\\t{},]+)[ \\n\\t]*(?:,|[ \\n\\t]+))?([ \\n\\t]*{(?:[ \\n\\t]*[^ \\n\\t\"'{}]+[ \\n\\t]*,?)+})?[ \\n\\t]*)|[ \\n\\t]*\\*[ \\n\\t]*as[ \\n\\t]+([^ \\n\\t{}]+)[ \\n\\t]+)from[ \\n\\t]*(?:['\"])([^'\"\\n]+)(['\"])/gm;\n\nconst NAMED_IMPORTS_REGEX = /[ \\n\\t]*{((?:[ \\n\\t]*[^ \\n\\t\"'{}]+[ \\n\\t]*,?)+)}[ \\n\\t]*/gm;\n\nconst allMatches = (regex: RegExp, str: string) => {\n regex.lastIndex = 0;\n\n let match;\n const matches = [];\n while ((match = regex.exec(str))) {\n matches.push(match);\n }\n\n return matches;\n};\n\ntype ParsedImport = {\n defaultImportName?: string;\n namedImports: string[];\n wildcardImportName?: string;\n moduleIdentifier: string;\n quotes: string;\n};\n\nconst analyzeSourceFileImports = (code: string): ParsedImport[] => {\n // TODO(dmaretskyi): Support import aliases and wildcard imports.\n const parsedImports = allMatches(IMPORT_REGEX, code);\n return parsedImports.map((capture) => {\n return {\n defaultImportName: capture[1],\n namedImports: capture[2]\n ?.trim()\n .slice(1, -1)\n .split(',')\n .map((importName) => importName.trim()),\n wildcardImportName: capture[3],\n moduleIdentifier: capture[4],\n quotes: capture[5],\n };\n });\n};\n\nconst httpPlugin: Plugin = {\n name: 'http',\n setup: (build) => {\n // Intercept import paths starting with \"http:\" and \"https:\" so esbuild doesn't attempt to map them to a file system location.\n // Tag them with the \"http-url\" namespace to associate them with this plugin.\n build.onResolve({ filter: /^https?:\\/\\// }, (args) => ({\n path: args.path,\n namespace: 'http-url',\n }));\n\n // We also want to intercept all import paths inside downloaded files and resolve them against the original URL.\n // All of these files will be in the \"http-url\" namespace.\n // Make sure to keep the newly resolved URL in the \"http-url\" namespace so imports inside it will also be resolved as URLs recursively.\n build.onResolve({ filter: /.*/, namespace: 'http-url' }, (args) => ({\n path: new URL(args.path, args.importer).toString(),\n namespace: 'http-url',\n }));\n\n // When a URL is loaded, we want to actually download the content from the internet.\n // This has just enough logic to be able to handle the example import from unpkg.com but in reality this would probably need to be more complex.\n build.onLoad({ filter: /.*/, namespace: 'http-url' }, async (args) => {\n const response = await fetch(args.path);\n return { contents: await response.text(), loader: 'jsx' };\n });\n },\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\n// @ts-ignore\nimport { transformServerSentEvents } from 'https://esm.sh/@dxos/script-toolbox';\n\n/**\n * Chatbot that answers questions based on the context data.\n */\nexport default async ({\n event: {\n data: { request },\n },\n context: { space, ai },\n}: any) => {\n const textBody = await request.text();\n let parsedRequest: any;\n try {\n parsedRequest = JSON.parse(textBody);\n } catch (err) {\n const answer = await ai.run('@cf/meta/llama-3.1-8b-instruct', {\n stream: true,\n prompt: `\n Using only the context data below to answer the user's question.\n If you cannot answer the question from the provided content, then reply with \"I don't know.\"\n\n CONTEXT:\n ${await getContext({ space })}\n\n QUESTION:\n ${textBody}\n `,\n });\n return new Response(transformServerSentEvents(answer));\n }\n\n const promptId = parsedRequest.trigger.promptId;\n const promptObject = await space.crud.query({ id: promptId }).first();\n\n if (parsedRequest.data.objects.length !== 1) {\n return new Response('Message batches not supported.');\n }\n\n const messageId = parsedRequest.data.objects[0];\n let message;\n try {\n message = await space.crud.query({ id: messageId }).first();\n } catch (err) {\n return new Response('Message not replicated yet.', { status: 409 });\n }\n\n if (message.text.includes('--------')) {\n return new Response('Message was already processed.');\n }\n\n let prompt = promptObject.template;\n for (const input of promptObject.inputs) {\n let value: string | null = null;\n if (input.type === ChainInputType.VALUE) {\n value = String(input.value);\n } else if (input.type === ChainInputType.RETRIEVER) {\n value = await getContext({ space });\n } else if (input.type === ChainInputType.PASS_THROUGH) {\n value = message.text;\n }\n if (value) {\n prompt = prompt.replaceAll(`{${input.name}}`, value);\n }\n }\n\n const answer = await ai.run('@cf/meta/llama-3.1-8b-instruct', {\n stream: false,\n prompt,\n });\n const response = { response: answer.response, prompt, message };\n const textWithAnswer = message.text + '\\n--------\\n\\n' + answer.response;\n await space.crud.update({ id: messageId }, { text: textWithAnswer });\n\n return new Response(JSON.stringify(response));\n};\n\nconst getContext = async ({ space }: any) => {\n let context = '';\n const { objects: docs } = await space.crud.query({ __typename: 'dxos.org/type/Document' }).run();\n for (const doc of docs) {\n const { content } = await space.crud.query({ id: doc.content }).first();\n context += content + '\\n\\n';\n }\n return context;\n};\n\nenum ChainInputType {\n VALUE = 0,\n PASS_THROUGH = 1,\n RETRIEVER = 2,\n FUNCTION = 3,\n QUERY = 4,\n RESOLVER = 5,\n CONTEXT = 6,\n SCHEMA = 7,\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\n// @ts-ignore\nimport { Chess } from 'https://esm.sh/chess.js@0.13.1';\n\n/**\n * Plays a random move in a chess game.\n */\nexport default async ({\n event: {\n data: { request },\n },\n context: { space },\n}: any) => {\n const {\n data: {\n objects: [gameId],\n player = 'b',\n },\n } = await request.json();\n\n const { pgn } = await space.crud.query({ id: gameId }).first();\n const game = new Chess();\n game.load_pgn(pgn);\n if (game.turn() !== player) {\n return new Response('Invalid turn', { status: 409 });\n }\n\n const moves = game.moves();\n const move = moves[Math.floor(Math.random() * moves.length)];\n if (!move) {\n return new Response('No legal moves', { status: 406 });\n }\n\n game.move(move);\n const newPgn = game.pgn();\n await space.crud.update({ id: gameId }, { pgn: newPgn });\n return new Response(game.ascii());\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\n/**\n * Echos the request data.\n */\nexport default async ({\n event: {\n data: { request },\n },\n}: any) => {\n const data = await request.json();\n return new Response(JSON.stringify(data ?? {}), { headers: { 'Content-Type': 'application/json' } });\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\n/**\n * Stores a message into ECHO Mailbox object.\n */\nexport default async ({\n event: {\n data: { request },\n },\n context: { space },\n}: any) => {\n const {\n data: {\n objects: [message],\n },\n } = await request.json();\n\n const mailbox = await space.crud.query({ __typename: 'dxos.org/type/MailboxType' }).first();\n if (!mailbox) {\n return new Response('Mailbox not found.', { status: 500 });\n }\n\n await space.crud.push(\n { id: mailbox.id },\n {\n sender: { email: message.from },\n timestamp: new Date(message.created).toISOString(),\n text: message.body,\n properties: {\n subject: message.subject,\n to: [{ email: message.to }],\n },\n },\n );\n return new Response(JSON.stringify(message));\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\n/**\n * Returns the exchange rate between two currencies.\n */\nexport default async ({\n event: {\n data: { request },\n },\n}: any) => {\n const { args: [from = 'EUR', to = 'USD'] = [] } = await request.json();\n\n const res = await fetch(`https://free.ratesdb.com/v1/rates?from=${from}&to=${to}`);\n const {\n data: { rates },\n } = await res.json();\n\n return new Response(rates[to].toString());\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\n// @ts-ignore\nimport chat from './templates/chat.ts?raw';\n// @ts-ignore\nimport chess from './templates/chess.ts?raw';\n// @ts-ignore\nimport echo from './templates/echo.ts?raw';\n// @ts-ignore\nimport email from './templates/email.ts?raw';\n// @ts-ignore\nimport forex from './templates/forex.ts?raw';\n\nconst removeHeader = (str: string) => str.split('\\n').slice(4).join('\\n');\n\nexport type Template = {\n id: string;\n name: string;\n source: string;\n presetId?: string;\n};\n\nexport const templates: Template[] = [\n {\n id: 'dxos.org/script/echo',\n name: 'Echo',\n source: removeHeader(echo),\n },\n {\n id: 'dxos.org/script/forex',\n name: 'Forex',\n source: removeHeader(forex),\n },\n {\n id: 'dxos.org/script/gpt',\n name: 'Gpt',\n source: removeHeader(chat),\n presetId: 'dxos.org/function/gpt',\n },\n {\n id: 'dxos.org/script/chess',\n name: 'Chess',\n source: removeHeader(chess),\n presetId: 'dxos.org/function/chess',\n },\n {\n id: 'dxos.org/script/email',\n name: 'Email',\n source: removeHeader(email),\n presetId: 'dxos.org/function/email',\n },\n];\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;AAKA,0BAAiE;AAEjE,oBAA6B;AAC7B,uBAA0B;AAC1B,iBAAoB;;AAsBpB,IAAIA;AACG,IAAMC,oBAAoB,OAAOC,YAAAA;AACtC,SAAOF,oBAAgBG,gCAAW;IAChCC,SAASF,QAAQG;EACnB,CAAA;AACF;AAKO,IAAMC,UAAN,MAAMA;EACXC,YAA6BC,UAA0B;SAA1BA,WAAAA;EAA2B;EAExD,MAAMC,OAAOC,QAAwC;AACnD,UAAM,EAAEC,kBAAkBC,iBAAiB,GAAGV,QAAAA,IAAY,KAAKM;AAE/D,UAAMK,eAAe,OAAOC,WAAAA;AAC1B,aAAO;QACLC,WAAWC,KAAKC,IAAG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IAAe,GAAG,CAACoD,UAAU;MACrDnD,MAAMmD,KAAKnD;MACXG,WAAW;IACb,EAAA;AAKAd,WAAMS,UAAU;MAAEC,QAAQ;MAAMI,WAAW;IAAW,GAAG,CAACgD,UAAU;MAClEnD,MAAM,IAAIoD,IAAID,KAAKnD,MAAMmD,KAAKE,QAAQ,EAAEC,SAAQ;MAChDnD,WAAW;IACb,EAAA;AAIAd,WAAMe,OAAO;MAAEL,QAAQ;MAAMI,WAAW;IAAW,GAAG,OAAOgD,SAAAA;AAC3D,YAAMI,WAAW,MAAMC,MAAML,KAAKnD,IAAI;AACtC,aAAO;QAAEK,UAAU,MAAMkD,SAASnC,KAAI;QAAId,QAAQ;MAAM;IAC1D,CAAA;EACF;AACF;ACrPA,IAAA,eAAA;ACAA,IAAA,gBAAA;ACAA,IAAA,eAAA;ACAA,IAAA,gBAAA;ACAA,IAAA,gBAAA;ACeA,IAAMmD,eAAe,CAACV,QAAgBA,IAAI7C,MAAM,IAAA,EAAMgD,MAAM,CAAA,EAAGrC,KAAK,IAAA;AAS7D,IAAM6C,YAAwB;EACnC;IACEC,IAAI;IACJ/D,MAAM;IACNxB,QAAQqF,aAAaG,YAAAA;EACvB;EACA;IACED,IAAI;IACJ/D,MAAM;IACNxB,QAAQqF,aAAaI,aAAAA;EACvB;EACA;IACEF,IAAI;IACJ/D,MAAM;IACNxB,QAAQqF,aAAaK,YAAAA;IACrBC,UAAU;EACZ;EACA;IACEJ,IAAI;IACJ/D,MAAM;IACNxB,QAAQqF,aAAaO,aAAAA;IACrBD,UAAU;EACZ;EACA;IACEJ,IAAI;IACJ/D,MAAM;IACNxB,QAAQqF,aAAaQ,aAAAA;IACrBF,UAAU;EACZ;;",
6
+ "names": ["initialized", "initializeBundler", "options", "initialize", "wasmURL", "wasmUrl", "Bundler", "constructor", "_options", "bundle", "source", "sandboxedModules", "providedModules", "createResult", "result", "timestamp", "Date", "now", "sourceHash", "Buffer", "from", "subtleCrypto", "digest", "platform", "invariant", "imports", "analyzeSourceFileImports", "build", "conditions", "metafile", "write", "entryPoints", "format", "plugins", "name", "setup", "onResolve", "filter", "path", "external", "split", "namespace", "onLoad", "contents", "loader", "module", "RegExp", "namedImports", "find", "entry", "moduleIdentifier", "join", "JSON", "stringify", "httpPlugin", "log", "analyzeImports", "outputFiles", "text", "err", "error", "parsedImports", "allMatches", "IMPORT_REGEX", "Object", "values", "outputs", "map", "parsedImport", "capture", "NAMED_IMPORTS_REGEX", "lastIndex", "namedImportsMatch", "exec", "forEach", "importName", "push", "trim", "moduleUrl", "defaultImport", "code", "defaultImportName", "wildcardImportName", "quotes", "regex", "str", "match", "matches", "slice", "args", "URL", "importer", "toString", "response", "fetch", "removeHeader", "templates", "id", "echo", "forex", "chat", "presetId", "chess", "email"]
7
+ }
@@ -16,15 +16,25 @@ var __copyProps = (to, from, except, desc) => {
16
16
  return to;
17
17
  };
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var TypescriptEditor_M3WWFIP2_exports = {};
20
- __export(TypescriptEditor_M3WWFIP2_exports, {
21
- TypescriptEditor: () => import_chunk_IMLDKD5Y.TypescriptEditor,
22
- default: () => import_chunk_IMLDKD5Y.TypescriptEditor_default
19
+ var chunk_EJC55SDD_exports = {};
20
+ __export(chunk_EJC55SDD_exports, {
21
+ SCRIPT_PLUGIN: () => SCRIPT_PLUGIN,
22
+ meta_default: () => meta_default
23
23
  });
24
- module.exports = __toCommonJS(TypescriptEditor_M3WWFIP2_exports);
25
- var import_chunk_IMLDKD5Y = require("./chunk-IMLDKD5Y.cjs");
24
+ module.exports = __toCommonJS(chunk_EJC55SDD_exports);
25
+ var SCRIPT_PLUGIN = "dxos.org/plugin/script";
26
+ var meta_default = {
27
+ id: SCRIPT_PLUGIN,
28
+ name: "Scripts",
29
+ description: "Distributed functions.",
30
+ tags: [
31
+ "experimental"
32
+ ],
33
+ icon: "ph--code--regular"
34
+ };
26
35
  // Annotate the CommonJS export names for ESM import in node:
27
36
  0 && (module.exports = {
28
- TypescriptEditor
37
+ SCRIPT_PLUGIN,
38
+ meta_default
29
39
  });
30
- //# sourceMappingURL=TypescriptEditor-M3WWFIP2.cjs.map
40
+ //# sourceMappingURL=chunk-EJC55SDD.cjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/meta.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport { type PluginMeta } from '@dxos/app-framework';\n\nexport const SCRIPT_PLUGIN = 'dxos.org/plugin/script';\n\nexport default {\n id: SCRIPT_PLUGIN,\n name: 'Scripts',\n description: 'Distributed functions.',\n tags: ['experimental'],\n icon: 'ph--code--regular',\n} satisfies PluginMeta;\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAMO,IAAMA,gBAAgB;AAE7B,IAAA,eAAe;EACbC,IAAID;EACJE,MAAM;EACNC,aAAa;EACbC,MAAM;IAAC;;EACPC,MAAM;AACR;",
6
+ "names": ["SCRIPT_PLUGIN", "id", "name", "description", "tags", "icon"]
7
+ }
@@ -16,17 +16,19 @@ var __copyProps = (to, from, except, desc) => {
16
16
  return to;
17
17
  };
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var chunk_PFH3ROEH_exports = {};
20
- __export(chunk_PFH3ROEH_exports, {
19
+ var chunk_FY5KKL5N_exports = {};
20
+ __export(chunk_FY5KKL5N_exports, {
21
21
  HeaderCodec: () => HeaderCodec,
22
+ USERFUNCTIONS_PRESET_META_KEY: () => USERFUNCTIONS_PRESET_META_KEY,
22
23
  codec: () => codec,
24
+ getInvocationUrl: () => getInvocationUrl,
23
25
  getUserFunctionUrlInMetadata: () => getUserFunctionUrlInMetadata,
24
26
  matchServiceCredential: () => matchServiceCredential,
25
27
  publicKeyToDid: () => publicKeyToDid,
26
28
  setUserFunctionUrlInMetadata: () => setUserFunctionUrlInMetadata,
27
29
  uploadWorkerFunction: () => uploadWorkerFunction
28
30
  });
29
- module.exports = __toCommonJS(chunk_PFH3ROEH_exports);
31
+ module.exports = __toCommonJS(chunk_FY5KKL5N_exports);
30
32
  var import_keys = require("@dxos/keys");
31
33
  var import_async = require("@dxos/async");
32
34
  var import_invariant = require("@dxos/invariant");
@@ -125,6 +127,7 @@ var publicKeyToDid = (key) => {
125
127
  };
126
128
  var __dxlog_file = "/home/runner/work/dxos/dxos/packages/plugins/experimental/plugin-script/src/edge/functions.ts";
127
129
  var USERFUNCTIONS_META_KEY = "dxos.org/service/function";
130
+ var USERFUNCTIONS_PRESET_META_KEY = "dxos.org/service/function-preset";
128
131
  var USERFUNCTIONS_CREDENTIAL_CAPABILITY = "composer:beta";
129
132
  var defaultUserFunctionsBaseUrl = "https://edge-main.dxos.workers.dev/functions";
130
133
  var getBaseUrl = (config) => {
@@ -151,7 +154,7 @@ var uploadWorkerFunction = async ({ clientConfig, halo, name, source, ownerDid,
151
154
  uploadUrl: uploadUrl.toString()
152
155
  }, {
153
156
  F: __dxlog_file,
154
- L: 71,
157
+ L: 73,
155
158
  S: void 0,
156
159
  C: (f, a) => f(...a)
157
160
  });
@@ -175,7 +178,7 @@ var uploadWorkerFunction = async ({ clientConfig, halo, name, source, ownerDid,
175
178
  res
176
179
  }, {
177
180
  F: __dxlog_file,
178
- L: 82,
181
+ L: 84,
179
182
  S: void 0,
180
183
  C: (f, a) => f(...a)
181
184
  });
@@ -224,13 +227,13 @@ var presentationForIdentity = async ({ halo, timeout }) => {
224
227
  credential
225
228
  }, {
226
229
  F: __dxlog_file,
227
- L: 128,
230
+ L: 130,
228
231
  S: void 0,
229
232
  C: (f, a) => f(...a)
230
233
  });
231
234
  (0, import_invariant.invariant)(credential.id, "beta credential missing id", {
232
235
  F: __dxlog_file,
233
- L: 130,
236
+ L: 132,
234
237
  S: void 0,
235
238
  A: [
236
239
  "credential.id",
@@ -246,14 +249,25 @@ var presentationForIdentity = async ({ halo, timeout }) => {
246
249
  Authorization: `Bearer ${codec.encode(presentation)}`
247
250
  };
248
251
  };
252
+ var getInvocationUrl = (functionUrl, edgeUrl, options = {}) => {
253
+ const baseUrl = new URL("functions/", edgeUrl);
254
+ const relativeUrl = functionUrl.replace(/^\//, "");
255
+ const url = new URL(`./${relativeUrl}`, baseUrl.toString());
256
+ options.spaceId && url.searchParams.set("spaceId", options.spaceId);
257
+ options.subjectId && url.searchParams.set("subjectId", options.subjectId);
258
+ url.protocol = "https";
259
+ return url.toString();
260
+ };
249
261
  // Annotate the CommonJS export names for ESM import in node:
250
262
  0 && (module.exports = {
251
263
  HeaderCodec,
264
+ USERFUNCTIONS_PRESET_META_KEY,
252
265
  codec,
266
+ getInvocationUrl,
253
267
  getUserFunctionUrlInMetadata,
254
268
  matchServiceCredential,
255
269
  publicKeyToDid,
256
270
  setUserFunctionUrlInMetadata,
257
271
  uploadWorkerFunction
258
272
  });
259
- //# sourceMappingURL=chunk-PFH3ROEH.cjs.map
273
+ //# sourceMappingURL=chunk-FY5KKL5N.cjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/edge/codec.ts", "../../../src/edge/header-codec.ts", "../../../src/edge/functions.ts", "../../../src/edge/hub-protocol.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { PublicKey } from '@dxos/keys';\n\nimport { HeaderCodec, type EncodedKey } from './header-codec';\n\nexport const codec = new HeaderCodec<PublicKey>({\n isKey: (value: any): value is PublicKey => value instanceof PublicKey,\n encode: (key: PublicKey): EncodedKey => ({ __k: key.toHex() }),\n decode: (value: EncodedKey): PublicKey => PublicKey.fromHex(value.__k),\n});\n", "//\n// Copyright 2024 DXOS.org\n//\n\n// TODO(burdon): Factor out from @dxos/hub-protocol\n\nconst ENCODING = 'base64';\n\nexport type EncodedKey = { __k: string };\n\nexport type EncodedBytes = { __b: string };\n\nexport type EncodedTimestamp = { __t: number };\n\nexport interface KeyCodec<KeyType> {\n isKey(value: any): value is KeyType;\n encode(key: KeyType): EncodedKey;\n decode(value: EncodedKey): KeyType;\n}\n\n// TODO(wittjosiah): Use deepMapValues from @dxos/util -- it handles recursion for you.\nexport class HeaderCodec<Key> {\n constructor(private readonly _keyCodec: KeyCodec<Key>) {}\n\n encode(obj: any): string {\n const objectToEncode = this._prepareForEncoding(obj);\n const encoded = Buffer.from(JSON.stringify(objectToEncode));\n return encoded.toString(ENCODING);\n }\n\n decode<Type>(buffer: string): Type {\n const json = JSON.parse(Buffer.from(buffer, ENCODING).toString());\n return this._decodeRecursive(json);\n }\n\n private _decodeRecursive(obj: any): any {\n return this._recurse(obj, (value) => {\n if (isEncodedBytes(value)) {\n return decodeBytes(value.__b);\n }\n if (isEncodedKey(value)) {\n return this._keyCodec.decode(value);\n }\n if (isEncodedDate(value)) {\n return decodeDate(value);\n }\n return null;\n });\n }\n\n private _prepareForEncoding(obj: any): any {\n return this._recurse(obj, (value) => {\n if (value instanceof Uint8Array) {\n return { __b: encodeBytes(value) };\n }\n if (this._keyCodec.isKey(value)) {\n return this._keyCodec.encode(value);\n }\n if (value instanceof Date) {\n return encodeDate(value);\n }\n return null;\n });\n }\n\n private _recurse(obj: any, handler: (obj: object) => any | null): any {\n if (typeof obj !== 'object') {\n return obj;\n }\n const handled = handler(obj);\n if (handled != null) {\n return handled;\n }\n if (Array.isArray(obj)) {\n const result = [];\n for (const elem of obj) {\n result.push(this._recurse(elem, handler));\n }\n return result;\n }\n const result: any = {};\n for (const [key, value] of Object.entries(obj)) {\n result[key] = this._recurse(value, handler);\n }\n return result;\n }\n}\n\nconst isEncodedKey = (obj: object): obj is EncodedKey => '__k' in obj && typeof obj.__k === 'string';\nconst isEncodedBytes = (obj: object): obj is EncodedBytes => '__b' in obj && typeof obj.__b === 'string';\nconst isEncodedDate = (obj: object): obj is EncodedTimestamp => '__t' in obj && typeof obj.__t === 'number';\n\nconst encodeDate = (date: Date) => ({ __t: date.getTime() });\nconst decodeDate = (timestamp: EncodedTimestamp) => new Date(timestamp.__t);\n\nconst encodeBytes = (bytes: Uint8Array) => Buffer.from(bytes).toString(ENCODING);\nconst decodeBytes = (bytes: string) => Buffer.from(bytes, ENCODING);\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { type DID } from 'iso-did/types';\n\nimport { Trigger } from '@dxos/async';\nimport { type Config } from '@dxos/client';\nimport { type Halo } from '@dxos/client-protocol';\nimport { type ObjectMeta } from '@dxos/echo-schema';\nimport { invariant } from '@dxos/invariant';\nimport type { SpaceId } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { type Credential } from '@dxos/protocols/proto/dxos/halo/credentials';\n\nimport { codec } from './codec';\nimport { matchServiceCredential } from './hub-protocol';\n\n// TODO: use URL scheme for source?\nconst USERFUNCTIONS_META_KEY = 'dxos.org/service/function';\nexport const USERFUNCTIONS_PRESET_META_KEY = 'dxos.org/service/function-preset';\nconst USERFUNCTIONS_CREDENTIAL_CAPABILITY = 'composer:beta';\n\n// TODO: Synchronize API types with server\nexport type UserFunctionUploadResult = {\n result: 'success' | 'error';\n errorMessage?: string;\n functionId?: string;\n functionVersionNumber?: number;\n};\n\nexport type UploadWorkerProps = {\n clientConfig: Config;\n halo: Halo;\n name?: string;\n source: string;\n functionId?: string;\n ownerDid: DID;\n credentialLoadTimeout?: number; // ms to wait for credentials to load\n};\n\n// TODO(burdon): Config.\nconst defaultUserFunctionsBaseUrl = 'https://edge-main.dxos.workers.dev/functions'; // 'http://localhost:8600';\n\nconst getBaseUrl = (config: Config) => {\n if (config.values.runtime?.services?.edge?.url) {\n const url = new URL('/functions', config.values.runtime?.services?.edge?.url);\n url.protocol = 'https';\n return url.toString();\n } else {\n return defaultUserFunctionsBaseUrl;\n }\n};\n\nexport const uploadWorkerFunction = async ({\n clientConfig,\n halo,\n name,\n source,\n ownerDid,\n functionId,\n credentialLoadTimeout,\n}: UploadWorkerProps) => {\n const identity = halo.identity.get();\n if (!identity) {\n throw new Error('Identity not available');\n }\n const userFunctionsBaseUrl = getBaseUrl(clientConfig);\n\n // TODO: codify naming convention\n const uploadUrl = `${userFunctionsBaseUrl}/${ownerDid}` + (functionId ? `/${functionId}` : '');\n\n log('Upload', { functionId, source, name, identityKey: identity.identityKey, uploadUrl: uploadUrl.toString() });\n const response = await fetch(uploadUrl, {\n method: 'PUT',\n body: JSON.stringify({ script: source, name }),\n headers: await presentationForIdentity({ halo, timeout: credentialLoadTimeout }),\n });\n if (!response.ok) {\n return (await response.json()) as UserFunctionUploadResult;\n }\n\n const res = await response.json();\n log('Upload response', { status: response.status, res });\n\n return res as UserFunctionUploadResult;\n};\n\nexport const getUserFunctionUrlInMetadata = (meta: ObjectMeta) => {\n return meta.keys.find((key) => key.source === USERFUNCTIONS_META_KEY)?.id;\n};\n\nexport const setUserFunctionUrlInMetadata = (meta: ObjectMeta, functionUrl: string) => {\n const key = meta.keys.find((key) => key.source === USERFUNCTIONS_META_KEY);\n if (key) {\n if (key.id !== functionUrl) {\n throw new Error('Metadata mismatch');\n }\n } else {\n meta.keys.push({ source: USERFUNCTIONS_META_KEY, id: functionUrl });\n }\n};\n\n// TODO: handle team owner\n\nconst presentationForIdentity = async ({ halo, timeout }: { halo: Halo; timeout?: number }) => {\n let credential: Credential | undefined;\n\n if (timeout) {\n const credentialsLoaded = new Trigger();\n halo.credentials.subscribe((c) => {\n credential = c.find(matchServiceCredential([USERFUNCTIONS_CREDENTIAL_CAPABILITY]));\n if (credential) {\n credentialsLoaded.wake();\n }\n });\n await credentialsLoaded.wait({\n timeout,\n });\n } else {\n credential = halo\n .queryCredentials()\n .toSorted((a, b) => b.issuanceDate.getTime() - a.issuanceDate.getTime())\n .find(matchServiceCredential([USERFUNCTIONS_CREDENTIAL_CAPABILITY]));\n }\n\n if (!credential) {\n throw new Error('No credential found');\n }\n log('credential found', { credential });\n // TODO(wittjosiah): If id is required to present credentials, then it should always be present for queried credentials.\n invariant(credential.id, 'beta credential missing id');\n const presentation = await halo.presentCredentials({ ids: [credential.id] });\n\n return { Authorization: `Bearer ${codec.encode(presentation)}` };\n};\n\nexport type InvocationOptions = {\n spaceId?: SpaceId;\n subjectId?: string;\n};\n\nexport const getInvocationUrl = (functionUrl: string, edgeUrl: string, options: InvocationOptions = {}) => {\n const baseUrl = new URL('functions/', edgeUrl);\n\n // Leading slashes cause the URL to be treated as an absolute path.\n const relativeUrl = functionUrl.replace(/^\\//, '');\n const url = new URL(`./${relativeUrl}`, baseUrl.toString());\n options.spaceId && url.searchParams.set('spaceId', options.spaceId);\n options.subjectId && url.searchParams.set('subjectId', options.subjectId);\n url.protocol = 'https';\n return url.toString();\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { type DID } from 'iso-did/types';\n\nimport { type Credential } from '@dxos/client/halo';\nimport { type PublicKey } from '@dxos/keys';\n\n// TODO(burdon): Factor out to @dxos/hub-protocol.\n\nexport const matchServiceCredential =\n (capabilities: string[] = []) =>\n (credential: Credential) => {\n if (credential.subject.assertion['@type'] !== 'dxos.halo.credentials.ServiceAccess') {\n return false;\n }\n\n const { capabilities: credentialCapabilities } = credential.subject.assertion;\n return capabilities.every((capability) => credentialCapabilities.includes(capability));\n };\n\n// TODO: reconcile with @dxos/hub-protocol\n\nexport const publicKeyToDid = (key: PublicKey): DID => {\n return `did:key:${key.toHex()}`;\n};\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,kBAA0B;AEE1B,mBAAwB;AAIxB,uBAA0B;AAE1B,iBAAoB;ADNpB,IAAMA,WAAW;AAeV,IAAMC,cAAN,MAAMA;EACXC,YAA6BC,WAA0B;SAA1BA,YAAAA;EAA2B;EAExDC,OAAOC,KAAkB;AACvB,UAAMC,iBAAiB,KAAKC,oBAAoBF,GAAAA;AAChD,UAAMG,UAAUC,OAAOC,KAAKC,KAAKC,UAAUN,cAAAA,CAAAA;AAC3C,WAAOE,QAAQK,SAASb,QAAAA;EAC1B;EAEAc,OAAaC,QAAsB;AACjC,UAAMC,OAAOL,KAAKM,MAAMR,OAAOC,KAAKK,QAAQf,Q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uB,QAAQ,OAAO,EAAA;AAC/C,QAAM1D,MAAM,IAAIC,IAAI,KAAKwD,WAAAA,IAAeD,QAAQnH,SAAQ,CAAA;AACxDkH,UAAQI,WAAW3D,IAAI4D,aAAaC,IAAI,WAAWN,QAAQI,OAAO;AAClEJ,UAAQO,aAAa9D,IAAI4D,aAAaC,IAAI,aAAaN,QAAQO,SAAS;AACxE9D,MAAIE,WAAW;AACf,SAAOF,IAAI3D,SAAQ;AACrB;",
6
+ "names": ["ENCODING", "HeaderCodec", "constructor", "_keyCodec", "encode", "obj", "objectToEncode", "_prepareForEncoding", "encoded", "Buffer", "from", "JSON", "stringify", "toString", "decode", "buffer", "json", "parse", "_decodeRecursive", "_recurse", "value", "isEncodedBytes", "decodeBytes", "__b", "isEncodedKey", "isEncodedDate", "decodeDate", "Uint8Array", "encodeBytes", "isKey", "Date", "encodeDate", "handler", "handled", "Array", "isArray", "result", "elem", "push", "key", "Object", "entries", "__k", "__t", "date", "getTime", "timestamp", "bytes", "codec", "PublicKey", "toHex", "fromHex", "matchServiceCredential", "capabilities", "credential", "subject", "assertion", "credentialCapabilities", "every", "capability", "includes", "publicKeyToDid", "USERFUNCTIONS_META_KEY", "USERFUNCTIONS_PRESET_META_KEY", "USERFUNCTIONS_CREDENTIAL_CAPABILITY", "defaultUserFunctionsBaseUrl", "getBaseUrl", "config", "values", "runtime", "services", "edge", "url", "URL", "protocol", "uploadWorkerFunction", "clientConfig", "halo", "name", "source", "ownerDid", "functionId", "credentialLoadTimeout", "identity", "get", "Error", "userFunctionsBaseUrl", "uploadUrl", "log", "identityKey", "response", "fetch", "method", "body", "script", "headers", "presentationForIdentity", "timeout", "ok", "res", "status", "getUserFunctionUrlInMetadata", "meta", "keys", "find", "id", "setUserFunctionUrlInMetadata", "functionUrl", "credentialsLoaded", "Trigger", "credentials", "subscribe", "c", "wake", "wait", "queryCredentials", "toSorted", "a", "b", "issuanceDate", "invariant", "presentation", "presentCredentials", "ids", "Authorization", "getInvocationUrl", "edgeUrl", "options", "baseUrl", "relativeUrl", "replace", "spaceId", "searchParams", "set", "subjectId"]
7
+ }
@@ -0,0 +1,277 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var chunk_JWKMTYYH_exports = {};
30
+ __export(chunk_JWKMTYYH_exports, {
31
+ DebugPanel: () => DebugPanel
32
+ });
33
+ module.exports = __toCommonJS(chunk_JWKMTYYH_exports);
34
+ var import_chunk_EJC55SDD = require("./chunk-EJC55SDD.cjs");
35
+ var import_react = __toESM(require("react"));
36
+ var import_log = require("@dxos/log");
37
+ var import_react_ui = require("@dxos/react-ui");
38
+ var import_react_ui_syntax_highlighter = require("@dxos/react-ui-syntax-highlighter");
39
+ var import_react_ui_theme = require("@dxos/react-ui-theme");
40
+ var __dxlog_file = "/home/runner/work/dxos/dxos/packages/plugins/experimental/plugin-script/src/components/DebugPanel/DebugPanel.tsx";
41
+ var DebugPanel = ({ classNames, functionUrl, binding: _binding, onBindingChange, showBindingConfig = false }) => {
42
+ const { t } = (0, import_react_ui.useTranslation)(import_chunk_EJC55SDD.SCRIPT_PLUGIN);
43
+ const bindingInputRef = (0, import_react.useRef)(null);
44
+ const [binding, setBinding] = (0, import_react_ui.useControlledValue)(_binding ?? "");
45
+ const handleBlur = () => {
46
+ onBindingChange?.(binding);
47
+ };
48
+ const inputRef = (0, import_react.useRef)(null);
49
+ const [input, setInput] = (0, import_react.useState)("");
50
+ const [result, setResult] = (0, import_react.useState)("");
51
+ const [state, setState] = (0, import_react.useState)(null);
52
+ const [history, setHistory] = (0, import_react.useState)([]);
53
+ const scrollerRef = (0, import_react.useRef)(null);
54
+ const handleScroll = () => {
55
+ if (scrollerRef.current) {
56
+ scrollerRef.current.scrollTop = scrollerRef.current.scrollHeight;
57
+ }
58
+ };
59
+ const controller = (0, import_react.useRef)();
60
+ (0, import_react.useEffect)(() => {
61
+ return () => {
62
+ handleStop();
63
+ };
64
+ }, []);
65
+ const handleStop = () => {
66
+ controller.current?.abort("stop");
67
+ controller.current = void 0;
68
+ };
69
+ const handleClear = () => {
70
+ handleStop();
71
+ setInput("");
72
+ setResult("");
73
+ setHistory([]);
74
+ inputRef.current?.focus();
75
+ };
76
+ const handleResponse = ({ text, data, error } = {}) => {
77
+ controller.current = void 0;
78
+ setHistory((history2) => [
79
+ ...history2,
80
+ {
81
+ type: "response",
82
+ text,
83
+ data,
84
+ error
85
+ }
86
+ ]);
87
+ setResult("");
88
+ setState(null);
89
+ handleScroll();
90
+ };
91
+ const handleRequest = async (input2) => {
92
+ try {
93
+ setState("pending");
94
+ let data = null;
95
+ if (input2.charAt(0) === "{") {
96
+ try {
97
+ const validJsonString = input2.replace(/'/g, '"').replace(/([{,]\s*)([a-zA-Z0-9_]+)(\s*:)/g, '$1"$2"$3');
98
+ data = JSON.parse(validJsonString);
99
+ input2 = JSON.stringify(data, null, 2);
100
+ } catch (err) {
101
+ inputRef.current?.focus();
102
+ return;
103
+ }
104
+ }
105
+ setInput("");
106
+ setResult("");
107
+ setHistory((history2) => [
108
+ ...history2,
109
+ {
110
+ type: "request",
111
+ text: input2
112
+ }
113
+ ]);
114
+ setTimeout(() => {
115
+ handleScroll();
116
+ });
117
+ controller.current = new AbortController();
118
+ const response = await fetch(functionUrl, {
119
+ signal: controller.current.signal,
120
+ method: "POST",
121
+ body: input2,
122
+ headers: {
123
+ "Content-Type": data ? "application/json" : "text/plain"
124
+ }
125
+ });
126
+ if (!response.ok) {
127
+ const text2 = await response.text();
128
+ handleResponse({
129
+ error: new Error(text2 || response.statusText || String(response.status))
130
+ });
131
+ return;
132
+ }
133
+ const contentType = response.headers.get("content-type");
134
+ if (contentType === "application/json") {
135
+ const data2 = await response.json();
136
+ handleResponse({
137
+ data: data2
138
+ });
139
+ return;
140
+ }
141
+ setState("responding");
142
+ let text = "";
143
+ const reader = response.body.getReader();
144
+ const pump = async ({ done, value }) => {
145
+ text = text + new TextDecoder().decode(value);
146
+ if (!controller.current || done) {
147
+ handleResponse({
148
+ text
149
+ });
150
+ return;
151
+ }
152
+ setResult(text);
153
+ setTimeout(() => {
154
+ handleScroll();
155
+ });
156
+ return reader.read().then(pump);
157
+ };
158
+ void reader.read().then(pump).catch((err) => {
159
+ if (err.name !== "AbortError") {
160
+ import_log.log.catch(err, void 0, {
161
+ F: __dxlog_file,
162
+ L: 161,
163
+ S: void 0,
164
+ C: (f, a) => f(...a)
165
+ });
166
+ }
167
+ });
168
+ } catch (err) {
169
+ if (err !== "stop") {
170
+ const error = err instanceof Error ? err : new Error(err);
171
+ handleResponse({
172
+ error
173
+ });
174
+ import_log.log.catch(err, void 0, {
175
+ F: __dxlog_file,
176
+ L: 168,
177
+ S: void 0,
178
+ C: (f, a) => f(...a)
179
+ });
180
+ } else {
181
+ handleResponse();
182
+ }
183
+ }
184
+ };
185
+ return /* @__PURE__ */ import_react.default.createElement("div", {
186
+ className: (0, import_react_ui_theme.mx)("flex flex-col h-full overflow-hidden", classNames)
187
+ }, /* @__PURE__ */ import_react.default.createElement("div", {
188
+ ref: scrollerRef,
189
+ className: "flex flex-col gap-6 h-full p-2 overflow-x-hidden overflow-y-auto"
190
+ }, /* @__PURE__ */ import_react.default.createElement(MessageThread, {
191
+ state,
192
+ result,
193
+ history
194
+ })), /* @__PURE__ */ import_react.default.createElement(import_react_ui.Toolbar.Root, {
195
+ classNames: "p-2"
196
+ }, /* @__PURE__ */ import_react.default.createElement(import_react_ui.Input.Root, null, /* @__PURE__ */ import_react.default.createElement(import_react_ui.Input.TextInput, {
197
+ ref: inputRef,
198
+ autoFocus: true,
199
+ placeholder: t("function request placeholder"),
200
+ value: input,
201
+ onChange: (ev) => setInput(ev.target.value),
202
+ onKeyDown: (ev) => ev.key === "Enter" && handleRequest(input)
203
+ })), showBindingConfig && /* @__PURE__ */ import_react.default.createElement(import_react_ui.Input.Root, null, /* @__PURE__ */ import_react.default.createElement(import_react_ui.Input.TextInput, {
204
+ ref: bindingInputRef,
205
+ classNames: "!w-[10rem]",
206
+ placeholder: t("binding placeholder"),
207
+ value: binding,
208
+ onChange: (ev) => setBinding(ev.target.value.toUpperCase()),
209
+ onBlur: handleBlur
210
+ })), /* @__PURE__ */ import_react.default.createElement(import_react_ui.Toolbar.Button, {
211
+ onClick: () => handleRequest(input)
212
+ }, /* @__PURE__ */ import_react.default.createElement(import_react_ui.Icon, {
213
+ icon: "ph--play--regular",
214
+ size: 4
215
+ })), /* @__PURE__ */ import_react.default.createElement(import_react_ui.Toolbar.Button, {
216
+ onClick: () => state ? handleStop() : handleClear()
217
+ }, /* @__PURE__ */ import_react.default.createElement(import_react_ui.Icon, {
218
+ icon: state ? "ph--stop--regular" : "ph--trash--regular",
219
+ size: 4
220
+ }))));
221
+ };
222
+ var MessageThread = ({ state, result, history }) => {
223
+ return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, history.map((message, i) => /* @__PURE__ */ import_react.default.createElement("div", {
224
+ key: i,
225
+ className: "grid grid-cols-[2rem_1fr_2rem]"
226
+ }, /* @__PURE__ */ import_react.default.createElement("div", {
227
+ className: "p-1"
228
+ }, message.type === "response" && /* @__PURE__ */ import_react.default.createElement(RobotAvatar, null)), /* @__PURE__ */ import_react.default.createElement("div", {
229
+ className: "overflow-auto"
230
+ }, /* @__PURE__ */ import_react.default.createElement(MessageItem, {
231
+ message
232
+ })))), result?.length > 0 && /* @__PURE__ */ import_react.default.createElement("div", {
233
+ className: "grid grid-cols-[2rem_1fr_2rem]"
234
+ }, /* @__PURE__ */ import_react.default.createElement("div", {
235
+ className: "p-1"
236
+ }, state === "pending" && /* @__PURE__ */ import_react.default.createElement(import_react_ui.Icon, {
237
+ icon: "ph--spinner--regular",
238
+ size: 6,
239
+ classNames: "animate-spin"
240
+ }) || /* @__PURE__ */ import_react.default.createElement(import_react_ui.Icon, {
241
+ icon: "ph--robot--regular",
242
+ size: 6,
243
+ classNames: "animate-[pulse_1s_ease-in-out_infinite]"
244
+ })), /* @__PURE__ */ import_react.default.createElement("div", {
245
+ className: "overflow-auto"
246
+ }, /* @__PURE__ */ import_react.default.createElement(MessageItem, {
247
+ message: {
248
+ type: "response",
249
+ text: result
250
+ }
251
+ }))));
252
+ };
253
+ var MessageItem = ({ classNames, message }) => {
254
+ const { type, text, data, error } = message;
255
+ const wrapper = "p-1 px-2 rounded-lg bg-hoverSurface overflow-auto";
256
+ return /* @__PURE__ */ import_react.default.createElement("div", {
257
+ className: (0, import_react_ui_theme.mx)("flex", type === "request" ? "ml-[1rem] justify-end" : "mr-[1rem]", classNames)
258
+ }, error && /* @__PURE__ */ import_react.default.createElement("div", {
259
+ className: (0, import_react_ui_theme.mx)(wrapper, "whitespace-pre text-error")
260
+ }, String(error)), text !== void 0 && /* @__PURE__ */ import_react.default.createElement("div", {
261
+ className: (0, import_react_ui_theme.mx)(wrapper, type === "request" && "bg-primary-400 dark:bg-primary-600")
262
+ }, text || "\xD8"), data && /* @__PURE__ */ import_react.default.createElement(import_react_ui_syntax_highlighter.SyntaxHighlighter, {
263
+ language: "json",
264
+ className: (0, import_react_ui_theme.mx)(wrapper, "px-8 py-2 text-xs")
265
+ }, JSON.stringify(data, null, 2)));
266
+ };
267
+ var RobotAvatar = () => /* @__PURE__ */ import_react.default.createElement(import_react_ui.Avatar.Root, {
268
+ size: 6,
269
+ variant: "circle"
270
+ }, /* @__PURE__ */ import_react.default.createElement(import_react_ui.Avatar.Frame, null, /* @__PURE__ */ import_react.default.createElement(import_react_ui.Avatar.Icon, {
271
+ icon: "ph--robot--regular"
272
+ })));
273
+ // Annotate the CommonJS export names for ESM import in node:
274
+ 0 && (module.exports = {
275
+ DebugPanel
276
+ });
277
+ //# sourceMappingURL=chunk-JWKMTYYH.cjs.map