@dxos/plugin-script 0.8.2-main.5885341 → 0.8.2-main.600d381
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/{DeploymentDialog-QEKJ54ZB.mjs → DeploymentDialog-W7PY33VN.mjs} +4 -4
- package/dist/lib/browser/{ScriptContainer-ATBYTIFH.mjs → ScriptContainer-FL5IQIOY.mjs} +30 -17
- package/dist/lib/browser/ScriptContainer-FL5IQIOY.mjs.map +7 -0
- package/dist/lib/browser/{artifact-definition-OEDM2SCN.mjs → artifact-definition-PD4UAAQZ.mjs} +41 -35
- package/dist/lib/browser/artifact-definition-PD4UAAQZ.mjs.map +7 -0
- package/dist/lib/browser/chunk-6MLJJI73.mjs +40 -0
- package/dist/lib/browser/chunk-6MLJJI73.mjs.map +7 -0
- package/dist/lib/browser/{chunk-EGDYE5MW.mjs → chunk-EYYIND3U.mjs} +81 -150
- package/dist/lib/browser/chunk-EYYIND3U.mjs.map +7 -0
- package/dist/lib/browser/chunk-GTJJTVTQ.mjs +87 -0
- package/dist/lib/browser/chunk-GTJJTVTQ.mjs.map +7 -0
- package/dist/lib/browser/{chunk-SXS6PUU5.mjs → chunk-INL55MFV.mjs} +7 -6
- package/dist/lib/browser/chunk-INL55MFV.mjs.map +7 -0
- package/dist/lib/browser/{chunk-QNXJNXQZ.mjs → chunk-IUOZNPZF.mjs} +6 -6
- package/dist/lib/browser/chunk-IUOZNPZF.mjs.map +7 -0
- package/dist/lib/browser/{chunk-OZEMT3NO.mjs → chunk-YNOCAJYT.mjs} +2 -2
- package/dist/lib/browser/chunk-YNOCAJYT.mjs.map +7 -0
- package/dist/lib/browser/index.mjs +12 -12
- package/dist/lib/browser/index.mjs.map +3 -3
- package/dist/lib/browser/{intent-resolver-C5D6TNPC.mjs → intent-resolver-E7HKIGR3.mjs} +11 -11
- package/dist/lib/browser/intent-resolver-E7HKIGR3.mjs.map +7 -0
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/browser/{react-surface-XJCN7XXF.mjs → react-surface-WPZCULNC.mjs} +8 -8
- package/dist/lib/browser/react-surface-WPZCULNC.mjs.map +7 -0
- package/dist/lib/browser/{settings-NK4XVS2E.mjs → settings-EOKSUGB6.mjs} +2 -2
- package/dist/lib/browser/types.mjs +1 -1
- package/dist/lib/node/{DeploymentDialog-NUKZNILK.cjs → DeploymentDialog-43SI7XFL.cjs} +9 -9
- package/dist/lib/node/{DeploymentDialog-NUKZNILK.cjs.map → DeploymentDialog-43SI7XFL.cjs.map} +2 -2
- package/dist/lib/node/{ScriptContainer-OHHMLPUE.cjs → ScriptContainer-EQFJBC66.cjs} +30 -19
- package/dist/lib/node/ScriptContainer-EQFJBC66.cjs.map +7 -0
- package/dist/lib/node/{artifact-definition-SEGATFNH.cjs → artifact-definition-C644EAYM.cjs} +47 -41
- package/dist/lib/node/artifact-definition-C644EAYM.cjs.map +7 -0
- package/dist/lib/node/{chunk-UUGLBCMY.cjs → chunk-57MPT7DU.cjs} +85 -152
- package/dist/lib/node/chunk-57MPT7DU.cjs.map +7 -0
- package/dist/lib/node/chunk-DGFQHBA7.cjs +91 -0
- package/dist/lib/node/chunk-DGFQHBA7.cjs.map +7 -0
- package/dist/lib/node/{chunk-DSFCLQ5F.cjs → chunk-K7PPLRVQ.cjs} +12 -11
- package/dist/lib/node/chunk-K7PPLRVQ.cjs.map +7 -0
- package/dist/lib/node/{chunk-PGEGRJP3.cjs → chunk-SXJGHLK6.cjs} +16 -17
- package/dist/lib/node/chunk-SXJGHLK6.cjs.map +7 -0
- package/dist/lib/node/{chunk-PMGWL64F.cjs → chunk-VHSIOCS5.cjs} +6 -6
- package/dist/lib/node/chunk-VHSIOCS5.cjs.map +7 -0
- package/dist/lib/node/{chunk-ZZ4HK5KM.cjs → chunk-WNV2RXSK.cjs} +11 -11
- package/dist/lib/node/chunk-WNV2RXSK.cjs.map +7 -0
- package/dist/lib/node/index.cjs +24 -24
- package/dist/lib/node/index.cjs.map +3 -3
- package/dist/lib/node/{intent-resolver-BQPBRVHM.cjs → intent-resolver-RNT5VWAM.cjs} +20 -20
- package/dist/lib/node/intent-resolver-RNT5VWAM.cjs.map +7 -0
- package/dist/lib/node/meta.json +1 -1
- package/dist/lib/node/{react-surface-5XHS5WYW.cjs → react-surface-GQM7SGY3.cjs} +26 -26
- package/dist/lib/node/react-surface-GQM7SGY3.cjs.map +7 -0
- package/dist/lib/node/{settings-7PVJBWC4.cjs → settings-425QHVGC.cjs} +7 -7
- package/dist/lib/node/types.cjs +3 -3
- package/dist/lib/node/types.cjs.map +1 -1
- package/dist/lib/node-esm/{DeploymentDialog-BIXZ5Q57.mjs → DeploymentDialog-2RRUJEBC.mjs} +4 -4
- package/dist/lib/node-esm/{ScriptContainer-4YWGWPY7.mjs → ScriptContainer-VG6BYEG6.mjs} +30 -17
- package/dist/lib/node-esm/ScriptContainer-VG6BYEG6.mjs.map +7 -0
- package/dist/lib/node-esm/{artifact-definition-5UHIXXHW.mjs → artifact-definition-J6UM6BQF.mjs} +41 -35
- package/dist/lib/node-esm/artifact-definition-J6UM6BQF.mjs.map +7 -0
- package/dist/lib/node-esm/chunk-5ES2REWL.mjs +89 -0
- package/dist/lib/node-esm/chunk-5ES2REWL.mjs.map +7 -0
- package/dist/lib/node-esm/{chunk-TN35DSTF.mjs → chunk-F47OE6ZM.mjs} +7 -6
- package/dist/lib/node-esm/chunk-F47OE6ZM.mjs.map +7 -0
- package/dist/lib/node-esm/{chunk-NNQXJQBG.mjs → chunk-SB3GNMN2.mjs} +81 -150
- package/dist/lib/node-esm/chunk-SB3GNMN2.mjs.map +7 -0
- package/dist/lib/node-esm/{chunk-GR4VTXVM.mjs → chunk-V733VFCJ.mjs} +2 -2
- package/dist/lib/node-esm/chunk-V733VFCJ.mjs.map +7 -0
- package/dist/lib/node-esm/{chunk-KGYTIL33.mjs → chunk-VMQPOPKV.mjs} +12 -13
- package/dist/lib/node-esm/chunk-VMQPOPKV.mjs.map +7 -0
- package/dist/lib/node-esm/{chunk-4ISQLIIH.mjs → chunk-ZB55NKKZ.mjs} +6 -6
- package/dist/lib/node-esm/chunk-ZB55NKKZ.mjs.map +7 -0
- package/dist/lib/node-esm/index.mjs +12 -12
- package/dist/lib/node-esm/index.mjs.map +3 -3
- package/dist/lib/node-esm/{intent-resolver-PPJKPHUQ.mjs → intent-resolver-BZFM7LZ2.mjs} +11 -11
- package/dist/lib/node-esm/intent-resolver-BZFM7LZ2.mjs.map +7 -0
- package/dist/lib/node-esm/meta.json +1 -1
- package/dist/lib/node-esm/{react-surface-7ELFL7IO.mjs → react-surface-QEOIJO4I.mjs} +8 -8
- package/dist/lib/node-esm/react-surface-QEOIJO4I.mjs.map +7 -0
- package/dist/lib/node-esm/{settings-SJYC4JLT.mjs → settings-BWSKKIVQ.mjs} +2 -2
- package/dist/lib/node-esm/types.mjs +1 -1
- package/dist/types/src/capabilities/app-graph-builder.d.ts.map +1 -1
- package/dist/types/src/capabilities/artifact-definition.d.ts.map +1 -1
- package/dist/types/src/capabilities/index.d.ts.map +1 -1
- package/dist/types/src/components/DeploymentDialog/DeploymentDialog.d.ts +2 -2
- package/dist/types/src/components/DeploymentDialog/DeploymentDialog.d.ts.map +1 -1
- package/dist/types/src/components/FrameContainer/FrameContainer.d.ts.map +1 -1
- package/dist/types/src/components/ScriptContainer.d.ts +1 -1
- package/dist/types/src/components/ScriptContainer.d.ts.map +1 -1
- package/dist/types/src/components/ScriptToolbar/ScriptToolbar.d.ts +1 -1
- package/dist/types/src/components/ScriptToolbar/ScriptToolbar.d.ts.map +1 -1
- package/dist/types/src/components/Settings/ScriptObjectSettings.d.ts +1 -1
- package/dist/types/src/components/Settings/ScriptObjectSettings.d.ts.map +1 -1
- package/dist/types/src/components/Settings/ScriptPluginSettings.d.ts.map +1 -1
- package/dist/types/src/components/TestPanel/TestPanel.d.ts.map +1 -1
- package/dist/types/src/components/TypescriptEditor/TypescriptEditor.d.ts.map +1 -1
- package/dist/types/src/components/index.d.ts +1 -1
- package/dist/types/src/hooks/deploy.d.ts +20 -17
- package/dist/types/src/hooks/deploy.d.ts.map +1 -1
- package/dist/types/src/hooks/format.d.ts +2 -5
- package/dist/types/src/hooks/format.d.ts.map +1 -1
- package/dist/types/src/hooks/index.d.ts +0 -1
- package/dist/types/src/hooks/index.d.ts.map +1 -1
- package/dist/types/src/hooks/template.d.ts +2 -5
- package/dist/types/src/hooks/template.d.ts.map +1 -1
- package/dist/types/src/hooks/useCreateAndDeployScriptTemplates.d.ts.map +1 -1
- package/dist/types/src/hooks/useToolbarState.d.ts.map +1 -1
- package/dist/types/src/templates/chat.d.ts.map +1 -1
- package/dist/types/src/templates/discord.d.ts.map +1 -1
- package/dist/types/src/templates/echo.d.ts.map +1 -1
- package/dist/types/src/templates/email.d.ts.map +1 -1
- package/dist/types/src/templates/gmail.d.ts.map +1 -1
- package/dist/types/src/translations.d.ts +2 -110
- package/dist/types/src/translations.d.ts.map +1 -1
- package/dist/types/src/types.d.ts +26 -25
- package/dist/types/src/types.d.ts.map +1 -1
- package/dist/types/src/util/deploy.d.ts.map +1 -1
- package/dist/types/src/util/functions.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +52 -50
- package/src/ScriptPlugin.tsx +3 -3
- package/src/capabilities/artifact-definition.ts +33 -30
- package/src/capabilities/intent-resolver.ts +5 -5
- package/src/capabilities/react-surface.tsx +3 -3
- package/src/components/DeploymentDialog/DeploymentDialog.stories.tsx +1 -1
- package/src/components/DeploymentDialog/DeploymentDialog.tsx +2 -2
- package/src/components/ScriptContainer.tsx +1 -1
- package/src/components/ScriptToolbar/ScriptToolbar.stories.tsx +1 -1
- package/src/components/ScriptToolbar/ScriptToolbar.tsx +16 -10
- package/src/components/Settings/ScriptObjectSettings.tsx +3 -3
- package/src/hooks/deploy.ts +60 -54
- package/src/hooks/format.ts +26 -26
- package/src/hooks/index.ts +0 -1
- package/src/hooks/template.ts +24 -32
- package/src/templates/discord.ts +10 -3
- package/src/templates/forex-effect.ts +1 -1
- package/src/templates/gmail.ts +42 -28
- package/src/translations.ts +1 -1
- package/src/types.ts +13 -14
- package/src/util/deploy.ts +3 -4
- package/dist/lib/browser/ScriptContainer-ATBYTIFH.mjs.map +0 -7
- package/dist/lib/browser/artifact-definition-OEDM2SCN.mjs.map +0 -7
- package/dist/lib/browser/chunk-EGDYE5MW.mjs.map +0 -7
- package/dist/lib/browser/chunk-OZEMT3NO.mjs.map +0 -7
- package/dist/lib/browser/chunk-QNXJNXQZ.mjs.map +0 -7
- package/dist/lib/browser/chunk-SXS6PUU5.mjs.map +0 -7
- package/dist/lib/browser/chunk-XEPVXV72.mjs +0 -87
- package/dist/lib/browser/chunk-XEPVXV72.mjs.map +0 -7
- package/dist/lib/browser/chunk-ZFTDU4WS.mjs +0 -41
- package/dist/lib/browser/chunk-ZFTDU4WS.mjs.map +0 -7
- package/dist/lib/browser/intent-resolver-C5D6TNPC.mjs.map +0 -7
- package/dist/lib/browser/react-surface-XJCN7XXF.mjs.map +0 -7
- package/dist/lib/node/ScriptContainer-OHHMLPUE.cjs.map +0 -7
- package/dist/lib/node/artifact-definition-SEGATFNH.cjs.map +0 -7
- package/dist/lib/node/chunk-4K23KEYT.cjs +0 -91
- package/dist/lib/node/chunk-4K23KEYT.cjs.map +0 -7
- package/dist/lib/node/chunk-DSFCLQ5F.cjs.map +0 -7
- package/dist/lib/node/chunk-PGEGRJP3.cjs.map +0 -7
- package/dist/lib/node/chunk-PMGWL64F.cjs.map +0 -7
- package/dist/lib/node/chunk-UUGLBCMY.cjs.map +0 -7
- package/dist/lib/node/chunk-ZZ4HK5KM.cjs.map +0 -7
- package/dist/lib/node/intent-resolver-BQPBRVHM.cjs.map +0 -7
- package/dist/lib/node/react-surface-5XHS5WYW.cjs.map +0 -7
- package/dist/lib/node-esm/ScriptContainer-4YWGWPY7.mjs.map +0 -7
- package/dist/lib/node-esm/artifact-definition-5UHIXXHW.mjs.map +0 -7
- package/dist/lib/node-esm/chunk-4ISQLIIH.mjs.map +0 -7
- package/dist/lib/node-esm/chunk-GR4VTXVM.mjs.map +0 -7
- package/dist/lib/node-esm/chunk-KGYTIL33.mjs.map +0 -7
- package/dist/lib/node-esm/chunk-NNQXJQBG.mjs.map +0 -7
- package/dist/lib/node-esm/chunk-TN35DSTF.mjs.map +0 -7
- package/dist/lib/node-esm/chunk-X64SI6XO.mjs +0 -89
- package/dist/lib/node-esm/chunk-X64SI6XO.mjs.map +0 -7
- package/dist/lib/node-esm/intent-resolver-PPJKPHUQ.mjs.map +0 -7
- package/dist/lib/node-esm/react-surface-7ELFL7IO.mjs.map +0 -7
- package/dist/types/src/hooks/useToolbarAction.d.ts +0 -13
- package/dist/types/src/hooks/useToolbarAction.d.ts.map +0 -1
- package/src/hooks/useToolbarAction.ts +0 -50
- /package/dist/lib/browser/{DeploymentDialog-QEKJ54ZB.mjs.map → DeploymentDialog-W7PY33VN.mjs.map} +0 -0
- /package/dist/lib/browser/{settings-NK4XVS2E.mjs.map → settings-EOKSUGB6.mjs.map} +0 -0
- /package/dist/lib/node/{settings-7PVJBWC4.cjs.map → settings-425QHVGC.cjs.map} +0 -0
- /package/dist/lib/node-esm/{DeploymentDialog-BIXZ5Q57.mjs.map → DeploymentDialog-2RRUJEBC.mjs.map} +0 -0
- /package/dist/lib/node-esm/{settings-SJYC4JLT.mjs.map → settings-BWSKKIVQ.mjs.map} +0 -0
|
@@ -26,25 +26,24 @@ 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_57MPT7DU_exports = {};
|
|
30
|
+
__export(chunk_57MPT7DU_exports, {
|
|
31
31
|
createDeploy: () => createDeploy,
|
|
32
32
|
createFormat: () => createFormat,
|
|
33
33
|
createTemplateSelect: () => createTemplateSelect,
|
|
34
|
+
useDeployDeps: () => useDeployDeps,
|
|
34
35
|
useDeployState: () => useDeployState,
|
|
35
|
-
useToolbarAction: () => useToolbarAction,
|
|
36
36
|
useToolbarState: () => useToolbarState
|
|
37
37
|
});
|
|
38
|
-
module.exports = __toCommonJS(
|
|
39
|
-
var
|
|
40
|
-
var
|
|
38
|
+
module.exports = __toCommonJS(chunk_57MPT7DU_exports);
|
|
39
|
+
var import_chunk_DGFQHBA7 = require("./chunk-DGFQHBA7.cjs");
|
|
40
|
+
var import_chunk_K7PPLRVQ = require("./chunk-K7PPLRVQ.cjs");
|
|
41
41
|
var import_chunk_NO5Y74F3 = require("./chunk-NO5Y74F3.cjs");
|
|
42
42
|
var import_react = require("react");
|
|
43
43
|
var import_functions = require("@dxos/functions");
|
|
44
44
|
var import_log = require("@dxos/log");
|
|
45
45
|
var import_react_client = require("@dxos/react-client");
|
|
46
46
|
var import_echo = require("@dxos/react-client/echo");
|
|
47
|
-
var import_react_ui = require("@dxos/react-ui");
|
|
48
47
|
var import_react_ui_menu = require("@dxos/react-ui-menu");
|
|
49
48
|
var import_react_ui_theme = require("@dxos/react-ui-theme");
|
|
50
49
|
var import_react2 = require("react");
|
|
@@ -52,18 +51,15 @@ var import_live_object = require("@dxos/live-object");
|
|
|
52
51
|
var import_prettier = require("prettier");
|
|
53
52
|
var import_estree = __toESM(require("prettier/plugins/estree"));
|
|
54
53
|
var import_typescript = __toESM(require("prettier/plugins/typescript"));
|
|
55
|
-
var import_react3 = require("react");
|
|
56
54
|
var import_log2 = require("@dxos/log");
|
|
57
55
|
var import_react_ui_menu2 = require("@dxos/react-ui-menu");
|
|
58
|
-
var
|
|
59
|
-
var import_types = require("@dxos/functions/types");
|
|
56
|
+
var import_functions2 = require("@dxos/functions");
|
|
60
57
|
var import_live_object2 = require("@dxos/live-object");
|
|
61
58
|
var import_react_ui_menu3 = require("@dxos/react-ui-menu");
|
|
62
|
-
var import_react5 = require("react");
|
|
63
|
-
var import_log3 = require("@dxos/log");
|
|
64
59
|
var __dxlog_file = "/home/runner/work/dxos/dxos/packages/plugins/plugin-script/src/hooks/deploy.ts";
|
|
65
|
-
var createDeploy = (state) => {
|
|
66
|
-
const errorItem = (0, import_react_ui_menu.createMenuAction)("error", {
|
|
60
|
+
var createDeploy = ({ state, script, space, fn, client, existingFunctionUrl, t }) => {
|
|
61
|
+
const errorItem = (0, import_react_ui_menu.createMenuAction)("error", () => {
|
|
62
|
+
}, {
|
|
67
63
|
label: state.error ?? [
|
|
68
64
|
"no error label",
|
|
69
65
|
{
|
|
@@ -74,7 +70,30 @@ var createDeploy = (state) => {
|
|
|
74
70
|
hidden: !state.error,
|
|
75
71
|
classNames: state.error && import_react_ui_theme.errorMessageColors
|
|
76
72
|
});
|
|
77
|
-
const deployAction = (0, import_react_ui_menu.createMenuAction)("deploy", {
|
|
73
|
+
const deployAction = (0, import_react_ui_menu.createMenuAction)("deploy", async () => {
|
|
74
|
+
if (!script.source || !space) {
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
state.error = void 0;
|
|
78
|
+
state.deploying = true;
|
|
79
|
+
const result = await (0, import_chunk_K7PPLRVQ.deployScript)({
|
|
80
|
+
script,
|
|
81
|
+
client,
|
|
82
|
+
space,
|
|
83
|
+
fn,
|
|
84
|
+
existingFunctionUrl
|
|
85
|
+
});
|
|
86
|
+
if (!result.success) {
|
|
87
|
+
import_log.log.catch(result.error, void 0, {
|
|
88
|
+
F: __dxlog_file,
|
|
89
|
+
L: 59,
|
|
90
|
+
S: void 0,
|
|
91
|
+
C: (f, a) => f(...a)
|
|
92
|
+
});
|
|
93
|
+
state.error = t("upload failed label");
|
|
94
|
+
}
|
|
95
|
+
state.deploying = false;
|
|
96
|
+
}, {
|
|
78
97
|
type: "deploy",
|
|
79
98
|
label: [
|
|
80
99
|
state.deploying ? "pending label" : "deploy label",
|
|
@@ -86,7 +105,12 @@ var createDeploy = (state) => {
|
|
|
86
105
|
disabled: state.deploying,
|
|
87
106
|
classNames: state.deploying ? "[&_svg]:animate-spin" : ""
|
|
88
107
|
});
|
|
89
|
-
const copyAction = (0, import_react_ui_menu.createMenuAction)("copy", {
|
|
108
|
+
const copyAction = (0, import_react_ui_menu.createMenuAction)("copy", async () => {
|
|
109
|
+
if (!state.functionUrl) {
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
await navigator.clipboard.writeText(state.functionUrl);
|
|
113
|
+
}, {
|
|
90
114
|
type: "copy",
|
|
91
115
|
label: [
|
|
92
116
|
"copy link label",
|
|
@@ -127,7 +151,7 @@ var useDeployState = ({ state, script }) => {
|
|
|
127
151
|
if (!existingFunctionUrl) {
|
|
128
152
|
return;
|
|
129
153
|
}
|
|
130
|
-
state.functionUrl = (0,
|
|
154
|
+
state.functionUrl = (0, import_chunk_K7PPLRVQ.getFunctionUrl)({
|
|
131
155
|
script,
|
|
132
156
|
fn,
|
|
133
157
|
edgeUrl: client.config.values.runtime?.services?.edge?.url ?? ""
|
|
@@ -140,7 +164,7 @@ var useDeployState = ({ state, script }) => {
|
|
|
140
164
|
client.config.values.runtime?.services?.edge?.url
|
|
141
165
|
]);
|
|
142
166
|
(0, import_react.useEffect)(() => {
|
|
143
|
-
state.deployed = (0,
|
|
167
|
+
state.deployed = (0, import_chunk_K7PPLRVQ.isScriptDeployed)({
|
|
144
168
|
script,
|
|
145
169
|
fn
|
|
146
170
|
});
|
|
@@ -167,57 +191,34 @@ var useDeployDeps = ({ script }) => {
|
|
|
167
191
|
existingFunctionUrl
|
|
168
192
|
};
|
|
169
193
|
};
|
|
170
|
-
var
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
if (!script.source
|
|
194
|
+
var useToolbarState = (initialState = {}) => {
|
|
195
|
+
return (0, import_react2.useMemo)(() => (0, import_live_object.live)(initialState), []);
|
|
196
|
+
};
|
|
197
|
+
var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/plugins/plugin-script/src/hooks/format.ts";
|
|
198
|
+
var createFormat = (script) => {
|
|
199
|
+
const formatAction = (0, import_react_ui_menu2.createMenuAction)("format", async () => {
|
|
200
|
+
if (!script.source) {
|
|
177
201
|
return;
|
|
178
202
|
}
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
203
|
+
try {
|
|
204
|
+
script.source.target.content = await (0, import_prettier.format)(script.source.target.content, {
|
|
205
|
+
parser: "typescript",
|
|
206
|
+
plugins: [
|
|
207
|
+
import_estree.default,
|
|
208
|
+
import_typescript.default
|
|
209
|
+
],
|
|
210
|
+
semi: true,
|
|
211
|
+
singleQuote: true
|
|
212
|
+
});
|
|
213
|
+
} catch (err) {
|
|
214
|
+
import_log2.log.catch(err, void 0, {
|
|
215
|
+
F: __dxlog_file2,
|
|
216
|
+
L: 34,
|
|
192
217
|
S: void 0,
|
|
193
218
|
C: (f, a) => f(...a)
|
|
194
219
|
});
|
|
195
|
-
state.error = t("upload failed label");
|
|
196
220
|
}
|
|
197
|
-
|
|
198
|
-
}, [
|
|
199
|
-
fn,
|
|
200
|
-
client,
|
|
201
|
-
t,
|
|
202
|
-
existingFunctionUrl,
|
|
203
|
-
script,
|
|
204
|
-
space
|
|
205
|
-
]);
|
|
206
|
-
};
|
|
207
|
-
var useCopyHandler = ({ state }) => (0, import_react.useCallback)(async () => {
|
|
208
|
-
if (!state.functionUrl) {
|
|
209
|
-
return;
|
|
210
|
-
}
|
|
211
|
-
await navigator.clipboard.writeText(state.functionUrl);
|
|
212
|
-
}, [
|
|
213
|
-
state.functionUrl
|
|
214
|
-
]);
|
|
215
|
-
var useToolbarState = (initialState = {}) => {
|
|
216
|
-
return (0, import_react2.useMemo)(() => (0, import_live_object.live)(initialState), []);
|
|
217
|
-
};
|
|
218
|
-
var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/plugins/plugin-script/src/hooks/format.ts";
|
|
219
|
-
var createFormat = () => {
|
|
220
|
-
const formatAction = (0, import_react_ui_menu2.createMenuAction)("format", {
|
|
221
|
+
}, {
|
|
221
222
|
label: [
|
|
222
223
|
"format label",
|
|
223
224
|
{
|
|
@@ -238,31 +239,6 @@ var createFormat = () => {
|
|
|
238
239
|
]
|
|
239
240
|
};
|
|
240
241
|
};
|
|
241
|
-
var useFormatHandler = ({ script }) => (0, import_react3.useCallback)(async () => {
|
|
242
|
-
if (!script.source) {
|
|
243
|
-
return;
|
|
244
|
-
}
|
|
245
|
-
try {
|
|
246
|
-
script.source.target.content = await (0, import_prettier.format)(script.source.target.content, {
|
|
247
|
-
parser: "typescript",
|
|
248
|
-
plugins: [
|
|
249
|
-
import_estree.default,
|
|
250
|
-
import_typescript.default
|
|
251
|
-
],
|
|
252
|
-
semi: true,
|
|
253
|
-
singleQuote: true
|
|
254
|
-
});
|
|
255
|
-
} catch (err) {
|
|
256
|
-
import_log2.log.catch(err, void 0, {
|
|
257
|
-
F: __dxlog_file2,
|
|
258
|
-
L: 45,
|
|
259
|
-
S: void 0,
|
|
260
|
-
C: (f, a) => f(...a)
|
|
261
|
-
});
|
|
262
|
-
}
|
|
263
|
-
}, [
|
|
264
|
-
script.source
|
|
265
|
-
]);
|
|
266
242
|
var createTemplateSelectGroup = () => {
|
|
267
243
|
return (0, import_react_ui_menu3.createMenuItemGroup)("template-select", {
|
|
268
244
|
label: [
|
|
@@ -274,18 +250,32 @@ var createTemplateSelectGroup = () => {
|
|
|
274
250
|
variant: "dropdownMenu"
|
|
275
251
|
});
|
|
276
252
|
};
|
|
277
|
-
var createTemplateSelectActions = () => {
|
|
278
|
-
return
|
|
279
|
-
return (0, import_react_ui_menu3.createMenuAction)(`template--${template.id}`, {
|
|
253
|
+
var createTemplateSelectActions = (script) => {
|
|
254
|
+
return import_chunk_DGFQHBA7.templates.map((template) => {
|
|
255
|
+
return (0, import_react_ui_menu3.createMenuAction)(`template--${template.id}`, () => {
|
|
256
|
+
script.name = template.name;
|
|
257
|
+
script.source.target.content = template.source;
|
|
258
|
+
const metaKeys = (0, import_live_object2.getMeta)(script).keys;
|
|
259
|
+
const oldPresetIndex = metaKeys.findIndex((key) => key.source === import_functions2.FUNCTIONS_PRESET_META_KEY);
|
|
260
|
+
if (oldPresetIndex >= 0) {
|
|
261
|
+
metaKeys.splice(oldPresetIndex, 1);
|
|
262
|
+
}
|
|
263
|
+
if (template.presetId) {
|
|
264
|
+
metaKeys.push({
|
|
265
|
+
source: import_functions2.FUNCTIONS_PRESET_META_KEY,
|
|
266
|
+
id: template.presetId
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
}, {
|
|
280
270
|
label: template.name,
|
|
281
271
|
value: template.id,
|
|
282
272
|
type: "template"
|
|
283
273
|
});
|
|
284
274
|
});
|
|
285
275
|
};
|
|
286
|
-
var createTemplateSelect = () => {
|
|
276
|
+
var createTemplateSelect = (script) => {
|
|
287
277
|
const templateSelectGroup = createTemplateSelectGroup();
|
|
288
|
-
const templateSelectActions = createTemplateSelectActions();
|
|
278
|
+
const templateSelectActions = createTemplateSelectActions(script);
|
|
289
279
|
return {
|
|
290
280
|
nodes: [
|
|
291
281
|
templateSelectGroup,
|
|
@@ -303,70 +293,13 @@ var createTemplateSelect = () => {
|
|
|
303
293
|
]
|
|
304
294
|
};
|
|
305
295
|
};
|
|
306
|
-
var useTemplateSelectHandler = ({ script }) => {
|
|
307
|
-
return (0, import_react4.useCallback)((templateId) => {
|
|
308
|
-
const template = import_chunk_4K23KEYT.templates.find((template2) => template2.id === templateId);
|
|
309
|
-
if (template) {
|
|
310
|
-
script.name = template.name;
|
|
311
|
-
script.source.target.content = template.source;
|
|
312
|
-
const metaKeys = (0, import_live_object2.getMeta)(script).keys;
|
|
313
|
-
const oldPresetIndex = metaKeys.findIndex((key) => key.source === import_types.FUNCTIONS_PRESET_META_KEY);
|
|
314
|
-
if (oldPresetIndex >= 0) {
|
|
315
|
-
metaKeys.splice(oldPresetIndex, 1);
|
|
316
|
-
}
|
|
317
|
-
if (template.presetId) {
|
|
318
|
-
metaKeys.push({
|
|
319
|
-
source: import_types.FUNCTIONS_PRESET_META_KEY,
|
|
320
|
-
id: template.presetId
|
|
321
|
-
});
|
|
322
|
-
}
|
|
323
|
-
}
|
|
324
|
-
}, [
|
|
325
|
-
script
|
|
326
|
-
]);
|
|
327
|
-
};
|
|
328
|
-
var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/plugins/plugin-script/src/hooks/useToolbarAction.ts";
|
|
329
|
-
var useToolbarAction = (props) => {
|
|
330
|
-
const handleTemplateSelect = useTemplateSelectHandler(props);
|
|
331
|
-
const handleFormat = useFormatHandler(props);
|
|
332
|
-
const handleDeploy = useDeployHandler(props);
|
|
333
|
-
const handleCopy = useCopyHandler(props);
|
|
334
|
-
return (0, import_react5.useCallback)((action) => {
|
|
335
|
-
switch (action.properties.type) {
|
|
336
|
-
case "template":
|
|
337
|
-
handleTemplateSelect(action.properties.value);
|
|
338
|
-
break;
|
|
339
|
-
case "format":
|
|
340
|
-
void handleFormat();
|
|
341
|
-
break;
|
|
342
|
-
case "deploy":
|
|
343
|
-
void handleDeploy();
|
|
344
|
-
break;
|
|
345
|
-
case "copy":
|
|
346
|
-
void handleCopy();
|
|
347
|
-
break;
|
|
348
|
-
default:
|
|
349
|
-
import_log3.log.error("Unknown action type", action, {
|
|
350
|
-
F: __dxlog_file3,
|
|
351
|
-
L: 45,
|
|
352
|
-
S: void 0,
|
|
353
|
-
C: (f, a) => f(...a)
|
|
354
|
-
});
|
|
355
|
-
}
|
|
356
|
-
}, [
|
|
357
|
-
handleTemplateSelect,
|
|
358
|
-
handleFormat,
|
|
359
|
-
handleDeploy,
|
|
360
|
-
handleCopy
|
|
361
|
-
]);
|
|
362
|
-
};
|
|
363
296
|
// Annotate the CommonJS export names for ESM import in node:
|
|
364
297
|
0 && (module.exports = {
|
|
365
298
|
createDeploy,
|
|
366
299
|
createFormat,
|
|
367
300
|
createTemplateSelect,
|
|
301
|
+
useDeployDeps,
|
|
368
302
|
useDeployState,
|
|
369
|
-
useToolbarAction,
|
|
370
303
|
useToolbarState
|
|
371
304
|
});
|
|
372
|
-
//# sourceMappingURL=chunk-
|
|
305
|
+
//# sourceMappingURL=chunk-57MPT7DU.cjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/hooks/deploy.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 { Filter, getMeta, getSpace, 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, Filter.schema(FunctionType, { source: script }));\n const client = useClient();\n const existingFunctionUrl = useMemo(() => fn && getUserFunctionUrlInMetadata(getMeta(fn)), [fn]);\n return { space, fn, client, existingFunctionUrl };\n};\n", "//\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: [{ source: 'root', target: 'format' }],\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
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,mBAAmC;AAEnC,uBAA4E;AAC5E,iBAAoB;AACpB,0BAAuC;AACvC,kBAAgE;AAEhE,2BAAiC;AACjC,4BAAmC;ACRnC,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;;AH8B/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,MAAMb,MAAMoB,YAAY,6BAA6B;IACrDO,UAAU3B,MAAMoB;IAChBL,YAAYf,MAAMoB,YAAY,yBAAyB;EACzD,CAAA;AAGF,QAAMQ,iBAAapB,uCACjB,QACA,YAAA;AACE,QAAI,CAACR,MAAM6B,aAAa;AACtB;IACF;AACA,UAAMC,UAAUC,UAAUC,UAAUhC,MAAM6B,WAAW;EACvD,GACA;IACEH,MAAM;IACNjB,OAAO;MAAC;MAAmB;QAAEE,IAAIC;MAAc;;IAC/CC,MAAM;IACNc,UAAU,CAAC3B,MAAM6B;EACnB,CAAA;AAGF,SAAO;IACLI,OAAO;MAAC1B;MAAWU;MAAcW;;IACjCM,OAAO;MACL;QAAEhB,QAAQ;QAAQiB,QAAQ;MAAQ;MAClC;QAAEjB,QAAQ;QAAQiB,QAAQ;MAAS;MACnC;QAAEjB,QAAQ;QAAQiB,QAAQ;MAAO;;EAErC;AACF;AAEO,IAAMC,iBAAiB,CAAC,EAAEpC,OAAOC,OAAM,MAAuD;AACnG,QAAM,EAAEC,OAAOE,QAAQD,IAAIE,oBAAmB,IAAKgC,cAAc;IAAEpC;EAAO,CAAA;AAC1EqC,8BAAU,MAAA;AACR,QAAI,CAACjC,qBAAqB;AACxB;IACF;AAEAL,UAAM6B,kBAAcU,sCAAe;MACjCtC;MACAE;MACAqC,SAASpC,OAAOqC,OAAOC,OAAOC,SAASC,UAAUC,MAAMC,OAAO;IAChE,CAAA;EACF,GAAG;IAACzC;IAAqBH;IAAOC;IAAIF;IAAQG,OAAOqC,OAAOC,OAAOC,SAASC,UAAUC,MAAMC;GAAI;AAE9FR,8BAAU,MAAA;AACRtC,UAAM+C,eAAWC,wCAAiB;MAAE/C;MAAQE;IAAG,CAAA;EACjD,GAAG;IAACF,OAAOgD;IAAS5C;IAAqBF;IAAIF;GAAO;AACtD;AAEO,IAAMoC,gBAAgB,CAAC,EAAEpC,OAAM,MAA0B;AAC9D,QAAMC,YAAQgD,sBAASjD,MAAAA;AACvB,QAAM,CAACE,EAAAA,QAAMgD,sBAASjD,OAAOkD,mBAAOC,OAAOC,+BAAc;IAAEpC,QAAQjB;EAAO,CAAA,CAAA;AAC1E,QAAMG,aAASmD,+BAAAA;AACf,QAAMlD,0BAAsBmD,sBAAQ,MAAMrD,UAAMsD,mDAA6BC,qBAAQvD,EAAAA,CAAAA,GAAM;IAACA;GAAG;AAC/F,SAAO;IAAED;IAAOC;IAAIC;IAAQC;EAAoB;AAClD;AC/GO,IAAMsD,kBAAkB,CAACC,eAAmC,CAAC,MAAC;AACnE,aAAOJ,cAAAA,SAAQ,UAAMK,yBAAyBD,YAAAA,GAAe,CAAA,CAAE;AACjE;;ACCO,IAAME,eAAe,CAAC7D,WAAAA;AAC3B,QAAM8D,mBAAevD,sBAAAA,kBACnB,UACA,YAAA;AACE,QAAI,CAACP,OAAOiB,QAAQ;AAClB;IACF;AAEA,QAAI;AACFjB,aAAOiB,OAAOiB,OAAQ6B,UAAU,UAAMC,wBAAOhE,OAAOiB,OAAOiB,OAAQ6B,SAAS;QAC1EE,QAAQ;QACRC,SAAS;UAACC,cAAAA;UAAsBC,kBAAAA;;QAChCC,MAAM;QACNC,aAAa;MACf,CAAA;IACF,SAASC,KAAU;AAEjBhD,kBAAAA,IAAIC,MAAM+C,KAAAA,QAAAA;;;;;;IACZ;EACF,GACA;IACE/D,OAAO;MAAC;MAAgB;QAAEE,IAAIC;MAAc;;IAC5CC,MAAM;EACR,CAAA;AAGF,SAAO;IACLoB,OAAO;MAAC8B;;IACR7B,OAAO;MAAC;QAAEhB,QAAQ;QAAQiB,QAAQ;MAAS;;EAC7C;AACF;ACjCA,IAAMsC,4BAA4B,MAAA;AAChC,aAAOC,2CAAoB,mBAAmB;IAC5CjE,OAAO;MAAC;MAA+B;QAAEE,IAAIC;MAAc;;IAC3D+D,SAAS;EACX,CAAA;AACF;AAEA,IAAMC,8BAA8B,CAAC3E,WAAAA;AACnC,SAAO4E,gCAAUC,IAAI,CAACC,aAAAA;AACpB,eAAOvE,sBAAAA,kBACL,aAAauE,SAASC,EAAE,IACxB,MAAA;AACE/E,aAAOgF,OAAOF,SAASE;AACvBhF,aAAOiB,OAAQiB,OAAQ6B,UAAUe,SAAS7D;AAC1C,YAAMgE,eAAWxB,oBAAAA,SAAQzD,MAAAA,EAAQkF;AACjC,YAAMC,iBAAiBF,SAASG,UAAU,CAACC,QAAQA,IAAIpE,WAAWqE,2CAAAA;AAClE,UAAIH,kBAAkB,GAAG;AACvBF,iBAASM,OAAOJ,gBAAgB,CAAA;MAClC;AACA,UAAIL,SAASU,UAAU;AACrBP,iBAASQ,KAAK;UAAExE,QAAQqE;UAA2BP,IAAID,SAASU;QAAS,CAAA;MAC3E;IACF,GACA;MACEhF,OAAOsE,SAASE;MAChBU,OAAOZ,SAASC;MAChBtD,MAAM;IACR,CAAA;EAEJ,CAAA;AACF;AAEO,IAAMkE,uBAAuB,CAAC3F,WAAAA;AACnC,QAAM4F,sBAAsBpB,0BAAAA;AAC5B,QAAMqB,wBAAwBlB,4BAA4B3E,MAAAA;AAC1D,SAAO;IACLgC,OAAO;MAAC4D;SAAwBC;;IAChC5D,OAAO;MACL;QAAEhB,QAAQ;QAAQiB,QAAQ;MAAkB;SACzC2D,sBAAsBhB,IAAI,CAACiB,YAAY;QAAE7E,QAAQ;QAAmBiB,QAAQ4D,OAAOf;MAAG,EAAA;;EAE7F;AACF;",
|
|
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", "Filter", "schema", "FunctionType", "useClient", "useMemo", "getUserFunctionUrlInMetadata", "getMeta", "useToolbarState", "initialState", "live", "createFormat", "formatAction", "content", "format", "parser", "plugins", "prettierPluginEstree", "prettierPluginTypescript", "semi", "singleQuote", "err", "createTemplateSelectGroup", "createMenuItemGroup", "variant", "createTemplateSelectActions", "templates", "map", "template", "id", "name", "metaKeys", "keys", "oldPresetIndex", "findIndex", "key", "FUNCTIONS_PRESET_META_KEY", "splice", "presetId", "push", "value", "createTemplateSelect", "templateSelectGroup", "templateSelectActions", "action"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
var chunk_DGFQHBA7_exports = {};
|
|
20
|
+
__export(chunk_DGFQHBA7_exports, {
|
|
21
|
+
templates: () => templates
|
|
22
|
+
});
|
|
23
|
+
module.exports = __toCommonJS(chunk_DGFQHBA7_exports);
|
|
24
|
+
var chat_default = "//\n// Copyright 2024 DXOS.org\n//\n\n// @ts-ignore\nimport { transformServerSentEvents } from 'https://esm.sh/@dxos/script-toolbox';\n\n/**\n * Chatbot that answers questions based on the context data.\n */\nexport default async ({\n event: {\n data: { request },\n },\n context: { space, ai },\n}: any) => {\n const textBody = await request.text();\n let parsedRequest: any;\n try {\n parsedRequest = JSON.parse(textBody);\n } catch (err) {\n const answer = await ai.run('@cf/meta/llama-3.1-8b-instruct', {\n stream: true,\n prompt: `\n Using only the context data below to answer the user's question.\n If you cannot answer the question from the provided content, then reply with \"I don't know.\"\n\n CONTEXT:\n ${await getContext({ space })}\n\n QUESTION:\n ${textBody}\n `,\n });\n return new Response(transformServerSentEvents(answer));\n }\n\n const promptId = parsedRequest.trigger.promptId;\n const promptObject = await space.crud.query({ id: promptId }).first();\n\n if (parsedRequest.data.objects.length !== 1) {\n return new Response('Message batches not supported.');\n }\n\n const messageId = parsedRequest.data.objects[0];\n let message;\n try {\n message = await space.crud.query({ id: messageId }).first();\n } catch (err) {\n return new Response('Message not replicated yet.', { status: 409 });\n }\n\n if (message.text.includes('--------')) {\n return new Response('Message was already processed.');\n }\n\n let prompt = promptObject.template;\n for (const input of promptObject.inputs) {\n let value: string | null = null;\n if (input.type === TemplateInputType.VALUE) {\n value = String(input.value);\n } else if (input.type === TemplateInputType.RETRIEVER) {\n value = await getContext({ space });\n } else if (input.type === TemplateInputType.PASS_THROUGH) {\n value = message.text;\n }\n if (value) {\n prompt = prompt.replaceAll(`{${input.name}}`, value);\n }\n }\n\n const answer = await ai.run('@cf/meta/llama-3.1-8b-instruct', {\n stream: false,\n prompt,\n });\n const response = { response: answer.response, prompt, message };\n const textWithAnswer = message.text + '\\n--------\\n\\n' + answer.response;\n await space.crud.update({ id: messageId }, { text: textWithAnswer });\n\n return new Response(JSON.stringify(response));\n};\n\nconst getContext = async ({ space }: any) => {\n let context = '';\n const { objects: docs } = await space.crud.query({ __typename: 'dxos.org/type/Document' }).run();\n for (const doc of docs) {\n const { content } = await space.crud.query({ id: doc.content }).first();\n context += content + '\\n\\n';\n }\n return context;\n};\n\nenum TemplateInputType {\n VALUE = 0,\n PASS_THROUGH = 1,\n RETRIEVER = 2,\n FUNCTION = 3,\n QUERY = 4,\n RESOLVER = 5,\n CONTEXT = 6,\n SCHEMA = 7,\n}\n";
|
|
25
|
+
var chess_default = "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { defineFunction, S } from 'dxos:functions';\n// @ts-ignore\nimport { Chess } from 'https://esm.sh/chess.js@0.13.1';\n\nexport default defineFunction({\n description: 'Plays a random move in a chess game.',\n\n inputSchema: S.Struct({\n changedObjectId: S.String.annotations({\n description: 'The objects to play the game on.',\n }),\n player: S.optional(S.Literal('w', 'b')).annotations({\n description: 'The player to play the game as.',\n }),\n }),\n\n outputSchema: S.Struct({\n state: S.String.annotations({\n description: 'The state of the game as an ASCII art board.',\n }),\n }),\n\n handler: async ({\n event: {\n data: { changedObjectId, player = 'b' },\n },\n context: { space },\n }: any) => {\n const { pgn } = await space.db.query({ id: changedObjectId }).first();\n const game = new Chess();\n game.load_pgn(pgn);\n if (game.turn() !== player) {\n return new Response('Invalid turn', { status: 409 });\n }\n\n const moves = game.moves();\n const move = moves[Math.floor(Math.random() * moves.length)];\n if (!move) {\n return new Response('No legal moves', { status: 406 });\n }\n\n game.move(move);\n const newPgn = game.pgn();\n await space.db.update({ id: changedObjectId }, { pgn: newPgn, fen: game.fen() });\n return { state: game.ascii() };\n },\n});\n";
|
|
26
|
+
var data_generator_default = "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { defineFunction, S, create, Expando } from 'dxos:functions';\n// @ts-ignore\nimport { randText } from 'https://esm.sh/@ngneat/falso@7.1.1';\n\nexport default defineFunction({\n inputSchema: S.Struct({\n documentAmount: S.optional(S.Number),\n textSize: S.optional(S.Number),\n mutationAmount: S.optional(S.Number),\n }),\n\n outputSchema: S.Struct({}),\n\n handler: async ({\n event: {\n data: { documentAmount = 1, textSize = 10, mutationAmount = 0 },\n },\n context: { space },\n }: any) => {\n await space.db.graph.schemaRegistry.addSchema([Expando]);\n const result: Record<string, any> = {};\n const objects: Expando[] = [];\n\n // Create objects.\n for (let i = 0; i < documentAmount; i++) {\n const obj = space.db.add(\n create(Expando, {\n name: 'scriptGenerated',\n content: randText({ charCount: textSize }),\n }),\n );\n objects.push(obj);\n const objectResult: any = {};\n // Mutate the object.\n for (let i = 0; i < mutationAmount; i++) {\n obj.content = randText({ charCount: textSize });\n }\n objectResult.mutations = mutationAmount;\n objectResult.contentLength = obj.content.length;\n result[obj.id] = objectResult;\n }\n\n // Flush and wait for data to propagate.\n await space.db.flush();\n await new Promise((resolve) => setTimeout(resolve, 10_000));\n return result;\n },\n});\n";
|
|
27
|
+
var discord_default = "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { create, defineFunction, DXN, Filter, ObjectId, S } from 'dxos:functions';\nimport {\n FetchHttpClient,\n // @ts-ignore\n} from 'https://esm.sh/@effect/platform@0.77.2?deps=effect@3.13.3';\n// @ts-ignore\nimport { DiscordConfig, DiscordREST, DiscordRESTMemoryLive } from 'https://esm.sh/dfx@0.113.0?deps=effect@3.13.3';\n// @ts-ignore\nimport { Effect, Config, Redacted, Ref } from 'https://esm.sh/effect@3.13.3';\n\nimport { Type } from '@dxos/echo';\n\nconst MessageSchema = S.Struct({\n id: ObjectId,\n foreignId: S.Any, // bigint?\n from: S.String,\n created: S.String,\n content: S.String,\n}).pipe(\n Type.def({\n typename: 'example.com/type/Message',\n version: '0.1.0',\n }),\n);\n\nconst DEFAULT_AFTER = 1704067200; // 2024-01-01\n\nconst generateSnowflake = (unixTimestamp: number): bigint => {\n const discordEpoch = 1420070400000n; // Discord Epoch (ms)\n return (BigInt(unixTimestamp * 1000) - discordEpoch) << 22n;\n};\n\nexport default defineFunction({\n inputSchema: S.Struct({\n // TODO(wittjosiah): Remove. This is used to provide a terminal for a cron trigger.\n tick: S.optional(S.String),\n channelId: S.String,\n after: S.optional(S.Number),\n pageSize: S.optional(S.Number),\n queueId: S.String,\n }),\n\n outputSchema: S.Struct({\n newMessages: S.Number,\n }),\n\n handler: ({\n event: {\n data: { channelId, queueId, after = DEFAULT_AFTER, pageSize = 5 },\n },\n context: { space },\n }: any) =>\n Effect.gen(function* () {\n const { token } = yield* Effect.tryPromise({\n try: () => space.db.query(Filter.typename('dxos.org/type/AccessToken', { source: 'discord.com' })).first(),\n catch: (e: any) => e,\n });\n const { objects } = yield* Effect.tryPromise({\n try: () => space.queues.queryQueue(DXN.parse(queueId)),\n catch: (e: any) => e,\n });\n const backfill = objects.length === 0;\n const newMessages = yield* Ref.make(0);\n const lastMessage = yield* Ref.make(objects.at(-1));\n\n const enqueueMessages = Effect.gen(function* () {\n const rest = yield* DiscordREST;\n\n while (true) {\n const last = yield* Ref.get(lastMessage);\n const options = {\n after: backfill && !last ? `${generateSnowflake(after)}` : last?.foreignId,\n limit: pageSize,\n };\n const messages = yield* rest.getChannelMessages(channelId, options).pipe((res: any) => res.json);\n const queueMessages = messages\n .map((message: any) =>\n create(MessageSchema, {\n id: ObjectId.random(),\n foreignId: message.id,\n from: message.author.username,\n created: message.timestamp,\n content: message.content,\n }),\n )\n .toReversed();\n if (queueMessages.length > 0) {\n yield* Effect.tryPromise({\n try: () => space.queues.insertIntoQueue(DXN.parse(queueId), queueMessages),\n catch: (e: any) => e,\n });\n yield* Ref.update(newMessages, (n: any) => n + queueMessages.length);\n yield* Ref.update(lastMessage, (m: any) => queueMessages.at(-1));\n }\n if (messages.length < pageSize) {\n break;\n }\n }\n }).pipe(\n Effect.provide(DiscordRESTMemoryLive),\n Effect.provide(\n DiscordConfig.layerConfig({\n token: Config.succeed(Redacted.make(token)),\n }),\n ),\n Effect.provide(FetchHttpClient.layer),\n );\n\n yield* enqueueMessages;\n return { newMessages: yield* Ref.get(newMessages) };\n }),\n});\n";
|
|
28
|
+
var echo_default = "//\n// Copyright 2024 DXOS.org\n//\n\n/**\n * Echos the request data.\n */\nexport default async ({\n event: {\n data: { request },\n },\n}: any) => {\n const data = await request.json();\n return new Response(JSON.stringify(data ?? {}), {\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n};\n";
|
|
29
|
+
var email_default = "//\n// Copyright 2024 DXOS.org\n//\n\n/**\n * Appends a message to the end of a Document configured through a trigger.\n * Trigger must have a targetDocumentId field set in Meta.\n */\nexport default async ({\n event: {\n data: { request },\n },\n context: { space },\n}: any) => {\n const { data, trigger } = (await request.json()) as RequestPayload;\n\n const documentId = trigger.meta.targetDocumentId;\n const document = await space.db.query({ id: documentId }, { format: 'plain' }).first();\n\n const contentId = document.content['/'].split(':')[3];\n const documentContent = await space.db.query({ id: contentId }, { format: 'plain' }).first();\n const modifiedContent = [\n documentContent.content,\n '',\n '---',\n `**From:** ${data.from}`,\n `**Subject:** ${data.subject}`,\n `**Date:** ${data.created}`,\n '',\n data.body,\n ].join('\\n');\n\n await space.db.update({ id: contentId }, { content: modifiedContent });\n\n return new Response(JSON.stringify({ success: true }));\n};\n\ntype RequestPayload = {\n data: { from: string; subject: string; created: string; body: string };\n trigger: { meta: { targetDocumentId: string } };\n};\n";
|
|
30
|
+
var forex_effect_default = "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { S, defineFunction } from 'dxos:functions';\nimport {\n HttpClient,\n HttpClientRequest,\n FetchHttpClient,\n // @ts-ignore\n} from 'https://esm.sh/@effect/platform@0.77.2?deps=effect@3.13.3';\n// @ts-ignore\nimport { Effect, Schedule } from 'https://esm.sh/effect@3.13.3';\n\nexport default defineFunction({\n description: 'Returns the exchange rate between two currencies.',\n\n inputSchema: S.Struct({\n from: S.String.annotations({ description: 'The source currency' }),\n to: S.String.annotations({ description: 'The target currency' }),\n }),\n\n outputSchema: S.String.annotations({ description: 'The exchange rate between the two currencies' }),\n\n handler: async ({\n event: {\n data: { from, to },\n },\n }: any) =>\n Effect.gen(function* () {\n const res = yield* HttpClientRequest.get(`https://free.ratesdb.com/v1/rates?from=${from}&to=${to}`).pipe(\n HttpClient.execute,\n Effect.flatMap((res: any) => res.json),\n Effect.timeout('1 second'),\n Effect.retry(Schedule.exponential(1_000).pipe(Schedule.compose(Schedule.recurs(3)))),\n Effect.scoped,\n );\n\n return res.data.rates[to].toString();\n }).pipe(Effect.provide(FetchHttpClient.layer)),\n});\n";
|
|
31
|
+
var forex_default = "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { defineFunction, S } from 'dxos:functions';\n\nexport default defineFunction({\n description: 'Returns the exchange rate between two currencies.',\n\n inputSchema: S.Struct({\n from: S.String.annotations({ description: 'The source currency' }),\n to: S.String.annotations({ description: 'The target currency' }),\n }),\n\n handler: async ({\n event: {\n data: { from, to },\n },\n }: any) => {\n const res = await fetch(`https://free.ratesdb.com/v1/rates?from=${from}&to=${to}`);\n const {\n data: { rates },\n } = await res.json();\n\n return rates[to].toString();\n },\n});\n";
|
|
32
|
+
var gmail_default = "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { create, defineFunction, Filter, ObjectId, S } from 'dxos:functions';\n// @ts-ignore\nimport {\n HttpClient,\n HttpClientRequest,\n FetchHttpClient,\n // @ts-ignore\n} from 'https://esm.sh/@effect/platform@0.77.2?deps=effect@3.13.3';\n// @ts-ignore\nimport { format, subDays } from 'https://esm.sh/date-fns@3.3.1';\n// @ts-ignore\nimport { pipe, Chunk, Effect, Ref, Schedule, Stream } from 'https://esm.sh/effect@3.13.3';\n\nimport { Type } from '@dxos/echo';\n\nexport default defineFunction({\n inputSchema: S.Struct({\n mailboxId: S.String,\n userId: S.optional(S.String).pipe(S.withDecodingDefault(() => 'me')),\n after: S.optional(S.Union(S.Number, S.String)).pipe(\n S.withDecodingDefault(() => format(subDays(new Date(), 30), 'yyyy-MM-dd')),\n ),\n pageSize: S.optional(S.Number).pipe(S.withDecodingDefault(() => 100)),\n // TODO(wittjosiah): Remove. This is used to provide a terminal for a cron trigger.\n tick: S.optional(S.String),\n }),\n\n outputSchema: S.Struct({\n newMessages: S.Number,\n }),\n\n handler: ({\n context: { space },\n event: {\n data: { mailboxId, userId, after, pageSize },\n },\n }: any) =>\n Effect.gen(function* () {\n const { token } = yield* Effect.tryPromise({\n try: () => space.db.query(Filter.typename('dxos.org/type/AccessToken', { source: 'gmail.com' })).first(),\n catch: (e: any) => e,\n });\n\n // NOTE: Google API bundles size is v. large and caused runtime issues.\n const makeRequest = (url: string) =>\n pipe(\n url,\n HttpClientRequest.get,\n HttpClientRequest.setHeaders({ Authorization: `Bearer ${token}`, Accept: 'application/json' }),\n HttpClient.execute,\n Effect.flatMap((res: any) => res.json),\n Effect.timeout('1 second'),\n Effect.retry(Schedule.exponential(1000).pipe(Schedule.compose(Schedule.recurs(3)))),\n Effect.scoped,\n );\n\n const listMessages = (userId: string, q: string, pageSize: number, pageToken: string | null) =>\n makeRequest(getUrl(userId, undefined, { q, pageSize, pageToken }));\n\n const getMessage = (userId: string, messageId: string) => makeRequest(getUrl(userId, messageId));\n\n const mailbox = yield* Effect.tryPromise({\n try: () => space.db.query({ id: mailboxId }).first(),\n catch: (e: any) => e,\n });\n const { objects } = yield* Effect.tryPromise({\n try: () => space.queues.queryQueue(mailbox.queue.dxn),\n catch: (e: any) => e,\n });\n const newMessages = yield* Ref.make([]);\n const nextPage = yield* Ref.make(null);\n\n do {\n const last = objects.at(-1);\n const q = last\n ? `in:inbox after:${Math.floor(new Date(last.created).getTime() / 1000)}`\n : `in:inbox after:${after}`;\n const pageToken = yield* Ref.get(nextPage);\n const { messages, nextPageToken } = yield* listMessages(userId, q, pageSize, pageToken);\n yield* Ref.update(nextPage, () => nextPageToken);\n for (const message of messages) {\n const messageDetails = yield* getMessage(userId, message.id);\n const created = new Date(parseInt(messageDetails.internalDate)).toISOString();\n const from = messageDetails.payload.headers.find((h: any) => h.name === 'From');\n const sender = from && parseEmailString(from.value);\n // TODO(wittjosiah): Improve parsing of email contents.\n const content =\n messageDetails.payload.body?.data ??\n messageDetails.payload.parts?.find((p: any) => p.mimeType === 'text/plain')?.body.data;\n // Skip the message if content or sender is missing.\n // Skip the message if it's the same as the last message.\n // TODO(wittjosiah): This comparison should be done via foreignId probably.\n if (!content || !sender || created === last?.created) {\n continue;\n }\n const subject = messageDetails.payload.headers.find((h: any) => h.name === 'Subject')?.value;\n const object = create(MessageType, {\n id: ObjectId.random(),\n created,\n sender,\n blocks: [\n {\n type: 'text',\n text: Buffer.from(content, 'base64').toString('utf-8'),\n },\n ],\n properties: {\n subject,\n threadId: message.threadId,\n },\n });\n // TODO(wittjosiah): Set foreignId in object meta.\n yield* Ref.update(newMessages, (n: any) => [object, ...n]);\n }\n } while (yield* Ref.get(nextPage));\n\n const queueMessages = yield* Ref.get(newMessages);\n if (queueMessages.length > 0) {\n yield* pipe(\n queueMessages,\n Stream.fromIterable,\n Stream.grouped(10),\n Stream.flatMap((batch: any) =>\n Effect.tryPromise({\n try: () => space.queues.insertIntoQueue(mailbox.queue.dxn, Chunk.toReadonlyArray(batch)),\n catch: (e: any) => e,\n }),\n ),\n Stream.runDrain,\n );\n }\n\n return { newMessages: queueMessages.length };\n }).pipe(Effect.provide(FetchHttpClient.layer)),\n});\n\nconst getUrl = (userId: string, messageId?: string, params?: Record<string, any>) => {\n const api = new URL(\n [`https://gmail.googleapis.com/gmail/v1/users/${userId}/messages`, messageId].filter(Boolean).join('/'),\n );\n Object.entries(params ?? {}).forEach(([key, value]) => api.searchParams.set(key, value));\n return api.toString();\n};\n\n/**\n * Parses an email string in the format \"Name <email@example.com>\" into separate name and email components.\n */\nconst parseEmailString = (emailString: string): { name?: string; email: string } | undefined => {\n const match = emailString.match(/^([^<]+?)\\s*<([^>]+@[^>]+)>$/);\n if (match) {\n const [, name, email] = match;\n return {\n name: name.trim(),\n email: email.trim(),\n };\n }\n\n return undefined;\n};\n\n//\n// Schemas\n// TODO(wittjosiah): These schemas should be imported from @dxos/S.\n//\n\nconst ActorRoles = ['user', 'assistant'] as const;\nconst ActorRole = S.Literal(...ActorRoles);\ntype ActorRole = S.S.Type<typeof ActorRole>;\n\nconst ActorSchema = S.Struct({\n identityKey: S.optional(S.String),\n email: S.optional(S.String),\n name: S.optional(S.String),\n role: S.optional(ActorRole),\n});\n\nconst AbstractContentBlock = S.Struct({\n pending: S.optional(S.Boolean),\n});\ntype AbstractContentBlock = S.S.Type<typeof AbstractContentBlock>;\nconst TextContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('text'),\n disposition: S.optional(S.String),\n text: S.String,\n }),\n).pipe(S.mutable);\ntype TextContentBlock = S.S.Type<typeof TextContentBlock>;\nconst JsonContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('json'),\n disposition: S.optional(S.String),\n data: S.String,\n }),\n).pipe(S.mutable);\ntype JsonContentBlock = S.S.Type<typeof JsonContentBlock>;\nconst Base64ImageSource = S.Struct({\n type: S.Literal('base64'),\n mediaType: S.String,\n data: S.String,\n}).pipe(S.mutable);\nconst HttpImageSource = S.Struct({\n type: S.Literal('http'),\n url: S.String,\n}).pipe(S.mutable);\nconst ImageSource = S.Union(Base64ImageSource, HttpImageSource);\ntype ImageSource = S.S.Type<typeof ImageSource>;\nconst ImageContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('image'),\n id: S.optional(S.String),\n source: S.optional(ImageSource),\n }),\n).pipe(S.mutable);\ntype ImageContentBlock = S.S.Type<typeof ImageContentBlock>;\nconst ReferenceContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('reference'),\n reference: S.Any,\n }),\n).pipe(S.mutable);\ntype ReferenceContentBlock = S.S.Type<typeof ReferenceContentBlock>;\nconst MessageContentBlock = S.Union(TextContentBlock, JsonContentBlock, ImageContentBlock, ReferenceContentBlock);\n\nconst MessageType = S.Struct({\n id: ObjectId,\n created: S.String.annotations({\n description: 'ISO date string when the message was sent.',\n }),\n sender: ActorSchema.annotations({\n description: 'Identity of the message sender.',\n }),\n blocks: S.Array(MessageContentBlock).annotations({\n description: 'Contents of the message.',\n }),\n properties: S.optional(\n S.mutable(\n S.Record({ key: S.String, value: S.Any }).annotations({\n description: 'Custom properties for specific message types (e.g. attention context, email subject, etc.).',\n }),\n ),\n ),\n}).pipe(\n Type.def({\n typename: 'dxos.org/type/Message',\n version: '0.1.0',\n }),\n);\ntype MessageType = S.S.Type<typeof MessageType>;\n";
|
|
33
|
+
var removeHeader = (str) => str.split("\n").slice(4).join("\n");
|
|
34
|
+
var templates = [
|
|
35
|
+
{
|
|
36
|
+
id: "dxos.org/script/echo",
|
|
37
|
+
name: "Echo",
|
|
38
|
+
source: removeHeader(echo_default)
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
id: "dxos.org/script/forex",
|
|
42
|
+
name: "Forex",
|
|
43
|
+
source: removeHeader(forex_default)
|
|
44
|
+
},
|
|
45
|
+
{
|
|
46
|
+
id: "dxos.org/script/forex-effect",
|
|
47
|
+
name: "Forex (Effect)",
|
|
48
|
+
source: removeHeader(forex_effect_default)
|
|
49
|
+
},
|
|
50
|
+
{
|
|
51
|
+
id: "dxos.org/script/gpt",
|
|
52
|
+
name: "Gpt",
|
|
53
|
+
source: removeHeader(chat_default),
|
|
54
|
+
presetId: "dxos.org/function/gpt"
|
|
55
|
+
},
|
|
56
|
+
{
|
|
57
|
+
id: "dxos.org/script/chess",
|
|
58
|
+
name: "Chess",
|
|
59
|
+
source: removeHeader(chess_default),
|
|
60
|
+
presetId: "dxos.org/function/chess"
|
|
61
|
+
},
|
|
62
|
+
{
|
|
63
|
+
id: "dxos.org/script/email",
|
|
64
|
+
name: "Email",
|
|
65
|
+
source: removeHeader(email_default),
|
|
66
|
+
presetId: "dxos.org/function/email"
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
id: "dxos.org/script/discord",
|
|
70
|
+
name: "Discord",
|
|
71
|
+
source: removeHeader(discord_default),
|
|
72
|
+
presetId: "dxos.org/function/discord"
|
|
73
|
+
},
|
|
74
|
+
{
|
|
75
|
+
id: "dxos.org/script/gmail",
|
|
76
|
+
name: "Gmail",
|
|
77
|
+
source: removeHeader(gmail_default),
|
|
78
|
+
presetId: "dxos.org/function/gmail"
|
|
79
|
+
},
|
|
80
|
+
{
|
|
81
|
+
id: "dxos.org/script/data-generator",
|
|
82
|
+
name: "Data Generator",
|
|
83
|
+
source: removeHeader(data_generator_default),
|
|
84
|
+
presetId: "dxos.org/function/data-generator"
|
|
85
|
+
}
|
|
86
|
+
];
|
|
87
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
88
|
+
0 && (module.exports = {
|
|
89
|
+
templates
|
|
90
|
+
});
|
|
91
|
+
//# sourceMappingURL=chunk-DGFQHBA7.cjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["raw-loader:./chat.ts?raw", "raw-loader:./chess.ts?raw", "raw-loader:./data-generator.ts?raw", "raw-loader:./discord.ts?raw", "raw-loader:./echo.ts?raw", "raw-loader:./email.ts?raw", "raw-loader:./forex-effect.ts?raw", "raw-loader:./forex.ts?raw", "raw-loader:./gmail.ts?raw", "../../../src/templates/index.ts"],
|
|
4
|
+
"sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\n// @ts-ignore\nimport { transformServerSentEvents } from 'https://esm.sh/@dxos/script-toolbox';\n\n/**\n * Chatbot that answers questions based on the context data.\n */\nexport default async ({\n event: {\n data: { request },\n },\n context: { space, ai },\n}: any) => {\n const textBody = await request.text();\n let parsedRequest: any;\n try {\n parsedRequest = JSON.parse(textBody);\n } catch (err) {\n const answer = await ai.run('@cf/meta/llama-3.1-8b-instruct', {\n stream: true,\n prompt: `\n Using only the context data below to answer the user's question.\n If you cannot answer the question from the provided content, then reply with \"I don't know.\"\n\n CONTEXT:\n ${await getContext({ space })}\n\n QUESTION:\n ${textBody}\n `,\n });\n return new Response(transformServerSentEvents(answer));\n }\n\n const promptId = parsedRequest.trigger.promptId;\n const promptObject = await space.crud.query({ id: promptId }).first();\n\n if (parsedRequest.data.objects.length !== 1) {\n return new Response('Message batches not supported.');\n }\n\n const messageId = parsedRequest.data.objects[0];\n let message;\n try {\n message = await space.crud.query({ id: messageId }).first();\n } catch (err) {\n return new Response('Message not replicated yet.', { status: 409 });\n }\n\n if (message.text.includes('--------')) {\n return new Response('Message was already processed.');\n }\n\n let prompt = promptObject.template;\n for (const input of promptObject.inputs) {\n let value: string | null = null;\n if (input.type === TemplateInputType.VALUE) {\n value = String(input.value);\n } else if (input.type === TemplateInputType.RETRIEVER) {\n value = await getContext({ space });\n } else if (input.type === TemplateInputType.PASS_THROUGH) {\n value = message.text;\n }\n if (value) {\n prompt = prompt.replaceAll(`{${input.name}}`, value);\n }\n }\n\n const answer = await ai.run('@cf/meta/llama-3.1-8b-instruct', {\n stream: false,\n prompt,\n });\n const response = { response: answer.response, prompt, message };\n const textWithAnswer = message.text + '\\n--------\\n\\n' + answer.response;\n await space.crud.update({ id: messageId }, { text: textWithAnswer });\n\n return new Response(JSON.stringify(response));\n};\n\nconst getContext = async ({ space }: any) => {\n let context = '';\n const { objects: docs } = await space.crud.query({ __typename: 'dxos.org/type/Document' }).run();\n for (const doc of docs) {\n const { content } = await space.crud.query({ id: doc.content }).first();\n context += content + '\\n\\n';\n }\n return context;\n};\n\nenum TemplateInputType {\n VALUE = 0,\n PASS_THROUGH = 1,\n RETRIEVER = 2,\n FUNCTION = 3,\n QUERY = 4,\n RESOLVER = 5,\n CONTEXT = 6,\n SCHEMA = 7,\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { defineFunction, S } from 'dxos:functions';\n// @ts-ignore\nimport { Chess } from 'https://esm.sh/chess.js@0.13.1';\n\nexport default defineFunction({\n description: 'Plays a random move in a chess game.',\n\n inputSchema: S.Struct({\n changedObjectId: S.String.annotations({\n description: 'The objects to play the game on.',\n }),\n player: S.optional(S.Literal('w', 'b')).annotations({\n description: 'The player to play the game as.',\n }),\n }),\n\n outputSchema: S.Struct({\n state: S.String.annotations({\n description: 'The state of the game as an ASCII art board.',\n }),\n }),\n\n handler: async ({\n event: {\n data: { changedObjectId, player = 'b' },\n },\n context: { space },\n }: any) => {\n const { pgn } = await space.db.query({ id: changedObjectId }).first();\n const game = new Chess();\n game.load_pgn(pgn);\n if (game.turn() !== player) {\n return new Response('Invalid turn', { status: 409 });\n }\n\n const moves = game.moves();\n const move = moves[Math.floor(Math.random() * moves.length)];\n if (!move) {\n return new Response('No legal moves', { status: 406 });\n }\n\n game.move(move);\n const newPgn = game.pgn();\n await space.db.update({ id: changedObjectId }, { pgn: newPgn, fen: game.fen() });\n return { state: game.ascii() };\n },\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { defineFunction, S, create, Expando } from 'dxos:functions';\n// @ts-ignore\nimport { randText } from 'https://esm.sh/@ngneat/falso@7.1.1';\n\nexport default defineFunction({\n inputSchema: S.Struct({\n documentAmount: S.optional(S.Number),\n textSize: S.optional(S.Number),\n mutationAmount: S.optional(S.Number),\n }),\n\n outputSchema: S.Struct({}),\n\n handler: async ({\n event: {\n data: { documentAmount = 1, textSize = 10, mutationAmount = 0 },\n },\n context: { space },\n }: any) => {\n await space.db.graph.schemaRegistry.addSchema([Expando]);\n const result: Record<string, any> = {};\n const objects: Expando[] = [];\n\n // Create objects.\n for (let i = 0; i < documentAmount; i++) {\n const obj = space.db.add(\n create(Expando, {\n name: 'scriptGenerated',\n content: randText({ charCount: textSize }),\n }),\n );\n objects.push(obj);\n const objectResult: any = {};\n // Mutate the object.\n for (let i = 0; i < mutationAmount; i++) {\n obj.content = randText({ charCount: textSize });\n }\n objectResult.mutations = mutationAmount;\n objectResult.contentLength = obj.content.length;\n result[obj.id] = objectResult;\n }\n\n // Flush and wait for data to propagate.\n await space.db.flush();\n await new Promise((resolve) => setTimeout(resolve, 10_000));\n return result;\n },\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { create, defineFunction, DXN, Filter, ObjectId, S } from 'dxos:functions';\nimport {\n FetchHttpClient,\n // @ts-ignore\n} from 'https://esm.sh/@effect/platform@0.77.2?deps=effect@3.13.3';\n// @ts-ignore\nimport { DiscordConfig, DiscordREST, DiscordRESTMemoryLive } from 'https://esm.sh/dfx@0.113.0?deps=effect@3.13.3';\n// @ts-ignore\nimport { Effect, Config, Redacted, Ref } from 'https://esm.sh/effect@3.13.3';\n\nimport { Type } from '@dxos/echo';\n\nconst MessageSchema = S.Struct({\n id: ObjectId,\n foreignId: S.Any, // bigint?\n from: S.String,\n created: S.String,\n content: S.String,\n}).pipe(\n Type.def({\n typename: 'example.com/type/Message',\n version: '0.1.0',\n }),\n);\n\nconst DEFAULT_AFTER = 1704067200; // 2024-01-01\n\nconst generateSnowflake = (unixTimestamp: number): bigint => {\n const discordEpoch = 1420070400000n; // Discord Epoch (ms)\n return (BigInt(unixTimestamp * 1000) - discordEpoch) << 22n;\n};\n\nexport default defineFunction({\n inputSchema: S.Struct({\n // TODO(wittjosiah): Remove. This is used to provide a terminal for a cron trigger.\n tick: S.optional(S.String),\n channelId: S.String,\n after: S.optional(S.Number),\n pageSize: S.optional(S.Number),\n queueId: S.String,\n }),\n\n outputSchema: S.Struct({\n newMessages: S.Number,\n }),\n\n handler: ({\n event: {\n data: { channelId, queueId, after = DEFAULT_AFTER, pageSize = 5 },\n },\n context: { space },\n }: any) =>\n Effect.gen(function* () {\n const { token } = yield* Effect.tryPromise({\n try: () => space.db.query(Filter.typename('dxos.org/type/AccessToken', { source: 'discord.com' })).first(),\n catch: (e: any) => e,\n });\n const { objects } = yield* Effect.tryPromise({\n try: () => space.queues.queryQueue(DXN.parse(queueId)),\n catch: (e: any) => e,\n });\n const backfill = objects.length === 0;\n const newMessages = yield* Ref.make(0);\n const lastMessage = yield* Ref.make(objects.at(-1));\n\n const enqueueMessages = Effect.gen(function* () {\n const rest = yield* DiscordREST;\n\n while (true) {\n const last = yield* Ref.get(lastMessage);\n const options = {\n after: backfill && !last ? `${generateSnowflake(after)}` : last?.foreignId,\n limit: pageSize,\n };\n const messages = yield* rest.getChannelMessages(channelId, options).pipe((res: any) => res.json);\n const queueMessages = messages\n .map((message: any) =>\n create(MessageSchema, {\n id: ObjectId.random(),\n foreignId: message.id,\n from: message.author.username,\n created: message.timestamp,\n content: message.content,\n }),\n )\n .toReversed();\n if (queueMessages.length > 0) {\n yield* Effect.tryPromise({\n try: () => space.queues.insertIntoQueue(DXN.parse(queueId), queueMessages),\n catch: (e: any) => e,\n });\n yield* Ref.update(newMessages, (n: any) => n + queueMessages.length);\n yield* Ref.update(lastMessage, (m: any) => queueMessages.at(-1));\n }\n if (messages.length < pageSize) {\n break;\n }\n }\n }).pipe(\n Effect.provide(DiscordRESTMemoryLive),\n Effect.provide(\n DiscordConfig.layerConfig({\n token: Config.succeed(Redacted.make(token)),\n }),\n ),\n Effect.provide(FetchHttpClient.layer),\n );\n\n yield* enqueueMessages;\n return { newMessages: yield* Ref.get(newMessages) };\n }),\n});\n", "//\n// Copyright 2024 DXOS.org\n//\n\n/**\n * Echos the request data.\n */\nexport default async ({\n event: {\n data: { request },\n },\n}: any) => {\n const data = await request.json();\n return new Response(JSON.stringify(data ?? {}), {\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\n/**\n * Appends a message to the end of a Document configured through a trigger.\n * Trigger must have a targetDocumentId field set in Meta.\n */\nexport default async ({\n event: {\n data: { request },\n },\n context: { space },\n}: any) => {\n const { data, trigger } = (await request.json()) as RequestPayload;\n\n const documentId = trigger.meta.targetDocumentId;\n const document = await space.db.query({ id: documentId }, { format: 'plain' }).first();\n\n const contentId = document.content['/'].split(':')[3];\n const documentContent = await space.db.query({ id: contentId }, { format: 'plain' }).first();\n const modifiedContent = [\n documentContent.content,\n '',\n '---',\n `**From:** ${data.from}`,\n `**Subject:** ${data.subject}`,\n `**Date:** ${data.created}`,\n '',\n data.body,\n ].join('\\n');\n\n await space.db.update({ id: contentId }, { content: modifiedContent });\n\n return new Response(JSON.stringify({ success: true }));\n};\n\ntype RequestPayload = {\n data: { from: string; subject: string; created: string; body: string };\n trigger: { meta: { targetDocumentId: string } };\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { S, defineFunction } from 'dxos:functions';\nimport {\n HttpClient,\n HttpClientRequest,\n FetchHttpClient,\n // @ts-ignore\n} from 'https://esm.sh/@effect/platform@0.77.2?deps=effect@3.13.3';\n// @ts-ignore\nimport { Effect, Schedule } from 'https://esm.sh/effect@3.13.3';\n\nexport default defineFunction({\n description: 'Returns the exchange rate between two currencies.',\n\n inputSchema: S.Struct({\n from: S.String.annotations({ description: 'The source currency' }),\n to: S.String.annotations({ description: 'The target currency' }),\n }),\n\n outputSchema: S.String.annotations({ description: 'The exchange rate between the two currencies' }),\n\n handler: async ({\n event: {\n data: { from, to },\n },\n }: any) =>\n Effect.gen(function* () {\n const res = yield* HttpClientRequest.get(`https://free.ratesdb.com/v1/rates?from=${from}&to=${to}`).pipe(\n HttpClient.execute,\n Effect.flatMap((res: any) => res.json),\n Effect.timeout('1 second'),\n Effect.retry(Schedule.exponential(1_000).pipe(Schedule.compose(Schedule.recurs(3)))),\n Effect.scoped,\n );\n\n return res.data.rates[to].toString();\n }).pipe(Effect.provide(FetchHttpClient.layer)),\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { defineFunction, S } from 'dxos:functions';\n\nexport default defineFunction({\n description: 'Returns the exchange rate between two currencies.',\n\n inputSchema: S.Struct({\n from: S.String.annotations({ description: 'The source currency' }),\n to: S.String.annotations({ description: 'The target currency' }),\n }),\n\n handler: async ({\n event: {\n data: { from, to },\n },\n }: any) => {\n const res = await fetch(`https://free.ratesdb.com/v1/rates?from=${from}&to=${to}`);\n const {\n data: { rates },\n } = await res.json();\n\n return rates[to].toString();\n },\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { create, defineFunction, Filter, ObjectId, S } from 'dxos:functions';\n// @ts-ignore\nimport {\n HttpClient,\n HttpClientRequest,\n FetchHttpClient,\n // @ts-ignore\n} from 'https://esm.sh/@effect/platform@0.77.2?deps=effect@3.13.3';\n// @ts-ignore\nimport { format, subDays } from 'https://esm.sh/date-fns@3.3.1';\n// @ts-ignore\nimport { pipe, Chunk, Effect, Ref, Schedule, Stream } from 'https://esm.sh/effect@3.13.3';\n\nimport { Type } from '@dxos/echo';\n\nexport default defineFunction({\n inputSchema: S.Struct({\n mailboxId: S.String,\n userId: S.optional(S.String).pipe(S.withDecodingDefault(() => 'me')),\n after: S.optional(S.Union(S.Number, S.String)).pipe(\n S.withDecodingDefault(() => format(subDays(new Date(), 30), 'yyyy-MM-dd')),\n ),\n pageSize: S.optional(S.Number).pipe(S.withDecodingDefault(() => 100)),\n // TODO(wittjosiah): Remove. This is used to provide a terminal for a cron trigger.\n tick: S.optional(S.String),\n }),\n\n outputSchema: S.Struct({\n newMessages: S.Number,\n }),\n\n handler: ({\n context: { space },\n event: {\n data: { mailboxId, userId, after, pageSize },\n },\n }: any) =>\n Effect.gen(function* () {\n const { token } = yield* Effect.tryPromise({\n try: () => space.db.query(Filter.typename('dxos.org/type/AccessToken', { source: 'gmail.com' })).first(),\n catch: (e: any) => e,\n });\n\n // NOTE: Google API bundles size is v. large and caused runtime issues.\n const makeRequest = (url: string) =>\n pipe(\n url,\n HttpClientRequest.get,\n HttpClientRequest.setHeaders({ Authorization: `Bearer ${token}`, Accept: 'application/json' }),\n HttpClient.execute,\n Effect.flatMap((res: any) => res.json),\n Effect.timeout('1 second'),\n Effect.retry(Schedule.exponential(1000).pipe(Schedule.compose(Schedule.recurs(3)))),\n Effect.scoped,\n );\n\n const listMessages = (userId: string, q: string, pageSize: number, pageToken: string | null) =>\n makeRequest(getUrl(userId, undefined, { q, pageSize, pageToken }));\n\n const getMessage = (userId: string, messageId: string) => makeRequest(getUrl(userId, messageId));\n\n const mailbox = yield* Effect.tryPromise({\n try: () => space.db.query({ id: mailboxId }).first(),\n catch: (e: any) => e,\n });\n const { objects } = yield* Effect.tryPromise({\n try: () => space.queues.queryQueue(mailbox.queue.dxn),\n catch: (e: any) => e,\n });\n const newMessages = yield* Ref.make([]);\n const nextPage = yield* Ref.make(null);\n\n do {\n const last = objects.at(-1);\n const q = last\n ? `in:inbox after:${Math.floor(new Date(last.created).getTime() / 1000)}`\n : `in:inbox after:${after}`;\n const pageToken = yield* Ref.get(nextPage);\n const { messages, nextPageToken } = yield* listMessages(userId, q, pageSize, pageToken);\n yield* Ref.update(nextPage, () => nextPageToken);\n for (const message of messages) {\n const messageDetails = yield* getMessage(userId, message.id);\n const created = new Date(parseInt(messageDetails.internalDate)).toISOString();\n const from = messageDetails.payload.headers.find((h: any) => h.name === 'From');\n const sender = from && parseEmailString(from.value);\n // TODO(wittjosiah): Improve parsing of email contents.\n const content =\n messageDetails.payload.body?.data ??\n messageDetails.payload.parts?.find((p: any) => p.mimeType === 'text/plain')?.body.data;\n // Skip the message if content or sender is missing.\n // Skip the message if it's the same as the last message.\n // TODO(wittjosiah): This comparison should be done via foreignId probably.\n if (!content || !sender || created === last?.created) {\n continue;\n }\n const subject = messageDetails.payload.headers.find((h: any) => h.name === 'Subject')?.value;\n const object = create(MessageType, {\n id: ObjectId.random(),\n created,\n sender,\n blocks: [\n {\n type: 'text',\n text: Buffer.from(content, 'base64').toString('utf-8'),\n },\n ],\n properties: {\n subject,\n threadId: message.threadId,\n },\n });\n // TODO(wittjosiah): Set foreignId in object meta.\n yield* Ref.update(newMessages, (n: any) => [object, ...n]);\n }\n } while (yield* Ref.get(nextPage));\n\n const queueMessages = yield* Ref.get(newMessages);\n if (queueMessages.length > 0) {\n yield* pipe(\n queueMessages,\n Stream.fromIterable,\n Stream.grouped(10),\n Stream.flatMap((batch: any) =>\n Effect.tryPromise({\n try: () => space.queues.insertIntoQueue(mailbox.queue.dxn, Chunk.toReadonlyArray(batch)),\n catch: (e: any) => e,\n }),\n ),\n Stream.runDrain,\n );\n }\n\n return { newMessages: queueMessages.length };\n }).pipe(Effect.provide(FetchHttpClient.layer)),\n});\n\nconst getUrl = (userId: string, messageId?: string, params?: Record<string, any>) => {\n const api = new URL(\n [`https://gmail.googleapis.com/gmail/v1/users/${userId}/messages`, messageId].filter(Boolean).join('/'),\n );\n Object.entries(params ?? {}).forEach(([key, value]) => api.searchParams.set(key, value));\n return api.toString();\n};\n\n/**\n * Parses an email string in the format \"Name <email@example.com>\" into separate name and email components.\n */\nconst parseEmailString = (emailString: string): { name?: string; email: string } | undefined => {\n const match = emailString.match(/^([^<]+?)\\s*<([^>]+@[^>]+)>$/);\n if (match) {\n const [, name, email] = match;\n return {\n name: name.trim(),\n email: email.trim(),\n };\n }\n\n return undefined;\n};\n\n//\n// Schemas\n// TODO(wittjosiah): These schemas should be imported from @dxos/S.\n//\n\nconst ActorRoles = ['user', 'assistant'] as const;\nconst ActorRole = S.Literal(...ActorRoles);\ntype ActorRole = S.S.Type<typeof ActorRole>;\n\nconst ActorSchema = S.Struct({\n identityKey: S.optional(S.String),\n email: S.optional(S.String),\n name: S.optional(S.String),\n role: S.optional(ActorRole),\n});\n\nconst AbstractContentBlock = S.Struct({\n pending: S.optional(S.Boolean),\n});\ntype AbstractContentBlock = S.S.Type<typeof AbstractContentBlock>;\nconst TextContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('text'),\n disposition: S.optional(S.String),\n text: S.String,\n }),\n).pipe(S.mutable);\ntype TextContentBlock = S.S.Type<typeof TextContentBlock>;\nconst JsonContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('json'),\n disposition: S.optional(S.String),\n data: S.String,\n }),\n).pipe(S.mutable);\ntype JsonContentBlock = S.S.Type<typeof JsonContentBlock>;\nconst Base64ImageSource = S.Struct({\n type: S.Literal('base64'),\n mediaType: S.String,\n data: S.String,\n}).pipe(S.mutable);\nconst HttpImageSource = S.Struct({\n type: S.Literal('http'),\n url: S.String,\n}).pipe(S.mutable);\nconst ImageSource = S.Union(Base64ImageSource, HttpImageSource);\ntype ImageSource = S.S.Type<typeof ImageSource>;\nconst ImageContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('image'),\n id: S.optional(S.String),\n source: S.optional(ImageSource),\n }),\n).pipe(S.mutable);\ntype ImageContentBlock = S.S.Type<typeof ImageContentBlock>;\nconst ReferenceContentBlock = S.extend(\n AbstractContentBlock,\n S.Struct({\n type: S.Literal('reference'),\n reference: S.Any,\n }),\n).pipe(S.mutable);\ntype ReferenceContentBlock = S.S.Type<typeof ReferenceContentBlock>;\nconst MessageContentBlock = S.Union(TextContentBlock, JsonContentBlock, ImageContentBlock, ReferenceContentBlock);\n\nconst MessageType = S.Struct({\n id: ObjectId,\n created: S.String.annotations({\n description: 'ISO date string when the message was sent.',\n }),\n sender: ActorSchema.annotations({\n description: 'Identity of the message sender.',\n }),\n blocks: S.Array(MessageContentBlock).annotations({\n description: 'Contents of the message.',\n }),\n properties: S.optional(\n S.mutable(\n S.Record({ key: S.String, value: S.Any }).annotations({\n description: 'Custom properties for specific message types (e.g. attention context, email subject, etc.).',\n }),\n ),\n ),\n}).pipe(\n Type.def({\n typename: 'dxos.org/type/Message',\n version: '0.1.0',\n }),\n);\ntype MessageType = S.S.Type<typeof MessageType>;\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport chat from './chat.ts?raw';\nimport chess from './chess.ts?raw';\nimport dataGenerator from './data-generator.ts?raw';\nimport discord from './discord.ts?raw';\nimport echo from './echo.ts?raw';\nimport email from './email.ts?raw';\nimport forexEffect from './forex-effect.ts?raw';\nimport forex from './forex.ts?raw';\nimport gmail from './gmail.ts?raw';\n\nconst removeHeader = (str: string) => str.split('\\n').slice(4).join('\\n');\n\nexport type Template = {\n id: string;\n name: string;\n source: string;\n presetId?: string;\n};\n\nexport const templates: Template[] = [\n {\n id: 'dxos.org/script/echo',\n name: 'Echo',\n source: removeHeader(echo),\n },\n {\n id: 'dxos.org/script/forex',\n name: 'Forex',\n source: removeHeader(forex),\n },\n {\n id: 'dxos.org/script/forex-effect',\n name: 'Forex (Effect)',\n source: removeHeader(forexEffect),\n },\n {\n id: 'dxos.org/script/gpt',\n name: 'Gpt',\n source: removeHeader(chat),\n presetId: 'dxos.org/function/gpt',\n },\n {\n id: 'dxos.org/script/chess',\n name: 'Chess',\n source: removeHeader(chess),\n presetId: 'dxos.org/function/chess',\n },\n {\n id: 'dxos.org/script/email',\n name: 'Email',\n source: removeHeader(email),\n presetId: 'dxos.org/function/email',\n },\n {\n id: 'dxos.org/script/discord',\n name: 'Discord',\n source: removeHeader(discord),\n presetId: 'dxos.org/function/discord',\n },\n {\n id: 'dxos.org/script/gmail',\n name: 'Gmail',\n source: removeHeader(gmail),\n presetId: 'dxos.org/function/gmail',\n },\n {\n id: 'dxos.org/script/data-generator',\n name: 'Data Generator',\n source: removeHeader(dataGenerator),\n presetId: 'dxos.org/function/data-generator',\n },\n];\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAA,eAAA;ACAA,IAAA,gBAAA;ACAA,IAAA,yBAAA;ACAA,IAAA,kBAAA;ACAA,IAAA,eAAA;ACAA,IAAA,gBAAA;ACAA,IAAA,uBAAA;ACAA,IAAA,gBAAA;ACAA,IAAA,gBAAA;ACcA,IAAMA,eAAe,CAACC,QAAgBA,IAAIC,MAAM,IAAA,EAAMC,MAAM,CAAA,EAAGC,KAAK,IAAA;AAS7D,IAAMC,YAAwB;EACnC;IACEC,IAAI;IACJC,MAAM;IACNC,QAAQR,aAAaS,YAAAA;EACvB;EACA;IACEH,IAAI;IACJC,MAAM;IACNC,QAAQR,aAAaU,aAAAA;EACvB;EACA;IACEJ,IAAI;IACJC,MAAM;IACNC,QAAQR,aAAaW,oBAAAA;EACvB;EACA;IACEL,IAAI;IACJC,MAAM;IACNC,QAAQR,aAAaY,YAAAA;IACrBC,UAAU;EACZ;EACA;IACEP,IAAI;IACJC,MAAM;IACNC,QAAQR,aAAac,aAAAA;IACrBD,UAAU;EACZ;EACA;IACEP,IAAI;IACJC,MAAM;IACNC,QAAQR,aAAae,aAAAA;IACrBF,UAAU;EACZ;EACA;IACEP,IAAI;IACJC,MAAM;IACNC,QAAQR,aAAagB,eAAAA;IACrBH,UAAU;EACZ;EACA;IACEP,IAAI;IACJC,MAAM;IACNC,QAAQR,aAAaiB,aAAAA;IACrBJ,UAAU;EACZ;EACA;IACEP,IAAI;IACJC,MAAM;IACNC,QAAQR,aAAakB,sBAAAA;IACrBL,UAAU;EACZ;;",
|
|
6
|
+
"names": ["removeHeader", "str", "split", "slice", "join", "templates", "id", "name", "source", "echo", "forex", "forexEffect", "chat", "presetId", "chess", "email", "discord", "gmail", "dataGenerator"]
|
|
7
|
+
}
|