@dxos/functions-runtime-cloudflare 0.8.4-main.3c1ae3b

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 (49) hide show
  1. package/LICENSE +8 -0
  2. package/README.md +47 -0
  3. package/dist/lib/browser/index.mjs +752 -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 +754 -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 +6 -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 +19 -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/logger.d.ts +2 -0
  26. package/dist/types/src/logger.d.ts.map +1 -0
  27. package/dist/types/src/queues-api.d.ts +22 -0
  28. package/dist/types/src/queues-api.d.ts.map +1 -0
  29. package/dist/types/src/space-proxy.d.ts +25 -0
  30. package/dist/types/src/space-proxy.d.ts.map +1 -0
  31. package/dist/types/src/types.d.ts +31 -0
  32. package/dist/types/src/types.d.ts.map +1 -0
  33. package/dist/types/src/wrap-handler-for-cloudflare.d.ts +6 -0
  34. package/dist/types/src/wrap-handler-for-cloudflare.d.ts.map +1 -0
  35. package/dist/types/tsconfig.tsbuildinfo +1 -0
  36. package/package.json +48 -0
  37. package/src/functions-client.ts +81 -0
  38. package/src/index.ts +9 -0
  39. package/src/internal/adapter.ts +48 -0
  40. package/src/internal/data-service-impl.ts +125 -0
  41. package/src/internal/index.ts +5 -0
  42. package/src/internal/query-service-impl.ts +103 -0
  43. package/src/internal/queue-service-impl.ts +51 -0
  44. package/src/internal/service-container.ts +54 -0
  45. package/src/logger.ts +40 -0
  46. package/src/queues-api.ts +38 -0
  47. package/src/space-proxy.ts +65 -0
  48. package/src/types.ts +40 -0
  49. package/src/wrap-handler-for-cloudflare.ts +132 -0
