@dxos/compute 0.7.5-main.499c70c

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 (83) hide show
  1. package/LICENSE +8 -0
  2. package/README.md +3 -0
  3. package/dist/lib/browser/chunk-OSKY2SKE.mjs +3080 -0
  4. package/dist/lib/browser/chunk-OSKY2SKE.mjs.map +7 -0
  5. package/dist/lib/browser/index.mjs +55 -0
  6. package/dist/lib/browser/index.mjs.map +7 -0
  7. package/dist/lib/browser/meta.json +1 -0
  8. package/dist/lib/browser/testing/index.mjs +174 -0
  9. package/dist/lib/browser/testing/index.mjs.map +7 -0
  10. package/dist/lib/node/chunk-XQZLJ4K6.cjs +3122 -0
  11. package/dist/lib/node/chunk-XQZLJ4K6.cjs.map +7 -0
  12. package/dist/lib/node/index.cjs +77 -0
  13. package/dist/lib/node/index.cjs.map +7 -0
  14. package/dist/lib/node/meta.json +1 -0
  15. package/dist/lib/node/testing/index.cjs +189 -0
  16. package/dist/lib/node/testing/index.cjs.map +7 -0
  17. package/dist/lib/node-esm/chunk-Y243AEFJ.mjs +3082 -0
  18. package/dist/lib/node-esm/chunk-Y243AEFJ.mjs.map +7 -0
  19. package/dist/lib/node-esm/index.mjs +56 -0
  20. package/dist/lib/node-esm/index.mjs.map +7 -0
  21. package/dist/lib/node-esm/meta.json +1 -0
  22. package/dist/lib/node-esm/testing/index.mjs +175 -0
  23. package/dist/lib/node-esm/testing/index.mjs.map +7 -0
  24. package/dist/types/src/compute-graph-registry.d.ts +34 -0
  25. package/dist/types/src/compute-graph-registry.d.ts.map +1 -0
  26. package/dist/types/src/compute-graph.d.ts +64 -0
  27. package/dist/types/src/compute-graph.d.ts.map +1 -0
  28. package/dist/types/src/compute-graph.test.d.ts +2 -0
  29. package/dist/types/src/compute-graph.test.d.ts.map +1 -0
  30. package/dist/types/src/compute-node.d.ts +25 -0
  31. package/dist/types/src/compute-node.d.ts.map +1 -0
  32. package/dist/types/src/functions/async-function.d.ts +66 -0
  33. package/dist/types/src/functions/async-function.d.ts.map +1 -0
  34. package/dist/types/src/functions/edge-function.d.ts +20 -0
  35. package/dist/types/src/functions/edge-function.d.ts.map +1 -0
  36. package/dist/types/src/functions/function-defs.d.ts +11 -0
  37. package/dist/types/src/functions/function-defs.d.ts.map +1 -0
  38. package/dist/types/src/functions/index.d.ts +4 -0
  39. package/dist/types/src/functions/index.d.ts.map +1 -0
  40. package/dist/types/src/hyperformula.test.d.ts +2 -0
  41. package/dist/types/src/hyperformula.test.d.ts.map +1 -0
  42. package/dist/types/src/index.d.ts +6 -0
  43. package/dist/types/src/index.d.ts.map +1 -0
  44. package/dist/types/src/testing/index.d.ts +4 -0
  45. package/dist/types/src/testing/index.d.ts.map +1 -0
  46. package/dist/types/src/testing/test-builder.d.ts +15 -0
  47. package/dist/types/src/testing/test-builder.d.ts.map +1 -0
  48. package/dist/types/src/testing/test-plugin.d.ts +36 -0
  49. package/dist/types/src/testing/test-plugin.d.ts.map +1 -0
  50. package/dist/types/src/testing/util.d.ts +2 -0
  51. package/dist/types/src/testing/util.d.ts.map +1 -0
  52. package/dist/types/src/types/hyperformula.d.ts +11 -0
  53. package/dist/types/src/types/hyperformula.d.ts.map +1 -0
  54. package/dist/types/src/types/index.d.ts +3 -0
  55. package/dist/types/src/types/index.d.ts.map +1 -0
  56. package/dist/types/src/types/types.d.ts +20 -0
  57. package/dist/types/src/types/types.d.ts.map +1 -0
  58. package/dist/types/src/types/types.test.d.ts +2 -0
  59. package/dist/types/src/types/types.test.d.ts.map +1 -0
  60. package/dist/types/src/util.d.ts +2 -0
  61. package/dist/types/src/util.d.ts.map +1 -0
  62. package/dist/types/tsconfig.tsbuildinfo +1 -0
  63. package/dist/vendor/hyperformula.mjs +37145 -0
  64. package/package.json +76 -0
  65. package/src/compute-graph-registry.ts +90 -0
  66. package/src/compute-graph.test.ts +87 -0
  67. package/src/compute-graph.ts +260 -0
  68. package/src/compute-node.ts +61 -0
  69. package/src/functions/async-function.ts +179 -0
  70. package/src/functions/edge-function.ts +100 -0
  71. package/src/functions/function-defs.ts +2427 -0
  72. package/src/functions/index.ts +7 -0
  73. package/src/hyperformula.test.ts +14 -0
  74. package/src/index.ts +35 -0
  75. package/src/testing/index.ts +7 -0
  76. package/src/testing/test-builder.ts +54 -0
  77. package/src/testing/test-plugin.ts +100 -0
  78. package/src/testing/util.ts +9 -0
  79. package/src/types/hyperformula.ts +19 -0
  80. package/src/types/index.ts +6 -0
  81. package/src/types/types.test.ts +91 -0
  82. package/src/types/types.ts +80 -0
  83. package/src/util.ts +8 -0
