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