@dxos/functions 0.8.4-main.2e9d522 → 0.8.4-main.3c1ae3b

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 (158) hide show
  1. package/dist/lib/browser/index.mjs +901 -369
  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 +901 -369
  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 +89 -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/index.d.ts +5 -7
  20. package/dist/types/src/index.d.ts.map +1 -1
  21. package/dist/types/src/protocol/index.d.ts +2 -0
  22. package/dist/types/src/protocol/index.d.ts.map +1 -0
  23. package/dist/types/src/protocol/protocol.d.ts +7 -0
  24. package/dist/types/src/protocol/protocol.d.ts.map +1 -0
  25. package/dist/types/src/protocol/protocol.test.d.ts +2 -0
  26. package/dist/types/src/protocol/protocol.test.d.ts.map +1 -0
  27. package/dist/types/src/sdk.d.ts +100 -0
  28. package/dist/types/src/sdk.d.ts.map +1 -0
  29. package/dist/types/src/services/credentials.d.ts +20 -3
  30. package/dist/types/src/services/credentials.d.ts.map +1 -1
  31. package/dist/types/src/services/event-logger.d.ts +80 -30
  32. package/dist/types/src/services/event-logger.d.ts.map +1 -1
  33. package/dist/types/src/services/function-invocation-service.d.ts +11 -0
  34. package/dist/types/src/services/function-invocation-service.d.ts.map +1 -0
  35. package/dist/types/src/services/index.d.ts +5 -5
  36. package/dist/types/src/services/index.d.ts.map +1 -1
  37. package/dist/types/src/services/queues.d.ts +23 -6
  38. package/dist/types/src/services/queues.d.ts.map +1 -1
  39. package/dist/types/src/services/tracing.d.ts +35 -6
  40. package/dist/types/src/services/tracing.d.ts.map +1 -1
  41. package/dist/types/src/types/Function.d.ts +63 -0
  42. package/dist/types/src/types/Function.d.ts.map +1 -0
  43. package/dist/types/src/types/Script.d.ts +28 -0
  44. package/dist/types/src/types/Script.d.ts.map +1 -0
  45. package/dist/types/src/types/Trigger.d.ts +141 -0
  46. package/dist/types/src/types/Trigger.d.ts.map +1 -0
  47. package/dist/types/src/types/TriggerEvent.d.ts +43 -0
  48. package/dist/types/src/types/TriggerEvent.d.ts.map +1 -0
  49. package/dist/types/src/types/index.d.ts +6 -0
  50. package/dist/types/src/types/index.d.ts.map +1 -0
  51. package/dist/types/src/types/url.d.ts +12 -0
  52. package/dist/types/src/types/url.d.ts.map +1 -0
  53. package/dist/types/tsconfig.tsbuildinfo +1 -1
  54. package/package.json +20 -68
  55. package/src/errors.ts +13 -5
  56. package/src/example/fib.ts +32 -0
  57. package/src/example/forex-effect.ts +40 -0
  58. package/src/example/index.ts +13 -0
  59. package/src/example/reply.ts +21 -0
  60. package/src/example/sleep.ts +24 -0
  61. package/src/index.ts +5 -9
  62. package/src/{executor → protocol}/index.ts +1 -1
  63. package/src/protocol/protocol.test.ts +59 -0
  64. package/src/protocol/protocol.ts +158 -0
  65. package/src/sdk.ts +240 -0
  66. package/src/services/credentials.ts +101 -3
  67. package/src/services/event-logger.ts +77 -37
  68. package/src/services/function-invocation-service.ts +23 -0
  69. package/src/services/index.ts +5 -5
  70. package/src/services/queues.ts +37 -10
  71. package/src/services/tracing.ts +82 -16
  72. package/src/types/Function.ts +80 -0
  73. package/src/types/Script.ts +33 -0
  74. package/src/types/Trigger.ts +141 -0
  75. package/src/types/TriggerEvent.ts +62 -0
  76. package/src/types/index.ts +9 -0
  77. package/src/types/url.ts +31 -0
  78. package/dist/lib/browser/bundler/index.mjs +0 -247
  79. package/dist/lib/browser/bundler/index.mjs.map +0 -7
  80. package/dist/lib/browser/chunk-3NGCSUEW.mjs +0 -328
  81. package/dist/lib/browser/chunk-3NGCSUEW.mjs.map +0 -7
  82. package/dist/lib/browser/edge/index.mjs +0 -69
  83. package/dist/lib/browser/edge/index.mjs.map +0 -7
  84. package/dist/lib/browser/testing/index.mjs +0 -59
  85. package/dist/lib/browser/testing/index.mjs.map +0 -7
  86. package/dist/lib/node-esm/bundler/index.mjs +0 -249
  87. package/dist/lib/node-esm/bundler/index.mjs.map +0 -7
  88. package/dist/lib/node-esm/chunk-FJ2MU7TL.mjs +0 -330
  89. package/dist/lib/node-esm/chunk-FJ2MU7TL.mjs.map +0 -7
  90. package/dist/lib/node-esm/edge/index.mjs +0 -71
  91. package/dist/lib/node-esm/edge/index.mjs.map +0 -7
  92. package/dist/lib/node-esm/testing/index.mjs +0 -60
  93. package/dist/lib/node-esm/testing/index.mjs.map +0 -7
  94. package/dist/types/src/bundler/bundler.d.ts +0 -50
  95. package/dist/types/src/bundler/bundler.d.ts.map +0 -1
  96. package/dist/types/src/bundler/bundler.test.d.ts +0 -2
  97. package/dist/types/src/bundler/bundler.test.d.ts.map +0 -1
  98. package/dist/types/src/bundler/index.d.ts +0 -2
  99. package/dist/types/src/bundler/index.d.ts.map +0 -1
  100. package/dist/types/src/edge/functions.d.ts +0 -16
  101. package/dist/types/src/edge/functions.d.ts.map +0 -1
  102. package/dist/types/src/edge/index.d.ts +0 -2
  103. package/dist/types/src/edge/index.d.ts.map +0 -1
  104. package/dist/types/src/executor/executor.d.ts +0 -8
  105. package/dist/types/src/executor/executor.d.ts.map +0 -1
  106. package/dist/types/src/executor/index.d.ts +0 -2
  107. package/dist/types/src/executor/index.d.ts.map +0 -1
  108. package/dist/types/src/handler.d.ts +0 -62
  109. package/dist/types/src/handler.d.ts.map +0 -1
  110. package/dist/types/src/schema.d.ts +0 -38
  111. package/dist/types/src/schema.d.ts.map +0 -1
  112. package/dist/types/src/services/database.d.ts +0 -29
  113. package/dist/types/src/services/database.d.ts.map +0 -1
  114. package/dist/types/src/services/function-call-service.d.ts +0 -16
  115. package/dist/types/src/services/function-call-service.d.ts.map +0 -1
  116. package/dist/types/src/services/service-container.d.ts +0 -56
  117. package/dist/types/src/services/service-container.d.ts.map +0 -1
  118. package/dist/types/src/services/service-registry.d.ts +0 -29
  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 -10
  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/services.d.ts +0 -59
  129. package/dist/types/src/testing/services.d.ts.map +0 -1
  130. package/dist/types/src/trace.d.ts +0 -124
  131. package/dist/types/src/trace.d.ts.map +0 -1
  132. package/dist/types/src/translations.d.ts +0 -12
  133. package/dist/types/src/translations.d.ts.map +0 -1
  134. package/dist/types/src/types.d.ts +0 -411
  135. package/dist/types/src/types.d.ts.map +0 -1
  136. package/dist/types/src/url.d.ts +0 -17
  137. package/dist/types/src/url.d.ts.map +0 -1
  138. package/src/bundler/bundler.test.ts +0 -59
  139. package/src/bundler/bundler.ts +0 -292
  140. package/src/bundler/index.ts +0 -5
  141. package/src/edge/functions.ts +0 -64
  142. package/src/edge/index.ts +0 -9
  143. package/src/executor/executor.ts +0 -54
  144. package/src/handler.ts +0 -120
  145. package/src/schema.ts +0 -57
  146. package/src/services/database.ts +0 -70
  147. package/src/services/function-call-service.ts +0 -64
  148. package/src/services/service-container.ts +0 -113
  149. package/src/services/service-registry.test.ts +0 -42
  150. package/src/services/service-registry.ts +0 -56
  151. package/src/testing/index.ts +0 -6
  152. package/src/testing/layer.ts +0 -31
  153. package/src/testing/logger.ts +0 -16
  154. package/src/testing/services.ts +0 -114
  155. package/src/trace.ts +0 -180
  156. package/src/translations.ts +0 -20
  157. package/src/types.ts +0 -211
  158. package/src/url.ts +0 -52
