@dxos/functions 0.8.4-main.3f58842 → 0.8.4-main.548089c

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/dist/lib/browser/index.mjs +663 -363
  2. package/dist/lib/browser/index.mjs.map +4 -4
  3. package/dist/lib/browser/meta.json +1 -1
  4. package/dist/lib/node-esm/index.mjs +663 -363
  5. package/dist/lib/node-esm/index.mjs.map +4 -4
  6. package/dist/lib/node-esm/meta.json +1 -1
  7. package/dist/types/src/errors.d.ts +81 -28
  8. package/dist/types/src/errors.d.ts.map +1 -1
  9. package/dist/types/src/example/fib.d.ts +7 -0
  10. package/dist/types/src/example/fib.d.ts.map +1 -0
  11. package/dist/types/src/example/forex-effect.d.ts +3 -0
  12. package/dist/types/src/example/forex-effect.d.ts.map +1 -0
  13. package/dist/types/src/example/index.d.ts +12 -0
  14. package/dist/types/src/example/index.d.ts.map +1 -0
  15. package/dist/types/src/example/reply.d.ts +3 -0
  16. package/dist/types/src/example/reply.d.ts.map +1 -0
  17. package/dist/types/src/example/sleep.d.ts +5 -0
  18. package/dist/types/src/example/sleep.d.ts.map +1 -0
  19. package/dist/types/src/handler.d.ts +56 -36
  20. package/dist/types/src/handler.d.ts.map +1 -1
  21. package/dist/types/src/index.d.ts +3 -5
  22. package/dist/types/src/index.d.ts.map +1 -1
  23. package/dist/types/src/services/credentials.d.ts +20 -3
  24. package/dist/types/src/services/credentials.d.ts.map +1 -1
  25. package/dist/types/src/services/event-logger.d.ts +80 -30
  26. package/dist/types/src/services/event-logger.d.ts.map +1 -1
  27. package/dist/types/src/services/function-invocation-service.d.ts +11 -0
  28. package/dist/types/src/services/function-invocation-service.d.ts.map +1 -0
  29. package/dist/types/src/services/index.d.ts +6 -5
  30. package/dist/types/src/services/index.d.ts.map +1 -1
  31. package/dist/types/src/services/queues.d.ts +23 -6
  32. package/dist/types/src/services/queues.d.ts.map +1 -1
  33. package/dist/types/src/services/tracing.d.ts +35 -6
  34. package/dist/types/src/services/tracing.d.ts.map +1 -1
  35. package/dist/types/src/types/Function.d.ts +52 -0
  36. package/dist/types/src/types/Function.d.ts.map +1 -0
  37. package/dist/types/src/types/Script.d.ts +28 -0
  38. package/dist/types/src/types/Script.d.ts.map +1 -0
  39. package/dist/types/src/types/Trigger.d.ts +139 -0
  40. package/dist/types/src/types/Trigger.d.ts.map +1 -0
  41. package/dist/types/src/types/TriggerEvent.d.ts +44 -0
  42. package/dist/types/src/types/TriggerEvent.d.ts.map +1 -0
  43. package/dist/types/src/types/index.d.ts +5 -0
  44. package/dist/types/src/types/index.d.ts.map +1 -0
  45. package/dist/types/src/url.d.ts +7 -12
  46. package/dist/types/src/url.d.ts.map +1 -1
  47. package/dist/types/tsconfig.tsbuildinfo +1 -1
  48. package/package.json +17 -68
  49. package/src/errors.ts +13 -5
  50. package/src/example/fib.ts +32 -0
  51. package/src/example/forex-effect.ts +40 -0
  52. package/src/example/index.ts +13 -0
  53. package/src/example/reply.ts +21 -0
  54. package/src/example/sleep.ts +24 -0
  55. package/src/handler.ts +145 -64
  56. package/src/index.ts +3 -7
  57. package/src/services/credentials.ts +85 -3
  58. package/src/services/event-logger.ts +77 -37
  59. package/src/services/function-invocation-service.ts +20 -0
  60. package/src/services/index.ts +7 -5
  61. package/src/services/queues.ts +39 -10
  62. package/src/services/tracing.ts +82 -16
  63. package/src/types/Function.ts +56 -0
  64. package/src/types/Script.ts +33 -0
  65. package/src/types/Trigger.ts +139 -0
  66. package/src/types/TriggerEvent.ts +62 -0
  67. package/src/types/index.ts +8 -0
  68. package/src/url.ts +12 -33
  69. package/dist/lib/browser/bundler/index.mjs +0 -247
  70. package/dist/lib/browser/bundler/index.mjs.map +0 -7
  71. package/dist/lib/browser/chunk-3NGCSUEW.mjs +0 -328
  72. package/dist/lib/browser/chunk-3NGCSUEW.mjs.map +0 -7
  73. package/dist/lib/browser/edge/index.mjs +0 -69
  74. package/dist/lib/browser/edge/index.mjs.map +0 -7
  75. package/dist/lib/browser/testing/index.mjs +0 -91
  76. package/dist/lib/browser/testing/index.mjs.map +0 -7
  77. package/dist/lib/node-esm/bundler/index.mjs +0 -249
  78. package/dist/lib/node-esm/bundler/index.mjs.map +0 -7
  79. package/dist/lib/node-esm/chunk-FJ2MU7TL.mjs +0 -330
  80. package/dist/lib/node-esm/chunk-FJ2MU7TL.mjs.map +0 -7
  81. package/dist/lib/node-esm/edge/index.mjs +0 -71
  82. package/dist/lib/node-esm/edge/index.mjs.map +0 -7
  83. package/dist/lib/node-esm/testing/index.mjs +0 -92
  84. package/dist/lib/node-esm/testing/index.mjs.map +0 -7
  85. package/dist/types/src/bundler/bundler.d.ts +0 -50
  86. package/dist/types/src/bundler/bundler.d.ts.map +0 -1
  87. package/dist/types/src/bundler/bundler.test.d.ts +0 -2
  88. package/dist/types/src/bundler/bundler.test.d.ts.map +0 -1
  89. package/dist/types/src/bundler/index.d.ts +0 -2
  90. package/dist/types/src/bundler/index.d.ts.map +0 -1
  91. package/dist/types/src/edge/functions.d.ts +0 -16
  92. package/dist/types/src/edge/functions.d.ts.map +0 -1
  93. package/dist/types/src/edge/index.d.ts +0 -2
  94. package/dist/types/src/edge/index.d.ts.map +0 -1
  95. package/dist/types/src/executor/executor.d.ts +0 -8
  96. package/dist/types/src/executor/executor.d.ts.map +0 -1
  97. package/dist/types/src/executor/index.d.ts +0 -2
  98. package/dist/types/src/executor/index.d.ts.map +0 -1
  99. package/dist/types/src/schema.d.ts +0 -38
  100. package/dist/types/src/schema.d.ts.map +0 -1
  101. package/dist/types/src/services/database.d.ts +0 -29
  102. package/dist/types/src/services/database.d.ts.map +0 -1
  103. package/dist/types/src/services/function-call-service.d.ts +0 -16
  104. package/dist/types/src/services/function-call-service.d.ts.map +0 -1
  105. package/dist/types/src/services/service-container.d.ts +0 -56
  106. package/dist/types/src/services/service-container.d.ts.map +0 -1
  107. package/dist/types/src/services/service-registry.d.ts +0 -29
  108. package/dist/types/src/services/service-registry.d.ts.map +0 -1
  109. package/dist/types/src/services/service-registry.test.d.ts +0 -2
  110. package/dist/types/src/services/service-registry.test.d.ts.map +0 -1
  111. package/dist/types/src/testing/index.d.ts +0 -3
  112. package/dist/types/src/testing/index.d.ts.map +0 -1
  113. package/dist/types/src/testing/layer.d.ts +0 -10
  114. package/dist/types/src/testing/layer.d.ts.map +0 -1
  115. package/dist/types/src/testing/logger.d.ts +0 -5
  116. package/dist/types/src/testing/logger.d.ts.map +0 -1
  117. package/dist/types/src/testing/services.d.ts +0 -70
  118. package/dist/types/src/testing/services.d.ts.map +0 -1
  119. package/dist/types/src/trace.d.ts +0 -124
  120. package/dist/types/src/trace.d.ts.map +0 -1
  121. package/dist/types/src/translations.d.ts +0 -12
  122. package/dist/types/src/translations.d.ts.map +0 -1
  123. package/dist/types/src/types.d.ts +0 -411
  124. package/dist/types/src/types.d.ts.map +0 -1
  125. package/src/bundler/bundler.test.ts +0 -59
  126. package/src/bundler/bundler.ts +0 -292
  127. package/src/bundler/index.ts +0 -5
  128. package/src/edge/functions.ts +0 -64
  129. package/src/edge/index.ts +0 -9
  130. package/src/executor/executor.ts +0 -54
  131. package/src/executor/index.ts +0 -5
  132. package/src/schema.ts +0 -57
  133. package/src/services/database.ts +0 -70
  134. package/src/services/function-call-service.ts +0 -64
  135. package/src/services/service-container.ts +0 -113
  136. package/src/services/service-registry.test.ts +0 -42
  137. package/src/services/service-registry.ts +0 -56
  138. package/src/testing/index.ts +0 -6
  139. package/src/testing/layer.ts +0 -31
  140. package/src/testing/logger.ts +0 -16
  141. package/src/testing/services.ts +0 -168
  142. package/src/trace.ts +0 -180
  143. package/src/translations.ts +0 -20
  144. package/src/types.ts +0 -211
