@dxos/functions 0.8.4-main.ae835ea → 0.8.4-main.bc2380dfbc

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 (197) hide show
  1. package/LICENSE +102 -5
  2. package/README.md +5 -7
  3. package/dist/lib/neutral/index.mjs +599 -0
  4. package/dist/lib/neutral/index.mjs.map +7 -0
  5. package/dist/lib/neutral/meta.json +1 -0
  6. package/dist/types/src/index.d.ts +2 -7
  7. package/dist/types/src/index.d.ts.map +1 -1
  8. package/dist/types/src/protocol/functions-ai-http-client.d.ts +12 -0
  9. package/dist/types/src/protocol/functions-ai-http-client.d.ts.map +1 -0
  10. package/dist/types/src/protocol/functions-ai-http-client.test.d.ts +2 -0
  11. package/dist/types/src/protocol/functions-ai-http-client.test.d.ts.map +1 -0
  12. package/dist/types/src/protocol/index.d.ts +2 -0
  13. package/dist/types/src/protocol/index.d.ts.map +1 -0
  14. package/dist/types/src/protocol/protocol.d.ts +24 -0
  15. package/dist/types/src/protocol/protocol.d.ts.map +1 -0
  16. package/dist/types/src/protocol/protocol.test.d.ts +2 -0
  17. package/dist/types/src/protocol/protocol.test.d.ts.map +1 -0
  18. package/dist/types/src/sdk.d.ts +10 -0
  19. package/dist/types/src/sdk.d.ts.map +1 -0
  20. package/dist/types/src/services/credentials.d.ts +17 -38
  21. package/dist/types/src/services/credentials.d.ts.map +1 -1
  22. package/dist/types/src/services/function-invocation-service.d.ts +6 -19
  23. package/dist/types/src/services/function-invocation-service.d.ts.map +1 -1
  24. package/dist/types/src/services/index.d.ts +1 -6
  25. package/dist/types/src/services/index.d.ts.map +1 -1
  26. package/dist/types/src/services/queues.d.ts +1 -46
  27. package/dist/types/src/services/queues.d.ts.map +1 -1
  28. package/dist/types/src/services/tracing.d.ts +2 -56
  29. package/dist/types/src/services/tracing.d.ts.map +1 -1
  30. package/dist/types/src/types/index.d.ts +1 -4
  31. package/dist/types/src/types/index.d.ts.map +1 -1
  32. package/dist/types/src/types/url.d.ts +13 -0
  33. package/dist/types/src/types/url.d.ts.map +1 -0
  34. package/dist/types/tsconfig.tsbuildinfo +1 -1
  35. package/package.json +26 -61
  36. package/src/index.ts +2 -7
  37. package/src/protocol/functions-ai-http-client.test.ts +105 -0
  38. package/src/protocol/functions-ai-http-client.ts +141 -0
  39. package/src/{executor → protocol}/index.ts +1 -1
  40. package/src/protocol/protocol.test.ts +58 -0
  41. package/src/protocol/protocol.ts +452 -0
  42. package/src/sdk.ts +31 -0
  43. package/src/services/credentials.ts +81 -110
  44. package/src/services/function-invocation-service.ts +19 -70
  45. package/src/services/index.ts +1 -6
  46. package/src/services/queues.ts +1 -80
  47. package/src/services/tracing.ts +1 -136
  48. package/src/types/index.ts +1 -4
  49. package/src/types/url.ts +32 -0
  50. package/dist/lib/browser/bundler/index.mjs +0 -256
  51. package/dist/lib/browser/bundler/index.mjs.map +0 -7
  52. package/dist/lib/browser/chunk-J5LGTIGS.mjs +0 -10
  53. package/dist/lib/browser/chunk-J5LGTIGS.mjs.map +0 -7
  54. package/dist/lib/browser/chunk-M6EXIREF.mjs +0 -610
  55. package/dist/lib/browser/chunk-M6EXIREF.mjs.map +0 -7
  56. package/dist/lib/browser/edge/index.mjs +0 -83
  57. package/dist/lib/browser/edge/index.mjs.map +0 -7
  58. package/dist/lib/browser/index.mjs +0 -1346
  59. package/dist/lib/browser/index.mjs.map +0 -7
  60. package/dist/lib/browser/meta.json +0 -1
  61. package/dist/lib/browser/testing/index.mjs +0 -131
  62. package/dist/lib/browser/testing/index.mjs.map +0 -7
  63. package/dist/lib/node-esm/bundler/index.mjs +0 -257
  64. package/dist/lib/node-esm/bundler/index.mjs.map +0 -7
  65. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +0 -11
  66. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs.map +0 -7
  67. package/dist/lib/node-esm/chunk-P3IATZMZ.mjs +0 -612
  68. package/dist/lib/node-esm/chunk-P3IATZMZ.mjs.map +0 -7
  69. package/dist/lib/node-esm/edge/index.mjs +0 -84
  70. package/dist/lib/node-esm/edge/index.mjs.map +0 -7
  71. package/dist/lib/node-esm/index.mjs +0 -1347
  72. package/dist/lib/node-esm/index.mjs.map +0 -7
  73. package/dist/lib/node-esm/meta.json +0 -1
  74. package/dist/lib/node-esm/testing/index.mjs +0 -132
  75. package/dist/lib/node-esm/testing/index.mjs.map +0 -7
  76. package/dist/types/src/bundler/bundler.d.ts +0 -49
  77. package/dist/types/src/bundler/bundler.d.ts.map +0 -1
  78. package/dist/types/src/bundler/bundler.test.d.ts +0 -2
  79. package/dist/types/src/bundler/bundler.test.d.ts.map +0 -1
  80. package/dist/types/src/bundler/index.d.ts +0 -2
  81. package/dist/types/src/bundler/index.d.ts.map +0 -1
  82. package/dist/types/src/e2e/deploy.test.d.ts +0 -2
  83. package/dist/types/src/e2e/deploy.test.d.ts.map +0 -1
  84. package/dist/types/src/edge/functions.d.ts +0 -17
  85. package/dist/types/src/edge/functions.d.ts.map +0 -1
  86. package/dist/types/src/edge/index.d.ts +0 -2
  87. package/dist/types/src/edge/index.d.ts.map +0 -1
  88. package/dist/types/src/errors.d.ts +0 -137
  89. package/dist/types/src/errors.d.ts.map +0 -1
  90. package/dist/types/src/example/fib.d.ts +0 -7
  91. package/dist/types/src/example/fib.d.ts.map +0 -1
  92. package/dist/types/src/example/forex-effect.d.ts +0 -3
  93. package/dist/types/src/example/forex-effect.d.ts.map +0 -1
  94. package/dist/types/src/example/index.d.ts +0 -12
  95. package/dist/types/src/example/index.d.ts.map +0 -1
  96. package/dist/types/src/example/reply.d.ts +0 -3
  97. package/dist/types/src/example/reply.d.ts.map +0 -1
  98. package/dist/types/src/example/sleep.d.ts +0 -5
  99. package/dist/types/src/example/sleep.d.ts.map +0 -1
  100. package/dist/types/src/executor/executor.d.ts +0 -14
  101. package/dist/types/src/executor/executor.d.ts.map +0 -1
  102. package/dist/types/src/executor/index.d.ts +0 -2
  103. package/dist/types/src/executor/index.d.ts.map +0 -1
  104. package/dist/types/src/handler.d.ts +0 -102
  105. package/dist/types/src/handler.d.ts.map +0 -1
  106. package/dist/types/src/services/database.d.ts +0 -67
  107. package/dist/types/src/services/database.d.ts.map +0 -1
  108. package/dist/types/src/services/event-logger.d.ts +0 -75
  109. package/dist/types/src/services/event-logger.d.ts.map +0 -1
  110. package/dist/types/src/services/function-invocation-service.test.d.ts +0 -2
  111. package/dist/types/src/services/function-invocation-service.test.d.ts.map +0 -1
  112. package/dist/types/src/services/local-function-execution.d.ts +0 -34
  113. package/dist/types/src/services/local-function-execution.d.ts.map +0 -1
  114. package/dist/types/src/services/remote-function-execution-service.d.ts +0 -22
  115. package/dist/types/src/services/remote-function-execution-service.d.ts.map +0 -1
  116. package/dist/types/src/services/service-container.d.ts +0 -57
  117. package/dist/types/src/services/service-container.d.ts.map +0 -1
  118. package/dist/types/src/services/service-registry.d.ts +0 -31
  119. package/dist/types/src/services/service-registry.d.ts.map +0 -1
  120. package/dist/types/src/services/service-registry.test.d.ts +0 -2
  121. package/dist/types/src/services/service-registry.test.d.ts.map +0 -1
  122. package/dist/types/src/testing/index.d.ts +0 -3
  123. package/dist/types/src/testing/index.d.ts.map +0 -1
  124. package/dist/types/src/testing/layer.d.ts +0 -18
  125. package/dist/types/src/testing/layer.d.ts.map +0 -1
  126. package/dist/types/src/testing/logger.d.ts +0 -5
  127. package/dist/types/src/testing/logger.d.ts.map +0 -1
  128. package/dist/types/src/testing/persist-database.test.d.ts +0 -2
  129. package/dist/types/src/testing/persist-database.test.d.ts.map +0 -1
  130. package/dist/types/src/testing/services.d.ts +0 -59
  131. package/dist/types/src/testing/services.d.ts.map +0 -1
  132. package/dist/types/src/trace.d.ts +0 -122
  133. package/dist/types/src/trace.d.ts.map +0 -1
  134. package/dist/types/src/translations.d.ts +0 -12
  135. package/dist/types/src/translations.d.ts.map +0 -1
  136. package/dist/types/src/triggers/index.d.ts +0 -4
  137. package/dist/types/src/triggers/index.d.ts.map +0 -1
  138. package/dist/types/src/triggers/input-builder.d.ts +0 -3
  139. package/dist/types/src/triggers/input-builder.d.ts.map +0 -1
  140. package/dist/types/src/triggers/invocation-tracer.d.ts +0 -37
  141. package/dist/types/src/triggers/invocation-tracer.d.ts.map +0 -1
  142. package/dist/types/src/triggers/trigger-dispatcher.d.ts +0 -78
  143. package/dist/types/src/triggers/trigger-dispatcher.d.ts.map +0 -1
  144. package/dist/types/src/triggers/trigger-dispatcher.test.d.ts +0 -2
  145. package/dist/types/src/triggers/trigger-dispatcher.test.d.ts.map +0 -1
  146. package/dist/types/src/triggers/trigger-state-store.d.ts +0 -28
  147. package/dist/types/src/triggers/trigger-state-store.d.ts.map +0 -1
  148. package/dist/types/src/types/Function.d.ts +0 -47
  149. package/dist/types/src/types/Function.d.ts.map +0 -1
  150. package/dist/types/src/types/Script.d.ts +0 -28
  151. package/dist/types/src/types/Script.d.ts.map +0 -1
  152. package/dist/types/src/types/Trigger.d.ts +0 -139
  153. package/dist/types/src/types/Trigger.d.ts.map +0 -1
  154. package/dist/types/src/types/TriggerEvent.d.ts +0 -44
  155. package/dist/types/src/types/TriggerEvent.d.ts.map +0 -1
  156. package/dist/types/src/url.d.ts +0 -21
  157. package/dist/types/src/url.d.ts.map +0 -1
  158. package/src/bundler/bundler.test.ts +0 -58
  159. package/src/bundler/bundler.ts +0 -295
  160. package/src/bundler/index.ts +0 -5
  161. package/src/e2e/deploy.test.ts +0 -69
  162. package/src/edge/functions.ts +0 -67
  163. package/src/edge/index.ts +0 -9
  164. package/src/errors.ts +0 -21
  165. package/src/example/fib.ts +0 -32
  166. package/src/example/forex-effect.ts +0 -40
  167. package/src/example/index.ts +0 -13
  168. package/src/example/reply.ts +0 -21
  169. package/src/example/sleep.ts +0 -24
  170. package/src/executor/executor.ts +0 -58
  171. package/src/handler.ts +0 -226
  172. package/src/services/database.ts +0 -175
  173. package/src/services/event-logger.ts +0 -121
  174. package/src/services/function-invocation-service.test.ts +0 -81
  175. package/src/services/local-function-execution.ts +0 -153
  176. package/src/services/remote-function-execution-service.ts +0 -63
  177. package/src/services/service-container.ts +0 -115
  178. package/src/services/service-registry.test.ts +0 -45
  179. package/src/services/service-registry.ts +0 -63
  180. package/src/testing/index.ts +0 -6
  181. package/src/testing/layer.ts +0 -114
  182. package/src/testing/logger.ts +0 -17
  183. package/src/testing/persist-database.test.ts +0 -87
  184. package/src/testing/services.ts +0 -115
  185. package/src/trace.ts +0 -178
  186. package/src/translations.ts +0 -20
  187. package/src/triggers/index.ts +0 -7
  188. package/src/triggers/input-builder.ts +0 -35
  189. package/src/triggers/invocation-tracer.ts +0 -101
  190. package/src/triggers/trigger-dispatcher.test.ts +0 -664
  191. package/src/triggers/trigger-dispatcher.ts +0 -521
  192. package/src/triggers/trigger-state-store.ts +0 -61
  193. package/src/types/Function.ts +0 -51
  194. package/src/types/Script.ts +0 -33
  195. package/src/types/Trigger.ts +0 -139
  196. package/src/types/TriggerEvent.ts +0 -62
  197. package/src/url.ts +0 -55
