@dxos/functions 0.6.10 → 0.6.11-staging.a542fc9

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 (44) hide show
  1. package/dist/lib/browser/chunk-563WM5C2.mjs +590 -0
  2. package/dist/lib/browser/chunk-563WM5C2.mjs.map +7 -0
  3. package/dist/lib/browser/{chunk-YSDC6YCF.mjs → chunk-XOBJR3A6.mjs} +2 -1
  4. package/dist/lib/browser/{chunk-YSDC6YCF.mjs.map → chunk-XOBJR3A6.mjs.map} +3 -3
  5. package/dist/lib/browser/index.mjs +9 -7
  6. package/dist/lib/browser/index.mjs.map +1 -1
  7. package/dist/lib/browser/meta.json +1 -1
  8. package/dist/lib/browser/testing/index.mjs +522 -11
  9. package/dist/lib/browser/testing/index.mjs.map +4 -4
  10. package/dist/lib/browser/types.mjs +1 -1
  11. package/dist/lib/node/{chunk-3E6PY6JH.cjs → chunk-GGTHSME4.cjs} +5 -4
  12. package/dist/lib/node/{chunk-3E6PY6JH.cjs.map → chunk-GGTHSME4.cjs.map} +3 -3
  13. package/dist/lib/node/chunk-S4S6FO6X.cjs +613 -0
  14. package/dist/lib/node/chunk-S4S6FO6X.cjs.map +7 -0
  15. package/dist/lib/node/index.cjs +14 -12
  16. package/dist/lib/node/index.cjs.map +1 -1
  17. package/dist/lib/node/meta.json +1 -1
  18. package/dist/lib/node/testing/index.cjs +521 -13
  19. package/dist/lib/node/testing/index.cjs.map +4 -4
  20. package/dist/lib/node/types.cjs +5 -5
  21. package/dist/lib/node/types.cjs.map +1 -1
  22. package/dist/types/src/index.d.ts +0 -1
  23. package/dist/types/src/index.d.ts.map +1 -1
  24. package/dist/types/src/runtime/scheduler.d.ts.map +1 -1
  25. package/dist/types/src/trigger/index.d.ts +1 -0
  26. package/dist/types/src/trigger/index.d.ts.map +1 -1
  27. package/dist/types/src/trigger/trigger-registry.d.ts +5 -4
  28. package/dist/types/src/trigger/trigger-registry.d.ts.map +1 -1
  29. package/dist/types/src/trigger/type/index.d.ts +0 -1
  30. package/dist/types/src/trigger/type/index.d.ts.map +1 -1
  31. package/dist/types/src/types.d.ts +4 -0
  32. package/dist/types/src/types.d.ts.map +1 -1
  33. package/package.json +14 -14
  34. package/src/index.ts +1 -1
  35. package/src/runtime/scheduler.ts +6 -3
  36. package/src/trigger/index.ts +1 -0
  37. package/src/trigger/trigger-registry.test.ts +2 -1
  38. package/src/trigger/trigger-registry.ts +15 -7
  39. package/src/trigger/type/index.ts +1 -1
  40. package/src/types.ts +1 -0
  41. package/dist/lib/browser/chunk-OERXFETS.mjs +0 -1120
  42. package/dist/lib/browser/chunk-OERXFETS.mjs.map +0 -7
  43. package/dist/lib/node/chunk-ITQU6E54.cjs +0 -1133
  44. package/dist/lib/node/chunk-ITQU6E54.cjs.map +0 -7
