@dxos/functions 0.1.52 → 0.1.53-main.09c4c35

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.
@@ -30,96 +30,265 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // packages/core/functions/src/index.ts
31
31
  var src_exports = {};
32
32
  __export(src_exports, {
33
- runFunctions: () => runFunctions
33
+ DevServer: () => DevServer,
34
+ TriggerManager: () => TriggerManager
34
35
  });
35
36
  module.exports = __toCommonJS(src_exports);
36
37
 
37
- // packages/core/functions/src/runtime/index.ts
38
+ // packages/core/functions/src/runtime/dev-server.ts
38
39
  var import_express = __toESM(require("express"));
39
- var import_promises = require("node:fs/promises");
40
40
  var import_node_path = require("node:path");
41
41
  var import_portfinder = require("portfinder");
42
+ var import_async = require("@dxos/async");
42
43
  var import_log = require("@dxos/log");
43
- var FUNCTION_EXTENSIONS = [
44
- ".js",
45
- ".ts"
46
- ];
47
- var runFunctions = async (options) => {
48
- const files = await (0, import_promises.readdir)(options.functionsDirectory);
49
- const functionHandlers = {};
50
- for (const file of files) {
51
- if (!FUNCTION_EXTENSIONS.some((ext) => (0, import_node_path.extname)(file) === ext)) {
52
- continue;
53
- }
54
- try {
55
- const module2 = require((0, import_node_path.join)(options.functionsDirectory, file));
56
- const handler = module2.default;
57
- if (typeof handler !== "function") {
58
- throw new Error(`Function ${file} does not export a default function`);
44
+ var DEFAULT_PORT = 7e3;
45
+ var DevServer = class {
46
+ // prettier-ignore
47
+ constructor(_client, _options) {
48
+ this._client = _client;
49
+ this._options = _options;
50
+ this._functionHandlers = {};
51
+ }
52
+ get port() {
53
+ return this._port;
54
+ }
55
+ get endpoint() {
56
+ return this._port ? `http://localhost:${this._port}` : void 0;
57
+ }
58
+ get functions() {
59
+ return Object.keys(this._functionHandlers);
60
+ }
61
+ async initialize() {
62
+ for (const [name, _] of Object.entries(this._options.manifest.functions)) {
63
+ try {
64
+ const module2 = require((0, import_node_path.join)(this._options.directory, name));
65
+ const handler = module2.default;
66
+ if (typeof handler !== "function") {
67
+ throw new Error(`Handler must export default function: ${name}`);
68
+ }
69
+ this._functionHandlers[name] = handler;
70
+ } catch (err) {
71
+ import_log.log.error("parsing function (check functions.yml manifest)", err, {
72
+ file: "dev-server.ts",
73
+ line: 63,
74
+ scope: this,
75
+ callSite: (f, a) => f(...a)
76
+ });
59
77
  }
60
- const functionName = file.slice(0, -(0, import_node_path.extname)(file).length);
61
- functionHandlers[functionName] = handler;
62
- } catch (e) {
63
- console.error(e);
64
78
  }
65
79
  }
66
- const port = await (0, import_portfinder.getPortPromise)({
67
- startPort: 7e3
68
- });
69
- const app = (0, import_express.default)();
70
- app.use(import_express.default.json());
71
- app.post("/:functionName", async (req, res) => {
72
- const functionName = req.params.functionName;
73
- const replyBuilder = {
74
- status: (code) => {
75
- res.statusCode = code;
76
- return replyBuilder;
77
- },
78
- succeed: (result) => {
79
- res.end(JSON.stringify(result));
80
- return replyBuilder;
80
+ async start() {
81
+ const app = (0, import_express.default)();
82
+ app.use(import_express.default.json());
83
+ app.post("/:functionName", async (req, res) => {
84
+ const functionName = req.params.functionName;
85
+ const builder = {
86
+ status: (code) => {
87
+ res.statusCode = code;
88
+ return builder;
89
+ },
90
+ succeed: (result = {}) => {
91
+ res.end(JSON.stringify(result));
92
+ return builder;
93
+ }
94
+ };
95
+ const context = {
96
+ client: this._client,
97
+ status: builder.status.bind(builder)
98
+ };
99
+ void (async () => {
100
+ try {
101
+ await this._functionHandlers[functionName](req.body, context);
102
+ } catch (err) {
103
+ res.statusCode = 500;
104
+ res.end(err.message);
105
+ }
106
+ })();
107
+ });
108
+ this._port = await (0, import_portfinder.getPortPromise)({
109
+ startPort: DEFAULT_PORT
110
+ });
111
+ this._server = app.listen(this._port);
112
+ const { registrationId } = await this._client.services.services.FunctionRegistryService.register({
113
+ endpoint: this.endpoint,
114
+ functions: this.functions.map((name) => ({
115
+ name
116
+ }))
117
+ });
118
+ this._registrationId = registrationId;
119
+ }
120
+ async stop() {
121
+ var _a;
122
+ const trigger = new import_async.Trigger();
123
+ (_a = this._server) == null ? void 0 : _a.close(async () => {
124
+ if (this._registrationId) {
125
+ await this._client.services.services.FunctionRegistryService.unregister({
126
+ registrationId: this._registrationId
127
+ });
128
+ this._registrationId = void 0;
81
129
  }
82
- };
83
- const context = {
84
- client: options.client,
85
- status: replyBuilder.status.bind(replyBuilder)
86
- };
87
- void (async () => {
88
- try {
89
- await functionHandlers[functionName](req.body, context);
90
- } catch (err) {
91
- res.statusCode = 500;
92
- res.end(err.message);
130
+ trigger.wake();
131
+ });
132
+ await trigger.wait();
133
+ this._server = void 0;
134
+ this._port = void 0;
135
+ }
136
+ };
137
+
138
+ // packages/core/functions/src/runtime/trigger-manager.ts
139
+ var import_node_assert = __toESM(require("node:assert"));
140
+ var import_async2 = require("@dxos/async");
141
+ var import_context = require("@dxos/context");
142
+ var import_echo_schema = require("@dxos/echo-schema");
143
+ var import_log2 = require("@dxos/log");
144
+ var import_util = require("@dxos/util");
145
+ var TriggerManager = class {
146
+ constructor(_client, _triggers, _invokeOptions) {
147
+ this._client = _client;
148
+ this._triggers = _triggers;
149
+ this._invokeOptions = _invokeOptions;
150
+ this._mounts = new import_util.ComplexMap(({ name, spaceKey }) => `${spaceKey.toHex()}:${name}`);
151
+ }
152
+ async start() {
153
+ this._client.spaces.subscribe(async (spaces) => {
154
+ for (const space of spaces) {
155
+ await space.waitUntilReady();
156
+ for (const trigger of this._triggers) {
157
+ await this.mount(new import_context.Context(), trigger, space);
158
+ }
93
159
  }
94
- })();
95
- });
96
- app.listen(port);
97
- const functionNames = Object.keys(functionHandlers);
98
- const { registrationId } = await options.client.services.services.FunctionRegistryService.register({
99
- endpoint: `http://localhost:${port}`,
100
- functions: functionNames.map((name) => ({
101
- name
102
- }))
103
- });
104
- process.on("SIGINT", async () => {
105
- await options.client.services.services.FunctionRegistryService.unregister({
106
- registrationId
107
160
  });
108
- process.exit();
109
- });
110
- import_log.log.info("functions runtime started", {
111
- port,
112
- functionNames,
113
- registrationId
114
- }, {
115
- file: "index.ts",
116
- line: 93,
117
- scope: void 0,
118
- callSite: (f, a) => f(...a)
119
- });
161
+ }
162
+ async stop() {
163
+ for (const { name, spaceKey } of this._mounts.keys()) {
164
+ await this.unmount(name, spaceKey);
165
+ }
166
+ }
167
+ async mount(ctx, trigger, space) {
168
+ const key = {
169
+ name: trigger.function,
170
+ spaceKey: space.key
171
+ };
172
+ const exists = this._mounts.get(key);
173
+ if (!exists) {
174
+ this._mounts.set(key, {
175
+ ctx,
176
+ trigger
177
+ });
178
+ if (ctx.disposed) {
179
+ return;
180
+ }
181
+ let count = 0;
182
+ const objectIds = /* @__PURE__ */ new Set();
183
+ const task = new import_async2.DeferredTask(ctx, async () => {
184
+ const updatedObjects = Array.from(objectIds);
185
+ objectIds.clear();
186
+ await this.invokeFunction(this._invokeOptions, trigger.function, {
187
+ space: space.key,
188
+ objects: updatedObjects
189
+ });
190
+ });
191
+ const selection = (0, import_echo_schema.createSubscription)(({ added, updated }) => {
192
+ for (const object of added) {
193
+ objectIds.add(object.id);
194
+ }
195
+ for (const object1 of updated) {
196
+ objectIds.add(object1.id);
197
+ }
198
+ import_log2.log.info("updated", {
199
+ space: space.key,
200
+ objects: objectIds.size,
201
+ added: added.length,
202
+ updated: updated.length,
203
+ count
204
+ }, {
205
+ file: "trigger-manager.ts",
206
+ line: 85,
207
+ scope: this,
208
+ callSite: (f, a) => f(...a)
209
+ });
210
+ if (count++) {
211
+ task.schedule();
212
+ }
213
+ });
214
+ ctx.onDispose(() => selection.unsubscribe());
215
+ const query = space.db.query({
216
+ ...trigger.subscription.props,
217
+ "@type": trigger.subscription.type
218
+ });
219
+ const unsubscribe = query.subscribe(({ objects }) => {
220
+ selection.update(objects);
221
+ });
222
+ ctx.onDispose(unsubscribe);
223
+ import_log2.log.info("mounted", {
224
+ space: space.key,
225
+ trigger
226
+ }, {
227
+ file: "trigger-manager.ts",
228
+ line: 109,
229
+ scope: this,
230
+ callSite: (f, a) => f(...a)
231
+ });
232
+ }
233
+ }
234
+ async unmount(name, spaceKey) {
235
+ var _a;
236
+ const key = {
237
+ name,
238
+ spaceKey
239
+ };
240
+ const { ctx } = (_a = this._mounts.get(key)) != null ? _a : {};
241
+ if (ctx) {
242
+ this._mounts.delete(key);
243
+ await ctx.dispose();
244
+ }
245
+ }
246
+ async invokeFunction(options, functionName, data) {
247
+ const { endpoint, runtime } = options;
248
+ (0, import_node_assert.default)(endpoint, "Missing endpoint");
249
+ (0, import_node_assert.default)(runtime, "Missing runtime");
250
+ try {
251
+ (0, import_log2.log)("invoke", {
252
+ function: functionName
253
+ }, {
254
+ file: "trigger-manager.ts",
255
+ line: 128,
256
+ scope: this,
257
+ callSite: (f, a) => f(...a)
258
+ });
259
+ const url = `${endpoint}/${runtime}/${functionName}`;
260
+ const res = await fetch(url, {
261
+ method: "POST",
262
+ body: JSON.stringify(data),
263
+ headers: {
264
+ "Content-Type": "application/json"
265
+ }
266
+ });
267
+ (0, import_log2.log)("result", {
268
+ function: functionName,
269
+ result: await res.json()
270
+ }, {
271
+ file: "trigger-manager.ts",
272
+ line: 138,
273
+ scope: this,
274
+ callSite: (f, a) => f(...a)
275
+ });
276
+ } catch (err) {
277
+ (0, import_log2.log)("error", {
278
+ function: functionName,
279
+ error: err.message
280
+ }, {
281
+ file: "trigger-manager.ts",
282
+ line: 140,
283
+ scope: this,
284
+ callSite: (f, a) => f(...a)
285
+ });
286
+ }
287
+ }
120
288
  };
121
289
  // Annotate the CommonJS export names for ESM import in node:
122
290
  0 && (module.exports = {
123
- runFunctions
291
+ DevServer,
292
+ TriggerManager
124
293
  });
125
294
  //# sourceMappingURL=index.cjs.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../../src/index.ts", "../../../src/runtime/index.ts"],
4
- "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nexport * from './interface';\nexport * from './runtime';\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport express from 'express';\nimport { readdir } from 'node:fs/promises';\nimport { extname, join } from 'node:path';\nimport { getPortPromise } from 'portfinder';\n\nimport { Client } from '@dxos/client';\nimport { log } from '@dxos/log';\n\nimport { FunctionContext, FunctionHandler, Reply } from '../interface';\n\nconst FUNCTION_EXTENSIONS = ['.js', '.ts'];\n\nexport type FunctionsRuntimeParams = {\n client: Client;\n functionsDirectory: string;\n};\n\nexport const runFunctions = async (options: FunctionsRuntimeParams) => {\n const files = await readdir(options.functionsDirectory);\n\n const functionHandlers: Record<string, FunctionHandler> = {};\n\n for (const file of files) {\n if (!FUNCTION_EXTENSIONS.some((ext) => extname(file) === ext)) {\n continue;\n }\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const module = require(join(options.functionsDirectory, file));\n const handler = module.default;\n if (typeof handler !== 'function') {\n throw new Error(`Function ${file} does not export a default function`);\n }\n\n const functionName = file.slice(0, -extname(file).length);\n\n functionHandlers[functionName] = handler;\n } catch (e) {\n console.error(e);\n }\n }\n\n const port = await getPortPromise({ startPort: 7000 });\n\n const app = express();\n app.use(express.json());\n\n app.post('/:functionName', async (req, res) => {\n const functionName = req.params.functionName;\n\n const replyBuilder: Reply = {\n status: (code: number) => {\n res.statusCode = code;\n return replyBuilder;\n },\n succeed: (result: any) => {\n res.end(JSON.stringify(result));\n return replyBuilder;\n },\n };\n const context: FunctionContext = {\n client: options.client,\n status: replyBuilder.status.bind(replyBuilder),\n };\n\n void (async () => {\n try {\n await functionHandlers[functionName](req.body, context);\n } catch (err: any) {\n res.statusCode = 500;\n res.end(err.message);\n }\n })();\n });\n app.listen(port);\n\n const functionNames = Object.keys(functionHandlers);\n const { registrationId } = await options.client.services.services.FunctionRegistryService!.register({\n endpoint: `http://localhost:${port}`,\n functions: functionNames.map((name) => ({ name })),\n });\n\n process.on('SIGINT', async () => {\n await options.client.services.services.FunctionRegistryService!.unregister({ registrationId });\n process.exit();\n });\n\n log.info('functions runtime started', { port, functionN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,QAAQ0C;MAChBT,QAAQD,aAAaC,OAAOU,KAAKX,YAAAA;IACnC;AAEA,UAAM,YAAY;AAChB,UAAI;AACF,cAAM5B,iBAAiBW,YAAAA,EAAcc,IAAIe,MAAMH,OAAAA;MACjD,SAASI,KAAP;AACAf,YAAIK,aAAa;AACjBL,YAAIQ,IAAIO,IAAIC,OAAO;MACrB;IACF,GAAA;EACF,CAAA;AACAtB,MAAIuB,OAAO1B,IAAAA;AAEX,QAAM2B,gBAAgBC,OAAOC,KAAK9C,gBAAAA;AAClC,QAAM,EAAE+C,eAAc,IAAK,MAAMnD,QAAQ0C,OAAOU,SAASA,SAASC,wBAAyBC,SAAS;IAClGC,UAAU,oBAAoBlC;IAC9BmC,WAAWR,cAAcS,IAAI,CAACC,UAAU;MAAEA;IAAK,EAAA;EACjD,CAAA;AAEAC,UAAQC,GAAG,UAAU,YAAY;AAC/B,UAAM5D,QAAQ0C,OAAOU,SAASA,SAASC,wBAAyBQ,WAAW;MAAEV;IAAe,CAAA;AAC5FQ,YAAQG,KAAI;EACd,CAAA;AAEAC,iBAAIC,KAAK,6BAA6B;IAAE3C;IAAM2B;IAAeG;EAAe,GAAA;;;;;;AAC9E;",
6
- "names": ["FUNCTION_EXTENSIONS", "runFunctions", "options", "files", "readdir", "functionsDirectory", "functionHandlers", "file", "some", "ext", "extname", "module", "require", "join", "handler", "default", "Error", "functionName", "slice", "length", "e", "console", "error", "port", "getPortPromise", "startPort", "app", "express", "use", "json", "post", "req", "res", "params", "replyBuilder", "status", "code", "statusCode", "succeed", "result", "end", "JSON", "stringify", "context", "client", "bind", "body", "err", "message", "listen", "functionNames", "Object", "keys", "registrationId", "services", "FunctionRegistryService", "register", "endpoint", "functions", "map", "name", "process", "on", "unregister", "exit", "log", "info"]
3
+ "sources": ["../../../src/index.ts", "../../../src/runtime/dev-server.ts", "../../../src/runtime/trigger-manager.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nexport * from './function';\nexport * from './runtime';\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport express from 'express';\nimport http from 'http';\nimport { join } from 'node:path';\nimport { getPortPromise } from 'portfinder';\n\nimport { Trigger } from '@dxos/async';\nimport { Client } from '@dxos/client';\nimport { log } from '@dxos/log';\n\nimport { FunctionContext, FunctionHandler, FunctionsManifest, Response } from '../function';\n\nconst DEFAULT_PORT = 7000;\n\nexport type DevServerOptions = {\n directory: string;\n manifest: FunctionsManifest;\n};\n\n/**\n * Functions dev server provides a local HTTP server for testing functions.\n */\nexport class DevServer {\n private readonly _functionHandlers: Record<string, FunctionHandler> = {};\n\n private _server?: http.Server;\n private _port?: number;\n private _registrationId?: string;\n\n // prettier-ignore\n constructor(\n private readonly _client: Client,\n private readonly _options: DevServerOptions\n ) {}\n\n get port() {\n return this._port;\n }\n\n get endpoint() {\n return this._port ? `http://localhost:${this._port}` : undefined;\n }\n\n get functions() {\n return Object.keys(this._functionHandlers);\n }\n\n async initialize() {\n for (const [name, _] of Object.entries(this._options.manifest.functions)) {\n try {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const module = require(join(this._options.directory, name));\n const handler = module.default;\n if (typeof handler !== 'function') {\n throw new Error(`Handler must export default function: ${name}`);\n }\n\n this._functionHandlers[name] = handler;\n } catch (err) {\n log.error('parsing function (check functions.yml manifest)', err);\n }\n }\n }\n\n async start() {\n const app = express();\n app.use(express.json());\n\n app.post('/:functionName', async (req, res) => {\n const functionName = req.params.functionName;\n\n const builder: Response = {\n status: (code: number) => {\n res.statusCode = code;\n return builder;\n },\n succeed: (result = {}) => {\n res.end(JSON.stringify(result));\n return builder;\n },\n };\n\n const context: FunctionContext = {\n client: this._client,\n status: builder.status.bind(builder),\n };\n\n void (async () => {\n try {\n await this._functionHandlers[functionName](req.body, context);\n } catch (err: any) {\n res.statusCode = 500;\n res.end(err.message);\n }\n })();\n });\n\n this._port = await getPortPromise({ startPort: DEFAULT_PORT });\n this._server = app.listen(this._port);\n\n const { registrationId } = await this._client.services.services.FunctionRegistryService!.register({\n endpoint: this.endpoint!,\n functions: this.functions.map((name) => ({ name })),\n });\n this._registrationId = registrationId;\n }\n\n async stop() {\n const trigger = new Trigger();\n this._server?.close(async () => {\n if (this._registrationId) {\n await this._client.services.services.FunctionRegistryService!.unregister({\n registrationId: this._registrationId,\n });\n this._registrationId = undefined;\n }\n\n trigger.wake();\n });\n\n await trigger.wait();\n this._server = undefined;\n this._port = undefined;\n }\n}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport assert from 'node:assert';\n\nimport { DeferredTask } from '@dxos/async';\nimport { Client, PublicKey, Space } from '@dxos/client';\nimport { Context } from '@dxos/context';\nimport { createSubscription } from '@dxos/echo-schema';\nimport { log } from '@dxos/log';\nimport { ComplexMap } from '@dxos/util';\n\nimport { FunctionTrigger } from '../function';\n\n// TODO(burdon): Rename.\nexport type InvokeOptions = {\n endpoint: string;\n runtime: string;\n};\n\nexport class TriggerManager {\n private readonly _mounts = new ComplexMap<\n { name: string; spaceKey: PublicKey },\n { ctx: Context; trigger: FunctionTrigger }\n >(({ name, spaceKey }) => `${spaceKey.toHex()}:${name}`);\n\n constructor(\n private readonly _client: Client,\n private readonly _triggers: FunctionTrigger[],\n private readonly _invokeOptions: InvokeOptions,\n ) {}\n\n async start() {\n // TODO(burdon): Make runtime configurable (via CLI)?\n this._client.spaces.subscribe(async (spaces) => {\n for (const space of spaces) {\n await space.waitUntilReady();\n for (const trigger of this._triggers) {\n // TODO(burdon): New context? Shared?\n await this.mount(new Context(), trigger, space);\n }\n }\n });\n }\n\n async stop() {\n for (const { name, spaceKey } of this._mounts.keys()) {\n await this.unmount(name, spaceKey);\n }\n }\n\n private async mount(ctx: Context, trigger: FunctionTrigger, space: Space) {\n const key = { name: trigger.function, spaceKey: space.key };\n const exists = this._mounts.get(key);\n if (!exists) {\n this._mounts.set(key, { ctx, trigger });\n if (ctx.disposed) {\n return;\n }\n\n // TODO(burdon): Factor out subscription/result delta.\n\n let count = 0;\n const objectIds = new Set<string>();\n const task = new DeferredTask(ctx, async () => {\n const updatedObjects = Array.from(objectIds);\n objectIds.clear();\n\n await this.invokeFunction(this._invokeOptions, trigger.function, {\n space: space.key,\n objects: updatedObjects,\n });\n });\n\n // TODO(burdon): Removed?\n const selection = createSubscription(({ added, updated }) => {\n for (const object of added) {\n objectIds.add(object.id);\n }\n for (const object of updated) {\n objectIds.add(object.id);\n }\n\n log.info('updated', {\n space: space.key,\n objects: objectIds.size,\n added: added.length,\n updated: updated.length,\n count,\n });\n if (count++) {\n task.schedule();\n }\n });\n\n ctx.onDispose(() => selection.unsubscribe());\n\n const query = space.db.query({ ...trigger.subscription.props, '@type': trigger.subscription.type });\n const unsubscribe = query.subscribe(({ objects }) => {\n selection.update(objects);\n });\n\n // Trigger first update, but don't schedule task.\n // selection.update(query.objects);\n\n ctx.onDispose(unsubscribe);\n\n log.info('mounted', { space: space.key, trigger });\n }\n }\n\n private async unmount(name: string, spaceKey: PublicKey) {\n const key = { name, spaceKey };\n const { ctx } = this._mounts.get(key) ?? {};\n if (ctx) {\n this._mounts.delete(key);\n await ctx.dispose();\n }\n }\n\n private async invokeFunction(options: InvokeOptions, functionName: string, data: any) {\n const { endpoint, runtime } = options;\n assert(endpoint, 'Missing endpoint');\n assert(runtime, 'Missing runtime');\n\n try {\n log('invoke', { function: functionName });\n const url = `${endpoint}/${runtime}/${functionName}`;\n const res = await fetch(url, {\n method: 'POST',\n body: JSON.stringify(data),\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n\n log('result', { function: functionName, result: await res.json() });\n } catch (err: any) {\n log('error', { function: functionName, error: err.message });\n }\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;ACIA,qBAAoB;AAEpB,uBAAqB;AACrB,wBAA+B;AAE/B,mBAAwB;AAExB,iBAAoB;AAIpB,IAAMA,eAAe;AAUd,IAAMC,YAAN,MAAMA;;EAQXC,YACmBC,SACAC,UACjB;mBAFiBD;oBACA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+ "names": ["DEFAULT_PORT", "DevServer", "constructor", "_client", "_options", "_functionHandlers", "port", "_port", "endpoint", "undefined", "functions", "Object", "keys", "initialize", "name", "_", "entries", "manifest", "module", "require", "join", "directory", "handler", "default", "Error", "err", "log", "error", "start", "app", "express", "use", "json", "post", "req", "res", "functionName", "params", "builder", "status", "code", "statusCode", "succeed", "result", "end", "JSON", "stringify", "context", "client", "bind", "body", "message", "getPortPromise", "startPort", "_server", "listen", "registrationId", "services", "FunctionRegistryService", "register", "map", "_registrationId", "stop", "trigger", "Trigger", "close", "unregister", "wake", "wait", "import_async", "import_log", "TriggerManager", "constructor", "_client", "_triggers", "_invokeOptions", "_mounts", "ComplexMap", "name", "spaceKey", "toHex", "start", "spaces", "subscribe", "space", "waitUntilReady", "trigger", "mount", "Context", "stop", "keys", "unmount", "ctx", "key", "function", "exists", "get", "set", "disposed", "count", "objectIds", "Set", "task", "DeferredTask", "updatedObjects", "Array", "from", "clear", "invokeFunction", "objects", "selection", "createSubscription", "added", "updated", "object", "add", "id", "log", "info", "size", "length", "schedule", "onDispose", "unsubscribe", "query", "db", "subscription", "props", "type", "update", "delete", "dispose", "options", "functionName", "data", "endpoint", "runtime", "assert", "url", "res", "fetch", "method", "body", "JSON", "stringify", "headers", "result", "json", "err", "error", "message"]
7
7
  }
@@ -1 +1 @@
1
- {"inputs":{"packages/core/functions/src/interface.ts":{"bytes":756,"imports":[]},"packages/core/functions/src/runtime/index.ts":{"bytes":9991,"imports":[{"path":"express","kind":"import-statement","external":true},{"path":"node:fs/promises","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"portfinder","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}]},"packages/core/functions/src/index.ts":{"bytes":464,"imports":[{"path":"packages/core/functions/src/interface.ts","kind":"import-statement","original":"./interface"},{"path":"packages/core/functions/src/runtime/index.ts","kind":"import-statement","original":"./runtime"}]}},"outputs":{"packages/core/functions/dist/lib/node/index.cjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":5363},"packages/core/functions/dist/lib/node/index.cjs":{"imports":[{"path":"express","kind":"require-call","external":true},{"path":"node:fs/promises","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"portfinder","kind":"require-call","external":true},{"path":"@dxos/log","kind":"require-call","external":true}],"exports":[],"entryPoint":"packages/core/functions/src/index.ts","inputs":{"packages/core/functions/src/index.ts":{"bytesInOutput":129},"packages/core/functions/src/runtime/index.ts":{"bytesInOutput":2530}},"bytes":4286}}}
1
+ {"inputs":{"packages/core/functions/src/function.ts":{"bytes":1332,"imports":[]},"packages/core/functions/src/runtime/dev-server.ts":{"bytes":12360,"imports":[{"path":"express","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"portfinder","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}]},"packages/core/functions/src/runtime/trigger-manager.ts":{"bytes":16101,"imports":[{"path":"node:assert","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}]},"packages/core/functions/src/runtime/index.ts":{"bytes":489,"imports":[{"path":"packages/core/functions/src/runtime/dev-server.ts","kind":"import-statement","original":"./dev-server"},{"path":"packages/core/functions/src/runtime/trigger-manager.ts","kind":"import-statement","original":"./trigger-manager"}]},"packages/core/functions/src/index.ts":{"bytes":463,"imports":[{"path":"packages/core/functions/src/function.ts","kind":"import-statement","original":"./function"},{"path":"packages/core/functions/src/runtime/index.ts","kind":"import-statement","original":"./runtime"}]}},"outputs":{"packages/core/functions/dist/lib/node/index.cjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":13962},"packages/core/functions/dist/lib/node/index.cjs":{"imports":[{"path":"express","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"portfinder","kind":"require-call","external":true},{"path":"@dxos/async","kind":"require-call","external":true},{"path":"@dxos/log","kind":"require-call","external":true},{"path":"node:assert","kind":"require-call","external":true},{"path":"@dxos/async","kind":"require-call","external":true},{"path":"@dxos/context","kind":"require-call","external":true},{"path":"@dxos/echo-schema","kind":"require-call","external":true},{"path":"@dxos/log","kind":"require-call","external":true},{"path":"@dxos/util","kind":"require-call","external":true}],"exports":[],"entryPoint":"packages/core/functions/src/index.ts","inputs":{"packages/core/functions/src/index.ts":{"bytesInOutput":163},"packages/core/functions/src/runtime/dev-server.ts":{"bytesInOutput":2991},"packages/core/functions/src/runtime/index.ts":{"bytesInOutput":0},"packages/core/functions/src/runtime/trigger-manager.ts":{"bytesInOutput":4325}},"bytes":9185}}}
@@ -0,0 +1,30 @@
1
+ import { Client } from '@dxos/client';
2
+ export interface Response {
3
+ status(code: number): Response;
4
+ succeed(data?: object): Response;
5
+ }
6
+ export interface FunctionContext {
7
+ client: Client;
8
+ status(code: number): Response;
9
+ }
10
+ export interface FunctionHandler {
11
+ (event: any, context: FunctionContext): Promise<Response>;
12
+ }
13
+ export type FunctionsManifest = {
14
+ functions: Record<string, FunctionConfig>;
15
+ triggers: FunctionTrigger[];
16
+ };
17
+ export type FunctionConfig = {
18
+ description?: string;
19
+ };
20
+ export type FunctionTrigger = {
21
+ function: string;
22
+ subscription: TriggerSubscription;
23
+ };
24
+ export type TriggerSubscription = {
25
+ type: string;
26
+ spaceKey: string;
27
+ props?: Record<string, any>;
28
+ nested?: string[];
29
+ };
30
+ //# sourceMappingURL=function.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"function.d.ts","sourceRoot":"","sources":["../../../src/function.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAEtC,MAAM,WAAW,QAAQ;IACvB,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,QAAQ,CAAC;IAC/B,OAAO,CAAC,IAAI,CAAC,EAAE,MAAM,GAAG,QAAQ,CAAC;CAClC;AAED,MAAM,WAAW,eAAe;IAC9B,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,QAAQ,CAAC;CAChC;AAED,MAAM,WAAW,eAAe;IAC9B,CAAC,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;CAC3D;AAED,MAAM,MAAM,iBAAiB,GAAG;IAC9B,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;IAC1C,QAAQ,EAAE,eAAe,EAAE,CAAC;CAC7B,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG;IAC3B,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG;IAC5B,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,mBAAmB,CAAC;CACnC,CAAC;AAEF,MAAM,MAAM,mBAAmB,GAAG;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC5B,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;CACnB,CAAC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=function.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"function.test.d.ts","sourceRoot":"","sources":["../../../src/function.test.ts"],"names":[],"mappings":""}
@@ -1,3 +1,3 @@
1
- export * from './interface';
1
+ export * from './function';
2
2
  export * from './runtime';
3
3
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAIA,cAAc,aAAa,CAAC;AAC5B,cAAc,WAAW,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAIA,cAAc,YAAY,CAAC;AAC3B,cAAc,WAAW,CAAC"}
@@ -0,0 +1,25 @@
1
+ import { Client } from '@dxos/client';
2
+ import { FunctionsManifest } from '../function';
3
+ export type DevServerOptions = {
4
+ directory: string;
5
+ manifest: FunctionsManifest;
6
+ };
7
+ /**
8
+ * Functions dev server provides a local HTTP server for testing functions.
9
+ */
10
+ export declare class DevServer {
11
+ private readonly _client;
12
+ private readonly _options;
13
+ private readonly _functionHandlers;
14
+ private _server?;
15
+ private _port?;
16
+ private _registrationId?;
17
+ constructor(_client: Client, _options: DevServerOptions);
18
+ get port(): number | undefined;
19
+ get endpoint(): string | undefined;
20
+ get functions(): string[];
21
+ initialize(): Promise<void>;
22
+ start(): Promise<void>;
23
+ stop(): Promise<void>;
24
+ }
25
+ //# sourceMappingURL=dev-server.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dev-server.d.ts","sourceRoot":"","sources":["../../../../src/runtime/dev-server.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAGtC,OAAO,EAAoC,iBAAiB,EAAY,MAAM,aAAa,CAAC;AAI5F,MAAM,MAAM,gBAAgB,GAAG;IAC7B,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,iBAAiB,CAAC;CAC7B,CAAC;AAEF;;GAEG;AACH,qBAAa,SAAS;IASlB,OAAO,CAAC,QAAQ,CAAC,OAAO;IACxB,OAAO,CAAC,QAAQ,CAAC,QAAQ;IAT3B,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAuC;IAEzE,OAAO,CAAC,OAAO,CAAC,CAAc;IAC9B,OAAO,CAAC,KAAK,CAAC,CAAS;IACvB,OAAO,CAAC,eAAe,CAAC,CAAS;gBAId,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,gBAAgB;IAG7C,IAAI,IAAI,uBAEP;IAED,IAAI,QAAQ,uBAEX;IAED,IAAI,SAAS,aAEZ;IAEK,UAAU;IAiBV,KAAK;IA2CL,IAAI;CAiBX"}
@@ -1,7 +1,3 @@
1
- import { Client } from '@dxos/client';
2
- export type FunctionsRuntimeParams = {
3
- client: Client;
4
- functionsDirectory: string;
5
- };
6
- export declare const runFunctions: (options: FunctionsRuntimeParams) => Promise<void>;
1
+ export * from './dev-server';
2
+ export * from './trigger-manager';
7
3
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/runtime/index.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAOtC,MAAM,MAAM,sBAAsB,GAAG;IACnC,MAAM,EAAE,MAAM,CAAC;IACf,kBAAkB,EAAE,MAAM,CAAC;CAC5B,CAAC;AAEF,eAAO,MAAM,YAAY,YAAmB,sBAAsB,kBAwEjE,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/runtime/index.ts"],"names":[],"mappings":"AAIA,cAAc,cAAc,CAAC;AAC7B,cAAc,mBAAmB,CAAC"}
@@ -0,0 +1,19 @@
1
+ import { Client } from '@dxos/client';
2
+ import { FunctionTrigger } from '../function';
3
+ export type InvokeOptions = {
4
+ endpoint: string;
5
+ runtime: string;
6
+ };
7
+ export declare class TriggerManager {
8
+ private readonly _client;
9
+ private readonly _triggers;
10
+ private readonly _invokeOptions;
11
+ private readonly _mounts;
12
+ constructor(_client: Client, _triggers: FunctionTrigger[], _invokeOptions: InvokeOptions);
13
+ start(): Promise<void>;
14
+ stop(): Promise<void>;
15
+ private mount;
16
+ private unmount;
17
+ private invokeFunction;
18
+ }
19
+ //# sourceMappingURL=trigger-manager.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trigger-manager.d.ts","sourceRoot":"","sources":["../../../../src/runtime/trigger-manager.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,MAAM,EAAoB,MAAM,cAAc,CAAC;AAMxD,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAG9C,MAAM,MAAM,aAAa,GAAG;IAC1B,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF,qBAAa,cAAc;IAOvB,OAAO,CAAC,QAAQ,CAAC,OAAO;IACxB,OAAO,CAAC,QAAQ,CAAC,SAAS;IAC1B,OAAO,CAAC,QAAQ,CAAC,cAAc;IARjC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAGiC;gBAGtC,OAAO,EAAE,MAAM,EACf,SAAS,EAAE,eAAe,EAAE,EAC5B,cAAc,EAAE,aAAa;IAG1C,KAAK;IAaL,IAAI;YAMI,KAAK;YA4DL,OAAO;YASP,cAAc;CAqB7B"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@dxos/functions",
3
- "version": "0.1.52",
4
- "description": "Functions SDK.",
3
+ "version": "0.1.53-main.09c4c35",
4
+ "description": "Functions SDK and runtime.",
5
5
  "homepage": "https://dxos.org",
6
6
  "bugs": "https://github.com/dxos/dxos/issues",
7
7
  "license": "MIT",
@@ -21,9 +21,13 @@
21
21
  "dependencies": {
22
22
  "express": "4.17.1",
23
23
  "portfinder": "^1.0.32",
24
- "@dxos/client": "0.1.52",
25
- "@dxos/log": "0.1.52",
26
- "@dxos/node-std": "0.1.52"
24
+ "@dxos/async": "0.1.53-main.09c4c35",
25
+ "@dxos/client": "0.1.53-main.09c4c35",
26
+ "@dxos/context": "0.1.53-main.09c4c35",
27
+ "@dxos/echo-schema": "0.1.53-main.09c4c35",
28
+ "@dxos/log": "0.1.53-main.09c4c35",
29
+ "@dxos/node-std": "0.1.53-main.09c4c35",
30
+ "@dxos/util": "0.1.53-main.09c4c35"
27
31
  },
28
32
  "devDependencies": {
29
33
  "@types/express": "^4.17.17"
@@ -0,0 +1,40 @@
1
+ //
2
+ // Copyright 2023 DXOS.org
3
+ //
4
+
5
+ import { Client } from '@dxos/client';
6
+
7
+ export interface Response {
8
+ status(code: number): Response;
9
+ succeed(data?: object): Response;
10
+ }
11
+
12
+ export interface FunctionContext {
13
+ client: Client;
14
+ status(code: number): Response;
15
+ }
16
+
17
+ export interface FunctionHandler {
18
+ (event: any, context: FunctionContext): Promise<Response>;
19
+ }
20
+
21
+ export type FunctionsManifest = {
22
+ functions: Record<string, FunctionConfig>;
23
+ triggers: FunctionTrigger[];
24
+ };
25
+
26
+ export type FunctionConfig = {
27
+ description?: string;
28
+ };
29
+
30
+ export type FunctionTrigger = {
31
+ function: string;
32
+ subscription: TriggerSubscription;
33
+ };
34
+
35
+ export type TriggerSubscription = {
36
+ type: string;
37
+ spaceKey: string;
38
+ props?: Record<string, any>;
39
+ nested?: string[];
40
+ };
package/src/index.ts CHANGED
@@ -2,5 +2,5 @@
2
2
  // Copyright 2023 DXOS.org
3
3
  //
4
4
 
5
- export * from './interface';
5
+ export * from './function';
6
6
  export * from './runtime';