@tinycloud/sdk-services 1.7.0 → 2.0.2-beta.0

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 (135) 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 -258
  117. package/dist/vault/DataVaultService.d.ts.map +0 -1
  118. package/dist/vault/DataVaultService.js +0 -977
  119. package/dist/vault/DataVaultService.js.map +0 -1
  120. package/dist/vault/IDataVaultService.d.ts +0 -150
  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/createVaultCrypto.d.ts +0 -16
  125. package/dist/vault/createVaultCrypto.d.ts.map +0 -1
  126. package/dist/vault/createVaultCrypto.js +0 -12
  127. package/dist/vault/createVaultCrypto.js.map +0 -1
  128. package/dist/vault/index.d.ts +0 -10
  129. package/dist/vault/index.d.ts.map +0 -1
  130. package/dist/vault/index.js +0 -11
  131. package/dist/vault/index.js.map +0 -1
  132. package/dist/vault/types.d.ts +0 -133
  133. package/dist/vault/types.d.ts.map +0 -1
  134. package/dist/vault/types.js +0 -23
  135. package/dist/vault/types.js.map +0 -1
package/dist/index.d.ts CHANGED
@@ -1,58 +1,1843 @@
1
+ import { I as IServiceContext, a as InvokeFunction, F as FetchFunction, S as ServiceSession, R as RetryPolicy, b as IService, c as ServiceError, d as Result, B as BaseService, e as StorageQuotaInfo } from './BaseService-D9BFm_rV.js';
2
+ export { E as ErrorCode, f as ErrorCodes, g as EventHandler, h as FetchRequestInit, i as FetchResponse, j as InvocationFact, k as InvocationFacts, l as ServiceErrorEvent, m as ServiceHeaders, n as ServiceRequestEvent, o as ServiceResponseEvent, p as ServiceRetryEvent, T as TelemetryEvents, q as defaultRetryPolicy, r as err, s as ok, t as serviceError } from './BaseService-D9BFm_rV.js';
3
+ import { z } from 'zod';
4
+ import { IKVService } from './kv/index.js';
5
+ export { IPrefixedKVService, KVAction, KVActionType, KVDeleteOptions, KVGetOptions, KVHeadOptions, KVListOptions, KVListResponse, KVPutOptions, KVResponse, KVResponseHeaders, KVService, KVServiceConfig, PrefixedKVService } from './kv/index.js';
6
+ export { BatchOptions, BatchResponse, DatabaseHandle, ExecuteOptions, ExecuteResponse, IDatabaseHandle, ISQLService, QueryOptions, QueryResponse, SQLAction, SQLActionType, SQLService, SQLServiceConfig, SqlStatement, SqlValue } from './sql/index.js';
7
+
1
8
  /**
2
- * TinyCloud SDK Services
9
+ * Zod schemas for SDK Services API response types.
3
10
  *
4
- * Platform-agnostic services with plugin architecture for TinyCloud.
11
+ * This is the source of truth for service response types. TypeScript types
12
+ * are derived from these schemas using z.infer<>.
5
13
  *
6
14
  * @packageDocumentation
15
+ */
16
+
17
+ /**
18
+ * Validation error type for schema validation failures.
19
+ */
20
+ interface ValidationError {
21
+ code: "VALIDATION_ERROR";
22
+ message: string;
23
+ service: string;
24
+ meta?: {
25
+ issues: z.ZodIssue[];
26
+ path?: string;
27
+ };
28
+ }
29
+ /**
30
+ * Schema for service error with structured information.
31
+ */
32
+ declare const ServiceErrorSchema: z.ZodObject<{
33
+ /** Error code for programmatic handling (e.g., 'KV_NOT_FOUND', 'AUTH_EXPIRED') */
34
+ code: z.ZodString;
35
+ /** Human-readable error message */
36
+ message: z.ZodString;
37
+ /** Service that produced the error (e.g., 'kv', 'sql') */
38
+ service: z.ZodString;
39
+ /** Original error if this wraps another error - not validated since Error is a class */
40
+ cause: z.ZodOptional<z.ZodUnknown>;
41
+ /** Additional metadata about the error - passthrough allows any object properties */
42
+ meta: z.ZodOptional<z.ZodObject<{}, "passthrough", z.ZodTypeAny, z.objectOutputType<{}, z.ZodTypeAny, "passthrough">, z.objectInputType<{}, z.ZodTypeAny, "passthrough">>>;
43
+ }, "strip", z.ZodTypeAny, {
44
+ code: string;
45
+ message: string;
46
+ service: string;
47
+ cause?: unknown;
48
+ meta?: z.objectOutputType<{}, z.ZodTypeAny, "passthrough"> | undefined;
49
+ }, {
50
+ code: string;
51
+ message: string;
52
+ service: string;
53
+ cause?: unknown;
54
+ meta?: z.objectInputType<{}, z.ZodTypeAny, "passthrough"> | undefined;
55
+ }>;
56
+ type ServiceErrorType = z.infer<typeof ServiceErrorSchema>;
57
+ /**
58
+ * Creates a Result schema for a given data type.
59
+ * Result is a discriminated union: { ok: true, data: T } | { ok: false, error: E }
60
+ *
61
+ * @param dataSchema - Zod schema for the success data type
62
+ * @param errorSchema - Zod schema for the error type (defaults to ServiceErrorSchema)
63
+ * @returns A Zod schema for Result<T, E>
64
+ *
65
+ * @example
66
+ * ```typescript
67
+ * const KVGetResultSchema = createResultSchema(z.string());
68
+ * type KVGetResult = z.infer<typeof KVGetResultSchema>;
69
+ * ```
70
+ */
71
+ declare function createResultSchema<T extends z.ZodTypeAny, E extends z.ZodTypeAny>(dataSchema: T, errorSchema?: E): z.ZodDiscriminatedUnion<"ok", [z.ZodObject<{
72
+ ok: z.ZodLiteral<true>;
73
+ data: T;
74
+ }, "strip", z.ZodTypeAny, z.objectUtil.addQuestionMarks<z.baseObjectOutputType<{
75
+ ok: z.ZodLiteral<true>;
76
+ data: T;
77
+ }>, any> extends infer T_1 ? { [k in keyof T_1]: z.objectUtil.addQuestionMarks<z.baseObjectOutputType<{
78
+ ok: z.ZodLiteral<true>;
79
+ data: T;
80
+ }>, any>[k]; } : never, z.baseObjectInputType<{
81
+ ok: z.ZodLiteral<true>;
82
+ data: T;
83
+ }> extends infer T_2 ? { [k_1 in keyof T_2]: z.baseObjectInputType<{
84
+ ok: z.ZodLiteral<true>;
85
+ data: T;
86
+ }>[k_1]; } : never>, z.ZodObject<{
87
+ ok: z.ZodLiteral<false>;
88
+ error: E;
89
+ }, "strip", z.ZodTypeAny, z.objectUtil.addQuestionMarks<z.baseObjectOutputType<{
90
+ ok: z.ZodLiteral<false>;
91
+ error: E;
92
+ }>, any> extends infer T_3 ? { [k_2 in keyof T_3]: z.objectUtil.addQuestionMarks<z.baseObjectOutputType<{
93
+ ok: z.ZodLiteral<false>;
94
+ error: E;
95
+ }>, any>[k_2]; } : never, z.baseObjectInputType<{
96
+ ok: z.ZodLiteral<false>;
97
+ error: E;
98
+ }> extends infer T_4 ? { [k_3 in keyof T_4]: z.baseObjectInputType<{
99
+ ok: z.ZodLiteral<false>;
100
+ error: E;
101
+ }>[k_3]; } : never>]>;
102
+ /**
103
+ * Pre-built Result schema with unknown data and ServiceError.
104
+ * Useful for generic validation before type narrowing.
105
+ */
106
+ declare const GenericResultSchema: z.ZodDiscriminatedUnion<"ok", [z.ZodObject<{
107
+ ok: z.ZodLiteral<true>;
108
+ data: z.ZodUnknown;
109
+ }, "strip", z.ZodTypeAny, {
110
+ ok: true;
111
+ data?: unknown;
112
+ }, {
113
+ ok: true;
114
+ data?: unknown;
115
+ }>, z.ZodObject<{
116
+ ok: z.ZodLiteral<false>;
117
+ error: z.ZodObject<{
118
+ /** Error code for programmatic handling (e.g., 'KV_NOT_FOUND', 'AUTH_EXPIRED') */
119
+ code: z.ZodString;
120
+ /** Human-readable error message */
121
+ message: z.ZodString;
122
+ /** Service that produced the error (e.g., 'kv', 'sql') */
123
+ service: z.ZodString;
124
+ /** Original error if this wraps another error - not validated since Error is a class */
125
+ cause: z.ZodOptional<z.ZodUnknown>;
126
+ /** Additional metadata about the error - passthrough allows any object properties */
127
+ meta: z.ZodOptional<z.ZodObject<{}, "passthrough", z.ZodTypeAny, z.objectOutputType<{}, z.ZodTypeAny, "passthrough">, z.objectInputType<{}, z.ZodTypeAny, "passthrough">>>;
128
+ }, "strip", z.ZodTypeAny, {
129
+ code: string;
130
+ message: string;
131
+ service: string;
132
+ cause?: unknown;
133
+ meta?: z.objectOutputType<{}, z.ZodTypeAny, "passthrough"> | undefined;
134
+ }, {
135
+ code: string;
136
+ message: string;
137
+ service: string;
138
+ cause?: unknown;
139
+ meta?: z.objectInputType<{}, z.ZodTypeAny, "passthrough"> | undefined;
140
+ }>;
141
+ }, "strip", z.ZodTypeAny, {
142
+ error: {
143
+ code: string;
144
+ message: string;
145
+ service: string;
146
+ cause?: unknown;
147
+ meta?: z.objectOutputType<{}, z.ZodTypeAny, "passthrough"> | undefined;
148
+ };
149
+ ok: false;
150
+ }, {
151
+ error: {
152
+ code: string;
153
+ message: string;
154
+ service: string;
155
+ cause?: unknown;
156
+ meta?: z.objectInputType<{}, z.ZodTypeAny, "passthrough"> | undefined;
157
+ };
158
+ ok: false;
159
+ }>]>;
160
+ /**
161
+ * Schema for KV response headers metadata.
162
+ * Note: The `get` method is a function and cannot be validated with Zod.
163
+ * This schema validates the data properties only.
164
+ */
165
+ declare const KVResponseHeadersSchema: z.ZodObject<{
166
+ /** ETag for conditional requests */
167
+ etag: z.ZodOptional<z.ZodString>;
168
+ /** Content type of the stored value */
169
+ contentType: z.ZodOptional<z.ZodString>;
170
+ /** Last modification timestamp */
171
+ lastModified: z.ZodOptional<z.ZodString>;
172
+ /** Content length in bytes */
173
+ contentLength: z.ZodOptional<z.ZodNumber>;
174
+ }, "strip", z.ZodTypeAny, {
175
+ etag?: string | undefined;
176
+ contentType?: string | undefined;
177
+ lastModified?: string | undefined;
178
+ contentLength?: number | undefined;
179
+ }, {
180
+ etag?: string | undefined;
181
+ contentType?: string | undefined;
182
+ lastModified?: string | undefined;
183
+ contentLength?: number | undefined;
184
+ }>;
185
+ type KVResponseHeadersType = z.infer<typeof KVResponseHeadersSchema>;
186
+ /**
187
+ * Creates a KVResponse schema for a given data type.
188
+ *
189
+ * @param dataSchema - Zod schema for the data payload type
190
+ * @returns A Zod schema for KVResponse<T>
191
+ *
192
+ * @example
193
+ * ```typescript
194
+ * const UserResponseSchema = createKVResponseSchema(UserSchema);
195
+ * type UserResponse = z.infer<typeof UserResponseSchema>;
196
+ * ```
197
+ */
198
+ declare function createKVResponseSchema<T extends z.ZodTypeAny>(dataSchema: T): z.ZodObject<{
199
+ /** The data payload */
200
+ data: T;
201
+ /** Response headers with metadata */
202
+ headers: z.ZodObject<{
203
+ /** ETag for conditional requests */
204
+ etag: z.ZodOptional<z.ZodString>;
205
+ /** Content type of the stored value */
206
+ contentType: z.ZodOptional<z.ZodString>;
207
+ /** Last modification timestamp */
208
+ lastModified: z.ZodOptional<z.ZodString>;
209
+ /** Content length in bytes */
210
+ contentLength: z.ZodOptional<z.ZodNumber>;
211
+ }, "strip", z.ZodTypeAny, {
212
+ etag?: string | undefined;
213
+ contentType?: string | undefined;
214
+ lastModified?: string | undefined;
215
+ contentLength?: number | undefined;
216
+ }, {
217
+ etag?: string | undefined;
218
+ contentType?: string | undefined;
219
+ lastModified?: string | undefined;
220
+ contentLength?: number | undefined;
221
+ }>;
222
+ }, "strip", z.ZodTypeAny, z.objectUtil.addQuestionMarks<z.baseObjectOutputType<{
223
+ /** The data payload */
224
+ data: T;
225
+ /** Response headers with metadata */
226
+ headers: z.ZodObject<{
227
+ /** ETag for conditional requests */
228
+ etag: z.ZodOptional<z.ZodString>;
229
+ /** Content type of the stored value */
230
+ contentType: z.ZodOptional<z.ZodString>;
231
+ /** Last modification timestamp */
232
+ lastModified: z.ZodOptional<z.ZodString>;
233
+ /** Content length in bytes */
234
+ contentLength: z.ZodOptional<z.ZodNumber>;
235
+ }, "strip", z.ZodTypeAny, {
236
+ etag?: string | undefined;
237
+ contentType?: string | undefined;
238
+ lastModified?: string | undefined;
239
+ contentLength?: number | undefined;
240
+ }, {
241
+ etag?: string | undefined;
242
+ contentType?: string | undefined;
243
+ lastModified?: string | undefined;
244
+ contentLength?: number | undefined;
245
+ }>;
246
+ }>, any> extends infer T_1 ? { [k in keyof T_1]: z.objectUtil.addQuestionMarks<z.baseObjectOutputType<{
247
+ /** The data payload */
248
+ data: T;
249
+ /** Response headers with metadata */
250
+ headers: z.ZodObject<{
251
+ /** ETag for conditional requests */
252
+ etag: z.ZodOptional<z.ZodString>;
253
+ /** Content type of the stored value */
254
+ contentType: z.ZodOptional<z.ZodString>;
255
+ /** Last modification timestamp */
256
+ lastModified: z.ZodOptional<z.ZodString>;
257
+ /** Content length in bytes */
258
+ contentLength: z.ZodOptional<z.ZodNumber>;
259
+ }, "strip", z.ZodTypeAny, {
260
+ etag?: string | undefined;
261
+ contentType?: string | undefined;
262
+ lastModified?: string | undefined;
263
+ contentLength?: number | undefined;
264
+ }, {
265
+ etag?: string | undefined;
266
+ contentType?: string | undefined;
267
+ lastModified?: string | undefined;
268
+ contentLength?: number | undefined;
269
+ }>;
270
+ }>, any>[k]; } : never, z.baseObjectInputType<{
271
+ /** The data payload */
272
+ data: T;
273
+ /** Response headers with metadata */
274
+ headers: z.ZodObject<{
275
+ /** ETag for conditional requests */
276
+ etag: z.ZodOptional<z.ZodString>;
277
+ /** Content type of the stored value */
278
+ contentType: z.ZodOptional<z.ZodString>;
279
+ /** Last modification timestamp */
280
+ lastModified: z.ZodOptional<z.ZodString>;
281
+ /** Content length in bytes */
282
+ contentLength: z.ZodOptional<z.ZodNumber>;
283
+ }, "strip", z.ZodTypeAny, {
284
+ etag?: string | undefined;
285
+ contentType?: string | undefined;
286
+ lastModified?: string | undefined;
287
+ contentLength?: number | undefined;
288
+ }, {
289
+ etag?: string | undefined;
290
+ contentType?: string | undefined;
291
+ lastModified?: string | undefined;
292
+ contentLength?: number | undefined;
293
+ }>;
294
+ }> extends infer T_2 ? { [k_1 in keyof T_2]: z.baseObjectInputType<{
295
+ /** The data payload */
296
+ data: T;
297
+ /** Response headers with metadata */
298
+ headers: z.ZodObject<{
299
+ /** ETag for conditional requests */
300
+ etag: z.ZodOptional<z.ZodString>;
301
+ /** Content type of the stored value */
302
+ contentType: z.ZodOptional<z.ZodString>;
303
+ /** Last modification timestamp */
304
+ lastModified: z.ZodOptional<z.ZodString>;
305
+ /** Content length in bytes */
306
+ contentLength: z.ZodOptional<z.ZodNumber>;
307
+ }, "strip", z.ZodTypeAny, {
308
+ etag?: string | undefined;
309
+ contentType?: string | undefined;
310
+ lastModified?: string | undefined;
311
+ contentLength?: number | undefined;
312
+ }, {
313
+ etag?: string | undefined;
314
+ contentType?: string | undefined;
315
+ lastModified?: string | undefined;
316
+ contentLength?: number | undefined;
317
+ }>;
318
+ }>[k_1]; } : never>;
319
+ /**
320
+ * Generic KVResponse schema with unknown data.
321
+ * Useful for generic validation before type narrowing.
322
+ */
323
+ declare const GenericKVResponseSchema: z.ZodObject<{
324
+ /** The data payload */
325
+ data: z.ZodUnknown;
326
+ /** Response headers with metadata */
327
+ headers: z.ZodObject<{
328
+ /** ETag for conditional requests */
329
+ etag: z.ZodOptional<z.ZodString>;
330
+ /** Content type of the stored value */
331
+ contentType: z.ZodOptional<z.ZodString>;
332
+ /** Last modification timestamp */
333
+ lastModified: z.ZodOptional<z.ZodString>;
334
+ /** Content length in bytes */
335
+ contentLength: z.ZodOptional<z.ZodNumber>;
336
+ }, "strip", z.ZodTypeAny, {
337
+ etag?: string | undefined;
338
+ contentType?: string | undefined;
339
+ lastModified?: string | undefined;
340
+ contentLength?: number | undefined;
341
+ }, {
342
+ etag?: string | undefined;
343
+ contentType?: string | undefined;
344
+ lastModified?: string | undefined;
345
+ contentLength?: number | undefined;
346
+ }>;
347
+ }, "strip", z.ZodTypeAny, {
348
+ headers: {
349
+ etag?: string | undefined;
350
+ contentType?: string | undefined;
351
+ lastModified?: string | undefined;
352
+ contentLength?: number | undefined;
353
+ };
354
+ data?: unknown;
355
+ }, {
356
+ headers: {
357
+ etag?: string | undefined;
358
+ contentType?: string | undefined;
359
+ lastModified?: string | undefined;
360
+ contentLength?: number | undefined;
361
+ };
362
+ data?: unknown;
363
+ }>;
364
+ type GenericKVResponseType = z.infer<typeof GenericKVResponseSchema>;
365
+ /**
366
+ * Schema for KV list response.
367
+ */
368
+ declare const KVListResponseSchema: z.ZodObject<{
369
+ /** Array of keys matching the list criteria */
370
+ keys: z.ZodArray<z.ZodString, "many">;
371
+ }, "strip", z.ZodTypeAny, {
372
+ keys: string[];
373
+ }, {
374
+ keys: string[];
375
+ }>;
376
+ type KVListResponseType = z.infer<typeof KVListResponseSchema>;
377
+ /**
378
+ * Result schema for KV list operations.
379
+ */
380
+ declare const KVListResultSchema: z.ZodDiscriminatedUnion<"ok", [z.ZodObject<{
381
+ ok: z.ZodLiteral<true>;
382
+ data: z.ZodObject<{
383
+ /** Array of keys matching the list criteria */
384
+ keys: z.ZodArray<z.ZodString, "many">;
385
+ }, "strip", z.ZodTypeAny, {
386
+ keys: string[];
387
+ }, {
388
+ keys: string[];
389
+ }>;
390
+ }, "strip", z.ZodTypeAny, {
391
+ data: {
392
+ keys: string[];
393
+ };
394
+ ok: true;
395
+ }, {
396
+ data: {
397
+ keys: string[];
398
+ };
399
+ ok: true;
400
+ }>, z.ZodObject<{
401
+ ok: z.ZodLiteral<false>;
402
+ error: z.ZodTypeAny;
403
+ }, "strip", z.ZodTypeAny, {
404
+ ok: false;
405
+ error?: any;
406
+ }, {
407
+ ok: false;
408
+ error?: any;
409
+ }>]>;
410
+ type KVListResultType = z.infer<typeof KVListResultSchema>;
411
+ /**
412
+ * Schema for service request event.
413
+ */
414
+ declare const ServiceRequestEventSchema: z.ZodObject<{
415
+ service: z.ZodString;
416
+ action: z.ZodString;
417
+ key: z.ZodOptional<z.ZodString>;
418
+ timestamp: z.ZodNumber;
419
+ }, "strip", z.ZodTypeAny, {
420
+ service: string;
421
+ action: string;
422
+ timestamp: number;
423
+ key?: string | undefined;
424
+ }, {
425
+ service: string;
426
+ action: string;
427
+ timestamp: number;
428
+ key?: string | undefined;
429
+ }>;
430
+ type ServiceRequestEventType = z.infer<typeof ServiceRequestEventSchema>;
431
+ /**
432
+ * Schema for service response event.
433
+ */
434
+ declare const ServiceResponseEventSchema: z.ZodObject<{
435
+ service: z.ZodString;
436
+ action: z.ZodString;
437
+ ok: z.ZodBoolean;
438
+ duration: z.ZodNumber;
439
+ status: z.ZodOptional<z.ZodNumber>;
440
+ }, "strip", z.ZodTypeAny, {
441
+ service: string;
442
+ ok: boolean;
443
+ action: string;
444
+ duration: number;
445
+ status?: number | undefined;
446
+ }, {
447
+ service: string;
448
+ ok: boolean;
449
+ action: string;
450
+ duration: number;
451
+ status?: number | undefined;
452
+ }>;
453
+ type ServiceResponseEventType = z.infer<typeof ServiceResponseEventSchema>;
454
+ /**
455
+ * Schema for service error event.
456
+ */
457
+ declare const ServiceErrorEventSchema: z.ZodObject<{
458
+ service: z.ZodString;
459
+ error: z.ZodObject<{
460
+ /** Error code for programmatic handling (e.g., 'KV_NOT_FOUND', 'AUTH_EXPIRED') */
461
+ code: z.ZodString;
462
+ /** Human-readable error message */
463
+ message: z.ZodString;
464
+ /** Service that produced the error (e.g., 'kv', 'sql') */
465
+ service: z.ZodString;
466
+ /** Original error if this wraps another error - not validated since Error is a class */
467
+ cause: z.ZodOptional<z.ZodUnknown>;
468
+ /** Additional metadata about the error - passthrough allows any object properties */
469
+ meta: z.ZodOptional<z.ZodObject<{}, "passthrough", z.ZodTypeAny, z.objectOutputType<{}, z.ZodTypeAny, "passthrough">, z.objectInputType<{}, z.ZodTypeAny, "passthrough">>>;
470
+ }, "strip", z.ZodTypeAny, {
471
+ code: string;
472
+ message: string;
473
+ service: string;
474
+ cause?: unknown;
475
+ meta?: z.objectOutputType<{}, z.ZodTypeAny, "passthrough"> | undefined;
476
+ }, {
477
+ code: string;
478
+ message: string;
479
+ service: string;
480
+ cause?: unknown;
481
+ meta?: z.objectInputType<{}, z.ZodTypeAny, "passthrough"> | undefined;
482
+ }>;
483
+ }, "strip", z.ZodTypeAny, {
484
+ error: {
485
+ code: string;
486
+ message: string;
487
+ service: string;
488
+ cause?: unknown;
489
+ meta?: z.objectOutputType<{}, z.ZodTypeAny, "passthrough"> | undefined;
490
+ };
491
+ service: string;
492
+ }, {
493
+ error: {
494
+ code: string;
495
+ message: string;
496
+ service: string;
497
+ cause?: unknown;
498
+ meta?: z.objectInputType<{}, z.ZodTypeAny, "passthrough"> | undefined;
499
+ };
500
+ service: string;
501
+ }>;
502
+ type ServiceErrorEventType = z.infer<typeof ServiceErrorEventSchema>;
503
+ /**
504
+ * Schema for service retry event.
505
+ */
506
+ declare const ServiceRetryEventSchema: z.ZodObject<{
507
+ service: z.ZodString;
508
+ attempt: z.ZodNumber;
509
+ maxAttempts: z.ZodNumber;
510
+ error: z.ZodObject<{
511
+ /** Error code for programmatic handling (e.g., 'KV_NOT_FOUND', 'AUTH_EXPIRED') */
512
+ code: z.ZodString;
513
+ /** Human-readable error message */
514
+ message: z.ZodString;
515
+ /** Service that produced the error (e.g., 'kv', 'sql') */
516
+ service: z.ZodString;
517
+ /** Original error if this wraps another error - not validated since Error is a class */
518
+ cause: z.ZodOptional<z.ZodUnknown>;
519
+ /** Additional metadata about the error - passthrough allows any object properties */
520
+ meta: z.ZodOptional<z.ZodObject<{}, "passthrough", z.ZodTypeAny, z.objectOutputType<{}, z.ZodTypeAny, "passthrough">, z.objectInputType<{}, z.ZodTypeAny, "passthrough">>>;
521
+ }, "strip", z.ZodTypeAny, {
522
+ code: string;
523
+ message: string;
524
+ service: string;
525
+ cause?: unknown;
526
+ meta?: z.objectOutputType<{}, z.ZodTypeAny, "passthrough"> | undefined;
527
+ }, {
528
+ code: string;
529
+ message: string;
530
+ service: string;
531
+ cause?: unknown;
532
+ meta?: z.objectInputType<{}, z.ZodTypeAny, "passthrough"> | undefined;
533
+ }>;
534
+ }, "strip", z.ZodTypeAny, {
535
+ error: {
536
+ code: string;
537
+ message: string;
538
+ service: string;
539
+ cause?: unknown;
540
+ meta?: z.objectOutputType<{}, z.ZodTypeAny, "passthrough"> | undefined;
541
+ };
542
+ service: string;
543
+ attempt: number;
544
+ maxAttempts: number;
545
+ }, {
546
+ error: {
547
+ code: string;
548
+ message: string;
549
+ service: string;
550
+ cause?: unknown;
551
+ meta?: z.objectInputType<{}, z.ZodTypeAny, "passthrough"> | undefined;
552
+ };
553
+ service: string;
554
+ attempt: number;
555
+ maxAttempts: number;
556
+ }>;
557
+ type ServiceRetryEventType = z.infer<typeof ServiceRetryEventSchema>;
558
+ /**
559
+ * Schema for retry policy configuration.
560
+ */
561
+ declare const RetryPolicySchema: z.ZodObject<{
562
+ /** Maximum number of attempts (including initial) */
563
+ maxAttempts: z.ZodNumber;
564
+ /** Backoff strategy between retries */
565
+ backoff: z.ZodEnum<["none", "linear", "exponential"]>;
566
+ /** Base delay in milliseconds for backoff calculation */
567
+ baseDelayMs: z.ZodNumber;
568
+ /** Maximum delay in milliseconds between retries */
569
+ maxDelayMs: z.ZodNumber;
570
+ /** Error codes that should trigger a retry */
571
+ retryableErrors: z.ZodArray<z.ZodString, "many">;
572
+ }, "strip", z.ZodTypeAny, {
573
+ maxAttempts: number;
574
+ backoff: "none" | "linear" | "exponential";
575
+ baseDelayMs: number;
576
+ maxDelayMs: number;
577
+ retryableErrors: string[];
578
+ }, {
579
+ maxAttempts: number;
580
+ backoff: "none" | "linear" | "exponential";
581
+ baseDelayMs: number;
582
+ maxDelayMs: number;
583
+ retryableErrors: string[];
584
+ }>;
585
+ type RetryPolicyType = z.infer<typeof RetryPolicySchema>;
586
+ /**
587
+ * Schema for service session data required for authenticated operations.
588
+ */
589
+ declare const ServiceSessionSchema: z.ZodObject<{
590
+ /** The delegation header containing the UCAN */
591
+ delegationHeader: z.ZodObject<{
592
+ Authorization: z.ZodString;
593
+ }, "strip", z.ZodTypeAny, {
594
+ Authorization: string;
595
+ }, {
596
+ Authorization: string;
597
+ }>;
598
+ /** The delegation CID */
599
+ delegationCid: z.ZodString;
600
+ /** The space ID for this session */
601
+ spaceId: z.ZodString;
602
+ /** The verification method DID */
603
+ verificationMethod: z.ZodString;
604
+ /** The session key JWK (required for invoke) */
605
+ jwk: z.ZodObject<{}, "passthrough", z.ZodTypeAny, z.objectOutputType<{}, z.ZodTypeAny, "passthrough">, z.objectInputType<{}, z.ZodTypeAny, "passthrough">>;
606
+ }, "strip", z.ZodTypeAny, {
607
+ delegationHeader: {
608
+ Authorization: string;
609
+ };
610
+ delegationCid: string;
611
+ spaceId: string;
612
+ verificationMethod: string;
613
+ jwk: {} & {
614
+ [k: string]: unknown;
615
+ };
616
+ }, {
617
+ delegationHeader: {
618
+ Authorization: string;
619
+ };
620
+ delegationCid: string;
621
+ spaceId: string;
622
+ verificationMethod: string;
623
+ jwk: {} & {
624
+ [k: string]: unknown;
625
+ };
626
+ }>;
627
+ type ServiceSessionType = z.infer<typeof ServiceSessionSchema>;
628
+ /**
629
+ * Validate service error against the schema.
630
+ *
631
+ * @param data - Unknown data to validate
632
+ * @returns Result with validated data or validation error
633
+ */
634
+ declare function validateServiceError(data: unknown): {
635
+ ok: true;
636
+ data: ServiceErrorType;
637
+ } | {
638
+ ok: false;
639
+ error: ValidationError;
640
+ };
641
+ /**
642
+ * Validate KV list response against the schema.
643
+ *
644
+ * @param data - Unknown data to validate
645
+ * @returns Result with validated data or validation error
646
+ */
647
+ declare function validateKVListResponse(data: unknown): {
648
+ ok: true;
649
+ data: KVListResponseType;
650
+ } | {
651
+ ok: false;
652
+ error: ValidationError;
653
+ };
654
+ /**
655
+ * Validate KV response headers against the schema.
656
+ *
657
+ * @param data - Unknown data to validate
658
+ * @returns Result with validated data or validation error
659
+ */
660
+ declare function validateKVResponseHeaders(data: unknown): {
661
+ ok: true;
662
+ data: KVResponseHeadersType;
663
+ } | {
664
+ ok: false;
665
+ error: ValidationError;
666
+ };
667
+ /**
668
+ * Validate service session against the schema.
669
+ *
670
+ * @param data - Unknown data to validate
671
+ * @returns Result with validated data or validation error
672
+ */
673
+ declare function validateServiceSession(data: unknown): {
674
+ ok: true;
675
+ data: ServiceSessionType;
676
+ } | {
677
+ ok: false;
678
+ error: ValidationError;
679
+ };
680
+ /**
681
+ * Validate retry policy against the schema.
682
+ *
683
+ * @param data - Unknown data to validate
684
+ * @returns Result with validated data or validation error
685
+ */
686
+ declare function validateRetryPolicy(data: unknown): {
687
+ ok: true;
688
+ data: RetryPolicyType;
689
+ } | {
690
+ ok: false;
691
+ error: ValidationError;
692
+ };
693
+ /**
694
+ * Validate service request event against the schema.
695
+ *
696
+ * @param data - Unknown data to validate
697
+ * @returns Result with validated data or validation error
698
+ */
699
+ declare function validateServiceRequestEvent(data: unknown): {
700
+ ok: true;
701
+ data: ServiceRequestEventType;
702
+ } | {
703
+ ok: false;
704
+ error: ValidationError;
705
+ };
706
+ /**
707
+ * Validate service response event against the schema.
708
+ *
709
+ * @param data - Unknown data to validate
710
+ * @returns Result with validated data or validation error
711
+ */
712
+ declare function validateServiceResponseEvent(data: unknown): {
713
+ ok: true;
714
+ data: ServiceResponseEventType;
715
+ } | {
716
+ ok: false;
717
+ error: ValidationError;
718
+ };
719
+
720
+ /**
721
+ * ServiceContext implementation for TinyCloud SDK Services
7
722
  * @module @tinycloud/sdk-services
723
+ */
724
+
725
+ /**
726
+ * Event handler type for telemetry events.
727
+ */
728
+ type EventHandler = (data: unknown) => void;
729
+ /**
730
+ * Configuration options for ServiceContext.
731
+ */
732
+ interface ServiceContextConfig {
733
+ /** Function to invoke WASM operations */
734
+ invoke: InvokeFunction;
735
+ /** Function to make HTTP requests (defaults to globalThis.fetch) */
736
+ fetch?: FetchFunction;
737
+ /** List of TinyCloud host URLs */
738
+ hosts: string[];
739
+ /** Initial session (optional) */
740
+ session?: ServiceSession | null;
741
+ /** Retry policy configuration */
742
+ retryPolicy?: Partial<RetryPolicy>;
743
+ }
744
+ /**
745
+ * ServiceContext provides platform dependencies and cross-service access to services.
746
+ * This is the primary interface services use to interact with the SDK runtime.
8
747
  *
9
748
  * @example
10
749
  * ```typescript
11
- * import {
12
- * ServiceContext,
13
- * BaseService,
14
- * Result,
15
- * ErrorCodes,
16
- * } from '@tinycloud/sdk-services';
17
- *
18
- * // Create a context
19
750
  * const context = new ServiceContext({
20
751
  * invoke: wasmInvoke,
21
752
  * hosts: ['https://node.tinycloud.xyz'],
753
+ * retryPolicy: { maxAttempts: 5 },
22
754
  * });
23
755
  *
24
- * // Create and register a service
25
- * const kv = new KVService({ prefix: 'myapp' });
26
- * context.registerService('kv', kv);
27
- * kv.initialize(context);
756
+ * // Register a service
757
+ * const kvService = new KVService({});
758
+ * context.registerService('kv', kvService);
759
+ * kvService.initialize(context);
28
760
  *
29
- * // Use the service
30
- * const result = await kv.get('key');
31
- * if (result.ok) {
32
- * console.log(result.data);
761
+ * // Update session when user signs in
762
+ * context.setSession(userSession);
763
+ * ```
764
+ */
765
+ declare class ServiceContext implements IServiceContext {
766
+ private _session;
767
+ private _services;
768
+ private _eventHandlers;
769
+ private _abortController;
770
+ private readonly _invoke;
771
+ private readonly _fetch;
772
+ private readonly _hosts;
773
+ private readonly _retryPolicy;
774
+ constructor(config: ServiceContextConfig);
775
+ /**
776
+ * Get the current session.
777
+ */
778
+ get session(): ServiceSession | null;
779
+ /**
780
+ * Check if the context has an authenticated session.
781
+ */
782
+ get isAuthenticated(): boolean;
783
+ /**
784
+ * Update the session and notify all registered services.
785
+ *
786
+ * @param session - New session or null to clear
787
+ */
788
+ setSession(session: ServiceSession | null): void;
789
+ /**
790
+ * Get the invoke function for WASM operations.
791
+ */
792
+ get invoke(): InvokeFunction;
793
+ /**
794
+ * Get the fetch function for HTTP requests.
795
+ */
796
+ get fetch(): FetchFunction;
797
+ /**
798
+ * Get the list of TinyCloud host URLs.
799
+ */
800
+ get hosts(): string[];
801
+ /**
802
+ * Register a service with the context.
803
+ *
804
+ * @param name - Service name (e.g., 'kv')
805
+ * @param service - Service instance
806
+ */
807
+ registerService(name: string, service: IService): void;
808
+ /**
809
+ * Unregister a service from the context.
810
+ *
811
+ * @param name - Service name to remove
812
+ */
813
+ unregisterService(name: string): void;
814
+ /**
815
+ * Get a registered service by name.
816
+ *
817
+ * @param name - Service name
818
+ * @returns The service instance or undefined if not registered
819
+ */
820
+ getService<T extends IService>(name: string): T | undefined;
821
+ /**
822
+ * Emit a telemetry event.
823
+ *
824
+ * @param event - Event name
825
+ * @param data - Event data
826
+ */
827
+ emit(event: string, data: unknown): void;
828
+ /**
829
+ * Subscribe to telemetry events.
830
+ *
831
+ * @param event - Event name to subscribe to
832
+ * @param handler - Handler function
833
+ * @returns Unsubscribe function
834
+ */
835
+ on(event: string, handler: EventHandler): () => void;
836
+ /**
837
+ * Remove all event handlers for an event.
838
+ *
839
+ * @param event - Event name (if omitted, clears all events)
840
+ */
841
+ clearEventHandlers(event?: string): void;
842
+ /**
843
+ * Get the abort signal for cancelling operations.
844
+ */
845
+ get abortSignal(): AbortSignal;
846
+ /**
847
+ * Abort all pending operations and notify services.
848
+ * Creates a new AbortController for future operations.
849
+ */
850
+ abort(): void;
851
+ /**
852
+ * Sign out - abort operations and clear session.
853
+ */
854
+ signOut(): void;
855
+ /**
856
+ * Get the retry policy configuration.
857
+ */
858
+ get retryPolicy(): RetryPolicy;
859
+ }
860
+
861
+ /**
862
+ * Create a service error for authentication required.
863
+ */
864
+ declare function authRequiredError(service: string): ServiceError;
865
+ /**
866
+ * Create a service error for expired authentication.
867
+ */
868
+ declare function authExpiredError(service: string): ServiceError;
869
+ /**
870
+ * Create a service error for network issues.
871
+ */
872
+ declare function networkError(service: string, message: string, cause?: Error): ServiceError;
873
+ /**
874
+ * Create a service error for timeouts.
875
+ */
876
+ declare function timeoutError(service: string): ServiceError;
877
+ /**
878
+ * Create a service error for aborted requests.
879
+ */
880
+ declare function abortedError(service: string): ServiceError;
881
+ /**
882
+ * Create a service error for not found resources.
883
+ */
884
+ declare function notFoundError(service: string, resource: string): ServiceError;
885
+ /**
886
+ * Create a service error for permission denied.
887
+ */
888
+ declare function permissionDeniedError(service: string, action: string): ServiceError;
889
+ /**
890
+ * Parse the server's "Unauthorized Action: {resource} / {ability}" pattern.
891
+ */
892
+ declare function parseAuthError(responseText: string): {
893
+ resource?: string;
894
+ action?: string;
895
+ };
896
+ /**
897
+ * Create a service error for unauthorized action (missing capability).
898
+ */
899
+ declare function authUnauthorizedError(service: string, message: string, meta?: Record<string, unknown>): ServiceError;
900
+ /**
901
+ * Create a service error for storage quota exceeded (402 Payment Required).
902
+ */
903
+ declare function storageQuotaExceededError(service: string, message: string, meta?: Record<string, unknown>): ServiceError;
904
+ /**
905
+ * Create a service error for storage limit reached (413 Payload Too Large).
906
+ */
907
+ declare function storageLimitReachedError(service: string, message: string, meta?: Record<string, unknown>): ServiceError;
908
+ /**
909
+ * Wrap an unknown error in a ServiceError.
910
+ */
911
+ declare function wrapError(service: string, error: unknown, defaultCode?: string): ServiceError;
912
+ /**
913
+ * Create an error Result from a ServiceError.
914
+ */
915
+ declare function errorResult(error: ServiceError): Result<never, ServiceError>;
916
+
917
+ /**
918
+ * Base Service Types
919
+ *
920
+ * Types specific to the base service infrastructure.
921
+ */
922
+
923
+ /**
924
+ * Service constructor type for registration.
925
+ * Used by the SDK to instantiate services.
926
+ */
927
+ interface ServiceConstructor<TConfig = Record<string, unknown>, TService extends IService = IService> {
928
+ /** Service identifier used for registration */
929
+ readonly serviceName: string;
930
+ /** Create a new instance of the service */
931
+ new (config?: TConfig): TService;
932
+ }
933
+ /**
934
+ * Service registration entry.
935
+ */
936
+ interface ServiceRegistration {
937
+ /** The service class constructor */
938
+ constructor: ServiceConstructor;
939
+ /** Configuration for this service instance */
940
+ config?: Record<string, unknown>;
941
+ }
942
+ /**
943
+ * Options for base service operations.
944
+ */
945
+ interface BaseServiceOptions {
946
+ /** Override the default timeout for this operation */
947
+ timeout?: number;
948
+ /** Custom abort signal for this operation */
949
+ signal?: AbortSignal;
950
+ }
951
+
952
+ /**
953
+ * DuckDB Service Types
954
+ *
955
+ * Type definitions for the DuckDB service operations.
956
+ */
957
+ /**
958
+ * Configuration for DuckDbService.
959
+ */
960
+ interface DuckDbServiceConfig {
961
+ /**
962
+ * Default database name.
963
+ * If not set, operations default to "default".
964
+ */
965
+ defaultDatabase?: string;
966
+ /**
967
+ * Default timeout in milliseconds for DuckDB operations.
968
+ */
969
+ timeout?: number;
970
+ /** Allow additional config properties */
971
+ [key: string]: unknown;
972
+ }
973
+ /**
974
+ * Options for DuckDB query operations.
975
+ */
976
+ interface DuckDbQueryOptions {
977
+ /**
978
+ * Custom abort signal for this operation.
979
+ */
980
+ signal?: AbortSignal;
981
+ }
982
+ /**
983
+ * Options for DuckDB execute operations.
984
+ */
985
+ interface DuckDbExecuteOptions {
986
+ /**
987
+ * Schema initialization statements (CREATE TABLE IF NOT EXISTS ...).
988
+ * Executed before the main statement on first write.
989
+ */
990
+ schema?: string[];
991
+ /**
992
+ * Custom abort signal for this operation.
993
+ */
994
+ signal?: AbortSignal;
995
+ }
996
+ /**
997
+ * Options for DuckDB batch operations.
998
+ */
999
+ interface DuckDbBatchOptions {
1000
+ /**
1001
+ * Whether to run statements in a transaction.
1002
+ */
1003
+ transactional?: boolean;
1004
+ /**
1005
+ * Custom abort signal for this operation.
1006
+ */
1007
+ signal?: AbortSignal;
1008
+ }
1009
+ /**
1010
+ * Options for DuckDB operations that only need an abort signal.
1011
+ */
1012
+ interface DuckDbOptions {
1013
+ /**
1014
+ * Custom abort signal for this operation.
1015
+ */
1016
+ signal?: AbortSignal;
1017
+ }
1018
+ /**
1019
+ * A DuckDB value: null, boolean, number, string, binary, array, or object.
1020
+ */
1021
+ type DuckDbValue = null | boolean | number | string | Uint8Array | DuckDbValueArray | DuckDbValueRecord;
1022
+ /** Array of DuckDB values (workaround for circular type alias). */
1023
+ interface DuckDbValueArray extends Array<DuckDbValue> {
1024
+ }
1025
+ /** Record of DuckDB values (workaround for circular type alias). */
1026
+ interface DuckDbValueRecord {
1027
+ [key: string]: DuckDbValue;
1028
+ }
1029
+ /**
1030
+ * A DuckDB statement with optional parameters.
1031
+ */
1032
+ interface DuckDbStatement {
1033
+ sql: string;
1034
+ params?: DuckDbValue[];
1035
+ }
1036
+ /**
1037
+ * Response from DuckDB query operations.
1038
+ */
1039
+ interface QueryResponse<T = Record<string, unknown>> {
1040
+ columns: string[];
1041
+ rows: T[][];
1042
+ rowCount: number;
1043
+ }
1044
+ /**
1045
+ * Response from DuckDB execute operations.
1046
+ */
1047
+ interface ExecuteResponse {
1048
+ changes: number;
1049
+ }
1050
+ /**
1051
+ * Response from DuckDB batch operations.
1052
+ */
1053
+ interface BatchResponse {
1054
+ results: ExecuteResponse[];
1055
+ }
1056
+ /**
1057
+ * Schema information for a DuckDB database.
1058
+ */
1059
+ interface SchemaInfo {
1060
+ tables: TableInfo[];
1061
+ views: ViewInfo[];
1062
+ }
1063
+ /**
1064
+ * Information about a table.
1065
+ */
1066
+ interface TableInfo {
1067
+ name: string;
1068
+ columns: ColumnInfo[];
1069
+ }
1070
+ /**
1071
+ * Information about a column.
1072
+ */
1073
+ interface ColumnInfo {
1074
+ name: string;
1075
+ type: string;
1076
+ nullable: boolean;
1077
+ }
1078
+ /**
1079
+ * Information about a view.
1080
+ */
1081
+ interface ViewInfo {
1082
+ name: string;
1083
+ sql: string;
1084
+ }
1085
+ /**
1086
+ * DuckDB service action types.
1087
+ */
1088
+ declare const DuckDbAction: {
1089
+ readonly READ: "tinycloud.duckdb/read";
1090
+ readonly WRITE: "tinycloud.duckdb/write";
1091
+ readonly ADMIN: "tinycloud.duckdb/admin";
1092
+ readonly DESCRIBE: "tinycloud.duckdb/describe";
1093
+ readonly EXPORT: "tinycloud.duckdb/export";
1094
+ readonly IMPORT: "tinycloud.duckdb/import";
1095
+ readonly EXECUTE: "tinycloud.duckdb/execute";
1096
+ readonly ALL: "tinycloud.duckdb/*";
1097
+ };
1098
+ type DuckDbActionType = (typeof DuckDbAction)[keyof typeof DuckDbAction];
1099
+
1100
+ /**
1101
+ * IDuckDbService - Interface for DuckDB service.
1102
+ *
1103
+ * Platform-agnostic interface for DuckDB database operations.
1104
+ */
1105
+
1106
+ /**
1107
+ * Database handle interface for operations on a specific named database.
1108
+ */
1109
+ interface IDuckDbDatabaseHandle {
1110
+ /** The database name */
1111
+ readonly name: string;
1112
+ /**
1113
+ * Execute a DuckDB query and return rows as JSON.
1114
+ */
1115
+ query<T = Record<string, unknown>>(sql: string, params?: DuckDbValue[], options?: DuckDbQueryOptions): Promise<Result<QueryResponse<T>>>;
1116
+ /**
1117
+ * Execute a DuckDB query and return results as Arrow IPC stream.
1118
+ */
1119
+ queryArrow(sql: string, params?: DuckDbValue[], options?: DuckDbQueryOptions): Promise<Result<ArrayBuffer>>;
1120
+ /**
1121
+ * Execute a DuckDB statement and return change count.
1122
+ */
1123
+ execute(sql: string, params?: DuckDbValue[], options?: DuckDbExecuteOptions): Promise<Result<ExecuteResponse>>;
1124
+ /**
1125
+ * Execute multiple statements in a batch.
1126
+ */
1127
+ batch(statements: DuckDbStatement[], options?: DuckDbBatchOptions): Promise<Result<BatchResponse>>;
1128
+ /**
1129
+ * Execute a named prepared statement from delegation caveats.
1130
+ */
1131
+ executeStatement(name: string, params?: DuckDbValue[], options?: DuckDbQueryOptions): Promise<Result<QueryResponse | ExecuteResponse>>;
1132
+ /**
1133
+ * Describe the database schema.
1134
+ */
1135
+ describe(options?: DuckDbOptions): Promise<Result<SchemaInfo>>;
1136
+ /**
1137
+ * Export the database as a Blob.
1138
+ */
1139
+ export(options?: DuckDbOptions): Promise<Result<Blob>>;
1140
+ /**
1141
+ * Import a binary DuckDB database file.
1142
+ */
1143
+ import(data: Uint8Array, options?: DuckDbOptions): Promise<Result<void>>;
1144
+ }
1145
+ /**
1146
+ * DuckDB service interface.
1147
+ *
1148
+ * Provides DuckDB database operations with:
1149
+ * - Result type pattern (no throwing)
1150
+ * - Named database handles
1151
+ * - Configurable timeouts
1152
+ * - Abort signal support
1153
+ * - Arrow format support via queryArrow()
1154
+ */
1155
+ interface IDuckDbService extends IService {
1156
+ /**
1157
+ * Get a handle to a named database.
1158
+ * @param name - Database name (defaults to "default")
1159
+ */
1160
+ db(name?: string): IDuckDbDatabaseHandle;
1161
+ /**
1162
+ * Shortcut: query the default database (JSON format).
1163
+ */
1164
+ query<T = Record<string, unknown>>(sql: string, params?: DuckDbValue[], options?: DuckDbQueryOptions): Promise<Result<QueryResponse<T>>>;
1165
+ /**
1166
+ * Shortcut: query the default database (Arrow IPC format).
1167
+ */
1168
+ queryArrow(sql: string, params?: DuckDbValue[], options?: DuckDbQueryOptions): Promise<Result<ArrayBuffer>>;
1169
+ /**
1170
+ * Shortcut: execute on the default database.
1171
+ */
1172
+ execute(sql: string, params?: DuckDbValue[], options?: DuckDbExecuteOptions): Promise<Result<ExecuteResponse>>;
1173
+ /**
1174
+ * Shortcut: batch on the default database.
1175
+ */
1176
+ batch(statements: DuckDbStatement[], options?: DuckDbBatchOptions): Promise<Result<BatchResponse>>;
1177
+ /**
1178
+ * Service configuration.
1179
+ */
1180
+ readonly config: DuckDbServiceConfig;
1181
+ }
1182
+
1183
+ /**
1184
+ * DuckDbService - DuckDB database service implementation.
1185
+ *
1186
+ * Platform-agnostic DuckDB service that works with both web-sdk and node-sdk.
1187
+ * Uses dependency injection via IServiceContext for platform dependencies.
1188
+ */
1189
+
1190
+ declare class DuckDbService extends BaseService implements IDuckDbService {
1191
+ static readonly serviceName = "duckdb";
1192
+ protected _config: DuckDbServiceConfig;
1193
+ constructor(config?: DuckDbServiceConfig);
1194
+ get config(): DuckDbServiceConfig;
1195
+ private get defaultDbName();
1196
+ private get host();
1197
+ /**
1198
+ * Get a handle to a named database.
1199
+ */
1200
+ db(name?: string): IDuckDbDatabaseHandle;
1201
+ /**
1202
+ * Shortcut: query the default database (JSON format).
1203
+ */
1204
+ query<T = Record<string, unknown>>(sql: string, params?: DuckDbValue[], options?: DuckDbQueryOptions): Promise<Result<QueryResponse<T>>>;
1205
+ /**
1206
+ * Shortcut: query the default database (Arrow IPC format).
1207
+ */
1208
+ queryArrow(sql: string, params?: DuckDbValue[], options?: DuckDbQueryOptions): Promise<Result<ArrayBuffer>>;
1209
+ /**
1210
+ * Shortcut: execute on the default database.
1211
+ */
1212
+ execute(sql: string, params?: DuckDbValue[], options?: DuckDbExecuteOptions): Promise<Result<ExecuteResponse>>;
1213
+ /**
1214
+ * Shortcut: batch on the default database.
1215
+ */
1216
+ batch(statements: DuckDbStatement[], options?: DuckDbBatchOptions): Promise<Result<BatchResponse>>;
1217
+ queryOnDb<T = Record<string, unknown>>(dbName: string, sql: string, params?: DuckDbValue[], options?: DuckDbQueryOptions): Promise<Result<QueryResponse<T>>>;
1218
+ queryArrowOnDb(dbName: string, sql: string, params?: DuckDbValue[], options?: DuckDbQueryOptions): Promise<Result<ArrayBuffer>>;
1219
+ executeOnDb(dbName: string, sql: string, params?: DuckDbValue[], options?: DuckDbExecuteOptions): Promise<Result<ExecuteResponse>>;
1220
+ batchOnDb(dbName: string, statements: DuckDbStatement[], options?: DuckDbBatchOptions): Promise<Result<BatchResponse>>;
1221
+ executeStatementOnDb(dbName: string, name: string, params?: DuckDbValue[], options?: DuckDbQueryOptions): Promise<Result<QueryResponse | ExecuteResponse>>;
1222
+ describeDb(dbName: string, options?: DuckDbOptions): Promise<Result<SchemaInfo>>;
1223
+ exportOnDb(dbName: string, options?: DuckDbOptions): Promise<Result<Blob>>;
1224
+ importOnDb(dbName: string, data: Uint8Array, options?: DuckDbOptions): Promise<Result<void>>;
1225
+ private invokeDuckDb;
1226
+ private handleErrorResponse;
1227
+ private mapHttpStatusToErrorCode;
1228
+ }
1229
+
1230
+ /**
1231
+ * DuckDbDatabaseHandle - Handle for operations on a specific named database.
1232
+ *
1233
+ * Delegates all operations to the parent DuckDbService with the database name.
1234
+ */
1235
+
1236
+ declare class DuckDbDatabaseHandle implements IDuckDbDatabaseHandle {
1237
+ private service;
1238
+ readonly name: string;
1239
+ constructor(service: DuckDbService, name: string);
1240
+ query<T = Record<string, unknown>>(sql: string, params?: DuckDbValue[], options?: DuckDbQueryOptions): Promise<Result<QueryResponse<T>>>;
1241
+ queryArrow(sql: string, params?: DuckDbValue[], options?: DuckDbQueryOptions): Promise<Result<ArrayBuffer>>;
1242
+ execute(sql: string, params?: DuckDbValue[], options?: DuckDbExecuteOptions): Promise<Result<ExecuteResponse>>;
1243
+ batch(statements: DuckDbStatement[], options?: DuckDbBatchOptions): Promise<Result<BatchResponse>>;
1244
+ executeStatement(name: string, params?: DuckDbValue[], options?: DuckDbQueryOptions): Promise<Result<QueryResponse | ExecuteResponse>>;
1245
+ describe(options?: DuckDbOptions): Promise<Result<SchemaInfo>>;
1246
+ export(options?: DuckDbOptions): Promise<Result<Blob>>;
1247
+ import(data: Uint8Array, options?: DuckDbOptions): Promise<Result<void>>;
1248
+ }
1249
+
1250
+ interface QuotaConfig {
1251
+ /** Called when a storage quota error is detected (402/413) */
1252
+ onUpgradeRequired?: (info: StorageQuotaInfo) => void;
1253
+ }
1254
+ interface QuotaStatus {
1255
+ /** Storage limit in bytes for this space */
1256
+ limitBytes: number;
1257
+ /** Storage used in bytes for this space */
1258
+ usedBytes?: number;
1259
+ /** Remaining storage in bytes */
1260
+ remainingBytes?: number;
1261
+ }
1262
+ declare class TinyCloudQuota {
1263
+ private config;
1264
+ private quotaUrl;
1265
+ constructor(config?: QuotaConfig);
1266
+ /** Set the quota URL discovered from the /info endpoint */
1267
+ setQuotaUrl(url: string | null): void;
1268
+ /** Whether a quota service is available */
1269
+ get available(): boolean;
1270
+ /** Query quota status for a space from the quota URL */
1271
+ getQuota(spaceId: string): Promise<QuotaStatus | null>;
1272
+ /** Trigger the upgrade callback when a quota error is encountered */
1273
+ handleQuotaError(info: StorageQuotaInfo): void;
1274
+ }
1275
+
1276
+ /**
1277
+ * Data Vault Service Types
1278
+ *
1279
+ * Type definitions for the Data Vault (encrypted KV) service operations.
1280
+ */
1281
+ /**
1282
+ * Configuration for DataVaultService.
1283
+ */
1284
+ interface DataVaultConfig {
1285
+ /** Space ID for encrypted data storage */
1286
+ spaceId: string;
1287
+ /** Key rotation policy */
1288
+ keyRotation?: "per-write" | "per-key";
1289
+ }
1290
+ /**
1291
+ * Options for vault put operations.
1292
+ */
1293
+ interface VaultPutOptions {
1294
+ /** Custom metadata tags appended to the envelope */
1295
+ metadata?: Record<string, string>;
1296
+ /** Content type hint for deserialization (default: auto-detect) */
1297
+ contentType?: string;
1298
+ /** Custom serializer (default: JSON.stringify for objects) */
1299
+ serialize?: (value: unknown) => Uint8Array;
1300
+ }
1301
+ /**
1302
+ * Options for vault get operations.
1303
+ */
1304
+ interface VaultGetOptions<T = unknown> {
1305
+ /** Custom deserializer (default: JSON.parse if content-type is JSON) */
1306
+ deserialize?: (data: Uint8Array) => T;
1307
+ /** Return raw decrypted bytes without deserialization */
1308
+ raw?: boolean;
1309
+ /** Delegated KV service for reading from the grantor's space (used by getShared) */
1310
+ kv?: {
1311
+ get<V>(key: string, options?: {
1312
+ raw?: boolean;
1313
+ }): Promise<{
1314
+ ok: boolean;
1315
+ data?: {
1316
+ data: V;
1317
+ };
1318
+ error?: {
1319
+ message: string;
1320
+ };
1321
+ }>;
1322
+ };
1323
+ }
1324
+ /**
1325
+ * Options for vault list operations.
1326
+ */
1327
+ interface VaultListOptions {
1328
+ /** Prefix filter for key names */
1329
+ prefix?: string;
1330
+ /** Remove prefix from returned keys */
1331
+ removePrefix?: boolean;
1332
+ }
1333
+ /**
1334
+ * Options for vault grant (sharing) operations.
1335
+ */
1336
+ interface VaultGrantOptions {
1337
+ /** Additional metadata on the grant */
1338
+ metadata?: Record<string, string>;
1339
+ }
1340
+ /**
1341
+ * A decrypted vault entry returned by get operations.
1342
+ *
1343
+ * @template T - Type of the decrypted value
1344
+ */
1345
+ interface VaultEntry<T> {
1346
+ /** Decrypted value */
1347
+ value: T;
1348
+ /** Envelope metadata */
1349
+ metadata: Record<string, string>;
1350
+ /** Key ID used for encryption */
1351
+ keyId: string;
1352
+ }
1353
+ /**
1354
+ * Structured error codes for vault operations.
1355
+ */
1356
+ /**
1357
+ * Input types for creating vault errors (service field added automatically).
1358
+ */
1359
+ type VaultErrorInput = {
1360
+ code: "DECRYPTION_FAILED";
1361
+ message?: string;
1362
+ cause?: Error;
1363
+ } | {
1364
+ code: "KEY_NOT_FOUND";
1365
+ key: string;
1366
+ message?: string;
1367
+ } | {
1368
+ code: "INTEGRITY_ERROR";
1369
+ message?: string;
1370
+ cause?: Error;
1371
+ } | {
1372
+ code: "GRANT_NOT_FOUND";
1373
+ grantor: string;
1374
+ key: string;
1375
+ message?: string;
1376
+ } | {
1377
+ code: "VAULT_LOCKED";
1378
+ message?: string;
1379
+ } | {
1380
+ code: "PUBLIC_KEY_NOT_FOUND";
1381
+ did: string;
1382
+ message?: string;
1383
+ } | {
1384
+ code: "STORAGE_ERROR";
1385
+ cause: Error;
1386
+ message?: string;
1387
+ };
1388
+ /**
1389
+ * Vault error with service field (compatible with ServiceError).
1390
+ */
1391
+ type VaultError = VaultErrorInput & {
1392
+ service: "vault";
1393
+ message: string;
1394
+ };
1395
+ /** KV actions the vault needs on the public space for key publishing. */
1396
+ declare const VaultPublicSpaceKVActions: readonly ["tinycloud.kv/get", "tinycloud.kv/put", "tinycloud.kv/metadata"];
1397
+ /** Metadata header keys used in vault envelopes */
1398
+ declare const VaultHeaders: {
1399
+ readonly VERSION: "x-vault-version";
1400
+ readonly CIPHER: "x-vault-cipher";
1401
+ readonly KEY_ID: "x-vault-key-id";
1402
+ readonly CONTENT_TYPE: "x-vault-content-type";
1403
+ readonly KDF: "x-vault-kdf";
1404
+ readonly KEY_ROTATION: "x-vault-key-rotation";
1405
+ readonly GRANT_VERSION: "x-vault-grant-version";
1406
+ readonly GRANTOR: "x-vault-grantor";
1407
+ };
1408
+
1409
+ /**
1410
+ * IDataVaultService - Interface for the Data Vault (encrypted KV) service.
1411
+ *
1412
+ * Platform-agnostic interface for encrypted key-value storage with
1413
+ * client-side encryption, key management, and sharing via grants.
1414
+ */
1415
+
1416
+ /**
1417
+ * Data Vault service interface.
1418
+ *
1419
+ * Provides encrypted key-value storage with:
1420
+ * - Client-side encryption (data is encrypted before leaving the device)
1421
+ * - Result type pattern (no throwing)
1422
+ * - Key management and rotation
1423
+ * - Sharing via grants (re-encrypt to recipient's public key)
1424
+ *
1425
+ * @example
1426
+ * ```typescript
1427
+ * // Unlock the vault (derives encryption keys)
1428
+ * await vault.unlock(signer);
1429
+ *
1430
+ * // Store encrypted data
1431
+ * const result = await vault.put('medical/records', { bloodType: 'O+' });
1432
+ *
1433
+ * // Retrieve and decrypt
1434
+ * const entry = await vault.get<{ bloodType: string }>('medical/records');
1435
+ * if (entry.ok) {
1436
+ * console.log(entry.data.value.bloodType); // 'O+'
33
1437
  * }
1438
+ *
1439
+ * // Share with another user
1440
+ * await vault.grant('medical/records', recipientDID);
1441
+ * ```
1442
+ */
1443
+ interface IDataVaultService extends IService {
1444
+ /**
1445
+ * Unlock the vault. Derives keys from wallet signatures.
1446
+ * Signer is optional when cached signatures exist (browser only).
1447
+ */
1448
+ unlock(signer?: unknown): Promise<Result<void, VaultError>>;
1449
+ /**
1450
+ * Clear the cached vault signature.
1451
+ * @param spaceId - Clear only this space's cache. If omitted, clears all.
1452
+ */
1453
+ clearCache(spaceId?: string): Promise<void>;
1454
+ /** Lock the vault, clearing all key material from memory. */
1455
+ lock(): void;
1456
+ /** Whether the vault is currently unlocked. */
1457
+ readonly isUnlocked: boolean;
1458
+ /**
1459
+ * Encrypt and store a value at the given key.
1460
+ *
1461
+ * @param key - The key to store under
1462
+ * @param value - The value to encrypt and store
1463
+ * @param options - Optional put configuration
1464
+ */
1465
+ put(key: string, value: unknown, options?: VaultPutOptions): Promise<Result<void, VaultError>>;
1466
+ /**
1467
+ * Retrieve and decrypt a value by key.
1468
+ *
1469
+ * @param key - The key to retrieve
1470
+ * @param options - Optional get configuration
1471
+ * @returns Result with the decrypted entry
1472
+ */
1473
+ get<T = unknown>(key: string, options?: VaultGetOptions<T>): Promise<Result<VaultEntry<T>, VaultError>>;
1474
+ /**
1475
+ * Delete an encrypted key.
1476
+ *
1477
+ * @param key - The key to delete
1478
+ */
1479
+ delete(key: string): Promise<Result<void, VaultError>>;
1480
+ /**
1481
+ * List vault keys with optional prefix filtering.
1482
+ *
1483
+ * @param options - Optional list configuration
1484
+ * @returns Result with array of key names
1485
+ */
1486
+ list(options?: VaultListOptions): Promise<Result<string[], VaultError>>;
1487
+ /**
1488
+ * Get envelope metadata for a key without decrypting the value.
1489
+ *
1490
+ * @param key - The key to inspect
1491
+ * @returns Result with metadata headers
1492
+ */
1493
+ head(key: string): Promise<Result<Record<string, string>, VaultError>>;
1494
+ /**
1495
+ * Encrypt and store multiple entries.
1496
+ *
1497
+ * @param entries - Array of key/value pairs with optional per-entry options
1498
+ * @returns Array of results, one per entry
1499
+ */
1500
+ putMany(entries: Array<{
1501
+ key: string;
1502
+ value: unknown;
1503
+ options?: VaultPutOptions;
1504
+ }>): Promise<Result<void, VaultError>[]>;
1505
+ /**
1506
+ * Retrieve and decrypt multiple keys.
1507
+ *
1508
+ * @param keys - Array of keys to retrieve
1509
+ * @param options - Optional get configuration applied to all entries
1510
+ * @returns Array of results, one per key
1511
+ */
1512
+ getMany<T = unknown>(keys: string[], options?: VaultGetOptions<T>): Promise<Result<VaultEntry<T>, VaultError>[]>;
1513
+ /**
1514
+ * Grant access to a vault key for another user.
1515
+ * Re-encrypts the data key to the recipient's public key.
1516
+ *
1517
+ * @deprecated Use reencrypt() instead.
1518
+ * @param key - The key to share
1519
+ * @param recipientDID - The recipient's primary DID (did:pkh:...)
1520
+ * @param options - Optional grant configuration
1521
+ */
1522
+ grant(key: string, recipientDID: string, options?: VaultGrantOptions): Promise<Result<void, VaultError>>;
1523
+ /**
1524
+ * Re-encrypt a vault key for another user (renamed from grant).
1525
+ * Re-encrypts the data key to the recipient's public key.
1526
+ *
1527
+ * @param key - The key to share
1528
+ * @param recipientDID - The recipient's primary DID (did:pkh:...)
1529
+ * @param options - Optional grant configuration
1530
+ */
1531
+ reencrypt(key: string, recipientDID: string, options?: VaultGrantOptions): Promise<Result<void, VaultError>>;
1532
+ /**
1533
+ * Revoke a previously issued grant.
1534
+ *
1535
+ * @param key - The key to revoke access to
1536
+ * @param recipientDID - The recipient whose access to revoke
1537
+ */
1538
+ revoke(key: string, recipientDID: string): Promise<Result<void, VaultError>>;
1539
+ /**
1540
+ * List DIDs that have been granted access to a key.
1541
+ *
1542
+ * @param key - The key to list grants for
1543
+ * @returns Result with array of recipient DIDs
1544
+ */
1545
+ listGrants(key: string): Promise<Result<string[], VaultError>>;
1546
+ /**
1547
+ * Retrieve and decrypt a value shared by another user.
1548
+ *
1549
+ * @param grantorDID - The DID of the user who shared the data
1550
+ * @param key - The key that was shared
1551
+ * @param options - Optional get configuration
1552
+ * @returns Result with the decrypted entry
1553
+ */
1554
+ getShared<T = unknown>(grantorDID: string, key: string, options?: VaultGetOptions<T>): Promise<Result<VaultEntry<T>, VaultError>>;
1555
+ /** The vault's public encryption key (X25519). */
1556
+ readonly publicKey: Uint8Array;
1557
+ /**
1558
+ * Resolve another user's public encryption key from their DID.
1559
+ *
1560
+ * @param did - The DID to resolve
1561
+ * @returns Result with the public key bytes
1562
+ */
1563
+ resolvePublicKey(did: string): Promise<Result<Uint8Array, VaultError>>;
1564
+ }
1565
+
1566
+ /**
1567
+ * DataVaultService - Encrypted key-value storage service implementation.
1568
+ *
1569
+ * Platform-agnostic encrypted KV service that wraps KVService internally.
1570
+ * Uses dependency injection via VaultCrypto for WASM crypto operations
1571
+ * and DataVaultServiceConfig for platform dependencies.
1572
+ *
1573
+ * Architecture:
1574
+ * - Extends BaseService (not KVService)
1575
+ * - Wraps two KV instances: dataKV (prefix "vault/") and keyKV (prefix "keys/")
1576
+ * - Master key and encryption identity live in memory only (cleared on lock)
1577
+ */
1578
+
1579
+ /**
1580
+ * Crypto operations interface - implementations provided by WASM bindings.
1581
+ * Passed via DataVaultServiceConfig to keep the service platform-agnostic.
1582
+ */
1583
+ interface VaultCrypto {
1584
+ encrypt(key: Uint8Array, plaintext: Uint8Array): Uint8Array;
1585
+ decrypt(key: Uint8Array, blob: Uint8Array): Uint8Array;
1586
+ deriveKey(signature: Uint8Array, salt: Uint8Array, info: Uint8Array): Uint8Array;
1587
+ x25519FromSeed(seed: Uint8Array): {
1588
+ publicKey: Uint8Array;
1589
+ privateKey: Uint8Array;
1590
+ };
1591
+ x25519Dh(privateKey: Uint8Array, publicKey: Uint8Array): Uint8Array;
1592
+ randomBytes(length: number): Uint8Array;
1593
+ sha256(data: Uint8Array): Uint8Array;
1594
+ }
1595
+ /**
1596
+ * Extended config used internally by DataVaultService.
1597
+ * Includes crypto operations and TinyCloud instance references.
1598
+ */
1599
+ interface DataVaultServiceConfig extends DataVaultConfig {
1600
+ [key: string]: unknown;
1601
+ /** Crypto operations (WASM bindings) */
1602
+ crypto: VaultCrypto;
1603
+ /** TinyCloud instance for space/kv/delegation operations */
1604
+ tc: {
1605
+ kv: IKVService;
1606
+ ensurePublicSpace(): Promise<Result<void>>;
1607
+ publicKV: IKVService;
1608
+ readPublicSpace<T>(host: string, spaceId: string, key: string): Promise<Result<T>>;
1609
+ makePublicSpaceId(address: string, chainId: number): string;
1610
+ did: string;
1611
+ address: string;
1612
+ chainId: number;
1613
+ hosts: string[];
1614
+ };
1615
+ }
1616
+ /**
1617
+ * Data Vault service implementation.
1618
+ *
1619
+ * Provides encrypted key-value storage with client-side encryption,
1620
+ * key management, and sharing via X25519 grants.
1621
+ *
1622
+ * @example
1623
+ * ```typescript
1624
+ * // Unlock the vault
1625
+ * await vault.unlock(signer);
1626
+ *
1627
+ * // Store encrypted data
1628
+ * await vault.put('secret/notes', { content: 'Hello' });
1629
+ *
1630
+ * // Retrieve and decrypt
1631
+ * const entry = await vault.get<{ content: string }>('secret/notes');
1632
+ * if (entry.ok) {
1633
+ * console.log(entry.data.value.content); // 'Hello'
1634
+ * }
1635
+ *
1636
+ * // Share with another user
1637
+ * await vault.grant('secret/notes', recipientDID);
34
1638
  * ```
35
1639
  */