@@ -0,0 +1,754 @@
1
+ import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
+
3
+ // src/functions-client.ts
4
+ import { Resource as Resource2 } from "@dxos/context";
5
+ import { EchoClient } from "@dxos/echo-db";
6
+ import { invariant as invariant5 } from "@dxos/invariant";
7
+
8
+ // src/internal/data-service-impl.ts
9
+ import { Stream } from "@dxos/codec-protobuf/stream";
10
+ import { raise } from "@dxos/debug";
11
+ import { NotImplementedError, RuntimeServiceError } from "@dxos/errors";
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: 35,
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 RuntimeServiceError({
46
+ message: "Subscription not found.",
47
+ context: {
48
+ subscriptionId
49
+ }
50
+ }));
51
+ if (addIds) {
52
+ log.info("request documents", {
53
+ count: addIds.length
54
+ }, {
55
+ F: __dxlog_file,
56
+ L: 55,
57
+ S: this,
58
+ C: (f, a) => f(...a)
59
+ });
60
+ for (const documentId of addIds) {
61
+ const document = await this._dataService.getDocument(this._executionContext, sub.spaceId, documentId);
62
+ log.info("document loaded", {
63
+ documentId,
64
+ spaceId: sub.spaceId,
65
+ found: !!document
66
+ }, {
67
+ F: __dxlog_file,
68
+ L: 59,
69
+ S: this,
70
+ C: (f, a) => f(...a)
71
+ });
72
+ if (!document) {
73
+ log.warn("not found", {
74
+ documentId
75
+ }, {
76
+ F: __dxlog_file,
77
+ L: 61,
78
+ S: this,
79
+ C: (f, a) => f(...a)
80
+ });
81
+ continue;
82
+ }
83
+ sub.next({
84
+ updates: [
85
+ {
86
+ documentId,
87
+ mutation: document.data
88
+ }
89
+ ]
90
+ });
91
+ }
92
+ }
93
+ }
94
+ async update({ updates, subscriptionId }) {
95
+ const sub = this.dataSubscriptions.get(subscriptionId) ?? raise(new RuntimeServiceError({
96
+ message: "Subscription not found.",
97
+ context: {
98
+ subscriptionId
99
+ }
100
+ }));
101
+ try {
102
+ for (const update of updates ?? []) {
103
+ await this._dataService.changeDocument(this._executionContext, sub.spaceId, update.documentId, update.mutation);
104
+ }
105
+ } catch (error) {
106
+ throw RuntimeServiceError.wrap({
107
+ message: "Failed to apply document updates.",
108
+ context: {
109
+ subscriptionId
110
+ },
111
+ ifTypeDiffers: true
112
+ })(error);
113
+ }
114
+ }
115
+ async flush() {
116
+ }
117
+ subscribeSpaceSyncState(request, options) {
118
+ throw new NotImplementedError({
119
+ message: "subscribeSpaceSyncState is not implemented."
120
+ });
121
+ }
122
+ async getDocumentHeads({ documentIds }) {
123
+ throw new NotImplementedError({
124
+ message: "getDocumentHeads is not implemented."
125
+ });
126
+ }
127
+ async reIndexHeads({ documentIds }) {
128
+ throw new NotImplementedError({
129
+ message: "reIndexHeads is not implemented."
130
+ });
131
+ }
132
+ async updateIndexes() {
133
+ throw new NotImplementedError({
134
+ message: "updateIndexes is not implemented."
135
+ });
136
+ }
137
+ async waitUntilHeadsReplicated({ heads }) {
138
+ throw new NotImplementedError({
139
+ message: "waitUntilHeadsReplicated is not implemented."
140
+ });
141
+ }
142
+ };
143
+
144
+ // src/internal/query-service-impl.ts
145
+ import * as Schema from "effect/Schema";
146
+ import { Stream as Stream2 } from "@dxos/codec-protobuf/stream";
147
+ import { QueryAST } from "@dxos/echo-protocol";
148
+ import { NotImplementedError as NotImplementedError2, RuntimeServiceError as RuntimeServiceError2 } from "@dxos/errors";
149
+ import { invariant as invariant3 } from "@dxos/invariant";
150
+ import { PublicKey } from "@dxos/keys";
151
+ import { SpaceId as SpaceId3 } from "@dxos/keys";
152
+ import { log as log2 } from "@dxos/log";
153
+
154
+ // src/internal/adapter.ts
155
+ import { failUndefined } from "@dxos/debug";
156
+ import { invariant as invariant2 } from "@dxos/invariant";
157
+ import { SpaceId as SpaceId2 } from "@dxos/keys";
158
+ var __dxlog_file2 = "/__w/dxos/dxos/packages/core/functions-runtime-cloudflare/src/internal/adapter.ts";
159
+ var queryToDataServiceRequest = (query) => {
160
+ const { filter, options } = isSimpleSelectionQuery(query) ?? failUndefined();
161
+ invariant2(options?.spaceIds?.length === 1, "Only one space is supported", {
162
+ F: __dxlog_file2,
163
+ L: 13,
164
+ S: void 0,
165
+ A: [
166
+ "options?.spaceIds?.length === 1",
167
+ "'Only one space is supported'"
168
+ ]
169
+ });
170
+ invariant2(filter.type === "object", "Only object filters are supported", {
171
+ F: __dxlog_file2,
172
+ L: 14,
173
+ S: void 0,
174
+ A: [
175
+ "filter.type === 'object'",
176
+ "'Only object filters are supported'"
177
+ ]
178
+ });
179
+ const spaceId = options.spaceIds[0];
180
+ invariant2(SpaceId2.isValid(spaceId), void 0, {
181
+ F: __dxlog_file2,
182
+ L: 17,
183
+ S: void 0,
184
+ A: [
185
+ "SpaceId.isValid(spaceId)",
186
+ ""
187
+ ]
188
+ });
189
+ return {
190
+ spaceId,
191
+ type: filter.typename ?? void 0,
192
+ objectIds: [
193
+ ...filter.id ?? []
194
+ ]
195
+ };
196
+ };
197
+ var isSimpleSelectionQuery = (query) => {
198
+ switch (query.type) {
199
+ case "options": {
200
+ const maybeFilter = isSimpleSelectionQuery(query.query);
201
+ if (!maybeFilter) {
202
+ return null;
203
+ }
204
+ return {
205
+ filter: maybeFilter.filter,
206
+ options: query.options
207
+ };
208
+ }
209
+ case "select": {
210
+ return {
211
+ filter: query.filter,
212
+ options: void 0
213
+ };
214
+ }
215
+ default: {
216
+ return null;
217
+ }
218
+ }
219
+ };
220
+
221
+ // src/internal/query-service-impl.ts
222
+ var __dxlog_file3 = "/__w/dxos/dxos/packages/core/functions-runtime-cloudflare/src/internal/query-service-impl.ts";
223
+ var QueryServiceImpl = class {
224
+ _executionContext;
225
+ _dataService;
226
+ _queryCount = 0;
227
+ constructor(_executionContext, _dataService) {
228
+ this._executionContext = _executionContext;
229
+ this._dataService = _dataService;
230
+ }
231
+ execQuery(request) {
232
+ log2.info("execQuery", {
233
+ request
234
+ }, {
235
+ F: __dxlog_file3,
236
+ L: 33,
237
+ S: this,
238
+ C: (f, a) => f(...a)
239
+ });
240
+ const query = QueryAST.Query.pipe(Schema.decodeUnknownSync)(JSON.parse(request.query));
241
+ const requestedSpaceIds = getTargetSpacesForQuery(query);
242
+ invariant3(requestedSpaceIds.length === 1, "Only one space is supported", {
243
+ F: __dxlog_file3,
244
+ L: 36,
245
+ S: this,
246
+ A: [
247
+ "requestedSpaceIds.length === 1",
248
+ "'Only one space is supported'"
249
+ ]
250
+ });
251
+ const spaceId = requestedSpaceIds[0];
252
+ return Stream2.fromPromise((async () => {
253
+ try {
254
+ this._queryCount++;
255
+ log2.info("begin query", {
256
+ spaceId
257
+ }, {
258
+ F: __dxlog_file3,
259
+ L: 43,
260
+ S: this,
261
+ C: (f, a) => f(...a)
262
+ });
263
+ const queryResponse = await this._dataService.queryDocuments(this._executionContext, queryToDataServiceRequest(query));
264
+ log2.info("query response", {
265
+ spaceId,
266
+ filter: request.filter,
267
+ resultCount: queryResponse.results.length
268
+ }, {
269
+ F: __dxlog_file3,
270
+ L: 48,
271
+ S: this,
272
+ C: (f, a) => f(...a)
273
+ });
274
+ return {
275
+ results: queryResponse.results.map((object) => ({
276
+ id: object.objectId,
277
+ spaceId,
278
+ spaceKey: PublicKey.ZERO,
279
+ documentId: object.document.documentId,
280
+ rank: 0,
281
+ documentAutomerge: object.document.data
282
+ }))
283
+ };
284
+ } catch (error) {
285
+ log2.error("query failed", {
286
+ err: error
287
+ }, {
288
+ F: __dxlog_file3,
289
+ L: 62,
290
+ S: this,
291
+ C: (f, a) => f(...a)
292
+ });
293
+ throw new RuntimeServiceError2({
294
+ message: `Query execution failed (queryCount=${this._queryCount})`,
295
+ context: {
296
+ spaceId,
297
+ filter: request.filter,
298
+ queryCount: this._queryCount
299
+ },
300
+ cause: error
301
+ });
302
+ }
303
+ })());
304
+ }
305
+ async reindex() {
306
+ throw new NotImplementedError2({
307
+ message: "Reindex is not implemented."
308
+ });
309
+ }
310
+ async setConfig() {
311
+ throw new NotImplementedError2({
312
+ message: "SetConfig is not implemented."
313
+ });
314
+ }
315
+ };
316
+ var getTargetSpacesForQuery = (query) => {
317
+ const spaces = /* @__PURE__ */ new Set();
318
+ const visitor = (node) => {
319
+ if (node.type === "options") {
320
+ if (node.options.spaceIds) {
321
+ for (const spaceId of node.options.spaceIds) {
322
+ spaces.add(SpaceId3.make(spaceId));
323
+ }
324
+ }
325
+ }
326
+ };
327
+ QueryAST.visit(query, visitor);
328
+ return [
329
+ ...spaces
330
+ ];
331
+ };
332
+
333
+ // src/internal/queue-service-impl.ts
334
+ import { NotImplementedError as NotImplementedError3, RuntimeServiceError as RuntimeServiceError3 } from "@dxos/errors";
335
+ var QueueServiceImpl = class {
336
+ _ctx;
337
+ _queueService;
338
+ constructor(_ctx, _queueService) {
339
+ this._ctx = _ctx;
340
+ this._queueService = _queueService;
341
+ }
342
+ async queryQueue(subspaceTag, spaceId, { queueId, ...query }) {
343
+ try {
344
+ const result = await this._queueService.query(this._ctx, `dxn:queue:${subspaceTag}:${spaceId}:${queueId}`, query);
345
+ return result;
346
+ } catch (error) {
347
+ throw RuntimeServiceError3.wrap({
348
+ message: "Queue query failed.",
349
+ context: {
350
+ subspaceTag,
351
+ spaceId,
352
+ queueId
353
+ },
354
+ ifTypeDiffers: true
355
+ })(error);
356
+ }
357
+ }
358
+ async insertIntoQueue(subspaceTag, spaceId, queueId, objects) {
359
+ try {
360
+ const result = await this._queueService.append(this._ctx, `dxn:queue:${subspaceTag}:${spaceId}:${queueId}`, objects);
361
+ return result;
362
+ } catch (error) {
363
+ throw RuntimeServiceError3.wrap({
364
+ message: "Queue append failed.",
365
+ context: {
366
+ subspaceTag,
367
+ spaceId,
368
+ queueId
369
+ },
370
+ ifTypeDiffers: true
371
+ })(error);
372
+ }
373
+ }
374
+ deleteFromQueue(subspaceTag, spaceId, queueId, _objectIds) {
375
+ throw new NotImplementedError3({
376
+ message: "Deleting from queue is not supported.",
377
+ context: {
378
+ subspaceTag,
379
+ spaceId,
380
+ queueId
381
+ }
382
+ });
383
+ }
384
+ };
385
+
386
+ // src/internal/service-container.ts
387
+ var ServiceContainer = class {
388
+ _executionContext;
389
+ _dataService;
390
+ _queueService;
391
+ constructor(_executionContext, _dataService, _queueService) {
392
+ this._executionContext = _executionContext;
393
+ this._dataService = _dataService;
394
+ this._queueService = _queueService;
395
+ }
396
+ async getSpaceMeta(spaceId) {
397
+ return this._dataService.getSpaceMeta(this._executionContext, spaceId);
398
+ }
399
+ async createServices() {
400
+ const dataService = new DataServiceImpl(this._executionContext, this._dataService);
401
+ const queryService = new QueryServiceImpl(this._executionContext, this._dataService);
402
+ const queueService = new QueueServiceImpl(this._executionContext, this._queueService);
403
+ return {
404
+ dataService,
405
+ queryService,
406
+ queueService
407
+ };
408
+ }
409
+ queryQueue(queue) {
410
+ return this._queueService.query({}, queue.toString(), {});
411
+ }
412
+ insertIntoQueue(queue, objects) {
413
+ return this._queueService.append({}, queue.toString(), objects);
414
+ }
415
+ };
416
+
417
+ // src/space-proxy.ts
418
+ import { Resource } from "@dxos/context";
419
+ import { invariant as invariant4 } from "@dxos/invariant";
420
+ import { PublicKey as PublicKey2 } from "@dxos/keys";
421
+
422
+ // src/queues-api.ts
423
+ var QueuesAPIImpl = class {
424
+ _serviceContainer;
425
+ _spaceId;
426
+ constructor(_serviceContainer, _spaceId) {
427
+ this._serviceContainer = _serviceContainer;
428
+ this._spaceId = _spaceId;
429
+ }
430
+ queryQueue(queue, options) {
431
+ return this._serviceContainer.queryQueue(queue);
432
+ }
433
+ insertIntoQueue(queue, objects) {
434
+ return this._serviceContainer.insertIntoQueue(queue, JSON.parse(JSON.stringify(objects)));
435
+ }
436
+ };
437
+
438
+ // src/space-proxy.ts
439
+ var __dxlog_file4 = "/__w/dxos/dxos/packages/core/functions-runtime-cloudflare/src/space-proxy.ts";
440
+ var SpaceProxy = class extends Resource {
441
+ _serviceContainer;
442
+ _echoClient;
443
+ _id;
444
+ _db = void 0;
445
+ _queuesApi;
446
+ constructor(_serviceContainer, _echoClient, _id) {
447
+ super(), this._serviceContainer = _serviceContainer, this._echoClient = _echoClient, this._id = _id;
448
+ this._queuesApi = new QueuesAPIImpl(this._serviceContainer, this._id);
449
+ }
450
+ get id() {
451
+ return this._id;
452
+ }
453
+ get db() {
454
+ invariant4(this._db, void 0, {
455
+ F: __dxlog_file4,
456
+ L: 34,
457
+ S: this,
458
+ A: [
459
+ "this._db",
460
+ ""
461
+ ]
462
+ });
463
+ return this._db;
464
+ }
465
+ /**
466
+ * @deprecated Use db API.
467
+ */
468
+ get crud() {
469
+ invariant4(this._db, void 0, {
470
+ F: __dxlog_file4,
471
+ L: 42,
472
+ S: this,
473
+ A: [
474
+ "this._db",
475
+ ""
476
+ ]
477
+ });
478
+ return this._db.coreDatabase;
479
+ }
480
+ get queues() {
481
+ return this._queuesApi;
482
+ }
483
+ async _open() {
484
+ const meta = await this._serviceContainer.getSpaceMeta(this._id);
485
+ if (!meta) {
486
+ throw new Error(`Space not found: ${this._id}`);
487
+ }
488
+ this._db = this._echoClient.constructDatabase({
489
+ spaceId: this._id,
490
+ spaceKey: PublicKey2.from(meta.spaceKey),
491
+ reactiveSchemaQuery: false,
492
+ owningObject: this
493
+ });
494
+ await this._db.coreDatabase.open({
495
+ rootUrl: meta.rootDocumentId
496
+ });
497
+ }
498
+ };
499
+
500
+ // src/functions-client.ts
501
+ var __dxlog_file5 = "/__w/dxos/dxos/packages/core/functions-runtime-cloudflare/src/functions-client.ts";
502
+ var FunctionsClient = class extends Resource2 {
503
+ _serviceContainer;
504
+ _echoClient;
505
+ _executionContext = {};
506
+ _spaces = /* @__PURE__ */ new Map();
507
+ constructor(services) {
508
+ super();
509
+ invariant5(typeof services.dataService !== "undefined", "DataService is required", {
510
+ F: __dxlog_file5,
511
+ L: 32,
512
+ S: this,
513
+ A: [
514
+ "typeof services.dataService !== 'undefined'",
515
+ "'DataService is required'"
516
+ ]
517
+ });
518
+ invariant5(typeof services.queueService !== "undefined", "QueueService is required", {
519
+ F: __dxlog_file5,
520
+ L: 33,
521
+ S: this,
522
+ A: [
523
+ "typeof services.queueService !== 'undefined'",
524
+ "'QueueService is required'"
525
+ ]
526
+ });
527
+ this._serviceContainer = new ServiceContainer(this._executionContext, services.dataService, services.queueService);
528
+ this._echoClient = new EchoClient({});
529
+ }
530
+ get echo() {
531
+ return this._echoClient;
532
+ }
533
+ async _open() {
534
+ const { dataService, queryService } = await this._serviceContainer.createServices();
535
+ this._echoClient.connectToService({
536
+ dataService,
537
+ queryService
538
+ });
539
+ await this._echoClient.open();
540
+ }
541
+ async _close() {
542
+ for (const space of this._spaces.values()) {
543
+ await space.close();
544
+ }
545
+ this._spaces.clear();
546
+ await this._echoClient.close();
547
+ }
548
+ async getSpace(spaceId) {
549
+ if (!this._spaces.has(spaceId)) {
550
+ const space2 = new SpaceProxy(this._serviceContainer, this._echoClient, spaceId);
551
+ this._spaces.set(spaceId, space2);
552
+ }
553
+ const space = this._spaces.get(spaceId);
554
+ await space.open();
555
+ return space;
556
+ }
557
+ };
558
+ var createClientFromEnv = async (env) => {
559
+ const client = new FunctionsClient({
560
+ dataService: env.DATA_SERVICE,
561
+ queueService: env.QUEUE_SERVICE
562
+ });
563
+ await client.open();
564
+ return client;
565
+ };
566
+
567
+ // src/types.ts
568
+ var FUNCTION_ROUTE_HEADER = "X-DXOS-Function-Route";
569
+ var FunctionRouteValue = /* @__PURE__ */ (function(FunctionRouteValue2) {
570
+ FunctionRouteValue2["Meta"] = "meta";
571
+ return FunctionRouteValue2;
572
+ })({});
573
+
574
+ // src/wrap-handler-for-cloudflare.ts
575
+ import { invariant as invariant6 } from "@dxos/invariant";
576
+ import { SpaceId as SpaceId4 } from "@dxos/keys";
577
+ import { log as log3 } from "@dxos/log";
578
+ import { EdgeResponse } from "@dxos/protocols";
579
+ var __dxlog_file6 = "/__w/dxos/dxos/packages/core/functions-runtime-cloudflare/src/wrap-handler-for-cloudflare.ts";
580
+ var wrapHandlerForCloudflare = (func) => {
581
+ return async (request, env) => {
582
+ if (request.headers.get(FUNCTION_ROUTE_HEADER) === FunctionRouteValue.Meta) {
583
+ log3.info(">>> meta", {
584
+ func
585
+ }, {
586
+ F: __dxlog_file6,
587
+ L: 25,
588
+ S: void 0,
589
+ C: (f, a) => f(...a)
590
+ });
591
+ return handleFunctionMetaCall(func, request);
592
+ }
593
+ try {
594
+ const spaceId = new URL(request.url).searchParams.get("spaceId");
595
+ if (spaceId) {
596
+ if (!SpaceId4.isValid(spaceId)) {
597
+ return new Response("Invalid spaceId", {
598
+ status: 400
599
+ });
600
+ }
601
+ }
602
+ const serviceContainer = new ServiceContainer({}, env.DATA_SERVICE, env.QUEUE_SERVICE);
603
+ const context = await createFunctionContext({
604
+ serviceContainer,
605
+ contextSpaceId: spaceId
606
+ });
607
+ return EdgeResponse.success(await invokeFunction(func, context, request));
608
+ } catch (error) {
609
+ log3.error("error invoking function", {
610
+ error,
611
+ stack: error.stack
612
+ }, {
613
+ F: __dxlog_file6,
614
+ L: 45,
615
+ S: void 0,
616
+ C: (f, a) => f(...a)
617
+ });
618
+ return EdgeResponse.failure({
619
+ message: error?.message ?? "Internal error",
620
+ error
621
+ });
622
+ }
623
+ };
624
+ };
625
+ var invokeFunction = async (func, context, request) => {
626
+ const { data } = await decodeRequest(request);
627
+ return func.handler({
628
+ context,
629
+ data
630
+ });
631
+ };
632
+ var decodeRequest = async (request) => {
633
+ const { data: { bodyText, ...rest }, trigger } = await request.json();
634
+ if (!bodyText) {
635
+ return {
636
+ data: rest,
637
+ trigger
638
+ };
639
+ }
640
+ try {
641
+ const data = JSON.parse(bodyText);
642
+ return {
643
+ data,
644
+ trigger: {
645
+ ...trigger,
646
+ ...rest
647
+ }
648
+ };
649
+ } catch (err) {
650
+ log3.catch(err, void 0, {
651
+ F: __dxlog_file6,
652
+ L: 80,
653
+ S: void 0,
654
+ C: (f, a) => f(...a)
655
+ });
656
+ return {
657
+ data: {
658
+ bodyText,
659
+ ...rest
660
+ }
661
+ };
662
+ }
663
+ };
664
+ var handleFunctionMetaCall = (functionDefinition, request) => {
665
+ const response = {
666
+ key: functionDefinition.meta.key,
667
+ name: functionDefinition.meta.name,
668
+ description: functionDefinition.meta.description,
669
+ inputSchema: functionDefinition.meta.inputSchema,
670
+ outputSchema: functionDefinition.meta.outputSchema
671
+ };
672
+ return new Response(JSON.stringify(response), {
673
+ headers: {
674
+ "Content-Type": "application/json"
675
+ }
676
+ });
677
+ };
678
+ var createFunctionContext = async ({ serviceContainer, contextSpaceId }) => {
679
+ const { dataService, queryService, queueService } = await serviceContainer.createServices();
680
+ let spaceKey;
681
+ let rootUrl;
682
+ if (contextSpaceId) {
683
+ const meta = await serviceContainer.getSpaceMeta(contextSpaceId);
684
+ if (!meta) {
685
+ throw new Error(`Space not found: ${contextSpaceId}`);
686
+ }
687
+ spaceKey = meta.spaceKey;
688
+ invariant6(!meta.rootDocumentId.startsWith("automerge:"), void 0, {
689
+ F: __dxlog_file6,
690
+ L: 118,
691
+ S: void 0,
692
+ A: [
693
+ "!meta.rootDocumentId.startsWith('automerge:')",
694
+ ""
695
+ ]
696
+ });
697
+ rootUrl = `automerge:${meta.rootDocumentId}`;
698
+ }
699
+ return {
700
+ services: {
701
+ dataService,
702
+ queryService,
703
+ queueService
704
+ },
705
+ spaceId: contextSpaceId,
706
+ spaceKey,
707
+ spaceRootUrl: rootUrl
708
+ };
709
+ };
710
+
711
+ // src/logger.ts
712
+ import { LogLevel, log as log4, shouldLog } from "@dxos/log";
713
+ var setupFunctionsLogger = () => {
714
+ log4.runtimeConfig.processors.length = 0;
715
+ log4.runtimeConfig.processors.push(functionLogProcessor);
716
+ };
717
+ var functionLogProcessor = (config, entry) => {
718
+ if (!shouldLog(entry, config.filters)) {
719
+ return;
720
+ }
721
+ switch (entry.level) {
722
+ case LogLevel.DEBUG:
723
+ console.debug(entry.message, entry.context);
724
+ break;
725
+ case LogLevel.TRACE:
726
+ console.debug(entry.message, entry.context);
727
+ break;
728
+ case LogLevel.VERBOSE:
729
+ console.log(entry.message, entry.context);
730
+ break;
731
+ case LogLevel.INFO:
732
+ console.info(entry.message, entry.context);
733
+ break;
734
+ case LogLevel.WARN:
735
+ console.warn(entry.message, entry.context);
736
+ break;
737
+ case LogLevel.ERROR:
738
+ console.error(entry.message, entry.context);
739
+ break;
740
+ default:
741
+ console.log(entry.message, entry.context);
742
+ break;
743
+ }
744
+ };
745
+ export {
746
+ FUNCTION_ROUTE_HEADER,
747
+ FunctionRouteValue,
748
+ FunctionsClient,
749
+ ServiceContainer,
750
+ createClientFromEnv,
751
+ setupFunctionsLogger,
752
+ wrapHandlerForCloudflare
753
+ };
754
+ //# sourceMappingURL=index.mjs.map