@dxos/plugin-script 0.7.5-labs.8a82073 → 0.7.5-labs.c0e040f

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 (95) hide show
  1. package/dist/lib/browser/{ScriptContainer-QI4NQT7V.mjs → ScriptContainer-SPKDYRXU.mjs} +8 -8
  2. package/dist/lib/browser/ScriptContainer-SPKDYRXU.mjs.map +7 -0
  3. package/dist/lib/browser/{artifact-3UZZBCZ2.mjs → artifact-YCIVHFSS.mjs} +3 -3
  4. package/dist/lib/browser/{artifact-3UZZBCZ2.mjs.map → artifact-YCIVHFSS.mjs.map} +3 -3
  5. package/dist/lib/browser/{chunk-VIX22OMB.mjs → chunk-GB5OS4JQ.mjs} +13 -4
  6. package/dist/lib/browser/chunk-GB5OS4JQ.mjs.map +7 -0
  7. package/dist/lib/browser/{chunk-F22QPQ6G.mjs → chunk-XTD6J6PC.mjs} +2 -2
  8. package/dist/lib/browser/{compiler-K3FNRDDN.mjs → compiler-YY2XSKHQ.mjs} +2 -4
  9. package/dist/lib/browser/compiler-YY2XSKHQ.mjs.map +7 -0
  10. package/dist/lib/browser/index.mjs +5 -11
  11. package/dist/lib/browser/index.mjs.map +1 -1
  12. package/dist/lib/browser/{intent-resolver-CMKQTLBG.mjs → intent-resolver-IKIQWAL4.mjs} +2 -2
  13. package/dist/lib/browser/meta.json +1 -1
  14. package/dist/lib/browser/{react-surface-YR4YO746.mjs → react-surface-ZP2FXWYA.mjs} +2 -2
  15. package/dist/lib/node/{ScriptContainer-FSKWJR6Z.cjs → ScriptContainer-M3PIEFIA.cjs} +13 -11
  16. package/dist/lib/node/ScriptContainer-M3PIEFIA.cjs.map +7 -0
  17. package/dist/lib/node/{artifact-A2QXHFGS.cjs → artifact-IPGGY2Z2.cjs} +6 -6
  18. package/dist/lib/node/{artifact-A2QXHFGS.cjs.map → artifact-IPGGY2Z2.cjs.map} +2 -2
  19. package/dist/lib/node/{chunk-PKT5DD3O.cjs → chunk-FGJJPY2L.cjs} +12 -5
  20. package/dist/lib/node/chunk-FGJJPY2L.cjs.map +7 -0
  21. package/dist/lib/node/{chunk-JSANQCTA.cjs → chunk-HEDZVP6A.cjs} +5 -5
  22. package/dist/lib/node/{compiler-P2HQB22H.cjs → compiler-UIBLKJKG.cjs} +6 -6
  23. package/dist/lib/node/compiler-UIBLKJKG.cjs.map +7 -0
  24. package/dist/lib/node/index.cjs +9 -14
  25. package/dist/lib/node/index.cjs.map +1 -1
  26. package/dist/lib/node/{intent-resolver-V5ASU5DW.cjs → intent-resolver-BLLSSUIM.cjs} +6 -6
  27. package/dist/lib/node/meta.json +1 -1
  28. package/dist/lib/node/{react-surface-MFTICFI5.cjs → react-surface-BI5NMAJM.cjs} +9 -9
  29. package/dist/lib/node-esm/{ScriptContainer-MNETNTNQ.mjs → ScriptContainer-6GCPTLOV.mjs} +8 -8
  30. package/dist/lib/node-esm/ScriptContainer-6GCPTLOV.mjs.map +7 -0
  31. package/dist/lib/node-esm/{artifact-RFZQ2AJJ.mjs → artifact-7H4HGX5W.mjs} +3 -3
  32. package/dist/lib/node-esm/{artifact-RFZQ2AJJ.mjs.map → artifact-7H4HGX5W.mjs.map} +3 -3
  33. package/dist/lib/node-esm/{chunk-FGO5DVO2.mjs → chunk-DWVYAASV.mjs} +2 -2
  34. package/dist/lib/node-esm/{chunk-NBAL5DXN.mjs → chunk-RFVLVTYI.mjs} +13 -4
  35. package/dist/lib/node-esm/chunk-RFVLVTYI.mjs.map +7 -0
  36. package/dist/lib/node-esm/{compiler-PDN46H4Y.mjs → compiler-XTXFGZJM.mjs} +2 -4
  37. package/dist/lib/node-esm/compiler-XTXFGZJM.mjs.map +7 -0
  38. package/dist/lib/node-esm/index.mjs +5 -11
  39. package/dist/lib/node-esm/index.mjs.map +1 -1
  40. package/dist/lib/node-esm/{intent-resolver-75BHFRUK.mjs → intent-resolver-QFIYWOWQ.mjs} +2 -2
  41. package/dist/lib/node-esm/meta.json +1 -1
  42. package/dist/lib/node-esm/{react-surface-NAK6LMCY.mjs → react-surface-N4Z5HGAC.mjs} +2 -2
  43. package/dist/types/src/capabilities/artifact.d.ts.map +1 -1
  44. package/dist/types/src/components/FrameContainer/FrameContainer.d.ts +2 -2
  45. package/dist/types/src/components/FrameContainer/FrameContainer.d.ts.map +1 -1
  46. package/dist/types/src/hooks/deploy.d.ts.map +1 -1
  47. package/dist/types/src/index.d.ts +0 -1
  48. package/dist/types/src/index.d.ts.map +1 -1
  49. package/dist/types/src/templates/discord.d.ts +3 -0
  50. package/dist/types/src/templates/discord.d.ts.map +1 -0
  51. package/dist/types/src/templates/forex-effect.d.ts.map +1 -1
  52. package/dist/types/src/templates/index.d.ts.map +1 -1
  53. package/package.json +41 -44
  54. package/src/capabilities/artifact.ts +2 -2
  55. package/src/capabilities/compiler.ts +1 -1
  56. package/src/components/FrameContainer/FrameContainer.tsx +4 -3
  57. package/src/components/TypescriptEditor/TypescriptEditor.tsx +2 -2
  58. package/src/hooks/deploy.ts +3 -3
  59. package/src/index.ts +0 -1
  60. package/src/templates/discord.ts +86 -0
  61. package/src/templates/forex-effect.ts +16 -14
  62. package/src/templates/index.ts +10 -2
  63. package/dist/lib/browser/ScriptContainer-QI4NQT7V.mjs.map +0 -7
  64. package/dist/lib/browser/chunk-SDHKTS6H.mjs +0 -237
  65. package/dist/lib/browser/chunk-SDHKTS6H.mjs.map +0 -7
  66. package/dist/lib/browser/chunk-VIX22OMB.mjs.map +0 -7
  67. package/dist/lib/browser/compiler-K3FNRDDN.mjs.map +0 -7
  68. package/dist/lib/node/ScriptContainer-FSKWJR6Z.cjs.map +0 -7
  69. package/dist/lib/node/chunk-PKT5DD3O.cjs.map +0 -7
  70. package/dist/lib/node/chunk-T4TXCRN5.cjs +0 -260
  71. package/dist/lib/node/chunk-T4TXCRN5.cjs.map +0 -7
  72. package/dist/lib/node/compiler-P2HQB22H.cjs.map +0 -7
  73. package/dist/lib/node-esm/ScriptContainer-MNETNTNQ.mjs.map +0 -7
  74. package/dist/lib/node-esm/chunk-G76M6O46.mjs +0 -239
  75. package/dist/lib/node-esm/chunk-G76M6O46.mjs.map +0 -7
  76. package/dist/lib/node-esm/chunk-NBAL5DXN.mjs.map +0 -7
  77. package/dist/lib/node-esm/compiler-PDN46H4Y.mjs.map +0 -7
  78. package/dist/types/src/bundler/bundler.d.ts +0 -39
  79. package/dist/types/src/bundler/bundler.d.ts.map +0 -1
  80. package/dist/types/src/bundler/bundler.test.d.ts +0 -2
  81. package/dist/types/src/bundler/bundler.test.d.ts.map +0 -1
  82. package/dist/types/src/bundler/index.d.ts +0 -2
  83. package/dist/types/src/bundler/index.d.ts.map +0 -1
  84. package/src/bundler/bundler.test.ts +0 -55
  85. package/src/bundler/bundler.ts +0 -250
  86. package/src/bundler/index.ts +0 -5
  87. /package/dist/lib/browser/{chunk-F22QPQ6G.mjs.map → chunk-XTD6J6PC.mjs.map} +0 -0
  88. /package/dist/lib/browser/{intent-resolver-CMKQTLBG.mjs.map → intent-resolver-IKIQWAL4.mjs.map} +0 -0
  89. /package/dist/lib/browser/{react-surface-YR4YO746.mjs.map → react-surface-ZP2FXWYA.mjs.map} +0 -0
  90. /package/dist/lib/node/{chunk-JSANQCTA.cjs.map → chunk-HEDZVP6A.cjs.map} +0 -0
  91. /package/dist/lib/node/{intent-resolver-V5ASU5DW.cjs.map → intent-resolver-BLLSSUIM.cjs.map} +0 -0
  92. /package/dist/lib/node/{react-surface-MFTICFI5.cjs.map → react-surface-BI5NMAJM.cjs.map} +0 -0
  93. /package/dist/lib/node-esm/{chunk-FGO5DVO2.mjs.map → chunk-DWVYAASV.mjs.map} +0 -0
  94. /package/dist/lib/node-esm/{intent-resolver-75BHFRUK.mjs.map → intent-resolver-QFIYWOWQ.mjs.map} +0 -0
  95. /package/dist/lib/node-esm/{react-surface-NAK6LMCY.mjs.map → react-surface-N4Z5HGAC.mjs.map} +0 -0