@@ -1,67 +0,0 @@
1
- //
2
- // Copyright 2024 DXOS.org
3
- //
4
-
5
- import { type DID } from 'iso-did/types';
6
-
7
- import { type Client } from '@dxos/client';
8
- import { createEdgeIdentity } from '@dxos/client/edge';
9
- import { EdgeHttpClient } from '@dxos/edge-client';
10
- import { invariant } from '@dxos/invariant';
11
- import { type PublicKey } from '@dxos/keys';
12
- import { log } from '@dxos/log';
13
- import { type UploadFunctionResponseBody } from '@dxos/protocols';
14
-
15
- export type UploadWorkerArgs = {
16
- client: Client;
17
- version: string;
18
- name?: string;
19
- functionId?: string;
20
- ownerPublicKey: PublicKey;
21
- entryPoint: string;
22
- assets: Record<string, Uint8Array>;
23
- };
24
-
25
- export const uploadWorkerFunction = async ({
26
- client,
27
- version,
28
- name,
29
- functionId,
30
- ownerPublicKey,
31
- entryPoint,
32
- assets,
33
- }: UploadWorkerArgs): Promise<UploadFunctionResponseBody> => {
34
- log('uploading function', { functionId, name, version, ownerPublicKey });
35
- const edgeUrl = client.config.values.runtime?.services?.edge?.url;
36
- invariant(edgeUrl, 'Edge is not configured.');
37
- const edgeClient = new EdgeHttpClient(edgeUrl);
38
- const edgeIdentity = createEdgeIdentity(client);
39
- edgeClient.setIdentity(edgeIdentity);
40
- const response = await edgeClient.uploadFunction(
41
- { functionId },
42
- { name, version, ownerPublicKey: ownerPublicKey.toHex(), entryPoint, assets },
43
- );
44
-
45
- // TODO(burdon): Edge service log.
46
- log('uploaded', {
47
- identityKey: edgeIdentity.identityKey,
48
- functionId,
49
- name,
50
- version,
51
- response,
52
- });
53
-
54
- return response;
55
- };
56
-
57
- export const incrementSemverPatch = (version: string): string => {
58
- const [major, minor, patch] = version.split('.');
59
- const patchNum = Number(patch);
60
- invariant(!Number.isNaN(patchNum), `Unexpected function version format: ${version}`);
61
- return [major, minor, String(patchNum + 1)].join('.');
62
- };
63
-
64
- // TODO(burdon): Factor out.
65
- export const publicKeyToDid = (key: PublicKey): DID => {
66
- return `did:key:${key.toHex()}`;
67
- };
package/src/edge/index.ts DELETED
@@ -1,9 +0,0 @@
1
- //
2
- // Copyright 2024 DXOS.org
3
- //
4
-
5
- // NOTE: This module is separate because it uses the edge client.
6
- // This means it cannot be used on edge itself.
7
- // TODO(wittjosiah): Factor out.
8
-
9
- export * from './functions';
package/src/errors.ts DELETED
@@ -1,21 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- import { BaseError, type BaseErrorOptions } from '@dxos/errors';
6
-
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
- }
11
- }
12
-
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') {}
@@ -1,32 +0,0 @@
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
- });
@@ -1,40 +0,0 @@
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
- });
@@ -1,13 +0,0 @@
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
- }
@@ -1,21 +0,0 @@
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
- });
@@ -1,24 +0,0 @@
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
- });
@@ -1,58 +0,0 @@
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 { type SpaceId } from '@dxos/client/echo';
9
- import { runAndForwardErrors } from '@dxos/effect';
10
-
11
- import type { FunctionContext, FunctionDefinition } from '../handler';
12
- import type { ServiceContainer, Services } from '../services';
13
-
14
- /**
15
- * @deprecated Use `FunctionInvocationService`
16
- */
17
- export class FunctionExecutor {
18
- constructor(private readonly _services: ServiceContainer) {}
19
-
20
- /**
21
- * Invoke function.
22
- */
23
- // TODO(dmaretskyi): Invocation context: queue, space, etc...
24
- async invoke<F extends FunctionDefinition<any, any>>(
25
- functionDef: F,
26
- input: F extends FunctionDefinition<infer I, infer _O> ? I : never,
27
- ): Promise<F extends FunctionDefinition<infer _I, infer O> ? O : never> {
28
- // Assert input matches schema
29
- const assertInput = functionDef.inputSchema.pipe(Schema.asserts);
30
- (assertInput as any)(input);
31
-
32
- const context: FunctionContext = {
33
- space: undefined,
34
- getService: this._services.getService.bind(this._services),
35
- getSpace: async (_spaceId: SpaceId) => {
36
- throw new Error('Not available. Use the database service instead.');
37
- },
38
- };
39
-
40
- const result = functionDef.handler({ context, data: input });
41
-
42
- let data: unknown;
43
- if (Effect.isEffect(result)) {
44
- data = await (result as Effect.Effect<unknown, unknown, Services>).pipe(
45
- Effect.provide(this._services.createLayer()),
46
- runAndForwardErrors,
47
- );
48
- } else {
49
- data = await result;
50
- }
51
-
52
- // Assert output matches schema
53
- const assertOutput = functionDef.outputSchema?.pipe(Schema.asserts);
54
- (assertOutput as any)(data);
55
-
56
- return data as any;
57
- }
58
- }
package/src/handler.ts DELETED
@@ -1,226 +0,0 @@
1
- //
2
- // Copyright 2023 DXOS.org
3
- //
4
-
5
- import type * as Context from 'effect/Context';
6
- import * as Effect from 'effect/Effect';
7
- import * as Schema from 'effect/Schema';
8
-
9
- import { Obj, Type } from '@dxos/echo';
10
- import { type HasId } from '@dxos/echo/internal';
11
- import { type EchoDatabase } from '@dxos/echo-db';
12
- import { assertArgument } from '@dxos/invariant';
13
- import { type DXN, type SpaceId } from '@dxos/keys';
14
- import { type QueryResult } from '@dxos/protocols';
15
-
16
- import { type Services } from './services';
17
- import { Function } from './types';
18
- import { getUserFunctionIdInMetadata, setUserFunctionIdInMetadata } from './url';
19
-
20
- // TODO(burdon): Model after http request. Ref Lambda/OpenFaaS.
21
- // https://docs.aws.amazon.com/lambda/latest/dg/typescript-handler.html
22
- // https://www.serverless.com/framework/docs/providers/aws/guide/serverless.yml/#functions
23
- // https://www.npmjs.com/package/aws-lambda
24
-
25
- /**
26
- * Function handler.
27
- */
28
- export type FunctionHandler<TData = {}, TOutput = any> = (params: {
29
- /**
30
- * Services and context available to the function.
31
- */
32
- context: FunctionContext;
33
-
34
- /**
35
- * Data passed as the input to the function.
36
- * Must match the function's input schema.
37
- * This will be the payload from the trigger or other data passed into the function in a workflow.
38
- */
39
- data: TData;
40
- }) => TOutput | Promise<TOutput> | Effect.Effect<TOutput, any, Services>;
41
-
42
- /**
43
- * Function context.
44
- */
45
- export interface FunctionContext {
46
- /**
47
- * Space from which the function was invoked.
48
- */
49
- space: SpaceAPI | undefined;
50
-
51
- /**
52
- * Resolves a service available to the function.
53
- * @throws if the service is not available.
54
- */
55
- getService: <T extends Context.Tag<any, any>>(tag: T) => Context.Tag.Service<T>;
56
-
57
- getSpace: (spaceId: SpaceId) => Promise<SpaceAPI>;
58
- }
59
-
60
- export interface FunctionContextAi {
61
- // TODO(dmaretskyi): Refer to cloudflare AI docs for more comprehensive typedefs.
62
- run(model: string, inputs: any, options?: any): Promise<any>;
63
- }
64
-
65
- //
66
- // API.
67
- //
68
-
69
- // TODO(dmaretskyi): Temporary API to get the queues working.
70
- // TODO(dmaretskyi): To be replaced with integrating queues into echo.
71
- export interface QueuesAPI {
72
- queryQueue(queue: DXN, options?: {}): Promise<QueryResult>;
73
- insertIntoQueue(queue: DXN, objects: HasId[]): Promise<void>;
74
- }
75
-
76
- /**
77
- * Space interface available to functions.
78
- */
79
- export interface SpaceAPI {
80
- get id(): SpaceId;
81
- get db(): EchoDatabase;
82
-
83
- // TODO(dmaretskyi): Align with echo api: queues.get(id).append(items);
84
- get queues(): QueuesAPI;
85
- }
86
-
87
- // TODO(wittjosiah): Queues are incompatible.
88
- const __assertFunctionSpaceIsCompatibleWithTheClientSpace = () => {
89
- // const _: SpaceAPI = {} as Space;
90
- };
91
-
92
- const typeId = Symbol.for('@dxos/functions/FunctionDefinition');
93
-
94
- export type FunctionDefinition<T = any, O = any> = {
95
- [typeId]: true;
96
- key: string;
97
- name: string;
98
- description?: string;
99
- inputSchema: Schema.Schema<T, any>;
100
- outputSchema?: Schema.Schema<O, any>;
101
- handler: FunctionHandler<T, O>;
102
- meta?: {
103
- /**
104
- * Tools that are projected from functions have this annotation.
105
- *
106
- * deployedFunctionId:
107
- * - Backend deployment ID assigned by the EDGE function service (typically a UUID).
108
- * - Used for remote invocation via `FunctionInvocationService` → `RemoteFunctionExecutionService`.
109
- * - Persisted on the corresponding ECHO `Function.Function` object's metadata under the
110
- * `FUNCTIONS_META_KEY` and retrieved with `getUserFunctionIdInMetadata`.
111
- */
112
- deployedFunctionId?: string;
113
- };
114
- };
115
-
116
- export type FunctionProps<T, O> = {
117
- key: string;
118
- name: string;
119
- description?: string;
120
- inputSchema: Schema.Schema<T, any>;
121
- outputSchema?: Schema.Schema<O, any>;
122
- handler: FunctionHandler<T, O>;
123
- };
124
-
125
- // TODO(dmaretskyi): Output type doesn't get typechecked.
126
- export const defineFunction: {
127
- <I, O>(params: FunctionProps<I, O>): FunctionDefinition<I, O>;
128
- } = ({ key, name, description, inputSchema, outputSchema = Schema.Any, handler }) => {
129
- if (!Schema.isSchema(inputSchema)) {
130
- throw new Error('Input schema must be a valid schema');
131
- }
132
- if (typeof handler !== 'function') {
133
- throw new Error('Handler must be a function');
134
- }
135
-
136
- // Captures the function definition location.
137
- const limit = Error.stackTraceLimit;
138
- Error.stackTraceLimit = 2;
139
- const traceError = new Error();
140
- Error.stackTraceLimit = limit;
141
- let cache: false | string = false;
142
- const captureStackTrace = () => {
143
- if (cache !== false) {
144
- return cache;
145
- }
146
- if (traceError.stack !== undefined) {
147
- const stack = traceError.stack.split('\n');
148
- if (stack[2] !== undefined) {
149
- cache = stack[2].trim();
150
- return cache;
151
- }
152
- }
153
- };
154
-
155
- const handlerWithSpan = (...args: any[]) => {
156
- const result = (handler as any)(...args);
157
- if (Effect.isEffect(result)) {
158
- return Effect.withSpan(result, `${key ?? name}`, {
159
- captureStackTrace,
160
- });
161
- }
162
- return result;
163
- };
164
-
165
- return {
166
- [typeId]: true,
167
- key,
168
- name,
169
- description,
170
- inputSchema,
171
- outputSchema,
172
- handler: handlerWithSpan,
173
- } satisfies FunctionDefinition.Any;
174
- };
175
-
176
- export const FunctionDefinition = {
177
- make: defineFunction,
178
- isFunction: (value: unknown): value is FunctionDefinition.Any => {
179
- return typeof value === 'object' && value !== null && Symbol.for('@dxos/functions/FunctionDefinition') in value;
180
- },
181
- serialize: (functionDef: FunctionDefinition.Any): Function.Function => {
182
- assertArgument(FunctionDefinition.isFunction(functionDef), 'functionDef');
183
- return serializeFunction(functionDef);
184
- },
185
- deserialize: (functionObj: Function.Function): FunctionDefinition.Any => {
186
- assertArgument(Obj.instanceOf(Function.Function, functionObj), 'functionObj');
187
- return deserializeFunction(functionObj);
188
- },
189
- };
190
- export declare namespace FunctionDefinition {
191
- export type Any = FunctionDefinition<any, any>;
192
- export type Input<T extends FunctionDefinition> = T extends FunctionDefinition<infer I, any> ? I : never;
193
- export type Output<T extends FunctionDefinition> = T extends FunctionDefinition<any, infer O> ? O : never;
194
- }
195
-
196
- export const serializeFunction = (functionDef: FunctionDefinition<any, any>): Function.Function => {
197
- const fn = Function.make({
198
- key: functionDef.key,
199
- name: functionDef.name,
200
- version: '0.1.0',
201
- description: functionDef.description,
202
- inputSchema: Type.toJsonSchema(functionDef.inputSchema),
203
- outputSchema: !functionDef.outputSchema ? undefined : Type.toJsonSchema(functionDef.outputSchema),
204
- });
205
- if (functionDef.meta?.deployedFunctionId) {
206
- setUserFunctionIdInMetadata(Obj.getMeta(fn), functionDef.meta.deployedFunctionId);
207
- }
208
- return fn;
209
- };
210
-
211
- export const deserializeFunction = (functionObj: Function.Function): FunctionDefinition<unknown, unknown> => {
212
- return {
213
- [typeId]: true,
214
- // TODO(dmaretskyi): Fix key.
215
- key: functionObj.key ?? functionObj.name,
216
- name: functionObj.name,
217
- description: functionObj.description,
218
- inputSchema: !functionObj.inputSchema ? Schema.Unknown : Type.toEffectSchema(functionObj.inputSchema),
219
- outputSchema: !functionObj.outputSchema ? undefined : Type.toEffectSchema(functionObj.outputSchema),
220
- // TODO(dmaretskyi): This should throw error.
221
- handler: () => {},
222
- meta: {
223
- deployedFunctionId: getUserFunctionIdInMetadata(Obj.getMeta(functionObj)),
224
- },
225
- };
226
- };
@@ -1,175 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- import * as Context from 'effect/Context';
6
- import * as Effect from 'effect/Effect';
7
- import * as Layer from 'effect/Layer';
8
- import * as Option from 'effect/Option';
9
- import type * as Schema from 'effect/Schema';
10
-
11
- import {
12
- type Filter,
13
- type Live,
14
- Obj,
15
- ObjectNotFoundError,
16
- type Query,
17
- type Ref,
18
- type Relation,
19
- type Type,
20
- } from '@dxos/echo';
21
- import type { EchoSchema } from '@dxos/echo/internal';
22
- import type { EchoDatabase, FlushOptions, OneShotQueryResult, QueryResult, SchemaRegistryQuery } from '@dxos/echo-db';
23
- import type { SchemaRegistryPreparedQuery } from '@dxos/echo-db';
24
- import { promiseWithCauseCapture } from '@dxos/effect';
25
- import { invariant } from '@dxos/invariant';
26
- import type { DXN } from '@dxos/keys';
27
-
28
- export class DatabaseService extends Context.Tag('@dxos/functions/DatabaseService')<
29
- DatabaseService,
30
- {
31
- readonly db: EchoDatabase;
32
- }
33
- >() {
34
- static notAvailable = Layer.succeed(DatabaseService, {
35
- get db(): EchoDatabase {
36
- throw new Error('Database not available');
37
- },
38
- });
39
-
40
- static make = (db: EchoDatabase): Context.Tag.Service<DatabaseService> => {
41
- return {
42
- get db() {
43
- return db;
44
- },
45
- };
46
- };
47
-
48
- static layer = (db: EchoDatabase): Layer.Layer<DatabaseService> => {
49
- return Layer.succeed(DatabaseService, DatabaseService.make(db));
50
- };
51
-
52
- /**
53
- * Resolves an object by its DXN.
54
- */
55
- static resolve: {
56
- // No type check.
57
- (dxn: DXN): Effect.Effect<Obj.Any | Relation.Any, never, DatabaseService>;
58
- // Check matches schema.
59
- <S extends Type.Obj.Any | Type.Relation.Any>(
60
- dxn: DXN,
61
- schema: S,
62
- ): Effect.Effect<Schema.Schema.Type<S>, ObjectNotFoundError, DatabaseService>;
63
- } = (<S extends Type.Obj.Any | Type.Relation.Any>(
64
- dxn: DXN,
65
- schema?: S,
66
- ): Effect.Effect<Schema.Schema.Type<S>, ObjectNotFoundError, DatabaseService> =>
67
- Effect.gen(function* () {
68
- const { db } = yield* DatabaseService;
69
- const object = yield* promiseWithCauseCapture(() =>
70
- db.graph
71
- .createRefResolver({
72
- context: {
73
- space: db.spaceId,
74
- },
75
- })
76
- .resolve(dxn),
77
- );
78
-
79
- if (!object) {
80
- return yield* Effect.fail(new ObjectNotFoundError(dxn));
81
- }
82
- invariant(!schema || Obj.instanceOf(schema, object), 'Object type mismatch.');
83
- return object as any;
84
- })) as any;
85
-
86
- /**
87
- * Loads an object reference.
88
- */
89
- static load: <T>(ref: Ref.Ref<T>) => Effect.Effect<T, ObjectNotFoundError, never> = Effect.fn(function* (ref) {
90
- const object = yield* promiseWithCauseCapture(() => ref.tryLoad());
91
- if (!object) {
92
- return yield* Effect.fail(new ObjectNotFoundError(ref.dxn));
93
- }
94
- return object;
95
- });
96
-
97
- /**
98
- * Loads an object reference option.
99
- */
100
- // TODO(burdon): Option?
101
- static loadOption: <T>(ref: Ref.Ref<T>) => Effect.Effect<Option.Option<T>, never, never> = Effect.fn(function* (ref) {
102
- const object = yield* DatabaseService.load(ref).pipe(
103
- Effect.catchTag('OBJECT_NOT_FOUND', () => Effect.succeed(undefined)),
104
- );
105
- return Option.fromNullable(object);
106
- });
107
-
108
- // TODO(burdon): Can we create a proxy for the following methods on EchoDatabase? Use @inheritDoc?
109
- // TODO(burdon): Figure out how to chain query().run();
110
-
111
- /**
112
- * @link EchoDatabase.add
113
- */
114
- static add = <T extends Obj.Any | Relation.Any>(obj: T): Effect.Effect<T, never, DatabaseService> =>
115
- DatabaseService.pipe(Effect.map(({ db }) => db.add(obj)));
116
-
117
- /**
118
- * @link EchoDatabase.remove
119
- */
120
- static remove = <T extends Obj.Any | Relation.Any>(obj: T): Effect.Effect<void, never, DatabaseService> =>
121
- DatabaseService.pipe(Effect.map(({ db }) => db.remove(obj)));
122
-
123
- /**
124
- * @link EchoDatabase.flush
125
- */
126
- static flush = (opts?: FlushOptions) =>
127
- DatabaseService.pipe(Effect.flatMap(({ db }) => promiseWithCauseCapture(() => db.flush(opts))));
128
-
129
- /**
130
- * @link EchoDatabase.getObjectById
131
- */
132
- static getObjectById = <T extends Obj.Any | Relation.Any>(
133
- id: string,
134
- ): Effect.Effect<Live<T> | undefined, never, DatabaseService> => {
135
- return DatabaseService.pipe(Effect.map(({ db }) => db.getObjectById(id)));
136
- };
137
-
138
- /**
139
- * Creates a `QueryResult` object that can be subscribed to.
140
- */
141
- static query: {
142
- <Q extends Query.Any>(query: Q): Effect.Effect<QueryResult<Live<Query.Type<Q>>>, never, DatabaseService>;
143
- <F extends Filter.Any>(filter: F): Effect.Effect<QueryResult<Live<Filter.Type<F>>>, never, DatabaseService>;
144
- } = (queryOrFilter: Query.Any | Filter.Any) =>
145
- DatabaseService.pipe(
146
- Effect.map(({ db }) => db.query(queryOrFilter as any)),
147
- Effect.withSpan('DatabaseService.query'),
148
- );
149
-
150
- /**
151
- * Executes the query once and returns the results.
152
- */
153
- static runQuery: {
154
- <Q extends Query.Any>(query: Q): Effect.Effect<OneShotQueryResult<Live<Query.Type<Q>>>, never, DatabaseService>;
155
- <F extends Filter.Any>(filter: F): Effect.Effect<OneShotQueryResult<Live<Filter.Type<F>>>, never, DatabaseService>;
156
- } = (queryOrFilter: Query.Any | Filter.Any) =>
157
- DatabaseService.query(queryOrFilter as any).pipe(
158
- Effect.flatMap((queryResult) => promiseWithCauseCapture(() => queryResult.run())),
159
- );
160
-
161
- static schemaQuery = <Q extends SchemaRegistryQuery>(
162
- query: Q,
163
- ): Effect.Effect<SchemaRegistryPreparedQuery<EchoSchema>, never, DatabaseService> =>
164
- DatabaseService.pipe(
165
- Effect.map(({ db }) => db.schemaRegistry.query(query)),
166
- Effect.withSpan('DatabaseService.schemaQuery'),
167
- );
168
-
169
- static runSchemaQuery = <Q extends SchemaRegistryQuery>(
170
- query: Q,
171
- ): Effect.Effect<EchoSchema[], never, DatabaseService> =>
172
- DatabaseService.schemaQuery(query).pipe(
173
- Effect.flatMap((queryResult) => promiseWithCauseCapture(() => queryResult.run())),
174
- );
175
- }