@dxos/plugin-script 0.8.3-main.7f5a14c → 0.8.3

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 (58) hide show
  1. package/dist/lib/browser/{ScriptContainer-BQS7LDI7.mjs → ScriptContainer-RSN52NH7.mjs} +6 -8
  2. package/dist/lib/browser/ScriptContainer-RSN52NH7.mjs.map +7 -0
  3. package/dist/lib/browser/{chunk-I6S7QLGR.mjs → chunk-3FU4QZVP.mjs} +2 -2
  4. package/dist/lib/browser/{chunk-I6S7QLGR.mjs.map → chunk-3FU4QZVP.mjs.map} +1 -1
  5. package/dist/lib/browser/{chunk-OMQLWT6X.mjs → chunk-3JLR2SHJ.mjs} +6 -6
  6. package/dist/lib/browser/{chunk-OMQLWT6X.mjs.map → chunk-3JLR2SHJ.mjs.map} +1 -1
  7. package/dist/lib/browser/index.mjs +9 -5
  8. package/dist/lib/browser/index.mjs.map +3 -3
  9. package/dist/lib/browser/{intent-resolver-52BWIOT6.mjs → intent-resolver-JOJNH4UX.mjs} +3 -3
  10. package/dist/lib/browser/meta.json +1 -1
  11. package/dist/lib/browser/{react-surface-3V4HK2LR.mjs → react-surface-7BKUWL2U.mjs} +4 -4
  12. package/dist/lib/browser/{react-surface-3V4HK2LR.mjs.map → react-surface-7BKUWL2U.mjs.map} +3 -3
  13. package/dist/lib/node/{ScriptContainer-OYFP6E5B.cjs → ScriptContainer-CAC7AISY.cjs} +22 -24
  14. package/dist/lib/node/ScriptContainer-CAC7AISY.cjs.map +7 -0
  15. package/dist/lib/node/{chunk-GUNGYAZU.cjs → chunk-AU2FOE26.cjs} +5 -5
  16. package/dist/lib/node/{chunk-GUNGYAZU.cjs.map → chunk-AU2FOE26.cjs.map} +1 -1
  17. package/dist/lib/node/{chunk-WHXKN26U.cjs → chunk-OSBMUJ4T.cjs} +11 -11
  18. package/dist/lib/node/{chunk-WHXKN26U.cjs.map → chunk-OSBMUJ4T.cjs.map} +1 -1
  19. package/dist/lib/node/index.cjs +16 -12
  20. package/dist/lib/node/index.cjs.map +3 -3
  21. package/dist/lib/node/{intent-resolver-UEBRMMP6.cjs → intent-resolver-BQ2NKEM7.cjs} +9 -9
  22. package/dist/lib/node/meta.json +1 -1
  23. package/dist/lib/node/{react-surface-AYOFUM7K.cjs → react-surface-EUKPDFU3.cjs} +13 -13
  24. package/dist/lib/node/{react-surface-AYOFUM7K.cjs.map → react-surface-EUKPDFU3.cjs.map} +3 -3
  25. package/dist/lib/node-esm/{ScriptContainer-G35TAL5S.mjs → ScriptContainer-4IOOIPBF.mjs} +6 -8
  26. package/dist/lib/node-esm/ScriptContainer-4IOOIPBF.mjs.map +7 -0
  27. package/dist/lib/node-esm/{chunk-AOI67UC7.mjs → chunk-B4TP3LSZ.mjs} +6 -6
  28. package/dist/lib/node-esm/{chunk-AOI67UC7.mjs.map → chunk-B4TP3LSZ.mjs.map} +1 -1
  29. package/dist/lib/node-esm/{chunk-T43WW6DG.mjs → chunk-W2DAXWHA.mjs} +2 -2
  30. package/dist/lib/node-esm/{chunk-T43WW6DG.mjs.map → chunk-W2DAXWHA.mjs.map} +1 -1
  31. package/dist/lib/node-esm/index.mjs +9 -5
  32. package/dist/lib/node-esm/index.mjs.map +3 -3
  33. package/dist/lib/node-esm/{intent-resolver-QEVLFH3G.mjs → intent-resolver-HTM5PSRZ.mjs} +3 -3
  34. package/dist/lib/node-esm/meta.json +1 -1
  35. package/dist/lib/node-esm/{react-surface-XNNTCP2O.mjs → react-surface-6UO64YOS.mjs} +4 -4
  36. package/dist/lib/node-esm/{react-surface-XNNTCP2O.mjs.map → react-surface-6UO64YOS.mjs.map} +3 -3
  37. package/dist/types/src/components/ScriptToolbar/ScriptToolbar.d.ts.map +1 -1
  38. package/dist/types/src/components/TypescriptEditor/TypescriptEditor.d.ts.map +1 -1
  39. package/dist/types/src/hooks/deploy.d.ts +11 -13
  40. package/dist/types/src/hooks/deploy.d.ts.map +1 -1
  41. package/dist/types/src/translations.d.ts +116 -2
  42. package/dist/types/src/translations.d.ts.map +1 -1
  43. package/dist/types/src/types.d.ts +3 -4
  44. package/dist/types/src/types.d.ts.map +1 -1
  45. package/package.json +49 -49
  46. package/src/capabilities/react-surface.tsx +1 -1
  47. package/src/components/ScriptToolbar/ScriptToolbar.tsx +5 -8
  48. package/src/components/Settings/ScriptObjectSettings.tsx +2 -2
  49. package/src/components/TestPanel/TestPanel.tsx +1 -1
  50. package/src/components/TypescriptEditor/TypescriptEditor.tsx +2 -0
  51. package/src/templates/gmail.ts +1 -1
  52. package/src/translations.ts +5 -1
  53. package/dist/lib/browser/ScriptContainer-BQS7LDI7.mjs.map +0 -7
  54. package/dist/lib/node/ScriptContainer-OYFP6E5B.cjs.map +0 -7
  55. package/dist/lib/node-esm/ScriptContainer-G35TAL5S.mjs.map +0 -7
  56. /package/dist/lib/browser/{intent-resolver-52BWIOT6.mjs.map → intent-resolver-JOJNH4UX.mjs.map} +0 -0
  57. /package/dist/lib/node/{intent-resolver-UEBRMMP6.cjs.map → intent-resolver-BQ2NKEM7.cjs.map} +0 -0
  58. /package/dist/lib/node-esm/{intent-resolver-QEVLFH3G.mjs.map → intent-resolver-HTM5PSRZ.mjs.map} +0 -0
@@ -5,7 +5,7 @@ import {
5
5
  useDeployDeps,
6
6
  useDeployState,
7
7
  useToolbarState
8
- } from "./chunk-I6S7QLGR.mjs";
8
+ } from "./chunk-3FU4QZVP.mjs";
9
9
  import "./chunk-QJH7I2UV.mjs";
10
10
  import "./chunk-WB3X5Z7Q.mjs";
