@dxos/plugin-script 0.8.2-main.5885341 → 0.8.2-main.5ca3450

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 (173) hide show
  1. package/dist/lib/browser/{DeploymentDialog-QEKJ54ZB.mjs → DeploymentDialog-EMYG5BCD.mjs} +4 -4
  2. package/dist/lib/browser/{ScriptContainer-ATBYTIFH.mjs → ScriptContainer-TXVLNVQ4.mjs} +5 -5
  3. package/dist/lib/browser/ScriptContainer-TXVLNVQ4.mjs.map +7 -0
  4. package/dist/lib/browser/{artifact-definition-OEDM2SCN.mjs → artifact-definition-PD4UAAQZ.mjs} +41 -35
  5. package/dist/lib/browser/artifact-definition-PD4UAAQZ.mjs.map +7 -0
  6. package/dist/lib/browser/chunk-6MLJJI73.mjs +40 -0
  7. package/dist/lib/browser/chunk-6MLJJI73.mjs.map +7 -0
  8. package/dist/lib/browser/{chunk-SXS6PUU5.mjs → chunk-AA3MEHWR.mjs} +5 -4
  9. package/dist/lib/browser/chunk-AA3MEHWR.mjs.map +7 -0
  10. package/dist/lib/browser/chunk-GTJJTVTQ.mjs +87 -0
  11. package/dist/lib/browser/chunk-GTJJTVTQ.mjs.map +7 -0
  12. package/dist/lib/browser/{chunk-EGDYE5MW.mjs → chunk-MGYLCUQA.mjs} +4 -4
  13. package/dist/lib/browser/{chunk-EGDYE5MW.mjs.map → chunk-MGYLCUQA.mjs.map} +1 -1
  14. package/dist/lib/browser/{chunk-OZEMT3NO.mjs → chunk-RIKHDIEO.mjs} +2 -2
  15. package/dist/lib/browser/chunk-RIKHDIEO.mjs.map +7 -0
  16. package/dist/lib/browser/{chunk-QNXJNXQZ.mjs → chunk-V26XPHYE.mjs} +6 -6
  17. package/dist/lib/browser/chunk-V26XPHYE.mjs.map +7 -0
  18. package/dist/lib/browser/index.mjs +12 -12
  19. package/dist/lib/browser/index.mjs.map +3 -3
  20. package/dist/lib/browser/{intent-resolver-C5D6TNPC.mjs → intent-resolver-PIDSNKRS.mjs} +11 -11
  21. package/dist/lib/browser/intent-resolver-PIDSNKRS.mjs.map +7 -0
  22. package/dist/lib/browser/meta.json +1 -1
  23. package/dist/lib/browser/{react-surface-XJCN7XXF.mjs → react-surface-FFTOHZXK.mjs} +8 -8
  24. package/dist/lib/browser/react-surface-FFTOHZXK.mjs.map +7 -0
  25. package/dist/lib/browser/{settings-NK4XVS2E.mjs → settings-EOKSUGB6.mjs} +2 -2
  26. package/dist/lib/browser/types.mjs +1 -1
  27. package/dist/lib/node/{DeploymentDialog-NUKZNILK.cjs → DeploymentDialog-VWKE3X2Y.cjs} +9 -9
  28. package/dist/lib/node/{DeploymentDialog-NUKZNILK.cjs.map → DeploymentDialog-VWKE3X2Y.cjs.map} +2 -2
  29. package/dist/lib/node/{ScriptContainer-OHHMLPUE.cjs → ScriptContainer-MNYXE47W.cjs} +14 -14
  30. package/dist/lib/node/ScriptContainer-MNYXE47W.cjs.map +7 -0
  31. package/dist/lib/node/{artifact-definition-SEGATFNH.cjs → artifact-definition-C644EAYM.cjs} +47 -41
  32. package/dist/lib/node/artifact-definition-C644EAYM.cjs.map +7 -0
  33. package/dist/lib/node/chunk-DGFQHBA7.cjs +91 -0
  34. package/dist/lib/node/chunk-DGFQHBA7.cjs.map +7 -0
  35. package/dist/lib/node/{chunk-UUGLBCMY.cjs → chunk-HLNSDICG.cjs} +14 -14
  36. package/dist/lib/node/chunk-HLNSDICG.cjs.map +7 -0
  37. package/dist/lib/node/{chunk-PMGWL64F.cjs → chunk-NBOJUJSM.cjs} +6 -6
  38. package/dist/lib/node/chunk-NBOJUJSM.cjs.map +7 -0
  39. package/dist/lib/node/{chunk-ZZ4HK5KM.cjs → chunk-SD6PUOJT.cjs} +11 -11
  40. package/dist/lib/node/chunk-SD6PUOJT.cjs.map +7 -0
  41. package/dist/lib/node/{chunk-PGEGRJP3.cjs → chunk-SXJGHLK6.cjs} +16 -17
  42. package/dist/lib/node/chunk-SXJGHLK6.cjs.map +7 -0
  43. package/dist/lib/node/{chunk-DSFCLQ5F.cjs → chunk-XT76CMHH.cjs} +10 -9
  44. package/dist/lib/node/chunk-XT76CMHH.cjs.map +7 -0
  45. package/dist/lib/node/index.cjs +24 -24
  46. package/dist/lib/node/index.cjs.map +3 -3
  47. package/dist/lib/node/{intent-resolver-BQPBRVHM.cjs → intent-resolver-5VH5Z724.cjs} +20 -20
  48. package/dist/lib/node/intent-resolver-5VH5Z724.cjs.map +7 -0
  49. package/dist/lib/node/meta.json +1 -1
  50. package/dist/lib/node/{react-surface-5XHS5WYW.cjs → react-surface-Y7IYF6UV.cjs} +26 -26
  51. package/dist/lib/node/react-surface-Y7IYF6UV.cjs.map +7 -0
  52. package/dist/lib/node/{settings-7PVJBWC4.cjs → settings-425QHVGC.cjs} +7 -7
  53. package/dist/lib/node/types.cjs +3 -3
  54. package/dist/lib/node/types.cjs.map +1 -1
  55. package/dist/lib/node-esm/{DeploymentDialog-BIXZ5Q57.mjs → DeploymentDialog-FGFA6MG2.mjs} +4 -4
  56. package/dist/lib/node-esm/{ScriptContainer-4YWGWPY7.mjs → ScriptContainer-QFSYBSKM.mjs} +5 -5
  57. package/dist/lib/node-esm/ScriptContainer-QFSYBSKM.mjs.map +7 -0
  58. package/dist/lib/node-esm/{artifact-definition-5UHIXXHW.mjs → artifact-definition-J6UM6BQF.mjs} +41 -35
  59. package/dist/lib/node-esm/artifact-definition-J6UM6BQF.mjs.map +7 -0
  60. package/dist/lib/node-esm/chunk-5ES2REWL.mjs +89 -0
  61. package/dist/lib/node-esm/chunk-5ES2REWL.mjs.map +7 -0
  62. package/dist/lib/node-esm/{chunk-GR4VTXVM.mjs → chunk-NERLX6GG.mjs} +2 -2
  63. package/dist/lib/node-esm/chunk-NERLX6GG.mjs.map +7 -0
  64. package/dist/lib/node-esm/{chunk-4ISQLIIH.mjs → chunk-TQ5VMPMV.mjs} +6 -6
  65. package/dist/lib/node-esm/chunk-TQ5VMPMV.mjs.map +7 -0
  66. package/dist/lib/node-esm/{chunk-KGYTIL33.mjs → chunk-VMQPOPKV.mjs} +12 -13
  67. package/dist/lib/node-esm/chunk-VMQPOPKV.mjs.map +7 -0
  68. package/dist/lib/node-esm/{chunk-TN35DSTF.mjs → chunk-X27CHZ64.mjs} +5 -4
  69. package/dist/lib/node-esm/chunk-X27CHZ64.mjs.map +7 -0
  70. package/dist/lib/node-esm/{chunk-NNQXJQBG.mjs → chunk-XFRKBSGA.mjs} +4 -4
  71. package/dist/lib/node-esm/{chunk-NNQXJQBG.mjs.map → chunk-XFRKBSGA.mjs.map} +1 -1
  72. package/dist/lib/node-esm/index.mjs +12 -12
  73. package/dist/lib/node-esm/index.mjs.map +3 -3
  74. package/dist/lib/node-esm/{intent-resolver-PPJKPHUQ.mjs → intent-resolver-GZEGKYFO.mjs} +11 -11
  75. package/dist/lib/node-esm/intent-resolver-GZEGKYFO.mjs.map +7 -0
  76. package/dist/lib/node-esm/meta.json +1 -1
  77. package/dist/lib/node-esm/{react-surface-7ELFL7IO.mjs → react-surface-NNATTNFP.mjs} +8 -8
  78. package/dist/lib/node-esm/react-surface-NNATTNFP.mjs.map +7 -0
  79. package/dist/lib/node-esm/{settings-SJYC4JLT.mjs → settings-BWSKKIVQ.mjs} +2 -2
  80. package/dist/lib/node-esm/types.mjs +1 -1
  81. package/dist/types/src/capabilities/app-graph-builder.d.ts.map +1 -1
  82. package/dist/types/src/capabilities/artifact-definition.d.ts.map +1 -1
  83. package/dist/types/src/capabilities/index.d.ts.map +1 -1
  84. package/dist/types/src/components/DeploymentDialog/DeploymentDialog.d.ts +2 -2
  85. package/dist/types/src/components/DeploymentDialog/DeploymentDialog.d.ts.map +1 -1
  86. package/dist/types/src/components/FrameContainer/FrameContainer.d.ts.map +1 -1
  87. package/dist/types/src/components/ScriptContainer.d.ts +1 -1
  88. package/dist/types/src/components/ScriptContainer.d.ts.map +1 -1
  89. package/dist/types/src/components/ScriptToolbar/ScriptToolbar.d.ts +1 -1
  90. package/dist/types/src/components/ScriptToolbar/ScriptToolbar.d.ts.map +1 -1
  91. package/dist/types/src/components/Settings/ScriptObjectSettings.d.ts +1 -1
  92. package/dist/types/src/components/Settings/ScriptObjectSettings.d.ts.map +1 -1
  93. package/dist/types/src/components/Settings/ScriptPluginSettings.d.ts.map +1 -1
  94. package/dist/types/src/components/TestPanel/TestPanel.d.ts.map +1 -1
  95. package/dist/types/src/components/TypescriptEditor/TypescriptEditor.d.ts.map +1 -1
  96. package/dist/types/src/components/index.d.ts +1 -1
  97. package/dist/types/src/hooks/deploy.d.ts +4 -3
  98. package/dist/types/src/hooks/deploy.d.ts.map +1 -1
  99. package/dist/types/src/hooks/format.d.ts +1 -1
  100. package/dist/types/src/hooks/format.d.ts.map +1 -1
  101. package/dist/types/src/hooks/template.d.ts +1 -1
  102. package/dist/types/src/hooks/template.d.ts.map +1 -1
  103. package/dist/types/src/hooks/useCreateAndDeployScriptTemplates.d.ts.map +1 -1
  104. package/dist/types/src/hooks/useToolbarAction.d.ts +1 -1
  105. package/dist/types/src/hooks/useToolbarAction.d.ts.map +1 -1
  106. package/dist/types/src/hooks/useToolbarState.d.ts.map +1 -1
  107. package/dist/types/src/templates/chat.d.ts.map +1 -1
  108. package/dist/types/src/templates/discord.d.ts.map +1 -1
  109. package/dist/types/src/templates/echo.d.ts.map +1 -1
  110. package/dist/types/src/templates/email.d.ts.map +1 -1
  111. package/dist/types/src/templates/gmail.d.ts.map +1 -1
  112. package/dist/types/src/translations.d.ts +2 -110
  113. package/dist/types/src/translations.d.ts.map +1 -1
  114. package/dist/types/src/types.d.ts +26 -25
  115. package/dist/types/src/types.d.ts.map +1 -1
  116. package/dist/types/src/util/deploy.d.ts.map +1 -1
  117. package/dist/types/src/util/functions.d.ts.map +1 -1
  118. package/dist/types/tsconfig.tsbuildinfo +1 -1
  119. package/package.json +51 -49
  120. package/src/ScriptPlugin.tsx +3 -3
  121. package/src/capabilities/artifact-definition.ts +33 -30
  122. package/src/capabilities/intent-resolver.ts +5 -5
  123. package/src/capabilities/react-surface.tsx +3 -3
  124. package/src/components/DeploymentDialog/DeploymentDialog.tsx +2 -2
  125. package/src/components/ScriptContainer.tsx +1 -1
  126. package/src/components/ScriptToolbar/ScriptToolbar.tsx +1 -1
  127. package/src/components/Settings/ScriptObjectSettings.tsx +3 -3
  128. package/src/hooks/format.ts +1 -1
  129. package/src/hooks/template.ts +1 -1
  130. package/src/hooks/useToolbarAction.ts +1 -1
  131. package/src/templates/discord.ts +10 -3
  132. package/src/templates/forex-effect.ts +1 -1
  133. package/src/templates/gmail.ts +42 -28
  134. package/src/translations.ts +1 -1
  135. package/src/types.ts +13 -14
  136. package/src/util/deploy.ts +1 -2
  137. package/dist/lib/browser/ScriptContainer-ATBYTIFH.mjs.map +0 -7
  138. package/dist/lib/browser/artifact-definition-OEDM2SCN.mjs.map +0 -7
  139. package/dist/lib/browser/chunk-OZEMT3NO.mjs.map +0 -7
  140. package/dist/lib/browser/chunk-QNXJNXQZ.mjs.map +0 -7
  141. package/dist/lib/browser/chunk-SXS6PUU5.mjs.map +0 -7
  142. package/dist/lib/browser/chunk-XEPVXV72.mjs +0 -87
  143. package/dist/lib/browser/chunk-XEPVXV72.mjs.map +0 -7
  144. package/dist/lib/browser/chunk-ZFTDU4WS.mjs +0 -41
  145. package/dist/lib/browser/chunk-ZFTDU4WS.mjs.map +0 -7
  146. package/dist/lib/browser/intent-resolver-C5D6TNPC.mjs.map +0 -7
  147. package/dist/lib/browser/react-surface-XJCN7XXF.mjs.map +0 -7
  148. package/dist/lib/node/ScriptContainer-OHHMLPUE.cjs.map +0 -7
  149. package/dist/lib/node/artifact-definition-SEGATFNH.cjs.map +0 -7
  150. package/dist/lib/node/chunk-4K23KEYT.cjs +0 -91
  151. package/dist/lib/node/chunk-4K23KEYT.cjs.map +0 -7
  152. package/dist/lib/node/chunk-DSFCLQ5F.cjs.map +0 -7
  153. package/dist/lib/node/chunk-PGEGRJP3.cjs.map +0 -7
  154. package/dist/lib/node/chunk-PMGWL64F.cjs.map +0 -7
  155. package/dist/lib/node/chunk-UUGLBCMY.cjs.map +0 -7
  156. package/dist/lib/node/chunk-ZZ4HK5KM.cjs.map +0 -7
  157. package/dist/lib/node/intent-resolver-BQPBRVHM.cjs.map +0 -7
  158. package/dist/lib/node/react-surface-5XHS5WYW.cjs.map +0 -7
  159. package/dist/lib/node-esm/ScriptContainer-4YWGWPY7.mjs.map +0 -7
  160. package/dist/lib/node-esm/artifact-definition-5UHIXXHW.mjs.map +0 -7
  161. package/dist/lib/node-esm/chunk-4ISQLIIH.mjs.map +0 -7
  162. package/dist/lib/node-esm/chunk-GR4VTXVM.mjs.map +0 -7
  163. package/dist/lib/node-esm/chunk-KGYTIL33.mjs.map +0 -7
  164. package/dist/lib/node-esm/chunk-TN35DSTF.mjs.map +0 -7
  165. package/dist/lib/node-esm/chunk-X64SI6XO.mjs +0 -89
  166. package/dist/lib/node-esm/chunk-X64SI6XO.mjs.map +0 -7
  167. package/dist/lib/node-esm/intent-resolver-PPJKPHUQ.mjs.map +0 -7
  168. package/dist/lib/node-esm/react-surface-7ELFL7IO.mjs.map +0 -7
  169. /package/dist/lib/browser/{DeploymentDialog-QEKJ54ZB.mjs.map → DeploymentDialog-EMYG5BCD.mjs.map} +0 -0
  170. /package/dist/lib/browser/{settings-NK4XVS2E.mjs.map → settings-EOKSUGB6.mjs.map} +0 -0
  171. /package/dist/lib/node/{settings-7PVJBWC4.cjs.map → settings-425QHVGC.cjs.map} +0 -0
  172. /package/dist/lib/node-esm/{DeploymentDialog-BIXZ5Q57.mjs.map → DeploymentDialog-FGFA6MG2.mjs.map} +0 -0
  173. /package/dist/lib/node-esm/{settings-SJYC4JLT.mjs.map → settings-BWSKKIVQ.mjs.map} +0 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/components/ScriptContainer.tsx", "../../../src/components/ScriptToolbar/ScriptToolbar.tsx", "../../../src/components/TypescriptEditor/TypescriptEditor.tsx"],