@@ -0,0 +1,179 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ import { type SimpleCellAddress } from 'hyperformula/typings/Cell';
6
+ import { type InterpreterState } from 'hyperformula/typings/interpreter/InterpreterState';
7
+ import { type InterpreterValue } from 'hyperformula/typings/interpreter/InterpreterValue';
8
+ import { type ProcedureAst } from 'hyperformula/typings/parser';
9
+ import defaultsDeep from 'lodash.defaultsdeep';
10
+
11
+ import { debounce, type UnsubscribeCallback } from '@dxos/async';
12
+ import { type Space } from '@dxos/client/echo';
13
+ import { log } from '@dxos/log';
14
+
15
+ import { CellError, ErrorType, EmptyValue, FunctionPlugin, type HyperFormula } from '#hyperformula';
16
+
17
+ // TODO(burdon): Create API gateways:
18
+ // https://publicapis.io
19
+ // https://api-ninjas.com/api/cryptoprice
20
+ // https://developers.google.com/apis-explorer
21
+ // https://publicapis.io/coin-desk-api
22
+
23
+ export type AsyncFunction = (...args: any) => Promise<InterpreterValue>;
24
+
25
+ export type FunctionUpdateEvent = {
26
+ name: string;
27
+ cell: SimpleCellAddress;
28
+ };
29
+
30
+ export type FunctionOptions = {
31
+ ttl?: number;
32
+ };
33
+
34
+ export type FunctionContextOptions = {
35
+ defaultTtl: number;
36
+ debounceDelay: number;
37
+ remoteFunctionUrl: string;
38
+ onUpdate?: (update: FunctionUpdateEvent) => void;
39
+ };
40
+
41
+ export const defaultFunctionContextOptions: FunctionContextOptions = {
42
+ defaultTtl: 5_000,
43
+ debounceDelay: 200,
44
+ remoteFunctionUrl: 'https://edge.dxos.workers.dev/functions', // TODO(burdon): Config.
45
+ };
46
+
47
+ /**
48
+ * The context singleton for the model is passed into custom functions.
49
+ *
50
+ * HyperFormula does not support async functions.
51
+ * - https://hyperformula.handsontable.com/guide/custom-functions.html
52
+ * - https://hyperformula.handsontable.com/guide/known-limitations.html#known-limitations
53
+ * - https://github.com/handsontable/hyperformula/issues/892
54
+ */
55
+ export class FunctionContext {
56
+ // Mangle name with params.
57
+ static createInvocationKey(name: string, ...args: any) {
58
+ return JSON.stringify({ name, ...args });
59
+ }
60
+
61
+ // TODO(wittjosiah): Persist cached values.
62
+ // Cached values for cell.
63
+ private readonly _cache = new Map<string, { value: InterpreterValue; ts: number }>();
64
+
65
+ // Active requests.
66
+ private readonly _pending = new Map<string, number>();
67
+
68
+ // Query subscriptions.
69
+ private readonly _subscriptions = new Map<string, UnsubscribeCallback>();
70
+
71
+ // Invocation count.
72
+ private _invocations: Record<string, number> = {};
73
+
74
+ private readonly _options: FunctionContextOptions;
75
+
76
+ // Debounced update handler.
77
+ private readonly _onUpdate: (update: FunctionUpdateEvent) => void;
78
+
79
+ constructor(
80
+ private readonly _hf: HyperFormula,
81
+ private readonly _space: Space | undefined,
82
+ _options?: Partial<FunctionContextOptions>,
83
+ ) {
84
+ this._options = defaultsDeep(_options ?? {}, defaultFunctionContextOptions);
85
+ this._onUpdate = debounce((update) => {
86
+ log('update', update);
87
+ // TODO(burdon): Better way to trigger recalculation? (NOTE: rebuildAndRecalculate resets the undo history.)
88
+ this._hf.resumeEvaluation();
89
+ this._options.onUpdate?.(update);
90
+ }, this._options.debounceDelay);
91
+ }
92
+
93
+ get space() {
94
+ return this._space;
95
+ }
96
+
97
+ get remoteFunctionUrl() {
98
+ return this._options.remoteFunctionUrl;
99
+ }
100
+
101
+ get info() {
102
+ return { cache: this._cache.size, invocations: this._invocations };
103
+ }
104
+
105
+ flush() {
106
+ this._cache.clear();
107
+ this._invocations = {};
108
+ this._subscriptions.forEach((unsubscribe) => unsubscribe());
109
+ this._subscriptions.clear();
110
+ }
111
+
112
+ createSubscription(name: string, unsubscribe: UnsubscribeCallback) {
113
+ this._subscriptions.get(name)?.();
114
+ this._subscriptions.set(name, unsubscribe);
115
+ }
116
+
117
+ /**
118
+ * Exec the function if TTL has expired.
119
+ * Return the cached value.
120
+ */
121
+ invokeFunction(
122
+ name: string,
123
+ state: InterpreterState,
124
+ args: any[],
125
+ cb: AsyncFunction,
126
+ options?: FunctionOptions,
127
+ ): InterpreterValue | undefined {
128
+ const ttl = options?.ttl ?? this._options.defaultTtl;
129
+
130
+ const { formulaAddress: cell } = state;
131
+ const invocationKey = FunctionContext.createInvocationKey(name, ...args);
132
+ const { value = undefined, ts = 0 } = this._cache.get(invocationKey) ?? {};
133
+
134
+ const now = Date.now();
135
+ const delta = now - ts;
136
+ if ((!ts || delta > ttl) && !this._pending.has(invocationKey)) {
137
+ this._pending.set(invocationKey, now);
138
+ setTimeout(async () => {
139
+ this._invocations[name] = (this._invocations[name] ?? 0) + 1;
140
+ try {
141
+ // Exec function.
142
+ const value = await cb(...args);
143
+ this._cache.set(invocationKey, { value, ts: Date.now() });
144
+ log('set', { cell, value });
145
+ this._onUpdate({ name, cell });
146
+ } catch (err) {
147
+ // TODO(burdon): Show error to user.
148
+ log.warn('failed', { cell, err });
149
+ this._cache.set(invocationKey, { value: new CellError(ErrorType.ERROR, 'Function failed.'), ts: Date.now() });
150
+ } finally {
151
+ this._pending.delete(invocationKey);
152
+ }
153
+ });
154
+ }
155
+
156
+ log('invoke', { cell, name, args, cache: value });
157
+ return value;
158
+ }
159
+ }
160
+
161
+ /**
162
+ * Base class for async functions.
163
+ */
164
+ export class AsyncFunctionPlugin extends FunctionPlugin {
165
+ get context() {
166
+ return this.config.context as FunctionContext;
167
+ }
168
+
169
+ /**
170
+ * Immediately returns cached value then runs the async function.
171
+ */
172
+ protected runAsyncFunction(ast: ProcedureAst, state: InterpreterState, cb: AsyncFunction, options?: FunctionOptions) {
173
+ const { procedureName } = ast;
174
+ const metadata = this.metadata(procedureName);
175
+ return this.runFunction(ast.args, state, metadata, (...args: any) => {
176
+ return this.context.invokeFunction(procedureName, state, args, cb, options) ?? EmptyValue;
177
+ });
178
+ }
179
+ }
@@ -0,0 +1,100 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ import { effect } from '@preact/signals-core';
6
+ import { type InterpreterState } from 'hyperformula/typings/interpreter/InterpreterState';
7
+ import { type ProcedureAst } from 'hyperformula/typings/parser';
8
+
9
+ import { Filter, getMeta } from '@dxos/client/echo';
10
+ import { FunctionType, getUserFunctionUrlInMetadata } from '@dxos/functions';
11
+ import { log } from '@dxos/log';
12
+ import { nonNullable } from '@dxos/util';
13
+
14
+ import { CellError, ErrorType, FunctionArgumentType } from '#hyperformula';
15
+ import { type AsyncFunction, AsyncFunctionPlugin } from './async-function';
16
+
17
+ export const EDGE_FUNCTION_NAME = 'DX';
18
+
19
+ const FUNCTION_TTL = 10_000;
20
+
21
+ /**
22
+ * A hyperformula function plugin for calling remote (EDGE) functions.
23
+ * https://hyperformula.handsontable.com/guide/custom-functions.html#add-a-simple-custom-function
24
+ */
25
+ export class EdgeFunctionPlugin extends AsyncFunctionPlugin {
26
+ dx(ast: ProcedureAst, state: InterpreterState) {
27
+ const handler =
28
+ (subscribe = false): AsyncFunction =>
29
+ async (binding: string, ...args: any) => {
30
+ const space = this.context.space;
31
+ if (!space) {
32
+ return new CellError(ErrorType.REF, 'Missing space');
33
+ }
34
+
35
+ const {
36
+ objects: [fn],
37
+ } = await space.db.query(Filter.schema(FunctionType, { binding })).run();
38
+ if (!fn) {
39
+ log.info('Function not found', { binding });
40
+ return new CellError(ErrorType.REF, 'Function not found');
41
+ }
42
+
43
+ if (subscribe) {
44
+ const unsubscribe = effect(() => {
45
+ log('function changed', { fn });
46
+ const _ = fn?.version;
47
+
48
+ // TODO(wittjosiah): `ttl` should be 0 to force a recalculation when a new version is deployed.
49
+ // This needs a ttl to prevent a binding change from causing the function not to be found.
50
+ this.runAsyncFunction(ast, state, handler(false), { ttl: FUNCTION_TTL });
51
+ });
52
+
53
+ this.context.createSubscription(ast.procedureName, unsubscribe);
54
+ }
55
+
56
+ const path = getUserFunctionUrlInMetadata(getMeta(fn));
57
+ const response = await fetch(`${this.context.remoteFunctionUrl}${path}`, {
58
+ method: 'POST',
59
+ headers: { 'Content-Type': 'application/json' },
60
+ body: JSON.stringify({ args: args.filter(nonNullable) }),
61
+ });
62
+ const result = await response.text();
63
+ log('function executed', { result });
64
+
65
+ return result;
66
+ };
67
+
68
+ return this.runAsyncFunction(ast, state, handler(true), { ttl: FUNCTION_TTL });
69
+ }
70
+ }
71
+
72
+ EdgeFunctionPlugin.implementedFunctions = {
73
+ [EDGE_FUNCTION_NAME]: {
74
+ method: 'dx',
75
+ parameters: [
76
+ // Binding
77
+ { argumentType: FunctionArgumentType.STRING },
78
+
79
+ // Remote function arguments (currently supporting up to 8).
80
+ { argumentType: FunctionArgumentType.ANY, optionalArg: true },
81
+ { argumentType: FunctionArgumentType.ANY, optionalArg: true },
82
+ { argumentType: FunctionArgumentType.ANY, optionalArg: true },
83
+ { argumentType: FunctionArgumentType.ANY, optionalArg: true },
84
+ { argumentType: FunctionArgumentType.ANY, optionalArg: true },
85
+ { argumentType: FunctionArgumentType.ANY, optionalArg: true },
86
+ { argumentType: FunctionArgumentType.ANY, optionalArg: true },
87
+ { argumentType: FunctionArgumentType.ANY, optionalArg: true },
88
+ ],
89
+ isVolatile: true,
90
+ },
91
+ };
92
+
93
+ export const EdgeFunctionPluginTranslations = {
94
+ enGB: {
95
+ [EDGE_FUNCTION_NAME]: 'Remote function',
96
+ },
97
+ enUS: {
98
+ [EDGE_FUNCTION_NAME]: 'Remote function',
99
+ },
100
+ };