@@ -1,9 +1,6 @@
1
- import {
2
- Bundler
3
- } from "./chunk-SDHKTS6H.mjs";
4
1
  import {
5
2
  templates
6
- } from "./chunk-VIX22OMB.mjs";
3
+ } from "./chunk-GB5OS4JQ.mjs";
7
4
  import {
8
5
  DebugPanel
9
6
  } from "./chunk-45LXDWNF.mjs";
@@ -29,6 +26,7 @@ import { createGapSeparator, MenuProvider, ToolbarMenu, useMenuActions } from "@
29
26
  // packages/plugins/experimental/plugin-script/src/hooks/deploy.ts
30
27
  import { useCallback, useEffect, useMemo } from "react";
31
28
  import { FunctionType, getInvocationUrl, getUserFunctionUrlInMetadata, incrementSemverPatch, setUserFunctionUrlInMetadata, uploadWorkerFunction } from "@dxos/functions";
29
+ import { Bundler } from "@dxos/functions/bundler";
32
30
  import { log } from "@dxos/log";
33
31
  import { useClient } from "@dxos/react-client";
34
32
  import { Filter, create, getMeta, getSpace, makeRef, useQuery } from "@dxos/react-client/echo";
@@ -149,7 +147,9 @@ var useDeployHandler = ({ state, script }) => {
149
147
  sandboxedModules: [],
150
148
  remoteModules: {}
151
149
  });
152
- const buildResult = await bundler.bundle(script.source.target.content);
150
+ const buildResult = await bundler.bundle({
151
+ source: script.source.target.content
152
+ });
153
153
  if (buildResult.error || !buildResult.bundle) {
154
154
  throw buildResult.error;
155
155
  }
@@ -540,7 +540,7 @@ import { tsSync, tsFacet, tsLinter, tsAutocomplete, tsHover } from "@valtown/cod
540
540
  import React2 from "react";
541
541
  import { useThemeContext } from "@dxos/react-ui";
542
542
  import { autocomplete, createBasicExtensions, createThemeExtensions, editorFullWidth, editorMonospace, EditorView, folding, InputModeExtensions, useTextEditor } from "@dxos/react-ui-editor";
543
- import { nonNullable } from "@dxos/util";
543
+ import { isNonNullable } from "@dxos/util";
544
544
  var TypescriptEditor = ({ id, env, className, initialValue, extensions, scrollTo, selection, toolbar, inputMode = "vscode" }) => {
545
545
  const { themeMode } = useThemeContext();
546
546
  const { parentRef, focusAttributes } = useTextEditor(() => ({
@@ -599,7 +599,7 @@ var TypescriptEditor = ({ id, env, className, initialValue, extensions, scrollTo
599
599
  })
600
600
  ] : []
601
601
  ]
602
- ].filter(nonNullable),
602
+ ].filter(isNonNullable),
603
603
  selection,
604
604
  scrollTo