4
+ "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport React, { useMemo } from 'react';\n\nimport { type ScriptType } from '@dxos/functions';\nimport { createDocAccessor, getSpace } from '@dxos/react-client/echo';\nimport { useIdentity } from '@dxos/react-client/halo';\nimport { type ThemedClassName } from '@dxos/react-ui';\nimport { createDataExtensions, listener, stackItemContentEditorClassNames } from '@dxos/react-ui-editor';\nimport { StackItem } from '@dxos/react-ui-stack';\nimport { mx } from '@dxos/react-ui-theme';\n\nimport { ScriptToolbar } from './ScriptToolbar';\nimport { TypescriptEditor, type TypescriptEditorProps } from './TypescriptEditor';\nimport { useDeployState, useToolbarState } from '../hooks';\nimport { type ScriptSettingsProps } from '../types';\n\nexport type ScriptEditorProps = ThemedClassName<\n {\n role?: string;\n script: ScriptType;\n settings?: ScriptSettingsProps;\n } & Pick<TypescriptEditorProps, 'env'>\n>;\n\nexport const ScriptContainer = ({\n classNames,\n role,\n script,\n settings = { editorInputMode: 'vscode' },\n env,\n}: ScriptEditorProps) => {\n const identity = useIdentity();\n const space = getSpace(script);\n const state = useToolbarState();\n useDeployState({ state, script });\n\n const extensions = useMemo(\n () => [\n listener({\n onChange: (text) => {\n if (script.source.target && script.source.target.content !== text) {\n script.changed = true;\n }\n },\n }),\n createDataExtensions({\n id: script.id,\n text: script.source.target && createDocAccessor(script.source.target, ['content']),\n space,\n identity,\n }),\n ],\n [identity, space, script, script.source.target],\n );\n\n return (\n <StackItem.Content toolbar classNames='divide-y divide-separator'>\n <ScriptToolbar state={state} role={role} script={script} />\n <TypescriptEditor\n id={script.id}\n env={env}\n initialValue={script.source?.target?.content}\n extensions={extensions}\n className={mx(stackItemContentEditorClassNames(role))}\n inputMode={settings.editorInputMode}\n toolbar\n />\n </StackItem.Content>\n );\n};\n\nexport default ScriptContainer;\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport React, { useCallback } from 'react';\n\nimport { type ScriptType } from '@dxos/functions';\nimport { fullyQualifiedId } from '@dxos/react-client/echo';\nimport { ElevationProvider, type ThemedClassName } from '@dxos/react-ui';\nimport { stackItemContentToolbarClassNames } from '@dxos/react-ui-editor';\nimport { createGapSeparator, MenuProvider, ToolbarMenu, useMenuActions } from '@dxos/react-ui-menu';\n\nimport {\n type ScriptToolbarState,\n createDeploy,\n createFormat,\n createTemplateSelect,\n useToolbarAction,\n} from '../../hooks';\n\nexport type ScriptToolbarProps = ThemedClassName<{\n role?: string;\n script: ScriptType;\n state: ScriptToolbarState;\n}>;\n\nconst createToolbar = (state: ScriptToolbarState) => {\n const templateSelect = createTemplateSelect();\n const format = createFormat();\n const gap = createGapSeparator();\n const deploy = createDeploy(state);\n return {\n nodes: [...templateSelect.nodes, ...format.nodes, ...gap.nodes, ...deploy.nodes],\n edges: [...templateSelect.edges, ...format.edges, ...gap.edges, ...deploy.edges],\n };\n};\n\nexport const ScriptToolbar = ({ script, role, state, classNames }: ScriptToolbarProps) => {\n const handleAction = useToolbarAction({ state, script });\n const toolbarCreator = useCallback(() => createToolbar(state), [state]);\n const menu = useMenuActions(toolbarCreator);\n\n return (\n <div role='none' className={stackItemContentToolbarClassNames(role)}>\n <ElevationProvider elevation={role === 'section' ? 'positioned' : 'base'}>\n <MenuProvider {...menu} onAction={handleAction} attendableId={fullyQualifiedId(script)}>\n <ToolbarMenu classNames={classNames} />\n </MenuProvider>\n </ElevationProvider>\n </div>\n );\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { javascript } from '@codemirror/lang-javascript';\nimport { defaultHighlightStyle } from '@codemirror/language';\nimport { Prec } from '@codemirror/state';\nimport { oneDarkHighlightStyle } from '@codemirror/theme-one-dark';\nimport { keymap } from '@codemirror/view';\nimport { tags } from '@lezer/highlight';\nimport { type VirtualTypeScriptEnvironment } from '@typescript/vfs';\nimport { continueKeymap } from '@valtown/codemirror-continue';\nimport { tsSync, tsFacet, tsLinter, tsAutocomplete, tsHover, type HoverInfo } from '@valtown/codemirror-ts';\nimport React from 'react';\n\nimport { type ThemeMode, useThemeContext } from '@dxos/react-ui';\nimport {\n autocomplete,\n createBasicExtensions,\n createThemeExtensions,\n editorFullWidth,\n type EditorInputMode,\n editorMonospace,\n EditorView,\n folding,\n InputModeExtensions,\n useTextEditor,\n type UseTextEditorProps,\n} from '@dxos/react-ui-editor';\nimport { isNonNullable } from '@dxos/util';\n\nexport type TypescriptEditorProps = {\n id: string;\n inputMode?: EditorInputMode;\n env?: VirtualTypeScriptEnvironment;\n toolbar?: boolean;\n} & Pick<UseTextEditorProps, 'className' | 'initialValue' | 'extensions' | 'scrollTo' | 'selection'>;\n\nexport const TypescriptEditor = ({\n id,\n env,\n className,\n initialValue,\n extensions,\n scrollTo,\n selection,\n toolbar,\n inputMode = 'vscode',\n}: TypescriptEditorProps) => {\n const { themeMode } = useThemeContext();\n const { parentRef, focusAttributes } = useTextEditor(\n () => ({\n id,\n initialValue,\n extensions: [\n extensions,\n createBasicExtensions({\n highlightActiveLine: true,\n indentWithTab: true,\n lineNumbers: true,\n lineWrapping: false,\n scrollPastEnd: true,\n }),\n createThemeExtensions({\n themeMode,\n syntaxHighlighting: true,\n slots: {\n content: { className: editorFullWidth },\n },\n }),\n // NOTE: Not using default editor gutter because folding for code works best right beside text.\n EditorView.theme({\n '.cm-gutters': {\n // Match margin from content.\n marginTop: '16px',\n background: 'var(--dx-baseSurface)',\n },\n }),\n InputModeExtensions[inputMode],\n folding(),\n // Continues block comments when you hit Enter.\n Prec.high(keymap.of(continueKeymap)),\n // TODO(burdon): Factor out.\n [\n editorMonospace,\n javascript({ typescript: true }),\n // https://github.com/val-town/codemirror-ts\n autocomplete({ override: env ? [tsAutocomplete()] : [] }),\n env\n ? [\n tsFacet.of({ env, path: `/src/${id}.ts` }),\n tsSync(),\n tsLinter(),\n tsHover({ renderTooltip: createTooltipRenderer(themeMode) }),\n ]\n : [],\n ],\n ].filter(isNonNullable),\n selection,\n scrollTo,\n }),\n [id, extensions, themeMode, inputMode, selection, scrollTo],\n );\n\n return (\n <div ref={parentRef} data-toolbar={toolbar ? 'enabled' : 'disabled'} className={className} {...focusAttributes} />\n );\n};\n\nconst createTooltipRenderer = (themeMode: ThemeMode) => {\n const theme = themeMode === 'dark' ? oneDarkHighlightStyle : defaultHighlightStyle;\n\n const classFromKind = (_kind: string) => {\n // E.g., localName, methodName, parameterName, etc.\n const kind = _kind.endsWith('Name') ? 'name' : _kind;\n const validTag = kind in tags;\n if (!validTag) {\n return '';\n }\n\n const tag = tags[kind as keyof typeof tags];\n if (typeof tag === 'function') {\n return '';\n }\n\n return theme.style([tag]) ?? '';\n };\n\n return (info: HoverInfo) => {\n const div = document.createElement('div');\n div.className = 'p-1 rounded border border-separator bg-baseSurface xs:max-w-80 max-w-lg';\n\n if (info.quickInfo?.displayParts) {\n for (const part of info.quickInfo.displayParts) {\n const span = div.appendChild(document.createElement('span'));\n span.className = classFromKind(part.kind);\n span.innerText = part.text;\n }\n }\n\n return { dom: div };\n };\n};\n\nexport default TypescriptEditor;\n"],
5
+ "mappings": "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",
6
+ "names": ["import_react", "import_echo", "import_react_ui_editor", "import_react_ui", "createToolbar", "state", "templateSelect", "createTemplateSelect", "format", "createFormat", "gap", "createGapSeparator", "deploy", "createDeploy", "nodes", "edges", "ScriptToolbar", "script", "role", "classNames", "handleAction", "useToolbarAction", "toolbarCreator", "useCallback", "menu", "useMenuActions", "React", "div", "className", "stackItemContentToolbarClassNames", "ElevationProvider", "elevation", "MenuProvider", "onAction", "attendableId", "fullyQualifiedId", "ToolbarMenu", "TypescriptEditor", "id", "env", "initialValue", "extensions", "scrollTo", "selection", "toolbar", "inputMode", "themeMode", "useThemeContext", "parentRef", "focusAttributes", "useTextEditor", "createBasicExtensions", "highlightActiveLine", "indentWithTab", "lineNumbers", "lineWrapping", "scrollPastEnd", "createThemeExtensions", "syntaxHighlighting", "slots", "content", "editorFullWidth", "EditorView", "theme", "marginTop", "background", "InputModeExtensions", "folding", "Prec", "high", "keymap", "of", "continueKeymap", "editorMonospace", "javascript", "typescript", "autocomplete", "override", "tsAutocomplete", "tsFacet", "path", "tsSync", "tsLinter", "tsHover", "renderTooltip", "createTooltipRenderer", "filter", "isNonNullable", "ref", "data-toolbar", "oneDarkHighlightStyle", "defaultHighlightStyle", "classFromKind", "_kind", "kind", "endsWith", "validTag", "tags", "tag", "style", "info", "document", "createElement", "quickInfo", "displayParts", "part", "span", "appendChild", "innerText", "text", "dom", "ScriptContainer", "settings", "editorInputMode", "identity", "useIdentity", "space", "getSpace", "useToolbarState", "useDeployState", "useMemo", "listener", "onChange", "source", "target", "changed", "createDataExtensions", "createDocAccessor", "StackItem", "Content", "mx", "stackItemContentEditorClassNames"]
7
+ }
@@ -16,19 +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 artifact_definition_SEGATFNH_exports = {};
20
- __export(artifact_definition_SEGATFNH_exports, {
19
+ var artifact_definition_C644EAYM_exports = {};
20
+ __export(artifact_definition_C644EAYM_exports, {
21
21
  default: () => artifact_definition_default
22
22
  });
23
- module.exports = __toCommonJS(artifact_definition_SEGATFNH_exports);
23
+ module.exports = __toCommonJS(artifact_definition_C644EAYM_exports);
24
24
  var import_chunk_NO5Y74F3 = require("./chunk-NO5Y74F3.cjs");
25
+ var import_effect = require("effect");
25
26
  var import_app_framework = require("@dxos/app-framework");
26
27
  var import_artifact = require("@dxos/artifact");
27
28
  var import_assistant = require("@dxos/assistant");
28
- var import_echo_schema = require("@dxos/echo-schema");
29
- var import_types = require("@dxos/functions/types");
29
+ var import_functions = require("@dxos/functions");
30
30
  var import_invariant = require("@dxos/invariant");
31
- var import_types2 = require("@dxos/plugin-space/types");
31
+ var import_types = require("@dxos/plugin-space/types");
32
32
  var import_echo = require("@dxos/react-client/echo");
33
33
  var import_schema = require("@dxos/schema");
34
34
  var __dxlog_file = "/home/runner/work/dxos/dxos/packages/plugins/plugin-script/src/capabilities/artifact-definition.ts";
@@ -82,28 +82,28 @@ var artifact_definition_default = () => {
82
82
  <apis>
83
83
  export function defineFunction(params: {
84
84
  description: string,
85
- inputSchema: S.Schema,
86
- outputSchema: S.Schema,
85
+ inputSchema: Schema.Schema,
86
+ outputSchema: Schema.Schema,
87
87
  handler: (params: { event: { data: TInput } }) => Promise<TOutput>
88
88
  }): FunctionDefinition
89
89
  /**
90
90
  * Effect Schema
91
91
  */
92
- export const S;
92
+ export const Schema;
93
93
 
94
94
  // Examples:
95
95
 
96
- S.String
97
- S.Number
98
- S.Boolean
99
- S.Struct({
100
- from: S.String.annotations({ description: 'The source currency' }),
101
- to: S.String.annotations({ description: 'The target currency' }),
96
+ Schema.String
97
+ Schema.Number
98
+ Schema.Boolean
99
+ Schema.Struct({
100
+ from: Schema.String.annotations({ description: 'The source currency' }),
101
+ to: Schema.String.annotations({ description: 'The target currency' }),
102
102
  })
103
- S.Array(S.String)
104
- S.Union(S.String, S.Number)
105
- S.optional(S.String)
106
- S.String.annotations({ description: 'The source currency' })
103
+ Schema.Array(Schema.String)
104
+ Schema.Union(Schema.String, Schema.Number)
105
+ Schema.optional(Schema.String)
106
+ Schema.String.annotations({ description: 'The source currency' })
107
107
  </apis>
108
108
 
109
109
  <handler_function>
@@ -124,13 +124,13 @@ var artifact_definition_default = () => {
124
124
  export default defineFunction({
125
125
  description: 'Returns the exchange rate between two currencies.',
126
126
 
127
- inputSchema: S.Struct({
128
- from: S.String.annotations({ description: 'The source currency' }),
129
- to: S.String.annotations({ description: 'The target currency' }),
127
+ inputSchema: Schema.Struct({
128
+ from: Schema.String.annotations({ description: 'The source currency' }),
129
+ to: Schema.String.annotations({ description: 'The target currency' }),
130
130
  }),
131
131
 
132
- outputSchema: S.Struct({
133
- rate: S.String.annotations({ description: 'The exchange rate' }),
132
+ outputSchema: Schema.Struct({
133
+ rate: Schema.String.annotations({ description: 'The exchange rate' }),
134
134
  }),
135
135
 
136
136
  handler: async ({
@@ -148,24 +148,24 @@ var artifact_definition_default = () => {
148
148
  });
149
149
  </example>
150
150
  `,
151
- schema: import_types.ScriptType,
151
+ schema: import_functions.ScriptType,
152
152
  tools: [
153
153
  (0, import_artifact.defineTool)(import_chunk_NO5Y74F3.meta.id, {
154
154
  name: "create",
155
155
  description: "Create a new script. Returns the artifact definition for the script",
156
156
  caption: "Creating script...",
157
- schema: import_echo_schema.S.Struct({
158
- name: import_echo_schema.S.String.annotations({
157
+ schema: import_effect.Schema.Struct({
158
+ name: import_effect.Schema.String.annotations({
159
159
  description: "The name of the script"
160
160
  }),
161
- code: import_echo_schema.S.String.annotations({
161
+ code: import_effect.Schema.String.annotations({
162
162
  description: "The full code of the script in JavaScript or TypeScript. Must be valid executable code."
163
163
  })
164
164
  }),
165
165
  execute: async ({ name, code }, { extensions }) => {
166
166
  (0, import_invariant.invariant)(extensions?.space, "No space", {
167
167
  F: __dxlog_file,
168
- L: 153,
168
+ L: 154,
169
169
  S: void 0,
170
170
  A: [
171
171
  "extensions?.space",
@@ -174,22 +174,22 @@ var artifact_definition_default = () => {
174
174
  });
175
175
  (0, import_invariant.invariant)(extensions?.dispatch, "No intent dispatcher", {
176
176
  F: __dxlog_file,
177
- L: 154,
177
+ L: 155,
178
178
  S: void 0,
179
179
  A: [
180
180
  "extensions?.dispatch",
181
181
  "'No intent dispatcher'"
182
182
  ]
183
183
  });
184
- const script = (0, import_echo.live)(import_types.ScriptType, {
184
+ const script = (0, import_echo.live)(import_functions.ScriptType, {
185
185
  name,
186
- source: (0, import_echo.makeRef)((0, import_echo.live)(import_schema.TextType, {
186
+ source: (0, import_echo.makeRef)((0, import_echo.live)(import_schema.DataType.Text, {
187
187
  content: code
188
188
  }))
189
189
  });
190
190
  extensions.space.db.add(script);
191
191
  await extensions.space.db.flush();
192
- const intent = (0, import_app_framework.createIntent)(import_types2.SpaceAction.AddObject, {
192
+ const intent = (0, import_app_framework.createIntent)(import_types.SpaceAction.AddObject, {
193
193
  target: extensions.space,
194
194
  object: script
195
195
  });
@@ -204,13 +204,16 @@ var artifact_definition_default = () => {
204
204
  name: "inspect",
205
205
  description: "Inspect a script. Returns the artifact definition for the script",
206
206
  caption: "Inspecting script...",
207
- schema: import_echo_schema.S.Struct({
208
- id: import_echo_schema.ObjectId
207
+ schema: import_effect.Schema.Struct({
208
+ // TODO(wittjosiah): ObjectId schema should be used here but it's not working.
209
+ id: import_effect.Schema.String.annotations({
210
+ description: "The ID of the script"
211
+ })
209
212
  }),
210
213
  execute: async ({ id }, { extensions }) => {
211
214
  (0, import_invariant.invariant)(extensions?.space, "No space", {
212
215
  F: __dxlog_file,
213
- L: 183,
216
+ L: 185,
214
217
  S: void 0,
215
218
  A: [
216
219
  "extensions?.space",
@@ -231,16 +234,19 @@ var artifact_definition_default = () => {
231
234
  name: "update",
232
235
  description: "Update a script. Returns the artifact definition for the script",
233
236
  caption: "Updating script...",
234
- schema: import_echo_schema.S.Struct({
235
- id: import_echo_schema.ObjectId,
236
- code: import_echo_schema.S.String.annotations({
237
+ schema: import_effect.Schema.Struct({
238
+ // TODO(wittjosiah): ObjectId schema should be used here but it's not working.
239
+ id: import_effect.Schema.String.annotations({
240
+ description: "The ID of the script to update"
241
+ }),
242
+ code: import_effect.Schema.String.annotations({
237
243
  description: "The full code of the script in JavaScript or TypeScript. Must be valid executable code."
238
244
  })
239
245
  }),
240
246
  execute: async ({ id, code }, { extensions }) => {
241
247
  (0, import_invariant.invariant)(extensions?.space, "No space", {
242
248
  F: __dxlog_file,
243
- L: 205,
249
+ L: 208,
244
250
  S: void 0,
245
251
  A: [
246
252
  "extensions?.space",
@@ -265,4 +271,4 @@ var artifact_definition_default = () => {
265
271
  });
266
272
  return (0, import_app_framework.contributes)(import_app_framework.Capabilities.ArtifactDefinition, definition);
267
273
  };
268
- //# sourceMappingURL=artifact-definition-SEGATFNH.cjs.map
274
+ //# sourceMappingURL=artifact-definition-C644EAYM.cjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/capabilities/artifact-definition.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport { Schema } from 'effect';\n\nimport { Capabilities, contributes, createIntent, type PromiseIntentDispatcher } from '@dxos/app-framework';\nimport { defineArtifact, defineTool, ToolResult } from '@dxos/artifact';\nimport { createArtifactElement } from '@dxos/assistant';\nimport { ScriptType } from '@dxos/functions';\nimport { invariant } from '@dxos/invariant';\nimport { SpaceAction } from '@dxos/plugin-space/types';\nimport { live, makeRef, type Space } from '@dxos/react-client/echo';\nimport { DataType } from '@dxos/schema';\n\nimport { meta } from '../meta';\n// TODO(burdon): Factor out.\ndeclare global {\n interface ToolContextExtensions {\n space?: Space;\n dispatch?: PromiseIntentDispatcher;\n }\n}\n\nexport default () => {\n const definition = defineArtifact({\n id: `artifact:${meta.id}`,\n name: meta.name,\n // TODO(dmaretskyi): Since writing scripts requires a lot of domain knowledge,\n // we should offload the work of synthesizing the code to a separate model.\n // The main reasoning model will give it a concrete task and the script model will synthesize the code, knowing all the docs.\n instructions: `\n If the user explicitly requests you to write a script, you can create one.\n If the user requests you to change one of the existing script, you can update it.\n You must not create a script unless the user explicitly requests it.\n Scripts are short code pieces of executable code that can be used to perform computations, integrate with external systems, and perform automated tasks.\n Each script must follow as strict shape for the definition but the body can contain any valid executable code.\n Scripts are written in JavaScript or TypeScript.\n Each script must define an input schema and output schema.\n Each script must have its own detailed description.\n\n Important: You cannot execute scripts. Scripts are only available as tools after the user deploys them. You must only call the available tools.\n\n Description:\n The description is a detailed description of the script.\n It is used to describe the script's purpose, input, and output.\n The description is used to generate the script's documentation.\n The description is also goes into the script metadata.\n The description is used by AI to understand the script and its purpose.\n The description must provide cases on when the script should be used.\n\n Schema: \n The schema is defined using a schema-DSL library called Effect Schema.\n The input schema describes the arguments that the script accepts.\n The output schema describes the result that the script produces.\n The schema is used to validate the script's input and output.\n The schema is also goes into the script metadata.\n The properties in the schema must have valid descriptions.\n The input and output schemas must both be a struct of fields.\n\n Restricts:\n The scripts can only import code from \"dxos:functions\" module. No other modules are allowed.\n Some web APIs are available - like fetch.\n\n Reasoning:\n Before writing a script, synthesize the following information:\n - Description\n - What APIs will be used.\n - Detailed input schema\n - Detailed output schema\n\n <apis>\n export function defineFunction(params: { \n description: string, \n inputSchema: Schema.Schema, \n outputSchema: Schema.Schema, \n handler: (params: { event: { data: TInput } }) => Promise<TOutput> \n }): FunctionDefinition\n /**\n * Effect Schema\n */\n export const Schema; \n\n // Examples: \n\n Schema.String\n Schema.Number\n Schema.Boolean\n Schema.Struct({\n from: Schema.String.annotations({ description: 'The source currency' }),\n to: Schema.String.annotations({ description: 'The target currency' }),\n })\n Schema.Array(Schema.String)\n Schema.Union(Schema.String, Schema.Number)\n Schema.optional(Schema.String)\n Schema.String.annotations({ description: 'The source currency' })\n </apis>\n\n <handler_function>\n Async function that takes the argument in the form of:\n\n type HandlerFunctionParam = {\n event: {\n data: T // The input schema\n },\n }\n\n The function must return the result that matches the output schema.\n </handler_function>\n \n <example>\n import { defineFunction, S } from 'dxos:functions';\n\n export default defineFunction({\n description: 'Returns the exchange rate between two currencies.',\n\n inputSchema: Schema.Struct({\n from: Schema.String.annotations({ description: 'The source currency' }),\n to: Schema.String.annotations({ description: 'The target currency' }),\n }),\n\n outputSchema: Schema.Struct({\n rate: Schema.String.annotations({ description: 'The exchange rate' }),\n }),\n\n handler: async ({\n event: {\n data: { from, to },\n },\n }: any) => {\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 { rate: rates[to].toString() };\n },\n });\n </example>\n `,\n schema: ScriptType,\n tools: [\n defineTool(meta.id, {\n name: 'create',\n description: 'Create a new script. Returns the artifact definition for the script',\n caption: 'Creating script...',\n schema: Schema.Struct({\n name: Schema.String.annotations({ description: 'The name of the script' }),\n code: Schema.String.annotations({\n description: 'The full code of the script in JavaScript or TypeScript. Must be valid executable code.',\n }),\n }),\n execute: async ({ name, code }, { extensions }) => {\n invariant(extensions?.space, 'No space');\n invariant(extensions?.dispatch, 'No intent dispatcher');\n const script = live(ScriptType, {\n name,\n source: makeRef(\n live(DataType.Text, {\n content: code,\n }),\n ),\n });\n extensions.space.db.add(script);\n await extensions.space.db.flush();\n\n const intent = createIntent(SpaceAction.AddObject, { target: extensions.space, object: script });\n const { data, error } = await extensions.dispatch(intent);\n if (!data || error) {\n return ToolResult.Error(error?.message ?? 'Failed to create chess game');\n }\n\n return ToolResult.Success(createArtifactElement(script.id));\n },\n }),\n defineTool(meta.id, {\n name: 'inspect',\n description: 'Inspect a script. Returns the artifact definition for the script',\n caption: 'Inspecting script...',\n schema: Schema.Struct({\n // TODO(wittjosiah): ObjectId schema should be used here but it's not working.\n id: Schema.String.annotations({ description: 'The ID of the script' }),\n }),\n execute: async ({ id }, { extensions }) => {\n invariant(extensions?.space, 'No space');\n\n const script = (await extensions.space.db.query({ id }).first()) as ScriptType;\n const { content } = await script.source.load();\n\n return ToolResult.Success({\n name: script.name,\n code: content,\n });\n },\n }),\n defineTool(meta.id, {\n name: 'update',\n description: 'Update a script. Returns the artifact definition for the script',\n caption: 'Updating script...',\n schema: Schema.Struct({\n // TODO(wittjosiah): ObjectId schema should be used here but it's not working.\n id: Schema.String.annotations({ description: 'The ID of the script to update' }),\n code: Schema.String.annotations({\n description: 'The full code of the script in JavaScript or TypeScript. Must be valid executable code.',\n }),\n }),\n execute: async ({ id, code }, { extensions }) => {\n invariant(extensions?.space, 'No space');\n\n const script = (await extensions.space.db.query({ id }).first()) as ScriptType;\n const source = await script.source.load();\n if (!source) {\n return ToolResult.Error('Script not found');\n }\n\n source.content = code;\n await extensions.space?.db.flush();\n\n return ToolResult.Success({\n name: script.name,\n });\n },\n }),\n ],\n });\n\n return contributes(Capabilities.ArtifactDefinition, definition);\n};\n"],
5
+ "mappings": "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",
6
+ "names": ["definition", "defineArtifact", "id", "meta", "name", "instructions", "schema", "ScriptType", "tools", "defineTool", "description", "caption", "Schema", "Struct", "String", "annotations", "code", "execute", "extensions", "invariant", "space", "dispatch", "script", "live", "source", "makeRef", "DataType", "Text", "content", "db", "add", "flush", "intent", "createIntent", "SpaceAction", "AddObject", "target", "object", "data", "error", "ToolResult", "Error", "message", "Success", "createArtifactElement", "query", "first", "load", "contributes", "Capabilities", "ArtifactDefinition"]
7
+ }
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var chunk_DGFQHBA7_exports = {};
20
+ __export(chunk_DGFQHBA7_exports, {
21
+ templates: () => templates
22
+ });
23
+ module.exports = __toCommonJS(chunk_DGFQHBA7_exports);
24
+ 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 === TemplateInputType.VALUE) {\n value = String(input.value);\n } else if (input.type === TemplateInputType.RETRIEVER) {\n value = await getContext({ space });\n } else if (input.type === TemplateInputType.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 TemplateInputType {\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";
25
+ var chess_default = "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { defineFunction, S } from 'dxos:functions';\n// @ts-ignore\nimport { Chess } from 'https://esm.sh/chess.js@0.13.1';\n\nexport default defineFunction({\n description: 'Plays a random move in a chess game.',\n\n inputSchema: S.Struct({\n changedObjectId: S.String.annotations({\n description: 'The objects to play the game on.',\n }),\n player: S.optional(S.Literal('w', 'b')).annotations({\n description: 'The player to play the game as.',\n }),\n }),\n\n outputSchema: S.Struct({\n state: S.String.annotations({\n description: 'The state of the game as an ASCII art board.',\n }),\n }),\n\n handler: async ({\n event: {\n data: { changedObjectId, player = 'b' },\n },\n context: { space },\n }: any) => {\n const { pgn } = await space.db.query({ id: changedObjectId }).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.db.update({ id: changedObjectId }, { pgn: newPgn, fen: game.fen() });\n return { state: game.ascii() };\n },\n});\n";
26
+ var data_generator_default = "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { defineFunction, S, create, Expando } from 'dxos:functions';\n// @ts-ignore\nimport { randText } from 'https://esm.sh/@ngneat/falso@7.1.1';\n\nexport default defineFunction({\n inputSchema: S.Struct({\n documentAmount: S.optional(S.Number),\n textSize: S.optional(S.Number),\n mutationAmount: S.optional(S.Number),\n }),\n\n outputSchema: S.Struct({}),\n\n handler: async ({\n event: {\n data: { documentAmount = 1, textSize = 10, mutationAmount = 0 },\n },\n context: { space },\n }: any) => {\n await space.db.graph.schemaRegistry.addSchema([Expando]);\n const result: Record<string, any> = {};\n const objects: Expando[] = [];\n\n // Create objects.\n for (let i = 0; i < documentAmount; i++) {\n const obj = space.db.add(\n create(Expando, {\n name: 'scriptGenerated',\n content: randText({ charCount: textSize }),\n }),\n );\n objects.push(obj);\n const objectResult: any = {};\n // Mutate the object.\n for (let i = 0; i < mutationAmount; i++) {\n obj.content = randText({ charCount: textSize });\n }\n objectResult.mutations = mutationAmount;\n objectResult.contentLength = obj.content.length;\n result[obj.id] = objectResult;\n }\n\n // Flush and wait for data to propagate.\n await space.db.flush();\n await new Promise((resolve) => setTimeout(resolve, 10_000));\n return result;\n },\n});\n";
27
+ var discord_default = "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { create, defineFunction, DXN, Filter, ObjectId, S } from 'dxos:functions';\nimport {\n FetchHttpClient,\n // @ts-ignore\n} from 'https://esm.sh/@effect/platform@0.77.2?deps=effect@3.13.3';\n// @ts-ignore\nimport { DiscordConfig, DiscordREST, DiscordRESTMemoryLive } from 'https://esm.sh/dfx@0.113.0?deps=effect@3.13.3';\n// @ts-ignore\nimport { Effect, Config, Redacted, Ref } from 'https://esm.sh/effect@3.13.3';\n\nimport { Type } from '@dxos/echo';\n\nconst MessageSchema = S.Struct({\n id: ObjectId,\n foreignId: S.Any, // bigint?\n from: S.String,\n created: S.String,\n content: S.String,\n}).pipe(\n Type.def({\n typename: 'example.com/type/Message',\n version: '0.1.0',\n }),\n);\n\nconst DEFAULT_AFTER = 1704067200; // 2024-01-01\n\nconst generateSnowflake = (unixTimestamp: number): bigint => {\n const discordEpoch = 1420070400000n; // Discord Epoch (ms)\n return (BigInt(unixTimestamp * 1000) - discordEpoch) << 22n;\n};\n\nexport default defineFunction({\n inputSchema: S.Struct({\n // TODO(wittjosiah): Remove. This is used to provide a terminal for a cron trigger.\n tick: S.optional(S.String),\n channelId: S.String,\n after: S.optional(S.Number),\n pageSize: S.optional(S.Number),\n queueId: S.String,\n }),\n\n outputSchema: S.Struct({\n newMessages: S.Number,\n }),\n\n handler: ({\n event: {\n data: { channelId, queueId, after = DEFAULT_AFTER, pageSize = 5 },\n },\n context: { space },\n }: any) =>\n Effect.gen(function* () {\n const { token } = yield* Effect.tryPromise({\n try: () => space.db.query(Filter.typename('dxos.org/type/AccessToken', { source: 'discord.com' })).first(),\n catch: (e: any) => e,\n });\n const { objects } = yield* Effect.tryPromise({\n try: () => space.queues.queryQueue(DXN.parse(queueId)),\n catch: (e: any) => e,\n });\n const backfill = objects.length === 0;\n const newMessages = yield* Ref.make(0);\n const lastMessage = yield* Ref.make(objects.at(-1));\n\n const enqueueMessages = Effect.gen(function* () {\n const rest = yield* DiscordREST;\n\n while (true) {\n const last = yield* Ref.get(lastMessage);\n const options = {\n after: backfill && !last ? `${generateSnowflake(after)}` : last?.foreignId,\n limit: pageSize,\n };\n const messages = yield* rest.getChannelMessages(channelId, options).pipe((res: any) => res.json);\n const queueMessages = messages\n .map((message: any) =>\n create(MessageSchema, {\n id: ObjectId.random(),\n foreignId: message.id,\n from: message.author.username,\n created: message.timestamp,\n content: message.content,\n }),\n )\n .toReversed();\n if (queueMessages.length > 0) {\n yield* Effect.tryPromise({\n try: () => space.queues.insertIntoQueue(DXN.parse(queueId), queueMessages),\n catch: (e: any) => e,\n });\n yield* Ref.update(newMessages, (n: any) => n + queueMessages.length);\n yield* Ref.update(lastMessage, (m: any) => queueMessages.at(-1));\n }\n if (messages.length < pageSize) {\n break;\n }\n }\n }).pipe(\n Effect.provide(DiscordRESTMemoryLive),\n Effect.provide(\n DiscordConfig.layerConfig({\n token: Config.succeed(Redacted.make(token)),\n }),\n ),\n Effect.provide(FetchHttpClient.layer),\n );\n\n yield* enqueueMessages;\n return { newMessages: yield* Ref.get(newMessages) };\n }),\n});\n";
28
+ 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 ?? {}), {\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n};\n";
29
+ var email_default = "//\n// Copyright 2024 DXOS.org\n//\n\n/**\n * Appends a message to the end of a Document configured through a trigger.\n * Trigger must have a targetDocumentId field set in Meta.\n */\nexport default async ({\n event: {\n data: { request },\n },\n context: { space },\n}: any) => {\n const { data, trigger } = (await request.json()) as RequestPayload;\n\n const documentId = trigger.meta.targetDocumentId;\n const document = await space.db.query({ id: documentId }, { format: 'plain' }).first();\n\n const contentId = document.content['/'].split(':')[3];\n const documentContent = await space.db.query({ id: contentId }, { format: 'plain' }).first();\n const modifiedContent = [\n documentContent.content,\n '',\n '---',\n `**From:** ${data.from}`,\n `**Subject:** ${data.subject}`,\n `**Date:** ${data.created}`,\n '',\n data.body,\n ].join('\\n');\n\n await space.db.update({ id: contentId }, { content: modifiedContent });\n\n return new Response(JSON.stringify({ success: true }));\n};\n\ntype RequestPayload = {\n data: { from: string; subject: string; created: string; body: string };\n trigger: { meta: { targetDocumentId: string } };\n};\n";
30
+ var forex_effect_default = "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { S, defineFunction } from 'dxos:functions';\nimport {\n HttpClient,\n HttpClientRequest,\n FetchHttpClient,\n // @ts-ignore\n} from 'https://esm.sh/@effect/platform@0.77.2?deps=effect@3.13.3';\n// @ts-ignore\nimport { Effect, Schedule } from 'https://esm.sh/effect@3.13.3';\n\nexport default defineFunction({\n description: 'Returns the exchange rate between two currencies.',\n\n inputSchema: S.Struct({\n from: S.String.annotations({ description: 'The source currency' }),\n to: S.String.annotations({ description: 'The target currency' }),\n }),\n\n outputSchema: S.String.annotations({ description: 'The exchange rate between the two currencies' }),\n\n handler: async ({\n event: {\n data: { from, to },\n },\n }: any) =>\n Effect.gen(function* () {\n const res = yield* HttpClientRequest.get(`https://free.ratesdb.com/v1/rates?from=${from}&to=${to}`).pipe(\n HttpClient.execute,\n Effect.flatMap((res: any) => res.json),\n Effect.timeout('1 second'),\n Effect.retry(Schedule.exponential(1_000).pipe(Schedule.compose(Schedule.recurs(3)))),\n Effect.scoped,\n );\n\n return res.data.rates[to].toString();\n }).pipe(Effect.provide(FetchHttpClient.layer)),\n});\n";
31
+ var forex_default = "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { defineFunction, S } from 'dxos:functions';\n\nexport default defineFunction({\n description: 'Returns the exchange rate between two currencies.',\n\n inputSchema: S.Struct({\n from: S.String.annotations({ description: 'The source currency' }),\n to: S.String.annotations({ description: 'The target currency' }),\n }),\n\n handler: async ({\n event: {\n data: { from, to },\n },\n }: any) => {\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 rates[to].toString();\n },\n});\n";
32
+ var gmail_default = "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { create, defineFunction, Filter, ObjectId, S } from 'dxos:functions';\n// @ts-ignore\nimport {\n HttpClient,\n HttpClientRequest,\n FetchHttpClient,\n // @ts-ignore\n} from 'https://esm.sh/@effect/platform@0.77.2?deps=effect@3.13.3';\n// @ts-ignore\nimport { format, subDays } from 'https://esm.sh/date-fns@3.3.1';\n// @ts-ignore\nimport { pipe, Chunk, Effect, Ref, Schedule, Stream } from 'https://esm.sh/effect@3.13.3';\n\nimport { Type } from '@dxos/echo';\n\nexport default defineFunction({\n inputSchema: S.Struct({\n mailboxId: S.String,\n userId: S.optional(S.String).pipe(S.withDecodingDefault(() => 'me')),\n after: S.optional(S.Union(S.Number, S.String)).pipe(\n S.withDecodingDefault(() => format(subDays(new Date(), 30), 'yyyy-MM-dd')),\n ),\n pageSize: S.optional(S.Number).pipe(S.withDecodingDefault(() => 100)),\n // TODO(wittjosiah): Remove. This is used to provide a terminal for a cron trigger.\n tick: S.optional(S.String),\n }),\n\n outputSchema: S.Struct({\n newMessages: S.Number,\n }),\n\n handler: ({\n context: { space },\n event: {\n data: { mailboxId, userId, after, pageSize },\n },\n }: any) =>\n Effect.gen(function* () {\n const { token } = yield* Effect.tryPromise({\n try: () => space.db.query(Filter.typename('dxos.org/type/AccessToken', { source: 'gmail.com' })).first(),\n catch: (e: any) => e,\n });\n\n // NOTE: Google API bundles size is v. large and caused runtime issues.\n const makeRequest = (url: string) =>\n pipe(\n url,\n HttpClientRequest.get,\n HttpClientRequest.setHeaders({ Authorization: `Bearer ${token}`, Accept: 'application/json' }),\n HttpClient.execute,\n Effect.flatMap((res: any) => res.json),\n Effect.timeout('1 second'),\n Effect.retry(Schedule.exponential(1000).pipe(Schedule.compose(Schedule.recurs(3)))),\n Effect.scoped,\n );\n\n const listMessages = (userId: string, q: string, pageSize: number, pageToken: string | null) =>\n makeRequest(getUrl(userId, undefined, { q, pageSize, pageToken }));\n\n const getMessage = (userId: string, messageId: string) => makeRequest(getUrl(userId, messageId));\n\n const mailbox = yield* Effect.tryPromise({\n try: () => space.db.query({ id: mailboxId }).first(),\n catch: (e: any) => e,\n });\n const { objects } = yield* Effect.tryPromise({\n try: () => space.queues.queryQueue(mailbox.queue.dxn),\n catch: (e: any) => e,\n });\n const newMessages = yield* Ref.make([]);\n const nextPage = yield* Ref.make(null);\n\n do {\n const last = objects.at(-1);\n const q = last\n ? `in:inbox after:${Math.floor(new Date(last.created).getTime() / 1000)}`\n : `in:inbox after:${after}`;\n const pageToken = yield* Ref.get(nextPage);\n const { messages, nextPageToken } = yield* listMessages(userId, q, pageSize, pageToken);\n yield* Ref.update(nextPage, () => nextPageToken);\n for (const message of messages) {\n const messageDetails = yield* getMessage(userId, message.id);\n const created = new Date(parseInt(messageDetails.internalDate)).toISOString();\n const from = messageDetails.payload.headers.find((h: any) => h.name === 'From');\n const sender = from && parseEmailString(from.value);\n // TODO(wittjosiah): Improve parsing of email contents.\n const content =\n messageDetails.payload.body?.data ??\n messageDetails.payload.parts?.find((p: any) => p.mimeType === 'text/plain')?.body.data;\n // Skip the message if content or sender is missing.\n // Skip the message if it's the same as the last message.\n // TODO(wittjosiah): This comparison should be done via foreignId probably.\n if (!content || !sender || created === last?.created) {\n continue;\n }\n const subject = messageDetails.payload.headers.find((h: any) => h.name === 'Subject')?.value;\n const object = create(MessageType, {\n id: ObjectId.random(),\n created,\n sender,\n blocks: [\n {\n type: 'text',\n text: Buffer.from(content, 'base64').toString('utf-8'),\n },\n ],\n properties: {\n subject,\n threadId: message.threadId,\n },\n });\n // TODO(wittjosiah): Set foreignId in object meta.\n yield* Ref.update(newMessages, (n: any) => [object, ...n]);\n }\n } while (yield* Ref.get(nextPage));\n\n const queueMessages = yield* Ref.get(newMessages);\n if (queueMessages.length > 0) {\n yield* pipe(\n queueMessages,\n Stream.fromIterable,\n Stream.grouped(10),\n Stream.flatMap((batch: any) =>\n Effect.tryPromise({\n try: () => space.queues.insertIntoQueue(mailbox.queue.dxn, Chunk.toReadonlyArray(batch)),\n catch: (e: any) => e,\n }),\n ),\n Stream.runDrain,\n );\n }\n\n return { newMessages: queueMessages.length };\n }).pipe(Effect.provide(FetchHttpClient.layer)),\n});\n\nconst getUrl = (userId: string, messageId?: string, params?: Record<string, any>) => {\n const api = new URL(\n [`https://gmail.googleapis.com/gmail/v1/users/${userId}/messages`, messageId].filter(Boolean).join('/'),\n );\n Object.entries(params ?? {}).forEach(([key, value]) => api.searchParams.set(key, value));\n return api.toString();\n};\n\n/**\n * Parses an email string in the format \"Name <email@example.com>\" into separate name and email components.\n */\nconst parseEmailString = (emailString: string): { name?: string; email: string } | undefined => {\n const match = emailString.match(/^([^<]+?)\\s*<([^>]+@[^>]+)>$/);\n if (match) {\n const [, name, email] = match;\n return {\n name: name.trim(),\n email: email.trim(),\n };\n }\n\n return undefined;\n};\n\n//\n// Schemas\n// TODO(wittjosiah): These schemas should be imported from @dxos/S.\n//\n\nconst ActorRoles = ['user', 'assistant'] as const;\nconst ActorRole = S.Literal(...ActorRoles);\ntype ActorRole = S.S.Type<typeof ActorRole>;\n\nconst ActorSchema = S.Struct({\n identityKey: S.optional(S.String),\n email: S.optional(S.String),\n name: S.optional(S.String),\n role: S.optional(ActorRole),\n});\n\nconst AbstractContentBlock = S.Struct({\n pending: S.optional(S.Boolean),\n});\ntype AbstractContentBlock = S.S.Type<typeof AbstractContentBlock>;\nconst TextContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('text'),\n disposition: S.optional(S.String),\n text: S.String,\n }),\n).pipe(S.mutable);\ntype TextContentBlock = S.S.Type<typeof TextContentBlock>;\nconst JsonContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('json'),\n disposition: S.optional(S.String),\n data: S.String,\n }),\n).pipe(S.mutable);\ntype JsonContentBlock = S.S.Type<typeof JsonContentBlock>;\nconst Base64ImageSource = S.Struct({\n type: S.Literal('base64'),\n mediaType: S.String,\n data: S.String,\n}).pipe(S.mutable);\nconst HttpImageSource = S.Struct({\n type: S.Literal('http'),\n url: S.String,\n}).pipe(S.mutable);\nconst ImageSource = S.Union(Base64ImageSource, HttpImageSource);\ntype ImageSource = S.S.Type<typeof ImageSource>;\nconst ImageContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('image'),\n id: S.optional(S.String),\n source: S.optional(ImageSource),\n }),\n).pipe(S.mutable);\ntype ImageContentBlock = S.S.Type<typeof ImageContentBlock>;\nconst ReferenceContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('reference'),\n reference: S.Any,\n }),\n).pipe(S.mutable);\ntype ReferenceContentBlock = S.S.Type<typeof ReferenceContentBlock>;\nconst MessageContentBlock = S.Union(TextContentBlock, JsonContentBlock, ImageContentBlock, ReferenceContentBlock);\n\nconst MessageType = S.Struct({\n id: ObjectId,\n created: S.String.annotations({\n description: 'ISO date string when the message was sent.',\n }),\n sender: ActorSchema.annotations({\n description: 'Identity of the message sender.',\n }),\n blocks: S.Array(MessageContentBlock).annotations({\n description: 'Contents of the message.',\n }),\n properties: S.optional(\n S.mutable(\n S.Record({ key: S.String, value: S.Any }).annotations({\n description: 'Custom properties for specific message types (e.g. attention context, email subject, etc.).',\n }),\n ),\n ),\n}).pipe(\n Type.def({\n typename: 'dxos.org/type/Message',\n version: '0.1.0',\n }),\n);\ntype MessageType = S.S.Type<typeof MessageType>;\n";
33
+ var removeHeader = (str) => str.split("\n").slice(4).join("\n");
34
+ var templates = [
35
+ {
36
+ id: "dxos.org/script/echo",
37
+ name: "Echo",
38
+ source: removeHeader(echo_default)
39
+ },
40
+ {
41
+ id: "dxos.org/script/forex",
42
+ name: "Forex",
43
+ source: removeHeader(forex_default)
44
+ },
45
+ {
46
+ id: "dxos.org/script/forex-effect",
47
+ name: "Forex (Effect)",
48
+ source: removeHeader(forex_effect_default)
49
+ },
50
+ {
51
+ id: "dxos.org/script/gpt",
52
+ name: "Gpt",
53
+ source: removeHeader(chat_default),
54
+ presetId: "dxos.org/function/gpt"
55
+ },
56
+ {
57
+ id: "dxos.org/script/chess",
58
+ name: "Chess",
59
+ source: removeHeader(chess_default),
60
+ presetId: "dxos.org/function/chess"
61
+ },
62
+ {
63
+ id: "dxos.org/script/email",
64
+ name: "Email",
65
+ source: removeHeader(email_default),
66
+ presetId: "dxos.org/function/email"
67
+ },
68
+ {
69
+ id: "dxos.org/script/discord",
70
+ name: "Discord",
71
+ source: removeHeader(discord_default),
72
+ presetId: "dxos.org/function/discord"
73
+ },
74
+ {
75
+ id: "dxos.org/script/gmail",
76
+ name: "Gmail",
77
+ source: removeHeader(gmail_default),
78
+ presetId: "dxos.org/function/gmail"
79
+ },
80
+ {
81
+ id: "dxos.org/script/data-generator",
82
+ name: "Data Generator",
83
+ source: removeHeader(data_generator_default),
84
+ presetId: "dxos.org/function/data-generator"
85
+ }
86
+ ];
87
+ // Annotate the CommonJS export names for ESM import in node:
88
+ 0 && (module.exports = {
89
+ templates
90
+ });
91
+ //# sourceMappingURL=chunk-DGFQHBA7.cjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["raw-loader:./chat.ts?raw", "raw-loader:./chess.ts?raw", "raw-loader:./data-generator.ts?raw", "raw-loader:./discord.ts?raw", "raw-loader:./echo.ts?raw", "raw-loader:./email.ts?raw", "raw-loader:./forex-effect.ts?raw", "raw-loader:./forex.ts?raw", "raw-loader:./gmail.ts?raw", "../../../src/templates/index.ts"],
4
+ "sourcesContent": ["//\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 === TemplateInputType.VALUE) {\n value = String(input.value);\n } else if (input.type === TemplateInputType.RETRIEVER) {\n value = await getContext({ space });\n } else if (input.type === TemplateInputType.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 TemplateInputType {\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 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { defineFunction, S } from 'dxos:functions';\n// @ts-ignore\nimport { Chess } from 'https://esm.sh/chess.js@0.13.1';\n\nexport default defineFunction({\n description: 'Plays a random move in a chess game.',\n\n inputSchema: S.Struct({\n changedObjectId: S.String.annotations({\n description: 'The objects to play the game on.',\n }),\n player: S.optional(S.Literal('w', 'b')).annotations({\n description: 'The player to play the game as.',\n }),\n }),\n\n outputSchema: S.Struct({\n state: S.String.annotations({\n description: 'The state of the game as an ASCII art board.',\n }),\n }),\n\n handler: async ({\n event: {\n data: { changedObjectId, player = 'b' },\n },\n context: { space },\n }: any) => {\n const { pgn } = await space.db.query({ id: changedObjectId }).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.db.update({ id: changedObjectId }, { pgn: newPgn, fen: game.fen() });\n return { state: game.ascii() };\n },\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { defineFunction, S, create, Expando } from 'dxos:functions';\n// @ts-ignore\nimport { randText } from 'https://esm.sh/@ngneat/falso@7.1.1';\n\nexport default defineFunction({\n inputSchema: S.Struct({\n documentAmount: S.optional(S.Number),\n textSize: S.optional(S.Number),\n mutationAmount: S.optional(S.Number),\n }),\n\n outputSchema: S.Struct({}),\n\n handler: async ({\n event: {\n data: { documentAmount = 1, textSize = 10, mutationAmount = 0 },\n },\n context: { space },\n }: any) => {\n await space.db.graph.schemaRegistry.addSchema([Expando]);\n const result: Record<string, any> = {};\n const objects: Expando[] = [];\n\n // Create objects.\n for (let i = 0; i < documentAmount; i++) {\n const obj = space.db.add(\n create(Expando, {\n name: 'scriptGenerated',\n content: randText({ charCount: textSize }),\n }),\n );\n objects.push(obj);\n const objectResult: any = {};\n // Mutate the object.\n for (let i = 0; i < mutationAmount; i++) {\n obj.content = randText({ charCount: textSize });\n }\n objectResult.mutations = mutationAmount;\n objectResult.contentLength = obj.content.length;\n result[obj.id] = objectResult;\n }\n\n // Flush and wait for data to propagate.\n await space.db.flush();\n await new Promise((resolve) => setTimeout(resolve, 10_000));\n return result;\n },\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { create, defineFunction, DXN, Filter, ObjectId, S } from 'dxos:functions';\nimport {\n FetchHttpClient,\n // @ts-ignore\n} from 'https://esm.sh/@effect/platform@0.77.2?deps=effect@3.13.3';\n// @ts-ignore\nimport { DiscordConfig, DiscordREST, DiscordRESTMemoryLive } from 'https://esm.sh/dfx@0.113.0?deps=effect@3.13.3';\n// @ts-ignore\nimport { Effect, Config, Redacted, Ref } from 'https://esm.sh/effect@3.13.3';\n\nimport { Type } from '@dxos/echo';\n\nconst MessageSchema = S.Struct({\n id: ObjectId,\n foreignId: S.Any, // bigint?\n from: S.String,\n created: S.String,\n content: S.String,\n}).pipe(\n Type.def({\n typename: 'example.com/type/Message',\n version: '0.1.0',\n }),\n);\n\nconst DEFAULT_AFTER = 1704067200; // 2024-01-01\n\nconst generateSnowflake = (unixTimestamp: number): bigint => {\n const discordEpoch = 1420070400000n; // Discord Epoch (ms)\n return (BigInt(unixTimestamp * 1000) - discordEpoch) << 22n;\n};\n\nexport default defineFunction({\n inputSchema: S.Struct({\n // TODO(wittjosiah): Remove. This is used to provide a terminal for a cron trigger.\n tick: S.optional(S.String),\n channelId: S.String,\n after: S.optional(S.Number),\n pageSize: S.optional(S.Number),\n queueId: S.String,\n }),\n\n outputSchema: S.Struct({\n newMessages: S.Number,\n }),\n\n handler: ({\n event: {\n data: { channelId, queueId, after = DEFAULT_AFTER, pageSize = 5 },\n },\n context: { space },\n }: any) =>\n Effect.gen(function* () {\n const { token } = yield* Effect.tryPromise({\n try: () => space.db.query(Filter.typename('dxos.org/type/AccessToken', { source: 'discord.com' })).first(),\n catch: (e: any) => e,\n });\n const { objects } = yield* Effect.tryPromise({\n try: () => space.queues.queryQueue(DXN.parse(queueId)),\n catch: (e: any) => e,\n });\n const backfill = objects.length === 0;\n const newMessages = yield* Ref.make(0);\n const lastMessage = yield* Ref.make(objects.at(-1));\n\n const enqueueMessages = Effect.gen(function* () {\n const rest = yield* DiscordREST;\n\n while (true) {\n const last = yield* Ref.get(lastMessage);\n const options = {\n after: backfill && !last ? `${generateSnowflake(after)}` : last?.foreignId,\n limit: pageSize,\n };\n const messages = yield* rest.getChannelMessages(channelId, options).pipe((res: any) => res.json);\n const queueMessages = messages\n .map((message: any) =>\n create(MessageSchema, {\n id: ObjectId.random(),\n foreignId: message.id,\n from: message.author.username,\n created: message.timestamp,\n content: message.content,\n }),\n )\n .toReversed();\n if (queueMessages.length > 0) {\n yield* Effect.tryPromise({\n try: () => space.queues.insertIntoQueue(DXN.parse(queueId), queueMessages),\n catch: (e: any) => e,\n });\n yield* Ref.update(newMessages, (n: any) => n + queueMessages.length);\n yield* Ref.update(lastMessage, (m: any) => queueMessages.at(-1));\n }\n if (messages.length < pageSize) {\n break;\n }\n }\n }).pipe(\n Effect.provide(DiscordRESTMemoryLive),\n Effect.provide(\n DiscordConfig.layerConfig({\n token: Config.succeed(Redacted.make(token)),\n }),\n ),\n Effect.provide(FetchHttpClient.layer),\n );\n\n yield* enqueueMessages;\n return { newMessages: yield* Ref.get(newMessages) };\n }),\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 ?? {}), {\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\n/**\n * Appends a message to the end of a Document configured through a trigger.\n * Trigger must have a targetDocumentId field set in Meta.\n */\nexport default async ({\n event: {\n data: { request },\n },\n context: { space },\n}: any) => {\n const { data, trigger } = (await request.json()) as RequestPayload;\n\n const documentId = trigger.meta.targetDocumentId;\n const document = await space.db.query({ id: documentId }, { format: 'plain' }).first();\n\n const contentId = document.content['/'].split(':')[3];\n const documentContent = await space.db.query({ id: contentId }, { format: 'plain' }).first();\n const modifiedContent = [\n documentContent.content,\n '',\n '---',\n `**From:** ${data.from}`,\n `**Subject:** ${data.subject}`,\n `**Date:** ${data.created}`,\n '',\n data.body,\n ].join('\\n');\n\n await space.db.update({ id: contentId }, { content: modifiedContent });\n\n return new Response(JSON.stringify({ success: true }));\n};\n\ntype RequestPayload = {\n data: { from: string; subject: string; created: string; body: string };\n trigger: { meta: { targetDocumentId: string } };\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { S, defineFunction } from 'dxos:functions';\nimport {\n HttpClient,\n HttpClientRequest,\n FetchHttpClient,\n // @ts-ignore\n} from 'https://esm.sh/@effect/platform@0.77.2?deps=effect@3.13.3';\n// @ts-ignore\nimport { Effect, Schedule } from 'https://esm.sh/effect@3.13.3';\n\nexport default defineFunction({\n description: 'Returns the exchange rate between two currencies.',\n\n inputSchema: S.Struct({\n from: S.String.annotations({ description: 'The source currency' }),\n to: S.String.annotations({ description: 'The target currency' }),\n }),\n\n outputSchema: S.String.annotations({ description: 'The exchange rate between the two currencies' }),\n\n handler: async ({\n event: {\n data: { from, to },\n },\n }: any) =>\n Effect.gen(function* () {\n const res = yield* HttpClientRequest.get(`https://free.ratesdb.com/v1/rates?from=${from}&to=${to}`).pipe(\n HttpClient.execute,\n Effect.flatMap((res: any) => res.json),\n Effect.timeout('1 second'),\n Effect.retry(Schedule.exponential(1_000).pipe(Schedule.compose(Schedule.recurs(3)))),\n Effect.scoped,\n );\n\n return res.data.rates[to].toString();\n }).pipe(Effect.provide(FetchHttpClient.layer)),\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { defineFunction, S } from 'dxos:functions';\n\nexport default defineFunction({\n description: 'Returns the exchange rate between two currencies.',\n\n inputSchema: S.Struct({\n from: S.String.annotations({ description: 'The source currency' }),\n to: S.String.annotations({ description: 'The target currency' }),\n }),\n\n handler: async ({\n event: {\n data: { from, to },\n },\n }: any) => {\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 rates[to].toString();\n },\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { create, defineFunction, Filter, ObjectId, S } from 'dxos:functions';\n// @ts-ignore\nimport {\n HttpClient,\n HttpClientRequest,\n FetchHttpClient,\n // @ts-ignore\n} from 'https://esm.sh/@effect/platform@0.77.2?deps=effect@3.13.3';\n// @ts-ignore\nimport { format, subDays } from 'https://esm.sh/date-fns@3.3.1';\n// @ts-ignore\nimport { pipe, Chunk, Effect, Ref, Schedule, Stream } from 'https://esm.sh/effect@3.13.3';\n\nimport { Type } from '@dxos/echo';\n\nexport default defineFunction({\n inputSchema: S.Struct({\n mailboxId: S.String,\n userId: S.optional(S.String).pipe(S.withDecodingDefault(() => 'me')),\n after: S.optional(S.Union(S.Number, S.String)).pipe(\n S.withDecodingDefault(() => format(subDays(new Date(), 30), 'yyyy-MM-dd')),\n ),\n pageSize: S.optional(S.Number).pipe(S.withDecodingDefault(() => 100)),\n // TODO(wittjosiah): Remove. This is used to provide a terminal for a cron trigger.\n tick: S.optional(S.String),\n }),\n\n outputSchema: S.Struct({\n newMessages: S.Number,\n }),\n\n handler: ({\n context: { space },\n event: {\n data: { mailboxId, userId, after, pageSize },\n },\n }: any) =>\n Effect.gen(function* () {\n const { token } = yield* Effect.tryPromise({\n try: () => space.db.query(Filter.typename('dxos.org/type/AccessToken', { source: 'gmail.com' })).first(),\n catch: (e: any) => e,\n });\n\n // NOTE: Google API bundles size is v. large and caused runtime issues.\n const makeRequest = (url: string) =>\n pipe(\n url,\n HttpClientRequest.get,\n HttpClientRequest.setHeaders({ Authorization: `Bearer ${token}`, Accept: 'application/json' }),\n HttpClient.execute,\n Effect.flatMap((res: any) => res.json),\n Effect.timeout('1 second'),\n Effect.retry(Schedule.exponential(1000).pipe(Schedule.compose(Schedule.recurs(3)))),\n Effect.scoped,\n );\n\n const listMessages = (userId: string, q: string, pageSize: number, pageToken: string | null) =>\n makeRequest(getUrl(userId, undefined, { q, pageSize, pageToken }));\n\n const getMessage = (userId: string, messageId: string) => makeRequest(getUrl(userId, messageId));\n\n const mailbox = yield* Effect.tryPromise({\n try: () => space.db.query({ id: mailboxId }).first(),\n catch: (e: any) => e,\n });\n const { objects } = yield* Effect.tryPromise({\n try: () => space.queues.queryQueue(mailbox.queue.dxn),\n catch: (e: any) => e,\n });\n const newMessages = yield* Ref.make([]);\n const nextPage = yield* Ref.make(null);\n\n do {\n const last = objects.at(-1);\n const q = last\n ? `in:inbox after:${Math.floor(new Date(last.created).getTime() / 1000)}`\n : `in:inbox after:${after}`;\n const pageToken = yield* Ref.get(nextPage);\n const { messages, nextPageToken } = yield* listMessages(userId, q, pageSize, pageToken);\n yield* Ref.update(nextPage, () => nextPageToken);\n for (const message of messages) {\n const messageDetails = yield* getMessage(userId, message.id);\n const created = new Date(parseInt(messageDetails.internalDate)).toISOString();\n const from = messageDetails.payload.headers.find((h: any) => h.name === 'From');\n const sender = from && parseEmailString(from.value);\n // TODO(wittjosiah): Improve parsing of email contents.\n const content =\n messageDetails.payload.body?.data ??\n messageDetails.payload.parts?.find((p: any) => p.mimeType === 'text/plain')?.body.data;\n // Skip the message if content or sender is missing.\n // Skip the message if it's the same as the last message.\n // TODO(wittjosiah): This comparison should be done via foreignId probably.\n if (!content || !sender || created === last?.created) {\n continue;\n }\n const subject = messageDetails.payload.headers.find((h: any) => h.name === 'Subject')?.value;\n const object = create(MessageType, {\n id: ObjectId.random(),\n created,\n sender,\n blocks: [\n {\n type: 'text',\n text: Buffer.from(content, 'base64').toString('utf-8'),\n },\n ],\n properties: {\n subject,\n threadId: message.threadId,\n },\n });\n // TODO(wittjosiah): Set foreignId in object meta.\n yield* Ref.update(newMessages, (n: any) => [object, ...n]);\n }\n } while (yield* Ref.get(nextPage));\n\n const queueMessages = yield* Ref.get(newMessages);\n if (queueMessages.length > 0) {\n yield* pipe(\n queueMessages,\n Stream.fromIterable,\n Stream.grouped(10),\n Stream.flatMap((batch: any) =>\n Effect.tryPromise({\n try: () => space.queues.insertIntoQueue(mailbox.queue.dxn, Chunk.toReadonlyArray(batch)),\n catch: (e: any) => e,\n }),\n ),\n Stream.runDrain,\n );\n }\n\n return { newMessages: queueMessages.length };\n }).pipe(Effect.provide(FetchHttpClient.layer)),\n});\n\nconst getUrl = (userId: string, messageId?: string, params?: Record<string, any>) => {\n const api = new URL(\n [`https://gmail.googleapis.com/gmail/v1/users/${userId}/messages`, messageId].filter(Boolean).join('/'),\n );\n Object.entries(params ?? {}).forEach(([key, value]) => api.searchParams.set(key, value));\n return api.toString();\n};\n\n/**\n * Parses an email string in the format \"Name <email@example.com>\" into separate name and email components.\n */\nconst parseEmailString = (emailString: string): { name?: string; email: string } | undefined => {\n const match = emailString.match(/^([^<]+?)\\s*<([^>]+@[^>]+)>$/);\n if (match) {\n const [, name, email] = match;\n return {\n name: name.trim(),\n email: email.trim(),\n };\n }\n\n return undefined;\n};\n\n//\n// Schemas\n// TODO(wittjosiah): These schemas should be imported from @dxos/S.\n//\n\nconst ActorRoles = ['user', 'assistant'] as const;\nconst ActorRole = S.Literal(...ActorRoles);\ntype ActorRole = S.S.Type<typeof ActorRole>;\n\nconst ActorSchema = S.Struct({\n identityKey: S.optional(S.String),\n email: S.optional(S.String),\n name: S.optional(S.String),\n role: S.optional(ActorRole),\n});\n\nconst AbstractContentBlock = S.Struct({\n pending: S.optional(S.Boolean),\n});\ntype AbstractContentBlock = S.S.Type<typeof AbstractContentBlock>;\nconst TextContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('text'),\n disposition: S.optional(S.String),\n text: S.String,\n }),\n).pipe(S.mutable);\ntype TextContentBlock = S.S.Type<typeof TextContentBlock>;\nconst JsonContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('json'),\n disposition: S.optional(S.String),\n data: S.String,\n }),\n).pipe(S.mutable);\ntype JsonContentBlock = S.S.Type<typeof JsonContentBlock>;\nconst Base64ImageSource = S.Struct({\n type: S.Literal('base64'),\n mediaType: S.String,\n data: S.String,\n}).pipe(S.mutable);\nconst HttpImageSource = S.Struct({\n type: S.Literal('http'),\n url: S.String,\n}).pipe(S.mutable);\nconst ImageSource = S.Union(Base64ImageSource, HttpImageSource);\ntype ImageSource = S.S.Type<typeof ImageSource>;\nconst ImageContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('image'),\n id: S.optional(S.String),\n source: S.optional(ImageSource),\n }),\n).pipe(S.mutable);\ntype ImageContentBlock = S.S.Type<typeof ImageContentBlock>;\nconst ReferenceContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('reference'),\n reference: S.Any,\n }),\n).pipe(S.mutable);\ntype ReferenceContentBlock = S.S.Type<typeof ReferenceContentBlock>;\nconst MessageContentBlock = S.Union(TextContentBlock, JsonContentBlock, ImageContentBlock, ReferenceContentBlock);\n\nconst MessageType = S.Struct({\n id: ObjectId,\n created: S.String.annotations({\n description: 'ISO date string when the message was sent.',\n }),\n sender: ActorSchema.annotations({\n description: 'Identity of the message sender.',\n }),\n blocks: S.Array(MessageContentBlock).annotations({\n description: 'Contents of the message.',\n }),\n properties: S.optional(\n S.mutable(\n S.Record({ key: S.String, value: S.Any }).annotations({\n description: 'Custom properties for specific message types (e.g. attention context, email subject, etc.).',\n }),\n ),\n ),\n}).pipe(\n Type.def({\n typename: 'dxos.org/type/Message',\n version: '0.1.0',\n }),\n);\ntype MessageType = S.S.Type<typeof MessageType>;\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport chat from './chat.ts?raw';\nimport chess from './chess.ts?raw';\nimport dataGenerator from './data-generator.ts?raw';\nimport discord from './discord.ts?raw';\nimport echo from './echo.ts?raw';\nimport email from './email.ts?raw';\nimport forexEffect from './forex-effect.ts?raw';\nimport forex from './forex.ts?raw';\nimport gmail from './gmail.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/forex-effect',\n name: 'Forex (Effect)',\n source: removeHeader(forexEffect),\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 id: 'dxos.org/script/discord',\n name: 'Discord',\n source: removeHeader(discord),\n presetId: 'dxos.org/function/discord',\n },\n {\n id: 'dxos.org/script/gmail',\n name: 'Gmail',\n source: removeHeader(gmail),\n presetId: 'dxos.org/function/gmail',\n },\n {\n id: 'dxos.org/script/data-generator',\n name: 'Data Generator',\n source: removeHeader(dataGenerator),\n presetId: 'dxos.org/function/data-generator',\n },\n];\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAA,eAAA;ACAA,IAAA,gBAAA;ACAA,IAAA,yBAAA;ACAA,IAAA,kBAAA;ACAA,IAAA,eAAA;ACAA,IAAA,gBAAA;ACAA,IAAA,uBAAA;ACAA,IAAA,gBAAA;ACAA,IAAA,gBAAA;ACcA,IAAMA,eAAe,CAACC,QAAgBA,IAAIC,MAAM,IAAA,EAAMC,MAAM,CAAA,EAAGC,KAAK,IAAA;AAS7D,IAAMC,YAAwB;EACnC;IACEC,IAAI;IACJC,MAAM;IACNC,QAAQR,aAAaS,YAAAA;EACvB;EACA;IACEH,IAAI;IACJC,MAAM;IACNC,QAAQR,aAAaU,aAAAA;EACvB;EACA;IACEJ,IAAI;IACJC,MAAM;IACNC,QAAQR,aAAaW,oBAAAA;EACvB;EACA;IACEL,IAAI;IACJC,MAAM;IACNC,QAAQR,aAAaY,YAAAA;IACrBC,UAAU;EACZ;EACA;IACEP,IAAI;IACJC,MAAM;IACNC,QAAQR,aAAac,aAAAA;IACrBD,UAAU;EACZ;EACA;IACEP,IAAI;IACJC,MAAM;IACNC,QAAQR,aAAae,aAAAA;IACrBF,UAAU;EACZ;EACA;IACEP,IAAI;IACJC,MAAM;IACNC,QAAQR,aAAagB,eAAAA;IACrBH,UAAU;EACZ;EACA;IACEP,IAAI;IACJC,MAAM;IACNC,QAAQR,aAAaiB,aAAAA;IACrBJ,UAAU;EACZ;EACA;IACEP,IAAI;IACJC,MAAM;IACNC,QAAQR,aAAakB,sBAAAA;IACrBL,UAAU;EACZ;;",
6
+ "names": ["removeHeader", "str", "split", "slice", "join", "templates", "id", "name", "source", "echo", "forex", "forexEffect", "chat", "presetId", "chess", "email", "discord", "gmail", "dataGenerator"]
7
+ }
@@ -26,8 +26,8 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
26
26
  mod
27
27
  ));
28
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var chunk_UUGLBCMY_exports = {};
30
- __export(chunk_UUGLBCMY_exports, {
29
+ var chunk_HLNSDICG_exports = {};
30
+ __export(chunk_HLNSDICG_exports, {
31
31
  createDeploy: () => createDeploy,
32
32
  createFormat: () => createFormat,
33
33
  createTemplateSelect: () => createTemplateSelect,
@@ -35,9 +35,9 @@ __export(chunk_UUGLBCMY_exports, {
35
35
  useToolbarAction: () => useToolbarAction,
36
36
  useToolbarState: () => useToolbarState
37
37
  });
38
- module.exports = __toCommonJS(chunk_UUGLBCMY_exports);
39
- var import_chunk_4K23KEYT = require("./chunk-4K23KEYT.cjs");
40
- var import_chunk_DSFCLQ5F = require("./chunk-DSFCLQ5F.cjs");
38
+ module.exports = __toCommonJS(chunk_HLNSDICG_exports);
39
+ var import_chunk_DGFQHBA7 = require("./chunk-DGFQHBA7.cjs");
40
+ var import_chunk_XT76CMHH = require("./chunk-XT76CMHH.cjs");
41
41
  var import_chunk_NO5Y74F3 = require("./chunk-NO5Y74F3.cjs");
42
42
  var import_react = require("react");
43
43
  var import_functions = require("@dxos/functions");
@@ -56,7 +56,7 @@ var import_react3 = require("react");
56
56
  var import_log2 = require("@dxos/log");
57
57
  var import_react_ui_menu2 = require("@dxos/react-ui-menu");
58
58
  var import_react4 = require("react");
59
- var import_types = require("@dxos/functions/types");
59
+ var import_functions2 = require("@dxos/functions");
60
60
  var import_live_object2 = require("@dxos/live-object");
61
61
  var import_react_ui_menu3 = require("@dxos/react-ui-menu");
62
62
  var import_react5 = require("react");
@@ -127,7 +127,7 @@ var useDeployState = ({ state, script }) => {
127
127
  if (!existingFunctionUrl) {
128
128
  return;
129
129
  }
130
- state.functionUrl = (0, import_chunk_DSFCLQ5F.getFunctionUrl)({
130
+ state.functionUrl = (0, import_chunk_XT76CMHH.getFunctionUrl)({
131
131
  script,
132
132
  fn,
133
133
  edgeUrl: client.config.values.runtime?.services?.edge?.url ?? ""
@@ -140,7 +140,7 @@ var useDeployState = ({ state, script }) => {
140
140
  client.config.values.runtime?.services?.edge?.url
141
141
  ]);
142
142
  (0, import_react.useEffect)(() => {
143
- state.deployed = (0, import_chunk_DSFCLQ5F.isScriptDeployed)({
143
+ state.deployed = (0, import_chunk_XT76CMHH.isScriptDeployed)({
144
144
  script,
145
145
  fn
146
146
  });
@@ -178,7 +178,7 @@ var useDeployHandler = ({ state, script }) => {
178
178
  }
179
179
  state.error = void 0;
180
180
  state.deploying = true;
181
- const result = await (0, import_chunk_DSFCLQ5F.deployScript)({
181
+ const result = await (0, import_chunk_XT76CMHH.deployScript)({
182
182
  script,
183
183
  client,
184
184
  space,
@@ -275,7 +275,7 @@ var createTemplateSelectGroup = () => {
275
275
  });
276
276
  };
277
277
  var createTemplateSelectActions = () => {
278
- return import_chunk_4K23KEYT.templates.map((template) => {
278
+ return import_chunk_DGFQHBA7.templates.map((template) => {
279
279
  return (0, import_react_ui_menu3.createMenuAction)(`template--${template.id}`, {
280
280
  label: template.name,
281
281
  value: template.id,
@@ -305,18 +305,18 @@ var createTemplateSelect = () => {
305
305
  };
306
306
  var useTemplateSelectHandler = ({ script }) => {
307
307
  return (0, import_react4.useCallback)((templateId) => {
308
- const template = import_chunk_4K23KEYT.templates.find((template2) => template2.id === templateId);
308
+ const template = import_chunk_DGFQHBA7.templates.find((template2) => template2.id === templateId);
309
309
  if (template) {
310
310
  script.name = template.name;
311
311
  script.source.target.content = template.source;
312
312
  const metaKeys = (0, import_live_object2.getMeta)(script).keys;
313
- const oldPresetIndex = metaKeys.findIndex((key) => key.source === import_types.FUNCTIONS_PRESET_META_KEY);
313
+ const oldPresetIndex = metaKeys.findIndex((key) => key.source === import_functions2.FUNCTIONS_PRESET_META_KEY);
314
314
  if (oldPresetIndex >= 0) {
315
315
  metaKeys.splice(oldPresetIndex, 1);
316
316
  }
317
317
  if (template.presetId) {
318
318
  metaKeys.push({
319
- source: import_types.FUNCTIONS_PRESET_META_KEY,
319
+ source: import_functions2.FUNCTIONS_PRESET_META_KEY,
320
320
  id: template.presetId
321
321
  });
322
322
  }
@@ -369,4 +369,4 @@ var useToolbarAction = (props) => {
369
369
  useToolbarAction,
370
370
  useToolbarState
371
371
  });
372
- //# sourceMappingURL=chunk-UUGLBCMY.cjs.map
372
+ //# sourceMappingURL=chunk-HLNSDICG.cjs.map