36
- export type { Result, ServiceError, StorageQuotaInfo, ErrorCode, IServiceContext, IService, ServiceSession, RetryPolicy, InvokeFunction, InvocationFact, InvocationFacts, FetchFunction, FetchRequestInit, FetchResponse, ServiceHeaders, EventHandler, ServiceRequestEvent, ServiceResponseEvent, ServiceErrorEvent, ServiceRetryEvent, } from "./types";
37
- export { ErrorCodes, defaultRetryPolicy, TelemetryEvents, ok, err, serviceError, } from "./types";
38
- export { ServiceErrorSchema, KVResponseHeadersSchema, KVListResponseSchema, ServiceRequestEventSchema, ServiceResponseEventSchema, ServiceErrorEventSchema, ServiceRetryEventSchema, RetryPolicySchema, ServiceSessionSchema, GenericResultSchema, GenericKVResponseSchema, KVListResultSchema, createResultSchema, createKVResponseSchema, validateServiceError, validateKVListResponse, validateKVResponseHeaders, validateServiceSession, validateRetryPolicy, validateServiceRequestEvent, validateServiceResponseEvent, } from "./types.schema";
39
- export type { ValidationError, ServiceErrorType, KVResponseHeadersType, KVListResponseType, GenericKVResponseType, KVListResultType, ServiceRequestEventType, ServiceResponseEventType, ServiceErrorEventType, ServiceRetryEventType, RetryPolicyType, ServiceSessionType, } from "./types.schema";
40
- export { ServiceContext } from "./context";
41
- export type { ServiceContextConfig } from "./context";
42
- export { authRequiredError, authExpiredError, networkError, timeoutError, abortedError, notFoundError, permissionDeniedError, wrapError, errorResult, storageQuotaExceededError, storageLimitReachedError, parseAuthError, authUnauthorizedError, } from "./errors";
43
- export { BaseService } from "./base/index";
44
- export type { ServiceConstructor, ServiceRegistration, BaseServiceOptions, } from "./base/index";
45
- export { KVService, PrefixedKVService, IKVService, KVAction } from "./kv";
46
- export type { IPrefixedKVService, KVServiceConfig, KVGetOptions, KVPutOptions, KVListOptions, KVDeleteOptions, KVHeadOptions, KVResponse, KVListResponse, KVResponseHeaders, KVActionType, } from "./kv";
47
- export { SQLService, DatabaseHandle, SQLAction } from "./sql";
48
- export type { ISQLService, IDatabaseHandle } from "./sql";
49
- export type { SQLServiceConfig, QueryOptions, ExecuteOptions, BatchOptions, SqlValue, SqlStatement, QueryResponse, ExecuteResponse, BatchResponse, SQLActionType, } from "./sql";
50
- export { DuckDbService, DuckDbDatabaseHandle, DuckDbAction } from "./duckdb";
51
- export type { IDuckDbService, IDuckDbDatabaseHandle } from "./duckdb";
52
- export type { DuckDbServiceConfig, DuckDbQueryOptions, DuckDbExecuteOptions, DuckDbBatchOptions, DuckDbOptions, DuckDbValue, DuckDbStatement, DuckDbQueryResponse, DuckDbExecuteResponse, DuckDbBatchResponse, DuckDbActionType, SchemaInfo, TableInfo, ColumnInfo, ViewInfo, } from "./duckdb";
53
- export { TinyCloudQuota } from "./quota";
54
- export type { QuotaConfig, QuotaStatus } from "./quota";
55
- export { DataVaultService, VaultHeaders, VaultPublicSpaceKVActions, createVaultCrypto } from "./vault";
56
- export type { IDataVaultService, VaultCrypto, WasmVaultFunctions } from "./vault";
57
- export type { DataVaultConfig, VaultPutOptions, VaultGetOptions, VaultListOptions, VaultGrantOptions, VaultEntry, VaultError, } from "./vault";
58
- //# sourceMappingURL=index.d.ts.map
1640
+ declare class DataVaultService extends BaseService implements IDataVaultService {
1641
+ /**
1642
+ * Service identifier for registration.
1643
+ */
1644
+ static readonly serviceName = "vault";
1645
+ /**
1646
+ * Service configuration.
1647
+ */
1648
+ protected _config: DataVaultServiceConfig;
1649
+ private masterKey;
1650
+ private encryptionIdentity;
1651
+ private _isUnlocked;
1652
+ private vaultConfig;
1653
+ /**
1654
+ * Create a new DataVaultService instance.
1655
+ *
1656
+ * @param config - Service configuration including crypto and tc references
1657
+ */
1658
+ constructor(config: DataVaultServiceConfig);
1659
+ /**
1660
+ * Get the service configuration.
1661
+ */
1662
+ get config(): DataVaultServiceConfig;
1663
+ /**
1664
+ * Whether the vault is currently unlocked.
1665
+ */
1666
+ get isUnlocked(): boolean;
1667
+ /**
1668
+ * The vault's public encryption key (X25519).
1669
+ * Throws if vault is locked.
1670
+ */
1671
+ get publicKey(): Uint8Array;
1672
+ /**
1673
+ * Convenience accessor for crypto operations.
1674
+ */
1675
+ private get crypto();
1676
+ /**
1677
+ * Convenience accessor for TinyCloud instance.
1678
+ */
1679
+ private get tc();
1680
+ /**
1681
+ * Get the host URL.
1682
+ */
1683
+ private get host();
1684
+ /**
1685
+ * Unlock the vault. Derives keys from two wallet signatures:
1686
+ * 1. Master signature (per-space) — used to derive the master encryption key
1687
+ * 2. Identity signature (per-address) — used to derive X25519 encryption identity
1688
+ *
1689
+ * If the identity public key already exists in the public space, the identity
1690
+ * signature is skipped entirely (no wallet popup). The identity private key is
1691
+ * only needed for sharing operations.
1692
+ *
1693
+ * @param signer - Object with signMessage method. Optional when cached
1694
+ * signatures exist (browser only).
1695
+ */
1696
+ unlock(signer?: {
1697
+ signMessage(message: string): Promise<string>;
1698
+ } | unknown): Promise<Result<void, VaultError>>;
1699
+ /**
1700
+ * Clear the cached vault signatures.
1701
+ *
1702
+ * @param spaceId - Clear only this space's master cache. If omitted, clears all.
1703
+ */
1704
+ clearCache(spaceId?: string): Promise<void>;
1705
+ /**
1706
+ * Lock the vault, clearing all key material from memory.
1707
+ */
1708
+ lock(): void;
1709
+ /**
1710
+ * Called when SDK signs out. Locks the vault and aborts operations.
1711
+ */
1712
+ onSignOut(): void;
1713
+ /**
1714
+ * Encrypt and store a value at the given key.
1715
+ *
1716
+ * @param key - The key to store under
1717
+ * @param value - The value to encrypt and store
1718
+ * @param options - Optional put configuration
1719
+ */
1720
+ put(key: string, value: unknown, options?: VaultPutOptions): Promise<Result<void, VaultError>>;
1721
+ /**
1722
+ * Retrieve and decrypt a value by key.
1723
+ *
1724
+ * @param key - The key to retrieve
1725
+ * @param options - Optional get configuration
1726
+ * @returns Result with the decrypted entry
1727
+ */
1728
+ get<T = unknown>(key: string, options?: VaultGetOptions<T>): Promise<Result<VaultEntry<T>, VaultError>>;
1729
+ /**
1730
+ * Delete an encrypted key.
1731
+ * Removes both the encrypted value and the key blob.
1732
+ *
1733
+ * @param key - The key to delete
1734
+ */
1735
+ delete(key: string): Promise<Result<void, VaultError>>;
1736
+ /**
1737
+ * List vault keys with optional prefix filtering.
1738
+ *
1739
+ * @param options - Optional list configuration
1740
+ * @returns Result with array of key names (vault/ prefix stripped)
1741
+ */
1742
+ list(options?: VaultListOptions): Promise<Result<string[], VaultError>>;
1743
+ /**
1744
+ * Get envelope metadata for a key without decrypting the value.
1745
+ *
1746
+ * @param key - The key to inspect
1747
+ * @returns Result with metadata headers
1748
+ */
1749
+ head(key: string): Promise<Result<Record<string, string>, VaultError>>;
1750
+ /**
1751
+ * Encrypt and store multiple entries.
1752
+ *
1753
+ * @param entries - Array of key/value pairs with optional per-entry options
1754
+ * @returns Array of results, one per entry
1755
+ */
1756
+ putMany(entries: Array<{
1757
+ key: string;
1758
+ value: unknown;
1759
+ options?: VaultPutOptions;
1760
+ }>): Promise<Result<void, VaultError>[]>;
1761
+ /**
1762
+ * Retrieve and decrypt multiple keys.
1763
+ *
1764
+ * @param keys - Array of keys to retrieve
1765
+ * @param options - Optional get configuration applied to all entries
1766
+ * @returns Array of results, one per key
1767
+ */
1768
+ getMany<T = unknown>(keys: string[], options?: VaultGetOptions<T>): Promise<Result<VaultEntry<T>, VaultError>[]>;
1769
+ /**
1770
+ * Re-encrypt a vault key for another user (renamed from grant).
1771
+ * Re-encrypts the data key to the recipient's public key via X25519 DH.
1772
+ *
1773
+ * @param key - The key to share
1774
+ * @param recipientDID - The recipient's primary DID (did:pkh:...)
1775
+ * @param options - Optional grant configuration
1776
+ */
1777
+ reencrypt(key: string, recipientDID: string, options?: VaultGrantOptions): Promise<Result<void, VaultError>>;
1778
+ /**
1779
+ * @deprecated Use reencrypt() instead.
1780
+ */
1781
+ grant(key: string, recipientDID: string, options?: VaultGrantOptions): Promise<Result<void, VaultError>>;
1782
+ /**
1783
+ * Retrieve and decrypt a value shared by another user.
1784
+ *
1785
+ * @param grantorDID - The DID of the user who shared the data
1786
+ * @param key - The key that was shared
1787
+ * @param options - Optional get configuration
1788
+ * @returns Result with the decrypted entry
1789
+ */
1790
+ getShared<T = unknown>(grantorDID: string, key: string, options?: VaultGetOptions<T>): Promise<Result<VaultEntry<T>, VaultError>>;
1791
+ /**
1792
+ * Resolve another user's public encryption key from their DID.
1793
+ *
1794
+ * @param did - The DID to resolve (did:pkh:eip155:{chainId}:{address})
1795
+ * @returns Result with the public key bytes
1796
+ */
1797
+ resolvePublicKey(did: string): Promise<Result<Uint8Array, VaultError>>;
1798
+ /**
1799
+ * List DIDs that have been granted access to a key.
1800
+ *
1801
+ * @param key - The key to list grants for
1802
+ * @returns Result with array of recipient DIDs
1803
+ */
1804
+ listGrants(key: string): Promise<Result<string[], VaultError>>;
1805
+ /**
1806
+ * Revoke a previously issued grant.
1807
+ *
1808
+ * This performs a full key rotation:
1809
+ * 1. Lists current grantees
1810
+ * 2. Removes the revoked recipient
1811
+ * 3. Re-encrypts the value with a new entry key
1812
+ * 4. Re-issues grants to remaining recipients
1813
+ *
1814
+ * @param key - The key to revoke access to
1815
+ * @param recipientDID - The recipient whose access to revoke
1816
+ */
1817
+ revoke(key: string, recipientDID: string): Promise<Result<void, VaultError>>;
1818
+ /**
1819
+ * Parse a DID string to extract address and chainId.
1820
+ * Expected format: did:pkh:eip155:{chainId}:{address}
1821
+ *
1822
+ * @param did - The DID to parse
1823
+ * @returns Parsed address and chainId, or null if invalid
1824
+ */
1825
+ private parseDID;
1826
+ }
1827
+
1828
+ interface WasmVaultFunctions {
1829
+ vault_encrypt(key: Uint8Array, plaintext: Uint8Array): Uint8Array;
1830
+ vault_decrypt(key: Uint8Array, blob: Uint8Array): Uint8Array;
1831
+ /** WASM order: (salt, signature, info) — NOT (signature, salt, info) */
1832
+ vault_derive_key(salt: Uint8Array, signature: Uint8Array, info: Uint8Array): Uint8Array;
1833
+ vault_x25519_from_seed(seed: Uint8Array): {
1834
+ publicKey: Uint8Array;
1835
+ privateKey: Uint8Array;
1836
+ };
1837
+ vault_x25519_dh(privateKey: Uint8Array, publicKey: Uint8Array): Uint8Array;
1838
+ vault_random_bytes(length: number): Uint8Array;
1839
+ vault_sha256(data: Uint8Array): Uint8Array;
1840
+ }
1841
+ declare function createVaultCrypto(wasm: WasmVaultFunctions): VaultCrypto;
1842
+
1843
+ export { BaseService, type BaseServiceOptions, type ColumnInfo, type DataVaultConfig, DataVaultService, DuckDbAction, type DuckDbActionType, type DuckDbBatchOptions, type BatchResponse as DuckDbBatchResponse, DuckDbDatabaseHandle, type DuckDbExecuteOptions, type ExecuteResponse as DuckDbExecuteResponse, type DuckDbOptions, type DuckDbQueryOptions, type QueryResponse as DuckDbQueryResponse, DuckDbService, type DuckDbServiceConfig, type DuckDbStatement, type DuckDbValue, FetchFunction, GenericKVResponseSchema, type GenericKVResponseType, GenericResultSchema, type IDataVaultService, type IDuckDbDatabaseHandle, type IDuckDbService, IKVService, IService, IServiceContext, InvokeFunction, KVListResponseSchema, type KVListResponseType, KVListResultSchema, type KVListResultType, KVResponseHeadersSchema, type KVResponseHeadersType, type QuotaConfig, type QuotaStatus, Result, RetryPolicy, RetryPolicySchema, type RetryPolicyType, type SchemaInfo, type ServiceConstructor, ServiceContext, type ServiceContextConfig, ServiceError, ServiceErrorEventSchema, type ServiceErrorEventType, ServiceErrorSchema, type ServiceErrorType, type ServiceRegistration, ServiceRequestEventSchema, type ServiceRequestEventType, ServiceResponseEventSchema, type ServiceResponseEventType, ServiceRetryEventSchema, type ServiceRetryEventType, ServiceSession, ServiceSessionSchema, type ServiceSessionType, StorageQuotaInfo, type TableInfo, TinyCloudQuota, type ValidationError, type VaultCrypto, type VaultEntry, type VaultError, type VaultGetOptions, type VaultGrantOptions, VaultHeaders, type VaultListOptions, VaultPublicSpaceKVActions, type VaultPutOptions, type ViewInfo, type WasmVaultFunctions, abortedError, authExpiredError, authRequiredError, authUnauthorizedError, createKVResponseSchema, createResultSchema, createVaultCrypto, errorResult, networkError, notFoundError, parseAuthError, permissionDeniedError, storageLimitReachedError, storageQuotaExceededError, timeoutError, validateKVListResponse, validateKVResponseHeaders, validateRetryPolicy, validateServiceError, validateServiceRequestEvent, validateServiceResponseEvent, validateServiceSession, wrapError };