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

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 +774 -213
  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 +774 -213
  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 +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 +4 -1
  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 +4 -3
  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,17 +1,87 @@
1
1
  import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
2
 
3
- // src/wrap-handler-for-cloudflare.ts
4
- import { invariant as invariant4 } from "@dxos/invariant";
5
- import { SpaceId as SpaceId4 } from "@dxos/keys";
6
- import { log as log3 } from "@dxos/log";
7
- import { EdgeResponse } from "@dxos/protocols";
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";
8
7
 
9
8
  // src/internal/data-service-impl.ts
10
9
  import { Stream } from "@dxos/codec-protobuf/stream";
11
10
  import { raise } from "@dxos/debug";
11
+ import { NotImplementedError, RuntimeServiceError } from "@dxos/errors";
12
12
  import { invariant } from "@dxos/invariant";
13
13
  import { SpaceId } from "@dxos/keys";
14
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
+ }
15
85
  var __dxlog_file = "/__w/dxos/dxos/packages/core/functions-runtime-cloudflare/src/internal/data-service-impl.ts";
16
86
  var DataServiceImpl = class {
17
87
  _executionContext;
@@ -25,7 +95,7 @@ var DataServiceImpl = class {
25
95
  return new Stream(({ next }) => {
26
96
  invariant(SpaceId.isValid(spaceId), void 0, {
27
97
  F: __dxlog_file,
28
- L: 34,
98
+ L: 39,
29
99
  S: this,
30
100
  A: [
31
101
  "SpaceId.isValid(spaceId)",
@@ -41,158 +111,218 @@ var DataServiceImpl = class {
41
111
  };
42
112
  });
43
113
  }
44
- async updateSubscription({ subscriptionId, addIds, removeIds }) {
45
- 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
+ }));
46
121
  if (addIds) {
47
122
  log.info("request documents", {
48
123
  count: addIds.length
49
124
  }, {
50
125
  F: __dxlog_file,
51
- L: 47,
126
+ L: 59,
52
127
  S: this,
53
128
  C: (f, a) => f(...a)
54
129
  });
55
130
  for (const documentId of addIds) {
56
- const document = await this._dataService.getDocument(this._executionContext, sub.spaceId, documentId);
57
- log.info("document loaded", {
58
- documentId,
59
- spaceId: sub.spaceId,
60
- found: !!document
61
- }, {
62
- F: __dxlog_file,
63
- L: 51,
64
- S: this,
65
- C: (f, a) => f(...a)
66
- });
67
- if (!document) {
68
- log.warn("not found", {
69
- documentId
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
70
142
  }, {
71
143
  F: __dxlog_file,
72
- L: 53,
144
+ L: 63,
73
145
  S: this,
74
146
  C: (f, a) => f(...a)
75
147
  });
76
- 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);
77
174
  }
78
- sub.next({
79
- updates: [
80
- {
81
- documentId,
82
- mutation: document.data
83
- }
84
- ]
85
- });
86
175
  }
87
176
  }
88
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
+ }
89
199
  async update({ updates, subscriptionId }) {
90
- const sub = this.dataSubscriptions.get(subscriptionId) ?? raise(new Error("Subscription not found"));
91
- for (const update of updates ?? []) {
92
- await this._dataService.changeDocument(this._executionContext, sub.spaceId, update.documentId, update.mutation);
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);
93
218
  }
94
- throw new Error("Method not implemented.");
95
219
  }
96
220
  async flush() {
97
221
  }
