@dxos/functions 0.8.1-main.ae460ac → 0.8.1-staging.31c3ee1

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 (75) hide show
  1. package/dist/lib/browser/{chunk-TMUL6AZC.mjs → chunk-HI7YZO2K.mjs} +27 -25
  2. package/dist/lib/browser/chunk-HI7YZO2K.mjs.map +7 -0
  3. package/dist/lib/browser/chunk-LT4LR4VU.mjs +72 -0
  4. package/dist/lib/browser/chunk-LT4LR4VU.mjs.map +7 -0
  5. package/dist/lib/browser/{chunk-XK3NINVF.mjs → chunk-RVSG6WTL.mjs} +156 -19
  6. package/dist/lib/browser/chunk-RVSG6WTL.mjs.map +7 -0
  7. package/dist/lib/browser/edge/index.mjs +1 -9
  8. package/dist/lib/browser/index.mjs +16 -10
  9. package/dist/lib/browser/index.mjs.map +2 -2
  10. package/dist/lib/browser/meta.json +1 -1
  11. package/dist/lib/browser/testing/index.mjs +2 -2
  12. package/dist/lib/browser/types/index.mjs +19 -5
  13. package/dist/lib/node/{chunk-3J6FVYUV.cjs → chunk-DSUGRAAL.cjs} +164 -22
  14. package/dist/lib/node/chunk-DSUGRAAL.cjs.map +7 -0
  15. package/dist/lib/node/chunk-NXZNXVT3.cjs +94 -0
  16. package/dist/lib/node/chunk-NXZNXVT3.cjs.map +7 -0
  17. package/dist/lib/node/{chunk-BGDVH6JU.cjs → chunk-RXMCVAMJ.cjs} +40 -38
  18. package/dist/lib/node/chunk-RXMCVAMJ.cjs.map +7 -0
  19. package/dist/lib/node/edge/index.cjs +4 -12
  20. package/dist/lib/node/edge/index.cjs.map +2 -2
  21. package/dist/lib/node/index.cjs +35 -29
  22. package/dist/lib/node/index.cjs.map +2 -2
  23. package/dist/lib/node/meta.json +1 -1
  24. package/dist/lib/node/testing/index.cjs +7 -7
  25. package/dist/lib/node/types/index.cjs +31 -17
  26. package/dist/lib/node/types/index.cjs.map +2 -2
  27. package/dist/lib/node-esm/{chunk-QRMVAODA.mjs → chunk-HBD2FZXO.mjs} +156 -19
  28. package/dist/lib/node-esm/chunk-HBD2FZXO.mjs.map +7 -0
  29. package/dist/lib/node-esm/chunk-O2SXVYU5.mjs +72 -0
  30. package/dist/lib/node-esm/chunk-O2SXVYU5.mjs.map +7 -0
  31. package/dist/lib/node-esm/{chunk-V3VOPFP3.mjs → chunk-SQSJO5HI.mjs} +27 -25
  32. package/dist/lib/node-esm/chunk-SQSJO5HI.mjs.map +7 -0
  33. package/dist/lib/node-esm/edge/index.mjs +1 -9
  34. package/dist/lib/node-esm/index.mjs +16 -10
  35. package/dist/lib/node-esm/index.mjs.map +2 -2
  36. package/dist/lib/node-esm/meta.json +1 -1
  37. package/dist/lib/node-esm/testing/index.mjs +2 -2
  38. package/dist/lib/node-esm/types/index.mjs +19 -5
  39. package/dist/types/src/edge/functions.d.ts +3 -12
  40. package/dist/types/src/edge/functions.d.ts.map +1 -1
  41. package/dist/types/src/handler.d.ts +1 -1
  42. package/dist/types/src/handler.d.ts.map +1 -1
  43. package/dist/types/src/trigger/type/timer-trigger.d.ts.map +1 -1
  44. package/dist/types/src/types/index.d.ts +1 -0
  45. package/dist/types/src/types/index.d.ts.map +1 -1
  46. package/dist/types/src/types/schema.d.ts +20 -26
  47. package/dist/types/src/types/schema.d.ts.map +1 -1
  48. package/dist/types/src/types/trace.d.ts +103 -97
  49. package/dist/types/src/types/trace.d.ts.map +1 -1
  50. package/dist/types/src/types/types.d.ts +7 -7
  51. package/dist/types/src/types/types.d.ts.map +1 -1
  52. package/dist/types/src/types/url.d.ts +11 -0
  53. package/dist/types/src/types/url.d.ts.map +1 -0
  54. package/package.json +20 -19
  55. package/src/edge/functions.ts +12 -71
  56. package/src/handler.ts +2 -2
  57. package/src/runtime/scheduler.test.ts +2 -1
  58. package/src/trigger/type/timer-trigger.ts +21 -18
  59. package/src/types/index.ts +1 -0
  60. package/src/types/schema.ts +7 -7
  61. package/src/types/trace.ts +120 -8
  62. package/src/types/types.ts +2 -1
  63. package/src/types/url.ts +47 -0
  64. package/dist/lib/browser/chunk-TMUL6AZC.mjs.map +0 -7
  65. package/dist/lib/browser/chunk-XK3NINVF.mjs.map +0 -7
  66. package/dist/lib/browser/chunk-YJEIETRB.mjs +0 -128
  67. package/dist/lib/browser/chunk-YJEIETRB.mjs.map +0 -7
  68. package/dist/lib/node/chunk-3J6FVYUV.cjs.map +0 -7
  69. package/dist/lib/node/chunk-BGDVH6JU.cjs.map +0 -7
  70. package/dist/lib/node/chunk-MZMHE4DC.cjs +0 -154
  71. package/dist/lib/node/chunk-MZMHE4DC.cjs.map +0 -7
  72. package/dist/lib/node-esm/chunk-QRMVAODA.mjs.map +0 -7
  73. package/dist/lib/node-esm/chunk-T2KBXTMR.mjs +0 -128
  74. package/dist/lib/node-esm/chunk-T2KBXTMR.mjs.map +0 -7
  75. package/dist/lib/node-esm/chunk-V3VOPFP3.mjs.map +0 -7
