@dxos/functions-runtime-cloudflare 0.8.4-main.70d3990 → 0.8.4-main.74a063c4e0

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