@dxos/edge-compute 0.0.0

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 (70) hide show
  1. package/LICENSE +105 -0
  2. package/dist/lib/neutral/bundler/index.mjs +213 -0
  3. package/dist/lib/neutral/bundler/index.mjs.map +7 -0
  4. package/dist/lib/neutral/chunk-J5LGTIGS.mjs +10 -0
  5. package/dist/lib/neutral/chunk-J5LGTIGS.mjs.map +7 -0
  6. package/dist/lib/neutral/chunk-RN6KVGN4.mjs +63 -0
  7. package/dist/lib/neutral/chunk-RN6KVGN4.mjs.map +7 -0
  8. package/dist/lib/neutral/index.mjs +343 -0
  9. package/dist/lib/neutral/index.mjs.map +7 -0
  10. package/dist/lib/neutral/meta.json +1 -0
  11. package/dist/lib/neutral/native/index.mjs +186 -0
  12. package/dist/lib/neutral/native/index.mjs.map +7 -0
  13. package/dist/lib/neutral/testing/index.mjs +41 -0
  14. package/dist/lib/neutral/testing/index.mjs.map +7 -0
  15. package/dist/types/src/EdgeOperationInvoker.d.ts +21 -0
  16. package/dist/types/src/EdgeOperationInvoker.d.ts.map +1 -0
  17. package/dist/types/src/EdgeProcessManager.d.ts +14 -0
  18. package/dist/types/src/EdgeProcessManager.d.ts.map +1 -0
  19. package/dist/types/src/EdgeTriggerManager.d.ts +14 -0
  20. package/dist/types/src/EdgeTriggerManager.d.ts.map +1 -0
  21. package/dist/types/src/FunctionsServiceClient.d.ts +65 -0
  22. package/dist/types/src/FunctionsServiceClient.d.ts.map +1 -0
  23. package/dist/types/src/bundler/bundler.d.ts +38 -0
  24. package/dist/types/src/bundler/bundler.d.ts.map +1 -0
  25. package/dist/types/src/bundler/bundler.test.d.ts +2 -0
  26. package/dist/types/src/bundler/bundler.test.d.ts.map +1 -0
  27. package/dist/types/src/bundler/index.d.ts +2 -0
  28. package/dist/types/src/bundler/index.d.ts.map +1 -0
  29. package/dist/types/src/bundler/plugins/embedded-vendored-packages.d.ts +3 -0
  30. package/dist/types/src/bundler/plugins/embedded-vendored-packages.d.ts.map +1 -0
  31. package/dist/types/src/bundler/plugins/http-plugin-esbuild.d.ts +34 -0
  32. package/dist/types/src/bundler/plugins/http-plugin-esbuild.d.ts.map +1 -0
  33. package/dist/types/src/bundler/plugins/index.d.ts +4 -0
  34. package/dist/types/src/bundler/plugins/index.d.ts.map +1 -0
  35. package/dist/types/src/bundler/plugins/r2-vendored-packages.d.ts +5 -0
  36. package/dist/types/src/bundler/plugins/r2-vendored-packages.d.ts.map +1 -0
  37. package/dist/types/src/edge-client.d.ts +39 -0
  38. package/dist/types/src/edge-client.d.ts.map +1 -0
  39. package/dist/types/src/index.d.ts +6 -0
  40. package/dist/types/src/index.d.ts.map +1 -0
  41. package/dist/types/src/native/bundler.d.ts +15 -0
  42. package/dist/types/src/native/bundler.d.ts.map +1 -0
  43. package/dist/types/src/native/index.d.ts +2 -0
  44. package/dist/types/src/native/index.d.ts.map +1 -0
  45. package/dist/types/src/testing/index.d.ts +2 -0
  46. package/dist/types/src/testing/index.d.ts.map +1 -0
  47. package/dist/types/src/testing/logger.d.ts +4 -0
  48. package/dist/types/src/testing/logger.d.ts.map +1 -0
  49. package/dist/types/src/testing/services.d.ts +53 -0
  50. package/dist/types/src/testing/services.d.ts.map +1 -0
  51. package/dist/types/tsconfig.tsbuildinfo +1 -0
  52. package/package.json +95 -0
  53. package/src/EdgeOperationInvoker.ts +65 -0
  54. package/src/EdgeProcessManager.ts +47 -0
  55. package/src/EdgeTriggerManager.ts +70 -0
  56. package/src/FunctionsServiceClient.ts +189 -0
  57. package/src/bundler/bundler.test.ts +108 -0
  58. package/src/bundler/bundler.ts +232 -0
  59. package/src/bundler/index.ts +5 -0
  60. package/src/bundler/plugins/embedded-vendored-packages.ts +39 -0
  61. package/src/bundler/plugins/http-plugin-esbuild.ts +77 -0
  62. package/src/bundler/plugins/index.ts +7 -0
  63. package/src/bundler/plugins/r2-vendored-packages.ts +35 -0
  64. package/src/edge-client.ts +156 -0
  65. package/src/index.ts +9 -0
  66. package/src/native/bundler.ts +231 -0
  67. package/src/native/index.ts +5 -0
  68. package/src/testing/index.ts +5 -0
  69. package/src/testing/logger.ts +14 -0
  70. package/src/testing/services.ts +95 -0
