@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,291 +0,0 @@
1
- //
2
- // Copyright 2023 DXOS.org
3
- //
4
-
5
- import { FetchHttpClient, HttpClient } from '@effect/platform';
6
- import { Duration, Effect, Schedule, pipe } from 'effect';
7
- import { type BuildOptions, type BuildResult, type Loader, type Plugin, build, initialize } from 'esbuild-wasm';
8
-
9
- import { subtleCrypto } from '@dxos/crypto';
10
- import { runAndForwardErrors } from '@dxos/effect';
11
- import { invariant } from '@dxos/invariant';
12
- import { log } from '@dxos/log';
13
-
14
- export type Import = {
15
- moduleUrl: string;
16
- defaultImport: boolean;
17
- namedImports: string[];
18
- };
19
-
20
- export type BundleOptions = {
21
- /**
22
- * Source code to bundle.
23
- */
24
- source: string;
25
- };
26
-
27
- export type BundleResult =
28
- | {
29
- timestamp: number;
30
- sourceHash: Buffer;
31
- error: unknown;
32
- }
33
- | {
34
- timestamp: number;
35
- sourceHash: Buffer;
36
- imports: Import[];
37
- entryPoint: string;
38
- asset: Uint8Array;
39
- bundle: string;
40
- };
41
-
42
- export type BundlerOptions = {
43
- platform: BuildOptions['platform'];
44
- sandboxedModules: string[];
45
- remoteModules: Record<string, string>;
46
- };
47
-
48
- let initialized: Promise<void>;
49
- export const initializeBundler = async (options: { wasmUrl: string }) => {
50
- await (initialized ??= initialize({
51
- wasmURL: options.wasmUrl,
52
- }));
53
- };
54
-
55
- /**
56
- * ESBuild bundler.
57
- */
58
- export class Bundler {
59
- constructor(private readonly _options: BundlerOptions) {}
60
-
61
- async bundle({ source }: BundleOptions): Promise<BundleResult> {
62
- const { sandboxedModules: providedModules, ...options } = this._options;
63
- const sourceHash = Buffer.from(await subtleCrypto.digest('SHA-256', Buffer.from(source)));
64
-
65
- if (this._options.platform === 'browser') {
66
- invariant(initialized, 'Compiler not initialized.');
67
- await initialized;
68
- }
69
-
70
- const imports = source ? analyzeSourceFileImports(source) : [];
71
-
72
- // https://esbuild.github.io/api/#build
73
- try {
74
- const result = await build({
75
- platform: options.platform,
76
- conditions: ['workerd', 'browser'],
77
- metafile: true,
78
- write: false,
79
- entryPoints: {
80
- // Gets mapped to `userFunc.js` by esbuild.
81
- userFunc: 'memory:main.tsx',
82
- },
83
- bundle: true,
84
- format: 'esm',
85
- plugins: [
86
- {
87
- name: 'memory',
88
- setup: (build) => {
89
- build.onResolve({ filter: /^\.\/runtime\.js$/ }, ({ path }) => {
90
- return { path, external: true };
91
- });
92
-
93
- build.onResolve({ filter: /^dxos:functions$/ }, ({ path }) => {
94
- return { path: './runtime.js', external: true };
95
- });
96
-
97
- build.onResolve({ filter: /^memory:/ }, ({ path }) => {
98
- return { path: path.split(':')[1], namespace: 'memory' };
99
- });
100
-
101
- build.onLoad({ filter: /.*/, namespace: 'memory' }, ({ path }) => {
102
- if (path === 'main.tsx') {
103
- return {
104
- contents: source,
105
- loader: 'tsx',
106
- };
107
- }
108
- });
109
-
110
- for (const module of providedModules) {
111
- build.onResolve({ filter: new RegExp(`^${module}$`) }, ({ path }) => {
112
- return { path, namespace: 'injected-module' };
113
- });
114
- }
115
-
116
- build.onLoad({ filter: /.*/, namespace: 'injected-module' }, ({ path }) => {
117
- const namedImports = imports.find((entry) => entry.moduleIdentifier === path)?.namedImports ?? [];
118
- return {
119
- contents: `
120
- const { ${namedImports.join(',')} } = window.__DXOS_SANDBOX_MODULES__[${JSON.stringify(path)}];
121
- export { ${namedImports.join(',')} };
122
- export default window.__DXOS_SANDBOX_MODULES__[${JSON.stringify(path)}].default;
123
- `,
124
- loader: 'tsx',
125
- };
126
- });
127
- },
128
- },
129
- httpPlugin,
130
- ],
131
- });
132
-
133
- log('compile complete', result.metafile);
134
-
135
- const entryPoint = 'userFunc.js';
136
- return {
137
- timestamp: Date.now(),
138
- sourceHash,
139
- imports: this.analyzeImports(result),
140
- entryPoint,
141
- asset: result.outputFiles![0].contents,
142
- bundle: result.outputFiles![0].text,
143
- };
144
- } catch (err) {
145
- return { timestamp: Date.now(), sourceHash, error: err };
146
- }
147
- }
148
-
149
- // TODO(dmaretskyi): In the future we can replace the compiler with SWC with plugins running in WASM.
150
- analyzeImports(result: BuildResult): Import[] {
151
- invariant(result.outputFiles);
152
-
153
- // TODO(dmaretskyi): Support import aliases and wildcard imports.
154
- const parsedImports = allMatches(IMPORT_REGEX, result.outputFiles[0].text);
155
- return Object.values(result.metafile!.outputs)[0].imports.map((entry): Import => {
156
- const namedImports: string[] = [];
157
- const parsedImport = parsedImports.find((capture) => capture?.[4] === entry.path);
158
- if (parsedImport?.[2]) {
159
- NAMED_IMPORTS_REGEX.lastIndex = 0;
160
- const namedImportsMatch = NAMED_IMPORTS_REGEX.exec(parsedImport[2]);
161
- if (namedImportsMatch) {
162
- namedImportsMatch[1].split(',').forEach((importName) => {
163
- namedImports.push(importName.trim());
164
- });
165
- }
166
- }
167
-
168
- return {
169
- moduleUrl: entry.path,
170
- defaultImport: !!parsedImport?.[1],
171
- namedImports,
172
- };
173
- });
174
- }
175
-
176
- analyzeSourceFileImports(code: string): {
177
- defaultImportName: string;
178
- namedImports: string[];
179
- wildcardImportName: string;
180
- moduleIdentifier: string;
181
- quotes: string;
182
- }[] {
183
- // TODO(dmaretskyi): Support import aliases and wildcard imports.
184
- const parsedImports = allMatches(IMPORT_REGEX, code);
185
- return parsedImports.map((capture) => {
186
- return {
187
- defaultImportName: capture[1],
188
- namedImports: capture[2]?.split(',').map((importName) => importName.trim()),
189
- wildcardImportName: capture[3],
190
- moduleIdentifier: capture[4],
191
- quotes: capture[5],
192
- };
193
- });
194
- }
195
- }
196
-
197
- // https://regex101.com/r/FEN5ks/1
198
- // https://stackoverflow.com/a/73265022
199
- // $1 = default import name (can be non-existent)
200
- // $2 = destructured exports (can be non-existent)
201
- // $3 = wildcard import name (can be non-existent)
202
- // $4 = module identifier
203
- // $5 = quotes used (either ' or ")
204
- const IMPORT_REGEX =
205
- /import(?:(?:(?:[ \n\t]+([^ *\n\t{},]+)[ \n\t]*(?:,|[ \n\t]+))?([ \n\t]*{(?:[ \n\t]*[^ \n\t"'{}]+[ \n\t]*,?)+})?[ \n\t]*)|[ \n\t]*\*[ \n\t]*as[ \n\t]+([^ \n\t{}]+)[ \n\t]+)from[ \n\t]*(?:['"])([^'"\n]+)(['"])/gm;
206
-
207
- const NAMED_IMPORTS_REGEX = /[ \n\t]*{((?:[ \n\t]*[^ \n\t"'{}]+[ \n\t]*,?)+)}[ \n\t]*/gm;
208
-
209
- const allMatches = (regex: RegExp, str: string) => {
210
- let match;
211
- const matches = [];
212
- regex.lastIndex = 0;
213
- while ((match = regex.exec(str))) {
214
- matches.push(match);
215
- }
216
-
217
- return matches;
218
- };
219
-
220
- type ParsedImport = {
221
- defaultImportName?: string;
222
- namedImports: string[];
223
- wildcardImportName?: string;
224
- moduleIdentifier: string;
225
- quotes: string;
226
- };
227
-
228
- const analyzeSourceFileImports = (code: string): ParsedImport[] => {
229
- // TODO(dmaretskyi): Support import aliases and wildcard imports.
230
- const parsedImports = allMatches(IMPORT_REGEX, code);
231
- return parsedImports.map((capture) => {
232
- return {
233
- defaultImportName: capture[1],
234
- namedImports: capture[2]
235
- ?.trim()
236
- .slice(1, -1)
237
- .split(',')
238
- .map((importName) => importName.trim()),
239
- wildcardImportName: capture[3],
240
- moduleIdentifier: capture[4],
241
- quotes: capture[5],
242
- };
243
- });
244
- };
245
-
246
- const MAX_RETRIES = 5;
247
- const INITIAL_DELAY = 1_000;
248
-
249
- const httpPlugin: Plugin = {
250
- name: 'http',
251
- setup: (build) => {
252
- // Intercept import paths starting with "http:" and "https:" so esbuild doesn't attempt to map them to a file system location.
253
- // Tag them with the "http-url" namespace to associate them with this plugin.
254
- build.onResolve({ filter: /^https?:\/\// }, (args) => ({
255
- path: args.path,
256
- namespace: 'http-url',
257
- }));
258
-
259
- // We also want to intercept all import paths inside downloaded files and resolve them against the original URL.
260
- // All of these files will be in the "http-url" namespace.
261
- // Make sure to keep the newly resolved URL in the "http-url" namespace so imports inside it will also be resolved as URLs recursively.
262
- build.onResolve({ filter: /.*/, namespace: 'http-url' }, (args) => ({
263
- path: new URL(args.path, args.importer).toString(),
264
- namespace: 'http-url',
265
- }));
266
-
267
- // When a URL is loaded, we want to actually download the content from the internet.
268
- // This has just enough logic to be able to handle the example import from unpkg.com but in reality this would probably need to be more complex.
269
- build.onLoad({ filter: /.*/, namespace: 'http-url' }, async (args) => {
270
- return Effect.gen(function* () {
271
- const response = yield* HttpClient.get(args.path);
272
- if (response.status !== 200) {
273
- throw new Error(`failed to fetch: ${response.status}`);
274
- }
275
-
276
- const text = yield* response.text;
277
- return { contents: text, loader: 'jsx' as Loader };
278
- }).pipe(
279
- Effect.retry(
280
- pipe(
281
- Schedule.exponential(Duration.millis(INITIAL_DELAY)),
282
- Schedule.jittered,
283
- Schedule.intersect(Schedule.recurs(MAX_RETRIES - 1)),
284
- ),
285
- ),
286
- Effect.provide(FetchHttpClient.layer),
287
- runAndForwardErrors,
288
- );
289
- });
290
- },
291
- };
@@ -1,5 +0,0 @@
1
- //
2
- // Copyright 2023 DXOS.org
3
- //
4
-
5
- export * from './bundler';
@@ -1,67 +0,0 @@
1
- //
2
- // Copyright 2024 DXOS.org
3
- //
4
-
5
- import { type DID } from 'iso-did/types';
6
-
7
- import { type Client } from '@dxos/client';
8
- import { createEdgeIdentity } from '@dxos/client/edge';
9
- import { EdgeHttpClient } from '@dxos/edge-client';
10
- import { invariant } from '@dxos/invariant';
11
- import { type PublicKey } from '@dxos/keys';
12
- import { log } from '@dxos/log';
13
- import { type UploadFunctionResponseBody } from '@dxos/protocols';
14
-
15
- export type UploadWorkerArgs = {
16
- client: Client;
17
- version: string;
18
- name?: string;
19
- functionId?: string;
20
- ownerPublicKey: PublicKey;
21
- entryPoint: string;
22
- assets: Record<string, Uint8Array>;
23
- };
24
-
25
- export const uploadWorkerFunction = async ({
26
- client,
27
- version,
28
- name,
29
- functionId,
30
- ownerPublicKey,
31
- entryPoint,
32
- assets,
33
- }: UploadWorkerArgs): Promise<UploadFunctionResponseBody> => {
34
- log('uploading function', { functionId, name, version, ownerPublicKey });
35
- const edgeUrl = client.config.values.runtime?.services?.edge?.url;
36
- invariant(edgeUrl, 'Edge is not configured.');
37
- const edgeClient = new EdgeHttpClient(edgeUrl);
38
- const edgeIdentity = createEdgeIdentity(client);
39
- edgeClient.setIdentity(edgeIdentity);
40
- const response = await edgeClient.uploadFunction(
41
- { functionId },
42
- { name, version, ownerPublicKey: ownerPublicKey.toHex(), entryPoint, assets },
43
- );
44
-
45
- // TODO(burdon): Edge service log.
46
- log('uploaded', {
47
- identityKey: edgeIdentity.identityKey,
48
- functionId,
49
- name,
50
- version,
51
- response,
52
- });
53
-
54
- return response;
55
- };
56
-
57
- export const incrementSemverPatch = (version: string): string => {
58
- const [major, minor, patch] = version.split('.');
59
- const patchNum = Number(patch);
60
- invariant(!Number.isNaN(patchNum), `Unexpected function version format: ${version}`);
61
- return [major, minor, String(patchNum + 1)].join('.');
62
- };
63
-
64
- // TODO(burdon): Factor out.
65
- export const publicKeyToDid = (key: PublicKey): DID => {
66
- return `did:key:${key.toHex()}`;
67
- };
package/src/edge/index.ts DELETED
@@ -1,9 +0,0 @@
1
- //
2
- // Copyright 2024 DXOS.org
3
- //
4
-
5
- // NOTE: This module is separate because it uses the edge client.
6
- // This means it cannot be used on edge itself.
7
- // TODO(wittjosiah): Factor out.
8
-
9
- export * from './functions';
@@ -1,7 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- export { default as fib } from './fib';
6
- export { default as reply } from './reply';
7
- export { default as sleep } from './sleep';
@@ -1,54 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- import { Effect, Schema } from 'effect';
6
-
7
- import { type SpaceId } from '@dxos/client/echo';
8
- import { runAndForwardErrors } from '@dxos/effect';
9
-
10
- import type { FunctionContext, FunctionDefinition } from '../handler';
11
- import type { ServiceContainer, Services } from '../services';
12
-
13
- export class FunctionExecutor {
14
- constructor(private readonly _services: ServiceContainer) {}
15
-
16
- /**
17
- * Invoke function.
18
- */
19
- // TODO(dmaretskyi): Invocation context: queue, space, etc...
20
- async invoke<F extends FunctionDefinition<any, any>>(
21
- functionDef: F,
22
- input: F extends FunctionDefinition<infer I, infer _O> ? I : never,
23
- ): Promise<F extends FunctionDefinition<infer _I, infer O> ? O : never> {
24
- // Assert input matches schema
25
- const assertInput = functionDef.inputSchema.pipe(Schema.asserts);
26
- (assertInput as any)(input);
27
-
28
- const context: FunctionContext = {
29
- space: undefined,
30
- getService: this._services.getService.bind(this._services),
31
- getSpace: async (_spaceId: SpaceId) => {
32
- throw new Error('Not available. Use the database service instead.');
33
- },
34
- };
35
-
36
- const result = functionDef.handler({ context, data: input });
37
-
38
- let data: unknown;
39
- if (Effect.isEffect(result)) {
40
- data = await (result as Effect.Effect<unknown, unknown, Services>).pipe(
41
- Effect.provide(this._services.createLayer()),
42
- runAndForwardErrors,
43
- );
44
- } else {
45
- data = await result;
46
- }
47
-
48
- // Assert output matches schema
49
- const assertOutput = functionDef.outputSchema?.pipe(Schema.asserts);
50
- (assertOutput as any)(data);
51
-
52
- return data as any;
53
- }
54
- }
package/src/handler.ts DELETED
@@ -1,201 +0,0 @@
1
- //
2
- // Copyright 2023 DXOS.org
3
- //
4
-
5
- import { type Context, Effect, Schema, type Types } from 'effect';
6
-
7
- import { Obj, Type } from '@dxos/echo';
8
- import { type EchoDatabase } from '@dxos/echo-db';
9
- import { type HasId } from '@dxos/echo-schema';
10
- import { assertArgument } from '@dxos/invariant';
11
- import { type DXN, type SpaceId } from '@dxos/keys';
12
- import { type QueryResult } from '@dxos/protocols';
13
-
14
- import { FunctionType } from './schema';
15
- import { type Services } from './services';
16
-
17
- // TODO(burdon): Model after http request. Ref Lambda/OpenFaaS.
18
- // https://docs.aws.amazon.com/lambda/latest/dg/typescript-handler.html
19
- // https://www.serverless.com/framework/docs/providers/aws/guide/serverless.yml/#functions
20
- // https://www.npmjs.com/package/aws-lambda
21
-
22
- /**
23
- * Function handler.
24
- */
25
- export type FunctionHandler<TData = {}, TOutput = any> = (params: {
26
- /**
27
- * Services and context available to the function.
28
- */
29
- context: FunctionContext;
30
-
31
- /**
32
- * Data passed as the input to the function.
33
- * Must match the function's input schema.
34
- * This will be the payload from the trigger or other data passed into the function in a workflow.
35
- */
36
- data: TData;
37
- }) => TOutput | Promise<TOutput> | Effect.Effect<TOutput, any, Services>;
38
-
39
- /**
40
- * Function context.
41
- */
42
- export interface FunctionContext {
43
- /**
44
- * Space from which the function was invoked.
45
- */
46
- space: SpaceAPI | undefined;
47
-
48
- /**
49
- * Resolves a service available to the function.
50
- * @throws if the service is not available.
51
- */
52
- getService: <T extends Context.Tag<any, any>>(tag: T) => Context.Tag.Service<T>;
53
-
54
- getSpace: (spaceId: SpaceId) => Promise<SpaceAPI>;
55
- }
56
-
57
- export interface FunctionContextAi {
58
- // TODO(dmaretskyi): Refer to cloudflare AI docs for more comprehensive typedefs.
59
- run(model: string, inputs: any, options?: any): Promise<any>;
60
- }
61
-
62
- //
63
- // API.
64
- //
65
-
66
- // TODO(dmaretskyi): Temporary API to get the queues working.
67
- // TODO(dmaretskyi): To be replaced with integrating queues into echo.
68
- export interface QueuesAPI {
69
- queryQueue(queue: DXN, options?: {}): Promise<QueryResult>;
70
- insertIntoQueue(queue: DXN, objects: HasId[]): Promise<void>;
71
- }
72
-
73
- /**
74
- * Space interface available to functions.
75
- */
76
- export interface SpaceAPI {
77
- get id(): SpaceId;
78
- get db(): EchoDatabase;
79
-
80
- // TODO(dmaretskyi): Align with echo api: queues.get(id).append(items);
81
- get queues(): QueuesAPI;
82
- }
83
-
84
- // TODO(wittjosiah): Queues are incompatible.
85
- const __assertFunctionSpaceIsCompatibleWithTheClientSpace = () => {
86
- // const _: SpaceAPI = {} as Space;
87
- };
88
-
89
- const typeId = Symbol.for('@dxos/functions/FunctionDefinition');
90
-
91
- export type FunctionDefinition<T = any, O = any> = {
92
- [typeId]: true;
93
- // TODO(dmaretskyi): Use `key` for FQN and `name` for human-readable-name.
94
- key: string;
95
- name: string;
96
- description?: string;
97
- inputSchema: Schema.Schema<T, any>;
98
- outputSchema?: Schema.Schema<O, any>;
99
- handler: FunctionHandler<T, O>;
100
- };
101
-
102
- export const defineFunction: {
103
- <I, O>(params: {
104
- // TODO(dmaretskyi): Make `key` required.
105
- key?: string;
106
- name: string;
107
- description?: string;
108
- inputSchema: Schema.Schema<I, any>;
109
- outputSchema?: Schema.Schema<O, any>;
110
- handler: Types.NoInfer<FunctionHandler<I, O>>;
111
- }): FunctionDefinition<I, O>;
112
- } = ({ key, name, description, inputSchema, outputSchema = Schema.Any, handler }) => {
113
- if (!Schema.isSchema(inputSchema)) {
114
- throw new Error('Input schema must be a valid schema');
115
- }
116
- if (typeof handler !== 'function') {
117
- throw new Error('Handler must be a function');
118
- }
119
-
120
- // Captures the function definition location.
121
- const limit = Error.stackTraceLimit;
122
- Error.stackTraceLimit = 2;
123
- const traceError = new Error();
124
- Error.stackTraceLimit = limit;
125
- let cache: false | string = false;
126
- const captureStackTrace = () => {
127
- if (cache !== false) {
128
- return cache;
129
- }
130
- if (traceError.stack !== undefined) {
131
- const stack = traceError.stack.split('\n');
132
- if (stack[2] !== undefined) {
133
- cache = stack[2].trim();
134
- return cache;
135
- }
136
- }
137
- };
138
-
139
- const handlerWithSpan = (...args: any[]) => {
140
- const result = (handler as any)(...args);
141
- if (Effect.isEffect(result)) {
142
- return Effect.withSpan(result, `${key ?? name}`, {
143
- captureStackTrace,
144
- });
145
- }
146
- return result;
147
- };
148
-
149
- return {
150
- [typeId]: true,
151
- key: key ?? name,
152
- name,
153
- description,
154
- inputSchema,
155
- outputSchema,
156
- handler: handlerWithSpan,
157
- };
158
- };
159
-
160
- export const FunctionDefinition = {
161
- make: defineFunction,
162
- isFunction: (value: unknown): value is FunctionDefinition.Any => {
163
- return typeof value === 'object' && value !== null && Symbol.for('@dxos/functions/FunctionDefinition') in value;
164
- },
165
- serialize: (functionDef: FunctionDefinition.Any): FunctionType => {
166
- assertArgument(FunctionDefinition.isFunction(functionDef), 'functionDef');
167
- return serializeFunction(functionDef);
168
- },
169
- deserialize: (functionObj: FunctionType): FunctionDefinition.Any => {
170
- assertArgument(Obj.instanceOf(FunctionType, functionObj), 'functionObj');
171
- return deserializeFunction(functionObj);
172
- },
173
- };
174
- export declare namespace FunctionDefinition {
175
- export type Any = FunctionDefinition<any, any>;
176
- export type Input<T extends FunctionDefinition> = T extends FunctionDefinition<infer I, any> ? I : never;
177
- export type Output<T extends FunctionDefinition> = T extends FunctionDefinition<any, infer O> ? O : never;
178
- }
179
-
180
- export const serializeFunction = (functionDef: FunctionDefinition<any, any>): FunctionType =>
181
- Obj.make(FunctionType, {
182
- key: functionDef.name,
183
- name: functionDef.name,
184
- version: '0.1.0',
185
- description: functionDef.description,
186
- inputSchema: Type.toJsonSchema(functionDef.inputSchema),
187
- outputSchema: !functionDef.outputSchema ? undefined : Type.toJsonSchema(functionDef.outputSchema),
188
- });
189
-
190
- export const deserializeFunction = (functionObj: FunctionType): FunctionDefinition<unknown, unknown> => {
191
- return {
192
- [typeId]: true,
193
- // TODO(dmaretskyi): Fix key.
194
- key: functionObj.key ?? functionObj.name,
195
- name: functionObj.name,
196
- description: functionObj.description,
197
- inputSchema: !functionObj.inputSchema ? Schema.Unknown : Type.toEffectSchema(functionObj.inputSchema),
198
- outputSchema: !functionObj.outputSchema ? undefined : Type.toEffectSchema(functionObj.outputSchema),
199
- handler: () => {},
200
- };
201
- };