@tinycloud/sdk-services 2.0.1 → 2.0.2

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 (139) hide show
  1. package/dist/{types.d.ts → BaseService-D9BFm_rV.d.cts} +179 -27
  2. package/dist/BaseService-D9BFm_rV.d.ts +440 -0
  3. package/dist/index.cjs +3221 -0
  4. package/dist/index.cjs.map +1 -0
  5. package/dist/index.d.cts +1843 -0
  6. package/dist/index.d.ts +1826 -41
  7. package/dist/index.js +3136 -58
  8. package/dist/index.js.map +1 -1
  9. package/dist/kv/index.cjs +909 -0
  10. package/dist/kv/index.cjs.map +1 -0
  11. package/dist/kv/index.d.cts +748 -0
  12. package/dist/kv/index.d.ts +745 -7
  13. package/dist/kv/index.js +877 -9
  14. package/dist/kv/index.js.map +1 -1
  15. package/dist/sql/index.cjs +596 -0
  16. package/dist/sql/index.cjs.map +1 -0
  17. package/dist/sql/index.d.cts +228 -0
  18. package/dist/sql/index.d.ts +225 -7
  19. package/dist/sql/index.js +566 -8
  20. package/dist/sql/index.js.map +1 -1
  21. package/package.json +7 -6
  22. package/dist/base/BaseService.d.ts +0 -151
  23. package/dist/base/BaseService.d.ts.map +0 -1
  24. package/dist/base/BaseService.js +0 -221
  25. package/dist/base/BaseService.js.map +0 -1
  26. package/dist/base/index.d.ts +0 -6
  27. package/dist/base/index.d.ts.map +0 -1
  28. package/dist/base/index.js +0 -6
  29. package/dist/base/index.js.map +0 -1
  30. package/dist/base/types.d.ts +0 -36
  31. package/dist/base/types.d.ts.map +0 -1
  32. package/dist/base/types.js +0 -7
  33. package/dist/base/types.js.map +0 -1
  34. package/dist/context.d.ts +0 -142
  35. package/dist/context.d.ts.map +0 -1
  36. package/dist/context.js +0 -218
  37. package/dist/context.js.map +0 -1
  38. package/dist/duckdb/DuckDbDatabaseHandle.d.ts +0 -23
  39. package/dist/duckdb/DuckDbDatabaseHandle.d.ts.map +0 -1
  40. package/dist/duckdb/DuckDbDatabaseHandle.js +0 -36
  41. package/dist/duckdb/DuckDbDatabaseHandle.js.map +0 -1
  42. package/dist/duckdb/DuckDbService.d.ts +0 -50
  43. package/dist/duckdb/DuckDbService.d.ts.map +0 -1
  44. package/dist/duckdb/DuckDbService.js +0 -285
  45. package/dist/duckdb/DuckDbService.js.map +0 -1
  46. package/dist/duckdb/IDuckDbService.d.ts +0 -84
  47. package/dist/duckdb/IDuckDbService.d.ts.map +0 -1
  48. package/dist/duckdb/IDuckDbService.js +0 -7
  49. package/dist/duckdb/IDuckDbService.js.map +0 -1
  50. package/dist/duckdb/index.d.ts +0 -10
  51. package/dist/duckdb/index.d.ts.map +0 -1
  52. package/dist/duckdb/index.js +0 -9
  53. package/dist/duckdb/index.js.map +0 -1
  54. package/dist/duckdb/types.d.ts +0 -148
  55. package/dist/duckdb/types.d.ts.map +0 -1
  56. package/dist/duckdb/types.js +0 -19
  57. package/dist/duckdb/types.js.map +0 -1
  58. package/dist/errors.d.ts +0 -62
  59. package/dist/errors.d.ts.map +0 -1
  60. package/dist/errors.js +0 -149
  61. package/dist/errors.js.map +0 -1
  62. package/dist/index.d.ts.map +0 -1
  63. package/dist/kv/IKVService.d.ts +0 -148
  64. package/dist/kv/IKVService.d.ts.map +0 -1
  65. package/dist/kv/IKVService.js +0 -8
  66. package/dist/kv/IKVService.js.map +0 -1
  67. package/dist/kv/KVService.d.ts +0 -155
  68. package/dist/kv/KVService.d.ts.map +0 -1
  69. package/dist/kv/KVService.js +0 -419
  70. package/dist/kv/KVService.js.map +0 -1
  71. package/dist/kv/PrefixedKVService.d.ts +0 -246
  72. package/dist/kv/PrefixedKVService.d.ts.map +0 -1
  73. package/dist/kv/PrefixedKVService.js +0 -145
  74. package/dist/kv/PrefixedKVService.js.map +0 -1
  75. package/dist/kv/index.d.ts.map +0 -1
  76. package/dist/kv/types.d.ts +0 -204
  77. package/dist/kv/types.d.ts.map +0 -1
  78. package/dist/kv/types.js +0 -16
  79. package/dist/kv/types.js.map +0 -1
  80. package/dist/quota/TinyCloudQuota.d.ts +0 -27
  81. package/dist/quota/TinyCloudQuota.d.ts.map +0 -1
  82. package/dist/quota/TinyCloudQuota.js +0 -31
  83. package/dist/quota/TinyCloudQuota.js.map +0 -1
  84. package/dist/quota/index.d.ts +0 -3
  85. package/dist/quota/index.d.ts.map +0 -1
  86. package/dist/quota/index.js +0 -2
  87. package/dist/quota/index.js.map +0 -1
  88. package/dist/sql/DatabaseHandle.d.ts +0 -20
  89. package/dist/sql/DatabaseHandle.d.ts.map +0 -1
  90. package/dist/sql/DatabaseHandle.js +0 -27
  91. package/dist/sql/DatabaseHandle.js.map +0 -1
  92. package/dist/sql/ISQLService.d.ts +0 -67
  93. package/dist/sql/ISQLService.d.ts.map +0 -1
  94. package/dist/sql/ISQLService.js +0 -7
  95. package/dist/sql/ISQLService.js.map +0 -1
  96. package/dist/sql/SQLService.d.ts +0 -44
  97. package/dist/sql/SQLService.d.ts.map +0 -1
  98. package/dist/sql/SQLService.js +0 -216
  99. package/dist/sql/SQLService.js.map +0 -1
  100. package/dist/sql/index.d.ts.map +0 -1
  101. package/dist/sql/types.d.ts +0 -102
  102. package/dist/sql/types.d.ts.map +0 -1
  103. package/dist/sql/types.js +0 -21
  104. package/dist/sql/types.js.map +0 -1
  105. package/dist/types.d.ts.map +0 -1
  106. package/dist/types.js +0 -94
  107. package/dist/types.js.map +0 -1
  108. package/dist/types.schema.d.ts +0 -712
  109. package/dist/types.schema.d.ts.map +0 -1
  110. package/dist/types.schema.js +0 -342
  111. package/dist/types.schema.js.map +0 -1
  112. package/dist/types.schema.test.d.ts +0 -5
  113. package/dist/types.schema.test.d.ts.map +0 -1
  114. package/dist/types.schema.test.js +0 -677
  115. package/dist/types.schema.test.js.map +0 -1
  116. package/dist/vault/DataVaultService.d.ts +0 -267
  117. package/dist/vault/DataVaultService.d.ts.map +0 -1
  118. package/dist/vault/DataVaultService.js +0 -1040
  119. package/dist/vault/DataVaultService.js.map +0 -1
  120. package/dist/vault/IDataVaultService.d.ts +0 -158
  121. package/dist/vault/IDataVaultService.d.ts.map +0 -1
  122. package/dist/vault/IDataVaultService.js +0 -8
  123. package/dist/vault/IDataVaultService.js.map +0 -1
  124. package/dist/vault/SignatureCache.d.ts +0 -20
  125. package/dist/vault/SignatureCache.d.ts.map +0 -1
  126. package/dist/vault/SignatureCache.js +0 -167
  127. package/dist/vault/SignatureCache.js.map +0 -1
  128. package/dist/vault/createVaultCrypto.d.ts +0 -16
  129. package/dist/vault/createVaultCrypto.d.ts.map +0 -1
  130. package/dist/vault/createVaultCrypto.js +0 -12
  131. package/dist/vault/createVaultCrypto.js.map +0 -1
  132. package/dist/vault/index.d.ts +0 -11
  133. package/dist/vault/index.d.ts.map +0 -1
  134. package/dist/vault/index.js +0 -12
  135. package/dist/vault/index.js.map +0 -1
  136. package/dist/vault/types.d.ts +0 -141
  137. package/dist/vault/types.d.ts.map +0 -1
  138. package/dist/vault/types.js +0 -31
  139. package/dist/vault/types.js.map +0 -1
