@dxos/plugin-script 0.8.3-main.7f5a14c → 0.8.3-staging.0fa589b
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.
- package/dist/lib/browser/{ScriptContainer-BQS7LDI7.mjs → ScriptContainer-RSN52NH7.mjs} +6 -8
- package/dist/lib/browser/ScriptContainer-RSN52NH7.mjs.map +7 -0
- package/dist/lib/browser/{chunk-I6S7QLGR.mjs → chunk-3FU4QZVP.mjs} +2 -2
- package/dist/lib/browser/{chunk-I6S7QLGR.mjs.map → chunk-3FU4QZVP.mjs.map} +1 -1
- package/dist/lib/browser/{chunk-OMQLWT6X.mjs → chunk-3JLR2SHJ.mjs} +6 -6
- package/dist/lib/browser/{chunk-OMQLWT6X.mjs.map → chunk-3JLR2SHJ.mjs.map} +1 -1
- package/dist/lib/browser/index.mjs +9 -5
- package/dist/lib/browser/index.mjs.map +3 -3
- package/dist/lib/browser/{intent-resolver-52BWIOT6.mjs → intent-resolver-JOJNH4UX.mjs} +3 -3
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/browser/{react-surface-3V4HK2LR.mjs → react-surface-7BKUWL2U.mjs} +4 -4
- package/dist/lib/browser/{react-surface-3V4HK2LR.mjs.map → react-surface-7BKUWL2U.mjs.map} +3 -3
- package/dist/lib/node/{ScriptContainer-OYFP6E5B.cjs → ScriptContainer-CAC7AISY.cjs} +22 -24
- package/dist/lib/node/ScriptContainer-CAC7AISY.cjs.map +7 -0
- package/dist/lib/node/{chunk-GUNGYAZU.cjs → chunk-AU2FOE26.cjs} +5 -5
- package/dist/lib/node/{chunk-GUNGYAZU.cjs.map → chunk-AU2FOE26.cjs.map} +1 -1
- package/dist/lib/node/{chunk-WHXKN26U.cjs → chunk-OSBMUJ4T.cjs} +11 -11
- package/dist/lib/node/{chunk-WHXKN26U.cjs.map → chunk-OSBMUJ4T.cjs.map} +1 -1
- package/dist/lib/node/index.cjs +16 -12
- package/dist/lib/node/index.cjs.map +3 -3
- package/dist/lib/node/{intent-resolver-UEBRMMP6.cjs → intent-resolver-BQ2NKEM7.cjs} +9 -9
- package/dist/lib/node/meta.json +1 -1
- package/dist/lib/node/{react-surface-AYOFUM7K.cjs → react-surface-EUKPDFU3.cjs} +13 -13
- package/dist/lib/node/{react-surface-AYOFUM7K.cjs.map → react-surface-EUKPDFU3.cjs.map} +3 -3
- package/dist/lib/node-esm/{ScriptContainer-G35TAL5S.mjs → ScriptContainer-4IOOIPBF.mjs} +6 -8
- package/dist/lib/node-esm/ScriptContainer-4IOOIPBF.mjs.map +7 -0
- package/dist/lib/node-esm/{chunk-AOI67UC7.mjs → chunk-B4TP3LSZ.mjs} +6 -6
- package/dist/lib/node-esm/{chunk-AOI67UC7.mjs.map → chunk-B4TP3LSZ.mjs.map} +1 -1
- package/dist/lib/node-esm/{chunk-T43WW6DG.mjs → chunk-W2DAXWHA.mjs} +2 -2
- package/dist/lib/node-esm/{chunk-T43WW6DG.mjs.map → chunk-W2DAXWHA.mjs.map} +1 -1
- package/dist/lib/node-esm/index.mjs +9 -5
- package/dist/lib/node-esm/index.mjs.map +3 -3
- package/dist/lib/node-esm/{intent-resolver-QEVLFH3G.mjs → intent-resolver-HTM5PSRZ.mjs} +3 -3
- package/dist/lib/node-esm/meta.json +1 -1
- package/dist/lib/node-esm/{react-surface-XNNTCP2O.mjs → react-surface-6UO64YOS.mjs} +4 -4
- package/dist/lib/node-esm/{react-surface-XNNTCP2O.mjs.map → react-surface-6UO64YOS.mjs.map} +3 -3
- package/dist/types/src/components/ScriptToolbar/ScriptToolbar.d.ts.map +1 -1
- package/dist/types/src/components/TypescriptEditor/TypescriptEditor.d.ts.map +1 -1
- package/dist/types/src/hooks/deploy.d.ts +11 -13
- package/dist/types/src/hooks/deploy.d.ts.map +1 -1
- package/dist/types/src/translations.d.ts +116 -2
- package/dist/types/src/translations.d.ts.map +1 -1
- package/dist/types/src/types.d.ts +3 -4
- package/dist/types/src/types.d.ts.map +1 -1
- package/package.json +49 -49
- package/src/capabilities/react-surface.tsx +1 -1
- package/src/components/ScriptToolbar/ScriptToolbar.tsx +5 -8
- package/src/components/Settings/ScriptObjectSettings.tsx +2 -2
- package/src/components/TestPanel/TestPanel.tsx +1 -1
- package/src/components/TypescriptEditor/TypescriptEditor.tsx +2 -0
- package/src/templates/gmail.ts +1 -1
- package/src/translations.ts +5 -1
- package/dist/lib/browser/ScriptContainer-BQS7LDI7.mjs.map +0 -7
- package/dist/lib/node/ScriptContainer-OYFP6E5B.cjs.map +0 -7
- package/dist/lib/node-esm/ScriptContainer-G35TAL5S.mjs.map +0 -7
- /package/dist/lib/browser/{intent-resolver-52BWIOT6.mjs.map → intent-resolver-JOJNH4UX.mjs.map} +0 -0
- /package/dist/lib/node/{intent-resolver-UEBRMMP6.cjs.map → intent-resolver-BQ2NKEM7.cjs.map} +0 -0
- /package/dist/lib/node-esm/{intent-resolver-QEVLFH3G.mjs.map → intent-resolver-HTM5PSRZ.mjs.map} +0 -0
|
@@ -26,13 +26,13 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
26
26
|
mod
|
|
27
27
|
));
|
|
28
28
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
-
var
|
|
30
|
-
__export(
|
|
29
|
+
var ScriptContainer_CAC7AISY_exports = {};
|
|
30
|
+
__export(ScriptContainer_CAC7AISY_exports, {
|
|
31
31
|
ScriptContainer: () => ScriptContainer,
|
|
32
32
|
default: () => ScriptContainer_default
|
|
33
33
|
});
|
|
34
|
-
module.exports = __toCommonJS(
|
|
35
|
-
var
|
|
34
|
+
module.exports = __toCommonJS(ScriptContainer_CAC7AISY_exports);
|
|
35
|
+
var import_chunk_AU2FOE26 = require("./chunk-AU2FOE26.cjs");
|
|
36
36
|
var import_chunk_YO5W2IPQ = require("./chunk-YO5W2IPQ.cjs");
|
|
37
37
|
var import_chunk_HCRW6T3G = require("./chunk-HCRW6T3G.cjs");
|
|
38
38
|
var import_chunk_QG2X6J74 = require("./chunk-QG2X6J74.cjs");
|
|
@@ -47,11 +47,11 @@ var import_rx_react = require("@effect-rx/rx-react");
|
|
|
47
47
|
var import_react2 = __toESM(require("react"));
|
|
48
48
|
var import_echo2 = require("@dxos/react-client/echo");
|
|
49
49
|
var import_react_ui = require("@dxos/react-ui");
|
|
50
|
-
var import_react_ui_editor2 = require("@dxos/react-ui-editor");
|
|
51
50
|
var import_react_ui_menu = require("@dxos/react-ui-menu");
|
|
52
51
|
var import_tracking3 = require("@preact-signals/safe-react/tracking");
|
|
53
52
|
var import_lang_javascript = require("@codemirror/lang-javascript");
|
|
54
53
|
var import_language = require("@codemirror/language");
|
|
54
|
+
var import_lint = require("@codemirror/lint");
|
|
55
55
|
var import_state = require("@codemirror/state");
|
|
56
56
|
var import_theme_one_dark = require("@codemirror/theme-one-dark");
|
|
57
57
|
var import_view = require("@codemirror/view");
|
|
@@ -60,14 +60,14 @@ var import_codemirror_continue = require("@valtown/codemirror-continue");
|
|
|
60
60
|
var import_codemirror_ts = require("@valtown/codemirror-ts");
|
|
61
61
|
var import_react3 = __toESM(require("react"));
|
|
62
62
|
var import_react_ui2 = require("@dxos/react-ui");
|
|
63
|
-
var
|
|
63
|
+
var import_react_ui_editor2 = require("@dxos/react-ui-editor");
|
|
64
64
|
var import_react_ui_theme = require("@dxos/react-ui-theme");
|
|
65
65
|
var import_util = require("@dxos/util");
|
|
66
66
|
var createToolbar = ({ state, script, ...options }) => import_rx_react.Rx.make((get) => get((0, import_react_ui_menu.rxFromSignal)(() => {
|
|
67
|
-
const templateSelect = (0,
|
|
68
|
-
const format = (0,
|
|
67
|
+
const templateSelect = (0, import_chunk_AU2FOE26.createTemplateSelect)(script);
|
|
68
|
+
const format = (0, import_chunk_AU2FOE26.createFormat)(script);
|
|
69
69
|
const gap = (0, import_react_ui_menu.createGapSeparator)();
|
|
70
|
-
const deploy = (0,
|
|
70
|
+
const deploy = (0, import_chunk_AU2FOE26.createDeploy)({
|
|
71
71
|
state,
|
|
72
72
|
script,
|
|
73
73
|
...options
|
|
@@ -91,7 +91,7 @@ var ScriptToolbar = ({ script, role, state, classNames }) => {
|
|
|
91
91
|
var _effect = (0, import_tracking2.useSignals)();
|
|
92
92
|
try {
|
|
93
93
|
const { t } = (0, import_react_ui.useTranslation)(import_chunk_QG2X6J74.SCRIPT_PLUGIN);
|
|
94
|
-
const options = (0,
|
|
94
|
+
const options = (0, import_chunk_AU2FOE26.useDeployDeps)({
|
|
95
95
|
script
|
|
96
96
|
});
|
|
97
97
|
const toolbarCreator = (0, import_react2.useMemo)(() => createToolbar({
|
|
@@ -106,17 +106,14 @@ var ScriptToolbar = ({ script, role, state, classNames }) => {
|
|
|
106
106
|
t
|
|
107
107
|
]);
|
|
108
108
|
const menu = (0, import_react_ui_menu.useMenuActions)(toolbarCreator);
|
|
109
|
-
return /* @__PURE__ */ import_react2.default.createElement(
|
|
110
|
-
role: "none",
|
|
111
|
-
className: (0, import_react_ui_editor2.stackItemContentToolbarClassNames)(role)
|
|
112
|
-
}, /* @__PURE__ */ import_react2.default.createElement(import_react_ui.ElevationProvider, {
|
|
109
|
+
return /* @__PURE__ */ import_react2.default.createElement(import_react_ui.ElevationProvider, {
|
|
113
110
|
elevation: role === "section" ? "positioned" : "base"
|
|
114
111
|
}, /* @__PURE__ */ import_react2.default.createElement(import_react_ui_menu.MenuProvider, {
|
|
115
112
|
...menu,
|
|
116
113
|
attendableId: (0, import_echo2.fullyQualifiedId)(script)
|
|
117
114
|
}, /* @__PURE__ */ import_react2.default.createElement(import_react_ui_menu.ToolbarMenu, {
|
|
118
115
|
classNames
|
|
119
|
-
})))
|
|
116
|
+
})));
|
|
120
117
|
} finally {
|
|
121
118
|
_effect.f();
|
|
122
119
|
}
|
|
@@ -125,14 +122,14 @@ var TypescriptEditor = ({ classNames, id, inputMode = "vscode", toolbar, env, in
|
|
|
125
122
|
var _effect = (0, import_tracking3.useSignals)();
|
|
126
123
|
try {
|
|
127
124
|
const { themeMode } = (0, import_react_ui2.useThemeContext)();
|
|
128
|
-
const { parentRef, focusAttributes } = (0,
|
|
125
|
+
const { parentRef, focusAttributes } = (0, import_react_ui_editor2.useTextEditor)(() => ({
|
|
129
126
|
id,
|
|
130
127
|
initialValue,
|
|
131
128
|
selection,
|
|
132
129
|
scrollTo,
|
|
133
130
|
extensions: [
|
|
134
131
|
extensions,
|
|
135
|
-
(0,
|
|
132
|
+
(0, import_react_ui_editor2.createBasicExtensions)({
|
|
136
133
|
highlightActiveLine: true,
|
|
137
134
|
indentWithTab: true,
|
|
138
135
|
lineNumbers: true,
|
|
@@ -140,12 +137,12 @@ var TypescriptEditor = ({ classNames, id, inputMode = "vscode", toolbar, env, in
|
|
|
140
137
|
monospace: true,
|
|
141
138
|
scrollPastEnd: true
|
|
142
139
|
}),
|
|
143
|
-
(0,
|
|
140
|
+
(0, import_react_ui_editor2.createThemeExtensions)({
|
|
144
141
|
themeMode,
|
|
145
142
|
syntaxHighlighting: true
|
|
146
143
|
}),
|
|
147
|
-
|
|
148
|
-
(0,
|
|
144
|
+
import_react_ui_editor2.InputModeExtensions[inputMode],
|
|
145
|
+
(0, import_react_ui_editor2.folding)(),
|
|
149
146
|
// Continues block comments when pressing Enter.
|
|
150
147
|
import_state.Prec.high(import_view.keymap.of(import_codemirror_continue.continueKeymap)),
|
|
151
148
|
// TODO(burdon): Factor out.
|
|
@@ -153,11 +150,12 @@ var TypescriptEditor = ({ classNames, id, inputMode = "vscode", toolbar, env, in
|
|
|
153
150
|
typescript: true
|
|
154
151
|
}),
|
|
155
152
|
// https://github.com/val-town/codemirror-ts
|
|
156
|
-
(0,
|
|
153
|
+
(0, import_react_ui_editor2.autocomplete)({
|
|
157
154
|
override: env ? [
|
|
158
155
|
(0, import_codemirror_ts.tsAutocomplete)()
|
|
159
156
|
] : void 0
|
|
160
157
|
}),
|
|
158
|
+
import_view.keymap.of(import_lint.lintKeymap),
|
|
161
159
|
env && [
|
|
162
160
|
import_codemirror_ts.tsFacet.of({
|
|
163
161
|
env,
|
|
@@ -226,8 +224,8 @@ var ScriptContainer = ({ role, script, settings = {
|
|
|
226
224
|
try {
|
|
227
225
|
const identity = (0, import_halo.useIdentity)();
|
|
228
226
|
const space = (0, import_echo.getSpace)(script);
|
|
229
|
-
const state = (0,
|
|
230
|
-
(0,
|
|
227
|
+
const state = (0, import_chunk_AU2FOE26.useToolbarState)();
|
|
228
|
+
(0, import_chunk_AU2FOE26.useDeployState)({
|
|
231
229
|
state,
|
|
232
230
|
script
|
|
233
231
|
});
|
|
@@ -277,4 +275,4 @@ var ScriptContainer_default = ScriptContainer;
|
|
|
277
275
|
0 && (module.exports = {
|
|
278
276
|
ScriptContainer
|
|
279
277
|
});
|
|
280
|
-
//# sourceMappingURL=ScriptContainer-
|
|
278
|
+
//# sourceMappingURL=ScriptContainer-CAC7AISY.cjs.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: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C,QAAQG,YAAYf,MAAM;AAC1CzG,mBAAOyH,UAAU;UACnB;QACF;MACF,CAAA;UACAC,6CAAqB;QACnBvF,IAAInC,OAAOmC;QACXsE,UAAMkB,+BAAkB3H,OAAOoH,OAAOC,QAAQ;UAAC;SAAU;QACzDL;QACAF;MACF,CAAA;QAEF,CAAA,GACN;MAACA;MAAUE;MAAOhH;MAAQA,OAAOoH,OAAOC;KAAO;AAGjD,WACE1F,6BAAAA,QAAA,cAACiG,gCAAUC,SAAO;MAACxF,SAAAA;OACjBV,6BAAAA,QAAA,cAACX,eAAAA;MAAcjB;MAAckB;MAAYjB;QACzC2B,6BAAAA,QAAA,cAACO,kBAAAA;MACCC,IAAInC,OAAOmC;MACXG;MACAC,cAAcvC,OAAOoH,QAAQC,QAAQG;MACrChF;MACAtB,gBAAY4G,yDAAiC7G,IAAAA;MAC7CmB,WAAWwE,SAASC;MACpBxE,SAAAA;;;;;AAIR;AAEA,IAAA,0BAAesE;",
|
|
6
|
+
"names": ["import_react", "import_echo", "import_react_ui", "import_react_ui_editor", "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", "React", "ElevationProvider", "elevation", "MenuProvider", "attendableId", "fullyQualifiedId", "ToolbarMenu", "TypescriptEditor", "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", "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", "settings", "editorInputMode", "identity", "useIdentity", "space", "getSpace", "useToolbarState", "useDeployState", "source", "target", "listener", "onChange", "content", "changed", "createDataExtensions", "createDocAccessor", "StackItem", "Content", "stackItemContentEditorClassNames"]
|
|
7
|
+
}
|
|
@@ -26,8 +26,8 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
26
26
|
mod
|
|
27
27
|
));
|
|
28
28
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
-
var
|
|
30
|
-
__export(
|
|
29
|
+
var chunk_AU2FOE26_exports = {};
|
|
30
|
+
__export(chunk_AU2FOE26_exports, {
|
|
31
31
|
createDeploy: () => createDeploy,
|
|
32
32
|
createFormat: () => createFormat,
|
|
33
33
|
createTemplateSelect: () => createTemplateSelect,
|
|
@@ -36,7 +36,7 @@ __export(chunk_GUNGYAZU_exports, {
|
|
|
36
36
|
useDeployState: () => useDeployState,
|
|
37
37
|
useToolbarState: () => useToolbarState
|
|
38
38
|
});
|
|
39
|
-
module.exports = __toCommonJS(
|
|
39
|
+
module.exports = __toCommonJS(chunk_AU2FOE26_exports);
|
|
40
40
|
var import_chunk_YO5W2IPQ = require("./chunk-YO5W2IPQ.cjs");
|
|
41
41
|
var import_chunk_QG2X6J74 = require("./chunk-QG2X6J74.cjs");
|
|
42
42
|
var import_react = require("react");
|
|
@@ -199,7 +199,7 @@ var echo_default = "//\n// Copyright 2024 DXOS.org\n//\n\n/**\n * Echos the requ
|
|
|
199
199
|
var email_default = "//\n// Copyright 2024 DXOS.org\n//\n\n/**\n * Appends a message to the end of a Document configured through a trigger.\n * Trigger must have a targetDocumentId field set in Meta.\n */\nexport default async ({ 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";
|
|
200
200
|
var forex_effect_default = "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { S, defineFunction } from 'dxos:functions';\nimport {\n HttpClient,\n HttpClientRequest,\n FetchHttpClient,\n // @ts-ignore\n} from 'https://esm.sh/@effect/platform@0.77.2?deps=effect@3.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";
|
|
201
201
|
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";
|
|
202
|
-
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.
|
|
202
|
+
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";
|
|
203
203
|
var removeHeader = (str) => str.split("\n").slice(4).join("\n");
|
|
204
204
|
var templates = [
|
|
205
205
|
{
|
|
@@ -366,4 +366,4 @@ var createTemplateSelect = (script) => {
|
|
|
366
366
|
useDeployState,
|
|
367
367
|
useToolbarState
|
|
368
368
|
});
|
|
369
|
-
//# sourceMappingURL=chunk-
|
|
369
|
+
//# sourceMappingURL=chunk-AU2FOE26.cjs.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,mBAAmC;AAEnC,uBAA4E;AAC5E,iBAAoB;AACpB,0BAAuC;AACvC,kBAAoE;AAEpE,2BAAiC;AACjC,4BAAmC;AWRnC,IAAAA,gBAAwB;AAExB,yBAAqB;ACFrB,sBAAuB;AACvB,oBAAiC;AACjC,wBAAqC;AAGrC,IAAAC,cAAoB;AACpB,IAAAC,wBAAiC;ACNjC,IAAAC,oBAA2D;AAC3D,IAAAC,sBAAwB;AACxB,IAAAF,wBAAsD;;Ab8B/C,IAAMG,eAAe,CAAC,EAAEC,OAAOC,QAAQC,OAAOC,IAAIC,QAAQC,qBAAqBC,EAAC,MAAuB;AAE5G,QAAMC,gBAAYC,uCAAiB,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,mBAAeT,uCACnB,UACA,YAAA;AACE,QAAI,CAACP,OAAOiB,UAAU,CAAChB,OAAO;AAC5B;IACF;AAEAF,UAAMU,QAAQS;AACdnB,UAAMoB,YAAY;AAElB,UAAMC,SAAS,UAAMC,oCAAa;MAAErB;MAAQG;MAAQF;MAAOC;MAAIE;IAAoB,CAAA;AAEnF,QAAI,CAACgB,OAAOE,SAAS;AACnBC,qBAAIC,MAAMJ,OAAOX,OAAK,QAAA;;;;;;AACtBV,YAAMU,QAAQJ,EAAE,qBAAA;IAClB;AAEAN,UAAMoB,YAAY;EACpB,GACA;IACEM,MAAM;IACNjB,OAAO;MAACT,MAAMoB,YAAY,kBAAkB;MAAgB;QAAET,IAAIC;MAAc;;IAChFC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AWqF,2CAAAA;AAClE,UAAIH,kBAAkB,GAAG;AACvBF,iBAASM,OAAOJ,gBAAgB,CAAA;MAClC;AACA,UAAIH,SAASzB,UAAU;AACrB0B,iBAASO,KAAK;UAAEvF,QAAQqF;UAA2BrC,IAAI+B,SAASzB;QAAS,CAAA;MAC3E;IACF,GACA;MACE/D,OAAOwF,SAAS9B;MAChBuC,OAAOT,SAAS/B;MAChBxC,MAAM;IACR,CAAA;EAEJ,CAAA;AACF;AAEO,IAAMiF,uBAAuB,CAAC1G,WAAAA;AACnC,QAAM2G,sBAAsBhB,0BAAAA;AAC5B,QAAMiB,wBAAwBd,4BAA4B9F,MAAAA;AAC1D,SAAO;IACLgC,OAAO;MAAC2E;SAAwBC;;IAChC3E,OAAO;MACL;QAAEhB,QAAQ;QAAQiB,QAAQ;MAAkB;SACzC0E,sBAAsBb,IAAI,CAACc,YAAY;QAAE5F,QAAQ;QAAmBiB,QAAQ2E,OAAO5C;MAAG,EAAA;;EAE7F;AACF;",
|
|
6
6
|
"names": ["import_react", "import_log", "import_react_ui_menu", "import_functions", "import_live_object", "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", "echo", "forex", "forexEffect", "chat", "presetId", "chess", "email", "discord", "gmail", "dataGenerator", "useToolbarState", "initialState", "live", "createFormat", "formatAction", "content", "format", "parser", "plugins", "prettierPluginEstree", "prettierPluginTypescript", "semi", "singleQuote", "err", "createTemplateSelectGroup", "createMenuItemGroup", "variant", "createTemplateSelectActions", "map", "template", "metaKeys", "keys", "oldPresetIndex", "findIndex", "key", "FUNCTIONS_PRESET_META_KEY", "splice", "push", "value", "createTemplateSelect", "templateSelectGroup", "templateSelectActions", "action"]
|
|
7
7
|
}
|
|
@@ -26,8 +26,8 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
26
26
|
mod
|
|
27
27
|
));
|
|
28
28
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
-
var
|
|
30
|
-
__export(
|
|
29
|
+
var chunk_OSBMUJ4T_exports = {};
|
|
30
|
+
__export(chunk_OSBMUJ4T_exports, {
|
|
31
31
|
DeploymentDialog: () => DeploymentDialog,
|
|
32
32
|
ScriptContainer: () => ScriptContainer,
|
|
33
33
|
ScriptObjectSettings: () => ScriptObjectSettings,
|
|
@@ -36,8 +36,8 @@ __export(chunk_WHXKN26U_exports, {
|
|
|
36
36
|
TestContainer: () => TestContainer,
|
|
37
37
|
TestPanel: () => TestPanel
|
|
38
38
|
});
|
|
39
|
-
module.exports = __toCommonJS(
|
|
40
|
-
var
|
|
39
|
+
module.exports = __toCommonJS(chunk_OSBMUJ4T_exports);
|
|
40
|
+
var import_chunk_AU2FOE26 = require("./chunk-AU2FOE26.cjs");
|
|
41
41
|
var import_chunk_QG2X6J74 = require("./chunk-QG2X6J74.cjs");
|
|
42
42
|
var import_tracking = require("@preact-signals/safe-react/tracking");
|
|
43
43
|
var import_core = require("@octokit/core");
|
|
@@ -123,7 +123,7 @@ var Binding = ({ object }) => {
|
|
|
123
123
|
}
|
|
124
124
|
return /* @__PURE__ */ import_react.default.createElement("div", {
|
|
125
125
|
role: "form",
|
|
126
|
-
className: "flex flex-col
|
|
126
|
+
className: "flex flex-col gap-2 mlb-cardSpacingBlock"
|
|
127
127
|
}, /* @__PURE__ */ import_react.default.createElement("h2", null, t("remote function settings heading")), /* @__PURE__ */ import_react.default.createElement(import_react_ui.Input.Root, null, /* @__PURE__ */ import_react.default.createElement("div", {
|
|
128
128
|
role: "none",
|
|
129
129
|
className: "flex flex-col gap-1"
|
|
@@ -238,7 +238,7 @@ var Publishing = ({ object }) => {
|
|
|
238
238
|
githubToken
|
|
239
239
|
]);
|
|
240
240
|
return /* @__PURE__ */ import_react.default.createElement("div", {
|
|
241
|
-
className: "flex flex-col
|
|
241
|
+
className: "flex flex-col gap-4 mlb-cardSpacingBlock"
|
|
242
242
|
}, /* @__PURE__ */ import_react.default.createElement("div", null, /* @__PURE__ */ import_react.default.createElement("h2", null, t("script publish settings label")), /* @__PURE__ */ import_react.default.createElement("p", {
|
|
243
243
|
className: "text-description text-sm"
|
|
244
244
|
}, t("script publish settings description"))), !githubToken && /* @__PURE__ */ import_react.default.createElement("div", {
|
|
@@ -521,7 +521,7 @@ var MessageItem = ({ classNames, message }) => {
|
|
|
521
521
|
var _effect = (0, import_tracking3.useSignals)();
|
|
522
522
|
try {
|
|
523
523
|
const { type, text, data, error } = message;
|
|
524
|
-
const wrapper = "p-1 px-2 rounded-
|
|
524
|
+
const wrapper = "p-1 px-2 rounded-md bg-hoverSurface overflow-auto";
|
|
525
525
|
return /* @__PURE__ */ import_react3.default.createElement("div", {
|
|
526
526
|
className: (0, import_react_ui_theme.mx)("flex", type === "request" ? "ml-[1rem] justify-end" : "mr-[1rem]", classNames)
|
|
527
527
|
}, error && /* @__PURE__ */ import_react3.default.createElement("div", {
|
|
@@ -551,8 +551,8 @@ var RobotAvatar = () => {
|
|
|
551
551
|
var TestContainer = ({ script, role }) => {
|
|
552
552
|
var _effect = (0, import_tracking4.useSignals)();
|
|
553
553
|
try {
|
|
554
|
-
const state = (0,
|
|
555
|
-
(0,
|
|
554
|
+
const state = (0, import_chunk_AU2FOE26.useToolbarState)();
|
|
555
|
+
(0, import_chunk_AU2FOE26.useDeployState)({
|
|
556
556
|
state,
|
|
557
557
|
script
|
|
558
558
|
});
|
|
@@ -565,7 +565,7 @@ var TestContainer = ({ script, role }) => {
|
|
|
565
565
|
_effect.f();
|
|
566
566
|
}
|
|
567
567
|
};
|
|
568
|
-
var ScriptContainer = (0, import_react5.lazy)(() => import("./ScriptContainer-
|
|
568
|
+
var ScriptContainer = (0, import_react5.lazy)(() => import("./ScriptContainer-CAC7AISY.cjs"));
|
|
569
569
|
var DeploymentDialog = (0, import_react5.lazy)(() => import("./DeploymentDialog-C3EEYGRH.cjs"));
|
|
570
570
|
// Annotate the CommonJS export names for ESM import in node:
|
|
571
571
|
0 && (module.exports = {
|
|
@@ -577,4 +577,4 @@ var DeploymentDialog = (0, import_react5.lazy)(() => import("./DeploymentDialog-
|
|
|
577
577
|
TestContainer,
|
|
578
578
|
TestPanel
|
|
579
579
|
});
|
|
580
|
-
//# sourceMappingURL=chunk-
|
|
580
|
+
//# sourceMappingURL=chunk-OSBMUJ4T.cjs.map
|