11
11
  import {
@@ -26,7 +26,6 @@ import { Rx } from "@effect-rx/rx-react";
26
26
  import React, { useMemo } from "react";
27
27
  import { fullyQualifiedId } from "@dxos/react-client/echo";
28
28
  import { ElevationProvider, useTranslation } from "@dxos/react-ui";
29
- import { stackItemContentToolbarClassNames } from "@dxos/react-ui-editor";
30
29
  import { createGapSeparator, MenuProvider, rxFromSignal, ToolbarMenu, useMenuActions } from "@dxos/react-ui-menu";
31
30
  var createToolbar = ({ state, script, ...options }) => Rx.make((get) => get(rxFromSignal(() => {
32
31
  const templateSelect = createTemplateSelect(script);
@@ -71,17 +70,14 @@ var ScriptToolbar = ({ script, role, state, classNames }) => {
71
70
  t
72
71
  ]);
73
72
  const menu = useMenuActions(toolbarCreator);
74
- return /* @__PURE__ */ React.createElement("div", {
75
- role: "none",
76
- className: stackItemContentToolbarClassNames(role)
77
- }, /* @__PURE__ */ React.createElement(ElevationProvider, {
73
+ return /* @__PURE__ */ React.createElement(ElevationProvider, {
78
74
  elevation: role === "section" ? "positioned" : "base"
79
75
  }, /* @__PURE__ */ React.createElement(MenuProvider, {
80
76
  ...menu,
81
77
  attendableId: fullyQualifiedId(script)
82
78
  }, /* @__PURE__ */ React.createElement(ToolbarMenu, {
83
79
  classNames
84
- }))));
80
+ })));
85
81
  } finally {
86
82
  _effect.f();
87
83
  }
@@ -91,6 +87,7 @@ var ScriptToolbar = ({ script, role, state, classNames }) => {
91
87
  import { useSignals as _useSignals2 } from "@preact-signals/safe-react/tracking";
92
88
  import { javascript } from "@codemirror/lang-javascript";
93
89
  import { defaultHighlightStyle } from "@codemirror/language";
90
+ import { lintKeymap } from "@codemirror/lint";
94
91
  import { Prec } from "@codemirror/state";
95
92
  import { oneDarkHighlightStyle } from "@codemirror/theme-one-dark";
96
93
  import { keymap } from "@codemirror/view";
@@ -139,6 +136,7 @@ var TypescriptEditor = ({ classNames, id, inputMode = "vscode", toolbar, env, in
139
136
  tsAutocomplete()
140
137
  ] : void 0
141
138
  }),
139
+ keymap.of(lintKeymap),
142
140
  env && [
143
141
  tsFacet.of({
144
142
  env,
@@ -260,4 +258,4 @@ export {
260
258
  ScriptContainer,
261
259
  ScriptContainer_default as default
262
260
  };
263
- //# sourceMappingURL=ScriptContainer-BQS7LDI7.mjs.map
261
+ //# sourceMappingURL=ScriptContainer-RSN52NH7.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/components/ScriptContainer.tsx", "../../../src/components/ScriptToolbar/ScriptToolbar.tsx", "../../../src/components/TypescriptEditor/TypescriptEditor.tsx"],
4
+ "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport React, { useMemo } from 'react';\n\nimport { type ScriptType } from '@dxos/functions';\nimport { createDocAccessor, getSpace } from '@dxos/react-client/echo';\nimport { useIdentity } from '@dxos/react-client/halo';\nimport { createDataExtensions, listener, stackItemContentEditorClassNames } from '@dxos/react-ui-editor';\nimport { StackItem, type StackItemContentProps } from '@dxos/react-ui-stack';\n\nimport { ScriptToolbar } from './ScriptToolbar';\nimport { TypescriptEditor, type TypescriptEditorProps } from './TypescriptEditor';\nimport { useDeployState, useToolbarState } from '../hooks';\nimport { type ScriptSettingsProps } from '../types';\n\nexport type ScriptEditorProps = Pick<StackItemContentProps, 'role'> & {\n script: ScriptType;\n settings?: ScriptSettingsProps;\n} & Pick<TypescriptEditorProps, 'env'>;\n\nexport const ScriptContainer = ({ role, script, settings = { editorInputMode: 'vscode' }, env }: ScriptEditorProps) => {\n const identity = useIdentity();\n const space = getSpace(script);\n const state = useToolbarState();\n useDeployState({ state, script });\n\n const extensions = useMemo(\n () =>\n script.source.target\n ? [\n listener({\n onChange: (text) => {\n if (script.source.target?.content !== text) {\n script.changed = true;\n }\n },\n }),\n createDataExtensions({\n id: script.id,\n text: createDocAccessor(script.source.target, ['content']),\n space,\n identity,\n }),\n ]\n : [],\n [identity, space, script, script.source.target],\n );\n\n return (\n <StackItem.Content toolbar>\n <ScriptToolbar state={state} role={role} script={script} />\n <TypescriptEditor\n id={script.id}\n env={env}\n initialValue={script.source?.target?.content}\n extensions={extensions}\n classNames={stackItemContentEditorClassNames(role)}\n inputMode={settings.editorInputMode}\n toolbar\n />\n </StackItem.Content>\n );\n};\n\nexport default ScriptContainer;\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { Rx } from '@effect-rx/rx-react';\nimport React, { useMemo } from 'react';\n\nimport { type ScriptType } from '@dxos/functions';\nimport { fullyQualifiedId } from '@dxos/react-client/echo';\nimport { ElevationProvider, useTranslation, type ThemedClassName } from '@dxos/react-ui';\nimport { createGapSeparator, MenuProvider, rxFromSignal, ToolbarMenu, useMenuActions } from '@dxos/react-ui-menu';\n\nimport {\n type CreateDeployOptions,\n type ScriptToolbarState,\n createDeploy,\n createFormat,\n createTemplateSelect,\n useDeployDeps,\n} from '../../hooks';\nimport { SCRIPT_PLUGIN } from '../../meta';\n\nconst createToolbar = ({ state, script, ...options }: CreateDeployOptions) =>\n Rx.make((get) =>\n get(\n rxFromSignal(() => {\n const templateSelect = createTemplateSelect(script);\n const format = createFormat(script);\n const gap = createGapSeparator();\n const deploy = createDeploy({ state, script, ...options });\n return {\n nodes: [...templateSelect.nodes, ...format.nodes, ...gap.nodes, ...deploy.nodes],\n edges: [...templateSelect.edges, ...format.edges, ...gap.edges, ...deploy.edges],\n };\n }),\n ),\n );\n\nexport type ScriptToolbarProps = ThemedClassName<{\n role?: string;\n script: ScriptType;\n state: ScriptToolbarState;\n}>;\n\nexport const ScriptToolbar = ({ script, role, state, classNames }: ScriptToolbarProps) => {\n const { t } = useTranslation(SCRIPT_PLUGIN);\n const options = useDeployDeps({ script });\n const toolbarCreator = useMemo(() => createToolbar({ state, script, t, ...options }), [state, script, options, t]);\n const menu = useMenuActions(toolbarCreator);\n\n return (\n <ElevationProvider elevation={role === 'section' ? 'positioned' : 'base'}>\n <MenuProvider {...menu} attendableId={fullyQualifiedId(script)}>\n <ToolbarMenu classNames={classNames} />\n </MenuProvider>\n </ElevationProvider>\n );\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { javascript } from '@codemirror/lang-javascript';\nimport { defaultHighlightStyle } from '@codemirror/language';\nimport { lintKeymap } from '@codemirror/lint';\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 ThemedClassName, type ThemeMode, useThemeContext } from '@dxos/react-ui';\nimport {\n type EditorInputMode,\n InputModeExtensions,\n type UseTextEditorProps,\n autocomplete,\n createBasicExtensions,\n createThemeExtensions,\n folding,\n useTextEditor,\n} from '@dxos/react-ui-editor';\nimport { mx } from '@dxos/react-ui-theme';\nimport { isNonNullable } from '@dxos/util';\n\nexport type TypescriptEditorProps = ThemedClassName<\n {\n id: string;\n inputMode?: EditorInputMode;\n toolbar?: boolean;\n env?: VirtualTypeScriptEnvironment;\n } & Pick<UseTextEditorProps, 'initialValue' | 'extensions' | 'scrollTo' | 'selection'>\n>;\n\nexport const TypescriptEditor = ({\n classNames,\n id,\n inputMode = 'vscode',\n toolbar,\n env,\n initialValue,\n extensions,\n scrollTo,\n selection,\n}: TypescriptEditorProps) => {\n const { themeMode } = useThemeContext();\n const { parentRef, focusAttributes } = useTextEditor(\n () => ({\n id,\n initialValue,\n selection,\n scrollTo,\n extensions: [\n extensions,\n createBasicExtensions({\n highlightActiveLine: true,\n indentWithTab: true,\n lineNumbers: true,\n lineWrapping: false,\n monospace: true,\n scrollPastEnd: true,\n }),\n createThemeExtensions({ themeMode, syntaxHighlighting: true }),\n InputModeExtensions[inputMode],\n folding(),\n // Continues block comments when pressing Enter.\n Prec.high(keymap.of(continueKeymap)),\n\n // TODO(burdon): Factor out.\n javascript({ typescript: true }),\n // https://github.com/val-town/codemirror-ts\n autocomplete({ override: env ? [tsAutocomplete()] : undefined }),\n keymap.of(lintKeymap),\n env && [\n tsFacet.of({ env, path: `/src/${id}.ts` }),\n tsSync(),\n tsLinter(),\n tsHover({ renderTooltip: createTooltipRenderer(themeMode) }),\n ],\n ].filter(isNonNullable),\n }),\n [id, extensions, themeMode, inputMode, selection, scrollTo],\n );\n\n return (\n <div\n ref={parentRef}\n data-toolbar={toolbar ? 'enabled' : 'disabled'}\n className={mx(classNames)}\n {...focusAttributes}\n />\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,gBAAgB;AAC5C,SAASC,mBAAmB;AAC5B,SAASC,sBAAsBC,UAAUC,wCAAwC;AACjF,SAASC,iBAA6C;;;;ACNtD,SAASC,UAAU;AACnB,OAAOC,SAASC,eAAe;AAG/B,SAASC,wBAAwB;AACjC,SAASC,mBAAmBC,sBAA4C;AACxE,SAASC,oBAAoBC,cAAcC,cAAcC,aAAaC,sBAAsB;AAY5F,IAAMC,gBAAgB,CAAC,EAAEC,OAAOC,QAAQ,GAAGC,QAAAA,MACzCC,GAAGC,KAAK,CAACC,QACPA,IACEC,aAAa,MAAA;AACX,QAAMC,iBAAiBC,qBAAqBP,MAAAA;AAC5C,QAAMQ,SAASC,aAAaT,MAAAA;AAC5B,QAAMU,MAAMC,mBAAAA;AACZ,QAAMC,SAASC,aAAa;IAAEd;IAAOC;IAAQ,GAAGC;EAAQ,CA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MAC7CiC,WAAW/B,SAASC;MACpBwB,SAAAA;;;;;AAIR;AAEA,IAAA,0BAAe5B;",
6
+ "names": ["React", "useMemo", "createDocAccessor", "getSpace", "useIdentity", "createDataExtensions", "listener", "stackItemContentEditorClassNames", "StackItem", "Rx", "React", "useMemo", "fullyQualifiedId", "ElevationProvider", "useTranslation", "createGapSeparator", "MenuProvider", "rxFromSignal", "ToolbarMenu", "useMenuActions", "createToolbar", "state", "script", "options", "Rx", "make", "get", "rxFromSignal", "templateSelect", "createTemplateSelect", "format", "createFormat", "gap", "createGapSeparator", "deploy", "createDeploy", "nodes", "edges", "ScriptToolbar", "role", "classNames", "t", "useTranslation", "SCRIPT_PLUGIN", "useDeployDeps", "toolbarCreator", "useMemo", "menu", "useMenuActions", "ElevationProvider", "elevation", "MenuProvider", "attendableId", "fullyQualifiedId", "ToolbarMenu", "javascript", "defaultHighlightStyle", "lintKeymap", "Prec", "oneDarkHighlightStyle", "keymap", "tags", "continueKeymap", "tsSync", "tsFacet", "tsLinter", "tsAutocomplete", "tsHover", "React", "useThemeContext", "InputModeExtensions", "autocomplete", "createBasicExtensions", "createThemeExtensions", "folding", "useTextEditor", "mx", "isNonNullable", "TypescriptEditor", "classNames", "id", "inputMode", "toolbar", "env", "initialValue", "extensions", "scrollTo", "selection", "themeMode", "useThemeContext", "parentRef", "focusAttributes", "useTextEditor", "createBasicExtensions", "highlightActiveLine", "indentWithTab", "lineNumbers", "lineWrapping", "monospace", "scrollPastEnd", "createThemeExtensions", "syntaxHighlighting", "InputModeExtensions", "folding", "Prec", "high", "keymap", "of", "continueKeymap", "javascript", "typescript", "autocomplete", "override", "tsAutocomplete", "undefined", "lintKeymap", "tsFacet", "path", "tsSync", "tsLinter", "tsHover", "renderTooltip", "createTooltipRenderer", "filter", "isNonNullable", "React", "div", "ref", "data-toolbar", "className", "mx", "theme", "oneDarkHighlightStyle", "defaultHighlightStyle", "classFromKind", "_kind", "kind", "endsWith", "validTag", "tags", "tag", "style", "info", "document", "createElement", "quickInfo", "displayParts", "part", "span", "appendChild", "innerText", "text", "dom", "ScriptContainer", "role", "script", "settings", "editorInputMode", "env", "identity", "useIdentity", "space", "getSpace", "state", "useToolbarState", "useDeployState", "extensions", "useMemo", "source", "target", "listener", "onChange", "text", "content", "changed", "createDataExtensions", "id", "createDocAccessor", "React", "StackItem", "Content", "toolbar", "ScriptToolbar", "TypescriptEditor", "initialValue", "classNames", "stackItemContentEditorClassNames", "inputMode"]
7
+ }
@@ -176,7 +176,7 @@ var forex_effect_default = "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\
176
176
  var forex_default = "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { defineFunction, S } from 'dxos:functions';\n\nexport default defineFunction({\n description: 'Returns the exchange rate between two currencies.',\n\n inputSchema: S.Struct({\n from: S.String.annotations({ description: 'The source currency' }),\n to: S.String.annotations({ description: 'The target currency' }),\n }),\n\n handler: async ({ data: { from, to } }: 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";
177
177
 
178
178
  // raw-loader:./gmail.ts?raw
179
- var gmail_default = "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { create, defineFunction, EchoObject, Filter, ObjectId, S } from 'dxos:functions';\n// @ts-ignore\nimport {\n HttpClient,\n HttpClientRequest,\n FetchHttpClient,\n // @ts-ignore\n} from 'https://esm.sh/@effect/platform@0.77.2?deps=effect@3.14.21&bundle=false';\n// @ts-ignore\nimport { format, subDays } from 'https://esm.sh/date-fns@3.3.1?bundle=false';\n// @ts-ignore\nimport { pipe, Chunk, Effect, Ref, Schedule, Stream } from 'https://esm.sh/effect@3.14.21?bundle=false';\n\nexport default defineFunction({\n inputSchema: S.Struct({\n mailboxId: S.String,\n userId: S.optional(S.String).pipe(S.withDecodingDefault(() => 'me')),\n after: S.optional(S.Union(S.Number, S.String)).pipe(\n S.withDecodingDefault(() => format(subDays(new Date(), 30), 'yyyy-MM-dd')),\n ),\n pageSize: S.optional(S.Number).pipe(S.withDecodingDefault(() => 100)),\n // TODO(wittjosiah): Remove. This is used to provide a terminal for a cron trigger.\n tick: S.optional(S.String),\n }),\n\n outputSchema: S.Struct({\n newMessages: S.Number,\n }),\n\n handler: ({ context: { space }, data: { mailboxId, userId, after, pageSize } }: any) =>\n Effect.gen(function* () {\n const { token } = yield* Effect.tryPromise({\n try: () => space.db.query(Filter.typename('dxos.org/type/AccessToken', { source: 'gmail.com' })).first(),\n catch: (e: any) => e,\n });\n\n // NOTE: Google API bundles size is v. large and caused runtime issues.\n const makeRequest = (url: string) =>\n pipe(\n url,\n HttpClientRequest.get,\n HttpClientRequest.setHeaders({ Authorization: `Bearer ${token}`, Accept: 'application/json' }),\n HttpClient.execute,\n Effect.flatMap((res: any) => res.json),\n Effect.timeout('1 second'),\n Effect.retry(Schedule.exponential(1000).pipe(Schedule.compose(Schedule.recurs(3)))),\n Effect.scoped,\n );\n\n const listMessages = (userId: string, q: string, pageSize: number, pageToken: string | null) =>\n makeRequest(getUrl(userId, undefined, { q, pageSize, pageToken }));\n\n const getMessage = (userId: string, messageId: string) => makeRequest(getUrl(userId, messageId));\n\n const mailbox = yield* Effect.tryPromise({\n try: () => space.db.query({ id: mailboxId }).first(),\n catch: (e: any) => e,\n });\n const { objects } = yield* Effect.tryPromise({\n try: () => space.queues.queryQueue(mailbox.queue.dxn),\n catch: (e: any) => e,\n });\n const newMessages = yield* Ref.make([]);\n const nextPage = yield* Ref.make(null);\n\n do {\n const last = objects.at(-1);\n const q = last\n ? `in:inbox after:${Math.floor(new Date(last.created).getTime() / 1000)}`\n : `in:inbox after:${after}`;\n const pageToken = yield* Ref.get(nextPage);\n const { messages, nextPageToken } = yield* listMessages(userId, q, pageSize, pageToken);\n yield* Ref.update(nextPage, () => nextPageToken);\n for (const message of messages) {\n const messageDetails = yield* getMessage(userId, message.id);\n const created = new Date(parseInt(messageDetails.internalDate)).toISOString();\n const from = messageDetails.payload.headers.find((h: any) => h.name === 'From');\n const sender = from && parseEmailString(from.value);\n // TODO(wittjosiah): Improve parsing of email contents.\n const content =\n messageDetails.payload.body?.data ??\n messageDetails.payload.parts?.find((p: any) => p.mimeType === 'text/plain')?.body.data;\n // Skip the message if content or sender is missing.\n // Skip the message if it's the same as the last message.\n // TODO(wittjosiah): This comparison should be done via foreignId probably.\n if (!content || !sender || created === last?.created) {\n continue;\n }\n const subject = messageDetails.payload.headers.find((h: any) => h.name === 'Subject')?.value;\n const object = create(MessageType, {\n id: ObjectId.random(),\n created,\n sender,\n blocks: [\n {\n type: 'text',\n text: Buffer.from(content, 'base64').toString('utf-8'),\n },\n ],\n properties: {\n subject,\n threadId: message.threadId,\n },\n });\n // TODO(wittjosiah): Set foreignId in object meta.\n yield* Ref.update(newMessages, (n: any) => [object, ...n]);\n }\n } while (yield* Ref.get(nextPage));\n\n const queueMessages = yield* Ref.get(newMessages);\n if (queueMessages.length > 0) {\n yield* pipe(\n queueMessages,\n Stream.fromIterable,\n Stream.grouped(10),\n Stream.flatMap((batch: any) =>\n Effect.tryPromise({\n try: () => space.queues.insertIntoQueue(mailbox.queue.dxn, Chunk.toReadonlyArray(batch)),\n catch: (e: any) => e,\n }),\n ),\n Stream.runDrain,\n );\n }\n\n return { newMessages: queueMessages.length };\n }).pipe(Effect.provide(FetchHttpClient.layer)),\n});\n\nconst getUrl = (userId: string, messageId?: string, params?: Record<string, any>) => {\n const api = new URL(\n [`https://gmail.googleapis.com/gmail/v1/users/${userId}/messages`, messageId].filter(Boolean).join('/'),\n );\n Object.entries(params ?? {})\n .filter(([_, value]) => value != null)\n .forEach(([key, value]) => api.searchParams.set(key, value));\n return api.toString();\n};\n\n/**\n * Parses an email string in the format \"Name <email@example.com>\" into separate name and email components.\n */\nconst parseEmailString = (emailString: string): { name?: string; email: string } | undefined => {\n const match = emailString.match(/^([^<]+?)\\s*<([^>]+@[^>]+)>$/);\n if (match) {\n const [, name, email] = match;\n return {\n name: name.trim(),\n email: email.trim(),\n };\n }\n\n return undefined;\n};\n\n//\n// Schemas\n// TODO(wittjosiah): These schemas should be imported from @dxos/S.\n//\n\nconst ActorRoles = ['user', 'assistant'] as const;\nconst ActorRole = S.Literal(...ActorRoles);\ntype ActorRole = S.Schema.Type<typeof ActorRole>;\n\nconst ActorSchema = S.Struct({\n identityKey: S.optional(S.String),\n email: S.optional(S.String),\n name: S.optional(S.String),\n role: S.optional(ActorRole),\n});\n\nconst AbstractContentBlock = S.Struct({\n pending: S.optional(S.Boolean),\n});\ntype AbstractContentBlock = S.Schema.Type<typeof AbstractContentBlock>;\nconst TextContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('text'),\n disposition: S.optional(S.String),\n text: S.String,\n }),\n).pipe(S.mutable);\ntype TextContentBlock = S.Schema.Type<typeof TextContentBlock>;\nconst JsonContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('json'),\n disposition: S.optional(S.String),\n data: S.String,\n }),\n).pipe(S.mutable);\ntype JsonContentBlock = S.Schema.Type<typeof JsonContentBlock>;\nconst Base64ImageSource = S.Struct({\n type: S.Literal('base64'),\n mediaType: S.String,\n data: S.String,\n}).pipe(S.mutable);\nconst HttpImageSource = S.Struct({\n type: S.Literal('http'),\n url: S.String,\n}).pipe(S.mutable);\nconst ImageSource = S.Union(Base64ImageSource, HttpImageSource);\ntype ImageSource = S.Schema.Type<typeof ImageSource>;\nconst ImageContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('image'),\n id: S.optional(S.String),\n source: S.optional(ImageSource),\n }),\n).pipe(S.mutable);\ntype ImageContentBlock = S.Schema.Type<typeof ImageContentBlock>;\nconst ReferenceContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('reference'),\n reference: S.Any,\n }),\n).pipe(S.mutable);\ntype ReferenceContentBlock = S.Schema.Type<typeof ReferenceContentBlock>;\nconst MessageContentBlock = S.Union(TextContentBlock, JsonContentBlock, ImageContentBlock, ReferenceContentBlock);\n\nconst MessageType = S.Struct({\n id: ObjectId,\n created: S.String.annotations({\n description: 'ISO date string when the message was sent.',\n }),\n sender: ActorSchema.annotations({\n description: 'Identity of the message sender.',\n }),\n blocks: S.Array(MessageContentBlock).annotations({\n description: 'Contents of the message.',\n }),\n properties: S.optional(\n S.mutable(\n S.Record({ key: S.String, value: S.Any }).annotations({\n description: 'Custom properties for specific message types (e.g. attention context, email subject, etc.).',\n }),\n ),\n ),\n}).pipe(\n EchoObject({\n typename: 'dxos.org/type/Message',\n version: '0.1.0',\n }),\n);\ntype MessageType = S.Schema.Type<typeof MessageType>;\n";
179
+ var gmail_default = "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { create, defineFunction, EchoObject, Filter, ObjectId, S } from 'dxos:functions';\n// @ts-ignore\nimport {\n HttpClient,\n HttpClientRequest,\n FetchHttpClient,\n // @ts-ignore\n} from 'https://esm.sh/@effect/platform@0.77.2?deps=effect@3.14.21&bundle=false';\n// @ts-ignore\nimport { format, subDays } from 'https://esm.sh/date-fns@3.3.1?bundle=false';\n// @ts-ignore\nimport { pipe, Chunk, Effect, Ref, Schedule, Stream } from 'https://esm.sh/effect@3.14.21?bundle=false';\n\nexport default defineFunction({\n inputSchema: S.Struct({\n mailboxId: S.String,\n userId: S.optional(S.String).pipe(S.withDecodingDefault(() => 'me')),\n after: S.optional(S.Union(S.Number, S.String)).pipe(\n S.withDecodingDefault(() => format(subDays(new Date(), 30), 'yyyy-MM-dd')),\n ),\n pageSize: S.optional(S.Number).pipe(S.withDecodingDefault(() => 100)),\n // TODO(wittjosiah): Remove. This is used to provide a terminal for a cron trigger.\n tick: S.optional(S.String),\n }),\n\n outputSchema: S.Struct({\n newMessages: S.Number,\n }),\n\n handler: ({ context: { space }, data: { mailboxId, userId, after, pageSize } }: any) =>\n Effect.gen(function* () {\n const { token } = yield* Effect.tryPromise({\n try: () => space.db.query(Filter.typename('dxos.org/type/AccessToken', { source: 'gmail.com' })).first(),\n catch: (e: any) => e,\n });\n\n // NOTE: Google API bundles size is v. large and caused runtime issues.\n const makeRequest = (url: string) =>\n pipe(\n url,\n HttpClientRequest.get,\n HttpClientRequest.setHeaders({ Authorization: `Bearer ${token}`, Accept: 'application/json' }),\n HttpClient.execute,\n Effect.flatMap((res: any) => res.json),\n Effect.timeout('1 second'),\n Effect.retry(Schedule.exponential(1000).pipe(Schedule.compose(Schedule.recurs(3)))),\n Effect.scoped,\n );\n\n const listMessages = (userId: string, q: string, pageSize: number, pageToken: string | null) =>\n makeRequest(getUrl(userId, undefined, { q, pageSize, pageToken }));\n\n const getMessage = (userId: string, messageId: string) => makeRequest(getUrl(userId, messageId));\n\n const mailbox = yield* Effect.tryPromise({\n try: () => space.db.query({ id: mailboxId }).first(),\n catch: (e: any) => e,\n });\n const { objects } = yield* Effect.tryPromise({\n try: () => space.queues.queryQueue(mailbox.queue.dxn),\n catch: (e: any) => e,\n });\n const newMessages = yield* Ref.make([]);\n const nextPage = yield* Ref.make(null);\n\n do {\n const last = objects.at(-1);\n const q = last\n ? `in:inbox after:${Math.floor(new Date(last.created).getTime() / 1000)}`\n : `in:inbox after:${after}`;\n const pageToken = yield* Ref.get(nextPage);\n const { messages, nextPageToken } = yield* listMessages(userId, q, pageSize, pageToken);\n yield* Ref.update(nextPage, () => nextPageToken);\n for (const message of messages) {\n const messageDetails = yield* getMessage(userId, message.id);\n const created = new Date(parseInt(messageDetails.internalDate)).toISOString();\n const from = messageDetails.payload.headers.find((h: any) => h.name === 'From');\n const sender = from && parseEmailString(from.value);\n // TODO(wittjosiah): Improve parsing of email contents.\n const content =\n messageDetails.payload.body?.data ??\n messageDetails.payload.parts?.find((p: any) => p.mimeType === 'text/plain')?.body.data;\n // Skip the message if content or sender is missing.\n // Skip the message if it's the same as the last message.\n // TODO(wittjosiah): This comparison should be done via foreignId probably.\n if (!content || !sender || created === last?.created) {\n continue;\n }\n const subject = messageDetails.payload.headers.find((h: any) => h.name === 'Subject')?.value;\n const object = create(MessageType, {\n id: ObjectId.random(),\n created,\n sender,\n blocks: [\n {\n type: 'text',\n text: Buffer.from(content, 'base64').toString('utf-8'),\n },\n ],\n properties: {\n subject,\n threadId: message.threadId,\n },\n });\n // TODO(wittjosiah): Set foreignId in object meta.\n yield* Ref.update(newMessages, (n: any) => [object, ...n]);\n }\n } while (yield* Ref.get(nextPage));\n\n const queueMessages = yield* Ref.get(newMessages);\n if (queueMessages.length > 0) {\n yield* pipe(\n queueMessages,\n Stream.fromIterable,\n Stream.grouped(10),\n Stream.flatMap((batch: any) =>\n Effect.tryPromise({\n try: () => space.queues.insertIntoQueue(mailbox.queue.dxn, Chunk.toReadonlyArray(batch)),\n catch: (e: any) => e,\n }),\n ),\n Stream.runDrain,\n );\n }\n\n return { newMessages: queueMessages.length };\n }).pipe(Effect.provide(FetchHttpClient.layer)),\n});\n\nconst getUrl = (userId: string, messageId?: string, params?: Record<string, any>) => {\n const api = new URL(\n [`https://gmail.googleapis.com/gmail/v1/users/${userId}/messages`, messageId].filter(Boolean).join('/'),\n );\n Object.entries(params ?? {})\n .filter(([_, value]) => value != null)\n .forEach(([key, value]) => api.searchParams.set(key, value));\n return api.toString();\n};\n\n/**\n * Parses an email string in the format \"Name <email@example.com>\" into separate name and email components.\n */\nconst parseEmailString = (emailString: string): { name?: string; email: string } | undefined => {\n const match = emailString.match(/^([^<]+?)\\s*<([^>]+@[^>]+)>$/);\n if (match) {\n const [, name, email] = match;\n return {\n name: name.trim(),\n email: email.trim(),\n };\n }\n\n return undefined;\n};\n\n//\n// Schemas\n// TODO(wittjosiah): These schemas should be imported from @dxos/S.\n//\n\nconst ActorRoles = ['user', 'assistant'] as const;\nconst ActorRole = S.Literal(...ActorRoles);\ntype ActorRole = S.Schema.Type<typeof ActorRole>;\n\nconst ActorSchema = S.Struct({\n identityKey: S.optional(S.String),\n email: S.optional(S.String),\n name: S.optional(S.String),\n role: S.optional(ActorRole),\n});\n\nconst AbstractContentBlock = S.Struct({\n pending: S.optional(S.Boolean),\n});\ntype AbstractContentBlock = S.Schema.Type<typeof AbstractContentBlock>;\nconst TextContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('text'),\n disposition: S.optional(S.String),\n text: S.String,\n }),\n).pipe(S.mutable);\ntype TextContentBlock = S.Schema.Type<typeof TextContentBlock>;\nconst JsonContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('json'),\n disposition: S.optional(S.String),\n data: S.String,\n }),\n).pipe(S.mutable);\ntype JsonContentBlock = S.Schema.Type<typeof JsonContentBlock>;\nconst Base64ImageSource = S.Struct({\n type: S.Literal('base64'),\n mediaType: S.String,\n data: S.String,\n}).pipe(S.mutable);\nconst HttpImageSource = S.Struct({\n type: S.Literal('http'),\n url: S.String,\n}).pipe(S.mutable);\nconst ImageSource = S.Union(Base64ImageSource, HttpImageSource);\ntype ImageSource = S.Schema.Type<typeof ImageSource>;\nconst ImageContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('image'),\n id: S.optional(S.String),\n source: S.optional(ImageSource),\n }),\n).pipe(S.mutable);\ntype ImageContentBlock = S.Schema.Type<typeof ImageContentBlock>;\nconst ReferenceContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('reference'),\n reference: S.Any,\n }),\n).pipe(S.mutable);\ntype ReferenceContentBlock = S.Schema.Type<typeof ReferenceContentBlock>;\nconst MessageContentBlock = S.Union(TextContentBlock, JsonContentBlock, ImageContentBlock, ReferenceContentBlock);\n\nconst MessageType = S.Struct({\n id: ObjectId,\n created: S.String.annotations({\n description: 'ISO date string when the message was sent.',\n }),\n sender: ActorSchema.annotations({\n description: 'Identity of the message sender.',\n }),\n blocks: S.Array(MessageContentBlock).annotations({\n description: 'Contents of the message.',\n }),\n properties: S.optional(\n S.mutable(\n S.Record({ key: S.String, value: S.Any }).annotations({\n description: 'Custom properties for specific message types (e.g. attention context, email subject, etc.).',\n }),\n ),\n ),\n}).pipe(\n EchoObject({\n typename: 'dxos.org/type/Message',\n version: '0.2.0',\n }),\n);\ntype MessageType = S.Schema.Type<typeof MessageType>;\n";
180
180
 
181
181
  // packages/plugins/plugin-script/src/templates/index.ts
182
182
  var removeHeader = (str) => str.split("\n").slice(4).join("\n");
@@ -361,4 +361,4 @@ export {
361
361
  createTemplateSelect,
362
362
  useToolbarState
363
363
  };
364
- //# sourceMappingURL=chunk-I6S7QLGR.mjs.map
364
+ //# sourceMappingURL=chunk-3FU4QZVP.mjs.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/hooks/deploy.ts", "raw-loader:./chat.ts?raw", "raw-loader:./chess.ts?raw", "raw-loader:./data-generator.ts?raw", "raw-loader:./discord.ts?raw", "raw-loader:./echo.ts?raw", "raw-loader:./email.ts?raw", "raw-loader:./forex-effect.ts?raw", "raw-loader:./forex.ts?raw", "raw-loader:./gmail.ts?raw", "../../../src/templates/index.ts", "../../../src/hooks/useToolbarState.ts", "../../../src/hooks/format.ts", "../../../src/hooks/template.ts"],
4
- "sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport { useEffect, useMemo } from 'react';\n\nimport { FunctionType, type ScriptType, getUserFunctionUrlInMetadata } from '@dxos/functions';\nimport { log } from '@dxos/log';\nimport { type Client, useClient } from '@dxos/react-client';\nimport { getMeta, getSpace, Query, Ref, type Space, useQuery } from '@dxos/react-client/echo';\nimport { type TFunction } from '@dxos/react-ui';\nimport { createMenuAction } from '@dxos/react-ui-menu';\nimport { errorMessageColors } from '@dxos/react-ui-theme';\n\nimport { SCRIPT_PLUGIN } from '../meta';\nimport { deployScript, getFunctionUrl, isScriptDeployed } from '../util';\n\nexport type DeployActionProperties = { type: 'deploy' } | { type: 'copy' };\n\nexport type DeployState = {\n deploying: boolean;\n deployed: boolean;\n functionUrl: string;\n error: string;\n};\n\nexport type CreateDeployOptions = {\n state: Partial<DeployState>;\n script: ScriptType;\n fn: FunctionType;\n space?: Space;\n existingFunctionUrl?: string;\n client: Client;\n t: TFunction;\n};\n\nexport const createDeploy = ({ state, script, space, fn, client, existingFunctionUrl, t }: CreateDeployOptions) => {\n // TODO(wittjosiah): Should this be an action?\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 classNames: state.error && errorMessageColors,\n });\n\n const deployAction = createMenuAction<DeployActionProperties>(\n 'deploy',\n async () => {\n if (!script.source || !space) {\n return;\n }\n\n state.error = undefined;\n state.deploying = true;\n\n const result = await deployScript({ script, client, space, fn, existingFunctionUrl });\n\n if (!result.success) {\n log.catch(result.error);\n state.error = t('upload failed label');\n }\n\n state.deploying = false;\n },\n {\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\n const copyAction = createMenuAction<DeployActionProperties>(\n 'copy',\n async () => {\n if (!state.functionUrl) {\n return;\n }\n await navigator.clipboard.writeText(state.functionUrl);\n },\n {\n type: 'copy',\n label: ['copy link label', { ns: SCRIPT_PLUGIN }],\n icon: 'ph--link--regular',\n disabled: !state.functionUrl,\n },\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\nexport const useDeployState = ({ state, script }: { state: Partial<DeployState>; script: ScriptType }) => {\n const { space, client, fn, existingFunctionUrl } = useDeployDeps({ script });\n useEffect(() => {\n if (!existingFunctionUrl) {\n return;\n }\n\n state.functionUrl = getFunctionUrl({\n script,\n fn,\n edgeUrl: client.config.values.runtime?.services?.edge?.url ?? '',\n });\n }, [existingFunctionUrl, space, fn, script, client.config.values.runtime?.services?.edge?.url]);\n\n useEffect(() => {\n state.deployed = isScriptDeployed({ script, fn });\n }, [script.changed, existingFunctionUrl, fn, script]);\n};\n\nexport const useDeployDeps = ({ script }: { script: ScriptType }) => {\n const space = getSpace(script);\n const [fn] = useQuery(space, Query.type(FunctionType, { source: Ref.make(script) }));\n const client = useClient();\n const existingFunctionUrl = useMemo(() => fn && getUserFunctionUrlInMetadata(getMeta(fn)), [fn]);\n return { space, fn, client, existingFunctionUrl };\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\n// @ts-ignore\nimport { transformServerSentEvents } from 'https://esm.sh/@dxos/script-toolbox?bundle=false';\n\n/**\n * Chatbot that answers questions based on the context data.\n */\nexport default async ({ data: { bodyText }, context: { space, ai } }: any) => {\n let parsedRequest: any;\n try {\n parsedRequest = JSON.parse(bodyText);\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 ${bodyText}\n `,\n });\n return new Response(transformServerSentEvents(answer));\n }\n\n const promptId = parsedRequest.trigger.promptId;\n const promptObject = await space.crud.query({ id: promptId }).first();\n\n if (parsedRequest.data.objects.length !== 1) {\n return new Response('Message batches not supported.');\n }\n\n const messageId = parsedRequest.data.objects[0];\n let message;\n try {\n message = await space.crud.query({ id: messageId }).first();\n } catch (err) {\n return new Response('Message not replicated yet.', { status: 409 });\n }\n\n if (message.text.includes('--------')) {\n return new Response('Message was already processed.');\n }\n\n let prompt = promptObject.template;\n for (const input of promptObject.inputs) {\n let value: string | null = null;\n if (input.type === TemplateInputType.VALUE) {\n value = String(input.value);\n } else if (input.type === TemplateInputType.RETRIEVER) {\n value = await getContext({ space });\n } else if (input.type === TemplateInputType.PASS_THROUGH) {\n value = message.text;\n }\n if (value) {\n prompt = prompt.replaceAll(`{${input.name}}`, value);\n }\n }\n\n const answer = await ai.run('@cf/meta/llama-3.1-8b-instruct', {\n stream: false,\n prompt,\n });\n const response = { response: answer.response, prompt, message };\n const textWithAnswer = message.text + '\\n--------\\n\\n' + answer.response;\n await space.crud.update({ id: messageId }, { text: textWithAnswer });\n\n return new Response(JSON.stringify(response));\n};\n\nconst getContext = async ({ space }: any) => {\n let context = '';\n const { objects: docs } = await space.crud.query({ __typename: 'dxos.org/type/Document' }).run();\n for (const doc of docs) {\n const { content } = await space.crud.query({ id: doc.content }).first();\n context += content + '\\n\\n';\n }\n return context;\n};\n\nenum TemplateInputType {\n VALUE = 0,\n PASS_THROUGH = 1,\n RETRIEVER = 2,\n FUNCTION = 3,\n QUERY = 4,\n RESOLVER = 5,\n CONTEXT = 6,\n SCHEMA = 7,\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { defineFunction, S } from 'dxos:functions';\n// @ts-ignore\nimport { Chess } from 'https://esm.sh/chess.js@0.13.1?bundle=false';\n\nexport default defineFunction({\n description: 'Plays a random move in a chess game.',\n\n inputSchema: S.Struct({\n changedObjectId: S.String.annotations({\n description: 'The objects to play the game on.',\n }),\n player: S.optional(S.Literal('w', 'b')).annotations({\n description: 'The player to play the game as.',\n }),\n }),\n\n outputSchema: S.Struct({\n state: S.String.annotations({\n description: 'The state of the game as an ASCII art board.',\n }),\n }),\n\n handler: async ({ data: { changedObjectId, player = 'b' }, context: { space } }: any) => {\n const { pgn } = await space.db.query({ id: changedObjectId }).first();\n const game = new Chess();\n game.load_pgn(pgn);\n if (game.turn() !== player) {\n return new Response('Invalid turn', { status: 409 });\n }\n\n const moves = game.moves();\n const move = moves[Math.floor(Math.random() * moves.length)];\n if (!move) {\n return new Response('No legal moves', { status: 406 });\n }\n\n game.move(move);\n const newPgn = game.pgn();\n await space.db.update({ id: changedObjectId }, { pgn: newPgn, fen: game.fen() });\n return { state: game.ascii() };\n },\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { defineFunction, S, create, Expando } from 'dxos:functions';\n// @ts-ignore\nimport { randText } from 'https://esm.sh/@ngneat/falso@7.1.1?bundle=false';\n\nexport default defineFunction({\n inputSchema: S.Struct({\n documentAmount: S.optional(S.Number),\n textSize: S.optional(S.Number),\n mutationAmount: S.optional(S.Number),\n }),\n\n outputSchema: S.Struct({}),\n\n handler: async ({ data: { documentAmount = 1, textSize = 10, mutationAmount = 0 }, context: { space } }: any) => {\n await space.db.graph.schemaRegistry.addSchema([Expando]);\n const result: Record<string, any> = {};\n const objects: Expando[] = [];\n\n // Create objects.\n for (let i = 0; i < documentAmount; i++) {\n const obj = space.db.add(\n create(Expando, {\n name: 'scriptGenerated',\n content: randText({ charCount: textSize }),\n }),\n );\n objects.push(obj);\n const objectResult: any = {};\n // Mutate the object.\n for (let i = 0; i < mutationAmount; i++) {\n obj.content = randText({ charCount: textSize });\n }\n objectResult.mutations = mutationAmount;\n objectResult.contentLength = obj.content.length;\n result[obj.id] = objectResult;\n }\n\n // Flush and wait for data to propagate.\n await space.db.flush();\n await new Promise((resolve) => setTimeout(resolve, 10_000));\n return result;\n },\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { create, defineFunction, DXN, EchoObject, Filter, ObjectId, S } from 'dxos:functions';\n// @ts-ignore\nimport { FetchHttpClient } from 'https://esm.sh/@effect/platform@0.77.2?deps=effect@3.14.21&bundle=false';\nimport {\n DiscordConfig,\n DiscordREST,\n DiscordRESTMemoryLive,\n // @ts-ignore\n} from 'https://esm.sh/dfx@0.113.0?deps=effect@3.14.21&bundle=false';\n// @ts-ignore\nimport { Effect, Config, Redacted, Ref } from 'https://esm.sh/effect@3.14.21?bundle=false';\n\nconst MessageSchema = S.Struct({\n id: ObjectId,\n foreignId: S.Any, // bigint?\n from: S.String,\n created: S.String,\n content: S.String,\n}).pipe(\n EchoObject({\n typename: 'example.com/type/Message',\n version: '0.1.0',\n }),\n);\n\nconst DEFAULT_AFTER = 1704067200; // 2024-01-01\n\nconst generateSnowflake = (unixTimestamp: number): bigint => {\n const discordEpoch = 1420070400000n; // Discord Epoch (ms)\n return (BigInt(unixTimestamp * 1000) - discordEpoch) << 22n;\n};\n\nexport default defineFunction({\n inputSchema: S.Struct({\n // TODO(wittjosiah): Remove. This is used to provide a terminal for a cron trigger.\n tick: S.optional(S.String),\n channelId: S.String,\n after: S.optional(S.Number),\n pageSize: S.optional(S.Number),\n queueId: S.String,\n }),\n\n outputSchema: S.Struct({\n newMessages: S.Number,\n }),\n\n handler: ({ data: { channelId, queueId, after = DEFAULT_AFTER, pageSize = 5 }, context: { space } }: any) =>\n Effect.gen(function* () {\n const { token } = yield* Effect.tryPromise({\n try: () => space.db.query(Filter.typename('dxos.org/type/AccessToken', { source: 'discord.com' })).first(),\n catch: (e: any) => e,\n });\n const { objects } = yield* Effect.tryPromise({\n try: () => space.queues.queryQueue(DXN.parse(queueId)),\n catch: (e: any) => e,\n });\n const backfill = objects.length === 0;\n const newMessages = yield* Ref.make(0);\n const lastMessage = yield* Ref.make(objects.at(-1));\n\n const enqueueMessages = Effect.gen(function* () {\n const rest = yield* DiscordREST;\n\n while (true) {\n const last = yield* Ref.get(lastMessage);\n const options = {\n after: backfill && !last ? `${generateSnowflake(after)}` : last?.foreignId,\n limit: pageSize,\n };\n const messages = yield* rest.getChannelMessages(channelId, options).pipe((res: any) => res.json);\n const queueMessages = messages\n .map((message: any) =>\n create(MessageSchema, {\n id: ObjectId.random(),\n foreignId: message.id,\n from: message.author.username,\n created: message.timestamp,\n content: message.content,\n }),\n )\n .toReversed();\n if (queueMessages.length > 0) {\n yield* Effect.tryPromise({\n try: () => space.queues.insertIntoQueue(DXN.parse(queueId), queueMessages),\n catch: (e: any) => e,\n });\n yield* Ref.update(newMessages, (n: any) => n + queueMessages.length);\n yield* Ref.update(lastMessage, (m: any) => queueMessages.at(-1));\n }\n if (messages.length < pageSize) {\n break;\n }\n }\n }).pipe(\n Effect.provide(DiscordRESTMemoryLive),\n Effect.provide(\n DiscordConfig.layerConfig({\n token: Config.succeed(Redacted.make(token)),\n }),\n ),\n Effect.provide(FetchHttpClient.layer),\n );\n\n yield* enqueueMessages;\n return { newMessages: yield* Ref.get(newMessages) };\n }),\n});\n", "//\n// Copyright 2024 DXOS.org\n//\n\n/**\n * Echos the request data.\n */\nexport default async ({ data }: any) => data;\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 ({ data: { bodyText }, context: { space } }: any) => {\n const { email, targetDocumentId: documentId } = JSON.parse(bodyText) as RequestPayload;\n\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:** ${email.from}`,\n `**Subject:** ${email.subject}`,\n `**Date:** ${email.created}`,\n '',\n email.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 email: { from: string; subject: string; created: string; body: string };\n targetDocumentId: string;\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { S, defineFunction } from 'dxos:functions';\nimport {\n HttpClient,\n HttpClientRequest,\n FetchHttpClient,\n // @ts-ignore\n} from 'https://esm.sh/@effect/platform@0.77.2?deps=effect@3.14.21&bundle=false';\n// @ts-ignore\nimport { Effect, Schedule } from 'https://esm.sh/effect@3.14.21?bundle=false';\n\nexport default defineFunction({\n description: 'Returns the exchange rate between two currencies.',\n\n inputSchema: S.Struct({\n from: S.String.annotations({ description: 'The source currency' }),\n to: S.String.annotations({ description: 'The target currency' }),\n }),\n\n outputSchema: S.String.annotations({ description: 'The exchange rate between the two currencies' }),\n\n handler: async ({ data: { from, to } }: any) =>\n Effect.gen(function* () {\n const res = yield* HttpClientRequest.get(`https://free.ratesdb.com/v1/rates?from=${from}&to=${to}`).pipe(\n HttpClient.execute,\n Effect.flatMap((res: any) => res.json),\n Effect.timeout('1 second'),\n Effect.retry(Schedule.exponential(1_000).pipe(Schedule.compose(Schedule.recurs(3)))),\n Effect.scoped,\n );\n\n return res.data.rates[to].toString();\n }).pipe(Effect.provide(FetchHttpClient.layer)),\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { defineFunction, S } from 'dxos:functions';\n\nexport default defineFunction({\n description: 'Returns the exchange rate between two currencies.',\n\n inputSchema: S.Struct({\n from: S.String.annotations({ description: 'The source currency' }),\n to: S.String.annotations({ description: 'The target currency' }),\n }),\n\n handler: async ({ data: { from, to } }: any) => {\n const res = await fetch(`https://free.ratesdb.com/v1/rates?from=${from}&to=${to}`);\n const {\n data: { rates },\n } = await res.json();\n\n return rates[to].toString();\n },\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { create, defineFunction, EchoObject, Filter, ObjectId, S } from 'dxos:functions';\n// @ts-ignore\nimport {\n HttpClient,\n HttpClientRequest,\n FetchHttpClient,\n // @ts-ignore\n} from 'https://esm.sh/@effect/platform@0.77.2?deps=effect@3.14.21&bundle=false';\n// @ts-ignore\nimport { format, subDays } from 'https://esm.sh/date-fns@3.3.1?bundle=false';\n// @ts-ignore\nimport { pipe, Chunk, Effect, Ref, Schedule, Stream } from 'https://esm.sh/effect@3.14.21?bundle=false';\n\nexport default defineFunction({\n inputSchema: S.Struct({\n mailboxId: S.String,\n userId: S.optional(S.String).pipe(S.withDecodingDefault(() => 'me')),\n after: S.optional(S.Union(S.Number, S.String)).pipe(\n S.withDecodingDefault(() => format(subDays(new Date(), 30), 'yyyy-MM-dd')),\n ),\n pageSize: S.optional(S.Number).pipe(S.withDecodingDefault(() => 100)),\n // TODO(wittjosiah): Remove. This is used to provide a terminal for a cron trigger.\n tick: S.optional(S.String),\n }),\n\n outputSchema: S.Struct({\n newMessages: S.Number,\n }),\n\n handler: ({ context: { space }, data: { mailboxId, userId, after, pageSize } }: any) =>\n Effect.gen(function* () {\n const { token } = yield* Effect.tryPromise({\n try: () => space.db.query(Filter.typename('dxos.org/type/AccessToken', { source: 'gmail.com' })).first(),\n catch: (e: any) => e,\n });\n\n // NOTE: Google API bundles size is v. large and caused runtime issues.\n const makeRequest = (url: string) =>\n pipe(\n url,\n HttpClientRequest.get,\n HttpClientRequest.setHeaders({ Authorization: `Bearer ${token}`, Accept: 'application/json' }),\n HttpClient.execute,\n Effect.flatMap((res: any) => res.json),\n Effect.timeout('1 second'),\n Effect.retry(Schedule.exponential(1000).pipe(Schedule.compose(Schedule.recurs(3)))),\n Effect.scoped,\n );\n\n const listMessages = (userId: string, q: string, pageSize: number, pageToken: string | null) =>\n makeRequest(getUrl(userId, undefined, { q, pageSize, pageToken }));\n\n const getMessage = (userId: string, messageId: string) => makeRequest(getUrl(userId, messageId));\n\n const mailbox = yield* Effect.tryPromise({\n try: () => space.db.query({ id: mailboxId }).first(),\n catch: (e: any) => e,\n });\n const { objects } = yield* Effect.tryPromise({\n try: () => space.queues.queryQueue(mailbox.queue.dxn),\n catch: (e: any) => e,\n });\n const newMessages = yield* Ref.make([]);\n const nextPage = yield* Ref.make(null);\n\n do {\n const last = objects.at(-1);\n const q = last\n ? `in:inbox after:${Math.floor(new Date(last.created).getTime() / 1000)}`\n : `in:inbox after:${after}`;\n const pageToken = yield* Ref.get(nextPage);\n const { messages, nextPageToken } = yield* listMessages(userId, q, pageSize, pageToken);\n yield* Ref.update(nextPage, () => nextPageToken);\n for (const message of messages) {\n const messageDetails = yield* getMessage(userId, message.id);\n const created = new Date(parseInt(messageDetails.internalDate)).toISOString();\n const from = messageDetails.payload.headers.find((h: any) => h.name === 'From');\n const sender = from && parseEmailString(from.value);\n // TODO(wittjosiah): Improve parsing of email contents.\n const content =\n messageDetails.payload.body?.data ??\n messageDetails.payload.parts?.find((p: any) => p.mimeType === 'text/plain')?.body.data;\n // Skip the message if content or sender is missing.\n // Skip the message if it's the same as the last message.\n // TODO(wittjosiah): This comparison should be done via foreignId probably.\n if (!content || !sender || created === last?.created) {\n continue;\n }\n const subject = messageDetails.payload.headers.find((h: any) => h.name === 'Subject')?.value;\n const object = create(MessageType, {\n id: ObjectId.random(),\n created,\n sender,\n blocks: [\n {\n type: 'text',\n text: Buffer.from(content, 'base64').toString('utf-8'),\n },\n ],\n properties: {\n subject,\n threadId: message.threadId,\n },\n });\n // TODO(wittjosiah): Set foreignId in object meta.\n yield* Ref.update(newMessages, (n: any) => [object, ...n]);\n }\n } while (yield* Ref.get(nextPage));\n\n const queueMessages = yield* Ref.get(newMessages);\n if (queueMessages.length > 0) {\n yield* pipe(\n queueMessages,\n Stream.fromIterable,\n Stream.grouped(10),\n Stream.flatMap((batch: any) =>\n Effect.tryPromise({\n try: () => space.queues.insertIntoQueue(mailbox.queue.dxn, Chunk.toReadonlyArray(batch)),\n catch: (e: any) => e,\n }),\n ),\n Stream.runDrain,\n );\n }\n\n return { newMessages: queueMessages.length };\n }).pipe(Effect.provide(FetchHttpClient.layer)),\n});\n\nconst getUrl = (userId: string, messageId?: string, params?: Record<string, any>) => {\n const api = new URL(\n [`https://gmail.googleapis.com/gmail/v1/users/${userId}/messages`, messageId].filter(Boolean).join('/'),\n );\n Object.entries(params ?? {})\n .filter(([_, value]) => value != null)\n .forEach(([key, value]) => api.searchParams.set(key, value));\n return api.toString();\n};\n\n/**\n * Parses an email string in the format \"Name <email@example.com>\" into separate name and email components.\n */\nconst parseEmailString = (emailString: string): { name?: string; email: string } | undefined => {\n const match = emailString.match(/^([^<]+?)\\s*<([^>]+@[^>]+)>$/);\n if (match) {\n const [, name, email] = match;\n return {\n name: name.trim(),\n email: email.trim(),\n };\n }\n\n return undefined;\n};\n\n//\n// Schemas\n// TODO(wittjosiah): These schemas should be imported from @dxos/S.\n//\n\nconst ActorRoles = ['user', 'assistant'] as const;\nconst ActorRole = S.Literal(...ActorRoles);\ntype ActorRole = S.Schema.Type<typeof ActorRole>;\n\nconst ActorSchema = S.Struct({\n identityKey: S.optional(S.String),\n email: S.optional(S.String),\n name: S.optional(S.String),\n role: S.optional(ActorRole),\n});\n\nconst AbstractContentBlock = S.Struct({\n pending: S.optional(S.Boolean),\n});\ntype AbstractContentBlock = S.Schema.Type<typeof AbstractContentBlock>;\nconst TextContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('text'),\n disposition: S.optional(S.String),\n text: S.String,\n }),\n).pipe(S.mutable);\ntype TextContentBlock = S.Schema.Type<typeof TextContentBlock>;\nconst JsonContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('json'),\n disposition: S.optional(S.String),\n data: S.String,\n }),\n).pipe(S.mutable);\ntype JsonContentBlock = S.Schema.Type<typeof JsonContentBlock>;\nconst Base64ImageSource = S.Struct({\n type: S.Literal('base64'),\n mediaType: S.String,\n data: S.String,\n}).pipe(S.mutable);\nconst HttpImageSource = S.Struct({\n type: S.Literal('http'),\n url: S.String,\n}).pipe(S.mutable);\nconst ImageSource = S.Union(Base64ImageSource, HttpImageSource);\ntype ImageSource = S.Schema.Type<typeof ImageSource>;\nconst ImageContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('image'),\n id: S.optional(S.String),\n source: S.optional(ImageSource),\n }),\n).pipe(S.mutable);\ntype ImageContentBlock = S.Schema.Type<typeof ImageContentBlock>;\nconst ReferenceContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('reference'),\n reference: S.Any,\n }),\n).pipe(S.mutable);\ntype ReferenceContentBlock = S.Schema.Type<typeof ReferenceContentBlock>;\nconst MessageContentBlock = S.Union(TextContentBlock, JsonContentBlock, ImageContentBlock, ReferenceContentBlock);\n\nconst MessageType = S.Struct({\n id: ObjectId,\n created: S.String.annotations({\n description: 'ISO date string when the message was sent.',\n }),\n sender: ActorSchema.annotations({\n description: 'Identity of the message sender.',\n }),\n blocks: S.Array(MessageContentBlock).annotations({\n description: 'Contents of the message.',\n }),\n properties: S.optional(\n S.mutable(\n S.Record({ key: S.String, value: S.Any }).annotations({\n description: 'Custom properties for specific message types (e.g. attention context, email subject, etc.).',\n }),\n ),\n ),\n}).pipe(\n EchoObject({\n typename: 'dxos.org/type/Message',\n version: '0.1.0',\n }),\n);\ntype MessageType = S.Schema.Type<typeof MessageType>;\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport chat from './chat.ts?raw';\nimport chess from './chess.ts?raw';\nimport dataGenerator from './data-generator.ts?raw';\nimport discord from './discord.ts?raw';\nimport echo from './echo.ts?raw';\nimport email from './email.ts?raw';\nimport forexEffect from './forex-effect.ts?raw';\nimport forex from './forex.ts?raw';\nimport gmail from './gmail.ts?raw';\n\nconst removeHeader = (str: string) => str.split('\\n').slice(4).join('\\n');\n\nexport type Template = {\n id: string;\n name: string;\n source: string;\n presetId?: string;\n};\n\nexport const templates: Template[] = [\n {\n id: 'dxos.org/script/echo',\n name: 'Echo',\n source: removeHeader(echo),\n },\n {\n id: 'dxos.org/script/forex',\n name: 'Forex',\n source: removeHeader(forex),\n },\n {\n id: 'dxos.org/script/forex-effect',\n name: 'Forex (Effect)',\n source: removeHeader(forexEffect),\n },\n {\n id: 'dxos.org/script/gpt',\n name: 'Gpt',\n source: removeHeader(chat),\n presetId: 'dxos.org/function/gpt',\n },\n {\n id: 'dxos.org/script/chess',\n name: 'Chess',\n source: removeHeader(chess),\n presetId: 'dxos.org/function/chess',\n },\n {\n id: 'dxos.org/script/email',\n name: 'Email',\n source: removeHeader(email),\n presetId: 'dxos.org/function/email',\n },\n {\n id: 'dxos.org/script/discord',\n name: 'Discord',\n source: removeHeader(discord),\n presetId: 'dxos.org/function/discord',\n },\n {\n id: 'dxos.org/script/gmail',\n name: 'Gmail',\n source: removeHeader(gmail),\n presetId: 'dxos.org/function/gmail',\n },\n {\n id: 'dxos.org/script/data-generator',\n name: 'Data Generator',\n source: removeHeader(dataGenerator),\n presetId: 'dxos.org/function/data-generator',\n },\n];\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { useMemo } from 'react';\n\nimport { live } from '@dxos/live-object';\n\nimport { type DeployState } from './deploy';\n\nexport type ScriptToolbarState = Partial<DeployState>;\n\n// TODO(burdon): Replace with context provider?\nexport const useToolbarState = (initialState: ScriptToolbarState = {}) => {\n return useMemo(() => live<ScriptToolbarState>(initialState), []);\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { format } from 'prettier';\nimport prettierPluginEstree from 'prettier/plugins/estree';\nimport prettierPluginTypescript from 'prettier/plugins/typescript';\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 = (script: ScriptType) => {\n const formatAction = createMenuAction(\n 'format',\n 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 },\n {\n label: ['format label', { ns: SCRIPT_PLUGIN }],\n icon: 'ph--magic-wand--regular',\n },\n );\n\n return {\n nodes: [formatAction],\n edges: [\n {\n source: 'root',\n target: 'format',\n },\n ],\n };\n};\n", "//\n// Copyright 2025 DXOS.org\n//\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 = (script: ScriptType) => {\n return templates.map((template) => {\n return createMenuAction<TemplateActionProperties>(\n `template--${template.id}`,\n () => {\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 label: template.name,\n value: template.id,\n type: 'template',\n },\n );\n });\n};\n\nexport const createTemplateSelect = (script: ScriptType) => {\n const templateSelectGroup = createTemplateSelectGroup();\n const templateSelectActions = createTemplateSelectActions(script);\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"],
4
+ "sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport { useEffect, useMemo } from 'react';\n\nimport { FunctionType, type ScriptType, getUserFunctionUrlInMetadata } from '@dxos/functions';\nimport { log } from '@dxos/log';\nimport { type Client, useClient } from '@dxos/react-client';\nimport { getMeta, getSpace, Query, Ref, type Space, useQuery } from '@dxos/react-client/echo';\nimport { type TFunction } from '@dxos/react-ui';\nimport { createMenuAction } from '@dxos/react-ui-menu';\nimport { errorMessageColors } from '@dxos/react-ui-theme';\n\nimport { SCRIPT_PLUGIN } from '../meta';\nimport { deployScript, getFunctionUrl, isScriptDeployed } from '../util';\n\nexport type DeployActionProperties = { type: 'deploy' } | { type: 'copy' };\n\nexport type DeployState = {\n deploying: boolean;\n deployed: boolean;\n functionUrl: string;\n error: string;\n};\n\nexport type CreateDeployOptions = {\n state: Partial<DeployState>;\n script: ScriptType;\n fn: FunctionType;\n space?: Space;\n existingFunctionUrl?: string;\n client: Client;\n t: TFunction;\n};\n\nexport const createDeploy = ({ state, script, space, fn, client, existingFunctionUrl, t }: CreateDeployOptions) => {\n // TODO(wittjosiah): Should this be an action?\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 classNames: state.error && errorMessageColors,\n });\n\n const deployAction = createMenuAction<DeployActionProperties>(\n 'deploy',\n async () => {\n if (!script.source || !space) {\n return;\n }\n\n state.error = undefined;\n state.deploying = true;\n\n const result = await deployScript({ script, client, space, fn, existingFunctionUrl });\n\n if (!result.success) {\n log.catch(result.error);\n state.error = t('upload failed label');\n }\n\n state.deploying = false;\n },\n {\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\n const copyAction = createMenuAction<DeployActionProperties>(\n 'copy',\n async () => {\n if (!state.functionUrl) {\n return;\n }\n await navigator.clipboard.writeText(state.functionUrl);\n },\n {\n type: 'copy',\n label: ['copy link label', { ns: SCRIPT_PLUGIN }],\n icon: 'ph--link--regular',\n disabled: !state.functionUrl,\n },\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\nexport const useDeployState = ({ state, script }: { state: Partial<DeployState>; script: ScriptType }) => {\n const { space, client, fn, existingFunctionUrl } = useDeployDeps({ script });\n useEffect(() => {\n if (!existingFunctionUrl) {\n return;\n }\n\n state.functionUrl = getFunctionUrl({\n script,\n fn,\n edgeUrl: client.config.values.runtime?.services?.edge?.url ?? '',\n });\n }, [existingFunctionUrl, space, fn, script, client.config.values.runtime?.services?.edge?.url]);\n\n useEffect(() => {\n state.deployed = isScriptDeployed({ script, fn });\n }, [script.changed, existingFunctionUrl, fn, script]);\n};\n\nexport const useDeployDeps = ({ script }: { script: ScriptType }) => {\n const space = getSpace(script);\n const [fn] = useQuery(space, Query.type(FunctionType, { source: Ref.make(script) }));\n const client = useClient();\n const existingFunctionUrl = useMemo(() => fn && getUserFunctionUrlInMetadata(getMeta(fn)), [fn]);\n return { space, fn, client, existingFunctionUrl };\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\n// @ts-ignore\nimport { transformServerSentEvents } from 'https://esm.sh/@dxos/script-toolbox?bundle=false';\n\n/**\n * Chatbot that answers questions based on the context data.\n */\nexport default async ({ data: { bodyText }, context: { space, ai } }: any) => {\n let parsedRequest: any;\n try {\n parsedRequest = JSON.parse(bodyText);\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 ${bodyText}\n `,\n });\n return new Response(transformServerSentEvents(answer));\n }\n\n const promptId = parsedRequest.trigger.promptId;\n const promptObject = await space.crud.query({ id: promptId }).first();\n\n if (parsedRequest.data.objects.length !== 1) {\n return new Response('Message batches not supported.');\n }\n\n const messageId = parsedRequest.data.objects[0];\n let message;\n try {\n message = await space.crud.query({ id: messageId }).first();\n } catch (err) {\n return new Response('Message not replicated yet.', { status: 409 });\n }\n\n if (message.text.includes('--------')) {\n return new Response('Message was already processed.');\n }\n\n let prompt = promptObject.template;\n for (const input of promptObject.inputs) {\n let value: string | null = null;\n if (input.type === TemplateInputType.VALUE) {\n value = String(input.value);\n } else if (input.type === TemplateInputType.RETRIEVER) {\n value = await getContext({ space });\n } else if (input.type === TemplateInputType.PASS_THROUGH) {\n value = message.text;\n }\n if (value) {\n prompt = prompt.replaceAll(`{${input.name}}`, value);\n }\n }\n\n const answer = await ai.run('@cf/meta/llama-3.1-8b-instruct', {\n stream: false,\n prompt,\n });\n const response = { response: answer.response, prompt, message };\n const textWithAnswer = message.text + '\\n--------\\n\\n' + answer.response;\n await space.crud.update({ id: messageId }, { text: textWithAnswer });\n\n return new Response(JSON.stringify(response));\n};\n\nconst getContext = async ({ space }: any) => {\n let context = '';\n const { objects: docs } = await space.crud.query({ __typename: 'dxos.org/type/Document' }).run();\n for (const doc of docs) {\n const { content } = await space.crud.query({ id: doc.content }).first();\n context += content + '\\n\\n';\n }\n return context;\n};\n\nenum TemplateInputType {\n VALUE = 0,\n PASS_THROUGH = 1,\n RETRIEVER = 2,\n FUNCTION = 3,\n QUERY = 4,\n RESOLVER = 5,\n CONTEXT = 6,\n SCHEMA = 7,\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { defineFunction, S } from 'dxos:functions';\n// @ts-ignore\nimport { Chess } from 'https://esm.sh/chess.js@0.13.1?bundle=false';\n\nexport default defineFunction({\n description: 'Plays a random move in a chess game.',\n\n inputSchema: S.Struct({\n changedObjectId: S.String.annotations({\n description: 'The objects to play the game on.',\n }),\n player: S.optional(S.Literal('w', 'b')).annotations({\n description: 'The player to play the game as.',\n }),\n }),\n\n outputSchema: S.Struct({\n state: S.String.annotations({\n description: 'The state of the game as an ASCII art board.',\n }),\n }),\n\n handler: async ({ data: { changedObjectId, player = 'b' }, context: { space } }: any) => {\n const { pgn } = await space.db.query({ id: changedObjectId }).first();\n const game = new Chess();\n game.load_pgn(pgn);\n if (game.turn() !== player) {\n return new Response('Invalid turn', { status: 409 });\n }\n\n const moves = game.moves();\n const move = moves[Math.floor(Math.random() * moves.length)];\n if (!move) {\n return new Response('No legal moves', { status: 406 });\n }\n\n game.move(move);\n const newPgn = game.pgn();\n await space.db.update({ id: changedObjectId }, { pgn: newPgn, fen: game.fen() });\n return { state: game.ascii() };\n },\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { defineFunction, S, create, Expando } from 'dxos:functions';\n// @ts-ignore\nimport { randText } from 'https://esm.sh/@ngneat/falso@7.1.1?bundle=false';\n\nexport default defineFunction({\n inputSchema: S.Struct({\n documentAmount: S.optional(S.Number),\n textSize: S.optional(S.Number),\n mutationAmount: S.optional(S.Number),\n }),\n\n outputSchema: S.Struct({}),\n\n handler: async ({ data: { documentAmount = 1, textSize = 10, mutationAmount = 0 }, context: { space } }: any) => {\n await space.db.graph.schemaRegistry.addSchema([Expando]);\n const result: Record<string, any> = {};\n const objects: Expando[] = [];\n\n // Create objects.\n for (let i = 0; i < documentAmount; i++) {\n const obj = space.db.add(\n create(Expando, {\n name: 'scriptGenerated',\n content: randText({ charCount: textSize }),\n }),\n );\n objects.push(obj);\n const objectResult: any = {};\n // Mutate the object.\n for (let i = 0; i < mutationAmount; i++) {\n obj.content = randText({ charCount: textSize });\n }\n objectResult.mutations = mutationAmount;\n objectResult.contentLength = obj.content.length;\n result[obj.id] = objectResult;\n }\n\n // Flush and wait for data to propagate.\n await space.db.flush();\n await new Promise((resolve) => setTimeout(resolve, 10_000));\n return result;\n },\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { create, defineFunction, DXN, EchoObject, Filter, ObjectId, S } from 'dxos:functions';\n// @ts-ignore\nimport { FetchHttpClient } from 'https://esm.sh/@effect/platform@0.77.2?deps=effect@3.14.21&bundle=false';\nimport {\n DiscordConfig,\n DiscordREST,\n DiscordRESTMemoryLive,\n // @ts-ignore\n} from 'https://esm.sh/dfx@0.113.0?deps=effect@3.14.21&bundle=false';\n// @ts-ignore\nimport { Effect, Config, Redacted, Ref } from 'https://esm.sh/effect@3.14.21?bundle=false';\n\nconst MessageSchema = S.Struct({\n id: ObjectId,\n foreignId: S.Any, // bigint?\n from: S.String,\n created: S.String,\n content: S.String,\n}).pipe(\n EchoObject({\n typename: 'example.com/type/Message',\n version: '0.1.0',\n }),\n);\n\nconst DEFAULT_AFTER = 1704067200; // 2024-01-01\n\nconst generateSnowflake = (unixTimestamp: number): bigint => {\n const discordEpoch = 1420070400000n; // Discord Epoch (ms)\n return (BigInt(unixTimestamp * 1000) - discordEpoch) << 22n;\n};\n\nexport default defineFunction({\n inputSchema: S.Struct({\n // TODO(wittjosiah): Remove. This is used to provide a terminal for a cron trigger.\n tick: S.optional(S.String),\n channelId: S.String,\n after: S.optional(S.Number),\n pageSize: S.optional(S.Number),\n queueId: S.String,\n }),\n\n outputSchema: S.Struct({\n newMessages: S.Number,\n }),\n\n handler: ({ data: { channelId, queueId, after = DEFAULT_AFTER, pageSize = 5 }, context: { space } }: any) =>\n Effect.gen(function* () {\n const { token } = yield* Effect.tryPromise({\n try: () => space.db.query(Filter.typename('dxos.org/type/AccessToken', { source: 'discord.com' })).first(),\n catch: (e: any) => e,\n });\n const { objects } = yield* Effect.tryPromise({\n try: () => space.queues.queryQueue(DXN.parse(queueId)),\n catch: (e: any) => e,\n });\n const backfill = objects.length === 0;\n const newMessages = yield* Ref.make(0);\n const lastMessage = yield* Ref.make(objects.at(-1));\n\n const enqueueMessages = Effect.gen(function* () {\n const rest = yield* DiscordREST;\n\n while (true) {\n const last = yield* Ref.get(lastMessage);\n const options = {\n after: backfill && !last ? `${generateSnowflake(after)}` : last?.foreignId,\n limit: pageSize,\n };\n const messages = yield* rest.getChannelMessages(channelId, options).pipe((res: any) => res.json);\n const queueMessages = messages\n .map((message: any) =>\n create(MessageSchema, {\n id: ObjectId.random(),\n foreignId: message.id,\n from: message.author.username,\n created: message.timestamp,\n content: message.content,\n }),\n )\n .toReversed();\n if (queueMessages.length > 0) {\n yield* Effect.tryPromise({\n try: () => space.queues.insertIntoQueue(DXN.parse(queueId), queueMessages),\n catch: (e: any) => e,\n });\n yield* Ref.update(newMessages, (n: any) => n + queueMessages.length);\n yield* Ref.update(lastMessage, (m: any) => queueMessages.at(-1));\n }\n if (messages.length < pageSize) {\n break;\n }\n }\n }).pipe(\n Effect.provide(DiscordRESTMemoryLive),\n Effect.provide(\n DiscordConfig.layerConfig({\n token: Config.succeed(Redacted.make(token)),\n }),\n ),\n Effect.provide(FetchHttpClient.layer),\n );\n\n yield* enqueueMessages;\n return { newMessages: yield* Ref.get(newMessages) };\n }),\n});\n", "//\n// Copyright 2024 DXOS.org\n//\n\n/**\n * Echos the request data.\n */\nexport default async ({ data }: any) => data;\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 ({ data: { bodyText }, context: { space } }: any) => {\n const { email, targetDocumentId: documentId } = JSON.parse(bodyText) as RequestPayload;\n\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:** ${email.from}`,\n `**Subject:** ${email.subject}`,\n `**Date:** ${email.created}`,\n '',\n email.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 email: { from: string; subject: string; created: string; body: string };\n targetDocumentId: string;\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { S, defineFunction } from 'dxos:functions';\nimport {\n HttpClient,\n HttpClientRequest,\n FetchHttpClient,\n // @ts-ignore\n} from 'https://esm.sh/@effect/platform@0.77.2?deps=effect@3.14.21&bundle=false';\n// @ts-ignore\nimport { Effect, Schedule } from 'https://esm.sh/effect@3.14.21?bundle=false';\n\nexport default defineFunction({\n description: 'Returns the exchange rate between two currencies.',\n\n inputSchema: S.Struct({\n from: S.String.annotations({ description: 'The source currency' }),\n to: S.String.annotations({ description: 'The target currency' }),\n }),\n\n outputSchema: S.String.annotations({ description: 'The exchange rate between the two currencies' }),\n\n handler: async ({ data: { from, to } }: any) =>\n Effect.gen(function* () {\n const res = yield* HttpClientRequest.get(`https://free.ratesdb.com/v1/rates?from=${from}&to=${to}`).pipe(\n HttpClient.execute,\n Effect.flatMap((res: any) => res.json),\n Effect.timeout('1 second'),\n Effect.retry(Schedule.exponential(1_000).pipe(Schedule.compose(Schedule.recurs(3)))),\n Effect.scoped,\n );\n\n return res.data.rates[to].toString();\n }).pipe(Effect.provide(FetchHttpClient.layer)),\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { defineFunction, S } from 'dxos:functions';\n\nexport default defineFunction({\n description: 'Returns the exchange rate between two currencies.',\n\n inputSchema: S.Struct({\n from: S.String.annotations({ description: 'The source currency' }),\n to: S.String.annotations({ description: 'The target currency' }),\n }),\n\n handler: async ({ data: { from, to } }: any) => {\n const res = await fetch(`https://free.ratesdb.com/v1/rates?from=${from}&to=${to}`);\n const {\n data: { rates },\n } = await res.json();\n\n return rates[to].toString();\n },\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { create, defineFunction, EchoObject, Filter, ObjectId, S } from 'dxos:functions';\n// @ts-ignore\nimport {\n HttpClient,\n HttpClientRequest,\n FetchHttpClient,\n // @ts-ignore\n} from 'https://esm.sh/@effect/platform@0.77.2?deps=effect@3.14.21&bundle=false';\n// @ts-ignore\nimport { format, subDays } from 'https://esm.sh/date-fns@3.3.1?bundle=false';\n// @ts-ignore\nimport { pipe, Chunk, Effect, Ref, Schedule, Stream } from 'https://esm.sh/effect@3.14.21?bundle=false';\n\nexport default defineFunction({\n inputSchema: S.Struct({\n mailboxId: S.String,\n userId: S.optional(S.String).pipe(S.withDecodingDefault(() => 'me')),\n after: S.optional(S.Union(S.Number, S.String)).pipe(\n S.withDecodingDefault(() => format(subDays(new Date(), 30), 'yyyy-MM-dd')),\n ),\n pageSize: S.optional(S.Number).pipe(S.withDecodingDefault(() => 100)),\n // TODO(wittjosiah): Remove. This is used to provide a terminal for a cron trigger.\n tick: S.optional(S.String),\n }),\n\n outputSchema: S.Struct({\n newMessages: S.Number,\n }),\n\n handler: ({ context: { space }, data: { mailboxId, userId, after, pageSize } }: any) =>\n Effect.gen(function* () {\n const { token } = yield* Effect.tryPromise({\n try: () => space.db.query(Filter.typename('dxos.org/type/AccessToken', { source: 'gmail.com' })).first(),\n catch: (e: any) => e,\n });\n\n // NOTE: Google API bundles size is v. large and caused runtime issues.\n const makeRequest = (url: string) =>\n pipe(\n url,\n HttpClientRequest.get,\n HttpClientRequest.setHeaders({ Authorization: `Bearer ${token}`, Accept: 'application/json' }),\n HttpClient.execute,\n Effect.flatMap((res: any) => res.json),\n Effect.timeout('1 second'),\n Effect.retry(Schedule.exponential(1000).pipe(Schedule.compose(Schedule.recurs(3)))),\n Effect.scoped,\n );\n\n const listMessages = (userId: string, q: string, pageSize: number, pageToken: string | null) =>\n makeRequest(getUrl(userId, undefined, { q, pageSize, pageToken }));\n\n const getMessage = (userId: string, messageId: string) => makeRequest(getUrl(userId, messageId));\n\n const mailbox = yield* Effect.tryPromise({\n try: () => space.db.query({ id: mailboxId }).first(),\n catch: (e: any) => e,\n });\n const { objects } = yield* Effect.tryPromise({\n try: () => space.queues.queryQueue(mailbox.queue.dxn),\n catch: (e: any) => e,\n });\n const newMessages = yield* Ref.make([]);\n const nextPage = yield* Ref.make(null);\n\n do {\n const last = objects.at(-1);\n const q = last\n ? `in:inbox after:${Math.floor(new Date(last.created).getTime() / 1000)}`\n : `in:inbox after:${after}`;\n const pageToken = yield* Ref.get(nextPage);\n const { messages, nextPageToken } = yield* listMessages(userId, q, pageSize, pageToken);\n yield* Ref.update(nextPage, () => nextPageToken);\n for (const message of messages) {\n const messageDetails = yield* getMessage(userId, message.id);\n const created = new Date(parseInt(messageDetails.internalDate)).toISOString();\n const from = messageDetails.payload.headers.find((h: any) => h.name === 'From');\n const sender = from && parseEmailString(from.value);\n // TODO(wittjosiah): Improve parsing of email contents.\n const content =\n messageDetails.payload.body?.data ??\n messageDetails.payload.parts?.find((p: any) => p.mimeType === 'text/plain')?.body.data;\n // Skip the message if content or sender is missing.\n // Skip the message if it's the same as the last message.\n // TODO(wittjosiah): This comparison should be done via foreignId probably.\n if (!content || !sender || created === last?.created) {\n continue;\n }\n const subject = messageDetails.payload.headers.find((h: any) => h.name === 'Subject')?.value;\n const object = create(MessageType, {\n id: ObjectId.random(),\n created,\n sender,\n blocks: [\n {\n type: 'text',\n text: Buffer.from(content, 'base64').toString('utf-8'),\n },\n ],\n properties: {\n subject,\n threadId: message.threadId,\n },\n });\n // TODO(wittjosiah): Set foreignId in object meta.\n yield* Ref.update(newMessages, (n: any) => [object, ...n]);\n }\n } while (yield* Ref.get(nextPage));\n\n const queueMessages = yield* Ref.get(newMessages);\n if (queueMessages.length > 0) {\n yield* pipe(\n queueMessages,\n Stream.fromIterable,\n Stream.grouped(10),\n Stream.flatMap((batch: any) =>\n Effect.tryPromise({\n try: () => space.queues.insertIntoQueue(mailbox.queue.dxn, Chunk.toReadonlyArray(batch)),\n catch: (e: any) => e,\n }),\n ),\n Stream.runDrain,\n );\n }\n\n return { newMessages: queueMessages.length };\n }).pipe(Effect.provide(FetchHttpClient.layer)),\n});\n\nconst getUrl = (userId: string, messageId?: string, params?: Record<string, any>) => {\n const api = new URL(\n [`https://gmail.googleapis.com/gmail/v1/users/${userId}/messages`, messageId].filter(Boolean).join('/'),\n );\n Object.entries(params ?? {})\n .filter(([_, value]) => value != null)\n .forEach(([key, value]) => api.searchParams.set(key, value));\n return api.toString();\n};\n\n/**\n * Parses an email string in the format \"Name <email@example.com>\" into separate name and email components.\n */\nconst parseEmailString = (emailString: string): { name?: string; email: string } | undefined => {\n const match = emailString.match(/^([^<]+?)\\s*<([^>]+@[^>]+)>$/);\n if (match) {\n const [, name, email] = match;\n return {\n name: name.trim(),\n email: email.trim(),\n };\n }\n\n return undefined;\n};\n\n//\n// Schemas\n// TODO(wittjosiah): These schemas should be imported from @dxos/S.\n//\n\nconst ActorRoles = ['user', 'assistant'] as const;\nconst ActorRole = S.Literal(...ActorRoles);\ntype ActorRole = S.Schema.Type<typeof ActorRole>;\n\nconst ActorSchema = S.Struct({\n identityKey: S.optional(S.String),\n email: S.optional(S.String),\n name: S.optional(S.String),\n role: S.optional(ActorRole),\n});\n\nconst AbstractContentBlock = S.Struct({\n pending: S.optional(S.Boolean),\n});\ntype AbstractContentBlock = S.Schema.Type<typeof AbstractContentBlock>;\nconst TextContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('text'),\n disposition: S.optional(S.String),\n text: S.String,\n }),\n).pipe(S.mutable);\ntype TextContentBlock = S.Schema.Type<typeof TextContentBlock>;\nconst JsonContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('json'),\n disposition: S.optional(S.String),\n data: S.String,\n }),\n).pipe(S.mutable);\ntype JsonContentBlock = S.Schema.Type<typeof JsonContentBlock>;\nconst Base64ImageSource = S.Struct({\n type: S.Literal('base64'),\n mediaType: S.String,\n data: S.String,\n}).pipe(S.mutable);\nconst HttpImageSource = S.Struct({\n type: S.Literal('http'),\n url: S.String,\n}).pipe(S.mutable);\nconst ImageSource = S.Union(Base64ImageSource, HttpImageSource);\ntype ImageSource = S.Schema.Type<typeof ImageSource>;\nconst ImageContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('image'),\n id: S.optional(S.String),\n source: S.optional(ImageSource),\n }),\n).pipe(S.mutable);\ntype ImageContentBlock = S.Schema.Type<typeof ImageContentBlock>;\nconst ReferenceContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('reference'),\n reference: S.Any,\n }),\n).pipe(S.mutable);\ntype ReferenceContentBlock = S.Schema.Type<typeof ReferenceContentBlock>;\nconst MessageContentBlock = S.Union(TextContentBlock, JsonContentBlock, ImageContentBlock, ReferenceContentBlock);\n\nconst MessageType = S.Struct({\n id: ObjectId,\n created: S.String.annotations({\n description: 'ISO date string when the message was sent.',\n }),\n sender: ActorSchema.annotations({\n description: 'Identity of the message sender.',\n }),\n blocks: S.Array(MessageContentBlock).annotations({\n description: 'Contents of the message.',\n }),\n properties: S.optional(\n S.mutable(\n S.Record({ key: S.String, value: S.Any }).annotations({\n description: 'Custom properties for specific message types (e.g. attention context, email subject, etc.).',\n }),\n ),\n ),\n}).pipe(\n EchoObject({\n typename: 'dxos.org/type/Message',\n version: '0.2.0',\n }),\n);\ntype MessageType = S.Schema.Type<typeof MessageType>;\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport chat from './chat.ts?raw';\nimport chess from './chess.ts?raw';\nimport dataGenerator from './data-generator.ts?raw';\nimport discord from './discord.ts?raw';\nimport echo from './echo.ts?raw';\nimport email from './email.ts?raw';\nimport forexEffect from './forex-effect.ts?raw';\nimport forex from './forex.ts?raw';\nimport gmail from './gmail.ts?raw';\n\nconst removeHeader = (str: string) => str.split('\\n').slice(4).join('\\n');\n\nexport type Template = {\n id: string;\n name: string;\n source: string;\n presetId?: string;\n};\n\nexport const templates: Template[] = [\n {\n id: 'dxos.org/script/echo',\n name: 'Echo',\n source: removeHeader(echo),\n },\n {\n id: 'dxos.org/script/forex',\n name: 'Forex',\n source: removeHeader(forex),\n },\n {\n id: 'dxos.org/script/forex-effect',\n name: 'Forex (Effect)',\n source: removeHeader(forexEffect),\n },\n {\n id: 'dxos.org/script/gpt',\n name: 'Gpt',\n source: removeHeader(chat),\n presetId: 'dxos.org/function/gpt',\n },\n {\n id: 'dxos.org/script/chess',\n name: 'Chess',\n source: removeHeader(chess),\n presetId: 'dxos.org/function/chess',\n },\n {\n id: 'dxos.org/script/email',\n name: 'Email',\n source: removeHeader(email),\n presetId: 'dxos.org/function/email',\n },\n {\n id: 'dxos.org/script/discord',\n name: 'Discord',\n source: removeHeader(discord),\n presetId: 'dxos.org/function/discord',\n },\n {\n id: 'dxos.org/script/gmail',\n name: 'Gmail',\n source: removeHeader(gmail),\n presetId: 'dxos.org/function/gmail',\n },\n {\n id: 'dxos.org/script/data-generator',\n name: 'Data Generator',\n source: removeHeader(dataGenerator),\n presetId: 'dxos.org/function/data-generator',\n },\n];\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { useMemo } from 'react';\n\nimport { live } from '@dxos/live-object';\n\nimport { type DeployState } from './deploy';\n\nexport type ScriptToolbarState = Partial<DeployState>;\n\n// TODO(burdon): Replace with context provider?\nexport const useToolbarState = (initialState: ScriptToolbarState = {}) => {\n return useMemo(() => live<ScriptToolbarState>(initialState), []);\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { format } from 'prettier';\nimport prettierPluginEstree from 'prettier/plugins/estree';\nimport prettierPluginTypescript from 'prettier/plugins/typescript';\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 = (script: ScriptType) => {\n const formatAction = createMenuAction(\n 'format',\n 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 },\n {\n label: ['format label', { ns: SCRIPT_PLUGIN }],\n icon: 'ph--magic-wand--regular',\n },\n );\n\n return {\n nodes: [formatAction],\n edges: [\n {\n source: 'root',\n target: 'format',\n },\n ],\n };\n};\n", "//\n// Copyright 2025 DXOS.org\n//\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 = (script: ScriptType) => {\n return templates.map((template) => {\n return createMenuAction<TemplateActionProperties>(\n `template--${template.id}`,\n () => {\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 label: template.name,\n value: template.id,\n type: 'template',\n },\n );\n });\n};\n\nexport const createTemplateSelect = (script: ScriptType) => {\n const templateSelectGroup = createTemplateSelectGroup();\n const templateSelectActions = createTemplateSelectActions(script);\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"],
5
5
  "mappings": ";;;;;;;;;;AAIA,SAASA,WAAWC,eAAe;AAEnC,SAASC,cAA+BC,oCAAoC;AAC5E,SAASC,WAAW;AACpB,SAAsBC,iBAAiB;AACvC,SAASC,SAASC,UAAUC,OAAOC,KAAiBC,gBAAgB;AAEpE,SAASC,wBAAwB;AACjC,SAASC,0BAA0B;;AAwB5B,IAAMC,eAAe,CAAC,EAAEC,OAAOC,QAAQC,OAAOC,IAAIC,QAAQC,qBAAqBC,EAAC,MAAuB;AAE5G,QAAMC,YAAYC,iBAAiB,SAAS,MAAA;EAAO,GAAG;IACpDC,OAAOT,MAAMU,SAAS;MAAC;MAAkB;QAAEC,IAAIC;MAAc;;IAC7DC,MAAM;IACNC,QAAQ,CAACd,MAAMU;IACfK,YAAYf,MAAMU,SAASM;EAC7B,CAAA;AAEA,QAAMC,eAAeT,iBACnB,UACA,YAAA;AACE,QAAI,CAACP,OAAOiB,UAAU,CAAChB,OAAO;AAC5B;IACF;AAEAF,UAAMU,QAAQS;AACdnB,UAAMoB,YAAY;AAElB,UAAMC,SAAS,MAAMC,aAAa;MAAErB;MAAQG;MAAQF;MAAOC;MAAIE;IAAoB,CAAA;AAEnF,QAAI,CAACgB,OAAOE,SAAS;AACnBC,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AOC,kBACL,aAAaD,SAASE,EAAE,IACxB,MAAA;AACEL,aAAOM,OAAOH,SAASG;AACvBN,aAAOO,OAAQC,OAAQC,UAAUN,SAASI;AAC1C,YAAMG,WAAWC,SAAQX,MAAAA,EAAQY;AACjC,YAAMC,iBAAiBH,SAASI,UAAU,CAACC,QAAQA,IAAIR,WAAWS,yBAAAA;AAClE,UAAIH,kBAAkB,GAAG;AACvBH,iBAASO,OAAOJ,gBAAgB,CAAA;MAClC;AACA,UAAIV,SAASe,UAAU;AACrBR,iBAASS,KAAK;UAAEZ,QAAQS;UAA2BX,IAAIF,SAASe;QAAS,CAAA;MAC3E;IACF,GACA;MACEvB,OAAOQ,SAASG;MAChBc,OAAOjB,SAASE;MAChBgB,MAAM;IACR,CAAA;EAEJ,CAAA;AACF;AAEO,IAAMC,uBAAuB,CAACtB,WAAAA;AACnC,QAAMuB,sBAAsB9B,0BAAAA;AAC5B,QAAM+B,wBAAwBzB,4BAA4BC,MAAAA;AAC1D,SAAO;IACLyB,OAAO;MAACF;SAAwBC;;IAChCE,OAAO;MACL;QAAEnB,QAAQ;QAAQC,QAAQ;MAAkB;SACzCgB,sBAAsBtB,IAAI,CAACyB,YAAY;QAAEpB,QAAQ;QAAmBC,QAAQmB,OAAOtB;MAAG,EAAA;;EAE7F;AACF;",
6
6
  "names": ["useEffect", "useMemo", "FunctionType", "getUserFunctionUrlInMetadata", "log", "useClient", "getMeta", "getSpace", "Query", "Ref", "useQuery", "createMenuAction", "errorMessageColors", "createDeploy", "state", "script", "space", "fn", "client", "existingFunctionUrl", "t", "errorItem", "createMenuAction", "label", "error", "ns", "SCRIPT_PLUGIN", "icon", "hidden", "classNames", "errorMessageColors", "deployAction", "source", "undefined", "deploying", "result", "deployScript", "success", "log", "catch", "type", "disabled", "copyAction", "functionUrl", "navigator", "clipboard", "writeText", "nodes", "edges", "target", "useDeployState", "useDeployDeps", "useEffect", "getFunctionUrl", "edgeUrl", "config", "values", "runtime", "services", "edge", "url", "deployed", "isScriptDeployed", "changed", "getSpace", "useQuery", "Query", "FunctionType", "Ref", "make", "useClient", "useMemo", "getUserFunctionUrlInMetadata", "getMeta", "removeHeader", "str", "split", "slice", "join", "templates", "id", "name", "source", "echo", "forex", "forexEffect", "chat", "presetId", "chess", "email", "discord", "gmail", "dataGenerator", "useMemo", "live", "useToolbarState", "initialState", "useMemo", "live", "format", "prettierPluginEstree", "prettierPluginTypescript", "log", "createMenuAction", "createFormat", "script", "formatAction", "createMenuAction", "source", "target", "content", "format", "parser", "plugins", "prettierPluginEstree", "prettierPluginTypescript", "semi", "singleQuote", "err", "log", "catch", "label", "ns", "SCRIPT_PLUGIN", "icon", "nodes", "edges", "FUNCTIONS_PRESET_META_KEY", "getMeta", "createMenuItemGroup", "createMenuAction", "createTemplateSelectGroup", "createMenuItemGroup", "label", "ns", "SCRIPT_PLUGIN", "variant", "createTemplateSelectActions", "script", "templates", "map", "template", "createMenuAction", "id", "name", "source", "target", "content", "metaKeys", "getMeta", "keys", "oldPresetIndex", "findIndex", "key", "FUNCTIONS_PRESET_META_KEY", "splice", "presetId", "push", "value", "type", "createTemplateSelect", "templateSelectGroup", "templateSelectActions", "nodes", "edges", "action"]
7
7
  }
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  useDeployState,
3
3
  useToolbarState
