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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/dist/lib/browser/index.mjs +663 -363
  2. package/dist/lib/browser/index.mjs.map +4 -4
  3. package/dist/lib/browser/meta.json +1 -1
  4. package/dist/lib/node-esm/index.mjs +663 -363
  5. package/dist/lib/node-esm/index.mjs.map +4 -4
  6. package/dist/lib/node-esm/meta.json +1 -1
  7. package/dist/types/src/errors.d.ts +81 -28
  8. package/dist/types/src/errors.d.ts.map +1 -1
  9. package/dist/types/src/example/fib.d.ts +7 -0
  10. package/dist/types/src/example/fib.d.ts.map +1 -0
  11. package/dist/types/src/example/forex-effect.d.ts +3 -0
  12. package/dist/types/src/example/forex-effect.d.ts.map +1 -0
  13. package/dist/types/src/example/index.d.ts +12 -0
  14. package/dist/types/src/example/index.d.ts.map +1 -0
  15. package/dist/types/src/example/reply.d.ts +3 -0
  16. package/dist/types/src/example/reply.d.ts.map +1 -0
  17. package/dist/types/src/example/sleep.d.ts +5 -0
  18. package/dist/types/src/example/sleep.d.ts.map +1 -0
  19. package/dist/types/src/handler.d.ts +56 -36
  20. package/dist/types/src/handler.d.ts.map +1 -1
  21. package/dist/types/src/index.d.ts +3 -5
  22. package/dist/types/src/index.d.ts.map +1 -1
  23. package/dist/types/src/services/credentials.d.ts +20 -3
  24. package/dist/types/src/services/credentials.d.ts.map +1 -1
  25. package/dist/types/src/services/event-logger.d.ts +80 -30
  26. package/dist/types/src/services/event-logger.d.ts.map +1 -1
  27. package/dist/types/src/services/function-invocation-service.d.ts +11 -0
  28. package/dist/types/src/services/function-invocation-service.d.ts.map +1 -0
  29. package/dist/types/src/services/index.d.ts +6 -5
  30. package/dist/types/src/services/index.d.ts.map +1 -1
  31. package/dist/types/src/services/queues.d.ts +23 -6
  32. package/dist/types/src/services/queues.d.ts.map +1 -1
  33. package/dist/types/src/services/tracing.d.ts +35 -6
  34. package/dist/types/src/services/tracing.d.ts.map +1 -1
  35. package/dist/types/src/types/Function.d.ts +52 -0
  36. package/dist/types/src/types/Function.d.ts.map +1 -0
  37. package/dist/types/src/types/Script.d.ts +28 -0
  38. package/dist/types/src/types/Script.d.ts.map +1 -0
  39. package/dist/types/src/types/Trigger.d.ts +139 -0
  40. package/dist/types/src/types/Trigger.d.ts.map +1 -0
  41. package/dist/types/src/types/TriggerEvent.d.ts +44 -0
  42. package/dist/types/src/types/TriggerEvent.d.ts.map +1 -0
  43. package/dist/types/src/types/index.d.ts +5 -0
  44. package/dist/types/src/types/index.d.ts.map +1 -0
  45. package/dist/types/src/url.d.ts +7 -12
  46. package/dist/types/src/url.d.ts.map +1 -1
  47. package/dist/types/tsconfig.tsbuildinfo +1 -1
  48. package/package.json +17 -68
  49. package/src/errors.ts +13 -5
  50. package/src/example/fib.ts +32 -0
  51. package/src/example/forex-effect.ts +40 -0
  52. package/src/example/index.ts +13 -0
  53. package/src/example/reply.ts +21 -0
  54. package/src/example/sleep.ts +24 -0
  55. package/src/handler.ts +145 -64
  56. package/src/index.ts +3 -7
  57. package/src/services/credentials.ts +85 -3
  58. package/src/services/event-logger.ts +77 -37
  59. package/src/services/function-invocation-service.ts +20 -0
  60. package/src/services/index.ts +7 -5
  61. package/src/services/queues.ts +39 -10
  62. package/src/services/tracing.ts +82 -16
  63. package/src/types/Function.ts +56 -0
  64. package/src/types/Script.ts +33 -0
  65. package/src/types/Trigger.ts +139 -0
  66. package/src/types/TriggerEvent.ts +62 -0
  67. package/src/types/index.ts +8 -0
  68. package/src/url.ts +12 -33
  69. package/dist/lib/browser/bundler/index.mjs +0 -247
  70. package/dist/lib/browser/bundler/index.mjs.map +0 -7
  71. package/dist/lib/browser/chunk-3NGCSUEW.mjs +0 -328
  72. package/dist/lib/browser/chunk-3NGCSUEW.mjs.map +0 -7
  73. package/dist/lib/browser/edge/index.mjs +0 -69
  74. package/dist/lib/browser/edge/index.mjs.map +0 -7
  75. package/dist/lib/browser/testing/index.mjs +0 -91
  76. package/dist/lib/browser/testing/index.mjs.map +0 -7
  77. package/dist/lib/node-esm/bundler/index.mjs +0 -249
  78. package/dist/lib/node-esm/bundler/index.mjs.map +0 -7
  79. package/dist/lib/node-esm/chunk-FJ2MU7TL.mjs +0 -330
  80. package/dist/lib/node-esm/chunk-FJ2MU7TL.mjs.map +0 -7
  81. package/dist/lib/node-esm/edge/index.mjs +0 -71
  82. package/dist/lib/node-esm/edge/index.mjs.map +0 -7
  83. package/dist/lib/node-esm/testing/index.mjs +0 -92
  84. package/dist/lib/node-esm/testing/index.mjs.map +0 -7
  85. package/dist/types/src/bundler/bundler.d.ts +0 -50
  86. package/dist/types/src/bundler/bundler.d.ts.map +0 -1
  87. package/dist/types/src/bundler/bundler.test.d.ts +0 -2
  88. package/dist/types/src/bundler/bundler.test.d.ts.map +0 -1
  89. package/dist/types/src/bundler/index.d.ts +0 -2
  90. package/dist/types/src/bundler/index.d.ts.map +0 -1
  91. package/dist/types/src/edge/functions.d.ts +0 -16
  92. package/dist/types/src/edge/functions.d.ts.map +0 -1
  93. package/dist/types/src/edge/index.d.ts +0 -2
  94. package/dist/types/src/edge/index.d.ts.map +0 -1
  95. package/dist/types/src/executor/executor.d.ts +0 -8
  96. package/dist/types/src/executor/executor.d.ts.map +0 -1
  97. package/dist/types/src/executor/index.d.ts +0 -2
  98. package/dist/types/src/executor/index.d.ts.map +0 -1
  99. package/dist/types/src/schema.d.ts +0 -38
  100. package/dist/types/src/schema.d.ts.map +0 -1
  101. package/dist/types/src/services/database.d.ts +0 -29
  102. package/dist/types/src/services/database.d.ts.map +0 -1
  103. package/dist/types/src/services/function-call-service.d.ts +0 -16
  104. package/dist/types/src/services/function-call-service.d.ts.map +0 -1
  105. package/dist/types/src/services/service-container.d.ts +0 -56
  106. package/dist/types/src/services/service-container.d.ts.map +0 -1
  107. package/dist/types/src/services/service-registry.d.ts +0 -29
  108. package/dist/types/src/services/service-registry.d.ts.map +0 -1
  109. package/dist/types/src/services/service-registry.test.d.ts +0 -2
  110. package/dist/types/src/services/service-registry.test.d.ts.map +0 -1
  111. package/dist/types/src/testing/index.d.ts +0 -3
  112. package/dist/types/src/testing/index.d.ts.map +0 -1
  113. package/dist/types/src/testing/layer.d.ts +0 -10
  114. package/dist/types/src/testing/layer.d.ts.map +0 -1
  115. package/dist/types/src/testing/logger.d.ts +0 -5
  116. package/dist/types/src/testing/logger.d.ts.map +0 -1
  117. package/dist/types/src/testing/services.d.ts +0 -70
  118. package/dist/types/src/testing/services.d.ts.map +0 -1
  119. package/dist/types/src/trace.d.ts +0 -124
  120. package/dist/types/src/trace.d.ts.map +0 -1
  121. package/dist/types/src/translations.d.ts +0 -12
  122. package/dist/types/src/translations.d.ts.map +0 -1
  123. package/dist/types/src/types.d.ts +0 -411
  124. package/dist/types/src/types.d.ts.map +0 -1
  125. package/src/bundler/bundler.test.ts +0 -59
  126. package/src/bundler/bundler.ts +0 -292
  127. package/src/bundler/index.ts +0 -5
  128. package/src/edge/functions.ts +0 -64
  129. package/src/edge/index.ts +0 -9
  130. package/src/executor/executor.ts +0 -54
  131. package/src/executor/index.ts +0 -5
  132. package/src/schema.ts +0 -57
  133. package/src/services/database.ts +0 -70
  134. package/src/services/function-call-service.ts +0 -64
  135. package/src/services/service-container.ts +0 -113
  136. package/src/services/service-registry.test.ts +0 -42
  137. package/src/services/service-registry.ts +0 -56
  138. package/src/testing/index.ts +0 -6
  139. package/src/testing/layer.ts +0 -31
  140. package/src/testing/logger.ts +0 -16
  141. package/src/testing/services.ts +0 -168
  142. package/src/trace.ts +0 -180
  143. package/src/translations.ts +0 -20
  144. package/src/types.ts +0 -211
