@dxos/functions-runtime-cloudflare 0.8.4-main.66e292d

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 (46) hide show
  1. package/LICENSE +8 -0
  2. package/README.md +47 -0
  3. package/dist/lib/browser/index.mjs +481 -0
  4. package/dist/lib/browser/index.mjs.map +7 -0
  5. package/dist/lib/browser/meta.json +1 -0
  6. package/dist/lib/node-esm/index.mjs +483 -0
  7. package/dist/lib/node-esm/index.mjs.map +7 -0
  8. package/dist/lib/node-esm/meta.json +1 -0
  9. package/dist/types/src/functions-client.d.ts +32 -0
  10. package/dist/types/src/functions-client.d.ts.map +1 -0
  11. package/dist/types/src/index.d.ts +3 -0
  12. package/dist/types/src/index.d.ts.map +1 -0
  13. package/dist/types/src/internal/adapter.d.ts +12 -0
  14. package/dist/types/src/internal/adapter.d.ts.map +1 -0
  15. package/dist/types/src/internal/data-service-impl.d.ts +25 -0
  16. package/dist/types/src/internal/data-service-impl.d.ts.map +1 -0
  17. package/dist/types/src/internal/index.d.ts +2 -0
  18. package/dist/types/src/internal/index.d.ts.map +1 -0
  19. package/dist/types/src/internal/query-service-impl.d.ts +18 -0
  20. package/dist/types/src/internal/query-service-impl.d.ts.map +1 -0
  21. package/dist/types/src/internal/queue-service-impl.d.ts +12 -0
  22. package/dist/types/src/internal/queue-service-impl.d.ts.map +1 -0
  23. package/dist/types/src/internal/service-container.d.ts +25 -0
  24. package/dist/types/src/internal/service-container.d.ts.map +1 -0
  25. package/dist/types/src/queues-api.d.ts +22 -0
  26. package/dist/types/src/queues-api.d.ts.map +1 -0
  27. package/dist/types/src/space-proxy.d.ts +25 -0
  28. package/dist/types/src/space-proxy.d.ts.map +1 -0
  29. package/dist/types/src/types.d.ts +31 -0
  30. package/dist/types/src/types.d.ts.map +1 -0
  31. package/dist/types/src/wrap-handler-for-cloudflare.d.ts +6 -0
  32. package/dist/types/src/wrap-handler-for-cloudflare.d.ts.map +1 -0
  33. package/dist/types/tsconfig.tsbuildinfo +1 -0
  34. package/package.json +47 -0
  35. package/src/functions-client.ts +81 -0
  36. package/src/index.ts +6 -0
  37. package/src/internal/adapter.ts +48 -0
  38. package/src/internal/data-service-impl.ts +93 -0
  39. package/src/internal/index.ts +5 -0
  40. package/src/internal/query-service-impl.ts +91 -0
  41. package/src/internal/queue-service-impl.ts +23 -0
  42. package/src/internal/service-container.ts +54 -0
  43. package/src/queues-api.ts +38 -0
  44. package/src/space-proxy.ts +65 -0
  45. package/src/types.ts +40 -0
  46. package/src/wrap-handler-for-cloudflare.ts +132 -0
