@dxos/functions 0.1.52 → 0.1.53-main.032dce6

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.
package/README.md CHANGED
@@ -1,11 +1,76 @@
1
- # @dxos/echo-db
1
+ # @dxos/functions
2
2
 
3
- ECHO database.
3
+ Functions SDK.
4
4
 
5
5
  ## Installation
6
6
 
7
7
  ```bash
8
- pnpm i @dxos/echo-db
8
+ pnpm i @dxos/functions
9
+ ```
10
+
11
+ ## Writing functions
12
+
13
+ Create a manifest file at the package root:
14
+
15
+ ```yaml
16
+ functions:
17
+ hello:
18
+ description: Test function.
19
+ ```
20
+
21
+ > NOTE: The function name must match the filename (e.g., `src/functions/hello.ts`).
22
+
23
+ Create an example function:
24
+
25
+ ```ts
26
+ import { FunctionContext } from '@dxos/functions';
27
+
28
+ export default (event: any, context: FunctionContext) => {
29
+ const identity = context.client.halo.identity.get();
30
+ return context
31
+ .status(200)
32
+ .succeed({
33
+ message: `Hello ${identity?.profile?.displayName}`
34
+ });
35
+ };
36
+ ```
37
+
38
+ ## Running functions with dev agent
39
+
40
+ Configure the agent to run functions on a given port:
41
+
42
+ ```yaml
43
+ # ~/.config/dx/profile/default.yml
44
+ runtime:
45
+ agent:
46
+ functions:
47
+ port: 7001
48
+ ```
49
+
50
+ Start functions in dev mode (from the related package):
51
+
52
+ ```bash
53
+ dx function dev -r ts-node/register
54
+ ```
55
+
56
+ > NOTE: `-r ts-node/register` configures native TypesScript support.
57
+
58
+ Install `nodemon` to support live reloading:
59
+
60
+ ```bash
61
+ npm i -g nodemon
62
+ export DXOS_ROOT=$(git rev-parse --show-toplevel)
63
+
64
+ nodemon -w ./src -e ts --exec $DXOS_ROOT/packages/devtools/cli/bin/dev function dev -r ts-node/register
65
+ ```
66
+
67
+ ## Invoking functions
68
+
69
+ > NOTE: The port (7001) must match the one in config.
70
+
71
+ ```bash
72
+ curl -X POST -H 'Content-Type: application/json' -w '\n' \
73
+ http://localhost:7001/dev/hello --data '{ "message": "Hello World!" }'
9
74
  ```
10
75
 
11
76
  ## DXOS Resources
@@ -7,91 +7,268 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
7
7
  throw new Error('Dynamic require of "' + x + '" is not supported');
8
8
  });
9
9
 
10
- // packages/core/functions/src/runtime/index.ts
10
+ // packages/core/functions/src/runtime/dev-server.ts
11
11
  import express from "express";
12
- import { readdir } from "@dxos/node-std/fs/promises";
13
- import { extname, join } from "@dxos/node-std/path";
12
+ import { join } from "@dxos/node-std/path";
14
13
  import { getPortPromise } from "portfinder";
14
+ import { Trigger } from "@dxos/async";
15
15
  import { log } from "@dxos/log";
