@dxos/functions 0.5.4-next.70d721e → 0.5.4

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 (40) hide show
  1. package/README.md +1 -1
  2. package/dist/lib/browser/index.mjs +1075 -17
  3. package/dist/lib/browser/index.mjs.map +4 -4
  4. package/dist/lib/browser/meta.json +1 -1
  5. package/dist/lib/node/index.cjs +1069 -15
  6. package/dist/lib/node/index.cjs.map +4 -4
  7. package/dist/lib/node/meta.json +1 -1
  8. package/dist/types/src/function/function-registry.d.ts +0 -1
  9. package/dist/types/src/function/function-registry.d.ts.map +1 -1
  10. package/dist/types/src/runtime/dev-server.d.ts +0 -1
  11. package/dist/types/src/runtime/dev-server.d.ts.map +1 -1
  12. package/dist/types/src/testing/index.d.ts +0 -1
  13. package/dist/types/src/testing/index.d.ts.map +1 -1
  14. package/dist/types/src/testing/setup.d.ts +1 -11
  15. package/dist/types/src/testing/setup.d.ts.map +1 -1
  16. package/dist/types/src/testing/util.d.ts +0 -2
  17. package/dist/types/src/testing/util.d.ts.map +1 -1
  18. package/package.json +14 -23
  19. package/src/function/function-registry.test.ts +1 -14
  20. package/src/function/function-registry.ts +0 -10
  21. package/src/runtime/dev-server.test.ts +24 -42
  22. package/src/runtime/dev-server.ts +13 -17
  23. package/src/testing/functions-integration.test.ts +45 -8
  24. package/src/testing/index.ts +0 -1
  25. package/src/testing/setup.ts +6 -63
  26. package/src/testing/util.ts +0 -10
  27. package/dist/lib/browser/chunk-ERL6PHMU.mjs +0 -1084
  28. package/dist/lib/browser/chunk-ERL6PHMU.mjs.map +0 -7
  29. package/dist/lib/browser/testing/index.mjs +0 -148
  30. package/dist/lib/browser/testing/index.mjs.map +0 -7
  31. package/dist/lib/node/chunk-INM6XAL7.cjs +0 -1097
  32. package/dist/lib/node/chunk-INM6XAL7.cjs.map +0 -7
  33. package/dist/lib/node/testing/index.cjs +0 -169
  34. package/dist/lib/node/testing/index.cjs.map +0 -7
  35. package/dist/types/src/testing/manifest.d.ts +0 -3
  36. package/dist/types/src/testing/manifest.d.ts.map +0 -1
  37. package/dist/types/src/testing/plugin-init.d.ts +0 -6
  38. package/dist/types/src/testing/plugin-init.d.ts.map +0 -1
  39. package/src/testing/manifest.ts +0 -15
  40. package/src/testing/plugin-init.ts +0 -20
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,34 +17,157 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
  var node_exports = {};
20
30
  __export(node_exports, {
21
- DevServer: () => import_chunk_INM6XAL7.DevServer,
31
+ DevServer: () => DevServer,
22
32
  FUNCTION_SCHEMA: () => import_chunk_3UYUR5N5.FUNCTION_SCHEMA,
23
33
  FunctionDef: () => import_chunk_3UYUR5N5.FunctionDef,
24
34
  FunctionManifestSchema: () => import_chunk_3UYUR5N5.FunctionManifestSchema,
25
- FunctionRegistry: () => import_chunk_INM6XAL7.FunctionRegistry,
35
+ FunctionRegistry: () => FunctionRegistry,
26
36
  FunctionTrigger: () => import_chunk_3UYUR5N5.FunctionTrigger,
27
- Scheduler: () => import_chunk_INM6XAL7.Scheduler,
28
- TriggerRegistry: () => import_chunk_INM6XAL7.TriggerRegistry,
37
+ Scheduler: () => Scheduler,
38
+ TriggerRegistry: () => TriggerRegistry,
29
39
  subscriptionHandler: () => subscriptionHandler
30
40
  });
31
41
  module.exports = __toCommonJS(node_exports);
32
- var import_chunk_INM6XAL7 = require("./chunk-INM6XAL7.cjs");
33
42
  var import_chunk_3UYUR5N5 = require("./chunk-3UYUR5N5.cjs");
34
- var import_types = require("@braneframe/types");
35
- var import_client = require("@dxos/client");
43
+ var import_async = require("@dxos/async");
44
+ var import_echo = require("@dxos/client/echo");
45
+ var import_context = require("@dxos/context");
46
+ var import_keys = require("@dxos/keys");
36
47
  var import_log = require("@dxos/log");
37
48
  var import_util = require("@dxos/util");
