@dxos/functions 0.8.3 → 0.8.4-main.28f8d3d
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/bundler/index.mjs +22 -10
- package/dist/lib/browser/bundler/index.mjs.map +3 -3
- package/dist/lib/browser/chunk-M2OIFLGE.mjs +486 -0
- package/dist/lib/browser/chunk-M2OIFLGE.mjs.map +7 -0
- package/dist/lib/browser/edge/index.mjs +2 -2
- package/dist/lib/browser/edge/index.mjs.map +1 -1
- package/dist/lib/browser/index.mjs +51 -37
- package/dist/lib/browser/index.mjs.map +3 -3
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/browser/testing/index.mjs +39 -8
- package/dist/lib/browser/testing/index.mjs.map +4 -4
- package/dist/lib/node-esm/bundler/index.mjs +22 -10
- package/dist/lib/node-esm/bundler/index.mjs.map +3 -3
- package/dist/lib/node-esm/chunk-K7REX6H4.mjs +488 -0
- package/dist/lib/node-esm/chunk-K7REX6H4.mjs.map +7 -0
- package/dist/lib/node-esm/edge/index.mjs +2 -2
- package/dist/lib/node-esm/edge/index.mjs.map +1 -1
- package/dist/lib/node-esm/index.mjs +51 -37
- package/dist/lib/node-esm/index.mjs.map +3 -3
- package/dist/lib/node-esm/meta.json +1 -1
- package/dist/lib/node-esm/testing/index.mjs +39 -8
- package/dist/lib/node-esm/testing/index.mjs.map +4 -4
- package/dist/types/src/bundler/bundler.d.ts +1 -2
- package/dist/types/src/bundler/bundler.d.ts.map +1 -1
- package/dist/types/src/edge/functions.d.ts +1 -1
- package/dist/types/src/edge/functions.d.ts.map +1 -1
- package/dist/types/src/errors.d.ts +70 -0
- package/dist/types/src/errors.d.ts.map +1 -0
- package/dist/types/src/executor/executor.d.ts +3 -0
- package/dist/types/src/executor/executor.d.ts.map +1 -1
- package/dist/types/src/handler.d.ts +16 -15
- package/dist/types/src/handler.d.ts.map +1 -1
- package/dist/types/src/index.d.ts +1 -0
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/schema.d.ts +5 -5
- package/dist/types/src/services/credentials.d.ts +7 -3
- package/dist/types/src/services/credentials.d.ts.map +1 -1
- package/dist/types/src/services/database.d.ts +71 -3
- package/dist/types/src/services/database.d.ts.map +1 -1
- package/dist/types/src/services/event-logger.d.ts +65 -30
- package/dist/types/src/services/event-logger.d.ts.map +1 -1
- package/dist/types/src/services/index.d.ts +2 -2
- package/dist/types/src/services/index.d.ts.map +1 -1
- package/dist/types/src/services/local-function-execution.d.ts +12 -0
- package/dist/types/src/services/local-function-execution.d.ts.map +1 -0
- package/dist/types/src/services/queues.d.ts +32 -6
- package/dist/types/src/services/queues.d.ts.map +1 -1
- package/dist/types/src/services/remote-function-execution-service.d.ts +15 -0
- package/dist/types/src/services/remote-function-execution-service.d.ts.map +1 -0
- package/dist/types/src/services/service-container.d.ts +29 -17
- package/dist/types/src/services/service-container.d.ts.map +1 -1
- package/dist/types/src/services/service-registry.d.ts +29 -0
- package/dist/types/src/services/service-registry.d.ts.map +1 -0
- package/dist/types/src/services/service-registry.test.d.ts +2 -0
- package/dist/types/src/services/service-registry.test.d.ts.map +1 -0
- package/dist/types/src/services/tracing.d.ts +13 -2
- package/dist/types/src/services/tracing.d.ts.map +1 -1
- package/dist/types/src/testing/index.d.ts +1 -0
- package/dist/types/src/testing/index.d.ts.map +1 -1
- package/dist/types/src/testing/layer.d.ts +10 -0
- package/dist/types/src/testing/layer.d.ts.map +1 -0
- package/dist/types/src/testing/logger.d.ts +3 -3
- package/dist/types/src/testing/logger.d.ts.map +1 -1
- package/dist/types/src/testing/services.d.ts +55 -9
- package/dist/types/src/testing/services.d.ts.map +1 -1
- package/dist/types/src/trace.d.ts +3 -5
- package/dist/types/src/trace.d.ts.map +1 -1
- package/dist/types/src/translations.d.ts +9 -9
- package/dist/types/src/translations.d.ts.map +1 -1
- package/dist/types/src/types.d.ts +7 -7
- package/dist/types/src/types.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +36 -26
- package/src/bundler/bundler.test.ts +1 -1
- package/src/bundler/bundler.ts +26 -4
- package/src/edge/functions.ts +1 -1
- package/src/errors.ts +13 -0
- package/src/executor/executor.ts +20 -13
- package/src/handler.ts +34 -25
- package/src/index.ts +1 -0
- package/src/services/credentials.ts +47 -4
- package/src/services/database.ts +91 -3
- package/src/services/event-logger.ts +68 -37
- package/src/services/index.ts +2 -2
- package/src/services/local-function-execution.ts +74 -0
- package/src/services/queues.ts +51 -11
- package/src/services/{function-call-service.ts → remote-function-execution-service.ts} +7 -5
- package/src/services/service-container.ts +47 -42
- package/src/services/service-registry.test.ts +42 -0
- package/src/services/service-registry.ts +59 -0
- package/src/services/tracing.ts +19 -2
- package/src/testing/index.ts +1 -0
- package/src/testing/layer.ts +31 -0
- package/src/testing/logger.ts +4 -4
- package/src/testing/services.ts +97 -14
- package/src/trace.ts +3 -5
- package/src/translations.ts +4 -4
- package/src/types.ts +1 -1
- package/dist/lib/browser/chunk-WEFZUEL2.mjs +0 -300
- package/dist/lib/browser/chunk-WEFZUEL2.mjs.map +0 -7
- package/dist/lib/node/bundler/index.cjs +0 -260
- package/dist/lib/node/bundler/index.cjs.map +0 -7
- package/dist/lib/node/chunk-IJAE7FZK.cjs +0 -320
- package/dist/lib/node/chunk-IJAE7FZK.cjs.map +0 -7
- package/dist/lib/node/edge/index.cjs +0 -94
- package/dist/lib/node/edge/index.cjs.map +0 -7
- package/dist/lib/node/index.cjs +0 -522
- package/dist/lib/node/index.cjs.map +0 -7
- package/dist/lib/node/meta.json +0 -1
- package/dist/lib/node/testing/index.cjs +0 -43
- package/dist/lib/node/testing/index.cjs.map +0 -7
- package/dist/lib/node-esm/chunk-LIYPMWNQ.mjs +0 -302
- package/dist/lib/node-esm/chunk-LIYPMWNQ.mjs.map +0 -7
- package/dist/types/src/services/ai.d.ts +0 -12
- package/dist/types/src/services/ai.d.ts.map +0 -1
- package/dist/types/src/services/function-call-service.d.ts +0 -16
- package/dist/types/src/services/function-call-service.d.ts.map +0 -1
- package/src/services/ai.ts +0 -32
|
@@ -1,9 +1,12 @@
|
|
|
1
|
-
//
|
|
1
|
+
// src/bundler/bundler.ts
|
|
2
|
+
import { FetchHttpClient, HttpClient } from "@effect/platform";
|
|
3
|
+
import { Duration, Effect, Schedule, pipe } from "effect";
|
|
2
4
|
import { build, initialize } from "esbuild-wasm";
|
|
3
5
|
import { subtleCrypto } from "@dxos/crypto";
|
|
6
|
+
import { runAndForwardErrors } from "@dxos/effect";
|
|
4
7
|
import { invariant } from "@dxos/invariant";
|
|
5
8
|
import { log } from "@dxos/log";
|
|
6
|
-
var __dxlog_file = "/
|
|
9
|
+
var __dxlog_file = "/__w/dxos/dxos/packages/core/functions/src/bundler/bundler.ts";
|
|
7
10
|
var initialized;
|
|
8
11
|
var initializeBundler = async (options) => {
|
|
9
12
|
await (initialized ??= initialize({
|
|
@@ -11,6 +14,7 @@ var initializeBundler = async (options) => {
|
|
|
11
14
|
}));
|
|
12
15
|
};
|
|
13
16
|
var Bundler = class {
|
|
17
|
+
_options;
|
|
14
18
|
constructor(_options) {
|
|
15
19
|
this._options = _options;
|
|
16
20
|
}
|
|
@@ -26,7 +30,7 @@ var Bundler = class {
|
|
|
26
30
|
if (this._options.platform === "browser") {
|
|
27
31
|
invariant(initialized, "Compiler not initialized.", {
|
|
28
32
|
F: __dxlog_file,
|
|
29
|
-
L:
|
|
33
|
+
L: 73,
|
|
30
34
|
S: this,
|
|
31
35
|
A: [
|
|
32
36
|
"initialized",
|
|
@@ -120,7 +124,7 @@ var Bundler = class {
|
|
|
120
124
|
});
|
|
121
125
|
log("compile complete", result.metafile, {
|
|
122
126
|
F: __dxlog_file,
|
|
123
|
-
L:
|
|
127
|
+
L: 137,
|
|
124
128
|
S: this,
|
|
125
129
|
C: (f, a) => f(...a)
|
|
126
130
|
});
|
|
@@ -138,7 +142,7 @@ var Bundler = class {
|
|
|
138
142
|
analyzeImports(result) {
|
|
139
143
|
invariant(result.outputFiles, void 0, {
|
|
140
144
|
F: __dxlog_file,
|
|
141
|
-
L:
|
|
145
|
+
L: 150,
|
|
142
146
|
S: this,
|
|
143
147
|
A: [
|
|
144
148
|
"result.outputFiles",
|
|
@@ -201,6 +205,8 @@ var analyzeSourceFileImports = (code) => {
|
|
|
201
205
|
};
|
|
202
206
|
});
|
|
203
207
|
};
|
|
208
|
+
var MAX_RETRIES = 5;
|
|
209
|
+
var INITIAL_DELAY = 1e3;
|
|
204
210
|
var httpPlugin = {
|
|
205
211
|
name: "http",
|
|
206
212
|
setup: (build2) => {
|
|
@@ -221,11 +227,17 @@ var httpPlugin = {
|
|
|
221
227
|
filter: /.*/,
|
|
222
228
|
namespace: "http-url"
|
|
223
229
|
}, async (args) => {
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
230
|
+
return Effect.gen(function* () {
|
|
231
|
+
const response = yield* HttpClient.get(args.path);
|
|
232
|
+
if (response.status !== 200) {
|
|
233
|
+
throw new Error(`failed to fetch: ${response.status}`);
|
|
234
|
+
}
|
|
235
|
+
const text = yield* response.text;
|
|
236
|
+
return {
|
|
237
|
+
contents: text,
|
|
238
|
+
loader: "jsx"
|
|
239
|
+
};
|
|
240
|
+
}).pipe(Effect.retry(pipe(Schedule.exponential(Duration.millis(INITIAL_DELAY)), Schedule.jittered, Schedule.intersect(Schedule.recurs(MAX_RETRIES - 1)))), Effect.provide(FetchHttpClient.layer), runAndForwardErrors);
|
|
229
241
|
});
|
|
230
242
|
}
|
|
231
243
|
};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/bundler/bundler.ts"],
|
|
4
|
-
"sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport {
|
|
5
|
-
"mappings": ";
|
|
6
|
-
"names": ["build", "initialize", "subtleCrypto", "invariant", "log", "initialized", "initializeBundler", "options", "wasmURL", "wasmUrl", "Bundler", "_options", "bundle", "path", "source", "sandboxedModules", "providedModules", "createResult", "result", "timestamp", "Date", "now", "sourceHash", "Buffer", "from", "digest", "undefined", "platform", "imports", "analyzeSourceFileImports", "conditions", "metafile", "write", "entryPoints", "format", "plugins", "name", "setup", "onResolve", "filter", "external", "split", "namespace", "onLoad", "contents", "loader", "module", "RegExp", "namedImports", "find", "entry", "moduleIdentifier", "join", "JSON", "stringify", "httpPlugin", "analyzeImports", "outputFiles", "text", "err", "error", "parsedImports", "allMatches", "IMPORT_REGEX", "Object", "values", "outputs", "map", "parsedImport", "capture", "NAMED_IMPORTS_REGEX", "lastIndex", "namedImportsMatch", "exec", "forEach", "importName", "push", "trim", "moduleUrl", "defaultImport", "code", "defaultImportName", "wildcardImportName", "quotes", "regex", "str", "match", "matches", "slice", "args", "URL", "importer", "toString", "response", "
|
|
4
|
+
"sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport { FetchHttpClient, HttpClient } from '@effect/platform';\nimport { Duration, Effect, Schedule, pipe } from 'effect';\nimport { type BuildOptions, type BuildResult, type Loader, type Plugin, build, initialize } from 'esbuild-wasm';\n\nimport { subtleCrypto } from '@dxos/crypto';\nimport { runAndForwardErrors } from '@dxos/effect';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\n\nexport type Import = {\n moduleUrl: string;\n defaultImport: boolean;\n namedImports: string[];\n};\n\nexport type BundleOptions = {\n /**\n * Path to the source file on the local file system.\n * If provided, the path will be used instead of the `source` code.\n */\n path?: string;\n\n /**\n * Source code to bundle.\n * Required if `path` is not provided.\n */\n source?: string;\n};\n\nexport type BundleResult = {\n timestamp: number;\n sourceHash?: Buffer;\n imports?: Import[];\n bundle?: string;\n error?: any;\n};\n\nexport type BundlerOptions = {\n platform: BuildOptions['platform'];\n sandboxedModules: string[];\n remoteModules: Record<string, string>;\n};\n\nlet initialized: Promise<void>;\nexport const initializeBundler = async (options: { wasmUrl: string }) => {\n await (initialized ??= initialize({\n wasmURL: options.wasmUrl,\n }));\n};\n\n/**\n * ESBuild bundler.\n */\nexport class Bundler {\n constructor(private readonly _options: BundlerOptions) {}\n\n async bundle({ path, source }: BundleOptions): Promise<BundleResult> {\n const { sandboxedModules: providedModules, ...options } = this._options;\n\n const createResult = async (result?: Partial<BundleResult>) => {\n return {\n timestamp: Date.now(),\n sourceHash: source ? Buffer.from(await subtleCrypto.digest('SHA-256', Buffer.from(source))) : undefined,\n ...result,\n };\n };\n\n if (this._options.platform === 'browser') {\n invariant(initialized, 'Compiler not initialized.');\n await initialized;\n }\n\n const imports = source ? analyzeSourceFileImports(source) : [];\n\n // https://esbuild.github.io/api/#build\n try {\n const result = await build({\n platform: options.platform,\n conditions: ['workerd', 'browser'],\n metafile: true,\n write: false,\n entryPoints: [path ?? 'memory:main.tsx'],\n bundle: true,\n format: 'esm',\n plugins: [\n {\n name: 'memory',\n setup: (build) => {\n build.onResolve({ filter: /^\\.\\/runtime\\.js$/ }, ({ path }) => {\n return { path, external: true };\n });\n\n build.onResolve({ filter: /^dxos:functions$/ }, ({ path }) => {\n return { path: './runtime.js', external: true };\n });\n\n build.onResolve({ filter: /^memory:/ }, ({ path }) => {\n return { path: path.split(':')[1], namespace: 'memory' };\n });\n\n build.onLoad({ filter: /.*/, namespace: 'memory' }, ({ path }) => {\n if (path === 'main.tsx') {\n return {\n contents: source,\n loader: 'tsx',\n };\n }\n });\n\n for (const module of providedModules) {\n build.onResolve({ filter: new RegExp(`^${module}$`) }, ({ path }) => {\n return { path, namespace: 'injected-module' };\n });\n }\n\n build.onLoad({ filter: /.*/, namespace: 'injected-module' }, ({ path }) => {\n const namedImports = imports.find((entry) => entry.moduleIdentifier === path)?.namedImports ?? [];\n return {\n contents: `\n const { ${namedImports.join(',')} } = window.__DXOS_SANDBOX_MODULES__[${JSON.stringify(path)}];\n export { ${namedImports.join(',')} };\n export default window.__DXOS_SANDBOX_MODULES__[${JSON.stringify(path)}].default;\n `,\n loader: 'tsx',\n };\n });\n },\n },\n httpPlugin,\n ],\n });\n\n log('compile complete', result.metafile);\n\n return await createResult({\n imports: this.analyzeImports(result),\n bundle: result.outputFiles![0].text,\n });\n } catch (err) {\n return await createResult({ error: err });\n }\n }\n\n // TODO(dmaretskyi): In the future we can replace the compiler with SWC with plugins running in WASM.\n analyzeImports(result: BuildResult): Import[] {\n invariant(result.outputFiles);\n\n // TODO(dmaretskyi): Support import aliases and wildcard imports.\n const parsedImports = allMatches(IMPORT_REGEX, result.outputFiles[0].text);\n return Object.values(result.metafile!.outputs)[0].imports.map((entry): Import => {\n const namedImports: string[] = [];\n\n const parsedImport = parsedImports.find((capture) => capture?.[4] === entry.path);\n if (parsedImport?.[2]) {\n NAMED_IMPORTS_REGEX.lastIndex = 0;\n const namedImportsMatch = NAMED_IMPORTS_REGEX.exec(parsedImport[2]);\n if (namedImportsMatch) {\n namedImportsMatch[1].split(',').forEach((importName) => {\n namedImports.push(importName.trim());\n });\n }\n }\n\n return {\n moduleUrl: entry.path,\n defaultImport: !!parsedImport?.[1],\n namedImports,\n };\n });\n }\n\n analyzeSourceFileImports(code: string): {\n defaultImportName: string;\n namedImports: string[];\n wildcardImportName: string;\n moduleIdentifier: string;\n quotes: string;\n }[] {\n // TODO(dmaretskyi): Support import aliases and wildcard imports.\n const parsedImports = allMatches(IMPORT_REGEX, code);\n return parsedImports.map((capture) => {\n return {\n defaultImportName: capture[1],\n namedImports: capture[2]?.split(',').map((importName) => importName.trim()),\n wildcardImportName: capture[3],\n moduleIdentifier: capture[4],\n quotes: capture[5],\n };\n });\n }\n}\n\n// https://regex101.com/r/FEN5ks/1\n// https://stackoverflow.com/a/73265022\n// $1 = default import name (can be non-existent)\n// $2 = destructured exports (can be non-existent)\n// $3 = wildcard import name (can be non-existent)\n// $4 = module identifier\n// $5 = quotes used (either ' or \")\nconst IMPORT_REGEX =\n /import(?:(?:(?:[ \\n\\t]+([^ *\\n\\t{},]+)[ \\n\\t]*(?:,|[ \\n\\t]+))?([ \\n\\t]*{(?:[ \\n\\t]*[^ \\n\\t\"'{}]+[ \\n\\t]*,?)+})?[ \\n\\t]*)|[ \\n\\t]*\\*[ \\n\\t]*as[ \\n\\t]+([^ \\n\\t{}]+)[ \\n\\t]+)from[ \\n\\t]*(?:['\"])([^'\"\\n]+)(['\"])/gm;\n\nconst NAMED_IMPORTS_REGEX = /[ \\n\\t]*{((?:[ \\n\\t]*[^ \\n\\t\"'{}]+[ \\n\\t]*,?)+)}[ \\n\\t]*/gm;\n\nconst allMatches = (regex: RegExp, str: string) => {\n regex.lastIndex = 0;\n\n let match;\n const matches = [];\n while ((match = regex.exec(str))) {\n matches.push(match);\n }\n\n return matches;\n};\n\ntype ParsedImport = {\n defaultImportName?: string;\n namedImports: string[];\n wildcardImportName?: string;\n moduleIdentifier: string;\n quotes: string;\n};\n\nconst analyzeSourceFileImports = (code: string): ParsedImport[] => {\n // TODO(dmaretskyi): Support import aliases and wildcard imports.\n const parsedImports = allMatches(IMPORT_REGEX, code);\n return parsedImports.map((capture) => {\n return {\n defaultImportName: capture[1],\n namedImports: capture[2]\n ?.trim()\n .slice(1, -1)\n .split(',')\n .map((importName) => importName.trim()),\n wildcardImportName: capture[3],\n moduleIdentifier: capture[4],\n quotes: capture[5],\n };\n });\n};\n\nconst MAX_RETRIES = 5;\nconst INITIAL_DELAY = 1_000;\n\nconst httpPlugin: Plugin = {\n name: 'http',\n setup: (build) => {\n // Intercept import paths starting with \"http:\" and \"https:\" so esbuild doesn't attempt to map them to a file system location.\n // Tag them with the \"http-url\" namespace to associate them with this plugin.\n build.onResolve({ filter: /^https?:\\/\\// }, (args) => ({\n path: args.path,\n namespace: 'http-url',\n }));\n\n // We also want to intercept all import paths inside downloaded files and resolve them against the original URL.\n // All of these files will be in the \"http-url\" namespace.\n // Make sure to keep the newly resolved URL in the \"http-url\" namespace so imports inside it will also be resolved as URLs recursively.\n build.onResolve({ filter: /.*/, namespace: 'http-url' }, (args) => ({\n path: new URL(args.path, args.importer).toString(),\n namespace: 'http-url',\n }));\n\n // When a URL is loaded, we want to actually download the content from the internet.\n // This has just enough logic to be able to handle the example import from unpkg.com but in reality this would probably need to be more complex.\n build.onLoad({ filter: /.*/, namespace: 'http-url' }, async (args) => {\n return Effect.gen(function* () {\n const response = yield* HttpClient.get(args.path);\n if (response.status !== 200) {\n throw new Error(`failed to fetch: ${response.status}`);\n }\n\n const text = yield* response.text;\n return { contents: text, loader: 'jsx' as Loader };\n }).pipe(\n Effect.retry(\n pipe(\n Schedule.exponential(Duration.millis(INITIAL_DELAY)),\n Schedule.jittered,\n Schedule.intersect(Schedule.recurs(MAX_RETRIES - 1)),\n ),\n ),\n Effect.provide(FetchHttpClient.layer),\n runAndForwardErrors,\n );\n });\n },\n};\n"],
|
|
5
|
+
"mappings": ";AAIA,SAASA,iBAAiBC,kBAAkB;AAC5C,SAASC,UAAUC,QAAQC,UAAUC,YAAY;AACjD,SAAwEC,OAAOC,kBAAkB;AAEjG,SAASC,oBAAoB;AAC7B,SAASC,2BAA2B;AACpC,SAASC,iBAAiB;AAC1B,SAASC,WAAW;;AAoCpB,IAAIC;AACG,IAAMC,oBAAoB,OAAOC,YAAAA;AACtC,SAAOF,gBAAgBL,WAAW;IAChCQ,SAASD,QAAQE;EACnB,CAAA;AACF;AAKO,IAAMC,UAAN,MAAMA;;EACX,YAA6BC,UAA0B;SAA1BA,WAAAA;EAA2B;EAExD,MAAMC,OAAO,EAAEC,MAAMC,OAAM,GAA0C;AACnE,UAAM,EAAEC,kBAAkBC,iBAAiB,GAAGT,QAAAA,IAAY,KAAKI;AAE/D,UAAMM,eAAe,OAAOC,WAAAA;AAC1B,aAAO;QACLC,WAAWC,KAAKC,IAAG;QACnBC,YAAYR,SAASS,OAAOC,KAAK,MAAMvB,aAAawB,OAAO,WAAWF,OAAOC,KAAKV,MAAAA,CAAAA,CAAAA,IAAYY;QAC9F,GAAGR;MACL;IACF;AAEA,QAAI,KAAKP,SAASgB,aAAa,WAAW;AACxCxB,gBAAUE,aAAa,6BAAA;;;;;;;;;AACvB,Y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;AAEA,IAAMoB,cAAc;AACpB,IAAMC,gBAAgB;AAEtB,IAAMnC,aAAqB;EACzBnB,MAAM;EACNC,OAAO,CAACtC,WAAAA;AAGNA,IAAAA,OAAMuC,UAAU;MAAEC,QAAQ;IAAe,GAAG,CAACoD,UAAU;MACrD9E,MAAM8E,KAAK9E;MACX6B,WAAW;IACb,EAAA;AAKA3C,IAAAA,OAAMuC,UAAU;MAAEC,QAAQ;MAAMG,WAAW;IAAW,GAAG,CAACiD,UAAU;MAClE9E,MAAM,IAAI+E,IAAID,KAAK9E,MAAM8E,KAAKE,QAAQ,EAAEC,SAAQ;MAChDpD,WAAW;IACb,EAAA;AAIA3C,IAAAA,OAAM4C,OAAO;MAAEJ,QAAQ;MAAMG,WAAW;IAAW,GAAG,OAAOiD,SAAAA;AAC3D,aAAO/F,OAAOmG,IAAI,aAAA;AAChB,cAAMC,WAAW,OAAOtG,WAAWuG,IAAIN,KAAK9E,IAAI;AAChD,YAAImF,SAASE,WAAW,KAAK;AAC3B,gBAAM,IAAIC,MAAM,oBAAoBH,SAASE,MAAM,EAAE;QACvD;AAEA,cAAMxC,OAAO,OAAOsC,SAAStC;AAC7B,eAAO;UAAEd,UAAUc;UAAMb,QAAQ;QAAgB;MACnD,CAAA,EAAG/C,KACDF,OAAOwG,MACLtG,KACED,SAASwG,YAAY1G,SAAS2G,OAAOZ,aAAAA,CAAAA,GACrC7F,SAAS0G,UACT1G,SAAS2G,UAAU3G,SAAS4G,OAAOhB,cAAc,CAAA,CAAA,CAAA,CAAA,GAGrD7F,OAAO8G,QAAQjH,gBAAgBkH,KAAK,GACpCzG,mBAAAA;IAEJ,CAAA;EACF;AACF;",
|
|
6
|
+
"names": ["FetchHttpClient", "HttpClient", "Duration", "Effect", "Schedule", "pipe", "build", "initialize", "subtleCrypto", "runAndForwardErrors", "invariant", "log", "initialized", "initializeBundler", "options", "wasmURL", "wasmUrl", "Bundler", "_options", "bundle", "path", "source", "sandboxedModules", "providedModules", "createResult", "result", "timestamp", "Date", "now", "sourceHash", "Buffer", "from", "digest", "undefined", "platform", "imports", "analyzeSourceFileImports", "conditions", "metafile", "write", "entryPoints", "format", "plugins", "name", "setup", "onResolve", "filter", "external", "split", "namespace", "onLoad", "contents", "loader", "module", "RegExp", "namedImports", "find", "entry", "moduleIdentifier", "join", "JSON", "stringify", "httpPlugin", "analyzeImports", "outputFiles", "text", "err", "error", "parsedImports", "allMatches", "IMPORT_REGEX", "Object", "values", "outputs", "map", "parsedImport", "capture", "NAMED_IMPORTS_REGEX", "lastIndex", "namedImportsMatch", "exec", "forEach", "importName", "push", "trim", "moduleUrl", "defaultImport", "code", "defaultImportName", "wildcardImportName", "quotes", "regex", "str", "match", "matches", "slice", "MAX_RETRIES", "INITIAL_DELAY", "args", "URL", "importer", "toString", "gen", "response", "get", "status", "Error", "retry", "exponential", "millis", "jittered", "intersect", "recurs", "provide", "layer"]
|
|
7
7
|
}
|
|
@@ -0,0 +1,486 @@
|
|
|
1
|
+
// src/services/database.ts
|
|
2
|
+
import { Context, Effect, Layer } from "effect";
|
|
3
|
+
import { Obj } from "@dxos/echo";
|
|
4
|
+
import { BaseError } from "@dxos/errors";
|
|
5
|
+
import { invariant } from "@dxos/invariant";
|
|
6
|
+
var __dxlog_file = "/__w/dxos/dxos/packages/core/functions/src/services/database.ts";
|
|
7
|
+
var DatabaseService = class _DatabaseService extends Context.Tag("@dxos/functions/DatabaseService")() {
|
|
8
|
+
static notAvailable = Layer.succeed(_DatabaseService, {
|
|
9
|
+
get db() {
|
|
10
|
+
throw new Error("Database not available");
|
|
11
|
+
}
|
|
12
|
+
});
|
|
13
|
+
static make = (db) => {
|
|
14
|
+
return {
|
|
15
|
+
get db() {
|
|
16
|
+
return db;
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
};
|
|
20
|
+
static layer = (db) => {
|
|
21
|
+
return Layer.succeed(_DatabaseService, _DatabaseService.make(db));
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* Resolves an object by its DXN.
|
|
25
|
+
*/
|
|
26
|
+
static resolve = (dxn, schema) => Effect.gen(function* () {
|
|
27
|
+
const { db } = yield* _DatabaseService;
|
|
28
|
+
const object = yield* Effect.promise(() => db.graph.createRefResolver({
|
|
29
|
+
context: {
|
|
30
|
+
space: db.spaceId
|
|
31
|
+
}
|
|
32
|
+
}).resolve(dxn));
|
|
33
|
+
if (!object) {
|
|
34
|
+
return yield* Effect.fail(new ObjectNotFoundError({
|
|
35
|
+
dxn
|
|
36
|
+
}));
|
|
37
|
+
}
|
|
38
|
+
invariant(!schema || Obj.instanceOf(schema, object), "Object type mismatch.", {
|
|
39
|
+
F: __dxlog_file,
|
|
40
|
+
L: 67,
|
|
41
|
+
S: this,
|
|
42
|
+
A: [
|
|
43
|
+
"!schema || Obj.instanceOf(schema, object)",
|
|
44
|
+
"'Object type mismatch.'"
|
|
45
|
+
]
|
|
46
|
+
});
|
|
47
|
+
return object;
|
|
48
|
+
});
|
|
49
|
+
/**
|
|
50
|
+
* Loads an object reference.
|
|
51
|
+
*/
|
|
52
|
+
static load = Effect.fn(function* (ref) {
|
|
53
|
+
return yield* Effect.promise(() => ref.load());
|
|
54
|
+
});
|
|
55
|
+
/**
|
|
56
|
+
* Creates a `QueryResult` object that can be subscribed to.
|
|
57
|
+
*/
|
|
58
|
+
static query = (queryOrFilter) => _DatabaseService.pipe(Effect.map(({ db }) => db.query(queryOrFilter)), Effect.withSpan("DatabaseService.query"));
|
|
59
|
+
/**
|
|
60
|
+
* Executes the query once and returns the results.
|
|
61
|
+
*/
|
|
62
|
+
static runQuery = (queryOrFilter) => _DatabaseService.query(queryOrFilter).pipe(Effect.flatMap((queryResult) => Effect.promise(() => queryResult.run())));
|
|
63
|
+
/**
|
|
64
|
+
* Adds an object to the database.
|
|
65
|
+
*/
|
|
66
|
+
static add = (obj) => _DatabaseService.pipe(Effect.map(({ db }) => db.add(obj)));
|
|
67
|
+
static flush = (opts) => _DatabaseService.pipe(Effect.flatMap(({ db }) => Effect.promise(() => db.flush(opts))));
|
|
68
|
+
};
|
|
69
|
+
var ObjectNotFoundError = class extends BaseError.extend("OBJECT_NOT_FOUND") {
|
|
70
|
+
constructor(context) {
|
|
71
|
+
super("Object not found", {
|
|
72
|
+
context
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
// src/services/queues.ts
|
|
78
|
+
import { Context as Context2, Effect as Effect2, Layer as Layer2 } from "effect";
|
|
79
|
+
var QueueService = class _QueueService extends Context2.Tag("@dxos/functions/QueueService")() {
|
|
80
|
+
static notAvailable = Layer2.succeed(_QueueService, {
|
|
81
|
+
queues: {
|
|
82
|
+
get(_dxn) {
|
|
83
|
+
throw new Error("Queues not available");
|
|
84
|
+
},
|
|
85
|
+
create() {
|
|
86
|
+
throw new Error("Queues not available");
|
|
87
|
+
}
|
|
88
|
+
},
|
|
89
|
+
queue: void 0
|
|
90
|
+
});
|
|
91
|
+
static make = (queues, queue) => {
|
|
92
|
+
return {
|
|
93
|
+
queues,
|
|
94
|
+
queue
|
|
95
|
+
};
|
|
96
|
+
};
|
|
97
|
+
static layer = (queues, queue) => Layer2.succeed(_QueueService, _QueueService.make(queues, queue));
|
|
98
|
+
/**
|
|
99
|
+
* Gets a queue by its DXN.
|
|
100
|
+
*/
|
|
101
|
+
static getQueue = (dxn) => _QueueService.pipe(Effect2.map(({ queues }) => queues.get(dxn)));
|
|
102
|
+
/**
|
|
103
|
+
* Creates a new queue.
|
|
104
|
+
*/
|
|
105
|
+
static createQueue = (options) => _QueueService.pipe(Effect2.map(({ queues }) => queues.create(options)));
|
|
106
|
+
};
|
|
107
|
+
var ContextQueueService = class _ContextQueueService extends Context2.Tag("@dxos/functions/ContextQueueService")() {
|
|
108
|
+
static layer = (queue) => Layer2.succeed(_ContextQueueService, {
|
|
109
|
+
queue
|
|
110
|
+
});
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
// src/services/credentials.ts
|
|
114
|
+
import { Context as Context3, Effect as Effect3, Layer as Layer3 } from "effect";
|
|
115
|
+
import { Query } from "@dxos/echo";
|
|
116
|
+
import { DataType } from "@dxos/schema";
|
|
117
|
+
var CredentialsService = class _CredentialsService extends Context3.Tag("@dxos/functions/CredentialsService")() {
|
|
118
|
+
static getCredential = (query) => Effect3.gen(function* () {
|
|
119
|
+
const credentials = yield* _CredentialsService;
|
|
120
|
+
return yield* Effect3.promise(() => credentials.getCredential(query));
|
|
121
|
+
});
|
|
122
|
+
static configuredLayer = (credentials) => Layer3.succeed(_CredentialsService, new ConfiguredCredentialsService(credentials));
|
|
123
|
+
static layerFromDatabase = () => Layer3.effect(_CredentialsService, Effect3.gen(function* () {
|
|
124
|
+
const dbService = yield* DatabaseService;
|
|
125
|
+
const queryCredentials = async (query) => {
|
|
126
|
+
const { objects: accessTokens } = await dbService.db.query(Query.type(DataType.AccessToken)).run();
|
|
127
|
+
return accessTokens.filter((accessToken) => accessToken.source === query.service).map((accessToken) => ({
|
|
128
|
+
service: accessToken.source,
|
|
129
|
+
apiKey: accessToken.token
|
|
130
|
+
}));
|
|
131
|
+
};
|
|
132
|
+
return {
|
|
133
|
+
getCredential: async (query) => {
|
|
134
|
+
const credentials = await queryCredentials(query);
|
|
135
|
+
if (credentials.length === 0) {
|
|
136
|
+
throw new Error(`Credential not found for service: ${query.service}`);
|
|
137
|
+
}
|
|
138
|
+
return credentials[0];
|
|
139
|
+
},
|
|
140
|
+
queryCredentials: async (query) => {
|
|
141
|
+
return queryCredentials(query);
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
}));
|
|
145
|
+
};
|
|
146
|
+
var ConfiguredCredentialsService = class {
|
|
147
|
+
credentials;
|
|
148
|
+
constructor(credentials = []) {
|
|
149
|
+
this.credentials = credentials;
|
|
150
|
+
}
|
|
151
|
+
addCredentials(credentials) {
|
|
152
|
+
this.credentials.push(...credentials);
|
|
153
|
+
return this;
|
|
154
|
+
}
|
|
155
|
+
async queryCredentials(query) {
|
|
156
|
+
return this.credentials.filter((credential) => credential.service === query.service);
|
|
157
|
+
}
|
|
158
|
+
async getCredential(query) {
|
|
159
|
+
const credential = this.credentials.find((credential2) => credential2.service === query.service);
|
|
160
|
+
if (!credential) {
|
|
161
|
+
throw new Error(`Credential not found for service: ${query.service}`);
|
|
162
|
+
}
|
|
163
|
+
return credential;
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
// src/services/tracing.ts
|
|
168
|
+
import { Context as Context4, Effect as Effect4, Layer as Layer4 } from "effect";
|
|
169
|
+
import { AgentStatus } from "@dxos/ai";
|
|
170
|
+
import { Obj as Obj2 } from "@dxos/echo";
|
|
171
|
+
var TracingService = class _TracingService extends Context4.Tag("@dxos/functions/TracingService")() {
|
|
172
|
+
static noop = {
|
|
173
|
+
write: () => {
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
static layerNoop = Layer4.succeed(_TracingService, _TracingService.noop);
|
|
177
|
+
static console = {
|
|
178
|
+
write: (event) => {
|
|
179
|
+
console.log(event);
|
|
180
|
+
}
|
|
181
|
+
};
|
|
182
|
+
/**
|
|
183
|
+
* Emit the current human-readable execution status.
|
|
184
|
+
*/
|
|
185
|
+
static emitStatus = Effect4.fnUntraced(function* (data) {
|
|
186
|
+
const tracing = yield* _TracingService;
|
|
187
|
+
tracing.write(Obj2.make(AgentStatus, data));
|
|
188
|
+
});
|
|
189
|
+
};
|
|
190
|
+
|
|
191
|
+
// src/services/event-logger.ts
|
|
192
|
+
import { Context as Context5, Effect as Effect5, Layer as Layer5, Schema } from "effect";
|
|
193
|
+
import { Obj as Obj3, Type } from "@dxos/echo";
|
|
194
|
+
import { invariant as invariant2 } from "@dxos/invariant";
|
|
195
|
+
import { LogLevel, log } from "@dxos/log";
|
|
196
|
+
var __dxlog_file2 = "/__w/dxos/dxos/packages/core/functions/src/services/event-logger.ts";
|
|
197
|
+
var ComputeEventPayload = Schema.Union(Schema.Struct({
|
|
198
|
+
type: Schema.Literal("begin-compute"),
|
|
199
|
+
nodeId: Schema.String,
|
|
200
|
+
inputs: Schema.Record({
|
|
201
|
+
key: Schema.String,
|
|
202
|
+
value: Schema.Any
|
|
203
|
+
})
|
|
204
|
+
}), Schema.Struct({
|
|
205
|
+
type: Schema.Literal("end-compute"),
|
|
206
|
+
nodeId: Schema.String,
|
|
207
|
+
outputs: Schema.Record({
|
|
208
|
+
key: Schema.String,
|
|
209
|
+
value: Schema.Any
|
|
210
|
+
})
|
|
211
|
+
}), Schema.Struct({
|
|
212
|
+
type: Schema.Literal("compute-input"),
|
|
213
|
+
nodeId: Schema.String,
|
|
214
|
+
property: Schema.String,
|
|
215
|
+
value: Schema.Any
|
|
216
|
+
}), Schema.Struct({
|
|
217
|
+
type: Schema.Literal("compute-output"),
|
|
218
|
+
nodeId: Schema.String,
|
|
219
|
+
property: Schema.String,
|
|
220
|
+
value: Schema.Any
|
|
221
|
+
}), Schema.Struct({
|
|
222
|
+
type: Schema.Literal("custom"),
|
|
223
|
+
nodeId: Schema.String,
|
|
224
|
+
event: Schema.Any
|
|
225
|
+
}));
|
|
226
|
+
var ComputeEvent = Schema.Struct({
|
|
227
|
+
payload: ComputeEventPayload
|
|
228
|
+
}).pipe(Type.Obj({
|
|
229
|
+
typename: "dxos.org/type/ComputeEvent",
|
|
230
|
+
version: "0.1.0"
|
|
231
|
+
}));
|
|
232
|
+
var ComputeEventLogger = class _ComputeEventLogger extends Context5.Tag("@dxos/functions/ComputeEventLogger")() {
|
|
233
|
+
static noop = {
|
|
234
|
+
log: () => {
|
|
235
|
+
},
|
|
236
|
+
nodeId: void 0
|
|
237
|
+
};
|
|
238
|
+
/**
|
|
239
|
+
* Implements ComputeEventLogger using TracingService.
|
|
240
|
+
*/
|
|
241
|
+
static layerFromTracing = Layer5.effect(_ComputeEventLogger, Effect5.gen(function* () {
|
|
242
|
+
const tracing = yield* TracingService;
|
|
243
|
+
return {
|
|
244
|
+
log: (event) => {
|
|
245
|
+
tracing.write(Obj3.make(ComputeEvent, {
|
|
246
|
+
payload: event
|
|
247
|
+
}));
|
|
248
|
+
},
|
|
249
|
+
nodeId: void 0
|
|
250
|
+
};
|
|
251
|
+
}));
|
|
252
|
+
};
|
|
253
|
+
var logCustomEvent = (data) => Effect5.gen(function* () {
|
|
254
|
+
const logger = yield* ComputeEventLogger;
|
|
255
|
+
if (!logger.nodeId) {
|
|
256
|
+
throw new Error("logCustomEvent must be called within a node compute function");
|
|
257
|
+
}
|
|
258
|
+
logger.log({
|
|
259
|
+
type: "custom",
|
|
260
|
+
nodeId: logger.nodeId,
|
|
261
|
+
event: data
|
|
262
|
+
});
|
|
263
|
+
});
|
|
264
|
+
var createDefectLogger = () => Effect5.catchAll((error) => Effect5.gen(function* () {
|
|
265
|
+
log.error("unhandled effect error", {
|
|
266
|
+
error
|
|
267
|
+
}, {
|
|
268
|
+
F: __dxlog_file2,
|
|
269
|
+
L: 93,
|
|
270
|
+
S: this,
|
|
271
|
+
C: (f, a) => f(...a)
|
|
272
|
+
});
|
|
273
|
+
throw error;
|
|
274
|
+
}));
|
|
275
|
+
var createEventLogger = (level, message = "event") => {
|
|
276
|
+
const logFunction = {
|
|
277
|
+
[LogLevel.WARN]: log.warn,
|
|
278
|
+
[LogLevel.VERBOSE]: log.verbose,
|
|
279
|
+
[LogLevel.DEBUG]: log.debug,
|
|
280
|
+
[LogLevel.INFO]: log.info,
|
|
281
|
+
[LogLevel.ERROR]: log.error
|
|
282
|
+
}[level];
|
|
283
|
+
invariant2(logFunction, void 0, {
|
|
284
|
+
F: __dxlog_file2,
|
|
285
|
+
L: 111,
|
|
286
|
+
S: void 0,
|
|
287
|
+
A: [
|
|
288
|
+
"logFunction",
|
|
289
|
+
""
|
|
290
|
+
]
|
|
291
|
+
});
|
|
292
|
+
return {
|
|
293
|
+
log: (event) => {
|
|
294
|
+
logFunction(message, event);
|
|
295
|
+
},
|
|
296
|
+
nodeId: void 0
|
|
297
|
+
};
|
|
298
|
+
};
|
|
299
|
+
|
|
300
|
+
// src/services/remote-function-execution-service.ts
|
|
301
|
+
import { Context as Context6, Layer as Layer6 } from "effect";
|
|
302
|
+
var RemoteFunctionExecutionService = class _RemoteFunctionExecutionService extends Context6.Tag("@dxos/functions/RemoteFunctionExecutionService")() {
|
|
303
|
+
static fromClient(baseUrl, spaceId) {
|
|
304
|
+
return {
|
|
305
|
+
callFunction: async (deployedFunctionId, input) => {
|
|
306
|
+
const url = getInvocationUrl(deployedFunctionId, baseUrl, {
|
|
307
|
+
spaceId
|
|
308
|
+
});
|
|
309
|
+
const result = await fetch(url, {
|
|
310
|
+
method: "POST",
|
|
311
|
+
headers: {
|
|
312
|
+
"Content-Type": "application/json"
|
|
313
|
+
},
|
|
314
|
+
body: JSON.stringify(input)
|
|
315
|
+
});
|
|
316
|
+
if (result.status >= 300 || result.status < 200) {
|
|
317
|
+
throw new Error("Failed to invoke function", {
|
|
318
|
+
cause: new Error(`HTTP error: ${await result.text()}`)
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
return await result.json();
|
|
322
|
+
}
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
static mock = () => {
|
|
326
|
+
return {
|
|
327
|
+
callFunction: async (deployedFunctionId, input) => {
|
|
328
|
+
return input;
|
|
329
|
+
}
|
|
330
|
+
};
|
|
331
|
+
};
|
|
332
|
+
static mockLayer = Layer6.succeed(_RemoteFunctionExecutionService, _RemoteFunctionExecutionService.mock());
|
|
333
|
+
};
|
|
334
|
+
var getInvocationUrl = (functionUrl, edgeUrl, options = {}) => {
|
|
335
|
+
const baseUrl = new URL("functions/", edgeUrl);
|
|
336
|
+
const relativeUrl = functionUrl.replace(/^\//, "");
|
|
337
|
+
const url = new URL(`./${relativeUrl}`, baseUrl.toString());
|
|
338
|
+
options.spaceId && url.searchParams.set("spaceId", options.spaceId);
|
|
339
|
+
options.subjectId && url.searchParams.set("subjectId", options.subjectId);
|
|
340
|
+
url.protocol = isSecure(url.protocol) ? "https" : "http";
|
|
341
|
+
return url.toString();
|
|
342
|
+
};
|
|
343
|
+
var isSecure = (protocol) => {
|
|
344
|
+
return protocol === "https:" || protocol === "wss:";
|
|
345
|
+
};
|
|
346
|
+
|
|
347
|
+
// src/services/service-container.ts
|
|
348
|
+
import { Layer as Layer7 } from "effect";
|
|
349
|
+
import { AiService } from "@dxos/ai";
|
|
350
|
+
import { entries } from "@dxos/util";
|
|
351
|
+
var SERVICES = {
|
|
352
|
+
ai: AiService.AiService,
|
|
353
|
+
credentials: CredentialsService,
|
|
354
|
+
database: DatabaseService,
|
|
355
|
+
eventLogger: ComputeEventLogger,
|
|
356
|
+
functionCallService: RemoteFunctionExecutionService,
|
|
357
|
+
queues: QueueService,
|
|
358
|
+
tracing: TracingService
|
|
359
|
+
};
|
|
360
|
+
var SERVICE_MAPPING = Object.fromEntries(entries(SERVICES).map(([name, tag]) => [
|
|
361
|
+
tag.key,
|
|
362
|
+
name
|
|
363
|
+
]));
|
|
364
|
+
var SERVICE_TAGS = Object.values(SERVICES);
|
|
365
|
+
var DEFAULT_SERVICES = {
|
|
366
|
+
tracing: TracingService.noop
|
|
367
|
+
};
|
|
368
|
+
var ServiceContainer = class _ServiceContainer {
|
|
369
|
+
_services = {
|
|
370
|
+
...DEFAULT_SERVICES
|
|
371
|
+
};
|
|
372
|
+
/**
|
|
373
|
+
* Set services.
|
|
374
|
+
* @param services - Services to set.
|
|
375
|
+
* @returns The container instance.
|
|
376
|
+
*/
|
|
377
|
+
setServices(services) {
|
|
378
|
+
this._services = {
|
|
379
|
+
...this._services,
|
|
380
|
+
...services
|
|
381
|
+
};
|
|
382
|
+
return this;
|
|
383
|
+
}
|
|
384
|
+
getService(tag) {
|
|
385
|
+
const serviceKey = SERVICE_MAPPING[tag.key];
|
|
386
|
+
const service = serviceKey != null ? this._services[serviceKey] : void 0;
|
|
387
|
+
if (!service) {
|
|
388
|
+
throw new Error(`Service not available: ${tag.key}`);
|
|
389
|
+
}
|
|
390
|
+
return service;
|
|
391
|
+
}
|
|
392
|
+
clone() {
|
|
393
|
+
return new _ServiceContainer().setServices({
|
|
394
|
+
...this._services
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
// TODO(dmaretskyi): `getService` is designed to error at runtime if the service is not available, but Layer forces us to provide all services and makes stubs for the ones that are not available.
|
|
398
|
+
createLayer() {
|
|
399
|
+
const ai = this._services.ai != null ? Layer7.succeed(AiService.AiService, this._services.ai) : AiService.notAvailable;
|
|
400
|
+
const credentials = Layer7.succeed(CredentialsService, this._services.credentials ?? new ConfiguredCredentialsService());
|
|
401
|
+
const database = this._services.database != null ? Layer7.succeed(DatabaseService, this._services.database) : DatabaseService.notAvailable;
|
|
402
|
+
const queues = this._services.queues != null ? Layer7.succeed(QueueService, this._services.queues) : QueueService.notAvailable;
|
|
403
|
+
const tracing = Layer7.succeed(TracingService, this._services.tracing ?? TracingService.noop);
|
|
404
|
+
const eventLogger = Layer7.succeed(ComputeEventLogger, this._services.eventLogger ?? ComputeEventLogger.noop);
|
|
405
|
+
const functionCallService = Layer7.succeed(RemoteFunctionExecutionService, this._services.functionCallService ?? RemoteFunctionExecutionService.mock());
|
|
406
|
+
return Layer7.mergeAll(ai, credentials, database, queues, tracing, eventLogger, functionCallService);
|
|
407
|
+
}
|
|
408
|
+
};
|
|
409
|
+
|
|
410
|
+
// src/errors.ts
|
|
411
|
+
import { BaseError as BaseError2 } from "@dxos/errors";
|
|
412
|
+
var ServiceNotAvailableError = class extends BaseError2.extend("SERVICE_NOT_AVAILABLE") {
|
|
413
|
+
constructor(serviceName) {
|
|
414
|
+
super(`Service not available: ${serviceName}`);
|
|
415
|
+
}
|
|
416
|
+
};
|
|
417
|
+
var FunctionError = class extends BaseError2.extend("FUNCTION_ERROR") {
|
|
418
|
+
};
|
|
419
|
+
|
|
420
|
+
// src/services/local-function-execution.ts
|
|
421
|
+
import { Context as Context7, Effect as Effect6, Layer as Layer8, Schema as Schema2 } from "effect";
|
|
422
|
+
import { todo } from "@dxos/debug";
|
|
423
|
+
var LocalFunctionExecutionService = class _LocalFunctionExecutionService extends Context7.Tag("@dxos/functions/LocalFunctionExecutionService")() {
|
|
424
|
+
static layer = Layer8.succeed(_LocalFunctionExecutionService, {
|
|
425
|
+
invokeFunction: (fnDef, input) => invokeFunction(fnDef, input)
|
|
426
|
+
});
|
|
427
|
+
static invokeFunction = Effect6.serviceFunctionEffect(_LocalFunctionExecutionService, (_) => _.invokeFunction);
|
|
428
|
+
};
|
|
429
|
+
var invokeFunction = (fnDef, input) => Effect6.gen(function* () {
|
|
430
|
+
const assertInput = fnDef.inputSchema.pipe(Schema2.asserts);
|
|
431
|
+
assertInput(input);
|
|
432
|
+
const context = {
|
|
433
|
+
space: void 0,
|
|
434
|
+
getService: () => todo(),
|
|
435
|
+
getSpace: async (_spaceId) => {
|
|
436
|
+
throw new Error("Not available. Use the database service instead.");
|
|
437
|
+
}
|
|
438
|
+
};
|
|
439
|
+
const data = yield* Effect6.gen(function* () {
|
|
440
|
+
const result = fnDef.handler({
|
|
441
|
+
context,
|
|
442
|
+
data: input
|
|
443
|
+
});
|
|
444
|
+
if (Effect6.isEffect(result)) {
|
|
445
|
+
return yield* result.pipe(Effect6.orDie);
|
|
446
|
+
} else if (typeof result === "object" && result !== null && "then" in result && typeof result.then === "function") {
|
|
447
|
+
return yield* Effect6.promise(() => result);
|
|
448
|
+
} else {
|
|
449
|
+
return result;
|
|
450
|
+
}
|
|
451
|
+
}).pipe(Effect6.orDie, Effect6.catchAllDefect((defect) => Effect6.die(new FunctionError("Error running function", {
|
|
452
|
+
context: {
|
|
453
|
+
name: fnDef.name
|
|
454
|
+
},
|
|
455
|
+
cause: defect
|
|
456
|
+
}))));
|
|
457
|
+
const assertOutput = fnDef.outputSchema?.pipe(Schema2.asserts);
|
|
458
|
+
assertOutput(data);
|
|
459
|
+
return data;
|
|
460
|
+
}).pipe(Effect6.withSpan("invokeFunction", {
|
|
461
|
+
attributes: {
|
|
462
|
+
name: fnDef.name
|
|
463
|
+
}
|
|
464
|
+
}));
|
|
465
|
+
|
|
466
|
+
export {
|
|
467
|
+
DatabaseService,
|
|
468
|
+
QueueService,
|
|
469
|
+
ContextQueueService,
|
|
470
|
+
CredentialsService,
|
|
471
|
+
ConfiguredCredentialsService,
|
|
472
|
+
TracingService,
|
|
473
|
+
ComputeEventPayload,
|
|
474
|
+
ComputeEvent,
|
|
475
|
+
ComputeEventLogger,
|
|
476
|
+
logCustomEvent,
|
|
477
|
+
createDefectLogger,
|
|
478
|
+
createEventLogger,
|
|
479
|
+
RemoteFunctionExecutionService,
|
|
480
|
+
SERVICE_TAGS,
|
|
481
|
+
ServiceContainer,
|
|
482
|
+
ServiceNotAvailableError,
|
|
483
|
+
FunctionError,
|
|
484
|
+
LocalFunctionExecutionService
|
|
485
|
+
};
|
|
486
|
+
//# sourceMappingURL=chunk-M2OIFLGE.mjs.map
|