package/dist/index.cjs ADDED
@@ -0,0 +1,3221 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ BaseService: () => BaseService,
24
+ DataVaultService: () => DataVaultService,
25
+ DatabaseHandle: () => DatabaseHandle,
26
+ DuckDbAction: () => DuckDbAction,
27
+ DuckDbDatabaseHandle: () => DuckDbDatabaseHandle,
28
+ DuckDbService: () => DuckDbService,
29
+ ErrorCodes: () => ErrorCodes,
30
+ GenericKVResponseSchema: () => GenericKVResponseSchema,
31
+ GenericResultSchema: () => GenericResultSchema,
32
+ KVAction: () => KVAction,
33
+ KVListResponseSchema: () => KVListResponseSchema,
34
+ KVListResultSchema: () => KVListResultSchema,
35
+ KVResponseHeadersSchema: () => KVResponseHeadersSchema,
36
+ KVService: () => KVService,
37
+ PrefixedKVService: () => PrefixedKVService,
38
+ RetryPolicySchema: () => RetryPolicySchema,
39
+ SQLAction: () => SQLAction,
40
+ SQLService: () => SQLService,
41
+ ServiceContext: () => ServiceContext,
42
+ ServiceErrorEventSchema: () => ServiceErrorEventSchema,
43
+ ServiceErrorSchema: () => ServiceErrorSchema,
44
+ ServiceRequestEventSchema: () => ServiceRequestEventSchema,
45
+ ServiceResponseEventSchema: () => ServiceResponseEventSchema,
46
+ ServiceRetryEventSchema: () => ServiceRetryEventSchema,
47
+ ServiceSessionSchema: () => ServiceSessionSchema,
48
+ TelemetryEvents: () => TelemetryEvents,
49
+ TinyCloudQuota: () => TinyCloudQuota,
50
+ VaultHeaders: () => VaultHeaders,
51
+ VaultPublicSpaceKVActions: () => VaultPublicSpaceKVActions,
52
+ abortedError: () => abortedError,
53
+ authExpiredError: () => authExpiredError,
54
+ authRequiredError: () => authRequiredError,
55
+ authUnauthorizedError: () => authUnauthorizedError,
56
+ createKVResponseSchema: () => createKVResponseSchema,
57
+ createResultSchema: () => createResultSchema,
58
+ createVaultCrypto: () => createVaultCrypto,
59
+ defaultRetryPolicy: () => defaultRetryPolicy,
60
+ err: () => err,
61
+ errorResult: () => errorResult,
62
+ networkError: () => networkError,
63
+ notFoundError: () => notFoundError,
64
+ ok: () => ok,
65
+ parseAuthError: () => parseAuthError,
66
+ permissionDeniedError: () => permissionDeniedError,
67
+ serviceError: () => serviceError,
68
+ storageLimitReachedError: () => storageLimitReachedError,
69
+ storageQuotaExceededError: () => storageQuotaExceededError,
70
+ timeoutError: () => timeoutError,
71
+ validateKVListResponse: () => validateKVListResponse,
72
+ validateKVResponseHeaders: () => validateKVResponseHeaders,
73
+ validateRetryPolicy: () => validateRetryPolicy,
74
+ validateServiceError: () => validateServiceError,
75
+ validateServiceRequestEvent: () => validateServiceRequestEvent,
76
+ validateServiceResponseEvent: () => validateServiceResponseEvent,
77
+ validateServiceSession: () => validateServiceSession,
78
+ wrapError: () => wrapError
79
+ });
80
+ module.exports = __toCommonJS(index_exports);
81
+
82
+ // src/types.ts
83
+ var ErrorCodes = {
84
+ // Common errors
85
+ NOT_FOUND: "NOT_FOUND",
86
+ AUTH_EXPIRED: "AUTH_EXPIRED",
87
+ AUTH_REQUIRED: "AUTH_REQUIRED",
88
+ AUTH_UNAUTHORIZED: "AUTH_UNAUTHORIZED",
89
+ NETWORK_ERROR: "NETWORK_ERROR",
90
+ TIMEOUT: "TIMEOUT",
91
+ ABORTED: "ABORTED",
92
+ INVALID_INPUT: "INVALID_INPUT",
93
+ PERMISSION_DENIED: "PERMISSION_DENIED",
94
+ // KV-specific errors
95
+ KV_NOT_FOUND: "KV_NOT_FOUND",
96
+ KV_WRITE_FAILED: "KV_WRITE_FAILED",
97
+ // SQL-specific errors
98
+ SQL_ERROR: "SQL_ERROR",
99
+ SQL_PERMISSION_DENIED: "SQL_PERMISSION_DENIED",
100
+ SQL_DATABASE_NOT_FOUND: "SQL_DATABASE_NOT_FOUND",
101
+ SQL_RESPONSE_TOO_LARGE: "SQL_RESPONSE_TOO_LARGE",
102
+ SQL_QUOTA_EXCEEDED: "SQL_QUOTA_EXCEEDED",
103
+ SQL_INVALID_STATEMENT: "SQL_INVALID_STATEMENT",
104
+ SQL_SCHEMA_ERROR: "SQL_SCHEMA_ERROR",
105
+ SQL_READONLY_VIOLATION: "SQL_READONLY_VIOLATION",
106
+ // Storage quota errors
107
+ STORAGE_QUOTA_EXCEEDED: "STORAGE_QUOTA_EXCEEDED",
108
+ STORAGE_LIMIT_REACHED: "STORAGE_LIMIT_REACHED",
109
+ // DuckDB-specific errors
110
+ DUCKDB_ERROR: "DUCKDB_ERROR",
111
+ DUCKDB_PERMISSION_DENIED: "DUCKDB_PERMISSION_DENIED",
112
+ DUCKDB_DATABASE_NOT_FOUND: "DUCKDB_DATABASE_NOT_FOUND",
113
+ DUCKDB_RESPONSE_TOO_LARGE: "DUCKDB_RESPONSE_TOO_LARGE",
114
+ DUCKDB_QUOTA_EXCEEDED: "DUCKDB_QUOTA_EXCEEDED",
115
+ DUCKDB_INVALID_STATEMENT: "DUCKDB_INVALID_STATEMENT",
116
+ DUCKDB_SCHEMA_ERROR: "DUCKDB_SCHEMA_ERROR",
117
+ DUCKDB_READONLY_VIOLATION: "DUCKDB_READONLY_VIOLATION"
118
+ };
119
+ var defaultRetryPolicy = {
120
+ maxAttempts: 3,
121
+ backoff: "exponential",
122
+ baseDelayMs: 1e3,
123
+ maxDelayMs: 1e4,
124
+ retryableErrors: [ErrorCodes.NETWORK_ERROR, ErrorCodes.TIMEOUT]
125
+ };
126
+ var TelemetryEvents = {
127
+ SERVICE_REQUEST: "service.request",
128
+ SERVICE_RESPONSE: "service.response",
129
+ SERVICE_ERROR: "service.error",
130
+ SERVICE_RETRY: "service.retry",
131
+ SESSION_CHANGED: "session.changed",
132
+ SESSION_EXPIRED: "session.expired"
133
+ };
134
+ function ok(data) {
135
+ return { ok: true, data };
136
+ }
137
+ function err(error) {
138
+ return { ok: false, error };
139
+ }
140
+ function serviceError(code, message, service, options) {
141
+ return {
142
+ code,
143
+ message,
144
+ service,
145
+ cause: options?.cause,
146
+ meta: options?.meta
147
+ };
148
+ }
149
+
150
+ // src/types.schema.ts
151
+ var import_zod = require("zod");
152
+ var ServiceErrorSchema = import_zod.z.object({
153
+ /** Error code for programmatic handling (e.g., 'KV_NOT_FOUND', 'AUTH_EXPIRED') */
154
+ code: import_zod.z.string(),
155
+ /** Human-readable error message */
156
+ message: import_zod.z.string(),
157
+ /** Service that produced the error (e.g., 'kv', 'sql') */
158
+ service: import_zod.z.string(),
159
+ /** Original error if this wraps another error - not validated since Error is a class */
160
+ cause: import_zod.z.unknown().optional(),
161
+ /** Additional metadata about the error - passthrough allows any object properties */
162
+ meta: import_zod.z.object({}).passthrough().optional()
163
+ });
164
+ function createResultSchema(dataSchema, errorSchema = ServiceErrorSchema) {
165
+ return import_zod.z.discriminatedUnion("ok", [
166
+ import_zod.z.object({
167
+ ok: import_zod.z.literal(true),
168
+ data: dataSchema
169
+ }),
170
+ import_zod.z.object({
171
+ ok: import_zod.z.literal(false),
172
+ error: errorSchema
173
+ })
174
+ ]);
175
+ }
176
+ var GenericResultSchema = createResultSchema(import_zod.z.unknown(), ServiceErrorSchema);
177
+ var KVResponseHeadersSchema = import_zod.z.object({
178
+ /** ETag for conditional requests */
179
+ etag: import_zod.z.string().optional(),
180
+ /** Content type of the stored value */
181
+ contentType: import_zod.z.string().optional(),
182
+ /** Last modification timestamp */
183
+ lastModified: import_zod.z.string().optional(),
184
+ /** Content length in bytes */
185
+ contentLength: import_zod.z.number().optional()
186
+ });
187
+ function createKVResponseSchema(dataSchema) {
188
+ return import_zod.z.object({
189
+ /** The data payload */
190
+ data: dataSchema,
191
+ /** Response headers with metadata */
192
+ headers: KVResponseHeadersSchema
193
+ });
194
+ }
195
+ var GenericKVResponseSchema = createKVResponseSchema(import_zod.z.unknown());
196
+ var KVListResponseSchema = import_zod.z.object({
197
+ /** Array of keys matching the list criteria */
198
+ keys: import_zod.z.array(import_zod.z.string())
199
+ });
200
+ var KVListResultSchema = createResultSchema(KVListResponseSchema);
201
+ var ServiceRequestEventSchema = import_zod.z.object({
202
+ service: import_zod.z.string(),
203
+ action: import_zod.z.string(),
204
+ key: import_zod.z.string().optional(),
205
+ timestamp: import_zod.z.number()
206
+ });
207
+ var ServiceResponseEventSchema = import_zod.z.object({
208
+ service: import_zod.z.string(),
209
+ action: import_zod.z.string(),
210
+ ok: import_zod.z.boolean(),
211
+ duration: import_zod.z.number(),
212
+ status: import_zod.z.number().optional()
213
+ });
214
+ var ServiceErrorEventSchema = import_zod.z.object({
215
+ service: import_zod.z.string(),
216
+ error: ServiceErrorSchema
217
+ });
218
+ var ServiceRetryEventSchema = import_zod.z.object({
219
+ service: import_zod.z.string(),
220
+ attempt: import_zod.z.number().int().positive(),
221
+ maxAttempts: import_zod.z.number().int().positive(),
222
+ error: ServiceErrorSchema
223
+ });
224
+ var RetryPolicySchema = import_zod.z.object({
225
+ /** Maximum number of attempts (including initial) */
226
+ maxAttempts: import_zod.z.number().int().positive(),
227
+ /** Backoff strategy between retries */
228
+ backoff: import_zod.z.enum(["none", "linear", "exponential"]),
229
+ /** Base delay in milliseconds for backoff calculation */
230
+ baseDelayMs: import_zod.z.number().nonnegative(),
231
+ /** Maximum delay in milliseconds between retries */
232
+ maxDelayMs: import_zod.z.number().nonnegative(),
233
+ /** Error codes that should trigger a retry */
234
+ retryableErrors: import_zod.z.array(import_zod.z.string())
235
+ });
236
+ var ServiceSessionSchema = import_zod.z.object({
237
+ /** The delegation header containing the UCAN */
238
+ delegationHeader: import_zod.z.object({
239
+ Authorization: import_zod.z.string()
240
+ }),
241
+ /** The delegation CID */
242
+ delegationCid: import_zod.z.string(),
243
+ /** The space ID for this session */
244
+ spaceId: import_zod.z.string(),
245
+ /** The verification method DID */
246
+ verificationMethod: import_zod.z.string(),
247
+ /** The session key JWK (required for invoke) */
248
+ jwk: import_zod.z.object({}).passthrough()
249
+ });
250
+ function validateServiceError(data) {
251
+ const result = ServiceErrorSchema.safeParse(data);
252
+ if (!result.success) {
253
+ return {
254
+ ok: false,
255
+ error: {
256
+ code: "VALIDATION_ERROR",
257
+ message: result.error.message,
258
+ service: "validation",
259
+ meta: { issues: result.error.issues }
260
+ }
261
+ };
262
+ }
263
+ return { ok: true, data: result.data };
264
+ }
265
+ function validateKVListResponse(data) {
266
+ const result = KVListResponseSchema.safeParse(data);
267
+ if (!result.success) {
268
+ return {
269
+ ok: false,
270
+ error: {
271
+ code: "VALIDATION_ERROR",
272
+ message: result.error.message,
273
+ service: "kv",
274
+ meta: { issues: result.error.issues }
275
+ }
276
+ };
277
+ }
278
+ return { ok: true, data: result.data };
279
+ }
280
+ function validateKVResponseHeaders(data) {
281
+ const result = KVResponseHeadersSchema.safeParse(data);
282
+ if (!result.success) {
283
+ return {
284
+ ok: false,
285
+ error: {
286
+ code: "VALIDATION_ERROR",
287
+ message: result.error.message,
288
+ service: "kv",
289
+ meta: { issues: result.error.issues }
290
+ }
291
+ };
292
+ }
293
+ return { ok: true, data: result.data };
294
+ }
295
+ function validateServiceSession(data) {
296
+ const result = ServiceSessionSchema.safeParse(data);
297
+ if (!result.success) {
298
+ return {
299
+ ok: false,
300
+ error: {
301
+ code: "VALIDATION_ERROR",
302
+ message: result.error.message,
303
+ service: "session",
304
+ meta: { issues: result.error.issues }
305
+ }
306
+ };
307
+ }
308
+ return { ok: true, data: result.data };
309
+ }
310
+ function validateRetryPolicy(data) {
311
+ const result = RetryPolicySchema.safeParse(data);
312
+ if (!result.success) {
313
+ return {
314
+ ok: false,
315
+ error: {
316
+ code: "VALIDATION_ERROR",
317
+ message: result.error.message,
318
+ service: "config",
319
+ meta: { issues: result.error.issues }
320
+ }
321
+ };
322
+ }
323
+ return { ok: true, data: result.data };
324
+ }
325
+ function validateServiceRequestEvent(data) {
326
+ const result = ServiceRequestEventSchema.safeParse(data);
327
+ if (!result.success) {
328
+ return {
329
+ ok: false,
330
+ error: {
331
+ code: "VALIDATION_ERROR",
332
+ message: result.error.message,
333
+ service: "telemetry",
334
+ meta: { issues: result.error.issues }
335
+ }
336
+ };
337
+ }
338
+ return { ok: true, data: result.data };
339
+ }
340
+ function validateServiceResponseEvent(data) {
341
+ const result = ServiceResponseEventSchema.safeParse(data);
342
+ if (!result.success) {
343
+ return {
344
+ ok: false,
345
+ error: {
346
+ code: "VALIDATION_ERROR",
347
+ message: result.error.message,
348
+ service: "telemetry",
349
+ meta: { issues: result.error.issues }
350
+ }
351
+ };
352
+ }
353
+ return { ok: true, data: result.data };
354
+ }
355
+
356
+ // src/context.ts
357
+ var ServiceContext = class {
358
+ constructor(config) {
359
+ this._session = null;
360
+ this._services = /* @__PURE__ */ new Map();
361
+ this._eventHandlers = /* @__PURE__ */ new Map();
362
+ this._abortController = new AbortController();
363
+ this._invoke = config.invoke;
364
+ this._fetch = config.fetch ?? globalThis.fetch.bind(globalThis);
365
+ this._hosts = config.hosts;
366
+ this._session = config.session ?? null;
367
+ this._retryPolicy = {
368
+ ...defaultRetryPolicy,
369
+ ...config.retryPolicy
370
+ };
371
+ }
372
+ // ============================================================
373
+ // Session Management
374
+ // ============================================================
375
+ /**
376
+ * Get the current session.
377
+ */
378
+ get session() {
379
+ return this._session;
380
+ }
381
+ /**
382
+ * Check if the context has an authenticated session.
383
+ */
384
+ get isAuthenticated() {
385
+ return this._session !== null;
386
+ }
387
+ /**
388
+ * Update the session and notify all registered services.
389
+ *
390
+ * @param session - New session or null to clear
391
+ */
392
+ setSession(session) {
393
+ this._session = session;
394
+ this.emit("session.changed", { authenticated: session !== null });
395
+ for (const service of this._services.values()) {
396
+ service.onSessionChange(session);
397
+ }
398
+ }
399
+ // ============================================================
400
+ // Platform Dependencies
401
+ // ============================================================
402
+ /**
403
+ * Get the invoke function for WASM operations.
404
+ */
405
+ get invoke() {
406
+ return this._invoke;
407
+ }
408
+ /**
409
+ * Get the fetch function for HTTP requests.
410
+ */
411
+ get fetch() {
412
+ return this._fetch;
413
+ }
414
+ /**
415
+ * Get the list of TinyCloud host URLs.
416
+ */
417
+ get hosts() {
418
+ return this._hosts;
419
+ }
420
+ // ============================================================
421
+ // Service Registry
422
+ // ============================================================
423
+ /**
424
+ * Register a service with the context.
425
+ *
426
+ * @param name - Service name (e.g., 'kv')
427
+ * @param service - Service instance
428
+ */
429
+ registerService(name, service) {
430
+ this._services.set(name, service);
431
+ }
432
+ /**
433
+ * Unregister a service from the context.
434
+ *
435
+ * @param name - Service name to remove
436
+ */
437
+ unregisterService(name) {
438
+ this._services.delete(name);
439
+ }
440
+ /**
441
+ * Get a registered service by name.
442
+ *
443
+ * @param name - Service name
444
+ * @returns The service instance or undefined if not registered
445
+ */
446
+ getService(name) {
447
+ return this._services.get(name);
448
+ }
449
+ // ============================================================
450
+ // Event System (Telemetry)
451
+ // ============================================================
452
+ /**
453
+ * Emit a telemetry event.
454
+ *
455
+ * @param event - Event name
456
+ * @param data - Event data
457
+ */
458
+ emit(event, data) {
459
+ const handlers = this._eventHandlers.get(event);
460
+ if (handlers) {
461
+ for (const handler of handlers) {
462
+ try {
463
+ handler(data);
464
+ } catch (error) {
465
+ console.error(`Error in event handler for "${event}":`, error);
466
+ }
467
+ }
468
+ }
469
+ }
470
+ /**
471
+ * Subscribe to telemetry events.
472
+ *
473
+ * @param event - Event name to subscribe to
474
+ * @param handler - Handler function
475
+ * @returns Unsubscribe function
476
+ */
477
+ on(event, handler) {
478
+ if (!this._eventHandlers.has(event)) {
479
+ this._eventHandlers.set(event, /* @__PURE__ */ new Set());
480
+ }
481
+ this._eventHandlers.get(event).add(handler);
482
+ return () => {
483
+ const handlers = this._eventHandlers.get(event);
484
+ if (handlers) {
485
+ handlers.delete(handler);
486
+ if (handlers.size === 0) {
487
+ this._eventHandlers.delete(event);
488
+ }
489
+ }
490
+ };
491
+ }
492
+ /**
493
+ * Remove all event handlers for an event.
494
+ *
495
+ * @param event - Event name (if omitted, clears all events)
496
+ */
497
+ clearEventHandlers(event) {
498
+ if (event) {
499
+ this._eventHandlers.delete(event);
500
+ } else {
501
+ this._eventHandlers.clear();
502
+ }
503
+ }
504
+ // ============================================================
505
+ // Lifecycle
506
+ // ============================================================
507
+ /**
508
+ * Get the abort signal for cancelling operations.
509
+ */
510
+ get abortSignal() {
511
+ return this._abortController.signal;
512
+ }
513
+ /**
514
+ * Abort all pending operations and notify services.
515
+ * Creates a new AbortController for future operations.
516
+ */
517
+ abort() {
518
+ this._abortController.abort();
519
+ this._abortController = new AbortController();
520
+ for (const service of this._services.values()) {
521
+ service.onSignOut();
522
+ }
523
+ }
524
+ /**
525
+ * Sign out - abort operations and clear session.
526
+ */
527
+ signOut() {
528
+ this.abort();
529
+ this.setSession(null);
530
+ this.emit("session.expired", {});
531
+ }
532
+ // ============================================================
533
+ // Retry Policy
534
+ // ============================================================
535
+ /**
536
+ * Get the retry policy configuration.
537
+ */
538
+ get retryPolicy() {
539
+ return this._retryPolicy;
540
+ }
541
+ };
542
+
543
+ // src/errors.ts
544
+ function authRequiredError(service) {
545
+ return {
546
+ code: ErrorCodes.AUTH_REQUIRED,
547
+ message: "Authentication required. Please sign in first.",
548
+ service
549
+ };
550
+ }
551
+ function authExpiredError(service) {
552
+ return {
553
+ code: ErrorCodes.AUTH_EXPIRED,
554
+ message: "Session has expired. Please sign in again.",
555
+ service
556
+ };
557
+ }
558
+ function networkError(service, message, cause) {
559
+ return {
560
+ code: ErrorCodes.NETWORK_ERROR,
561
+ message,
562
+ service,
563
+ cause
564
+ };
565
+ }
566
+ function timeoutError(service) {
567
+ return {
568
+ code: ErrorCodes.TIMEOUT,
569
+ message: "Request timed out.",
570
+ service
571
+ };
572
+ }
573
+ function abortedError(service) {
574
+ return {
575
+ code: ErrorCodes.ABORTED,
576
+ message: "Request was aborted.",
577
+ service
578
+ };
579
+ }
580
+ function notFoundError(service, resource) {
581
+ return {
582
+ code: ErrorCodes.NOT_FOUND,
583
+ message: `Resource not found: ${resource}`,
584
+ service
585
+ };
586
+ }
587
+ function permissionDeniedError(service, action) {
588
+ return {
589
+ code: ErrorCodes.PERMISSION_DENIED,
590
+ message: `Permission denied for action: ${action}`,
591
+ service
592
+ };
593
+ }
594
+ function parseAuthError(responseText) {
595
+ const match = responseText.match(/^Unauthorized Action:\s*(.+?)\s*\/\s*(tinycloud\.\S+)$/m);
596
+ if (match) {
597
+ return { resource: match[1].trim(), action: match[2].trim() };
598
+ }
599
+ return {};
600
+ }
601
+ function authUnauthorizedError(service, message, meta) {
602
+ return serviceError(ErrorCodes.AUTH_UNAUTHORIZED, message, service, { meta });
603
+ }
604
+ function storageQuotaExceededError(service, message, meta) {
605
+ return {
606
+ code: ErrorCodes.STORAGE_QUOTA_EXCEEDED,
607
+ message,
608
+ service,
609
+ meta
610
+ };
611
+ }
612
+ function storageLimitReachedError(service, message, meta) {
613
+ return {
614
+ code: ErrorCodes.STORAGE_LIMIT_REACHED,
615
+ message,
616
+ service,
617
+ meta
618
+ };
619
+ }
620
+ function wrapError(service, error, defaultCode = ErrorCodes.NETWORK_ERROR) {
621
+ if (error instanceof Error) {
622
+ if (error.name === "AbortError") {
623
+ return abortedError(service);
624
+ }
625
+ if (error.name === "TimeoutError" || error.message.toLowerCase().includes("timeout")) {
626
+ return timeoutError(service);
627
+ }
628
+ return {
629
+ code: defaultCode,
630
+ message: error.message,
631
+ service,
632
+ cause: error
633
+ };
634
+ }
635
+ return {
636
+ code: defaultCode,
637
+ message: String(error),
638
+ service
639
+ };
640
+ }
641
+ function errorResult(error) {
642
+ return err(error);
643
+ }
644
+
645
+ // src/base/BaseService.ts
646
+ var BaseService = class {
647
+ constructor() {
648
+ /**
649
+ * Abort controller for this service's operations.
650
+ * Reset on sign-out.
651
+ */
652
+ this.abortController = new AbortController();
653
+ /**
654
+ * Service-specific configuration.
655
+ */
656
+ this._config = {};
657
+ }
658
+ /**
659
+ * Get the service configuration.
660
+ */
661
+ get config() {
662
+ return this._config;
663
+ }
664
+ /**
665
+ * Initialize the service with context.
666
+ * Called by the SDK after instantiation.
667
+ *
668
+ * @param context - The service context
669
+ */
670
+ initialize(context) {
671
+ this.context = context;
672
+ }
673
+ /**
674
+ * Called when session changes (sign-in, sign-out, refresh).
675
+ * Override in subclasses to handle session changes.
676
+ *
677
+ * @param session - The new session, or null if signed out
678
+ */
679
+ onSessionChange(session) {
680
+ }
681
+ /**
682
+ * Called when SDK signs out.
683
+ * Aborts all pending operations.
684
+ */
685
+ onSignOut() {
686
+ this.abortController.abort();
687
+ this.abortController = new AbortController();
688
+ }
689
+ /**
690
+ * Get the abort signal for this service.
691
+ * Combines the service-level abort with context-level abort.
692
+ */
693
+ get abortSignal() {
694
+ return this.abortController.signal;
695
+ }
696
+ /**
697
+ * Check if the service is authenticated.
698
+ */
699
+ get isAuthenticated() {
700
+ return this.context?.isAuthenticated ?? false;
701
+ }
702
+ /**
703
+ * Get the current session.
704
+ * Throws if not authenticated.
705
+ */
706
+ get session() {
707
+ if (!this.context?.session) {
708
+ throw new Error("Not authenticated");
709
+ }
710
+ return this.context.session;
711
+ }
712
+ /**
713
+ * Check authentication and return error result if not authenticated.
714
+ * Use this at the start of methods that require authentication.
715
+ *
716
+ * @returns true if authenticated, false otherwise
717
+ */
718
+ requireAuth() {
719
+ return this.isAuthenticated;
720
+ }
721
+ /**
722
+ * Emit a telemetry event.
723
+ *
724
+ * @param event - Event name
725
+ * @param data - Event data
726
+ */
727
+ emit(event, data) {
728
+ this.context?.emit(event, data);
729
+ }
730
+ /**
731
+ * Emit a service request event.
732
+ *
733
+ * @param action - The action being performed
734
+ * @param key - Optional key/path being accessed
735
+ */
736
+ emitRequest(action, key) {
737
+ this.emit(TelemetryEvents.SERVICE_REQUEST, {
738
+ service: this.getServiceName(),
739
+ action,
740
+ key,
741
+ timestamp: Date.now()
742
+ });
743
+ }
744
+ /**
745
+ * Emit a service response event.
746
+ *
747
+ * @param action - The action that was performed
748
+ * @param ok - Whether the request was successful
749
+ * @param startTime - Start time for duration calculation
750
+ * @param status - Optional HTTP status code
751
+ */
752
+ emitResponse(action, ok2, startTime, status) {
753
+ this.emit(TelemetryEvents.SERVICE_RESPONSE, {
754
+ service: this.getServiceName(),
755
+ action,
756
+ ok: ok2,
757
+ duration: Date.now() - startTime,
758
+ status
759
+ });
760
+ }
761
+ /**
762
+ * Emit a service error event.
763
+ *
764
+ * @param error - The service error
765
+ */
766
+ emitError(error) {
767
+ this.emit(TelemetryEvents.SERVICE_ERROR, {
768
+ service: this.getServiceName(),
769
+ error
770
+ });
771
+ }
772
+ /**
773
+ * Get the service name from the static property.
774
+ * Subclasses must define static serviceName.
775
+ */
776
+ getServiceName() {
777
+ return this.constructor.serviceName;
778
+ }
779
+ /**
780
+ * Create a combined abort signal from multiple sources.
781
+ *
782
+ * @param signals - Additional abort signals to combine
783
+ * @returns A combined abort signal
784
+ */
785
+ combineSignals(...signals) {
786
+ const controller = new AbortController();
787
+ const allSignals = [this.abortSignal, ...signals.filter(Boolean)];
788
+ for (const signal of allSignals) {
789
+ if (signal.aborted) {
790
+ controller.abort(signal.reason);
791
+ return controller.signal;
792
+ }
793
+ signal.addEventListener("abort", () => controller.abort(signal.reason), {
794
+ once: true
795
+ });
796
+ }
797
+ return controller.signal;
798
+ }
799
+ /**
800
+ * Wrap an operation with error handling and telemetry.
801
+ *
802
+ * @param action - The action name for telemetry
803
+ * @param key - Optional key for telemetry
804
+ * @param operation - The operation to execute
805
+ * @returns Result of the operation
806
+ */
807
+ async withTelemetry(action, key, operation) {
808
+ const startTime = Date.now();
809
+ this.emitRequest(action, key);
810
+ try {
811
+ const result = await operation();
812
+ if (result.ok) {
813
+ this.emitResponse(action, true, startTime);
814
+ } else {
815
+ this.emitResponse(action, false, startTime);
816
+ this.emitError(result.error);
817
+ }
818
+ return result;
819
+ } catch (error) {
820
+ const serviceError3 = wrapError(this.getServiceName(), error);
821
+ this.emitResponse(action, false, startTime);
822
+ this.emitError(serviceError3);
823
+ return err(serviceError3);
824
+ }
825
+ }
826
+ };
827
+
828
+ // src/kv/PrefixedKVService.ts
829
+ var PrefixedKVService = class _PrefixedKVService {
830
+ /**
831
+ * Create a new PrefixedKVService.
832
+ *
833
+ * @param kv - The underlying KV service to delegate to
834
+ * @param prefix - The prefix to apply to all operations
835
+ */
836
+ constructor(kv, prefix) {
837
+ this._kv = kv;
838
+ this._prefix = prefix.endsWith("/") ? prefix.slice(0, -1) : prefix;
839
+ }
840
+ /**
841
+ * The current prefix for this scoped view.
842
+ */
843
+ get prefix() {
844
+ return this._prefix;
845
+ }
846
+ /**
847
+ * Compute the full key path by combining prefix and key.
848
+ *
849
+ * @param key - The key to prefix
850
+ * @returns The full path including prefix
851
+ */
852
+ getFullKey(key) {
853
+ const normalizedKey = key.startsWith("/") ? key : `/${key}`;
854
+ return `${this._prefix}${normalizedKey}`;
855
+ }
856
+ /**
857
+ * Get a value by key.
858
+ */
859
+ async get(key, options) {
860
+ const fullKey = this.getFullKey(key);
861
+ return this._kv.get(fullKey, { ...options, prefix: "" });
862
+ }
863
+ /**
864
+ * Store a value at a key.
865
+ */
866
+ async put(key, value, options) {
867
+ const fullKey = this.getFullKey(key);
868
+ return this._kv.put(fullKey, value, { ...options, prefix: "" });
869
+ }
870
+ /**
871
+ * List keys within this prefix.
872
+ */
873
+ async list(options) {
874
+ const removePrefix = options?.removePrefix ?? true;
875
+ return this._kv.list({
876
+ ...options,
877
+ prefix: this._prefix,
878
+ removePrefix
879
+ });
880
+ }
881
+ /**
882
+ * Delete a key.
883
+ */
884
+ async delete(key, options) {
885
+ const fullKey = this.getFullKey(key);
886
+ return this._kv.delete(fullKey, { ...options, prefix: "" });
887
+ }
888
+ /**
889
+ * Get metadata for a key without retrieving the value.
890
+ */
891
+ async head(key, options) {
892
+ const fullKey = this.getFullKey(key);
893
+ return this._kv.head(fullKey, { ...options, prefix: "" });
894
+ }
895
+ /**
896
+ * Create a nested prefix-scoped view.
897
+ */
898
+ withPrefix(subPrefix) {
899
+ const normalizedSubPrefix = subPrefix.startsWith("/") ? subPrefix : `/${subPrefix}`;
900
+ const combinedPrefix = `${this._prefix}${normalizedSubPrefix}`;
901
+ return new _PrefixedKVService(this._kv, combinedPrefix);
902
+ }
903
+ };
904
+
905
+ // src/kv/types.ts
906
+ var KVAction = {
907
+ GET: "tinycloud.kv/get",
908
+ PUT: "tinycloud.kv/put",
909
+ LIST: "tinycloud.kv/list",
910
+ DELETE: "tinycloud.kv/del",
911
+ HEAD: "tinycloud.kv/metadata"
912
+ };
913
+
914
+ // src/kv/KVService.ts
915
+ var KVService = class extends BaseService {
916
+ /**
917
+ * Create a new KVService instance.
918
+ *
919
+ * @param config - Service configuration
920
+ */
921
+ constructor(config = {}) {
922
+ super();
923
+ this._config = config;
924
+ }
925
+ /**
926
+ * Get the service configuration.
927
+ */
928
+ get config() {
929
+ return this._config;
930
+ }
931
+ // Parses "Used: X bytes, Limit: Y bytes" from tinycloud-node error responses
932
+ parseQuotaInfo(errorText) {
933
+ const match = errorText.match(
934
+ /Used:\s*(\d+)\s*bytes,\s*Limit:\s*(\d+)\s*bytes/i
935
+ );
936
+ if (match) {
937
+ return {
938
+ usedBytes: parseInt(match[1], 10),
939
+ limitBytes: parseInt(match[2], 10)
940
+ };
941
+ }
942
+ return void 0;
943
+ }
944
+ handleQuotaErrorResponse(response, errorText, key) {
945
+ if (response.status === 402) {
946
+ const quotaInfo = this.parseQuotaInfo(errorText);
947
+ return err(
948
+ storageQuotaExceededError(
949
+ "kv",
950
+ `Storage quota exceeded for key "${key}": ${errorText}`,
951
+ {
952
+ status: response.status,
953
+ ...quotaInfo ? { usedBytes: quotaInfo.usedBytes, limitBytes: quotaInfo.limitBytes } : {}
954
+ }
955
+ )
956
+ );
957
+ }
958
+ if (response.status === 413) {
959
+ const quotaInfo = this.parseQuotaInfo(errorText);
960
+ return err(
961
+ storageLimitReachedError(
962
+ "kv",
963
+ `Storage limit reached for key "${key}": ${errorText}`,
964
+ {
965
+ status: response.status,
966
+ ...quotaInfo ? { usedBytes: quotaInfo.usedBytes, limitBytes: quotaInfo.limitBytes } : {}
967
+ }
968
+ )
969
+ );
970
+ }
971
+ return void 0;
972
+ }
973
+ /**
974
+ * Get the full path with optional prefix.
975
+ *
976
+ * @param key - The key
977
+ * @param prefixOverride - Optional prefix override
978
+ * @returns The full path
979
+ */
980
+ getFullPath(key, prefixOverride) {
981
+ const prefix = prefixOverride ?? this._config.prefix ?? "";
982
+ return prefix ? `${prefix}/${key}` : key;
983
+ }
984
+ /**
985
+ * Get the host URL.
986
+ */
987
+ get host() {
988
+ return this.context.hosts[0];
989
+ }
990
+ /**
991
+ * Execute an invoke operation.
992
+ *
993
+ * @param path - Resource path
994
+ * @param action - KV action
995
+ * @param body - Optional request body
996
+ * @param signal - Optional abort signal
997
+ * @returns Fetch response
998
+ */
999
+ async invokeOperation(path, action, body, signal) {
1000
+ const session = this.context.session;
1001
+ const headers = this.context.invoke(
1002
+ session,
1003
+ "kv",
1004
+ path,
1005
+ action
1006
+ );
1007
+ return this.context.fetch(`${this.host}/invoke`, {
1008
+ method: "POST",
1009
+ headers,
1010
+ body,
1011
+ signal: this.combineSignals(signal)
1012
+ });
1013
+ }
1014
+ /**
1015
+ * Create KVResponseHeaders from fetch response headers.
1016
+ *
1017
+ * @param headers - Fetch response headers
1018
+ * @returns KVResponseHeaders object
1019
+ */
1020
+ createResponseHeaders(headers) {
1021
+ return {
1022
+ etag: headers.get("etag") ?? void 0,
1023
+ contentType: headers.get("content-type") ?? void 0,
1024
+ lastModified: headers.get("last-modified") ?? void 0,
1025
+ contentLength: headers.get("content-length") ? parseInt(headers.get("content-length"), 10) : void 0,
1026
+ get: (name) => headers.get(name)
1027
+ };
1028
+ }
1029
+ /**
1030
+ * Parse response body based on content type.
1031
+ *
1032
+ * @param response - Fetch response
1033
+ * @param raw - Whether to return raw text
1034
+ * @returns Parsed data
1035
+ */
1036
+ async parseResponse(response, raw = false) {
1037
+ if (!response.ok) {
1038
+ return void 0;
1039
+ }
1040
+ if (raw) {
1041
+ return await response.text();
1042
+ }
1043
+ const contentType = response.headers.get("content-type");
1044
+ if (contentType?.includes("application/json")) {
1045
+ return await response.json();
1046
+ } else if (contentType?.startsWith("text/")) {
1047
+ return await response.text();
1048
+ }
1049
+ const text = await response.text();
1050
+ if (!text) {
1051
+ return void 0;
1052
+ }
1053
+ try {
1054
+ return JSON.parse(text);
1055
+ } catch {
1056
+ return text;
1057
+ }
1058
+ }
1059
+ /**
1060
+ * Get a value by key.
1061
+ */
1062
+ async get(key, options) {
1063
+ return this.withTelemetry("get", key, async () => {
1064
+ if (!this.requireAuth()) {
1065
+ return err(authRequiredError("kv"));
1066
+ }
1067
+ const path = this.getFullPath(key, options?.prefix);
1068
+ try {
1069
+ const response = await this.invokeOperation(
1070
+ path,
1071
+ KVAction.GET,
1072
+ void 0,
1073
+ options?.signal
1074
+ );
1075
+ if (!response.ok) {
1076
+ if (response.status === 401) {
1077
+ const errorText2 = await response.text();
1078
+ const { resource, action } = parseAuthError(errorText2);
1079
+ return err(authUnauthorizedError("kv", errorText2, {
1080
+ status: response.status,
1081
+ ...action && { requiredAction: action },
1082
+ ...resource && { resource }
1083
+ }));
1084
+ }
1085
+ if (response.status === 404) {
1086
+ return err(
1087
+ serviceError(
1088
+ ErrorCodes.KV_NOT_FOUND,
1089
+ `Key not found: ${key}`,
1090
+ "kv"
1091
+ )
1092
+ );
1093
+ }
1094
+ const errorText = await response.text();
1095
+ return err(
1096
+ serviceError(
1097
+ ErrorCodes.NETWORK_ERROR,
1098
+ `Failed to get key "${key}": ${response.status} - ${errorText}`,
1099
+ "kv",
1100
+ { meta: { status: response.status, statusText: response.statusText } }
1101
+ )
1102
+ );
1103
+ }
1104
+ const data = await this.parseResponse(response, options?.raw);
1105
+ return ok({
1106
+ data,
1107
+ headers: this.createResponseHeaders(response.headers)
1108
+ });
1109
+ } catch (error) {
1110
+ return err(wrapError("kv", error));
1111
+ }
1112
+ });
1113
+ }
1114
+ /**
1115
+ * Store a value at a key.
1116
+ */
1117
+ async put(key, value, options) {
1118
+ return this.withTelemetry("put", key, async () => {
1119
+ if (!this.requireAuth()) {
1120
+ return err(authRequiredError("kv"));
1121
+ }
1122
+ const path = this.getFullPath(key, options?.prefix);
1123
+ let body;
1124
+ if (typeof value === "string") {
1125
+ body = value;
1126
+ } else {
1127
+ body = JSON.stringify(value);
1128
+ }
1129
+ try {
1130
+ const response = await this.invokeOperation(
1131
+ path,
1132
+ KVAction.PUT,
1133
+ body,
1134
+ options?.signal
1135
+ );
1136
+ if (!response.ok) {
1137
+ if (response.status === 401) {
1138
+ const errorText2 = await response.text();
1139
+ const { resource, action } = parseAuthError(errorText2);
1140
+ return err(authUnauthorizedError("kv", errorText2, {
1141
+ status: response.status,
1142
+ ...action && { requiredAction: action },
1143
+ ...resource && { resource }
1144
+ }));
1145
+ }
1146
+ const errorText = await response.text();
1147
+ const quotaError = this.handleQuotaErrorResponse(
1148
+ response,
1149
+ errorText,
1150
+ key
1151
+ );
1152
+ if (quotaError) {
1153
+ return quotaError;
1154
+ }
1155
+ return err(
1156
+ serviceError(
1157
+ ErrorCodes.KV_WRITE_FAILED,
1158
+ `Failed to put key "${key}": ${response.status} - ${errorText}`,
1159
+ "kv",
1160
+ { meta: { status: response.status, statusText: response.statusText } }
1161
+ )
1162
+ );
1163
+ }
1164
+ return ok({
1165
+ data: void 0,
1166
+ headers: this.createResponseHeaders(response.headers)
1167
+ });
1168
+ } catch (error) {
1169
+ return err(wrapError("kv", error));
1170
+ }
1171
+ });
1172
+ }
1173
+ /**
1174
+ * List keys with optional prefix filtering.
1175
+ */
1176
+ async list(options) {
1177
+ return this.withTelemetry("list", options?.prefix, async () => {
1178
+ if (!this.requireAuth()) {
1179
+ return err(authRequiredError("kv"));
1180
+ }
1181
+ let listPath = options?.prefix ?? this._config.prefix ?? "";
1182
+ if (options?.path) {
1183
+ listPath = listPath ? `${listPath}/${options.path}` : options.path;
1184
+ }
1185
+ try {
1186
+ const response = await this.invokeOperation(
1187
+ listPath,
1188
+ KVAction.LIST,
1189
+ void 0,
1190
+ options?.signal
1191
+ );
1192
+ if (!response.ok) {
1193
+ if (response.status === 401) {
1194
+ const errorText2 = await response.text();
1195
+ const { resource, action } = parseAuthError(errorText2);
1196
+ return err(authUnauthorizedError("kv", errorText2, {
1197
+ status: response.status,
1198
+ ...action && { requiredAction: action },
1199
+ ...resource && { resource }
1200
+ }));
1201
+ }
1202
+ const errorText = await response.text();
1203
+ return err(
1204
+ serviceError(
1205
+ ErrorCodes.NETWORK_ERROR,
1206
+ `Failed to list keys: ${response.status} - ${errorText}`,
1207
+ "kv",
1208
+ { meta: { status: response.status, statusText: response.statusText } }
1209
+ )
1210
+ );
1211
+ }
1212
+ let keys = await this.parseResponse(response, options?.raw);
1213
+ keys = keys ?? [];
1214
+ if (options?.removePrefix && listPath) {
1215
+ const prefixWithSlash = listPath.endsWith("/") ? listPath : `${listPath}/`;
1216
+ keys = keys.map(
1217
+ (key) => key.startsWith(prefixWithSlash) ? key.slice(prefixWithSlash.length) : key
1218
+ );
1219
+ }
1220
+ return ok({ keys });
1221
+ } catch (error) {
1222
+ return err(wrapError("kv", error));
1223
+ }
1224
+ });
1225
+ }
1226
+ /**
1227
+ * Delete a key.
1228
+ */
1229
+ async delete(key, options) {
1230
+ return this.withTelemetry("delete", key, async () => {
1231
+ if (!this.requireAuth()) {
1232
+ return err(authRequiredError("kv"));
1233
+ }
1234
+ const path = this.getFullPath(key, options?.prefix);
1235
+ try {
1236
+ const response = await this.invokeOperation(
1237
+ path,
1238
+ KVAction.DELETE,
1239
+ void 0,
1240
+ options?.signal
1241
+ );
1242
+ if (!response.ok) {
1243
+ if (response.status === 401) {
1244
+ const errorText2 = await response.text();
1245
+ const { resource, action } = parseAuthError(errorText2);
1246
+ return err(authUnauthorizedError("kv", errorText2, {
1247
+ status: response.status,
1248
+ ...action && { requiredAction: action },
1249
+ ...resource && { resource }
1250
+ }));
1251
+ }
1252
+ if (response.status === 404) {
1253
+ return err(
1254
+ serviceError(
1255
+ ErrorCodes.KV_NOT_FOUND,
1256
+ `Key not found: ${key}`,
1257
+ "kv"
1258
+ )
1259
+ );
1260
+ }
1261
+ const errorText = await response.text();
1262
+ return err(
1263
+ serviceError(
1264
+ ErrorCodes.NETWORK_ERROR,
1265
+ `Failed to delete key "${key}": ${response.status} - ${errorText}`,
1266
+ "kv",
1267
+ { meta: { status: response.status, statusText: response.statusText } }
1268
+ )
1269
+ );
1270
+ }
1271
+ return ok(void 0);
1272
+ } catch (error) {
1273
+ return err(wrapError("kv", error));
1274
+ }
1275
+ });
1276
+ }
1277
+ /**
1278
+ * Get metadata for a key without retrieving the value.
1279
+ */
1280
+ async head(key, options) {
1281
+ return this.withTelemetry("head", key, async () => {
1282
+ if (!this.requireAuth()) {
1283
+ return err(authRequiredError("kv"));
1284
+ }
1285
+ const path = this.getFullPath(key, options?.prefix);
1286
+ try {
1287
+ const response = await this.invokeOperation(
1288
+ path,
1289
+ KVAction.HEAD,
1290
+ void 0,
1291
+ options?.signal
1292
+ );
1293
+ if (!response.ok) {
1294
+ if (response.status === 401) {
1295
+ const errorText2 = await response.text();
1296
+ const { resource, action } = parseAuthError(errorText2);
1297
+ return err(authUnauthorizedError("kv", errorText2, {
1298
+ status: response.status,
1299
+ ...action && { requiredAction: action },
1300
+ ...resource && { resource }
1301
+ }));
1302
+ }
1303
+ if (response.status === 404) {
1304
+ return err(
1305
+ serviceError(
1306
+ ErrorCodes.KV_NOT_FOUND,
1307
+ `Key not found: ${key}`,
1308
+ "kv"
1309
+ )
1310
+ );
1311
+ }
1312
+ const errorText = await response.text();
1313
+ return err(
1314
+ serviceError(
1315
+ ErrorCodes.NETWORK_ERROR,
1316
+ `Failed to get metadata for key "${key}": ${response.status} - ${errorText}`,
1317
+ "kv",
1318
+ { meta: { status: response.status, statusText: response.statusText } }
1319
+ )
1320
+ );
1321
+ }
1322
+ return ok({
1323
+ data: void 0,
1324
+ headers: this.createResponseHeaders(response.headers)
1325
+ });
1326
+ } catch (error) {
1327
+ return err(wrapError("kv", error));
1328
+ }
1329
+ });
1330
+ }
1331
+ /**
1332
+ * Create a prefix-scoped view of this KV service.
1333
+ *
1334
+ * Returns a PrefixedKVService that automatically prefixes all
1335
+ * key operations with the specified prefix. This enables apps
1336
+ * to isolate their data within a shared space.
1337
+ *
1338
+ * @param prefix - The prefix to apply to all operations
1339
+ * @returns A PrefixedKVService scoped to the prefix
1340
+ *
1341
+ * ## Prefix Conventions
1342
+ *
1343
+ * | Pattern | Use Case | Example |
1344
+ * | -- | -- | -- |
1345
+ * | `/app.{domain}/` | App-private data | `/app.photos.xyz/settings.json` |
1346
+ * | `/{type}/` | Shared data type | `/photos/vacation.jpg` |
1347
+ * | `/.{name}/` | Hidden/system data | `/.cache/thumbnails/` |
1348
+ * | `/public/` | Explicitly shareable | `/public/profile.json` |
1349
+ *
1350
+ * @example
1351
+ * ```typescript
1352
+ * const space = sdk.space('default');
1353
+ *
1354
+ * // Create prefix-scoped views
1355
+ * const myApp = space.kv.withPrefix('/app.myapp.com');
1356
+ * const sharedPhotos = space.kv.withPrefix('/photos');
1357
+ *
1358
+ * // Operations are automatically prefixed
1359
+ * await myApp.put('settings.json', { theme: 'dark' });
1360
+ * // -> Actually writes to: /app.myapp.com/settings.json
1361
+ *
1362
+ * await myApp.get('settings.json');
1363
+ * // -> Actually reads from: /app.myapp.com/settings.json
1364
+ *
1365
+ * await sharedPhotos.list();
1366
+ * // -> Lists: /photos/*
1367
+ *
1368
+ * // Nested prefixes
1369
+ * const settings = myApp.withPrefix('/settings');
1370
+ * await settings.get('theme.json'); // -> /app.myapp.com/settings/theme.json
1371
+ * ```
1372
+ */
1373
+ withPrefix(prefix) {
1374
+ return new PrefixedKVService(this, prefix);
1375
+ }
1376
+ };
1377
+ /**
1378
+ * Service identifier for registration.
1379
+ */
1380
+ KVService.serviceName = "kv";
1381
+
1382
+ // src/sql/DatabaseHandle.ts
1383
+ var DatabaseHandle = class {
1384
+ constructor(service, name) {
1385
+ this.service = service;
1386
+ this.name = name;
1387
+ }
1388
+ async query(sql, params, options) {
1389
+ return this.service.queryOnDb(this.name, sql, params, options);
1390
+ }
1391
+ async execute(sql, params, options) {
1392
+ return this.service.executeOnDb(this.name, sql, params, options);
1393
+ }
1394
+ async batch(statements, options) {
1395
+ return this.service.batchOnDb(this.name, statements, options);
1396
+ }
1397
+ async executeStatement(name, params, options) {
1398
+ return this.service.executeStatementOnDb(this.name, name, params, options);
1399
+ }
1400
+ async export(options) {
1401
+ return this.service.exportDb(this.name, options);
1402
+ }
1403
+ };
1404
+
1405
+ // src/sql/types.ts
1406
+ var SQLAction = {
1407
+ READ: "tinycloud.sql/read",
1408
+ WRITE: "tinycloud.sql/write",
1409
+ ADMIN: "tinycloud.sql/admin",
1410
+ SELECT: "tinycloud.sql/select",
1411
+ INSERT: "tinycloud.sql/insert",
1412
+ UPDATE: "tinycloud.sql/update",
1413
+ DELETE: "tinycloud.sql/delete",
1414
+ EXECUTE: "tinycloud.sql/execute",
1415
+ EXPORT: "tinycloud.sql/export",
1416
+ ALL: "tinycloud.sql/*"
1417
+ };
1418
+
1419
+ // src/sql/SQLService.ts
1420
+ var SQLService = class extends BaseService {
1421
+ constructor(config = {}) {
1422
+ super();
1423
+ this._config = config;
1424
+ }
1425
+ get config() {
1426
+ return this._config;
1427
+ }
1428
+ get defaultDbName() {
1429
+ return this._config.defaultDatabase ?? "default";
1430
+ }
1431
+ get host() {
1432
+ return this.context.hosts[0];
1433
+ }
1434
+ /**
1435
+ * Get a handle to a named database.
1436
+ */
1437
+ db(name) {
1438
+ return new DatabaseHandle(this, name ?? this.defaultDbName);
1439
+ }
1440
+ /**
1441
+ * Shortcut: query the default database.
1442
+ */
1443
+ async query(sql, params, options) {
1444
+ return this.queryOnDb(this.defaultDbName, sql, params, options);
1445
+ }
1446
+ /**
1447
+ * Shortcut: execute on the default database.
1448
+ */
1449
+ async execute(sql, params, options) {
1450
+ return this.executeOnDb(this.defaultDbName, sql, params, options);
1451
+ }
1452
+ /**
1453
+ * Shortcut: batch on the default database.
1454
+ */
1455
+ async batch(statements, options) {
1456
+ return this.batchOnDb(this.defaultDbName, statements, options);
1457
+ }
1458
+ // === Internal methods called by DatabaseHandle ===
1459
+ async queryOnDb(dbName, sql, params, options) {
1460
+ return this.withTelemetry("query", dbName, async () => {
1461
+ if (!this.requireAuth()) {
1462
+ return err(authRequiredError("sql"));
1463
+ }
1464
+ try {
1465
+ const response = await this.invokeSQL(
1466
+ dbName,
1467
+ SQLAction.READ,
1468
+ { action: "query", sql, params: params ?? [] },
1469
+ options?.signal
1470
+ );
1471
+ if (!response.ok) {
1472
+ return this.handleErrorResponse(response, "query");
1473
+ }
1474
+ const data = await response.json();
1475
+ return ok(data);
1476
+ } catch (error) {
1477
+ return err(wrapError("sql", error));
1478
+ }
1479
+ });
1480
+ }
1481
+ async executeOnDb(dbName, sql, params, options) {
1482
+ return this.withTelemetry("execute", dbName, async () => {
1483
+ if (!this.requireAuth()) {
1484
+ return err(authRequiredError("sql"));
1485
+ }
1486
+ try {
1487
+ const body = {
1488
+ action: "execute",
1489
+ sql,
1490
+ params: params ?? []
1491
+ };
1492
+ if (options?.schema) {
1493
+ body.schema = options.schema;
1494
+ }
1495
+ const response = await this.invokeSQL(
1496
+ dbName,
1497
+ SQLAction.WRITE,
1498
+ body,
1499
+ options?.signal
1500
+ );
1501
+ if (!response.ok) {
1502
+ return this.handleErrorResponse(response, "execute");
1503
+ }
1504
+ const data = await response.json();
1505
+ return ok(data);
1506
+ } catch (error) {
1507
+ return err(wrapError("sql", error));
1508
+ }
1509
+ });
1510
+ }
1511
+ async batchOnDb(dbName, statements, options) {
1512
+ return this.withTelemetry("batch", dbName, async () => {
1513
+ if (!this.requireAuth()) {
1514
+ return err(authRequiredError("sql"));
1515
+ }
1516
+ try {
1517
+ const response = await this.invokeSQL(
1518
+ dbName,
1519
+ SQLAction.WRITE,
1520
+ { action: "batch", statements },
1521
+ options?.signal
1522
+ );
1523
+ if (!response.ok) {
1524
+ return this.handleErrorResponse(response, "batch");
1525
+ }
1526
+ const data = await response.json();
1527
+ return ok(data);
1528
+ } catch (error) {
1529
+ return err(wrapError("sql", error));
1530
+ }
1531
+ });
1532
+ }
1533
+ async executeStatementOnDb(dbName, name, params, options) {
1534
+ return this.withTelemetry("executeStatement", dbName, async () => {
1535
+ if (!this.requireAuth()) {
1536
+ return err(authRequiredError("sql"));
1537
+ }
1538
+ try {
1539
+ const response = await this.invokeSQL(
1540
+ dbName,
1541
+ SQLAction.EXECUTE,
1542
+ { action: "execute_statement", name, params: params ?? [] },
1543
+ options?.signal
1544
+ );
1545
+ if (!response.ok) {
1546
+ return this.handleErrorResponse(response, "executeStatement");
1547
+ }
1548
+ const data = await response.json();
1549
+ return ok(data);
1550
+ } catch (error) {
1551
+ return err(wrapError("sql", error));
1552
+ }
1553
+ });
1554
+ }
1555
+ async exportDb(dbName, options) {
1556
+ return this.withTelemetry("export", dbName, async () => {
1557
+ if (!this.requireAuth()) {
1558
+ return err(authRequiredError("sql"));
1559
+ }
1560
+ try {
1561
+ const response = await this.invokeSQL(
1562
+ dbName,
1563
+ SQLAction.EXPORT,
1564
+ { action: "export" },
1565
+ options?.signal
1566
+ );
1567
+ if (!response.ok) {
1568
+ return this.handleErrorResponse(response, "export");
1569
+ }
1570
+ const resp = response;
1571
+ if (typeof resp.blob === "function") {
1572
+ const blob = await resp.blob();
1573
+ return ok(blob);
1574
+ }
1575
+ const text = await response.text();
1576
+ return ok(text);
1577
+ } catch (error) {
1578
+ return err(wrapError("sql", error));
1579
+ }
1580
+ });
1581
+ }
1582
+ // === Private helpers ===
1583
+ async invokeSQL(dbName, action, body, signal) {
1584
+ const session = this.context.session;
1585
+ const headers = this.context.invoke(session, "sql", dbName, action);
1586
+ return this.context.fetch(`${this.host}/invoke`, {
1587
+ method: "POST",
1588
+ headers: {
1589
+ ...headers,
1590
+ "Content-Type": "application/json"
1591
+ },
1592
+ body: JSON.stringify(body),
1593
+ signal: this.combineSignals(signal)
1594
+ });
1595
+ }
1596
+ async handleErrorResponse(response, operation) {
1597
+ const errorText = await response.text();
1598
+ let errorBody = {};
1599
+ try {
1600
+ errorBody = JSON.parse(errorText);
1601
+ } catch {
1602
+ }
1603
+ const errorCode = this.mapHttpStatusToErrorCode(
1604
+ response.status,
1605
+ errorBody.error
1606
+ );
1607
+ const message = errorBody.message || `SQL ${operation} failed: ${response.status} - ${errorText}`;
1608
+ const meta = { status: response.status, statusText: response.statusText };
1609
+ if (response.status === 401) {
1610
+ const { resource, action } = parseAuthError(errorText);
1611
+ if (action) meta.requiredAction = action;
1612
+ if (resource) meta.resource = resource;
1613
+ }
1614
+ return err(
1615
+ serviceError(errorCode, message, "sql", { meta })
1616
+ );
1617
+ }
1618
+ mapHttpStatusToErrorCode(status, serverError) {
1619
+ switch (status) {
1620
+ case 400:
1621
+ return ErrorCodes.SQL_ERROR;
1622
+ case 401:
1623
+ return ErrorCodes.AUTH_UNAUTHORIZED;
1624
+ case 403:
1625
+ if (serverError === "sql_readonly_violation") {
1626
+ return ErrorCodes.SQL_READONLY_VIOLATION;
1627
+ }
1628
+ return ErrorCodes.SQL_PERMISSION_DENIED;
1629
+ case 404:
1630
+ return ErrorCodes.SQL_DATABASE_NOT_FOUND;
1631
+ case 413:
1632
+ return ErrorCodes.SQL_RESPONSE_TOO_LARGE;
1633
+ case 429:
1634
+ return ErrorCodes.SQL_QUOTA_EXCEEDED;
1635
+ default:
1636
+ return ErrorCodes.NETWORK_ERROR;
1637
+ }
1638
+ }
1639
+ };
1640
+ SQLService.serviceName = "sql";
1641
+
1642
+ // src/duckdb/DuckDbDatabaseHandle.ts
1643
+ var DuckDbDatabaseHandle = class {
1644
+ constructor(service, name) {
1645
+ this.service = service;
1646
+ this.name = name;
1647
+ }
1648
+ async query(sql, params, options) {
1649
+ return this.service.queryOnDb(this.name, sql, params, options);
1650
+ }
1651
+ async queryArrow(sql, params, options) {
1652
+ return this.service.queryArrowOnDb(this.name, sql, params, options);
1653
+ }
1654
+ async execute(sql, params, options) {
1655
+ return this.service.executeOnDb(this.name, sql, params, options);
1656
+ }
1657
+ async batch(statements, options) {
1658
+ return this.service.batchOnDb(this.name, statements, options);
1659
+ }
1660
+ async executeStatement(name, params, options) {
1661
+ return this.service.executeStatementOnDb(this.name, name, params, options);
1662
+ }
1663
+ async describe(options) {
1664
+ return this.service.describeDb(this.name, options);
1665
+ }
1666
+ async export(options) {
1667
+ return this.service.exportOnDb(this.name, options);
1668
+ }
1669
+ async import(data, options) {
1670
+ return this.service.importOnDb(this.name, data, options);
1671
+ }
1672
+ };
1673
+
1674
+ // src/duckdb/types.ts
1675
+ var DuckDbAction = {
1676
+ READ: "tinycloud.duckdb/read",
1677
+ WRITE: "tinycloud.duckdb/write",
1678
+ ADMIN: "tinycloud.duckdb/admin",
1679
+ DESCRIBE: "tinycloud.duckdb/describe",
1680
+ EXPORT: "tinycloud.duckdb/export",
1681
+ IMPORT: "tinycloud.duckdb/import",
1682
+ EXECUTE: "tinycloud.duckdb/execute",
1683
+ ALL: "tinycloud.duckdb/*"
1684
+ };
1685
+
1686
+ // src/duckdb/DuckDbService.ts
1687
+ var DuckDbService = class extends BaseService {
1688
+ constructor(config = {}) {
1689
+ super();
1690
+ this._config = config;
1691
+ }
1692
+ get config() {
1693
+ return this._config;
1694
+ }
1695
+ get defaultDbName() {
1696
+ return this._config.defaultDatabase ?? "default";
1697
+ }
1698
+ get host() {
1699
+ return this.context.hosts[0];
1700
+ }
1701
+ /**
1702
+ * Get a handle to a named database.
1703
+ */
1704
+ db(name) {
1705
+ return new DuckDbDatabaseHandle(this, name ?? this.defaultDbName);
1706
+ }
1707
+ /**
1708
+ * Shortcut: query the default database (JSON format).
1709
+ */
1710
+ async query(sql, params, options) {
1711
+ return this.queryOnDb(this.defaultDbName, sql, params, options);
1712
+ }
1713
+ /**
1714
+ * Shortcut: query the default database (Arrow IPC format).
1715
+ */
1716
+ async queryArrow(sql, params, options) {
1717
+ return this.queryArrowOnDb(this.defaultDbName, sql, params, options);
1718
+ }
1719
+ /**
1720
+ * Shortcut: execute on the default database.
1721
+ */
1722
+ async execute(sql, params, options) {
1723
+ return this.executeOnDb(this.defaultDbName, sql, params, options);
1724
+ }
1725
+ /**
1726
+ * Shortcut: batch on the default database.
1727
+ */
1728
+ async batch(statements, options) {
1729
+ return this.batchOnDb(this.defaultDbName, statements, options);
1730
+ }
1731
+ // === Internal methods called by DuckDbDatabaseHandle ===
1732
+ async queryOnDb(dbName, sql, params, options) {
1733
+ return this.withTelemetry("query", dbName, async () => {
1734
+ if (!this.requireAuth()) {
1735
+ return err(authRequiredError("duckdb"));
1736
+ }
1737
+ try {
1738
+ const response = await this.invokeDuckDb(
1739
+ dbName,
1740
+ DuckDbAction.READ,
1741
+ { action: "query", sql, params: params ?? [] },
1742
+ options?.signal
1743
+ );
1744
+ if (!response.ok) {
1745
+ return this.handleErrorResponse(response, "query");
1746
+ }
1747
+ const data = await response.json();
1748
+ return ok(data);
1749
+ } catch (error) {
1750
+ return err(wrapError("duckdb", error));
1751
+ }
1752
+ });
1753
+ }
1754
+ async queryArrowOnDb(dbName, sql, params, options) {
1755
+ return this.withTelemetry("queryArrow", dbName, async () => {
1756
+ if (!this.requireAuth()) {
1757
+ return err(authRequiredError("duckdb"));
1758
+ }
1759
+ try {
1760
+ const response = await this.invokeDuckDb(
1761
+ dbName,
1762
+ DuckDbAction.READ,
1763
+ { action: "query", sql, params: params ?? [] },
1764
+ options?.signal,
1765
+ { Accept: "application/vnd.apache.arrow.stream" }
1766
+ );
1767
+ if (!response.ok) {
1768
+ return this.handleErrorResponse(response, "queryArrow");
1769
+ }
1770
+ const buffer = await response.arrayBuffer();
1771
+ return ok(buffer);
1772
+ } catch (error) {
1773
+ return err(wrapError("duckdb", error));
1774
+ }
1775
+ });
1776
+ }
1777
+ async executeOnDb(dbName, sql, params, options) {
1778
+ return this.withTelemetry("execute", dbName, async () => {
1779
+ if (!this.requireAuth()) {
1780
+ return err(authRequiredError("duckdb"));
1781
+ }
1782
+ try {
1783
+ const body = {
1784
+ action: "execute",
1785
+ sql,
1786
+ params: params ?? []
1787
+ };
1788
+ if (options?.schema) {
1789
+ body.schema = options.schema;
1790
+ }
1791
+ const response = await this.invokeDuckDb(
1792
+ dbName,
1793
+ DuckDbAction.WRITE,
1794
+ body,
1795
+ options?.signal
1796
+ );
1797
+ if (!response.ok) {
1798
+ return this.handleErrorResponse(response, "execute");
1799
+ }
1800
+ const data = await response.json();
1801
+ return ok(data);
1802
+ } catch (error) {
1803
+ return err(wrapError("duckdb", error));
1804
+ }
1805
+ });
1806
+ }
1807
+ async batchOnDb(dbName, statements, options) {
1808
+ return this.withTelemetry("batch", dbName, async () => {
1809
+ if (!this.requireAuth()) {
1810
+ return err(authRequiredError("duckdb"));
1811
+ }
1812
+ try {
1813
+ const body = {
1814
+ action: "batch",
1815
+ statements
1816
+ };
1817
+ if (options?.transactional !== void 0) {
1818
+ body.transactional = options.transactional;
1819
+ }
1820
+ const response = await this.invokeDuckDb(
1821
+ dbName,
1822
+ DuckDbAction.WRITE,
1823
+ body,
1824
+ options?.signal
1825
+ );
1826
+ if (!response.ok) {
1827
+ return this.handleErrorResponse(response, "batch");
1828
+ }
1829
+ const data = await response.json();
1830
+ return ok(data);
1831
+ } catch (error) {
1832
+ return err(wrapError("duckdb", error));
1833
+ }
1834
+ });
1835
+ }
1836
+ async executeStatementOnDb(dbName, name, params, options) {
1837
+ return this.withTelemetry("executeStatement", dbName, async () => {
1838
+ if (!this.requireAuth()) {
1839
+ return err(authRequiredError("duckdb"));
1840
+ }
1841
+ try {
1842
+ const response = await this.invokeDuckDb(
1843
+ dbName,
1844
+ DuckDbAction.EXECUTE,
1845
+ { action: "executeStatement", name, params: params ?? [] },
1846
+ options?.signal
1847
+ );
1848
+ if (!response.ok) {
1849
+ return this.handleErrorResponse(response, "executeStatement");
1850
+ }
1851
+ const data = await response.json();
1852
+ return ok(data);
1853
+ } catch (error) {
1854
+ return err(wrapError("duckdb", error));
1855
+ }
1856
+ });
1857
+ }
1858
+ async describeDb(dbName, options) {
1859
+ return this.withTelemetry("describe", dbName, async () => {
1860
+ if (!this.requireAuth()) {
1861
+ return err(authRequiredError("duckdb"));
1862
+ }
1863
+ try {
1864
+ const response = await this.invokeDuckDb(
1865
+ dbName,
1866
+ DuckDbAction.DESCRIBE,
1867
+ { action: "describe" },
1868
+ options?.signal
1869
+ );
1870
+ if (!response.ok) {
1871
+ return this.handleErrorResponse(response, "describe");
1872
+ }
1873
+ const data = await response.json();
1874
+ return ok(data);
1875
+ } catch (error) {
1876
+ return err(wrapError("duckdb", error));
1877
+ }
1878
+ });
1879
+ }
1880
+ async exportOnDb(dbName, options) {
1881
+ return this.withTelemetry("export", dbName, async () => {
1882
+ if (!this.requireAuth()) {
1883
+ return err(authRequiredError("duckdb"));
1884
+ }
1885
+ try {
1886
+ const response = await this.invokeDuckDb(
1887
+ dbName,
1888
+ DuckDbAction.EXPORT,
1889
+ { action: "export" },
1890
+ options?.signal
1891
+ );
1892
+ if (!response.ok) {
1893
+ return this.handleErrorResponse(response, "export");
1894
+ }
1895
+ const blob = await response.blob();
1896
+ return ok(blob);
1897
+ } catch (error) {
1898
+ return err(wrapError("duckdb", error));
1899
+ }
1900
+ });
1901
+ }
1902
+ async importOnDb(dbName, data, options) {
1903
+ return this.withTelemetry("import", dbName, async () => {
1904
+ if (!this.requireAuth()) {
1905
+ return err(authRequiredError("duckdb"));
1906
+ }
1907
+ try {
1908
+ const session = this.context.session;
1909
+ const headers = this.context.invoke(
1910
+ session,
1911
+ "duckdb",
1912
+ dbName,
1913
+ DuckDbAction.IMPORT
1914
+ );
1915
+ const response = await this.context.fetch(`${this.host}/invoke`, {
1916
+ method: "POST",
1917
+ headers: {
1918
+ ...headers,
1919
+ "Content-Type": "application/x-duckdb"
1920
+ },
1921
+ body: new Blob([data]),
1922
+ signal: this.combineSignals(options?.signal)
1923
+ });
1924
+ if (!response.ok) {
1925
+ return this.handleErrorResponse(response, "import");
1926
+ }
1927
+ return ok(void 0);
1928
+ } catch (error) {
1929
+ return err(wrapError("duckdb", error));
1930
+ }
1931
+ });
1932
+ }
1933
+ // === Private helpers ===
1934
+ async invokeDuckDb(dbName, action, body, signal, extraHeaders) {
1935
+ const session = this.context.session;
1936
+ const headers = this.context.invoke(session, "duckdb", dbName, action);
1937
+ return this.context.fetch(`${this.host}/invoke`, {
1938
+ method: "POST",
1939
+ headers: {
1940
+ ...headers,
1941
+ "Content-Type": "application/json",
1942
+ ...extraHeaders
1943
+ },
1944
+ body: JSON.stringify(body),
1945
+ signal: this.combineSignals(signal)
1946
+ });
1947
+ }
1948
+ async handleErrorResponse(response, operation) {
1949
+ const errorText = await response.text();
1950
+ let errorBody = {};
1951
+ try {
1952
+ errorBody = JSON.parse(errorText);
1953
+ } catch {
1954
+ }
1955
+ const errorCode = this.mapHttpStatusToErrorCode(
1956
+ response.status,
1957
+ errorBody.error
1958
+ );
1959
+ const message = errorBody.message || `DuckDB ${operation} failed: ${response.status} - ${errorText}`;
1960
+ const meta = { status: response.status, statusText: response.statusText };
1961
+ if (response.status === 401) {
1962
+ const { resource, action } = parseAuthError(errorText);
1963
+ if (action) meta.requiredAction = action;
1964
+ if (resource) meta.resource = resource;
1965
+ }
1966
+ return err(
1967
+ serviceError(errorCode, message, "duckdb", { meta })
1968
+ );
1969
+ }
1970
+ mapHttpStatusToErrorCode(status, serverError) {
1971
+ switch (status) {
1972
+ case 400:
1973
+ return ErrorCodes.DUCKDB_ERROR;
1974
+ case 401:
1975
+ return ErrorCodes.AUTH_UNAUTHORIZED;
1976
+ case 403:
1977
+ if (serverError === "duckdb_readonly_violation") {
1978
+ return ErrorCodes.DUCKDB_READONLY_VIOLATION;
1979
+ }
1980
+ return ErrorCodes.DUCKDB_PERMISSION_DENIED;
1981
+ case 404:
1982
+ return ErrorCodes.DUCKDB_DATABASE_NOT_FOUND;
1983
+ case 413:
1984
+ return ErrorCodes.DUCKDB_RESPONSE_TOO_LARGE;
1985
+ case 429:
1986
+ return ErrorCodes.DUCKDB_QUOTA_EXCEEDED;
1987
+ default:
1988
+ return ErrorCodes.NETWORK_ERROR;
1989
+ }
1990
+ }
1991
+ };
1992
+ DuckDbService.serviceName = "duckdb";
1993
+
1994
+ // src/quota/TinyCloudQuota.ts
1995
+ var TinyCloudQuota = class {
1996
+ constructor(config = {}) {
1997
+ this.quotaUrl = null;
1998
+ this.config = config;
1999
+ }
2000
+ /** Set the quota URL discovered from the /info endpoint */
2001
+ setQuotaUrl(url) {
2002
+ this.quotaUrl = url;
2003
+ }
2004
+ /** Whether a quota service is available */
2005
+ get available() {
2006
+ return this.quotaUrl !== null;
2007
+ }
2008
+ /** Query quota status for a space from the quota URL */
2009
+ async getQuota(spaceId) {
2010
+ if (!this.quotaUrl) return null;
2011
+ const resp = await fetch(
2012
+ `${this.quotaUrl}/api/quota/${encodeURIComponent(spaceId)}`
2013
+ );
2014
+ if (!resp.ok) return null;
2015
+ const data = await resp.json();
2016
+ return {
2017
+ limitBytes: data.storage_limit_bytes ?? 0
2018
+ };
2019
+ }
2020
+ /** Trigger the upgrade callback when a quota error is encountered */
2021
+ handleQuotaError(info) {
2022
+ this.config.onUpgradeRequired?.(info);
2023
+ }
2024
+ };
2025
+
2026
+ // src/vault/types.ts
2027
+ var VaultPublicSpaceKVActions = [
2028
+ "tinycloud.kv/get",
2029
+ "tinycloud.kv/put",
2030
+ "tinycloud.kv/metadata"
2031
+ ];
2032
+ var VaultVersionConfig = {
2033
+ "1": {
2034
+ masterMessage: (spaceId) => `tinycloud-vault-master-v1:${spaceId}`,
2035
+ identityMessage: "tinycloud-encryption-identity-v1"
2036
+ }
2037
+ };
2038
+ var CURRENT_VAULT_VERSION = "1";
2039
+ var VaultHeaders = {
2040
+ VERSION: "x-vault-version",
2041
+ CIPHER: "x-vault-cipher",
2042
+ KEY_ID: "x-vault-key-id",
2043
+ CONTENT_TYPE: "x-vault-content-type",
2044
+ KDF: "x-vault-kdf",
2045
+ KEY_ROTATION: "x-vault-key-rotation",
2046
+ GRANT_VERSION: "x-vault-grant-version",
2047
+ GRANTOR: "x-vault-grantor"
2048
+ };
2049
+
2050
+ // src/vault/SignatureCache.ts
2051
+ var DB_NAME = "tinycloud-vault-cache";
2052
+ var DB_VERSION = 1;
2053
+ var STORE_NAME = "signatures";
2054
+ var WRAP_KEY_ID = "__wrap_key__";
2055
+ function isBrowser() {
2056
+ try {
2057
+ return typeof indexedDB !== "undefined" && typeof crypto !== "undefined" && typeof crypto.subtle !== "undefined";
2058
+ } catch {
2059
+ return false;
2060
+ }
2061
+ }
2062
+ function openDB() {
2063
+ return new Promise((resolve, reject) => {
2064
+ const request = indexedDB.open(DB_NAME, DB_VERSION);
2065
+ request.onupgradeneeded = () => {
2066
+ const db = request.result;
2067
+ if (!db.objectStoreNames.contains(STORE_NAME)) {
2068
+ db.createObjectStore(STORE_NAME);
2069
+ }
2070
+ };
2071
+ request.onsuccess = () => resolve(request.result);
2072
+ request.onerror = () => reject(request.error);
2073
+ });
2074
+ }
2075
+ function idbGet(db, key) {
2076
+ return new Promise((resolve, reject) => {
2077
+ const tx = db.transaction(STORE_NAME, "readonly");
2078
+ const store = tx.objectStore(STORE_NAME);
2079
+ const req = store.get(key);
2080
+ req.onsuccess = () => resolve(req.result);
2081
+ req.onerror = () => reject(req.error);
2082
+ });
2083
+ }
2084
+ function idbPut(db, key, value) {
2085
+ return new Promise((resolve, reject) => {
2086
+ const tx = db.transaction(STORE_NAME, "readwrite");
2087
+ const store = tx.objectStore(STORE_NAME);
2088
+ const req = store.put(value, key);
2089
+ req.onsuccess = () => resolve();
2090
+ req.onerror = () => reject(req.error);
2091
+ });
2092
+ }
2093
+ function idbDelete(db, key) {
2094
+ return new Promise((resolve, reject) => {
2095
+ const tx = db.transaction(STORE_NAME, "readwrite");
2096
+ const store = tx.objectStore(STORE_NAME);
2097
+ const req = store.delete(key);
2098
+ req.onsuccess = () => resolve();
2099
+ req.onerror = () => reject(req.error);
2100
+ });
2101
+ }
2102
+ function idbKeys(db) {
2103
+ return new Promise((resolve, reject) => {
2104
+ const tx = db.transaction(STORE_NAME, "readonly");
2105
+ const store = tx.objectStore(STORE_NAME);
2106
+ const req = store.getAllKeys();
2107
+ req.onsuccess = () => resolve(req.result.filter((k) => typeof k === "string"));
2108
+ req.onerror = () => reject(req.error);
2109
+ });
2110
+ }
2111
+ async function getWrapKey(db) {
2112
+ const existing = await idbGet(db, WRAP_KEY_ID);
2113
+ if (existing) return existing;
2114
+ const key = await crypto.subtle.generateKey(
2115
+ { name: "AES-GCM", length: 256 },
2116
+ false,
2117
+ // non-extractable
2118
+ ["encrypt", "decrypt"]
2119
+ );
2120
+ await idbPut(db, WRAP_KEY_ID, key);
2121
+ return key;
2122
+ }
2123
+ async function encryptSig(wrapKey, sigBytes) {
2124
+ const iv = crypto.getRandomValues(new Uint8Array(12));
2125
+ const ciphertext = new Uint8Array(
2126
+ await crypto.subtle.encrypt({ name: "AES-GCM", iv }, wrapKey, sigBytes)
2127
+ );
2128
+ return { iv, ciphertext };
2129
+ }
2130
+ async function decryptSig(wrapKey, entry) {
2131
+ const plaintext = await crypto.subtle.decrypt(
2132
+ { name: "AES-GCM", iv: entry.iv },
2133
+ wrapKey,
2134
+ entry.ciphertext
2135
+ );
2136
+ return new Uint8Array(plaintext);
2137
+ }
2138
+ function cacheKey(spaceId) {
2139
+ return `sig:${spaceId}`;
2140
+ }
2141
+ async function loadCachedSignature(spaceId) {
2142
+ if (!isBrowser()) return null;
2143
+ try {
2144
+ const db = await openDB();
2145
+ const entry = await idbGet(db, cacheKey(spaceId));
2146
+ if (!entry) return null;
2147
+ const wrapKey = await getWrapKey(db);
2148
+ return await decryptSig(wrapKey, entry);
2149
+ } catch {
2150
+ return null;
2151
+ }
2152
+ }
2153
+ async function cacheSignature(spaceId, sigBytes) {
2154
+ if (!isBrowser()) return;
2155
+ try {
2156
+ const db = await openDB();
2157
+ const wrapKey = await getWrapKey(db);
2158
+ const encrypted = await encryptSig(wrapKey, sigBytes);
2159
+ await idbPut(db, cacheKey(spaceId), encrypted);
2160
+ } catch {
2161
+ }
2162
+ }
2163
+ async function clearSignatureCache(spaceId) {
2164
+ if (!isBrowser()) return;
2165
+ try {
2166
+ const db = await openDB();
2167
+ if (spaceId) {
2168
+ await idbDelete(db, cacheKey(spaceId));
2169
+ } else {
2170
+ const keys = await idbKeys(db);
2171
+ for (const k of keys) {
2172
+ if (k.startsWith("sig:")) {
2173
+ await idbDelete(db, k);
2174
+ }
2175
+ }
2176
+ }
2177
+ } catch {
2178
+ }
2179
+ }
2180
+
2181
+ // src/vault/DataVaultService.ts
2182
+ function toError(error) {
2183
+ if (error instanceof Error) return error;
2184
+ if (typeof error === "object" && error !== null) {
2185
+ return new Error(JSON.stringify(error));
2186
+ }
2187
+ return new Error(String(error));
2188
+ }
2189
+ function toBytes(str) {
2190
+ return new TextEncoder().encode(str);
2191
+ }
2192
+ function fromBytes(bytes) {
2193
+ return new TextDecoder().decode(bytes);
2194
+ }
2195
+ function hexEncode(bytes) {
2196
+ return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
2197
+ }
2198
+ function concatBytes(...arrays) {
2199
+ const total = arrays.reduce((acc, arr) => acc + arr.length, 0);
2200
+ const result = new Uint8Array(total);
2201
+ let offset = 0;
2202
+ for (const arr of arrays) {
2203
+ result.set(arr, offset);
2204
+ offset += arr.length;
2205
+ }
2206
+ return result;
2207
+ }
2208
+ function base64Encode(bytes) {
2209
+ let binary = "";
2210
+ for (let i = 0; i < bytes.length; i++) {
2211
+ binary += String.fromCharCode(bytes[i]);
2212
+ }
2213
+ return btoa(binary);
2214
+ }
2215
+ function base64Decode(str) {
2216
+ const binary = atob(str);
2217
+ const bytes = new Uint8Array(binary.length);
2218
+ for (let i = 0; i < binary.length; i++) {
2219
+ bytes[i] = binary.charCodeAt(i);
2220
+ }
2221
+ return bytes;
2222
+ }
2223
+ function defaultVaultMessage(input) {
2224
+ switch (input.code) {
2225
+ case "DECRYPTION_FAILED":
2226
+ return input.message ?? "Decryption failed";
2227
+ case "KEY_NOT_FOUND":
2228
+ return input.message ?? `Key not found: ${input.key}`;
2229
+ case "INTEGRITY_ERROR":
2230
+ return input.message ?? "Integrity check failed";
2231
+ case "GRANT_NOT_FOUND":
2232
+ return input.message ?? `Grant not found: ${input.grantor} / ${input.key}`;
2233
+ case "VAULT_LOCKED":
2234
+ return input.message ?? "Vault is locked";
2235
+ case "PUBLIC_KEY_NOT_FOUND":
2236
+ return input.message ?? `Public key not found for ${input.did}`;
2237
+ case "STORAGE_ERROR":
2238
+ return input.message ?? input.cause.message;
2239
+ }
2240
+ }
2241
+ function vaultError(input) {
2242
+ const error = {
2243
+ ...input,
2244
+ service: "vault",
2245
+ message: defaultVaultMessage(input)
2246
+ };
2247
+ return { ok: false, error };
2248
+ }
2249
+ var DataVaultService = class extends BaseService {
2250
+ /**
2251
+ * Create a new DataVaultService instance.
2252
+ *
2253
+ * @param config - Service configuration including crypto and tc references
2254
+ */
2255
+ constructor(config) {
2256
+ super();
2257
+ this.masterKey = null;
2258
+ this.encryptionIdentity = null;
2259
+ this._isUnlocked = false;
2260
+ this.vaultConfig = config;
2261
+ this._config = config;
2262
+ }
2263
+ /**
2264
+ * Get the service configuration.
2265
+ */
2266
+ get config() {
2267
+ return this._config;
2268
+ }
2269
+ /**
2270
+ * Whether the vault is currently unlocked.
2271
+ */
2272
+ get isUnlocked() {
2273
+ return this._isUnlocked;
2274
+ }
2275
+ /**
2276
+ * The vault's public encryption key (X25519).
2277
+ * Throws if vault is locked.
2278
+ */
2279
+ get publicKey() {
2280
+ if (!this.encryptionIdentity) {
2281
+ throw new Error("Vault is locked");
2282
+ }
2283
+ return this.encryptionIdentity.publicKey;
2284
+ }
2285
+ /**
2286
+ * Convenience accessor for crypto operations.
2287
+ */
2288
+ get crypto() {
2289
+ return this.vaultConfig.crypto;
2290
+ }
2291
+ /**
2292
+ * Convenience accessor for TinyCloud instance.
2293
+ */
2294
+ get tc() {
2295
+ return this.vaultConfig.tc;
2296
+ }
2297
+ /**
2298
+ * Get the host URL.
2299
+ */
2300
+ get host() {
2301
+ return this.tc.hosts[0];
2302
+ }
2303
+ // =========================================================================
2304
+ // Phase 1: Core Operations
2305
+ // =========================================================================
2306
+ /**
2307
+ * Unlock the vault. Derives keys from two wallet signatures:
2308
+ * 1. Master signature (per-space) — used to derive the master encryption key
2309
+ * 2. Identity signature (per-address) — used to derive X25519 encryption identity
2310
+ *
2311
+ * If the identity public key already exists in the public space, the identity
2312
+ * signature is skipped entirely (no wallet popup). The identity private key is
2313
+ * only needed for sharing operations.
2314
+ *
2315
+ * @param signer - Object with signMessage method. Optional when cached
2316
+ * signatures exist (browser only).
2317
+ */
2318
+ async unlock(signer) {
2319
+ return this.withTelemetry("unlock", void 0, async () => {
2320
+ const spaceId = this.vaultConfig.spaceId;
2321
+ const versionConfig = VaultVersionConfig[CURRENT_VAULT_VERSION];
2322
+ const masterCacheKey = `vault-master:${spaceId}`;
2323
+ const identityCacheKey = `vault-identity:${this.tc.address}`;
2324
+ try {
2325
+ let masterSigBytes = await loadCachedSignature(masterCacheKey);
2326
+ if (!masterSigBytes) {
2327
+ if (!signer) {
2328
+ return vaultError({
2329
+ code: "VAULT_LOCKED",
2330
+ message: "Signer is required when no cached master signature exists"
2331
+ });
2332
+ }
2333
+ const s = signer;
2334
+ const sig = await s.signMessage(versionConfig.masterMessage(spaceId));
2335
+ masterSigBytes = toBytes(sig);
2336
+ await cacheSignature(masterCacheKey, masterSigBytes);
2337
+ }
2338
+ this.masterKey = this.crypto.deriveKey(
2339
+ masterSigBytes,
2340
+ this.crypto.sha256(toBytes(spaceId)),
2341
+ toBytes("vault-master")
2342
+ );
2343
+ const publicSpaceId = this.tc.makePublicSpaceId(this.tc.address, this.tc.chainId);
2344
+ let existingPubKey = null;
2345
+ try {
2346
+ const existing = await this.tc.readPublicSpace(
2347
+ this.host,
2348
+ publicSpaceId,
2349
+ ".well-known/vault-pubkey"
2350
+ );
2351
+ if (existing.ok && existing.data) {
2352
+ existingPubKey = existing.data;
2353
+ }
2354
+ } catch {
2355
+ }
2356
+ if (existingPubKey) {
2357
+ this.encryptionIdentity = {
2358
+ publicKey: base64Decode(existingPubKey),
2359
+ privateKey: new Uint8Array(0)
2360
+ // private key not available without signing
2361
+ };
2362
+ } else {
2363
+ let identitySigBytes = await loadCachedSignature(identityCacheKey);
2364
+ if (!identitySigBytes) {
2365
+ if (!signer) {
2366
+ this.encryptionIdentity = null;
2367
+ this._isUnlocked = true;
2368
+ return ok(void 0);
2369
+ }
2370
+ const s = signer;
2371
+ const sig = await s.signMessage(versionConfig.identityMessage);
2372
+ identitySigBytes = toBytes(sig);
2373
+ await cacheSignature(identityCacheKey, identitySigBytes);
2374
+ }
2375
+ const seed = this.crypto.deriveKey(
2376
+ identitySigBytes,
2377
+ toBytes("tinycloud-x25519"),
2378
+ toBytes("encryption-identity")
2379
+ );
2380
+ this.encryptionIdentity = this.crypto.x25519FromSeed(seed);
2381
+ try {
2382
+ const pubKeyB64 = base64Encode(this.encryptionIdentity.publicKey);
2383
+ await this.tc.ensurePublicSpace();
2384
+ await this.tc.publicKV.put(".well-known/vault-pubkey", pubKeyB64);
2385
+ await this.tc.publicKV.put(".well-known/vault-version", CURRENT_VAULT_VERSION);
2386
+ await this.tc.publicKV.put(".well-known/vault-space", this.vaultConfig.spaceId);
2387
+ } catch {
2388
+ }
2389
+ }
2390
+ this._isUnlocked = true;
2391
+ return ok(void 0);
2392
+ } catch (error) {
2393
+ this.masterKey = null;
2394
+ this.encryptionIdentity = null;
2395
+ return vaultError({
2396
+ code: "STORAGE_ERROR",
2397
+ cause: toError(error)
2398
+ });
2399
+ }
2400
+ });
2401
+ }
2402
+ /**
2403
+ * Clear the cached vault signatures.
2404
+ *
2405
+ * @param spaceId - Clear only this space's master cache. If omitted, clears all.
2406
+ */
2407
+ async clearCache(spaceId) {
2408
+ if (spaceId) {
2409
+ await clearSignatureCache(`vault-master:${spaceId}`);
2410
+ } else {
2411
+ await clearSignatureCache();
2412
+ }
2413
+ }
2414
+ /**
2415
+ * Lock the vault, clearing all key material from memory.
2416
+ */
2417
+ lock() {
2418
+ this.masterKey = null;
2419
+ this.encryptionIdentity = null;
2420
+ this._isUnlocked = false;
2421
+ }
2422
+ /**
2423
+ * Called when SDK signs out. Locks the vault and aborts operations.
2424
+ */
2425
+ onSignOut() {
2426
+ this.lock();
2427
+ super.onSignOut();
2428
+ }
2429
+ /**
2430
+ * Encrypt and store a value at the given key.
2431
+ *
2432
+ * @param key - The key to store under
2433
+ * @param value - The value to encrypt and store
2434
+ * @param options - Optional put configuration
2435
+ */
2436
+ async put(key, value, options) {
2437
+ return this.withTelemetry("put", key, async () => {
2438
+ if (!this._isUnlocked || !this.masterKey) {
2439
+ return vaultError({
2440
+ code: "VAULT_LOCKED",
2441
+ message: "Vault must be unlocked before storing data"
2442
+ });
2443
+ }
2444
+ if (!this.requireAuth()) {
2445
+ return vaultError({
2446
+ code: "VAULT_LOCKED",
2447
+ message: "Authentication required"
2448
+ });
2449
+ }
2450
+ try {
2451
+ let plaintext;
2452
+ if (value instanceof Uint8Array) {
2453
+ plaintext = value;
2454
+ } else if (options?.serialize) {
2455
+ plaintext = options.serialize(value);
2456
+ } else if (typeof value === "string") {
2457
+ plaintext = toBytes(value);
2458
+ } else {
2459
+ plaintext = toBytes(JSON.stringify(value));
2460
+ }
2461
+ const contentType = options?.contentType ?? (value instanceof Uint8Array ? "application/octet-stream" : "application/json");
2462
+ const entryKey = this.crypto.randomBytes(32);
2463
+ const keyId = hexEncode(this.crypto.sha256(entryKey)).slice(0, 16);
2464
+ const encrypted = this.crypto.encrypt(entryKey, plaintext);
2465
+ const keyBlob = this.crypto.encrypt(this.masterKey, entryKey);
2466
+ const metadata = {
2467
+ [VaultHeaders.VERSION]: "1",
2468
+ [VaultHeaders.CIPHER]: "aes-256-gcm",
2469
+ [VaultHeaders.KEY_ID]: keyId,
2470
+ [VaultHeaders.CONTENT_TYPE]: contentType,
2471
+ [VaultHeaders.KDF]: "hkdf-sha256",
2472
+ [VaultHeaders.KEY_ROTATION]: this.vaultConfig.keyRotation ?? "per-write",
2473
+ ...options?.metadata ?? {}
2474
+ };
2475
+ const keyMetadata = JSON.stringify({
2476
+ keyId,
2477
+ contentType,
2478
+ ...metadata
2479
+ });
2480
+ const keyPayload = JSON.stringify({
2481
+ key: base64Encode(keyBlob),
2482
+ metadata: keyMetadata
2483
+ });
2484
+ const keyPutResult = await this.tc.kv.put(
2485
+ `keys/${key}`,
2486
+ keyPayload
2487
+ );
2488
+ if (!keyPutResult.ok) {
2489
+ return vaultError({
2490
+ code: "STORAGE_ERROR",
2491
+ cause: new Error(
2492
+ `Failed to store key blob: ${keyPutResult.error.message}`
2493
+ )
2494
+ });
2495
+ }
2496
+ const valuePayload = JSON.stringify({
2497
+ data: base64Encode(encrypted),
2498
+ metadata
2499
+ });
2500
+ const valuePutResult = await this.tc.kv.put(
2501
+ `vault/${key}`,
2502
+ valuePayload
2503
+ );
2504
+ if (!valuePutResult.ok) {
2505
+ return vaultError({
2506
+ code: "STORAGE_ERROR",
2507
+ cause: new Error(
2508
+ `Failed to store encrypted value: ${valuePutResult.error.message}`
2509
+ )
2510
+ });
2511
+ }
2512
+ return ok(void 0);
2513
+ } catch (error) {
2514
+ return vaultError({
2515
+ code: "STORAGE_ERROR",
2516
+ cause: toError(error)
2517
+ });
2518
+ }
2519
+ });
2520
+ }
2521
+ /**
2522
+ * Retrieve and decrypt a value by key.
2523
+ *
2524
+ * @param key - The key to retrieve
2525
+ * @param options - Optional get configuration
2526
+ * @returns Result with the decrypted entry
2527
+ */
2528
+ async get(key, options) {
2529
+ return this.withTelemetry("get", key, async () => {
2530
+ if (!this._isUnlocked || !this.masterKey) {
2531
+ return vaultError({
2532
+ code: "VAULT_LOCKED",
2533
+ message: "Vault must be unlocked before reading data"
2534
+ });
2535
+ }
2536
+ if (!this.requireAuth()) {
2537
+ return vaultError({
2538
+ code: "VAULT_LOCKED",
2539
+ message: "Authentication required"
2540
+ });
2541
+ }
2542
+ try {
2543
+ const keyResult = await this.tc.kv.get(`keys/${key}`, {
2544
+ raw: true
2545
+ });
2546
+ if (!keyResult.ok) {
2547
+ return vaultError({ code: "KEY_NOT_FOUND", key });
2548
+ }
2549
+ const keyEnvelope = JSON.parse(keyResult.data.data);
2550
+ const keyBlobBytes = base64Decode(keyEnvelope.key);
2551
+ const entryKey = this.crypto.decrypt(this.masterKey, keyBlobBytes);
2552
+ const valueResult = await this.tc.kv.get(`vault/${key}`, {
2553
+ raw: true
2554
+ });
2555
+ if (!valueResult.ok) {
2556
+ return vaultError({ code: "KEY_NOT_FOUND", key });
2557
+ }
2558
+ const valueEnvelope = JSON.parse(valueResult.data.data);
2559
+ const encryptedBytes = base64Decode(valueEnvelope.data);
2560
+ const plaintext = this.crypto.decrypt(entryKey, encryptedBytes);
2561
+ const metadata = valueEnvelope.metadata ?? {};
2562
+ const contentType = metadata[VaultHeaders.CONTENT_TYPE] ?? "application/json";
2563
+ const keyId = metadata[VaultHeaders.KEY_ID] ?? "";
2564
+ let value;
2565
+ if (options?.raw) {
2566
+ value = plaintext;
2567
+ } else if (options?.deserialize) {
2568
+ value = options.deserialize(plaintext);
2569
+ } else if (contentType === "application/json") {
2570
+ value = JSON.parse(fromBytes(plaintext));
2571
+ } else {
2572
+ value = plaintext;
2573
+ }
2574
+ return ok({ value, metadata, keyId });
2575
+ } catch (error) {
2576
+ if (error instanceof Error && error.message.includes("decryption")) {
2577
+ return vaultError({
2578
+ code: "DECRYPTION_FAILED",
2579
+ message: error.message
2580
+ });
2581
+ }
2582
+ return vaultError({
2583
+ code: "STORAGE_ERROR",
2584
+ cause: toError(error)
2585
+ });
2586
+ }
2587
+ });
2588
+ }
2589
+ /**
2590
+ * Delete an encrypted key.
2591
+ * Removes both the encrypted value and the key blob.
2592
+ *
2593
+ * @param key - The key to delete
2594
+ */
2595
+ async delete(key) {
2596
+ return this.withTelemetry("delete", key, async () => {
2597
+ if (!this._isUnlocked) {
2598
+ return vaultError({
2599
+ code: "VAULT_LOCKED",
2600
+ message: "Vault must be unlocked before deleting data"
2601
+ });
2602
+ }
2603
+ if (!this.requireAuth()) {
2604
+ return vaultError({
2605
+ code: "VAULT_LOCKED",
2606
+ message: "Authentication required"
2607
+ });
2608
+ }
2609
+ try {
2610
+ const [keyDelResult, valueDelResult] = await Promise.all([
2611
+ this.tc.kv.delete(`keys/${key}`),
2612
+ this.tc.kv.delete(`vault/${key}`)
2613
+ ]);
2614
+ if (!keyDelResult.ok && !valueDelResult.ok) {
2615
+ return vaultError({ code: "KEY_NOT_FOUND", key });
2616
+ }
2617
+ return ok(void 0);
2618
+ } catch (error) {
2619
+ return vaultError({
2620
+ code: "STORAGE_ERROR",
2621
+ cause: toError(error)
2622
+ });
2623
+ }
2624
+ });
2625
+ }
2626
+ /**
2627
+ * List vault keys with optional prefix filtering.
2628
+ *
2629
+ * @param options - Optional list configuration
2630
+ * @returns Result with array of key names (vault/ prefix stripped)
2631
+ */
2632
+ async list(options) {
2633
+ return this.withTelemetry("list", options?.prefix, async () => {
2634
+ if (!this._isUnlocked) {
2635
+ return vaultError({
2636
+ code: "VAULT_LOCKED",
2637
+ message: "Vault must be unlocked before listing data"
2638
+ });
2639
+ }
2640
+ if (!this.requireAuth()) {
2641
+ return vaultError({
2642
+ code: "VAULT_LOCKED",
2643
+ message: "Authentication required"
2644
+ });
2645
+ }
2646
+ try {
2647
+ const listPrefix = options?.prefix ? `vault/${options.prefix}` : "vault/";
2648
+ const listResult = await this.tc.kv.list({
2649
+ prefix: listPrefix,
2650
+ removePrefix: true
2651
+ });
2652
+ if (!listResult.ok) {
2653
+ return vaultError({
2654
+ code: "STORAGE_ERROR",
2655
+ cause: new Error(
2656
+ `Failed to list vault keys: ${listResult.error.message}`
2657
+ )
2658
+ });
2659
+ }
2660
+ let keys = listResult.data.keys;
2661
+ if (options?.removePrefix && options.prefix) {
2662
+ const userPrefix = options.prefix.endsWith("/") ? options.prefix : `${options.prefix}/`;
2663
+ keys = keys.map(
2664
+ (k) => k.startsWith(userPrefix) ? k.slice(userPrefix.length) : k
2665
+ );
2666
+ }
2667
+ return ok(keys);
2668
+ } catch (error) {
2669
+ return vaultError({
2670
+ code: "STORAGE_ERROR",
2671
+ cause: toError(error)
2672
+ });
2673
+ }
2674
+ });
2675
+ }
2676
+ /**
2677
+ * Get envelope metadata for a key without decrypting the value.
2678
+ *
2679
+ * @param key - The key to inspect
2680
+ * @returns Result with metadata headers
2681
+ */
2682
+ async head(key) {
2683
+ return this.withTelemetry("head", key, async () => {
2684
+ if (!this._isUnlocked) {
2685
+ return vaultError({
2686
+ code: "VAULT_LOCKED",
2687
+ message: "Vault must be unlocked before reading metadata"
2688
+ });
2689
+ }
2690
+ if (!this.requireAuth()) {
2691
+ return vaultError({
2692
+ code: "VAULT_LOCKED",
2693
+ message: "Authentication required"
2694
+ });
2695
+ }
2696
+ try {
2697
+ const valueResult = await this.tc.kv.get(`vault/${key}`, {
2698
+ raw: true
2699
+ });
2700
+ if (!valueResult.ok) {
2701
+ return vaultError({ code: "KEY_NOT_FOUND", key });
2702
+ }
2703
+ const valueEnvelope = JSON.parse(valueResult.data.data);
2704
+ const metadata = valueEnvelope.metadata ?? {};
2705
+ return ok(metadata);
2706
+ } catch (error) {
2707
+ return vaultError({
2708
+ code: "STORAGE_ERROR",
2709
+ cause: toError(error)
2710
+ });
2711
+ }
2712
+ });
2713
+ }
2714
+ // =========================================================================
2715
+ // Batch Operations
2716
+ // =========================================================================
2717
+ /**
2718
+ * Encrypt and store multiple entries.
2719
+ *
2720
+ * @param entries - Array of key/value pairs with optional per-entry options
2721
+ * @returns Array of results, one per entry
2722
+ */
2723
+ async putMany(entries) {
2724
+ return Promise.all(
2725
+ entries.map((entry) => this.put(entry.key, entry.value, entry.options))
2726
+ );
2727
+ }
2728
+ /**
2729
+ * Retrieve and decrypt multiple keys.
2730
+ *
2731
+ * @param keys - Array of keys to retrieve
2732
+ * @param options - Optional get configuration applied to all entries
2733
+ * @returns Array of results, one per key
2734
+ */
2735
+ async getMany(keys, options) {
2736
+ return Promise.all(keys.map((key) => this.get(key, options)));
2737
+ }
2738
+ // =========================================================================
2739
+ // Phase 2: Sharing
2740
+ // =========================================================================
2741
+ /**
2742
+ * Re-encrypt a vault key for another user (renamed from grant).
2743
+ * Re-encrypts the data key to the recipient's public key via X25519 DH.
2744
+ *
2745
+ * @param key - The key to share
2746
+ * @param recipientDID - The recipient's primary DID (did:pkh:...)
2747
+ * @param options - Optional grant configuration
2748
+ */
2749
+ async reencrypt(key, recipientDID, options) {
2750
+ return this.withTelemetry("reencrypt", key, async () => {
2751
+ if (!this._isUnlocked || !this.masterKey) {
2752
+ return vaultError({
2753
+ code: "VAULT_LOCKED",
2754
+ message: "Vault must be unlocked before granting access"
2755
+ });
2756
+ }
2757
+ if (!this.requireAuth()) {
2758
+ return vaultError({
2759
+ code: "VAULT_LOCKED",
2760
+ message: "Authentication required"
2761
+ });
2762
+ }
2763
+ try {
2764
+ const pubKeyResult = await this.resolvePublicKey(recipientDID);
2765
+ if (!pubKeyResult.ok) {
2766
+ return pubKeyResult;
2767
+ }
2768
+ const bobPubKey = pubKeyResult.data;
2769
+ const keyResult = await this.tc.kv.get(`keys/${key}`, {
2770
+ raw: true
2771
+ });
2772
+ if (!keyResult.ok) {
2773
+ return vaultError({ code: "KEY_NOT_FOUND", key });
2774
+ }
2775
+ const keyEnvelope = JSON.parse(keyResult.data.data);
2776
+ const keyBlobBytes = base64Decode(keyEnvelope.key);
2777
+ const entryKey = this.crypto.decrypt(this.masterKey, keyBlobBytes);
2778
+ const ephemeralSeed = this.crypto.randomBytes(32);
2779
+ const ephemeralKeyPair = this.crypto.x25519FromSeed(ephemeralSeed);
2780
+ const sharedSecret = this.crypto.x25519Dh(
2781
+ ephemeralKeyPair.privateKey,
2782
+ bobPubKey
2783
+ );
2784
+ const encryptionKey = this.crypto.deriveKey(
2785
+ sharedSecret,
2786
+ toBytes("tinycloud-x25519"),
2787
+ toBytes("vault-grant")
2788
+ );
2789
+ const encryptedGrant = this.crypto.encrypt(encryptionKey, entryKey);
2790
+ const grantBlob = concatBytes(
2791
+ ephemeralKeyPair.publicKey,
2792
+ encryptedGrant
2793
+ );
2794
+ const grantPayload = JSON.stringify({
2795
+ grant: base64Encode(grantBlob),
2796
+ spaceId: this.vaultConfig.spaceId,
2797
+ metadata: {
2798
+ [VaultHeaders.GRANT_VERSION]: "1",
2799
+ [VaultHeaders.GRANTOR]: this.tc.did,
2800
+ ...options?.metadata ?? {}
2801
+ }
2802
+ });
2803
+ const grantPutResult = await this.tc.kv.put(
2804
+ `grants/${recipientDID}/${key}`,
2805
+ grantPayload
2806
+ );
2807
+ if (!grantPutResult.ok) {
2808
+ return vaultError({
2809
+ code: "STORAGE_ERROR",
2810
+ cause: new Error(
2811
+ `Failed to store grant: ${grantPutResult.error.message}`
2812
+ )
2813
+ });
2814
+ }
2815
+ return ok(void 0);
2816
+ } catch (error) {
2817
+ return vaultError({
2818
+ code: "STORAGE_ERROR",
2819
+ cause: toError(error)
2820
+ });
2821
+ }
2822
+ });
2823
+ }
2824
+ /**
2825
+ * @deprecated Use reencrypt() instead.
2826
+ */
2827
+ async grant(key, recipientDID, options) {
2828
+ return this.reencrypt(key, recipientDID, options);
2829
+ }
2830
+ /**
2831
+ * Retrieve and decrypt a value shared by another user.
2832
+ *
2833
+ * @param grantorDID - The DID of the user who shared the data
2834
+ * @param key - The key that was shared
2835
+ * @param options - Optional get configuration
2836
+ * @returns Result with the decrypted entry
2837
+ */
2838
+ async getShared(grantorDID, key, options) {
2839
+ return this.withTelemetry("getShared", key, async () => {
2840
+ if (!this._isUnlocked || !this.masterKey || !this.encryptionIdentity) {
2841
+ return vaultError({
2842
+ code: "VAULT_LOCKED",
2843
+ message: "Vault must be unlocked before reading shared data"
2844
+ });
2845
+ }
2846
+ if (!this.requireAuth()) {
2847
+ return vaultError({
2848
+ code: "VAULT_LOCKED",
2849
+ message: "Authentication required"
2850
+ });
2851
+ }
2852
+ try {
2853
+ const myDID = this.tc.did;
2854
+ const grantorKV = options?.kv;
2855
+ if (!grantorKV) {
2856
+ return vaultError({
2857
+ code: "STORAGE_ERROR",
2858
+ cause: new Error(
2859
+ "getShared requires a delegated KV service via options.kv. Use useDelegation() to get delegated access, then pass { kv: access.kv }."
2860
+ )
2861
+ });
2862
+ }
2863
+ const grantResult = await grantorKV.get(`grants/${myDID}/${key}`, {
2864
+ raw: true
2865
+ });
2866
+ if (!grantResult.ok) {
2867
+ return vaultError({
2868
+ code: "GRANT_NOT_FOUND",
2869
+ grantor: grantorDID,
2870
+ key
2871
+ });
2872
+ }
2873
+ const grantEnvelope = typeof grantResult.data?.data === "string" ? JSON.parse(grantResult.data.data) : grantResult.data?.data;
2874
+ const grantBlobBytes = base64Decode(grantEnvelope.grant);
2875
+ const ephemeralPubKey = grantBlobBytes.slice(0, 32);
2876
+ const encryptedGrant = grantBlobBytes.slice(32);
2877
+ const sharedSecret = this.crypto.x25519Dh(
2878
+ this.encryptionIdentity.privateKey,
2879
+ ephemeralPubKey
2880
+ );
2881
+ const encryptionKey = this.crypto.deriveKey(
2882
+ sharedSecret,
2883
+ toBytes("tinycloud-x25519"),
2884
+ toBytes("vault-grant")
2885
+ );
2886
+ const entryKey = this.crypto.decrypt(encryptionKey, encryptedGrant);
2887
+ const valueResult = await grantorKV.get(`vault/${key}`, {
2888
+ raw: true
2889
+ });
2890
+ if (!valueResult.ok) {
2891
+ return vaultError({
2892
+ code: "KEY_NOT_FOUND",
2893
+ key
2894
+ });
2895
+ }
2896
+ const valueEnvelope = typeof valueResult.data?.data === "string" ? JSON.parse(valueResult.data.data) : valueResult.data?.data;
2897
+ const encryptedBytes = base64Decode(valueEnvelope.data);
2898
+ const plaintext = this.crypto.decrypt(entryKey, encryptedBytes);
2899
+ const metadata = valueEnvelope.metadata ?? {};
2900
+ const contentType = metadata[VaultHeaders.CONTENT_TYPE] ?? "application/json";
2901
+ const keyId = metadata[VaultHeaders.KEY_ID] ?? "";
2902
+ let value;
2903
+ if (options?.raw) {
2904
+ value = plaintext;
2905
+ } else if (options?.deserialize) {
2906
+ value = options.deserialize(plaintext);
2907
+ } else if (contentType === "application/json") {
2908
+ value = JSON.parse(fromBytes(plaintext));
2909
+ } else {
2910
+ value = plaintext;
2911
+ }
2912
+ return ok({ value, metadata, keyId });
2913
+ } catch (error) {
2914
+ if (error instanceof Error && error.message.includes("decryption")) {
2915
+ return vaultError({
2916
+ code: "DECRYPTION_FAILED",
2917
+ message: error.message
2918
+ });
2919
+ }
2920
+ return vaultError({
2921
+ code: "STORAGE_ERROR",
2922
+ cause: toError(error)
2923
+ });
2924
+ }
2925
+ });
2926
+ }
2927
+ /**
2928
+ * Resolve another user's public encryption key from their DID.
2929
+ *
2930
+ * @param did - The DID to resolve (did:pkh:eip155:{chainId}:{address})
2931
+ * @returns Result with the public key bytes
2932
+ */
2933
+ async resolvePublicKey(did) {
2934
+ try {
2935
+ const parts = this.parseDID(did);
2936
+ if (!parts) {
2937
+ return vaultError({ code: "PUBLIC_KEY_NOT_FOUND", did });
2938
+ }
2939
+ const spaceId = this.tc.makePublicSpaceId(
2940
+ parts.address,
2941
+ parts.chainId
2942
+ );
2943
+ const result = await this.tc.readPublicSpace(
2944
+ this.host,
2945
+ spaceId,
2946
+ ".well-known/vault-pubkey"
2947
+ );
2948
+ if (!result.ok) {
2949
+ return vaultError({ code: "PUBLIC_KEY_NOT_FOUND", did });
2950
+ }
2951
+ const pubKeyBytes = base64Decode(result.data);
2952
+ return { ok: true, data: pubKeyBytes };
2953
+ } catch (error) {
2954
+ return vaultError({ code: "PUBLIC_KEY_NOT_FOUND", did });
2955
+ }
2956
+ }
2957
+ /**
2958
+ * List DIDs that have been granted access to a key.
2959
+ *
2960
+ * @param key - The key to list grants for
2961
+ * @returns Result with array of recipient DIDs
2962
+ */
2963
+ async listGrants(key) {
2964
+ return this.withTelemetry("listGrants", key, async () => {
2965
+ if (!this._isUnlocked) {
2966
+ return vaultError({
2967
+ code: "VAULT_LOCKED",
2968
+ message: "Vault must be unlocked before listing grants"
2969
+ });
2970
+ }
2971
+ if (!this.requireAuth()) {
2972
+ return vaultError({
2973
+ code: "VAULT_LOCKED",
2974
+ message: "Authentication required"
2975
+ });
2976
+ }
2977
+ try {
2978
+ const listResult = await this.tc.kv.list({
2979
+ prefix: "grants/",
2980
+ removePrefix: true
2981
+ });
2982
+ if (!listResult.ok) {
2983
+ return vaultError({
2984
+ code: "STORAGE_ERROR",
2985
+ cause: new Error(
2986
+ `Failed to list grants: ${listResult.error.message}`
2987
+ )
2988
+ });
2989
+ }
2990
+ const dids = [];
2991
+ for (const grantPath of listResult.data.keys) {
2992
+ if (grantPath.endsWith(`/${key}`)) {
2993
+ const did = grantPath.slice(
2994
+ 0,
2995
+ grantPath.length - key.length - 1
2996
+ );
2997
+ if (did) {
2998
+ dids.push(did);
2999
+ }
3000
+ }
3001
+ }
3002
+ return ok(dids);
3003
+ } catch (error) {
3004
+ return vaultError({
3005
+ code: "STORAGE_ERROR",
3006
+ cause: toError(error)
3007
+ });
3008
+ }
3009
+ });
3010
+ }
3011
+ // =========================================================================
3012
+ // Phase 3: Key Rotation / Revocation
3013
+ // =========================================================================
3014
+ /**
3015
+ * Revoke a previously issued grant.
3016
+ *
3017
+ * This performs a full key rotation:
3018
+ * 1. Lists current grantees
3019
+ * 2. Removes the revoked recipient
3020
+ * 3. Re-encrypts the value with a new entry key
3021
+ * 4. Re-issues grants to remaining recipients
3022
+ *
3023
+ * @param key - The key to revoke access to
3024
+ * @param recipientDID - The recipient whose access to revoke
3025
+ */
3026
+ async revoke(key, recipientDID) {
3027
+ return this.withTelemetry("revoke", key, async () => {
3028
+ if (!this._isUnlocked || !this.masterKey) {
3029
+ return vaultError({
3030
+ code: "VAULT_LOCKED",
3031
+ message: "Vault must be unlocked before revoking access"
3032
+ });
3033
+ }
3034
+ if (!this.requireAuth()) {
3035
+ return vaultError({
3036
+ code: "VAULT_LOCKED",
3037
+ message: "Authentication required"
3038
+ });
3039
+ }
3040
+ try {
3041
+ const granteesResult = await this.listGrants(key);
3042
+ if (!granteesResult.ok) {
3043
+ return granteesResult;
3044
+ }
3045
+ const remainingGrantees = granteesResult.data.filter(
3046
+ (did) => did !== recipientDID
3047
+ );
3048
+ const deleteGrantResult = await this.tc.kv.delete(
3049
+ `grants/${recipientDID}/${key}`
3050
+ );
3051
+ const getResult = await this.get(key);
3052
+ if (!getResult.ok) {
3053
+ return getResult;
3054
+ }
3055
+ const currentEntry = getResult.data;
3056
+ const newEntryKey = this.crypto.randomBytes(32);
3057
+ const newKeyId = hexEncode(this.crypto.sha256(newEntryKey)).slice(
3058
+ 0,
3059
+ 16
3060
+ );
3061
+ let plaintext;
3062
+ if (currentEntry.value instanceof Uint8Array) {
3063
+ plaintext = currentEntry.value;
3064
+ } else {
3065
+ plaintext = toBytes(JSON.stringify(currentEntry.value));
3066
+ }
3067
+ const encrypted = this.crypto.encrypt(newEntryKey, plaintext);
3068
+ const newKeyBlob = this.crypto.encrypt(this.masterKey, newEntryKey);
3069
+ const metadata = {
3070
+ ...currentEntry.metadata,
3071
+ [VaultHeaders.KEY_ID]: newKeyId
3072
+ };
3073
+ const keyPayload = JSON.stringify({
3074
+ key: base64Encode(newKeyBlob),
3075
+ metadata: JSON.stringify({
3076
+ keyId: newKeyId,
3077
+ ...metadata
3078
+ })
3079
+ });
3080
+ const keyPutResult = await this.tc.kv.put(
3081
+ `keys/${key}`,
3082
+ keyPayload
3083
+ );
3084
+ if (!keyPutResult.ok) {
3085
+ return vaultError({
3086
+ code: "STORAGE_ERROR",
3087
+ cause: new Error(
3088
+ `Failed to store rotated key blob: ${keyPutResult.error.message}`
3089
+ )
3090
+ });
3091
+ }
3092
+ const valuePayload = JSON.stringify({
3093
+ data: base64Encode(encrypted),
3094
+ metadata
3095
+ });
3096
+ const valuePutResult = await this.tc.kv.put(
3097
+ `vault/${key}`,
3098
+ valuePayload
3099
+ );
3100
+ if (!valuePutResult.ok) {
3101
+ return vaultError({
3102
+ code: "STORAGE_ERROR",
3103
+ cause: new Error(
3104
+ `Failed to store re-encrypted value: ${valuePutResult.error.message}`
3105
+ )
3106
+ });
3107
+ }
3108
+ for (const did of remainingGrantees) {
3109
+ const grantResult = await this.reencrypt(key, did);
3110
+ if (!grantResult.ok) {
3111
+ }
3112
+ }
3113
+ return ok(void 0);
3114
+ } catch (error) {
3115
+ return vaultError({
3116
+ code: "STORAGE_ERROR",
3117
+ cause: toError(error)
3118
+ });
3119
+ }
3120
+ });
3121
+ }
3122
+ // =========================================================================
3123
+ // Internal Helpers
3124
+ // =========================================================================
3125
+ /**
3126
+ * Parse a DID string to extract address and chainId.
3127
+ * Expected format: did:pkh:eip155:{chainId}:{address}
3128
+ *
3129
+ * @param did - The DID to parse
3130
+ * @returns Parsed address and chainId, or null if invalid
3131
+ */
3132
+ parseDID(did) {
3133
+ const parts = did.split(":");
3134
+ if (parts.length !== 5 || parts[0] !== "did" || parts[1] !== "pkh" || parts[2] !== "eip155") {
3135
+ return null;
3136
+ }
3137
+ const chainId = parseInt(parts[3], 10);
3138
+ const address = parts[4];
3139
+ if (isNaN(chainId) || !address) {
3140
+ return null;
3141
+ }
3142
+ return { address, chainId };
3143
+ }
3144
+ };
3145
+ /**
3146
+ * Service identifier for registration.
3147
+ */
3148
+ DataVaultService.serviceName = "vault";
3149
+
3150
+ // src/vault/createVaultCrypto.ts
3151
+ function createVaultCrypto(wasm) {
3152
+ return {
3153
+ encrypt: (key, plaintext) => wasm.vault_encrypt(key, plaintext),
3154
+ decrypt: (key, blob) => wasm.vault_decrypt(key, blob),
3155
+ deriveKey: (signature, salt, info) => wasm.vault_derive_key(salt, signature, info),
3156
+ x25519FromSeed: (seed) => wasm.vault_x25519_from_seed(seed),
3157
+ x25519Dh: (privateKey, publicKey) => wasm.vault_x25519_dh(privateKey, publicKey),
3158
+ randomBytes: (length) => wasm.vault_random_bytes(length),
3159
+ sha256: (data) => wasm.vault_sha256(data)
3160
+ };
3161
+ }
3162
+ // Annotate the CommonJS export names for ESM import in node:
3163
+ 0 && (module.exports = {
3164
+ BaseService,
3165
+ DataVaultService,
3166
+ DatabaseHandle,
3167
+ DuckDbAction,
3168
+ DuckDbDatabaseHandle,
3169
+ DuckDbService,
3170
+ ErrorCodes,
3171
+ GenericKVResponseSchema,
3172
+ GenericResultSchema,
3173
+ KVAction,
3174
+ KVListResponseSchema,
3175
+ KVListResultSchema,
3176
+ KVResponseHeadersSchema,
3177
+ KVService,
3178
+ PrefixedKVService,
3179
+ RetryPolicySchema,
3180
+ SQLAction,
3181
+ SQLService,
3182
+ ServiceContext,
3183
+ ServiceErrorEventSchema,
3184
+ ServiceErrorSchema,
3185
+ ServiceRequestEventSchema,
3186
+ ServiceResponseEventSchema,
3187
+ ServiceRetryEventSchema,
3188
+ ServiceSessionSchema,
3189
+ TelemetryEvents,
3190
+ TinyCloudQuota,
3191
+ VaultHeaders,
3192
+ VaultPublicSpaceKVActions,
3193
+ abortedError,
3194
+ authExpiredError,
3195
+ authRequiredError,
3196
+ authUnauthorizedError,
3197
+ createKVResponseSchema,
3198
+ createResultSchema,
3199
+ createVaultCrypto,
3200
+ defaultRetryPolicy,
3201
+ err,
3202
+ errorResult,
3203
+ networkError,
3204
+ notFoundError,
3205
+ ok,
3206
+ parseAuthError,
3207
+ permissionDeniedError,
3208
+ serviceError,
3209
+ storageLimitReachedError,
3210
+ storageQuotaExceededError,
3211
+ timeoutError,
3212
+ validateKVListResponse,
3213
+ validateKVResponseHeaders,
3214
+ validateRetryPolicy,
3215
+ validateServiceError,
3216
+ validateServiceRequestEvent,
3217
+ validateServiceResponseEvent,
3218
+ validateServiceSession,
3219
+ wrapError
3220
+ });
3221
+ //# sourceMappingURL=index.cjs.map