package/package.json CHANGED
@@ -1,94 +1,43 @@
1
1
  {
2
2
  "name": "@dxos/functions",
3
- "version": "0.8.4-main.3f58842",
4
- "description": "Functions API and runtime.",
3
+ "version": "0.8.4-main.548089c",
4
+ "description": "Functions API.",
5
5
  "homepage": "https://dxos.org",
6
6
  "bugs": "https://github.com/dxos/dxos/issues",
7
7
  "license": "MIT",
8
8
  "author": "info@dxos.org",
9
- "sideEffects": true,
9
+ "sideEffects": false,
10
10
  "type": "module",
11
11
  "exports": {
12
- "./bundler": {
13
- "types": "./dist/types/src/bundler/index.d.ts",
14
- "browser": "./dist/lib/browser/bundler/index.mjs",
15
- "node": "./dist/lib/node-esm/bundler/index.mjs"
16
- },
17
- "./edge": {
18
- "types": "./dist/types/src/edge/index.d.ts",
19
- "browser": "./dist/lib/browser/edge/index.mjs",
20
- "node": "./dist/lib/node-esm/edge/index.mjs"
21
- },
22
12
  ".": {
13
+ "source": "./src/index.ts",
23
14
  "types": "./dist/types/src/index.d.ts",
24
15
  "browser": "./dist/lib/browser/index.mjs",
25
16
  "node": "./dist/lib/node-esm/index.mjs"
26
- },
27
- "./testing": {
28
- "types": "./dist/types/src/testing/index.d.ts",
29
- "browser": "./dist/lib/browser/testing/index.mjs",
30
- "node": "./dist/lib/node-esm/testing/index.mjs"
31
17
  }
32
18
  },
33
19
  "types": "dist/types/src/index.d.ts",
34
- "typesVersions": {
35
- "*": {
36
- "bundler": [
37
- "dist/types/src/bundler/index.d.ts"
38
- ],
39
- "edge": [
40
- "dist/types/src/edge/index.d.ts"
41
- ]
42
- }
43
- },
44
20
  "files": [
45
21
  "dist",
46
22
  "schema",
47
23
  "src"
48
24
  ],
49
25
  "dependencies": {
50
- "@effect/platform": "0.89.0",
51
- "@preact/signals-core": "^1.9.0",
52
- "cron": "^3.1.6",
53
- "cron-schedule": "^5.0.4",
54
- "effect": "3.17.0",
55
- "esbuild-wasm": "^0.16.14",
56
- "express": "^4.19.2",
57
- "get-port-please": "^3.1.1",
58
- "i18next": "^24.2.1",
59
- "iso-did": "^1.6.0",
60
- "ws": "^8.14.2",
61
- "@dxos/ai": "0.8.4-main.3f58842",
62
- "@dxos/async": "0.8.4-main.3f58842",
63
- "@dxos/client": "0.8.4-main.3f58842",
64
- "@dxos/context": "0.8.4-main.3f58842",
65
- "@dxos/crypto": "0.8.4-main.3f58842",
66
- "@dxos/echo-db": "0.8.4-main.3f58842",
67
- "@dxos/echo-pipeline": "0.8.4-main.3f58842",
68
- "@dxos/echo": "0.8.4-main.3f58842",
69
- "@dxos/echo-protocol": "0.8.4-main.3f58842",
70
- "@dxos/echo-schema": "0.8.4-main.3f58842",
71
- "@dxos/edge-client": "0.8.4-main.3f58842",
72
- "@dxos/effect": "0.8.4-main.3f58842",
73
- "@dxos/errors": "0.8.4-main.3f58842",
74
- "@dxos/invariant": "0.8.4-main.3f58842",
75
- "@dxos/keys": "0.8.4-main.3f58842",
76
- "@dxos/log": "0.8.4-main.3f58842",
77
- "@dxos/live-object": "0.8.4-main.3f58842",
78
- "@dxos/node-std": "0.8.4-main.3f58842",
79
- "@dxos/protocols": "0.8.4-main.3f58842",
80
- "@dxos/util": "0.8.4-main.3f58842",
81
- "@dxos/schema": "0.8.4-main.3f58842"
82
- },
83
- "devDependencies": {
84
- "@types/express": "^4.17.17",
85
- "@types/ws": "^7.4.0",
86
- "@dxos/agent": "0.8.4-main.3f58842"
26
+ "@effect/platform": "0.92.1",
27
+ "effect": "3.18.3",
28
+ "@dxos/ai": "0.8.4-main.548089c",
29
+ "@dxos/errors": "0.8.4-main.548089c",
30
+ "@dxos/invariant": "0.8.4-main.548089c",
31
+ "@dxos/keys": "0.8.4-main.548089c",
32
+ "@dxos/log": "0.8.4-main.548089c",
33
+ "@dxos/node-std": "0.8.4-main.548089c",
34
+ "@dxos/schema": "0.8.4-main.548089c",
35
+ "@dxos/echo-db": "0.8.4-main.548089c",
36
+ "@dxos/echo": "0.8.4-main.548089c",
37
+ "@dxos/types": "0.8.4-main.548089c"
87
38
  },
88
39
  "publishConfig": {
89
40
  "access": "public"
90
41
  },
91
- "scripts": {
92
- "gen-schema": "ts-node ./tools/schema.ts"
93
- }
42
+ "scripts": {}
94
43
  }
