@dxos/functions 0.8.4-main.dedc0f3 → 0.8.4-main.e8ec1fe

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 (190) hide show
  1. package/dist/lib/browser/index.mjs +732 -1070
  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 +732 -1070
  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 +47 -55
  8. package/dist/types/src/errors.d.ts.map +1 -1
  9. package/dist/types/src/{examples → example}/fib.d.ts +1 -1
  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/{examples → example}/reply.d.ts +1 -1
  16. package/dist/types/src/example/reply.d.ts.map +1 -0
  17. package/dist/types/src/{examples → example}/sleep.d.ts +1 -1
  18. package/dist/types/src/example/sleep.d.ts.map +1 -0
  19. package/dist/types/src/index.d.ts +4 -8
  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 +89 -0
  28. package/dist/types/src/sdk.d.ts.map +1 -0
  29. package/dist/types/src/services/credentials.d.ts +7 -3
  30. package/dist/types/src/services/credentials.d.ts.map +1 -1
  31. package/dist/types/src/services/event-logger.d.ts +20 -5
  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 +6 -6
  36. package/dist/types/src/services/index.d.ts.map +1 -1
  37. package/dist/types/src/services/queues.d.ts +3 -1
  38. package/dist/types/src/services/queues.d.ts.map +1 -1
  39. package/dist/types/src/services/tracing.d.ts +9 -12
  40. package/dist/types/src/services/tracing.d.ts.map +1 -1
  41. package/dist/types/src/types/Function.d.ts +58 -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 +139 -0
  46. package/dist/types/src/types/Trigger.d.ts.map +1 -0
  47. package/dist/types/src/types/TriggerEvent.d.ts +44 -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/{url.d.ts → types/url.d.ts} +1 -10
  52. package/dist/types/src/types/url.d.ts.map +1 -0
  53. package/dist/types/tsconfig.tsbuildinfo +1 -1
  54. package/package.json +16 -70
  55. package/src/errors.ts +9 -9
  56. package/src/{examples → example}/fib.ts +5 -3
  57. package/src/example/forex-effect.ts +40 -0
  58. package/src/example/index.ts +13 -0
  59. package/src/{examples → example}/reply.ts +6 -3
  60. package/src/{examples → example}/sleep.ts +5 -3
  61. package/src/index.ts +4 -8
  62. package/src/{executor → protocol}/index.ts +1 -1
  63. package/src/protocol/protocol.test.ts +59 -0
  64. package/src/protocol/protocol.ts +145 -0
  65. package/src/sdk.ts +226 -0
  66. package/src/services/credentials.ts +12 -6
  67. package/src/services/event-logger.ts +12 -3
  68. package/src/services/function-invocation-service.ts +23 -0
  69. package/src/services/index.ts +7 -6
  70. package/src/services/queues.ts +3 -1
  71. package/src/services/tracing.ts +24 -56
  72. package/src/{schema.ts → types/Function.ts} +20 -26
  73. package/src/types/Script.ts +33 -0
  74. package/src/types/Trigger.ts +139 -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 -265
  79. package/dist/lib/browser/bundler/index.mjs.map +0 -7
  80. package/dist/lib/browser/chunk-ANP3DFCO.mjs +0 -623
  81. package/dist/lib/browser/chunk-ANP3DFCO.mjs.map +0 -7
  82. package/dist/lib/browser/chunk-J5LGTIGS.mjs +0 -10
  83. package/dist/lib/browser/chunk-J5LGTIGS.mjs.map +0 -7
  84. package/dist/lib/browser/edge/index.mjs +0 -83
  85. package/dist/lib/browser/edge/index.mjs.map +0 -7
  86. package/dist/lib/browser/testing/index.mjs +0 -129
  87. package/dist/lib/browser/testing/index.mjs.map +0 -7
  88. package/dist/lib/node-esm/bundler/index.mjs +0 -266
  89. package/dist/lib/node-esm/bundler/index.mjs.map +0 -7
  90. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +0 -11
  91. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs.map +0 -7
  92. package/dist/lib/node-esm/chunk-MPKVY7ZR.mjs +0 -625
  93. package/dist/lib/node-esm/chunk-MPKVY7ZR.mjs.map +0 -7
  94. package/dist/lib/node-esm/edge/index.mjs +0 -84
  95. package/dist/lib/node-esm/edge/index.mjs.map +0 -7
  96. package/dist/lib/node-esm/testing/index.mjs +0 -130
  97. package/dist/lib/node-esm/testing/index.mjs.map +0 -7
  98. package/dist/types/src/bundler/bundler.d.ts +0 -49
  99. package/dist/types/src/bundler/bundler.d.ts.map +0 -1
  100. package/dist/types/src/bundler/bundler.test.d.ts +0 -2
  101. package/dist/types/src/bundler/bundler.test.d.ts.map +0 -1
  102. package/dist/types/src/bundler/index.d.ts +0 -2
  103. package/dist/types/src/bundler/index.d.ts.map +0 -1
  104. package/dist/types/src/edge/functions.d.ts +0 -17
  105. package/dist/types/src/edge/functions.d.ts.map +0 -1
  106. package/dist/types/src/edge/index.d.ts +0 -2
  107. package/dist/types/src/edge/index.d.ts.map +0 -1
  108. package/dist/types/src/examples/fib.d.ts.map +0 -1
  109. package/dist/types/src/examples/index.d.ts +0 -4
  110. package/dist/types/src/examples/index.d.ts.map +0 -1
  111. package/dist/types/src/examples/reply.d.ts.map +0 -1
  112. package/dist/types/src/examples/sleep.d.ts.map +0 -1
  113. package/dist/types/src/executor/executor.d.ts +0 -11
  114. package/dist/types/src/executor/executor.d.ts.map +0 -1
  115. package/dist/types/src/executor/index.d.ts +0 -2
  116. package/dist/types/src/executor/index.d.ts.map +0 -1
  117. package/dist/types/src/handler.d.ts +0 -94
  118. package/dist/types/src/handler.d.ts.map +0 -1
  119. package/dist/types/src/schema.d.ts +0 -43
  120. package/dist/types/src/schema.d.ts.map +0 -1
  121. package/dist/types/src/services/database.d.ts +0 -98
  122. package/dist/types/src/services/database.d.ts.map +0 -1
  123. package/dist/types/src/services/local-function-execution.d.ts +0 -25
  124. package/dist/types/src/services/local-function-execution.d.ts.map +0 -1
  125. package/dist/types/src/services/remote-function-execution-service.d.ts +0 -15
  126. package/dist/types/src/services/remote-function-execution-service.d.ts.map +0 -1
  127. package/dist/types/src/services/service-container.d.ts +0 -56
  128. package/dist/types/src/services/service-container.d.ts.map +0 -1
  129. package/dist/types/src/services/service-registry.d.ts +0 -29
  130. package/dist/types/src/services/service-registry.d.ts.map +0 -1
  131. package/dist/types/src/services/service-registry.test.d.ts +0 -2
  132. package/dist/types/src/services/service-registry.test.d.ts.map +0 -1
  133. package/dist/types/src/testing/index.d.ts +0 -3
  134. package/dist/types/src/testing/index.d.ts.map +0 -1
  135. package/dist/types/src/testing/layer.d.ts +0 -15
  136. package/dist/types/src/testing/layer.d.ts.map +0 -1
  137. package/dist/types/src/testing/logger.d.ts +0 -5
  138. package/dist/types/src/testing/logger.d.ts.map +0 -1
  139. package/dist/types/src/testing/persist-database.test.d.ts +0 -2
  140. package/dist/types/src/testing/persist-database.test.d.ts.map +0 -1
  141. package/dist/types/src/testing/services.d.ts +0 -59
  142. package/dist/types/src/testing/services.d.ts.map +0 -1
  143. package/dist/types/src/trace.d.ts +0 -122
  144. package/dist/types/src/trace.d.ts.map +0 -1
  145. package/dist/types/src/translations.d.ts +0 -12
  146. package/dist/types/src/translations.d.ts.map +0 -1
  147. package/dist/types/src/triggers/index.d.ts +0 -4
  148. package/dist/types/src/triggers/index.d.ts.map +0 -1
  149. package/dist/types/src/triggers/input-builder.d.ts +0 -3
  150. package/dist/types/src/triggers/input-builder.d.ts.map +0 -1
  151. package/dist/types/src/triggers/invocation-tracer.d.ts +0 -35
  152. package/dist/types/src/triggers/invocation-tracer.d.ts.map +0 -1
  153. package/dist/types/src/triggers/trigger-dispatcher.d.ts +0 -75
  154. package/dist/types/src/triggers/trigger-dispatcher.d.ts.map +0 -1
  155. package/dist/types/src/triggers/trigger-dispatcher.test.d.ts +0 -2
  156. package/dist/types/src/triggers/trigger-dispatcher.test.d.ts.map +0 -1
  157. package/dist/types/src/triggers/trigger-state-store.d.ts +0 -27
  158. package/dist/types/src/triggers/trigger-state-store.d.ts.map +0 -1
  159. package/dist/types/src/types.d.ts +0 -211
  160. package/dist/types/src/types.d.ts.map +0 -1
  161. package/dist/types/src/url.d.ts.map +0 -1
  162. package/src/bundler/bundler.test.ts +0 -58
  163. package/src/bundler/bundler.ts +0 -291
  164. package/src/bundler/index.ts +0 -5
  165. package/src/edge/functions.ts +0 -67
  166. package/src/edge/index.ts +0 -9
  167. package/src/examples/index.ts +0 -7
  168. package/src/executor/executor.ts +0 -54
  169. package/src/handler.ts +0 -201
  170. package/src/services/database.ts +0 -170
  171. package/src/services/local-function-execution.ts +0 -114
  172. package/src/services/remote-function-execution-service.ts +0 -46
  173. package/src/services/service-container.ts +0 -114
  174. package/src/services/service-registry.test.ts +0 -42
  175. package/src/services/service-registry.ts +0 -59
  176. package/src/testing/index.ts +0 -6
  177. package/src/testing/layer.ts +0 -111
  178. package/src/testing/logger.ts +0 -16
  179. package/src/testing/persist-database.test.ts +0 -87
  180. package/src/testing/services.ts +0 -115
  181. package/src/trace.ts +0 -178
  182. package/src/translations.ts +0 -20
  183. package/src/triggers/index.ts +0 -7
  184. package/src/triggers/input-builder.ts +0 -35
  185. package/src/triggers/invocation-tracer.ts +0 -99
  186. package/src/triggers/trigger-dispatcher.test.ts +0 -652
  187. package/src/triggers/trigger-dispatcher.ts +0 -512
  188. package/src/triggers/trigger-state-store.ts +0 -60
  189. package/src/types.ts +0 -200
  190. package/src/url.ts +0 -55
@@ -1,72 +1,86 @@
1
- import {
2
- ComputeEvent,
3
- ComputeEventLogger,
4
- ComputeEventPayload,
5
- ConfiguredCredentialsService,
6
- ContextQueueService,
7
- CredentialsService,
8
- DatabaseService,
9
- FUNCTIONS_META_KEY,
10
- FUNCTIONS_PRESET_META_KEY,
11
- MESSAGE_PROPERTY_TOOL_CALL_ID,
12
- QueueService,
13
- RemoteFunctionExecutionService,
14
- SERVICE_TAGS,
15
- ServiceContainer,
16
- TracingService,
17
- createDefectLogger,
18
- createEventLogger,
19
- getInvocationUrl,
20
- getUserFunctionIdInMetadata,
21
- logCustomEvent,
22
- setUserFunctionIdInMetadata,
23
- withAuthorization
24
- } from "./chunk-ANP3DFCO.mjs";
25
- import {
26
- __export
27
- } from "./chunk-J5LGTIGS.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
+ };
28
6
 