38
- var __dxlog_file = "/home/runner/work/dxos/dxos/packages/core/functions/src/handler.ts";
49
+ var import_types = require("@braneframe/types");
50
+ var import_client = require("@dxos/client");
51
+ var import_log2 = require("@dxos/log");
52
+ var import_util2 = require("@dxos/util");
53
+ var import_express = __toESM(require("express"));
54
+ var import_get_port_please = require("get-port-please");
55
+ var import_node_path = require("node:path");
56
+ var import_async2 = require("@dxos/async");
57
+ var import_context2 = require("@dxos/context");
58
+ var import_invariant = require("@dxos/invariant");
59
+ var import_log3 = require("@dxos/log");
60
+ var import_node_path2 = __toESM(require("node:path"));
61
+ var import_async3 = require("@dxos/async");
62
+ var import_context3 = require("@dxos/context");
63
+ var import_log4 = require("@dxos/log");
64
+ var import_async4 = require("@dxos/async");
65
+ var import_echo2 = require("@dxos/client/echo");
66
+ var import_context4 = require("@dxos/context");
67
+ var import_echo_schema = require("@dxos/echo-schema");
68
+ var import_invariant2 = require("@dxos/invariant");
69
+ var import_keys2 = require("@dxos/keys");
70
+ var import_log5 = require("@dxos/log");
71
+ var import_util3 = require("@dxos/util");
72
+ var import_types2 = require("@braneframe/types");
73
+ var import_async5 = require("@dxos/async");
74
+ var import_echo3 = require("@dxos/client/echo");
75
+ var import_echo_db = require("@dxos/echo-db");
76
+ var import_log6 = require("@dxos/log");
77
+ var import_cron = require("cron");
78
+ var import_async6 = require("@dxos/async");
79
+ var import_log7 = require("@dxos/log");
80
+ var import_get_port_please2 = require("get-port-please");
81
+ var import_node_http = __toESM(require("node:http"));
82
+ var import_log8 = require("@dxos/log");
83
+ var import_ws = __toESM(require("ws"));
84
+ var import_async7 = require("@dxos/async");
85
+ var import_log9 = require("@dxos/log");
86
+ var __dxlog_file = "/home/runner/work/dxos/dxos/packages/core/functions/src/function/function-registry.ts";
87
+ var FunctionRegistry = class extends import_context.Resource {
88
+ constructor(_client) {
89
+ super();
90
+ this._client = _client;
91
+ this._functionBySpaceKey = new import_util.ComplexMap(import_keys.PublicKey.hash);
92
+ this.registered = new import_async.Event();
93
+ }
94
+ getFunctions(space) {
95
+ return this._functionBySpaceKey.get(space.key) ?? [];
96
+ }
97
+ /**
98
+ * Loads function definitions from the manifest into the space.
99
+ * We first load all the definitions from the space to deduplicate by functionId.
100
+ */
101
+ async register(space, functions) {
102
+ (0, import_log.log)("register", {
103
+ space: space.key,
104
+ functions: functions?.length ?? 0
105
+ }, {
106
+ F: __dxlog_file,
107
+ L: 38,
108
+ S: this,
109
+ C: (f, a) => f(...a)
110
+ });
111
+ if (!functions?.length) {
112
+ return;
113
+ }
114
+ if (!space.db.graph.runtimeSchemaRegistry.hasSchema(import_chunk_3UYUR5N5.FunctionDef)) {
115
+ space.db.graph.runtimeSchemaRegistry.registerSchema(import_chunk_3UYUR5N5.FunctionDef);
116
+ }
117
+ const { objects: existing } = await space.db.query(import_echo.Filter.schema(import_chunk_3UYUR5N5.FunctionDef)).run();
118
+ const { added } = (0, import_util.diff)(existing, functions, (a, b) => a.uri === b.uri);
119
+ added.forEach((def) => space.db.add((0, import_echo.create)(import_chunk_3UYUR5N5.FunctionDef, def)));
120
+ }
121
+ async _open() {
122
+ import_log.log.info("opening...", void 0, {
123
+ F: __dxlog_file,
124
+ L: 54,
125
+ S: this,
126
+ C: (f, a) => f(...a)
127
+ });
128
+ const spacesSubscription = this._client.spaces.subscribe(async (spaces) => {
129
+ for (const space of spaces) {
130
+ if (this._functionBySpaceKey.has(space.key)) {
131
+ continue;
132
+ }
133
+ const registered = [];
134
+ this._functionBySpaceKey.set(space.key, registered);
135
+ await space.waitUntilReady();
136
+ if (this._ctx.disposed) {
137
+ break;
138
+ }
139
+ this._ctx.onDispose(space.db.query(import_echo.Filter.schema(import_chunk_3UYUR5N5.FunctionDef)).subscribe(({ objects }) => {
140
+ const { added } = (0, import_util.diff)(registered, objects, (a, b) => a.uri === b.uri);
141
+ if (added.length > 0) {
142
+ registered.push(...added);
143
+ this.registered.emit({
144
+ space,
145
+ added
146
+ });
147
+ }
148
+ }));
149
+ }
150
+ });
151
+ this._ctx.onDispose(() => spacesSubscription.unsubscribe());
152
+ }
153
+ async _close(_) {
154
+ import_log.log.info("closing...", void 0, {
155
+ F: __dxlog_file,
156
+ L: 87,
157
+ S: this,
158
+ C: (f, a) => f(...a)
159
+ });
160
+ this._functionBySpaceKey.clear();
161
+ }
162
+ };
163
+ var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/core/functions/src/handler.ts";
39
164
  var subscriptionHandler = (handler, types) => {
40
165
  return async ({ event: { data }, context, response, ...rest }) => {
41
166
  const { client } = context;
42
167
  const space = data.spaceKey ? client.spaces.get(import_client.PublicKey.from(data.spaceKey)) : void 0;
43
168
  if (!space) {
44
- import_log.log.error("Invalid space", void 0, {
45
- F: __dxlog_file,
169
+ import_log2.log.error("Invalid space", void 0, {
170
+ F: __dxlog_file2,
46
171
  L: 90,
47
172
  S: void 0,
48
173
  C: (f, a) => f(...a)
@@ -50,22 +175,22 @@ var subscriptionHandler = (handler, types) => {
50
175
  return response.status(500);
51
176
  }
52
177
  registerTypes(space, types);
53
- const objects = space ? data.objects?.map((id) => space.db.getObjectById(id)).filter(import_util.nonNullable) : [];
178
+ const objects = space ? data.objects?.map((id) => space.db.getObjectById(id)).filter(import_util2.nonNullable) : [];
54
179
  if (!!data.spaceKey && !space) {
55
- import_log.log.warn("invalid space", {
180
+ import_log2.log.warn("invalid space", {
56
181
  data
57
182
  }, {
58
- F: __dxlog_file,
183
+ F: __dxlog_file2,
59
184
  L: 100,
60
185
  S: void 0,
61
186
  C: (f, a) => f(...a)
62
187
  });
63
188
  } else {
64
- import_log.log.info("handler", {
189
+ import_log2.log.info("handler", {
65
190
  space: space?.key.truncate(),
66
191
  objects: objects?.length
67
192
  }, {
68
- F: __dxlog_file,
193
+ F: __dxlog_file2,
69
194
  L: 102,
70
195
  S: void 0,
71
196
  C: (f, a) => f(...a)
@@ -96,6 +221,935 @@ var registerTypes = (space, types = []) => {
96
221
  }
97
222
  }
98
223
  };
224
+ var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/core/functions/src/runtime/dev-server.ts";
225
+ var DevServer = class {
226
+ constructor(_client, _functionsRegistry, _options) {
227
+ this._client = _client;
228
+ this._functionsRegistry = _functionsRegistry;
229
+ this._options = _options;
230
+ this._ctx = createContext();
231
+ this._handlers = {};
232
+ this._seq = 0;
233
+ this.update = new import_async2.Event();
234
+ this._functionsRegistry.registered.on(async ({ added }) => {
235
+ added.forEach((def) => this._load(def));
236
+ await this._safeUpdateRegistration();
237
+ (0, import_log3.log)("new functions loaded", {
238
+ added
239
+ }, {
240
+ F: __dxlog_file3,
241
+ L: 53,
242
+ S: this,
243
+ C: (f, a) => f(...a)
244
+ });
245
+ });
246
+ }
247
+ get stats() {
248
+ return {
249
+ seq: this._seq
250
+ };
251
+ }
252
+ get endpoint() {
253
+ (0, import_invariant.invariant)(this._port, void 0, {
254
+ F: __dxlog_file3,
255
+ L: 64,
256
+ S: this,
257
+ A: [
258
+ "this._port",
259
+ ""
260
+ ]
261
+ });
262
+ return `http://localhost:${this._port}`;
263
+ }
264
+ get proxy() {
265
+ return this._proxy;
266
+ }
267
+ get functions() {
268
+ return Object.values(this._handlers);
269
+ }
270
+ async start() {
271
+ (0, import_invariant.invariant)(!this._server, void 0, {
272
+ F: __dxlog_file3,
273
+ L: 77,
274
+ S: this,
275
+ A: [
276
+ "!this._server",
277
+ ""
278
+ ]
279
+ });
280
+ import_log3.log.info("starting...", void 0, {
281
+ F: __dxlog_file3,
282
+ L: 78,
283
+ S: this,
284
+ C: (f, a) => f(...a)
285
+ });
286
+ this._ctx = createContext();
287
+ const app = (0, import_express.default)();
288
+ app.use(import_express.default.json());
289
+ app.post("/:path", async (req, res) => {
290
+ const { path: path2 } = req.params;
291
+ try {
292
+ import_log3.log.info("calling", {
293
+ path: path2
294
+ }, {
295
+ F: __dxlog_file3,
296
+ L: 88,
297
+ S: this,
298
+ C: (f, a) => f(...a)
299
+ });
300
+ if (this._options.reload) {
301
+ const { def } = this._handlers["/" + path2];
302
+ await this._load(def, true);
303
+ }
304
+ res.statusCode = await this.invoke("/" + path2, req.body);
305
+ res.end();
306
+ } catch (err) {
307
+ import_log3.log.catch(err, void 0, {
308
+ F: __dxlog_file3,
309
+ L: 98,
310
+ S: this,
311
+ C: (f, a) => f(...a)
312
+ });
313
+ res.statusCode = 500;
314
+ res.end();
315
+ }
316
+ });
317
+ this._port = await (0, import_get_port_please.getPort)({
318
+ host: "localhost",
319
+ port: 7200,
320
+ portRange: [
321
+ 7200,
322
+ 7299
323
+ ]
324
+ });
325
+ this._server = app.listen(this._port);
326
+ try {
327
+ const { registrationId, endpoint } = await this._client.services.services.FunctionRegistryService.register({
328
+ endpoint: this.endpoint
329
+ });
330
+ import_log3.log.info("registered", {
331
+ endpoint
332
+ }, {
333
+ F: __dxlog_file3,
334
+ L: 113,
335
+ S: this,
336
+ C: (f, a) => f(...a)
337
+ });
338
+ this._proxy = endpoint;
339
+ this._functionServiceRegistration = registrationId;
340
+ await this._functionsRegistry.open(this._ctx);
341
+ } catch (err) {
342
+ await this.stop();
343
+ throw new Error("FunctionRegistryService not available (check plugin is configured).");
344
+ }
345
+ import_log3.log.info("started", {
346
+ port: this._port
347
+ }, {
348
+ F: __dxlog_file3,
349
+ L: 124,
350
+ S: this,
351
+ C: (f, a) => f(...a)
352
+ });
353
+ }
354
+ async stop() {
355
+ (0, import_invariant.invariant)(this._server, void 0, {
356
+ F: __dxlog_file3,
357
+ L: 128,
358
+ S: this,
359
+ A: [
360
+ "this._server",
361
+ ""
362
+ ]
363
+ });
364
+ import_log3.log.info("stopping...", void 0, {
365
+ F: __dxlog_file3,
366
+ L: 129,
367
+ S: this,
368
+ C: (f, a) => f(...a)
369
+ });
370
+ const trigger = new import_async2.Trigger();
371
+ this._server.close(async () => {
372
+ import_log3.log.info("server stopped", void 0, {
373
+ F: __dxlog_file3,
374
+ L: 133,
375
+ S: this,
376
+ C: (f, a) => f(...a)
377
+ });
378
+ try {
379
+ if (this._functionServiceRegistration) {
380
+ (0, import_invariant.invariant)(this._client.services.services.FunctionRegistryService, void 0, {
381
+ F: __dxlog_file3,
382
+ L: 136,
383
+ S: this,
384
+ A: [
385
+ "this._client.services.services.FunctionRegistryService",
386
+ ""
387
+ ]
388
+ });
389
+ await this._client.services.services.FunctionRegistryService.unregister({
390
+ registrationId: this._functionServiceRegistration
391
+ });
392
+ import_log3.log.info("unregistered", {
393
+ registrationId: this._functionServiceRegistration
394
+ }, {
395
+ F: __dxlog_file3,
396
+ L: 141,
397
+ S: this,
398
+ C: (f, a) => f(...a)
399
+ });
400
+ this._functionServiceRegistration = void 0;
401
+ this._proxy = void 0;
402
+ }
403
+ trigger.wake();
404
+ } catch (err) {
405
+ trigger.throw(err);
406
+ }
407
+ });
408
+ await trigger.wait();
409
+ this._port = void 0;
410
+ this._server = void 0;
411
+ import_log3.log.info("stopped", void 0, {
412
+ F: __dxlog_file3,
413
+ L: 155,
414
+ S: this,
415
+ C: (f, a) => f(...a)
416
+ });
417
+ }
418
+ /**
419
+ * Load function.
420
+ */
421
+ async _load(def, force) {
422
+ const { uri, route, handler } = def;
423
+ const filePath = (0, import_node_path.join)(this._options.baseDir, handler);
424
+ import_log3.log.info("loading", {
425
+ uri,
426
+ force
427
+ }, {
428
+ F: __dxlog_file3,
429
+ L: 164,
430
+ S: this,
431
+ C: (f, a) => f(...a)
432
+ });
433
+ if (force) {
434
+ Object.keys(import_chunk_3UYUR5N5.__require.cache).filter((key) => key.startsWith(filePath)).forEach((key) => {
435
+ delete import_chunk_3UYUR5N5.__require.cache[key];
436
+ });
437
+ }
438
+ const module2 = (0, import_chunk_3UYUR5N5.__require)(filePath);
439
+ if (typeof module2.default !== "function") {
440
+ throw new Error(`Handler must export default function: ${uri}`);
441
+ }
442
+ this._handlers[route] = {
443
+ def,
444
+ handler: module2.default
445
+ };
446
+ }
447
+ async _safeUpdateRegistration() {
448
+ (0, import_invariant.invariant)(this._functionServiceRegistration, void 0, {
449
+ F: __dxlog_file3,
450
+ L: 186,
451
+ S: this,
452
+ A: [
453
+ "this._functionServiceRegistration",
454
+ ""
455
+ ]
456
+ });
457
+ try {
458
+ await this._client.services.services.FunctionRegistryService.updateRegistration({
459
+ registrationId: this._functionServiceRegistration,
460
+ functions: this.functions.map(({ def: { id, route } }) => ({
461
+ id,
462
+ route
463
+ }))
464
+ });
465
+ } catch (err) {
466
+ import_log3.log.catch(err, void 0, {
467
+ F: __dxlog_file3,
468
+ L: 193,
469
+ S: this,
470
+ C: (f, a) => f(...a)
471
+ });
472
+ }
473
+ }
474
+ /**
475
+ * Invoke function.
476
+ */
477
+ async invoke(path2, data) {
478
+ const seq = ++this._seq;
479
+ const now = Date.now();
480
+ import_log3.log.info("req", {
481
+ seq,
482
+ path: path2
483
+ }, {
484
+ F: __dxlog_file3,
485
+ L: 204,
486
+ S: this,
487
+ C: (f, a) => f(...a)
488
+ });
489
+ const statusCode = await this._invoke(path2, {
490
+ data
491
+ });
492
+ import_log3.log.info("res", {
493
+ seq,
494
+ path: path2,
495
+ statusCode,
496
+ duration: Date.now() - now
497
+ }, {
498
+ F: __dxlog_file3,
499
+ L: 207,
500
+ S: this,
501
+ C: (f, a) => f(...a)
502
+ });
503
+ this.update.emit(statusCode);
504
+ return statusCode;
505
+ }
506
+ async _invoke(path2, event) {
507
+ const { handler } = this._handlers[path2] ?? {};
508
+ (0, import_invariant.invariant)(handler, `invalid path: ${path2}`, {
509
+ F: __dxlog_file3,
510
+ L: 214,
511
+ S: this,
512
+ A: [
513
+ "handler",
514
+ "`invalid path: ${path}`"
515
+ ]
516
+ });
517
+ const context = {
518
+ client: this._client,
519
+ dataDir: this._options.dataDir
520
+ };
521
+ let statusCode = 200;
522
+ const response = {
523
+ status: (code) => {
524
+ statusCode = code;
525
+ return response;
526
+ }
527
+ };
528
+ await handler({
529
+ context,
530
+ event,
531
+ response
532
+ });
533
+ return statusCode;
534
+ }
535
+ };
536
+ var createContext = () => new import_context2.Context({
537
+ name: "DevServer"
538
+ });
539
+ var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/core/functions/src/runtime/scheduler.ts";
540
+ var Scheduler = class {
541
+ constructor(functions, triggers, _options = {}) {
542
+ this.functions = functions;
543
+ this.triggers = triggers;
544
+ this._options = _options;
545
+ this._ctx = createContext2();
546
+ this._functionUriToCallMutex = /* @__PURE__ */ new Map();
547
+ this.functions.registered.on(async ({ space, added }) => {
548
+ await this._safeActivateTriggers(space, this.triggers.getInactiveTriggers(space), added);
549
+ });
550
+ this.triggers.registered.on(async ({ space, triggers: triggers2 }) => {
551
+ await this._safeActivateTriggers(space, triggers2, this.functions.getFunctions(space));
552
+ });
553
+ }
554
+ async start() {
555
+ await this._ctx.dispose();
556
+ this._ctx = createContext2();
557
+ await this.functions.open(this._ctx);
558
+ await this.triggers.open(this._ctx);
559
+ }
560
+ async stop() {
561
+ await this._ctx.dispose();
562
+ await this.functions.close();
563
+ await this.triggers.close();
564
+ }
565
+ // TODO(burdon): Remove and update registries directly.
566
+ async register(space, manifest) {
567
+ await this.functions.register(space, manifest.functions);
568
+ await this.triggers.register(space, manifest);
569
+ }
570
+ async _safeActivateTriggers(space, triggers, functions) {
571
+ const mountTasks = triggers.map((trigger) => {
572
+ return this.activate(space, functions, trigger);
573
+ });
574
+ await Promise.all(mountTasks).catch(import_log4.log.catch);
575
+ }
576
+ async activate(space, functions, trigger) {
577
+ const definition = functions.find((def) => def.uri === trigger.function);
578
+ if (!definition) {
579
+ import_log4.log.info("function is not found for trigger", {
580
+ trigger
581
+ }, {
582
+ F: __dxlog_file4,
583
+ L: 78,
584
+ S: this,
585
+ C: (f, a) => f(...a)
586
+ });
587
+ return;
588
+ }
589
+ await this.triggers.activate(space, trigger, async (args) => {
590
+ const mutex = this._functionUriToCallMutex.get(definition.uri) ?? new import_async3.Mutex();
591
+ this._functionUriToCallMutex.set(definition.uri, mutex);
592
+ import_log4.log.info("function triggered, waiting for mutex", {
593
+ uri: definition.uri
594
+ }, {
595
+ F: __dxlog_file4,
596
+ L: 86,
597
+ S: this,
598
+ C: (f, a) => f(...a)
599
+ });
600
+ return mutex.executeSynchronized(() => {
601
+ import_log4.log.info("mutex acquired", {
602
+ uri: definition.uri
603
+ }, {
604
+ F: __dxlog_file4,
605
+ L: 88,
606
+ S: this,
607
+ C: (f, a) => f(...a)
608
+ });
609
+ return this._execFunction(definition, trigger, {
610
+ meta: trigger.meta ?? {},
611
+ data: {
612
+ ...args,
613
+ spaceKey: space.key
614
+ }
615
+ });
616
+ });
617
+ });
618
+ (0, import_log4.log)("activated trigger", {
619
+ space: space.key,
620
+ trigger
621
+ }, {
622
+ F: __dxlog_file4,
623
+ L: 96,
624
+ S: this,
625
+ C: (f, a) => f(...a)
626
+ });
627
+ }
628
+ async _execFunction(def, trigger, { data, meta }) {
629
+ let status = 0;
630
+ try {
631
+ const payload = Object.assign({}, meta && {
632
+ meta
633
+ }, data);
634
+ const { endpoint, callback } = this._options;
635
+ if (endpoint) {
636
+ const url = import_node_path2.default.join(endpoint, def.route);
637
+ import_log4.log.info("exec", {
638
+ function: def.uri,
639
+ url,
640
+ triggerType: trigger.spec.type
641
+ }, {
642
+ F: __dxlog_file4,
643
+ L: 113,
644
+ S: this,
645
+ C: (f, a) => f(...a)
646
+ });
647
+ const response = await fetch(url, {
648
+ method: "POST",
649
+ headers: {
650
+ "Content-Type": "application/json"
651
+ },
652
+ body: JSON.stringify(payload)
653
+ });
654
+ status = response.status;
655
+ } else if (callback) {
656
+ import_log4.log.info("exec", {
657
+ function: def.uri
658
+ }, {
659
+ F: __dxlog_file4,
660
+ L: 124,
661
+ S: this,
662
+ C: (f, a) => f(...a)
663
+ });
664
+ status = await callback(payload) ?? 200;
665
+ }
666
+ if (status && status >= 400) {
667
+ throw new Error(`Response: ${status}`);
668
+ }
669
+ import_log4.log.info("done", {
670
+ function: def.uri,
671
+ status
672
+ }, {
673
+ F: __dxlog_file4,
674
+ L: 134,
675
+ S: this,
676
+ C: (f, a) => f(...a)
677
+ });
678
+ } catch (err) {
679
+ import_log4.log.error("error", {
680
+ function: def.uri,
681
+ error: err.message
682
+ }, {
683
+ F: __dxlog_file4,
684
+ L: 136,
685
+ S: this,
686
+ C: (f, a) => f(...a)
687
+ });
688
+ status = 500;
689
+ }
690
+ return status;
691
+ }
692
+ };
693
+ var createContext2 = () => new import_context3.Context({
694
+ name: "FunctionScheduler"
695
+ });
696
+ var __dxlog_file5 = "/home/runner/work/dxos/dxos/packages/core/functions/src/trigger/type/subscription-trigger.ts";
697
+ var createSubscriptionTrigger = async (ctx, space, spec, callback) => {
698
+ const objectIds = /* @__PURE__ */ new Set();
699
+ const task = new import_async5.UpdateScheduler(ctx, async () => {
700
+ if (objectIds.size > 0) {
701
+ const objects = Array.from(objectIds);
702
+ objectIds.clear();
703
+ await callback({
704
+ objects
705
+ });
706
+ }
707
+ }, {
708
+ maxFrequency: 4
709
+ });
710
+ const subscriptions = [];
711
+ const subscription = (0, import_echo_db.createSubscription)(({ added, updated }) => {
712
+ const sizeBefore = objectIds.size;
713
+ for (const object of added) {
714
+ objectIds.add(object.id);
715
+ }
716
+ for (const object of updated) {
717
+ objectIds.add(object.id);
718
+ }
719
+ if (objectIds.size > sizeBefore) {
720
+ import_log6.log.info("updated", {
721
+ added: added.length,
722
+ updated: updated.length
723
+ }, {
724
+ F: __dxlog_file5,
725
+ L: 47,
726
+ S: void 0,
727
+ C: (f, a) => f(...a)
728
+ });
729
+ task.trigger();
730
+ }
731
+ });
732
+ subscriptions.push(() => subscription.unsubscribe());
733
+ const { filter, options: { deep, delay } = {} } = spec;
734
+ const update = ({ objects }) => {
735
+ import_log6.log.info("update", {
736
+ objects: objects.length
737
+ }, {
738
+ F: __dxlog_file5,
739
+ L: 57,
740
+ S: void 0,
741
+ C: (f, a) => f(...a)
742
+ });
743
+ subscription.update(objects);
744
+ if (deep) {
745
+ for (const object of objects) {
746
+ const content = object.content;
747
+ if (content instanceof import_types2.TextV0Type) {
748
+ subscriptions.push((0, import_echo_db.getAutomergeObjectCore)(content).updates.on((0, import_async5.debounce)(() => subscription.update([
749
+ object
750
+ ]), 1e3)));
751
+ }
752
+ }
753
+ }
754
+ };
755
+ import_log6.log.info("subscription", {
756
+ filter
757
+ }, {
758
+ F: __dxlog_file5,
759
+ L: 76,
760
+ S: void 0,
761
+ C: (f, a) => f(...a)
762
+ });
763
+ if (filter) {
764
+ const query = space.db.query(import_echo3.Filter.typename(filter[0].type, filter[0].props));
765
+ subscriptions.push(query.subscribe(delay ? (0, import_async5.debounce)(update, delay) : update));
766
+ }
767
+ ctx.onDispose(() => {
768
+ subscriptions.forEach((unsubscribe) => unsubscribe());
769
+ });
770
+ };
771
+ var __dxlog_file6 = "/home/runner/work/dxos/dxos/packages/core/functions/src/trigger/type/timer-trigger.ts";
772
+ var createTimerTrigger = async (ctx, space, spec, callback) => {
773
+ const task = new import_async6.DeferredTask(ctx, async () => {
774
+ await callback({});
775
+ });
776
+ let last = 0;
777
+ let run = 0;
778
+ const job = import_cron.CronJob.from({
779
+ cronTime: spec.cron,
780
+ runOnInit: false,
781
+ onTick: () => {
782
+ const now = Date.now();
783
+ const delta = last ? now - last : 0;
784
+ last = now;
785
+ run++;
786
+ import_log7.log.info("tick", {
787
+ space: space.key.truncate(),
788
+ count: run,
789
+ delta
790
+ }, {
791
+ F: __dxlog_file6,
792
+ L: 38,
793
+ S: void 0,
794
+ C: (f, a) => f(...a)
795
+ });
796
+ task.schedule();
797
+ }
798
+ });
799
+ job.start();
800
+ ctx.onDispose(() => job.stop());
801
+ };
802
+ var __dxlog_file7 = "/home/runner/work/dxos/dxos/packages/core/functions/src/trigger/type/webhook-trigger.ts";
803
+ var createWebhookTrigger = async (ctx, space, spec, callback) => {
804
+ const server = import_node_http.default.createServer(async (req, res) => {
805
+ if (req.method !== spec.method) {
806
+ res.statusCode = 405;
807
+ return res.end();
808
+ }
809
+ res.statusCode = await callback({});
810
+ res.end();
811
+ });
812
+ const port = await (0, import_get_port_please2.getPort)({
813
+ random: true
814
+ });
815
+ server.listen(port, () => {
816
+ import_log8.log.info("started webhook", {
817
+ port
818
+ }, {
819
+ F: __dxlog_file7,
820
+ L: 41,
821
+ S: void 0,
822
+ C: (f, a) => f(...a)
823
+ });
824
+ spec.port = port;
825
+ });
826
+ ctx.onDispose(() => {
827
+ server.close();
828
+ });
829
+ };
830
+ var __dxlog_file8 = "/home/runner/work/dxos/dxos/packages/core/functions/src/trigger/type/websocket-trigger.ts";
831
+ var createWebsocketTrigger = async (ctx, space, spec, callback, options = {
832
+ retryDelay: 2,
833
+ maxAttempts: 5
834
+ }) => {
835
+ const { url, init } = spec;
836
+ let ws;
837
+ for (let attempt = 1; attempt <= options.maxAttempts; attempt++) {
838
+ const open = new import_async7.Trigger();
839
+ ws = new import_ws.default(url);
840
+ Object.assign(ws, {
841
+ onopen: () => {
842
+ import_log9.log.info("opened", {
843
+ url
844
+ }, {
845
+ F: __dxlog_file8,
846
+ L: 40,
847
+ S: void 0,
848
+ C: (f, a) => f(...a)
849
+ });
850
+ if (spec.init) {
851
+ ws.send(new TextEncoder().encode(JSON.stringify(init)));
852
+ }
853
+ open.wake(true);
854
+ },
855
+ onclose: (event) => {
856
+ import_log9.log.info("closed", {
857
+ url,
858
+ code: event.code
859
+ }, {
860
+ F: __dxlog_file8,
861
+ L: 49,
862
+ S: void 0,
863
+ C: (f, a) => f(...a)
864
+ });
865
+ if (event.code === 1006) {
866
+ setTimeout(async () => {
867
+ import_log9.log.info(`reconnecting in ${options.retryDelay}s...`, {
868
+ url
869
+ }, {
870
+ F: __dxlog_file8,
871
+ L: 54,
872
+ S: void 0,
873
+ C: (f, a) => f(...a)
874
+ });
875
+ await createWebsocketTrigger(ctx, space, spec, callback, options);
876
+ }, options.retryDelay * 1e3);
877
+ }
878
+ open.wake(false);
879
+ },
880
+ onerror: (event) => {
881
+ import_log9.log.catch(event.error, {
882
+ url
883
+ }, {
884
+ F: __dxlog_file8,
885
+ L: 63,
886
+ S: void 0,
887
+ C: (f, a) => f(...a)
888
+ });
889
+ },
890
+ onmessage: async (event) => {
891
+ try {
892
+ import_log9.log.info("message", void 0, {
893
+ F: __dxlog_file8,
894
+ L: 68,
895
+ S: void 0,
896
+ C: (f, a) => f(...a)
897
+ });
898
+ const data = JSON.parse(new TextDecoder().decode(event.data));
899
+ await callback({
900
+ data
901
+ });
902
+ } catch (err) {
903
+ import_log9.log.catch(err, {
904
+ url
905
+ }, {
906
+ F: __dxlog_file8,
907
+ L: 72,
908
+ S: void 0,
909
+ C: (f, a) => f(...a)
910
+ });
911
+ }
912
+ }
913
+ });
914
+ const isOpen = await open.wait();
915
+ if (isOpen) {
916
+ break;
917
+ } else {
918
+ const wait = Math.pow(attempt, 2) * options.retryDelay;
919
+ if (attempt < options.maxAttempts) {
920
+ import_log9.log.warn(`failed to connect; trying again in ${wait}s`, {
921
+ attempt
922
+ }, {
923
+ F: __dxlog_file8,
924
+ L: 83,
925
+ S: void 0,
926
+ C: (f, a) => f(...a)
927
+ });
928
+ await (0, import_async7.sleep)(wait * 1e3);
929
+ }
930
+ }
931
+ }
932
+ ctx.onDispose(() => {
933
+ ws?.close();
934
+ });
935
+ };
936
+ var __dxlog_file9 = "/home/runner/work/dxos/dxos/packages/core/functions/src/trigger/trigger-registry.ts";
937
+ var triggerHandlers = {
938
+ subscription: createSubscriptionTrigger,
939
+ timer: createTimerTrigger,
940
+ webhook: createWebhookTrigger,
941
+ websocket: createWebsocketTrigger
942
+ };
943
+ var TriggerRegistry = class extends import_context4.Resource {
944
+ constructor(_client, _options) {
945
+ super();
946
+ this._client = _client;
947
+ this._options = _options;
948
+ this._triggersBySpaceKey = new import_util3.ComplexMap(import_keys2.PublicKey.hash);
949
+ this.registered = new import_async4.Event();
950
+ this.removed = new import_async4.Event();
951
+ }
952
+ getActiveTriggers(space) {
953
+ return this._getTriggers(space, (t) => t.activationCtx != null);
954
+ }
955
+ getInactiveTriggers(space) {
956
+ return this._getTriggers(space, (t) => t.activationCtx == null);
957
+ }
958
+ async activate(space, trigger, callback) {
959
+ (0, import_log5.log)("activate", {
960
+ space: space.key,
961
+ trigger
962
+ }, {
963
+ F: __dxlog_file9,
964
+ L: 72,
965
+ S: this,
966
+ C: (f, a) => f(...a)
967
+ });
968
+ const activationCtx = new import_context4.Context({
969
+ name: `FunctionTrigger-${trigger.function}`
970
+ });
971
+ this._ctx.onDispose(() => activationCtx.dispose());
972
+ const registeredTrigger = this._triggersBySpaceKey.get(space.key)?.find((reg) => reg.trigger.id === trigger.id);
973
+ (0, import_invariant2.invariant)(registeredTrigger, `Trigger is not registered: ${trigger.function}`, {
974
+ F: __dxlog_file9,
975
+ L: 77,
976
+ S: this,
977
+ A: [
978
+ "registeredTrigger",
979
+ "`Trigger is not registered: ${trigger.function}`"
980
+ ]
981
+ });
982
+ registeredTrigger.activationCtx = activationCtx;
983
+ try {
984
+ const options = this._options?.[trigger.spec.type];
985
+ await triggerHandlers[trigger.spec.type](activationCtx, space, trigger.spec, callback, options);
986
+ } catch (err) {
987
+ delete registeredTrigger.activationCtx;
988
+ throw err;
989
+ }
990
+ }
991
+ /**
992
+ * Loads triggers from the manifest into the space.
993
+ */
994
+ async register(space, manifest) {
995
+ (0, import_log5.log)("register", {
996
+ space: space.key
997
+ }, {
998
+ F: __dxlog_file9,
999
+ L: 93,
1000
+ S: this,
1001
+ C: (f, a) => f(...a)
1002
+ });
1003
+ if (!manifest.triggers?.length) {
1004
+ return;
1005
+ }
1006
+ if (!space.db.graph.runtimeSchemaRegistry.hasSchema(import_chunk_3UYUR5N5.FunctionTrigger)) {
1007
+ space.db.graph.runtimeSchemaRegistry.registerSchema(import_chunk_3UYUR5N5.FunctionTrigger);
1008
+ }
1009
+ const manifestTriggers = manifest.triggers.map((trigger) => {
1010
+ let keys = trigger[import_echo_schema.ECHO_ATTR_META]?.keys;
1011
+ delete trigger[import_echo_schema.ECHO_ATTR_META];
1012
+ if (!keys?.length) {
1013
+ keys = [
1014
+ (0, import_echo_schema.foreignKey)("manifest", [
1015
+ trigger.function,
1016
+ trigger.spec.type
1017
+ ].join(":"))
1018
+ ];
1019
+ }
1020
+ return (0, import_echo2.create)(import_chunk_3UYUR5N5.FunctionTrigger, trigger, {
1021
+ keys
1022
+ });
1023
+ });
1024
+ const { objects: existing } = await space.db.query(import_echo2.Filter.schema(import_chunk_3UYUR5N5.FunctionTrigger)).run();
1025
+ const { added } = (0, import_util3.diff)(existing, manifestTriggers, import_echo_schema.compareForeignKeys);
1026
+ added.forEach((trigger) => {
1027
+ space.db.add(trigger);
1028
+ import_log5.log.info("added", {
1029
+ meta: (0, import_echo2.getMeta)(trigger)
1030
+ }, {
1031
+ F: __dxlog_file9,
1032
+ L: 120,
1033
+ S: this,
1034
+ C: (f, a) => f(...a)
1035
+ });
1036
+ });
1037
+ if (added.length > 0) {
1038
+ await space.db.flush();
1039
+ }
1040
+ }
1041
+ async _open() {
1042
+ import_log5.log.info("open...", void 0, {
1043
+ F: __dxlog_file9,
1044
+ L: 129,
1045
+ S: this,
1046
+ C: (f, a) => f(...a)
1047
+ });
1048
+ const spaceListSubscription = this._client.spaces.subscribe(async (spaces) => {
1049
+ for (const space of spaces) {
1050
+ if (this._triggersBySpaceKey.has(space.key)) {
1051
+ continue;
1052
+ }
1053
+ const registered = [];
1054
+ this._triggersBySpaceKey.set(space.key, registered);
1055
+ await space.waitUntilReady();
1056
+ if (this._ctx.disposed) {
1057
+ break;
1058
+ }
1059
+ this._ctx.onDispose(space.db.query(import_echo2.Filter.schema(import_chunk_3UYUR5N5.FunctionTrigger)).subscribe(async ({ objects: current }) => {
1060
+ import_log5.log.info("update", {
1061
+ space: space.key,
1062
+ registered: registered.length,
1063
+ current: current.length
1064
+ }, {
1065
+ F: __dxlog_file9,
1066
+ L: 146,
1067
+ S: this,
1068
+ C: (f, a) => f(...a)
1069
+ });
1070
+ await this._handleRemovedTriggers(space, current, registered);
1071
+ this._handleNewTriggers(space, current, registered);
1072
+ }));
1073
+ }
1074
+ });
1075
+ this._ctx.onDispose(() => spaceListSubscription.unsubscribe());
1076
+ import_log5.log.info("opened", void 0, {
1077
+ F: __dxlog_file9,
1078
+ L: 155,
1079
+ S: this,
1080
+ C: (f, a) => f(...a)
1081
+ });
1082
+ }
1083
+ async _close(_) {
1084
+ import_log5.log.info("close...", void 0, {
1085
+ F: __dxlog_file9,
1086
+ L: 159,
1087
+ S: this,
1088
+ C: (f, a) => f(...a)
1089
+ });
1090
+ this._triggersBySpaceKey.clear();
1091
+ import_log5.log.info("closed", void 0, {
1092
+ F: __dxlog_file9,
1093
+ L: 161,
1094
+ S: this,
1095
+ C: (f, a) => f(...a)
1096
+ });
1097
+ }
1098
+ _handleNewTriggers(space, current, registered) {
1099
+ const added = current.filter((candidate) => {
1100
+ return candidate.enabled && registered.find((reg) => reg.trigger.id === candidate.id) == null;
1101
+ });
1102
+ if (added.length > 0) {
1103
+ const newRegisteredTriggers = added.map((trigger) => ({
1104
+ trigger
1105
+ }));
1106
+ registered.push(...newRegisteredTriggers);
1107
+ import_log5.log.info("added", () => ({
1108
+ spaceKey: space.key,
1109
+ triggers: added.map((trigger) => trigger.function)
1110
+ }), {
1111
+ F: __dxlog_file9,
1112
+ L: 172,
1113
+ S: this,
1114
+ C: (f, a) => f(...a)
1115
+ });
1116
+ this.registered.emit({
1117
+ space,
1118
+ triggers: added
1119
+ });
1120
+ }
1121
+ }
1122
+ async _handleRemovedTriggers(space, current, registered) {
1123
+ const removed = [];
1124
+ for (let i = registered.length - 1; i >= 0; i--) {
1125
+ const wasRemoved = current.filter((trigger) => trigger.enabled).find((trigger) => trigger.id === registered[i].trigger.id) == null;
1126
+ if (wasRemoved) {
1127
+ const unregistered = registered.splice(i, 1)[0];
1128
+ await unregistered.activationCtx?.dispose();
1129
+ removed.push(unregistered.trigger);
1130
+ }
1131
+ }
1132
+ if (removed.length > 0) {
1133
+ import_log5.log.info("removed", () => ({
1134
+ spaceKey: space.key,
1135
+ triggers: removed.map((trigger) => trigger.function)
1136
+ }), {
1137
+ F: __dxlog_file9,
1138
+ L: 198,
1139
+ S: this,
1140
+ C: (f, a) => f(...a)
1141
+ });
1142
+ this.removed.emit({
1143
+ space,
1144
+ triggers: removed
1145
+ });
1146
+ }
1147
+ }
1148
+ _getTriggers(space, predicate) {
1149
+ const allSpaceTriggers = this._triggersBySpaceKey.get(space.key) ?? [];
1150
+ return allSpaceTriggers.filter(predicate).map((trigger) => trigger.trigger);
1151
+ }
1152
+ };
99
1153
  // Annotate the CommonJS export names for ESM import in node:
100
1154
  0 && (module.exports = {
101
1155
  DevServer,