package/src/errors.ts CHANGED
@@ -2,12 +2,20 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { BaseError } from '@dxos/errors';
5
+ import { BaseError, type BaseErrorOptions } from '@dxos/errors';
6
6
 
7
- export class ServiceNotAvailableError extends BaseError.extend('SERVICE_NOT_AVAILABLE') {
8
- constructor(serviceName: string) {
9
- super(`Service not available: ${serviceName}`);
7
+ export class ServiceNotAvailableError extends BaseError.extend('SERVICE_NOT_AVAILABLE', 'Service not available') {
8
+ constructor(service: string, options?: Omit<BaseErrorOptions, 'context'>) {
9
+ super({ context: { service }, ...options });
10
10
  }
11
11
  }
12
12
 
13
- export class FunctionError extends BaseError.extend('FUNCTION_ERROR') {}
13
+ export class FunctionNotFoundError extends BaseError.extend('FUNCTION_NOT_FOUND', 'Function not found') {
14
+ constructor(functionKey: string, options?: Omit<BaseErrorOptions, 'context'>) {
15
+ super({ context: { function: functionKey }, ...options });
16
+ }
17
+ }
18
+
19
+ export class FunctionError extends BaseError.extend('FUNCTION_ERROR', 'Function invocation error') {}
20
+
21
+ export class TriggerStateNotFoundError extends BaseError.extend('TRIGGER_STATE_NOT_FOUND', 'Trigger state not found') {}
@@ -0,0 +1,32 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import * as Effect from 'effect/Effect';
6
+ import * as Schema from 'effect/Schema';
7
+
8
+ import { defineFunction } from '../handler';
9
+
10
+ export default defineFunction({
11
+ key: 'example.org/function/fib',
12
+ name: 'Fibonacci',
13
+ description: 'Function that calculates a Fibonacci number',
14
+ inputSchema: Schema.Struct({
15
+ iterations: Schema.optional(Schema.Number).annotations({
16
+ description: 'Number of iterations',
17
+ default: 100_000,
18
+ }),
19
+ }),
20
+ outputSchema: Schema.Struct({
21
+ result: Schema.String,
22
+ }),
23
+ handler: Effect.fn(function* ({ data: { iterations = 100_000 } }) {
24
+ let a = 0n;
25
+ let b = 1n;
26
+ for (let i = 0; i < iterations; i++) {
27
+ a += b;
28
+ b = a - b;
29
+ }
30
+ return { result: a.toString() };
31
+ }),
32
+ });
@@ -0,0 +1,40 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ // @ts-ignore
6
+ import { S, defineFunction } from 'dxos:functions';
7
+ import {
8
+ FetchHttpClient,
9
+ HttpClient,
10
+ HttpClientRequest,
11
+ // @ts-ignore
12
+ } from 'https://esm.sh/@effect/platform@0.89.0?deps=effect@3.17.0&bundle=false';
13
+ // @ts-ignore
14
+ import { Effect, Schedule } from 'https://esm.sh/effect@3.17.0?bundle=false';
15
+
16
+ export default defineFunction({
17
+ key: 'dxos.org/script/forex-effect',
18
+ name: 'Forex Effect',
19
+ description: 'Returns the exchange rate between two currencies.',
20
+
21
+ inputSchema: S.Struct({
22
+ from: S.String.annotations({ description: 'The source currency' }),
23
+ to: S.String.annotations({ description: 'The target currency' }),
24
+ }),
25
+
26
+ outputSchema: S.String.annotations({ description: 'The exchange rate between the two currencies' }),
27
+
28
+ handler: async ({ data: { from, to } }: any) =>
29
+ Effect.gen(function* () {
30
+ const res = yield* HttpClientRequest.get(`https://free.ratesdb.com/v1/rates?from=${from}&to=${to}`).pipe(
31
+ HttpClient.execute,
32
+ Effect.flatMap((res: any) => res.json),
33
+ Effect.timeout('1 second'),
34
+ Effect.retry(Schedule.exponential(1_000).pipe(Schedule.compose(Schedule.recurs(3)))),
35
+ Effect.scoped,
36
+ );
37
+
38
+ return res.data.rates[to].toString();
39
+ }).pipe(Effect.provide(FetchHttpClient.layer)),
40
+ });
@@ -0,0 +1,13 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { default as fib$ } from './fib';
6
+ import { default as reply$ } from './reply';
7
+ import { default as sleep$ } from './sleep';
8
+
9
+ export namespace Example {
10
+ export const fib = fib$;
11
+ export const reply = reply$;
12
+ export const sleep = sleep$;
13
+ }
@@ -0,0 +1,21 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import * as Console from 'effect/Console';
6
+ import * as Effect from 'effect/Effect';
7
+ import * as Schema from 'effect/Schema';
8
+
9
+ import { defineFunction } from '../handler';
10
+
11
+ export default defineFunction({
12
+ key: 'example.org/function/reply',
13
+ name: 'Reply',
14
+ description: 'Function that echoes the input',
15
+ inputSchema: Schema.Any,
16
+ outputSchema: Schema.Any,
17
+ handler: Effect.fn(function* ({ data }) {
18
+ yield* Console.log('reply', { data });
19
+ return data;
20
+ }),
21
+ });
@@ -0,0 +1,24 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import * as Effect from 'effect/Effect';
6
+ import * as Schema from 'effect/Schema';
7
+
8
+ import { defineFunction } from '../handler';
9
+
10
+ export default defineFunction({
11
+ key: 'example.org/function/sleep',
12
+ name: 'Sleep',
13
+ description: 'Function that sleeps for a given amount of time',
14
+ inputSchema: Schema.Struct({
15
+ duration: Schema.optional(Schema.Number).annotations({
16
+ description: 'Milliseconds to sleep',
17
+ default: 100_000,
18
+ }),
19
+ }),
20
+ outputSchema: Schema.Void,
21
+ handler: Effect.fn(function* ({ data: { duration = 100_000 } }) {
22
+ yield* Effect.sleep(duration);
23
+ }),
24
+ });
package/src/handler.ts CHANGED
@@ -2,22 +2,44 @@
2
2
  // Copyright 2023 DXOS.org
3
3
  //
4
4
 
5
- import { Schema, type Context, type Effect } from 'effect';
6
-
7
- import { type AiServiceClient } from '@dxos/ai';
8
- // import { type Space } from '@dxos/client/echo';
9
- import type { EchoDatabase } from '@dxos/echo-db';
10
- import { type HasId } from '@dxos/echo-schema';
11
- import { type SpaceId, type DXN } from '@dxos/keys';
12
- import { type QueryResult } from '@dxos/protocols';
13
-
14
- import type { Services } from './services';
5
+ import * as Effect from 'effect/Effect';
6
+ import * as Schema from 'effect/Schema';
7
+
8
+ import { type AiService } from '@dxos/ai';
9
+ import { Obj, Type } from '@dxos/echo';
10
+ import { type DatabaseService } from '@dxos/echo-db';
11
+ import { assertArgument } from '@dxos/invariant';
12
+
13
+ import {
14
+ type CredentialsService,
15
+ type FunctionInvocationService,
16
+ type QueueService,
17
+ type TracingService,
18
+ } from './services';
19
+ import { Function } from './types';
20
+ import { getUserFunctionIdInMetadata, setUserFunctionIdInMetadata } from './url';
15
21
 
16
22
  // TODO(burdon): Model after http request. Ref Lambda/OpenFaaS.
17
23
  // https://docs.aws.amazon.com/lambda/latest/dg/typescript-handler.html
18
24
  // https://www.serverless.com/framework/docs/providers/aws/guide/serverless.yml/#functions
19
25
  // https://www.npmjs.com/package/aws-lambda
20
26
 
27
+ /**
28
+ * Services that are provided at the function call site by the caller.
29
+ */
30
+ export type InvocationServices = TracingService;
31
+
32
+ /**
33
+ * Services that are available to invoked functions.
34
+ */
35
+ export type FunctionServices =
36
+ | InvocationServices
37
+ | AiService.AiService
38
+ | CredentialsService
39
+ | DatabaseService
40
+ | QueueService
41
+ | FunctionInvocationService;
42
+
21
43
  /**
22
44
  * Function handler.
23
45
  */
@@ -33,61 +55,41 @@ export type FunctionHandler<TData = {}, TOutput = any> = (params: {
33
55
  * This will be the payload from the trigger or other data passed into the function in a workflow.
34
56
  */
35
57
  data: TData;
36
- }) => TOutput | Promise<TOutput> | Effect.Effect<TOutput, any, Services>;
58
+ }) => TOutput | Promise<TOutput> | Effect.Effect<TOutput, any, FunctionServices>;
37
59
 
