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

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 (40) hide show
  1. package/dist/lib/browser/index.mjs +769 -113
  2. package/dist/lib/browser/index.mjs.map +4 -4
  3. package/dist/lib/browser/meta.json +1 -1
  4. package/dist/lib/node-esm/index.mjs +769 -113
  5. package/dist/lib/node-esm/index.mjs.map +4 -4
  6. package/dist/lib/node-esm/meta.json +1 -1
  7. package/dist/types/src/functions-client.d.ts +1 -0
  8. package/dist/types/src/functions-client.d.ts.map +1 -1
  9. package/dist/types/src/index.d.ts +4 -1
  10. package/dist/types/src/index.d.ts.map +1 -1
  11. package/dist/types/src/internal/data-service-impl.d.ts +7 -6
  12. package/dist/types/src/internal/data-service-impl.d.ts.map +1 -1
  13. package/dist/types/src/internal/query-service-impl.d.ts +1 -0
  14. package/dist/types/src/internal/query-service-impl.d.ts.map +1 -1
  15. package/dist/types/src/internal/queue-service-impl.d.ts +4 -5
  16. package/dist/types/src/internal/queue-service-impl.d.ts.map +1 -1
  17. package/dist/types/src/internal/service-container.d.ts +5 -3
  18. package/dist/types/src/internal/service-container.d.ts.map +1 -1
  19. package/dist/types/src/internal/utils.d.ts +2 -0
  20. package/dist/types/src/internal/utils.d.ts.map +1 -0
  21. package/dist/types/src/logger.d.ts +2 -0
  22. package/dist/types/src/logger.d.ts.map +1 -0
  23. package/dist/types/src/queues-api.d.ts +3 -3
  24. package/dist/types/src/queues-api.d.ts.map +1 -1
  25. package/dist/types/src/space-proxy.d.ts +3 -2
  26. package/dist/types/src/space-proxy.d.ts.map +1 -1
  27. package/dist/types/src/wrap-handler-for-cloudflare.d.ts.map +1 -1
  28. package/dist/types/tsconfig.tsbuildinfo +1 -1
  29. package/package.json +20 -15
  30. package/src/functions-client.ts +8 -1
  31. package/src/index.ts +4 -1
  32. package/src/internal/data-service-impl.ts +66 -17
  33. package/src/internal/query-service-impl.ts +24 -8
  34. package/src/internal/queue-service-impl.ts +54 -8
  35. package/src/internal/service-container.ts +25 -6
  36. package/src/internal/utils.ts +5 -0
  37. package/src/logger.ts +42 -0
  38. package/src/queues-api.ts +3 -3
  39. package/src/space-proxy.ts +4 -3
  40. package/src/wrap-handler-for-cloudflare.ts +3 -3
@@ -1,15 +1,85 @@
1
- // src/wrap-handler-for-cloudflare.ts
2
- import { invariant as invariant4 } from "@dxos/invariant";
3
- import { SpaceId as SpaceId4 } from "@dxos/keys";
4
- import { log as log3 } from "@dxos/log";
5
- import { EdgeResponse } from "@dxos/protocols";
1
+ // src/functions-client.ts
2
+ import { Resource as Resource2 } from "@dxos/context";
3
+ import { EchoClient } from "@dxos/echo-db";
4
+ import { invariant as invariant6 } from "@dxos/invariant";
6
5
 
7
6
  // src/internal/data-service-impl.ts
8
7
  import { Stream } from "@dxos/codec-protobuf/stream";
9
8
  import { raise } from "@dxos/debug";
9
+ import { NotImplementedError, RuntimeServiceError } from "@dxos/errors";
10
10
  import { invariant } from "@dxos/invariant";
11
11
  import { SpaceId } from "@dxos/keys";
12
12
  import { log } from "@dxos/log";
13
+
14
+ // src/internal/utils.ts
15
+ var copyUint8Array = (value) => new Uint8Array(value);
16
+
17
+ // src/internal/data-service-impl.ts
18
+ function _ts_add_disposable_resource(env, value, async) {
19
+ if (value !== null && value !== void 0) {
20
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
21
+ var dispose, inner;
22
+ if (async) {
23
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
24
+ dispose = value[Symbol.asyncDispose];
25
+ }
26
+ if (dispose === void 0) {
27
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
28
+ dispose = value[Symbol.dispose];
29
+ if (async) inner = dispose;
30
+ }
31
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
32
+ if (inner) dispose = function() {
33
+ try {
34
+ inner.call(this);
35
+ } catch (e) {
36
+ return Promise.reject(e);
37
+ }
38
+ };
39
+ env.stack.push({
40
+ value,
41
+ dispose,
42
+ async
43
+ });
44
+ } else if (async) {
45
+ env.stack.push({
46
+ async: true
47
+ });
48
+ }
49
+ return value;
50
+ }
51
+ function _ts_dispose_resources(env) {
52
+ var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
53
+ var e = new Error(message);
54
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
55
+ };
56
+ return (_ts_dispose_resources = function _ts_dispose_resources5(env2) {
57
+ function fail(e) {
58
+ env2.error = env2.hasError ? new _SuppressedError(e, env2.error, "An error was suppressed during disposal.") : e;
59
+ env2.hasError = true;
60
+ }
61
+ var r, s = 0;
62
+ function next() {
63
+ while (r = env2.stack.pop()) {
64
+ try {
65
+ if (!r.async && s === 1) return s = 0, env2.stack.push(r), Promise.resolve().then(next);
66
+ if (r.dispose) {
67
+ var result = r.dispose.call(r.value);
68
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
69
+ fail(e);
70
+ return next();
71
+ });
72
+ } else s |= 1;
73
+ } catch (e) {
74
+ fail(e);
75
+ }
76
+ }
77
+ if (s === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve();
78
+ if (env2.hasError) throw env2.error;
79
+ }
80
+ return next();
81
+ })(env);
82
+ }
13
83
  var __dxlog_file = "/__w/dxos/dxos/packages/core/functions-runtime-cloudflare/src/internal/data-service-impl.ts";