4
- } from "./chunk-I6S7QLGR.mjs";
4
+ } from "./chunk-3FU4QZVP.mjs";
5
5
  import {
6
6
  SCRIPT_PLUGIN,
7
7
  meta
@@ -76,7 +76,7 @@ var Binding = ({ object }) => {
76
76
  }
77
77
  return /* @__PURE__ */ React.createElement("div", {
78
78
  role: "form",
79
- className: "flex flex-col p-2 gap-2"
79
+ className: "flex flex-col gap-2 mlb-cardSpacingBlock"
80
80
  }, /* @__PURE__ */ React.createElement("h2", null, t("remote function settings heading")), /* @__PURE__ */ React.createElement(Input.Root, null, /* @__PURE__ */ React.createElement("div", {
81
81
  role: "none",
82
82
  className: "flex flex-col gap-1"
@@ -191,7 +191,7 @@ var Publishing = ({ object }) => {
191
191
  githubToken
192
192
  ]);
193
193
  return /* @__PURE__ */ React.createElement("div", {
194
- className: "flex flex-col p-2 gap-4"
194
+ className: "flex flex-col gap-4 mlb-cardSpacingBlock"
195
195
  }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", null, t("script publish settings label")), /* @__PURE__ */ React.createElement("p", {
196
196
  className: "text-description text-sm"
197
197
  }, t("script publish settings description"))), !githubToken && /* @__PURE__ */ React.createElement("div", {
@@ -490,7 +490,7 @@ var MessageItem = ({ classNames, message }) => {
490
490
  var _effect = _useSignals3();
491
491
  try {
492
492
  const { type, text, data, error } = message;
493
- const wrapper = "p-1 px-2 rounded-lg bg-hoverSurface overflow-auto";
493
+ const wrapper = "p-1 px-2 rounded-md bg-hoverSurface overflow-auto";
494
494
  return /* @__PURE__ */ React3.createElement("div", {
495
495
  className: mx("flex", type === "request" ? "ml-[1rem] justify-end" : "mr-[1rem]", classNames)
496
496
  }, error && /* @__PURE__ */ React3.createElement("div", {
@@ -542,7 +542,7 @@ var TestContainer = ({ script, role }) => {
542
542
 
543
543
  // packages/plugins/plugin-script/src/components/index.ts
544
544
  import { lazy } from "react";
545
- var ScriptContainer = lazy(() => import("./ScriptContainer-BQS7LDI7.mjs"));
545
+ var ScriptContainer = lazy(() => import("./ScriptContainer-RSN52NH7.mjs"));
546
546
  var DeploymentDialog = lazy(() => import("./DeploymentDialog-RPPPWEEL.mjs"));
547
547
 
548
548
  export {
@@ -554,4 +554,4 @@ export {
554
554
  ScriptContainer,
555
555
  DeploymentDialog
556
556
  };
557
- //# sourceMappingURL=chunk-OMQLWT6X.mjs.map
557
+ //# sourceMappingURL=chunk-3JLR2SHJ.mjs.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/components/Settings/ScriptObjectSettings.tsx", "../../../src/components/Settings/ScriptPluginSettings.tsx", "../../../src/components/TestPanel/TestPanel.tsx", "../../../src/components/TestPanel/TestContainer.tsx", "../../../src/components/index.ts"],
4
- "sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { Octokit } from '@octokit/core';\nimport React, { type ChangeEvent, useCallback, useEffect, useState } from 'react';\n\nimport { createIntent, SettingsAction, useIntentDispatcher } from '@dxos/app-framework';\nimport { FunctionType, type ScriptType, getInvocationUrl, getUserFunctionUrlInMetadata } from '@dxos/functions';\nimport { log } from '@dxos/log';\nimport { useClient } from '@dxos/react-client';\nimport { Filter, getMeta, getSpace, Ref, useQuery } from '@dxos/react-client/echo';\nimport { Button, Clipboard, Input, useControlledState, useTranslation } from '@dxos/react-ui';\nimport { DataType } from '@dxos/schema';\n\nimport { SCRIPT_PLUGIN } from '../../meta';\n\nexport type ScriptObjectSettingsProps = {\n object: ScriptType;\n};\n\nexport const ScriptObjectSettings = ({ object }: ScriptObjectSettingsProps) => {\n return (\n <>\n <Binding object={object} />\n <Publishing object={object} />\n </>\n );\n};\n\nexport const ScriptProperties = ({ object }: ScriptObjectSettingsProps) => {\n const { t } = useTranslation(SCRIPT_PLUGIN);\n return (\n <Input.Root>\n <Input.Label>{t('description label')}</Input.Label>\n <Input.TextInput\n placeholder={t('description placeholder')}\n value={object.description ?? ''}\n onChange={(event) => {\n object.description = event.target.value;\n }}\n />\n </Input.Root>\n );\n};\n\nconst Binding = ({ object }: ScriptObjectSettingsProps) => {\n const { t } = useTranslation(SCRIPT_PLUGIN);\n const client = useClient();\n const space = getSpace(object);\n const [fn] = useQuery(space, Filter.type(FunctionType, { source: Ref.make(object) }));\n\n const functionPath = fn && getUserFunctionUrlInMetadata(getMeta(fn));\n const functionUrl =\n functionPath &&\n getInvocationUrl(functionPath, client.config.values.runtime?.services?.edge?.url ?? '', {\n spaceId: space?.id,\n });\n\n const [binding, setBinding] = useControlledState(fn?.binding ?? '');\n const handleBindingChange = useCallback(\n (event: ChangeEvent<HTMLInputElement>) => {\n setBinding(event.target.value);\n },\n [setBinding],\n );\n\n const handleBindingBlur = useCallback(() => {\n fn.binding = binding;\n }, [fn, binding]);\n\n if (!fn || !functionUrl) {\n return null;\n }\n\n // TODO(burdon): Use form.\n return (\n <div role='form' className='flex flex-col p-2 gap-2'>\n <h2>{t('remote function settings heading')}</h2>\n <Input.Root>\n <div role='none' className='flex flex-col gap-1'>\n <Input.Label>{t('function url label')}</Input.Label>\n <div role='none' className='flex gap-1'>\n <Input.TextInput\n disabled\n value={functionUrl}\n onChange={(event) => {\n fn.name = event.target.value;\n }}\n />\n <Clipboard.IconButton value={functionUrl} />\n </div>\n </div>\n </Input.Root>\n <Input.Root>\n <div role='none' className='flex flex-col gap-1'>\n <Input.Label>{t('function binding label')}</Input.Label>\n <Input.TextInput\n placeholder={t('function binding placeholder')}\n value={binding}\n onChange={handleBindingChange}\n onBlur={handleBindingBlur}\n />\n </div>\n </Input.Root>\n </div>\n );\n};\n\n// TODO(burdon): Move to separate tab?\nconst Publishing = ({ object }: ScriptObjectSettingsProps) => {\n const { t } = useTranslation(SCRIPT_PLUGIN);\n const { dispatchPromise: dispatch } = useIntentDispatcher();\n const space = getSpace(object);\n const [githubToken] = useQuery(space, Filter.type(DataType.AccessToken, { source: 'github.com' }));\n const gistKey = getMeta(object).keys.find(({ source }) => source === 'github.com');\n const [gistUrl, setGistUrl] = useState<string | undefined>();\n\n useEffect(() => {\n const token = githubToken?.token;\n const gistId = gistKey?.id;\n if (!token || !gistId) {\n setGistUrl(undefined);\n return;\n }\n\n const timeout = setTimeout(async () => {\n try {\n const octokit = new Octokit({ auth: githubToken.token });\n const response = await octokit.request('GET /gists/{gist_id}', {\n gist_id: gistId,\n });\n setGistUrl(response.data.html_url);\n } catch (err) {\n log.catch(err);\n setGistUrl(undefined);\n }\n });\n\n return () => clearTimeout(timeout);\n }, [githubToken, gistKey]);\n\n const handleOpenTokenManager = useCallback(\n () => dispatch(createIntent(SettingsAction.Open, { plugin: 'dxos.org/plugin/token-manager' })),\n [],\n );\n\n const [publishing, setPublishing] = useState(false);\n const handlePublish = useCallback(async () => {\n setPublishing(true);\n const octokit = new Octokit({ auth: githubToken.token });\n const source = await object.source.load();\n const filename = object.name ? kebabize(object.name) : 'composer-script';\n const files = { [`${filename}.ts`]: { content: source.content } };\n\n try {\n // TODO(wittjosiah): Factor out to intent.\n const meta = getMeta(object);\n const githubKey = meta.keys.find(({ source }) => source === 'github.com');\n const gistId = githubKey?.id;\n if (gistId) {\n await octokit.request('PATCH /gists/{gist_id}', {\n gist_id: gistId,\n files,\n });\n } else {\n const response = await octokit.request('POST /gists', {\n public: true,\n files,\n });\n if (response.data.id) {\n meta.keys.push({ source: 'github.com', id: response.data.id });\n }\n }\n } finally {\n setPublishing(false);\n }\n }, [object, githubToken]);\n\n return (\n <div className='flex flex-col p-2 gap-4'>\n <div>\n <h2>{t('script publish settings label')}</h2>\n <p className='text-description text-sm'>{t('script publish settings description')}</p>\n </div>\n {!githubToken && (\n <div className='flex flex-col gap-2'>\n <span>{t('no github token label')}</span>\n <Button onClick={handleOpenTokenManager}>{t('open token manager label')}</Button>\n </div>\n )}\n {githubToken && (\n <div className='flex justify-end gap-2'>\n {gistUrl && <Clipboard.IconButton value={gistUrl} />}\n <Button disabled={publishing} onClick={handlePublish}>\n {t(publishing ? 'publishing label' : 'publish label')}\n </Button>\n </div>\n )}\n </div>\n );\n};\n\n// TODO(wittjosiah): Factor out.\n// From https://stackoverflow.com/a/67243723/2804332\nconst kebabize = (str: string) => str.replace(/[A-Z]+(?![a-z])|[A-Z]/g, ($, ofs) => (ofs ? '-' : '') + $.toLowerCase());\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport React from 'react';\n\nimport { type Credential } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { useClient } from '@dxos/react-client';\nimport { Button, Select, useTranslation } from '@dxos/react-ui';\nimport { type EditorInputMode, EditorInputModes } from '@dxos/react-ui-editor';\nimport { DeprecatedFormContainer, DeprecatedFormInput } from '@dxos/react-ui-form';\n\nimport { meta } from '../../meta';\nimport { type ScriptSettingsProps } from '../../types';\n\nexport const ScriptPluginSettings = ({ settings }: { settings: ScriptSettingsProps }) => {\n const { t } = useTranslation(meta.id);\n const client = useClient();\n\n // TODO(burdon): Check token.\n const handleAuthenticate = async () => {\n const { identityKey } = client.halo.identity.get()!;\n await client.halo.writeCredentials([\n {\n issuer: identityKey,\n issuanceDate: new Date(),\n subject: {\n id: identityKey,\n assertion: {\n '@type': 'dxos.halo.credentials.ServiceAccess',\n serverName: 'hub.dxos.network',\n serverKey: identityKey,\n identityKey,\n capabilities: ['composer:beta'],\n },\n },\n } satisfies Credential,\n ]);\n };\n\n return (\n <DeprecatedFormContainer>\n {/* TODO(wittjosiah): Hide outside of dev environments. */}\n <DeprecatedFormInput label={t('authenticate action label')}>\n <Button onClick={handleAuthenticate}>{t('authenticate button label')}</Button>\n </DeprecatedFormInput>\n\n <DeprecatedFormInput label={t('editor input mode label')}>\n <Select.Root\n value={settings.editorInputMode ?? 'default'}\n onValueChange={(value) => {\n settings.editorInputMode = value as EditorInputMode;\n }}\n >\n <Select.TriggerButton placeholder={t('select editor input mode placeholder')} />\n <Select.Portal>\n <Select.Content>\n <Select.Viewport>\n {EditorInputModes.map((mode) => (\n <Select.Option key={mode} value={mode}>\n {t(`settings editor input mode ${mode} label`)}\n </Select.Option>\n ))}\n </Select.Viewport>\n </Select.Content>\n </Select.Portal>\n </Select.Root>\n </DeprecatedFormInput>\n </DeprecatedFormContainer>\n );\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport React, { forwardRef, useEffect, useRef, useState } from 'react';\n\nimport { log } from '@dxos/log';\nimport { Avatar, Icon, Input, type ThemedClassName, Toolbar, useTranslation } from '@dxos/react-ui';\nimport { SyntaxHighlighter } from '@dxos/react-ui-syntax-highlighter';\nimport { errorText, mx } from '@dxos/react-ui-theme';\n\nimport { SCRIPT_PLUGIN } from '../../meta';\n\ntype State = 'pending' | 'responding';\n\n/**\n * Request or response.\n */\ntype Message = { type: 'request' | 'response'; text?: string; data?: any; error?: Error };\n\nexport type TestPanelProps = ThemedClassName<{\n functionUrl?: string;\n}>;\n\n// TODO(burdon): Need persistent history (currently lost when switching tabs)..\nexport const TestPanel = ({ classNames, functionUrl }: TestPanelProps) => {\n const { t } = useTranslation(SCRIPT_PLUGIN);\n\n const inputRef = useRef<HTMLInputElement>(null);\n const [input, setInput] = useState('');\n const [result, setResult] = useState('');\n const [state, setState] = useState<State | null>(null);\n\n // TODO(burdon): Persistent history (thread).\n const [history, setHistory] = useState<Message[]>([]);\n\n const scrollerRef = useRef<HTMLDivElement>(null);\n const handleScroll = () => {\n if (scrollerRef.current) {\n scrollerRef.current.scrollTop = scrollerRef.current.scrollHeight;\n }\n };\n\n const controller = useRef<AbortController>();\n useEffect(() => {\n return () => {\n handleStop();\n };\n }, []);\n\n const handleStop = () => {\n controller.current?.abort('stop');\n controller.current = undefined;\n };\n\n const handleClear = () => {\n handleStop();\n setInput('');\n setResult('');\n setHistory([]);\n inputRef.current?.focus();\n };\n\n const handleResponse = ({ text, data, error }: { text?: string; data?: any; error?: Error } = {}) => {\n controller.current = undefined;\n setHistory((history) => [...history, { type: 'response', text, data, error } satisfies Message]);\n setResult('');\n setState(null);\n handleScroll();\n };\n\n const handleRequest = async (input: string) => {\n // Returns a promise that resolves when a value has been received.\n try {\n setState('pending');\n\n let data = null;\n // Detect JSON input.\n if (input.charAt(0) === '{') {\n try {\n const validJsonString = input.replace(/'/g, '\"').replace(/([{,]\\s*)([a-zA-Z0-9_]+)(\\s*:)/g, '$1\"$2\"$3');\n data = JSON.parse(validJsonString);\n input = JSON.stringify(data, null, 2);\n } catch (err) {\n inputRef.current?.focus();\n return;\n }\n }\n\n setInput('');\n setResult('');\n setHistory((history) => [...history, { type: 'request', text: input }]);\n setTimeout(() => {\n handleScroll();\n });\n\n // Throws DOMException when aborted.\n controller.current = new AbortController();\n const response = await fetch(functionUrl!, {\n signal: controller.current.signal,\n method: 'POST',\n body: input,\n headers: {\n 'Content-Type': data ? 'application/json' : 'text/plain',\n },\n });\n\n // Check for error.\n if (!response.ok) {\n const text = await response.text();\n handleResponse({ error: new Error(text || response.statusText || String(response.status)) });\n return;\n }\n\n // Check for JSON.\n const contentType = response.headers.get('content-type');\n if (contentType === 'application/json') {\n const data = await response.json();\n handleResponse({ data });\n return;\n }\n\n // Text (including streaming).\n setState('responding');\n let text = '';\n const reader = response.body!.getReader();\n const pump = async ({ done, value }: ReadableStreamReadResult<Uint8Array>): Promise<void> => {\n text = text + new TextDecoder().decode(value);\n if (!controller.current || done) {\n handleResponse({ text });\n return;\n }\n\n setResult(text);\n setTimeout(() => {\n handleScroll();\n });\n\n return reader.read().then(pump);\n };\n\n void reader\n .read()\n .then(pump)\n .catch((err) => {\n if (err.name !== 'AbortError') {\n log.catch(err);\n }\n });\n } catch (err: any) {\n if (err !== 'stop') {\n const error = err instanceof Error ? err : new Error(err);\n handleResponse({ error });\n log.catch(err);\n } else {\n handleResponse();\n }\n }\n };\n\n return (\n <div className={mx('flex flex-col h-full overflow-hidden', classNames)}>\n {/* TODO(burdon): Replace with Thread. */}\n <MessageThread ref={scrollerRef} state={state} result={result} history={history} />\n {/* TODO(burdon): Replace with Form based on the function's input schema. */}\n <Toolbar.Root classNames='p-2'>\n <Input.Root>\n <Input.TextInput\n ref={inputRef}\n autoFocus\n placeholder={t('function request placeholder')}\n value={input}\n onChange={(ev) => setInput(ev.target.value)}\n onKeyDown={(ev) => ev.key === 'Enter' && handleRequest(input)}\n />\n </Input.Root>\n <Toolbar.Button onClick={() => handleRequest(input)}>\n <Icon icon='ph--play--regular' size={4} />\n </Toolbar.Button>\n <Toolbar.Button onClick={() => (state ? handleStop() : handleClear())}>\n <Icon icon={state ? 'ph--stop--regular' : 'ph--trash--regular'} size={4} />\n </Toolbar.Button>\n </Toolbar.Root>\n </div>\n );\n};\n\n// TODO(burdon): Replace with thread?\n// TODO(burdon): Button to edit/re-run question.\ntype MessageThreadProps = {\n state: State | null;\n history: Message[];\n result: string;\n};\n\nconst MessageThread = forwardRef<HTMLDivElement, MessageThreadProps>(\n ({ state, history, result }: MessageThreadProps, forwardedRef) => {\n return (\n <div ref={forwardedRef} className='flex flex-col gap-6 h-full p-2 overflow-x-hidden overflow-y-auto'>\n {history.map((message, i) => (\n <div key={i} className='grid grid-cols-[2rem_1fr_2rem]'>\n <div className='p-1'>{message.type === 'response' && <RobotAvatar />}</div>\n <div className='overflow-auto'>\n <MessageItem message={message} />\n </div>\n </div>\n ))}\n\n {result?.length > 0 && (\n <div className='grid grid-cols-[2rem_1fr_2rem]'>\n <div className='p-1'>\n {(state === 'pending' && <Icon icon='ph--spinner--regular' size={6} classNames='animate-spin' />) || (\n <Icon icon='ph--robot--regular' size={6} classNames='animate-[pulse_1s_ease-in-out_infinite]' />\n )}\n </div>\n <div className='overflow-auto'>\n <MessageItem message={{ type: 'response', text: result }} />\n </div>\n </div>\n )}\n </div>\n );\n },\n);\n\nconst MessageItem = ({ classNames, message }: ThemedClassName<{ message: Message }>) => {\n const { type, text, data, error } = message;\n const wrapper = 'p-1 px-2 rounded-lg bg-hoverSurface overflow-auto';\n return (\n <div className={mx('flex', type === 'request' ? 'ml-[1rem] justify-end' : 'mr-[1rem]', classNames)}>\n {error && <div className={mx(wrapper, 'whitespace-pre', errorText)}>{String(error)}</div>}\n\n {text !== undefined && (\n <div className={mx(wrapper, type === 'request' && 'bg-primary-400 dark:bg-primary-600')}>\n {text || '\\u00D8'}\n </div>\n )}\n\n {data && (\n <SyntaxHighlighter language='json' className={mx(wrapper, 'px-8 py-2 text-xs')}>\n {JSON.stringify(data, null, 2)}\n </SyntaxHighlighter>\n )}\n </div>\n );\n};\n\nconst RobotAvatar = () => (\n <Avatar.Root>\n <Avatar.Content size={6} variant='circle' icon='ph--robot--regular' />\n </Avatar.Root>\n);\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport React from 'react';\n\nimport { type ScriptType } from '@dxos/functions';\nimport { StackItem } from '@dxos/react-ui-stack';\n\nimport { TestPanel } from './TestPanel';\nimport { useDeployState, useToolbarState } from '../../hooks';\n\nexport const TestContainer = ({ script, role }: { script: ScriptType; role: string }) => {\n const state = useToolbarState();\n useDeployState({ state, script });\n return (\n <StackItem.Content role={role}>\n <TestPanel functionUrl={state.functionUrl} />\n </StackItem.Content>\n );\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { lazy } from 'react';\n\nexport * from './Settings';\nexport * from './TestPanel';\nexport { DEPLOYMENT_DIALOG } from './DeploymentDialog';\n\nexport const ScriptContainer = lazy(() => import('./ScriptContainer'));\nexport const DeploymentDialog = lazy(() => import('./DeploymentDialog'));\n"],
4
+ "sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { Octokit } from '@octokit/core';\nimport React, { type ChangeEvent, useCallback, useEffect, useState } from 'react';\n\nimport { createIntent, SettingsAction, useIntentDispatcher } from '@dxos/app-framework';\nimport { FunctionType, type ScriptType, getInvocationUrl, getUserFunctionUrlInMetadata } from '@dxos/functions';\nimport { log } from '@dxos/log';\nimport { useClient } from '@dxos/react-client';\nimport { Filter, getMeta, getSpace, Ref, useQuery } from '@dxos/react-client/echo';\nimport { Button, Clipboard, Input, useControlledState, useTranslation } from '@dxos/react-ui';\nimport { DataType } from '@dxos/schema';\n\nimport { SCRIPT_PLUGIN } from '../../meta';\n\nexport type ScriptObjectSettingsProps = {\n object: ScriptType;\n};\n\nexport const ScriptObjectSettings = ({ object }: ScriptObjectSettingsProps) => {\n return (\n <>\n <Binding object={object} />\n <Publishing object={object} />\n </>\n );\n};\n\nexport const ScriptProperties = ({ object }: ScriptObjectSettingsProps) => {\n const { t } = useTranslation(SCRIPT_PLUGIN);\n return (\n <Input.Root>\n <Input.Label>{t('description label')}</Input.Label>\n <Input.TextInput\n placeholder={t('description placeholder')}\n value={object.description ?? ''}\n onChange={(event) => {\n object.description = event.target.value;\n }}\n />\n </Input.Root>\n );\n};\n\nconst Binding = ({ object }: ScriptObjectSettingsProps) => {\n const { t } = useTranslation(SCRIPT_PLUGIN);\n const client = useClient();\n const space = getSpace(object);\n const [fn] = useQuery(space, Filter.type(FunctionType, { source: Ref.make(object) }));\n\n const functionPath = fn && getUserFunctionUrlInMetadata(getMeta(fn));\n const functionUrl =\n functionPath &&\n getInvocationUrl(functionPath, client.config.values.runtime?.services?.edge?.url ?? '', {\n spaceId: space?.id,\n });\n\n const [binding, setBinding] = useControlledState(fn?.binding ?? '');\n const handleBindingChange = useCallback(\n (event: ChangeEvent<HTMLInputElement>) => {\n setBinding(event.target.value);\n },\n [setBinding],\n );\n\n const handleBindingBlur = useCallback(() => {\n fn.binding = binding;\n }, [fn, binding]);\n\n if (!fn || !functionUrl) {\n return null;\n }\n\n // TODO(burdon): Use form.\n return (\n <div role='form' className='flex flex-col gap-2 mlb-cardSpacingBlock'>\n <h2>{t('remote function settings heading')}</h2>\n <Input.Root>\n <div role='none' className='flex flex-col gap-1'>\n <Input.Label>{t('function url label')}</Input.Label>\n <div role='none' className='flex gap-1'>\n <Input.TextInput\n disabled\n value={functionUrl}\n onChange={(event) => {\n fn.name = event.target.value;\n }}\n />\n <Clipboard.IconButton value={functionUrl} />\n </div>\n </div>\n </Input.Root>\n <Input.Root>\n <div role='none' className='flex flex-col gap-1'>\n <Input.Label>{t('function binding label')}</Input.Label>\n <Input.TextInput\n placeholder={t('function binding placeholder')}\n value={binding}\n onChange={handleBindingChange}\n onBlur={handleBindingBlur}\n />\n </div>\n </Input.Root>\n </div>\n );\n};\n\n// TODO(burdon): Move to separate tab?\nconst Publishing = ({ object }: ScriptObjectSettingsProps) => {\n const { t } = useTranslation(SCRIPT_PLUGIN);\n const { dispatchPromise: dispatch } = useIntentDispatcher();\n const space = getSpace(object);\n const [githubToken] = useQuery(space, Filter.type(DataType.AccessToken, { source: 'github.com' }));\n const gistKey = getMeta(object).keys.find(({ source }) => source === 'github.com');\n const [gistUrl, setGistUrl] = useState<string | undefined>();\n\n useEffect(() => {\n const token = githubToken?.token;\n const gistId = gistKey?.id;\n if (!token || !gistId) {\n setGistUrl(undefined);\n return;\n }\n\n const timeout = setTimeout(async () => {\n try {\n const octokit = new Octokit({ auth: githubToken.token });\n const response = await octokit.request('GET /gists/{gist_id}', {\n gist_id: gistId,\n });\n setGistUrl(response.data.html_url);\n } catch (err) {\n log.catch(err);\n setGistUrl(undefined);\n }\n });\n\n return () => clearTimeout(timeout);\n }, [githubToken, gistKey]);\n\n const handleOpenTokenManager = useCallback(\n () => dispatch(createIntent(SettingsAction.Open, { plugin: 'dxos.org/plugin/token-manager' })),\n [],\n );\n\n const [publishing, setPublishing] = useState(false);\n const handlePublish = useCallback(async () => {\n setPublishing(true);\n const octokit = new Octokit({ auth: githubToken.token });\n const source = await object.source.load();\n const filename = object.name ? kebabize(object.name) : 'composer-script';\n const files = { [`${filename}.ts`]: { content: source.content } };\n\n try {\n // TODO(wittjosiah): Factor out to intent.\n const meta = getMeta(object);\n const githubKey = meta.keys.find(({ source }) => source === 'github.com');\n const gistId = githubKey?.id;\n if (gistId) {\n await octokit.request('PATCH /gists/{gist_id}', {\n gist_id: gistId,\n files,\n });\n } else {\n const response = await octokit.request('POST /gists', {\n public: true,\n files,\n });\n if (response.data.id) {\n meta.keys.push({ source: 'github.com', id: response.data.id });\n }\n }\n } finally {\n setPublishing(false);\n }\n }, [object, githubToken]);\n\n return (\n <div className='flex flex-col gap-4 mlb-cardSpacingBlock'>\n <div>\n <h2>{t('script publish settings label')}</h2>\n <p className='text-description text-sm'>{t('script publish settings description')}</p>\n </div>\n {!githubToken && (\n <div className='flex flex-col gap-2'>\n <span>{t('no github token label')}</span>\n <Button onClick={handleOpenTokenManager}>{t('open token manager label')}</Button>\n </div>\n )}\n {githubToken && (\n <div className='flex justify-end gap-2'>\n {gistUrl && <Clipboard.IconButton value={gistUrl} />}\n <Button disabled={publishing} onClick={handlePublish}>\n {t(publishing ? 'publishing label' : 'publish label')}\n </Button>\n </div>\n )}\n </div>\n );\n};\n\n// TODO(wittjosiah): Factor out.\n// From https://stackoverflow.com/a/67243723/2804332\nconst kebabize = (str: string) => str.replace(/[A-Z]+(?![a-z])|[A-Z]/g, ($, ofs) => (ofs ? '-' : '') + $.toLowerCase());\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport React from 'react';\n\nimport { type Credential } from '@dxos/protocols/proto/dxos/halo/credentials';\nimport { useClient } from '@dxos/react-client';\nimport { Button, Select, useTranslation } from '@dxos/react-ui';\nimport { type EditorInputMode, EditorInputModes } from '@dxos/react-ui-editor';\nimport { DeprecatedFormContainer, DeprecatedFormInput } from '@dxos/react-ui-form';\n\nimport { meta } from '../../meta';\nimport { type ScriptSettingsProps } from '../../types';\n\nexport const ScriptPluginSettings = ({ settings }: { settings: ScriptSettingsProps }) => {\n const { t } = useTranslation(meta.id);\n const client = useClient();\n\n // TODO(burdon): Check token.\n const handleAuthenticate = async () => {\n const { identityKey } = client.halo.identity.get()!;\n await client.halo.writeCredentials([\n {\n issuer: identityKey,\n issuanceDate: new Date(),\n subject: {\n id: identityKey,\n assertion: {\n '@type': 'dxos.halo.credentials.ServiceAccess',\n serverName: 'hub.dxos.network',\n serverKey: identityKey,\n identityKey,\n capabilities: ['composer:beta'],\n },\n },\n } satisfies Credential,\n ]);\n };\n\n return (\n <DeprecatedFormContainer>\n {/* TODO(wittjosiah): Hide outside of dev environments. */}\n <DeprecatedFormInput label={t('authenticate action label')}>\n <Button onClick={handleAuthenticate}>{t('authenticate button label')}</Button>\n </DeprecatedFormInput>\n\n <DeprecatedFormInput label={t('editor input mode label')}>\n <Select.Root\n value={settings.editorInputMode ?? 'default'}\n onValueChange={(value) => {\n settings.editorInputMode = value as EditorInputMode;\n }}\n >\n <Select.TriggerButton placeholder={t('select editor input mode placeholder')} />\n <Select.Portal>\n <Select.Content>\n <Select.Viewport>\n {EditorInputModes.map((mode) => (\n <Select.Option key={mode} value={mode}>\n {t(`settings editor input mode ${mode} label`)}\n </Select.Option>\n ))}\n </Select.Viewport>\n </Select.Content>\n </Select.Portal>\n </Select.Root>\n </DeprecatedFormInput>\n </DeprecatedFormContainer>\n );\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport React, { forwardRef, useEffect, useRef, useState } from 'react';\n\nimport { log } from '@dxos/log';\nimport { Avatar, Icon, Input, type ThemedClassName, Toolbar, useTranslation } from '@dxos/react-ui';\nimport { SyntaxHighlighter } from '@dxos/react-ui-syntax-highlighter';\nimport { errorText, mx } from '@dxos/react-ui-theme';\n\nimport { SCRIPT_PLUGIN } from '../../meta';\n\ntype State = 'pending' | 'responding';\n\n/**\n * Request or response.\n */\ntype Message = { type: 'request' | 'response'; text?: string; data?: any; error?: Error };\n\nexport type TestPanelProps = ThemedClassName<{\n functionUrl?: string;\n}>;\n\n// TODO(burdon): Need persistent history (currently lost when switching tabs)..\nexport const TestPanel = ({ classNames, functionUrl }: TestPanelProps) => {\n const { t } = useTranslation(SCRIPT_PLUGIN);\n\n const inputRef = useRef<HTMLInputElement>(null);\n const [input, setInput] = useState('');\n const [result, setResult] = useState('');\n const [state, setState] = useState<State | null>(null);\n\n // TODO(burdon): Persistent history (thread).\n const [history, setHistory] = useState<Message[]>([]);\n\n const scrollerRef = useRef<HTMLDivElement>(null);\n const handleScroll = () => {\n if (scrollerRef.current) {\n scrollerRef.current.scrollTop = scrollerRef.current.scrollHeight;\n }\n };\n\n const controller = useRef<AbortController>();\n useEffect(() => {\n return () => {\n handleStop();\n };\n }, []);\n\n const handleStop = () => {\n controller.current?.abort('stop');\n controller.current = undefined;\n };\n\n const handleClear = () => {\n handleStop();\n setInput('');\n setResult('');\n setHistory([]);\n inputRef.current?.focus();\n };\n\n const handleResponse = ({ text, data, error }: { text?: string; data?: any; error?: Error } = {}) => {\n controller.current = undefined;\n setHistory((history) => [...history, { type: 'response', text, data, error } satisfies Message]);\n setResult('');\n setState(null);\n handleScroll();\n };\n\n const handleRequest = async (input: string) => {\n // Returns a promise that resolves when a value has been received.\n try {\n setState('pending');\n\n let data = null;\n // Detect JSON input.\n if (input.charAt(0) === '{') {\n try {\n const validJsonString = input.replace(/'/g, '\"').replace(/([{,]\\s*)([a-zA-Z0-9_]+)(\\s*:)/g, '$1\"$2\"$3');\n data = JSON.parse(validJsonString);\n input = JSON.stringify(data, null, 2);\n } catch (err) {\n inputRef.current?.focus();\n return;\n }\n }\n\n setInput('');\n setResult('');\n setHistory((history) => [...history, { type: 'request', text: input }]);\n setTimeout(() => {\n handleScroll();\n });\n\n // Throws DOMException when aborted.\n controller.current = new AbortController();\n const response = await fetch(functionUrl!, {\n signal: controller.current.signal,\n method: 'POST',\n body: input,\n headers: {\n 'Content-Type': data ? 'application/json' : 'text/plain',\n },\n });\n\n // Check for error.\n if (!response.ok) {\n const text = await response.text();\n handleResponse({ error: new Error(text || response.statusText || String(response.status)) });\n return;\n }\n\n // Check for JSON.\n const contentType = response.headers.get('content-type');\n if (contentType === 'application/json') {\n const data = await response.json();\n handleResponse({ data });\n return;\n }\n\n // Text (including streaming).\n setState('responding');\n let text = '';\n const reader = response.body!.getReader();\n const pump = async ({ done, value }: ReadableStreamReadResult<Uint8Array>): Promise<void> => {\n text = text + new TextDecoder().decode(value);\n if (!controller.current || done) {\n handleResponse({ text });\n return;\n }\n\n setResult(text);\n setTimeout(() => {\n handleScroll();\n });\n\n return reader.read().then(pump);\n };\n\n void reader\n .read()\n .then(pump)\n .catch((err) => {\n if (err.name !== 'AbortError') {\n log.catch(err);\n }\n });\n } catch (err: any) {\n if (err !== 'stop') {\n const error = err instanceof Error ? err : new Error(err);\n handleResponse({ error });\n log.catch(err);\n } else {\n handleResponse();\n }\n }\n };\n\n return (\n <div className={mx('flex flex-col h-full overflow-hidden', classNames)}>\n {/* TODO(burdon): Replace with Thread. */}\n <MessageThread ref={scrollerRef} state={state} result={result} history={history} />\n {/* TODO(burdon): Replace with Form based on the function's input schema. */}\n <Toolbar.Root classNames='p-2'>\n <Input.Root>\n <Input.TextInput\n ref={inputRef}\n autoFocus\n placeholder={t('function request placeholder')}\n value={input}\n onChange={(ev) => setInput(ev.target.value)}\n onKeyDown={(ev) => ev.key === 'Enter' && handleRequest(input)}\n />\n </Input.Root>\n <Toolbar.Button onClick={() => handleRequest(input)}>\n <Icon icon='ph--play--regular' size={4} />\n </Toolbar.Button>\n <Toolbar.Button onClick={() => (state ? handleStop() : handleClear())}>\n <Icon icon={state ? 'ph--stop--regular' : 'ph--trash--regular'} size={4} />\n </Toolbar.Button>\n </Toolbar.Root>\n </div>\n );\n};\n\n// TODO(burdon): Replace with thread?\n// TODO(burdon): Button to edit/re-run question.\ntype MessageThreadProps = {\n state: State | null;\n history: Message[];\n result: string;\n};\n\nconst MessageThread = forwardRef<HTMLDivElement, MessageThreadProps>(\n ({ state, history, result }: MessageThreadProps, forwardedRef) => {\n return (\n <div ref={forwardedRef} className='flex flex-col gap-6 h-full p-2 overflow-x-hidden overflow-y-auto'>\n {history.map((message, i) => (\n <div key={i} className='grid grid-cols-[2rem_1fr_2rem]'>\n <div className='p-1'>{message.type === 'response' && <RobotAvatar />}</div>\n <div className='overflow-auto'>\n <MessageItem message={message} />\n </div>\n </div>\n ))}\n\n {result?.length > 0 && (\n <div className='grid grid-cols-[2rem_1fr_2rem]'>\n <div className='p-1'>\n {(state === 'pending' && <Icon icon='ph--spinner--regular' size={6} classNames='animate-spin' />) || (\n <Icon icon='ph--robot--regular' size={6} classNames='animate-[pulse_1s_ease-in-out_infinite]' />\n )}\n </div>\n <div className='overflow-auto'>\n <MessageItem message={{ type: 'response', text: result }} />\n </div>\n </div>\n )}\n </div>\n );\n },\n);\n\nconst MessageItem = ({ classNames, message }: ThemedClassName<{ message: Message }>) => {\n const { type, text, data, error } = message;\n const wrapper = 'p-1 px-2 rounded-md bg-hoverSurface overflow-auto';\n return (\n <div className={mx('flex', type === 'request' ? 'ml-[1rem] justify-end' : 'mr-[1rem]', classNames)}>\n {error && <div className={mx(wrapper, 'whitespace-pre', errorText)}>{String(error)}</div>}\n\n {text !== undefined && (\n <div className={mx(wrapper, type === 'request' && 'bg-primary-400 dark:bg-primary-600')}>\n {text || '\\u00D8'}\n </div>\n )}\n\n {data && (\n <SyntaxHighlighter language='json' className={mx(wrapper, 'px-8 py-2 text-xs')}>\n {JSON.stringify(data, null, 2)}\n </SyntaxHighlighter>\n )}\n </div>\n );\n};\n\nconst RobotAvatar = () => (\n <Avatar.Root>\n <Avatar.Content size={6} variant='circle' icon='ph--robot--regular' />\n </Avatar.Root>\n);\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport React from 'react';\n\nimport { type ScriptType } from '@dxos/functions';\nimport { StackItem } from '@dxos/react-ui-stack';\n\nimport { TestPanel } from './TestPanel';\nimport { useDeployState, useToolbarState } from '../../hooks';\n\nexport const TestContainer = ({ script, role }: { script: ScriptType; role: string }) => {\n const state = useToolbarState();\n useDeployState({ state, script });\n return (\n <StackItem.Content role={role}>\n <TestPanel functionUrl={state.functionUrl} />\n </StackItem.Content>\n );\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { lazy } from 'react';\n\nexport * from './Settings';\nexport * from './TestPanel';\nexport { DEPLOYMENT_DIALOG } from './DeploymentDialog';\n\nexport const ScriptContainer = lazy(() => import('./ScriptContainer'));\nexport const DeploymentDialog = lazy(() => import('./DeploymentDialog'));\n"],
5
5
  "mappings": ";;;;;;;;;;;AAIA,SAASA,eAAe;AACxB,OAAOC,SAA2BC,aAAaC,WAAWC,gBAAgB;AAE1E,SAASC,cAAcC,gBAAgBC,2BAA2B;AAClE,SAASC,cAA+BC,kBAAkBC,oCAAoC;AAC9F,SAASC,WAAW;AACpB,SAASC,iBAAiB;AAC1B,SAASC,QAAQC,SAASC,UAAUC,KAAKC,gBAAgB;AACzD,SAASC,QAAQC,WAAWC,OAAOC,oBAAoBC,sBAAsB;AAC7E,SAASC,gBAAgB;;AAQlB,IAAMC,uBAAuB,CAAC,EAAEC,OAAM,MAA6B;;;AACxE,WACE,sBAAA,cAAA,MAAA,UAAA,MACE,sBAAA,cAACC,SAAAA;MAAQD;QACT,sBAAA,cAACE,YAAAA;MAAWF;;;;;AAGlB;AAEO,IAAMG,mBAAmB,CAAC,EAAEH,OAAM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AAE9D,MAAMH,MAAMC,MAAMC,MAAK,IAAK+D;AACpC,UAAMK,UAAU;AAChB,WACE,gBAAA9B,OAAA,cAACC,OAAAA;MAAIC,WAAWC,GAAG,QAAQxC,SAAS,YAAY,0BAA0B,aAAahC,UAAAA;OACpF+B,SAAS,gBAAAsC,OAAA,cAACC,OAAAA;MAAIC,WAAWC,GAAG2B,SAAS,kBAAkBC,SAAAA;OAAahD,OAAOrB,KAAAA,CAAAA,GAE3EF,SAASJ,UACR,gBAAA4C,OAAA,cAACC,OAAAA;MAAIC,WAAWC,GAAG2B,SAASnE,SAAS,aAAa,oCAAA;OAC/CH,QAAQ,MAAA,GAIZC,QACC,gBAAAuC,OAAA,cAACgC,mBAAAA;MAAkBC,UAAS;MAAO/B,WAAWC,GAAG2B,SAAS,mBAAA;OACvD9D,KAAKE,UAAUT,MAAM,MAAM,CAAA,CAAA,CAAA;;;;AAKtC;AAEA,IAAMkE,cAAc,MAAA;;;WAClB,gBAAA3B,OAAA,cAACkC,OAAO3B,MAAI,MACV,gBAAAP,OAAA,cAACkC,OAAOC,SAAO;MAACd,MAAM;MAAGe,SAAQ;MAAShB,MAAK;;;;;;;;;ACrPnD,OAAOiB,YAAW;AAGlB,SAASC,iBAAiB;AAKnB,IAAMC,gBAAgB,CAAC,EAAEC,QAAQC,KAAI,MAAwC;;;AAClF,UAAMC,QAAQC,gBAAAA;AACdC,mBAAe;MAAEF;MAAOF;IAAO,CAAA;AAC/B,WACE,gBAAAK,OAAA,cAACC,UAAUC,SAAO;MAACN;OACjB,gBAAAI,OAAA,cAACG,WAAAA;MAAUC,aAAaP,MAAMO;;;;;AAGpC;;;AChBA,SAASC,YAAY;AAMd,IAAMC,kBAAkBC,KAAK,MAAM,OAAO,gCAAA,CAAA;AAC1C,IAAMC,mBAAmBD,KAAK,MAAM,OAAO,iCAAA,CAAA;",
6
6
  "names": ["Octokit", "React", "useCallback", "useEffect", "useState", "createIntent", "SettingsAction", "useIntentDispatcher", "FunctionType", "getInvocationUrl", "getUserFunctionUrlInMetadata", "log", "useClient", "Filter", "getMeta", "getSpace", "Ref", "useQuery", "Button", "Clipboard", "Input", "useControlledState", "useTranslation", "DataType", "ScriptObjectSettings", "object", "Binding", "Publishing", "ScriptProperties", "t", "useTranslation", "SCRIPT_PLUGIN", "Input", "Root", "Label", "TextInput", "placeholder", "value", "description", "onChange", "event", "target", "client", "useClient", "space", "getSpace", "fn", "useQuery", "Filter", "type", "FunctionType", "source", "Ref", "make", "functionPath", "getUserFunctionUrlInMetadata", "getMeta", "functionUrl", "getInvocationUrl", "config", "values", "runtime", "services", "edge", "url", "spaceId", "id", "binding", "setBinding", "useControlledState", "handleBindingChange", "useCallback", "handleBindingBlur", "div", "role", "className", "h2", "disabled", "name", "Clipboard", "IconButton", "onBlur", "dispatchPromise", "dispatch", "useIntentDispatcher", "githubToken", "DataType", "AccessToken", "gistKey", "keys", "find", "gistUrl", "setGistUrl", "useState", "useEffect", "token", "gistId", "undefined", "timeout", "setTimeout", "octokit", "Octokit", "auth", "response", "request", "gist_id", "data", "html_url", "err", "log", "catch", "clearTimeout", "handleOpenTokenManager", "createIntent", "SettingsAction", "Open", "plugin", "publishing", "setPublishing", "handlePublish", "load", "filename", "kebabize", "files", "content", "meta", "githubKey", "public", "push", "p", "span", "Button", "onClick", "str", "replace", "$", "ofs", "toLowerCase", "React", "useClient", "Button", "Select", "useTranslation", "EditorInputModes", "DeprecatedFormContainer", "DeprecatedFormInput", "ScriptPluginSettings", "settings", "t", "useTranslation", "meta", "id", "client", "useClient", "handleAuthenticate", "identityKey", "halo", "identity", "get", "writeCredentials", "issuer", "issuanceDate", "Date", "subject", "assertion", "serverName", "serverKey", "capabilities", "React", "DeprecatedFormContainer", "DeprecatedFormInput", "label", "Button", "onClick", "Select", "Root", "value", "editorInputMode", "onValueChange", "TriggerButton", "placeholder", "Portal", "Content", "Viewport", "EditorInputModes", "map", "mode", "Option", "key", "React", "forwardRef", "useEffect", "useRef", "useState", "log", "Avatar", "Icon", "Input", "Toolbar", "useTranslation", "SyntaxHighlighter", "errorText", "mx", "TestPanel", "classNames", "functionUrl", "t", "useTranslation", "SCRIPT_PLUGIN", "inputRef", "useRef", "input", "setInput", "useState", "result", "setResult", "state", "setState", "history", "setHistory", "scrollerRef", "handleScroll", "current", "scrollTop", "scrollHeight", "controller", "useEffect", "handleStop", "abort", "undefined", "handleClear", "focus", "handleResponse", "text", "data", "error", "type", "handleRequest", "charAt", "validJsonString", "replace", "JSON", "parse", "stringify", "err", "setTimeout", "AbortController", "response", "fetch", "signal", "method", "body", "headers", "ok", "Error", "statusText", "String", "status", "contentType", "get", "json", "reader", "getReader", "pump", "done", "value", "TextDecoder", "decode", "read", "then", "catch", "name", "log", "React", "div", "className", "mx", "MessageThread", "ref", "Toolbar", "Root", "Input", "TextInput", "autoFocus", "placeholder", "onChange", "ev", "target", "onKeyDown", "key", "Button", "onClick", "Icon", "icon", "size", "forwardRef", "forwardedRef", "map", "message", "i", "RobotAvatar", "MessageItem", "length", "wrapper", "errorText", "SyntaxHighlighter", "language", "Avatar", "Content", "variant", "React", "StackItem", "TestContainer", "script", "role", "state", "useToolbarState", "useDeployState", "React", "StackItem", "Content", "TestPanel", "functionUrl", "lazy", "ScriptContainer", "lazy", "DeploymentDialog"]
7
7
  }
@@ -9,11 +9,11 @@ import {
9
9
  ScriptProperties,
10
10
  TestContainer,
11
11
  TestPanel
12
- } from "./chunk-OMQLWT6X.mjs";
12
+ } from "./chunk-3JLR2SHJ.mjs";
13
13
  import {
14
14
  DEPLOYMENT_DIALOG
15
15
  } from "./chunk-LA66DQGU.mjs";
16
- import "./chunk-I6S7QLGR.mjs";
16
+ import "./chunk-3FU4QZVP.mjs";
17
17
  import "./chunk-QJH7I2UV.mjs";
18
18
  import {
19
19
  ScriptAction
@@ -29,8 +29,8 @@ import { lazy } from "@dxos/app-framework";
29
29
  var AppGraphBuilder = lazy(() => import("./app-graph-builder-5Z3MUX4N.mjs"));
30
30
  var ArtifactDefinition = lazy(() => import("./artifact-definition-A4TBQL75.mjs"));
31
31
  var Compiler = lazy(() => import("./compiler-W4BYJYTL.mjs"));
32
- var IntentResolver = lazy(() => import("./intent-resolver-52BWIOT6.mjs"));
33
- var ReactSurface = lazy(() => import("./react-surface-3V4HK2LR.mjs"));
32
+ var IntentResolver = lazy(() => import("./intent-resolver-JOJNH4UX.mjs"));
33
+ var ReactSurface = lazy(() => import("./react-surface-7BKUWL2U.mjs"));
34
34
  var ScriptSettings = lazy(() => import("./settings-Z22D6JVJ.mjs"));
35
35
 
36
36
  // packages/plugins/plugin-script/src/ScriptPlugin.tsx
@@ -50,12 +50,16 @@ import { defineEvent } from "@dxos/app-framework";
50
50
  var ScriptEvents;
51
51
 
52
52
  // packages/plugins/plugin-script/src/translations.ts
53
+ import { Type } from "@dxos/echo";
53
54
  import { ScriptType } from "@dxos/functions";
54
55
  var translations_default = [
55
56
  {
56
57
  "en-US": {
57
- [ScriptType.typename]: {
58
+ [Type.getTypename(ScriptType)]: {
58
59
  "typename label": "Script",
60
+ "typename label_zero": "Scripts",
61
+ "typename label_one": "Script",
62
+ "typename label_other": "Scripts",
59
63
  "object name placeholder": "New script"
60
64
  },
61
65
  [SCRIPT_PLUGIN]: {