@@ -0,0 +1,94 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var chunk_NXZNXVT3_exports = {};
20
+ __export(chunk_NXZNXVT3_exports, {
21
+ incrementSemverPatch: () => incrementSemverPatch,
22
+ publicKeyToDid: () => publicKeyToDid,
23
+ uploadWorkerFunction: () => uploadWorkerFunction
24
+ });
25
+ module.exports = __toCommonJS(chunk_NXZNXVT3_exports);
26
+ var import_edge = require("@dxos/client/edge");
27
+ var import_edge_client = require("@dxos/edge-client");
28
+ var import_invariant = require("@dxos/invariant");
29
+ var import_log = require("@dxos/log");
30
+ var __dxlog_file = "/home/runner/work/dxos/dxos/packages/core/functions/src/edge/functions.ts";
31
+ var uploadWorkerFunction = async ({ client, spaceId, version, source, name, functionId }) => {
32
+ const edgeUrl = client.config.values.runtime?.services?.edge?.url;
33
+ (0, import_invariant.invariant)(edgeUrl, "Edge is not configured.", {
34
+ F: __dxlog_file,
35
+ L: 33,
36
+ S: void 0,
37
+ A: [
38
+ "edgeUrl",
39
+ "'Edge is not configured.'"
40
+ ]
41
+ });
42
+ const edgeClient = new import_edge_client.EdgeHttpClient(edgeUrl);
43
+ const edgeIdentity = (0, import_edge.createEdgeIdentity)(client);
44
+ edgeClient.setIdentity(edgeIdentity);
45
+ const response = await edgeClient.uploadFunction({
46
+ spaceId,
47
+ functionId
48
+ }, {
49
+ name,
50
+ version,
51
+ script: source
52
+ });
53
+ import_log.log.info("Uploaded", {
54
+ identityKey: edgeIdentity.identityKey,
55
+ functionId,
56
+ name,
57
+ source: source.length,
58
+ response
59
+ }, {
60
+ F: __dxlog_file,
61
+ L: 40,
62
+ S: void 0,
63
+ C: (f, a) => f(...a)
64
+ });
65
+ return response;
66
+ };
67
+ var incrementSemverPatch = (version) => {
68
+ const [major, minor, patch] = version.split(".");
69
+ const patchNum = Number(patch);
70
+ (0, import_invariant.invariant)(!Number.isNaN(patchNum), `Unexpected function version format: ${version}`, {
71
+ F: __dxlog_file,
72
+ L: 54,
73
+ S: void 0,
74
+ A: [
75
+ "!Number.isNaN(patchNum)",
76
+ "`Unexpected function version format: ${version}`"
77
+ ]
78
+ });
79
+ return [
80
+ major,
81
+ minor,
82
+ String(patchNum + 1)
83
+ ].join(".");
84
+ };
85
+ var publicKeyToDid = (key) => {
86
+ return `did:key:${key.toHex()}`;
87
+ };
88
+ // Annotate the CommonJS export names for ESM import in node:
89
+ 0 && (module.exports = {
90
+ incrementSemverPatch,
91
+ publicKeyToDid,
92
+ uploadWorkerFunction
93
+ });
94
+ //# sourceMappingURL=chunk-NXZNXVT3.cjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/edge/functions.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { type DID } from 'iso-did/types';\n\nimport { type Client } from '@dxos/client';\nimport { createEdgeIdentity } from '@dxos/client/edge';\nimport { EdgeHttpClient } from '@dxos/edge-client';\nimport { invariant } from '@dxos/invariant';\nimport type { PublicKey, SpaceId } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { type UploadFunctionResponseBody } from '@dxos/protocols';\n\nexport type UploadWorkerArgs = {\n client: Client;\n spaceId: SpaceId;\n source: string;\n version: string;\n name?: string;\n functionId?: string;\n};\n\nexport const uploadWorkerFunction = async ({\n client,\n spaceId,\n version,\n source,\n name,\n functionId,\n}: UploadWorkerArgs): Promise<UploadFunctionResponseBody> => {\n const edgeUrl = client.config.values.runtime?.services?.edge?.url;\n invariant(edgeUrl, 'Edge is not configured.');\n const edgeClient = new EdgeHttpClient(edgeUrl);\n const edgeIdentity = createEdgeIdentity(client);\n edgeClient.setIdentity(edgeIdentity);\n const response = await edgeClient.uploadFunction({ spaceId, functionId }, { name, version, script: source });\n\n // TODO(burdon): Edge service log.\n log.info('Uploaded', {\n identityKey: edgeIdentity.identityKey,\n functionId,\n name,\n source: source.length,\n response,\n });\n\n return response;\n};\n\nexport const incrementSemverPatch = (version: string): string => {\n const [major, minor, patch] = version.split('.');\n const patchNum = Number(patch);\n invariant(!Number.isNaN(patchNum), `Unexpected function version format: ${version}`);\n return [major, minor, String(patchNum + 1)].join('.');\n};\n\n// TODO(burdon): Factor out.\nexport const publicKeyToDid = (key: PublicKey): DID => {\n return `did:key:${key.toHex()}`;\n};\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;AAOA,kBAAmC;AACnC,yBAA+B;AAC/B,uBAA0B;AAE1B,iBAAoB;;AAYb,IAAMA,uBAAuB,OAAO,EACzCC,QACAC,SACAC,SACAC,QACAC,MACAC,WAAU,MACO;AACjB,QAAMC,UAAUN,OAAOO,OAAOC,OAAOC,SAASC,UAAUC,MAAMC;AAC9DC,kCAAUP,SAAS,2BAAA;;;;;;;;;AACnB,QAAMQ,aAAa,IAAIC,kCAAeT,OAAAA;AACtC,QAAMU,mBAAeC,gCAAmBjB,MAAAA;AACxCc,aAAWI,YAAYF,YAAAA;AACvB,QAAMG,WAAW,MAAML,WAAWM,eAAe;IAAEnB;IAASI;EAAW,GAAG;IAAED;IAAMF;IAASmB,QAAQlB;EAAO,CAAA;AAG1GmB,iBAAIC,KAAK,YAAY;IACnBC,aAAaR,aAAaQ;IAC1BnB;IACAD;IACAD,QAAQA,OAAOsB;IACfN;EACF,GAAA;;;;;;AAEA,SAAOA;AACT;AAEO,IAAMO,uBAAuB,CAACxB,YAAAA;AACnC,QAAM,CAACyB,OAAOC,OAAOC,KAAAA,IAAS3B,QAAQ4B,MAAM,GAAA;AAC5C,QAAMC,WAAWC,OAAOH,KAAAA;AACxBhB,kCAAU,CAACmB,OAAOC,MAAMF,QAAAA,GAAW,uCAAuC7B,OAAAA,IAAS;;;;;;;;;AACnF,SAAO;IAACyB;IAAOC;IAAOM,OAAOH,WAAW,CAAA;IAAII,KAAK,GAAA;AACnD;AAGO,IAAMC,iBAAiB,CAACC,QAAAA;AAC7B,SAAO,WAAWA,IAAIC,MAAK,CAAA;AAC7B;",
6
+ "names": ["uploadWorkerFunction", "client", "spaceId", "version", "source", "name", "functionId", "edgeUrl", "config", "values", "runtime", "services", "edge", "url", "invariant", "edgeClient", "EdgeHttpClient", "edgeIdentity", "createEdgeIdentity", "setIdentity", "response", "uploadFunction", "script", "log", "info", "identityKey", "length", "incrementSemverPatch", "major", "minor", "patch", "split", "patchNum", "Number", "isNaN", "String", "join", "publicKeyToDid", "key", "toHex"]
7
+ }
@@ -16,15 +16,15 @@ var __copyProps = (to, from, except, desc) => {
16
16
  return to;
17
17
  };
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var chunk_BGDVH6JU_exports = {};
20
- __export(chunk_BGDVH6JU_exports, {
19
+ var chunk_RXMCVAMJ_exports = {};
20
+ __export(chunk_RXMCVAMJ_exports, {
21
21
  FunctionRegistry: () => FunctionRegistry,
22
22
  TriggerRegistry: () => TriggerRegistry,
23
23
  createSubscriptionTrigger: () => createSubscriptionTrigger,
24
24
  createTimerTrigger: () => createTimerTrigger
25
25
  });
26
- module.exports = __toCommonJS(chunk_BGDVH6JU_exports);
27
- var import_chunk_3J6FVYUV = require("./chunk-3J6FVYUV.cjs");
26
+ module.exports = __toCommonJS(chunk_RXMCVAMJ_exports);
27
+ var import_chunk_DSUGRAAL = require("./chunk-DSUGRAAL.cjs");
28
28
  var import_async = require("@dxos/async");
29
29
  var import_echo = require("@dxos/client/echo");
30
30
  var import_context = require("@dxos/context");
@@ -35,7 +35,7 @@ var import_async2 = require("@dxos/async");
35
35
  var import_echo2 = require("@dxos/client/echo");
36
36
  var import_echo_db = require("@dxos/echo-db");
37
37
  var import_log2 = require("@dxos/log");
38
- var import_cron = require("cron");
38
+ var import_cron_schedule = require("cron-schedule");
39
39
  var import_async3 = require("@dxos/async");
40
40
  var import_log3 = require("@dxos/log");
41
41
  var import_async4 = require("@dxos/async");
@@ -85,14 +85,14 @@ var FunctionRegistry = class extends import_context.Resource {
85
85
  if (!functions?.length) {
86
86
  return;
87
87
  }
88
- if (!space.db.graph.schemaRegistry.hasSchema(import_chunk_3J6FVYUV.FunctionDef)) {
88
+ if (!space.db.graph.schemaRegistry.hasSchema(import_chunk_DSUGRAAL.FunctionDef)) {
89
89
  space.db.graph.schemaRegistry.addSchema([
90
- import_chunk_3J6FVYUV.FunctionDef
90
+ import_chunk_DSUGRAAL.FunctionDef
91
91
  ]);
92
92
  }
93
- const { objects: existing } = await space.db.query(import_echo.Filter.schema(import_chunk_3J6FVYUV.FunctionDef)).run();
93
+ const { objects: existing } = await space.db.query(import_echo.Filter.schema(import_chunk_DSUGRAAL.FunctionDef)).run();
94
94
  const { added } = (0, import_util.diff)(existing, functions, (a, b) => a.uri === b.uri);
95
- added.forEach((def) => space.db.add((0, import_echo.create)(import_chunk_3J6FVYUV.FunctionDef, def)));
95
+ added.forEach((def) => space.db.add((0, import_echo.create)(import_chunk_DSUGRAAL.FunctionDef, def)));
96
96
  if (added.length > 0) {
97
97
  await space.db.flush({
98
98
  indexes: true,
@@ -118,7 +118,7 @@ var FunctionRegistry = class extends import_context.Resource {
118
118
  if (this._ctx.disposed) {
119
119
  break;
120
120
  }
121
- this._ctx.onDispose(space.db.query(import_echo.Filter.schema(import_chunk_3J6FVYUV.FunctionDef)).subscribe(({ objects }) => {
121
+ this._ctx.onDispose(space.db.query(import_echo.Filter.schema(import_chunk_DSUGRAAL.FunctionDef)).subscribe(({ objects }) => {
122
122
  const { added } = (0, import_util.diff)(registered, objects, (a, b) => a.uri === b.uri);
123
123
  if (added.length > 0) {
124
124
  registered.push(...added);
@@ -216,29 +216,31 @@ var createTimerTrigger = async (ctx, space, spec, callback) => {
216
216
  });
217
217
  let last = 0;
218
218
  let run = 0;
219
- const job = import_cron.CronJob.from({
220
- cronTime: spec.cron,
221
- runOnInit: false,
222
- onTick: () => {
223
- const now = Date.now();
224
- const delta = last ? now - last : 0;
225
- last = now;
226
- run++;
227
- import_log3.log.info("tick", {
228
- space: space.key.truncate(),
229
- count: run,
230
- delta
231
- }, {
232
- F: __dxlog_file3,
233
- L: 38,
234
- S: void 0,
235
- C: (f, a) => f(...a)
236
- });
237
- task.schedule();
219
+ const schedule = (0, import_cron_schedule.parseCronExpression)(spec.cron);
220
+ const getRunTimeout = () => Date.now() - schedule.getNextDate().getTime();
221
+ const runCron = () => {
222
+ if (ctx.disposed) {
223
+ return;
238
224
  }
239
- });
240
- job.start();
241
- ctx.onDispose(() => job.stop());
225
+ const now = Date.now();
226
+ const delta = last ? now - last : 0;
227
+ last = now;
228
+ run++;
229
+ import_log3.log.info("tick", {
230
+ space: space.key.truncate(),
231
+ count: run,
232
+ delta
233
+ }, {
234
+ F: __dxlog_file3,
235
+ L: 39,
236
+ S: void 0,
237
+ C: (f, a) => f(...a)
238
+ });
239
+ task.schedule();
240
+ timeout = setTimeout(runCron, getRunTimeout());
241
+ };
242
+ let timeout = setTimeout(runCron, getRunTimeout());
243
+ ctx.onDispose(() => clearTimeout(timeout));
242
244
  };
243
245
  var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/core/functions/src/trigger/trigger-registry.ts";
244
246
  var triggerFactory = {
@@ -335,9 +337,9 @@ var TriggerRegistry = class extends import_context2.Resource {
335
337
  if (!manifest.triggers?.length) {
336
338
  return;
337
339
  }
338
- if (!space.db.graph.schemaRegistry.hasSchema(import_chunk_3J6FVYUV.FunctionTrigger)) {
340
+ if (!space.db.graph.schemaRegistry.hasSchema(import_chunk_DSUGRAAL.FunctionTrigger)) {
339
341
  space.db.graph.schemaRegistry.addSchema([
340
- import_chunk_3J6FVYUV.FunctionTrigger
342
+ import_chunk_DSUGRAAL.FunctionTrigger
341
343
  ]);
342
344
  }
343
345
  const manifestTriggers = manifest.triggers.map((trigger) => {
@@ -351,11 +353,11 @@ var TriggerRegistry = class extends import_context2.Resource {
351
353
  ].join(":"))
352
354
  ];
353
355
  }
354
- return (0, import_echo3.create)(import_chunk_3J6FVYUV.FunctionTrigger, trigger, {
356
+ return (0, import_echo3.create)(import_chunk_DSUGRAAL.FunctionTrigger, trigger, {
355
357
  keys
356
358
  });
357
359
  });
358
- const { objects: existing } = await space.db.query(import_echo3.Filter.schema(import_chunk_3J6FVYUV.FunctionTrigger)).run();
360
+ const { objects: existing } = await space.db.query(import_echo3.Filter.schema(import_chunk_DSUGRAAL.FunctionTrigger)).run();
359
361
  const { added } = (0, import_util2.diff)(existing, manifestTriggers, import_echo3.compareForeignKeys);
360
362
  added.forEach((trigger) => {
361
363
  space.db.add(trigger);
@@ -390,7 +392,7 @@ var TriggerRegistry = class extends import_context2.Resource {
390
392
  if (this._ctx.disposed) {
391
393
  break;
392
394
  }
393
- this._ctx.onDispose(space.db.query(import_echo3.Filter.schema(import_chunk_3J6FVYUV.FunctionTrigger)).subscribe(async ({ objects: current }) => {
395
+ this._ctx.onDispose(space.db.query(import_echo3.Filter.schema(import_chunk_DSUGRAAL.FunctionTrigger)).subscribe(async ({ objects: current }) => {
394
396
  import_log4.log.info("update", {
395
397
  space: space.key,
396
398
  registered: registered.length,
@@ -491,4 +493,4 @@ var TriggerRegistry = class extends import_context2.Resource {
491
493
  createSubscriptionTrigger,
492
494
  createTimerTrigger
493
495
  });
494
- //# sourceMappingURL=chunk-BGDVH6JU.cjs.map
496
+ //# sourceMappingURL=chunk-RXMCVAMJ.cjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/function/function-registry.ts", "../../../src/trigger/type/subscription-trigger.ts", "../../../src/trigger/type/timer-trigger.ts", "../../../src/trigger/trigger-registry.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { Event } from '@dxos/async';\nimport { type Client } from '@dxos/client';\nimport { create, Filter, type Space } from '@dxos/client/echo';\nimport { type Context, Resource } from '@dxos/context';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { ComplexMap, diff } from '@dxos/util';\n\nimport { FunctionDef, type FunctionManifest } from '../types';\n\nexport type FunctionsRegisteredEvent = {\n space: Space;\n added: FunctionDef[];\n};\n\nexport class FunctionRegistry extends Resource {\n private readonly _functionBySpaceKey = new ComplexMap<PublicKey, FunctionDef[]>(PublicKey.hash);\n\n public readonly registered = new Event<FunctionsRegisteredEvent>();\n\n constructor(private readonly _client: Client) {\n super();\n }\n\n public getFunctions(space: Space): FunctionDef[] {\n return this._functionBySpaceKey.get(space.key) ?? [];\n }\n\n public getUniqueByUri(): FunctionDef[] {\n const uniqueByUri = [...this._functionBySpaceKey.values()]\n .flatMap((defs) => defs)\n .reduce((acc, v) => {\n acc.set(v.uri, v);\n return acc;\n }, new Map<string, FunctionDef>());\n return [...uniqueByUri.values()];\n }\n\n /**\n * Loads function definitions from the manifest into the space.\n * We first load all the definitions from the space to deduplicate by functionId.\n */\n public async register(space: Space, functions: FunctionManifest['functions']): Promise<void> {\n log('register', { space: space.key, functions: functions?.length ?? 0 });\n if (!functions?.length) {\n return;\n }\n if (!space.db.graph.schemaRegistry.hasSchema(FunctionDef)) {\n space.db.graph.schemaRegistry.addSchema([FunctionDef]);\n }\n\n // Sync definitions.\n const { objects: existing } = await space.db.query(Filter.schema(FunctionDef)).run();\n const { added } = diff(existing, functions, (a, b) => a.uri === b.uri);\n // TODO(burdon): Update existing templates.\n added.forEach((def) => space.db.add(create(FunctionDef, def)));\n\n if (added.length > 0) {\n await space.db.flush({ indexes: true, updates: true });\n }\n }\n\n protected override async _open(): Promise<void> {\n log.info('opening...');\n const spacesSubscription = this._client.spaces.subscribe(async (spaces) => {\n for (const space of spaces) {\n if (this._functionBySpaceKey.has(space.key)) {\n continue;\n }\n\n const registered: FunctionDef[] = [];\n this._functionBySpaceKey.set(space.key, registered);\n await space.waitUntilReady();\n if (this._ctx.disposed) {\n break;\n }\n\n // Subscribe to updates.\n this._ctx.onDispose(\n space.db.query(Filter.schema(FunctionDef)).subscribe(({ objects }) => {\n const { added } = diff(registered, objects, (a, b) => a.uri === b.uri);\n // TODO(burdon): Update and remove.\n if (added.length > 0) {\n registered.push(...added);\n this.registered.emit({ space, added });\n }\n }),\n );\n }\n });\n\n // TODO(burdon): API: Normalize unsubscribe methods.\n this._ctx.onDispose(() => spacesSubscription.unsubscribe());\n }\n\n protected override async _close(_: Context): Promise<void> {\n log.info('closing...');\n this._functionBySpaceKey.clear();\n }\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { debounce, UpdateScheduler } from '@dxos/async';\nimport { Filter, type Space } from '@dxos/client/echo';\nimport { type Context } from '@dxos/context';\nimport { createSubscription, type Query } from '@dxos/echo-db';\nimport { log } from '@dxos/log';\n\nimport type { SubscriptionTrigger } from '../../types';\nimport { type TriggerCallback, type TriggerFactory } from '../trigger-registry';\n\nexport const createSubscriptionTrigger: TriggerFactory<SubscriptionTrigger> = async (\n ctx: Context,\n space: Space,\n spec: SubscriptionTrigger,\n callback: TriggerCallback,\n) => {\n const objectIds = new Set<string>();\n const task = new UpdateScheduler(\n ctx,\n async () => {\n if (objectIds.size > 0) {\n const objects = Array.from(objectIds);\n objectIds.clear();\n await callback({ objects });\n }\n },\n { maxFrequency: 4 },\n );\n\n // TODO(burdon): Factor out diff.\n // TODO(burdon): Don't fire initially?\n // TODO(burdon): Create queue. Only allow one invocation per trigger at a time?\n const subscriptions: (() => void)[] = [];\n const subscription = createSubscription(({ added, updated }) => {\n const sizeBefore = objectIds.size;\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 if (objectIds.size > sizeBefore) {\n log.info('updated', { added: added.length, updated: updated.length });\n task.trigger();\n }\n });\n\n subscriptions.push(() => subscription.unsubscribe());\n\n // TODO(burdon): Disable trigger if keeps failing.\n const { filter, options: { deep, delay } = {} } = spec;\n const update = ({ objects }: Query) => {\n log.info('update', { objects: objects.length });\n subscription.update(objects);\n\n // TODO(burdon): Hack to monitor changes to Document's text object.\n if (deep) {\n // TODO(dmaretskyi): Removed to not have dependency on markdown-plugin.\n // for (const object of objects) {\n // const content = object.content;\n // if (content instanceof TextType) {\n // subscriptions.push(getObjectCore(content).updates.on(debounce(() => subscription.update([object]), 1_000)));\n // }\n // }\n }\n };\n\n // TODO(burdon): OR not working.\n // TODO(burdon): [Bug]: all callbacks are fired on the first mutation.\n // TODO(burdon): [Bug]: not updated when document is deleted (either top or hierarchically).\n log.info('subscription', { filter });\n // const query = triggerCtx.space.db.query(Filter.or(filter.map(({ type, props }) => Filter.typename(type, props))));\n if (filter.type) {\n const query = space.db.query(Filter.typename(filter.type, filter.props));\n subscriptions.push(query.subscribe(delay ? debounce(update, delay) : update));\n }\n\n ctx.onDispose(() => {\n subscriptions.forEach((unsubscribe) => unsubscribe());\n });\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { parseCronExpression } from 'cron-schedule';\n\nimport { DeferredTask } from '@dxos/async';\nimport { type Space } from '@dxos/client/echo';\nimport { type Context } from '@dxos/context';\nimport { log } from '@dxos/log';\n\nimport type { TimerTrigger } from '../../types';\nimport { type TriggerCallback, type TriggerFactory } from '../trigger-registry';\n\nexport const createTimerTrigger: TriggerFactory<TimerTrigger> = async (\n ctx: Context,\n space: Space,\n spec: TimerTrigger,\n callback: TriggerCallback,\n) => {\n const task = new DeferredTask(ctx, async () => {\n await callback({});\n });\n\n let last = 0;\n let run = 0;\n const schedule = parseCronExpression(spec.cron);\n const getRunTimeout = () => Date.now() - schedule.getNextDate().getTime();\n const runCron = () => {\n if (ctx.disposed) {\n return;\n }\n // TODO(burdon): Check greater than 30s (use cron-parser).\n const now = Date.now();\n const delta = last ? now - last : 0;\n last = now;\n\n run++;\n log.info('tick', { space: space.key.truncate(), count: run, delta });\n task.schedule();\n\n timeout = setTimeout(runCron, getRunTimeout());\n };\n\n let timeout = setTimeout(runCron, getRunTimeout());\n\n ctx.onDispose(() => clearTimeout(timeout));\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { Event } from '@dxos/async';\nimport { type Client } from '@dxos/client';\nimport { create, Filter, getMeta, type Space, compareForeignKeys } from '@dxos/client/echo';\nimport { Context, Resource } from '@dxos/context';\nimport { ECHO_ATTR_META, foreignKey } from '@dxos/echo-schema';\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { ComplexMap, diff } from '@dxos/util';\n\nimport { createSubscriptionTrigger, createTimerTrigger } from './type';\nimport { type FunctionManifest, FunctionTrigger, type TriggerKind, type TriggerType } from '../types';\n\ntype ResponseCode = number;\n\nexport type TriggerCallback = (args: object) => Promise<ResponseCode>;\n\n// TODO(burdon): Make object?\nexport type TriggerFactory<Spec extends TriggerType, Options = any> = (\n ctx: Context,\n space: Space,\n spec: Spec,\n callback: TriggerCallback,\n options?: Options,\n) => Promise<void>;\n\nexport type TriggerFactoryMap = Partial<Record<TriggerKind, TriggerFactory<any>>>;\n\nconst triggerFactory: TriggerFactoryMap = {\n timer: createTimerTrigger,\n // TODO(burdon): Cannot use in browser.\n // webhook: createWebhookTrigger,\n subscription: createSubscriptionTrigger,\n};\n\nexport type TriggerEvent = {\n space: Space;\n triggers: FunctionTrigger[];\n};\n\ntype RegisteredTrigger = {\n activationCtx?: Context;\n trigger: FunctionTrigger;\n};\n\nexport class TriggerRegistry extends Resource {\n private readonly _triggersBySpaceKey = new ComplexMap<PublicKey, RegisteredTrigger[]>(PublicKey.hash);\n\n public readonly registered = new Event<TriggerEvent>();\n public readonly removed = new Event<TriggerEvent>();\n\n constructor(\n private readonly _client: Client,\n private readonly _options?: TriggerFactoryMap,\n ) {\n super();\n }\n\n public getActiveTriggers(space: Space): FunctionTrigger[] {\n return this._getTriggers(space, (t) => t.activationCtx != null);\n }\n\n public getInactiveTriggers(space: Space): FunctionTrigger[] {\n return this._getTriggers(space, (t) => t.activationCtx == null);\n }\n\n /**\n * Set callback for trigger.\n */\n public async activate(space: Space, trigger: FunctionTrigger, callback: TriggerCallback): Promise<void> {\n log('activate', { space: space.key, trigger });\n\n const activationCtx = new Context({ name: `FunctionTrigger-${trigger.function}` });\n this._ctx.onDispose(() => activationCtx.dispose());\n const registeredTrigger = this._triggersBySpaceKey.get(space.key)?.find((reg) => reg.trigger.id === trigger.id);\n invariant(registeredTrigger, `Trigger is not registered: ${trigger.function}`);\n registeredTrigger.activationCtx = activationCtx;\n\n try {\n // Create trigger.\n invariant(trigger.spec);\n const options = this._options?.[trigger.spec.type];\n const createTrigger = triggerFactory[trigger.spec.type];\n invariant(createTrigger, `Trigger factory not found: ${trigger.spec.type}`);\n await createTrigger(activationCtx, space, trigger.spec, callback, options);\n } catch (err) {\n delete registeredTrigger.activationCtx;\n throw err;\n }\n }\n\n /**\n * Loads triggers from the manifest into the space.\n */\n public async register(space: Space, manifest: FunctionManifest): Promise<void> {\n log('register', { space: space.key });\n if (!manifest.triggers?.length) {\n return;\n }\n\n if (!space.db.graph.schemaRegistry.hasSchema(FunctionTrigger)) {\n space.db.graph.schemaRegistry.addSchema([FunctionTrigger]);\n }\n\n // Create FK to enable syncing if none are set (NOTE: Possible collision).\n const manifestTriggers = manifest.triggers.map((trigger) => {\n let keys = trigger[ECHO_ATTR_META]?.keys;\n delete trigger[ECHO_ATTR_META];\n if (!keys?.length) {\n keys = [foreignKey('manifest', [trigger.function, trigger.spec?.type].join(':'))];\n }\n\n return create(FunctionTrigger, trigger, { keys });\n });\n\n // Sync triggers.\n const { objects: existing } = await space.db.query(Filter.schema(FunctionTrigger)).run();\n const { added } = diff(existing, manifestTriggers, compareForeignKeys);\n\n // TODO(burdon): Update existing.\n added.forEach((trigger) => {\n space.db.add(trigger);\n log.info('added', { meta: getMeta(trigger) });\n });\n\n if (added.length > 0) {\n await space.db.flush();\n }\n }\n\n protected override async _open(): Promise<void> {\n log.info('open...');\n const spaceListSubscription = this._client.spaces.subscribe(async (spaces) => {\n for (const space of spaces) {\n if (this._triggersBySpaceKey.has(space.key)) {\n continue;\n }\n\n const registered: RegisteredTrigger[] = [];\n this._triggersBySpaceKey.set(space.key, registered);\n await space.waitUntilReady();\n if (this._ctx.disposed) {\n break;\n }\n\n // Subscribe to updates.\n this._ctx.onDispose(\n space.db.query(Filter.schema(FunctionTrigger)).subscribe(async ({ objects: current }) => {\n log.info('update', { space: space.key, registered: registered.length, current: current.length });\n await this._handleRemovedTriggers(space, current, registered);\n this._handleNewTriggers(space, current, registered);\n }),\n );\n }\n });\n\n this._ctx.onDispose(() => spaceListSubscription.unsubscribe());\n log.info('opened');\n }\n\n protected override async _close(_: Context): Promise<void> {\n log.info('close...');\n this._triggersBySpaceKey.clear();\n log.info('closed');\n }\n\n private _handleNewTriggers(space: Space, current: FunctionTrigger[], registered: RegisteredTrigger[]) {\n const added = current.filter((candidate) => {\n return candidate.enabled && registered.find((reg) => reg.trigger.id === candidate.id) == null;\n });\n\n if (added.length > 0) {\n const newRegisteredTriggers: RegisteredTrigger[] = added.map((trigger) => ({ trigger }));\n registered.push(...newRegisteredTriggers);\n log.info('added', () => ({\n spaceKey: space.key,\n triggers: added.map((trigger) => trigger.function),\n }));\n\n this.registered.emit({ space, triggers: added });\n }\n }\n\n private async _handleRemovedTriggers(\n space: Space,\n current: FunctionTrigger[],\n registered: RegisteredTrigger[],\n ): Promise<void> {\n const removed: FunctionTrigger[] = [];\n for (let i = registered.length - 1; i >= 0; i--) {\n const wasRemoved =\n current.filter((trigger) => trigger.enabled).find((trigger) => trigger.id === registered[i].trigger.id) == null;\n if (wasRemoved) {\n const unregistered = registered.splice(i, 1)[0];\n await unregistered.activationCtx?.dispose();\n removed.push(unregistered.trigger);\n }\n }\n\n if (removed.length > 0) {\n log.info('removed', () => ({\n spaceKey: space.key,\n triggers: removed.map((trigger) => trigger.function),\n }));\n\n this.removed.emit({ space, triggers: removed });\n }\n }\n\n private _getTriggers(space: Space, predicate: (trigger: RegisteredTrigger) => boolean): FunctionTrigger[] {\n const allSpaceTriggers = this._triggersBySpaceKey.get(space.key) ?? [];\n return allSpaceTriggers.filter(predicate).map((trigger) => trigger.trigger);\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,mBAAsB;AAEtB,kBAA2C;AAC3C,qBAAuC;AACvC,kBAA0B;AAC1B,iBAAoB;AACpB,kBAAiC;ACNjC,IAAAA,gBAA0C;AAC1C,IAAAC,eAAmC;AAEnC,qBAA+C;AAC/C,IAAAC,cAAoB;ACJpB,2BAAoC;AAEpC,IAAAF,gBAA6B;AAG7B,IAAAE,cAAoB;ACLpB,IAAAF,gBAAsB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,OAAO;QACvBuG,UAAUjJ,MAAME;QAChB6H,UAAUjG,MAAMoG,IAAI,CAACtD,YAAYA,QAAQ0C,QAAQ;MACnD,IAAA;;;;;;AAEA,WAAKzH,WAAWuD,KAAK;QAAEpD;QAAO+H,UAAUjG;MAAM,CAAA;IAChD;EACF;EAEA,MAAc8G,uBACZ5I,OACA2I,SACA9I,YACe;AACf,UAAMgH,UAA6B,CAAA;AACnC,aAASqC,IAAIrJ,WAAWoB,SAAS,GAAGiI,KAAK,GAAGA,KAAK;AAC/C,YAAMC,aACJR,QAAQ9D,OAAO,CAACD,YAAYA,QAAQmE,OAAO,EAAEtB,KAAK,CAAC7C,YAAYA,QAAQD,OAAO9E,WAAWqJ,CAAAA,EAAGtE,QAAQD,EAAE,KAAK;AAC7G,UAAIwE,YAAY;AACd,cAAMC,eAAevJ,WAAWwJ,OAAOH,GAAG,CAAA,EAAG,CAAA;AAC7C,cAAME,aAAanC,eAAeM,QAAAA;AAClCV,gBAAQ1D,KAAKiG,aAAaxE,OAAO;MACnC;IACF;AAEA,QAAIiC,QAAQ5F,SAAS,GAAG;AACtBD,kBAAAA,IAAI0B,KAAK,WAAW,OAAO;QACzBuG,UAAUjJ,MAAME;QAChB6H,UAAUlB,QAAQqB,IAAI,CAACtD,YAAYA,QAAQ0C,QAAQ;MACrD,IAAA;;;;;;AAEA,WAAKT,QAAQzD,KAAK;QAAEpD;QAAO+H,UAAUlB;MAAQ,CAAA;IAC/C;EACF;EAEQE,aAAa/G,OAAcsJ,WAAuE;AACxG,UAAMC,mBAAmB,KAAK3C,oBAAoB3G,IAAID,MAAME,GAAG,KAAK,CAAA;AACpE,WAAOqJ,iBAAiB1E,OAAOyE,SAAAA,EAAWpB,IAAI,CAACtD,YAAYA,QAAQA,OAAO;EAC5E;AACF;",
6
+ "names": ["import_async", "import_echo", "import_log", "import_context", "import_keys", "import_util", "FunctionRegistry", "Resource", "constructor", "_client", "_functionBySpaceKey", "ComplexMap", "PublicKey", "hash", "registered", "Event", "getFunctions", "space", "get", "key", "getUniqueByUri", "uniqueByUri", "values", "flatMap", "defs", "reduce", "acc", "v", "set", "uri", "Map", "register", "functions", "log", "length", "db", "graph", "schemaRegistry", "hasSchema", "FunctionDef", "addSchema", "objects", "existing", "query", "Filter", "schema", "run", "added", "diff", "a", "b", "forEach", "def", "add", "create", "flush", "indexes", "updates", "_open", "info", "spacesSubscription", "spaces", "subscribe", "has", "waitUntilReady", "_ctx", "disposed", "onDispose", "push", "emit", "unsubscribe", "_close", "_", "clear", "createSubscriptionTrigger", "ctx", "spec", "callback", "objectIds", "Set", "task", "UpdateScheduler", "size", "Array", "from", "maxFrequency", "subscriptions", "subscription", "createSubscription", "updated", "sizeBefore", "object", "id", "trigger", "filter", "options", "deep", "delay", "update", "type", "typename", "props", "debounce", "createTimerTrigger", "DeferredTask", "last", "schedule", "parseCronExpression", "cron", "getRunTimeout", "Date", "now", "getNextDate", "getTime", "runCron", "delta", "truncate", "count", "timeout", "setTimeout", "clearTimeout", "triggerFactory", "timer", "TriggerRegistry", "_options", "_triggersBySpaceKey", "removed", "getActiveTriggers", "_getTriggers", "t", "activationCtx", "getInactiveTriggers", "activate", "Context", "name", "function", "dispose", "registeredTrigger", "find", "reg", "invariant", "createTrigger", "err", "manifest", "triggers", "FunctionTrigger", "manifestTriggers", "map", "keys", "ECHO_ATTR_META", "foreignKey", "join", "compareForeignKeys", "meta", "getMeta", "spaceListSubscription", "current", "_handleRemovedTriggers", "_handleNewTriggers", "candidate", "enabled", "newRegisteredTriggers", "spaceKey", "i", "wasRemoved", "unregistered", "splice", "predicate", "allSpaceTriggers"]
7
+ }
@@ -18,25 +18,17 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
  var edge_exports = {};
20
20
  __export(edge_exports, {
21
- FUNCTIONS_PRESET_META_KEY: () => import_chunk_MZMHE4DC.FUNCTIONS_PRESET_META_KEY,
22
- getInvocationUrl: () => import_chunk_MZMHE4DC.getInvocationUrl,
23
- getUserFunctionUrlInMetadata: () => import_chunk_MZMHE4DC.getUserFunctionUrlInMetadata,
24
- incrementSemverPatch: () => import_chunk_MZMHE4DC.incrementSemverPatch,
25
- publicKeyToDid: () => import_chunk_MZMHE4DC.publicKeyToDid,
26
- setUserFunctionUrlInMetadata: () => import_chunk_MZMHE4DC.setUserFunctionUrlInMetadata,
27
- uploadWorkerFunction: () => import_chunk_MZMHE4DC.uploadWorkerFunction
21
+ incrementSemverPatch: () => import_chunk_NXZNXVT3.incrementSemverPatch,
22
+ publicKeyToDid: () => import_chunk_NXZNXVT3.publicKeyToDid,
23
+ uploadWorkerFunction: () => import_chunk_NXZNXVT3.uploadWorkerFunction
28
24
  });
29
25
  module.exports = __toCommonJS(edge_exports);
30
- var import_chunk_MZMHE4DC = require("../chunk-MZMHE4DC.cjs");
26
+ var import_chunk_NXZNXVT3 = require("../chunk-NXZNXVT3.cjs");
31
27
  var import_chunk_JEQ2X3Z6 = require("../chunk-JEQ2X3Z6.cjs");
32
28
  // Annotate the CommonJS export names for ESM import in node:
33
29
  0 && (module.exports = {
34
- FUNCTIONS_PRESET_META_KEY,
35
- getInvocationUrl,
36
- getUserFunctionUrlInMetadata,
37
30
  incrementSemverPatch,
38
31
  publicKeyToDid,
39
- setUserFunctionUrlInMetadata,
40
32
  uploadWorkerFunction
41
33
  });
42
34
  //# sourceMappingURL=index.cjs.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["index.cjs"],
4
- "sourcesContent": ["import {\n FUNCTIONS_PRESET_META_KEY,\n getInvocationUrl,\n getUserFunctionUrlInMetadata,\n incrementSemverPatch,\n publicKeyToDid,\n setUserFunctionUrlInMetadata,\n uploadWorkerFunction\n} from \"../chunk-MZMHE4DC.cjs\";\nimport \"../chunk-JEQ2X3Z6.cjs\";\nexport {\n FUNCTIONS_PRESET_META_KEY,\n getInvocationUrl,\n getUserFunctionUrlInMetadata,\n incrementSemverPatch,\n publicKeyToDid,\n setUserFunctionUrlInMetadata,\n uploadWorkerFunction\n};\n//# sourceMappingURL=index.cjs.map\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,4BAQO;AACP,4BAAO;",
4
+ "sourcesContent": ["import {\n incrementSemverPatch,\n publicKeyToDid,\n uploadWorkerFunction\n} from \"../chunk-NXZNXVT3.cjs\";\nimport \"../chunk-JEQ2X3Z6.cjs\";\nexport {\n incrementSemverPatch,\n publicKeyToDid,\n uploadWorkerFunction\n};\n//# sourceMappingURL=index.cjs.map\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,4BAIO;AACP,4BAAO;",
6
6
  "names": []
7
7
  }
@@ -18,38 +18,41 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
  var node_exports = {};
20
20
  __export(node_exports, {
21
- FUNCTIONS_PRESET_META_KEY: () => import_chunk_MZMHE4DC.FUNCTIONS_PRESET_META_KEY,
22
- FUNCTION_TYPES: () => import_chunk_3J6FVYUV.FUNCTION_TYPES,
23
- FunctionDef: () => import_chunk_3J6FVYUV.FunctionDef,
24
- FunctionManifestSchema: () => import_chunk_3J6FVYUV.FunctionManifestSchema,
25
- FunctionRegistry: () => import_chunk_BGDVH6JU.FunctionRegistry,
26
- FunctionTrigger: () => import_chunk_3J6FVYUV.FunctionTrigger,
27
- FunctionTriggerSchema: () => import_chunk_3J6FVYUV.FunctionTriggerSchema,
28
- FunctionType: () => import_chunk_3J6FVYUV.FunctionType,
29
- InvocationOutcome: () => import_chunk_3J6FVYUV.InvocationOutcome,
30
- InvocationTraceEvent: () => import_chunk_3J6FVYUV.InvocationTraceEvent,
31
- ScriptType: () => import_chunk_3J6FVYUV.ScriptType,
32
- TraceEvent: () => import_chunk_3J6FVYUV.TraceEvent,
33
- TraceEventException: () => import_chunk_3J6FVYUV.TraceEventException,
34
- TraceEventLog: () => import_chunk_3J6FVYUV.TraceEventLog,
35
- TriggerKind: () => import_chunk_3J6FVYUV.TriggerKind,
36
- TriggerRegistry: () => import_chunk_BGDVH6JU.TriggerRegistry,
37
- TriggerSchema: () => import_chunk_3J6FVYUV.TriggerSchema,
38
- createSubscriptionTrigger: () => import_chunk_BGDVH6JU.createSubscriptionTrigger,
39
- createTimerTrigger: () => import_chunk_BGDVH6JU.createTimerTrigger,
21
+ FUNCTIONS_PRESET_META_KEY: () => import_chunk_DSUGRAAL.FUNCTIONS_PRESET_META_KEY,
22
+ FUNCTION_TYPES: () => import_chunk_DSUGRAAL.FUNCTION_TYPES,
23
+ FunctionDef: () => import_chunk_DSUGRAAL.FunctionDef,
24
+ FunctionManifestSchema: () => import_chunk_DSUGRAAL.FunctionManifestSchema,
25
+ FunctionRegistry: () => import_chunk_RXMCVAMJ.FunctionRegistry,
26
+ FunctionTrigger: () => import_chunk_DSUGRAAL.FunctionTrigger,
27
+ FunctionTriggerSchema: () => import_chunk_DSUGRAAL.FunctionTriggerSchema,
28
+ FunctionType: () => import_chunk_DSUGRAAL.FunctionType,
29
+ InvocationOutcome: () => import_chunk_DSUGRAAL.InvocationOutcome,
30
+ InvocationTraceEndEvent: () => import_chunk_DSUGRAAL.InvocationTraceEndEvent,
31
+ InvocationTraceEventType: () => import_chunk_DSUGRAAL.InvocationTraceEventType,
32
+ InvocationTraceStartEvent: () => import_chunk_DSUGRAAL.InvocationTraceStartEvent,
33
+ ScriptType: () => import_chunk_DSUGRAAL.ScriptType,
34
+ TraceEvent: () => import_chunk_DSUGRAAL.TraceEvent,
35
+ TraceEventException: () => import_chunk_DSUGRAAL.TraceEventException,
36
+ TraceEventLog: () => import_chunk_DSUGRAAL.TraceEventLog,
37
+ TriggerKind: () => import_chunk_DSUGRAAL.TriggerKind,
38
+ TriggerRegistry: () => import_chunk_RXMCVAMJ.TriggerRegistry,
39
+ TriggerSchema: () => import_chunk_DSUGRAAL.TriggerSchema,
40
+ createInvocationSpans: () => import_chunk_DSUGRAAL.createInvocationSpans,
41
+ createSubscriptionTrigger: () => import_chunk_RXMCVAMJ.createSubscriptionTrigger,
42
+ createTimerTrigger: () => import_chunk_RXMCVAMJ.createTimerTrigger,
40
43
  defineFunction: () => defineFunction,
41
- getInvocationUrl: () => import_chunk_MZMHE4DC.getInvocationUrl,
42
- getUserFunctionUrlInMetadata: () => import_chunk_MZMHE4DC.getUserFunctionUrlInMetadata,
43
- incrementSemverPatch: () => import_chunk_MZMHE4DC.incrementSemverPatch,
44
- publicKeyToDid: () => import_chunk_MZMHE4DC.publicKeyToDid,
45
- setUserFunctionUrlInMetadata: () => import_chunk_MZMHE4DC.setUserFunctionUrlInMetadata,
44
+ getInvocationUrl: () => import_chunk_DSUGRAAL.getInvocationUrl,
45
+ getUserFunctionUrlInMetadata: () => import_chunk_DSUGRAAL.getUserFunctionUrlInMetadata,
46
+ incrementSemverPatch: () => import_chunk_NXZNXVT3.incrementSemverPatch,
47
+ publicKeyToDid: () => import_chunk_NXZNXVT3.publicKeyToDid,
48
+ setUserFunctionUrlInMetadata: () => import_chunk_DSUGRAAL.setUserFunctionUrlInMetadata,
46
49
  subscriptionHandler: () => subscriptionHandler,
47
- uploadWorkerFunction: () => import_chunk_MZMHE4DC.uploadWorkerFunction
50
+ uploadWorkerFunction: () => import_chunk_NXZNXVT3.uploadWorkerFunction
48
51
  });
49
52
  module.exports = __toCommonJS(node_exports);
50
- var import_chunk_MZMHE4DC = require("./chunk-MZMHE4DC.cjs");
51
- var import_chunk_BGDVH6JU = require("./chunk-BGDVH6JU.cjs");
52
- var import_chunk_3J6FVYUV = require("./chunk-3J6FVYUV.cjs");
53
+ var import_chunk_NXZNXVT3 = require("./chunk-NXZNXVT3.cjs");
54
+ var import_chunk_RXMCVAMJ = require("./chunk-RXMCVAMJ.cjs");
55
+ var import_chunk_DSUGRAAL = require("./chunk-DSUGRAAL.cjs");
53
56
  var import_chunk_JEQ2X3Z6 = require("./chunk-JEQ2X3Z6.cjs");
54
57
  var import_effect = require("effect");
55
58
  var import_client = require("@dxos/client");
@@ -140,7 +143,9 @@ var registerTypes = (space, types = []) => {
140
143
  FunctionTriggerSchema,
141
144
  FunctionType,
142
145
  InvocationOutcome,
143
- InvocationTraceEvent,
146
+ InvocationTraceEndEvent,
147
+ InvocationTraceEventType,
148
+ InvocationTraceStartEvent,
144
149
  ScriptType,
145
150
  TraceEvent,
146
151
  TraceEventException,
@@ -148,6 +153,7 @@ var registerTypes = (space, types = []) => {
148
153
  TriggerKind,
149
154
  TriggerRegistry,
150
155
  TriggerSchema,
156
+ createInvocationSpans,
151
157
  createSubscriptionTrigger,
152
158
  createTimerTrigger,
153
159
  defineFunction,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/handler.ts"],
4
- "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport { Schema as S } from 'effect';\nimport { type Effect } from 'effect';\n\nimport { type Client, PublicKey } from '@dxos/client';\nimport { type Space, type SpaceId } from '@dxos/client/echo';\nimport type { CoreDatabase, EchoDatabase, ReactiveEchoObject } from '@dxos/echo-db';\nimport { type HasId } from '@dxos/echo-schema';\nimport { type DXN } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { type QueryResult } from '@dxos/protocols';\nimport { isNonNullable } from '@dxos/util';\n\n// TODO(burdon): Model after http request. Ref Lambda/OpenFaaS.\n// https://docs.aws.amazon.com/lambda/latest/dg/typescript-handler.html\n// https://www.serverless.com/framework/docs/providers/aws/guide/serverless.yml/#functions\n// https://www.npmjs.com/package/aws-lambda\n\n/**\n * Function handler.\n */\nexport type FunctionHandler<TData = {}, TMeta = {}, TOutput = any> = (params: {\n context: FunctionContext;\n event: FunctionEvent<TData, TMeta>;\n /**\n * @deprecated\n */\n response: FunctionResponse;\n}) => TOutput | Promise<TOutput> | Effect.Effect<TOutput, any>;\n\n/**\n * Function context.\n */\nexport interface FunctionContext {\n getSpace: (spaceId: SpaceId) => Promise<SpaceAPI>;\n\n /**\n * Space from which the function was invoked.\n */\n space: SpaceAPI | undefined;\n\n ai: FunctionContextAi;\n\n /**\n * @deprecated\n */\n // TODO(burdon): Limit access to individual space.\n client: Client;\n /**\n * @deprecated\n */\n // TODO(burdon): Replace with storage service abstraction.\n dataDir?: string;\n}\n\nexport interface FunctionContextAi {\n // TODO(dmaretskyi): Refer to cloudflare AI docs for more comprehensive typedefs.\n run(model: string, inputs: any, options?: any): Promise<any>;\n}\n\n/**\n * Event payload.\n */\n// TODO(dmaretskyi): Update type definitions to match the actual payload.\nexport type FunctionEvent<TData = {}, TMeta = {}> = {\n data: FunctionEventMeta<TMeta> & TData;\n};\n\n/**\n * Metadata from trigger.\n */\nexport type FunctionEventMeta<TMeta = {}> = {\n meta: TMeta;\n};\n\n/**\n * Function response.\n */\nexport type FunctionResponse = {\n status(code: number): FunctionResponse;\n};\n\n//\n// API.\n//\n\n// TODO(dmaretskyi): Temporary API to get the queues working.\n// TODO(dmaretskyi): To be replaced with integrating queues into echo.\nexport interface QueuesAPI {\n queryQueue(queue: DXN, options?: {}): Promise<QueryResult>;\n insertIntoQueue(queue: DXN, objects: HasId[]): Promise<void>;\n}\n\n/**\n * Space interface available to functions.\n */\nexport interface SpaceAPI {\n get id(): SpaceId;\n /**\n * @deprecated\n */\n get crud(): CoreDatabase;\n get db(): EchoDatabase;\n // TODO(dmaretskyi): Align with echo api --- queues.get(id).append(items);\n get queues(): QueuesAPI;\n}\n\n// TODO(wittjosiah): Fix this.\nconst __assertFunctionSpaceIsCompatibleWithTheClientSpace = () => {\n // const _: SpaceAPI = {} as Space;\n};\n\nexport type FunctionDefinition = {\n description?: string;\n inputSchema: S.Schema.AnyNoContext;\n outputSchema?: S.Schema.AnyNoContext;\n handler: FunctionHandler<any>;\n};\n\nexport type DefineFunctionParams<T, O = any> = {\n description?: string;\n inputSchema: S.Schema<T, any>;\n outputSchema?: S.Schema<O, any>;\n handler: FunctionHandler<T, any, O>;\n};\n\n// TODO(dmaretskyi): Bind input type to function handler.\nexport const defineFunction = <T, O>(params: DefineFunctionParams<T, O>): FunctionDefinition => {\n if (!S.isSchema(params.inputSchema)) {\n throw new Error('Input schema must be a valid schema');\n }\n if (typeof params.handler !== 'function') {\n throw new Error('Handler must be a function');\n }\n\n return {\n description: params.description,\n inputSchema: params.inputSchema,\n outputSchema: params.outputSchema ?? S.Any,\n handler: params.handler,\n };\n};\n\n//\n// Subscription utils.\n//\n\nexport type RawSubscriptionData = {\n spaceKey?: string;\n objects?: string[];\n};\n\nexport type SubscriptionData = {\n space?: Space;\n objects?: ReactiveEchoObject<any>[];\n};\n\n/**\n * Handler wrapper for subscription events; extracts space and objects.\n *\n * To test:\n * ```\n * curl -s -X POST -H \"Content-Type: application/json\" --data '{\"space\": \"0446...1cbb\"}' http://localhost:7100/dev/email-extractor\n * ```\n *\n * NOTE: Get space key from devtools or `dx space list --json`\n */\n// TODO(burdon): Evolve into plugin definition like Composer.\nexport const subscriptionHandler = <TMeta>(\n handler: FunctionHandler<SubscriptionData, TMeta>,\n types?: S.Schema<any>[],\n): FunctionHandler<RawSubscriptionData, TMeta> => {\n return async ({ event: { data }, context, response, ...rest }) => {\n const { client } = context;\n const space = data.spaceKey ? client.spaces.get(PublicKey.from(data.spaceKey)) : undefined;\n if (!space) {\n log.error('Invalid space');\n return response.status(500);\n }\n\n registerTypes(space, types);\n const objects = space\n ? data.objects\n ?.map<ReactiveEchoObject<any> | undefined>((id) => space!.db.getObjectById(id))\n .filter(isNonNullable)\n : [];\n\n if (!!data.spaceKey && !space) {\n log.warn('invalid space', { data });\n } else {\n log.info('handler', { space: space?.key.truncate(), objects: objects?.length });\n }\n\n return handler({ event: { data: { ...data, space, objects } }, context, response, ...rest });\n };\n};\n\n// TODO(burdon): Evolve types as part of function metadata.\nconst registerTypes = (space: Space, types: S.Schema<any>[] = []) => {\n const registry = space.db.graph.schemaRegistry;\n for (const type of types) {\n if (!registry.hasSchema(type)) {\n registry.addSchema([type]);\n }\n }\n};\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,oBAA4B;AAG5B,oBAAuC;AAKvC,iBAAoB;AAEpB,kBAA8B;;AAoHvB,IAAMA,iBAAiB,CAAOC,WAAAA;AACnC,MAAI,CAACC,cAAAA,OAAEC,SAASF,OAAOG,WAAW,GAAG;AACnC,UAAM,IAAIC,MAAM,qCAAA;EAClB;AACA,MAAI,OAAOJ,OAAOK,YAAY,YAAY;AACxC,UAAM,IAAID,MAAM,4BAAA;EAClB;AAEA,SAAO;IACLE,aAAaN,OAAOM;IACpBH,aAAaH,OAAOG;IACpBI,cAAcP,OAAOO,gBAAgBN,cAAAA,OAAEO;IACvCH,SAASL,OAAOK;EAClB;AACF;AA2BO,IAAMI,sBAAsB,CACjCJ,SACAK,UAAAA;AAEA,SAAO,OAAO,EAAEC,OAAO,EAAEC,KAAI,GAAIC,SAASC,UAAU,GAAGC,KAAAA,MAAM;AAC3D,UAAM,EAAEC,OAAM,IAAKH;AACnB,UAAMI,QAAQL,KAAKM,WAAWF,OAAOG,OAAOC,IAAIC,wBAAUC,KAAKV,KAAKM,QAAQ,CAAA,IAAKK;AACjF,QAAI,CAACN,OAAO;AACVO,qBAAIC,MAAM,iBAAA,QAAA;;;;;;AACV,aAAOX,SAASY,OAAO,GAAA;IACzB;AAEAC,kBAAcV,OAAOP,KAAAA;AACrB,UAAMkB,UAAUX,QACZL,KAAKgB,SACDC,IAAyC,CAACC,OAAOb,MAAOc,GAAGC,cAAcF,EAAAA,CAAAA,EAC1EG,OAAOC,yBAAAA,IACV,CAAA;AAEJ,QAAI,CAAC,CAACtB,KAAKM,YAAY,CAACD,OAAO;AAC7BO,qBAAIW,KAAK,iBAAiB;QAAEvB;MAAK,GAAA;;;;;;IACnC,OAAO;AACLY,qBAAIY,KAAK,WAAW;QAAEnB,OAAOA,OAAOoB,IAAIC,SAAAA;QAAYV,SAASA,SAASW;MAAO,GAAA;;;;;;IAC/E;AAEA,WAAOlC,QAAQ;MAAEM,OAAO;QAAEC,MAAM;UAAE,GAAGA;UAAMK;UAAOW;QAAQ;MAAE;MAAGf;MAASC;MAAU,GAAGC;IAAK,CAAA;EAC5F;AACF;AAGA,IAAMY,gBAAgB,CAACV,OAAcP,QAAyB,CAAA,MAAE;AAC9D,QAAM8B,WAAWvB,MAAMc,GAAGU,MAAMC;AAChC,aAAWC,QAAQjC,OAAO;AACxB,QAAI,CAAC8B,SAASI,UAAUD,IAAAA,GAAO;AAC7BH,eAASK,UAAU;QAACF;OAAK;IAC3B;EACF;AACF;",
4
+ "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport { Schema as S } from 'effect';\nimport { type Effect } from 'effect';\n\nimport { type Client, PublicKey } from '@dxos/client';\nimport { type Space, type SpaceId } from '@dxos/client/echo';\nimport type { CoreDatabase, EchoDatabase, ReactiveEchoObject } from '@dxos/echo-db';\nimport { type HasId } from '@dxos/echo-schema';\nimport { type DXN } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { type QueryResult } from '@dxos/protocols';\nimport { isNonNullable } from '@dxos/util';\n\n// TODO(burdon): Model after http request. Ref Lambda/OpenFaaS.\n// https://docs.aws.amazon.com/lambda/latest/dg/typescript-handler.html\n// https://www.serverless.com/framework/docs/providers/aws/guide/serverless.yml/#functions\n// https://www.npmjs.com/package/aws-lambda\n\n/**\n * Function handler.\n */\nexport type FunctionHandler<TData = {}, TMeta = {}, TOutput = any> = (params: {\n context: FunctionContext;\n event: FunctionEvent<TData, TMeta>;\n /**\n * @deprecated\n */\n response: FunctionResponse;\n}) => TOutput | Promise<TOutput> | Effect.Effect<TOutput, any>;\n\n/**\n * Function context.\n */\nexport interface FunctionContext {\n getSpace: (spaceId: SpaceId) => Promise<SpaceAPI>;\n\n /**\n * Space from which the function was invoked.\n */\n space: SpaceAPI | undefined;\n\n ai: FunctionContextAi;\n\n /**\n * @deprecated\n */\n // TODO(burdon): Limit access to individual space.\n client: Client;\n /**\n * @deprecated\n */\n // TODO(burdon): Replace with storage service abstraction.\n dataDir?: string;\n}\n\nexport interface FunctionContextAi {\n // TODO(dmaretskyi): Refer to cloudflare AI docs for more comprehensive typedefs.\n run(model: string, inputs: any, options?: any): Promise<any>;\n}\n\n/**\n * Event payload.\n */\n// TODO(dmaretskyi): Update type definitions to match the actual payload.\nexport type FunctionEvent<TData = {}, TMeta = {}> = {\n data: FunctionEventMeta<TMeta> & TData;\n};\n\n/**\n * Metadata from trigger.\n */\nexport type FunctionEventMeta<TMeta = {}> = {\n meta: TMeta;\n};\n\n/**\n * Function response.\n */\nexport type FunctionResponse = {\n status(code: number): FunctionResponse;\n};\n\n//\n// API.\n//\n\n// TODO(dmaretskyi): Temporary API to get the queues working.\n// TODO(dmaretskyi): To be replaced with integrating queues into echo.\nexport interface QueuesAPI {\n queryQueue(queue: DXN, options?: {}): Promise<QueryResult>;\n insertIntoQueue(queue: DXN, objects: HasId[]): Promise<void>;\n}\n\n/**\n * Space interface available to functions.\n */\nexport interface SpaceAPI {\n get id(): SpaceId;\n /**\n * @deprecated\n */\n get crud(): CoreDatabase;\n get db(): EchoDatabase;\n // TODO(dmaretskyi): Align with echo api --- queues.get(id).append(items);\n get queues(): QueuesAPI;\n}\n\n// TODO(wittjosiah): Fix this.\nconst __assertFunctionSpaceIsCompatibleWithTheClientSpace = () => {\n // const _: SpaceAPI = {} as Space;\n};\n\nexport type FunctionDefinition = {\n description?: string;\n inputSchema: S.Schema.AnyNoContext;\n outputSchema?: S.Schema.AnyNoContext;\n handler: FunctionHandler<any>;\n};\n\nexport type DefineFunctionParams<T, O = any> = {\n description?: string;\n inputSchema: S.Schema<T, any>;\n outputSchema?: S.Schema<O, any>;\n handler: FunctionHandler<T, any, O>;\n};\n\n// TODO(dmaretskyi): Bind input type to function handler.\nexport const defineFunction = <T, O>(params: DefineFunctionParams<T, O>): FunctionDefinition => {\n if (!S.isSchema(params.inputSchema)) {\n throw new Error('Input schema must be a valid schema');\n }\n if (typeof params.handler !== 'function') {\n throw new Error('Handler must be a function');\n }\n\n return {\n description: params.description,\n inputSchema: params.inputSchema,\n outputSchema: params.outputSchema ?? S.Any,\n handler: params.handler,\n };\n};\n\n//\n// Subscription utils.\n//\n\nexport type RawSubscriptionData = {\n spaceKey?: string;\n objects?: string[];\n};\n\nexport type SubscriptionData = {\n space?: Space;\n objects?: ReactiveEchoObject<any>[];\n};\n\n/**\n * Handler wrapper for subscription events; extracts space and objects.\n *\n * To test:\n * ```\n * curl -s -X POST -H \"Content-Type: application/json\" --data '{\"space\": \"0446...1cbb\"}' http://localhost:7100/dev/email-extractor\n * ```\n *\n * NOTE: Get space key from devtools or `dx space list --json`\n */\n// TODO(burdon): Evolve into plugin definition like Composer.\nexport const subscriptionHandler = <TMeta>(\n handler: FunctionHandler<SubscriptionData, TMeta>,\n types?: S.Schema.AnyNoContext[],\n): FunctionHandler<RawSubscriptionData, TMeta> => {\n return async ({ event: { data }, context, response, ...rest }) => {\n const { client } = context;\n const space = data.spaceKey ? client.spaces.get(PublicKey.from(data.spaceKey)) : undefined;\n if (!space) {\n log.error('Invalid space');\n return response.status(500);\n }\n\n registerTypes(space, types);\n const objects = space\n ? data.objects\n ?.map<ReactiveEchoObject<any> | undefined>((id) => space!.db.getObjectById(id))\n .filter(isNonNullable)\n : [];\n\n if (!!data.spaceKey && !space) {\n log.warn('invalid space', { data });\n } else {\n log.info('handler', { space: space?.key.truncate(), objects: objects?.length });\n }\n\n return handler({ event: { data: { ...data, space, objects } }, context, response, ...rest });\n };\n};\n\n// TODO(burdon): Evolve types as part of function metadata.\nconst registerTypes = (space: Space, types: S.Schema.AnyNoContext[] = []) => {\n const registry = space.db.graph.schemaRegistry;\n for (const type of types) {\n if (!registry.hasSchema(type)) {\n registry.addSchema([type]);\n }\n }\n};\n"],
5
+ "mappings": ";;;;;;;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C,QAAQ;MAAEM,OAAO;QAAEC,MAAM;UAAE,GAAGA;UAAMK;UAAOW;QAAQ;MAAE;MAAGf;MAASC;MAAU,GAAGC;IAAK,CAAA;EAC5F;AACF;AAGA,IAAMY,gBAAgB,CAACV,OAAcP,QAAiC,CAAA,MAAE;AACtE,QAAM8B,WAAWvB,MAAMc,GAAGU,MAAMC;AAChC,aAAWC,QAAQjC,OAAO;AACxB,QAAI,CAAC8B,SAASI,UAAUD,IAAAA,GAAO;AAC7BH,eAASK,UAAU;QAACF;OAAK;IAC3B;EACF;AACF;",
6
6
  "names": ["defineFunction", "params", "S", "isSchema", "inputSchema", "Error", "handler", "description", "outputSchema", "Any", "subscriptionHandler", "types", "event", "data", "context", "response", "rest", "client", "space", "spaceKey", "spaces", "get", "PublicKey", "from", "undefined", "log", "error", "status", "registerTypes", "objects", "map", "id", "db", "getObjectById", "filter", "isNonNullable", "warn", "info", "key", "truncate", "length", "registry", "graph", "schemaRegistry", "type", "hasSchema", "addSchema"]
7
7
  }