98
- subscribeSpaceSyncState(request, options) {
99
- throw new Error("Method not implemented.");
222
+ subscribeSpaceSyncState(_request, _options) {
223
+ throw new NotImplementedError({
224
+ message: "subscribeSpaceSyncState is not implemented."
225
+ });
100
226
  }
101
- async getDocumentHeads({ documentIds }) {
102
- throw new Error("Method not implemented.");
227
+ async getDocumentHeads({ documentIds: _documentIds }) {
228
+ throw new NotImplementedError({
229
+ message: "getDocumentHeads is not implemented."
230
+ });
103
231
  }
104
- async reIndexHeads({ documentIds }) {
105
- throw new Error("Method not implemented.");
232
+ async reIndexHeads({ documentIds: _documentIds }) {
233
+ throw new NotImplementedError({
234
+ message: "reIndexHeads is not implemented."
235
+ });
106
236
  }
107
237
  async updateIndexes() {
108
- 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
+ });
109
244
  }
110
- async waitUntilHeadsReplicated({ heads }) {
111
- throw new Error("Method not implemented.");
245
+ async waitUntilHeadsReplicated({ heads: _heads }) {
246
+ throw new NotImplementedError({
247
+ message: "waitUntilHeadsReplicated is not implemented."
248
+ });
112
249
  }
113
250
  };
114
251
 
115
252
  // src/internal/query-service-impl.ts
116
- import * as Schema from "effect/Schema";
117
253
  import { Stream as Stream2 } from "@dxos/codec-protobuf/stream";
118
- import { QueryAST } from "@dxos/echo-protocol";
119
- import { invariant as invariant3 } from "@dxos/invariant";
120
- import { PublicKey } from "@dxos/keys";
121
- import { SpaceId as SpaceId3 } from "@dxos/keys";
254
+ import { NotImplementedError as NotImplementedError2, RuntimeServiceError as RuntimeServiceError2 } from "@dxos/errors";
122
255
  import { log as log2 } from "@dxos/log";
123
-
124
- // src/internal/adapter.ts
125
- import { failUndefined } from "@dxos/debug";
126
- import { invariant as invariant2 } from "@dxos/invariant";
127
- import { SpaceId as SpaceId2 } from "@dxos/keys";
128
- var __dxlog_file2 = "/__w/dxos/dxos/packages/core/functions-runtime-cloudflare/src/internal/adapter.ts";
129
- var queryToDataServiceRequest = (query) => {
130
- const { filter, options } = isSimpleSelectionQuery(query) ?? failUndefined();
131
- invariant2(options?.spaceIds?.length === 1, "Only one space is supported", {
132
- F: __dxlog_file2,
133
- L: 13,
134
- S: void 0,
135
- A: [
136
- "options?.spaceIds?.length === 1",
137
- "'Only one space is supported'"
138
- ]
139
- });
140
- invariant2(filter.type === "object", "Only object filters are supported", {
141
- F: __dxlog_file2,
142
- L: 14,
143
- S: void 0,
144
- A: [
145
- "filter.type === 'object'",
146
- "'Only object filters are supported'"
147
- ]
148
- });
149
- const spaceId = options.spaceIds[0];
150
- invariant2(SpaceId2.isValid(spaceId), void 0, {
151
- F: __dxlog_file2,
152
- L: 17,
153
- S: void 0,
154
- A: [
155
- "SpaceId.isValid(spaceId)",
156
- ""
157
- ]
158
- });
159
- return {
160
- spaceId,
161
- type: filter.typename ?? void 0,
162
- objectIds: [
163
- ...filter.id ?? []
164
- ]
165
- };
166
- };
167
- var isSimpleSelectionQuery = (query) => {
168
- switch (query.type) {
169
- case "options": {
170
- const maybeFilter = isSimpleSelectionQuery(query.query);
171
- if (!maybeFilter) {
172
- return null;
173
- }
174
- return {
175
- filter: maybeFilter.filter,
176
- options: query.options
177
- };
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
- case "select": {
180
- return {
181
- filter: query.filter,
182
- options: void 0
183
- };
184
- }
185
- default: {
186
- 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;
187
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
+ });
188
286
  }
189
- };
190
-
191
- // src/internal/query-service-impl.ts
192
- var __dxlog_file3 = "/__w/dxos/dxos/packages/core/functions-runtime-cloudflare/src/internal/query-service-impl.ts";
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";
193
322
  var QueryServiceImpl = class {
194
323
  _executionContext;
195
324
  _dataService;
325
+ _queryCount = 0;
196
326
  constructor(_executionContext, _dataService) {
197
327
  this._executionContext = _executionContext;
198
328
  this._dataService = _dataService;
@@ -201,92 +331,142 @@ var QueryServiceImpl = class {
201
331
  log2.info("execQuery", {
202
332
  request
203
333
  }, {
204
- F: __dxlog_file3,
205
- L: 30,
334
+ F: __dxlog_file2,
335
+ L: 20,
206
336
  S: this,
207
337
  C: (f, a) => f(...a)
208
338
  });
209
- const query = QueryAST.Query.pipe(Schema.decodeUnknownSync)(JSON.parse(request.query));
210
- const requestedSpaceIds = getTargetSpacesForQuery(query);
211
- invariant3(requestedSpaceIds.length === 1, "Only one space is supported", {
212
- F: __dxlog_file3,
213
- L: 33,
214
- S: this,
215
- A: [
216
- "requestedSpaceIds.length === 1",
217
- "'Only one space is supported'"
218
- ]
219
- });
220
- const spaceId = requestedSpaceIds[0];
221
339
  return Stream2.fromPromise((async () => {
222
340
  try {
223
- log2.info("begin query", {
224
- spaceId
225
- }, {
226
- F: __dxlog_file3,
227
- L: 39,
228
- S: this,
229
- C: (f, a) => f(...a)
230
- });
231
- const queryResponse = await this._dataService.queryDocuments(this._executionContext, queryToDataServiceRequest(query));
232
- log2.info("query response", {
233
- spaceId,
234
- filter: request.filter,
235
- resultCount: queryResponse.results.length
236
- }, {
237
- F: __dxlog_file3,
238
- L: 44,
239
- S: this,
240
- C: (f, a) => f(...a)
241
- });
242
- return {
243
- results: queryResponse.results.map((object) => ({
244
- id: object.objectId,
245
- spaceId,
246
- spaceKey: PublicKey.ZERO,
247
- documentId: object.document.documentId,
248
- rank: 0,
249
- documentAutomerge: object.document.data
250
- }))
341
+ const env = {
342
+ stack: [],
343
+ error: void 0,
344
+ hasError: false
251
345
  };
252
- } 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) {
253
373
  log2.error("query failed", {
254
- err
374
+ err: error
255
375
  }, {
256
- F: __dxlog_file3,
257
- L: 58,
376
+ F: __dxlog_file2,
377
+ L: 31,
258
378
  S: this,
259
379
  C: (f, a) => f(...a)
260
380
  });
261
- 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
+ });
262
388
  }
263
389
  })());
264
390
  }
265
391
  async reindex() {
266
- throw new Error("Method not implemented.");
392
+ throw new NotImplementedError2({
393
+ message: "Reindex is not implemented."
394
+ });
267
395
  }
268
396
  async setConfig() {
269
- throw new Error("Method not implemented.");
397
+ throw new NotImplementedError2({
398
+ message: "SetConfig is not implemented."
399
+ });
270
400
  }
271
401
  };