14
84
  var DataServiceImpl = class {
15
85
  _executionContext;
@@ -23,7 +93,7 @@ var DataServiceImpl = class {
23
93
  return new Stream(({ next }) => {
24
94
  invariant(SpaceId.isValid(spaceId), void 0, {
25
95
  F: __dxlog_file,
26
- L: 34,
96
+ L: 39,
27
97
  S: this,
28
98
  A: [
29
99
  "SpaceId.isValid(spaceId)",
@@ -39,74 +109,141 @@ var DataServiceImpl = class {
39
109
  };
40
110
  });
41
111
  }
42
- async updateSubscription({ subscriptionId, addIds, removeIds }) {
43
- const sub = this.dataSubscriptions.get(subscriptionId) ?? raise(new Error("Subscription not found"));
112
+ async updateSubscription({ subscriptionId, addIds }) {
113
+ const sub = this.dataSubscriptions.get(subscriptionId) ?? raise(new RuntimeServiceError({
114
+ message: "Subscription not found.",
115
+ context: {
116
+ subscriptionId
117
+ }
118
+ }));
44
119
  if (addIds) {
45
120
  log.info("request documents", {
46
121
  count: addIds.length
47
122
  }, {
48
123
  F: __dxlog_file,
49
- L: 47,
124
+ L: 59,
50
125
  S: this,
51
126
  C: (f, a) => f(...a)
52
127
  });
53
128
  for (const documentId of addIds) {
54
- const document = await this._dataService.getDocument(this._executionContext, sub.spaceId, documentId);
55
- log.info("document loaded", {
56
- documentId,
57
- spaceId: sub.spaceId,
58
- found: !!document
59
- }, {
60
- F: __dxlog_file,
61
- L: 51,
62
- S: this,
63
- C: (f, a) => f(...a)
64
- });
65
- if (!document) {
66
- log.warn("not found", {
67
- documentId
129
+ const env = {
130
+ stack: [],
131
+ error: void 0,
132
+ hasError: false
133
+ };
134
+ try {
135
+ const document = _ts_add_disposable_resource(env, await this._dataService.getDocument(this._executionContext, sub.spaceId, documentId), false);
136
+ log.info("document loaded", {
137
+ documentId,
138
+ spaceId: sub.spaceId,
139
+ found: !!document
68
140
  }, {
69
141
  F: __dxlog_file,
70
- L: 53,
142
+ L: 63,
71
143
  S: this,
72
144
  C: (f, a) => f(...a)
73
145
  });
74
- continue;
146
+ if (!document) {
147
+ log.warn("not found", {
148
+ documentId
149
+ }, {
150
+ F: __dxlog_file,
151
+ L: 65,
152
+ S: this,
153
+ C: (f, a) => f(...a)
154
+ });
155
+ continue;
156
+ }
157
+ sub.next({
158
+ updates: [
159
+ {
160
+ documentId,
161
+ // Copy returned object to avoid hanging RPC stub
162
+ // See https://developers.cloudflare.com/workers/runtime-apis/rpc/lifecycle/
163
+ mutation: copyUint8Array(document.data)
164
+ }
165
+ ]
166
+ });
167
+ } catch (e) {
168
+ env.error = e;
169
+ env.hasError = true;
170
+ } finally {
171
+ _ts_dispose_resources(env);
75
172
  }
76
- sub.next({
77
- updates: [
78
- {
79
- documentId,
80
- mutation: document.data
81
- }
82
- ]
83
- });
84
173
  }
85
174
  }
86
175
  }
176
+ async createDocument({ spaceId, initialValue }) {
177
+ const env = {
178
+ stack: [],
179
+ error: void 0,
180
+ hasError: false
181
+ };
182
+ try {
183
+ const response = _ts_add_disposable_resource(env, await this._dataService.createDocument(this._executionContext, {
184
+ spaceId,
185
+ initialValue
186
+ }), false);
187
+ return {
188
+ documentId: response.documentId
189
+ };
190
+ } catch (e) {
191
+ env.error = e;
192
+ env.hasError = true;
193
+ } finally {
194
+ _ts_dispose_resources(env);
195
+ }
196
+ }
87
197
  async update({ updates, subscriptionId }) {
88
- const sub = this.dataSubscriptions.get(subscriptionId) ?? raise(new Error("Subscription not found"));
89
- for (const update of updates ?? []) {
90
- await this._dataService.changeDocument(this._executionContext, sub.spaceId, update.documentId, update.mutation);
198
+ const sub = this.dataSubscriptions.get(subscriptionId) ?? raise(new RuntimeServiceError({
199
+ message: "Subscription not found.",
200
+ context: {
201
+ subscriptionId
202
+ }
203
+ }));
204
+ try {
205
+ for (const update of updates ?? []) {
206
+ await this._dataService.changeDocument(this._executionContext, sub.spaceId, update.documentId, update.mutation);
207
+ }
208
+ } catch (error) {
209
+ throw RuntimeServiceError.wrap({
210
+ message: "Failed to apply document updates.",
211
+ context: {
212
+ subscriptionId
213
+ },
214
+ ifTypeDiffers: true
215
+ })(error);
91
216
  }
92
- throw new Error("Method not implemented.");
93
217
  }
94
218
  async flush() {
95
219
  }
96
- subscribeSpaceSyncState(request, options) {
97
- throw new Error("Method not implemented.");
220
+ subscribeSpaceSyncState(_request, _options) {
221
+ throw new NotImplementedError({
222
+ message: "subscribeSpaceSyncState is not implemented."
223
+ });
98
224
  }
99
- async getDocumentHeads({ documentIds }) {
100
- throw new Error("Method not implemented.");
225
+ async getDocumentHeads({ documentIds: _documentIds }) {
226
+ throw new NotImplementedError({
227
+ message: "getDocumentHeads is not implemented."
228
+ });
101
229
  }
102
- async reIndexHeads({ documentIds }) {
103
- throw new Error("Method not implemented.");
230
+ async reIndexHeads({ documentIds: _documentIds }) {
231
+ throw new NotImplementedError({
232
+ message: "reIndexHeads is not implemented."
233
+ });
104
234
  }
105
235
  async updateIndexes() {
106
- throw new Error("Method not implemented.");
236
+ log.error("updateIndexes is not available in EDGE env.", void 0, {
237
+ F: __dxlog_file,
238
+ L: 133,
239
+ S: this,
240
+ C: (f, a) => f(...a)
241
+ });
107
242
  }
108
- async waitUntilHeadsReplicated({ heads }) {
109
- throw new Error("Method not implemented.");
243
+ async waitUntilHeadsReplicated({ heads: _heads }) {
244
+ throw new NotImplementedError({
245
+ message: "waitUntilHeadsReplicated is not implemented."
246
+ });
110
247
  }
111
248
  };
112
249
 
@@ -114,6 +251,7 @@ var DataServiceImpl = class {
114
251
  import * as Schema from "effect/Schema";
115
252
  import { Stream as Stream2 } from "@dxos/codec-protobuf/stream";
116
253
  import { QueryAST } from "@dxos/echo-protocol";
254
+ import { NotImplementedError as NotImplementedError2, RuntimeServiceError as RuntimeServiceError2 } from "@dxos/errors";
117
255
  import { invariant as invariant3 } from "@dxos/invariant";
118
256
  import { PublicKey } from "@dxos/keys";
119
257
  import { SpaceId as SpaceId3 } from "@dxos/keys";
@@ -187,10 +325,76 @@ var isSimpleSelectionQuery = (query) => {
187
325
  };
188
326
 
189
327
  // src/internal/query-service-impl.ts
328
+ function _ts_add_disposable_resource2(env, value, async) {
329
+ if (value !== null && value !== void 0) {
330
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
331
+ var dispose, inner;
332
+ if (async) {
333
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
334
+ dispose = value[Symbol.asyncDispose];
335
+ }
336
+ if (dispose === void 0) {
337
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
338
+ dispose = value[Symbol.dispose];
339
+ if (async) inner = dispose;
340
+ }
341
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
342
+ if (inner) dispose = function() {
343
+ try {
344
+ inner.call(this);
345
+ } catch (e) {
346
+ return Promise.reject(e);
347
+ }
348
+ };
349
+ env.stack.push({
350
+ value,
351
+ dispose,
352
+ async
353
+ });
354
+ } else if (async) {
355
+ env.stack.push({
356
+ async: true
357
+ });
358
+ }
359
+ return value;
360
+ }
361
+ function _ts_dispose_resources2(env) {
362
+ var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
363
+ var e = new Error(message);
364
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
365
+ };
366
+ return (_ts_dispose_resources2 = function _ts_dispose_resources5(env2) {
367
+ function fail(e) {
368
+ env2.error = env2.hasError ? new _SuppressedError(e, env2.error, "An error was suppressed during disposal.") : e;
369
+ env2.hasError = true;
370
+ }
371
+ var r, s = 0;
372
+ function next() {
373
+ while (r = env2.stack.pop()) {
374
+ try {
375
+ if (!r.async && s === 1) return s = 0, env2.stack.push(r), Promise.resolve().then(next);
376
+ if (r.dispose) {
377
+ var result = r.dispose.call(r.value);
378
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
379
+ fail(e);
380
+ return next();
381
+ });
382
+ } else s |= 1;
383
+ } catch (e) {
384
+ fail(e);
385
+ }
386
+ }
387
+ if (s === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve();
388
+ if (env2.hasError) throw env2.error;
389
+ }
390
+ return next();
391
+ })(env);
392
+ }
190
393
  var __dxlog_file3 = "/__w/dxos/dxos/packages/core/functions-runtime-cloudflare/src/internal/query-service-impl.ts";
191
394
  var QueryServiceImpl = class {
192
395
  _executionContext;
193
396
  _dataService;
397
+ _queryCount = 0;
194
398
  constructor(_executionContext, _dataService) {
195
399
  this._executionContext = _executionContext;
196
400
  this._dataService = _dataService;
@@ -200,7 +404,7 @@ var QueryServiceImpl = class {
200
404
  request
201
405
  }, {
202
406
  F: __dxlog_file3,
203
- L: 30,
407
+ L: 34,
204
408
  S: this,
205
409
  C: (f, a) => f(...a)
206
410
  });
@@ -208,7 +412,7 @@ var QueryServiceImpl = class {
208
412
  const requestedSpaceIds = getTargetSpacesForQuery(query);
209
413
  invariant3(requestedSpaceIds.length === 1, "Only one space is supported", {
210
414
  F: __dxlog_file3,
211
- L: 33,
415
+ L: 37,
212
416
  S: this,
213
417
  A: [
214
418
  "requestedSpaceIds.length === 1",
@@ -218,53 +422,81 @@ var QueryServiceImpl = class {
218
422
  const spaceId = requestedSpaceIds[0];
219
423
  return Stream2.fromPromise((async () => {
220
424
  try {
221
- log2.info("begin query", {
222
- spaceId
223
- }, {
224
- F: __dxlog_file3,
225
- L: 39,
226
- S: this,
227
- C: (f, a) => f(...a)
228
- });
229
- const queryResponse = await this._dataService.queryDocuments(this._executionContext, queryToDataServiceRequest(query));
230
- log2.info("query response", {
231
- spaceId,
232
- filter: request.filter,
233
- resultCount: queryResponse.results.length
234
- }, {
235
- F: __dxlog_file3,
236
- L: 44,
237
- S: this,
238
- C: (f, a) => f(...a)
239
- });
240
- return {
241
- results: queryResponse.results.map((object) => ({
242
- id: object.objectId,
243
- spaceId,
244
- spaceKey: PublicKey.ZERO,
245
- documentId: object.document.documentId,
246
- rank: 0,
247
- documentAutomerge: object.document.data
248
- }))
425
+ const env = {
426
+ stack: [],
427
+ error: void 0,
428
+ hasError: false
249
429
  };
250
- } catch (err) {
430
+ try {
431
+ this._queryCount++;
432
+ log2.info("begin query", {
433
+ spaceId
434
+ }, {
435
+ F: __dxlog_file3,
436
+ L: 44,
437
+ S: this,
438
+ C: (f, a) => f(...a)
439
+ });
440
+ const queryResponse = _ts_add_disposable_resource2(env, await this._dataService.queryDocuments(this._executionContext, queryToDataServiceRequest(query)), false);
441
+ log2.info("query response", {
442
+ spaceId,
443
+ filter: request.filter,
444
+ resultCount: queryResponse.results.length
445
+ }, {
446
+ F: __dxlog_file3,
447
+ L: 49,
448
+ S: this,
449
+ C: (f, a) => f(...a)
450
+ });
451
+ return {
452
+ results: queryResponse.results.map((object) => ({
453
+ id: object.objectId,
454
+ spaceId,
455
+ spaceKey: PublicKey.ZERO,
456
+ documentId: object.document.documentId,
457
+ // Rank 1 for predicate matches where ranking is not determined.
458
+ rank: 1,
459
+ // Copy returned object to avoid hanging RPC stub.
460
+ // See https://developers.cloudflare.com/workers/runtime-apis/rpc/lifecycle/
461
+ documentAutomerge: copyUint8Array(object.document.data)
462
+ }))
463
+ };
464
+ } catch (e) {
465
+ env.error = e;
466
+ env.hasError = true;
467
+ } finally {
468
+ _ts_dispose_resources2(env);
469
+ }
470
+ } catch (error) {
251
471
  log2.error("query failed", {
252
- err
472
+ err: error
253
473
  }, {
254
474
  F: __dxlog_file3,
255
- L: 58,
475
+ L: 66,
256
476
  S: this,
257
477
  C: (f, a) => f(...a)
258
478
  });
259
- throw err;
479
+ throw new RuntimeServiceError2({
480
+ message: `Query execution failed (queryCount=${this._queryCount})`,
481
+ context: {
482
+ spaceId,
483
+ filter: request.filter,
484
+ queryCount: this._queryCount
485
+ },
486
+ cause: error
487
+ });
260
488
  }
261
489
  })());
262
490
  }
263
491
  async reindex() {
264
- throw new Error("Method not implemented.");
492
+ throw new NotImplementedError2({
493
+ message: "Reindex is not implemented."
494
+ });
265
495
  }
266
496
  async setConfig() {
267
- throw new Error("Method not implemented.");
497
+ throw new NotImplementedError2({
498
+ message: "SetConfig is not implemented."
499
+ });
268
500
  }
269
501
  };
270
502
  var getTargetSpacesForQuery = (query) => {
@@ -285,6 +517,74 @@ var getTargetSpacesForQuery = (query) => {
285
517
  };
286
518
 
287
519
  // src/internal/queue-service-impl.ts
520
+ import { NotImplementedError as NotImplementedError3, RuntimeServiceError as RuntimeServiceError3 } from "@dxos/errors";
521
+ import { invariant as invariant4 } from "@dxos/invariant";
522
+ function _ts_add_disposable_resource3(env, value, async) {
523
+ if (value !== null && value !== void 0) {
524
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
525
+ var dispose, inner;
526
+ if (async) {
527
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
528
+ dispose = value[Symbol.asyncDispose];
529
+ }
530
+ if (dispose === void 0) {
531
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
532
+ dispose = value[Symbol.dispose];
533
+ if (async) inner = dispose;
534
+ }
535
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
536
+ if (inner) dispose = function() {
537
+ try {
538
+ inner.call(this);
539
+ } catch (e) {
540
+ return Promise.reject(e);
541
+ }
542
+ };
543
+ env.stack.push({
544
+ value,
545
+ dispose,
546
+ async
547
+ });
548
+ } else if (async) {
549
+ env.stack.push({
550
+ async: true
551
+ });
552
+ }
553
+ return value;
554
+ }
555
+ function _ts_dispose_resources3(env) {
556
+ var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
557
+ var e = new Error(message);
558
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
559
+ };
560
+ return (_ts_dispose_resources3 = function _ts_dispose_resources5(env2) {
561
+ function fail(e) {
562
+ env2.error = env2.hasError ? new _SuppressedError(e, env2.error, "An error was suppressed during disposal.") : e;
563
+ env2.hasError = true;
564
+ }
565
+ var r, s = 0;
566
+ function next() {
567
+ while (r = env2.stack.pop()) {
568
+ try {
569
+ if (!r.async && s === 1) return s = 0, env2.stack.push(r), Promise.resolve().then(next);
570
+ if (r.dispose) {
571
+ var result = r.dispose.call(r.value);
572
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
573
+ fail(e);
574
+ return next();
575
+ });
576
+ } else s |= 1;
577
+ } catch (e) {
578
+ fail(e);
579
+ }
580
+ }
581
+ if (s === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve();
582
+ if (env2.hasError) throw env2.error;
583
+ }
584
+ return next();
585
+ })(env);
586
+ }
587
+ var __dxlog_file4 = "/__w/dxos/dxos/packages/core/functions-runtime-cloudflare/src/internal/queue-service-impl.ts";
288
588
  var QueueServiceImpl = class {
289
589
  _ctx;
290
590
  _queueService;
@@ -292,29 +592,177 @@ var QueueServiceImpl = class {
292
592
  this._ctx = _ctx;
293
593
  this._queueService = _queueService;
294
594
  }
295
- queryQueue(subspaceTag, spaceId, { queueId, ...query }) {
296
- return this._queueService.query(this._ctx, `dxn:queue:${subspaceTag}:${spaceId}:${queueId}`, query);
595
+ async queryQueue(request) {
596
+ const { query } = request;
597
+ const { queueIds, ...filter } = query;
598
+ const spaceId = query.spaceId;
599
+ const queueId = queueIds?.[0];
600
+ invariant4(request.query.queuesNamespace, void 0, {
601
+ F: __dxlog_file4,
602
+ L: 26,
603
+ S: this,
604
+ A: [
605
+ "request.query.queuesNamespace",
606
+ ""
607
+ ]
608
+ });
609
+ try {
610
+ const env = {
611
+ stack: [],
612
+ error: void 0,
613
+ hasError: false
614
+ };
615
+ try {
616
+ const result = _ts_add_disposable_resource3(env, await this._queueService.query(this._ctx, `dxn:queue:${request.query.queuesNamespace}:${spaceId}:${queueId}`, filter), false);
617
+ return {
618
+ // Copy returned object to avoid hanging RPC stub
619
+ // See https://developers.cloudflare.com/workers/runtime-apis/rpc/lifecycle/
620
+ objects: structuredClone(result.objects),
621
+ nextCursor: result.nextCursor,
622
+ prevCursor: result.prevCursor
623
+ };
624
+ } catch (e) {
625
+ env.error = e;
626
+ env.hasError = true;
627
+ } finally {
628
+ _ts_dispose_resources3(env);
629
+ }
630
+ } catch (error) {
631
+ throw RuntimeServiceError3.wrap({
632
+ message: "Queue query failed.",
633
+ context: {
634
+ subspaceTag: request.query.queuesNamespace,
635
+ spaceId,
636
+ queueId
637
+ },
638
+ ifTypeDiffers: true
639
+ })(error);
640
+ }
297
641
  }
298
- insertIntoQueue(subspaceTag, spaceId, queueId, objects) {
299
- return this._queueService.append(this._ctx, `dxn:queue:${subspaceTag}:${spaceId}:${queueId}`, objects);
642
+ async insertIntoQueue(request) {
643
+ const { subspaceTag, spaceId, queueId, objects } = request;
644
+ try {
645
+ await this._queueService.append(this._ctx, `dxn:queue:${subspaceTag}:${spaceId}:${queueId}`, objects ?? []);
646
+ } catch (error) {
647
+ throw RuntimeServiceError3.wrap({
648
+ message: "Queue append failed.",
649
+ context: {
650
+ subspaceTag,
651
+ spaceId,
652
+ queueId
653
+ },
654
+ ifTypeDiffers: true
655
+ })(error);
656
+ }
300
657
  }
301
- deleteFromQueue(subspaceTag, spaceId, queueId, objectIds) {
302
- throw new Error("Deleting from queue is not supported.");
658
+ deleteFromQueue(request) {
659
+ const { subspaceTag, spaceId, queueId } = request;
660
+ throw new NotImplementedError3({
661
+ message: "Deleting from queue is not supported.",
662
+ context: {
663
+ subspaceTag,
664
+ spaceId,
665
+ queueId
666
+ }
667
+ });
303
668
  }
304
669
  };
305
670
 
306
671
  // src/internal/service-container.ts
672
+ function _ts_add_disposable_resource4(env, value, async) {
673
+ if (value !== null && value !== void 0) {
674
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
675
+ var dispose, inner;
676
+ if (async) {
677
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
678
+ dispose = value[Symbol.asyncDispose];
679
+ }
680
+ if (dispose === void 0) {
681
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
682
+ dispose = value[Symbol.dispose];
683
+ if (async) inner = dispose;
684
+ }
685
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
686
+ if (inner) dispose = function() {
687
+ try {
688
+ inner.call(this);
689
+ } catch (e) {
690
+ return Promise.reject(e);
691
+ }
692
+ };
693
+ env.stack.push({
694
+ value,
695
+ dispose,
696
+ async
697
+ });
698
+ } else if (async) {
699
+ env.stack.push({
700
+ async: true
701
+ });
702
+ }
703
+ return value;
704
+ }
705
+ function _ts_dispose_resources4(env) {
706
+ var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
707
+ var e = new Error(message);
708
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
709
+ };
710
+ return (_ts_dispose_resources4 = function _ts_dispose_resources5(env2) {
711
+ function fail(e) {
712
+ env2.error = env2.hasError ? new _SuppressedError(e, env2.error, "An error was suppressed during disposal.") : e;
713
+ env2.hasError = true;
714
+ }
715
+ var r, s = 0;
716
+ function next() {
717
+ while (r = env2.stack.pop()) {
718
+ try {
719
+ if (!r.async && s === 1) return s = 0, env2.stack.push(r), Promise.resolve().then(next);
720
+ if (r.dispose) {
721
+ var result = r.dispose.call(r.value);
722
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
723
+ fail(e);
724
+ return next();
725
+ });
726
+ } else s |= 1;
727
+ } catch (e) {
728
+ fail(e);
729
+ }
730
+ }
731
+ if (s === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve();
732
+ if (env2.hasError) throw env2.error;
733
+ }
734
+ return next();
735
+ })(env);
736
+ }
307
737
  var ServiceContainer = class {
308
738
  _executionContext;
309
739
  _dataService;
310
740
  _queueService;
311
- constructor(_executionContext, _dataService, _queueService) {
741
+ _functionsService;
742
+ constructor(_executionContext, _dataService, _queueService, _functionsService) {
312
743
  this._executionContext = _executionContext;
313
744
  this._dataService = _dataService;
314
745
  this._queueService = _queueService;
746
+ this._functionsService = _functionsService;
315
747
  }
316
748
  async getSpaceMeta(spaceId) {
317
- return this._dataService.getSpaceMeta(this._executionContext, spaceId);
749
+ const env = {
750
+ stack: [],
751
+ error: void 0,
752
+ hasError: false
753
+ };
754
+ try {
755
+ const result = _ts_add_disposable_resource4(env, await this._dataService.getSpaceMeta(this._executionContext, spaceId), false);
756
+ return result ? {
757
+ spaceKey: result.spaceKey,
758
+ rootDocumentId: result.rootDocumentId
759
+ } : void 0;
760
+ } catch (e) {
761
+ env.error = e;
762
+ env.hasError = true;
763
+ } finally {
764
+ _ts_dispose_resources4(env);
765
+ }
318
766
  }
319
767
  async createServices() {
320
768
  const dataService = new DataServiceImpl(this._executionContext, this._dataService);
@@ -323,16 +771,188 @@ var ServiceContainer = class {
323
771
  return {
324
772
  dataService,
325
773
  queryService,
326
- queueService
774
+ queueService,
775
+ functionsAiService: this._functionsService
776
+ };
777
+ }
778
+ async queryQueue(queue) {
779
+ const env = {
780
+ stack: [],
781
+ error: void 0,
782
+ hasError: false
327
783
  };
784
+ try {
785
+ const { spaceId } = queue.asQueueDXN() ?? {};
786
+ const result = _ts_add_disposable_resource4(env, await this._queueService.query({}, queue.toString(), {
787
+ spaceId
788
+ }), false);
789
+ return {
790
+ objects: structuredClone(result.objects),
791
+ nextCursor: result.nextCursor ?? null,
792
+ prevCursor: result.prevCursor ?? null
793
+ };
794
+ } catch (e) {
795
+ env.error = e;
796
+ env.hasError = true;
797
+ } finally {
798
+ _ts_dispose_resources4(env);
799
+ }
800
+ }
801
+ async insertIntoQueue(queue, objects) {
802
+ await this._queueService.append({}, queue.toString(), objects);
803
+ }
804
+ };
805
+
806
+ // src/space-proxy.ts
807
+ import { Resource } from "@dxos/context";
808
+ import { invariant as invariant5 } from "@dxos/invariant";
809
+ import { PublicKey as PublicKey2 } from "@dxos/keys";
810
+
811
+ // src/queues-api.ts
812
+ var QueuesAPIImpl = class {
813
+ _serviceContainer;
814
+ _spaceId;
815
+ constructor(_serviceContainer, _spaceId) {
816
+ this._serviceContainer = _serviceContainer;
817
+ this._spaceId = _spaceId;
328
818
  }
329
- queryQueue(queue) {
330
- return this._queueService.query({}, queue.toString(), {});
819
+ queryQueue(queue, options) {
820
+ return this._serviceContainer.queryQueue(queue);
331
821
  }
332
822
  insertIntoQueue(queue, objects) {
333
- return this._queueService.append({}, queue.toString(), objects);
823
+ return this._serviceContainer.insertIntoQueue(queue, JSON.parse(JSON.stringify(objects)));
824
+ }
825
+ };
826
+
827
+ // src/space-proxy.ts
828
+ var __dxlog_file5 = "/__w/dxos/dxos/packages/core/functions-runtime-cloudflare/src/space-proxy.ts";
829
+ var SpaceProxy = class extends Resource {
830
+ _serviceContainer;
831
+ _echoClient;
832
+ _id;
833
+ _db = void 0;
834
+ _queuesApi;
835
+ constructor(_serviceContainer, _echoClient, _id) {
836
+ super(), this._serviceContainer = _serviceContainer, this._echoClient = _echoClient, this._id = _id;
837
+ this._queuesApi = new QueuesAPIImpl(this._serviceContainer, this._id);
838
+ }
839
+ get id() {
840
+ return this._id;
841
+ }
842
+ get db() {
843
+ invariant5(this._db, void 0, {
844
+ F: __dxlog_file5,
845
+ L: 35,
846
+ S: this,
847
+ A: [
848
+ "this._db",
849
+ ""
850
+ ]
851
+ });
852
+ return this._db;
853
+ }
854
+ /**
855
+ * @deprecated Use db API.
856
+ */
857
+ get crud() {
858
+ invariant5(this._db, void 0, {
859
+ F: __dxlog_file5,
860
+ L: 43,
861
+ S: this,
862
+ A: [
863
+ "this._db",
864
+ ""
865
+ ]
866
+ });
867
+ return this._db.coreDatabase;
868
+ }
869
+ get queues() {
870
+ return this._queuesApi;
871
+ }
872
+ async _open() {
873
+ const meta = await this._serviceContainer.getSpaceMeta(this._id);
874
+ if (!meta) {
875
+ throw new Error(`Space not found: ${this._id}`);
876
+ }
877
+ this._db = this._echoClient.constructDatabase({
878
+ spaceId: this._id,
879
+ spaceKey: PublicKey2.from(meta.spaceKey),
880
+ reactiveSchemaQuery: false,
881
+ owningObject: this
882
+ });
883
+ await this._db.coreDatabase.open({
884
+ rootUrl: meta.rootDocumentId
885
+ });
886
+ }
887
+ };
888
+
889
+ // src/functions-client.ts
890
+ var __dxlog_file6 = "/__w/dxos/dxos/packages/core/functions-runtime-cloudflare/src/functions-client.ts";
891
+ var FunctionsClient = class extends Resource2 {
892
+ _serviceContainer;
893
+ _echoClient;
894
+ _executionContext = {};
895
+ _spaces = /* @__PURE__ */ new Map();
896
+ constructor(services) {
897
+ super();
898
+ invariant6(typeof services.dataService !== "undefined", "DataService is required", {
899
+ F: __dxlog_file6,
900
+ L: 33,
901
+ S: this,
902
+ A: [
903
+ "typeof services.dataService !== 'undefined'",
904
+ "'DataService is required'"
905
+ ]
906
+ });
907
+ invariant6(typeof services.queueService !== "undefined", "QueueService is required", {
908
+ F: __dxlog_file6,
909
+ L: 34,
910
+ S: this,
911
+ A: [
912
+ "typeof services.queueService !== 'undefined'",
913
+ "'QueueService is required'"
914
+ ]
915
+ });
916
+ this._serviceContainer = new ServiceContainer(this._executionContext, services.dataService, services.queueService, services.functionsAiService);
917
+ this._echoClient = new EchoClient({});
918
+ }
919
+ get echo() {
920
+ return this._echoClient;
921
+ }
922
+ async _open() {
923
+ const { dataService, queryService } = await this._serviceContainer.createServices();
924
+ this._echoClient.connectToService({
925
+ dataService,
926
+ queryService
927
+ });
928
+ await this._echoClient.open();
929
+ }
930
+ async _close() {
931
+ for (const space of this._spaces.values()) {
932
+ await space.close();
933
+ }
934
+ this._spaces.clear();
935
+ await this._echoClient.close();
936
+ }
937
+ async getSpace(spaceId) {
938
+ if (!this._spaces.has(spaceId)) {
939
+ const space2 = new SpaceProxy(this._serviceContainer, this._echoClient, spaceId);
940
+ this._spaces.set(spaceId, space2);
941
+ }
942
+ const space = this._spaces.get(spaceId);
943
+ await space.open();
944
+ return space;
334
945
  }
335
946
  };
947
+ var createClientFromEnv = async (env) => {
948
+ const client = new FunctionsClient({
949
+ dataService: env.DATA_SERVICE,
950
+ queueService: env.QUEUE_SERVICE,
951
+ functionsAiService: env.FUNCTIONS_AI_SERVICE
952
+ });
953
+ await client.open();
954
+ return client;
955
+ };
336
956
 
337
957
  // src/types.ts
338
958
  var FUNCTION_ROUTE_HEADER = "X-DXOS-Function-Route";
@@ -342,18 +962,14 @@ var FunctionRouteValue = /* @__PURE__ */ (function(FunctionRouteValue2) {
342
962
  })({});
343
963
 
344
964
  // src/wrap-handler-for-cloudflare.ts
345
- var __dxlog_file4 = "/__w/dxos/dxos/packages/core/functions-runtime-cloudflare/src/wrap-handler-for-cloudflare.ts";
965
+ import { invariant as invariant7 } from "@dxos/invariant";
966
+ import { SpaceId as SpaceId4 } from "@dxos/keys";
967
+ import { log as log3 } from "@dxos/log";
968
+ import { EdgeResponse } from "@dxos/protocols";
969
+ var __dxlog_file7 = "/__w/dxos/dxos/packages/core/functions-runtime-cloudflare/src/wrap-handler-for-cloudflare.ts";
346
970
  var wrapHandlerForCloudflare = (func) => {
347
971
  return async (request, env) => {
348
972
  if (request.headers.get(FUNCTION_ROUTE_HEADER) === FunctionRouteValue.Meta) {
349
- log3.info(">>> meta", {
350
- func
351
- }, {
352
- F: __dxlog_file4,
353
- L: 25,
354
- S: void 0,
355
- C: (f, a) => f(...a)
356
- });
357
973
  return handleFunctionMetaCall(func, request);
358
974
  }
359
975
  try {
@@ -365,7 +981,7 @@ var wrapHandlerForCloudflare = (func) => {
365
981
  });
366
982
  }
367
983
  }
368
- const serviceContainer = new ServiceContainer({}, env.DATA_SERVICE, env.QUEUE_SERVICE);
984
+ const serviceContainer = new ServiceContainer({}, env.DATA_SERVICE, env.QUEUE_SERVICE, env.FUNCTIONS_AI_SERVICE);
369
985
  const context = await createFunctionContext({
370
986
  serviceContainer,
371
987
  contextSpaceId: spaceId
@@ -376,8 +992,8 @@ var wrapHandlerForCloudflare = (func) => {
376
992
  error,
377
993
  stack: error.stack
378
994
  }, {
379
- F: __dxlog_file4,
380
- L: 45,
995
+ F: __dxlog_file7,
996
+ L: 44,
381
997
  S: void 0,
382
998
  C: (f, a) => f(...a)
383
999
  });
@@ -414,8 +1030,8 @@ var decodeRequest = async (request) => {
414
1030
  };
415
1031
  } catch (err) {
416
1032
  log3.catch(err, void 0, {
417
- F: __dxlog_file4,
418
- L: 80,
1033
+ F: __dxlog_file7,
1034
+ L: 79,
419
1035
  S: void 0,
420
1036
  C: (f, a) => f(...a)
421
1037
  });
@@ -442,7 +1058,7 @@ var handleFunctionMetaCall = (functionDefinition, request) => {
442
1058
  });
443
1059
  };
444
1060
  var createFunctionContext = async ({ serviceContainer, contextSpaceId }) => {
445
- const { dataService, queryService, queueService } = await serviceContainer.createServices();
1061
+ const { dataService, queryService, queueService, functionsAiService } = await serviceContainer.createServices();
446
1062
  let spaceKey;
447
1063
  let rootUrl;
448
1064
  if (contextSpaceId) {
@@ -451,9 +1067,9 @@ var createFunctionContext = async ({ serviceContainer, contextSpaceId }) => {
451
1067
  throw new Error(`Space not found: ${contextSpaceId}`);
452
1068
  }
453
1069
  spaceKey = meta.spaceKey;
454
- invariant4(!meta.rootDocumentId.startsWith("automerge:"), void 0, {
455
- F: __dxlog_file4,
456
- L: 118,
1070
+ invariant7(!meta.rootDocumentId.startsWith("automerge:"), void 0, {
1071
+ F: __dxlog_file7,
1072
+ L: 117,
457
1073
  S: void 0,
458
1074
  A: [
459
1075
  "!meta.rootDocumentId.startsWith('automerge:')",
@@ -466,16 +1082,56 @@ var createFunctionContext = async ({ serviceContainer, contextSpaceId }) => {
466
1082
  services: {
467
1083
  dataService,
468
1084
  queryService,
469
- queueService
1085
+ queueService,
1086
+ functionsAiService
470
1087
  },
471
1088
  spaceId: contextSpaceId,
472
1089
  spaceKey,
473
1090
  spaceRootUrl: rootUrl
474
1091
  };
475
1092
  };
1093
+
1094
+ // src/logger.ts
1095
+ import { LogLevel, log as log4, shouldLog } from "@dxos/log";
1096
+ var setupFunctionsLogger = () => {
1097
+ log4.runtimeConfig.processors.length = 0;
1098
+ log4.runtimeConfig.processors.push(functionLogProcessor);
1099
+ };
1100
+ var functionLogProcessor = (config, entry) => {
1101
+ if (!shouldLog(entry, config.filters)) {
1102
+ return;
1103
+ }
1104
+ switch (entry.level) {
1105
+ case LogLevel.DEBUG:
1106
+ console.debug(entry.message, entry.context);
1107
+ break;
1108
+ case LogLevel.TRACE:
1109
+ console.debug(entry.message, entry.context);
1110
+ break;
1111
+ case LogLevel.VERBOSE:
1112
+ console.log(entry.message, entry.context);
1113
+ break;
1114
+ case LogLevel.INFO:
1115
+ console.info(entry.message, entry.context);
1116
+ break;
1117
+ case LogLevel.WARN:
1118
+ console.warn(entry.message, entry.context);
1119
+ break;
1120
+ case LogLevel.ERROR:
1121
+ console.error(entry.message, entry.context);
1122
+ break;
1123
+ default:
1124
+ console.log(entry.message, entry.context);
1125
+ break;
1126
+ }
1127
+ };
476
1128
  export {
477
1129
  FUNCTION_ROUTE_HEADER,
478
1130
  FunctionRouteValue,
1131
+ FunctionsClient,
1132
+ ServiceContainer,
1133
+ createClientFromEnv,
1134
+ setupFunctionsLogger,
479
1135
  wrapHandlerForCloudflare
480
1136
  };
481
1137
  //# sourceMappingURL=index.mjs.map