@@ -1,98 +1,193 @@
1
1
  import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
- import {
3
- ConfiguredCredentialsService,
4
- ContextQueueService,
5
- CredentialsService,
6
- DatabaseService,
7
- EventLogger,
8
- FunctionCallService,
9
- QueueService,
10
- SERVICE_TAGS,
11
- ServiceContainer,
12
- TracingService,
13
- createDefectLogger,
14
- createEventLogger,
15
- logCustomEvent
16
- } from "./chunk-FJ2MU7TL.mjs";
2
+ var __defProp = Object.defineProperty;
3
+ var __export = (target, all) => {
4
+ for (var name in all)
5
+ __defProp(target, name, { get: all[name], enumerable: true });
6
+ };
17
7
 
18
- // src/handler.ts
19
- import { Schema } from "effect";
20
- var defineFunction = ({ name, description, inputSchema, outputSchema = Schema.Any, handler }) => {
21
- if (!Schema.isSchema(inputSchema)) {
22
- throw new Error("Input schema must be a valid schema");
8
+ // src/errors.ts
9
+ import { BaseError } from "@dxos/errors";
10
+ var ServiceNotAvailableError = class extends BaseError.extend("SERVICE_NOT_AVAILABLE", "Service not available") {
11
+ constructor(service, options) {
12
+ super({
13
+ context: {
14
+ service
15
+ },
16
+ ...options
17
+ });
23
18
  }
24
- if (typeof handler !== "function") {
25
- throw new Error("Handler must be a function");
19
+ };
20
+ var FunctionNotFoundError = class extends BaseError.extend("FUNCTION_NOT_FOUND", "Function not found") {
21
+ constructor(functionKey, options) {
22
+ super({
23
+ context: {
24
+ function: functionKey
25
+ },
26
+ ...options
27
+ });
26
28
  }
27
- return {
28
- name,
29
- description,
30
- inputSchema,
31
- outputSchema,
32
- handler
33
- };
29
+ };
30
+ var FunctionError = class extends BaseError.extend("FUNCTION_ERROR", "Function invocation error") {
31
+ };
32
+ var TriggerStateNotFoundError = class extends BaseError.extend("TRIGGER_STATE_NOT_FOUND", "Trigger state not found") {
34
33
  };
35
34
 
36
- // src/schema.ts
37
- import { Schema as Schema2 } from "effect";
38
- import { Type } from "@dxos/echo";
39
- import { JsonSchemaType, LabelAnnotation, Ref } from "@dxos/echo-schema";
40
- import { DataType } from "@dxos/schema";
41
- var ScriptType = Schema2.Struct({
42
- name: Schema2.optional(Schema2.String),
43
- description: Schema2.optional(Schema2.String),
35
+ // src/example/fib.ts
36
+ import * as Effect2 from "effect/Effect";
37
+ import * as Schema6 from "effect/Schema";
38
+
39
+ // src/sdk.ts
40
+ import * as Effect from "effect/Effect";
41
+ import * as Schema5 from "effect/Schema";
42
+ import { Obj as Obj5, Type as Type5 } from "@dxos/echo";
43
+ import { assertArgument, failedInvariant } from "@dxos/invariant";
44
+
45
+ // src/types/Function.ts
46
+ var Function_exports = {};
47
+ __export(Function_exports, {
48
+ Function: () => Function,
49
+ make: () => make2,
50
+ setFrom: () => setFrom
51
+ });
52
+ import * as Schema2 from "effect/Schema";
53
+ import { Annotation as Annotation2, JsonSchema, Obj as Obj2, Type as Type2 } from "@dxos/echo";
54
+ import { SystemTypeAnnotation } from "@dxos/echo/internal";
55
+
56
+ // src/types/Script.ts
57
+ var Script_exports = {};
58
+ __export(Script_exports, {
59
+ Script: () => Script,
60
+ make: () => make
61
+ });
62
+ import * as Schema from "effect/Schema";
63
+ import { Annotation, Obj, Ref, Type } from "@dxos/echo";
64
+ import { FormInputAnnotation } from "@dxos/echo/internal";
65
+ import { Text } from "@dxos/schema";
66
+ var Script = Schema.Struct({
67
+ name: Schema.String.pipe(Schema.optional),
68
+ description: Schema.String.pipe(Schema.optional),
44
69
  // TODO(burdon): Change to hash of deployed content.
45
70
  // Whether source has changed since last deploy.
46
- changed: Schema2.optional(Schema2.Boolean),
47
- source: Ref(DataType.Text)
71
+ changed: Schema.Boolean.pipe(FormInputAnnotation.set(false), Schema.optional),
72
+ source: Type.Ref(Text.Text).pipe(FormInputAnnotation.set(false))
48
73
  }).pipe(Type.Obj({
49
74
  typename: "dxos.org/type/Script",
50
75
  version: "0.1.0"
51
- }), LabelAnnotation.set([
76
+ }), Annotation.LabelAnnotation.set([
52
77
  "name"
53
78
  ]));
54
- var FunctionType = Schema2.Struct({
55
- // TODO(burdon): Rename to id/uri?
79
+ var make = ({ source = "", ...props } = {}) => Obj.make(Script, {
80
+ ...props,
81
+ source: Ref.make(Text.make(source))
82
+ });
83
+
84
+ // src/types/Function.ts
85
+ var Function = Schema2.Struct({
86
+ /**
87
+ * Global registry ID.
88
+ * NOTE: The `key` property refers to the original registry entry.
89
+ */
90
+ // TODO(burdon): Create Format type for DXN-like ids, such as this and schema type.
91
+ // TODO(dmaretskyi): Consider making it part of ECHO meta.
92
+ // TODO(dmaretskyi): Make required.
93
+ key: Schema2.optional(Schema2.String).annotations({
94
+ description: "Unique registration key for the blueprint"
95
+ }),
56
96
  name: Schema2.NonEmptyString,
57
97
  version: Schema2.String,
58
98
  description: Schema2.optional(Schema2.String),
99
+ /**
100
+ * ISO date string of the last deployment.
101
+ */
102
+ updated: Schema2.optional(Schema2.String),
59
103
  // Reference to a source script if it exists within ECHO.
60
104
  // TODO(burdon): Don't ref ScriptType directly (core).
61
- source: Schema2.optional(Ref(ScriptType)),
62
- inputSchema: Schema2.optional(JsonSchemaType),
63
- outputSchema: Schema2.optional(JsonSchemaType),
105
+ source: Schema2.optional(Type2.Ref(Script)),
106
+ inputSchema: Schema2.optional(JsonSchema.JsonSchema),
107
+ outputSchema: Schema2.optional(JsonSchema.JsonSchema),
108
+ /**
109
+ * List of required services.
110
+ * Match the Context.Tag keys of the FunctionServices variants.
111
+ */
112
+ services: Schema2.optional(Schema2.Array(Schema2.String)),
64
113
  // Local binding to a function name.
65
114
  binding: Schema2.optional(Schema2.String)
66
- }).pipe(Type.Obj({
115
+ }).pipe(Type2.Obj({
67
116
  typename: "dxos.org/type/Function",
68
117
  version: "0.1.0"
69
- }), LabelAnnotation.set([
118
+ }), Annotation2.LabelAnnotation.set([
70
119
  "name"
71
- ]));
72
-
73
- // src/trace.ts
74
- import { Schema as Schema4 } from "effect";
75
- import { Type as Type2 } from "@dxos/echo";
76
- import { Queue } from "@dxos/echo-db";
77
- import { ObjectId } from "@dxos/echo-schema";
78
- import { log } from "@dxos/log";
120
+ ]), SystemTypeAnnotation.set(true));
121
+ var make2 = (props) => Obj2.make(Function, props);
122
+ var setFrom = (target, source) => {
123
+ target.key = source.key ?? target.key;
124
+ target.name = source.name ?? target.name;
125
+ target.version = source.version;
126
+ target.description = source.description;
127
+ target.updated = source.updated;
128
+ target.inputSchema = source.inputSchema ? JSON.parse(JSON.stringify(source.inputSchema)) : void 0;
129
+ target.outputSchema = source.outputSchema ? JSON.parse(JSON.stringify(source.outputSchema)) : void 0;
130
+ Obj2.getMeta(target).keys = JSON.parse(JSON.stringify(Obj2.getMeta(source).keys));
131
+ };
79
132
 
80
- // src/types.ts
81
- import { Schema as Schema3, SchemaAST } from "effect";
82
- import { Expando, OptionsAnnotationId, TypedObject, Ref as Ref2, RawObject } from "@dxos/echo-schema";
133
+ // src/types/Trigger.ts
134
+ var Trigger_exports = {};
135
+ __export(Trigger_exports, {
136
+ EmailSpec: () => EmailSpec,
137
+ Kinds: () => Kinds,
138
+ QueueSpec: () => QueueSpec,
139
+ Spec: () => Spec,
140
+ SubscriptionSpec: () => SubscriptionSpec,
141
+ TimerSpec: () => TimerSpec,
142
+ Trigger: () => Trigger,
143
+ WebhookSpec: () => WebhookSpec,
144
+ make: () => make3
145
+ });
146
+ import * as Schema3 from "effect/Schema";
147
+ import * as SchemaAST from "effect/SchemaAST";
148
+ import { Obj as Obj3, QueryAST, Type as Type3 } from "@dxos/echo";
149
+ import { OptionsAnnotationId, SystemTypeAnnotation as SystemTypeAnnotation2 } from "@dxos/echo/internal";
83
150
  import { DXN } from "@dxos/keys";
84
- var TriggerKind = /* @__PURE__ */ function(TriggerKind2) {
85
- TriggerKind2["Timer"] = "timer";
86
- TriggerKind2["Webhook"] = "webhook";
87
- TriggerKind2["Subscription"] = "subscription";
88
- TriggerKind2["Email"] = "email";
89
- TriggerKind2["Queue"] = "queue";
90
- return TriggerKind2;
91
- }({});
151
+ var Kinds = [
152
+ "email",
153
+ "queue",
154
+ "subscription",
155
+ "timer",
156
+ "webhook"
157
+ ];
92
158
  var kindLiteralAnnotations = {
93
159
  title: "Kind"
94
160
  };
95
- var TimerTriggerSchema = Schema3.Struct({
161
+ var EmailSpec = Schema3.Struct({
162
+ kind: Schema3.Literal("email").annotations(kindLiteralAnnotations)
163
+ }).pipe(Schema3.mutable);
164
+ var QueueSpec = Schema3.Struct({
165
+ kind: Schema3.Literal("queue").annotations(kindLiteralAnnotations),
166
+ // TODO(dmaretskyi): Change to a reference.
167
+ queue: DXN.Schema
168
+ }).pipe(Schema3.mutable);
169
+ var SubscriptionSpec = Schema3.Struct({
170
+ kind: Schema3.Literal("subscription").annotations(kindLiteralAnnotations),
171
+ query: Schema3.Struct({
172
+ raw: Schema3.optional(Schema3.String.annotations({
173
+ title: "Query"
174
+ })),
175
+ ast: QueryAST.Query
176
+ }).pipe(Schema3.mutable),
177
+ options: Schema3.optional(Schema3.Struct({
178
+ // Watch changes to object (not just creation).
179
+ deep: Schema3.optional(Schema3.Boolean.annotations({
180
+ title: "Nested"
181
+ })),
182
+ // Debounce changes (delay in ms).
183
+ delay: Schema3.optional(Schema3.Number.annotations({
184
+ title: "Delay"
185
+ }))
186
+ }).annotations({
187
+ title: "Options"
188
+ }))
189
+ }).pipe(Schema3.mutable);
190
+ var TimerSpec = Schema3.Struct({
96
191
  kind: Schema3.Literal("timer").annotations(kindLiteralAnnotations),
97
192
  cron: Schema3.String.annotations({
98
193
  title: "Cron",
@@ -101,14 +196,7 @@ var TimerTriggerSchema = Schema3.Struct({
101
196
  ]
102
197
  })
103
198
  }).pipe(Schema3.mutable);
104
- var EmailTriggerSchema = Schema3.Struct({
105
- kind: Schema3.Literal("email").annotations(kindLiteralAnnotations)
106
- }).pipe(Schema3.mutable);
107
- var QueueTriggerSchema = Schema3.Struct({
108
- kind: Schema3.Literal("queue").annotations(kindLiteralAnnotations),
109
- queue: DXN.Schema
110
- }).pipe(Schema3.mutable);
111
- var WebhookTriggerSchema = Schema3.Struct({
199
+ var WebhookSpec = Schema3.Struct({
112
200
  kind: Schema3.Literal("webhook").annotations(kindLiteralAnnotations),
113
201
  method: Schema3.optional(Schema3.String.annotations({
114
202
  title: "Method",
@@ -121,71 +209,15 @@ var WebhookTriggerSchema = Schema3.Struct({
121
209
  title: "Port"
122
210
  }))
123
211
  }).pipe(Schema3.mutable);
124
- var QuerySchema = Schema3.Struct({
125
- type: Schema3.optional(Schema3.String.annotations({
126
- title: "Type"
127
- })),
128
- props: Schema3.optional(Schema3.Record({
129
- key: Schema3.String,
130
- value: Schema3.Any
131
- }))
132
- }).annotations({
133
- title: "Query"
134
- });
135
- var SubscriptionTriggerSchema = Schema3.Struct({
136
- kind: Schema3.Literal("subscription").annotations(kindLiteralAnnotations),
137
- // TODO(burdon): Define query DSL (from ECHO). Reconcile with Table.Query.
138
- filter: QuerySchema,
139
- options: Schema3.optional(Schema3.Struct({
140
- // Watch changes to object (not just creation).
141
- deep: Schema3.optional(Schema3.Boolean.annotations({
142
- title: "Nested"
143
- })),
144
- // Debounce changes (delay in ms).
145
- delay: Schema3.optional(Schema3.Number.annotations({
146
- title: "Delay"
147
- }))
148
- }).annotations({
149
- title: "Options"
150
- }))
151
- }).pipe(Schema3.mutable);
152
- var TriggerSchema = Schema3.Union(TimerTriggerSchema, WebhookTriggerSchema, SubscriptionTriggerSchema, EmailTriggerSchema, QueueTriggerSchema).annotations({
212
+ var Spec = Schema3.Union(EmailSpec, QueueSpec, SubscriptionSpec, TimerSpec, WebhookSpec).annotations({
153
213
  title: "Trigger"
154
214
  });
155
- var EmailTriggerOutput = Schema3.mutable(Schema3.Struct({
156
- from: Schema3.String,
157
- to: Schema3.String,
158
- subject: Schema3.String,
159
- created: Schema3.String,
160
- body: Schema3.String
161
- }));
162
- var WebhookTriggerOutput = Schema3.mutable(Schema3.Struct({
163
- url: Schema3.String,
164
- method: Schema3.Literal("GET", "POST"),
165
- headers: Schema3.Record({
166
- key: Schema3.String,
167
- value: Schema3.String
168
- }),
169
- bodyText: Schema3.String
170
- }));
171
- var QueueTriggerOutput = Schema3.mutable(Schema3.Struct({
172
- queue: DXN.Schema,
173
- item: Schema3.Any,
174
- cursor: Schema3.String
175
- }));
176
- var SubscriptionTriggerOutput = Schema3.mutable(Schema3.Struct({
177
- type: Schema3.String,
178
- changedObjectId: Schema3.String
179
- }));
180
- var TimerTriggerOutput = Schema3.mutable(Schema3.Struct({
181
- tick: Schema3.Number
182
- }));
183
- var FunctionTriggerSchema = Schema3.Struct({
215
+ var Trigger_ = Schema3.Struct({
184
216
  /**
185
217
  * Function or workflow to invoke.
186
218
  */
187
219
  // TODO(dmaretskyi): Can be a Ref(FunctionType) or Ref(ComputeGraphType).
188
- function: Schema3.optional(Ref2(Expando).annotations({
220
+ function: Schema3.optional(Type3.Ref(Type3.Expando).annotations({
189
221
  title: "Function"
190
222
  })),
191
223
  /**
@@ -199,7 +231,7 @@ var FunctionTriggerSchema = Schema3.Struct({
199
231
  enabled: Schema3.optional(Schema3.Boolean.annotations({
200
232
  title: "Enabled"
201
233
  })),
202
- spec: Schema3.optional(TriggerSchema),
234
+ spec: Schema3.optional(Spec),
203
235
  /**
204
236
  * Passed as the input data to the function.
205
237
  * Must match the function's input schema.
@@ -215,290 +247,790 @@ var FunctionTriggerSchema = Schema3.Struct({
215
247
  key: Schema3.String,
216
248
  value: Schema3.Any
217
249
  })))
218
- });
219
- var FunctionTrigger = class extends TypedObject({
220
- typename: "dxos.org/type/FunctionTrigger",
221
- version: "0.2.0"
222
- })(FunctionTriggerSchema.fields) {
223
- };
224
- var FunctionManifestSchema = Schema3.Struct({
225
- functions: Schema3.optional(Schema3.mutable(Schema3.Array(RawObject(FunctionType)))),
226
- triggers: Schema3.optional(Schema3.mutable(Schema3.Array(RawObject(FunctionTrigger))))
227
- });
228
- var FUNCTION_TYPES = [
229
- FunctionType,
230
- FunctionTrigger
231
- ];
250
+ }).pipe(Type3.Obj({
251
+ typename: "dxos.org/type/Trigger",
252
+ version: "0.1.0"
253
+ }), SystemTypeAnnotation2.set(true));
254
+ var Trigger = Trigger_;
255
+ var make3 = (props) => Obj3.make(Trigger, props);
232
256
 
233
- // src/trace.ts
234
- var __dxlog_file = "/__w/dxos/dxos/packages/core/functions/src/trace.ts";
235
- var InvocationOutcome = /* @__PURE__ */ function(InvocationOutcome2) {
236
- InvocationOutcome2["SUCCESS"] = "success";
237
- InvocationOutcome2["FAILURE"] = "failure";
238
- InvocationOutcome2["PENDING"] = "pending";
239
- return InvocationOutcome2;
240
- }({});
241
- var InvocationTraceEventType = /* @__PURE__ */ function(InvocationTraceEventType2) {
242
- InvocationTraceEventType2["START"] = "start";
243
- InvocationTraceEventType2["END"] = "end";
244
- return InvocationTraceEventType2;
245
- }({});
246
- var TraceEventException = Schema4.Struct({
247
- timestampMs: Schema4.Number,
248
- message: Schema4.String,
249
- name: Schema4.String,
250
- stack: Schema4.optional(Schema4.String)
257
+ // src/types/TriggerEvent.ts
258
+ var TriggerEvent_exports = {};
259
+ __export(TriggerEvent_exports, {
260
+ EmailEvent: () => EmailEvent,
261
+ QueueEvent: () => QueueEvent,
262
+ SubscriptionEvent: () => SubscriptionEvent,
263
+ TimerEvent: () => TimerEvent,
264
+ WebhookEvent: () => WebhookEvent
251
265
  });
252
- var InvocationTraceStartEvent = Schema4.Struct({
253
- /**
254
- * Queue message id.
255
- */
256
- id: ObjectId,
257
- type: Schema4.Literal("start"),
258
- /**
259
- * Invocation id, the same for invocation start and end events.
260
- */
261
- invocationId: ObjectId,
262
- /**
263
- * Event generation time.
264
- */
265
- timestampMs: Schema4.Number,
266
- /**
267
- * Data passed to function / workflow as an argument.
268
- */
269
- // TODO(burdon): Input schema?
270
- input: Schema4.Object,
271
- /**
272
- * Queue for function/workflow invocation events.
273
- */
274
- invocationTraceQueue: Type2.Ref(Queue),
275
- /**
276
- * DXN of the invoked function/workflow.
277
- */
278
- invocationTarget: Type2.Ref(Type2.Expando),
279
- /**
280
- * Present for automatic invocations.
281
- */
282
- trigger: Schema4.optional(Type2.Ref(FunctionTrigger))
283
- }).pipe(Type2.Obj({
284
- typename: "dxos.org/type/InvocationTraceStart",
285
- version: "0.1.0"
266
+ import * as Schema4 from "effect/Schema";
267
+ import { DXN as DXN2, Obj as Obj4, Type as Type4 } from "@dxos/echo";
268
+ var EmailEvent = Schema4.mutable(Schema4.Struct({
269
+ from: Schema4.String,
270
+ to: Schema4.String,
271
+ subject: Schema4.String,
272
+ created: Schema4.String,
273
+ body: Schema4.String
274
+ }));
275
+ var QueueEvent = Schema4.mutable(Schema4.Struct({
276
+ queue: DXN2.Schema,
277
+ item: Schema4.Any,
278
+ cursor: Schema4.String
286
279
  }));
287
- var InvocationTraceEndEvent = Schema4.Struct({
280
+ var SubscriptionEvent = Schema4.Struct({
288
281
  /**
289
- * Trace event id.
282
+ * Type of the mutation.
290
283
  */
291
- id: ObjectId,
292
- type: Schema4.Literal("end"),
284
+ // TODO(dmaretskyi): Specify enum.
285
+ type: Schema4.String,
293
286
  /**
294
- * Invocation id, will be the same for invocation start and end.
287
+ * Reference to the object that was changed or created.
295
288
  */
296
- invocationId: ObjectId,
289
+ subject: Type4.Ref(Obj4.Any),
297
290
  /**
298
- * Event generation time.
291
+ * @deprecated
299
292
  */
300
- // TODO(burdon): Remove ms suffix.
301
- timestampMs: Schema4.Number,
302
- outcome: Schema4.Enums(InvocationOutcome),
303
- exception: Schema4.optional(TraceEventException)
304
- }).pipe(Type2.Obj({
305
- typename: "dxos.org/type/InvocationTraceEnd",
306
- version: "0.1.0"
293
+ changedObjectId: Schema4.optional(Schema4.String)
294
+ }).pipe(Schema4.mutable);
295
+ var TimerEvent = Schema4.mutable(Schema4.Struct({
296
+ tick: Schema4.Number
307
297
  }));
308
- var TraceEventLog = Schema4.Struct({
309
- timestampMs: Schema4.Number,
310
- level: Schema4.String,
311
- message: Schema4.String,
312
- context: Schema4.optional(Schema4.Object)
313
- });
314
- var TraceEvent = Schema4.Struct({
315
- id: ObjectId,
316
- // TODO(burdon): Need enum/numeric result (not string).
317
- outcome: Schema4.String,
318
- truncated: Schema4.Boolean,
319
- /**
320
- * Time when the event was persisted.
321
- */
322
- ingestionTimestampMs: Schema4.Number,
323
- logs: Schema4.Array(TraceEventLog),
324
- exceptions: Schema4.Array(TraceEventException)
325
- }).pipe(Type2.Obj({
326
- typename: "dxos.org/type/TraceEvent",
327
- version: "0.1.0"
298
+ var WebhookEvent = Schema4.mutable(Schema4.Struct({
299
+ url: Schema4.String,
300
+ method: Schema4.Literal("GET", "POST"),
301
+ headers: Schema4.Record({
302
+ key: Schema4.String,
303
+ value: Schema4.String
304
+ }),
305
+ bodyText: Schema4.String
328
306
  }));
329
- var createInvocationSpans = (items) => {
330
- if (!items) {
331
- return [];
332
- }
333
- const eventsByInvocationId = /* @__PURE__ */ new Map();
334
- for (const event of items) {
335
- if (!("invocationId" in event)) {
336
- continue;
337
- }
338
- const invocationId = event.invocationId;
339
- const entry = eventsByInvocationId.get(invocationId) || {
340
- start: void 0,
341
- end: void 0
342
- };
343
- if (event.type === "start") {
344
- entry.start = event;
345
- } else if (event.type === "end") {
346
- entry.end = event;
347
- }
348
- eventsByInvocationId.set(invocationId, entry);
349
- }
350
- const now = Date.now();
351
- const result = [];
352
- for (const [invocationId, { start, end }] of eventsByInvocationId.entries()) {
353
- if (!start) {
354
- log.warn("found end event without matching start", {
355
- invocationId
356
- }, {
357
- F: __dxlog_file,
358
- L: 160,
359
- S: void 0,
360
- C: (f, a) => f(...a)
361
- });
362
- continue;
363
- }
364
- const isInProgress = end === void 0;
365
- result.push({
366
- id: invocationId,
367
- timestampMs: start.timestampMs,
368
- durationMs: isInProgress ? now - start.timestampMs : end.timestampMs - start.timestampMs,
369
- outcome: end?.outcome ?? "pending",
370
- exception: end?.exception,
371
- input: start.input,
372
- invocationTraceQueue: start.invocationTraceQueue,
373
- invocationTarget: start.invocationTarget,
374
- trigger: start.trigger
375
- });
376
- }
377
- return result;
378
- };
379
307
 
380
- // src/url.ts
308
+ // src/types/url.ts
381
309
  var FUNCTIONS_META_KEY = "dxos.org/service/function";
382
310
  var FUNCTIONS_PRESET_META_KEY = "dxos.org/service/function-preset";
383
- var isSecure = (protocol) => {
384
- return protocol === "https:" || protocol === "wss:";
385
- };
386
- var getUserFunctionUrlInMetadata = (meta) => {
311
+ var getUserFunctionIdInMetadata = (meta) => {
387
312
  return meta.keys.find((key) => key.source === FUNCTIONS_META_KEY)?.id;
388
313
  };
389
- var setUserFunctionUrlInMetadata = (meta, functionUrl) => {
314
+ var setUserFunctionIdInMetadata = (meta, functionId) => {
390
315
  const key = meta.keys.find((key2) => key2.source === FUNCTIONS_META_KEY);
391
316
  if (key) {
392
- if (key.id !== functionUrl) {
317
+ if (key.id !== functionId) {
393
318
  throw new Error("Metadata mismatch");
394
319
  }
395
320
  } else {
396
321
  meta.keys.push({
397
322
  source: FUNCTIONS_META_KEY,
398
- id: functionUrl
323
+ id: functionId
399
324
  });
400
325
  }
401
326
  };
402
- var makeFunctionUrl = (fn) => `/${fn.functionId}`;
403
- var getInvocationUrl = (functionUrl, edgeUrl, options = {}) => {
404
- const baseUrl = new URL("functions/", edgeUrl);
405
- const relativeUrl = functionUrl.replace(/^\//, "");
406
- const url = new URL(`./${relativeUrl}`, baseUrl.toString());
407
- options.spaceId && url.searchParams.set("spaceId", options.spaceId);
408
- options.subjectId && url.searchParams.set("subjectId", options.subjectId);
409
- url.protocol = isSecure(url.protocol) ? "https" : "http";
410
- return url.toString();
411
- };
412
327
 
413
- // src/executor/executor.ts
414
- import { Effect, Schema as Schema5 } from "effect";
415
- import { runAndForwardErrors } from "@dxos/effect";
416
- var FunctionExecutor = class {
417
- constructor(_services) {
418
- this._services = _services;
328
+ // src/sdk.ts
329
+ var typeId = Symbol.for("@dxos/functions/FunctionDefinition");
330
+ var defineFunction = ({ key, name, description, inputSchema, outputSchema = Schema5.Any, handler, types, services }) => {
331
+ if (!Schema5.isSchema(inputSchema)) {
332
+ throw new Error("Input schema must be a valid schema");
419
333
  }
420
- // TODO(dmaretskyi): Invocation context: queue, space, etc...
421
- async invoke(fnDef, input) {
422
- const assertInput = fnDef.inputSchema.pipe(Schema5.asserts);
423
- assertInput(input);
424
- const context = {
425
- getService: this._services.getService.bind(this._services),
426
- getSpace: async (_spaceId) => {
427
- throw new Error("Not available. Use the database service instead.");
428
- },
429
- space: void 0,
430
- get ai() {
431
- throw new Error("Not available. Use the ai service instead.");
334
+ if (typeof handler !== "function") {
335
+ throw new Error("Handler must be a function");
336
+ }
337
+ const limit = Error.stackTraceLimit;
338
+ Error.stackTraceLimit = 2;
339
+ const traceError = new Error();
340
+ Error.stackTraceLimit = limit;
341
+ let cache = false;
342
+ const captureStackTrace = () => {
343
+ if (cache !== false) {
344
+ return cache;
345
+ }
346
+ if (traceError.stack !== void 0) {
347
+ const stack = traceError.stack.split("\n");
348
+ if (stack[2] !== void 0) {
349
+ cache = stack[2].trim();
350
+ return cache;
432
351
  }
433
- };
434
- const result = fnDef.handler({
435
- context,
436
- data: input
437
- });
438
- let data;
352
+ }
353
+ };
354
+ const handlerWithSpan = (...args) => {
355
+ const result = handler(...args);
439
356
  if (Effect.isEffect(result)) {
440
- data = await result.pipe(Effect.provide(this._services.createLayer()), runAndForwardErrors);
441
- } else {
442
- data = await result;
357
+ return Effect.withSpan(result, `${key ?? name}`, {
358
+ captureStackTrace
359
+ });
360
+ }
361
+ return result;
362
+ };
363
+ return {
364
+ [typeId]: true,
365
+ key,
366
+ name,
367
+ description,
368
+ inputSchema,
369
+ outputSchema,
370
+ handler: handlerWithSpan,
371
+ types: types ?? [],
372
+ services: !services ? [] : getServiceKeys(services)
373
+ };
374
+ };
375
+ var getServiceKeys = (services) => {
376
+ return services.map((tag) => {
377
+ if (typeof tag.key === "string") {
378
+ return tag.key;
379
+ }
380
+ console.log(tag);
381
+ failedInvariant();
382
+ });
383
+ };
384
+ var FunctionDefinition = {
385
+ make: defineFunction,
386
+ isFunction: (value2) => {
387
+ return typeof value2 === "object" && value2 !== null && Symbol.for("@dxos/functions/FunctionDefinition") in value2;
388
+ },
389
+ serialize: (functionDef) => {
390
+ assertArgument(FunctionDefinition.isFunction(functionDef), "functionDef");
391
+ return serializeFunction(functionDef);
392
+ },
393
+ deserialize: (functionObj) => {
394
+ assertArgument(Obj5.instanceOf(Function_exports.Function, functionObj), "functionObj");
395
+ return deserializeFunction(functionObj);
396
+ }
397
+ };
398
+ var serializeFunction = (functionDef) => {
399
+ const fn4 = Function_exports.make({
400
+ key: functionDef.key,
401
+ name: functionDef.name,
402
+ version: "0.1.0",
403
+ description: functionDef.description,
404
+ inputSchema: Type5.toJsonSchema(functionDef.inputSchema),
405
+ outputSchema: !functionDef.outputSchema ? void 0 : Type5.toJsonSchema(functionDef.outputSchema),
406
+ services: functionDef.services
407
+ });
408
+ if (functionDef.meta?.deployedFunctionId) {
409
+ setUserFunctionIdInMetadata(Obj5.getMeta(fn4), functionDef.meta.deployedFunctionId);
410
+ }
411
+ return fn4;
412
+ };
413
+ var deserializeFunction = (functionObj) => {
414
+ return {
415
+ [typeId]: true,
416
+ // TODO(dmaretskyi): Fix key.
417
+ key: functionObj.key ?? functionObj.name,
418
+ name: functionObj.name,
419
+ description: functionObj.description,
420
+ inputSchema: !functionObj.inputSchema ? Schema5.Unknown : Type5.toEffectSchema(functionObj.inputSchema),
421
+ outputSchema: !functionObj.outputSchema ? void 0 : Type5.toEffectSchema(functionObj.outputSchema),
422
+ // TODO(dmaretskyi): This should throw error.
423
+ handler: () => {
424
+ },
425
+ services: functionObj.services ?? [],
426
+ types: [],
427
+ meta: {
428
+ deployedFunctionId: getUserFunctionIdInMetadata(Obj5.getMeta(functionObj))
443
429
  }
444
- const assertOutput = fnDef.outputSchema?.pipe(Schema5.asserts);
445
- assertOutput(data);
430
+ };
431
+ };
432
+
433
+ // src/example/fib.ts
434
+ var fib_default = defineFunction({
435
+ key: "example.org/function/fib",
436
+ name: "Fibonacci",
437
+ description: "Function that calculates a Fibonacci number",
438
+ inputSchema: Schema6.Struct({
439
+ iterations: Schema6.optional(Schema6.Number).annotations({
440
+ description: "Number of iterations",
441
+ default: 1e5
442
+ })
443
+ }),
444
+ outputSchema: Schema6.Struct({
445
+ result: Schema6.String
446
+ }),
447
+ handler: Effect2.fn(function* ({ data: { iterations = 1e5 } }) {
448
+ let a = 0n;
449
+ let b = 1n;
450
+ for (let i = 0; i < iterations; i++) {
451
+ a += b;
452
+ b = a - b;
453
+ }
454
+ return {
455
+ result: a.toString()
456
+ };
457
+ })
458
+ });
459
+
460
+ // src/example/reply.ts
461
+ import * as Console from "effect/Console";
462
+ import * as Effect3 from "effect/Effect";
463
+ import * as Schema7 from "effect/Schema";
464
+ var reply_default = defineFunction({
465
+ key: "example.org/function/reply",
466
+ name: "Reply",
467
+ description: "Function that echoes the input",
468
+ inputSchema: Schema7.Any,
469
+ outputSchema: Schema7.Any,
470
+ handler: Effect3.fn(function* ({ data }) {
471
+ yield* Console.log("reply", {
472
+ data
473
+ });
446
474
  return data;
475
+ })
476
+ });
477
+
478
+ // src/example/sleep.ts
479
+ import * as Effect4 from "effect/Effect";
480
+ import * as Schema8 from "effect/Schema";
481
+ var sleep_default = defineFunction({
482
+ key: "example.org/function/sleep",
483
+ name: "Sleep",
484
+ description: "Function that sleeps for a given amount of time",
485
+ inputSchema: Schema8.Struct({
486
+ duration: Schema8.optional(Schema8.Number).annotations({
487
+ description: "Milliseconds to sleep",
488
+ default: 1e5
489
+ })
490
+ }),
491
+ outputSchema: Schema8.Void,
492
+ handler: Effect4.fn(function* ({ data: { duration = 1e5 } }) {
493
+ yield* Effect4.sleep(duration);
494
+ })
495
+ });
496
+
497
+ // src/example/index.ts
498
+ (function(Example2) {
499
+ Example2.fib = fib_default;
500
+ Example2.reply = reply_default;
501
+ Example2.sleep = sleep_default;
502
+ })(Example || (Example = {}));
503
+ var Example;
504
+
505
+ // src/services/credentials.ts
506
+ import * as HttpClient from "@effect/platform/HttpClient";
507
+ import * as HttpClientRequest from "@effect/platform/HttpClientRequest";
508
+ import * as Context from "effect/Context";
509
+ import * as Effect5 from "effect/Effect";
510
+ import * as Layer from "effect/Layer";
511
+ import * as Redacted from "effect/Redacted";
512
+ import { Query } from "@dxos/echo";
513
+ import { Database } from "@dxos/echo";
514
+ import { AccessToken } from "@dxos/types";
515
+ var CredentialsService = class _CredentialsService extends Context.Tag("@dxos/functions/CredentialsService")() {
516
+ static getCredential = (query) => Effect5.gen(function* () {
517
+ const credentials = yield* _CredentialsService;
518
+ return yield* Effect5.promise(() => credentials.getCredential(query));
519
+ });
520
+ static getApiKey = (query) => Effect5.gen(function* () {
521
+ const credential = yield* _CredentialsService.getCredential(query);
522
+ if (!credential.apiKey) {
523
+ throw new Error(`API key not found for service: ${query.service}`);
524
+ }
525
+ return Redacted.make(credential.apiKey);
526
+ });
527
+ static configuredLayer = (credentials) => Layer.succeed(_CredentialsService, new ConfiguredCredentialsService(credentials));
528
+ static layerConfig = (credentials) => Layer.effect(_CredentialsService, Effect5.gen(function* () {
529
+ const serviceCredentials = yield* Effect5.forEach(credentials, ({ service, apiKey }) => Effect5.gen(function* () {
530
+ return {
531
+ service,
532
+ apiKey: Redacted.value(yield* apiKey)
533
+ };
534
+ }));
535
+ return new ConfiguredCredentialsService(serviceCredentials);
536
+ }));
537
+ static layerFromDatabase = () => Layer.effect(_CredentialsService, Effect5.gen(function* () {
538
+ const dbService = yield* Database.Service;
539
+ const cache = /* @__PURE__ */ new Map();
540
+ const queryCredentials = async (query) => {
541
+ const cacheKey = JSON.stringify(query);
542
+ if (cache.has(cacheKey)) {
543
+ return cache.get(cacheKey);
544
+ }
545
+ const accessTokens = await dbService.db.query(Query.type(AccessToken.AccessToken)).run();
546
+ const credentials = accessTokens.filter((accessToken) => accessToken.source === query.service).map((accessToken) => ({
547
+ service: accessToken.source,
548
+ apiKey: accessToken.token
549
+ }));
550
+ cache.set(cacheKey, credentials);
551
+ return credentials;
552
+ };
553
+ return {
554
+ getCredential: async (query) => {
555
+ const credentials = await queryCredentials(query);
556
+ if (credentials.length === 0) {
557
+ throw new Error(`Credential not found for service: ${query.service}`);
558
+ }
559
+ return credentials[0];
560
+ },
561
+ queryCredentials: async (query) => {
562
+ return queryCredentials(query);
563
+ }
564
+ };
565
+ }));
566
+ };
567
+ var ConfiguredCredentialsService = class {
568
+ credentials;
569
+ constructor(credentials = []) {
570
+ this.credentials = credentials;
571
+ }
572
+ addCredentials(credentials) {
573
+ this.credentials.push(...credentials);
574
+ return this;
575
+ }
576
+ async queryCredentials(query) {
577
+ return this.credentials.filter((credential) => credential.service === query.service);
578
+ }
579
+ async getCredential(query) {
580
+ const credential = this.credentials.find((credential2) => credential2.service === query.service);
581
+ if (!credential) {
582
+ throw new Error(`Credential not found for service: ${query.service}`);
583
+ }
584
+ return credential;
447
585
  }
448
586
  };
587
+ var withAuthorization = (query, kind) => HttpClient.mapRequestEffect(Effect5.fnUntraced(function* (request) {
588
+ const key = yield* CredentialsService.getApiKey(query).pipe(Effect5.map(Redacted.value));
589
+ const authorization = kind ? `${kind} ${key}` : key;
590
+ return HttpClientRequest.setHeader(request, "Authorization", authorization);
591
+ }));
449
592
 
450
- // src/errors.ts
451
- import { BaseError } from "@dxos/errors";
452
- var ServiceNotAvailableError = class extends BaseError.extend("SERVICE_NOT_AVAILABLE") {
453
- constructor(serviceName) {
454
- super(`Service not available: ${serviceName}`);
593
+ // src/services/event-logger.ts
594
+ import * as Context3 from "effect/Context";
595
+ import * as Effect7 from "effect/Effect";
596
+ import * as Layer3 from "effect/Layer";
597
+ import * as Schema9 from "effect/Schema";
598
+ import { Obj as Obj7, Type as Type6 } from "@dxos/echo";
599
+ import { invariant } from "@dxos/invariant";
600
+ import { LogLevel, log as log2 } from "@dxos/log";
601
+
602
+ // src/services/tracing.ts
603
+ import * as Context2 from "effect/Context";
604
+ import * as Effect6 from "effect/Effect";
605
+ import * as Layer2 from "effect/Layer";
606
+ import { AgentStatus } from "@dxos/ai";
607
+ import { Obj as Obj6 } from "@dxos/echo";
608
+ import { Message } from "@dxos/types";
609
+ var TracingService = class _TracingService extends Context2.Tag("@dxos/functions/TracingService")() {
610
+ static noop = {
611
+ getTraceContext: () => ({}),
612
+ write: () => {
613
+ }
614
+ };
615
+ static layerNoop = Layer2.succeed(_TracingService, _TracingService.noop);
616
+ /**
617
+ * Creates a TracingService layer that emits events to the parent tracing service.
618
+ */
619
+ static layerSubframe = (mapContext) => Layer2.effect(_TracingService, Effect6.gen(function* () {
620
+ const tracing = yield* _TracingService;
621
+ const context = mapContext(tracing.getTraceContext());
622
+ return {
623
+ write: (event) => tracing.write(event),
624
+ getTraceContext: () => context
625
+ };
626
+ }));
627
+ /**
628
+ * Emit the current human-readable execution status.
629
+ */
630
+ static emitStatus = Effect6.fnUntraced(function* (data) {
631
+ const tracing = yield* _TracingService;
632
+ tracing.write(Obj6.make(AgentStatus, {
633
+ parentMessage: tracing.getTraceContext().parentMessage,
634
+ toolCallId: tracing.getTraceContext().toolCallId,
635
+ created: (/* @__PURE__ */ new Date()).toISOString(),
636
+ ...data
637
+ }));
638
+ });
639
+ static emitConverationMessage = Effect6.fnUntraced(function* (data) {
640
+ const tracing = yield* _TracingService;
641
+ tracing.write(Obj6.make(Message.Message, {
642
+ parentMessage: tracing.getTraceContext().parentMessage,
643
+ ...data,
644
+ properties: {
645
+ [MESSAGE_PROPERTY_TOOL_CALL_ID]: tracing.getTraceContext().toolCallId,
646
+ ...data.properties
647
+ }
648
+ }));
649
+ });
650
+ };
651
+ var MESSAGE_PROPERTY_TOOL_CALL_ID = "toolCallId";
652
+
653
+ // src/services/event-logger.ts
654
+ var __dxlog_file = "/__w/dxos/dxos/packages/core/functions/src/services/event-logger.ts";
655
+ var ComputeEventPayload = Schema9.Union(Schema9.Struct({
656
+ type: Schema9.Literal("begin-compute"),
657
+ nodeId: Schema9.String,
658
+ /**
659
+ * Names of the inputs begin computed.
660
+ */
661
+ inputs: Schema9.Array(Schema9.String)
662
+ }), Schema9.Struct({
663
+ type: Schema9.Literal("end-compute"),
664
+ nodeId: Schema9.String,
665
+ /**
666
+ * Names of the outputs computed.
667
+ */
668
+ outputs: Schema9.Array(Schema9.String)
669
+ }), Schema9.Struct({
670
+ type: Schema9.Literal("compute-input"),
671
+ nodeId: Schema9.String,
672
+ property: Schema9.String,
673
+ value: Schema9.Any
674
+ }), Schema9.Struct({
675
+ type: Schema9.Literal("compute-output"),
676
+ nodeId: Schema9.String,
677
+ property: Schema9.String,
678
+ value: Schema9.Any
679
+ }), Schema9.Struct({
680
+ type: Schema9.Literal("custom"),
681
+ nodeId: Schema9.String,
682
+ event: Schema9.Any
683
+ }));
684
+ var ComputeEvent = Schema9.Struct({
685
+ payload: ComputeEventPayload
686
+ }).pipe(Type6.Obj({
687
+ typename: "dxos.org/type/ComputeEvent",
688
+ version: "0.1.0"
689
+ }));
690
+ var ComputeEventLogger = class _ComputeEventLogger extends Context3.Tag("@dxos/functions/ComputeEventLogger")() {
691
+ static noop = {
692
+ log: () => {
693
+ },
694
+ nodeId: void 0
695
+ };
696
+ /**
697
+ * Implements ComputeEventLogger using TracingService.
698
+ */
699
+ static layerFromTracing = Layer3.effect(_ComputeEventLogger, Effect7.gen(function* () {
700
+ const tracing = yield* TracingService;
701
+ return {
702
+ log: (event) => {
703
+ tracing.write(Obj7.make(ComputeEvent, {
704
+ payload: event
705
+ }));
706
+ },
707
+ nodeId: void 0
708
+ };
709
+ }));
710
+ };
711
+ var logCustomEvent = (data) => Effect7.gen(function* () {
712
+ const logger = yield* ComputeEventLogger;
713
+ if (!logger.nodeId) {
714
+ throw new Error("logCustomEvent must be called within a node compute function");
455
715
  }
716
+ logger.log({
717
+ type: "custom",
718
+ nodeId: logger.nodeId,
719
+ event: data
720
+ });
721
+ });
722
+ var createDefectLogger = () => Effect7.catchAll((error) => Effect7.gen(function* () {
723
+ log2.error("unhandled effect error", {
724
+ error
725
+ }, {
726
+ F: __dxlog_file,
727
+ L: 102,
728
+ S: this,
729
+ C: (f, a) => f(...a)
730
+ });
731
+ throw error;
732
+ }));
733
+ var createEventLogger = (level, message = "event") => {
734
+ const logFunction = {
735
+ [LogLevel.WARN]: log2.warn,
736
+ [LogLevel.VERBOSE]: log2.verbose,
737
+ [LogLevel.DEBUG]: log2.debug,
738
+ [LogLevel.INFO]: log2.info,
739
+ [LogLevel.ERROR]: log2.error
740
+ }[level];
741
+ invariant(logFunction, void 0, {
742
+ F: __dxlog_file,
743
+ L: 120,
744
+ S: void 0,
745
+ A: [
746
+ "logFunction",
747
+ ""
748
+ ]
749
+ });
750
+ return {
751
+ log: (event) => {
752
+ logFunction(message, event);
753
+ },
754
+ nodeId: void 0
755
+ };
456
756
  };
457
- var FunctionError = class extends BaseError.extend("FUNCTION_ERROR") {
757
+
758
+ // src/services/function-invocation-service.ts
759
+ import * as Context4 from "effect/Context";
760
+ import * as Effect8 from "effect/Effect";
761
+ var FunctionInvocationService = class _FunctionInvocationService extends Context4.Tag("@dxos/functions/FunctionInvocationService")() {
762
+ static invokeFunction = (functionDef, input) => Effect8.serviceFunctionEffect(_FunctionInvocationService, (service) => service.invokeFunction)(functionDef, input);
458
763
  };
764
+
765
+ // src/services/queues.ts
766
+ import * as Context5 from "effect/Context";
767
+ import * as Effect9 from "effect/Effect";
768
+ import * as Layer4 from "effect/Layer";
769
+ var QueueService = class _QueueService extends Context5.Tag("@dxos/functions/QueueService")() {
770
+ static notAvailable = Layer4.succeed(_QueueService, {
771
+ queues: {
772
+ get(_dxn) {
773
+ throw new Error("Queues not available");
774
+ },
775
+ create() {
776
+ throw new Error("Queues not available");
777
+ }
778
+ },
779
+ queue: void 0
780
+ });
781
+ static make = (queues, queue) => {
782
+ return {
783
+ queues,
784
+ queue
785
+ };
786
+ };
787
+ static layer = (queues, queue) => Layer4.succeed(_QueueService, _QueueService.make(queues, queue));
788
+ /**
789
+ * Gets a queue by its DXN.
790
+ */
791
+ static getQueue = (dxn) => _QueueService.pipe(Effect9.map(({ queues }) => queues.get(dxn)));
792
+ /**
793
+ * Creates a new queue.
794
+ */
795
+ static createQueue = (options) => _QueueService.pipe(Effect9.map(({ queues }) => queues.create(options)));
796
+ static append = (queue, objects) => Effect9.promise(() => queue.append(objects));
797
+ };
798
+ var ContextQueueService = class _ContextQueueService extends Context5.Tag("@dxos/functions/ContextQueueService")() {
799
+ static layer = (queue) => Layer4.succeed(_ContextQueueService, {
800
+ queue
801
+ });
802
+ };
803
+
804
+ // src/protocol/protocol.ts
805
+ import * as Effect10 from "effect/Effect";
806
+ import * as Layer5 from "effect/Layer";
807
+ import * as Schema10 from "effect/Schema";
808
+ import * as SchemaAST2 from "effect/SchemaAST";
809
+ import { AiService } from "@dxos/ai";
810
+ import { LifecycleState, Resource } from "@dxos/context";
811
+ import { Database as Database2, Type as Type7 } from "@dxos/echo";
812
+ import { EchoClient } from "@dxos/echo-db";
813
+ import { runAndForwardErrors } from "@dxos/effect";
814
+ import { assertState, failedInvariant as failedInvariant2, invariant as invariant2 } from "@dxos/invariant";
815
+ import { PublicKey } from "@dxos/keys";
816
+ function _ts_add_disposable_resource(env, value2, async) {
817
+ if (value2 !== null && value2 !== void 0) {
818
+ if (typeof value2 !== "object" && typeof value2 !== "function") throw new TypeError("Object expected.");
819
+ var dispose, inner;
820
+ if (async) {
821
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
822
+ dispose = value2[Symbol.asyncDispose];
823
+ }
824
+ if (dispose === void 0) {
825
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
826
+ dispose = value2[Symbol.dispose];
827
+ if (async) inner = dispose;
828
+ }
829
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
830
+ if (inner) dispose = function() {
831
+ try {
832
+ inner.call(this);
833
+ } catch (e) {
834
+ return Promise.reject(e);
835
+ }
836
+ };
837
+ env.stack.push({
838
+ value: value2,
839
+ dispose,
840
+ async
841
+ });
842
+ } else if (async) {
843
+ env.stack.push({
844
+ async: true
845
+ });
846
+ }
847
+ return value2;
848
+ }
849
+ function _ts_dispose_resources(env) {
850
+ var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
851
+ var e = new Error(message);
852
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
853
+ };
854
+ return (_ts_dispose_resources = function _ts_dispose_resources2(env2) {
855
+ function fail(e) {
856
+ env2.error = env2.hasError ? new _SuppressedError(e, env2.error, "An error was suppressed during disposal.") : e;
857
+ env2.hasError = true;
858
+ }
859
+ var r, s = 0;
860
+ function next() {
861
+ while (r = env2.stack.pop()) {
862
+ try {
863
+ if (!r.async && s === 1) return s = 0, env2.stack.push(r), Promise.resolve().then(next);
864
+ if (r.dispose) {
865
+ var result = r.dispose.call(r.value);
866
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
867
+ fail(e);
868
+ return next();
869
+ });
870
+ } else s |= 1;
871
+ } catch (e) {
872
+ fail(e);
873
+ }
874
+ }
875
+ if (s === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve();
876
+ if (env2.hasError) throw env2.error;
877
+ }
878
+ return next();
879
+ })(env);
880
+ }
881
+ var __dxlog_file2 = "/__w/dxos/dxos/packages/core/functions/src/protocol/protocol.ts";
882
+ var wrapFunctionHandler = (func) => {
883
+ if (!FunctionDefinition.isFunction(func)) {
884
+ throw new TypeError("Invalid function definition");
885
+ }
886
+ return {
887
+ meta: {
888
+ key: func.key,
889
+ name: func.name,
890
+ description: func.description,
891
+ inputSchema: Type7.toJsonSchema(func.inputSchema),
892
+ outputSchema: func.outputSchema === void 0 ? void 0 : Type7.toJsonSchema(func.outputSchema),
893
+ services: func.services
894
+ },
895
+ handler: async ({ data, context }) => {
896
+ if ((func.services.includes(Database2.Service.key) || func.services.includes(QueueService.key)) && (!context.services.dataService || !context.services.queryService)) {
897
+ throw new FunctionError({
898
+ message: "Services not provided: dataService, queryService"
899
+ });
900
+ }
901
+ try {
902
+ const env = {
903
+ stack: [],
904
+ error: void 0,
905
+ hasError: false
906
+ };
907
+ try {
908
+ if (!SchemaAST2.isAnyKeyword(func.inputSchema.ast)) {
909
+ try {
910
+ Schema10.validateSync(func.inputSchema)(data);
911
+ } catch (error) {
912
+ throw new FunctionError({
913
+ message: "Invalid input schema",
914
+ cause: error
915
+ });
916
+ }
917
+ }
918
+ const funcContext = _ts_add_disposable_resource(env, await new FunctionContext(context).open(), true);
919
+ if (func.types.length > 0) {
920
+ invariant2(funcContext.db, "Database is required for functions with types", {
921
+ F: __dxlog_file2,
922
+ L: 64,
923
+ S: void 0,
924
+ A: [
925
+ "funcContext.db",
926
+ "'Database is required for functions with types'"
927
+ ]
928
+ });
929
+ await funcContext.db.graph.schemaRegistry.register(func.types);
930
+ }
931
+ let result = await func.handler({
932
+ // TODO(dmaretskyi): Fix the types.
933
+ context,
934
+ data
935
+ });
936
+ if (Effect10.isEffect(result)) {
937
+ result = await runAndForwardErrors(result.pipe(Effect10.orDie, Effect10.provide(funcContext.createLayer())));
938
+ }
939
+ if (func.outputSchema && !SchemaAST2.isAnyKeyword(func.outputSchema.ast)) {
940
+ Schema10.validateSync(func.outputSchema)(result);
941
+ }
942
+ return result;
943
+ } catch (e) {
944
+ env.error = e;
945
+ env.hasError = true;
946
+ } finally {
947
+ const result = _ts_dispose_resources(env);
948
+ if (result) await result;
949
+ }
950
+ } catch (error) {
951
+ throw error;
952
+ }
953
+ }
954
+ };
955
+ };
956
+ var FunctionContext = class extends Resource {
957
+ context;
958
+ client;
959
+ db;
960
+ queues;
961
+ constructor(context) {
962
+ super();
963
+ this.context = context;
964
+ if (context.services.dataService && context.services.queryService) {
965
+ this.client = new EchoClient().connectToService({
966
+ dataService: context.services.dataService,
967
+ queryService: context.services.queryService,
968
+ queueService: context.services.queueService
969
+ });
970
+ }
971
+ }
972
+ async _open() {
973
+ await this.client?.open();
974
+ this.db = this.client && this.context.spaceId ? this.client.constructDatabase({
975
+ spaceId: this.context.spaceId ?? failedInvariant2(),
976
+ spaceKey: PublicKey.fromHex(this.context.spaceKey ?? failedInvariant2("spaceKey missing in context")),
977
+ reactiveSchemaQuery: false,
978
+ preloadSchemaOnOpen: false
979
+ }) : void 0;
980
+ await this.db?.setSpaceRoot(this.context.spaceRootUrl ?? failedInvariant2("spaceRootUrl missing in context"));
981
+ await this.db?.open();
982
+ this.queues = this.client && this.context.spaceId ? this.client.constructQueueFactory(this.context.spaceId) : void 0;
983
+ }
984
+ async _close() {
985
+ await this.db?.close();
986
+ await this.client?.close();
987
+ }
988
+ createLayer() {
989
+ assertState(this._lifecycleState === LifecycleState.OPEN, "FunctionContext is not open");
990
+ const dbLayer = this.db ? Database2.Service.layer(this.db) : Database2.Service.notAvailable;
991
+ const queuesLayer = this.queues ? QueueService.layer(this.queues) : QueueService.notAvailable;
992
+ const credentials = dbLayer ? CredentialsService.layerFromDatabase().pipe(Layer5.provide(dbLayer)) : CredentialsService.configuredLayer([]);
993
+ const functionInvocationService = MockedFunctionInvocationService;
994
+ const aiService = AiService.notAvailable;
995
+ const tracing = TracingService.layerNoop;
996
+ return Layer5.mergeAll(dbLayer, queuesLayer, credentials, functionInvocationService, aiService, tracing);
997
+ }
998
+ };
999
+ var MockedFunctionInvocationService = Layer5.succeed(FunctionInvocationService, {
1000
+ invokeFunction: () => Effect10.die("Calling functions from functions is not implemented yet.")
1001
+ });
459
1002
  export {
1003
+ ComputeEvent,
1004
+ ComputeEventLogger,
1005
+ ComputeEventPayload,
460
1006
  ConfiguredCredentialsService,
461
1007
  ContextQueueService,
462
1008
  CredentialsService,
463
- DatabaseService,
464
- EmailTriggerOutput,
465
- EventLogger,
1009
+ Example,
1010
+ FUNCTIONS_META_KEY,
466
1011
  FUNCTIONS_PRESET_META_KEY,
467
- FUNCTION_TYPES,
468
- FunctionCallService,
1012
+ Function_exports as Function,
1013
+ FunctionDefinition,
469
1014
  FunctionError,
470
- FunctionExecutor,
471
- FunctionManifestSchema,
472
- FunctionTrigger,
473
- FunctionTriggerSchema,
474
- FunctionType,
475
- InvocationOutcome,
476
- InvocationTraceEndEvent,
477
- InvocationTraceEventType,
478
- InvocationTraceStartEvent,
1015
+ FunctionInvocationService,
1016
+ FunctionNotFoundError,
1017
+ MESSAGE_PROPERTY_TOOL_CALL_ID,
479
1018
  QueueService,
480
- QueueTriggerOutput,
481
- SERVICE_TAGS,
482
- ScriptType,
483
- ServiceContainer,
1019
+ Script_exports as Script,
484
1020
  ServiceNotAvailableError,
485
- SubscriptionTriggerOutput,
486
- TimerTriggerOutput,
487
- TraceEvent,
488
- TraceEventException,
489
- TraceEventLog,
490
1021
  TracingService,
491
- TriggerKind,
492
- TriggerSchema,
493
- WebhookTriggerOutput,
1022
+ Trigger_exports as Trigger,
1023
+ TriggerEvent_exports as TriggerEvent,
1024
+ TriggerStateNotFoundError,
494
1025
  createDefectLogger,
495
1026
  createEventLogger,
496
- createInvocationSpans,
497
1027
  defineFunction,
498
- getInvocationUrl,
499
- getUserFunctionUrlInMetadata,
1028
+ deserializeFunction,
1029
+ getUserFunctionIdInMetadata,
500
1030
  logCustomEvent,
501
- makeFunctionUrl,
502
- setUserFunctionUrlInMetadata
1031
+ serializeFunction,
1032
+ setUserFunctionIdInMetadata,
1033
+ withAuthorization,
1034
+ wrapFunctionHandler
503
1035
  };
504
1036
  //# sourceMappingURL=index.mjs.map