605
605
  }), [
@@ -710,4 +710,4 @@ export {
710
710
  ScriptContainer,
711
711
  ScriptContainer_default as default
712
712
  };
713
- //# sourceMappingURL=ScriptContainer-QI4NQT7V.mjs.map
713
+ //# sourceMappingURL=ScriptContainer-SPKDYRXU.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/components/ScriptContainer.tsx", "../../../src/components/ScriptToolbar/ScriptToolbar.tsx", "../../../src/hooks/deploy.ts", "../../../src/hooks/format.ts", "../../../src/hooks/template.ts", "../../../src/hooks/view.ts", "../../../src/hooks/useToolbarAction.ts", "../../../src/hooks/useToolbarState.ts", "../../../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 { DebugPanel } from './DebugPanel';\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 script: ScriptType;\n settings?: ScriptSettingsProps;\n role?: string;\n}> &\n Pick<TypescriptEditorProps, 'env'>;\n\nexport const ScriptContainer = ({\n role,\n classNames,\n script,\n settings = { editorInputMode: 'vscode' },\n env,\n}: ScriptEditorProps) => {\n const identity = useIdentity();\n const space = getSpace(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 [script, script.source.target, space, identity],\n );\n\n const state = useToolbarState({ view: 'editor' });\n useDeployState({ state, script });\n\n return (\n <StackItem.Content toolbar>\n <ScriptToolbar state={state} role={role} script={script} />\n <div role='none' className={mx('flex flex-col w-full overflow-hidden divide-y divide-separator', classNames)}>\n {state.view !== 'debug' && (\n <TypescriptEditor\n id={script.id}\n env={env}\n initialValue={script.source?.target?.content}\n extensions={extensions}\n className={stackItemContentEditorClassNames(role)}\n inputMode={settings.editorInputMode}\n toolbar\n />\n )}\n\n {state.view !== 'editor' && <DebugPanel functionUrl={state.functionUrl} />}\n </div>\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 createView,\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 const view = createView(state);\n return {\n nodes: [...templateSelect.nodes, ...format.nodes, ...gap.nodes, ...deploy.nodes, ...view.nodes],\n edges: [...templateSelect.edges, ...format.edges, ...gap.edges, ...deploy.edges, ...view.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 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 2025 DXOS.org\n//\n\nimport { useCallback, useEffect, useMemo } from 'react';\n\nimport {\n FunctionType,\n type ScriptType,\n getInvocationUrl,\n getUserFunctionUrlInMetadata,\n incrementSemverPatch,\n setUserFunctionUrlInMetadata,\n uploadWorkerFunction,\n} from '@dxos/functions';\nimport { Bundler } from '@dxos/functions/bundler';\nimport { log } from '@dxos/log';\nimport { useClient } from '@dxos/react-client';\nimport { Filter, create, getMeta, getSpace, makeRef, useQuery } from '@dxos/react-client/echo';\nimport { useTranslation } from '@dxos/react-ui';\nimport { createMenuAction } from '@dxos/react-ui-menu';\n\nimport { type ViewState } from './view';\nimport { SCRIPT_PLUGIN } from '../meta';\n\nexport type DeployActionProperties = { type: 'deploy' } | { type: 'copy' };\n\nexport type DeployState = ViewState & {\n deploying: boolean;\n deployed: boolean;\n functionUrl: string;\n error: string;\n};\n\nexport const createDeploy = (state: Partial<DeployState>) => {\n const errorItem = createMenuAction('error', {\n label: state.error ?? ['no error label', { ns: SCRIPT_PLUGIN }],\n icon: 'ph--warning-circle--regular',\n hidden: !state.error,\n });\n\n const deployAction = createMenuAction<DeployActionProperties>('deploy', {\n type: 'deploy',\n label: [state.deploying ? 'pending label' : 'deploy label', { ns: SCRIPT_PLUGIN }],\n icon: state.deploying ? 'ph--spinner-gap--regular' : 'ph--cloud-arrow-up--regular',\n disabled: state.deploying,\n classNames: state.deploying ? '[&_svg]:animate-spin' : '',\n });\n\n const copyAction = createMenuAction<DeployActionProperties>('copy', {\n type: 'copy',\n label: ['copy link label', { ns: SCRIPT_PLUGIN }],\n icon: 'ph--link--regular',\n disabled: !state.functionUrl,\n });\n\n return {\n nodes: [errorItem, deployAction, copyAction],\n edges: [\n { source: 'root', target: 'error' },\n { source: 'root', target: 'deploy' },\n { source: 'root', target: 'copy' },\n ],\n };\n};\n\nconst useDeployDeps = ({ state, script }: { state: Partial<DeployState>; script: ScriptType }) => {\n const space = getSpace(script);\n const [fn] = useQuery(space, Filter.schema(FunctionType, { source: script }));\n const client = useClient();\n const existingFunctionUrl = useMemo(() => fn && getUserFunctionUrlInMetadata(getMeta(fn)), [fn]);\n return { space, fn, client, existingFunctionUrl };\n};\n\nexport const useDeployState = ({ state, script }: { state: Partial<DeployState>; script: ScriptType }) => {\n const { space, client, existingFunctionUrl } = useDeployDeps({ state, script });\n useEffect(() => {\n if (!existingFunctionUrl) {\n return;\n }\n\n state.functionUrl = getInvocationUrl(existingFunctionUrl, client.config.values.runtime?.services?.edge?.url ?? '', {\n spaceId: space?.id,\n });\n }, [existingFunctionUrl, space]);\n\n useEffect(() => {\n state.deployed = Boolean(existingFunctionUrl) && !script.changed;\n }, [script.changed, existingFunctionUrl]);\n};\n\nexport const useDeployHandler = ({ state, script }: { state: Partial<DeployState>; script: ScriptType }) => {\n const { space, fn, client, existingFunctionUrl } = useDeployDeps({ state, script });\n const { t } = useTranslation(SCRIPT_PLUGIN);\n\n return useCallback(async () => {\n if (!script.source || !space) {\n return;\n }\n\n state.error = undefined;\n state.deploying = true;\n\n try {\n const existingFunctionId = existingFunctionUrl?.split('/').at(-1);\n\n const bundler = new Bundler({ platform: 'browser', sandboxedModules: [], remoteModules: {} });\n const buildResult = await bundler.bundle({ source: script.source.target!.content });\n if (buildResult.error || !buildResult.bundle) {\n throw buildResult.error;\n }\n\n const { functionId, version, meta } = await uploadWorkerFunction({\n client,\n spaceId: space.id,\n version: fn ? incrementSemverPatch(fn.version) : '0.0.1',\n functionId: existingFunctionId,\n source: buildResult.bundle,\n });\n if (functionId === undefined || version === undefined) {\n throw new Error(`Upload didn't return expected data: functionId=${functionId}, version=${version}`);\n }\n\n log.info('function uploaded', { functionId, version });\n if (fn) {\n fn.version = version;\n }\n\n const deployedFunction =\n fn ?? space.db.add(create(FunctionType, { name: functionId, version, source: makeRef(script) }));\n\n script.changed = false;\n if (script.description !== undefined && script.description.trim() !== '') {\n deployedFunction.description = script.description;\n } else if (meta.description) {\n deployedFunction.description = meta.description;\n } else {\n log.verbose('no description in function metadata', { functionId });\n }\n\n if (meta.inputSchema) {\n deployedFunction.inputSchema = meta.inputSchema;\n } else {\n log.verbose('no input schema in function metadata', { functionId });\n }\n if (meta.outputSchema) {\n deployedFunction.outputSchema = meta.outputSchema;\n } else {\n log.verbose('no output schema in function metadata', { functionId });\n }\n\n setUserFunctionUrlInMetadata(getMeta(deployedFunction), `/${space.id}/${functionId}`);\n\n state.view = 'split';\n } catch (err: any) {\n log.catch(err);\n state.error = t('upload failed label');\n }\n state.deploying = false;\n }, [fn, client, t, existingFunctionUrl, script, script.name, script.source, space?.id ?? null]);\n};\n\nexport const useCopyHandler = ({ state }: { state: Partial<DeployState> }) =>\n useCallback(async () => {\n if (!state.functionUrl) {\n return;\n }\n await navigator.clipboard.writeText(state.functionUrl);\n }, [state.functionUrl]);\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { format } from 'prettier';\nimport prettierPluginEstree from 'prettier/plugins/estree';\nimport prettierPluginTypescript from 'prettier/plugins/typescript';\nimport { useCallback } from 'react';\n\nimport { type ScriptType } from '@dxos/functions';\nimport { log } from '@dxos/log';\nimport { createMenuAction } from '@dxos/react-ui-menu';\n\nimport { SCRIPT_PLUGIN } from '../meta';\n\nexport type FormatActionProperties = { type: 'format' };\n\nexport const createFormat = () => {\n const formatAction = createMenuAction('format', {\n label: ['format label', { ns: SCRIPT_PLUGIN }],\n icon: 'ph--magic-wand--regular',\n });\n\n return {\n nodes: [formatAction],\n edges: [{ source: 'root', target: 'format' }],\n };\n};\n\nexport const useFormatHandler = ({ script }: { script: ScriptType }) =>\n useCallback(async () => {\n if (!script.source) {\n return;\n }\n\n try {\n script.source.target!.content = await format(script.source.target!.content, {\n parser: 'typescript',\n plugins: [prettierPluginEstree, prettierPluginTypescript],\n semi: true,\n singleQuote: true,\n });\n } catch (err: any) {\n // TODO(wittjosiah): Show error in UI.\n log.catch(err);\n }\n }, [script.source]);\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { useCallback } from 'react';\n\nimport { FUNCTIONS_PRESET_META_KEY, type ScriptType } from '@dxos/functions';\nimport { getMeta } from '@dxos/live-object';\nimport { createMenuItemGroup, createMenuAction } from '@dxos/react-ui-menu';\n\nimport { SCRIPT_PLUGIN } from '../meta';\nimport { templates } from '../templates';\n\nexport type TemplateActionProperties = { type: 'template'; value: string };\n\nconst createTemplateSelectGroup = () => {\n return createMenuItemGroup('template-select', {\n label: ['template select group label', { ns: SCRIPT_PLUGIN }],\n variant: 'dropdownMenu',\n });\n};\n\nconst createTemplateSelectActions = () => {\n return templates.map((template) => {\n return createMenuAction<TemplateActionProperties>(`template--${template.id}`, {\n label: template.name,\n value: template.id,\n type: 'template',\n });\n });\n};\n\nexport const createTemplateSelect = () => {\n const templateSelectGroup = createTemplateSelectGroup();\n const templateSelectActions = createTemplateSelectActions();\n return {\n nodes: [templateSelectGroup, ...templateSelectActions],\n edges: [\n { source: 'root', target: 'template-select' },\n ...templateSelectActions.map((action) => ({ source: 'template-select', target: action.id })),\n ],\n };\n};\n\nexport const useTemplateSelectHandler = ({ script }: { script: ScriptType }) => {\n return useCallback(\n (templateId: string) => {\n const template = templates.find((template) => template.id === templateId);\n if (template) {\n script.name = template.name;\n script.source!.target!.content = template.source;\n const metaKeys = getMeta(script).keys;\n const oldPresetIndex = metaKeys.findIndex((key) => key.source === FUNCTIONS_PRESET_META_KEY);\n if (oldPresetIndex >= 0) {\n metaKeys.splice(oldPresetIndex, 1);\n }\n if (template.presetId) {\n metaKeys.push({ source: FUNCTIONS_PRESET_META_KEY, id: template.presetId });\n }\n }\n },\n [script],\n );\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { createMenuAction, createMenuItemGroup } from '@dxos/react-ui-menu';\n\nimport { SCRIPT_PLUGIN } from '../meta';\n\nexport type ViewType = 'editor' | 'split' | 'debug';\n\nexport type ViewState = { view: ViewType };\n\nexport type ViewActionProperties = { type: 'view'; value: ViewType };\n\nconst views: Record<ViewType, string> = {\n editor: 'ph--code--regular',\n split: 'ph--square-split-vertical--regular',\n debug: 'ph--bug--regular',\n};\n\nconst createViewGroupItem = (state: Partial<ViewState>) => {\n return createMenuItemGroup('view', {\n label: ['view group label', { ns: SCRIPT_PLUGIN }],\n variant: 'dropdownMenu',\n applyActive: true,\n value: state.view,\n });\n};\n\nconst createViewActions = (state: Partial<ViewState>) => {\n return Object.entries(views).map(([viewType, icon]) => {\n return createMenuAction<ViewActionProperties>(`view--${viewType}`, {\n type: 'view',\n value: viewType as ViewType,\n label: [`view ${viewType} label`, { ns: SCRIPT_PLUGIN }],\n icon,\n checked: state.view === viewType,\n });\n });\n};\n\nexport const createView = (state: Partial<ViewState>) => {\n const viewGroupItem = createViewGroupItem(state);\n const viewActions = createViewActions(state);\n return {\n nodes: [viewGroupItem, ...viewActions],\n edges: [\n { source: 'root', target: 'view' },\n ...viewActions.map((action) => ({ source: 'view', target: action.id })),\n ],\n };\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { useCallback } from 'react';\n\nimport { type ScriptType } from '@dxos/functions';\nimport { log } from '@dxos/log';\nimport { type MenuAction, type MenuActionHandler } from '@dxos/react-ui-menu';\n\nimport { type DeployActionProperties, useDeployHandler, useCopyHandler } from './deploy';\nimport { type FormatActionProperties, useFormatHandler } from './format';\nimport { type TemplateActionProperties, useTemplateSelectHandler } from './template';\nimport { type ScriptToolbarState } from './useToolbarState';\nimport { type ViewActionProperties } from './view';\n\nexport type ScriptToolbarActionProperties =\n | TemplateActionProperties\n | ViewActionProperties\n | FormatActionProperties\n | DeployActionProperties;\n\nexport type ScriptToolbarAction = MenuAction<ScriptToolbarActionProperties>;\n\nexport const useToolbarAction = (props: { state: ScriptToolbarState; script: ScriptType }) => {\n const handleTemplateSelect = useTemplateSelectHandler(props);\n const handleFormat = useFormatHandler(props);\n const handleDeploy = useDeployHandler(props);\n const handleCopy = useCopyHandler(props);\n return useCallback(\n ((action: ScriptToolbarAction) => {\n switch (action.properties.type) {\n case 'template':\n handleTemplateSelect(action.properties.value);\n break;\n case 'view':\n props.state.view = action.properties.value;\n break;\n case 'format':\n void handleFormat();\n break;\n case 'deploy':\n void handleDeploy();\n break;\n case 'copy':\n void handleCopy();\n break;\n default:\n log.error('Unknown action type', action);\n }\n }) as MenuActionHandler,\n [handleTemplateSelect, handleFormat, handleDeploy, handleCopy],\n );\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { useMemo } from 'react';\n\nimport { create } from '@dxos/live-object';\n\nimport { type DeployState } from './deploy';\nimport { type ViewState } from './view';\n\nexport type ScriptToolbarState = Partial<DeployState & ViewState>;\n\nexport const useToolbarState = (initialState: ScriptToolbarState = {}) => {\n return useMemo(() => create<ScriptToolbarState>(initialState), []);\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 },\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": ";;;;;;;;;;;AAIA,OAAOA,UAASC,WAAAA,gBAAe;AAG/B,SAASC,mBAAmBC,YAAAA,iBAAgB;AAC5C,SAASC,mBAAmB;AAE5B,SAASC,sBAAsBC,UAAUC,wCAAwC;AACjF,SAASC,iBAAiB;AAC1B,SAASC,UAAU;;;ACRnB,OAAOC,SAASC,eAAAA,oBAAmB;AAGnC,SAASC,wBAAwB;AACjC,SAASC,yBAA+C;AACxD,SAASC,yCAAyC;AAClD,SAASC,oBAAoBC,cAAcC,aAAaC,sBAAsB;;;ACN9E,SAASC,aAAaC,WAAWC,eAAe;AAEhD,SACEC,cAEAC,kBACAC,8BACAC,sBACAC,8BACAC,4BACK;AACP,SAASC,eAAe;AACxB,SAASC,WAAW;AACpB,SAASC,iBAAiB;AAC1B,SAASC,QAAQC,QAAQC,SAASC,UAAUC,SAASC,gBAAgB;AACrE,SAASC,sBAAsB;AAC/B,SAASC,wBAAwB;;AAc1B,IAAMC,eAAe,CAACC,UAAAA;AAC3B,QAAMC,YAAYC,iBAAiB,SAAS;IAC1CC,OAAOH,MAAMI,SAAS;MAAC;MAAkB;QAAEC,IAAIC;MAAc;;IAC7DC,MAAM;IACNC,QAAQ,CA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ACjFR;MACAF;IACF,CAAA;KAEF;IAACJ;IAAQA,OAAOa,OAAOC;IAAQR;IAAOF;GAAS;AAGjD,QAAMgB,QAAQC,gBAAgB;IAAEC,MAAM;EAAS,CAAA;AAC/CC,iBAAe;IAAEH;IAAOpB;EAAO,CAAA;AAE/B,SACE,gBAAAwB,OAAA,cAACC,UAAUC,SAAO;IAACC,SAAAA;KACjB,gBAAAH,OAAA,cAACI,eAAAA;IAAcR;IAActB;IAAYE;MACzC,gBAAAwB,OAAA,cAACK,OAAAA;IAAI/B,MAAK;IAAOgC,WAAWC,GAAG,kEAAkEhC,UAAAA;KAC9FqB,MAAME,SAAS,WACd,gBAAAE,OAAA,cAACQ,kBAAAA;IACCd,IAAIlB,OAAOkB;IACXf;IACA8B,cAAcjC,OAAOa,QAAQC,QAAQC;IACrCP;IACAsB,WAAWI,iCAAiCpC,IAAAA;IAC5CqC,WAAWlC,SAASC;IACpByB,SAAAA;MAIHP,MAAME,SAAS,YAAY,gBAAAE,OAAA,cAACY,YAAAA;IAAWC,aAAajB,MAAMiB;;AAInE;AAEA,IAAA,0BAAexC;",
6
+ "names": ["React", "useMemo", "createDocAccessor", "getSpace", "useIdentity", "createDataExtensions", "listener", "stackItemContentEditorClassNames", "StackItem", "mx", "React", "useCallback", "fullyQualifiedId", "ElevationProvider", "stackItemContentToolbarClassNames", "createGapSeparator", "MenuProvider", "ToolbarMenu", "useMenuActions", "useCallback", "useEffect", "useMemo", "FunctionType", "getInvocationUrl", "getUserFunctionUrlInMetadata", "incrementSemverPatch", "setUserFunctionUrlInMetadata", "uploadWorkerFunction", "Bundler", "log", "useClient", "Filter", "create", "getMeta", "getSpace", "makeRef", "useQuery", "useTranslation", "createMenuAction", "createDeploy", "state", "errorItem", "createMenuAction", "label", "error", "ns", "SCRIPT_PLUGIN", "icon", "hidden", "deployAction", "type", "deploying", "disabled", "classNames", "copyAction", "functionUrl", "nodes", "edges", "source", "target", "useDeployDeps", "script", "space", "getSpace", "fn", "useQuery", "Filter", "schema", "FunctionType", "client", "useClient", "existingFunctionUrl", "useMemo", "getUserFunctionUrlInMetadata", "getMeta", "useDeployState", "useEffect", "getInvocationUrl", "config", "values", "runtime", "services", "edge", "url", "spaceId", "id", "deployed", "Boolean", "changed", "useDeployHandler", "t", "useTranslation", "useCallback", "undefined", "existingFunctionId", "split", "at", "bundler", "Bundler", "platform", "sandboxedModules", "remoteModules", "buildResult", "bundle", "content", "functionId", "version", "meta", "uploadWorkerFunction", "incrementSemverPatch", "Error", "log", "info", "deployedFunction", "db", "add", "create", "name", "makeRef", "description", "trim", "verbose", "inputSchema", "outputSchema", "setUserFunctionUrlInMetadata", "view", "err", "catch", "useCopyHandler", "navigator", "clipboard", "writeText", "format", "prettierPluginEstree", "prettierPluginTypescript", "useCallback", "log", "createMenuAction", "createFormat", "formatAction", "createMenuAction", "label", "ns", "SCRIPT_PLUGIN", "icon", "nodes", "edges", "source", "target", "useFormatHandler", "script", "useCallback", "content", "format", "parser", "plugins", "prettierPluginEstree", "prettierPluginTypescript", "semi", "singleQuote", "err", "log", "catch", "useCallback", "FUNCTIONS_PRESET_META_KEY", "getMeta", "createMenuItemGroup", "createMenuAction", "createTemplateSelectGroup", "createMenuItemGroup", "label", "ns", "SCRIPT_PLUGIN", "variant", "createTemplateSelectActions", "templates", "map", "template", "createMenuAction", "id", "name", "value", "type", "createTemplateSelect", "templateSelectGroup", "templateSelectActions", "nodes", "edges", "source", "target", "action", "useTemplateSelectHandler", "script", "useCallback", "templateId", "find", "content", "metaKeys", "getMeta", "keys", "oldPresetIndex", "findIndex", "key", "FUNCTIONS_PRESET_META_KEY", "splice", "presetId", "push", "createMenuAction", "createMenuItemGroup", "views", "editor", "split", "debug", "createViewGroupItem", "state", "createMenuItemGroup", "label", "ns", "SCRIPT_PLUGIN", "variant", "applyActive", "value", "view", "createViewActions", "Object", "entries", "map", "viewType", "icon", "createMenuAction", "type", "checked", "createView", "viewGroupItem", "viewActions", "nodes", "edges", "source", "target", "action", "id", "useCallback", "log", "useToolbarAction", "props", "handleTemplateSelect", "useTemplateSelectHandler", "handleFormat", "useFormatHandler", "handleDeploy", "useDeployHandler", "handleCopy", "useCopyHandler", "useCallback", "action", "properties", "type", "value", "state", "view", "log", "error", "useMemo", "create", "useToolbarState", "initialState", "useMemo", "create", "createToolbar", "state", "templateSelect", "createTemplateSelect", "format", "createFormat", "gap", "createGapSeparator", "deploy", "createDeploy", "view", "createView", "nodes", "edges", "ScriptToolbar", "script", "role", "classNames", "handleAction", "useToolbarAction", "toolbarCreator", "useCallback", "menu", "useMenuActions", "div", "className", "stackItemContentToolbarClassNames", "ElevationProvider", "elevation", "MenuProvider", "onAction", "attendableId", "fullyQualifiedId", "ToolbarMenu", "javascript", "defaultHighlightStyle", "Prec", "oneDarkHighlightStyle", "keymap", "tags", "continueKeymap", "tsSync", "tsFacet", "tsLinter", "tsAutocomplete", "tsHover", "React", "useThemeContext", "autocomplete", "createBasicExtensions", "createThemeExtensions", "editorFullWidth", "editorMonospace", "EditorView", "folding", "InputModeExtensions", "useTextEditor", "isNonNullable", "TypescriptEditor", "id", "env", "className", "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", "InputModeExtensions", "folding", "Prec", "high", "keymap", "of", "continueKeymap", "editorMonospace", "javascript", "typescript", "autocomplete", "override", "tsAutocomplete", "tsFacet", "path", "tsSync", "tsLinter", "tsHover", "renderTooltip", "createTooltipRenderer", "filter", "isNonNullable", "React", "div", "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", "role", "classNames", "script", "settings", "editorInputMode", "env", "identity", "useIdentity", "space", "getSpace", "extensions", "useMemo", "listener", "onChange", "text", "source", "target", "content", "changed", "createDataExtensions", "id", "createDocAccessor", "state", "useToolbarState", "view", "useDeployState", "React", "StackItem", "Content", "toolbar", "ScriptToolbar", "div", "className", "mx", "TypescriptEditor", "initialValue", "stackItemContentEditorClassNames", "inputMode", "DebugPanel", "functionUrl"]
7
+ }
@@ -5,9 +5,9 @@ import { createArtifactElement } from "@dxos/assistant";
5
5
  import { ObjectId, S } from "@dxos/echo-schema";