272
- var getTargetSpacesForQuery = (query) => {
273
- const spaces = /* @__PURE__ */ new Set();
274
- const visitor = (node) => {
275
- if (node.type === "options") {
276
- if (node.options.spaceIds) {
277
- for (const spaceId of node.options.spaceIds) {
278
- spaces.add(SpaceId3.make(spaceId));
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);
279
462
  }
280
463
  }
464
+ if (s === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve();
465
+ if (env2.hasError) throw env2.error;
281
466
  }
282
- };
283
- QueryAST.visit(query, visitor);
284
- return [
285
- ...spaces
286
- ];
287
- };
288
-
289
- // src/internal/queue-service-impl.ts
467
+ return next();
468
+ })(env);
469
+ }
290
470
  var QueueServiceImpl = class {
291
471
  _ctx;
292
472
  _queueService;
@@ -294,29 +474,194 @@ var QueueServiceImpl = class {
294
474
  this._ctx = _ctx;
295
475
  this._queueService = _queueService;
296
476
  }
297
- queryQueue(subspaceTag, spaceId, { queueId, ...query }) {
298
- 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
+ }
299
537
  }
300
- insertIntoQueue(subspaceTag, spaceId, queueId, objects) {
301
- 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
+ }
302
565
  }
303
- deleteFromQueue(subspaceTag, spaceId, queueId, objectIds) {
304
- throw new Error("Deleting from queue is not supported.");
566
+ async syncQueue(_) {
305
567
  }
306
568
  };
307
569
 
308
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
+ }
309
636
  var ServiceContainer = class {
310
637
  _executionContext;
311
638
  _dataService;
312
639
  _queueService;
313
- constructor(_executionContext, _dataService, _queueService) {
640
+ _functionsService;
641
+ constructor(_executionContext, _dataService, _queueService, _functionsService) {
314
642
  this._executionContext = _executionContext;
315
643
  this._dataService = _dataService;
316
644
  this._queueService = _queueService;
645
+ this._functionsService = _functionsService;
317
646
  }
318
647
  async getSpaceMeta(spaceId) {
319
- 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
+ }
320
665
  }
321
666
  async createServices() {
322
667
  const dataService = new DataServiceImpl(this._executionContext, this._dataService);
@@ -325,15 +670,195 @@ var ServiceContainer = class {
325
670
  return {
326
671
  dataService,
327
672
  queryService,
328
- queueService
673
+ queueService,
674
+ functionsAiService: this._functionsService
675
+ };
676
+ }
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
329
696
  };
330
697
  }
331
- queryQueue(queue) {
332
- return this._queueService.query({}, queue.toString(), {});
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);
333
728
  }