16
- var FUNCTION_EXTENSIONS = [
17
- ".js",
18
- ".ts"
19
- ];
20
- var runFunctions = async (options) => {
21
- const files = await readdir(options.functionsDirectory);
22
- const functionHandlers = {};
23
- for (const file of files) {
24
- if (!FUNCTION_EXTENSIONS.some((ext) => extname(file) === ext)) {
25
- continue;
26
- }
27
- try {
28
- const module = __require(join(options.functionsDirectory, file));
29
- const handler = module.default;
30
- if (typeof handler !== "function") {
31
- throw new Error(`Function ${file} does not export a default function`);
16
+ var DEFAULT_PORT = 7e3;
17
+ var DevServer = class {
18
+ // prettier-ignore
19
+ constructor(_client, _options) {
20
+ this._client = _client;
21
+ this._options = _options;
22
+ this._functionHandlers = {};
23
+ }
24
+ get port() {
25
+ return this._port;
26
+ }
27
+ get endpoint() {
28
+ return this._port ? `http://localhost:${this._port}` : void 0;
29
+ }
30
+ get functions() {
31
+ return Object.keys(this._functionHandlers);
32
+ }
33
+ async initialize() {
34
+ for (const [name, _] of Object.entries(this._options.manifest.functions)) {
35
+ try {
36
+ const module = __require(join(this._options.directory, name));
37
+ const handler = module.default;
38
+ if (typeof handler !== "function") {
39
+ throw new Error(`Handler must export default function: ${name}`);
40
+ }
41
+ this._functionHandlers[name] = handler;
42
+ } catch (err) {
43
+ log.error("parsing function (check functions.yml manifest)", err, {
44
+ file: "dev-server.ts",
45
+ line: 63,
46
+ scope: this,
47
+ callSite: (f, a) => f(...a)
48
+ });
32
49
  }
33
- const functionName = file.slice(0, -extname(file).length);
34
- functionHandlers[functionName] = handler;
35
- } catch (e) {
36
- console.error(e);
37
50
  }
38
51
  }
39
- const port = await getPortPromise({
40
- startPort: 7e3
41
- });
42
- const app = express();
43
- app.use(express.json());
44
- app.post("/:functionName", async (req, res) => {
45
- const functionName = req.params.functionName;
46
- const replyBuilder = {
47
- status: (code) => {
48
- res.statusCode = code;
49
- return replyBuilder;
50
- },
51
- succeed: (result) => {
52
- res.end(JSON.stringify(result));
53
- return replyBuilder;
52
+ async start() {
53
+ const app = express();
54
+ app.use(express.json());
55
+ app.post("/:functionName", async (req, res) => {
56
+ const functionName = req.params.functionName;
57
+ log("invoke", {
58
+ function: functionName,
59
+ data: req.body
60
+ }, {
61
+ file: "dev-server.ts",
62
+ line: 74,
63
+ scope: this,
64
+ callSite: (f, a) => f(...a)
65
+ });
66
+ const builder = {
67
+ status: (code) => {
68
+ res.statusCode = code;
69
+ return builder;
70
+ },
71
+ succeed: (result = {}) => {
72
+ res.end(JSON.stringify(result));
73
+ return builder;
74
+ }
75
+ };
76
+ const context = {
77
+ client: this._client,
78
+ status: builder.status.bind(builder)
79
+ };
80
+ void (async () => {
81
+ try {
82
+ await this._functionHandlers[functionName](req.body, context);
83
+ } catch (err) {
84
+ res.statusCode = 500;
85
+ res.end(err.message);
86
+ }
87
+ })();
88
+ });
89
+ this._port = await getPortPromise({
90
+ startPort: DEFAULT_PORT
91
+ });
92
+ this._server = app.listen(this._port);
93
+ const { registrationId } = await this._client.services.services.FunctionRegistryService.register({
94
+ endpoint: this.endpoint,
95
+ functions: this.functions.map((name) => ({
96
+ name
97
+ }))
98
+ });
99
+ this._registrationId = registrationId;
100
+ }
101
+ async stop() {
102
+ var _a;
103
+ const trigger = new Trigger();
104
+ (_a = this._server) == null ? void 0 : _a.close(async () => {
105
+ if (this._registrationId) {
106
+ await this._client.services.services.FunctionRegistryService.unregister({
107
+ registrationId: this._registrationId
108
+ });
109
+ this._registrationId = void 0;
54
110
  }
55
- };
56
- const context = {
57
- client: options.client,
58
- status: replyBuilder.status.bind(replyBuilder)
59
- };
60
- void (async () => {
61
- try {
62
- await functionHandlers[functionName](req.body, context);
63
- } catch (err) {
64
- res.statusCode = 500;
65
- res.end(err.message);
111
+ trigger.wake();
112
+ });
113
+ await trigger.wait();
114
+ this._server = void 0;
115
+ this._port = void 0;
116
+ }
117
+ };
118
+
119
+ // packages/core/functions/src/runtime/trigger-manager.ts
120
+ import assert from "@dxos/node-std/assert";
121
+ import { DeferredTask } from "@dxos/async";
122
+ import { Context } from "@dxos/context";
123
+ import { createSubscription } from "@dxos/echo-schema";
124
+ import { log as log2 } from "@dxos/log";
125
+ import { ComplexMap } from "@dxos/util";
126
+ var TriggerManager = class {
127
+ constructor(_client, _triggers, _invokeOptions) {
128
+ this._client = _client;
129
+ this._triggers = _triggers;
130
+ this._invokeOptions = _invokeOptions;
131
+ this._mounts = new ComplexMap(({ name, spaceKey }) => `${spaceKey.toHex()}:${name}`);
132
+ }
133
+ async start() {
134
+ this._client.spaces.subscribe(async (spaces) => {
135
+ for (const space of spaces) {
136
+ await space.waitUntilReady();
137
+ for (const trigger of this._triggers) {
138
+ await this.mount(new Context(), trigger, space);
139
+ }
66
140
  }
67
- })();
68
- });
69
- app.listen(port);
70
- const functionNames = Object.keys(functionHandlers);
71
- const { registrationId } = await options.client.services.services.FunctionRegistryService.register({
72
- endpoint: `http://localhost:${port}`,
73
- functions: functionNames.map((name) => ({
74
- name
75
- }))
76
- });
77
- process.on("SIGINT", async () => {
78
- await options.client.services.services.FunctionRegistryService.unregister({
79
- registrationId
80
141
  });
81
- process.exit();
82
- });
83
- log.info("functions runtime started", {
84
- port,
85
- functionNames,
86
- registrationId
87
- }, {
88
- file: "index.ts",
89
- line: 93,
90
- scope: void 0,
91
- callSite: (f, a) => f(...a)
92
- });
142
+ }
143
+ async stop() {
144
+ for (const { name, spaceKey } of this._mounts.keys()) {
145
+ await this.unmount(name, spaceKey);
146
+ }
147
+ }
148
+ async mount(ctx, trigger, space) {
149
+ const key = {
150
+ name: trigger.function,
151
+ spaceKey: space.key
152
+ };
153
+ const exists = this._mounts.get(key);
154
+ if (!exists) {
155
+ this._mounts.set(key, {
156
+ ctx,
157
+ trigger
158
+ });
159
+ if (ctx.disposed) {
160
+ return;
161
+ }
162
+ let count = 0;
163
+ const objectIds = /* @__PURE__ */ new Set();
164
+ const task = new DeferredTask(ctx, async () => {
165
+ const updatedObjects = Array.from(objectIds);
166
+ objectIds.clear();
167
+ await this.invokeFunction(this._invokeOptions, trigger.function, {
168
+ space: space.key,
169
+ objects: updatedObjects
170
+ });
171
+ });
172
+ const selection = createSubscription(({ added, updated }) => {
173
+ for (const object of added) {
174
+ objectIds.add(object.id);
175
+ }
176
+ for (const object1 of updated) {
177
+ objectIds.add(object1.id);
178
+ }
179
+ log2.info("updated", {
180
+ space: space.key,
181
+ objects: objectIds.size,
182
+ added: added.length,
183
+ updated: updated.length,
184
+ count
185
+ }, {
186
+ file: "trigger-manager.ts",
187
+ line: 85,
188
+ scope: this,
189
+ callSite: (f, a) => f(...a)
190
+ });
191
+ if (count++) {
192
+ task.schedule();
193
+ }
194
+ });
195
+ ctx.onDispose(() => selection.unsubscribe());
196
+ const query = space.db.query({
197
+ ...trigger.subscription.props,
198
+ "@type": trigger.subscription.type
199
+ });
200
+ const unsubscribe = query.subscribe(({ objects }) => {
201
+ selection.update(objects);
202
+ });
203
+ ctx.onDispose(unsubscribe);
204
+ log2.info("mounted", {
205
+ space: space.key,
206
+ trigger
207
+ }, {
208
+ file: "trigger-manager.ts",
209
+ line: 109,
210
+ scope: this,
211
+ callSite: (f, a) => f(...a)
212
+ });
213
+ }
214
+ }
215
+ async unmount(name, spaceKey) {
216
+ var _a;
217
+ const key = {
218
+ name,
219
+ spaceKey
220
+ };
221
+ const { ctx } = (_a = this._mounts.get(key)) != null ? _a : {};
222
+ if (ctx) {
223
+ this._mounts.delete(key);
224
+ await ctx.dispose();
225
+ }
226
+ }
227
+ async invokeFunction(options, functionName, data) {
228
+ const { endpoint, runtime } = options;
229
+ assert(endpoint, "Missing endpoint");
230
+ assert(runtime, "Missing runtime");
231
+ try {
232
+ log2("invoke", {
233
+ function: functionName
234
+ }, {
235
+ file: "trigger-manager.ts",
236
+ line: 128,
237
+ scope: this,
238
+ callSite: (f, a) => f(...a)
239
+ });
240
+ const url = `${endpoint}/${runtime}/${functionName}`;
241
+ const res = await fetch(url, {
242
+ method: "POST",
243
+ body: JSON.stringify(data),
244
+ headers: {
245
+ "Content-Type": "application/json"
246
+ }
247
+ });
248
+ log2("result", {
249
+ function: functionName,
250
+ result: await res.json()
251
+ }, {
252
+ file: "trigger-manager.ts",
253
+ line: 138,
254
+ scope: this,
255
+ callSite: (f, a) => f(...a)
256
+ });
257
+ } catch (err) {
258
+ log2.error("error", {
259
+ function: functionName,
260
+ error: err.message
261
+ }, {
262
+ file: "trigger-manager.ts",
263
+ line: 140,
264
+ scope: this,
265
+ callSite: (f, a) => f(...a)
266
+ });
267
+ }
268
+ }
93
269
  };
94
270
  export {
95
- runFunctions
271
+ DevServer,
272
+ TriggerManager
96
273
  };
97
274
  //# sourceMappingURL=index.mjs.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../../src/runtime/index.ts"],
4
- "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport express from 'express';\nimport { readdir } from 'node:fs/promises';\nimport { extname, join } from 'node:path';\nimport { getPortPromise } from 'portfinder';\n\nimport { Client } from '@dxos/client';\nimport { log } from '@dxos/log';\n\nimport { FunctionContext, FunctionHandler, Reply } from '../interface';\n\nconst FUNCTION_EXTENSIONS = ['.js', '.ts'];\n\nexport type FunctionsRuntimeParams = {\n client: Client;\n functionsDirectory: string;\n};\n\nexport const runFunctions = async (options: FunctionsRuntimeParams) => {\n const files = await readdir(options.functionsDirectory);\n\n const functionHandlers: Record<string, FunctionHandler> = {};\n\n for (const file of files) {\n if (!FUNCTION_EXTENSIONS.some((ext) => extname(file) === ext)) {\n continue;\n }\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const module = require(join(options.functionsDirectory, file));\n const handler = module.default;\n if (typeof handler !== 'function') {\n throw new Error(`Function ${file} does not export a default function`);\n }\n\n const functionName = file.slice(0, -extname(file).length);\n\n functionHandlers[functionName] = handler;\n } catch (e) {\n console.error(e);\n }\n }\n\n const port = await getPortPromise({ startPort: 7000 });\n\n const app = express();\n app.use(express.json());\n\n app.post('/:functionName', async (req, res) => {\n const functionName = req.params.functionName;\n\n const replyBuilder: Reply = {\n status: (code: number) => {\n res.statusCode = code;\n return replyBuilder;\n },\n succeed: (result: any) => {\n res.end(JSON.stringify(result));\n return replyBuilder;\n },\n };\n const context: FunctionContext = {\n client: options.client,\n status: replyBuilder.status.bind(replyBuilder),\n };\n\n void (async () => {\n try {\n await functionHandlers[functionName](req.body, context);\n } catch (err: any) {\n res.statusCode = 500;\n res.end(err.message);\n }\n })();\n });\n app.listen(port);\n\n const functionNames = Object.keys(functionHandlers);\n const { registrationId } = await options.client.services.services.FunctionRegistryService!.register({\n endpoint: `http://localhost:${port}`,\n functions: functionNames.map((name) => ({ name })),\n });\n\n process.on('SIGINT', async () => {\n await options.client.services.services.FunctionRegistryService!.unregister({ registrationId });\n process.exit();\n });\n\n log.info('functions runtime started', { port, functionNames, registrationId });\n};\n"],
5
- "mappings": ";;;;;;;;;;AAIA,OAAOA,aAAa;AACpB,SAASC,eAAe;AACxB,SAASC,SAASC,YAAY;AAC9B,SAASC,sBAAsB;AAG/B,SAASC,WAAW;AAIpB,IAAMC,sBAAsB;EAAC;EAAO;;AAO7B,IAAMC,eAAe,OAAOC,YAAoC;AACrE,QAAMC,QAAQ,MAAMC,QAAQF,QAAQG,kBAAkB;AAEtD,QAAMC,mBAAoD,CAAC;AAE3D,aAAWC,QAAQJ,OAAO;AACxB,QAAI,CAACH,oBAAoBQ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OAAOU,SAASA,SAASC,wBAAyBC,SAAS;IAClGC,UAAU,oBAAoBlC;IAC9BmC,WAAWR,cAAcS,IAAI,CAACC,UAAU;MAAEA;IAAK,EAAA;EACjD,CAAA;AAEAC,UAAQC,GAAG,UAAU,YAAY;AAC/B,UAAM5D,QAAQ0C,OAAOU,SAASA,SAASC,wBAAyBQ,WAAW;MAAEV;IAAe,CAAA;AAC5FQ,YAAQG,KAAI;EACd,CAAA;AAEAC,MAAIC,KAAK,6BAA6B;IAAE3C;IAAM2B;IAAeG;EAAe,GAAA;;;;;;AAC9E;",
6
- "names": ["express", "readdir", "extname", "join", "getPortPromise", "log", "FUNCTION_EXTENSIONS", "runFunctions", "options", "files", "readdir", "functionsDirectory", "functionHandlers", "file", "some", "ext", "extname", "module", "require", "join", "handler", "default", "Error", "functionName", "slice", "length", "e", "console", "error", "port", "getPortPromise", "startPort", "app", "express", "use", "json", "post", "req", "res", "params", "replyBuilder", "status", "code", "statusCode", "succeed", "result", "end", "JSON", "stringify", "context", "client", "bind", "body", "err", "message", "listen", "functionNames", "Object", "keys", "registrationId", "services", "FunctionRegistryService", "register", "endpoint", "functions", "map", "name", "process", "on", "unregister", "exit", "log", "info"]
3
+ "sources": ["../../../src/runtime/dev-server.ts", "../../../src/runtime/trigger-manager.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport express from 'express';\nimport http from 'http';\nimport { join } from 'node:path';\nimport { getPortPromise } from 'portfinder';\n\nimport { Trigger } from '@dxos/async';\nimport { Client } from '@dxos/client';\nimport { log } from '@dxos/log';\n\nimport { FunctionContext, FunctionHandler, FunctionsManifest, Response } from '../function';\n\nconst DEFAULT_PORT = 7000;\n\nexport type DevServerOptions = {\n directory: string;\n manifest: FunctionsManifest;\n};\n\n/**\n * Functions dev server provides a local HTTP server for testing functions.\n */\nexport class DevServer {\n private readonly _functionHandlers: Record<string, FunctionHandler> = {};\n\n private _server?: http.Server;\n private _port?: number;\n private _registrationId?: string;\n\n // prettier-ignore\n constructor(\n private readonly _client: Client,\n private readonly _options: DevServerOptions\n ) {}\n\n get port() {\n return this._port;\n }\n\n get endpoint() {\n return this._port ? `http://localhost:${this._port}` : undefined;\n }\n\n get functions() {\n return Object.keys(this._functionHandlers);\n }\n\n async initialize() {\n for (const [name, _] of Object.entries(this._options.manifest.functions)) {\n try {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const module = require(join(this._options.directory, name));\n const handler = module.default;\n if (typeof handler !== 'function') {\n throw new Error(`Handler must export default function: ${name}`);\n }\n\n this._functionHandlers[name] = handler;\n } catch (err) {\n log.error('parsing function (check functions.yml manifest)', err);\n }\n }\n }\n\n async start() {\n const app = express();\n app.use(express.json());\n\n app.post('/:functionName', async (req, res) => {\n const functionName = req.params.functionName;\n log('invoke', { function: functionName, data: req.body });\n\n const builder: Response = {\n status: (code: number) => {\n res.statusCode = code;\n return builder;\n },\n succeed: (result = {}) => {\n res.end(JSON.stringify(result));\n return builder;\n },\n };\n\n const context: FunctionContext = {\n client: this._client,\n status: builder.status.bind(builder),\n };\n\n void (async () => {\n try {\n await this._functionHandlers[functionName](req.body, context);\n } catch (err: any) {\n res.statusCode = 500;\n res.end(err.message);\n }\n })();\n });\n\n this._port = await getPortPromise({ startPort: DEFAULT_PORT });\n this._server = app.listen(this._port);\n\n // TODO(burdon): Check plugin is registered.\n // TypeError: Cannot read properties of undefined (reading 'register')\n const { registrationId } = await this._client.services.services.FunctionRegistryService!.register({\n endpoint: this.endpoint!,\n functions: this.functions.map((name) => ({ name })),\n });\n this._registrationId = registrationId;\n }\n\n async stop() {\n const trigger = new Trigger();\n this._server?.close(async () => {\n if (this._registrationId) {\n await this._client.services.services.FunctionRegistryService!.unregister({\n registrationId: this._registrationId,\n });\n this._registrationId = undefined;\n }\n\n trigger.wake();\n });\n\n await trigger.wait();\n this._server = undefined;\n this._port = undefined;\n }\n}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport assert from 'node:assert';\n\nimport { DeferredTask } from '@dxos/async';\nimport { Client, PublicKey, Space } from '@dxos/client';\nimport { Context } from '@dxos/context';\nimport { createSubscription } from '@dxos/echo-schema';\nimport { log } from '@dxos/log';\nimport { ComplexMap } from '@dxos/util';\n\nimport { FunctionTrigger } from '../function';\n\n// TODO(burdon): Rename.\nexport type InvokeOptions = {\n endpoint: string;\n runtime: string;\n};\n\nexport class TriggerManager {\n private readonly _mounts = new ComplexMap<\n { name: string; spaceKey: PublicKey },\n { ctx: Context; trigger: FunctionTrigger }\n >(({ name, spaceKey }) => `${spaceKey.toHex()}:${name}`);\n\n constructor(\n private readonly _client: Client,\n private readonly _triggers: FunctionTrigger[],\n private readonly _invokeOptions: InvokeOptions,\n ) {}\n\n async start() {\n // TODO(burdon): Make runtime configurable (via CLI)?\n this._client.spaces.subscribe(async (spaces) => {\n for (const space of spaces) {\n await space.waitUntilReady();\n for (const trigger of this._triggers) {\n // TODO(burdon): New context? Shared?\n await this.mount(new Context(), trigger, space);\n }\n }\n });\n }\n\n async stop() {\n for (const { name, spaceKey } of this._mounts.keys()) {\n await this.unmount(name, spaceKey);\n }\n }\n\n private async mount(ctx: Context, trigger: FunctionTrigger, space: Space) {\n const key = { name: trigger.function, spaceKey: space.key };\n const exists = this._mounts.get(key);\n if (!exists) {\n this._mounts.set(key, { ctx, trigger });\n if (ctx.disposed) {\n return;\n }\n\n // TODO(burdon): Factor out subscription/result delta.\n\n let count = 0;\n const objectIds = new Set<string>();\n const task = new DeferredTask(ctx, async () => {\n const updatedObjects = Array.from(objectIds);\n objectIds.clear();\n\n await this.invokeFunction(this._invokeOptions, trigger.function, {\n space: space.key,\n objects: updatedObjects,\n });\n });\n\n // TODO(burdon): Removed?\n const selection = createSubscription(({ added, updated }) => {\n for (const object of added) {\n objectIds.add(object.id);\n }\n for (const object of updated) {\n objectIds.add(object.id);\n }\n\n log.info('updated', {\n space: space.key,\n objects: objectIds.size,\n added: added.length,\n updated: updated.length,\n count,\n });\n if (count++) {\n task.schedule();\n }\n });\n\n ctx.onDispose(() => selection.unsubscribe());\n\n const query = space.db.query({ ...trigger.subscription.props, '@type': trigger.subscription.type });\n const unsubscribe = query.subscribe(({ objects }) => {\n selection.update(objects);\n });\n\n // Trigger first update, but don't schedule task.\n // selection.update(query.objects);\n\n ctx.onDispose(unsubscribe);\n\n log.info('mounted', { space: space.key, trigger });\n }\n }\n\n private async unmount(name: string, spaceKey: PublicKey) {\n const key = { name, spaceKey };\n const { ctx } = this._mounts.get(key) ?? {};\n if (ctx) {\n this._mounts.delete(key);\n await ctx.dispose();\n }\n }\n\n private async invokeFunction(options: InvokeOptions, functionName: string, data: any) {\n const { endpoint, runtime } = options;\n assert(endpoint, 'Missing endpoint');\n assert(runtime, 'Missing runtime');\n\n try {\n log('invoke', { function: functionName });\n const url = `${endpoint}/${runtime}/${functionName}`;\n const res = await fetch(url, {\n method: 'POST',\n body: JSON.stringify(data),\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n\n log('result', { function: functionName, result: await res.json() });\n } catch (err: any) {\n log.error('error', { function: functionName, error: err.message });\n }\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;AAIA,OAAOA,aAAa;AAEpB,SAASC,YAAY;AACrB,SAASC,sBAAsB;AAE/B,SAASC,eAAe;AAExB,SAASC,WAAW;AAIpB,IAAMC,eAAe;AAUd,IAAMC,YAAN,MAAMA;;EAQXC,YACmBC,SACAC,UACjB;mBAFiBD;oBACAC;SATFC,oBAAqD,CAAC;EAUpE;EAEH,IAAIC,OAAO;AACT,WAAO,KAAKC;EACd;EAEA,IAAIC,WAAW;AACb,WAAO,KAAKD,QAAQ,oBAAoB,KAAKA,UAAUE;EACzD;EAEA,IAAIC,YAAY;AACd,WAAOC,OAAOC,KAAK,KAAKP,iBAAiB;EAC3C;EAEA,MAAMQ,aAAa;AACjB,eAAW,CAACC,MAAMC,CAAAA,KAAMJ,OAAOK,QAAQ,KAAKZ,SAASa,SAASP,SAAS,GAAG;AACxE,UAAI;AAEF,cAAMQ,SAASC,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djD,MAAAA,KAAI4C,KAAK,WAAW;QAAE9B,OAAOA,MAAMQ;QAAKN;MAAQ,GAAA;;;;;;IAClD;EACF;EAEA,MAAcI,QAAQZ,MAAcC,UAAqB;AAhH3D;AAiHI,UAAMa,MAAM;MAAEd;MAAMC;IAAS;AAC7B,UAAM,EAAEY,IAAG,KAAK,UAAKd,QAAQkB,IAAIH,GAAAA,MAAjB,YAAyB,CAAC;AAC1C,QAAID,KAAK;AACP,WAAKd,QAAQiD,OAAOlC,GAAAA;AACpB,YAAMD,IAAIoC,QAAO;IACnB;EACF;EAEA,MAAcrB,eAAesB,SAAwBC,cAAsBC,MAAW;AACpF,UAAM,EAAEC,UAAUC,QAAO,IAAKJ;AAC9B9D,WAAOiE,UAAU,kBAAA;AACjBjE,WAAOkE,SAAS,iBAAA;AAEhB,QAAI;AACF9D,MAAAA,KAAI,UAAU;QAAEuB,UAAUoC;MAAa,GAAA;;;;;;AACvC,YAAMI,MAAM,GAAGF,YAAYC,WAAWH;AACtC,YAAMK,MAAM,MAAMC,MAAMF,KAAK;QAC3BG,QAAQ;QACRC,MAAMC,KAAKC,UAAUT,IAAAA;QACrBU,SAAS;UACP,gBAAgB;QAClB;MACF,CAAA;AAEAtE,MAAAA,KAAI,UAAU;QAAEuB,UAAUoC;QAAcY,QAAQ,MAAMP,IAAIQ,KAAI;MAAG,GAAA;;;;;;IACnE,SAASC,KAAP;AACAzE,MAAAA,KAAI0E,MAAM,SAAS;QAAEnD,UAAUoC;QAAce,OAAOD,IAAIE;MAAQ,GAAA;;;;;;IAClE;EACF;AACF;",
6
+ "names": ["express", "join", "getPortPromise", "Trigger", "log", "DEFAULT_PORT", "DevServer", "constructor", "_client", "_options", "_functionHandlers", "port", "_port", "endpoint", "undefined", "functions", "Object", "keys", "initialize", "name", "_", "entries", "manifest", "module", "require", "join", "directory", "handler", "default", "Error", "err", "log", "error", "start", "app", "express", "use", "json", "post", "req", "res", "functionName", "params", "function", "data", "body", "builder", "status", "code", "statusCode", "succeed", "result", "end", "JSON", "stringify", "context", "client", "bind", "message", "getPortPromise", "startPort", "_server", "listen", "registrationId", "services", "FunctionRegistryService", "register", "map", "_registrationId", "stop", "trigger", "Trigger", "close", "unregister", "wake", "wait", "assert", "DeferredTask", "Context", "createSubscription", "log", "ComplexMap", "TriggerManager", "constructor", "_client", "_triggers", "_invokeOptions", "_mounts", "name", "spaceKey", "toHex", "start", "spaces", "subscribe", "space", "waitUntilReady", "trigger", "mount", "stop", "keys", "unmount", "ctx", "key", "function", "exists", "get", "set", "disposed", "count", "objectIds", "Set", "task", "updatedObjects", "Array", "from", "clear", "invokeFunction", "objects", "selection", "added", "updated", "object", "add", "id", "info", "size", "length", "schedule", "onDispose", "unsubscribe", "query", "db", "subscription", "props", "type", "update", "delete", "dispose", "options", "functionName", "data", "endpoint", "runtime", "url", "res", "fetch", "method", "body", "JSON", "stringify", "headers", "result", "json", "err", "error", "message"]
7
7
  }
@@ -1 +1 @@
1
- {"inputs":{"packages/core/functions/src/interface.ts":{"bytes":756,"imports":[]},"packages/core/functions/src/runtime/index.ts":{"bytes":9991,"imports":[{"path":"express","kind":"import-statement","external":true},{"path":"@dxos/node-std/fs/promises","kind":"import-statement","external":true},{"path":"@dxos/node-std/path","kind":"import-statement","external":true},{"path":"portfinder","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"<runtime>","kind":"import-statement","external":true}]},"packages/core/functions/src/index.ts":{"bytes":464,"imports":[{"path":"packages/core/functions/src/interface.ts","kind":"import-statement","original":"./interface"},{"path":"packages/core/functions/src/runtime/index.ts","kind":"import-statement","original":"./runtime"}]}},"outputs":{"packages/core/functions/dist/lib/browser/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":5283},"packages/core/functions/dist/lib/browser/index.mjs":{"imports":[{"path":"express","kind":"import-statement","external":true},{"path":"@dxos/node-std/fs/promises","kind":"import-statement","external":true},{"path":"@dxos/node-std/path","kind":"import-statement","external":true},{"path":"portfinder","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"exports":["runFunctions"],"entryPoint":"packages/core/functions/src/index.ts","inputs":{"packages/core/functions/src/index.ts":{"bytesInOutput":0},"packages/core/functions/src/runtime/index.ts":{"bytesInOutput":2358}},"bytes":2874}}}
1
+ {"inputs":{"packages/core/functions/src/function.ts":{"bytes":1332,"imports":[]},"packages/core/functions/src/runtime/dev-server.ts":{"bytes":13165,"imports":[{"path":"express","kind":"import-statement","external":true},{"path":"@dxos/node-std/path","kind":"import-statement","external":true},{"path":"portfinder","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"<runtime>","kind":"import-statement","external":true}]},"packages/core/functions/src/runtime/trigger-manager.ts":{"bytes":16131,"imports":[{"path":"@dxos/node-std/assert","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}]},"packages/core/functions/src/runtime/index.ts":{"bytes":489,"imports":[{"path":"packages/core/functions/src/runtime/dev-server.ts","kind":"import-statement","original":"./dev-server"},{"path":"packages/core/functions/src/runtime/trigger-manager.ts","kind":"import-statement","original":"./trigger-manager"}]},"packages/core/functions/src/index.ts":{"bytes":463,"imports":[{"path":"packages/core/functions/src/function.ts","kind":"import-statement","original":"./function"},{"path":"packages/core/functions/src/runtime/index.ts","kind":"import-statement","original":"./runtime"}]}},"outputs":{"packages/core/functions/dist/lib/browser/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":14165},"packages/core/functions/dist/lib/browser/index.mjs":{"imports":[{"path":"express","kind":"import-statement","external":true},{"path":"@dxos/node-std/path","kind":"import-statement","external":true},{"path":"portfinder","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/node-std/assert","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"exports":["DevServer","TriggerManager"],"entryPoint":"packages/core/functions/src/index.ts","inputs":{"packages/core/functions/src/index.ts":{"bytesInOutput":0},"packages/core/functions/src/runtime/dev-server.ts":{"bytesInOutput":3059},"packages/core/functions/src/runtime/index.ts":{"bytesInOutput":0},"packages/core/functions/src/runtime/trigger-manager.ts":{"bytesInOutput":4128}},"bytes":7782}}}