@dxos/functions 0.8.1 → 0.8.2-main.12df754
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.
- package/dist/lib/browser/{chunk-RVSG6WTL.mjs → chunk-2YE6S7XY.mjs} +3 -1
- package/dist/lib/{node-esm/chunk-HBD2FZXO.mjs.map → browser/chunk-2YE6S7XY.mjs.map} +3 -3
- package/dist/lib/browser/{chunk-HI7YZO2K.mjs → chunk-7CHDHCV3.mjs} +6 -6
- package/dist/lib/browser/chunk-7CHDHCV3.mjs.map +7 -0
- package/dist/lib/browser/index.mjs +7 -5
- package/dist/lib/browser/index.mjs.map +2 -2
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/browser/testing/index.mjs +2 -2
- package/dist/lib/browser/types/index.mjs +3 -1
- package/dist/lib/node/{chunk-RXMCVAMJ.cjs → chunk-FBIUZ7SD.cjs} +15 -15
- package/dist/lib/node/chunk-FBIUZ7SD.cjs.map +7 -0
- package/dist/lib/node/{chunk-DSUGRAAL.cjs → chunk-SV5NRE5L.cjs} +7 -4
- package/dist/lib/node/{chunk-DSUGRAAL.cjs.map → chunk-SV5NRE5L.cjs.map} +3 -3
- package/dist/lib/node/index.cjs +32 -30
- package/dist/lib/node/index.cjs.map +2 -2
- package/dist/lib/node/meta.json +1 -1
- package/dist/lib/node/testing/index.cjs +7 -7
- package/dist/lib/node/types/index.cjs +24 -22
- package/dist/lib/node/types/index.cjs.map +2 -2
- package/dist/lib/node-esm/{chunk-HBD2FZXO.mjs → chunk-3XMJFSID.mjs} +3 -1
- package/dist/lib/{browser/chunk-RVSG6WTL.mjs.map → node-esm/chunk-3XMJFSID.mjs.map} +3 -3
- package/dist/lib/node-esm/{chunk-SQSJO5HI.mjs → chunk-C6YINTWG.mjs} +6 -6
- package/dist/lib/node-esm/chunk-C6YINTWG.mjs.map +7 -0
- package/dist/lib/node-esm/index.mjs +7 -5
- package/dist/lib/node-esm/index.mjs.map +2 -2
- package/dist/lib/node-esm/meta.json +1 -1
- package/dist/lib/node-esm/testing/index.mjs +2 -2
- package/dist/lib/node-esm/types/index.mjs +3 -1
- package/dist/types/src/function/function-registry.d.ts.map +1 -1
- package/dist/types/src/handler.d.ts +4 -3
- package/dist/types/src/handler.d.ts.map +1 -1
- package/dist/types/src/trigger/trigger-registry.d.ts.map +1 -1
- package/dist/types/src/types/url.d.ts +6 -0
- package/dist/types/src/types/url.d.ts.map +1 -1
- package/package.json +19 -18
- package/src/function/function-registry.test.ts +3 -3
- package/src/function/function-registry.ts +2 -2
- package/src/handler.ts +4 -3
- package/src/runtime/scheduler.test.ts +2 -2
- package/src/testing/functions-integration.test.ts +4 -4
- package/src/trigger/trigger-registry.test.ts +6 -6
- package/src/trigger/trigger-registry.ts +2 -2
- package/src/types/url.ts +5 -0
- package/dist/lib/browser/chunk-HI7YZO2K.mjs.map +0 -7
- package/dist/lib/node/chunk-RXMCVAMJ.cjs.map +0 -7
- package/dist/lib/node-esm/chunk-SQSJO5HI.mjs.map +0 -7
|
@@ -16,15 +16,15 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
16
16
|
return to;
|
|
17
17
|
};
|
|
18
18
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
-
var
|
|
20
|
-
__export(
|
|
19
|
+
var chunk_FBIUZ7SD_exports = {};
|
|
20
|
+
__export(chunk_FBIUZ7SD_exports, {
|
|
21
21
|
FunctionRegistry: () => FunctionRegistry,
|
|
22
22
|
TriggerRegistry: () => TriggerRegistry,
|
|
23
23
|
createSubscriptionTrigger: () => createSubscriptionTrigger,
|
|
24
24
|
createTimerTrigger: () => createTimerTrigger
|
|
25
25
|
});
|
|
26
|
-
module.exports = __toCommonJS(
|
|
27
|
-
var
|
|
26
|
+
module.exports = __toCommonJS(chunk_FBIUZ7SD_exports);
|
|
27
|
+
var import_chunk_SV5NRE5L = require("./chunk-SV5NRE5L.cjs");
|
|
28
28
|
var import_async = require("@dxos/async");
|
|
29
29
|
var import_echo = require("@dxos/client/echo");
|
|
30
30
|
var import_context = require("@dxos/context");
|
|
@@ -85,14 +85,14 @@ var FunctionRegistry = class extends import_context.Resource {
|
|
|
85
85
|
if (!functions?.length) {
|
|
86
86
|
return;
|
|
87
87
|
}
|
|
88
|
-
if (!space.db.graph.schemaRegistry.hasSchema(
|
|
88
|
+
if (!space.db.graph.schemaRegistry.hasSchema(import_chunk_SV5NRE5L.FunctionDef)) {
|
|
89
89
|
space.db.graph.schemaRegistry.addSchema([
|
|
90
|
-
|
|
90
|
+
import_chunk_SV5NRE5L.FunctionDef
|
|
91
91
|
]);
|
|
92
92
|
}
|
|
93
|
-
const { objects: existing } = await space.db.query(import_echo.Filter.schema(
|
|
93
|
+
const { objects: existing } = await space.db.query(import_echo.Filter.schema(import_chunk_SV5NRE5L.FunctionDef)).run();
|
|
94
94
|
const { added } = (0, import_util.diff)(existing, functions, (a, b) => a.uri === b.uri);
|
|
95
|
-
added.forEach((def) => space.db.add((0, import_echo.
|
|
95
|
+
added.forEach((def) => space.db.add((0, import_echo.live)(import_chunk_SV5NRE5L.FunctionDef, def)));
|
|
96
96
|
if (added.length > 0) {
|
|
97
97
|
await space.db.flush({
|
|
98
98
|
indexes: true,
|
|
@@ -118,7 +118,7 @@ var FunctionRegistry = class extends import_context.Resource {
|
|
|
118
118
|
if (this._ctx.disposed) {
|
|
119
119
|
break;
|
|
120
120
|
}
|
|
121
|
-
this._ctx.onDispose(space.db.query(import_echo.Filter.schema(
|
|
121
|
+
this._ctx.onDispose(space.db.query(import_echo.Filter.schema(import_chunk_SV5NRE5L.FunctionDef)).subscribe(({ objects }) => {
|
|
122
122
|
const { added } = (0, import_util.diff)(registered, objects, (a, b) => a.uri === b.uri);
|
|
123
123
|
if (added.length > 0) {
|
|
124
124
|
registered.push(...added);
|
|
@@ -337,9 +337,9 @@ var TriggerRegistry = class extends import_context2.Resource {
|
|
|
337
337
|
if (!manifest.triggers?.length) {
|
|
338
338
|
return;
|
|
339
339
|
}
|
|
340
|
-
if (!space.db.graph.schemaRegistry.hasSchema(
|
|
340
|
+
if (!space.db.graph.schemaRegistry.hasSchema(import_chunk_SV5NRE5L.FunctionTrigger)) {
|
|
341
341
|
space.db.graph.schemaRegistry.addSchema([
|
|
342
|
-
|
|
342
|
+
import_chunk_SV5NRE5L.FunctionTrigger
|
|
343
343
|
]);
|
|
344
344
|
}
|
|
345
345
|
const manifestTriggers = manifest.triggers.map((trigger) => {
|
|
@@ -353,11 +353,11 @@ var TriggerRegistry = class extends import_context2.Resource {
|
|
|
353
353
|
].join(":"))
|
|
354
354
|
];
|
|
355
355
|
}
|
|
356
|
-
return (0, import_echo3.
|
|
356
|
+
return (0, import_echo3.live)(import_chunk_SV5NRE5L.FunctionTrigger, trigger, {
|
|
357
357
|
keys
|
|
358
358
|
});
|
|
359
359
|
});
|
|
360
|
-
const { objects: existing } = await space.db.query(import_echo3.Filter.schema(
|
|
360
|
+
const { objects: existing } = await space.db.query(import_echo3.Filter.schema(import_chunk_SV5NRE5L.FunctionTrigger)).run();
|
|
361
361
|
const { added } = (0, import_util2.diff)(existing, manifestTriggers, import_echo3.compareForeignKeys);
|
|
362
362
|
added.forEach((trigger) => {
|
|
363
363
|
space.db.add(trigger);
|
|
@@ -392,7 +392,7 @@ var TriggerRegistry = class extends import_context2.Resource {
|
|
|
392
392
|
if (this._ctx.disposed) {
|
|
393
393
|
break;
|
|
394
394
|
}
|
|
395
|
-
this._ctx.onDispose(space.db.query(import_echo3.Filter.schema(
|
|
395
|
+
this._ctx.onDispose(space.db.query(import_echo3.Filter.schema(import_chunk_SV5NRE5L.FunctionTrigger)).subscribe(async ({ objects: current }) => {
|
|
396
396
|
import_log4.log.info("update", {
|
|
397
397
|
space: space.key,
|
|
398
398
|
registered: registered.length,
|
|
@@ -493,4 +493,4 @@ var TriggerRegistry = class extends import_context2.Resource {
|
|
|
493
493
|
createSubscriptionTrigger,
|
|
494
494
|
createTimerTrigger
|
|
495
495
|
});
|
|
496
|
-
//# sourceMappingURL=chunk-
|
|
496
|
+
//# sourceMappingURL=chunk-FBIUZ7SD.cjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/function/function-registry.ts", "../../../src/trigger/type/subscription-trigger.ts", "../../../src/trigger/type/timer-trigger.ts", "../../../src/trigger/trigger-registry.ts"],
|
|
4
|
+
"sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { Event } from '@dxos/async';\nimport { type Client } from '@dxos/client';\nimport { live, Filter, type Space } from '@dxos/client/echo';\nimport { type Context, Resource } from '@dxos/context';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { ComplexMap, diff } from '@dxos/util';\n\nimport { FunctionDef, type FunctionManifest } from '../types';\n\nexport type FunctionsRegisteredEvent = {\n space: Space;\n added: FunctionDef[];\n};\n\nexport class FunctionRegistry extends Resource {\n private readonly _functionBySpaceKey = new ComplexMap<PublicKey, FunctionDef[]>(PublicKey.hash);\n\n public readonly registered = new Event<FunctionsRegisteredEvent>();\n\n constructor(private readonly _client: Client) {\n super();\n }\n\n public getFunctions(space: Space): FunctionDef[] {\n return this._functionBySpaceKey.get(space.key) ?? [];\n }\n\n public getUniqueByUri(): FunctionDef[] {\n const uniqueByUri = [...this._functionBySpaceKey.values()]\n .flatMap((defs) => defs)\n .reduce((acc, v) => {\n acc.set(v.uri, v);\n return acc;\n }, new Map<string, FunctionDef>());\n return [...uniqueByUri.values()];\n }\n\n /**\n * Loads function definitions from the manifest into the space.\n * We first load all the definitions from the space to deduplicate by functionId.\n */\n public async register(space: Space, functions: FunctionManifest['functions']): Promise<void> {\n log('register', { space: space.key, functions: functions?.length ?? 0 });\n if (!functions?.length) {\n return;\n }\n if (!space.db.graph.schemaRegistry.hasSchema(FunctionDef)) {\n space.db.graph.schemaRegistry.addSchema([FunctionDef]);\n }\n\n // Sync definitions.\n const { objects: existing } = await space.db.query(Filter.schema(FunctionDef)).run();\n const { added } = diff(existing, functions, (a, b) => a.uri === b.uri);\n // TODO(burdon): Update existing templates.\n added.forEach((def) => space.db.add(live(FunctionDef, def)));\n\n if (added.length > 0) {\n await space.db.flush({ indexes: true, updates: true });\n }\n }\n\n protected override async _open(): Promise<void> {\n log.info('opening...');\n const spacesSubscription = this._client.spaces.subscribe(async (spaces) => {\n for (const space of spaces) {\n if (this._functionBySpaceKey.has(space.key)) {\n continue;\n }\n\n const registered: FunctionDef[] = [];\n this._functionBySpaceKey.set(space.key, registered);\n await space.waitUntilReady();\n if (this._ctx.disposed) {\n break;\n }\n\n // Subscribe to updates.\n this._ctx.onDispose(\n space.db.query(Filter.schema(FunctionDef)).subscribe(({ objects }) => {\n const { added } = diff(registered, objects, (a, b) => a.uri === b.uri);\n // TODO(burdon): Update and remove.\n if (added.length > 0) {\n registered.push(...added);\n this.registered.emit({ space, added });\n }\n }),\n );\n }\n });\n\n // TODO(burdon): API: Normalize unsubscribe methods.\n this._ctx.onDispose(() => spacesSubscription.unsubscribe());\n }\n\n protected override async _close(_: Context): Promise<void> {\n log.info('closing...');\n this._functionBySpaceKey.clear();\n }\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { debounce, UpdateScheduler } from '@dxos/async';\nimport { Filter, type Space } from '@dxos/client/echo';\nimport { type Context } from '@dxos/context';\nimport { createSubscription, type Query } from '@dxos/echo-db';\nimport { log } from '@dxos/log';\n\nimport type { SubscriptionTrigger } from '../../types';\nimport { type TriggerCallback, type TriggerFactory } from '../trigger-registry';\n\nexport const createSubscriptionTrigger: TriggerFactory<SubscriptionTrigger> = async (\n ctx: Context,\n space: Space,\n spec: SubscriptionTrigger,\n callback: TriggerCallback,\n) => {\n const objectIds = new Set<string>();\n const task = new UpdateScheduler(\n ctx,\n async () => {\n if (objectIds.size > 0) {\n const objects = Array.from(objectIds);\n objectIds.clear();\n await callback({ objects });\n }\n },\n { maxFrequency: 4 },\n );\n\n // TODO(burdon): Factor out diff.\n // TODO(burdon): Don't fire initially?\n // TODO(burdon): Create queue. Only allow one invocation per trigger at a time?\n const subscriptions: (() => void)[] = [];\n const subscription = createSubscription(({ added, updated }) => {\n const sizeBefore = objectIds.size;\n for (const object of added) {\n objectIds.add(object.id);\n }\n for (const object of updated) {\n objectIds.add(object.id);\n }\n if (objectIds.size > sizeBefore) {\n log.info('updated', { added: added.length, updated: updated.length });\n task.trigger();\n }\n });\n\n subscriptions.push(() => subscription.unsubscribe());\n\n // TODO(burdon): Disable trigger if keeps failing.\n const { filter, options: { deep, delay } = {} } = spec;\n const update = ({ objects }: Query) => {\n log.info('update', { objects: objects.length });\n subscription.update(objects);\n\n // TODO(burdon): Hack to monitor changes to Document's text object.\n if (deep) {\n // TODO(dmaretskyi): Removed to not have dependency on markdown-plugin.\n // for (const object of objects) {\n // const content = object.content;\n // if (content instanceof TextType) {\n // subscriptions.push(getObjectCore(content).updates.on(debounce(() => subscription.update([object]), 1_000)));\n // }\n // }\n }\n };\n\n // TODO(burdon): OR not working.\n // TODO(burdon): [Bug]: all callbacks are fired on the first mutation.\n // TODO(burdon): [Bug]: not updated when document is deleted (either top or hierarchically).\n log.info('subscription', { filter });\n // const query = triggerCtx.space.db.query(Filter.or(filter.map(({ type, props }) => Filter.typename(type, props))));\n if (filter.type) {\n const query = space.db.query(Filter.typename(filter.type, filter.props));\n subscriptions.push(query.subscribe(delay ? debounce(update, delay) : update));\n }\n\n ctx.onDispose(() => {\n subscriptions.forEach((unsubscribe) => unsubscribe());\n });\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { parseCronExpression } from 'cron-schedule';\n\nimport { DeferredTask } from '@dxos/async';\nimport { type Space } from '@dxos/client/echo';\nimport { type Context } from '@dxos/context';\nimport { log } from '@dxos/log';\n\nimport type { TimerTrigger } from '../../types';\nimport { type TriggerCallback, type TriggerFactory } from '../trigger-registry';\n\nexport const createTimerTrigger: TriggerFactory<TimerTrigger> = async (\n ctx: Context,\n space: Space,\n spec: TimerTrigger,\n callback: TriggerCallback,\n) => {\n const task = new DeferredTask(ctx, async () => {\n await callback({});\n });\n\n let last = 0;\n let run = 0;\n const schedule = parseCronExpression(spec.cron);\n const getRunTimeout = () => Date.now() - schedule.getNextDate().getTime();\n const runCron = () => {\n if (ctx.disposed) {\n return;\n }\n // TODO(burdon): Check greater than 30s (use cron-parser).\n const now = Date.now();\n const delta = last ? now - last : 0;\n last = now;\n\n run++;\n log.info('tick', { space: space.key.truncate(), count: run, delta });\n task.schedule();\n\n timeout = setTimeout(runCron, getRunTimeout());\n };\n\n let timeout = setTimeout(runCron, getRunTimeout());\n\n ctx.onDispose(() => clearTimeout(timeout));\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { Event } from '@dxos/async';\nimport { type Client } from '@dxos/client';\nimport { live, Filter, getMeta, type Space, compareForeignKeys } from '@dxos/client/echo';\nimport { Context, Resource } from '@dxos/context';\nimport { ECHO_ATTR_META, foreignKey } from '@dxos/echo-schema';\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { ComplexMap, diff } from '@dxos/util';\n\nimport { createSubscriptionTrigger, createTimerTrigger } from './type';\nimport { type FunctionManifest, FunctionTrigger, type TriggerKind, type TriggerType } from '../types';\n\ntype ResponseCode = number;\n\nexport type TriggerCallback = (args: object) => Promise<ResponseCode>;\n\n// TODO(burdon): Make object?\nexport type TriggerFactory<Spec extends TriggerType, Options = any> = (\n ctx: Context,\n space: Space,\n spec: Spec,\n callback: TriggerCallback,\n options?: Options,\n) => Promise<void>;\n\nexport type TriggerFactoryMap = Partial<Record<TriggerKind, TriggerFactory<any>>>;\n\nconst triggerFactory: TriggerFactoryMap = {\n timer: createTimerTrigger,\n // TODO(burdon): Cannot use in browser.\n // webhook: createWebhookTrigger,\n subscription: createSubscriptionTrigger,\n};\n\nexport type TriggerEvent = {\n space: Space;\n triggers: FunctionTrigger[];\n};\n\ntype RegisteredTrigger = {\n activationCtx?: Context;\n trigger: FunctionTrigger;\n};\n\nexport class TriggerRegistry extends Resource {\n private readonly _triggersBySpaceKey = new ComplexMap<PublicKey, RegisteredTrigger[]>(PublicKey.hash);\n\n public readonly registered = new Event<TriggerEvent>();\n public readonly removed = new Event<TriggerEvent>();\n\n constructor(\n private readonly _client: Client,\n private readonly _options?: TriggerFactoryMap,\n ) {\n super();\n }\n\n public getActiveTriggers(space: Space): FunctionTrigger[] {\n return this._getTriggers(space, (t) => t.activationCtx != null);\n }\n\n public getInactiveTriggers(space: Space): FunctionTrigger[] {\n return this._getTriggers(space, (t) => t.activationCtx == null);\n }\n\n /**\n * Set callback for trigger.\n */\n public async activate(space: Space, trigger: FunctionTrigger, callback: TriggerCallback): Promise<void> {\n log('activate', { space: space.key, trigger });\n\n const activationCtx = new Context({ name: `FunctionTrigger-${trigger.function}` });\n this._ctx.onDispose(() => activationCtx.dispose());\n const registeredTrigger = this._triggersBySpaceKey.get(space.key)?.find((reg) => reg.trigger.id === trigger.id);\n invariant(registeredTrigger, `Trigger is not registered: ${trigger.function}`);\n registeredTrigger.activationCtx = activationCtx;\n\n try {\n // Create trigger.\n invariant(trigger.spec);\n const options = this._options?.[trigger.spec.type];\n const createTrigger = triggerFactory[trigger.spec.type];\n invariant(createTrigger, `Trigger factory not found: ${trigger.spec.type}`);\n await createTrigger(activationCtx, space, trigger.spec, callback, options);\n } catch (err) {\n delete registeredTrigger.activationCtx;\n throw err;\n }\n }\n\n /**\n * Loads triggers from the manifest into the space.\n */\n public async register(space: Space, manifest: FunctionManifest): Promise<void> {\n log('register', { space: space.key });\n if (!manifest.triggers?.length) {\n return;\n }\n\n if (!space.db.graph.schemaRegistry.hasSchema(FunctionTrigger)) {\n space.db.graph.schemaRegistry.addSchema([FunctionTrigger]);\n }\n\n // Create FK to enable syncing if none are set (NOTE: Possible collision).\n const manifestTriggers = manifest.triggers.map((trigger) => {\n let keys = trigger[ECHO_ATTR_META]?.keys;\n delete trigger[ECHO_ATTR_META];\n if (!keys?.length) {\n keys = [foreignKey('manifest', [trigger.function, trigger.spec?.type].join(':'))];\n }\n\n return live(FunctionTrigger, trigger, { keys });\n });\n\n // Sync triggers.\n const { objects: existing } = await space.db.query(Filter.schema(FunctionTrigger)).run();\n const { added } = diff(existing, manifestTriggers, compareForeignKeys);\n\n // TODO(burdon): Update existing.\n added.forEach((trigger) => {\n space.db.add(trigger);\n log.info('added', { meta: getMeta(trigger) });\n });\n\n if (added.length > 0) {\n await space.db.flush();\n }\n }\n\n protected override async _open(): Promise<void> {\n log.info('open...');\n const spaceListSubscription = this._client.spaces.subscribe(async (spaces) => {\n for (const space of spaces) {\n if (this._triggersBySpaceKey.has(space.key)) {\n continue;\n }\n\n const registered: RegisteredTrigger[] = [];\n this._triggersBySpaceKey.set(space.key, registered);\n await space.waitUntilReady();\n if (this._ctx.disposed) {\n break;\n }\n\n // Subscribe to updates.\n this._ctx.onDispose(\n space.db.query(Filter.schema(FunctionTrigger)).subscribe(async ({ objects: current }) => {\n log.info('update', { space: space.key, registered: registered.length, current: current.length });\n await this._handleRemovedTriggers(space, current, registered);\n this._handleNewTriggers(space, current, registered);\n }),\n );\n }\n });\n\n this._ctx.onDispose(() => spaceListSubscription.unsubscribe());\n log.info('opened');\n }\n\n protected override async _close(_: Context): Promise<void> {\n log.info('close...');\n this._triggersBySpaceKey.clear();\n log.info('closed');\n }\n\n private _handleNewTriggers(space: Space, current: FunctionTrigger[], registered: RegisteredTrigger[]) {\n const added = current.filter((candidate) => {\n return candidate.enabled && registered.find((reg) => reg.trigger.id === candidate.id) == null;\n });\n\n if (added.length > 0) {\n const newRegisteredTriggers: RegisteredTrigger[] = added.map((trigger) => ({ trigger }));\n registered.push(...newRegisteredTriggers);\n log.info('added', () => ({\n spaceKey: space.key,\n triggers: added.map((trigger) => trigger.function),\n }));\n\n this.registered.emit({ space, triggers: added });\n }\n }\n\n private async _handleRemovedTriggers(\n space: Space,\n current: FunctionTrigger[],\n registered: RegisteredTrigger[],\n ): Promise<void> {\n const removed: FunctionTrigger[] = [];\n for (let i = registered.length - 1; i >= 0; i--) {\n const wasRemoved =\n current.filter((trigger) => trigger.enabled).find((trigger) => trigger.id === registered[i].trigger.id) == null;\n if (wasRemoved) {\n const unregistered = registered.splice(i, 1)[0];\n await unregistered.activationCtx?.dispose();\n removed.push(unregistered.trigger);\n }\n }\n\n if (removed.length > 0) {\n log.info('removed', () => ({\n spaceKey: space.key,\n triggers: removed.map((trigger) => trigger.function),\n }));\n\n this.removed.emit({ space, triggers: removed });\n }\n }\n\n private _getTriggers(space: Space, predicate: (trigger: RegisteredTrigger) => boolean): FunctionTrigger[] {\n const allSpaceTriggers = this._triggersBySpaceKey.get(space.key) ?? [];\n return allSpaceTriggers.filter(predicate).map((trigger) => trigger.trigger);\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,mBAAsB;AAEtB,kBAAyC;AACzC,qBAAuC;AACvC,kBAA0B;AAC1B,iBAAoB;AACpB,kBAAiC;ACNjC,IAAAA,gBAA0C;AAC1C,IAAAC,eAAmC;AAEnC,qBAA+C;AAC/C,IAAAC,cAAoB;ACJpB,2BAAoC;AAEpC,IAAAF,gBAA6B;AAG7B,IAAAE,cAAoB;ACLpB,IAAAF,gBAAsB;AAEtB,IAAAC,eAAsE;AACtE,IAAAE,kBAAkC;AAClC,yBAA2C;AAC3C,uBAA0B;AAC1B,IAAAC,eAA0B;AAC1B,IAAAF,cAAoB;AACpB,IAAAG,eAAiC;;AHO1B,IAAMC,mBAAN,cAA+BC,wBAAAA;EAKpCC,YAA6BC,SAAiB;AAC5C,UAAK;SADsBA,UAAAA;SAJZC,sBAAsB,IAAIC,uBAAqCC,sBAAUC,IAAI;SAE9EC,aAAa,IAAIC,mBAAAA;EAIjC;EAEOC,aAAaC,OAA6B;AAC/C,WAAO,KAAKP,oBAAoBQ,IAAID,MAAME,GAAG,KAAK,CAAA;EACpD;EAEOC,iBAAgC;AACrC,UAAMC,cAAc;SA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qJ,CAAAA,EAAGtE,QAAQD,EAAE,KAAK;AAC7G,UAAIwE,YAAY;AACd,cAAMC,eAAevJ,WAAWwJ,OAAOH,GAAG,CAAA,EAAG,CAAA;AAC7C,cAAME,aAAanC,eAAeM,QAAAA;AAClCV,gBAAQ1D,KAAKiG,aAAaxE,OAAO;MACnC;IACF;AAEA,QAAIiC,QAAQ5F,SAAS,GAAG;AACtBD,kBAAAA,IAAI0B,KAAK,WAAW,OAAO;QACzBuG,UAAUjJ,MAAME;QAChB6H,UAAUlB,QAAQqB,IAAI,CAACtD,YAAYA,QAAQ0C,QAAQ;MACrD,IAAA;;;;;;AAEA,WAAKT,QAAQzD,KAAK;QAAEpD;QAAO+H,UAAUlB;MAAQ,CAAA;IAC/C;EACF;EAEQE,aAAa/G,OAAcsJ,WAAuE;AACxG,UAAMC,mBAAmB,KAAK3C,oBAAoB3G,IAAID,MAAME,GAAG,KAAK,CAAA;AACpE,WAAOqJ,iBAAiB1E,OAAOyE,SAAAA,EAAWpB,IAAI,CAACtD,YAAYA,QAAQA,OAAO;EAC5E;AACF;",
|
|
6
|
+
"names": ["import_async", "import_echo", "import_log", "import_context", "import_keys", "import_util", "FunctionRegistry", "Resource", "constructor", "_client", "_functionBySpaceKey", "ComplexMap", "PublicKey", "hash", "registered", "Event", "getFunctions", "space", "get", "key", "getUniqueByUri", "uniqueByUri", "values", "flatMap", "defs", "reduce", "acc", "v", "set", "uri", "Map", "register", "functions", "log", "length", "db", "graph", "schemaRegistry", "hasSchema", "FunctionDef", "addSchema", "objects", "existing", "query", "Filter", "schema", "run", "added", "diff", "a", "b", "forEach", "def", "add", "live", "flush", "indexes", "updates", "_open", "info", "spacesSubscription", "spaces", "subscribe", "has", "waitUntilReady", "_ctx", "disposed", "onDispose", "push", "emit", "unsubscribe", "_close", "_", "clear", "createSubscriptionTrigger", "ctx", "spec", "callback", "objectIds", "Set", "task", "UpdateScheduler", "size", "Array", "from", "maxFrequency", "subscriptions", "subscription", "createSubscription", "updated", "sizeBefore", "object", "id", "trigger", "filter", "options", "deep", "delay", "update", "type", "typename", "props", "debounce", "createTimerTrigger", "DeferredTask", "last", "schedule", "parseCronExpression", "cron", "getRunTimeout", "Date", "now", "getNextDate", "getTime", "runCron", "delta", "truncate", "count", "timeout", "setTimeout", "clearTimeout", "triggerFactory", "timer", "TriggerRegistry", "_options", "_triggersBySpaceKey", "removed", "getActiveTriggers", "_getTriggers", "t", "activationCtx", "getInactiveTriggers", "activate", "Context", "name", "function", "dispose", "registeredTrigger", "find", "reg", "invariant", "createTrigger", "err", "manifest", "triggers", "FunctionTrigger", "manifestTriggers", "map", "keys", "ECHO_ATTR_META", "foreignKey", "join", "compareForeignKeys", "meta", "getMeta", "spaceListSubscription", "current", "_handleRemovedTriggers", "_handleNewTriggers", "candidate", "enabled", "newRegisteredTriggers", "spaceKey", "i", "wasRemoved", "unregistered", "splice", "predicate", "allSpaceTriggers"]
|
|
7
|
+
}
|
|
@@ -16,8 +16,8 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
16
16
|
return to;
|
|
17
17
|
};
|
|
18
18
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
-
var
|
|
20
|
-
__export(
|
|
19
|
+
var chunk_SV5NRE5L_exports = {};
|
|
20
|
+
__export(chunk_SV5NRE5L_exports, {
|
|
21
21
|
FUNCTIONS_PRESET_META_KEY: () => FUNCTIONS_PRESET_META_KEY,
|
|
22
22
|
FUNCTION_TYPES: () => FUNCTION_TYPES,
|
|
23
23
|
FunctionDef: () => FunctionDef,
|
|
@@ -38,9 +38,10 @@ __export(chunk_DSUGRAAL_exports, {
|
|
|
38
38
|
createInvocationSpans: () => createInvocationSpans,
|
|
39
39
|
getInvocationUrl: () => getInvocationUrl,
|
|
40
40
|
getUserFunctionUrlInMetadata: () => getUserFunctionUrlInMetadata,
|
|
41
|
+
makeFunctionUrl: () => makeFunctionUrl,
|
|
41
42
|
setUserFunctionUrlInMetadata: () => setUserFunctionUrlInMetadata
|
|
42
43
|
});
|
|
43
|
-
module.exports = __toCommonJS(
|
|
44
|
+
module.exports = __toCommonJS(chunk_SV5NRE5L_exports);
|
|
44
45
|
var import_echo_schema = require("@dxos/echo-schema");
|
|
45
46
|
var import_schema = require("@dxos/schema");
|
|
46
47
|
var import_echo_schema2 = require("@dxos/echo-schema");
|
|
@@ -356,6 +357,7 @@ var setUserFunctionUrlInMetadata = (meta, functionUrl) => {
|
|
|
356
357
|
});
|
|
357
358
|
}
|
|
358
359
|
};
|
|
360
|
+
var makeFunctionUrl = (spaceId, fn) => `/${spaceId}/${fn.functionId}`;
|
|
359
361
|
var getInvocationUrl = (functionUrl, edgeUrl, options = {}) => {
|
|
360
362
|
const baseUrl = new URL("functions/", edgeUrl);
|
|
361
363
|
const relativeUrl = functionUrl.replace(/^\//, "");
|
|
@@ -387,6 +389,7 @@ var getInvocationUrl = (functionUrl, edgeUrl, options = {}) => {
|
|
|
387
389
|
createInvocationSpans,
|
|
388
390
|
getInvocationUrl,
|
|
389
391
|
getUserFunctionUrlInMetadata,
|
|
392
|
+
makeFunctionUrl,
|
|
390
393
|
setUserFunctionUrlInMetadata
|
|
391
394
|
});
|
|
392
|
-
//# sourceMappingURL=chunk-
|
|
395
|
+
//# sourceMappingURL=chunk-SV5NRE5L.cjs.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/types/schema.ts", "../../../src/types/types.ts", "../../../src/types/trace.ts", "../../../src/types/url.ts"],
|
|
4
|
-
"sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { EchoObject, JsonSchemaType, LabelAnnotationId, Ref, S, TypedObject } from '@dxos/echo-schema';\nimport { TextType } from '@dxos/schema';\n\n/**\n * Source script.\n */\nexport const ScriptType = S.Struct({\n name: S.optional(S.String),\n description: S.optional(S.String),\n // TODO(burdon): Change to hash of deployed content.\n // Whether source has changed since last deploy.\n changed: S.optional(S.Boolean),\n source: Ref(TextType),\n})\n .annotations({ [LabelAnnotationId]: 'name' })\n .pipe(EchoObject({ typename: 'dxos.org/type/Script', version: '0.1.0' }));\n\nexport type ScriptType = S.Schema.Type<typeof ScriptType>;\n\n/**\n * Function deployment.\n */\nexport class FunctionType extends TypedObject({\n typename: 'dxos.org/type/Function',\n version: '0.1.0',\n})({\n // TODO(burdon): Rename to id/uri?\n name: S.NonEmptyString,\n version: S.String,\n\n description: S.optional(S.String),\n\n // Reference to a source script if it exists within ECHO.\n // TODO(burdon): Don't ref ScriptType directly (core).\n source: S.optional(Ref(ScriptType)),\n\n inputSchema: S.optional(JsonSchemaType),\n outputSchema: S.optional(JsonSchemaType),\n\n // Local binding to a function name.\n binding: S.optional(S.String),\n}) {}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { AST, OptionsAnnotationId, RawObject, S, TypedObject, DXN } from '@dxos/echo-schema';\n\n/**\n * Type discriminator for TriggerType.\n * Every spec has a type field of type TriggerKind that we can use to understand which type we're working with.\n * https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions\n */\nexport enum TriggerKind {\n Timer = 'timer',\n Webhook = 'webhook',\n Subscription = 'subscription',\n Email = 'email',\n Queue = 'queue',\n}\n\n// TODO(burdon): Rename prop kind.\nconst typeLiteralAnnotations = { [AST.TitleAnnotationId]: 'Type' };\n\n/**\n * Cron timer.\n */\nconst TimerTriggerSchema = S.Struct({\n type: S.Literal(TriggerKind.Timer).annotations(typeLiteralAnnotations),\n cron: S.String.annotations({\n [AST.TitleAnnotationId]: 'Cron',\n [AST.ExamplesAnnotationId]: ['0 0 * * *'],\n }),\n}).pipe(S.mutable);\n\nexport type TimerTrigger = S.Schema.Type<typeof TimerTriggerSchema>;\n\nconst EmailTriggerSchema = S.Struct({\n type: S.Literal(TriggerKind.Email).annotations(typeLiteralAnnotations),\n}).pipe(S.mutable);\n\nexport type EmailTrigger = S.Schema.Type<typeof EmailTriggerSchema>;\n\nconst QueueTriggerSchema = S.Struct({\n type: S.Literal(TriggerKind.Queue).annotations(typeLiteralAnnotations),\n queue: DXN,\n}).pipe(S.mutable);\n\nexport type QueueTrigger = S.Schema.Type<typeof QueueTriggerSchema>;\n\n/**\n * Webhook.\n */\nconst WebhookTriggerSchema = S.Struct({\n type: S.Literal(TriggerKind.Webhook).annotations(typeLiteralAnnotations),\n method: S.optional(\n S.String.annotations({\n [AST.TitleAnnotationId]: 'Method',\n [OptionsAnnotationId]: ['GET', 'POST'],\n }),\n ),\n port: S.optional(\n S.Number.annotations({\n [AST.TitleAnnotationId]: 'Port',\n }),\n ),\n}).pipe(S.mutable);\n\nexport type WebhookTrigger = S.Schema.Type<typeof WebhookTriggerSchema>;\n\n// TODO(burdon): Use ECHO definition (from https://github.com/dxos/dxos/pull/8233).\nconst QuerySchema = S.Struct({\n type: S.optional(S.String.annotations({ [AST.TitleAnnotationId]: 'Type' })),\n props: S.optional(S.Record({ key: S.String, value: S.Any })),\n}).annotations({ [AST.TitleAnnotationId]: 'Query' });\n\n/**\n * Subscription.\n */\nconst SubscriptionTriggerSchema = S.Struct({\n type: S.Literal(TriggerKind.Subscription).annotations(typeLiteralAnnotations),\n // TODO(burdon): Define query DSL (from ECHO). Reconcile with Table.Query.\n filter: QuerySchema,\n options: S.optional(\n S.Struct({\n // Watch changes to object (not just creation).\n deep: S.optional(S.Boolean.annotations({ [AST.TitleAnnotationId]: 'Nested' })),\n // Debounce changes (delay in ms).\n delay: S.optional(S.Number.annotations({ [AST.TitleAnnotationId]: 'Delay' })),\n }).annotations({ [AST.TitleAnnotationId]: 'Options' }),\n ),\n}).pipe(S.mutable);\n\nexport type SubscriptionTrigger = S.Schema.Type<typeof SubscriptionTriggerSchema>;\n\n/**\n * Trigger schema (discriminated union).\n */\nexport const TriggerSchema = S.Union(\n TimerTriggerSchema,\n WebhookTriggerSchema,\n SubscriptionTriggerSchema,\n EmailTriggerSchema,\n QueueTriggerSchema,\n).annotations({\n [AST.TitleAnnotationId]: 'Trigger',\n});\n\nexport type TriggerType = S.Schema.Type<typeof TriggerSchema>;\n\n/**\n * Function trigger.\n */\nexport const FunctionTriggerSchema = S.Struct({\n // TODO(burdon): What type does this reference.\n // TODO(wittjosiah): This should probably be a Ref?\n function: S.optional(S.String.annotations({ [AST.TitleAnnotationId]: 'Function' })),\n\n enabled: S.optional(S.Boolean.annotations({ [AST.TitleAnnotationId]: 'Enabled' })),\n\n // TODO(burdon): Flatten entire schema.\n spec: S.optional(TriggerSchema),\n\n // TODO(burdon): Get schema as partial from function.\n // TODO(wittjosiah): Rename to payload.\n // The `meta` property is merged into the event data passed to the function.\n meta: S.optional(S.mutable(S.Record({ key: S.String, value: S.Any }))),\n});\n\nexport type FunctionTriggerType = S.Schema.Type<typeof FunctionTriggerSchema>;\n\n/**\n * Function trigger.\n */\nexport class FunctionTrigger extends TypedObject({\n typename: 'dxos.org/type/FunctionTrigger',\n version: '0.1.0',\n})(FunctionTriggerSchema.fields) {}\n\n/**\n * Function definition.\n * @deprecated (Use dxos.org/type/Function)\n */\n// TODO(burdon): Reconcile with FunctionType.\nexport class FunctionDef extends TypedObject({\n typename: 'dxos.org/type/FunctionDef',\n version: '0.1.0',\n})({\n uri: S.String,\n description: S.optional(S.String),\n route: S.String,\n handler: S.String,\n}) {}\n\n/**\n * Function manifest file.\n */\nexport const FunctionManifestSchema = S.Struct({\n functions: S.optional(S.mutable(S.Array(RawObject(FunctionDef)))),\n triggers: S.optional(S.mutable(S.Array(RawObject(FunctionTrigger)))),\n});\n\nexport type FunctionManifest = S.Schema.Type<typeof FunctionManifestSchema>;\n\nexport const FUNCTION_TYPES = [FunctionDef, FunctionTrigger];\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { EchoObject, Expando, ObjectId, Ref, S } from '@dxos/echo-schema';\nimport { log } from '@dxos/log';\n\nimport { FunctionTrigger, type FunctionTriggerType } from './types';\n\nexport enum InvocationOutcome {\n SUCCESS = 'success',\n FAILURE = 'failure',\n PENDING = 'pending',\n}\n\n// TODO(burdon): Convert to extensible discriminated union of EDGE events.\nexport enum InvocationTraceEventType {\n START = 'start',\n END = 'end',\n}\n\nexport const TraceEventException = S.Struct({\n timestampMs: S.Number,\n message: S.String,\n name: S.String,\n stack: S.optional(S.String),\n});\nexport type TraceEventException = S.Schema.Type<typeof TraceEventException>;\n\nexport const InvocationTraceStartEvent = S.Struct({\n /**\n * Queue message id.\n */\n id: ObjectId,\n type: S.Literal(InvocationTraceEventType.START),\n /**\n * Invocation id, the same for invocation start and end events.\n */\n invocationId: ObjectId,\n /**\n * Event generation time.\n */\n timestampMs: S.Number,\n /**\n * Data passed to function / workflow as an argument.\n */\n // TODO(burdon): Input schema?\n input: S.Object,\n /**\n * Queue DXN for function/workflow invocation events.\n */\n // TODO(burdon): Need reference type for queue. vs. string?\n invocationTraceQueue: Ref(Expando),\n /**\n * DXN of the invoked function/workflow.\n */\n invocationTarget: Ref(Expando),\n /**\n * Present for automatic invocations.\n */\n trigger: S.optional(Ref(FunctionTrigger)),\n}).pipe(EchoObject({ typename: 'dxos.org/type/InvocationTraceStart', version: '0.1.0' }));\n\nexport type InvocationTraceStartEvent = S.Schema.Type<typeof InvocationTraceStartEvent>;\n\nexport const InvocationTraceEndEvent = S.Struct({\n /**\n * Trace event id.\n */\n id: ObjectId,\n type: S.Literal(InvocationTraceEventType.END),\n /**\n * Invocation id, will be the same for invocation start and end.\n */\n invocationId: ObjectId,\n /**\n * Event generation time.\n */\n // TODO(burdon): Remove ms suffix.\n timestampMs: S.Number,\n outcome: S.Enums(InvocationOutcome),\n exception: S.optional(TraceEventException),\n}).pipe(EchoObject({ typename: 'dxos.org/type/InvocationTraceEnd', version: '0.1.0' }));\n\nexport type InvocationTraceEndEvent = S.Schema.Type<typeof InvocationTraceEndEvent>;\n\nexport type InvocationTraceEvent = InvocationTraceStartEvent | InvocationTraceEndEvent;\n\nexport const TraceEventLog = S.Struct({\n timestampMs: S.Number,\n level: S.String,\n message: S.String,\n context: S.optional(S.Object),\n});\n\nexport const TraceEvent = S.Struct({\n id: ObjectId,\n // TODO(burdon): Need enum/numeric result (not string).\n outcome: S.String,\n truncated: S.Boolean,\n /**\n * Time when the event was persisted.\n */\n ingestionTimestampMs: S.Number,\n logs: S.Array(TraceEventLog),\n exceptions: S.Array(TraceEventException),\n}).pipe(EchoObject({ typename: 'dxos.org/type/TraceEvent', version: '0.1.0' }));\n\nexport type TraceEvent = S.Schema.Type<typeof TraceEvent>;\n\n/**\n * Deprecated InvocationTrace event format.\n * @deprecated\n */\n// TODO(burdon): Remove.\nexport type InvocationSpan = {\n id: string;\n timestampMs: number;\n outcome: InvocationOutcome;\n input: object;\n durationMs: number;\n invocationTraceQueue: Ref<Expando>;\n invocationTarget: Ref<Expando>;\n trigger?: Ref<FunctionTriggerType>;\n exception?: TraceEventException;\n};\n\nexport const createInvocationSpans = (items?: InvocationTraceEvent[]): InvocationSpan[] => {\n if (!items) {\n return [];\n }\n\n const eventsByInvocationId = new Map<string, { start?: InvocationTraceStartEvent; end?: InvocationTraceEndEvent }>();\n for (const event of items) {\n if (!('invocationId' in event)) {\n // Skip legacy format entries.\n continue;\n }\n\n const invocationId = event.invocationId;\n const entry = eventsByInvocationId.get(invocationId) || { start: undefined, end: undefined };\n if (event.type === InvocationTraceEventType.START) {\n entry.start = event as InvocationTraceStartEvent;\n } else if (event.type === InvocationTraceEventType.END) {\n entry.end = event as InvocationTraceEndEvent;\n }\n\n eventsByInvocationId.set(invocationId, entry);\n }\n\n const now = Date.now();\n const result: InvocationSpan[] = [];\n\n // Create spans for each invocation\n for (const [invocationId, { start, end }] of eventsByInvocationId.entries()) {\n if (!start) {\n // No start event, can't create a meaningful span\n log.warn('found end event without matching start', { invocationId });\n continue;\n }\n\n const isInProgress = end === undefined;\n\n result.push({\n id: invocationId,\n timestampMs: start.timestampMs,\n durationMs: isInProgress ? now - start.timestampMs : end!.timestampMs - start.timestampMs,\n outcome: end?.outcome ?? InvocationOutcome.PENDING,\n exception: end?.exception,\n input: start.input,\n invocationTraceQueue: start.invocationTraceQueue,\n invocationTarget: start.invocationTarget,\n trigger: start.trigger,\n });\n }\n\n return result;\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { type ObjectMeta } from '@dxos/echo-schema';\nimport { type SpaceId } from '@dxos/keys';\n\n// TODO: use URL scheme for source?\nconst FUNCTIONS_META_KEY = 'dxos.org/service/function';\n\nexport const FUNCTIONS_PRESET_META_KEY = 'dxos.org/service/function-preset';\n\nconst isSecure = (protocol: string) => {\n return protocol === 'https:' || protocol === 'wss:';\n};\n\nexport const getUserFunctionUrlInMetadata = (meta: ObjectMeta) => {\n return meta.keys.find((key) => key.source === FUNCTIONS_META_KEY)?.id;\n};\n\nexport const setUserFunctionUrlInMetadata = (meta: ObjectMeta, functionUrl: string) => {\n const key = meta.keys.find((key) => key.source === FUNCTIONS_META_KEY);\n if (key) {\n if (key.id !== functionUrl) {\n throw new Error('Metadata mismatch');\n }\n } else {\n meta.keys.push({ source: FUNCTIONS_META_KEY, id: functionUrl });\n }\n};\n\nexport const getInvocationUrl = (functionUrl: string, edgeUrl: string, options: InvocationOptions = {}) => {\n const baseUrl = new URL('functions/', edgeUrl);\n\n // Leading slashes cause the URL to be treated as an absolute path.\n const relativeUrl = functionUrl.replace(/^\\//, '');\n const url = new URL(`./${relativeUrl}`, baseUrl.toString());\n options.spaceId && url.searchParams.set('spaceId', options.spaceId);\n options.subjectId && url.searchParams.set('subjectId', options.subjectId);\n url.protocol = isSecure(url.protocol) ? 'https' : 'http';\n return url.toString();\n};\n\nexport type InvocationOptions = {\n spaceId?: SpaceId;\n subjectId?: string;\n};\n"],
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": ["import_echo_schema", "ScriptType", "S", "Struct", "name", "optional", "String", "description", "changed", "Boolean", "source", "Ref", "TextType", "annotations", "LabelAnnotationId", "pipe", "EchoObject", "typename", "version", "FunctionType", "TypedObject", "NonEmptyString", "inputSchema", "JsonSchemaType", "outputSchema", "binding", "TriggerKind", "typeLiteralAnnotations", "AST", "TitleAnnotationId", "TimerTriggerSchema", "type", "Literal", "cron", "ExamplesAnnotationId", "mutable", "EmailTriggerSchema", "QueueTriggerSchema", "queue", "DXN", "WebhookTriggerSchema", "method", "OptionsAnnotationId", "port", "Number", "QuerySchema", "props", "Record", "key", "value", "Any", "SubscriptionTriggerSchema", "filter", "options", "deep", "delay", "TriggerSchema", "Union", "FunctionTriggerSchema", "function", "enabled", "spec", "meta", "FunctionTrigger", "fields", "FunctionDef", "uri", "route", "handler", "FunctionManifestSchema", "functions", "Array", "RawObject", "triggers", "FUNCTION_TYPES", "InvocationOutcome", "InvocationTraceEventType", "TraceEventException", "timestampMs", "message", "stack", "InvocationTraceStartEvent", "id", "ObjectId", "invocationId", "input", "Object", "invocationTraceQueue", "Expando", "invocationTarget", "trigger", "InvocationTraceEndEvent", "outcome", "Enums", "exception", "TraceEventLog", "level", "context", "TraceEvent", "truncated", "ingestionTimestampMs", "logs", "exceptions", "createInvocationSpans", "items", "eventsByInvocationId", "Map", "event", "entry", "get", "start", "undefined", "end", "set", "now", "Date", "result", "entries", "log", "warn", "isInProgress", "push", "durationMs", "FUNCTIONS_META_KEY", "FUNCTIONS_PRESET_META_KEY", "isSecure", "protocol", "getUserFunctionUrlInMetadata", "keys", "find", "setUserFunctionUrlInMetadata", "functionUrl", "Error", "getInvocationUrl", "edgeUrl", "baseUrl", "URL", "relativeUrl", "replace", "url", "toString", "
|
|
4
|
+
"sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { EchoObject, JsonSchemaType, LabelAnnotationId, Ref, S, TypedObject } from '@dxos/echo-schema';\nimport { TextType } from '@dxos/schema';\n\n/**\n * Source script.\n */\nexport const ScriptType = S.Struct({\n name: S.optional(S.String),\n description: S.optional(S.String),\n // TODO(burdon): Change to hash of deployed content.\n // Whether source has changed since last deploy.\n changed: S.optional(S.Boolean),\n source: Ref(TextType),\n})\n .annotations({ [LabelAnnotationId]: 'name' })\n .pipe(EchoObject({ typename: 'dxos.org/type/Script', version: '0.1.0' }));\n\nexport type ScriptType = S.Schema.Type<typeof ScriptType>;\n\n/**\n * Function deployment.\n */\nexport class FunctionType extends TypedObject({\n typename: 'dxos.org/type/Function',\n version: '0.1.0',\n})({\n // TODO(burdon): Rename to id/uri?\n name: S.NonEmptyString,\n version: S.String,\n\n description: S.optional(S.String),\n\n // Reference to a source script if it exists within ECHO.\n // TODO(burdon): Don't ref ScriptType directly (core).\n source: S.optional(Ref(ScriptType)),\n\n inputSchema: S.optional(JsonSchemaType),\n outputSchema: S.optional(JsonSchemaType),\n\n // Local binding to a function name.\n binding: S.optional(S.String),\n}) {}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { AST, OptionsAnnotationId, RawObject, S, TypedObject, DXN } from '@dxos/echo-schema';\n\n/**\n * Type discriminator for TriggerType.\n * Every spec has a type field of type TriggerKind that we can use to understand which type we're working with.\n * https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions\n */\nexport enum TriggerKind {\n Timer = 'timer',\n Webhook = 'webhook',\n Subscription = 'subscription',\n Email = 'email',\n Queue = 'queue',\n}\n\n// TODO(burdon): Rename prop kind.\nconst typeLiteralAnnotations = { [AST.TitleAnnotationId]: 'Type' };\n\n/**\n * Cron timer.\n */\nconst TimerTriggerSchema = S.Struct({\n type: S.Literal(TriggerKind.Timer).annotations(typeLiteralAnnotations),\n cron: S.String.annotations({\n [AST.TitleAnnotationId]: 'Cron',\n [AST.ExamplesAnnotationId]: ['0 0 * * *'],\n }),\n}).pipe(S.mutable);\n\nexport type TimerTrigger = S.Schema.Type<typeof TimerTriggerSchema>;\n\nconst EmailTriggerSchema = S.Struct({\n type: S.Literal(TriggerKind.Email).annotations(typeLiteralAnnotations),\n}).pipe(S.mutable);\n\nexport type EmailTrigger = S.Schema.Type<typeof EmailTriggerSchema>;\n\nconst QueueTriggerSchema = S.Struct({\n type: S.Literal(TriggerKind.Queue).annotations(typeLiteralAnnotations),\n queue: DXN,\n}).pipe(S.mutable);\n\nexport type QueueTrigger = S.Schema.Type<typeof QueueTriggerSchema>;\n\n/**\n * Webhook.\n */\nconst WebhookTriggerSchema = S.Struct({\n type: S.Literal(TriggerKind.Webhook).annotations(typeLiteralAnnotations),\n method: S.optional(\n S.String.annotations({\n [AST.TitleAnnotationId]: 'Method',\n [OptionsAnnotationId]: ['GET', 'POST'],\n }),\n ),\n port: S.optional(\n S.Number.annotations({\n [AST.TitleAnnotationId]: 'Port',\n }),\n ),\n}).pipe(S.mutable);\n\nexport type WebhookTrigger = S.Schema.Type<typeof WebhookTriggerSchema>;\n\n// TODO(burdon): Use ECHO definition (from https://github.com/dxos/dxos/pull/8233).\nconst QuerySchema = S.Struct({\n type: S.optional(S.String.annotations({ [AST.TitleAnnotationId]: 'Type' })),\n props: S.optional(S.Record({ key: S.String, value: S.Any })),\n}).annotations({ [AST.TitleAnnotationId]: 'Query' });\n\n/**\n * Subscription.\n */\nconst SubscriptionTriggerSchema = S.Struct({\n type: S.Literal(TriggerKind.Subscription).annotations(typeLiteralAnnotations),\n // TODO(burdon): Define query DSL (from ECHO). Reconcile with Table.Query.\n filter: QuerySchema,\n options: S.optional(\n S.Struct({\n // Watch changes to object (not just creation).\n deep: S.optional(S.Boolean.annotations({ [AST.TitleAnnotationId]: 'Nested' })),\n // Debounce changes (delay in ms).\n delay: S.optional(S.Number.annotations({ [AST.TitleAnnotationId]: 'Delay' })),\n }).annotations({ [AST.TitleAnnotationId]: 'Options' }),\n ),\n}).pipe(S.mutable);\n\nexport type SubscriptionTrigger = S.Schema.Type<typeof SubscriptionTriggerSchema>;\n\n/**\n * Trigger schema (discriminated union).\n */\nexport const TriggerSchema = S.Union(\n TimerTriggerSchema,\n WebhookTriggerSchema,\n SubscriptionTriggerSchema,\n EmailTriggerSchema,\n QueueTriggerSchema,\n).annotations({\n [AST.TitleAnnotationId]: 'Trigger',\n});\n\nexport type TriggerType = S.Schema.Type<typeof TriggerSchema>;\n\n/**\n * Function trigger.\n */\nexport const FunctionTriggerSchema = S.Struct({\n // TODO(burdon): What type does this reference.\n // TODO(wittjosiah): This should probably be a Ref?\n function: S.optional(S.String.annotations({ [AST.TitleAnnotationId]: 'Function' })),\n\n enabled: S.optional(S.Boolean.annotations({ [AST.TitleAnnotationId]: 'Enabled' })),\n\n // TODO(burdon): Flatten entire schema.\n spec: S.optional(TriggerSchema),\n\n // TODO(burdon): Get schema as partial from function.\n // TODO(wittjosiah): Rename to payload.\n // The `meta` property is merged into the event data passed to the function.\n meta: S.optional(S.mutable(S.Record({ key: S.String, value: S.Any }))),\n});\n\nexport type FunctionTriggerType = S.Schema.Type<typeof FunctionTriggerSchema>;\n\n/**\n * Function trigger.\n */\nexport class FunctionTrigger extends TypedObject({\n typename: 'dxos.org/type/FunctionTrigger',\n version: '0.1.0',\n})(FunctionTriggerSchema.fields) {}\n\n/**\n * Function definition.\n * @deprecated (Use dxos.org/type/Function)\n */\n// TODO(burdon): Reconcile with FunctionType.\nexport class FunctionDef extends TypedObject({\n typename: 'dxos.org/type/FunctionDef',\n version: '0.1.0',\n})({\n uri: S.String,\n description: S.optional(S.String),\n route: S.String,\n handler: S.String,\n}) {}\n\n/**\n * Function manifest file.\n */\nexport const FunctionManifestSchema = S.Struct({\n functions: S.optional(S.mutable(S.Array(RawObject(FunctionDef)))),\n triggers: S.optional(S.mutable(S.Array(RawObject(FunctionTrigger)))),\n});\n\nexport type FunctionManifest = S.Schema.Type<typeof FunctionManifestSchema>;\n\nexport const FUNCTION_TYPES = [FunctionDef, FunctionTrigger];\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { EchoObject, Expando, ObjectId, Ref, S } from '@dxos/echo-schema';\nimport { log } from '@dxos/log';\n\nimport { FunctionTrigger, type FunctionTriggerType } from './types';\n\nexport enum InvocationOutcome {\n SUCCESS = 'success',\n FAILURE = 'failure',\n PENDING = 'pending',\n}\n\n// TODO(burdon): Convert to extensible discriminated union of EDGE events.\nexport enum InvocationTraceEventType {\n START = 'start',\n END = 'end',\n}\n\nexport const TraceEventException = S.Struct({\n timestampMs: S.Number,\n message: S.String,\n name: S.String,\n stack: S.optional(S.String),\n});\nexport type TraceEventException = S.Schema.Type<typeof TraceEventException>;\n\nexport const InvocationTraceStartEvent = S.Struct({\n /**\n * Queue message id.\n */\n id: ObjectId,\n type: S.Literal(InvocationTraceEventType.START),\n /**\n * Invocation id, the same for invocation start and end events.\n */\n invocationId: ObjectId,\n /**\n * Event generation time.\n */\n timestampMs: S.Number,\n /**\n * Data passed to function / workflow as an argument.\n */\n // TODO(burdon): Input schema?\n input: S.Object,\n /**\n * Queue DXN for function/workflow invocation events.\n */\n // TODO(burdon): Need reference type for queue. vs. string?\n invocationTraceQueue: Ref(Expando),\n /**\n * DXN of the invoked function/workflow.\n */\n invocationTarget: Ref(Expando),\n /**\n * Present for automatic invocations.\n */\n trigger: S.optional(Ref(FunctionTrigger)),\n}).pipe(EchoObject({ typename: 'dxos.org/type/InvocationTraceStart', version: '0.1.0' }));\n\nexport type InvocationTraceStartEvent = S.Schema.Type<typeof InvocationTraceStartEvent>;\n\nexport const InvocationTraceEndEvent = S.Struct({\n /**\n * Trace event id.\n */\n id: ObjectId,\n type: S.Literal(InvocationTraceEventType.END),\n /**\n * Invocation id, will be the same for invocation start and end.\n */\n invocationId: ObjectId,\n /**\n * Event generation time.\n */\n // TODO(burdon): Remove ms suffix.\n timestampMs: S.Number,\n outcome: S.Enums(InvocationOutcome),\n exception: S.optional(TraceEventException),\n}).pipe(EchoObject({ typename: 'dxos.org/type/InvocationTraceEnd', version: '0.1.0' }));\n\nexport type InvocationTraceEndEvent = S.Schema.Type<typeof InvocationTraceEndEvent>;\n\nexport type InvocationTraceEvent = InvocationTraceStartEvent | InvocationTraceEndEvent;\n\nexport const TraceEventLog = S.Struct({\n timestampMs: S.Number,\n level: S.String,\n message: S.String,\n context: S.optional(S.Object),\n});\n\nexport const TraceEvent = S.Struct({\n id: ObjectId,\n // TODO(burdon): Need enum/numeric result (not string).\n outcome: S.String,\n truncated: S.Boolean,\n /**\n * Time when the event was persisted.\n */\n ingestionTimestampMs: S.Number,\n logs: S.Array(TraceEventLog),\n exceptions: S.Array(TraceEventException),\n}).pipe(EchoObject({ typename: 'dxos.org/type/TraceEvent', version: '0.1.0' }));\n\nexport type TraceEvent = S.Schema.Type<typeof TraceEvent>;\n\n/**\n * Deprecated InvocationTrace event format.\n * @deprecated\n */\n// TODO(burdon): Remove.\nexport type InvocationSpan = {\n id: string;\n timestampMs: number;\n outcome: InvocationOutcome;\n input: object;\n durationMs: number;\n invocationTraceQueue: Ref<Expando>;\n invocationTarget: Ref<Expando>;\n trigger?: Ref<FunctionTriggerType>;\n exception?: TraceEventException;\n};\n\nexport const createInvocationSpans = (items?: InvocationTraceEvent[]): InvocationSpan[] => {\n if (!items) {\n return [];\n }\n\n const eventsByInvocationId = new Map<string, { start?: InvocationTraceStartEvent; end?: InvocationTraceEndEvent }>();\n for (const event of items) {\n if (!('invocationId' in event)) {\n // Skip legacy format entries.\n continue;\n }\n\n const invocationId = event.invocationId;\n const entry = eventsByInvocationId.get(invocationId) || { start: undefined, end: undefined };\n if (event.type === InvocationTraceEventType.START) {\n entry.start = event as InvocationTraceStartEvent;\n } else if (event.type === InvocationTraceEventType.END) {\n entry.end = event as InvocationTraceEndEvent;\n }\n\n eventsByInvocationId.set(invocationId, entry);\n }\n\n const now = Date.now();\n const result: InvocationSpan[] = [];\n\n // Create spans for each invocation\n for (const [invocationId, { start, end }] of eventsByInvocationId.entries()) {\n if (!start) {\n // No start event, can't create a meaningful span\n log.warn('found end event without matching start', { invocationId });\n continue;\n }\n\n const isInProgress = end === undefined;\n\n result.push({\n id: invocationId,\n timestampMs: start.timestampMs,\n durationMs: isInProgress ? now - start.timestampMs : end!.timestampMs - start.timestampMs,\n outcome: end?.outcome ?? InvocationOutcome.PENDING,\n exception: end?.exception,\n input: start.input,\n invocationTraceQueue: start.invocationTraceQueue,\n invocationTarget: start.invocationTarget,\n trigger: start.trigger,\n });\n }\n\n return result;\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { type ObjectMeta } from '@dxos/echo-schema';\nimport { type SpaceId } from '@dxos/keys';\n\n// TODO: use URL scheme for source?\nconst FUNCTIONS_META_KEY = 'dxos.org/service/function';\n\nexport const FUNCTIONS_PRESET_META_KEY = 'dxos.org/service/function-preset';\n\nconst isSecure = (protocol: string) => {\n return protocol === 'https:' || protocol === 'wss:';\n};\n\nexport const getUserFunctionUrlInMetadata = (meta: ObjectMeta) => {\n return meta.keys.find((key) => key.source === FUNCTIONS_META_KEY)?.id;\n};\n\nexport const setUserFunctionUrlInMetadata = (meta: ObjectMeta, functionUrl: string) => {\n const key = meta.keys.find((key) => key.source === FUNCTIONS_META_KEY);\n if (key) {\n if (key.id !== functionUrl) {\n throw new Error('Metadata mismatch');\n }\n } else {\n meta.keys.push({ source: FUNCTIONS_META_KEY, id: functionUrl });\n }\n};\n\n/**\n * NOTE: functionId is backend ID, not ECHO object id.\n */\nexport const makeFunctionUrl = (spaceId: SpaceId, fn: { functionId: string }) => `/${spaceId}/${fn.functionId}`;\n\nexport const getInvocationUrl = (functionUrl: string, edgeUrl: string, options: InvocationOptions = {}) => {\n const baseUrl = new URL('functions/', edgeUrl);\n\n // Leading slashes cause the URL to be treated as an absolute path.\n const relativeUrl = functionUrl.replace(/^\\//, '');\n const url = new URL(`./${relativeUrl}`, baseUrl.toString());\n options.spaceId && url.searchParams.set('spaceId', options.spaceId);\n options.subjectId && url.searchParams.set('subjectId', options.subjectId);\n url.protocol = isSecure(url.protocol) ? 'https' : 'http';\n return url.toString();\n};\n\nexport type InvocationOptions = {\n spaceId?: SpaceId;\n subjectId?: string;\n};\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,yBAAmF;AACnF,oBAAyB;ACDzB,IAAAA,sBAAyE;ACAzE,IAAAA,sBAAsD;AACtD,iBAAoB;AFKb,IAAMC,aAAaC,qBAAEC,OAAO;EACjCC,M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jF,SAAQA,KAAItC,WAAWiH,kBAAAA;AACnD,MAAI3E,KAAK;AACP,QAAIA,IAAIkC,OAAOiD,aAAa;AAC1B,YAAM,IAAIC,MAAM,mBAAA;IAClB;EACF,OAAO;AACLtE,SAAKkE,KAAKP,KAAK;MAAE/G,QAAQiH;MAAoBzC,IAAIiD;IAAY,CAAA;EAC/D;AACF;AAKO,IAAME,kBAAkB,CAACC,SAAkBC,OAA+B,IAAID,OAAAA,IAAWC,GAAGC,UAAU;AAEtG,IAAMC,mBAAmB,CAACN,aAAqBO,SAAiBrF,UAA6B,CAAC,MAAC;AACpG,QAAMsF,UAAU,IAAIC,IAAI,cAAcF,OAAAA;AAGtC,QAAMG,cAAcV,YAAYW,QAAQ,OAAO,EAAA;AAC/C,QAAMC,MAAM,IAAIH,IAAI,KAAKC,WAAAA,IAAeF,QAAQK,SAAQ,CAAA;AACxD3F,UAAQiF,WAAWS,IAAIE,aAAahC,IAAI,WAAW5D,QAAQiF,OAAO;AAClEjF,UAAQ6F,aAAaH,IAAIE,aAAahC,IAAI,aAAa5D,QAAQ6F,SAAS;AACxEH,MAAIjB,WAAWD,SAASkB,IAAIjB,QAAQ,IAAI,UAAU;AAClD,SAAOiB,IAAIC,SAAQ;AACrB;",
|
|
6
|
+
"names": ["import_echo_schema", "ScriptType", "S", "Struct", "name", "optional", "String", "description", "changed", "Boolean", "source", "Ref", "TextType", "annotations", "LabelAnnotationId", "pipe", "EchoObject", "typename", "version", "FunctionType", "TypedObject", "NonEmptyString", "inputSchema", "JsonSchemaType", "outputSchema", "binding", "TriggerKind", "typeLiteralAnnotations", "AST", "TitleAnnotationId", "TimerTriggerSchema", "type", "Literal", "cron", "ExamplesAnnotationId", "mutable", "EmailTriggerSchema", "QueueTriggerSchema", "queue", "DXN", "WebhookTriggerSchema", "method", "OptionsAnnotationId", "port", "Number", "QuerySchema", "props", "Record", "key", "value", "Any", "SubscriptionTriggerSchema", "filter", "options", "deep", "delay", "TriggerSchema", "Union", "FunctionTriggerSchema", "function", "enabled", "spec", "meta", "FunctionTrigger", "fields", "FunctionDef", "uri", "route", "handler", "FunctionManifestSchema", "functions", "Array", "RawObject", "triggers", "FUNCTION_TYPES", "InvocationOutcome", "InvocationTraceEventType", "TraceEventException", "timestampMs", "message", "stack", "InvocationTraceStartEvent", "id", "ObjectId", "invocationId", "input", "Object", "invocationTraceQueue", "Expando", "invocationTarget", "trigger", "InvocationTraceEndEvent", "outcome", "Enums", "exception", "TraceEventLog", "level", "context", "TraceEvent", "truncated", "ingestionTimestampMs", "logs", "exceptions", "createInvocationSpans", "items", "eventsByInvocationId", "Map", "event", "entry", "get", "start", "undefined", "end", "set", "now", "Date", "result", "entries", "log", "warn", "isInProgress", "push", "durationMs", "FUNCTIONS_META_KEY", "FUNCTIONS_PRESET_META_KEY", "isSecure", "protocol", "getUserFunctionUrlInMetadata", "keys", "find", "setUserFunctionUrlInMetadata", "functionUrl", "Error", "makeFunctionUrl", "spaceId", "fn", "functionId", "getInvocationUrl", "edgeUrl", "baseUrl", "URL", "relativeUrl", "replace", "url", "toString", "searchParams", "subjectId"]
|
|
7
7
|
}
|
package/dist/lib/node/index.cjs
CHANGED
|
@@ -18,41 +18,42 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
18
18
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
19
|
var node_exports = {};
|
|
20
20
|
__export(node_exports, {
|
|
21
|
-
FUNCTIONS_PRESET_META_KEY: () =>
|
|
22
|
-
FUNCTION_TYPES: () =>
|
|
23
|
-
FunctionDef: () =>
|
|
24
|
-
FunctionManifestSchema: () =>
|
|
25
|
-
FunctionRegistry: () =>
|
|
26
|
-
FunctionTrigger: () =>
|
|
27
|
-
FunctionTriggerSchema: () =>
|
|
28
|
-
FunctionType: () =>
|
|
29
|
-
InvocationOutcome: () =>
|
|
30
|
-
InvocationTraceEndEvent: () =>
|
|
31
|
-
InvocationTraceEventType: () =>
|
|
32
|
-
InvocationTraceStartEvent: () =>
|
|
33
|
-
ScriptType: () =>
|
|
34
|
-
TraceEvent: () =>
|
|
35
|
-
TraceEventException: () =>
|
|
36
|
-
TraceEventLog: () =>
|
|
37
|
-
TriggerKind: () =>
|
|
38
|
-
TriggerRegistry: () =>
|
|
39
|
-
TriggerSchema: () =>
|
|
40
|
-
createInvocationSpans: () =>
|
|
41
|
-
createSubscriptionTrigger: () =>
|
|
42
|
-
createTimerTrigger: () =>
|
|
21
|
+
FUNCTIONS_PRESET_META_KEY: () => import_chunk_SV5NRE5L.FUNCTIONS_PRESET_META_KEY,
|
|
22
|
+
FUNCTION_TYPES: () => import_chunk_SV5NRE5L.FUNCTION_TYPES,
|
|
23
|
+
FunctionDef: () => import_chunk_SV5NRE5L.FunctionDef,
|
|
24
|
+
FunctionManifestSchema: () => import_chunk_SV5NRE5L.FunctionManifestSchema,
|
|
25
|
+
FunctionRegistry: () => import_chunk_FBIUZ7SD.FunctionRegistry,
|
|
26
|
+
FunctionTrigger: () => import_chunk_SV5NRE5L.FunctionTrigger,
|
|
27
|
+
FunctionTriggerSchema: () => import_chunk_SV5NRE5L.FunctionTriggerSchema,
|
|
28
|
+
FunctionType: () => import_chunk_SV5NRE5L.FunctionType,
|
|
29
|
+
InvocationOutcome: () => import_chunk_SV5NRE5L.InvocationOutcome,
|
|
30
|
+
InvocationTraceEndEvent: () => import_chunk_SV5NRE5L.InvocationTraceEndEvent,
|
|
31
|
+
InvocationTraceEventType: () => import_chunk_SV5NRE5L.InvocationTraceEventType,
|
|
32
|
+
InvocationTraceStartEvent: () => import_chunk_SV5NRE5L.InvocationTraceStartEvent,
|
|
33
|
+
ScriptType: () => import_chunk_SV5NRE5L.ScriptType,
|
|
34
|
+
TraceEvent: () => import_chunk_SV5NRE5L.TraceEvent,
|
|
35
|
+
TraceEventException: () => import_chunk_SV5NRE5L.TraceEventException,
|
|
36
|
+
TraceEventLog: () => import_chunk_SV5NRE5L.TraceEventLog,
|
|
37
|
+
TriggerKind: () => import_chunk_SV5NRE5L.TriggerKind,
|
|
38
|
+
TriggerRegistry: () => import_chunk_FBIUZ7SD.TriggerRegistry,
|
|
39
|
+
TriggerSchema: () => import_chunk_SV5NRE5L.TriggerSchema,
|
|
40
|
+
createInvocationSpans: () => import_chunk_SV5NRE5L.createInvocationSpans,
|
|
41
|
+
createSubscriptionTrigger: () => import_chunk_FBIUZ7SD.createSubscriptionTrigger,
|
|
42
|
+
createTimerTrigger: () => import_chunk_FBIUZ7SD.createTimerTrigger,
|
|
43
43
|
defineFunction: () => defineFunction,
|
|
44
|
-
getInvocationUrl: () =>
|
|
45
|
-
getUserFunctionUrlInMetadata: () =>
|
|
44
|
+
getInvocationUrl: () => import_chunk_SV5NRE5L.getInvocationUrl,
|
|
45
|
+
getUserFunctionUrlInMetadata: () => import_chunk_SV5NRE5L.getUserFunctionUrlInMetadata,
|
|
46
46
|
incrementSemverPatch: () => import_chunk_NXZNXVT3.incrementSemverPatch,
|
|
47
|
+
makeFunctionUrl: () => import_chunk_SV5NRE5L.makeFunctionUrl,
|
|
47
48
|
publicKeyToDid: () => import_chunk_NXZNXVT3.publicKeyToDid,
|
|
48
|
-
setUserFunctionUrlInMetadata: () =>
|
|
49
|
+
setUserFunctionUrlInMetadata: () => import_chunk_SV5NRE5L.setUserFunctionUrlInMetadata,
|
|
49
50
|
subscriptionHandler: () => subscriptionHandler,
|
|
50
51
|
uploadWorkerFunction: () => import_chunk_NXZNXVT3.uploadWorkerFunction
|
|
51
52
|
});
|
|
52
53
|
module.exports = __toCommonJS(node_exports);
|
|
53
54
|
var import_chunk_NXZNXVT3 = require("./chunk-NXZNXVT3.cjs");
|
|
54
|
-
var
|
|
55
|
-
var
|
|
55
|
+
var import_chunk_FBIUZ7SD = require("./chunk-FBIUZ7SD.cjs");
|
|
56
|
+
var import_chunk_SV5NRE5L = require("./chunk-SV5NRE5L.cjs");
|
|
56
57
|
var import_chunk_JEQ2X3Z6 = require("./chunk-JEQ2X3Z6.cjs");
|
|
57
58
|
var import_effect = require("effect");
|
|
58
59
|
var import_client = require("@dxos/client");
|
|
@@ -80,7 +81,7 @@ var subscriptionHandler = (handler, types) => {
|
|
|
80
81
|
if (!space) {
|
|
81
82
|
import_log.log.error("Invalid space", void 0, {
|
|
82
83
|
F: __dxlog_file,
|
|
83
|
-
L:
|
|
84
|
+
L: 181,
|
|
84
85
|
S: void 0,
|
|
85
86
|
C: (f, a) => f(...a)
|
|
86
87
|
});
|
|
@@ -93,7 +94,7 @@ var subscriptionHandler = (handler, types) => {
|
|
|
93
94
|
data
|
|
94
95
|
}, {
|
|
95
96
|
F: __dxlog_file,
|
|
96
|
-
L:
|
|
97
|
+
L: 193,
|
|
97
98
|
S: void 0,
|
|
98
99
|
C: (f, a) => f(...a)
|
|
99
100
|
});
|
|
@@ -103,7 +104,7 @@ var subscriptionHandler = (handler, types) => {
|
|
|
103
104
|
objects: objects?.length
|
|
104
105
|
}, {
|
|
105
106
|
F: __dxlog_file,
|
|
106
|
-
L:
|
|
107
|
+
L: 195,
|
|
107
108
|
S: void 0,
|
|
108
109
|
C: (f, a) => f(...a)
|
|
109
110
|
});
|
|
@@ -160,6 +161,7 @@ var registerTypes = (space, types = []) => {
|
|
|
160
161
|
getInvocationUrl,
|
|
161
162
|
getUserFunctionUrlInMetadata,
|
|
162
163
|
incrementSemverPatch,
|
|
164
|
+
makeFunctionUrl,
|
|
163
165
|
publicKeyToDid,
|
|
164
166
|
setUserFunctionUrlInMetadata,
|
|
165
167
|
subscriptionHandler,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/handler.ts"],
|
|
4
|
-
"sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport { Schema as S } from 'effect';\nimport { type Effect } from 'effect';\n\nimport { type Client, PublicKey } from '@dxos/client';\nimport { type Space
|
|
5
|
-
"mappings": "
|
|
4
|
+
"sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport { Schema as S } from 'effect';\nimport { type Effect } from 'effect';\n\nimport { type AIServiceClient } from '@dxos/assistant';\nimport { type Client, PublicKey } from '@dxos/client';\nimport { type Space } from '@dxos/client/echo';\nimport type { CoreDatabase, EchoDatabase, ReactiveEchoObject } from '@dxos/echo-db';\nimport { type HasId } from '@dxos/echo-schema';\nimport { type SpaceId, type DXN } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { type QueryResult } from '@dxos/protocols';\nimport { isNonNullable } from '@dxos/util';\n\n// TODO(burdon): Model after http request. Ref Lambda/OpenFaaS.\n// https://docs.aws.amazon.com/lambda/latest/dg/typescript-handler.html\n// https://www.serverless.com/framework/docs/providers/aws/guide/serverless.yml/#functions\n// https://www.npmjs.com/package/aws-lambda\n\n/**\n * Function handler.\n */\nexport type FunctionHandler<TData = {}, TMeta = {}, TOutput = any> = (params: {\n context: FunctionContext;\n event: FunctionEvent<TData, TMeta>;\n /**\n * @deprecated\n */\n response: FunctionResponse;\n}) => TOutput | Promise<TOutput> | Effect.Effect<TOutput, any>;\n\n/**\n * Function context.\n */\nexport interface FunctionContext {\n getSpace: (spaceId: SpaceId) => Promise<SpaceAPI>;\n\n /**\n * Space from which the function was invoked.\n */\n space: SpaceAPI | undefined;\n\n ai: AIServiceClient;\n\n /**\n * @deprecated\n */\n // TODO(burdon): Limit access to individual space.\n client: Client;\n /**\n * @deprecated\n */\n // TODO(burdon): Replace with storage service abstraction.\n dataDir?: string;\n}\n\nexport interface FunctionContextAi {\n // TODO(dmaretskyi): Refer to cloudflare AI docs for more comprehensive typedefs.\n run(model: string, inputs: any, options?: any): Promise<any>;\n}\n\n/**\n * Event payload.\n */\n// TODO(dmaretskyi): Update type definitions to match the actual payload.\nexport type FunctionEvent<TData = {}, TMeta = {}> = {\n data: FunctionEventMeta<TMeta> & TData;\n};\n\n/**\n * Metadata from trigger.\n */\nexport type FunctionEventMeta<TMeta = {}> = {\n meta: TMeta;\n};\n\n/**\n * Function response.\n */\nexport type FunctionResponse = {\n status(code: number): FunctionResponse;\n};\n\n//\n// API.\n//\n\n// TODO(dmaretskyi): Temporary API to get the queues working.\n// TODO(dmaretskyi): To be replaced with integrating queues into echo.\nexport interface QueuesAPI {\n queryQueue(queue: DXN, options?: {}): Promise<QueryResult>;\n insertIntoQueue(queue: DXN, objects: HasId[]): Promise<void>;\n}\n\n/**\n * Space interface available to functions.\n */\nexport interface SpaceAPI {\n get id(): SpaceId;\n /**\n * @deprecated\n */\n get crud(): CoreDatabase;\n get db(): EchoDatabase;\n // TODO(dmaretskyi): Align with echo api --- queues.get(id).append(items);\n get queues(): QueuesAPI;\n}\n\n// TODO(wittjosiah): Fix this.\nconst __assertFunctionSpaceIsCompatibleWithTheClientSpace = () => {\n // const _: SpaceAPI = {} as Space;\n};\n\nexport type FunctionDefinition = {\n description?: string;\n inputSchema: S.Schema.AnyNoContext;\n outputSchema?: S.Schema.AnyNoContext;\n handler: FunctionHandler<any>;\n};\n\nexport type DefineFunctionParams<T, O = any> = {\n description?: string;\n inputSchema: S.Schema<T, any>;\n outputSchema?: S.Schema<O, any>;\n handler: FunctionHandler<T, any, O>;\n};\n\n// TODO(dmaretskyi): Bind input type to function handler.\nexport const defineFunction = <T, O>(params: DefineFunctionParams<T, O>): FunctionDefinition => {\n if (!S.isSchema(params.inputSchema)) {\n throw new Error('Input schema must be a valid schema');\n }\n if (typeof params.handler !== 'function') {\n throw new Error('Handler must be a function');\n }\n\n return {\n description: params.description,\n inputSchema: params.inputSchema,\n outputSchema: params.outputSchema ?? S.Any,\n handler: params.handler,\n };\n};\n\n//\n// Subscription utils.\n//\n\nexport type RawSubscriptionData = {\n spaceKey?: string;\n objects?: string[];\n};\n\nexport type SubscriptionData = {\n space?: Space;\n objects?: ReactiveEchoObject<any>[];\n};\n\n/**\n * Handler wrapper for subscription events; extracts space and objects.\n *\n * To test:\n * ```\n * curl -s -X POST -H \"Content-Type: application/json\" --data '{\"space\": \"0446...1cbb\"}' http://localhost:7100/dev/email-extractor\n * ```\n *\n * NOTE: Get space key from devtools or `dx space list --json`\n */\n// TODO(burdon): Evolve into plugin definition like Composer.\nexport const subscriptionHandler = <TMeta>(\n handler: FunctionHandler<SubscriptionData, TMeta>,\n types?: S.Schema.AnyNoContext[],\n): FunctionHandler<RawSubscriptionData, TMeta> => {\n return async ({ event: { data }, context, response, ...rest }) => {\n const { client } = context;\n const space = data.spaceKey ? client.spaces.get(PublicKey.from(data.spaceKey)) : undefined;\n if (!space) {\n log.error('Invalid space');\n return response.status(500);\n }\n\n registerTypes(space, types);\n const objects = space\n ? data.objects\n ?.map<ReactiveEchoObject<any> | undefined>((id) => space!.db.getObjectById(id))\n .filter(isNonNullable)\n : [];\n\n if (!!data.spaceKey && !space) {\n log.warn('invalid space', { data });\n } else {\n log.info('handler', { space: space?.key.truncate(), objects: objects?.length });\n }\n\n return handler({ event: { data: { ...data, space, objects } }, context, response, ...rest });\n };\n};\n\n// TODO(burdon): Evolve types as part of function metadata.\nconst registerTypes = (space: Space, types: S.Schema.AnyNoContext[] = []) => {\n const registry = space.db.graph.schemaRegistry;\n for (const type of types) {\n if (!registry.hasSchema(type)) {\n registry.addSchema([type]);\n }\n }\n};\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,oBAA4B;AAI5B,oBAAuC;AAKvC,iBAAoB;AAEpB,kBAA8B;;AAoHvB,IAAMA,iBAAiB,CAAOC,WAAAA;AACnC,MAAI,CAACC,cAAAA,OAAEC,SAASF,OAAOG,WAAW,GAAG;AACnC,UAAM,IAAIC,MAAM,qCAAA;EAClB;AACA,MAAI,OAAOJ,OAAOK,YAAY,YAAY;AACxC,UAAM,IAAID,MAAM,4BAAA;EAClB;AAEA,SAAO;IACLE,aAAaN,OAAOM;IACpBH,aAAaH,OAAOG;IACpBI,cAAcP,OAAOO,gBAAgBN,cAAAA,OAAEO;IACvCH,SAASL,OAAOK;EAClB;AACF;AA2BO,IAAMI,sBAAsB,CACjCJ,SACAK,UAAAA;AAEA,SAAO,OAAO,EAAEC,OAAO,EAAEC,KAAI,GAAIC,SAASC,UAAU,GAAGC,KAAAA,MAAM;AAC3D,UAAM,EAAEC,OAAM,IAAKH;AACnB,UAAMI,QAAQL,KAAKM,WAAWF,OAAOG,OAAOC,IAAIC,wBAAUC,KAAKV,KAAKM,QAAQ,CAAA,IAAKK;AACjF,QAAI,CAACN,OAAO;AACVO,qBAAIC,MAAM,iBAAA,QAAA;;;;;;AACV,aAAOX,SAASY,OAAO,GAAA;IACzB;AAEAC,kBAAcV,OAAOP,KAAAA;AACrB,UAAMkB,UAAUX,QACZL,KAAKgB,SACDC,IAAyC,CAACC,OAAOb,MAAOc,GAAGC,cAAcF,EAAAA,CAAAA,EAC1EG,OAAOC,yBAAAA,IACV,CAAA;AAEJ,QAAI,CAAC,CAACtB,KAAKM,YAAY,CAACD,OAAO;AAC7BO,qBAAIW,KAAK,iBAAiB;QAAEvB;MAAK,GAAA;;;;;;IACnC,OAAO;AACLY,qBAAIY,KAAK,WAAW;QAAEnB,OAAOA,OAAOoB,IAAIC,SAAAA;QAAYV,SAASA,SAASW;MAAO,GAAA;;;;;;IAC/E;AAEA,WAAOlC,QAAQ;MAAEM,OAAO;QAAEC,MAAM;UAAE,GAAGA;UAAMK;UAAOW;QAAQ;MAAE;MAAGf;MAASC;MAAU,GAAGC;IAAK,CAAA;EAC5F;AACF;AAGA,IAAMY,gBAAgB,CAACV,OAAcP,QAAiC,CAAA,MAAE;AACtE,QAAM8B,WAAWvB,MAAMc,GAAGU,MAAMC;AAChC,aAAWC,QAAQjC,OAAO;AACxB,QAAI,CAAC8B,SAASI,UAAUD,IAAAA,GAAO;AAC7BH,eAASK,UAAU;QAACF;OAAK;IAC3B;EACF;AACF;",
|
|
6
6
|
"names": ["defineFunction", "params", "S", "isSchema", "inputSchema", "Error", "handler", "description", "outputSchema", "Any", "subscriptionHandler", "types", "event", "data", "context", "response", "rest", "client", "space", "spaceKey", "spaces", "get", "PublicKey", "from", "undefined", "log", "error", "status", "registerTypes", "objects", "map", "id", "db", "getObjectById", "filter", "isNonNullable", "warn", "info", "key", "truncate", "length", "registry", "graph", "schemaRegistry", "type", "hasSchema", "addSchema"]
|
|
7
7
|
}
|