334
729
  insertIntoQueue(queue, objects) {
335
- return this._queueService.append({}, queue.toString(), objects);
730
+ return this._serviceContainer.insertIntoQueue(queue, JSON.parse(JSON.stringify(objects)));
731
+ }
732
+ };
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);
336
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({
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;
337
862
  };
338
863
 
339
864
  // src/types.ts
@@ -344,30 +869,26 @@ var FunctionRouteValue = /* @__PURE__ */ (function(FunctionRouteValue2) {
344
869
  })({});
345
870
 
346
871
  // src/wrap-handler-for-cloudflare.ts
347
- var __dxlog_file4 = "/__w/dxos/dxos/packages/core/functions-runtime-cloudflare/src/wrap-handler-for-cloudflare.ts";
872
+ import { invariant as invariant4 } from "@dxos/invariant";
873
+ import { SpaceId as SpaceId2 } from "@dxos/keys";
874
+ import { log as log3 } from "@dxos/log";
875
+ import { EdgeResponse } from "@dxos/protocols";
876
+ var __dxlog_file5 = "/__w/dxos/dxos/packages/core/functions-runtime-cloudflare/src/wrap-handler-for-cloudflare.ts";
348
877
  var wrapHandlerForCloudflare = (func) => {
349
878
  return async (request, env) => {
350
879
  if (request.headers.get(FUNCTION_ROUTE_HEADER) === FunctionRouteValue.Meta) {
351
- log3.info(">>> meta", {
352
- func
353
- }, {
354
- F: __dxlog_file4,
355
- L: 25,
356
- S: void 0,
357
- C: (f, a) => f(...a)
358
- });
359
880
  return handleFunctionMetaCall(func, request);
360
881
  }
361
882
  try {
362
883
  const spaceId = new URL(request.url).searchParams.get("spaceId");
363
884
  if (spaceId) {
364
- if (!SpaceId4.isValid(spaceId)) {
885
+ if (!SpaceId2.isValid(spaceId)) {
365
886
  return new Response("Invalid spaceId", {
366
887
  status: 400
367
888
  });
368
889
  }
369
890
  }
370
- 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);
371
892
  const context = await createFunctionContext({
372
893
  serviceContainer,
373
894
  contextSpaceId: spaceId
@@ -378,8 +899,8 @@ var wrapHandlerForCloudflare = (func) => {
378
899
  error,
379
900
  stack: error.stack
380
901
  }, {
381
- F: __dxlog_file4,
382
- L: 45,
902
+ F: __dxlog_file5,
903
+ L: 44,
383
904
  S: void 0,
384
905
  C: (f, a) => f(...a)
385
906
  });
@@ -416,8 +937,8 @@ var decodeRequest = async (request) => {
416
937
  };
417
938
  } catch (err) {
418
939
  log3.catch(err, void 0, {
419
- F: __dxlog_file4,
420
- L: 80,
940
+ F: __dxlog_file5,
941
+ L: 79,
421
942
  S: void 0,
422
943
  C: (f, a) => f(...a)
423
944
  });
@@ -444,7 +965,7 @@ var handleFunctionMetaCall = (functionDefinition, request) => {
444
965
  });
445
966
  };
446
967
  var createFunctionContext = async ({ serviceContainer, contextSpaceId }) => {
447
- const { dataService, queryService, queueService } = await serviceContainer.createServices();
968
+ const { dataService, queryService, queueService, functionsAiService } = await serviceContainer.createServices();
448
969
  let spaceKey;
449
970
  let rootUrl;
450
971
  if (contextSpaceId) {
@@ -454,8 +975,8 @@ var createFunctionContext = async ({ serviceContainer, contextSpaceId }) => {
454
975
  }
455
976
  spaceKey = meta.spaceKey;
456
977
  invariant4(!meta.rootDocumentId.startsWith("automerge:"), void 0, {
457
- F: __dxlog_file4,
458
- L: 118,
978
+ F: __dxlog_file5,
979
+ L: 117,
459
980
  S: void 0,
460
981
  A: [
461
982
  "!meta.rootDocumentId.startsWith('automerge:')",
@@ -468,16 +989,56 @@ var createFunctionContext = async ({ serviceContainer, contextSpaceId }) => {
468
989
  services: {
469
990
  dataService,
470
991
  queryService,
471
- queueService
992
+ queueService,
993
+ functionsAiService
472
994
  },
473
995
  spaceId: contextSpaceId,
474
996
  spaceKey,
475
997
  spaceRootUrl: rootUrl
476
998
  };
477
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
+ };
478
1035
  export {
479
1036
  FUNCTION_ROUTE_HEADER,
480
1037
  FunctionRouteValue,
1038
+ FunctionsClient,
1039
+ ServiceContainer,
1040
+ createClientFromEnv,
1041
+ setupFunctionsLogger,
481
1042
  wrapHandlerForCloudflare
482
1043
  };
483
1044
  //# sourceMappingURL=index.mjs.map