29
7
  // src/errors.ts
30
8
  import { BaseError } from "@dxos/errors";
31
- var ServiceNotAvailableError = class extends BaseError.extend("SERVICE_NOT_AVAILABLE") {
32
- constructor(serviceName) {
33
- super(`Service not available: ${serviceName}`);
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
+ });
34
17
  }
35
18
  };
36
- var FunctionNotFoundError = class extends BaseError.extend("FUNCTION_NOT_FOUND") {
37
- constructor(functionKey) {
38
- super(`Function not found: ${functionKey}`);
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
+ });
39
27
  }
40
28
  };
41
- var FunctionError = class extends BaseError.extend("FUNCTION_ERROR") {
29
+ var FunctionError = class extends BaseError.extend("FUNCTION_ERROR", "Function invocation error") {
42
30
  };
43
- var TriggerStateNotFoundError = class extends BaseError.extend("TRIGGER_STATE_NOT_FOUND") {
31
+ var TriggerStateNotFoundError = class extends BaseError.extend("TRIGGER_STATE_NOT_FOUND", "Trigger state not found") {
44
32
  };
45
33
 
46
- // src/handler.ts
47
- import { Effect, Schema as Schema2 } from "effect";
48
- import { Obj, Type as Type2 } from "@dxos/echo";
49
- import { assertArgument } from "@dxos/invariant";
34
+ // src/example/fib.ts
35
+ import * as Effect2 from "effect/Effect";
36
+ import * as Schema6 from "effect/Schema";
37
+
38
+ // src/sdk.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, failedInvariant } 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";
50
53
 
51
- // src/schema.ts
52
- import { Schema } from "effect";
53
- import { Type } from "@dxos/echo";
54
- import { JsonSchemaType, LabelAnnotation, Ref } from "@dxos/echo-schema";
55
- import { DataType } from "@dxos/schema";
56
- var ScriptType = Schema.Struct({
57
- name: Schema.optional(Schema.String),
58
- description: Schema.optional(Schema.String),
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),
59
67
  // TODO(burdon): Change to hash of deployed content.
60
68
  // Whether source has changed since last deploy.
61
- changed: Schema.optional(Schema.Boolean),
62
- source: Ref(DataType.Text)
69
+ changed: Schema.Boolean.pipe(FormAnnotation.set(false), Schema.optional),
70
+ source: Type.Ref(Text.Text).pipe(FormAnnotation.set(false))
63
71
  }).pipe(Type.Obj({
64
72
  typename: "dxos.org/type/Script",
65
73
  version: "0.1.0"
66
74
  }), LabelAnnotation.set([
67
75
  "name"
68
76
  ]));
69
- var FunctionType = Schema.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({
70
84
  /**
71
85
  * Global registry ID.
72
86
  * NOTE: The `key` property refers to the original registry entry.
@@ -74,165 +88,81 @@ var FunctionType = Schema.Struct({
74
88
  // TODO(burdon): Create Format type for DXN-like ids, such as this and schema type.
75
89
  // TODO(dmaretskyi): Consider making it part of ECHO meta.
76
90
  // TODO(dmaretskyi): Make required.
77
- key: Schema.optional(Schema.String).annotations({
91
+ key: Schema2.optional(Schema2.String).annotations({
78
92
  description: "Unique registration key for the blueprint"
79
93
  }),
80
94
  // TODO(burdon): Rename to id/uri?
81
- name: Schema.NonEmptyString,
82
- version: Schema.String,
83
- description: Schema.optional(Schema.String),
95
+ name: Schema2.NonEmptyString,
96
+ version: Schema2.String,
97
+ description: Schema2.optional(Schema2.String),
98
+ /**
99
+ * ISO date string of the last deployment.
100
+ */
101
+ updated: Schema2.optional(Schema2.String),
84
102
  // Reference to a source script if it exists within ECHO.
85
103
  // TODO(burdon): Don't ref ScriptType directly (core).
86
- source: Schema.optional(Ref(ScriptType)),
87
- inputSchema: Schema.optional(JsonSchemaType),
88
- outputSchema: Schema.optional(JsonSchemaType),
104
+ source: Schema2.optional(Ref2(Script)),
105
+ inputSchema: Schema2.optional(JsonSchemaType),
106
+ outputSchema: Schema2.optional(JsonSchemaType),
107
+ /**
108
+ * List of required services.
109
+ * Match the Context.Tag keys of the FunctionServices variants.
110
+ */
111
+ services: Schema2.optional(Schema2.Array(Schema2.String)),
89
112
  // Local binding to a function name.
90
- binding: Schema.optional(Schema.String)
91
- }).pipe(Type.Obj({
113
+ binding: Schema2.optional(Schema2.String)
114
+ }).pipe(Type2.Obj({
92
115
  typename: "dxos.org/type/Function",
93
116
  version: "0.1.0"
94
- }), LabelAnnotation.set([
117
+ }), LabelAnnotation2.set([
95
118
  "name"
96
119
  ]));
120
+ var make2 = (props) => Obj2.make(Function, props);
97
121
 
98
- // src/handler.ts
99
- var typeId = Symbol.for("@dxos/functions/FunctionDefinition");
100
- var defineFunction = ({ key, name, description, inputSchema, outputSchema = Schema2.Any, handler }) => {
101
- if (!Schema2.isSchema(inputSchema)) {
102
- throw new Error("Input schema must be a valid schema");
103
- }
104
- if (typeof handler !== "function") {
105
- throw new Error("Handler must be a function");
106
- }
107
- const limit = Error.stackTraceLimit;
108
- Error.stackTraceLimit = 2;
109
- const traceError = new Error();
110
- Error.stackTraceLimit = limit;
111
- let cache = false;
112
- const captureStackTrace = () => {
113
- if (cache !== false) {
114
- return cache;
115
- }
116
- if (traceError.stack !== void 0) {
117
- const stack = traceError.stack.split("\n");
118
- if (stack[2] !== void 0) {
119
- cache = stack[2].trim();
120
- return cache;
121
- }
122
- }
123
- };
124
- const handlerWithSpan = (...args) => {
125
- const result = handler(...args);
126
- if (Effect.isEffect(result)) {
127
- return Effect.withSpan(result, `${key ?? name}`, {
128
- captureStackTrace
129
- });
130
- }
131
- return result;
132
- };
133
- return {
134
- [typeId]: true,
135
- key: key ?? name,
136
- name,
137
- description,
138
- inputSchema,
139
- outputSchema,
140
- handler: handlerWithSpan
141
- };
142
- };
143
- var FunctionDefinition = {
144
- make: defineFunction,
145
- isFunction: (value) => {
146
- return typeof value === "object" && value !== null && Symbol.for("@dxos/functions/FunctionDefinition") in value;
147
- },
148
- serialize: (functionDef) => {
149
- assertArgument(FunctionDefinition.isFunction(functionDef), "functionDef");
150
- return serializeFunction(functionDef);
151
- },
152
- deserialize: (functionObj) => {
153
- assertArgument(Obj.instanceOf(FunctionType, functionObj), "functionObj");
154
- return deserializeFunction(functionObj);
155
- }
156
- };
157
- var serializeFunction = (functionDef) => Obj.make(FunctionType, {
158
- key: functionDef.name,
159
- name: functionDef.name,
160
- version: "0.1.0",
161
- description: functionDef.description,
162
- inputSchema: Type2.toJsonSchema(functionDef.inputSchema),
163
- outputSchema: !functionDef.outputSchema ? void 0 : Type2.toJsonSchema(functionDef.outputSchema)
122
+ // src/types/Trigger.ts
123
+ var Trigger_exports = {};
124
+ __export(Trigger_exports, {
125
+ EmailSpec: () => EmailSpec,
126
+ Kinds: () => Kinds,
127
+ QueueSpec: () => QueueSpec,
128
+ Spec: () => Spec,
129
+ SubscriptionSpec: () => SubscriptionSpec,
130
+ TimerSpec: () => TimerSpec,
131
+ Trigger: () => Trigger,
132
+ WebhookSpec: () => WebhookSpec,
133
+ make: () => make3
164
134
  });
165
- var deserializeFunction = (functionObj) => {
166
- return {
167
- [typeId]: true,
168
- // TODO(dmaretskyi): Fix key.
169
- key: functionObj.key ?? functionObj.name,
170
- name: functionObj.name,
171
- description: functionObj.description,
172
- inputSchema: !functionObj.inputSchema ? Schema2.Unknown : Type2.toEffectSchema(functionObj.inputSchema),
173
- outputSchema: !functionObj.outputSchema ? void 0 : Type2.toEffectSchema(functionObj.outputSchema),
174
- handler: () => {
175
- }
176
- };
177
- };
178
-
179
- // src/trace.ts
180
- import { Schema as Schema4 } from "effect";
181
- import { Type as Type4 } from "@dxos/echo";
182
- import { Queue } from "@dxos/echo-db";
183
- import { ObjectId } from "@dxos/echo-schema";
184
- import { log } from "@dxos/log";
185
-
186
- // src/types.ts
187
- import { Schema as Schema3, SchemaAST } from "effect";
188
- import { QueryAST, Type as Type3 } from "@dxos/echo";
189
- import { Expando, OptionsAnnotationId, RawObject, Ref as Ref2 } from "@dxos/echo-schema";
135
+ import * as Schema3 from "effect/Schema";
136
+ import * as SchemaAST from "effect/SchemaAST";
137
+ import { Obj as Obj3, QueryAST, Type as Type3 } from "@dxos/echo";
138
+ import { Expando, OptionsAnnotationId, Ref as Ref3 } from "@dxos/echo/internal";
190
139
  import { DXN } from "@dxos/keys";
191
- var TriggerKinds = [
192
- "timer",
193
- "webhook",
194
- "subscription",
140
+ var Kinds = [
195
141
  "email",
196
- "queue"
142
+ "queue",
143
+ "subscription",
144
+ "timer",
145
+ "webhook"
197
146
  ];
198
147
  var kindLiteralAnnotations = {
199
148
  title: "Kind"
200
149
  };
201
- var TimerTriggerSchema = Schema3.Struct({
202
- kind: Schema3.Literal("timer").annotations(kindLiteralAnnotations),
203
- cron: Schema3.String.annotations({
204
- title: "Cron",
205
- [SchemaAST.ExamplesAnnotationId]: [
206
- "0 0 * * *"
207
- ]
208
- })
209
- }).pipe(Schema3.mutable);
210
- var EmailTriggerSchema = Schema3.Struct({
150
+ var EmailSpec = Schema3.Struct({
211
151
  kind: Schema3.Literal("email").annotations(kindLiteralAnnotations)
212
152
  }).pipe(Schema3.mutable);
213
- var QueueTriggerSchema = Schema3.Struct({
153
+ var QueueSpec = Schema3.Struct({
214
154
  kind: Schema3.Literal("queue").annotations(kindLiteralAnnotations),
215
155
  // TODO(dmaretskyi): Change to a reference.
216
156
  queue: DXN.Schema
217
157
  }).pipe(Schema3.mutable);
218
- var WebhookTriggerSchema = Schema3.Struct({
219
- kind: Schema3.Literal("webhook").annotations(kindLiteralAnnotations),
220
- method: Schema3.optional(Schema3.String.annotations({
221
- title: "Method",
222
- [OptionsAnnotationId]: [
223
- "GET",
224
- "POST"
225
- ]
226
- })),
227
- port: Schema3.optional(Schema3.Number.annotations({
228
- title: "Port"
229
- }))
230
- }).pipe(Schema3.mutable);
231
- var SubscriptionTriggerSchema = Schema3.Struct({
158
+ var SubscriptionSpec = Schema3.Struct({
232
159
  kind: Schema3.Literal("subscription").annotations(kindLiteralAnnotations),
233
- query: QueryAST.Query.annotations({
234
- title: "Query"
235
- }),
160
+ query: Schema3.Struct({
161
+ raw: Schema3.optional(Schema3.String.annotations({
162
+ title: "Query"
163
+ })),
164
+ ast: QueryAST.Query
165
+ }).pipe(Schema3.mutable),
236
166
  options: Schema3.optional(Schema3.Struct({
237
167
  // Watch changes to object (not just creation).
238
168
  deep: Schema3.optional(Schema3.Boolean.annotations({
@@ -246,43 +176,37 @@ var SubscriptionTriggerSchema = Schema3.Struct({
246
176
  title: "Options"
247
177
  }))
248
178
  }).pipe(Schema3.mutable);
249
- var TriggerSchema = Schema3.Union(TimerTriggerSchema, WebhookTriggerSchema, SubscriptionTriggerSchema, EmailTriggerSchema, QueueTriggerSchema).annotations({
179
+ var TimerSpec = Schema3.Struct({
180
+ kind: Schema3.Literal("timer").annotations(kindLiteralAnnotations),
181
+ cron: Schema3.String.annotations({
182
+ title: "Cron",
183
+ [SchemaAST.ExamplesAnnotationId]: [
184
+ "0 0 * * *"
185
+ ]
186
+ })
187
+ }).pipe(Schema3.mutable);
188
+ var WebhookSpec = Schema3.Struct({
189
+ kind: Schema3.Literal("webhook").annotations(kindLiteralAnnotations),
190
+ method: Schema3.optional(Schema3.String.annotations({
191
+ title: "Method",
192
+ [OptionsAnnotationId]: [
193
+ "GET",
194
+ "POST"
195
+ ]
196
+ })),
197
+ port: Schema3.optional(Schema3.Number.annotations({
198
+ title: "Port"
199
+ }))
200
+ }).pipe(Schema3.mutable);
201
+ var Spec = Schema3.Union(EmailSpec, QueueSpec, SubscriptionSpec, TimerSpec, WebhookSpec).annotations({
250
202
  title: "Trigger"
251
203
  });
252
- var EmailTriggerOutput = Schema3.mutable(Schema3.Struct({
253
- from: Schema3.String,
254
- to: Schema3.String,
255
- subject: Schema3.String,
256
- created: Schema3.String,
257
- body: Schema3.String
258
- }));
259
- var WebhookTriggerOutput = Schema3.mutable(Schema3.Struct({
260
- url: Schema3.String,
261
- method: Schema3.Literal("GET", "POST"),
262
- headers: Schema3.Record({
263
- key: Schema3.String,
264
- value: Schema3.String
265
- }),
266
- bodyText: Schema3.String
267
- }));
268
- var QueueTriggerOutput = Schema3.mutable(Schema3.Struct({
269
- queue: DXN.Schema,
270
- item: Schema3.Any,
271
- cursor: Schema3.String
272
- }));
273
- var SubscriptionTriggerOutput = Schema3.mutable(Schema3.Struct({
274
- type: Schema3.String,
275
- changedObjectId: Schema3.String
276
- }));
277
- var TimerTriggerOutput = Schema3.mutable(Schema3.Struct({
278
- tick: Schema3.Number
279
- }));
280
- var FunctionTrigger_ = Schema3.Struct({
204
+ var Trigger_ = Schema3.Struct({
281
205
  /**
282
206
  * Function or workflow to invoke.
283
207
  */
284
208
  // TODO(dmaretskyi): Can be a Ref(FunctionType) or Ref(ComputeGraphType).
285
- function: Schema3.optional(Ref2(Expando).annotations({
209
+ function: Schema3.optional(Ref3(Expando).annotations({
286
210
  title: "Function"
287
211
  })),
288
212
  /**
@@ -296,7 +220,7 @@ var FunctionTrigger_ = Schema3.Struct({
296
220
  enabled: Schema3.optional(Schema3.Boolean.annotations({
297
221
  title: "Enabled"
298
222
  })),
299
- spec: Schema3.optional(TriggerSchema),
223
+ spec: Schema3.optional(Spec),
300
224
  /**
301
225
  * Passed as the input data to the function.
302
226
  * Must match the function's input schema.
@@ -313,852 +237,201 @@ var FunctionTrigger_ = Schema3.Struct({
313
237
  value: Schema3.Any
314
238
  })))
315
239
  }).pipe(Type3.Obj({
316
- typename: "dxos.org/type/FunctionTrigger",
317
- version: "0.2.0"
240
+ typename: "dxos.org/type/Trigger",
241
+ version: "0.1.0"
318
242
  }));
319
- var FunctionTrigger = FunctionTrigger_;
320
- var FunctionManifestSchema = Schema3.Struct({
321
- functions: Schema3.optional(Schema3.mutable(Schema3.Array(RawObject(FunctionType)))),
322
- triggers: Schema3.optional(Schema3.mutable(Schema3.Array(RawObject(FunctionTrigger))))
323
- });
324
- var FUNCTION_TYPES = [
325
- FunctionType,
326
- FunctionTrigger
327
- ];
243
+ var Trigger = Trigger_;
244
+ var make3 = (props) => Obj3.make(Trigger, props);
328
245
 
329
- // src/trace.ts
330
- var __dxlog_file = "/__w/dxos/dxos/packages/core/functions/src/trace.ts";
331
- var InvocationOutcome = /* @__PURE__ */ function(InvocationOutcome2) {
332
- InvocationOutcome2["SUCCESS"] = "success";
333
- InvocationOutcome2["FAILURE"] = "failure";
334
- InvocationOutcome2["PENDING"] = "pending";
335
- return InvocationOutcome2;
336
- }({});
337
- var InvocationTraceEventType = /* @__PURE__ */ function(InvocationTraceEventType2) {
338
- InvocationTraceEventType2["START"] = "start";
339
- InvocationTraceEventType2["END"] = "end";
340
- return InvocationTraceEventType2;
341
- }({});
342
- var TraceEventException = Schema4.Struct({
343
- timestamp: Schema4.Number,
344
- message: Schema4.String,
345
- name: Schema4.String,
346
- stack: Schema4.optional(Schema4.String)
246
+ // src/types/TriggerEvent.ts
247
+ var TriggerEvent_exports = {};
248
+ __export(TriggerEvent_exports, {
249
+ EmailEvent: () => EmailEvent,
250
+ QueueEvent: () => QueueEvent,
251
+ SubscriptionEvent: () => SubscriptionEvent,
252
+ TimerEvent: () => TimerEvent,
253
+ WebhookEvent: () => WebhookEvent
347
254
  });
348
- var InvocationTraceStartEvent = Schema4.Struct({
349
- /**
350
- * Queue message id.
351
- */
352
- id: ObjectId,
353
- type: Schema4.Literal("start"),
354
- /**
355
- * Invocation id, the same for invocation start and end events.
356
- */
357
- invocationId: ObjectId,
358
- /**
359
- * Event generation time.
360
- */
361
- timestamp: Schema4.Number,
362
- /**
363
- * Data passed to function / workflow as an argument.
364
- */
365
- // TODO(burdon): Input schema?
366
- input: Schema4.Object,
367
- /**
368
- * Queue for function/workflow invocation events.
369
- */
370
- invocationTraceQueue: Schema4.optional(Type4.Ref(Queue)),
371
- /**
372
- * DXN of the invoked function/workflow.
373
- */
374
- invocationTarget: Schema4.optional(Type4.Ref(Type4.Expando)),
375
- /**
376
- * Present for automatic invocations.
377
- */
378
- trigger: Schema4.optional(Type4.Ref(FunctionTrigger))
379
- }).pipe(Type4.Obj({
380
- typename: "dxos.org/type/InvocationTraceStart",
381
- version: "0.1.0"
255
+ import * as Schema4 from "effect/Schema";
256
+ import { DXN as DXN2, Obj as Obj4, Type as Type4 } from "@dxos/echo";
257
+ var EmailEvent = Schema4.mutable(Schema4.Struct({
258
+ from: Schema4.String,
259
+ to: Schema4.String,
260
+ subject: Schema4.String,
261
+ created: Schema4.String,
262
+ body: Schema4.String
382
263
  }));
383
- var InvocationTraceEndEvent = Schema4.Struct({
264
+ var QueueEvent = Schema4.mutable(Schema4.Struct({
265
+ queue: DXN2.Schema,
266
+ item: Schema4.Any,
267
+ cursor: Schema4.String
268
+ }));
269
+ var SubscriptionEvent = Schema4.Struct({
384
270
  /**
385
- * Trace event id.
271
+ * Type of the mutation.
386
272
  */
387
- id: ObjectId,
388
- type: Schema4.Literal("end"),
273
+ // TODO(dmaretskyi): Specify enum.
274
+ type: Schema4.String,
389
275
  /**
390
- * Invocation id, will be the same for invocation start and end.
276
+ * Reference to the object that was changed or created.
391
277
  */
392
- invocationId: ObjectId,
278
+ subject: Type4.Ref(Obj4.Any),
393
279
  /**
394
- * Event generation time.
280
+ * @deprecated
395
281
  */
396
- // TODO(burdon): Remove ms suffix.
397
- timestamp: Schema4.Number,
398
- outcome: Schema4.Enums(InvocationOutcome),
399
- exception: Schema4.optional(TraceEventException)
400
- }).pipe(Type4.Obj({
401
- typename: "dxos.org/type/InvocationTraceEnd",
402
- version: "0.1.0"
282
+ changedObjectId: Schema4.optional(Schema4.String)
283
+ }).pipe(Schema4.mutable);
284
+ var TimerEvent = Schema4.mutable(Schema4.Struct({
285
+ tick: Schema4.Number
403
286
  }));
404
- var TraceEventLog = Schema4.Struct({
405
- timestamp: Schema4.Number,
406
- level: Schema4.String,
407
- message: Schema4.String,
408
- context: Schema4.optional(Schema4.Object)
409
- });
410
- var TraceEvent = Schema4.Struct({
411
- id: ObjectId,
412
- // TODO(burdon): Need enum/numeric result (not string).
413
- outcome: Schema4.String,
414
- truncated: Schema4.Boolean,
415
- /** Time when the event was persisted. */
416
- ingestionTimestamp: Schema4.Number,
417
- logs: Schema4.Array(TraceEventLog),
418
- exceptions: Schema4.Array(TraceEventException)
419
- }).pipe(Type4.Obj({
420
- typename: "dxos.org/type/TraceEvent",
421
- version: "0.1.0"
287
+ var WebhookEvent = Schema4.mutable(Schema4.Struct({
288
+ url: Schema4.String,
289
+ method: Schema4.Literal("GET", "POST"),
290
+ headers: Schema4.Record({
291
+ key: Schema4.String,
292
+ value: Schema4.String
293
+ }),
294
+ bodyText: Schema4.String
422
295
  }));
423
- var createInvocationSpans = (items) => {
424
- if (!items) {
425
- return [];
426
- }
427
- const eventsByInvocationId = /* @__PURE__ */ new Map();
428
- for (const event of items) {
429
- if (!("invocationId" in event)) {
430
- continue;
431
- }
432
- const invocationId = event.invocationId;
433
- const entry = eventsByInvocationId.get(invocationId) || {
434
- start: void 0,
435
- end: void 0
436
- };
437
- if (event.type === "start") {
438
- entry.start = event;
439
- } else if (event.type === "end") {
440
- entry.end = event;
441
- }
442
- eventsByInvocationId.set(invocationId, entry);
443
- }
444
- const now = Date.now();
445
- const result = [];
446
- for (const [invocationId, { start, end }] of eventsByInvocationId.entries()) {
447
- if (!start) {
448
- log.warn("found end event without matching start", {
449
- invocationId
450
- }, {
451
- F: __dxlog_file,
452
- L: 158,
453
- S: void 0,
454
- C: (f, a) => f(...a)
455
- });
456
- continue;
457
- }
458
- const isInProgress = end === void 0;
459
- result.push({
460
- id: invocationId,
461
- timestamp: start.timestamp,
462
- duration: isInProgress ? now - start.timestamp : end.timestamp - start.timestamp,
463
- outcome: end?.outcome ?? "pending",
464
- exception: end?.exception,
465
- input: start.input,
466
- invocationTraceQueue: start.invocationTraceQueue,
467
- invocationTarget: start.invocationTarget,
468
- trigger: start.trigger
469
- });
470
- }
471
- return result;
472
- };
473
-
474
- // src/triggers/invocation-tracer.ts
475
- import { Context as Context2, Effect as Effect3, Layer as Layer2 } from "effect";
476
- import { Obj as Obj2, Ref as Ref3 } from "@dxos/echo";
477
- import { DXN as DXN2, ObjectId as ObjectId2 } from "@dxos/keys";
478
296
 
479
- // src/services/local-function-execution.ts
480
- import { Context, Effect as Effect2, Layer, Schema as Schema5 } from "effect";
481
- import { todo } from "@dxos/debug";
482
- function _define_property(obj, key, value) {
483
- if (key in obj) {
484
- Object.defineProperty(obj, key, {
485
- value,
486
- enumerable: true,
487
- configurable: true,
488
- writable: true
489
- });
490
- } else {
491
- obj[key] = value;
492
- }
493
- return obj;
494
- }
495
- var _Context_Tag;
496
- var LocalFunctionExecutionService = class extends (_Context_Tag = Context.Tag("@dxos/functions/LocalFunctionExecutionService")()) {
297
+ // src/types/url.ts
298
+ var FUNCTIONS_META_KEY = "dxos.org/service/function";
299
+ var FUNCTIONS_PRESET_META_KEY = "dxos.org/service/function-preset";
300
+ var getUserFunctionIdInMetadata = (meta) => {
301
+ return meta.keys.find((key) => key.source === FUNCTIONS_META_KEY)?.id;
497
302
  };
498
- _define_property(LocalFunctionExecutionService, "layer", Layer.succeed(LocalFunctionExecutionService, {
499
- invokeFunction: (functionDef, input) => invokeFunction(functionDef, input)
500
- }));
501
- _define_property(LocalFunctionExecutionService, "layerLive", Layer.effect(LocalFunctionExecutionService, Effect2.gen(function* () {
502
- const resolver = yield* FunctionImplementationResolver;
503
- return {
504
- invokeFunction: Effect2.fn("invokeFunction")(function* (functionDef, input) {
505
- const resolved = yield* resolver.resolveFunctionImplementation(functionDef).pipe(Effect2.orDie);
506
- return yield* invokeFunction(resolved, input);
507
- })
508
- };
509
- })));
510
- _define_property(LocalFunctionExecutionService, "invokeFunction", Effect2.serviceFunctionEffect(LocalFunctionExecutionService, (_) => _.invokeFunction));
511
- var invokeFunction = (functionDef, input) => Effect2.gen(function* () {
512
- const assertInput = functionDef.inputSchema.pipe(Schema5.asserts);
513
- assertInput(input);
514
- const context = {
515
- space: void 0,
516
- getService: () => todo(),
517
- getSpace: async (_spaceId) => {
518
- throw new Error("Not available. Use the database service instead.");
303
+ var setUserFunctionIdInMetadata = (meta, functionId) => {
304
+ const key = meta.keys.find((key2) => key2.source === FUNCTIONS_META_KEY);
305
+ if (key) {
306
+ if (key.id !== functionId) {
307
+ throw new Error("Metadata mismatch");
519
308
  }
520
- };
521
- const data = yield* Effect2.gen(function* () {
522
- const result = functionDef.handler({
523
- context,
524
- data: input
309
+ } else {
310
+ meta.keys.push({
311
+ source: FUNCTIONS_META_KEY,
312
+ id: functionId
525
313
  });
526
- if (Effect2.isEffect(result)) {
527
- return yield* result.pipe(Effect2.orDie);
528
- } else if (typeof result === "object" && result !== null && "then" in result && typeof result.then === "function") {
529
- return yield* Effect2.promise(() => result);
530
- } else {
531
- return result;
532
- }
533
- }).pipe(Effect2.orDie, Effect2.catchAllDefect((defect) => Effect2.die(new FunctionError("Error running function", {
534
- context: {
535
- name: functionDef.name
536
- },
537
- cause: defect
538
- }))));
539
- const assertOutput = functionDef.outputSchema?.pipe(Schema5.asserts);
540
- assertOutput(data);
541
- return data;
542
- }).pipe(Effect2.withSpan("invokeFunction", {
543
- attributes: {
544
- name: functionDef.name
545
314
  }
546
- }));
547
- var _Context_Tag1;
548
- var FunctionImplementationResolver = class extends (_Context_Tag1 = Context.Tag("@dxos/functions/FunctionImplementationResolver")()) {
549
315
  };
550
- _define_property(FunctionImplementationResolver, "layerTest", ({ functions }) => Layer.succeed(FunctionImplementationResolver, {
551
- resolveFunctionImplementation: (functionDef) => {
552
- const resolved = functions.find((f) => f.name === functionDef.name);
553
- if (!resolved) {
554
- return Effect2.fail(new FunctionNotFoundError(functionDef.name));
555
- }
556
- return Effect2.succeed(resolved);
557
- }
558
- }));
559
316
 
560
- // src/triggers/invocation-tracer.ts
561
- function _define_property2(obj, key, value) {
562
- if (key in obj) {
563
- Object.defineProperty(obj, key, {
564
- value,
565
- enumerable: true,
566
- configurable: true,
567
- writable: true
568
- });
569
- } else {
570
- obj[key] = value;
317
+ // src/sdk.ts
318
+ var typeId = Symbol.for("@dxos/functions/FunctionDefinition");
319
+ var defineFunction = ({ key, name, description, inputSchema, outputSchema = Schema5.Any, handler, services }) => {
320
+ if (!Schema5.isSchema(inputSchema)) {
321
+ throw new Error("Input schema must be a valid schema");
571
322
  }
572
- return obj;
573
- }
574
- var _Context_Tag2;
575
- var InvocationTracer = class extends (_Context_Tag2 = Context2.Tag("@dxos/functions/InvocationTracer")()) {
576
- };
577
- _define_property2(InvocationTracer, "layerLive", (opts) => Layer2.effect(InvocationTracer, Effect3.gen(function* () {
578
- return {
579
- traceInvocationStart: Effect3.fn("traceInvocationStart")(function* ({ payload, target }) {
580
- const invocationId = ObjectId2.random();
581
- const invocationTraceQueue = yield* QueueService.createQueue({
582
- subspaceTag: "trace"
583
- });
584
- const now = Date.now();
585
- const traceEvent = Obj2.make(InvocationTraceStartEvent, {
586
- type: InvocationTraceEventType.START,
587
- invocationId,
588
- timestamp: now,
589
- // TODO(dmaretskyi): Not json-stringifying this makes ECHO fail when one ECHO object becomes embedded in another ECHO object.
590
- input: JSON.parse(JSON.stringify(payload.data ?? {})),
591
- invocationTraceQueue: Ref3.fromDXN(invocationTraceQueue.dxn),
592
- invocationTarget: target ? Ref3.fromDXN(target) : void 0,
593
- trigger: payload.trigger ? Ref3.fromDXN(DXN2.fromLocalObjectId(payload.trigger.id)) : void 0
594
- });
595
- yield* QueueService.append(opts.invocationTraceQueue, [
596
- traceEvent
597
- ]);
598
- return {
599
- invocationId,
600
- invocationTraceQueue
601
- };
602
- }),
603
- traceInvocationEnd: Effect3.fn("traceInvocationEnd")(function* ({ trace, exception }) {
604
- const now = Date.now();
605
- const traceEvent = Obj2.make(InvocationTraceEndEvent, {
606
- type: InvocationTraceEventType.END,
607
- invocationId: trace.invocationId,
608
- timestamp: now,
609
- outcome: exception ? InvocationOutcome.FAILURE : InvocationOutcome.SUCCESS,
610
- exception: exception ? {
611
- name: exception.constructor.name,
612
- timestamp: now,
613
- message: exception?.message ?? "Unknown error",
614
- stack: exception?.stack
615
- } : void 0
616
- });
617
- yield* QueueService.append(opts.invocationTraceQueue, [
618
- traceEvent
619
- ]);
620
- })
621
- };
622
- })));
623
- _define_property2(InvocationTracer, "layerTest", Layer2.unwrapEffect(Effect3.gen(function* () {
624
- const queue = yield* QueueService.createQueue({
625
- subspaceTag: "trace"
626
- });
627
- return InvocationTracer.layerLive({
628
- invocationTraceQueue: queue
629
- });
630
- })));
631
-
632
- // src/triggers/trigger-dispatcher.ts
633
- import { Cause, Context as Context4, Cron, Duration, Effect as Effect5, Either, Exit, Fiber, Layer as Layer4, Option as Option2, Record, Schedule } from "effect";
634
- import { DXN as DXN3, Filter, Obj as Obj3, Query } from "@dxos/echo";
635
- import { causeToError } from "@dxos/effect";
636
- import { invariant } from "@dxos/invariant";
637
- import { log as log2 } from "@dxos/log";
638
- import { KEY_QUEUE_POSITION } from "@dxos/protocols";
639
-
640
- // src/triggers/input-builder.ts
641
- var createInvocationPayload = (trigger, event) => {
642
- if (!trigger.input) {
643
- return event;
323
+ if (typeof handler !== "function") {
324
+ throw new Error("Handler must be a function");
644
325
  }
645
- const payload = {};
646
- for (const [key, value] of Object.entries(trigger.input)) {
647
- if (typeof value !== "string" || !(value.startsWith("{{") && value.endsWith("}}"))) {
648
- payload[key] = value;
649
- continue;
326
+ const limit = Error.stackTraceLimit;
327
+ Error.stackTraceLimit = 2;
328
+ const traceError = new Error();
329
+ Error.stackTraceLimit = limit;
330
+ let cache = false;
331
+ const captureStackTrace = () => {
332
+ if (cache !== false) {
333
+ return cache;
650
334
  }
651
- const propertyPath = value.slice(2, -2);
652
- let valueSubstitution = propertyPath.startsWith("trigger.") ? trigger : propertyPath.startsWith("event.") ? event : void 0;
653
- for (const pathSegment of propertyPath.split(".").slice(1)) {
654
- if (valueSubstitution && typeof valueSubstitution === "object") {
655
- valueSubstitution = valueSubstitution[pathSegment];
335
+ if (traceError.stack !== void 0) {
336
+ const stack = traceError.stack.split("\n");
337
+ if (stack[2] !== void 0) {
338
+ cache = stack[2].trim();
339
+ return cache;
656
340
  }
657
341
  }
658
- payload[key] = valueSubstitution;
659
- }
660
- return payload;
342
+ };
343
+ const handlerWithSpan = (...args) => {
344
+ const result = handler(...args);
345
+ if (Effect.isEffect(result)) {
346
+ return Effect.withSpan(result, `${key ?? name}`, {
347
+ captureStackTrace
348
+ });
349
+ }
350
+ return result;
351
+ };
352
+ return {
353
+ [typeId]: true,
354
+ key,
355
+ name,
356
+ description,
357
+ inputSchema,
358
+ outputSchema,
359
+ handler: handlerWithSpan,
360
+ services: !services ? [] : getServiceKeys(services)
361
+ };
661
362
  };
662
-
663
- // src/triggers/trigger-state-store.ts
664
- import { KeyValueStore } from "@effect/platform";
665
- import { Context as Context3 } from "effect";
666
- import { Schema as Schema6 } from "effect";
667
- import { Effect as Effect4, Layer as Layer3 } from "effect";
668
- import { Option } from "effect";
669
- import { ObjectId as ObjectId3 } from "@dxos/keys";
670
- function _define_property3(obj, key, value) {
671
- if (key in obj) {
672
- Object.defineProperty(obj, key, {
673
- value,
674
- enumerable: true,
675
- configurable: true,
676
- writable: true
677
- });
678
- } else {
679
- obj[key] = value;
680
- }
681
- return obj;
682
- }
683
- var TriggerState = Schema6.Struct({
684
- version: Schema6.Literal("1"),
685
- triggerId: Schema6.String,
686
- state: Schema6.optional(Schema6.Union(Schema6.TaggedStruct("subscription", {
687
- processedVersions: Schema6.Record({
688
- key: ObjectId3,
689
- value: Schema6.String
690
- })
691
- })))
692
- });
693
- var _Context_Tag3;
694
- var TriggerStateStore = class extends (_Context_Tag3 = Context3.Tag("@dxos/functions/TriggerStateStore")()) {
363
+ var getServiceKeys = (services) => {
364
+ return services.map((tag) => {
365
+ if (typeof tag.key === "string") {
366
+ return tag.key;
367
+ }
368
+ console.log(tag);
369
+ failedInvariant();
370
+ });
695
371
  };
696
- _define_property3(TriggerStateStore, "getState", Effect4.serviceFunctionEffect(TriggerStateStore, (_) => _.getState));
697
- _define_property3(TriggerStateStore, "saveState", Effect4.serviceFunctionEffect(TriggerStateStore, (_) => _.saveState));
698
- _define_property3(TriggerStateStore, "layerKv", Layer3.effect(TriggerStateStore, Effect4.gen(function* () {
699
- const kv = yield* KeyValueStore.KeyValueStore;
700
- const schemaStore = kv.forSchema(Schema6.parseJson(TriggerState));
701
- const store = {
702
- getState: Effect4.fn("TriggerStateStore.getState")(function* (triggerId) {
703
- const valueOption = yield* schemaStore.get(triggerId).pipe(Effect4.orDie);
704
- if (Option.isNone(valueOption)) {
705
- return yield* Effect4.fail(new TriggerStateNotFoundError("Trigger state not found"));
706
- }
707
- return valueOption.value;
708
- }),
709
- saveState: Effect4.fn("TriggerStateStore.saveState")(function* (state) {
710
- yield* schemaStore.set(state.triggerId, state).pipe(Effect4.orDie);
711
- })
712
- };
713
- return store;
714
- })));
715
- _define_property3(TriggerStateStore, "layerMemory", TriggerStateStore.layerKv.pipe(Layer3.provide(KeyValueStore.layerMemory)));
716
-
717
- // src/triggers/trigger-dispatcher.ts
718
- function _define_property4(obj, key, value) {
719
- if (key in obj) {
720
- Object.defineProperty(obj, key, {
721
- value,
722
- enumerable: true,
723
- configurable: true,
724
- writable: true
725
- });
726
- } else {
727
- obj[key] = value;
372
+ var FunctionDefinition = {
373
+ make: defineFunction,
374
+ isFunction: (value2) => {
375
+ return typeof value2 === "object" && value2 !== null && Symbol.for("@dxos/functions/FunctionDefinition") in value2;
376
+ },
377
+ serialize: (functionDef) => {
378
+ assertArgument(FunctionDefinition.isFunction(functionDef), "functionDef");
379
+ return serializeFunction(functionDef);
380
+ },
381
+ deserialize: (functionObj) => {
382
+ assertArgument(Obj5.instanceOf(Function_exports.Function, functionObj), "functionObj");
383
+ return deserializeFunction(functionObj);
728
384
  }
729
- return obj;
730
- }
731
- var __dxlog_file2 = "/__w/dxos/dxos/packages/core/functions/src/triggers/trigger-dispatcher.ts";
732
- var _Context_Tag4;
733
- var TriggerDispatcher = class extends (_Context_Tag4 = Context4.Tag("@dxos/functions/TriggerDispatcher")()) {
734
385
  };
735
- _define_property4(TriggerDispatcher, "layer", (options) => Layer4.effect(TriggerDispatcher, Effect5.gen(function* () {
736
- return new TriggerDispatcherImpl(options);
737
- })));
738
- var TriggerDispatcherImpl = class {
739
- get running() {
740
- return this._running;
741
- }
742
- constructor(options) {
743
- _define_property4(this, "livePollInterval", void 0);
744
- _define_property4(this, "timeControl", void 0);
745
- _define_property4(this, "_running", false);
746
- _define_property4(this, "_internalTime", void 0);
747
- _define_property4(this, "_timerFiber", void 0);
748
- _define_property4(this, "_scheduledTriggers", /* @__PURE__ */ new Map());
749
- _define_property4(this, "start", () => Effect5.gen(this, function* () {
750
- if (this._running) {
751
- return;
752
- }
753
- this._running = true;
754
- if (this.timeControl === "natural") {
755
- this._timerFiber = yield* this._startNaturalTimeProcessing().pipe(Effect5.tapErrorCause((cause) => {
756
- const error = causeToError(cause);
757
- log2.error("trigger dispatcher error", {
758
- error
759
- }, {
760
- F: __dxlog_file2,
761
- L: 170,
762
- S: this,
763
- C: (f, a) => f(...a)
764
- });
765
- this._running = false;
766
- return Effect5.void;
767
- }), Effect5.forkDaemon);
768
- } else {
769
- return yield* Effect5.dieMessage("TriggerDispatcher started in manual time control mode");
770
- }
771
- log2.info("TriggerDispatcher started", {
772
- timeControl: this.timeControl
773
- }, {
774
- F: __dxlog_file2,
775
- L: 180,
776
- S: this,
777
- C: (f, a) => f(...a)
778
- });
779
- }));
780
- _define_property4(this, "stop", () => Effect5.gen(this, function* () {
781
- if (!this._running) {
782
- return;
783
- }
784
- this._running = false;
785
- if (this._timerFiber) {
786
- yield* Fiber.interrupt(this._timerFiber);
787
- this._timerFiber = void 0;
788
- }
789
- this._scheduledTriggers.clear();
790
- log2.info("TriggerDispatcher stopped", void 0, {
791
- F: __dxlog_file2,
792
- L: 200,
793
- S: this,
794
- C: (f, a) => f(...a)
795
- });
796
- }));
797
- _define_property4(this, "invokeTrigger", (options2) => Effect5.gen(this, function* () {
798
- const { trigger, event } = options2;
799
- log2.info("running trigger", {
800
- triggerId: trigger.id,
801
- spec: trigger.spec,
802
- event
803
- }, {
804
- F: __dxlog_file2,
805
- L: 208,
806
- S: this,
807
- C: (f, a) => f(...a)
808
- });
809
- const tracer = yield* InvocationTracer;
810
- const trace = yield* tracer.traceInvocationStart({
811
- target: trigger.function?.dxn,
812
- payload: {
813
- trigger: {
814
- id: trigger.id,
815
- // TODO(dmaretskyi): Is `spec` always there>
816
- kind: trigger.spec.kind
817
- },
818
- data: event
819
- }
820
- });
821
- const result = yield* Effect5.gen(this, function* () {
822
- if (!trigger.enabled) {
823
- return yield* Effect5.dieMessage("Attempting to invoke disabled trigger");
824
- }
825
- if (!trigger.function) {
826
- return yield* Effect5.dieMessage("Trigger has no function reference");
827
- }
828
- const serialiedFunction = yield* DatabaseService.load(trigger.function).pipe(Effect5.orDie);
829
- invariant(Obj3.instanceOf(FunctionType, serialiedFunction), void 0, {
830
- F: __dxlog_file2,
831
- L: 235,
832
- S: this,
833
- A: [
834
- "Obj.instanceOf(FunctionType, serialiedFunction)",
835
- ""
836
- ]
837
- });
838
- const functionDef = deserializeFunction(serialiedFunction);
839
- const inputData = this._prepareInputData(trigger, event);
840
- return yield* LocalFunctionExecutionService.invokeFunction(functionDef, inputData).pipe(Effect5.provide(ComputeEventLogger.layerFromTracing.pipe(Layer4.provideMerge(TracingService.layerQueue(trace.invocationTraceQueue)))));
841
- }).pipe(Effect5.exit);
842
- const triggerExecutionResult = {
843
- triggerId: trigger.id,
844
- result
845
- };
846
- if (Exit.isSuccess(result)) {
847
- log2.info("trigger execution success", {
848
- triggerId: trigger.id
849
- }, {
850
- F: __dxlog_file2,
851
- L: 256,
852
- S: this,
853
- C: (f, a) => f(...a)
854
- });
855
- } else {
856
- log2.error("trigger execution failure", {
857
- error: causeToError(result.cause)
858
- }, {
859
- F: __dxlog_file2,
860
- L: 260,
861
- S: this,
862
- C: (f, a) => f(...a)
863
- });
864
- }
865
- yield* tracer.traceInvocationEnd({
866
- trace,
867
- // TODO(dmaretskyi): Might miss errors.
868
- exception: Exit.isFailure(result) ? Cause.prettyErrors(result.cause)[0] : void 0
869
- });
870
- return triggerExecutionResult;
871
- }));
872
- _define_property4(this, "invokeScheduledTriggers", ({ kinds = [
873
- "timer",
874
- "queue",
875
- "subscription"
876
- ] } = {}) => Effect5.gen(this, function* () {
877
- const invocations = [];
878
- for (const kind of kinds) {
879
- switch (kind) {
880
- case "timer":
881
- {
882
- yield* this.refreshTriggers();
883
- const now = this.getCurrentTime();
884
- const triggersToInvoke = [];
885
- for (const [triggerId, scheduledTrigger] of this._scheduledTriggers.entries()) {
886
- if (scheduledTrigger.nextExecution <= now) {
887
- triggersToInvoke.push(scheduledTrigger.trigger);
888
- scheduledTrigger.nextExecution = Cron.next(scheduledTrigger.cron, now);
889
- }
890
- }
891
- invocations.push(...yield* Effect5.forEach(triggersToInvoke, (trigger) => this.invokeTrigger({
892
- trigger,
893
- event: {
894
- tick: now.getTime()
895
- }
896
- }), {
897
- concurrency: 1
898
- }));
899
- }
900
- break;
901
- case "queue": {
902
- const triggers = yield* this._fetchTriggers();
903
- for (const trigger of triggers) {
904
- const spec = trigger.spec;
905
- if (spec?.kind !== "queue") {
906
- continue;
907
- }
908
- const cursor = Obj3.getKeys(trigger, KEY_QUEUE_CURSOR).at(0)?.id;
909
- const queue = yield* QueueService.getQueue(DXN3.parse(spec.queue));
910
- const objects = yield* Effect5.promise(() => queue.queryObjects());
911
- for (const object of objects) {
912
- const objectPos = Obj3.getKeys(object, KEY_QUEUE_POSITION).at(0)?.id;
913
- if (!objectPos || cursor && parseInt(cursor) >= parseInt(objectPos)) {
914
- continue;
915
- }
916
- invocations.push(yield* this.invokeTrigger({
917
- trigger,
918
- event: {
919
- queue: spec.queue,
920
- item: object,
921
- cursor: objectPos
922
- }
923
- }));
924
- Obj3.deleteKeys(trigger, KEY_QUEUE_CURSOR);
925
- Obj3.getMeta(trigger).keys.push({
926
- source: KEY_QUEUE_CURSOR,
927
- id: objectPos
928
- });
929
- yield* DatabaseService.flush();
930
- break;
931
- }
932
- }
933
- break;
934
- }
935
- case "subscription": {
936
- const triggers = yield* this._fetchTriggers();
937
- for (const trigger of triggers) {
938
- const spec = Obj3.getSnapshot(trigger).spec;
939
- if (spec?.kind !== "subscription") {
940
- continue;
941
- }
942
- const { objects } = yield* DatabaseService.runQuery(Query.fromAst(spec.query));
943
- const state = yield* TriggerStateStore.getState(trigger.id).pipe(Effect5.catchTag("TRIGGER_STATE_NOT_FOUND", () => Effect5.succeed({
944
- version: "1",
945
- triggerId: trigger.id,
946
- state: {
947
- _tag: "subscription",
948
- processedVersions: {}
949
- }
950
- })));
951
- invariant(state.state?._tag === "subscription", void 0, {
952
- F: __dxlog_file2,
953
- L: 373,
954
- S: this,
955
- A: [
956
- "state.state?._tag === 'subscription'",
957
- ""
958
- ]
959
- });
960
- let updated = false;
961
- for (const object of objects) {
962
- const existingVersion = Record.get(state.state.processedVersions, object.id).pipe(Option2.map(Obj3.decodeVersion));
963
- const currentVersion = Obj3.version(object);
964
- const run = Option2.isNone(existingVersion) || Obj3.compareVersions(currentVersion, existingVersion.value) === "different";
965
- if (!run) {
966
- continue;
967
- }
968
- invocations.push(yield* this.invokeTrigger({
969
- trigger,
970
- event: {
971
- // TODO(dmaretskyi): Change type not supported.
972
- type: "unknown",
973
- changedObjectId: object.id
974
- }
975
- }));
976
- state.state.processedVersions[object.id] = Obj3.encodeVersion(currentVersion);
977
- updated = true;
978
- }
979
- if (updated) {
980
- yield* TriggerStateStore.saveState(state);
981
- }
982
- }
983
- break;
984
- }
985
- default: {
986
- return yield* Effect5.dieMessage(`Unknown trigger kind: ${kind}`);
987
- }
988
- }
989
- }
990
- return invocations;
991
- }));
992
- _define_property4(this, "advanceTime", (duration) => Effect5.gen(this, function* () {
993
- if (this.timeControl !== "manual") {
994
- return yield* Effect5.dieMessage("advanceTime can only be used in manual time control mode");
995
- }
996
- const millis = Duration.toMillis(duration);
997
- this._internalTime = new Date(this._internalTime.getTime() + millis);
998
- log2("Advanced internal time", {
999
- newTime: this._internalTime,
1000
- advancedBy: Duration.format(duration)
1001
- }, {
1002
- F: __dxlog_file2,
1003
- L: 426,
1004
- S: this,
1005
- C: (f, a) => f(...a)
1006
- });
1007
- }).pipe(Effect5.orDie));
1008
- _define_property4(this, "getCurrentTime", () => {
1009
- if (this.timeControl === "natural") {
1010
- return /* @__PURE__ */ new Date();
1011
- } else {
1012
- return new Date(this._internalTime);
1013
- }
1014
- });
1015
- _define_property4(this, "refreshTriggers", () => Effect5.gen(this, function* () {
1016
- const triggers = yield* this._fetchTriggers();
1017
- const currentTriggerIds = new Set(triggers.map((t) => t.id));
1018
- for (const triggerId of this._scheduledTriggers.keys()) {
1019
- if (!currentTriggerIds.has(triggerId)) {
1020
- this._scheduledTriggers.delete(triggerId);
1021
- }
1022
- }
1023
- for (const trigger of triggers) {
1024
- if (trigger.spec?.kind === "timer" && trigger.enabled) {
1025
- const timerSpec = trigger.spec;
1026
- const cronEither = Cron.parse(timerSpec.cron);
1027
- if (Either.isRight(cronEither)) {
1028
- const cron = cronEither.right;
1029
- const existing = this._scheduledTriggers.get(trigger.id);
1030
- const now = this.getCurrentTime();
1031
- const nextExecution = existing?.nextExecution ?? Cron.next(cron, now);
1032
- log2("Updated scheduled trigger", {
1033
- triggerId: trigger.id,
1034
- cron: timerSpec.cron,
1035
- nextExecution,
1036
- now
1037
- }, {
1038
- F: __dxlog_file2,
1039
- L: 466,
1040
- S: this,
1041
- C: (f, a) => f(...a)
1042
- });
1043
- this._scheduledTriggers.set(trigger.id, {
1044
- trigger,
1045
- cron,
1046
- nextExecution
1047
- });
1048
- } else {
1049
- log2.error("Invalid cron expression", {
1050
- triggerId: trigger.id,
1051
- cron: timerSpec.cron,
1052
- error: cronEither.left.message
1053
- }, {
1054
- F: __dxlog_file2,
1055
- L: 478,
1056
- S: this,
1057
- C: (f, a) => f(...a)
1058
- });
1059
- }
1060
- }
1061
- }
1062
- log2("Updated scheduled triggers", {
1063
- count: this._scheduledTriggers.size
1064
- }, {
1065
- F: __dxlog_file2,
1066
- L: 487,
1067
- S: this,
1068
- C: (f, a) => f(...a)
1069
- });
1070
- }).pipe(Effect5.withSpan("TriggerDispatcher.refreshTriggers")));
1071
- _define_property4(this, "_fetchTriggers", () => Effect5.gen(this, function* () {
1072
- const { objects } = yield* DatabaseService.runQuery(Filter.type(FunctionTrigger));
1073
- return objects;
1074
- }).pipe(Effect5.withSpan("TriggerDispatcher.fetchTriggers")));
1075
- _define_property4(this, "_startNaturalTimeProcessing", () => Effect5.gen(this, function* () {
1076
- yield* this.invokeScheduledTriggers();
1077
- }).pipe(Effect5.repeat(Schedule.fixed(this.livePollInterval)), Effect5.asVoid));
1078
- _define_property4(this, "_prepareInputData", (trigger, event) => {
1079
- return createInvocationPayload(trigger, event);
1080
- });
1081
- this.timeControl = options.timeControl;
1082
- this.livePollInterval = options.livePollInterval ?? Duration.seconds(1);
1083
- this._internalTime = options.startingTime ?? /* @__PURE__ */ new Date();
386
+ var serializeFunction = (functionDef) => {
387
+ const fn4 = Function_exports.make({
388
+ key: functionDef.key,
389
+ name: functionDef.name,
390
+ version: "0.1.0",
391
+ description: functionDef.description,
392
+ inputSchema: Type5.toJsonSchema(functionDef.inputSchema),
393
+ outputSchema: !functionDef.outputSchema ? void 0 : Type5.toJsonSchema(functionDef.outputSchema),
394
+ services: functionDef.services
395
+ });
396
+ if (functionDef.meta?.deployedFunctionId) {
397
+ setUserFunctionIdInMetadata(Obj5.getMeta(fn4), functionDef.meta.deployedFunctionId);
1084
398
  }
399
+ return fn4;
1085
400
  };
1086
- var KEY_QUEUE_CURSOR = "dxos.org/key/local-trigger-dispatcher/queue-cursor";
1087
-
1088
- // src/executor/executor.ts
1089
- import { Effect as Effect6, Schema as Schema7 } from "effect";
1090
- import { runAndForwardErrors } from "@dxos/effect";
1091
- function _define_property5(obj, key, value) {
1092
- if (key in obj) {
1093
- Object.defineProperty(obj, key, {
1094
- value,
1095
- enumerable: true,
1096
- configurable: true,
1097
- writable: true
1098
- });
1099
- } else {
1100
- obj[key] = value;
1101
- }
1102
- return obj;
1103
- }
1104
- var FunctionExecutor = class {
1105
- /**
1106
- * Invoke function.
1107
- */
1108
- // TODO(dmaretskyi): Invocation context: queue, space, etc...
1109
- async invoke(functionDef, input) {
1110
- const assertInput = functionDef.inputSchema.pipe(Schema7.asserts);
1111
- assertInput(input);
1112
- const context = {
1113
- space: void 0,
1114
- getService: this._services.getService.bind(this._services),
1115
- getSpace: async (_spaceId) => {
1116
- throw new Error("Not available. Use the database service instead.");
1117
- }
1118
- };
1119
- const result = functionDef.handler({
1120
- context,
1121
- data: input
1122
- });
1123
- let data;
1124
- if (Effect6.isEffect(result)) {
1125
- data = await result.pipe(Effect6.provide(this._services.createLayer()), runAndForwardErrors);
1126
- } else {
1127
- data = await result;
401
+ var deserializeFunction = (functionObj) => {
402
+ return {
403
+ [typeId]: true,
404
+ // TODO(dmaretskyi): Fix key.
405
+ key: functionObj.key ?? functionObj.name,
406
+ name: functionObj.name,
407
+ description: functionObj.description,
408
+ inputSchema: !functionObj.inputSchema ? Schema5.Unknown : Type5.toEffectSchema(functionObj.inputSchema),
409
+ outputSchema: !functionObj.outputSchema ? void 0 : Type5.toEffectSchema(functionObj.outputSchema),
410
+ // TODO(dmaretskyi): This should throw error.
411
+ handler: () => {
412
+ },
413
+ services: functionObj.services ?? [],
414
+ meta: {
415
+ deployedFunctionId: getUserFunctionIdInMetadata(Obj5.getMeta(functionObj))
1128
416
  }
1129
- const assertOutput = functionDef.outputSchema?.pipe(Schema7.asserts);
1130
- assertOutput(data);
1131
- return data;
1132
- }
1133
- constructor(_services) {
1134
- _define_property5(this, "_services", void 0);
1135
- this._services = _services;
1136
- }
417
+ };
1137
418
  };
1138
419
 
1139
- // src/examples/index.ts
1140
- var examples_exports = {};
1141
- __export(examples_exports, {
1142
- fib: () => fib_default,
1143
- reply: () => reply_default,
1144
- sleep: () => sleep_default
1145
- });
1146
-
1147
- // src/examples/fib.ts
1148
- import { Effect as Effect7, Schema as Schema8 } from "effect";
420
+ // src/example/fib.ts
1149
421
  var fib_default = defineFunction({
1150
- name: "example.org/function/fib",
422
+ key: "example.org/function/fib",
423
+ name: "Fibonacci",
1151
424
  description: "Function that calculates a Fibonacci number",
1152
- inputSchema: Schema8.Struct({
1153
- iterations: Schema8.optional(Schema8.Number).annotations({
425
+ inputSchema: Schema6.Struct({
426
+ iterations: Schema6.optional(Schema6.Number).annotations({
1154
427
  description: "Number of iterations",
1155
428
  default: 1e5
1156
429
  })
1157
430
  }),
1158
- outputSchema: Schema8.Struct({
1159
- result: Schema8.String
431
+ outputSchema: Schema6.Struct({
432
+ result: Schema6.String
1160
433
  }),
1161
- handler: Effect7.fn(function* ({ data: { iterations = 1e5 } }) {
434
+ handler: Effect2.fn(function* ({ data: { iterations = 1e5 } }) {
1162
435
  let a = 0n;
1163
436
  let b = 1n;
1164
437
  for (let i = 0; i < iterations; i++) {
@@ -1171,14 +444,17 @@ var fib_default = defineFunction({
1171
444
  })
1172
445
  });
1173
446
 
1174
- // src/examples/reply.ts
1175
- import { Console, Effect as Effect8, Schema as Schema9 } from "effect";
447
+ // src/example/reply.ts
448
+ import * as Console from "effect/Console";
449
+ import * as Effect3 from "effect/Effect";
450
+ import * as Schema7 from "effect/Schema";
1176
451
  var reply_default = defineFunction({
1177
- name: "example.org/function/reply",
452
+ key: "example.org/function/reply",
453
+ name: "Reply",
1178
454
  description: "Function that echoes the input",
1179
- inputSchema: Schema9.Any,
1180
- outputSchema: Schema9.Any,
1181
- handler: Effect8.fn(function* ({ data }) {
455
+ inputSchema: Schema7.Any,
456
+ outputSchema: Schema7.Any,
457
+ handler: Effect3.fn(function* ({ data }) {
1182
458
  yield* Console.log("reply", {
1183
459
  data
1184
460
  });
@@ -1186,22 +462,433 @@ var reply_default = defineFunction({
1186
462
  })
1187
463
  });
1188
464
 
1189
- // src/examples/sleep.ts
1190
- import { Effect as Effect9, Schema as Schema10 } from "effect";
465
+ // src/example/sleep.ts
466
+ import * as Effect4 from "effect/Effect";
467
+ import * as Schema8 from "effect/Schema";
1191
468
  var sleep_default = defineFunction({
1192
- name: "example.org/function/sleep",
469
+ key: "example.org/function/sleep",
470
+ name: "Sleep",
1193
471
  description: "Function that sleeps for a given amount of time",
1194
- inputSchema: Schema10.Struct({
1195
- duration: Schema10.optional(Schema10.Number).annotations({
472
+ inputSchema: Schema8.Struct({
473
+ duration: Schema8.optional(Schema8.Number).annotations({
1196
474
  description: "Milliseconds to sleep",
1197
475
  default: 1e5
1198
476
  })
1199
477
  }),
1200
- outputSchema: Schema10.Void,
1201
- handler: Effect9.fn(function* ({ data: { duration = 1e5 } }) {
1202
- yield* Effect9.sleep(duration);
478
+ outputSchema: Schema8.Void,
479
+ handler: Effect4.fn(function* ({ data: { duration = 1e5 } }) {
480
+ yield* Effect4.sleep(duration);
1203
481
  })
1204
482
  });
483
+
484
+ // src/example/index.ts
485
+ (function(Example2) {
486
+ Example2.fib = fib_default;
487
+ Example2.reply = reply_default;
488
+ Example2.sleep = sleep_default;
489
+ })(Example || (Example = {}));
490
+ var Example;
491
+
492
+ // src/services/index.ts
493
+ import { DatabaseService as DatabaseService2 } from "@dxos/echo-db";
494
+
495
+ // src/services/credentials.ts
496
+ import * as HttpClient from "@effect/platform/HttpClient";
497
+ import * as HttpClientRequest from "@effect/platform/HttpClientRequest";
498
+ import * as Context from "effect/Context";
499
+ import * as Effect5 from "effect/Effect";
500
+ import * as Layer from "effect/Layer";
501
+ import * as Redacted from "effect/Redacted";
502
+ import { Query } from "@dxos/echo";
503
+ import { DatabaseService } from "@dxos/echo-db";
504
+ import { AccessToken } from "@dxos/types";
505
+ var CredentialsService = class _CredentialsService extends Context.Tag("@dxos/functions/CredentialsService")() {
506
+ static getCredential = (query) => Effect5.gen(function* () {
507
+ const credentials = yield* _CredentialsService;
508
+ return yield* Effect5.promise(() => credentials.getCredential(query));
509
+ });
510
+ static getApiKey = (query) => Effect5.gen(function* () {
511
+ const credential = yield* _CredentialsService.getCredential(query);
512
+ if (!credential.apiKey) {
513
+ throw new Error(`API key not found for service: ${query.service}`);
514
+ }
515
+ return Redacted.make(credential.apiKey);
516
+ });
517
+ static configuredLayer = (credentials) => Layer.succeed(_CredentialsService, new ConfiguredCredentialsService(credentials));
518
+ static layerConfig = (credentials) => Layer.effect(_CredentialsService, Effect5.gen(function* () {
519
+ const serviceCredentials = yield* Effect5.forEach(credentials, ({ service, apiKey }) => Effect5.gen(function* () {
520
+ return {
521
+ service,
522
+ apiKey: Redacted.value(yield* apiKey)
523
+ };
524
+ }));
525
+ return new ConfiguredCredentialsService(serviceCredentials);
526
+ }));
527
+ static layerFromDatabase = () => Layer.effect(_CredentialsService, Effect5.gen(function* () {
528
+ const dbService = yield* DatabaseService;
529
+ const queryCredentials = async (query) => {
530
+ const { objects: accessTokens } = await dbService.db.query(Query.type(AccessToken.AccessToken)).run();
531
+ return accessTokens.filter((accessToken) => accessToken.source === query.service).map((accessToken) => ({
532
+ service: accessToken.source,
533
+ apiKey: accessToken.token
534
+ }));
535
+ };
536
+ return {
537
+ getCredential: async (query) => {
538
+ const credentials = await queryCredentials(query);
539
+ if (credentials.length === 0) {
540
+ throw new Error(`Credential not found for service: ${query.service}`);
541
+ }
542
+ return credentials[0];
543
+ },
544
+ queryCredentials: async (query) => {
545
+ return queryCredentials(query);
546
+ }
547
+ };
548
+ }));
549
+ };
550
+ var ConfiguredCredentialsService = class {
551
+ credentials;
552
+ constructor(credentials = []) {
553
+ this.credentials = credentials;
554
+ }
555
+ addCredentials(credentials) {
556
+ this.credentials.push(...credentials);
557
+ return this;
558
+ }
559
+ async queryCredentials(query) {
560
+ return this.credentials.filter((credential) => credential.service === query.service);
561
+ }
562
+ async getCredential(query) {
563
+ const credential = this.credentials.find((credential2) => credential2.service === query.service);
564
+ if (!credential) {
565
+ throw new Error(`Credential not found for service: ${query.service}`);
566
+ }
567
+ return credential;
568
+ }
569
+ };
570
+ var withAuthorization = (query, kind) => HttpClient.mapRequestEffect(Effect5.fnUntraced(function* (request) {
571
+ const key = yield* CredentialsService.getApiKey(query).pipe(Effect5.map(Redacted.value));
572
+ const authorization = kind ? `${kind} ${key}` : key;
573
+ return HttpClientRequest.setHeader(request, "Authorization", authorization);
574
+ }));
575
+
576
+ // src/services/event-logger.ts
577
+ import * as Context3 from "effect/Context";
578
+ import * as Effect7 from "effect/Effect";
579
+ import * as Layer3 from "effect/Layer";
580
+ import * as Schema9 from "effect/Schema";
581
+ import { Obj as Obj7, Type as Type6 } from "@dxos/echo";
582
+ import { invariant } from "@dxos/invariant";
583
+ import { LogLevel, log as log2 } from "@dxos/log";
584
+
585
+ // src/services/tracing.ts
586
+ import * as Context2 from "effect/Context";
587
+ import * as Effect6 from "effect/Effect";
588
+ import * as Layer2 from "effect/Layer";
589
+ import { AgentStatus } from "@dxos/ai";
590
+ import { Obj as Obj6 } from "@dxos/echo";
591
+ import { Message } from "@dxos/types";
592
+ var TracingService = class _TracingService extends Context2.Tag("@dxos/functions/TracingService")() {
593
+ static noop = {
594
+ getTraceContext: () => ({}),
595
+ write: () => {
596
+ }
597
+ };
598
+ static layerNoop = Layer2.succeed(_TracingService, _TracingService.noop);
599
+ /**
600
+ * Creates a TracingService layer that emits events to the parent tracing service.
601
+ */
602
+ static layerSubframe = (mapContext) => Layer2.effect(_TracingService, Effect6.gen(function* () {
603
+ const tracing = yield* _TracingService;
604
+ const context = mapContext(tracing.getTraceContext());
605
+ return {
606
+ write: (event) => tracing.write(event),
607
+ getTraceContext: () => context
608
+ };
609
+ }));
610
+ /**
611
+ * Emit the current human-readable execution status.
612
+ */
613
+ static emitStatus = Effect6.fnUntraced(function* (data) {
614
+ const tracing = yield* _TracingService;
615
+ tracing.write(Obj6.make(AgentStatus, {
616
+ parentMessage: tracing.getTraceContext().parentMessage,
617
+ toolCallId: tracing.getTraceContext().toolCallId,
618
+ created: (/* @__PURE__ */ new Date()).toISOString(),
619
+ ...data
620
+ }));
621
+ });
622
+ static emitConverationMessage = Effect6.fnUntraced(function* (data) {
623
+ const tracing = yield* _TracingService;
624
+ tracing.write(Obj6.make(Message.Message, {
625
+ parentMessage: tracing.getTraceContext().parentMessage,
626
+ ...data,
627
+ properties: {
628
+ [MESSAGE_PROPERTY_TOOL_CALL_ID]: tracing.getTraceContext().toolCallId,
629
+ ...data.properties
630
+ }
631
+ }));
632
+ });
633
+ };
634
+ var MESSAGE_PROPERTY_TOOL_CALL_ID = "toolCallId";
635
+
636
+ // src/services/event-logger.ts
637
+ var __dxlog_file = "/__w/dxos/dxos/packages/core/functions/src/services/event-logger.ts";
638
+ var ComputeEventPayload = Schema9.Union(Schema9.Struct({
639
+ type: Schema9.Literal("begin-compute"),
640
+ nodeId: Schema9.String,
641
+ /**
642
+ * Names of the inputs begin computed.
643
+ */
644
+ inputs: Schema9.Array(Schema9.String)
645
+ }), Schema9.Struct({
646
+ type: Schema9.Literal("end-compute"),
647
+ nodeId: Schema9.String,
648
+ /**
649
+ * Names of the outputs computed.
650
+ */
651
+ outputs: Schema9.Array(Schema9.String)
652
+ }), Schema9.Struct({
653
+ type: Schema9.Literal("compute-input"),
654
+ nodeId: Schema9.String,
655
+ property: Schema9.String,
656
+ value: Schema9.Any
657
+ }), Schema9.Struct({
658
+ type: Schema9.Literal("compute-output"),
659
+ nodeId: Schema9.String,
660
+ property: Schema9.String,
661
+ value: Schema9.Any
662
+ }), Schema9.Struct({
663
+ type: Schema9.Literal("custom"),
664
+ nodeId: Schema9.String,
665
+ event: Schema9.Any
666
+ }));
667
+ var ComputeEvent = Schema9.Struct({
668
+ payload: ComputeEventPayload
669
+ }).pipe(Type6.Obj({
670
+ typename: "dxos.org/type/ComputeEvent",
671
+ version: "0.1.0"
672
+ }));
673
+ var ComputeEventLogger = class _ComputeEventLogger extends Context3.Tag("@dxos/functions/ComputeEventLogger")() {
674
+ static noop = {
675
+ log: () => {
676
+ },
677
+ nodeId: void 0
678
+ };
679
+ /**
680
+ * Implements ComputeEventLogger using TracingService.
681
+ */
682
+ static layerFromTracing = Layer3.effect(_ComputeEventLogger, Effect7.gen(function* () {
683
+ const tracing = yield* TracingService;
684
+ return {
685
+ log: (event) => {
686
+ tracing.write(Obj7.make(ComputeEvent, {
687
+ payload: event
688
+ }));
689
+ },
690
+ nodeId: void 0
691
+ };
692
+ }));
693
+ };
694
+ var logCustomEvent = (data) => Effect7.gen(function* () {
695
+ const logger = yield* ComputeEventLogger;
696
+ if (!logger.nodeId) {
697
+ throw new Error("logCustomEvent must be called within a node compute function");
698
+ }
699
+ logger.log({
700
+ type: "custom",
701
+ nodeId: logger.nodeId,
702
+ event: data
703
+ });
704
+ });
705
+ var createDefectLogger = () => Effect7.catchAll((error) => Effect7.gen(function* () {
706
+ log2.error("unhandled effect error", {
707
+ error
708
+ }, {
709
+ F: __dxlog_file,
710
+ L: 102,
711
+ S: this,
712
+ C: (f, a) => f(...a)
713
+ });
714
+ throw error;
715
+ }));
716
+ var createEventLogger = (level, message = "event") => {
717
+ const logFunction = {
718
+ [LogLevel.WARN]: log2.warn,
719
+ [LogLevel.VERBOSE]: log2.verbose,
720
+ [LogLevel.DEBUG]: log2.debug,
721
+ [LogLevel.INFO]: log2.info,
722
+ [LogLevel.ERROR]: log2.error
723
+ }[level];
724
+ invariant(logFunction, void 0, {
725
+ F: __dxlog_file,
726
+ L: 120,
727
+ S: void 0,
728
+ A: [
729
+ "logFunction",
730
+ ""
731
+ ]
732
+ });
733
+ return {
734
+ log: (event) => {
735
+ logFunction(message, event);
736
+ },
737
+ nodeId: void 0
738
+ };
739
+ };
740
+
741
+ // src/services/function-invocation-service.ts
742
+ import * as Context4 from "effect/Context";
743
+ import * as Effect8 from "effect/Effect";
744
+ var FunctionInvocationService = class _FunctionInvocationService extends Context4.Tag("@dxos/functions/FunctionInvocationService")() {
745
+ static invokeFunction = (functionDef, input) => Effect8.serviceFunctionEffect(_FunctionInvocationService, (service) => service.invokeFunction)(functionDef, input);
746
+ };
747
+
748
+ // src/services/queues.ts
749
+ import * as Context5 from "effect/Context";
750
+ import * as Effect9 from "effect/Effect";
751
+ import * as Layer4 from "effect/Layer";
752
+ var QueueService = class _QueueService extends Context5.Tag("@dxos/functions/QueueService")() {
753
+ static notAvailable = Layer4.succeed(_QueueService, {
754
+ queues: {
755
+ get(_dxn) {
756
+ throw new Error("Queues not available");
757
+ },
758
+ create() {
759
+ throw new Error("Queues not available");
760
+ }
761
+ },
762
+ queue: void 0
763
+ });
764
+ static make = (queues, queue) => {
765
+ return {
766
+ queues,
767
+ queue
768
+ };
769
+ };
770
+ static layer = (queues, queue) => Layer4.succeed(_QueueService, _QueueService.make(queues, queue));
771
+ /**
772
+ * Gets a queue by its DXN.
773
+ */
774
+ static getQueue = (dxn) => _QueueService.pipe(Effect9.map(({ queues }) => queues.get(dxn)));
775
+ /**
776
+ * Creates a new queue.
777
+ */
778
+ static createQueue = (options) => _QueueService.pipe(Effect9.map(({ queues }) => queues.create(options)));
779
+ static append = (queue, objects) => Effect9.promise(() => queue.append(objects));
780
+ };
781
+ var ContextQueueService = class _ContextQueueService extends Context5.Tag("@dxos/functions/ContextQueueService")() {
782
+ static layer = (queue) => Layer4.succeed(_ContextQueueService, {
783
+ queue
784
+ });
785
+ };
786
+
787
+ // src/protocol/protocol.ts
788
+ import * as Effect10 from "effect/Effect";
789
+ import * as Layer5 from "effect/Layer";
790
+ import * as Schema10 from "effect/Schema";
791
+ import * as SchemaAST2 from "effect/SchemaAST";
792
+ import { AiService } from "@dxos/ai";
793
+ import { Type as Type7 } from "@dxos/echo";
794
+ import { EchoClient } from "@dxos/echo-db";
795
+ import { acquireReleaseResource } from "@dxos/effect";
796
+ import { failedInvariant as failedInvariant2, invariant as invariant2 } from "@dxos/invariant";
797
+ import { PublicKey } from "@dxos/keys";
798
+ var __dxlog_file2 = "/__w/dxos/dxos/packages/core/functions/src/protocol/protocol.ts";
799
+ var wrapFunctionHandler = (func) => {
800
+ if (!FunctionDefinition.isFunction(func)) {
801
+ throw new TypeError("Invalid function definition");
802
+ }
803
+ return {
804
+ meta: {
805
+ key: func.key,
806
+ name: func.name,
807
+ description: func.description,
808
+ inputSchema: Type7.toJsonSchema(func.inputSchema),
809
+ outputSchema: func.outputSchema === void 0 ? void 0 : Type7.toJsonSchema(func.outputSchema),
810
+ services: func.services
811
+ },
812
+ handler: async ({ data, context }) => {
813
+ if ((func.services.includes(DatabaseService2.key) || func.services.includes(QueueService.key)) && (!context.services.dataService || !context.services.queryService)) {
814
+ throw new FunctionError({
815
+ message: "Services not provided: dataService, queryService"
816
+ });
817
+ }
818
+ try {
819
+ if (!SchemaAST2.isAnyKeyword(func.inputSchema.ast)) {
820
+ Schema10.validateSync(func.inputSchema)(data);
821
+ }
822
+ let result = await func.handler({
823
+ // TODO(dmaretskyi): Fix the types.
824
+ context,
825
+ data
826
+ });
827
+ if (Effect10.isEffect(result)) {
828
+ result = await Effect10.runPromise(result.pipe(Effect10.orDie, Effect10.provide(createServiceLayer(context))));
829
+ }
830
+ if (func.outputSchema && !SchemaAST2.isAnyKeyword(func.outputSchema.ast)) {
831
+ Schema10.validateSync(func.outputSchema)(result);
832
+ }
833
+ return result;
834
+ } catch (error) {
835
+ if (FunctionError.is(error)) {
836
+ throw error;
837
+ } else {
838
+ throw new FunctionError({
839
+ cause: error,
840
+ context: {
841
+ func: func.key
842
+ }
843
+ });
844
+ }
845
+ }
846
+ }
847
+ };
848
+ };
849
+ var createServiceLayer = (context) => {
850
+ return Layer5.unwrapScoped(Effect10.gen(function* () {
851
+ let client;
852
+ if (context.services.dataService && context.services.queryService) {
853
+ client = yield* acquireReleaseResource(() => {
854
+ invariant2(context.services.dataService && context.services.queryService, void 0, {
855
+ F: __dxlog_file2,
856
+ L: 99,
857
+ S: this,
858
+ A: [
859
+ "context.services.dataService && context.services.queryService",
860
+ ""
861
+ ]
862
+ });
863
+ return new EchoClient().connectToService({
864
+ dataService: context.services.dataService,
865
+ queryService: context.services.queryService,
866
+ queueService: context.services.queueService
867
+ });
868
+ });
869
+ }
870
+ const db = client && context.spaceId ? yield* acquireReleaseResource(() => client.constructDatabase({
871
+ spaceId: context.spaceId ?? failedInvariant2(),
872
+ spaceKey: PublicKey.fromHex(context.spaceKey ?? failedInvariant2("spaceKey missing in context")),
873
+ reactiveSchemaQuery: false
874
+ })) : void 0;
875
+ if (db) {
876
+ console.log("Setting space root", context.spaceRootUrl);
877
+ yield* Effect10.promise(() => db.setSpaceRoot(context.spaceRootUrl ?? failedInvariant2("spaceRootUrl missing in context")));
878
+ }
879
+ const queues = client && context.spaceId ? client.constructQueueFactory(context.spaceId) : void 0;
880
+ const dbLayer = db ? DatabaseService2.layer(db) : DatabaseService2.notAvailable;
881
+ const queuesLayer = queues ? QueueService.layer(queues) : QueueService.notAvailable;
882
+ const credentials = dbLayer ? CredentialsService.layerFromDatabase().pipe(Layer5.provide(dbLayer)) : CredentialsService.configuredLayer([]);
883
+ const functionInvocationService = MockedFunctionInvocationService;
884
+ const aiService = AiService.notAvailable;
885
+ const tracing = TracingService.layerNoop;
886
+ return Layer5.mergeAll(dbLayer, queuesLayer, credentials, functionInvocationService, aiService, tracing);
887
+ }));
888
+ };
889
+ var MockedFunctionInvocationService = Layer5.succeed(FunctionInvocationService, {
890
+ invokeFunction: () => Effect10.die("Calling functions from functions is not implemented yet.")
891
+ });
1205
892
  export {
1206
893
  ComputeEvent,
1207
894
  ComputeEventLogger,
@@ -1209,57 +896,32 @@ export {
1209
896
  ConfiguredCredentialsService,
1210
897
  ContextQueueService,
1211
898
  CredentialsService,
1212
- DatabaseService,
1213
- EmailTriggerOutput,
899
+ DatabaseService2 as DatabaseService,
900
+ Example,
1214
901
  FUNCTIONS_META_KEY,
1215
902
  FUNCTIONS_PRESET_META_KEY,
1216
- FUNCTION_TYPES,
903
+ Function_exports as Function,
1217
904
  FunctionDefinition,
1218
905
  FunctionError,
1219
- FunctionExecutor,
1220
- FunctionImplementationResolver,
1221
- FunctionManifestSchema,
906
+ FunctionInvocationService,
1222
907
  FunctionNotFoundError,
1223
- FunctionTrigger,
1224
- FunctionType,
1225
- InvocationOutcome,
1226
- InvocationTraceEndEvent,
1227
- InvocationTraceEventType,
1228
- InvocationTraceStartEvent,
1229
- InvocationTracer,
1230
- LocalFunctionExecutionService,
1231
908
  MESSAGE_PROPERTY_TOOL_CALL_ID,
1232
909
  QueueService,
1233
- QueueTriggerOutput,
1234
- RemoteFunctionExecutionService,
1235
- SERVICE_TAGS,
1236
- ScriptType,
1237
- ServiceContainer,
910
+ Script_exports as Script,
1238
911
  ServiceNotAvailableError,
1239
- SubscriptionTriggerOutput,
1240
- TimerTriggerOutput,
1241
- TraceEvent,
1242
- TraceEventException,
1243
- TraceEventLog,
1244
912
  TracingService,
1245
- TriggerDispatcher,
1246
- TriggerKinds,
1247
- TriggerSchema,
1248
- TriggerState,
913
+ Trigger_exports as Trigger,
914
+ TriggerEvent_exports as TriggerEvent,
1249
915
  TriggerStateNotFoundError,
1250
- TriggerStateStore,
1251
- WebhookTriggerOutput,
1252
916
  createDefectLogger,
1253
917
  createEventLogger,
1254
- createInvocationSpans,
1255
918
  defineFunction,
1256
919
  deserializeFunction,
1257
- examples_exports as exampleFunctions,
1258
- getInvocationUrl,
1259
920
  getUserFunctionIdInMetadata,
1260
921
  logCustomEvent,
1261
922
  serializeFunction,
1262
923
  setUserFunctionIdInMetadata,
1263
- withAuthorization
924
+ withAuthorization,
925
+ wrapFunctionHandler
1264
926
  };
1265
927
  //# sourceMappingURL=index.mjs.map