@@ -1,97 +1,177 @@
1
- import {
2
- ConfiguredCredentialsService,
3
- ContextQueueService,
4
- CredentialsService,
5
- DatabaseService,
6
- EventLogger,
7
- FunctionCallService,
8
- QueueService,
9
- SERVICE_TAGS,
10
- ServiceContainer,
11
- TracingService,
12
- createDefectLogger,
13
- createEventLogger,
14
- logCustomEvent
15
- } from "./chunk-3NGCSUEW.mjs";
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
16
6
 
17
- // src/handler.ts
18
- import { Schema } from "effect";
19
- var defineFunction = ({ name, description, inputSchema, outputSchema = Schema.Any, handler }) => {
20
- if (!Schema.isSchema(inputSchema)) {
21
- throw new Error("Input schema must be a valid schema");
7
+ // src/errors.ts
8
+ import { BaseError } from "@dxos/errors";
9
+ var ServiceNotAvailableError = class extends BaseError.extend("SERVICE_NOT_AVAILABLE", "Service not available") {
10
+ constructor(service, options) {
11
+ super({
12
+ context: {
13
+ service
14
+ },
15
+ ...options
16
+ });
22
17
  }
23
- if (typeof handler !== "function") {
24
- throw new Error("Handler must be a function");
18
+ };
19
+ var FunctionNotFoundError = class extends BaseError.extend("FUNCTION_NOT_FOUND", "Function not found") {
20
+ constructor(functionKey, options) {
21
+ super({
22
+ context: {
23
+ function: functionKey
24
+ },
25
+ ...options
26
+ });
25
27
  }
26
- return {
27
- name,
28
- description,
29
- inputSchema,
30
- outputSchema,
31
- handler
32
- };
28
+ };
29
+ var FunctionError = class extends BaseError.extend("FUNCTION_ERROR", "Function invocation error") {
30
+ };
31
+ var TriggerStateNotFoundError = class extends BaseError.extend("TRIGGER_STATE_NOT_FOUND", "Trigger state not found") {
33
32
  };
34
33
 
35
- // src/schema.ts
36
- import { Schema as Schema2 } from "effect";
37
- import { Type } from "@dxos/echo";
38
- import { JsonSchemaType, LabelAnnotation, Ref } from "@dxos/echo-schema";
39
- import { DataType } from "@dxos/schema";
40
- var ScriptType = Schema2.Struct({
41
- name: Schema2.optional(Schema2.String),
42
- description: Schema2.optional(Schema2.String),
34
+ // src/example/fib.ts
35
+ import * as Effect2 from "effect/Effect";
36
+ import * as Schema6 from "effect/Schema";
37
+
38
+ // src/handler.ts
39
+ import * as Effect from "effect/Effect";
40
+ import * as Schema5 from "effect/Schema";
41
+ import { Obj as Obj5, Type as Type5 } from "@dxos/echo";
42
+ import { assertArgument } from "@dxos/invariant";
43
+
44
+ // src/types/Function.ts
45
+ var Function_exports = {};
46
+ __export(Function_exports, {
47
+ Function: () => Function,
48
+ make: () => make2
49
+ });
50
+ import * as Schema2 from "effect/Schema";
51
+ import { Obj as Obj2, Type as Type2 } from "@dxos/echo";
52
+ import { JsonSchemaType, LabelAnnotation as LabelAnnotation2, Ref as Ref2 } from "@dxos/echo/internal";
53
+
54
+ // src/types/Script.ts
55
+ var Script_exports = {};
56
+ __export(Script_exports, {
57
+ Script: () => Script,
58
+ make: () => make
59
+ });
60
+ import * as Schema from "effect/Schema";
61
+ import { Obj, Ref, Type } from "@dxos/echo";
62
+ import { FormAnnotation, LabelAnnotation } from "@dxos/echo/internal";
63
+ import { Text } from "@dxos/schema";
64
+ var Script = Schema.Struct({
65
+ name: Schema.String.pipe(Schema.optional),
66
+ description: Schema.String.pipe(Schema.optional),
43
67
  // TODO(burdon): Change to hash of deployed content.
44
68
  // Whether source has changed since last deploy.
45
- changed: Schema2.optional(Schema2.Boolean),
46
- source: Ref(DataType.Text)
69
+ changed: Schema.Boolean.pipe(FormAnnotation.set(false), Schema.optional),
70
+ source: Type.Ref(Text.Text).pipe(FormAnnotation.set(false))
47
71
  }).pipe(Type.Obj({
48
72
  typename: "dxos.org/type/Script",
49
73
  version: "0.1.0"
50
74
  }), LabelAnnotation.set([
51
75
  "name"
52
76
  ]));
53
- var FunctionType = Schema2.Struct({
77
+ var make = ({ source = "", ...props } = {}) => Obj.make(Script, {
78
+ ...props,
79
+ source: Ref.make(Text.make(source))
80
+ });
81
+
82
+ // src/types/Function.ts
83
+ var Function = Schema2.Struct({
84
+ /**
85
+ * Global registry ID.
86
+ * NOTE: The `key` property refers to the original registry entry.
87
+ */
88
+ // TODO(burdon): Create Format type for DXN-like ids, such as this and schema type.
89
+ // TODO(dmaretskyi): Consider making it part of ECHO meta.
90
+ // TODO(dmaretskyi): Make required.
91
+ key: Schema2.optional(Schema2.String).annotations({
92
+ description: "Unique registration key for the blueprint"
93
+ }),
54
94
  // TODO(burdon): Rename to id/uri?
55
95
  name: Schema2.NonEmptyString,
56
96
  version: Schema2.String,
57
97
  description: Schema2.optional(Schema2.String),
98
+ /**
99
+ * ISO date string of the last deployment.
100
+ */
101
+ updated: Schema2.optional(Schema2.String),
58
102
  // Reference to a source script if it exists within ECHO.
59
103
  // TODO(burdon): Don't ref ScriptType directly (core).
60
- source: Schema2.optional(Ref(ScriptType)),
104
+ source: Schema2.optional(Ref2(Script)),
61
105
  inputSchema: Schema2.optional(JsonSchemaType),
62
106
  outputSchema: Schema2.optional(JsonSchemaType),
63
107
  // Local binding to a function name.
64
108
  binding: Schema2.optional(Schema2.String)
65
- }).pipe(Type.Obj({
109
+ }).pipe(Type2.Obj({
66
110
  typename: "dxos.org/type/Function",
67
111
  version: "0.1.0"
68
- }), LabelAnnotation.set([
112
+ }), LabelAnnotation2.set([
69
113
  "name"
70
114
  ]));
115
+ var make2 = (props) => Obj2.make(Function, props);
71
116
 
72
- // src/trace.ts
73
- import { Schema as Schema4 } from "effect";
74
- import { Type as Type2 } from "@dxos/echo";
75
- import { Queue } from "@dxos/echo-db";
76
- import { ObjectId } from "@dxos/echo-schema";
77
- import { log } from "@dxos/log";
78
-
79
- // src/types.ts
80
- import { Schema as Schema3, SchemaAST } from "effect";
81
- import { Expando, OptionsAnnotationId, TypedObject, Ref as Ref2, RawObject } from "@dxos/echo-schema";
117
+ // src/types/Trigger.ts
118
+ var Trigger_exports = {};
119
+ __export(Trigger_exports, {
120
+ EmailSpec: () => EmailSpec,
121
+ Kinds: () => Kinds,
122
+ QueueSpec: () => QueueSpec,
123
+ Spec: () => Spec,
124
+ SubscriptionSpec: () => SubscriptionSpec,
125
+ TimerSpec: () => TimerSpec,
126
+ Trigger: () => Trigger,
127
+ WebhookSpec: () => WebhookSpec,
128
+ make: () => make3
129
+ });
130
+ import * as Schema3 from "effect/Schema";
131
+ import * as SchemaAST from "effect/SchemaAST";
132
+ import { Obj as Obj3, QueryAST, Type as Type3 } from "@dxos/echo";
133
+ import { Expando, OptionsAnnotationId, Ref as Ref3 } from "@dxos/echo/internal";
82
134
  import { DXN } from "@dxos/keys";
83
- var TriggerKind = /* @__PURE__ */ function(TriggerKind2) {
84
- TriggerKind2["Timer"] = "timer";
85
- TriggerKind2["Webhook"] = "webhook";
86
- TriggerKind2["Subscription"] = "subscription";
87
- TriggerKind2["Email"] = "email";
88
- TriggerKind2["Queue"] = "queue";
89
- return TriggerKind2;
90
- }({});
135
+ var Kinds = [
136
+ "email",
137
+ "queue",
138
+ "subscription",
139
+ "timer",
140
+ "webhook"
141
+ ];
91
142
  var kindLiteralAnnotations = {
92
143
  title: "Kind"
93
144
  };
94
- var TimerTriggerSchema = Schema3.Struct({
145
+ var EmailSpec = Schema3.Struct({
146
+ kind: Schema3.Literal("email").annotations(kindLiteralAnnotations)
147
+ }).pipe(Schema3.mutable);
148
+ var QueueSpec = Schema3.Struct({
149
+ kind: Schema3.Literal("queue").annotations(kindLiteralAnnotations),
150
+ // TODO(dmaretskyi): Change to a reference.
151
+ queue: DXN.Schema
152
+ }).pipe(Schema3.mutable);
153
+ var SubscriptionSpec = Schema3.Struct({
154
+ kind: Schema3.Literal("subscription").annotations(kindLiteralAnnotations),
155
+ query: Schema3.Struct({
156
+ raw: Schema3.optional(Schema3.String.annotations({
157
+ title: "Query"
158
+ })),
159
+ ast: QueryAST.Query
160
+ }).pipe(Schema3.mutable),
161
+ options: Schema3.optional(Schema3.Struct({
162
+ // Watch changes to object (not just creation).
163
+ deep: Schema3.optional(Schema3.Boolean.annotations({
164
+ title: "Nested"
165
+ })),
166
+ // Debounce changes (delay in ms).
167
+ delay: Schema3.optional(Schema3.Number.annotations({
168
+ title: "Delay"
169
+ }))
170
+ }).annotations({
171
+ title: "Options"
172
+ }))
173
+ }).pipe(Schema3.mutable);
174
+ var TimerSpec = Schema3.Struct({
95
175
  kind: Schema3.Literal("timer").annotations(kindLiteralAnnotations),
96
176
  cron: Schema3.String.annotations({
97
177
  title: "Cron",
@@ -100,14 +180,7 @@ var TimerTriggerSchema = Schema3.Struct({
100
180
  ]
101
181
  })
102
182
  }).pipe(Schema3.mutable);
103
- var EmailTriggerSchema = Schema3.Struct({
104
- kind: Schema3.Literal("email").annotations(kindLiteralAnnotations)
105
- }).pipe(Schema3.mutable);
106
- var QueueTriggerSchema = Schema3.Struct({
107
- kind: Schema3.Literal("queue").annotations(kindLiteralAnnotations),
108
- queue: DXN.Schema
109
- }).pipe(Schema3.mutable);
110
- var WebhookTriggerSchema = Schema3.Struct({
183
+ var WebhookSpec = Schema3.Struct({
111
184
  kind: Schema3.Literal("webhook").annotations(kindLiteralAnnotations),
112
185
  method: Schema3.optional(Schema3.String.annotations({
113
186
  title: "Method",
@@ -120,71 +193,15 @@ var WebhookTriggerSchema = Schema3.Struct({
120
193
  title: "Port"
121
194
  }))
122
195
  }).pipe(Schema3.mutable);
123
- var QuerySchema = Schema3.Struct({
124
- type: Schema3.optional(Schema3.String.annotations({
125
- title: "Type"
126
- })),
127
- props: Schema3.optional(Schema3.Record({
128
- key: Schema3.String,
129
- value: Schema3.Any
130
- }))
131
- }).annotations({
132
- title: "Query"
133
- });
134
- var SubscriptionTriggerSchema = Schema3.Struct({
135
- kind: Schema3.Literal("subscription").annotations(kindLiteralAnnotations),
136
- // TODO(burdon): Define query DSL (from ECHO). Reconcile with Table.Query.
137
- filter: QuerySchema,
138
- options: Schema3.optional(Schema3.Struct({
139
- // Watch changes to object (not just creation).
140
- deep: Schema3.optional(Schema3.Boolean.annotations({
141
- title: "Nested"
142
- })),
143
- // Debounce changes (delay in ms).
144
- delay: Schema3.optional(Schema3.Number.annotations({
145
- title: "Delay"
146
- }))
147
- }).annotations({
148
- title: "Options"
149
- }))
150
- }).pipe(Schema3.mutable);
151
- var TriggerSchema = Schema3.Union(TimerTriggerSchema, WebhookTriggerSchema, SubscriptionTriggerSchema, EmailTriggerSchema, QueueTriggerSchema).annotations({
196
+ var Spec = Schema3.Union(EmailSpec, QueueSpec, SubscriptionSpec, TimerSpec, WebhookSpec).annotations({
152
197
  title: "Trigger"
153
198
  });
154
- var EmailTriggerOutput = Schema3.mutable(Schema3.Struct({
155
- from: Schema3.String,
156
- to: Schema3.String,
157
- subject: Schema3.String,
158
- created: Schema3.String,
159
- body: Schema3.String
160
- }));
161
- var WebhookTriggerOutput = Schema3.mutable(Schema3.Struct({
162
- url: Schema3.String,
163
- method: Schema3.Literal("GET", "POST"),
164
- headers: Schema3.Record({
165
- key: Schema3.String,
166
- value: Schema3.String
167
- }),
168
- bodyText: Schema3.String
169
- }));
170
- var QueueTriggerOutput = Schema3.mutable(Schema3.Struct({
171
- queue: DXN.Schema,
172
- item: Schema3.Any,
173
- cursor: Schema3.String
174
- }));
175
- var SubscriptionTriggerOutput = Schema3.mutable(Schema3.Struct({
176
- type: Schema3.String,
177
- changedObjectId: Schema3.String
178
- }));
179
- var TimerTriggerOutput = Schema3.mutable(Schema3.Struct({
180
- tick: Schema3.Number
181
- }));
182
- var FunctionTriggerSchema = Schema3.Struct({
199
+ var Trigger_ = Schema3.Struct({
183
200
  /**
184
201
  * Function or workflow to invoke.
185
202
  */
186
203
  // TODO(dmaretskyi): Can be a Ref(FunctionType) or Ref(ComputeGraphType).
187
- function: Schema3.optional(Ref2(Expando).annotations({
204
+ function: Schema3.optional(Ref3(Expando).annotations({
188
205
  title: "Function"
189
206
  })),
190
207
  /**
@@ -198,7 +215,7 @@ var FunctionTriggerSchema = Schema3.Struct({
198
215
  enabled: Schema3.optional(Schema3.Boolean.annotations({
199
216
  title: "Enabled"
200
217
  })),
201
- spec: Schema3.optional(TriggerSchema),
218
+ spec: Schema3.optional(Spec),
202
219
  /**
203
220
  * Passed as the input data to the function.
204
221
  * Must match the function's input schema.
@@ -214,290 +231,573 @@ var FunctionTriggerSchema = Schema3.Struct({
214
231
  key: Schema3.String,
215
232
  value: Schema3.Any
216
233
  })))
217
- });
218
- var FunctionTrigger = class extends TypedObject({
219
- typename: "dxos.org/type/FunctionTrigger",
220
- version: "0.2.0"
221
- })(FunctionTriggerSchema.fields) {
222
- };
223
- var FunctionManifestSchema = Schema3.Struct({
224
- functions: Schema3.optional(Schema3.mutable(Schema3.Array(RawObject(FunctionType)))),
225
- triggers: Schema3.optional(Schema3.mutable(Schema3.Array(RawObject(FunctionTrigger))))
226
- });
227
- var FUNCTION_TYPES = [
228
- FunctionType,
229
- FunctionTrigger
230
- ];
234
+ }).pipe(Type3.Obj({
235
+ typename: "dxos.org/type/Trigger",
236
+ version: "0.1.0"
237
+ }));
238
+ var Trigger = Trigger_;
239
+ var make3 = (props) => Obj3.make(Trigger, props);
231
240
 
232
- // src/trace.ts
233
- var __dxlog_file = "/__w/dxos/dxos/packages/core/functions/src/trace.ts";
234
- var InvocationOutcome = /* @__PURE__ */ function(InvocationOutcome2) {
235
- InvocationOutcome2["SUCCESS"] = "success";
236
- InvocationOutcome2["FAILURE"] = "failure";
237
- InvocationOutcome2["PENDING"] = "pending";
238
- return InvocationOutcome2;
239
- }({});
240
- var InvocationTraceEventType = /* @__PURE__ */ function(InvocationTraceEventType2) {
241
- InvocationTraceEventType2["START"] = "start";
242
- InvocationTraceEventType2["END"] = "end";
243
- return InvocationTraceEventType2;
244
- }({});
245
- var TraceEventException = Schema4.Struct({
246
- timestampMs: Schema4.Number,
247
- message: Schema4.String,
248
- name: Schema4.String,
249
- stack: Schema4.optional(Schema4.String)
241
+ // src/types/TriggerEvent.ts
242
+ var TriggerEvent_exports = {};
243
+ __export(TriggerEvent_exports, {
244
+ EmailEvent: () => EmailEvent,
245
+ QueueEvent: () => QueueEvent,
246
+ SubscriptionEvent: () => SubscriptionEvent,
247
+ TimerEvent: () => TimerEvent,
248
+ WebhookEvent: () => WebhookEvent
250
249
  });
251
- var InvocationTraceStartEvent = Schema4.Struct({
252
- /**
253
- * Queue message id.
254
- */
255
- id: ObjectId,
256
- type: Schema4.Literal("start"),
257
- /**
258
- * Invocation id, the same for invocation start and end events.
259
- */
260
- invocationId: ObjectId,
261
- /**
262
- * Event generation time.
263
- */
264
- timestampMs: Schema4.Number,
265
- /**
266
- * Data passed to function / workflow as an argument.
267
- */
268
- // TODO(burdon): Input schema?
269
- input: Schema4.Object,
270
- /**
271
- * Queue for function/workflow invocation events.
272
- */
273
- invocationTraceQueue: Type2.Ref(Queue),
274
- /**
275
- * DXN of the invoked function/workflow.
276
- */
277
- invocationTarget: Type2.Ref(Type2.Expando),
278
- /**
279
- * Present for automatic invocations.
280
- */
281
- trigger: Schema4.optional(Type2.Ref(FunctionTrigger))
282
- }).pipe(Type2.Obj({
283
- typename: "dxos.org/type/InvocationTraceStart",
284
- version: "0.1.0"
250
+ import * as Schema4 from "effect/Schema";
251
+ import { DXN as DXN2, Obj as Obj4, Type as Type4 } from "@dxos/echo";
252
+ var EmailEvent = Schema4.mutable(Schema4.Struct({
253
+ from: Schema4.String,
254
+ to: Schema4.String,
255
+ subject: Schema4.String,
256
+ created: Schema4.String,
257
+ body: Schema4.String
285
258
  }));
286
- var InvocationTraceEndEvent = Schema4.Struct({
259
+ var QueueEvent = Schema4.mutable(Schema4.Struct({
260
+ queue: DXN2.Schema,
261
+ item: Schema4.Any,
262
+ cursor: Schema4.String
263
+ }));
264
+ var SubscriptionEvent = Schema4.Struct({
287
265
  /**
288
- * Trace event id.
266
+ * Type of the mutation.
289
267
  */
290
- id: ObjectId,
291
- type: Schema4.Literal("end"),
268
+ // TODO(dmaretskyi): Specify enum.
269
+ type: Schema4.String,
292
270
  /**
293
- * Invocation id, will be the same for invocation start and end.
271
+ * Reference to the object that was changed or created.
294
272
  */
295
- invocationId: ObjectId,
273
+ subject: Type4.Ref(Obj4.Any),
296
274
  /**
297
- * Event generation time.
275
+ * @deprecated
298
276
  */
299
- // TODO(burdon): Remove ms suffix.
300
- timestampMs: Schema4.Number,
301
- outcome: Schema4.Enums(InvocationOutcome),
302
- exception: Schema4.optional(TraceEventException)
303
- }).pipe(Type2.Obj({
304
- typename: "dxos.org/type/InvocationTraceEnd",
305
- version: "0.1.0"
277
+ changedObjectId: Schema4.optional(Schema4.String)
278
+ }).pipe(Schema4.mutable);
279
+ var TimerEvent = Schema4.mutable(Schema4.Struct({
280
+ tick: Schema4.Number
306
281
  }));
307
- var TraceEventLog = Schema4.Struct({
308
- timestampMs: Schema4.Number,
309
- level: Schema4.String,
310
- message: Schema4.String,
311
- context: Schema4.optional(Schema4.Object)
312
- });
313
- var TraceEvent = Schema4.Struct({
314
- id: ObjectId,
315
- // TODO(burdon): Need enum/numeric result (not string).
316
- outcome: Schema4.String,
317
- truncated: Schema4.Boolean,
318
- /**
319
- * Time when the event was persisted.
320
- */
321
- ingestionTimestampMs: Schema4.Number,
322
- logs: Schema4.Array(TraceEventLog),
323
- exceptions: Schema4.Array(TraceEventException)
324
- }).pipe(Type2.Obj({
325
- typename: "dxos.org/type/TraceEvent",
326
- version: "0.1.0"
282
+ var WebhookEvent = Schema4.mutable(Schema4.Struct({
283
+ url: Schema4.String,
284
+ method: Schema4.Literal("GET", "POST"),
285
+ headers: Schema4.Record({
286
+ key: Schema4.String,
287
+ value: Schema4.String
288
+ }),
289
+ bodyText: Schema4.String
327
290
  }));
328
- var createInvocationSpans = (items) => {
329
- if (!items) {
330
- return [];
331
- }
332
- const eventsByInvocationId = /* @__PURE__ */ new Map();
333
- for (const event of items) {
334
- if (!("invocationId" in event)) {
335
- continue;
336
- }
337
- const invocationId = event.invocationId;
338
- const entry = eventsByInvocationId.get(invocationId) || {
339
- start: void 0,
340
- end: void 0
341
- };
342
- if (event.type === "start") {
343
- entry.start = event;
344
- } else if (event.type === "end") {
345
- entry.end = event;
346
- }
347
- eventsByInvocationId.set(invocationId, entry);
348
- }
349
- const now = Date.now();
350
- const result = [];
351
- for (const [invocationId, { start, end }] of eventsByInvocationId.entries()) {
352
- if (!start) {
353
- log.warn("found end event without matching start", {
354
- invocationId
355
- }, {
356
- F: __dxlog_file,
357
- L: 160,
358
- S: void 0,
359
- C: (f, a) => f(...a)
360
- });
361
- continue;
362
- }
363
- const isInProgress = end === void 0;
364
- result.push({
365
- id: invocationId,
366
- timestampMs: start.timestampMs,
367
- durationMs: isInProgress ? now - start.timestampMs : end.timestampMs - start.timestampMs,
368
- outcome: end?.outcome ?? "pending",
369
- exception: end?.exception,
370
- input: start.input,
371
- invocationTraceQueue: start.invocationTraceQueue,
372
- invocationTarget: start.invocationTarget,
373
- trigger: start.trigger
374
- });
375
- }
376
- return result;
377
- };
378
291
 
379
292
  // src/url.ts
380
293
  var FUNCTIONS_META_KEY = "dxos.org/service/function";
381
294
  var FUNCTIONS_PRESET_META_KEY = "dxos.org/service/function-preset";
382
- var isSecure = (protocol) => {
383
- return protocol === "https:" || protocol === "wss:";
384
- };
385
- var getUserFunctionUrlInMetadata = (meta) => {
295
+ var getUserFunctionIdInMetadata = (meta) => {
386
296
  return meta.keys.find((key) => key.source === FUNCTIONS_META_KEY)?.id;
387
297
  };
388
- var setUserFunctionUrlInMetadata = (meta, functionUrl) => {
298
+ var setUserFunctionIdInMetadata = (meta, functionId) => {
389
299
  const key = meta.keys.find((key2) => key2.source === FUNCTIONS_META_KEY);
390
300
  if (key) {
391
- if (key.id !== functionUrl) {
301
+ if (key.id !== functionId) {
392
302
  throw new Error("Metadata mismatch");
393
303
  }
394
304
  } else {
395
305
  meta.keys.push({
396
306
  source: FUNCTIONS_META_KEY,
397
- id: functionUrl
307
+ id: functionId
398
308
  });
399
309
  }
400
310
  };
401
- var makeFunctionUrl = (fn) => `/${fn.functionId}`;
402
- var getInvocationUrl = (functionUrl, edgeUrl, options = {}) => {
403
- const baseUrl = new URL("functions/", edgeUrl);
404
- const relativeUrl = functionUrl.replace(/^\//, "");
405
- const url = new URL(`./${relativeUrl}`, baseUrl.toString());
406
- options.spaceId && url.searchParams.set("spaceId", options.spaceId);
407
- options.subjectId && url.searchParams.set("subjectId", options.subjectId);
408
- url.protocol = isSecure(url.protocol) ? "https" : "http";
409
- return url.toString();
410
- };
411
311
 
412
- // src/executor/executor.ts
413
- import { Effect, Schema as Schema5 } from "effect";
414
- import { runAndForwardErrors } from "@dxos/effect";
415
- var FunctionExecutor = class {
416
- constructor(_services) {
417
- this._services = _services;
312
+ // src/handler.ts
313
+ var typeId = Symbol.for("@dxos/functions/FunctionDefinition");
314
+ var defineFunction = ({ key, name, description, inputSchema, outputSchema = Schema5.Any, handler }) => {
315
+ if (!Schema5.isSchema(inputSchema)) {
316
+ throw new Error("Input schema must be a valid schema");
418
317
  }
419
- // TODO(dmaretskyi): Invocation context: queue, space, etc...
420
- async invoke(fnDef, input) {
421
- const assertInput = fnDef.inputSchema.pipe(Schema5.asserts);
422
- assertInput(input);
423
- const context = {
424
- getService: this._services.getService.bind(this._services),
425
- getSpace: async (_spaceId) => {
426
- throw new Error("Not available. Use the database service instead.");
427
- },
428
- space: void 0,
429
- get ai() {
430
- throw new Error("Not available. Use the ai service instead.");
318
+ if (typeof handler !== "function") {
319
+ throw new Error("Handler must be a function");
320
+ }
321
+ const limit = Error.stackTraceLimit;
322
+ Error.stackTraceLimit = 2;
323
+ const traceError = new Error();
324
+ Error.stackTraceLimit = limit;
325
+ let cache = false;
326
+ const captureStackTrace = () => {
327
+ if (cache !== false) {
328
+ return cache;
329
+ }
330
+ if (traceError.stack !== void 0) {
331
+ const stack = traceError.stack.split("\n");
332
+ if (stack[2] !== void 0) {
333
+ cache = stack[2].trim();
334
+ return cache;
431
335
  }
432
- };
433
- const result = fnDef.handler({
434
- context,
435
- data: input
436
- });
437
- let data;
336
+ }
337
+ };
338
+ const handlerWithSpan = (...args) => {
339
+ const result = handler(...args);
438
340
  if (Effect.isEffect(result)) {
439
- data = await result.pipe(Effect.provide(this._services.createLayer()), runAndForwardErrors);
440
- } else {
441
- data = await result;
341
+ return Effect.withSpan(result, `${key ?? name}`, {
342
+ captureStackTrace
343
+ });
344
+ }
345
+ return result;
346
+ };
347
+ return {
348
+ [typeId]: true,
349
+ key,
350
+ name,
351
+ description,
352
+ inputSchema,
353
+ outputSchema,
354
+ handler: handlerWithSpan
355
+ };
356
+ };
357
+ var FunctionDefinition = {
358
+ make: defineFunction,
359
+ isFunction: (value2) => {
360
+ return typeof value2 === "object" && value2 !== null && Symbol.for("@dxos/functions/FunctionDefinition") in value2;
361
+ },
362
+ serialize: (functionDef) => {
363
+ assertArgument(FunctionDefinition.isFunction(functionDef), "functionDef");
364
+ return serializeFunction(functionDef);
365
+ },
366
+ deserialize: (functionObj) => {
367
+ assertArgument(Obj5.instanceOf(Function_exports.Function, functionObj), "functionObj");
368
+ return deserializeFunction(functionObj);
369
+ }
370
+ };
371
+ var serializeFunction = (functionDef) => {
372
+ const fn4 = Function_exports.make({
373
+ key: functionDef.key,
374
+ name: functionDef.name,
375
+ version: "0.1.0",
376
+ description: functionDef.description,
377
+ inputSchema: Type5.toJsonSchema(functionDef.inputSchema),
378
+ outputSchema: !functionDef.outputSchema ? void 0 : Type5.toJsonSchema(functionDef.outputSchema)
379
+ });
380
+ if (functionDef.meta?.deployedFunctionId) {
381
+ setUserFunctionIdInMetadata(Obj5.getMeta(fn4), functionDef.meta.deployedFunctionId);
382
+ }
383
+ return fn4;
384
+ };
385
+ var deserializeFunction = (functionObj) => {
386
+ return {
387
+ [typeId]: true,
388
+ // TODO(dmaretskyi): Fix key.
389
+ key: functionObj.key ?? functionObj.name,
390
+ name: functionObj.name,
391
+ description: functionObj.description,
392
+ inputSchema: !functionObj.inputSchema ? Schema5.Unknown : Type5.toEffectSchema(functionObj.inputSchema),
393
+ outputSchema: !functionObj.outputSchema ? void 0 : Type5.toEffectSchema(functionObj.outputSchema),
394
+ // TODO(dmaretskyi): This should throw error.
395
+ handler: () => {
396
+ },
397
+ meta: {
398
+ deployedFunctionId: getUserFunctionIdInMetadata(Obj5.getMeta(functionObj))
399
+ }
400
+ };
401
+ };
402
+
403
+ // src/example/fib.ts
404
+ var fib_default = defineFunction({
405
+ key: "example.org/function/fib",
406
+ name: "Fibonacci",
407
+ description: "Function that calculates a Fibonacci number",
408
+ inputSchema: Schema6.Struct({
409
+ iterations: Schema6.optional(Schema6.Number).annotations({
410
+ description: "Number of iterations",
411
+ default: 1e5
412
+ })
413
+ }),
414
+ outputSchema: Schema6.Struct({
415
+ result: Schema6.String
416
+ }),
417
+ handler: Effect2.fn(function* ({ data: { iterations = 1e5 } }) {
418
+ let a = 0n;
419
+ let b = 1n;
420
+ for (let i = 0; i < iterations; i++) {
421
+ a += b;
422
+ b = a - b;
442
423
  }
443
- const assertOutput = fnDef.outputSchema?.pipe(Schema5.asserts);
444
- assertOutput(data);
424
+ return {
425
+ result: a.toString()
426
+ };
427
+ })
428
+ });
429
+
430
+ // src/example/reply.ts
431
+ import * as Console from "effect/Console";
432
+ import * as Effect3 from "effect/Effect";
433
+ import * as Schema7 from "effect/Schema";
434
+ var reply_default = defineFunction({
435
+ key: "example.org/function/reply",
436
+ name: "Reply",
437
+ description: "Function that echoes the input",
438
+ inputSchema: Schema7.Any,
439
+ outputSchema: Schema7.Any,
440
+ handler: Effect3.fn(function* ({ data }) {
441
+ yield* Console.log("reply", {
442
+ data
443
+ });
445
444
  return data;
445
+ })
446
+ });
447
+
448
+ // src/example/sleep.ts
449
+ import * as Effect4 from "effect/Effect";
450
+ import * as Schema8 from "effect/Schema";
451
+ var sleep_default = defineFunction({
452
+ key: "example.org/function/sleep",
453
+ name: "Sleep",
454
+ description: "Function that sleeps for a given amount of time",
455
+ inputSchema: Schema8.Struct({
456
+ duration: Schema8.optional(Schema8.Number).annotations({
457
+ description: "Milliseconds to sleep",
458
+ default: 1e5
459
+ })
460
+ }),
461
+ outputSchema: Schema8.Void,
462
+ handler: Effect4.fn(function* ({ data: { duration = 1e5 } }) {
463
+ yield* Effect4.sleep(duration);
464
+ })
465
+ });
466
+
467
+ // src/example/index.ts
468
+ (function(Example2) {
469
+ Example2.fib = fib_default;
470
+ Example2.reply = reply_default;
471
+ Example2.sleep = sleep_default;
472
+ })(Example || (Example = {}));
473
+ var Example;
474
+
475
+ // src/services/index.ts
476
+ import { DatabaseService as DatabaseService2 } from "@dxos/echo-db";
477
+
478
+ // src/services/credentials.ts
479
+ import * as HttpClient from "@effect/platform/HttpClient";
480
+ import * as HttpClientRequest from "@effect/platform/HttpClientRequest";
481
+ import * as Context from "effect/Context";
482
+ import * as Effect5 from "effect/Effect";
483
+ import * as Layer from "effect/Layer";
484
+ import * as Redacted from "effect/Redacted";
485
+ import { Query } from "@dxos/echo";
486
+ import { DatabaseService } from "@dxos/echo-db";
487
+ import { AccessToken } from "@dxos/types";
488
+ var CredentialsService = class _CredentialsService extends Context.Tag("@dxos/functions/CredentialsService")() {
489
+ static getCredential = (query) => Effect5.gen(function* () {
490
+ const credentials = yield* _CredentialsService;
491
+ return yield* Effect5.promise(() => credentials.getCredential(query));
492
+ });
493
+ static getApiKey = (query) => Effect5.gen(function* () {
494
+ const credential = yield* _CredentialsService.getCredential(query);
495
+ if (!credential.apiKey) {
496
+ throw new Error(`API key not found for service: ${query.service}`);
497
+ }
498
+ return Redacted.make(credential.apiKey);
499
+ });
500
+ static configuredLayer = (credentials) => Layer.succeed(_CredentialsService, new ConfiguredCredentialsService(credentials));
501
+ static layerConfig = (credentials) => Layer.effect(_CredentialsService, Effect5.gen(function* () {
502
+ const serviceCredentials = yield* Effect5.forEach(credentials, ({ service, apiKey }) => Effect5.gen(function* () {
503
+ return {
504
+ service,
505
+ apiKey: Redacted.value(yield* apiKey)
506
+ };
507
+ }));
508
+ return new ConfiguredCredentialsService(serviceCredentials);
509
+ }));
510
+ static layerFromDatabase = () => Layer.effect(_CredentialsService, Effect5.gen(function* () {
511
+ const dbService = yield* DatabaseService;
512
+ const queryCredentials = async (query) => {
513
+ const { objects: accessTokens } = await dbService.db.query(Query.type(AccessToken.AccessToken)).run();
514
+ return accessTokens.filter((accessToken) => accessToken.source === query.service).map((accessToken) => ({
515
+ service: accessToken.source,
516
+ apiKey: accessToken.token
517
+ }));
518
+ };
519
+ return {
520
+ getCredential: async (query) => {
521
+ const credentials = await queryCredentials(query);
522
+ if (credentials.length === 0) {
523
+ throw new Error(`Credential not found for service: ${query.service}`);
524
+ }
525
+ return credentials[0];
526
+ },
527
+ queryCredentials: async (query) => {
528
+ return queryCredentials(query);
529
+ }
530
+ };
531
+ }));
532
+ };
533
+ var ConfiguredCredentialsService = class {
534
+ credentials;
535
+ constructor(credentials = []) {
536
+ this.credentials = credentials;
537
+ }
538
+ addCredentials(credentials) {
539
+ this.credentials.push(...credentials);
540
+ return this;
541
+ }
542
+ async queryCredentials(query) {
543
+ return this.credentials.filter((credential) => credential.service === query.service);
544
+ }
545
+ async getCredential(query) {
546
+ const credential = this.credentials.find((credential2) => credential2.service === query.service);
547
+ if (!credential) {
548
+ throw new Error(`Credential not found for service: ${query.service}`);
549
+ }
550
+ return credential;
446
551
  }
447
552
  };
553
+ var withAuthorization = (query, kind) => HttpClient.mapRequestEffect(Effect5.fnUntraced(function* (request) {
554
+ const key = yield* CredentialsService.getApiKey(query).pipe(Effect5.map(Redacted.value));
555
+ const authorization = kind ? `${kind} ${key}` : key;
556
+ return HttpClientRequest.setHeader(request, "Authorization", authorization);
557
+ }));
448
558
 
449
- // src/errors.ts
450
- import { BaseError } from "@dxos/errors";
451
- var ServiceNotAvailableError = class extends BaseError.extend("SERVICE_NOT_AVAILABLE") {
452
- constructor(serviceName) {
453
- super(`Service not available: ${serviceName}`);
559
+ // src/services/event-logger.ts
560
+ import * as Context3 from "effect/Context";
561
+ import * as Effect7 from "effect/Effect";
562
+ import * as Layer3 from "effect/Layer";
563
+ import * as Schema9 from "effect/Schema";
564
+ import { Obj as Obj7, Type as Type6 } from "@dxos/echo";
565
+ import { invariant } from "@dxos/invariant";
566
+ import { LogLevel, log as log2 } from "@dxos/log";
567
+
568
+ // src/services/tracing.ts
569
+ import * as Context2 from "effect/Context";
570
+ import * as Effect6 from "effect/Effect";
571
+ import * as Layer2 from "effect/Layer";
572
+ import { AgentStatus } from "@dxos/ai";
573
+ import { Obj as Obj6 } from "@dxos/echo";
574
+ import { Message } from "@dxos/types";
575
+ var TracingService = class _TracingService extends Context2.Tag("@dxos/functions/TracingService")() {
576
+ static noop = {
577
+ getTraceContext: () => ({}),
578
+ write: () => {
579
+ }
580
+ };
581
+ static layerNoop = Layer2.succeed(_TracingService, _TracingService.noop);
582
+ /**
583
+ * Creates a TracingService layer that emits events to the parent tracing service.
584
+ */
585
+ static layerSubframe = (mapContext) => Layer2.effect(_TracingService, Effect6.gen(function* () {
586
+ const tracing = yield* _TracingService;
587
+ const context = mapContext(tracing.getTraceContext());
588
+ return {
589
+ write: (event) => tracing.write(event),
590
+ getTraceContext: () => context
591
+ };
592
+ }));
593
+ /**
594
+ * Emit the current human-readable execution status.
595
+ */
596
+ static emitStatus = Effect6.fnUntraced(function* (data) {
597
+ const tracing = yield* _TracingService;
598
+ tracing.write(Obj6.make(AgentStatus, {
599
+ parentMessage: tracing.getTraceContext().parentMessage,
600
+ toolCallId: tracing.getTraceContext().toolCallId,
601
+ created: (/* @__PURE__ */ new Date()).toISOString(),
602
+ ...data
603
+ }));
604
+ });
605
+ static emitConverationMessage = Effect6.fnUntraced(function* (data) {
606
+ const tracing = yield* _TracingService;
607
+ tracing.write(Obj6.make(Message.Message, {
608
+ parentMessage: tracing.getTraceContext().parentMessage,
609
+ ...data,
610
+ properties: {
611
+ [MESSAGE_PROPERTY_TOOL_CALL_ID]: tracing.getTraceContext().toolCallId,
612
+ ...data.properties
613
+ }
614
+ }));
615
+ });
616
+ };
617
+ var MESSAGE_PROPERTY_TOOL_CALL_ID = "toolCallId";
618
+
619
+ // src/services/event-logger.ts
620
+ var __dxlog_file = "/__w/dxos/dxos/packages/core/functions/src/services/event-logger.ts";
621
+ var ComputeEventPayload = Schema9.Union(Schema9.Struct({
622
+ type: Schema9.Literal("begin-compute"),
623
+ nodeId: Schema9.String,
624
+ /**
625
+ * Names of the inputs begin computed.
626
+ */
627
+ inputs: Schema9.Array(Schema9.String)
628
+ }), Schema9.Struct({
629
+ type: Schema9.Literal("end-compute"),
630
+ nodeId: Schema9.String,
631
+ /**
632
+ * Names of the outputs computed.
633
+ */
634
+ outputs: Schema9.Array(Schema9.String)
635
+ }), Schema9.Struct({
636
+ type: Schema9.Literal("compute-input"),
637
+ nodeId: Schema9.String,
638
+ property: Schema9.String,
639
+ value: Schema9.Any
640
+ }), Schema9.Struct({
641
+ type: Schema9.Literal("compute-output"),
642
+ nodeId: Schema9.String,
643
+ property: Schema9.String,
644
+ value: Schema9.Any
645
+ }), Schema9.Struct({
646
+ type: Schema9.Literal("custom"),
647
+ nodeId: Schema9.String,
648
+ event: Schema9.Any
649
+ }));
650
+ var ComputeEvent = Schema9.Struct({
651
+ payload: ComputeEventPayload
652
+ }).pipe(Type6.Obj({
653
+ typename: "dxos.org/type/ComputeEvent",
654
+ version: "0.1.0"
655
+ }));
656
+ var ComputeEventLogger = class _ComputeEventLogger extends Context3.Tag("@dxos/functions/ComputeEventLogger")() {
657
+ static noop = {
658
+ log: () => {
659
+ },
660
+ nodeId: void 0
661
+ };
662
+ /**
663
+ * Implements ComputeEventLogger using TracingService.
664
+ */
665
+ static layerFromTracing = Layer3.effect(_ComputeEventLogger, Effect7.gen(function* () {
666
+ const tracing = yield* TracingService;
667
+ return {
668
+ log: (event) => {
669
+ tracing.write(Obj7.make(ComputeEvent, {
670
+ payload: event
671
+ }));
672
+ },
673
+ nodeId: void 0
674
+ };
675
+ }));
676
+ };
677
+ var logCustomEvent = (data) => Effect7.gen(function* () {
678
+ const logger = yield* ComputeEventLogger;
679
+ if (!logger.nodeId) {
680
+ throw new Error("logCustomEvent must be called within a node compute function");
454
681
  }
682
+ logger.log({
683
+ type: "custom",
684
+ nodeId: logger.nodeId,
685
+ event: data
686
+ });
687
+ });
688
+ var createDefectLogger = () => Effect7.catchAll((error) => Effect7.gen(function* () {
689
+ log2.error("unhandled effect error", {
690
+ error
691
+ }, {
692
+ F: __dxlog_file,
693
+ L: 102,
694
+ S: this,
695
+ C: (f, a) => f(...a)
696
+ });
697
+ throw error;
698
+ }));
699
+ var createEventLogger = (level, message = "event") => {
700
+ const logFunction = {
701
+ [LogLevel.WARN]: log2.warn,
702
+ [LogLevel.VERBOSE]: log2.verbose,
703
+ [LogLevel.DEBUG]: log2.debug,
704
+ [LogLevel.INFO]: log2.info,
705
+ [LogLevel.ERROR]: log2.error
706
+ }[level];
707
+ invariant(logFunction, void 0, {
708
+ F: __dxlog_file,
709
+ L: 120,
710
+ S: void 0,
711
+ A: [
712
+ "logFunction",
713
+ ""
714
+ ]
715
+ });
716
+ return {
717
+ log: (event) => {
718
+ logFunction(message, event);
719
+ },
720
+ nodeId: void 0
721
+ };
722
+ };
723
+
724
+ // src/services/function-invocation-service.ts
725
+ import * as Context4 from "effect/Context";
726
+ import * as Effect8 from "effect/Effect";
727
+ var FunctionInvocationService = class _FunctionInvocationService extends Context4.Tag("@dxos/functions/FunctionInvocationService")() {
728
+ static invokeFunction = (functionDef, input) => Effect8.serviceFunctionEffect(_FunctionInvocationService, (service) => service.invokeFunction)(functionDef, input);
729
+ };
730
+
731
+ // src/services/queues.ts
732
+ import * as Context5 from "effect/Context";
733
+ import * as Effect9 from "effect/Effect";
734
+ import * as Layer4 from "effect/Layer";
735
+ var QueueService = class _QueueService extends Context5.Tag("@dxos/functions/QueueService")() {
736
+ static notAvailable = Layer4.succeed(_QueueService, {
737
+ queues: {
738
+ get(_dxn) {
739
+ throw new Error("Queues not available");
740
+ },
741
+ create() {
742
+ throw new Error("Queues not available");
743
+ }
744
+ },
745
+ queue: void 0
746
+ });
747
+ static make = (queues, queue) => {
748
+ return {
749
+ queues,
750
+ queue
751
+ };
752
+ };
753
+ static layer = (queues, queue) => Layer4.succeed(_QueueService, _QueueService.make(queues, queue));
754
+ /**
755
+ * Gets a queue by its DXN.
756
+ */
757
+ static getQueue = (dxn) => _QueueService.pipe(Effect9.map(({ queues }) => queues.get(dxn)));
758
+ /**
759
+ * Creates a new queue.
760
+ */
761
+ static createQueue = (options) => _QueueService.pipe(Effect9.map(({ queues }) => queues.create(options)));
762
+ static append = (queue, objects) => Effect9.promise(() => queue.append(objects));
455
763
  };
456
- var FunctionError = class extends BaseError.extend("FUNCTION_ERROR") {
764
+ var ContextQueueService = class _ContextQueueService extends Context5.Tag("@dxos/functions/ContextQueueService")() {
765
+ static layer = (queue) => Layer4.succeed(_ContextQueueService, {
766
+ queue
767
+ });
457
768
  };
458
769
  export {
770
+ ComputeEvent,
771
+ ComputeEventLogger,
772
+ ComputeEventPayload,
459
773
  ConfiguredCredentialsService,
460
774
  ContextQueueService,
461
775
  CredentialsService,
462
- DatabaseService,
463
- EmailTriggerOutput,
464
- EventLogger,
776
+ DatabaseService2 as DatabaseService,
777
+ Example,
778
+ FUNCTIONS_META_KEY,
465
779
  FUNCTIONS_PRESET_META_KEY,
466
- FUNCTION_TYPES,
467
- FunctionCallService,
780
+ Function_exports as Function,
781
+ FunctionDefinition,
468
782
  FunctionError,
469
- FunctionExecutor,
470
- FunctionManifestSchema,
471
- FunctionTrigger,
472
- FunctionTriggerSchema,
473
- FunctionType,
474
- InvocationOutcome,
475
- InvocationTraceEndEvent,
476
- InvocationTraceEventType,
477
- InvocationTraceStartEvent,
783
+ FunctionInvocationService,
784
+ FunctionNotFoundError,
785
+ MESSAGE_PROPERTY_TOOL_CALL_ID,
478
786
  QueueService,
479
- QueueTriggerOutput,
480
- SERVICE_TAGS,
481
- ScriptType,
482
- ServiceContainer,
787
+ Script_exports as Script,
483
788
  ServiceNotAvailableError,
484
- SubscriptionTriggerOutput,
485
- TimerTriggerOutput,
486
- TraceEvent,
487
- TraceEventException,
488
- TraceEventLog,
489
789
  TracingService,
490
- TriggerKind,
491
- TriggerSchema,
492
- WebhookTriggerOutput,
790
+ Trigger_exports as Trigger,
791
+ TriggerEvent_exports as TriggerEvent,
792
+ TriggerStateNotFoundError,
493
793
  createDefectLogger,
494
794
  createEventLogger,
495
- createInvocationSpans,
496
795
  defineFunction,
497
- getInvocationUrl,
498
- getUserFunctionUrlInMetadata,
796
+ deserializeFunction,
797
+ getUserFunctionIdInMetadata,
499
798
  logCustomEvent,
500
- makeFunctionUrl,
501
- setUserFunctionUrlInMetadata
799
+ serializeFunction,
800
+ setUserFunctionIdInMetadata,
801
+ withAuthorization
502
802
  };
503
803
  //# sourceMappingURL=index.mjs.map