@@ -0,0 +1,232 @@
1
+ //
2
+ // Copyright 2023 DXOS.org
3
+ //
4
+
5
+ import { type BuildResult, type Plugin, type PluginBuild, build, initialize } from 'esbuild-wasm';
6
+
7
+ import { subtleCrypto } from '@dxos/crypto';
8
+ import { invariant } from '@dxos/invariant';
9
+ import { isNode, trim } from '@dxos/util';
10
+
11
+ import { httpPlugin } from './plugins/http-plugin-esbuild';
12
+ import { PluginR2VendoredPackages } from './plugins/r2-vendored-packages';
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
+ assets: Record<string, Uint8Array>;
39
+ };
40
+
41
+ let initialized: Promise<void>;
42
+ /**
43
+ * Initializes the bundler.
44
+ * Must be called before using the bundler in browser.
45
+ */
46
+ export const initializeBundler = async (options: { wasmUrl: string }) => {
47
+ await (initialized ??= initialize({
48
+ wasmURL: options.wasmUrl,
49
+ }));
50
+ };
51
+
52
+ /**
53
+ * ESBuild bundler implemented as a function (parity with native bundler API style).
54
+ * Bundles source code directly, does not really on filesystem or Node APIs.
55
+ *
56
+ * This is browser friendly version of the bundler, but it could also be used in Node environment.
57
+ * `initializeBundler` should be called before using it in browser, not required in Node.
58
+ */
59
+ export const bundleFunction = async ({ source }: BundleOptions): Promise<BundleResult> => {
60
+ const sourceHash = Buffer.from(await subtleCrypto.digest('SHA-256', Buffer.from(source)));
61
+
62
+ if (!isNode()) {
63
+ invariant(initialized, 'Compiler not initialized.');
64
+ await initialized;
65
+ }
66
+ const outdir = '/tmp/bundle';
67
+ try {
68
+ const result = await build({
69
+ platform: 'browser',
70
+ conditions: ['workerd', 'worker', 'browser'],
71
+ metafile: true,
72
+ write: false,
73
+ entryPoints: {
74
+ // Keep output name stable as `index.js` to preserve API.
75
+ index: 'dxos:entrypoint',
76
+ },
77
+ outdir,
78
+ bundle: true,
79
+
80
+ // NOTE: Splitting causes an error in Cloudflare-Workers:
81
+ // Disallowed operation called within global scope.
82
+ // Asynchronous I/O (ex: fetch() or connect()), setting a timeout, and generating random values are not allowed within global scope.
83
+ // To fix this error, perform this operation within a handler. https://developers.cloudflare.com/workers/runtime-apis/handlers/
84
+ //
85
+ // Likely, workerd is treating asynchronously-loaded modules as if they were executing in global scope.
86
+ // splitting: true,
87
+ format: 'esm',
88
+ target: 'esnext',
89
+ supported: {
90
+ 'class-private-accessor': true,
91
+ 'class-private-brand-check': true,
92
+ 'class-private-field': true,
93
+ 'class-private-method': true,
94
+ 'class-private-static-accessor': true,
95
+ 'class-private-static-field': true,
96
+ 'class-private-static-method': true,
97
+ },
98
+ external: ['cloudflare:workers'],
99
+ alias: {
100
+ 'node:path': 'path',
101
+ },
102
+ plugins: [
103
+ httpPlugin as any as Plugin,
104
+ {
105
+ // Provide a virtual entrypoint that wraps the user handler similar to the native bundler.
106
+ name: 'entrypoint',
107
+ setup: (build: PluginBuild) => {
108
+ build.onResolve({ filter: /^dxos:entrypoint$/ }, () => ({
109
+ path: 'dxos:entrypoint',
110
+ namespace: 'dxos:entrypoint',
111
+ }));
112
+ // TODO(dmaretskyi): Move into memory plugin
113
+ build.onLoad({ filter: /^dxos:entrypoint$/, namespace: 'dxos:entrypoint' }, () => {
114
+ return {
115
+ contents: trim`
116
+ export default {
117
+ fetch: async (...args) => {
118
+ const { wrapFunctionHandler } = await import('@dxos/compute-runtime');
119
+ const { wrapHandlerForCloudflare } = await import('@dxos/functions-runtime-cloudflare');
120
+ const { default: handler } = await import('memory:source.tsx');
121
+
122
+ //
123
+ // Wrapper to make the function cloudflare-compatible.
124
+ //
125
+ return wrapHandlerForCloudflare(wrapFunctionHandler(handler))(...args);
126
+ },
127
+ };
128
+ `,
129
+ loader: 'ts',
130
+ } as const;
131
+ });
132
+ },
133
+ },
134
+ {
135
+ name: 'memory',
136
+ setup: (build) => {
137
+ build.onResolve({ filter: /^memory:/ }, ({ path }) => {
138
+ return { path: path.split(':')[1], namespace: 'memory' };
139
+ });
140
+
141
+ build.onLoad({ filter: /.*/, namespace: 'memory' }, ({ path }) => {
142
+ switch (path) {
143
+ case 'source.tsx':
144
+ return {
145
+ contents: source,
146
+ loader: 'tsx',
147
+ };
148
+ case 'empty':
149
+ return {
150
+ contents: '',
151
+ loader: 'js',
152
+ };
153
+ }
154
+ });
155
+ },
156
+ },
157
+ // PluginESMSh(),
158
+ PluginR2VendoredPackages(),
159
+ ],
160
+ });
161
+
162
+ // log.info('Bundling complete', result.metafile);
163
+ // log.info('Output files', { files: result.outputFiles });
164
+
165
+ const entryPoint = 'index.js';
166
+ return {
167
+ timestamp: Date.now(),
168
+ sourceHash,
169
+ imports: analyzeImports(result),
170
+ entryPoint,
171
+ assets: result.outputFiles.reduce(
172
+ (acc, file) => {
173
+ acc[file.path.replace(outdir + '/', '')] = file.contents;
174
+ return acc;
175
+ },
176
+ {} as Record<string, Uint8Array>,
177
+ ),
178
+ };
179
+ } catch (err) {
180
+ return { timestamp: Date.now(), sourceHash, error: err };
181
+ }
182
+ };
183
+
184
+ // TODO(dmaretskyi): In the future we can replace the compiler with SWC with plugins running in WASM.
185
+ const analyzeImports = (result: BuildResult): Import[] => {
186
+ invariant(result.outputFiles);
187
+
188
+ // TODO(dmaretskyi): Support import aliases and wildcard imports.
189
+ const parsedImports = allMatches(IMPORT_REGEX, result.outputFiles[0].text);
190
+ return Object.values(result.metafile!.outputs)[0].imports.map((entry): Import => {
191
+ const namedImports: string[] = [];
192
+ const parsedImport = parsedImports.find((capture) => capture?.[4] === entry.path);
193
+ if (parsedImport?.[2]) {
194
+ NAMED_IMPORTS_REGEX.lastIndex = 0;
195
+ const namedImportsMatch = NAMED_IMPORTS_REGEX.exec(parsedImport[2]);
196
+ if (namedImportsMatch) {
197
+ namedImportsMatch[1].split(',').forEach((importName) => {
198
+ namedImports.push(importName.trim());
199
+ });
200
+ }
201
+ }
202
+
203
+ return {
204
+ moduleUrl: entry.path,
205
+ defaultImport: !!parsedImport?.[1],
206
+ namedImports,
207
+ };
208
+ });
209
+ };
210
+
211
+ // https://regex101.com/r/FEN5ks/1
212
+ // https://stackoverflow.com/a/73265022
213
+ // $1 = default import name (can be non-existent)
214
+ // $2 = destructured exports (can be non-existent)
215
+ // $3 = wildcard import name (can be non-existent)
216
+ // $4 = module identifier
217
+ // $5 = quotes used (either ' or ")
218
+ const IMPORT_REGEX =
219
+ /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;
220
+
221
+ const NAMED_IMPORTS_REGEX = /[ \n\t]*{((?:[ \n\t]*[^ \n\t"'{}]+[ \n\t]*,?)+)}[ \n\t]*/gm;
222
+
223
+ const allMatches = (regex: RegExp, str: string) => {
224
+ let match;
225
+ const matches = [];
226
+ regex.lastIndex = 0;
227
+ while ((match = regex.exec(str))) {
228
+ matches.push(match);
229
+ }
230
+
231
+ return matches;
232
+ };
@@ -0,0 +1,5 @@
1
+ //
2
+ // Copyright 2023 DXOS.org
3
+ //
4
+
5
+ export * from './bundler';
@@ -0,0 +1,39 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import * as Function from 'effect/Function';
6
+ import * as Record from 'effect/Record';
7
+ import type { Plugin } from 'esbuild-wasm';
8
+
9
+ // TODO(dmaretskyi): Haven't managed to get this working.
10
+ export const PluginEmbeddedVendoredPackages = (): Plugin => ({
11
+ name: 'embedded-vendored-packages',
12
+ setup: (build) => {
13
+ // // https://vite.dev/guide/features#custom-queries
14
+ const moduleUrls = Function.pipe(
15
+ // NOTE: Vite-specific API.
16
+ // @ts-expect-error
17
+ import.meta.glob('../../dist/vendor/**/*.js', {
18
+ query: '?url',
19
+ import: 'default',
20
+ eager: true,
21
+ }) as Record<string, string>,
22
+ Record.mapKeys((s) => s.replace('../../dist/vendor/', '').replace(/\.js$/, '')),
23
+ Record.filter((_, key) => !key.startsWith('internal/')),
24
+ );
25
+
26
+ // console.log(moduleUrls);
27
+
28
+ build.onResolve({ filter: /^[^./]/ }, (args) => {
29
+ if (args.kind === 'entry-point') {
30
+ return;
31
+ }
32
+
33
+ return build.resolve(new URL(moduleUrls[args.path], import.meta.url).href, {
34
+ kind: args.kind,
35
+ resolveDir: args.resolveDir,
36
+ });
37
+ });
38
+ },
39
+ });
@@ -0,0 +1,77 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import * as FetchHttpClient from '@effect/platform/FetchHttpClient';
6
+ import * as HttpClient from '@effect/platform/HttpClient';
7
+ import * as Duration from 'effect/Duration';
8
+ import * as Effect from 'effect/Effect';
9
+ import * as Function from 'effect/Function';
10
+ import * as Schedule from 'effect/Schedule';
11
+ import { type Loader, type Plugin } from 'esbuild';
12
+
13
+ import { EffectEx } from '@dxos/effect';
14
+ import { BaseError } from '@dxos/errors';
15
+
16
+ const MAX_RETRIES = 5;
17
+ const INITIAL_DELAY = 1_000;
18
+
19
+ export class HttpPluginError extends BaseError.extend('HttpPluginError') {}
20
+
21
+ const LOADERS: Record<string, Loader> = {
22
+ js: 'js',
23
+ jsx: 'jsx',
24
+ ts: 'ts',
25
+ tsx: 'tsx',
26
+ wasm: 'copy',
27
+ } as const;
28
+
29
+ export const httpPlugin: Plugin = {
30
+ name: 'http',
31
+ setup: (build) => {
32
+ // Intercept import paths starting with "http:" and "https:" so esbuild doesn't attempt to map them to a file system location.
33
+ // Tag them with the "http-url" namespace to associate them with this plugin.
34
+ build.onResolve({ filter: /^https?:\/\// }, (args) => ({
35
+ path: args.path,
36
+ namespace: 'http-url',
37
+ }));
38
+
39
+ // We also want to intercept all import paths inside downloaded files and resolve them against the original URL.
40
+ // All of these files will be in the "http-url" namespace.
41
+ // Make sure to keep the newly resolved URL in the "http-url" namespace so imports inside it will also be resolved as URLs recursively.
42
+ build.onResolve({ filter: /.*/, namespace: 'http-url' }, (args) => ({
43
+ path: new URL(args.path, args.importer).toString(),
44
+ namespace: 'http-url',
45
+ }));
46
+
47
+ // When a URL is loaded, we want to actually download the content from the internet.
48
+ // 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.
49
+ build.onLoad({ filter: /.*/, namespace: 'http-url' }, async (args) => {
50
+ return Effect.gen(function* () {
51
+ const response = yield* HttpClient.get(args.path);
52
+ if (response.status !== 200) {
53
+ yield* Effect.fail(
54
+ new HttpPluginError({
55
+ message: `failed to fetch ${args.path}, status: ${response.status}`,
56
+ }),
57
+ );
58
+ }
59
+
60
+ const contents = new Uint8Array(yield* response.arrayBuffer);
61
+ const extension = new URL(args.path).pathname.split('.').pop() || '';
62
+ const loader = LOADERS[extension.toLowerCase()] ?? 'jsx';
63
+ return { contents, loader };
64
+ }).pipe(
65
+ Effect.retry(
66
+ Function.pipe(
67
+ Schedule.exponential(Duration.millis(INITIAL_DELAY)),
68
+ Schedule.jittered,
69
+ Schedule.intersect(Schedule.recurs(MAX_RETRIES - 1)),
70
+ ),
71
+ ),
72
+ Effect.provide(FetchHttpClient.layer),
73
+ EffectEx.runAndForwardErrors,
74
+ );
75
+ });
76
+ },
77
+ };
@@ -0,0 +1,7 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ export * from './http-plugin-esbuild';
6
+ export * from './r2-vendored-packages';
7
+ export * from './embedded-vendored-packages';
@@ -0,0 +1,35 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import type { Plugin } from 'esbuild-wasm';
6
+
7
+ /*
8
+
9
+ script-vendored-packages bucket on R2
10
+
11
+ https://dash.cloudflare.com/950816f3f59b079880a1ae33fb0ec320/r2/default/buckets/script-vendored-packages/settings
12
+
13
+ 'https://pub-5745ae82e450484aa28f75fc6a175935.r2.dev/dev' -- last portion is the env
14
+
15
+
16
+ */
17
+
18
+ const DEFAULT_SCRIPT_PACKAGES_BUCKET = 'https://pub-5745ae82e450484aa28f75fc6a175935.r2.dev/dev/';
19
+
20
+ export const PluginR2VendoredPackages = ({ url = DEFAULT_SCRIPT_PACKAGES_BUCKET }: { url?: string } = {}): Plugin => ({
21
+ name: 'r2-vendored-packages',
22
+ setup: (build) => {
23
+ build.onResolve({ filter: /^[^./]/ }, (args) => {
24
+ if (args.kind === 'entry-point') {
25
+ return;
26
+ }
27
+
28
+ return {
29
+ // NOTE: Use .js extension for tsdown
30
+ path: new URL(`${args.path}.js`, url).href,
31
+ namespace: 'http-url', // Uses http plugin.
32
+ };
33
+ });
34
+ },
35
+ });
@@ -0,0 +1,156 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ import * as Array from 'effect/Array';
6
+ import * as Function$ from 'effect/Function';
7
+ import * as Order from 'effect/Order';
8
+ import { type DID } from 'iso-did/types';
9
+
10
+ import { type Client } from '@dxos/client';
11
+ import { createEdgeIdentity } from '@dxos/client/edge';
12
+ import { Operation } from '@dxos/compute';
13
+ import { FUNCTIONS_META_KEY, setUserFunctionIdInMetadata } from '@dxos/compute-runtime';
14
+ import { Context } from '@dxos/context';
15
+ import { Obj } from '@dxos/echo';
16
+ import { EdgeHttpClient } from '@dxos/edge-client';
17
+ import { invariant } from '@dxos/invariant';
18
+ import { type PublicKey, type SpaceId } from '@dxos/keys';
19
+ import { log } from '@dxos/log';
20
+ import { type UploadFunctionResponseBody } from '@dxos/protocols';
21
+ import { safeParseJson } from '@dxos/util';
22
+
23
+ /** @deprecated Use {@link FunctionsServiceClient} instead. */
24
+ export type UploadWorkerArgs = {
25
+ client: Client;
26
+ version: string;
27
+ name?: string;
28
+ functionId?: string;
29
+ /** Owner identity DID (`did:halo:…`). */
30
+ ownerUri: string;
31
+ entryPoint: string;
32
+ assets: Record<string, Uint8Array>;
33
+ };
34
+
35
+ /** @deprecated Migrate to `client.edge`. */
36
+ export const createEdgeClient = (client: Client): EdgeHttpClient => {
37
+ const edgeUrl = client.config.values.runtime?.services?.edge?.url;
38
+ invariant(edgeUrl, 'Edge is not configured.');
39
+ const edgeClient = new EdgeHttpClient(edgeUrl);
40
+ const edgeIdentity = createEdgeIdentity(client);
41
+ edgeClient.setIdentity(edgeIdentity);
42
+ return edgeClient;
43
+ };
44
+
45
+ /**
46
+ * @deprecated Use {@link FunctionsServiceClient} instead.
47
+ */
48
+ export const uploadWorkerFunction = async (
49
+ ctx: Context,
50
+ { client, version, name, functionId, ownerUri, entryPoint, assets }: UploadWorkerArgs,
51
+ ): Promise<UploadFunctionResponseBody> => {
52
+ log('uploading function', { functionId, name, version, ownerUri });
53
+ const edgeClient = createEdgeClient(client);
54
+ const response = await edgeClient.uploadFunction(
55
+ ctx,
56
+ { functionId },
57
+ { name, version, ownerUri, entryPoint, assets },
58
+ );
59
+
60
+ // TODO(burdon): Edge service log.
61
+ log('uploaded', {
62
+ identityKey: client.halo.identity.get()?.identityKey,
63
+ did: client.halo.identity.get()?.did,
64
+ functionId,
65
+ name,
66
+ version,
67
+ response,
68
+ });
69
+
70
+ return response;
71
+ };
72
+
73
+ /**
74
+ * @deprecated Use {@link FunctionsServiceClient} instead.
75
+ */
76
+ export const getDeployedFunctions = async (
77
+ ctx: Context,
78
+ client: Client,
79
+ dedupe = false,
80
+ ): Promise<Operation.PersistentOperation[]> => {
81
+ const edgeClient = createEdgeClient(client);
82
+ const result = await edgeClient.listFunctions(ctx);
83
+ const functions: Operation.PersistentOperation[] = result.uploadedFunctions.flatMap((record: any) => {
84
+ // Record shape is determined by EDGE API. We defensively parse.
85
+ const latest = record.latestVersion ?? {};
86
+ const versionMeta = safeParseJson<any>(latest.versionMetaJSON);
87
+ if (!versionMeta) {
88
+ return [];
89
+ }
90
+ const fn = Obj.make(Operation.PersistentOperation, {
91
+ [Obj.Meta]: {
92
+ key: versionMeta.key,
93
+ version: latest?.version ?? '0.0.0',
94
+ },
95
+ name: versionMeta.name ?? versionMeta.key ?? record.id,
96
+ updated: record?.updated !== undefined ? new Date(record.updated).toISOString() : undefined,
97
+ description: versionMeta.description,
98
+ inputSchema: versionMeta.inputSchema,
99
+ outputSchema: versionMeta.outputSchema,
100
+ });
101
+
102
+ Obj.update(fn, (fn) => setUserFunctionIdInMetadata(Obj.getMeta(fn), record.id));
103
+ return [fn];
104
+ });
105
+
106
+ if (dedupe) {
107
+ return Function$.pipe(
108
+ functions,
109
+ Array.filter((_) => Obj.getMeta(_).key !== undefined),
110
+ Array.sort(Order.reverse(Order.mapInput(Order.string, (_: Operation.PersistentOperation) => _.updated ?? ''))),
111
+ Array.dedupeWith((self, that) => Obj.getMeta(self).key === Obj.getMeta(that).key),
112
+ Array.sort(Order.mapInput(Order.string, (_: Operation.PersistentOperation) => Obj.getMeta(_).key ?? '')),
113
+ );
114
+ } else {
115
+ return functions;
116
+ }
117
+ };
118
+
119
+ /**
120
+ * @deprecated Use {@link FunctionsServiceClient} instead.
121
+ */
122
+ export const invokeFunction = async (
123
+ ctx: Context,
124
+ edgeClient: EdgeHttpClient,
125
+ fn: Operation.PersistentOperation,
126
+ input: unknown,
127
+ {
128
+ spaceId,
129
+ cpuTimeLimit,
130
+ subrequestsLimit,
131
+ }: { spaceId?: SpaceId; cpuTimeLimit?: number; subrequestsLimit?: number } = {},
132
+ ) => {
133
+ const functionId = Obj.getMeta(fn).keys.find((key) => key.source === FUNCTIONS_META_KEY)?.id;
134
+ if (!functionId) {
135
+ throw new Error('No identifier for the function at the EDGE service');
136
+ }
137
+ // COMPAT: Previously functionId was a URL `/<guid>`. Now it's just the `<guid>`.
138
+ const cleanedId = functionId.replace(/^\//, '');
139
+ return await edgeClient.invokeFunction(
140
+ ctx,
141
+ { functionId: cleanedId, spaceId, cpuTimeLimit, subrequestsLimit },
142
+ input,
143
+ );
144
+ };
145
+
146
+ export const incrementSemverPatch = (version: string): string => {
147
+ const [major, minor, patch] = version.split('.');
148
+ const patchNum = Number(patch);
149
+ invariant(!Number.isNaN(patchNum), `Unexpected function version format: ${version}`);
150
+ return [major, minor, String(patchNum + 1)].join('.');
151
+ };
152
+
153
+ // TODO(burdon): Factor out.
154
+ export const publicKeyToDid = (key: PublicKey): DID => {
155
+ return `did:key:${key.toHex()}`;
156
+ };
package/src/index.ts ADDED
@@ -0,0 +1,9 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ export * from './edge-client';
6
+ export * as EdgeOperationInvoker from './EdgeOperationInvoker';
7
+ export * as EdgeProcessManager from './EdgeProcessManager';
8
+ export * as EdgeTriggerManager from './EdgeTriggerManager';
9
+ export * from './FunctionsServiceClient';