38
60
  /**
39
61
  * Function context.
40
62
  */
41
63
  export interface FunctionContext {
42
- /**
43
- * Space from which the function was invoked.
44
- */
45
- space: SpaceAPI | undefined;
46
-
47
- ai: AiServiceClient;
48
-
49
- /**
50
- * Resolves a service available to the function.
51
- * @throws if the service is not available.
52
- */
53
- getService: <T extends Context.Tag<any, any>>(tag: T) => Context.Tag.Service<T>;
54
-
55
- getSpace: (spaceId: SpaceId) => Promise<SpaceAPI>;
64
+ // TODO(dmaretskyi):
56
65
  }
57
66
 
58
- export interface FunctionContextAi {
59
- // TODO(dmaretskyi): Refer to cloudflare AI docs for more comprehensive typedefs.
60
- run(model: string, inputs: any, options?: any): Promise<any>;
61
- }
67
+ const typeId = Symbol.for('@dxos/functions/FunctionDefinition');
62
68
 
63
- //
64
- // API.
65
- //
66
-
67
- // TODO(dmaretskyi): Temporary API to get the queues working.
68
- // TODO(dmaretskyi): To be replaced with integrating queues into echo.
69
- export interface QueuesAPI {
70
- queryQueue(queue: DXN, options?: {}): Promise<QueryResult>;
71
- insertIntoQueue(queue: DXN, objects: HasId[]): Promise<void>;
72
- }
73
-
74
- /**
75
- * Space interface available to functions.
76
- */
77
- export interface SpaceAPI {
78
- get id(): SpaceId;
79
- get db(): EchoDatabase;
80
-
81
- // TODO(dmaretskyi): Align with echo api: queues.get(id).append(items);
82
- get queues(): QueuesAPI;
83
- }
84
-
85
- // TODO(wittjosiah): Queues are incompatible.
86
- const __assertFunctionSpaceIsCompatibleWithTheClientSpace = () => {
87
- // const _: SpaceAPI = {} as Space;
69
+ export type FunctionDefinition<T = any, O = any> = {
70
+ [typeId]: true;
71
+ key: string;
72
+ name: string;
73
+ description?: string;
74
+ inputSchema: Schema.Schema<T, any>;
75
+ outputSchema?: Schema.Schema<O, any>;
76
+ handler: FunctionHandler<T, O>;
77
+ meta?: {
78
+ /**
79
+ * Tools that are projected from functions have this annotation.
80
+ *
81
+ * deployedFunctionId:
82
+ * - Backend deployment ID assigned by the EDGE function service (typically a UUID).
83
+ * - Used for remote invocation via `FunctionInvocationService` → `RemoteFunctionExecutionService`.
84
+ * - Persisted on the corresponding ECHO `Function.Function` object's metadata under the
85
+ * `FUNCTIONS_META_KEY` and retrieved with `getUserFunctionIdInMetadata`.
86
+ */
87
+ deployedFunctionId?: string;
88
+ };
88
89
  };
89
90
 
90
- export type FunctionDefinition<T = {}, O = any> = {
91
+ export type FunctionProps<T, O> = {
92
+ key: string;
91
93
  name: string;
92
94
  description?: string;
93
95
  inputSchema: Schema.Schema<T, any>;
@@ -95,14 +97,10 @@ export type FunctionDefinition<T = {}, O = any> = {
95
97
  handler: FunctionHandler<T, O>;
96
98
  };
97
99
 
98
- // TODO(dmaretskyi): Bind input type to function handler.
99
- export const defineFunction = <T, O>({
100
- name,
101
- description,
102
- inputSchema,
103
- outputSchema = Schema.Any,
104
- handler,
105
- }: FunctionDefinition<T, O>): FunctionDefinition<T, O> => {
100
+ // TODO(dmaretskyi): Output type doesn't get typechecked.
101
+ export const defineFunction: {
102
+ <I, O>(params: FunctionProps<I, O>): FunctionDefinition<I, O>;
103
+ } = ({ key, name, description, inputSchema, outputSchema = Schema.Any, handler }) => {
106
104
  if (!Schema.isSchema(inputSchema)) {
107
105
  throw new Error('Input schema must be a valid schema');
108
106
  }
@@ -110,11 +108,94 @@ export const defineFunction = <T, O>({
110
108
  throw new Error('Handler must be a function');
111
109
  }
112
110
 
111
+ // Captures the function definition location.
112
+ const limit = Error.stackTraceLimit;
113
+ Error.stackTraceLimit = 2;
114
+ const traceError = new Error();
115
+ Error.stackTraceLimit = limit;
116
+ let cache: false | string = false;
117
+ const captureStackTrace = () => {
118
+ if (cache !== false) {
119
+ return cache;
120
+ }
121
+ if (traceError.stack !== undefined) {
122
+ const stack = traceError.stack.split('\n');
123
+ if (stack[2] !== undefined) {
124
+ cache = stack[2].trim();
125
+ return cache;
126
+ }
127
+ }
128
+ };
129
+
130
+ const handlerWithSpan = (...args: any[]) => {
131
+ const result = (handler as any)(...args);
132
+ if (Effect.isEffect(result)) {
133
+ return Effect.withSpan(result, `${key ?? name}`, {
134
+ captureStackTrace,
135
+ });
136
+ }
137
+ return result;
138
+ };
139
+
113
140
  return {
141
+ [typeId]: true,
142
+ key,
114
143
  name,
115
144
  description,
116
145
  inputSchema,
117
146
  outputSchema,
118
- handler,
147
+ handler: handlerWithSpan,
148
+ } satisfies FunctionDefinition.Any;
149
+ };
150
+
151
+ export const FunctionDefinition = {
152
+ make: defineFunction,
153
+ isFunction: (value: unknown): value is FunctionDefinition.Any => {
154
+ return typeof value === 'object' && value !== null && Symbol.for('@dxos/functions/FunctionDefinition') in value;
155
+ },
156
+ serialize: (functionDef: FunctionDefinition.Any): Function.Function => {
157
+ assertArgument(FunctionDefinition.isFunction(functionDef), 'functionDef');
158
+ return serializeFunction(functionDef);
159
+ },
160
+ deserialize: (functionObj: Function.Function): FunctionDefinition.Any => {
161
+ assertArgument(Obj.instanceOf(Function.Function, functionObj), 'functionObj');
162
+ return deserializeFunction(functionObj);
163
+ },
164
+ };
165
+ export declare namespace FunctionDefinition {
166
+ export type Any = FunctionDefinition<any, any>;
167
+ export type Input<T extends FunctionDefinition> = T extends FunctionDefinition<infer I, any> ? I : never;
168
+ export type Output<T extends FunctionDefinition> = T extends FunctionDefinition<any, infer O> ? O : never;
169
+ }
170
+
171
+ export const serializeFunction = (functionDef: FunctionDefinition<any, any>): Function.Function => {
172
+ const fn = Function.make({
173
+ key: functionDef.key,
174
+ name: functionDef.name,
175
+ version: '0.1.0',
176
+ description: functionDef.description,
177
+ inputSchema: Type.toJsonSchema(functionDef.inputSchema),
178
+ outputSchema: !functionDef.outputSchema ? undefined : Type.toJsonSchema(functionDef.outputSchema),
179
+ });
180
+ if (functionDef.meta?.deployedFunctionId) {
181
+ setUserFunctionIdInMetadata(Obj.getMeta(fn), functionDef.meta.deployedFunctionId);
182
+ }
183
+ return fn;
184
+ };
185
+
186
+ export const deserializeFunction = (functionObj: Function.Function): FunctionDefinition<unknown, unknown> => {
187
+ return {
188
+ [typeId]: true,
189
+ // TODO(dmaretskyi): Fix key.
190
+ key: functionObj.key ?? functionObj.name,
191
+ name: functionObj.name,
192
+ description: functionObj.description,
193
+ inputSchema: !functionObj.inputSchema ? Schema.Unknown : Type.toEffectSchema(functionObj.inputSchema),
194
+ outputSchema: !functionObj.outputSchema ? undefined : Type.toEffectSchema(functionObj.outputSchema),
195
+ // TODO(dmaretskyi): This should throw error.
196
+ handler: () => {},
197
+ meta: {
198
+ deployedFunctionId: getUserFunctionIdInMetadata(Obj.getMeta(functionObj)),
199
+ },
119
200
  };
120
201
  };
package/src/index.ts CHANGED
@@ -2,13 +2,9 @@
2
2
  // Copyright 2024 DXOS.org
3
3
  //
4
4
 
5
+ export * from './errors';
6
+ export * from './example';
5
7
  export * from './handler';
6
- export * from './schema';
7
- export * from './trace';
8
+ export * from './services';
8
9
  export * from './types';
9
10
  export * from './url';
10
- export * from './services';
11
- export * from './executor';
12
- export * from './errors';
13
-
14
- // Blow up cache
@@ -2,9 +2,19 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { Context, Effect } from 'effect';
5
+ import * as HttpClient from '@effect/platform/HttpClient';
6
+ import * as HttpClientRequest from '@effect/platform/HttpClientRequest';
7
+ import type * as Config from 'effect/Config';
8
+ import * as Context from 'effect/Context';
9
+ import * as Effect from 'effect/Effect';
10
+ import * as Layer from 'effect/Layer';
11
+ import * as Redacted from 'effect/Redacted';
6
12
 
7
- type CredentialQuery = {
13
+ import { Query } from '@dxos/echo';
14
+ import { DatabaseService } from '@dxos/echo-db';
15
+ import { AccessToken } from '@dxos/types';
16
+
17
+ export type CredentialQuery = {
8
18
  service?: string;
9
19
  };
10
20
 
@@ -17,7 +27,7 @@ export type ServiceCredential = {
17
27
  apiKey?: string;
18
28
  };
19
29
 
20
- export class CredentialsService extends Context.Tag('CredentialsService')<
30
+ export class CredentialsService extends Context.Tag('@dxos/functions/CredentialsService')<
21
31
  CredentialsService,
22
32
  {
23
33
  /**
@@ -37,6 +47,65 @@ export class CredentialsService extends Context.Tag('CredentialsService')<
37
47
  const credentials = yield* CredentialsService;
38
48
  return yield* Effect.promise(() => credentials.getCredential(query));
39
49
  });
50
+
51
+ static getApiKey = (query: CredentialQuery): Effect.Effect<Redacted.Redacted<string>, never, CredentialsService> =>
52
+ Effect.gen(function* () {
53
+ const credential = yield* CredentialsService.getCredential(query);
54
+ if (!credential.apiKey) {
55
+ throw new Error(`API key not found for service: ${query.service}`);
56
+ }
57
+ return Redacted.make(credential.apiKey);
58
+ });
59
+
60
+ static configuredLayer = (credentials: ServiceCredential[]) =>
61
+ Layer.succeed(CredentialsService, new ConfiguredCredentialsService(credentials));
62
+
63
+ static layerConfig = (credentials: { service: string; apiKey: Config.Config<Redacted.Redacted<string>> }[]) =>
64
+ Layer.effect(
65
+ CredentialsService,
66
+ Effect.gen(function* () {
67
+ const serviceCredentials = yield* Effect.forEach(credentials, ({ service, apiKey }) =>
68
+ Effect.gen(function* () {
69
+ return {
70
+ service,
71
+ apiKey: Redacted.value(yield* apiKey),
72
+ };
73
+ }),
74
+ );
75
+
76
+ return new ConfiguredCredentialsService(serviceCredentials);
77
+ }),
78
+ );
79
+
80
+ static layerFromDatabase = () =>
81
+ Layer.effect(
82
+ CredentialsService,
83
+ Effect.gen(function* () {
84
+ const dbService = yield* DatabaseService;
85
+ const queryCredentials = async (query: CredentialQuery): Promise<ServiceCredential[]> => {
86
+ const { objects: accessTokens } = await dbService.db.query(Query.type(AccessToken.AccessToken)).run();
87
+ return accessTokens
88
+ .filter((accessToken) => accessToken.source === query.service)
89
+ .map((accessToken) => ({
90
+ service: accessToken.source,
91
+ apiKey: accessToken.token,
92
+ }));
93
+ };
94
+ return {
95
+ getCredential: async (query) => {
96
+ const credentials = await queryCredentials(query);
97
+ if (credentials.length === 0) {
98
+ throw new Error(`Credential not found for service: ${query.service}`);
99
+ }
100
+
101
+ return credentials[0];
102
+ },
103
+ queryCredentials: async (query) => {
104
+ return queryCredentials(query);
105
+ },
106
+ };
107
+ }),
108
+ );
40
109
  }
41
110
 
42
111
  export class ConfiguredCredentialsService implements Context.Tag.Service<CredentialsService> {
@@ -56,6 +125,19 @@ export class ConfiguredCredentialsService implements Context.Tag.Service<Credent
56
125
  if (!credential) {
57
126
  throw new Error(`Credential not found for service: ${query.service}`);
58
127
  }
128
+
59
129
  return credential;
60
130
  }
61
131
  }
132
+
133
+ /**
134
+ * Maps the request to include the API key from the credential.
135
+ */
136
+ export const withAuthorization = (query: CredentialQuery, kind?: 'Bearer' | 'Basic') =>
137
+ HttpClient.mapRequestEffect(
138
+ Effect.fnUntraced(function* (request) {
139
+ const key = yield* CredentialsService.getApiKey(query).pipe(Effect.map(Redacted.value));
140
+ const authorization = kind ? `${kind} ${key}` : key;
141
+ return HttpClientRequest.setHeader(request, 'Authorization', authorization);
142
+ }),
143
+ );