@@ -0,0 +1,483 @@
1
+ import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
+
3
+ // src/wrap-handler-for-cloudflare.ts
4
+ import { invariant as invariant4 } from "@dxos/invariant";
5
+ import { SpaceId as SpaceId4 } from "@dxos/keys";
6
+ import { log as log3 } from "@dxos/log";
7
+ import { EdgeResponse } from "@dxos/protocols";
8
+
9
+ // src/internal/data-service-impl.ts
10
+ import { Stream } from "@dxos/codec-protobuf/stream";
11
+ import { raise } from "@dxos/debug";
12
+ import { invariant } from "@dxos/invariant";
13
+ import { SpaceId } from "@dxos/keys";
14
+ import { log } from "@dxos/log";
15
+ var __dxlog_file = "/__w/dxos/dxos/packages/core/functions-runtime-cloudflare/src/internal/data-service-impl.ts";
16
+ var DataServiceImpl = class {
17
+ _executionContext;
18
+ _dataService;
19
+ dataSubscriptions = /* @__PURE__ */ new Map();
20
+ constructor(_executionContext, _dataService) {
21
+ this._executionContext = _executionContext;
22
+ this._dataService = _dataService;
23
+ }
24
+ subscribe({ subscriptionId, spaceId }) {
25
+ return new Stream(({ next }) => {
26
+ invariant(SpaceId.isValid(spaceId), void 0, {
27
+ F: __dxlog_file,
28
+ L: 34,
29
+ S: this,
30
+ A: [
31
+ "SpaceId.isValid(spaceId)",
32
+ ""
33
+ ]
34
+ });
35
+ this.dataSubscriptions.set(subscriptionId, {
36
+ spaceId,
37
+ next
38
+ });
39
+ return () => {
40
+ this.dataSubscriptions.delete(subscriptionId);
41
+ };
42
+ });
43
+ }
44
+ async updateSubscription({ subscriptionId, addIds, removeIds }) {
45
+ const sub = this.dataSubscriptions.get(subscriptionId) ?? raise(new Error("Subscription not found"));
46
+ if (addIds) {
47
+ log.info("request documents", {
48
+ count: addIds.length
49
+ }, {
50
+ F: __dxlog_file,
51
+ L: 47,
52
+ S: this,
53
+ C: (f, a) => f(...a)
54
+ });
55
+ for (const documentId of addIds) {
56
+ const document = await this._dataService.getDocument(this._executionContext, sub.spaceId, documentId);
57
+ log.info("document loaded", {
58
+ documentId,
59
+ spaceId: sub.spaceId,
60
+ found: !!document
61
+ }, {
62
+ F: __dxlog_file,
63
+ L: 51,
64
+ S: this,
65
+ C: (f, a) => f(...a)
66
+ });
67
+ if (!document) {
68
+ log.warn("not found", {
69
+ documentId
70
+ }, {
71
+ F: __dxlog_file,
72
+ L: 53,
73
+ S: this,
74
+ C: (f, a) => f(...a)
75
+ });
76
+ continue;
77
+ }
78
+ sub.next({
79
+ updates: [
80
+ {
81
+ documentId,
82
+ mutation: document.data
83
+ }
84
+ ]
85
+ });
86
+ }
87
+ }
88
+ }
89
+ async update({ updates, subscriptionId }) {
90
+ const sub = this.dataSubscriptions.get(subscriptionId) ?? raise(new Error("Subscription not found"));
91
+ for (const update of updates ?? []) {
92
+ await this._dataService.changeDocument(this._executionContext, sub.spaceId, update.documentId, update.mutation);
93
+ }
94
+ throw new Error("Method not implemented.");
95
+ }
96
+ async flush() {
97
+ }
98
+ subscribeSpaceSyncState(request, options) {
99
+ throw new Error("Method not implemented.");
100
+ }
101
+ async getDocumentHeads({ documentIds }) {
102
+ throw new Error("Method not implemented.");
103
+ }
104
+ async reIndexHeads({ documentIds }) {
105
+ throw new Error("Method not implemented.");
106
+ }
107
+ async updateIndexes() {
108
+ throw new Error("Method not implemented.");
109
+ }
110
+ async waitUntilHeadsReplicated({ heads }) {
111
+ throw new Error("Method not implemented.");
112
+ }
113
+ };
114
+
115
+ // src/internal/query-service-impl.ts
116
+ import * as Schema from "effect/Schema";
117
+ import { Stream as Stream2 } from "@dxos/codec-protobuf/stream";
118
+ import { QueryAST } from "@dxos/echo-protocol";
119
+ import { invariant as invariant3 } from "@dxos/invariant";
120
+ import { PublicKey } from "@dxos/keys";
121
+ import { SpaceId as SpaceId3 } from "@dxos/keys";
122
+ import { log as log2 } from "@dxos/log";
123
+
124
+ // src/internal/adapter.ts
125
+ import { failUndefined } from "@dxos/debug";
126
+ import { invariant as invariant2 } from "@dxos/invariant";
127
+ import { SpaceId as SpaceId2 } from "@dxos/keys";
128
+ var __dxlog_file2 = "/__w/dxos/dxos/packages/core/functions-runtime-cloudflare/src/internal/adapter.ts";
129
+ var queryToDataServiceRequest = (query) => {
130
+ const { filter, options } = isSimpleSelectionQuery(query) ?? failUndefined();
131
+ invariant2(options?.spaceIds?.length === 1, "Only one space is supported", {
132
+ F: __dxlog_file2,
133
+ L: 13,
134
+ S: void 0,
135
+ A: [
136
+ "options?.spaceIds?.length === 1",
137
+ "'Only one space is supported'"
138
+ ]
139
+ });
140
+ invariant2(filter.type === "object", "Only object filters are supported", {
141
+ F: __dxlog_file2,
142
+ L: 14,
143
+ S: void 0,
144
+ A: [
145
+ "filter.type === 'object'",
146
+ "'Only object filters are supported'"
147
+ ]
148
+ });
149
+ const spaceId = options.spaceIds[0];
150
+ invariant2(SpaceId2.isValid(spaceId), void 0, {
151
+ F: __dxlog_file2,
152
+ L: 17,
153
+ S: void 0,
154
+ A: [
155
+ "SpaceId.isValid(spaceId)",
156
+ ""
157
+ ]
158
+ });
159
+ return {
160
+ spaceId,
161
+ type: filter.typename ?? void 0,
162
+ objectIds: [
163
+ ...filter.id ?? []
164
+ ]
165
+ };
166
+ };
167
+ var isSimpleSelectionQuery = (query) => {
168
+ switch (query.type) {
169
+ case "options": {
170
+ const maybeFilter = isSimpleSelectionQuery(query.query);
171
+ if (!maybeFilter) {
172
+ return null;
173
+ }
174
+ return {
175
+ filter: maybeFilter.filter,
176
+ options: query.options
177
+ };
178
+ }
179
+ case "select": {
180
+ return {
181
+ filter: query.filter,
182
+ options: void 0
183
+ };
184
+ }
185
+ default: {
186
+ return null;
187
+ }
188
+ }
189
+ };
190
+
191
+ // src/internal/query-service-impl.ts
192
+ var __dxlog_file3 = "/__w/dxos/dxos/packages/core/functions-runtime-cloudflare/src/internal/query-service-impl.ts";
193
+ var QueryServiceImpl = class {
194
+ _executionContext;
195
+ _dataService;
196
+ constructor(_executionContext, _dataService) {
197
+ this._executionContext = _executionContext;
198
+ this._dataService = _dataService;
199
+ }
200
+ execQuery(request) {
201
+ log2.info("execQuery", {
202
+ request
203
+ }, {
204
+ F: __dxlog_file3,
205
+ L: 30,
206
+ S: this,
207
+ C: (f, a) => f(...a)
208
+ });
209
+ const query = QueryAST.Query.pipe(Schema.decodeUnknownSync)(JSON.parse(request.query));
210
+ const requestedSpaceIds = getTargetSpacesForQuery(query);
211
+ invariant3(requestedSpaceIds.length === 1, "Only one space is supported", {
212
+ F: __dxlog_file3,
213
+ L: 33,
214
+ S: this,
215
+ A: [
216
+ "requestedSpaceIds.length === 1",
217
+ "'Only one space is supported'"
218
+ ]
219
+ });
220
+ const spaceId = requestedSpaceIds[0];
221
+ return Stream2.fromPromise((async () => {
222
+ try {
223
+ log2.info("begin query", {
224
+ spaceId
225
+ }, {
226
+ F: __dxlog_file3,
227
+ L: 39,
228
+ S: this,
229
+ C: (f, a) => f(...a)
230
+ });
231
+ const queryResponse = await this._dataService.queryDocuments(this._executionContext, queryToDataServiceRequest(query));
232
+ log2.info("query response", {
233
+ spaceId,
234
+ filter: request.filter,
235
+ resultCount: queryResponse.results.length
236
+ }, {
237
+ F: __dxlog_file3,
238
+ L: 44,
239
+ S: this,
240
+ C: (f, a) => f(...a)
241
+ });
242
+ return {
243
+ results: queryResponse.results.map((object) => ({
244
+ id: object.objectId,
245
+ spaceId,
246
+ spaceKey: PublicKey.ZERO,
247
+ documentId: object.document.documentId,
248
+ rank: 0,
249
+ documentAutomerge: object.document.data
250
+ }))
251
+ };
252
+ } catch (err) {
253
+ log2.error("query failed", {
254
+ err
255
+ }, {
256
+ F: __dxlog_file3,
257
+ L: 58,
258
+ S: this,
259
+ C: (f, a) => f(...a)
260
+ });
261
+ throw err;
262
+ }
263
+ })());
264
+ }
265
+ async reindex() {
266
+ throw new Error("Method not implemented.");
267
+ }
268
+ async setConfig() {
269
+ throw new Error("Method not implemented.");
270
+ }
271
+ };
272
+ var getTargetSpacesForQuery = (query) => {
273
+ const spaces = /* @__PURE__ */ new Set();
274
+ const visitor = (node) => {
275
+ if (node.type === "options") {
276
+ if (node.options.spaceIds) {
277
+ for (const spaceId of node.options.spaceIds) {
278
+ spaces.add(SpaceId3.make(spaceId));
279
+ }
280
+ }
281
+ }
282
+ };
283
+ QueryAST.visit(query, visitor);
284
+ return [
285
+ ...spaces
286
+ ];
287
+ };
288
+
289
+ // src/internal/queue-service-impl.ts
290
+ var QueueServiceImpl = class {
291
+ _ctx;
292
+ _queueService;
293
+ constructor(_ctx, _queueService) {
294
+ this._ctx = _ctx;
295
+ this._queueService = _queueService;
296
+ }
297
+ queryQueue(subspaceTag, spaceId, { queueId, ...query }) {
298
+ return this._queueService.query(this._ctx, `dxn:queue:${subspaceTag}:${spaceId}:${queueId}`, query);
299
+ }
300
+ insertIntoQueue(subspaceTag, spaceId, queueId, objects) {
301
+ return this._queueService.append(this._ctx, `dxn:queue:${subspaceTag}:${spaceId}:${queueId}`, objects);
302
+ }
303
+ deleteFromQueue(subspaceTag, spaceId, queueId, objectIds) {
304
+ throw new Error("Deleting from queue is not supported.");
305
+ }
306
+ };
307
+
308
+ // src/internal/service-container.ts
309
+ var ServiceContainer = class {
310
+ _executionContext;
311
+ _dataService;
312
+ _queueService;
313
+ constructor(_executionContext, _dataService, _queueService) {
314
+ this._executionContext = _executionContext;
315
+ this._dataService = _dataService;
316
+ this._queueService = _queueService;
317
+ }
318
+ async getSpaceMeta(spaceId) {
319
+ return this._dataService.getSpaceMeta(this._executionContext, spaceId);
320
+ }
321
+ async createServices() {
322
+ const dataService = new DataServiceImpl(this._executionContext, this._dataService);
323
+ const queryService = new QueryServiceImpl(this._executionContext, this._dataService);
324
+ const queueService = new QueueServiceImpl(this._executionContext, this._queueService);
325
+ return {
326
+ dataService,
327
+ queryService,
328
+ queueService
329
+ };
330
+ }
331
+ queryQueue(queue) {
332
+ return this._queueService.query({}, queue.toString(), {});
333
+ }
334
+ insertIntoQueue(queue, objects) {
335
+ return this._queueService.append({}, queue.toString(), objects);
336
+ }
337
+ };
338
+
339
+ // src/types.ts
340
+ var FUNCTION_ROUTE_HEADER = "X-DXOS-Function-Route";
341
+ var FunctionRouteValue = /* @__PURE__ */ (function(FunctionRouteValue2) {
342
+ FunctionRouteValue2["Meta"] = "meta";
343
+ return FunctionRouteValue2;
344
+ })({});
345
+
346
+ // src/wrap-handler-for-cloudflare.ts
347
+ var __dxlog_file4 = "/__w/dxos/dxos/packages/core/functions-runtime-cloudflare/src/wrap-handler-for-cloudflare.ts";
348
+ var wrapHandlerForCloudflare = (func) => {
349
+ return async (request, env) => {
350
+ if (request.headers.get(FUNCTION_ROUTE_HEADER) === FunctionRouteValue.Meta) {
351
+ log3.info(">>> meta", {
352
+ func
353
+ }, {
354
+ F: __dxlog_file4,
355
+ L: 25,
356
+ S: void 0,
357
+ C: (f, a) => f(...a)
358
+ });
359
+ return handleFunctionMetaCall(func, request);
360
+ }
361
+ try {
362
+ const spaceId = new URL(request.url).searchParams.get("spaceId");
363
+ if (spaceId) {
364
+ if (!SpaceId4.isValid(spaceId)) {
365
+ return new Response("Invalid spaceId", {
366
+ status: 400
367
+ });
368
+ }
369
+ }
370
+ const serviceContainer = new ServiceContainer({}, env.DATA_SERVICE, env.QUEUE_SERVICE);
371
+ const context = await createFunctionContext({
372
+ serviceContainer,
373
+ contextSpaceId: spaceId
374
+ });
375
+ return EdgeResponse.success(await invokeFunction(func, context, request));
376
+ } catch (error) {
377
+ log3.error("error invoking function", {
378
+ error,
379
+ stack: error.stack
380
+ }, {
381
+ F: __dxlog_file4,
382
+ L: 45,
383
+ S: void 0,
384
+ C: (f, a) => f(...a)
385
+ });
386
+ return EdgeResponse.failure({
387
+ message: error?.message ?? "Internal error",
388
+ error
389
+ });
390
+ }
391
+ };
392
+ };
393
+ var invokeFunction = async (func, context, request) => {
394
+ const { data } = await decodeRequest(request);
395
+ return func.handler({
396
+ context,
397
+ data
398
+ });
399
+ };
400
+ var decodeRequest = async (request) => {
401
+ const { data: { bodyText, ...rest }, trigger } = await request.json();
402
+ if (!bodyText) {
403
+ return {
404
+ data: rest,
405
+ trigger
406
+ };
407
+ }
408
+ try {
409
+ const data = JSON.parse(bodyText);
410
+ return {
411
+ data,
412
+ trigger: {
413
+ ...trigger,
414
+ ...rest
415
+ }
416
+ };
417
+ } catch (err) {
418
+ log3.catch(err, void 0, {
419
+ F: __dxlog_file4,
420
+ L: 80,
421
+ S: void 0,
422
+ C: (f, a) => f(...a)
423
+ });
424
+ return {
425
+ data: {
426
+ bodyText,
427
+ ...rest
428
+ }
429
+ };
430
+ }
431
+ };
432
+ var handleFunctionMetaCall = (functionDefinition, request) => {
433
+ const response = {
434
+ key: functionDefinition.meta.key,
435
+ name: functionDefinition.meta.name,
436
+ description: functionDefinition.meta.description,
437
+ inputSchema: functionDefinition.meta.inputSchema,
438
+ outputSchema: functionDefinition.meta.outputSchema
439
+ };
440
+ return new Response(JSON.stringify(response), {
441
+ headers: {
442
+ "Content-Type": "application/json"
443
+ }
444
+ });
445
+ };
446
+ var createFunctionContext = async ({ serviceContainer, contextSpaceId }) => {
447
+ const { dataService, queryService, queueService } = await serviceContainer.createServices();
448
+ let spaceKey;
449
+ let rootUrl;
450
+ if (contextSpaceId) {
451
+ const meta = await serviceContainer.getSpaceMeta(contextSpaceId);
452
+ if (!meta) {
453
+ throw new Error(`Space not found: ${contextSpaceId}`);
454
+ }
455
+ spaceKey = meta.spaceKey;
456
+ invariant4(!meta.rootDocumentId.startsWith("automerge:"), void 0, {
457
+ F: __dxlog_file4,
458
+ L: 118,
459
+ S: void 0,
460
+ A: [
461
+ "!meta.rootDocumentId.startsWith('automerge:')",
462
+ ""
463
+ ]
464
+ });
465
+ rootUrl = `automerge:${meta.rootDocumentId}`;
466
+ }
467
+ return {
468
+ services: {
469
+ dataService,
470
+ queryService,
471
+ queueService
472
+ },
473
+ spaceId: contextSpaceId,
474
+ spaceKey,
475
+ spaceRootUrl: rootUrl
476
+ };
477
+ };
478
+ export {
479
+ FUNCTION_ROUTE_HEADER,
480
+ FunctionRouteValue,
481
+ wrapHandlerForCloudflare
482
+ };
483
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/wrap-handler-for-cloudflare.ts", "../../../src/internal/data-service-impl.ts", "../../../src/internal/query-service-impl.ts", "../../../src/internal/adapter.ts", "../../../src/internal/queue-service-impl.ts", "../../../src/internal/service-container.ts", "../../../src/types.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport type { JsonSchemaType } from '@dxos/echo/internal';\nimport { invariant } from '@dxos/invariant';\nimport { SpaceId } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { EdgeResponse } from '@dxos/protocols';\nimport type { EdgeFunctionEnv, FunctionProtocol } from '@dxos/protocols';\n\nimport { ServiceContainer } from './internal';\nimport { FUNCTION_ROUTE_HEADER, type FunctionMetadata, FunctionRouteValue } from './types';\n\n/**\n * Wraps a user function in a Cloudflare-compatible handler.\n */\nexport const wrapHandlerForCloudflare = (func: FunctionProtocol.Func): ExportedHandlerFetchHandler<any> => {\n return async (request: Request, env: EdgeFunctionEnv.Env): Promise<Response> => {\n // TODO(dmaretskyi): Should theÓ scope name reflect the function name?\n // TODO(mykola): Wrap in withCleanAutomergeWasmState;\n // TODO(mykola): Wrap in withNewExecutionContext;\n // Meta route is used to get the input schema of the function by the functions service.\n if (request.headers.get(FUNCTION_ROUTE_HEADER) === FunctionRouteValue.Meta) {\n log.info('>>> meta', { func });\n return handleFunctionMetaCall(func, request);\n }\n\n try {\n const spaceId = new URL(request.url).searchParams.get('spaceId');\n if (spaceId) {\n if (!SpaceId.isValid(spaceId)) {\n return new Response('Invalid spaceId', { status: 400 });\n }\n }\n\n const serviceContainer = new ServiceContainer({}, env.DATA_SERVICE, env.QUEUE_SERVICE);\n const context = await createFunctionContext({\n serviceContainer,\n contextSpaceId: spaceId as SpaceId | undefined,\n });\n\n return EdgeResponse.success(await invokeFunction(func, context, request));\n } catch (error: any) {\n log.error('error invoking function', { error, stack: error.stack });\n return EdgeResponse.failure({\n message: error?.message ?? 'Internal error',\n error,\n });\n }\n };\n};\n\nconst invokeFunction = async (func: FunctionProtocol.Func, context: FunctionProtocol.Context, request: Request) => {\n // TODO(dmaretskyi): For some reason requests get wrapped like this.\n const { data } = await decodeRequest(request);\n\n return func.handler({\n context,\n data,\n });\n};\n\nconst decodeRequest = async (request: Request) => {\n const {\n data: { bodyText, ...rest },\n trigger,\n } = (await request.json()) as any;\n\n if (!bodyText) {\n return { data: rest, trigger };\n }\n\n // Webhook passed body as bodyText. Use it as function input if a well-formatted JSON\n // TODO: better trigger input mapping\n try {\n const data = JSON.parse(bodyText);\n return { data, trigger: { ...trigger, ...rest } };\n } catch (err) {\n log.catch(err);\n return { data: { bodyText, ...rest } };\n }\n};\n\nconst handleFunctionMetaCall = (functionDefinition: FunctionProtocol.Func, request: Request): Response => {\n const response: FunctionMetadata = {\n key: functionDefinition.meta.key,\n name: functionDefinition.meta.name,\n description: functionDefinition.meta.description,\n inputSchema: functionDefinition.meta.inputSchema as JsonSchemaType | undefined,\n outputSchema: functionDefinition.meta.outputSchema as JsonSchemaType | undefined,\n };\n\n return new Response(JSON.stringify(response), {\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n};\n\nconst createFunctionContext = async ({\n serviceContainer,\n contextSpaceId,\n}: {\n serviceContainer: ServiceContainer;\n contextSpaceId: SpaceId | undefined;\n}): Promise<FunctionProtocol.Context> => {\n const { dataService, queryService, queueService } = await serviceContainer.createServices();\n\n let spaceKey: string | undefined;\n let rootUrl: string | undefined;\n if (contextSpaceId) {\n const meta = await serviceContainer.getSpaceMeta(contextSpaceId);\n if (!meta) {\n throw new Error(`Space not found: ${contextSpaceId}`);\n }\n spaceKey = meta.spaceKey;\n invariant(!meta.rootDocumentId.startsWith('automerge:'));\n rootUrl = `automerge:${meta.rootDocumentId}`;\n }\n\n return {\n services: {\n dataService,\n queryService,\n queueService,\n },\n spaceId: contextSpaceId,\n spaceKey,\n spaceRootUrl: rootUrl,\n } as any; // TODO(dmaretskyi): Link and fix before merging\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport type { RequestOptions } from '@dxos/codec-protobuf';\nimport { Stream } from '@dxos/codec-protobuf/stream';\nimport { raise } from '@dxos/debug';\nimport { invariant } from '@dxos/invariant';\nimport { SpaceId } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { type EdgeFunctionEnv } from '@dxos/protocols';\nimport type {\n BatchedDocumentUpdates,\n DataService as DataServiceProto,\n GetDocumentHeadsRequest,\n GetDocumentHeadsResponse,\n GetSpaceSyncStateRequest,\n ReIndexHeadsRequest,\n SpaceSyncState,\n UpdateRequest,\n UpdateSubscriptionRequest,\n} from '@dxos/protocols/proto/dxos/echo/service';\n\nexport class DataServiceImpl implements DataServiceProto {\n private dataSubscriptions = new Map<string, { spaceId: SpaceId; next: (msg: BatchedDocumentUpdates) => void }>();\n\n constructor(\n private _executionContext: EdgeFunctionEnv.ExecutionContext,\n private _dataService: EdgeFunctionEnv.DataService,\n ) {}\n\n subscribe({ subscriptionId, spaceId }: { subscriptionId: string; spaceId: string }): Stream<BatchedDocumentUpdates> {\n return new Stream(({ next }) => {\n invariant(SpaceId.isValid(spaceId));\n this.dataSubscriptions.set(subscriptionId, { spaceId, next });\n\n return () => {\n this.dataSubscriptions.delete(subscriptionId);\n };\n });\n }\n\n async updateSubscription({ subscriptionId, addIds, removeIds }: UpdateSubscriptionRequest): Promise<void> {\n const sub = this.dataSubscriptions.get(subscriptionId) ?? raise(new Error('Subscription not found'));\n\n if (addIds) {\n log.info('request documents', { count: addIds.length });\n // TODO(dmaretskyi): Batch.\n for (const documentId of addIds) {\n const document = await this._dataService.getDocument(this._executionContext, sub.spaceId, documentId);\n log.info('document loaded', { documentId, spaceId: sub.spaceId, found: !!document });\n if (!document) {\n log.warn('not found', { documentId });\n continue;\n }\n sub.next({ updates: [{ documentId, mutation: document.data }] });\n }\n }\n }\n\n async update({ updates, subscriptionId }: UpdateRequest): Promise<void> {\n const sub = this.dataSubscriptions.get(subscriptionId) ?? raise(new Error('Subscription not found'));\n // TODO(dmaretskyi): Batch.\n for (const update of updates ?? []) {\n await this._dataService.changeDocument(this._executionContext, sub.spaceId, update.documentId, update.mutation);\n }\n throw new Error('Method not implemented.');\n }\n\n async flush(): Promise<void> {\n // No-op.\n }\n\n subscribeSpaceSyncState(request: GetSpaceSyncStateRequest, options?: RequestOptions): Stream<SpaceSyncState> {\n throw new Error('Method not implemented.');\n }\n\n async getDocumentHeads({ documentIds }: GetDocumentHeadsRequest): Promise<GetDocumentHeadsResponse> {\n throw new Error('Method not implemented.');\n }\n\n async reIndexHeads({ documentIds }: ReIndexHeadsRequest): Promise<void> {\n throw new Error('Method not implemented.');\n }\n\n async updateIndexes(): Promise<void> {\n throw new Error('Method not implemented.');\n }\n\n async waitUntilHeadsReplicated({ heads }: { heads: any }): Promise<void> {\n throw new Error('Method not implemented.');\n }\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport { Stream } from '@dxos/codec-protobuf/stream';\nimport { QueryAST } from '@dxos/echo-protocol';\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { SpaceId } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { type EdgeFunctionEnv } from '@dxos/protocols';\nimport {\n type QueryRequest,\n type QueryResponse,\n type QueryResult as QueryResultProto,\n type QueryService as QueryServiceProto,\n} from '@dxos/protocols/proto/dxos/echo/query';\n\nimport { queryToDataServiceRequest } from './adapter';\n\nexport class QueryServiceImpl implements QueryServiceProto {\n constructor(\n private readonly _executionContext: EdgeFunctionEnv.ExecutionContext,\n private readonly _dataService: EdgeFunctionEnv.DataService,\n ) {}\n\n execQuery(request: QueryRequest): Stream<QueryResponse> {\n log.info('execQuery', { request });\n const query = QueryAST.Query.pipe(Schema.decodeUnknownSync)(JSON.parse(request.query));\n const requestedSpaceIds = getTargetSpacesForQuery(query);\n invariant(requestedSpaceIds.length === 1, 'Only one space is supported');\n const spaceId = requestedSpaceIds[0];\n\n return Stream.fromPromise<QueryResponse>(\n (async () => {\n try {\n log.info('begin query', { spaceId });\n const queryResponse = await this._dataService.queryDocuments(\n this._executionContext,\n queryToDataServiceRequest(query),\n );\n log.info('query response', { spaceId, filter: request.filter, resultCount: queryResponse.results.length });\n return {\n results: queryResponse.results.map(\n (object): QueryResultProto => ({\n id: object.objectId,\n spaceId,\n spaceKey: PublicKey.ZERO,\n documentId: object.document.documentId,\n rank: 0,\n documentAutomerge: object.document.data,\n }),\n ),\n } satisfies QueryResponse;\n } catch (err) {\n log.error('query failed', { err });\n throw err;\n }\n })(),\n );\n }\n\n async reindex() {\n throw new Error('Method not implemented.');\n }\n\n async setConfig() {\n throw new Error('Method not implemented.');\n }\n}\n\n/**\n * Lists spaces this query will select from.\n */\nexport const getTargetSpacesForQuery = (query: QueryAST.Query): SpaceId[] => {\n const spaces = new Set<SpaceId>();\n\n const visitor = (node: QueryAST.Query) => {\n if (node.type === 'options') {\n if (node.options.spaceIds) {\n for (const spaceId of node.options.spaceIds) {\n spaces.add(SpaceId.make(spaceId));\n }\n }\n }\n };\n QueryAST.visit(query, visitor);\n return [...spaces];\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { failUndefined } from '@dxos/debug';\nimport { type QueryAST } from '@dxos/echo-protocol';\nimport { invariant } from '@dxos/invariant';\nimport { SpaceId } from '@dxos/keys';\nimport { type EdgeFunctionEnv } from '@dxos/protocols';\n\nexport const queryToDataServiceRequest = (query: QueryAST.Query): EdgeFunctionEnv.QueryRequest => {\n const { filter, options } = isSimpleSelectionQuery(query) ?? failUndefined();\n invariant(options?.spaceIds?.length === 1, 'Only one space is supported');\n invariant(filter.type === 'object', 'Only object filters are supported');\n\n const spaceId = options.spaceIds[0];\n invariant(SpaceId.isValid(spaceId));\n\n return {\n spaceId,\n type: filter.typename ?? undefined,\n objectIds: [...(filter.id ?? [])],\n };\n};\n\n/**\n * Extracts the filter and options from a query.\n * Supports Select(...) and Options(Select(...)) queries.\n */\nexport const isSimpleSelectionQuery = (\n query: QueryAST.Query,\n): { filter: QueryAST.Filter; options?: QueryAST.QueryOptions } | null => {\n switch (query.type) {\n case 'options': {\n const maybeFilter = isSimpleSelectionQuery(query.query);\n if (!maybeFilter) {\n return null;\n }\n return { filter: maybeFilter.filter, options: query.options };\n }\n case 'select': {\n return { filter: query.filter, options: undefined };\n }\n default: {\n return null;\n }\n }\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport type { ObjectId, SpaceId } from '@dxos/keys';\nimport { type QueueService as QueueServiceProto } from '@dxos/protocols';\nimport type { EdgeFunctionEnv, QueryResult, QueueQuery } from '@dxos/protocols';\n\nexport class QueueServiceImpl implements QueueServiceProto {\n constructor(\n protected _ctx: EdgeFunctionEnv.ExecutionContext,\n private readonly _queueService: EdgeFunctionEnv.QueueService,\n ) {}\n queryQueue(subspaceTag: string, spaceId: SpaceId, { queueId, ...query }: QueueQuery): Promise<QueryResult> {\n return this._queueService.query(this._ctx, `dxn:queue:${subspaceTag}:${spaceId}:${queueId}`, query);\n }\n insertIntoQueue(subspaceTag: string, spaceId: SpaceId, queueId: ObjectId, objects: unknown[]): Promise<void> {\n return this._queueService.append(this._ctx, `dxn:queue:${subspaceTag}:${spaceId}:${queueId}`, objects);\n }\n deleteFromQueue(subspaceTag: string, spaceId: SpaceId, queueId: ObjectId, objectIds: ObjectId[]): Promise<void> {\n throw new Error('Deleting from queue is not supported.');\n }\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport type { HasId } from '@dxos/echo/internal';\nimport { type DXN, type SpaceId } from '@dxos/keys';\nimport type { QueryResult } from '@dxos/protocols';\nimport { type EdgeFunctionEnv } from '@dxos/protocols';\nimport { type QueueService as QueueServiceProto } from '@dxos/protocols';\nimport { type QueryService as QueryServiceProto } from '@dxos/protocols/proto/dxos/echo/query';\nimport type { DataService as DataServiceProto } from '@dxos/protocols/proto/dxos/echo/service';\n\nimport { DataServiceImpl } from './data-service-impl';\nimport { QueryServiceImpl } from './query-service-impl';\nimport { QueueServiceImpl } from './queue-service-impl';\n\n/**\n * TODO: make this implement DataService and QueryService to unify API over edge and web backend\n */\nexport class ServiceContainer {\n constructor(\n private readonly _executionContext: EdgeFunctionEnv.ExecutionContext,\n private readonly _dataService: EdgeFunctionEnv.DataService,\n private readonly _queueService: EdgeFunctionEnv.QueueService,\n ) {}\n\n async getSpaceMeta(spaceId: SpaceId): Promise<EdgeFunctionEnv.SpaceMeta | undefined> {\n return this._dataService.getSpaceMeta(this._executionContext, spaceId);\n }\n\n async createServices(): Promise<{\n dataService: DataServiceProto;\n queryService: QueryServiceProto;\n queueService: QueueServiceProto;\n }> {\n const dataService = new DataServiceImpl(this._executionContext, this._dataService);\n const queryService = new QueryServiceImpl(this._executionContext, this._dataService);\n const queueService = new QueueServiceImpl(this._executionContext, this._queueService);\n\n return {\n dataService,\n queryService,\n queueService,\n };\n }\n\n queryQueue(queue: DXN): Promise<QueryResult> {\n return this._queueService.query({}, queue.toString(), {});\n }\n\n insertIntoQueue(queue: DXN, objects: HasId[]): Promise<void> {\n return this._queueService.append({}, queue.toString(), objects);\n }\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport type { JsonSchemaType } from '@dxos/echo/internal';\n\n/**\n * Is used for to route the request to the metadata handler instead of the main handler.\n */\nexport const FUNCTION_ROUTE_HEADER = 'X-DXOS-Function-Route';\n\nexport enum FunctionRouteValue {\n Meta = 'meta',\n}\n\nexport type FunctionMetadata = {\n /**\n * FQN.\n */\n key: string;\n /**\n * Human-readable name.\n */\n name?: string;\n\n /**\n * Description.\n */\n description?: string;\n\n /**\n * Input schema.\n */\n inputSchema?: JsonSchemaType;\n\n /**\n * Output schema.\n */\n outputSchema?: JsonSchemaType;\n};\n"],
5
+ "mappings": ";;;AAKA,SAASA,aAAAA,kBAAiB;AAC1B,SAASC,WAAAA,gBAAe;AACxB,SAASC,OAAAA,YAAW;AACpB,SAASC,oBAAoB;;;ACH7B,SAASC,cAAc;AACvB,SAASC,aAAa;AACtB,SAASC,iBAAiB;AAC1B,SAASC,eAAe;AACxB,SAASC,WAAW;;AAcb,IAAMC,kBAAN,MAAMA;;;EACHC,oBAAoB,oBAAIC,IAAAA;EAEhC,YACUC,mBACAC,cACR;SAFQD,oBAAAA;SACAC,eAAAA;EACP;EAEHC,UAAU,EAAEC,gBAAgBC,QAAO,GAAiF;AAClH,WAAO,IAAIZ,OAAO,CAAC,EAAEa,KAAI,MAAE;AACzBX,gBAAUC,QAAQW,QAAQF,OAAAA,GAAAA,QAAAA;;;;;;;;;AAC1B,WAAKN,kBAAkBS,IAAIJ,gBAAgB;QAAEC;QAASC;MAAK,CAAA;AAE3D,aAAO,MAAA;AACL,aAAKP,kBAAkBU,OAAOL,cAAAA;MAChC;IACF,CAAA;EACF;EAEA,MAAMM,mBAAmB,EAAEN,gBAAgBO,QAAQC,UAAS,GAA8C;AACxG,UAAMC,MAAM,KAAKd,kBAAkBe,IAAIV,cAAAA,KAAmBV,MAAM,IAAIqB,MAAM,wBAAA,CAAA;AAE1E,QAAIJ,QAAQ;AACVd,UAAImB,KAAK,qBAAqB;QAAEC,OAAON,OAAOO;MAAO,GAAA;;;;;;AAErD,iBAAWC,cAAcR,QAAQ;AAC/B,cAAMS,WAAW,MAAM,KAAKlB,aAAamB,YAAY,KAAKpB,mBAAmBY,IAAIR,SAASc,UAAAA;AA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WAAO;MAAEH;MAAMK,SAAS;QAAE,GAAGA;QAAS,GAAGD;MAAK;IAAE;EAClD,SAASK,KAAK;AACZlC,IAAAA,KAAImC,MAAMD,KAAAA,QAAAA;;;;;;AACV,WAAO;MAAET,MAAM;QAAEG;QAAU,GAAGC;MAAK;IAAE;EACvC;AACF;AAEA,IAAM3B,yBAAyB,CAACkC,oBAA2C3C,YAAAA;AACzE,QAAM4C,WAA6B;IACjCC,KAAKF,mBAAmBG,KAAKD;IAC7BE,MAAMJ,mBAAmBG,KAAKC;IAC9BC,aAAaL,mBAAmBG,KAAKE;IACrCC,aAAaN,mBAAmBG,KAAKG;IACrCC,cAAcP,mBAAmBG,KAAKI;EACxC;AAEA,SAAO,IAAIlC,SAASuB,KAAKY,UAAUP,QAAAA,GAAW;IAC5C1C,SAAS;MACP,gBAAgB;IAClB;EACF,CAAA;AACF;AAEA,IAAMqB,wBAAwB,OAAO,EACnCL,kBACAM,eAAc,MAIf;AACC,QAAM,EAAE4B,aAAaC,cAAcC,aAAY,IAAK,MAAMpC,iBAAiBqC,eAAc;AAEzF,MAAIC;AACJ,MAAIC;AACJ,MAAIjC,gBAAgB;AAClB,UAAMsB,OAAO,MAAM5B,iBAAiBwC,aAAalC,cAAAA;AACjD,QAAI,CAACsB,MAAM;AACT,YAAM,IAAIa,MAAM,oBAAoBnC,cAAAA,EAAgB;IACtD;AACAgC,eAAWV,KAAKU;AAChBI,IAAAA,WAAU,CAACd,KAAKe,eAAeC,WAAW,YAAA,GAAA,QAAA;;;;;;;;;AAC1CL,cAAU,aAAaX,KAAKe,cAAc;EAC5C;AAEA,SAAO;IACLE,UAAU;MACRX;MACAC;MACAC;IACF;IACA5C,SAASc;IACTgC;IACAQ,cAAcP;EAChB;AACF;",
6
+ "names": ["invariant", "SpaceId", "log", "EdgeResponse", "Stream", "raise", "invariant", "SpaceId", "log", "DataServiceImpl", "dataSubscriptions", "Map", "_executionContext", "_dataService", "subscribe", "subscriptionId", "spaceId", "next", "isValid", "set", "delete", "updateSubscription", "addIds", "removeIds", "sub", "get", "Error", "info", "count", "length", "documentId", "document", "getDocument", "found", "warn", "updates", "mutation", "data", "update", "changeDocument", "flush", "subscribeSpaceSyncState", "request", "options", "getDocumentHeads", "documentIds", "reIndexHeads", "updateIndexes", "waitUntilHeadsReplicated", "heads", "Schema", "Stream", "QueryAST", "invariant", "PublicKey", "SpaceId", "log", "failUndefined", "invariant", "SpaceId", "queryToDataServiceRequest", "query", "filter", "options", "isSimpleSelectionQuery", "spaceIds", "length", "type", "spaceId", "isValid", "typename", "undefined", "objectIds", "id", "maybeFilter", "QueryServiceImpl", "_executionContext", "_dataService", "execQuery", "request", "log", "info", "query", "QueryAST", "Query", "pipe", "decodeUnknownSync", "JSON", "parse", "requestedSpaceIds", "getTargetSpacesForQuery", "invariant", "length", "spaceId", "Stream", "fromPromise", "queryResponse", "queryDocuments", "queryToDataServiceRequest", "filter", "resultCount", "results", "map", "object", "id", "objectId", "spaceKey", "PublicKey", "ZERO", "documentId", "document", "rank", "documentAutomerge", "data", "err", "error", "reindex", "Error", "setConfig", "spaces", "Set", "visitor", "node", "type", "options", "spaceIds", "add", "SpaceId", "make", "visit", "QueueServiceImpl", "_ctx", "_queueService", "queryQueue", "subspaceTag", "spaceId", "queueId", "query", "insertIntoQueue", "objects", "append", "deleteFromQueue", "objectIds", "Error", "ServiceContainer", "_executionContext", "_dataService", "_queueService", "getSpaceMeta", "spaceId", "createServices", "dataService", "DataServiceImpl", "queryService", "QueryServiceImpl", "queueService", "QueueServiceImpl", "queryQueue", "queue", "query", "toString", "insertIntoQueue", "objects", "append", "FUNCTION_ROUTE_HEADER", "FunctionRouteValue", "wrapHandlerForCloudflare", "func", "request", "env", "headers", "get", "FUNCTION_ROUTE_HEADER", "FunctionRouteValue", "Meta", "log", "info", "handleFunctionMetaCall", "spaceId", "URL", "url", "searchParams", "SpaceId", "isValid", "Response", "status", "serviceContainer", "ServiceContainer", "DATA_SERVICE", "QUEUE_SERVICE", "context", "createFunctionContext", "contextSpaceId", "EdgeResponse", "success", "invokeFunction", "error", "stack", "failure", "message", "data", "decodeRequest", "handler", "bodyText", "rest", "trigger", "json", "JSON", "parse", "err", "catch", "functionDefinition", "response", "key", "meta", "name", "description", "inputSchema", "outputSchema", "stringify", "dataService", "queryService", "queueService", "createServices", "spaceKey", "rootUrl", "getSpaceMeta", "Error", "invariant", "rootDocumentId", "startsWith", "services", "spaceRootUrl"]
7
+ }
@@ -0,0 +1 @@
1
+ {"inputs":{"src/internal/data-service-impl.ts":{"bytes":11699,"imports":[{"path":"@dxos/codec-protobuf/stream","kind":"import-statement","external":true},{"path":"@dxos/debug","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}],"format":"esm"},"src/internal/adapter.ts":{"bytes":5596,"imports":[{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true}],"format":"esm"},"src/internal/query-service-impl.ts":{"bytes":10794,"imports":[{"path":"effect/Schema","kind":"import-statement","external":true},{"path":"@dxos/codec-protobuf/stream","kind":"import-statement","external":true},{"path":"@dxos/echo-protocol","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"src/internal/adapter.ts","kind":"import-statement","original":"./adapter"}],"format":"esm"},"src/internal/queue-service-impl.ts":{"bytes":3509,"imports":[],"format":"esm"},"src/internal/service-container.ts":{"bytes":5889,"imports":[{"path":"src/internal/data-service-impl.ts","kind":"import-statement","original":"./data-service-impl"},{"path":"src/internal/query-service-impl.ts","kind":"import-statement","original":"./query-service-impl"},{"path":"src/internal/queue-service-impl.ts","kind":"import-statement","original":"./queue-service-impl"}],"format":"esm"},"src/internal/index.ts":{"bytes":503,"imports":[{"path":"src/internal/service-container.ts","kind":"import-statement","original":"./service-container"}],"format":"esm"},"src/types.ts":{"bytes":1696,"imports":[],"format":"esm"},"src/wrap-handler-for-cloudflare.ts":{"bytes":15414,"imports":[{"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/protocols","kind":"import-statement","external":true},{"path":"src/internal/index.ts","kind":"import-statement","original":"./internal"},{"path":"src/types.ts","kind":"import-statement","original":"./types"}],"format":"esm"},"src/index.ts":{"bytes":712,"imports":[{"path":"src/wrap-handler-for-cloudflare.ts","kind":"import-statement","original":"./wrap-handler-for-cloudflare"},{"path":"src/types.ts","kind":"import-statement","original":"./types"}],"format":"esm"}},"outputs":{"dist/lib/node-esm/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":26488},"dist/lib/node-esm/index.mjs":{"imports":[{"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/protocols","kind":"import-statement","external":true},{"path":"@dxos/codec-protobuf/stream","kind":"import-statement","external":true},{"path":"@dxos/debug","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":"effect/Schema","kind":"import-statement","external":true},{"path":"@dxos/codec-protobuf/stream","kind":"import-statement","external":true},{"path":"@dxos/echo-protocol","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true}],"exports":["FUNCTION_ROUTE_HEADER","FunctionRouteValue","wrapHandlerForCloudflare"],"entryPoint":"src/index.ts","inputs":{"src/wrap-handler-for-cloudflare.ts":{"bytesInOutput":3598},"src/internal/data-service-impl.ts":{"bytesInOutput":3070},"src/internal/query-service-impl.ts":{"bytesInOutput":2975},"src/internal/adapter.ts":{"bytesInOutput":1609},"src/internal/queue-service-impl.ts":{"bytesInOutput":631},"src/internal/service-container.ts":{"bytesInOutput":970},"src/types.ts":{"bytesInOutput":205},"src/index.ts":{"bytesInOutput":0}},"bytes":13587}}}
@@ -0,0 +1,32 @@
1
+ import { Resource } from '@dxos/context';
2
+ import { EchoClient } from '@dxos/echo-db';
3
+ import { type SpaceId } from '@dxos/keys';
4
+ import { type EdgeFunctionEnv } from '@dxos/protocols';
5
+ import { SpaceProxy } from './space-proxy';
6
+ type Services = {
7
+ dataService: EdgeFunctionEnv.DataService;
8
+ queueService: EdgeFunctionEnv.QueueService;
9
+ };
10
+ /**
11
+ * API for functions to integrate with ECHO and HALO.
12
+ * @deprecated
13
+ */
14
+ export declare class FunctionsClient extends Resource {
15
+ private readonly _serviceContainer;
16
+ private readonly _echoClient;
17
+ private readonly _executionContext;
18
+ private readonly _spaces;
19
+ constructor(services: Services);
20
+ get echo(): EchoClient;
21
+ protected _open(): Promise<void>;
22
+ protected _close(): Promise<void>;
23
+ getSpace(spaceId: SpaceId): Promise<SpaceProxy>;
24
+ }
25
+ export declare const createClientFromEnv: (env: any) => Promise<FunctionsClient>;
26
+ export {};
27
+ /**
28
+ - Provides data access capabilities for user functions.
29
+ - No real-time replication or reactive queries -- function receives a snapshot.
30
+ - Function event contains the metadata but doesn't need to include the data.
31
+ */
32
+ //# sourceMappingURL=functions-client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"functions-client.d.ts","sourceRoot":"","sources":["../../../src/functions-client.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAE3C,OAAO,EAAE,KAAK,OAAO,EAAE,MAAM,YAAY,CAAC;AAC1C,OAAO,EAAE,KAAK,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAGvD,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAE3C,KAAK,QAAQ,GAAG;IACd,WAAW,EAAE,eAAe,CAAC,WAAW,CAAC;IACzC,YAAY,EAAE,eAAe,CAAC,YAAY,CAAC;CAC5C,CAAC;AAEF;;;GAGG;AACH,qBAAa,eAAgB,SAAQ,QAAQ;IAC3C,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAC;IACnC,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAC;IAC7B,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAwC;IAE1E,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAkC;gBAE9C,QAAQ,EAAE,QAAQ;IAQ9B,IAAI,IAAI,IAAI,UAAU,CAErB;cAEwB,KAAK;cAML,MAAM;IASzB,QAAQ,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,UAAU,CAAC;CAStD;AAED,eAAO,MAAM,mBAAmB,GAAU,KAAK,GAAG,KAAG,OAAO,CAAC,eAAe,CAO3E,CAAC;;AAEF;;;;GAIG"}
@@ -0,0 +1,3 @@
1
+ export { wrapHandlerForCloudflare } from './wrap-handler-for-cloudflare';
2
+ export * from './types';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AACzE,cAAc,SAAS,CAAC"}
@@ -0,0 +1,12 @@
1
+ import { type QueryAST } from '@dxos/echo-protocol';
2
+ import { type EdgeFunctionEnv } from '@dxos/protocols';
3
+ export declare const queryToDataServiceRequest: (query: QueryAST.Query) => EdgeFunctionEnv.QueryRequest;
4
+ /**
5
+ * Extracts the filter and options from a query.
6
+ * Supports Select(...) and Options(Select(...)) queries.
7
+ */
8
+ export declare const isSimpleSelectionQuery: (query: QueryAST.Query) => {
9
+ filter: QueryAST.Filter;
10
+ options?: QueryAST.QueryOptions;
11
+ } | null;
12
+ //# sourceMappingURL=adapter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../../../../src/internal/adapter.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,KAAK,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAGpD,OAAO,EAAE,KAAK,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAEvD,eAAO,MAAM,yBAAyB,GAAI,OAAO,QAAQ,CAAC,KAAK,KAAG,eAAe,CAAC,YAajF,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,sBAAsB,GACjC,OAAO,QAAQ,CAAC,KAAK,KACpB;IAAE,MAAM,EAAE,QAAQ,CAAC,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,QAAQ,CAAC,YAAY,CAAA;CAAE,GAAG,IAgBjE,CAAC"}
@@ -0,0 +1,25 @@
1
+ import type { RequestOptions } from '@dxos/codec-protobuf';
2
+ import { Stream } from '@dxos/codec-protobuf/stream';
3
+ import { type EdgeFunctionEnv } from '@dxos/protocols';
4
+ import type { BatchedDocumentUpdates, DataService as DataServiceProto, GetDocumentHeadsRequest, GetDocumentHeadsResponse, GetSpaceSyncStateRequest, ReIndexHeadsRequest, SpaceSyncState, UpdateRequest, UpdateSubscriptionRequest } from '@dxos/protocols/proto/dxos/echo/service';
5
+ export declare class DataServiceImpl implements DataServiceProto {
6
+ private _executionContext;
7
+ private _dataService;
8
+ private dataSubscriptions;
9
+ constructor(_executionContext: EdgeFunctionEnv.ExecutionContext, _dataService: EdgeFunctionEnv.DataService);
10
+ subscribe({ subscriptionId, spaceId }: {
11
+ subscriptionId: string;
12
+ spaceId: string;
13
+ }): Stream<BatchedDocumentUpdates>;
14
+ updateSubscription({ subscriptionId, addIds, removeIds }: UpdateSubscriptionRequest): Promise<void>;
15
+ update({ updates, subscriptionId }: UpdateRequest): Promise<void>;
16
+ flush(): Promise<void>;
17
+ subscribeSpaceSyncState(request: GetSpaceSyncStateRequest, options?: RequestOptions): Stream<SpaceSyncState>;
18
+ getDocumentHeads({ documentIds }: GetDocumentHeadsRequest): Promise<GetDocumentHeadsResponse>;
19
+ reIndexHeads({ documentIds }: ReIndexHeadsRequest): Promise<void>;
20
+ updateIndexes(): Promise<void>;
21
+ waitUntilHeadsReplicated({ heads }: {
22
+ heads: any;
23
+ }): Promise<void>;
24
+ }
25
+ //# sourceMappingURL=data-service-impl.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"data-service-impl.d.ts","sourceRoot":"","sources":["../../../../src/internal/data-service-impl.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EAAE,MAAM,EAAE,MAAM,6BAA6B,CAAC;AAKrD,OAAO,EAAE,KAAK,eAAe,EAAE,MAAM,iBAAiB,CAAC;AACvD,OAAO,KAAK,EACV,sBAAsB,EACtB,WAAW,IAAI,gBAAgB,EAC/B,uBAAuB,EACvB,wBAAwB,EACxB,wBAAwB,EACxB,mBAAmB,EACnB,cAAc,EACd,aAAa,EACb,yBAAyB,EAC1B,MAAM,yCAAyC,CAAC;AAEjD,qBAAa,eAAgB,YAAW,gBAAgB;IAIpD,OAAO,CAAC,iBAAiB;IACzB,OAAO,CAAC,YAAY;IAJtB,OAAO,CAAC,iBAAiB,CAAwF;gBAGvG,iBAAiB,EAAE,eAAe,CAAC,gBAAgB,EACnD,YAAY,EAAE,eAAe,CAAC,WAAW;IAGnD,SAAS,CAAC,EAAE,cAAc,EAAE,OAAO,EAAE,EAAE;QAAE,cAAc,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,GAAG,MAAM,CAAC,sBAAsB,CAAC;IAW7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