6
6
  import { ScriptType } from "@dxos/functions";
7
7
  import { invariant } from "@dxos/invariant";
8
+ import { SpaceAction } from "@dxos/plugin-space/types";
8
9
  import { create, makeRef } from "@dxos/react-client/echo";
9
10
  import { TextType } from "@dxos/schema";
10
- import { SpaceAction } from "@dxos/plugin-space/types";
11
11
  var __dxlog_file = "/home/runner/work/dxos/dxos/packages/plugins/experimental/plugin-script/src/capabilities/artifact.ts";
12
12
  var artifact_default = () => {
13
13
  const definition = defineArtifact({
@@ -77,7 +77,7 @@ var artifact_default = () => {
77
77
  })
78
78
  S.Array(S.String)
79
79
  S.Union(S.String, S.Number)
80
- S.Optional(S.String)
80
+ S.optional(S.String)
81
81
  S.String.annotations({ description: 'The source currency' })
82
82
  </apis>
83
83
 
@@ -240,4 +240,4 @@ var artifact_default = () => {
240
240
  export {
241
241
  artifact_default as default
242
242
  };
243
- //# sourceMappingURL=artifact-3UZZBCZ2.mjs.map
243
+ //# sourceMappingURL=artifact-YCIVHFSS.mjs.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/capabilities/artifact.ts"],
4
- "sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport { Capabilities, contributes, createIntent, type PromiseIntentDispatcher } from '@dxos/app-framework';\nimport { defineArtifact, defineTool, ToolResult } from '@dxos/artifact';\nimport { createArtifactElement } from '@dxos/assistant';\nimport { ObjectId, S } from '@dxos/echo-schema';\nimport { ScriptType } from '@dxos/functions';\nimport { invariant } from '@dxos/invariant';\nimport { create, makeRef, type Space } from '@dxos/react-client/echo';\nimport { TextType } from '@dxos/schema';\nimport { SpaceAction } from '@dxos/plugin-space/types';\n\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: 'plugin-script',\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 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: S.Schema, \n outputSchema: S.Schema, \n handler: (params: { event: { data: TInput } }) => Promise<TOutput> \n }): FunctionDefinition\n /**\n * Effect Schema\n */\n export const S; \n\n // Examples: \n\n S.String\n S.Number\n S.Boolean\n S.Struct({\n from: S.String.annotations({ description: 'The source currency' }),\n to: S.String.annotations({ description: 'The target currency' }),\n })\n S.Array(S.String)\n S.Union(S.String, S.Number)\n S.Optional(S.String)\n S.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: 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.Struct({\n rate: S.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({\n name: 'script_new',\n description: 'Create a new script. Returns the artifact definition for the script',\n schema: S.Struct({\n name: S.String.annotations({ description: 'The name of the script' }),\n code: S.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 = create(ScriptType, {\n name,\n source: makeRef(\n create(TextType, {\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({\n name: 'script_inspect',\n description: 'Inspect a script. Returns the artifact definition for the script',\n schema: S.Struct({\n id: ObjectId,\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({\n name: 'script_update',\n description: 'Update a script. Returns the artifact definition for the script',\n schema: S.Struct({\n id: ObjectId,\n code: S.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": ";AAIA,SAASA,cAAcC,aAAaC,oBAAkD;AACtF,SAASC,gBAAgBC,YAAYC,kBAAkB;AACvD,SAASC,6BAA6B;AACtC,SAASC,UAAUC,SAAS;AAC5B,SAASC,kBAAkB;AAC3B,SAASC,iBAAiB;AAC1B,SAASC,QAAQC,eAA2B;AAC5C,SAASC,gBAAgB;AACzB,SAASC,mBAAmB;;AAU5B,IAAA,mBAAe,MAAA;AACb,QAAMC,aAAaZ,eAAe;IAChCa,IAAI;;;;IAIJC,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IA4GdC,QAAQT;IACRU,OAAO;MACLf,WAAW;QACTgB,MAAM;QACNC,aAAa;QACbH,QAAQV,EAAEc,OAAO;UACfF,MAAMZ,EAAEe,OAAOC,YAAY;YAAEH,aAAa;UAAyB,CAAA;UACnEI,MAAMjB,E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QACbH,QAAQV,EAAEc,OAAO;UACfN,IAAIT;UACJkB,MAAMjB,EAAEe,OAAOC,YAAY;YACzBH,aAAa;UACf,CAAA;QACF,CAAA;QACAK,SAAS,OAAO,EAAEV,IAAIS,KAAI,GAAI,EAAEE,WAAU,MAAE;AAC1CjB,oBAAUiB,YAAYC,OAAO,YAAA;;;;;;;;;AAE7B,gBAAME,SAAU,MAAMH,WAAWC,MAAMK,GAAGY,MAAM;YAAE7B;UAAG,CAAA,EAAG8B,MAAK;AAC7D,gBAAMf,SAAS,MAAMD,OAAOC,OAAOgB,KAAI;AACvC,cAAI,CAAChB,QAAQ;AACX,mBAAO1B,WAAWqC,MAAM,kBAAA;UAC1B;AAEAX,iBAAOC,UAAUP;AACjB,gBAAME,WAAWC,OAAOK,GAAGE,MAAAA;AAE3B,iBAAO9B,WAAWuC,QAAQ;YACxBxB,MAAMU,OAAOV;UACf,CAAA;QACF;MACF,CAAA;;EAEJ,CAAA;AAEA,SAAOnB,YAAYD,aAAagD,oBAAoBjC,UAAAA;AACtD;",
6
- "names": ["Capabilities", "contributes", "createIntent", "defineArtifact", "defineTool", "ToolResult", "createArtifactElement", "ObjectId", "S", "ScriptType", "invariant", "create", "makeRef", "TextType", "SpaceAction", "definition", "id", "instructions", "schema", "tools", "name", "description", "Struct", "String", "annotations", "code", "execute", "extensions", "space", "dispatch", "script", "source", "content", "db", "add", "flush", "intent", "AddObject", "target", "object", "data", "error", "Error", "message", "Success", "query", "first", "load", "ArtifactDefinition"]
4
+ "sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport { Capabilities, contributes, createIntent, type PromiseIntentDispatcher } from '@dxos/app-framework';\nimport { defineArtifact, defineTool, ToolResult } from '@dxos/artifact';\nimport { createArtifactElement } from '@dxos/assistant';\nimport { ObjectId, S } from '@dxos/echo-schema';\nimport { ScriptType } from '@dxos/functions';\nimport { invariant } from '@dxos/invariant';\nimport { SpaceAction } from '@dxos/plugin-space/types';\nimport { create, makeRef, type Space } from '@dxos/react-client/echo';\nimport { TextType } from '@dxos/schema';\n\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: 'plugin-script',\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 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: S.Schema, \n outputSchema: S.Schema, \n handler: (params: { event: { data: TInput } }) => Promise<TOutput> \n }): FunctionDefinition\n /**\n * Effect Schema\n */\n export const S; \n\n // Examples: \n\n S.String\n S.Number\n S.Boolean\n S.Struct({\n from: S.String.annotations({ description: 'The source currency' }),\n to: S.String.annotations({ description: 'The target currency' }),\n })\n S.Array(S.String)\n S.Union(S.String, S.Number)\n S.optional(S.String)\n S.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: 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.Struct({\n rate: S.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({\n name: 'script_new',\n description: 'Create a new script. Returns the artifact definition for the script',\n schema: S.Struct({\n name: S.String.annotations({ description: 'The name of the script' }),\n code: S.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 = create(ScriptType, {\n name,\n source: makeRef(\n create(TextType, {\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({\n name: 'script_inspect',\n description: 'Inspect a script. Returns the artifact definition for the script',\n schema: S.Struct({\n id: ObjectId,\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({\n name: 'script_update',\n description: 'Update a script. Returns the artifact definition for the script',\n schema: S.Struct({\n id: ObjectId,\n code: S.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": ";AAIA,SAASA,cAAcC,aAAaC,oBAAkD;AACtF,SAASC,gBAAgBC,YAAYC,kBAAkB;AACvD,SAASC,6BAA6B;AACtC,SAASC,UAAUC,SAAS;AAC5B,SAASC,kBAAkB;AAC3B,SAASC,iBAAiB;AAC1B,SAASC,mBAAmB;AAC5B,SAASC,QAAQC,eAA2B;AAC5C,SAASC,gBAAgB;;AAUzB,IAAA,mBAAe,MAAA;AACb,QAAMC,aAAaZ,eAAe;IAChCa,IAAI;;;;IAIJC,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IA4GdC,QAAQT;IACRU,OAAO;MACLf,WAAW;QACTgB,MAAM;QACNC,aAAa;QACbH,QAAQV,EAAEc,OAAO;UACfF,MAAMZ,EAAEe,OAAOC,YAAY;YAAEH,aAAa;UAAyB,CAAA;UACnEI,MAAMjB,EAAEe,OAAOC,YAAY;YACzBH,aAAa;UACf,CAAA;QACF,CAAA;QACAK,SAAS,OAAO,EAAEN,MAAMK,KAAI,GAAI,EAAEE,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AAA;QACAK,SAAS,OAAO,EAAEV,IAAIS,KAAI,GAAI,EAAEE,WAAU,MAAE;AAC1CjB,oBAAUiB,YAAYC,OAAO,YAAA;;;;;;;;;AAE7B,gBAAME,SAAU,MAAMH,WAAWC,MAAMK,GAAGY,MAAM;YAAE7B;UAAG,CAAA,EAAG8B,MAAK;AAC7D,gBAAMf,SAAS,MAAMD,OAAOC,OAAOgB,KAAI;AACvC,cAAI,CAAChB,QAAQ;AACX,mBAAO1B,WAAWqC,MAAM,kBAAA;UAC1B;AAEAX,iBAAOC,UAAUP;AACjB,gBAAME,WAAWC,OAAOK,GAAGE,MAAAA;AAE3B,iBAAO9B,WAAWuC,QAAQ;YACxBxB,MAAMU,OAAOV;UACf,CAAA;QACF;MACF,CAAA;;EAEJ,CAAA;AAEA,SAAOnB,YAAYD,aAAagD,oBAAoBjC,UAAAA;AACtD;",
6
+ "names": ["Capabilities", "contributes", "createIntent", "defineArtifact", "defineTool", "ToolResult", "createArtifactElement", "ObjectId", "S", "ScriptType", "invariant", "SpaceAction", "create", "makeRef", "TextType", "definition", "id", "instructions", "schema", "tools", "name", "description", "Struct", "String", "annotations", "code", "execute", "extensions", "space", "dispatch", "script", "source", "content", "db", "add", "flush", "intent", "AddObject", "target", "object", "data", "error", "Error", "message", "Success", "query", "first", "load", "ArtifactDefinition"]
7
7
  }
@@ -4,18 +4,21 @@ var chat_default = "//\n// Copyright 2024 DXOS.org\n//\n\n// @ts-ignore\nimport
4
4
  // raw-loader:./chess.ts?raw
5
5
  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";
6
6
 
7
+ // raw-loader:./discord.ts?raw
8
+ var discord_default = "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { createStatic, EchoObject, 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 } from 'https://esm.sh/effect@3.13.3';\n\nconst MessageSchema = S.Struct({\n id: S.String,\n foreignId: S.Number,\n content: S.String,\n}).pipe(EchoObject('example.com/type/Message', '0.1.0'));\n\nexport default defineFunction({\n inputSchema: S.Struct({\n channelId: S.String,\n queueId: S.String,\n pageSize: S.optional(S.Number),\n }),\n\n outputSchema: S.Struct({\n newMessages: S.Number,\n }),\n\n handler: ({\n event: {\n data: { channelId, queueId, pageSize = 5 },\n },\n context: { space },\n }: any) =>\n Effect.gen(function* () {\n const { token } = yield* Effect.tryPromise(() =>\n space.db.query(Filter.typename('dxos.org/type/AccessToken', { source: 'discord.com' })).first(),\n );\n\n const enqueueMessages = Effect.gen(function* () {\n const rest = yield* DiscordREST;\n const { objects } = yield* Effect.tryPromise(() => space.queues.queryQueue(DXN.parse(queueId)));\n\n let newMessages = 0;\n let lastMessage = objects.at(-1);\n while (true) {\n // NOTE: If `after` is specified, the specified message is included in the results.\n const messages = yield* rest\n .getChannelMessages(channelId, { after: lastMessage?.foreignId, limit: pageSize })\n .pipe((res: any) => res.json);\n if (messages.length === 1) {\n break;\n }\n const queueMessages = messages\n .map((message: any) =>\n createStatic(MessageSchema, {\n id: ObjectId.random(),\n foreignId: parseInt(message.id),\n content: message.content,\n }),\n )\n .slice(lastMessage ? 1 : 0)\n .toReversed();\n yield* Effect.tryPromise(() => space.queues.insertIntoQueue(DXN.parse(queueId), queueMessages));\n newMessages += queueMessages.length;\n lastMessage = queueMessages.at(-1);\n }\n\n return { newMessages };\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 return yield* enqueueMessages;\n }),\n});\n";
9
+
7
10
  // raw-loader:./echo.ts?raw
8
11
  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";
9
12
 
10
13
  // raw-loader:./email.ts?raw
11
14
  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";
12
15
 
16
+ // raw-loader:./forex-effect.ts?raw
17
+ var forex_effect_default = "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { defineFunction, S } 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\n/**\n * Returns the exchange rate between two currencies.\n */\nexport default defineFunction({\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.Struct({\n rate: S.Number,\n }),\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(1000).pipe(Schedule.compose(Schedule.recurs(3)))),\n Effect.scoped,\n );\n return { rate: res.data.rates[to].toString() };\n }).pipe(Effect.provide(FetchHttpClient.layer)),\n});\n";
18
+
13
19
  // raw-loader:./forex.ts?raw
14
20
  var forex_default = "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { defineFunction, S } from 'dxos:functions';\n\n/**\n * Returns the exchange rate between two currencies.\n */\nexport default defineFunction({\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";
15
21
 
16
- // raw-loader:./forex-effect.ts?raw
17
- var forex_effect_default = "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { defineFunction, S } from 'dxos:functions';\nimport {\n HttpClient,\n HttpClientRequest,\n HttpClientResponse,\n HttpClientError,\n // @ts-ignore\n} from 'https://esm.sh/@effect/platform@0.61.0?deps=effect@3.6.0';\n// @ts-ignore\nimport type { Cause } from 'https://esm.sh/effect@3.6.0';\n// @ts-ignore\nimport { Effect, Schedule } from 'https://esm.sh/effect@3.6.0';\n\n/**\n * Returns the exchange rate between two currencies.\n */\nexport default defineFunction({\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,\n\n handler: async ({\n event: {\n data: { from, to },\n },\n }: any) =>\n HttpClientRequest.get(`https://free.ratesdb.com/v1/rates?from=${from}&to=${to}`).pipe(\n HttpClient.fetchOk,\n HttpClientResponse.json,\n Effect.timeout('1 second'),\n Effect.retry(Schedule.exponential(1000).pipe(Schedule.compose(Schedule.recurs(3)))),\n Effect.map(({ data: { rates } }: any) => rates[to].toString()),\n ),\n});\n";
18
-
19
22
  // packages/plugins/experimental/plugin-script/src/templates/index.ts
20
23
  var removeHeader = (str) => str.split("\n").slice(4).join("\n");
21
24
  var templates = [
@@ -51,10 +54,16 @@ var templates = [
51
54
  name: "Email",
52
55
  source: removeHeader(email_default),
53
56
  presetId: "dxos.org/function/email"
57
+ },
58
+ {
59
+ id: "dxos.org/script/discord",
60
+ name: "Discord",
61
+ source: removeHeader(discord_default),
62
+ presetId: "dxos.org/function/discord"
54
63
  }
55
64
  ];
56
65
 
57
66
  export {
58
67
  templates
59
68
  };
60
- //# sourceMappingURL=chunk-VIX22OMB.mjs.map
69
+ //# sourceMappingURL=chunk-GB5OS4JQ.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["raw-loader:./chat.ts?raw", "raw-loader:./chess.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", "../../../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 === 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 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { createStatic, EchoObject, 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 } from 'https://esm.sh/effect@3.13.3';\n\nconst MessageSchema = S.Struct({\n id: S.String,\n foreignId: S.Number,\n content: S.String,\n}).pipe(EchoObject('example.com/type/Message', '0.1.0'));\n\nexport default defineFunction({\n inputSchema: S.Struct({\n channelId: S.String,\n queueId: S.String,\n pageSize: S.optional(S.Number),\n }),\n\n outputSchema: S.Struct({\n newMessages: S.Number,\n }),\n\n handler: ({\n event: {\n data: { channelId, queueId, pageSize = 5 },\n },\n context: { space },\n }: any) =>\n Effect.gen(function* () {\n const { token } = yield* Effect.tryPromise(() =>\n space.db.query(Filter.typename('dxos.org/type/AccessToken', { source: 'discord.com' })).first(),\n );\n\n const enqueueMessages = Effect.gen(function* () {\n const rest = yield* DiscordREST;\n const { objects } = yield* Effect.tryPromise(() => space.queues.queryQueue(DXN.parse(queueId)));\n\n let newMessages = 0;\n let lastMessage = objects.at(-1);\n while (true) {\n // NOTE: If `after` is specified, the specified message is included in the results.\n const messages = yield* rest\n .getChannelMessages(channelId, { after: lastMessage?.foreignId, limit: pageSize })\n .pipe((res: any) => res.json);\n if (messages.length === 1) {\n break;\n }\n const queueMessages = messages\n .map((message: any) =>\n createStatic(MessageSchema, {\n id: ObjectId.random(),\n foreignId: parseInt(message.id),\n content: message.content,\n }),\n )\n .slice(lastMessage ? 1 : 0)\n .toReversed();\n yield* Effect.tryPromise(() => space.queues.insertIntoQueue(DXN.parse(queueId), queueMessages));\n newMessages += queueMessages.length;\n lastMessage = queueMessages.at(-1);\n }\n\n return { newMessages };\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 return yield* enqueueMessages;\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 { defineFunction, S } 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\n/**\n * Returns the exchange rate between two currencies.\n */\nexport default defineFunction({\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.Struct({\n rate: S.Number,\n }),\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(1000).pipe(Schedule.compose(Schedule.recurs(3)))),\n Effect.scoped,\n );\n return { rate: 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\n/**\n * Returns the exchange rate between two currencies.\n */\nexport default defineFunction({\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 2024 DXOS.org\n//\n\n// @ts-ignore\nimport chat from './chat.ts?raw';\n// @ts-ignore\nimport chess from './chess.ts?raw';\n// @ts-ignore\nimport discord from './discord.ts?raw';\n// @ts-ignore\nimport echo from './echo.ts?raw';\n// @ts-ignore\nimport email from './email.ts?raw';\n// @ts-ignore\nimport forexEffect from './forex-effect.ts?raw';\n// @ts-ignore\nimport forex from './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/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"],
5
+ "mappings": ";AAAA;;;ACAA;;;ACAA;;;ACAA;;;ACAA;;;ACAA;;;ACAA;;;ACmBA,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;;",
6
+ "names": ["removeHeader", "str", "split", "slice", "join", "templates", "id", "name", "source", "echo", "forex", "forexEffect", "chat", "presetId", "chess", "email", "discord"]
7
+ }
@@ -225,7 +225,7 @@ var ScriptSettingsPanel = ({ script }) => {
225
225
  // packages/plugins/experimental/plugin-script/src/components/index.ts
226
226
  import { lazy } from "react";
227
227
  var AutomationPanel = lazy(() => import("./AutomationPanel-J3SZ5L3Y.mjs"));
228
- var ScriptContainer = lazy(() => import("./ScriptContainer-QI4NQT7V.mjs"));
228
+ var ScriptContainer = lazy(() => import("./ScriptContainer-SPKDYRXU.mjs"));
229
229
 
230
230
  export {
231
231
  ScriptSettings,
@@ -233,4 +233,4 @@ export {
233
233
  AutomationPanel,
234
234
  ScriptContainer
235
235
  };
236
- //# sourceMappingURL=chunk-F22QPQ6G.mjs.map
236
+ //# sourceMappingURL=chunk-XTD6J6PC.mjs.map
@@ -1,6 +1,3 @@
1
- import {
2
- initializeBundler
3
- } from "./chunk-SDHKTS6H.mjs";
4
1
  import {
5
2
  ScriptCapabilities
6
3
  } from "./chunk-6MOQ4BP3.mjs";
@@ -9,6 +6,7 @@ import "./chunk-FVVCAWNP.mjs";
9
6
  // packages/plugins/experimental/plugin-script/src/capabilities/compiler.ts
10
7
  import wasmUrl from "esbuild-wasm/esbuild.wasm?url";
11
8
  import { contributes } from "@dxos/app-framework";
9
+ import { initializeBundler } from "@dxos/functions/bundler";
12
10
 
13
11
  // packages/plugins/experimental/plugin-script/src/compiler/compiler.ts
14
12
  import { createDefaultMapFromCDN, createSystem, createVirtualTypeScriptEnvironment } from "@typescript/vfs";
@@ -81,4 +79,4 @@ var compiler_default = async () => {
81
79
  export {
82
80
  compiler_default as default
83
81
  };
84
- //# sourceMappingURL=compiler-K3FNRDDN.mjs.map
82
+ //# sourceMappingURL=compiler-YY2XSKHQ.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/capabilities/compiler.ts", "../../../src/compiler/compiler.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport wasmUrl from 'esbuild-wasm/esbuild.wasm?url';\n\nimport { contributes } from '@dxos/app-framework';\nimport { initializeBundler } from '@dxos/functions/bundler';\n\nimport { ScriptCapabilities } from './capabilities';\nimport { Compiler } from '../compiler';\n\nexport default async () => {\n const compiler = new Compiler();\n\n await compiler.initialize();\n // TODO(wittjosiah): Fetch types for https modules.\n compiler.setFile('/src/typings.d.ts', \"declare module 'https://*';\");\n // TODO(wittjosiah): Proper function handler types.\n // TODO(wittjosiah): Remove.\n compiler.setFile(\n '/src/runtime.ts',\n `\n export const Filter: any = {};\n export type FunctionHandler = ({ event, context }: { event: any; context: any }) => Promise<Response>;\n export const functionHandler = (handler: FunctionHandler) => handler;\n `,\n );\n await initializeBundler({ wasmUrl });\n\n return contributes(ScriptCapabilities.Compiler, compiler);\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport {\n createDefaultMapFromCDN,\n createSystem,\n createVirtualTypeScriptEnvironment,\n type VirtualTypeScriptEnvironment,\n} from '@typescript/vfs';\nimport ts from 'typescript';\n\nimport { invariant } from '@dxos/invariant';\n\nconst defaultOptions: ts.CompilerOptions = {\n lib: ['DOM', 'es2022'],\n target: ts.ScriptTarget.ES2022,\n};\n\nexport class Compiler {\n private _env: VirtualTypeScriptEnvironment | undefined;\n private _fsMap: Map<string, string> | undefined;\n\n constructor(private readonly _options: ts.CompilerOptions = defaultOptions) {}\n\n async initialize() {\n if (this._env) {\n return;\n }\n\n // TODO(wittjosiah): Figure out how to get workers working in plugin packages.\n // https://github.com/val-town/codemirror-ts?tab=readme-ov-file#setup-worker\n this._fsMap = await createDefaultMapFromCDN(this._options, '5.5.4', true, ts);\n const system = createSystem(this._fsMap);\n this._env = createVirtualTypeScriptEnvironment(system, [], ts, this._options);\n }\n\n get environment() {\n invariant(this._env, 'Compiler environment not initialized.');\n return this._env;\n }\n\n setFile(fileName: string, content: string) {\n invariant(this._fsMap, 'File system map not initialized.');\n this.environment.createFile(fileName, content);\n }\n\n compile(fileName: string) {\n return this.environment.languageService.getEmitOutput(fileName);\n }\n}\n"],
5
+ "mappings": ";;;;;;AAKA,OAAOA,aAAa;AAEpB,SAASC,mBAAmB;AAC5B,SAASC,yBAAyB;;;ACJlC,SACEC,yBACAC,cACAC,0CAEK;AACP,OAAOC,QAAQ;AAEf,SAASC,iBAAiB;;AAE1B,IAAMC,iBAAqC;EACzCC,KAAK;IAAC;IAAO;;EACbC,QAAQJ,GAAGK,aAAaC;AAC1B;AAEO,IAAMC,WAAN,MAAMA;EAIXC,YAA6BC,WAA+BP,gBAAgB;SAA/CO,WAAAA;EAAgD;EAE7E,MAAMC,aAAa;AACjB,QAAI,KAAKC,MAAM;AACb;IACF;AAIA,SAAKC,SAAS,MAAMf,wBAAwB,KAAKY,UAAU,SAAS,MAAMT,EAAAA;AAC1E,UAAMa,SAASf,aAAa,KAAKc,MAAM;AACvC,SAAKD,OAAOZ,mCAAmCc,QAAQ,CAAA,GAAIb,IAAI,KAAKS,QAAQ;EAC9E;EAEA,IAAIK,cAAc;AAChBb,cAAU,KAAKU,MAAM,yCAAA;;;;;;;;;AACrB,WAAO,KAAKA;EACd;EAEAI,QAAQC,UAAkBC,SAAiB;AACzChB,cAAU,KAAKW,QAAQ,oCAAA;;;;;;;;;AACvB,SAAKE,YAAYI,WAAWF,UAAUC,OAAAA;EACxC;EAEAE,QAAQH,UAAkB;AACxB,WAAO,KAAKF,YAAYM,gBAAgBC,cAAcL,QAAAA;EACxD;AACF;;;ADrCA,IAAA,mBAAe,YAAA;AACb,QAAMM,WAAW,IAAIC,SAAAA;AAErB,QAAMD,SAASE,WAAU;AAEzBF,WAASG,QAAQ,qBAAqB,6BAAA;AAGtCH,WAASG,QACP,mBACA;;;;OAIG;AAEL,QAAMC,kBAAkB;IAAEC;EAAQ,CAAA;AAElC,SAAOC,YAAYC,mBAAmBN,UAAUD,QAAAA;AAClD;",
6
+ "names": ["wasmUrl", "contributes", "initializeBundler", "createDefaultMapFromCDN", "createSystem", "createVirtualTypeScriptEnvironment", "ts", "invariant", "defaultOptions", "lib", "target", "ScriptTarget", "ES2022", "Compiler", "constructor", "_options", "initialize", "_env", "_fsMap", "system", "environment", "setFile", "fileName", "content", "createFile", "compile", "languageService", "getEmitOutput", "compiler", "Compiler", "initialize", "setFile", "initializeBundler", "wasmUrl", "contributes", "ScriptCapabilities"]
7
+ }
@@ -1,13 +1,9 @@
1
- import {
2
- Bundler,
3
- initializeBundler
4
- } from "./chunk-SDHKTS6H.mjs";
5
1
  import {
6
2
  AutomationPanel,
7
3
  ScriptContainer,
8
4
  ScriptSettings,
9
5
  ScriptSettingsPanel
10
- } from "./chunk-F22QPQ6G.mjs";
6
+ } from "./chunk-XTD6J6PC.mjs";
11
7
  import {
12
8
  ScriptCapabilities
13
9
  } from "./chunk-6MOQ4BP3.mjs";
@@ -21,11 +17,11 @@ import {
21
17
 
22
18
  // packages/plugins/experimental/plugin-script/src/capabilities/index.ts
23
19
  import { lazy } from "@dxos/app-framework";
24
- var Compiler = lazy(() => import("./compiler-K3FNRDDN.mjs"));
25
- var IntentResolver = lazy(() => import("./intent-resolver-CMKQTLBG.mjs"));
26
- var ReactSurface = lazy(() => import("./react-surface-YR4YO746.mjs"));
20
+ var Compiler = lazy(() => import("./compiler-YY2XSKHQ.mjs"));
21
+ var IntentResolver = lazy(() => import("./intent-resolver-IKIQWAL4.mjs"));
22
+ var ReactSurface = lazy(() => import("./react-surface-ZP2FXWYA.mjs"));
27
23
  var ScriptSettings2 = lazy(() => import("./settings-SZCDKHWO.mjs"));
28
- var Artifact = lazy(() => import("./artifact-3UZZBCZ2.mjs"));
24
+ var Artifact = lazy(() => import("./artifact-YCIVHFSS.mjs"));
29
25
 
30
26
  // packages/plugins/experimental/plugin-script/src/ScriptPlugin.tsx
31
27
  import { Capabilities, contributes, createIntent, defineModule, definePlugin, Events } from "@dxos/app-framework";
@@ -156,14 +152,12 @@ var ScriptPlugin = () => definePlugin(meta, [
156
152
  ]);
157
153
  export {
158
154
  AutomationPanel,
159
- Bundler,
160
155
  SCRIPT_PLUGIN,
161
156
  ScriptCapabilities,
162
157
  ScriptContainer,
163
158
  ScriptPlugin,
164
159
  ScriptSettings,
165
160
  ScriptSettingsPanel,
166
- initializeBundler,
167
161
  meta
168
162
  };
169
163
  //# sourceMappingURL=index.mjs.map
@@ -2,6 +2,6 @@
2
2
  "version": 3,
3
3
  "sources": ["../../../src/capabilities/index.ts", "../../../src/ScriptPlugin.tsx", "../../../src/translations.ts"],
4
4
  "sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport { lazy } from '@dxos/app-framework';\n\nexport const Compiler = lazy(() => import('./compiler'));\nexport const IntentResolver = lazy(() => import('./intent-resolver'));\nexport const ReactSurface = lazy(() => import('./react-surface'));\nexport const ScriptSettings = lazy(() => import('./settings'));\nexport const Artifact = lazy(() => import('./artifact'));\n\nexport * from './capabilities';\n", "//\n// Copyright 2023 DXOS.org\n//\n\n// @ts-ignore\n\nimport { Capabilities, contributes, createIntent, defineModule, definePlugin, Events } from '@dxos/app-framework';\nimport { type Space } from '@dxos/client/echo';\nimport { FunctionType, ScriptType } from '@dxos/functions';\nimport { RefArray } from '@dxos/live-object';\nimport { ClientCapabilities, ClientEvents } from '@dxos/plugin-client';\n\nimport { Artifact, Compiler, IntentResolver, ReactSurface, ScriptSettings } from './capabilities';\nimport { meta, SCRIPT_PLUGIN } from './meta';\nimport translations from './translations';\nimport { ScriptAction } from './types';\n\nexport const ScriptPlugin = () =>\n definePlugin(meta, [\n defineModule({\n id: `${meta.id}/module/settings`,\n activatesOn: Events.SetupSettings,\n activate: ScriptSettings,\n }),\n defineModule({\n id: `${meta.id}/module/compiler`,\n activatesOn: Events.Startup,\n activate: Compiler,\n }),\n defineModule({\n id: `${meta.id}/module/translations`,\n activatesOn: Events.SetupTranslations,\n activate: () => contributes(Capabilities.Translations, translations),\n }),\n defineModule({\n id: `${meta.id}/module/metadata`,\n activatesOn: Events.SetupMetadata,\n activate: () =>\n contributes(Capabilities.Metadata, {\n id: ScriptType.typename,\n metadata: {\n creationSchema: ScriptAction.CreateScriptSchema,\n createObject: (props: ScriptAction.CreateScriptProps, { space }: { space: Space }) =>\n createIntent(ScriptAction.Create, { ...props, space }),\n placeholder: ['object title placeholder', { ns: SCRIPT_PLUGIN }],\n icon: 'ph--code--regular',\n // TODO(wittjosiah): Move out of metadata.\n loadReferences: async (script: ScriptType) => await RefArray.loadAll([script.source]),\n },\n }),\n }),\n defineModule({\n id: `${meta.id}/module/schema`,\n activatesOn: ClientEvents.SetupSchema,\n activate: () => [\n contributes(ClientCapabilities.SystemSchema, [FunctionType]),\n contributes(ClientCapabilities.Schema, [ScriptType]),\n ],\n }),\n defineModule({\n id: `${meta.id}/module/react-surface`,\n activatesOn: Events.SetupSurfaces,\n activate: ReactSurface,\n }),\n defineModule({\n id: `${meta.id}/module/intent-resolver`,\n activatesOn: Events.SetupIntents,\n activate: IntentResolver,\n }),\n defineModule({\n id: `${meta.id}/module/artifact`,\n activatesOn: Events.Startup,\n activate: Artifact,\n }),\n ]);\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { ScriptType } from '@dxos/functions';\n\nimport { SCRIPT_PLUGIN } from './meta';\n\nexport default [\n {\n 'en-US': {\n [ScriptType.typename]: {\n 'typename label': 'Script',\n },\n [SCRIPT_PLUGIN]: {\n 'plugin name': 'Scripts',\n 'object title placeholder': 'New script',\n 'create object label': 'Create script',\n 'create stack section label': 'Create script',\n 'description label': 'Description',\n 'description placeholder': 'Describe what the script does.',\n 'binding placeholder': 'Function name',\n 'function request placeholder': 'Function request',\n 'deploy label': 'Deploy',\n 'deployed label': 'Current version of the script is deployed',\n 'upload failed label': 'Upload failed',\n 'copy link label': 'Copy function link',\n 'format label': 'Format',\n 'toggle details label': 'Toggle details panel',\n 'authenticate action label': 'Authenticate functions service',\n 'authenticate button label': 'Authenticate',\n 'name label': 'Name',\n 'remote function settings heading': 'Remote Function',\n 'function url label': 'Invocation URL',\n 'function binding label': 'Function binding',\n 'function binding placeholder': 'BINDING',\n 'script publish settings label': 'Publishing',\n 'script publish settings description': 'Scripts can be shared publicly as Github gists.',\n 'no github token label': 'This space has no Github access token available.',\n 'open token manager label': 'Open Token Manager',\n 'publish label': 'Publish',\n 'publishing label': 'Publishing',\n 'editor input mode label': 'Editor input mode',\n 'select editor input mode placeholder': 'Select editor input mode…',\n 'settings editor input mode default label': 'Default',\n 'settings editor input mode vim label': 'Vim',\n 'settings editor input mode vscode label': 'VS Code',\n 'view group label': 'View',\n 'view editor label': 'Editor',\n 'view split label': 'Split',\n 'view debug label': 'Debug',\n 'template select group label': 'Select template',\n },\n },\n },\n];\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;AAIA,SAASA,YAAY;AAEd,IAAMC,WAAWC,KAAK,MAAM,OAAO,yBAAA,CAAA;AACnC,IAAMC,iBAAiBD,KAAK,MAAM,OAAO,gCAAA,CAAA;AACzC,IAAME,eAAeF,KAAK,MAAM,OAAO,8BAAA,CAAA;AACvC,IAAMG,kBAAiBH,KAAK,MAAM,OAAO,yBAAA,CAAA;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AGF,KAAKE,EAAE;IACdC,aAAaC,OAAOW;IACpBT,UAAU,MACRK,YAAYC,aAAaI,UAAU;MACjCd,IAAIe,YAAWC;MACfC,UAAU;QACRC,gBAAgBC,aAAaC;QAC7BC,cAAc,CAACC,OAAuC,EAAEC,MAAK,MAC3DC,aAAaL,aAAaM,QAAQ;UAAE,GAAGH;UAAOC;QAAM,CAAA;QACtDG,aAAa;UAAC;UAA4B;YAAEC,IAAIC;UAAc;;QAC9DC,MAAM;;QAENC,gBAAgB,OAAOC,WAAuB,MAAMC,SAASC,QAAQ;UAACF,OAAOG;SAAO;MACtF;IACF,CAAA;EACJ,CAAA;EACAnC,aAAa;IACXC,IAAI,GAAGF,KAAKE,EAAE;IACdC,aAAakC,aAAaC;IAC1BhC,UAAU,MAAM;MACdK,YAAY4B,mBAAmBC,cAAc;QAACC;OAAa;MAC3D9B,YAAY4B,mBAAmBG,QAAQ;QAACzB;OAAW;;EAEvD,CAAA;EACAhB,aAAa;IACXC,IAAI,GAAGF,KAAKE,EAAE;IACdC,aAAaC,OAAOuC;IACpBrC,UAAUsC;EACZ,CAAA;EACA3C,aAAa;IACXC,IAAI,GAAGF,KAAKE,EAAE;IACdC,aAAaC,OAAOyC;IACpBvC,UAAUwC;EACZ,CAAA;EACA7C,aAAa;IACXC,IAAI,GAAGF,KAAKE,EAAE;IACdC,aAAaC,OAAOI;IACpBF,UAAUyC;EACZ,CAAA;CACD;",
6
6
  "names": ["lazy", "Compiler", "lazy", "IntentResolver", "ReactSurface", "ScriptSettings", "Artifact", "Capabilities", "contributes", "createIntent", "defineModule", "definePlugin", "Events", "FunctionType", "ScriptType", "RefArray", "ClientCapabilities", "ClientEvents", "ScriptType", "ScriptType", "typename", "SCRIPT_PLUGIN", "ScriptPlugin", "definePlugin", "meta", "defineModule", "id", "activatesOn", "Events", "SetupSettings", "activate", "ScriptSettings", "Startup", "Compiler", "SetupTranslations", "contributes", "Capabilities", "Translations", "translations", "SetupMetadata", "Metadata", "ScriptType", "typename", "metadata", "creationSchema", "ScriptAction", "CreateScriptSchema", "createObject", "props", "space", "createIntent", "Create", "placeholder", "ns", "SCRIPT_PLUGIN", "icon", "loadReferences", "script", "RefArray", "loadAll", "source", "ClientEvents", "SetupSchema", "ClientCapabilities", "SystemSchema", "FunctionType", "Schema", "SetupSurfaces", "ReactSurface", "SetupIntents", "IntentResolver", "Artifact"]
7
7
  }
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  templates
3
- } from "./chunk-VIX22OMB.mjs";
3
+ } from "./chunk-GB5OS4JQ.mjs";
4
4
  import {
5
5
  ScriptAction
6
6
  } from "./chunk-N46LE7FS.mjs";
@@ -42,4 +42,4 @@ var intent_resolver_default = () => contributes(Capabilities.IntentResolver, cre
42
42
  export {
43
43
  intent_resolver_default as default
44
44
  };
45
- //# sourceMappingURL=intent-resolver-CMKQTLBG.mjs.map
45
+ //# sourceMappingURL=intent-resolver-IKIQWAL4.mjs.map