@dxos/functions 0.5.3-main.59db342 → 0.5.3-main.61bbff4

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 (86) hide show
  1. package/dist/lib/browser/index.mjs +829 -265
  2. package/dist/lib/browser/index.mjs.map +4 -4
  3. package/dist/lib/browser/meta.json +1 -1
  4. package/dist/lib/node/index.cjs +817 -266
  5. package/dist/lib/node/index.cjs.map +4 -4
  6. package/dist/lib/node/meta.json +1 -1
  7. package/dist/types/src/handler.d.ts +33 -12
  8. package/dist/types/src/handler.d.ts.map +1 -1
  9. package/dist/types/src/index.d.ts +3 -1
  10. package/dist/types/src/index.d.ts.map +1 -1
  11. package/dist/types/src/registry/function-registry.d.ts +24 -0
  12. package/dist/types/src/registry/function-registry.d.ts.map +1 -0
  13. package/dist/types/src/registry/function-registry.test.d.ts +2 -0
  14. package/dist/types/src/registry/function-registry.test.d.ts.map +1 -0
  15. package/dist/types/src/registry/index.d.ts +2 -0
  16. package/dist/types/src/registry/index.d.ts.map +1 -0
  17. package/dist/types/src/runtime/dev-server.d.ts +15 -7
  18. package/dist/types/src/runtime/dev-server.d.ts.map +1 -1
  19. package/dist/types/src/runtime/dev-server.test.d.ts +2 -0
  20. package/dist/types/src/runtime/dev-server.test.d.ts.map +1 -0
  21. package/dist/types/src/runtime/scheduler.d.ts +14 -15
  22. package/dist/types/src/runtime/scheduler.d.ts.map +1 -1
  23. package/dist/types/src/testing/functions-integration.test.d.ts +2 -0
  24. package/dist/types/src/testing/functions-integration.test.d.ts.map +1 -0
  25. package/dist/types/src/testing/index.d.ts +4 -0
  26. package/dist/types/src/testing/index.d.ts.map +1 -0
  27. package/dist/types/src/testing/setup.d.ts +5 -0
  28. package/dist/types/src/testing/setup.d.ts.map +1 -0
  29. package/dist/types/src/testing/test/handler.d.ts +4 -0
  30. package/dist/types/src/testing/test/handler.d.ts.map +1 -0
  31. package/dist/types/src/testing/test/index.d.ts +3 -0
  32. package/dist/types/src/testing/test/index.d.ts.map +1 -0
  33. package/dist/types/src/testing/types.d.ts +9 -0
  34. package/dist/types/src/testing/types.d.ts.map +1 -0
  35. package/dist/types/src/testing/util.d.ts +3 -0
  36. package/dist/types/src/testing/util.d.ts.map +1 -0
  37. package/dist/types/src/trigger/index.d.ts +2 -0
  38. package/dist/types/src/trigger/index.d.ts.map +1 -0
  39. package/dist/types/src/trigger/trigger-registry.d.ts +40 -0
  40. package/dist/types/src/trigger/trigger-registry.d.ts.map +1 -0
  41. package/dist/types/src/trigger/trigger-registry.test.d.ts +2 -0
  42. package/dist/types/src/trigger/trigger-registry.test.d.ts.map +1 -0
  43. package/dist/types/src/trigger/type/index.d.ts +5 -0
  44. package/dist/types/src/trigger/type/index.d.ts.map +1 -0
  45. package/dist/types/src/trigger/type/subscription-trigger.d.ts +4 -0
  46. package/dist/types/src/trigger/type/subscription-trigger.d.ts.map +1 -0
  47. package/dist/types/src/trigger/type/timer-trigger.d.ts +4 -0
  48. package/dist/types/src/trigger/type/timer-trigger.d.ts.map +1 -0
  49. package/dist/types/src/trigger/type/webhook-trigger.d.ts +4 -0
  50. package/dist/types/src/trigger/type/webhook-trigger.d.ts.map +1 -0
  51. package/dist/types/src/trigger/type/websocket-trigger.d.ts +13 -0
  52. package/dist/types/src/trigger/type/websocket-trigger.d.ts.map +1 -0
  53. package/dist/types/src/types.d.ts +188 -0
  54. package/dist/types/src/types.d.ts.map +1 -0
  55. package/dist/types/tools/schema.d.ts +2 -0
  56. package/dist/types/tools/schema.d.ts.map +1 -0
  57. package/package.json +23 -11
  58. package/schema/functions.json +197 -0
  59. package/src/handler.ts +56 -26
  60. package/src/index.ts +3 -1
  61. package/src/registry/function-registry.test.ts +105 -0
  62. package/src/registry/function-registry.ts +84 -0
  63. package/src/registry/index.ts +5 -0
  64. package/src/runtime/dev-server.test.ts +60 -0
  65. package/src/runtime/dev-server.ts +104 -52
  66. package/src/runtime/scheduler.test.ts +154 -21
  67. package/src/runtime/scheduler.ts +76 -152
  68. package/src/testing/functions-integration.test.ts +99 -0
  69. package/src/testing/index.ts +7 -0
  70. package/src/testing/setup.ts +45 -0
  71. package/src/testing/test/handler.ts +15 -0
  72. package/src/testing/test/index.ts +7 -0
  73. package/src/testing/types.ts +9 -0
  74. package/src/testing/util.ts +16 -0
  75. package/src/trigger/index.ts +5 -0
  76. package/src/trigger/trigger-registry.test.ts +229 -0
  77. package/src/trigger/trigger-registry.ts +176 -0
  78. package/src/trigger/type/index.ts +8 -0
  79. package/src/trigger/type/subscription-trigger.ts +73 -0
  80. package/src/trigger/type/timer-trigger.ts +44 -0
  81. package/src/trigger/type/webhook-trigger.ts +47 -0
  82. package/src/trigger/type/websocket-trigger.ts +91 -0
  83. package/src/types.ts +101 -0
  84. package/dist/types/src/manifest.d.ts +0 -26
  85. package/dist/types/src/manifest.d.ts.map +0 -1
  86. package/src/manifest.ts +0 -42
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../../src/handler.ts", "../../../src/runtime/dev-server.ts", "../../../src/runtime/scheduler.ts"],
4
- "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport { type Client, PublicKey } from '@dxos/client';\nimport { type Space } from '@dxos/client/echo';\nimport { type EchoReactiveObject } from '@dxos/echo-schema';\nimport { log } from '@dxos/log';\nimport { nonNullable } from '@dxos/util';\n\n// TODO(burdon): No response?\nexport interface Response {\n status(code: number): Response;\n}\n\n// TODO(burdon): Limit access to individual space?\nexport interface FunctionContext {\n client: Client;\n dataDir?: string;\n}\n\n// TODO(burdon): Model after http request. Ref Lambda/OpenFaaS.\n// https://docs.aws.amazon.com/lambda/latest/dg/typescript-handler.html\nexport type FunctionHandler<T extends {}> = (params: {\n event: T;\n context: FunctionContext;\n response: Response;\n}) => Promise<Response | void>;\n\nexport type FunctionSubscriptionEvent = {\n space?: string; // TODO(burdon): Convert to PublicKey.\n objects?: string[];\n};\n\nexport type FunctionSubscriptionEvent2 = {\n space?: Space;\n objects?: EchoReactiveObject<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 */\nexport const subscriptionHandler = (\n handler: FunctionHandler<FunctionSubscriptionEvent2>,\n): FunctionHandler<FunctionSubscriptionEvent> => {\n return ({ event, context, ...rest }) => {\n const { client } = context;\n const space = event.space ? client.spaces.get(PublicKey.from(event.space)) : undefined;\n const objects =\n space &&\n event.objects?.map<EchoReactiveObject<any> | undefined>((id) => space!.db.getObjectById(id)).filter(nonNullable);\n\n if (!!event.space && !space) {\n log.warn('invalid space', { event });\n } else {\n log.info('handler', { space: space?.key.truncate(), objects: objects?.length });\n }\n\n return handler({ event: { space, objects }, context, ...rest });\n };\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport express from 'express';\nimport { getPort } from 'get-port-please';\nimport type http from 'http';\nimport { join } from 'node:path';\n\nimport { Trigger } from '@dxos/async';\nimport { type Client } from '@dxos/client';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\n\nimport { type FunctionContext, type FunctionHandler, type Response } from '../handler';\nimport { type FunctionDef, type FunctionManifest } from '../manifest';\n\nexport type DevServerOptions = {\n port?: number;\n directory: string;\n manifest: FunctionManifest;\n reload?: boolean;\n dataDir?: string;\n};\n\n/**\n * Functions dev server provides a local HTTP server for testing functions.\n */\nexport class DevServer {\n // Function handlers indexed by name (URL path).\n private readonly _handlers: Record<string, { def: FunctionDef; handler: FunctionHandler<any> }> = {};\n\n private _server?: http.Server;\n private _port?: number;\n private _registrationId?: string;\n private _proxy?: string;\n private _seq = 0;\n\n // prettier-ignore\n constructor(\n private readonly _client: Client,\n private readonly _options: DevServerOptions,\n ) {}\n\n get endpoint() {\n invariant(this._port);\n return `http://localhost:${this._port}`;\n }\n\n get proxy() {\n return this._proxy;\n }\n\n get functions() {\n return Object.values(this._handlers);\n }\n\n async initialize() {\n for (const def of this._options.manifest.functions) {\n try {\n await this._load(def);\n } catch (err) {\n log.error('parsing function (check manifest)', err);\n }\n }\n }\n\n async start() {\n const app = express();\n app.use(express.json());\n\n app.post('/:name', async (req, res) => {\n const { name } = req.params;\n try {\n log.info('calling', { name });\n if (this._options.reload) {\n const { def } = this._handlers[name];\n await this._load(def, true);\n }\n\n res.statusCode = await this._invoke(name, req.body);\n res.end();\n } catch (err: any) {\n log.catch(err);\n res.statusCode = 500;\n res.end();\n }\n });\n\n this._port = await getPort({ host: 'localhost', port: 7200, portRange: [7200, 7299] });\n this._server = app.listen(this._port);\n\n try {\n // Register functions.\n const { registrationId, endpoint } = await this._client.services.services.FunctionRegistryService!.register({\n endpoint: this.endpoint,\n functions: this.functions.map(({ def: { name } }) => ({ name })),\n });\n\n log.info('registered', { registrationId, endpoint });\n this._registrationId = registrationId;\n this._proxy = endpoint;\n } catch (err: any) {\n await this.stop();\n throw new Error('FunctionRegistryService not available (check plugin is configured).');\n }\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\n log.info('unregistered', { registrationId: this._registrationId });\n this._registrationId = undefined;\n this._proxy = undefined;\n }\n\n trigger.wake();\n });\n\n await trigger.wait();\n this._port = undefined;\n this._server = undefined;\n }\n\n /**\n * Load function.\n */\n private async _load(def: FunctionDef, flush = false) {\n const { id, name, handler } = def;\n const path = join(this._options.directory, handler);\n log.info('loading', { id });\n\n // Remove from cache.\n if (flush) {\n Object.keys(require.cache)\n .filter((key) => key.startsWith(path))\n .forEach((key) => delete require.cache[key]);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const module = require(path);\n if (typeof module.default !== 'function') {\n throw new Error(`Handler must export default function: ${id}`);\n }\n\n this._handlers[name] = { def, handler: module.default };\n }\n\n /**\n * Invoke function handler.\n */\n private async _invoke(name: string, event: any) {\n const seq = ++this._seq;\n const now = Date.now();\n\n log.info('req', { seq, name });\n const { handler } = this._handlers[name];\n\n const context: FunctionContext = {\n client: this._client,\n dataDir: this._options.dataDir,\n };\n\n let statusCode = 200;\n const response: Response = {\n status: (code: number) => {\n statusCode = code;\n return response;\n },\n };\n\n await handler({ context, event, response });\n log.info('res', { seq, name, statusCode, duration: Date.now() - now });\n\n return statusCode;\n }\n}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { CronJob } from 'cron';\n\nimport { TextV0Type } from '@braneframe/types';\nimport { debounce, DeferredTask } from '@dxos/async';\nimport { type Client, type PublicKey } from '@dxos/client';\nimport { type Space, Filter, createSubscription, type Query, getAutomergeObjectCore } from '@dxos/client/echo';\nimport { Context } from '@dxos/context';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport { ComplexMap } from '@dxos/util';\n\nimport { type FunctionSubscriptionEvent } from '../handler';\nimport { type FunctionDef, type FunctionManifest, type FunctionTrigger, type TriggerSubscription } from '../manifest';\n\ntype Callback = (data: FunctionSubscriptionEvent) => Promise<number>;\n\ntype SchedulerOptions = {\n endpoint?: string;\n callback?: Callback;\n};\n\n/**\n * Functions scheduler.\n */\n// TODO(burdon): Create tests.\nexport class Scheduler {\n // Map of mounted functions.\n private readonly _mounts = new ComplexMap<\n { id: string; spaceKey: PublicKey },\n { ctx: Context; trigger: FunctionTrigger }\n >(({ id, spaceKey }) => `${spaceKey.toHex()}:${id}`);\n\n constructor(\n private readonly _client: Client,\n private readonly _manifest: FunctionManifest,\n private readonly _options: SchedulerOptions = {},\n ) {}\n\n async start() {\n this._client.spaces.subscribe(async (spaces) => {\n for (const space of spaces) {\n await space.waitUntilReady();\n for (const trigger of this._manifest.triggers ?? []) {\n await this.mount(new Context(), space, trigger);\n }\n }\n });\n }\n\n async stop() {\n for (const { id, spaceKey } of this._mounts.keys()) {\n await this.unmount(id, spaceKey);\n }\n }\n\n private async mount(ctx: Context, space: Space, trigger: FunctionTrigger) {\n const key = { id: trigger.function, spaceKey: space.key };\n const def = this._manifest.functions.find((config) => config.id === trigger.function);\n invariant(def, `Function not found: ${trigger.function}`);\n\n // Currently supports only one trigger declaration per function.\n const exists = this._mounts.get(key);\n if (!exists) {\n this._mounts.set(key, { ctx, trigger });\n log('mount', { space: space.key, trigger });\n if (ctx.disposed) {\n return;\n }\n\n // Timer.\n if (trigger.schedule) {\n this._createTimer(ctx, space, def, trigger);\n }\n\n // Subscription.\n for (const triggerSubscription of trigger.subscriptions ?? []) {\n this._createSubscription(ctx, space, def, triggerSubscription);\n }\n }\n }\n\n private async unmount(id: string, spaceKey: PublicKey) {\n const key = { id, 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 _createTimer(ctx: Context, space: Space, def: FunctionDef, trigger: FunctionTrigger) {\n const task = new DeferredTask(ctx, async () => {\n await this._execFunction(def, {\n space: space.key,\n });\n });\n\n invariant(trigger.schedule);\n let last = 0;\n let run = 0;\n // https://www.npmjs.com/package/cron#constructor\n const job = CronJob.from({\n cronTime: trigger.schedule,\n runOnInit: false,\n onTick: () => {\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 });\n\n job.start();\n ctx.onDispose(() => job.stop());\n }\n\n private _createSubscription(ctx: Context, space: Space, def: FunctionDef, triggerSubscription: TriggerSubscription) {\n log.info('subscription', { space: space.key, triggerSubscription });\n const objectIds = new Set<string>();\n const task = new DeferredTask(ctx, async () => {\n await this._execFunction(def, {\n space: space.key,\n objects: Array.from(objectIds),\n });\n });\n\n // TODO(burdon): Don't fire initially.\n // TODO(burdon): Standardize subscription handles.\n const subscriptions: (() => void)[] = [];\n const subscription = createSubscription(({ added, updated }) => {\n log.info('updated', { added: added.length, updated: updated.length });\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 task.schedule();\n });\n subscriptions.push(() => subscription.unsubscribe());\n\n // TODO(burdon): Create queue. Only allow one invocation per trigger at a time?\n // TODO(burdon): Disable trigger if keeps failing.\n const { type, props, deep, delay } = triggerSubscription;\n const update = ({ objects }: Query) => {\n subscription.update(objects);\n\n // TODO(burdon): Hack to monitor changes to Document's text object.\n if (deep) {\n log.info('update', { type, deep, objects: objects.length });\n for (const object of objects) {\n const content = object.content;\n if (content instanceof TextV0Type) {\n subscriptions.push(\n getAutomergeObjectCore(content).updates.on(debounce(() => subscription.update([object]), 1_000)),\n );\n }\n }\n }\n };\n\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 const query = space.db.query(Filter.typename(type, props));\n subscriptions.push(query.subscribe(delay ? debounce(update, delay * 1_000) : update));\n\n ctx.onDispose(() => {\n subscriptions.forEach((unsubscribe) => unsubscribe());\n });\n }\n\n private async _execFunction(def: FunctionDef, data: any) {\n try {\n log('request', { function: def.id });\n const { endpoint, callback } = this._options;\n let status = 0;\n if (endpoint) {\n // TODO(burdon): Move out of scheduler (generalize as callback).\n const response = await fetch(`${this._options.endpoint}/${def.name}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(data),\n });\n\n status = response.status;\n } else if (callback) {\n status = await callback(data);\n }\n\n // const result = await response.json();\n log('result', { function: def.id, result: status });\n } catch (err: any) {\n log.error('error', { function: def.id, error: err.message });\n }\n }\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,oBAAuC;AAGvC,iBAAoB;AACpB,kBAA4B;ACJ5B,qBAAoB;AACpB,6BAAwB;AAExB,uBAAqB;AAErB,mBAAwB;AAExB,uBAA0B;AAC1B,IAAAA,cAAoB;ACRpB,kBAAwB;AAExB,mBAA2B;AAC3B,IAA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AAMoE,SAASD,IAAAA;MAC1B;AAGAhJ,sBAAAA,KAAI,UAAU;QAAE6F,UAAUxE,IAAI1B;QAAI4J,QAAQ1E;MAAO,GAAA;;;;;;IACnD,SAASrD,KAAU;AACjBxB,kBAAAA,IAAIyB,MAAM,SAAS;QAAEoE,UAAUxE,IAAI1B;QAAI8B,OAAOD,IAAIgI;MAAQ,GAAA;;;;;;IAC5D;EACF;AACF;",
6
- "names": ["import_log", "import_async", "import_invariant", "import_util", "subscriptionHandler", "handler", "event", "context", "rest", "client", "space", "spaces", "get", "PublicKey", "from", "undefined", "objects", "map", "id", "db", "getObjectById", "filter", "nonNullable", "log", "warn", "info", "key", "truncate", "length", "DevServer", "constructor", "_client", "_options", "_handlers", "_seq", "endpoint", "invariant", "_port", "proxy", "_proxy", "functions", "Object", "values", "initialize", "def", "manifest", "_load", "err", "error", "start", "app", "express", "use", "json", "post", "req", "res", "name", "params", "reload", "statusCode", "_invoke", "body", "end", "catch", "getPort", "host", "port", "portRange", "_server", "listen", "registrationId", "services", "FunctionRegistryService", "register", "_registrationId", "stop", "Error", "trigger", "Trigger", "close", "unregister", "wake", "wait", "flush", "path", "join", "directory", "keys", "require", "cache", "startsWith", "forEach", "module", "default", "seq", "now", "Date", "dataDir", "response", "status", "code", "duration", "Scheduler", "_manifest", "_mounts", "ComplexMap", "spaceKey", "toHex", "subscribe", "waitUntilReady", "triggers", "mount", "Context", "unmount", "ctx", "function", "find", "config", "exists", "set", "disposed", "schedule", "_createTimer", "triggerSubscription", "subscriptions", "_createSubscription", "delete", "dispose", "task", "DeferredTask", "_execFunction", "last", "run", "job", "CronJob", "cronTime", "runOnInit", "onTick", "delta", "count", "onDispose", "objectIds", "Set", "Array", "subscription", "createSubscription", "added", "updated", "object", "add", "push", "unsubscribe", "type", "props", "deep", "delay", "update", "content", "TextV0Type", "getAutomergeObjectCore", "updates", "on", "debounce", "query", "Filter", "typename", "data", "callback", "fetch", "method", "headers", "JSON", "stringify", "result", "message"]
3
+ "sources": ["../../../src/handler.ts", "../../../src/registry/function-registry.ts", "../../../src/types.ts", "../../../src/runtime/dev-server.ts", "../../../src/runtime/scheduler.ts", "../../../src/trigger/trigger-registry.ts", "../../../src/trigger/type/subscription-trigger.ts", "../../../src/trigger/type/timer-trigger.ts", "../../../src/trigger/type/webhook-trigger.ts", "../../../src/trigger/type/websocket-trigger.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport { type Client, PublicKey } from '@dxos/client';\nimport { type Space } from '@dxos/client/echo';\nimport { type EchoReactiveObject } from '@dxos/echo-schema';\nimport { log } from '@dxos/log';\nimport { nonNullable } 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 = {}> = (params: {\n context: FunctionContext;\n event: FunctionEvent<TData, TMeta>;\n response: FunctionResponse;\n}) => Promise<FunctionResponse | void>;\n\n/**\n * Function context.\n */\nexport interface FunctionContext {\n // TODO(burdon): Limit access to individual space.\n client: Client;\n // TODO(burdon): Replace with storage service abstraction.\n dataDir?: string;\n}\n\n/**\n * Event payload.\n */\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 interface FunctionResponse {\n status(code: number): FunctionResponse;\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?: EchoReactiveObject<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 */\nexport const subscriptionHandler = <TMeta>(\n handler: FunctionHandler<SubscriptionData, TMeta>,\n): FunctionHandler<RawSubscriptionData, TMeta> => {\n return ({ event: { data }, context, ...rest }) => {\n const { client } = context;\n const space = data.spaceKey ? client.spaces.get(PublicKey.from(data.spaceKey)) : undefined;\n const objects = space\n ? data.objects?.map<EchoReactiveObject<any> | undefined>((id) => space!.db.getObjectById(id)).filter(nonNullable)\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, ...rest });\n };\n};\n", "//\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 { ComplexMap } from '@dxos/util';\n\nimport { FunctionDef, type FunctionManifest } from '../types';\n\nexport type FunctionsRegisteredEvent = {\n space: Space;\n newFunctions: FunctionDef[];\n};\n\nexport class FunctionRegistry extends Resource {\n private readonly _functionBySpaceKey = new ComplexMap<PublicKey, FunctionDef[]>(PublicKey.hash);\n\n public readonly onFunctionsRegistered = 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 /**\n * The method 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 // TODO(burdon): This should not be space specific (they are static for the agent).\n public async register(space: Space, manifest: FunctionManifest): Promise<void> {\n if (!manifest.functions?.length) {\n return;\n }\n if (!space.db.graph.runtimeSchemaRegistry.hasSchema(FunctionDef)) {\n space.db.graph.runtimeSchemaRegistry.registerSchema(FunctionDef);\n }\n\n const { objects: existingDefinitions } = await space.db.query(Filter.schema(FunctionDef)).run();\n const newDefinitions = getNewDefinitions(manifest.functions, existingDefinitions);\n const reactiveObjects = newDefinitions.map((template) => create(FunctionDef, { ...template }));\n reactiveObjects.forEach((obj) => space.db.add(obj));\n }\n\n protected override async _open(): Promise<void> {\n const spaceListSubscription = this._client.spaces.subscribe(async (spaces) => {\n for (const space of spaces) {\n if (this._functionBySpaceKey.has(space.key)) {\n continue;\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 const functionsSubscription = space.db.query(Filter.schema(FunctionDef)).subscribe((definitions) => {\n const newFunctions = getNewDefinitions(definitions.objects, registered);\n if (newFunctions.length > 0) {\n registered.push(...newFunctions);\n this.onFunctionsRegistered.emit({ space, newFunctions });\n }\n });\n this._ctx.onDispose(functionsSubscription);\n }\n });\n this._ctx.onDispose(() => spaceListSubscription.unsubscribe());\n }\n\n protected override async _close(_: Context): Promise<void> {\n this._functionBySpaceKey.clear();\n }\n}\n\nconst getNewDefinitions = <T extends { uri: string }>(candidateList: T[], existing: FunctionDef[]): T[] => {\n return candidateList.filter((candidate) => existing.find((def) => def.uri === candidate.uri) == null);\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { AST, S, TypedObject } from '@dxos/echo-schema';\n\n// TODO(burdon): Factor out.\nconst omitEchoId = <T>(schema: S.Schema<T>): S.Schema<Omit<T, 'id'>> => S.make(AST.omit(schema.ast, ['id']));\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.struct({\n type: S.literal('subscription'),\n // TODO(burdon): Define query DSL.\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});\nexport type SubscriptionTrigger = S.Schema.Type<typeof SubscriptionTriggerSchema>;\n\nconst TimerTriggerSchema = S.struct({\n type: S.literal('timer'),\n cron: S.string,\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);\nexport type WebhookTrigger = S.Schema.Type<typeof WebhookTriggerSchema>;\n\nconst WebsocketTriggerSchema = S.struct({\n type: S.literal('websocket'),\n url: S.string,\n init: S.optional(S.record(S.string, S.any)),\n});\nexport type WebsocketTrigger = S.Schema.Type<typeof WebsocketTriggerSchema>;\n\nconst TriggerSpecSchema = S.union(\n TimerTriggerSchema,\n WebhookTriggerSchema,\n WebsocketTriggerSchema,\n SubscriptionTriggerSchema,\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 // TODO(burdon): NPM/GitHub/Docker/CF URL?\n handler: S.string,\n}) {}\n\nexport class FunctionTrigger extends TypedObject({\n typename: 'dxos.org/type/FunctionTrigger',\n version: '0.1.0',\n})({\n function: S.string.pipe(S.description('Function ID/URI.')),\n // Context passed to a function.\n meta: S.optional(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(omitEchoId(FunctionDef)))),\n triggers: S.optional(S.mutable(S.array(omitEchoId(FunctionTrigger)))),\n});\n\nexport type FunctionManifest = S.Schema.Type<typeof FunctionManifestSchema>;\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport express from 'express';\nimport { getPort } from 'get-port-please';\nimport type http from 'http';\nimport { join } from 'node:path';\n\nimport { Event, Trigger } from '@dxos/async';\nimport { type Client } from '@dxos/client';\nimport { Context } from '@dxos/context';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\n\nimport { type FunctionContext, type FunctionEvent, type FunctionHandler, type FunctionResponse } from '../handler';\nimport { type FunctionRegistry } from '../registry';\nimport { type FunctionDef } from '../types';\n\nexport type DevServerOptions = {\n baseDir: string;\n port?: number;\n reload?: boolean;\n dataDir?: string;\n};\n\n/**\n * Functions dev server provides a local HTTP server for testing functions.\n */\nexport class DevServer {\n private _ctx = createContext();\n\n // Function handlers indexed by name (URL path).\n private readonly _handlers: Record<string, { def: FunctionDef; handler: FunctionHandler<any> }> = {};\n\n private _server?: http.Server;\n private _port?: number;\n private _functionServiceRegistration?: string;\n private _proxy?: string;\n private _seq = 0;\n\n public readonly update = new Event<number>();\n\n // prettier-ignore\n constructor(\n private readonly _client: Client,\n private readonly _functionsRegistry: FunctionRegistry,\n private readonly _options: DevServerOptions,\n ) {\n this._functionsRegistry.onFunctionsRegistered.on(async ({ newFunctions }) => {\n newFunctions.forEach((def) => this._load(def));\n await this._safeUpdateRegistration();\n log('new functions loaded', { newFunctions });\n });\n }\n\n get stats() {\n return {\n seq: this._seq,\n };\n }\n\n get endpoint() {\n invariant(this._port);\n return `http://localhost:${this._port}`;\n }\n\n get proxy() {\n return this._proxy;\n }\n\n get functions() {\n return Object.values(this._handlers);\n }\n\n async start() {\n invariant(!this._server);\n log.info('starting...');\n this._ctx = createContext();\n\n // TODO(burdon): Move to hono.\n const app = express();\n app.use(express.json());\n\n app.post('/:path', async (req, res) => {\n const { path } = req.params;\n try {\n log.info('calling', { path });\n if (this._options.reload) {\n const { def } = this._handlers['/' + path];\n await this._load(def, true);\n }\n\n // TODO(burdon): Get function context.\n res.statusCode = await this.invoke('/' + path, req.body);\n res.end();\n } catch (err: any) {\n log.catch(err);\n res.statusCode = 500;\n res.end();\n }\n });\n\n this._port = await getPort({ host: 'localhost', port: 7200, portRange: [7200, 7299] });\n this._server = app.listen(this._port);\n\n try {\n // Register functions.\n const { registrationId, endpoint } = await this._client.services.services.FunctionRegistryService!.register({\n endpoint: this.endpoint,\n });\n\n log.info('registered', { endpoint });\n this._proxy = endpoint;\n this._functionServiceRegistration = registrationId;\n\n // Open after registration, so that it can be updated with the list of function definitions.\n await this._functionsRegistry.open(this._ctx);\n } catch (err: any) {\n await this.stop();\n throw new Error('FunctionRegistryService not available (check plugin is configured).');\n }\n\n log.info('started', { port: this._port });\n }\n\n async stop() {\n invariant(this._server);\n log.info('stopping...');\n\n const trigger = new Trigger();\n this._server.close(async () => {\n log.info('server stopped');\n try {\n if (this._functionServiceRegistration) {\n invariant(this._client.services.services.FunctionRegistryService);\n await this._client.services.services.FunctionRegistryService.unregister({\n registrationId: this._functionServiceRegistration,\n });\n\n log.info('unregistered', { registrationId: this._functionServiceRegistration });\n this._functionServiceRegistration = undefined;\n this._proxy = undefined;\n }\n\n trigger.wake();\n } catch (err) {\n trigger.throw(err as Error);\n }\n });\n\n await trigger.wait();\n this._port = undefined;\n this._server = undefined;\n log.info('stopped');\n }\n\n /**\n * Load function.\n */\n private async _load(def: FunctionDef, force = false) {\n const { uri, route, handler } = def;\n const filePath = join(this._options.baseDir, handler);\n log.info('loading', { uri, force });\n\n // Remove from cache.\n if (force) {\n Object.keys(require.cache)\n .filter((key) => key.startsWith(filePath))\n .forEach((key) => {\n delete require.cache[key];\n });\n }\n\n // TODO(burdon): Import types.\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const module = require(filePath);\n if (typeof module.default !== 'function') {\n throw new Error(`Handler must export default function: ${uri}`);\n }\n\n this._handlers[route] = { def, handler: module.default };\n }\n\n private async _safeUpdateRegistration(): Promise<void> {\n invariant(this._functionServiceRegistration);\n try {\n await this._client.services.services.FunctionRegistryService!.updateRegistration({\n registrationId: this._functionServiceRegistration,\n functions: this.functions.map(({ def: { id, route } }) => ({ id, route })),\n });\n } catch (e) {\n log.catch(e);\n }\n }\n\n /**\n * Invoke function.\n */\n public async invoke(path: string, data: any): Promise<number> {\n const seq = ++this._seq;\n const now = Date.now();\n\n log.info('req', { seq, path });\n const statusCode = await this._invoke(path, { data });\n\n log.info('res', { seq, path, statusCode, duration: Date.now() - now });\n this.update.emit(statusCode);\n return statusCode;\n }\n\n private async _invoke(path: string, event: FunctionEvent) {\n const { handler } = this._handlers[path] ?? {};\n invariant(handler, `invalid path: ${path}`);\n\n const context: FunctionContext = {\n client: this._client,\n dataDir: this._options.dataDir,\n };\n\n let statusCode = 200;\n const response: FunctionResponse = {\n status: (code: number) => {\n statusCode = code;\n return response;\n },\n };\n\n await handler({ context, event, response });\n return statusCode;\n }\n}\n\nconst createContext = () => new Context({ name: 'DevServer' });\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport path from 'node:path';\n\nimport { type Space } from '@dxos/client/echo';\nimport { Context } from '@dxos/context';\nimport { log } from '@dxos/log';\n\nimport { type FunctionEventMeta } from '../handler';\nimport { type FunctionRegistry } from '../registry';\nimport { type TriggerRegistry } from '../trigger';\nimport { type FunctionDef, type FunctionManifest, type FunctionTrigger } from '../types';\n\nexport type Callback = (data: any) => Promise<void | number>;\n\nexport type SchedulerOptions = {\n endpoint?: string;\n callback?: Callback;\n};\n\n/**\n * The scheduler triggers function execution based on various triggers.\n */\nexport class Scheduler {\n private _ctx = createContext();\n\n constructor(\n public readonly functions: FunctionRegistry,\n public readonly triggers: TriggerRegistry,\n private readonly _options: SchedulerOptions = {},\n ) {\n this.functions.onFunctionsRegistered.on(async ({ space, newFunctions }) => {\n await this._safeActivateTriggers(space, this.triggers.getInactiveTriggers(space), newFunctions);\n });\n this.triggers.registered.on(async ({ space, triggers }) => {\n await this._safeActivateTriggers(space, triggers, this.functions.getFunctions(space));\n });\n }\n\n async start() {\n await this._ctx.dispose();\n this._ctx = createContext();\n await this.functions.open(this._ctx);\n await this.triggers.open(this._ctx);\n }\n\n async stop() {\n await this._ctx.dispose();\n await this.functions.close();\n await this.triggers.close();\n }\n\n public async register(space: Space, manifest: FunctionManifest) {\n await this.functions.register(space, manifest);\n await this.triggers.register(space, manifest);\n }\n\n private async _safeActivateTriggers(\n space: Space,\n triggers: FunctionTrigger[],\n functions: FunctionDef[],\n ): Promise<void> {\n const mountTasks = triggers.map((trigger) => {\n return this.activate(space, functions, trigger);\n });\n await Promise.all(mountTasks).catch(log.catch);\n }\n\n private async activate(space: Space, functions: FunctionDef[], fnTrigger: FunctionTrigger) {\n const definition = functions.find((def) => def.uri === fnTrigger.function);\n if (!definition) {\n log.info('function is not found for trigger', { fnTrigger });\n return;\n }\n\n await this.triggers.activate({ space }, fnTrigger, async (args) => {\n return this._execFunction(definition, {\n meta: fnTrigger.meta,\n data: { ...args, spaceKey: space.key },\n });\n });\n log('activated trigger', { space: space.key, trigger: fnTrigger });\n }\n\n private async _execFunction<TData, TMeta>(\n def: FunctionDef,\n { data, meta }: { data: TData; meta?: TMeta },\n ): Promise<number> {\n let status = 0;\n try {\n // TODO(burdon): Pass in Space key (common context)?\n const payload = Object.assign({}, meta && ({ meta } satisfies FunctionEventMeta<TMeta>), data);\n\n const { endpoint, callback } = this._options;\n if (endpoint) {\n // TODO(burdon): Move out of scheduler (generalize as callback).\n const url = path.join(endpoint, def.route);\n log.info('exec', { function: def.uri, url });\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(payload),\n });\n\n status = response.status;\n } else if (callback) {\n log.info('exec', { function: def.uri });\n status = (await callback(payload)) ?? 200;\n }\n\n // Check errors.\n if (status && status >= 400) {\n throw new Error(`Response: ${status}`);\n }\n\n // const result = await response.json();\n log.info('done', { function: def.uri, status });\n } catch (err: any) {\n log.error('error', { function: def.uri, error: err.message });\n status = 500;\n }\n\n return status;\n }\n}\n\nconst createContext = () => new Context({ name: 'FunctionScheduler' });\n", "//\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 { Context, Resource } from '@dxos/context';\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { ComplexMap } from '@dxos/util';\n\nimport { createSubscriptionTrigger, createTimerTrigger, createWebhookTrigger, createWebsocketTrigger } from './type';\nimport { type FunctionManifest, FunctionTrigger, type FunctionTriggerType, type TriggerSpec } from '../types';\n\ntype ResponseCode = number;\n\nexport type TriggerCallback = (args: object) => Promise<ResponseCode>;\n\nexport type TriggerContext = { space: Space };\n\n// TODO(burdon): Make object?\nexport type TriggerFactory<Spec extends TriggerSpec, Options = any> = (\n ctx: Context,\n context: TriggerContext,\n spec: Spec,\n callback: TriggerCallback,\n options?: Options,\n) => Promise<void>;\n\nexport type TriggerHandlerMap = { [type in FunctionTriggerType]: TriggerFactory<any> };\n\nconst triggerHandlers: TriggerHandlerMap = {\n subscription: createSubscriptionTrigger,\n timer: createTimerTrigger,\n webhook: createWebhookTrigger,\n websocket: createWebsocketTrigger,\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?: TriggerHandlerMap,\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 async activate(triggerCtx: TriggerContext, trigger: FunctionTrigger, callback: TriggerCallback): Promise<void> {\n log('activate', { space: triggerCtx.space.key, trigger });\n const activationCtx = new Context({ name: `trigger_${trigger.function}` });\n this._ctx.onDispose(() => activationCtx.dispose());\n const registeredTrigger = this._triggersBySpaceKey\n .get(triggerCtx.space.key)\n ?.find((reg) => reg.trigger.id === trigger.id);\n invariant(registeredTrigger, `Trigger is not registered: ${trigger.function}`);\n registeredTrigger.activationCtx = activationCtx;\n\n try {\n const options = this._options?.[trigger.spec.type];\n await triggerHandlers[trigger.spec.type](activationCtx, triggerCtx, 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 if (!space.db.graph.runtimeSchemaRegistry.hasSchema(FunctionTrigger)) {\n space.db.graph.runtimeSchemaRegistry.registerSchema(FunctionTrigger);\n }\n\n const reactiveObjects = manifest.triggers.map((template: Omit<FunctionTrigger, 'id'>) =>\n create(FunctionTrigger, { ...template }),\n );\n reactiveObjects.forEach((obj) => space.db.add(obj));\n }\n\n protected override async _open(): Promise<void> {\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 const functionsSubscription = space.db.query(Filter.schema(FunctionTrigger)).subscribe(async (triggers) => {\n await this._handleRemovedTriggers(space, triggers.objects, registered);\n this._handleNewTriggers(space, triggers.objects, registered);\n });\n\n this._ctx.onDispose(functionsSubscription);\n }\n });\n\n this._ctx.onDispose(() => spaceListSubscription.unsubscribe());\n }\n\n protected override async _close(_: Context): Promise<void> {\n this._triggersBySpaceKey.clear();\n }\n\n private _handleNewTriggers(space: Space, allTriggers: FunctionTrigger[], registered: RegisteredTrigger[]) {\n const newTriggers = allTriggers.filter((candidate) => {\n return registered.find((reg) => reg.trigger.id === candidate.id) == null;\n });\n\n if (newTriggers.length > 0) {\n const newRegisteredTriggers: RegisteredTrigger[] = newTriggers.map((trigger) => ({ trigger }));\n registered.push(...newRegisteredTriggers);\n log('registered new triggers', () => ({ spaceKey: space.key, functions: newTriggers.map((t) => t.function) }));\n this.registered.emit({ space, triggers: newTriggers });\n }\n }\n\n private async _handleRemovedTriggers(\n space: Space,\n allTriggers: 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 allTriggers.find((trigger: FunctionTrigger) => 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 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", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { TextV0Type } from '@braneframe/types';\nimport { debounce, DeferredTask } from '@dxos/async';\nimport { type Context } from '@dxos/context';\nimport { createSubscription, Filter, getAutomergeObjectCore, type Query } from '@dxos/echo-db';\nimport { log } from '@dxos/log';\n\nimport type { SubscriptionTrigger } from '../../types';\nimport { type TriggerCallback, type TriggerContext, type TriggerFactory } from '../trigger-registry';\n\nexport const createSubscriptionTrigger: TriggerFactory<SubscriptionTrigger> = async (\n ctx: Context,\n triggerCtx: TriggerContext,\n spec: SubscriptionTrigger,\n callback: TriggerCallback,\n) => {\n const objectIds = new Set<string>();\n const task = new DeferredTask(ctx, async () => {\n if (objectIds.size > 0) {\n await callback({ objects: Array.from(objectIds) });\n objectIds.clear();\n }\n });\n\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 log.info('updated', { added: added.length, updated: updated.length });\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 task.schedule();\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 subscription.update(objects);\n\n // TODO(burdon): Hack to monitor changes to Document's text object.\n if (deep) {\n log.info('update', { objects: objects.length });\n for (const object of objects) {\n const content = object.content;\n if (content instanceof TextV0Type) {\n subscriptions.push(\n getAutomergeObjectCore(content).updates.on(debounce(() => subscription.update([object]), 1_000)),\n );\n }\n }\n }\n };\n\n // TODO(burdon): Is Filter.or implemented?\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 const query = triggerCtx.space.db.query(Filter.or(filter.map(({ type, props }) => Filter.typename(type, props))));\n subscriptions.push(query.subscribe(delay ? debounce(update, delay) : update));\n\n ctx.onDispose(() => {\n subscriptions.forEach((unsubscribe) => unsubscribe());\n });\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { CronJob } from 'cron';\n\nimport { DeferredTask } from '@dxos/async';\nimport { type Context } from '@dxos/context';\nimport { log } from '@dxos/log';\n\nimport type { TimerTrigger } from '../../types';\nimport { type TriggerCallback, type TriggerContext, type TriggerFactory } from '../trigger-registry';\n\nexport const createTimerTrigger: TriggerFactory<TimerTrigger> = async (\n ctx: Context,\n triggerContext: TriggerContext,\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 // https://www.npmjs.com/package/cron#constructor\n const job = CronJob.from({\n cronTime: spec.cron,\n runOnInit: false,\n onTick: () => {\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: triggerContext.space.key.truncate(), count: run, delta });\n task.schedule();\n },\n });\n\n job.start();\n ctx.onDispose(() => job.stop());\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { getPort } from 'get-port-please';\nimport http from 'node:http';\n\nimport { type Context } from '@dxos/context';\nimport { log } from '@dxos/log';\n\nimport type { WebhookTrigger } from '../../types';\nimport { type TriggerCallback, type TriggerContext, type TriggerFactory } from '../trigger-registry';\n\nexport const createWebhookTrigger: TriggerFactory<WebhookTrigger> = async (\n ctx: Context,\n _: TriggerContext,\n spec: WebhookTrigger,\n callback: TriggerCallback,\n) => {\n // TODO(burdon): Enable POST hook with payload.\n const server = http.createServer(async (req, res) => {\n if (req.method !== spec.method) {\n res.statusCode = 405;\n return res.end();\n }\n res.statusCode = await callback({});\n res.end();\n });\n\n // TODO(burdon): Not used.\n // const DEF_PORT_RANGE = { min: 7500, max: 7599 };\n // const portRange = Object.assign({}, trigger.port, DEF_PORT_RANGE) as WebhookTrigger['port'];\n const port = await getPort({\n random: true,\n // portRange: [portRange!.min, portRange!.max],\n });\n\n // TODO(burdon): Update trigger object with actual port.\n server.listen(port, () => {\n log.info('started webhook', { port });\n spec.port = port;\n });\n\n ctx.onDispose(() => {\n server.close();\n });\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport WebSocket from 'ws';\n\nimport { sleep, Trigger } from '@dxos/async';\nimport { type Context } from '@dxos/context';\nimport { log } from '@dxos/log';\n\nimport { type WebsocketTrigger } from '../../types';\nimport { type TriggerCallback, type TriggerContext, type TriggerFactory } from '../trigger-registry';\n\ninterface WebsocketTriggerOptions {\n retryDelay: number;\n maxAttempts: number;\n}\n\n/**\n * Websocket.\n * NOTE: The port must be unique, so the same hook cannot be used for multiple spaces.\n */\nexport const createWebsocketTrigger: TriggerFactory<WebsocketTrigger, WebsocketTriggerOptions> = async (\n ctx: Context,\n triggerCtx: TriggerContext,\n spec: WebsocketTrigger,\n callback: TriggerCallback,\n options: WebsocketTriggerOptions = { retryDelay: 2, maxAttempts: 5 },\n) => {\n const { url, init } = spec;\n\n let ws: WebSocket;\n for (let attempt = 1; attempt <= options.maxAttempts; attempt++) {\n const open = new Trigger<boolean>();\n\n ws = new WebSocket(url);\n Object.assign(ws, {\n onopen: () => {\n log.info('opened', { url });\n if (spec.init) {\n ws.send(new TextEncoder().encode(JSON.stringify(init)));\n }\n\n open.wake(true);\n },\n\n onclose: (event) => {\n log.info('closed', { url, code: event.code });\n // Reconnect if server closes (e.g., CF restart).\n // https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent/code\n if (event.code === 1006) {\n setTimeout(async () => {\n log.info(`reconnecting in ${options.retryDelay}s...`, { url });\n await createWebsocketTrigger(ctx, triggerCtx, spec, callback, options);\n }, options.retryDelay * 1_000);\n }\n\n open.wake(false);\n },\n\n onerror: (event) => {\n log.catch(event.error, { url });\n },\n\n onmessage: async (event) => {\n try {\n log.info('message');\n const data = JSON.parse(new TextDecoder().decode(event.data as Uint8Array));\n await callback({ data });\n } catch (err) {\n log.catch(err, { url });\n }\n },\n } satisfies Partial<WebSocket>);\n\n const isOpen = await open.wait();\n if (isOpen) {\n break;\n } else {\n const wait = Math.pow(attempt, 2) * options.retryDelay;\n if (attempt < options.maxAttempts) {\n log.warn(`failed to connect; trying again in ${wait}s`, { attempt });\n await sleep(wait * 1_000);\n }\n }\n }\n\n ctx.onDispose(() => {\n ws?.close();\n });\n};\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,oBAAuC;AAGvC,iBAAoB;AACpB,kBAA4B;ACJ5B,mBAAsB;AAEtB,kBAA2C;AAC3C,qBAAuC;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O2F,WAAWkM,CAAAA,EAAG9H,QAAQ/J,EAAE,KAAK;AAC7F,UAAI8R,YAAY;AACd,cAAMC,eAAepM,WAAWqM,OAAOH,GAAG,CAAA,EAAG,CAAA;AAC7C,cAAME,aAAaV,eAAetF,QAAAA;AAClCkF,gBAAQ9K,KAAK4L,aAAahI,OAAO;MACnC;IACF;AAEA,QAAIkH,QAAQvQ,SAAS,GAAG;AACtB,WAAKuQ,QAAQ7K,KAAK;QAAE7G;QAAOmE,UAAUuN;MAAQ,CAAA;IAC/C;EACF;EAEQE,aAAa5R,OAAc0S,WAAuE;AACxG,UAAMC,mBAAmB,KAAKlB,oBAAoBtR,IAAIH,MAAMiB,GAAG,KAAK,CAAA;AACpE,WAAO0R,iBAAiB/R,OAAO8R,SAAAA,EAAWlS,IAAI,CAACgK,YAAYA,QAAQA,OAAO;EAC5E;AACF;",
6
+ "names": ["import_util", "import_async", "import_context", "import_log", "import_node_path", "import_echo", "import_invariant", "import_keys", "import_get_port_please", "subscriptionHandler", "handler", "event", "data", "context", "rest", "client", "space", "spaceKey", "spaces", "get", "PublicKey", "from", "undefined", "objects", "map", "id", "db", "getObjectById", "filter", "nonNullable", "log", "warn", "info", "key", "truncate", "length", "omitEchoId", "schema", "S", "make", "AST", "omit", "ast", "SubscriptionTriggerSchema", "struct", "type", "literal", "array", "string", "props", "optional", "record", "any", "options", "deep", "boolean", "delay", "number", "TimerTriggerSchema", "cron", "WebhookTriggerSchema", "mutable", "method", "port", "WebsocketTriggerSchema", "url", "init", "TriggerSpecSchema", "union", "FunctionDef", "TypedObject", "typename", "version", "uri", "description", "route", "FunctionTrigger", "function", "pipe", "meta", "spec", "FunctionManifestSchema", "functions", "triggers", "FunctionRegistry", "Resource", "constructor", "_client", "_functionBySpaceKey", "ComplexMap", "hash", "onFunctionsRegistered", "Event", "getFunctions", "register", "manifest", "graph", "runtimeSchemaRegistry", "hasSchema", "registerSchema", "existingDefinitions", "query", "Filter", "run", "newDefinitions", "getNewDefinitions", "reactiveObjects", "template", "create", "forEach", "obj", "add", "_open", "spaceListSubscription", "subscribe", "has", "registered", "set", "waitUntilReady", "_ctx", "disposed", "functionsSubscription", "definitions", "newFunctions", "push", "emit", "onDispose", "unsubscribe", "_close", "_", "clear", "candidateList", "existing", "candidate", "find", "def", "DevServer", "_functionsRegistry", "_options", "createContext", "_handlers", "_seq", "update", "on", "_load", "_safeUpdateRegistration", "stats", "seq", "endpoint", "invariant", "_port", "proxy", "_proxy", "Object", "values", "start", "_server", "app", "express", "use", "json", "post", "req", "res", "path", "params", "reload", "statusCode", "invoke", "body", "end", "err", "catch", "getPort", "host", "portRange", "listen", "registrationId", "services", "FunctionRegistryService", "_functionServiceRegistration", "open", "stop", "Error", "trigger", "Trigger", "close", "unregister", "wake", "throw", "wait", "force", "filePath", "join", "baseDir", "keys", "require", "cache", "startsWith", "module", "default", "updateRegistration", "e", "now", "Date", "_invoke", "duration", "dataDir", "response", "status", "code", "Context", "name", "Scheduler", "_safeActivateTriggers", "getInactiveTriggers", "dispose", "mountTasks", "activate", "Promise", "all", "fnTrigger", "definition", "args", "_execFunction", "payload", "assign", "callback", "fetch", "headers", "JSON", "stringify", "error", "message", "createSubscriptionTrigger", "ctx", "triggerCtx", "objectIds", "Set", "task", "DeferredTask", "size", "Array", "subscriptions", "subscription", "createSubscription", "added", "updated", "object", "schedule", "content", "TextV0Type", "getAutomergeObjectCore", "updates", "debounce", "or", "createTimerTrigger", "triggerContext", "last", "job", "CronJob", "cronTime", "runOnInit", "onTick", "delta", "count", "createWebhookTrigger", "server", "http", "createServer", "random", "createWebsocketTrigger", "retryDelay", "maxAttempts", "ws", "attempt", "WebSocket", "onopen", "send", "TextEncoder", "encode", "onclose", "setTimeout", "onerror", "onmessage", "parse", "TextDecoder", "decode", "isOpen", "Math", "pow", "sleep", "triggerHandlers", "timer", "webhook", "websocket", "TriggerRegistry", "_triggersBySpaceKey", "removed", "getActiveTriggers", "_getTriggers", "t", "activationCtx", "registeredTrigger", "reg", "_handleRemovedTriggers", "_handleNewTriggers", "allTriggers", "newTriggers", "newRegisteredTriggers", "i", "wasRemoved", "unregistered", "splice", "predicate", "allSpaceTriggers"]
7
7
  }
@@ -1 +1 @@
1
- {"inputs":{"packages/core/functions/src/handler.ts":{"bytes":5873,"imports":[{"path":"@dxos/client","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/manifest.ts":{"bytes":1910,"imports":[],"format":"esm"},"packages/core/functions/src/runtime/dev-server.ts":{"bytes":19229,"imports":[{"path":"express","kind":"import-statement","external":true},{"path":"get-port-please","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"<runtime>","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/runtime/scheduler.ts":{"bytes":25793,"imports":[{"path":"cron","kind":"import-statement","external":true},{"path":"@braneframe/types","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/runtime/index.ts":{"bytes":566,"imports":[{"path":"packages/core/functions/src/runtime/dev-server.ts","kind":"import-statement","original":"./dev-server"},{"path":"packages/core/functions/src/runtime/scheduler.ts","kind":"import-statement","original":"./scheduler"}],"format":"esm"},"packages/core/functions/src/index.ts":{"bytes":637,"imports":[{"path":"packages/core/functions/src/handler.ts","kind":"import-statement","original":"./handler"},{"path":"packages/core/functions/src/manifest.ts","kind":"import-statement","original":"./manifest"},{"path":"packages/core/functions/src/runtime/index.ts","kind":"import-statement","original":"./runtime"}],"format":"esm"}},"outputs":{"packages/core/functions/dist/lib/node/index.cjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":24099},"packages/core/functions/dist/lib/node/index.cjs":{"imports":[{"path":"@dxos/client","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"express","kind":"import-statement","external":true},{"path":"get-port-please","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"cron","kind":"import-statement","external":true},{"path":"@braneframe/types","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"exports":["DevServer","Scheduler","subscriptionHandler"],"entryPoint":"packages/core/functions/src/index.ts","inputs":{"packages/core/functions/src/handler.ts":{"bytesInOutput":1057},"packages/core/functions/src/index.ts":{"bytesInOutput":0},"packages/core/functions/src/runtime/dev-server.ts":{"bytesInOutput":4983},"packages/core/functions/src/runtime/index.ts":{"bytesInOutput":0},"packages/core/functions/src/runtime/scheduler.ts":{"bytesInOutput":6345}},"bytes":12999}}}
1
+ {"inputs":{"packages/core/functions/src/handler.ts":{"bytes":6874,"imports":[{"path":"@dxos/client","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/types.ts":{"bytes":9313,"imports":[{"path":"@dxos/echo-schema","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/registry/function-registry.ts":{"bytes":11255,"imports":[{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"packages/core/functions/src/types.ts","kind":"import-statement","original":"../types"}],"format":"esm"},"packages/core/functions/src/registry/index.ts":{"bytes":497,"imports":[{"path":"packages/core/functions/src/registry/function-registry.ts","kind":"import-statement","original":"./function-registry"}],"format":"esm"},"packages/core/functions/src/runtime/dev-server.ts":{"bytes":27510,"imports":[{"path":"express","kind":"import-statement","external":true},{"path":"get-port-please","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"<runtime>","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/runtime/scheduler.ts":{"bytes":15341,"imports":[{"path":"node:path","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/runtime/index.ts":{"bytes":566,"imports":[{"path":"packages/core/functions/src/runtime/dev-server.ts","kind":"import-statement","original":"./dev-server"},{"path":"packages/core/functions/src/runtime/scheduler.ts","kind":"import-statement","original":"./scheduler"}],"format":"esm"},"packages/core/functions/src/trigger/type/subscription-trigger.ts":{"bytes":9356,"imports":[{"path":"@braneframe/types","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/echo-db","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/trigger/type/timer-trigger.ts":{"bytes":4169,"imports":[{"path":"cron","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/trigger/type/webhook-trigger.ts":{"bytes":4272,"imports":[{"path":"get-port-please","kind":"import-statement","external":true},{"path":"node:http","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/trigger/type/websocket-trigger.ts":{"bytes":10377,"imports":[{"path":"ws","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/trigger/type/index.ts":{"bytes":829,"imports":[{"path":"packages/core/functions/src/trigger/type/subscription-trigger.ts","kind":"import-statement","original":"./subscription-trigger"},{"path":"packages/core/functions/src/trigger/type/timer-trigger.ts","kind":"import-statement","original":"./timer-trigger"},{"path":"packages/core/functions/src/trigger/type/webhook-trigger.ts","kind":"import-statement","original":"./webhook-trigger"},{"path":"packages/core/functions/src/trigger/type/websocket-trigger.ts","kind":"import-statement","original":"./websocket-trigger"}],"format":"esm"},"packages/core/functions/src/trigger/trigger-registry.ts":{"bytes":21823,"imports":[{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"packages/core/functions/src/trigger/type/index.ts","kind":"import-statement","original":"./type"},{"path":"packages/core/functions/src/types.ts","kind":"import-statement","original":"../types"}],"format":"esm"},"packages/core/functions/src/trigger/index.ts":{"bytes":495,"imports":[{"path":"packages/core/functions/src/trigger/trigger-registry.ts","kind":"import-statement","original":"./trigger-registry"}],"format":"esm"},"packages/core/functions/src/index.ts":{"bytes":801,"imports":[{"path":"packages/core/functions/src/handler.ts","kind":"import-statement","original":"./handler"},{"path":"packages/core/functions/src/registry/index.ts","kind":"import-statement","original":"./registry"},{"path":"packages/core/functions/src/runtime/index.ts","kind":"import-statement","original":"./runtime"},{"path":"packages/core/functions/src/trigger/index.ts","kind":"import-statement","original":"./trigger"},{"path":"packages/core/functions/src/types.ts","kind":"import-statement","original":"./types"}],"format":"esm"}},"outputs":{"packages/core/functions/dist/lib/node/index.cjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":59018},"packages/core/functions/dist/lib/node/index.cjs":{"imports":[{"path":"@dxos/client","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"express","kind":"import-statement","external":true},{"path":"get-port-please","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"@braneframe/types","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/echo-db","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"cron","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"get-port-please","kind":"import-statement","external":true},{"path":"node:http","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"ws","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}],"exports":["DevServer","FunctionDef","FunctionManifestSchema","FunctionRegistry","FunctionTrigger","Scheduler","TriggerRegistry","subscriptionHandler"],"entryPoint":"packages/core/functions/src/index.ts","inputs":{"packages/core/functions/src/handler.ts":{"bytesInOutput":1124},"packages/core/functions/src/index.ts":{"bytesInOutput":0},"packages/core/functions/src/registry/function-registry.ts":{"bytesInOutput":2596},"packages/core/functions/src/types.ts":{"bytesInOutput":1789},"packages/core/functions/src/registry/index.ts":{"bytesInOutput":0},"packages/core/functions/src/runtime/dev-server.ts":{"bytesInOutput":7819},"packages/core/functions/src/runtime/index.ts":{"bytesInOutput":0},"packages/core/functions/src/runtime/scheduler.ts":{"bytesInOutput":3827},"packages/core/functions/src/trigger/trigger-registry.ts":{"bytesInOutput":5257},"packages/core/functions/src/trigger/type/subscription-trigger.ts":{"bytesInOutput":2083},"packages/core/functions/src/trigger/type/index.ts":{"bytesInOutput":0},"packages/core/functions/src/trigger/type/timer-trigger.ts":{"bytesInOutput":940},"packages/core/functions/src/trigger/type/webhook-trigger.ts":{"bytesInOutput":825},"packages/core/functions/src/trigger/type/websocket-trigger.ts":{"bytesInOutput":2847},"packages/core/functions/src/trigger/index.ts":{"bytesInOutput":0}},"bytes":30366}}}
@@ -1,23 +1,44 @@
1
1
  import { type Client } from '@dxos/client';
2
2
  import { type Space } from '@dxos/client/echo';
3
3
  import { type EchoReactiveObject } from '@dxos/echo-schema';
4
- export interface Response {
5
- status(code: number): Response;
6
- }
4
+ /**
5
+ * Function handler.
6
+ */
7
+ export type FunctionHandler<TData = {}, TMeta = {}> = (params: {
8
+ context: FunctionContext;
9
+ event: FunctionEvent<TData, TMeta>;
10
+ response: FunctionResponse;
11
+ }) => Promise<FunctionResponse | void>;
12
+ /**
13
+ * Function context.
14
+ */
7
15
  export interface FunctionContext {
8
16
  client: Client;
9
17
  dataDir?: string;
10
18
  }
11
- export type FunctionHandler<T extends {}> = (params: {
12
- event: T;
13
- context: FunctionContext;
14
- response: Response;
15
- }) => Promise<Response | void>;
16
- export type FunctionSubscriptionEvent = {
17
- space?: string;
19
+ /**
20
+ * Event payload.
21
+ */
22
+ export type FunctionEvent<TData = {}, TMeta = {}> = {
23
+ data: FunctionEventMeta<TMeta> & TData;
24
+ };
25
+ /**
26
+ * Metadata from trigger.
27
+ */
28
+ export type FunctionEventMeta<TMeta = {}> = {
29
+ meta: TMeta;
30
+ };
31
+ /**
32
+ * Function response.
33
+ */
34
+ export interface FunctionResponse {
35
+ status(code: number): FunctionResponse;
36
+ }
37
+ export type RawSubscriptionData = {
38
+ spaceKey?: string;
18
39
  objects?: string[];
19
40
  };
20
- export type FunctionSubscriptionEvent2 = {
41
+ export type SubscriptionData = {
21
42
  space?: Space;
22
43
  objects?: EchoReactiveObject<any>[];
23
44
  };
@@ -31,5 +52,5 @@ export type FunctionSubscriptionEvent2 = {
31
52
  *
32
53
  * NOTE: Get space key from devtools or `dx space list --json`
33
54
  */
34
- export declare const subscriptionHandler: (handler: FunctionHandler<FunctionSubscriptionEvent2>) => FunctionHandler<FunctionSubscriptionEvent>;
55
+ export declare const subscriptionHandler: <TMeta>(handler: FunctionHandler<SubscriptionData, TMeta>) => FunctionHandler<RawSubscriptionData, TMeta>;
35
56
  //# sourceMappingURL=handler.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"handler.d.ts","sourceRoot":"","sources":["../../../src/handler.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,KAAK,MAAM,EAAa,MAAM,cAAc,CAAC;AACtD,OAAO,EAAE,KAAK,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAE,KAAK,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAK5D,MAAM,WAAW,QAAQ;IACvB,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,QAAQ,CAAC;CAChC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C;;GAEG;AACH,MAAM,WAAW,eAAe;IAE9B,MAAM,EAAE,MAAM,CAAC;IAEf,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;GAEG;AACH,MAAM,MAAM,aAAa,CAAC,KAAK,GAAG,EAAE,EAAE,KAAK,GAAG,EAAE,IAAI;IAClD,IAAI,EAAE,iBAAiB,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC;CACxC,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,iBAAiB,CAAC,KAAK,GAAG,EAAE,IAAI;IAC1C,IAAI,EAAE,KAAK,CAAC;CACb,CAAC;AAEF;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,gBAAgB,CAAC;CACxC;AAMD,MAAM,MAAM,mBAAmB,GAAG;IAChC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;CACpB,CAAC;AAEF,MAAM,MAAM,gBAAgB,GAAG;IAC7B,KAAK,CAAC,EAAE,KAAK,CAAC;IACd,OAAO,CAAC,EAAE,kBAAkB,CAAC,GAAG,CAAC,EAAE,CAAC;CACrC,CAAC;AAEF;;;;;;;;;GASG;AACH,eAAO,MAAM,mBAAmB,2GAkB/B,CAAC"}
@@ -1,4 +1,6 @@
1
1
  export * from './handler';
2
- export * from './manifest';
2
+ export * from './registry';
3
3
  export * from './runtime';
4
+ export * from './trigger';
5
+ export * from './types';
4
6
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAIA,cAAc,WAAW,CAAC;AAC1B,cAAc,YAAY,CAAC;AAC3B,cAAc,WAAW,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAIA,cAAc,WAAW,CAAC;AAC1B,cAAc,YAAY,CAAC;AAC3B,cAAc,WAAW,CAAC;AAC1B,cAAc,WAAW,CAAC;AAC1B,cAAc,SAAS,CAAC"}
@@ -0,0 +1,24 @@
1
+ import { Event } from '@dxos/async';
2
+ import { type Client } from '@dxos/client';
3
+ import { type Space } from '@dxos/client/echo';
4
+ import { type Context, Resource } from '@dxos/context';
5
+ import { FunctionDef, type FunctionManifest } from '../types';
6
+ export type FunctionsRegisteredEvent = {
7
+ space: Space;
8
+ newFunctions: FunctionDef[];
9
+ };
10
+ export declare class FunctionRegistry extends Resource {
11
+ private readonly _client;
12
+ private readonly _functionBySpaceKey;
13
+ readonly onFunctionsRegistered: Event<FunctionsRegisteredEvent>;
14
+ constructor(_client: Client);
15
+ getFunctions(space: Space): FunctionDef[];
16
+ /**
17
+ * The method loads function definitions from the manifest into the space.
18
+ * We first load all the definitions from the space to deduplicate by functionId.
19
+ */
20
+ register(space: Space, manifest: FunctionManifest): Promise<void>;
21
+ protected _open(): Promise<void>;
22
+ protected _close(_: Context): Promise<void>;
23
+ }
24
+ //# sourceMappingURL=function-registry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"function-registry.d.ts","sourceRoot":"","sources":["../../../../src/registry/function-registry.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAkB,KAAK,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC/D,OAAO,EAAE,KAAK,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAIvD,OAAO,EAAE,WAAW,EAAE,KAAK,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAE9D,MAAM,MAAM,wBAAwB,GAAG;IACrC,KAAK,EAAE,KAAK,CAAC;IACb,YAAY,EAAE,WAAW,EAAE,CAAC;CAC7B,CAAC;AAEF,qBAAa,gBAAiB,SAAQ,QAAQ;IAKhC,OAAO,CAAC,QAAQ,CAAC,OAAO;IAJpC,OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAA4D;IAEhG,SAAgB,qBAAqB,kCAAyC;gBAEjD,OAAO,EAAE,MAAM;IAIrC,YAAY,CAAC,KAAK,EAAE,KAAK,GAAG,WAAW,EAAE;IAIhD;;;OAGG;IAEU,QAAQ,CAAC,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC;cAcrD,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;cA0BtB,MAAM,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;CAG3D"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=function-registry.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"function-registry.test.d.ts","sourceRoot":"","sources":["../../../../src/registry/function-registry.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,2 @@
1
+ export * from './function-registry';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/registry/index.ts"],"names":[],"mappings":"AAIA,cAAc,qBAAqB,CAAC"}
@@ -1,10 +1,11 @@
1
+ import { Event } from '@dxos/async';
1
2
  import { type Client } from '@dxos/client';
2
3
  import { type FunctionHandler } from '../handler';
3
- import { type FunctionDef, type FunctionManifest } from '../manifest';
4
+ import { type FunctionRegistry } from '../registry';
5
+ import { type FunctionDef } from '../types';
4
6
  export type DevServerOptions = {
7
+ baseDir: string;
5
8
  port?: number;
6
- directory: string;
7
- manifest: FunctionManifest;
8
9
  reload?: boolean;
9
10
  dataDir?: string;
10
11
  };
@@ -13,30 +14,37 @@ export type DevServerOptions = {
13
14
  */
14
15
  export declare class DevServer {
15
16
  private readonly _client;
17
+ private readonly _functionsRegistry;
16
18
  private readonly _options;
19
+ private _ctx;
17
20
  private readonly _handlers;
18
21
  private _server?;
19
22
  private _port?;
20
- private _registrationId?;
23
+ private _functionServiceRegistration?;
21
24
  private _proxy?;
22
25
  private _seq;
23
- constructor(_client: Client, _options: DevServerOptions);
26
+ readonly update: Event<number>;
27
+ constructor(_client: Client, _functionsRegistry: FunctionRegistry, _options: DevServerOptions);
28
+ get stats(): {
29
+ seq: number;
30
+ };
24
31
  get endpoint(): string;
25
32
  get proxy(): string | undefined;
26
33
  get functions(): {
27
34
  def: FunctionDef;
28
35
  handler: FunctionHandler<any>;
29
36
  }[];
30
- initialize(): Promise<void>;
31
37
  start(): Promise<void>;
32
38
  stop(): Promise<void>;
33
39
  /**
34
40
  * Load function.
35
41
  */
36
42
  private _load;
43
+ private _safeUpdateRegistration;
37
44
  /**
38
- * Invoke function handler.
45
+ * Invoke function.
39
46
  */
47
+ invoke(path: string, data: any): Promise<number>;
40
48
  private _invoke;
41
49
  }
42
50
  //# sourceMappingURL=dev-server.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"dev-server.d.ts","sourceRoot":"","sources":["../../../../src/runtime/dev-server.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,cAAc,CAAC;AAI3C,OAAO,EAAwB,KAAK,eAAe,EAAiB,MAAM,YAAY,CAAC;AACvF,OAAO,EAAE,KAAK,WAAW,EAAE,KAAK,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAEtE,MAAM,MAAM,gBAAgB,GAAG;IAC7B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,gBAAgB,CAAC;IAC3B,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF;;GAEG;AACH,qBAAa,SAAS;IAYlB,OAAO,CAAC,QAAQ,CAAC,OAAO;IACxB,OAAO,CAAC,QAAQ,CAAC,QAAQ;IAX3B,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA2E;IAErG,OAAO,CAAC,OA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CAAC,4BAA4B,CAAC,CAAS;IAC9C,OAAO,CAAC,MAAM,CAAC,CAAS;IACxB,OAAO,CAAC,IAAI,CAAK;IAEjB,SAAgB,MAAM,gBAAuB;gBAI1B,OAAO,EAAE,MAAM,EACf,kBAAkB,EAAE,gBAAgB,EACpC,QAAQ,EAAE,gBAAgB;IAS7C,IAAI,KAAK;;MAIR;IAED,IAAI,QAAQ,WAGX;IAED,IAAI,KAAK,uBAER;IAED,IAAI,SAAS;;;QAEZ;IAEK,KAAK;IAmDL,IAAI;IA+BV;;OAEG;YACW,KAAK;YAwBL,uBAAuB;IAYrC;;OAEG;IACU,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,GAAG,OAAO,CAAC,MAAM,CAAC;YAY/C,OAAO;CAoBtB"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=dev-server.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dev-server.test.d.ts","sourceRoot":"","sources":["../../../../src/runtime/dev-server.test.ts"],"names":[],"mappings":""}
@@ -1,27 +1,26 @@
1
- import { type Client } from '@dxos/client';
2
- import { type FunctionSubscriptionEvent } from '../handler';
3
- import { type FunctionManifest } from '../manifest';
4
- type Callback = (data: FunctionSubscriptionEvent) => Promise<number>;
5
- type SchedulerOptions = {
1
+ import { type Space } from '@dxos/client/echo';
2
+ import { type FunctionRegistry } from '../registry';
3
+ import { type TriggerRegistry } from '../trigger';
4
+ import { type FunctionManifest } from '../types';
5
+ export type Callback = (data: any) => Promise<void | number>;
6
+ export type SchedulerOptions = {
6
7
  endpoint?: string;
7
8
  callback?: Callback;
8
9
  };
9
10
  /**
10
- * Functions scheduler.
11
+ * The scheduler triggers function execution based on various triggers.
11
12
  */
12
13
  export declare class Scheduler {
13
- private readonly _client;
14
- private readonly _manifest;
14
+ readonly functions: FunctionRegistry;
15
+ readonly triggers: TriggerRegistry;
15
16
  private readonly _options;
16
- private readonly _mounts;
17
- constructor(_client: Client, _manifest: FunctionManifest, _options?: SchedulerOptions);
17
+ private _ctx;
18
+ constructor(functions: FunctionRegistry, triggers: TriggerRegistry, _options?: SchedulerOptions);
18
19
  start(): Promise<void>;
19
20
  stop(): Promise<void>;
20
- private mount;
21
- private unmount;
22
- private _createTimer;
23
- private _createSubscription;
21
+ register(space: Space, manifest: FunctionManifest): Promise<void>;
22
+ private _safeActivateTriggers;
23
+ private activate;
24
24
  private _execFunction;
25
25
  }
26
- export {};
27
26
  //# sourceMappingURL=scheduler.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"scheduler.d.ts","sourceRoot":"","sources":["../../../../src/runtime/scheduler.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,KAAK,MAAM,EAAkB,MAAM,cAAc,CAAC;AAO3D,OAAO,EAAE,KAAK,yBAAyB,EAAE,MAAM,YAAY,CAAC;AAC5D,OAAO,EAAoB,KAAK,gBAAgB,EAAkD,MAAM,aAAa,CAAC;AAEtH,KAAK,QAAQ,GAAG,CAAC,IAAI,EAAE,yBAAyB,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;AAErE,KAAK,gBAAgB,GAAG;IACtB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,QAAQ,CAAC;CACrB,CAAC;AAEF;;GAEG;AAEH,qBAAa,SAAS;IAQlB,OAAO,CAAC,QAAQ,CAAC,OAAO;IACxB,OAAO,CAAC,QAAQ,CAAC,SAAS;IAC1B,OAAO,CAAC,QAAQ,CAAC,QAAQ;IAR3B,OAAO,CAAC,QAAQ,CAAC,OAAO,CAG6B;gBAGlC,OAAO,EAAE,MAAM,EACf,SAAS,EAAE,gBAAgB,EAC3B,QAAQ,GAAE,gBAAqB;IAG5C,KAAK;IAWL,IAAI;YAMI,KAAK;YA0BL,OAAO;IASrB,OAAO,CAAC,YAAY;IA8BpB,OAAO,CAAC,mBAAmB;YAwDb,aAAa;CA0B5B"}
1
+ {"version":3,"file":"scheduler.d.ts","sourceRoot":"","sources":["../../../../src/runtime/scheduler.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,KAAK,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAK/C,OAAO,EAAE,KAAK,gBAAgB,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EAAE,KAAK,eAAe,EAAE,MAAM,YAAY,CAAC;AAClD,OAAO,EAAoB,KAAK,gBAAgB,EAAwB,MAAM,UAAU,CAAC;AAEzF,MAAM,MAAM,QAAQ,GAAG,CAAC,IAAI,EAAE,GAAG,KAAK,OAAO,CAAC,IAAI,GAAG,MAAM,CAAC,CAAC;AAE7D,MAAM,MAAM,gBAAgB,GAAG;IAC7B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,QAAQ,CAAC;CACrB,CAAC;AAEF;;GAEG;AACH,qBAAa,SAAS;aAIF,SAAS,EAAE,gBAAgB;aAC3B,QAAQ,EAAE,eAAe;IACzC,OAAO,CAAC,QAAQ,CAAC,QAAQ;IAL3B,OAAO,CAAC,IAAI,CAAmB;gBAGb,SAAS,EAAE,gBAAgB,EAC3B,QAAQ,EAAE,eAAe,EACxB,QAAQ,GAAE,gBAAqB;IAU5C,KAAK;IAOL,IAAI;IAMG,QAAQ,CAAC,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,gBAAgB;YAKhD,qBAAqB;YAWrB,QAAQ;YAgBR,aAAa;CA0C5B"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=functions-integration.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"functions-integration.test.d.ts","sourceRoot":"","sources":["../../../../src/testing/functions-integration.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,4 @@
1
+ export * from './setup';
2
+ export * from './types';
3
+ export * from './util';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/testing/index.ts"],"names":[],"mappings":"AAIA,cAAc,SAAS,CAAC;AACxB,cAAc,SAAS,CAAC;AACxB,cAAc,QAAQ,CAAC"}
@@ -0,0 +1,5 @@
1
+ import { Client, Config } from '@dxos/client';
2
+ import { type TestBuilder } from '@dxos/client/testing';
3
+ export declare const createInitializedClients: (testBuilder: TestBuilder, count?: number, config?: Config) => Promise<Client[]>;
4
+ export declare const createFunctionRuntime: (testBuilder: TestBuilder) => Promise<Client>;
5
+ //# sourceMappingURL=setup.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setup.d.ts","sourceRoot":"","sources":["../../../../src/testing/setup.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,EAAE,KAAK,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAQxD,eAAO,MAAM,wBAAwB,gBAAuB,WAAW,UAAS,MAAM,WAAe,MAAM,sBAW1G,CAAC;AAEF,eAAO,MAAM,qBAAqB,gBAAuB,WAAW,KAAG,QAAQ,MAAM,CAiBpF,CAAC"}
@@ -0,0 +1,4 @@
1
+ import { type FunctionHandler } from '../../handler';
2
+ export declare const setTestCallHandler: (handler: FunctionHandler<any>) => void;
3
+ export declare const handler: FunctionHandler<any>;
4
+ //# sourceMappingURL=handler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handler.d.ts","sourceRoot":"","sources":["../../../../../src/testing/test/handler.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,KAAK,eAAe,EAAE,MAAM,eAAe,CAAC;AAIrD,eAAO,MAAM,kBAAkB,YAAa,gBAAgB,GAAG,CAAC,SAE/D,CAAC;AAEF,eAAO,MAAM,OAAO,EAAE,eAAe,CAAC,GAAG,CAExC,CAAC"}
@@ -0,0 +1,3 @@
1
+ import { handler } from './handler';
2
+ export default handler;
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../src/testing/test/index.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,eAAe,OAAO,CAAC"}
@@ -0,0 +1,9 @@
1
+ declare const TestType_base: import("@dxos/echo-schema").EchoSchemaClass<{
2
+ title: string;
3
+ } & {
4
+ id: string;
5
+ }>;
6
+ export declare class TestType extends TestType_base {
7
+ }
8
+ export {};
9
+ //# sourceMappingURL=types.d.ts.map