@dxos/functions 0.5.4 → 0.5.5-main.288794c

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