@@ -4,7 +4,7 @@ import {
4
4
  FunctionDef,
5
5
  FunctionManifestSchema,
6
6
  FunctionTrigger
7
- } from "./chunk-YSDC6YCF.mjs";
7
+ } from "./chunk-XOBJR3A6.mjs";
8
8
  export {
9
9
  FUNCTION_SCHEMA,
10
10
  FunctionDef,
@@ -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_3E6PY6JH_exports = {};
20
- __export(chunk_3E6PY6JH_exports, {
19
+ var chunk_GGTHSME4_exports = {};
20
+ __export(chunk_GGTHSME4_exports, {
21
21
  FUNCTION_SCHEMA: () => FUNCTION_SCHEMA,
22
22
  FunctionDef: () => FunctionDef,
23
23
  FunctionManifestSchema: () => FunctionManifestSchema,
24
24
  FunctionTrigger: () => FunctionTrigger,
25
25
  __require: () => __require
26
26
  });
27
- module.exports = __toCommonJS(chunk_3E6PY6JH_exports);
27
+ module.exports = __toCommonJS(chunk_GGTHSME4_exports);
28
28
  var import_echo_schema = require("@dxos/echo-schema");
29
29
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
30
30
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
@@ -77,6 +77,7 @@ var FunctionTrigger = class extends (0, import_echo_schema.TypedObject)({
77
77
  typename: "dxos.org/type/FunctionTrigger",
78
78
  version: "0.1.0"
79
79
  })({
80
+ name: import_echo_schema.S.optional(import_echo_schema.S.String),
80
81
  enabled: import_echo_schema.S.optional(import_echo_schema.S.Boolean),
81
82
  function: import_echo_schema.S.String.pipe(import_echo_schema.S.description("Function URI.")),
82
83
  // The `meta` property is merged into the event data passed to the function.
@@ -100,4 +101,4 @@ var FUNCTION_SCHEMA = [
100
101
  FunctionTrigger,
101
102
  __require
102
103
  });
103
- //# sourceMappingURL=chunk-3E6PY6JH.cjs.map
104
+ //# sourceMappingURL=chunk-GGTHSME4.cjs.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/types.ts"],
4
- "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport { RawObject, S, TypedObject } from '@dxos/echo-schema';\n\n/**\n * Type discriminator for TriggerSpec.\n * Every spec has a type field of type FunctionTriggerType that we can use to understand which\n * type we're working with.\n * https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions\n */\nexport type FunctionTriggerType = 'subscription' | 'timer' | 'webhook' | 'websocket';\n\nconst SubscriptionTriggerSchema = S.mutable(\n S.Struct({\n type: S.Literal('subscription'),\n // TODO(burdon): Define query DSL (from ECHO).\n filter: S.Array(\n S.Struct({\n type: S.String,\n props: S.optional(S.Record(S.String, S.Any)),\n }),\n ),\n options: S.optional(\n S.Struct({\n // Watch changes to object (not just creation).\n deep: S.optional(S.Boolean),\n // Debounce changes (delay in ms).\n delay: S.optional(S.Number),\n }),\n ),\n }),\n);\n\nexport type SubscriptionTrigger = S.Schema.Type<typeof SubscriptionTriggerSchema>;\n\nconst TimerTriggerSchema = S.mutable(\n S.Struct({\n type: S.Literal('timer'),\n cron: S.String,\n }),\n);\n\nexport type TimerTrigger = S.Schema.Type<typeof TimerTriggerSchema>;\n\nconst WebhookTriggerSchema = S.mutable(\n S.Struct({\n type: S.Literal('webhook'),\n method: S.String,\n // Assigned port.\n port: S.optional(S.Number),\n }),\n);\n\nexport type WebhookTrigger = S.Schema.Type<typeof WebhookTriggerSchema>;\n\nconst WebsocketTriggerSchema = S.mutable(\n S.Struct({\n type: S.Literal('websocket'),\n url: S.String,\n init: S.optional(S.Record(S.String, S.Any)),\n }),\n);\n\nexport type WebsocketTrigger = S.Schema.Type<typeof WebsocketTriggerSchema>;\n\nconst TriggerSpecSchema = S.Union(\n TimerTriggerSchema,\n WebhookTriggerSchema,\n WebsocketTriggerSchema,\n SubscriptionTriggerSchema,\n);\n\nexport type TriggerSpec = TimerTrigger | WebhookTrigger | WebsocketTrigger | SubscriptionTrigger;\n\n/**\n * Function definition.\n */\nexport class FunctionDef extends TypedObject({\n typename: 'dxos.org/type/FunctionDef',\n version: '0.1.0',\n})({\n uri: S.String,\n description: S.optional(S.String),\n route: S.String,\n handler: S.String,\n}) {}\n\n/**\n * Function trigger.\n */\nexport class FunctionTrigger extends TypedObject({\n typename: 'dxos.org/type/FunctionTrigger',\n version: '0.1.0',\n})({\n enabled: S.optional(S.Boolean),\n function: S.String.pipe(S.description('Function URI.')),\n // The `meta` property is merged into the event data passed to the function.\n meta: S.optional(S.mutable(S.Record(S.String, S.Any))),\n spec: TriggerSpecSchema,\n}) {}\n\n/**\n * Function manifest file.\n */\nexport const FunctionManifestSchema = S.Struct({\n functions: S.optional(S.mutable(S.Array(RawObject(FunctionDef)))),\n triggers: S.optional(S.mutable(S.Array(RawObject(FunctionTrigger)))),\n});\n\nexport type FunctionManifest = S.Schema.Type<typeof FunctionManifestSchema>;\n\n// TODO(burdon): Standards?\nexport const FUNCTION_SCHEMA = [FunctionDef, FunctionTrigger];\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,yBAA0C;;;;;;;;AAU1C,IAAMA,4BAA4BC,qBAAEC,QAClCD,qBAAEE,OAAO;EACPC,MAAMH,qBAAEI,QAAQ,cAAA;;EAEhBC,QAAQL,qBAAEM,MACRN,qBAAEE,OAAO;IACPC,MAAMH,qBAAEO;IACRC,OAAOR,qBAAES,SAAST,qBAAEU,OAAOV,qBAAEO,QAAQP,qBAAEW,GAAG,CAAA;EAC5C,CAAA,CAAA;EAEFC,SAASZ,qBAAES,SACTT,qBAAEE,OAAO;;IAEPW,MAAMb,qBAAES,SAAST,qBAAEc,OAAO;;IAE1BC,OAAOf,qBAAES,SAAST,qBAAEgB,MAAM;EAC5B,CAAA,CAAA;AAEJ,CAAA,CAAA;AAKF,IAAMC,qBAAqBjB,qBAAEC,QAC3BD,qBAAEE,OAAO;EACPC,MAAMH,qBAAEI,QAAQ,OAAA;EAChBc,MAAMlB,qBAAEO;AACV,CAAA,CAAA;AAKF,IAAMY,uBAAuBnB,qBAAEC,QAC7BD,qBAAEE,OAAO;EACPC,MAAMH,qBAAEI,QAAQ,SAAA;EAChBgB,QAAQpB,qBAAEO;;EAEVc,MAAMrB,qBAAES,SAAST,qBAAEgB,MAAM;AAC3B,CAAA,CAAA;AAKF,IAAMM,yBAAyBtB,qBAAEC,QAC/BD,qBAAEE,OAAO;EACPC,MAAMH,qBAAEI,QAAQ,WAAA;EAChBmB,KAAKvB,qBAAEO;EACPiB,MAAMxB,qBAAES,SAAST,qBAAEU,OAAOV,qBAAEO,QAAQP,qBAAEW,GAAG,CAAA;AAC3C,CAAA,CAAA;AAKF,IAAMc,oBAAoBzB,qBAAE0B,MAC1BT,oBACAE,sBACAG,wBACAvB,yBAAAA;AAQK,IAAM4B,cAAN,kBAA0BC,gCAAY;EAC3CC,UAAU;EACVC,SAAS;AACX,CAAA,EAAG;EACDC,KAAK/B,qBAAEO;EACPyB,aAAahC,qBAAES,SAAST,qBAAEO,MAAM;EAChC0B,OAAOjC,qBAAEO;EACT2B,SAASlC,qBAAEO;AACb,CAAA,EAAA;AAAI;AAKG,IAAM4B,kBAAN,kBAA8BP,gCAAY;EAC/CC,UAAU;EACVC,SAAS;AACX,CAAA,EAAG;EACDM,SAASpC,qBAAES,SAAST,qBAAEc,OAAO;EAC7BuB,UAAUrC,qBAAEO,OAAO+B,KAAKtC,qBAAEgC,YAAY,eAAA,CAAA;;EAEtCO,MAAMvC,qBAAES,SAAST,qBAAEC,QAAQD,qBAAEU,OAAOV,qBAAEO,QAAQP,qBAAEW,GAAG,CAAA,CAAA;EACnD6B,MAAMf;AACR,CAAA,EAAA;AAAI;AAKG,IAAMgB,yBAAyBzC,qBAAEE,OAAO;EAC7CwC,WAAW1C,qBAAES,SAAST,qBAAEC,QAAQD,qBAAEM,UAAMqC,8BAAUhB,WAAAA,CAAAA,CAAAA,CAAAA;EAClDiB,UAAU5C,qBAAES,SAAST,qBAAEC,QAAQD,qBAAEM,UAAMqC,8BAAUR,eAAAA,CAAAA,CAAAA,CAAAA;AACnD,CAAA;AAKO,IAAMU,kBAAkB;EAAClB;EAAaQ;;",
6
- "names": ["SubscriptionTriggerSchema", "S", "mutable", "Struct", "type", "Literal", "filter", "Array", "String", "props", "optional", "Record", "Any", "options", "deep", "Boolean", "delay", "Number", "TimerTriggerSchema", "cron", "WebhookTriggerSchema", "method", "port", "WebsocketTriggerSchema", "url", "init", "TriggerSpecSchema", "Union", "FunctionDef", "TypedObject", "typename", "version", "uri", "description", "route", "handler", "FunctionTrigger", "enabled", "function", "pipe", "meta", "spec", "FunctionManifestSchema", "functions", "RawObject", "triggers", "FUNCTION_SCHEMA"]
4
+ "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport { RawObject, S, TypedObject } from '@dxos/echo-schema';\n\n/**\n * Type discriminator for TriggerSpec.\n * Every spec has a type field of type FunctionTriggerType that we can use to understand which\n * type we're working with.\n * https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions\n */\nexport type FunctionTriggerType = 'subscription' | 'timer' | 'webhook' | 'websocket';\n\nconst SubscriptionTriggerSchema = S.mutable(\n S.Struct({\n type: S.Literal('subscription'),\n // TODO(burdon): Define query DSL (from ECHO).\n filter: S.Array(\n S.Struct({\n type: S.String,\n props: S.optional(S.Record(S.String, S.Any)),\n }),\n ),\n options: S.optional(\n S.Struct({\n // Watch changes to object (not just creation).\n deep: S.optional(S.Boolean),\n // Debounce changes (delay in ms).\n delay: S.optional(S.Number),\n }),\n ),\n }),\n);\n\nexport type SubscriptionTrigger = S.Schema.Type<typeof SubscriptionTriggerSchema>;\n\nconst TimerTriggerSchema = S.mutable(\n S.Struct({\n type: S.Literal('timer'),\n cron: S.String,\n }),\n);\n\nexport type TimerTrigger = S.Schema.Type<typeof TimerTriggerSchema>;\n\nconst WebhookTriggerSchema = S.mutable(\n S.Struct({\n type: S.Literal('webhook'),\n method: S.String,\n // Assigned port.\n port: S.optional(S.Number),\n }),\n);\n\nexport type WebhookTrigger = S.Schema.Type<typeof WebhookTriggerSchema>;\n\nconst WebsocketTriggerSchema = S.mutable(\n S.Struct({\n type: S.Literal('websocket'),\n url: S.String,\n init: S.optional(S.Record(S.String, S.Any)),\n }),\n);\n\nexport type WebsocketTrigger = S.Schema.Type<typeof WebsocketTriggerSchema>;\n\nconst TriggerSpecSchema = S.Union(\n TimerTriggerSchema,\n WebhookTriggerSchema,\n WebsocketTriggerSchema,\n SubscriptionTriggerSchema,\n);\n\nexport type TriggerSpec = TimerTrigger | WebhookTrigger | WebsocketTrigger | SubscriptionTrigger;\n\n/**\n * Function definition.\n */\nexport class FunctionDef extends TypedObject({\n typename: 'dxos.org/type/FunctionDef',\n version: '0.1.0',\n})({\n uri: S.String,\n description: S.optional(S.String),\n route: S.String,\n handler: S.String,\n}) {}\n\n/**\n * Function trigger.\n */\nexport class FunctionTrigger extends TypedObject({\n typename: 'dxos.org/type/FunctionTrigger',\n version: '0.1.0',\n})({\n name: S.optional(S.String),\n enabled: S.optional(S.Boolean),\n function: S.String.pipe(S.description('Function URI.')),\n // The `meta` property is merged into the event data passed to the function.\n meta: S.optional(S.mutable(S.Record(S.String, S.Any))),\n spec: TriggerSpecSchema,\n}) {}\n\n/**\n * Function manifest file.\n */\nexport const FunctionManifestSchema = S.Struct({\n functions: S.optional(S.mutable(S.Array(RawObject(FunctionDef)))),\n triggers: S.optional(S.mutable(S.Array(RawObject(FunctionTrigger)))),\n});\n\nexport type FunctionManifest = S.Schema.Type<typeof FunctionManifestSchema>;\n\n// TODO(burdon): Standards?\nexport const FUNCTION_SCHEMA = [FunctionDef, FunctionTrigger];\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,yBAA0C;;;;;;;;AAU1C,IAAMA,4BAA4BC,qBAAEC,QAClCD,qBAAEE,OAAO;EACPC,MAAMH,qBAAEI,QAAQ,cAAA;;EAEhBC,QAAQL,qBAAEM,MACRN,qBAAEE,OAAO;IACPC,MAAMH,qBAAEO;IACRC,OAAOR,qBAAES,SAAST,qBAAEU,OAAOV,qBAAEO,QAAQP,qBAAEW,GAAG,CAAA;EAC5C,CAAA,CAAA;EAEFC,SAASZ,qBAAES,SACTT,qBAAEE,OAAO;;IAEPW,MAAMb,qBAAES,SAAST,qBAAEc,OAAO;;IAE1BC,OAAOf,qBAAES,SAAST,qBAAEgB,MAAM;EAC5B,CAAA,CAAA;AAEJ,CAAA,CAAA;AAKF,IAAMC,qBAAqBjB,qBAAEC,QAC3BD,qBAAEE,OAAO;EACPC,MAAMH,qBAAEI,QAAQ,OAAA;EAChBc,MAAMlB,qBAAEO;AACV,CAAA,CAAA;AAKF,IAAMY,uBAAuBnB,qBAAEC,QAC7BD,qBAAEE,OAAO;EACPC,MAAMH,qBAAEI,QAAQ,SAAA;EAChBgB,QAAQpB,qBAAEO;;EAEVc,MAAMrB,qBAAES,SAAST,qBAAEgB,MAAM;AAC3B,CAAA,CAAA;AAKF,IAAMM,yBAAyBtB,qBAAEC,QAC/BD,qBAAEE,OAAO;EACPC,MAAMH,qBAAEI,QAAQ,WAAA;EAChBmB,KAAKvB,qBAAEO;EACPiB,MAAMxB,qBAAES,SAAST,qBAAEU,OAAOV,qBAAEO,QAAQP,qBAAEW,GAAG,CAAA;AAC3C,CAAA,CAAA;AAKF,IAAMc,oBAAoBzB,qBAAE0B,MAC1BT,oBACAE,sBACAG,wBACAvB,yBAAAA;AAQK,IAAM4B,cAAN,kBAA0BC,gCAAY;EAC3CC,UAAU;EACVC,SAAS;AACX,CAAA,EAAG;EACDC,KAAK/B,qBAAEO;EACPyB,aAAahC,qBAAES,SAAST,qBAAEO,MAAM;EAChC0B,OAAOjC,qBAAEO;EACT2B,SAASlC,qBAAEO;AACb,CAAA,EAAA;AAAI;AAKG,IAAM4B,kBAAN,kBAA8BP,gCAAY;EAC/CC,UAAU;EACVC,SAAS;AACX,CAAA,EAAG;EACDM,MAAMpC,qBAAES,SAAST,qBAAEO,MAAM;EACzB8B,SAASrC,qBAAES,SAAST,qBAAEc,OAAO;EAC7BwB,UAAUtC,qBAAEO,OAAOgC,KAAKvC,qBAAEgC,YAAY,eAAA,CAAA;;EAEtCQ,MAAMxC,qBAAES,SAAST,qBAAEC,QAAQD,qBAAEU,OAAOV,qBAAEO,QAAQP,qBAAEW,GAAG,CAAA,CAAA;EACnD8B,MAAMhB;AACR,CAAA,EAAA;AAAI;AAKG,IAAMiB,yBAAyB1C,qBAAEE,OAAO;EAC7CyC,WAAW3C,qBAAES,SAAST,qBAAEC,QAAQD,qBAAEM,UAAMsC,8BAAUjB,WAAAA,CAAAA,CAAAA,CAAAA;EAClDkB,UAAU7C,qBAAES,SAAST,qBAAEC,QAAQD,qBAAEM,UAAMsC,8BAAUT,eAAAA,CAAAA,CAAAA,CAAAA;AACnD,CAAA;AAKO,IAAMW,kBAAkB;EAACnB;EAAaQ;;",
6
+ "names": ["SubscriptionTriggerSchema", "S", "mutable", "Struct", "type", "Literal", "filter", "Array", "String", "props", "optional", "Record", "Any", "options", "deep", "Boolean", "delay", "Number", "TimerTriggerSchema", "cron", "WebhookTriggerSchema", "method", "port", "WebsocketTriggerSchema", "url", "init", "TriggerSpecSchema", "Union", "FunctionDef", "TypedObject", "typename", "version", "uri", "description", "route", "handler", "FunctionTrigger", "name", "enabled", "function", "pipe", "meta", "spec", "FunctionManifestSchema", "functions", "RawObject", "triggers", "FUNCTION_SCHEMA"]
7
7
  }
@@ -0,0 +1,613 @@
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_S4S6FO6X_exports = {};
30
+ __export(chunk_S4S6FO6X_exports, {
31
+ FunctionRegistry: () => FunctionRegistry,
32
+ TriggerRegistry: () => TriggerRegistry,
33
+ createSubscriptionTrigger: () => createSubscriptionTrigger,
34
+ createTimerTrigger: () => createTimerTrigger,
35
+ createWebsocketTrigger: () => createWebsocketTrigger
36
+ });
37
+ module.exports = __toCommonJS(chunk_S4S6FO6X_exports);
38
+ var import_chunk_GGTHSME4 = require("./chunk-GGTHSME4.cjs");
39
+ var import_async = require("@dxos/async");
40
+ var import_echo = require("@dxos/client/echo");
41
+ var import_context = require("@dxos/context");
42
+ var import_keys = require("@dxos/keys");
43
+ var import_log = require("@dxos/log");
44
+ var import_util = require("@dxos/util");
45
+ var import_async2 = require("@dxos/async");
46
+ var import_echo2 = require("@dxos/client/echo");
47
+ var import_echo_db = require("@dxos/echo-db");
48
+ var import_log2 = require("@dxos/log");
49
+ var import_cron = require("cron");
50
+ var import_async3 = require("@dxos/async");
51
+ var import_log3 = require("@dxos/log");
52
+ var import_ws = __toESM(require("ws"));
53
+ var import_async4 = require("@dxos/async");
54
+ var import_log4 = require("@dxos/log");
55
+ var import_async5 = require("@dxos/async");
56
+ var import_echo3 = require("@dxos/client/echo");
57
+ var import_context2 = require("@dxos/context");
58
+ var import_echo_schema = require("@dxos/echo-schema");
59
+ var import_invariant = require("@dxos/invariant");
60
+ var import_keys2 = require("@dxos/keys");
61
+ var import_log5 = require("@dxos/log");
62
+ var import_util2 = require("@dxos/util");
63
+ var __dxlog_file = "/home/runner/work/dxos/dxos/packages/core/functions/src/function/function-registry.ts";
64
+ var FunctionRegistry = class extends import_context.Resource {
65
+ constructor(_client) {
66
+ super();
67
+ this._client = _client;
68
+ this._functionBySpaceKey = new import_util.ComplexMap(import_keys.PublicKey.hash);
69
+ this.registered = new import_async.Event();
70
+ }
71
+ getFunctions(space) {
72
+ return this._functionBySpaceKey.get(space.key) ?? [];
73
+ }
74
+ getUniqueByUri() {
75
+ const uniqueByUri = [
76
+ ...this._functionBySpaceKey.values()
77
+ ].flatMap((defs) => defs).reduce((acc, v) => {
78
+ acc.set(v.uri, v);
79
+ return acc;
80
+ }, /* @__PURE__ */ new Map());
81
+ return [
82
+ ...uniqueByUri.values()
83
+ ];
84
+ }
85
+ /**
86
+ * Loads function definitions from the manifest into the space.
87
+ * We first load all the definitions from the space to deduplicate by functionId.
88
+ */
89
+ async register(space, functions) {
90
+ (0, import_log.log)("register", {
91
+ space: space.key,
92
+ functions: functions?.length ?? 0
93
+ }, {
94
+ F: __dxlog_file,
95
+ L: 48,
96
+ S: this,
97
+ C: (f, a) => f(...a)
98
+ });
99
+ if (!functions?.length) {
100
+ return;
101
+ }
102
+ if (!space.db.graph.schemaRegistry.hasSchema(import_chunk_GGTHSME4.FunctionDef)) {
103
+ space.db.graph.schemaRegistry.addSchema([
104
+ import_chunk_GGTHSME4.FunctionDef
105
+ ]);
106
+ }
107
+ const { objects: existing } = await space.db.query(import_echo.Filter.schema(import_chunk_GGTHSME4.FunctionDef)).run();
108
+ const { added } = (0, import_util.diff)(existing, functions, (a, b) => a.uri === b.uri);
109
+ added.forEach((def) => space.db.add((0, import_echo.create)(import_chunk_GGTHSME4.FunctionDef, def)));
110
+ if (added.length > 0) {
111
+ await space.db.flush({
112
+ indexes: true,
113
+ updates: true
114
+ });
115
+ }
116
+ }
117
+ async _open() {
118
+ import_log.log.info("opening...", void 0, {
119
+ F: __dxlog_file,
120
+ L: 68,
121
+ S: this,
122
+ C: (f, a) => f(...a)
123
+ });
124
+ const spacesSubscription = this._client.spaces.subscribe(async (spaces) => {
125
+ for (const space of spaces) {
126
+ if (this._functionBySpaceKey.has(space.key)) {
127
+ continue;
128
+ }
129
+ const registered = [];
130
+ this._functionBySpaceKey.set(space.key, registered);
131
+ await space.waitUntilReady();
132
+ if (this._ctx.disposed) {
133
+ break;
134
+ }
135
+ this._ctx.onDispose(space.db.query(import_echo.Filter.schema(import_chunk_GGTHSME4.FunctionDef)).subscribe(({ objects }) => {
136
+ const { added } = (0, import_util.diff)(registered, objects, (a, b) => a.uri === b.uri);
137
+ if (added.length > 0) {
138
+ registered.push(...added);
139
+ this.registered.emit({
140
+ space,
141
+ added
142
+ });
143
+ }
144
+ }));
145
+ }
146
+ });
147
+ this._ctx.onDispose(() => spacesSubscription.unsubscribe());
148
+ }
149
+ async _close(_) {
150
+ import_log.log.info("closing...", void 0, {
151
+ F: __dxlog_file,
152
+ L: 101,
153
+ S: this,
154
+ C: (f, a) => f(...a)
155
+ });
156
+ this._functionBySpaceKey.clear();
157
+ }
158
+ };
159
+ var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/core/functions/src/trigger/type/subscription-trigger.ts";
160
+ var createSubscriptionTrigger = async (ctx, space, spec, callback) => {
161
+ const objectIds = /* @__PURE__ */ new Set();
162
+ const task = new import_async2.UpdateScheduler(ctx, async () => {
163
+ if (objectIds.size > 0) {
164
+ const objects = Array.from(objectIds);
165
+ objectIds.clear();
166
+ await callback({
167
+ objects
168
+ });
169
+ }
170
+ }, {
171
+ maxFrequency: 4
172
+ });
173
+ const subscriptions = [];
174
+ const subscription = (0, import_echo_db.createSubscription)(({ added, updated }) => {
175
+ const sizeBefore = objectIds.size;
176
+ for (const object of added) {
177
+ objectIds.add(object.id);
178
+ }
179
+ for (const object of updated) {
180
+ objectIds.add(object.id);
181
+ }
182
+ if (objectIds.size > sizeBefore) {
183
+ import_log2.log.info("updated", {
184
+ added: added.length,
185
+ updated: updated.length
186
+ }, {
187
+ F: __dxlog_file2,
188
+ L: 46,
189
+ S: void 0,
190
+ C: (f, a) => f(...a)
191
+ });
192
+ task.trigger();
193
+ }
194
+ });
195
+ subscriptions.push(() => subscription.unsubscribe());
196
+ const { filter, options: { deep, delay } = {} } = spec;
197
+ const update = ({ objects }) => {
198
+ import_log2.log.info("update", {
199
+ objects: objects.length
200
+ }, {
201
+ F: __dxlog_file2,
202
+ L: 56,
203
+ S: void 0,
204
+ C: (f, a) => f(...a)
205
+ });
206
+ subscription.update(objects);
207
+ if (deep) {
208
+ }
209
+ };
210
+ import_log2.log.info("subscription", {
211
+ filter
212
+ }, {
213
+ F: __dxlog_file2,
214
+ L: 74,
215
+ S: void 0,
216
+ C: (f, a) => f(...a)
217
+ });
218
+ if (filter) {
219
+ const query = space.db.query(import_echo2.Filter.typename(filter[0].type, filter[0].props));
220
+ subscriptions.push(query.subscribe(delay ? (0, import_async2.debounce)(update, delay) : update));
221
+ }
222
+ ctx.onDispose(() => {
223
+ subscriptions.forEach((unsubscribe) => unsubscribe());
224
+ });
225
+ };
226
+ var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/core/functions/src/trigger/type/timer-trigger.ts";
227
+ var createTimerTrigger = async (ctx, space, spec, callback) => {
228
+ const task = new import_async3.DeferredTask(ctx, async () => {
229
+ await callback({});
230
+ });
231
+ let last = 0;
232
+ let run = 0;
233
+ const job = import_cron.CronJob.from({
234
+ cronTime: spec.cron,
235
+ runOnInit: false,
236
+ onTick: () => {
237
+ const now = Date.now();
238
+ const delta = last ? now - last : 0;
239
+ last = now;
240
+ run++;
241
+ import_log3.log.info("tick", {
242
+ space: space.key.truncate(),
243
+ count: run,
244
+ delta
245
+ }, {
246
+ F: __dxlog_file3,
247
+ L: 38,
248
+ S: void 0,
249
+ C: (f, a) => f(...a)
250
+ });
251
+ task.schedule();
252
+ }
253
+ });
254
+ job.start();
255
+ ctx.onDispose(() => job.stop());
256
+ };
257
+ var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/core/functions/src/trigger/type/websocket-trigger.ts";
258
+ var createWebsocketTrigger = async (ctx, space, spec, callback, options = {
259
+ retryDelay: 2,
260
+ maxAttempts: 5
261
+ }) => {
262
+ const { url, init } = spec;
263
+ let wasOpen = false;
264
+ let ws;
265
+ for (let attempt = 1; attempt <= options.maxAttempts; attempt++) {
266
+ const open = new import_async4.Trigger();
267
+ ws = new import_ws.default(url);
268
+ Object.assign(ws, {
269
+ onopen: () => {
270
+ import_log4.log.info("opened", {
271
+ url
272
+ }, {
273
+ F: __dxlog_file4,
274
+ L: 41,
275
+ S: void 0,
276
+ C: (f, a) => f(...a)
277
+ });
278
+ if (spec.init) {
279
+ ws.send(new TextEncoder().encode(JSON.stringify(init)));
280
+ }
281
+ open.wake(true);
282
+ },
283
+ onclose: (event) => {
284
+ import_log4.log.info("closed", {
285
+ url,
286
+ code: event.code
287
+ }, {
288
+ F: __dxlog_file4,
289
+ L: 50,
290
+ S: void 0,
291
+ C: (f, a) => f(...a)
292
+ });
293
+ if (event.code === 1006 && wasOpen && !ctx.disposed) {
294
+ setTimeout(async () => {
295
+ import_log4.log.info(`reconnecting in ${options.retryDelay}s...`, {
296
+ url
297
+ }, {
298
+ F: __dxlog_file4,
299
+ L: 55,
300
+ S: void 0,
301
+ C: (f, a) => f(...a)
302
+ });
303
+ await createWebsocketTrigger(ctx, space, spec, callback, options);
304
+ }, options.retryDelay * 1e3);
305
+ }
306
+ open.wake(false);
307
+ },
308
+ onerror: (event) => {
309
+ import_log4.log.catch(event.error, {
310
+ url
311
+ }, {
312
+ F: __dxlog_file4,
313
+ L: 63,
314
+ S: void 0,
315
+ C: (f, a) => f(...a)
316
+ });
317
+ open.wake(false);
318
+ },
319
+ onmessage: async (event) => {
320
+ try {
321
+ import_log4.log.info("message", void 0, {
322
+ F: __dxlog_file4,
323
+ L: 69,
324
+ S: void 0,
325
+ C: (f, a) => f(...a)
326
+ });
327
+ const data = JSON.parse(new TextDecoder().decode(event.data));
328
+ await callback({
329
+ data
330
+ });
331
+ } catch (err) {
332
+ import_log4.log.catch(err, {
333
+ url
334
+ }, {
335
+ F: __dxlog_file4,
336
+ L: 73,
337
+ S: void 0,
338
+ C: (f, a) => f(...a)
339
+ });
340
+ }
341
+ }
342
+ });
343
+ const isOpen = await open.wait();
344
+ if (ctx.disposed) {
345
+ break;
346
+ }
347
+ if (isOpen) {
348
+ wasOpen = true;
349
+ break;
350
+ }
351
+ const wait = Math.pow(attempt, 2) * options.retryDelay;
352
+ if (attempt < options.maxAttempts) {
353
+ import_log4.log.warn(`failed to connect; trying again in ${wait}s`, {
354
+ attempt
355
+ }, {
356
+ F: __dxlog_file4,
357
+ L: 88,
358
+ S: void 0,
359
+ C: (f, a) => f(...a)
360
+ });
361
+ await (0, import_async4.sleep)(wait * 1e3);
362
+ }
363
+ }
364
+ ctx.onDispose(() => {
365
+ ws?.close();
366
+ });
367
+ };
368
+ var __dxlog_file5 = "/home/runner/work/dxos/dxos/packages/core/functions/src/trigger/trigger-registry.ts";
369
+ var triggerFactory = {
370
+ subscription: createSubscriptionTrigger,
371
+ timer: createTimerTrigger,
372
+ // TODO(burdon): Cannot use in browser.
373
+ // webhook: createWebhookTrigger,
374
+ webhook: null,
375
+ websocket: createWebsocketTrigger
376
+ };
377
+ var TriggerRegistry = class extends import_context2.Resource {
378
+ constructor(_client, _options) {
379
+ super();
380
+ this._client = _client;
381
+ this._options = _options;
382
+ this._triggersBySpaceKey = new import_util2.ComplexMap(import_keys2.PublicKey.hash);
383
+ this.registered = new import_async5.Event();
384
+ this.removed = new import_async5.Event();
385
+ }
386
+ getActiveTriggers(space) {
387
+ return this._getTriggers(space, (t) => t.activationCtx != null);
388
+ }
389
+ getInactiveTriggers(space) {
390
+ return this._getTriggers(space, (t) => t.activationCtx == null);
391
+ }
392
+ /**
393
+ * Set callback for trigger.
394
+ */
395
+ async activate(space, trigger, callback) {
396
+ (0, import_log5.log)("activate", {
397
+ space: space.key,
398
+ trigger
399
+ }, {
400
+ F: __dxlog_file5,
401
+ L: 77,
402
+ S: this,
403
+ C: (f, a) => f(...a)
404
+ });
405
+ const activationCtx = new import_context2.Context({
406
+ name: `FunctionTrigger-${trigger.function}`
407
+ }, {
408
+ F: __dxlog_file5,
409
+ L: 79
410
+ });
411
+ this._ctx.onDispose(() => activationCtx.dispose());
412
+ const registeredTrigger = this._triggersBySpaceKey.get(space.key)?.find((reg) => reg.trigger.id === trigger.id);
413
+ (0, import_invariant.invariant)(registeredTrigger, `Trigger is not registered: ${trigger.function}`, {
414
+ F: __dxlog_file5,
415
+ L: 82,
416
+ S: this,
417
+ A: [
418
+ "registeredTrigger",
419
+ "`Trigger is not registered: ${trigger.function}`"
420
+ ]
421
+ });
422
+ registeredTrigger.activationCtx = activationCtx;
423
+ try {
424
+ const options = this._options?.[trigger.spec.type];
425
+ const createTrigger = triggerFactory[trigger.spec.type];
426
+ (0, import_invariant.invariant)(createTrigger, `Trigger factory not found: ${trigger.spec.type}`, {
427
+ F: __dxlog_file5,
428
+ L: 89,
429
+ S: this,
430
+ A: [
431
+ "createTrigger",
432
+ "`Trigger factory not found: ${trigger.spec.type}`"
433
+ ]
434
+ });
435
+ await createTrigger(activationCtx, space, trigger.spec, callback, options);
436
+ } catch (err) {
437
+ delete registeredTrigger.activationCtx;
438
+ throw err;
439
+ }
440
+ }
441
+ /**
442
+ * Loads triggers from the manifest into the space.
443
+ */
444
+ async register(space, manifest) {
445
+ (0, import_log5.log)("register", {
446
+ space: space.key
447
+ }, {
448
+ F: __dxlog_file5,
449
+ L: 101,
450
+ S: this,
451
+ C: (f, a) => f(...a)
452
+ });
453
+ if (!manifest.triggers?.length) {
454
+ return;
455
+ }
456
+ if (!space.db.graph.schemaRegistry.hasSchema(import_chunk_GGTHSME4.FunctionTrigger)) {
457
+ space.db.graph.schemaRegistry.addSchema([
458
+ import_chunk_GGTHSME4.FunctionTrigger
459
+ ]);
460
+ }
461
+ const manifestTriggers = manifest.triggers.map((trigger) => {
462
+ let keys = trigger[import_echo_schema.ECHO_ATTR_META]?.keys;
463
+ delete trigger[import_echo_schema.ECHO_ATTR_META];
464
+ if (!keys?.length) {
465
+ keys = [
466
+ (0, import_echo_schema.foreignKey)("manifest", [
467
+ trigger.function,
468
+ trigger.spec.type
469
+ ].join(":"))
470
+ ];
471
+ }
472
+ return (0, import_echo3.create)(import_chunk_GGTHSME4.FunctionTrigger, trigger, {
473
+ keys
474
+ });
475
+ });
476
+ const { objects: existing } = await space.db.query(import_echo3.Filter.schema(import_chunk_GGTHSME4.FunctionTrigger)).run();
477
+ const { added } = (0, import_util2.diff)(existing, manifestTriggers, import_echo_schema.compareForeignKeys);
478
+ added.forEach((trigger) => {
479
+ space.db.add(trigger);
480
+ import_log5.log.info("added", {
481
+ meta: (0, import_echo3.getMeta)(trigger)
482
+ }, {
483
+ F: __dxlog_file5,
484
+ L: 128,
485
+ S: this,
486
+ C: (f, a) => f(...a)
487
+ });
488
+ });
489
+ if (added.length > 0) {
490
+ await space.db.flush();
491
+ }
492
+ }
493
+ async _open() {
494
+ import_log5.log.info("open...", void 0, {
495
+ F: __dxlog_file5,
496
+ L: 137,
497
+ S: this,
498
+ C: (f, a) => f(...a)
499
+ });
500
+ const spaceListSubscription = this._client.spaces.subscribe(async (spaces) => {
501
+ for (const space of spaces) {
502
+ if (this._triggersBySpaceKey.has(space.key)) {
503
+ continue;
504
+ }
505
+ const registered = [];
506
+ this._triggersBySpaceKey.set(space.key, registered);
507
+ await space.waitUntilReady();
508
+ if (this._ctx.disposed) {
509
+ break;
510
+ }
511
+ this._ctx.onDispose(space.db.query(import_echo3.Filter.schema(import_chunk_GGTHSME4.FunctionTrigger)).subscribe(async ({ objects: current }) => {
512
+ import_log5.log.info("update", {
513
+ space: space.key,
514
+ registered: registered.length,
515
+ current: current.length
516
+ }, {
517
+ F: __dxlog_file5,
518
+ L: 154,
519
+ S: this,
520
+ C: (f, a) => f(...a)
521
+ });
522
+ await this._handleRemovedTriggers(space, current, registered);
523
+ this._handleNewTriggers(space, current, registered);
524
+ }));
525
+ }
526
+ });
527
+ this._ctx.onDispose(() => spaceListSubscription.unsubscribe());
528
+ import_log5.log.info("opened", void 0, {
529
+ F: __dxlog_file5,
530
+ L: 163,
531
+ S: this,
532
+ C: (f, a) => f(...a)
533
+ });
534
+ }
535
+ async _close(_) {
536
+ import_log5.log.info("close...", void 0, {
537
+ F: __dxlog_file5,
538
+ L: 167,
539
+ S: this,
540
+ C: (f, a) => f(...a)
541
+ });
542
+ this._triggersBySpaceKey.clear();
543
+ import_log5.log.info("closed", void 0, {
544
+ F: __dxlog_file5,
545
+ L: 169,
546
+ S: this,
547
+ C: (f, a) => f(...a)
548
+ });
549
+ }
550
+ _handleNewTriggers(space, current, registered) {
551
+ const added = current.filter((candidate) => {
552
+ return candidate.enabled && registered.find((reg) => reg.trigger.id === candidate.id) == null;
553
+ });
554
+ if (added.length > 0) {
555
+ const newRegisteredTriggers = added.map((trigger) => ({
556
+ trigger
557
+ }));
558
+ registered.push(...newRegisteredTriggers);
559
+ import_log5.log.info("added", () => ({
560
+ spaceKey: space.key,
561
+ triggers: added.map((trigger) => trigger.function)
562
+ }), {
563
+ F: __dxlog_file5,
564
+ L: 180,
565
+ S: this,
566
+ C: (f, a) => f(...a)
567
+ });
568
+ this.registered.emit({
569
+ space,
570
+ triggers: added
571
+ });
572
+ }
573
+ }
574
+ async _handleRemovedTriggers(space, current, registered) {
575
+ const removed = [];
576
+ for (let i = registered.length - 1; i >= 0; i--) {
577
+ const wasRemoved = current.filter((trigger) => trigger.enabled).find((trigger) => trigger.id === registered[i].trigger.id) == null;
578
+ if (wasRemoved) {
579
+ const unregistered = registered.splice(i, 1)[0];
580
+ await unregistered.activationCtx?.dispose();
581
+ removed.push(unregistered.trigger);
582
+ }
583
+ }
584
+ if (removed.length > 0) {
585
+ import_log5.log.info("removed", () => ({
586
+ spaceKey: space.key,
587
+ triggers: removed.map((trigger) => trigger.function)
588
+ }), {
589
+ F: __dxlog_file5,
590
+ L: 206,
591
+ S: this,
592
+ C: (f, a) => f(...a)
593
+ });
594
+ this.removed.emit({
595
+ space,
596
+ triggers: removed
597
+ });
598
+ }
599
+ }
600
+ _getTriggers(space, predicate) {
601
+ const allSpaceTriggers = this._triggersBySpaceKey.get(space.key) ?? [];
602
+ return allSpaceTriggers.filter(predicate).map((trigger) => trigger.trigger);
603
+ }
604
+ };
605
+ // Annotate the CommonJS export names for ESM import in node:
606
+ 0 && (module.exports = {
607
+ FunctionRegistry,
608
+ TriggerRegistry,
609
+ createSubscriptionTrigger,
610
+ createTimerTrigger,
611
+ createWebsocketTrigger
612
+ });
613
+ //# sourceMappingURL=chunk-S4S6FO6X.cjs.map