@tinycloud/sdk-services 3.1.0-beta.1 → 3.1.0-beta.10

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.
@@ -1,4 +1,55 @@
1
- import { I as IService, a as IServiceContext, S as ServiceSession, b as ServiceError, R as Result } from './types-qwMmB7qB.cjs';
1
+ import { I as IService, a as IServiceContext, S as ServiceSession, b as ServiceError, R as Result } from './types-CVwwxqXF.js';
2
+
3
+ /**
4
+ * Base Service Types
5
+ *
6
+ * Types specific to the base service infrastructure.
7
+ */
8
+
9
+ /**
10
+ * Service constructor type for registration.
11
+ * Used by the SDK to instantiate services.
12
+ */
13
+ interface ServiceConstructor<TConfig = Record<string, unknown>, TService extends IService = IService> {
14
+ /** Service identifier used for registration */
15
+ readonly serviceName: string;
16
+ /** Create a new instance of the service */
17
+ new (config?: TConfig): TService;
18
+ }
19
+ /**
20
+ * Service registration entry.
21
+ */
22
+ interface ServiceRegistration {
23
+ /** The service class constructor */
24
+ constructor: ServiceConstructor;
25
+ /** Configuration for this service instance */
26
+ config?: Record<string, unknown>;
27
+ }
28
+ /**
29
+ * Options for base service operations.
30
+ */
31
+ interface BaseServiceOptions {
32
+ /** Override the default timeout for this operation */
33
+ timeout?: number;
34
+ /** Custom abort signal for this operation */
35
+ signal?: AbortSignal;
36
+ }
37
+ /**
38
+ * A per-request abort signal and the cleanup that releases it.
39
+ * Created by `BaseService.createRequestSignal()`.
40
+ */
41
+ interface RequestSignal {
42
+ /**
43
+ * Aborts on service sign-out, context abort, the caller's signal, or when
44
+ * the request timeout elapses (reason: a `TimeoutError`).
45
+ */
46
+ readonly signal: AbortSignal;
47
+ /**
48
+ * Clear the timeout and detach from the parent signals. Call once the
49
+ * response has been consumed. Idempotent.
50
+ */
51
+ dispose(): void;
52
+ }
2
53
 
3
54
  /**
4
55
  * BaseService - Abstract base class for all TinyCloud services.
@@ -144,6 +195,27 @@ declare abstract class BaseService implements IService {
144
195
  * @returns A combined abort signal
145
196
  */
146
197
  protected combineSignals(...signals: (AbortSignal | undefined)[]): AbortSignal;
198
+ /**
199
+ * Create the abort signal for one request, bounded by the request timeout.
200
+ *
201
+ * The signal aborts when the service signs out, the context aborts, the
202
+ * caller's `signal` aborts, or the timeout elapses, whichever comes first.
203
+ * A timeout aborts with a {@link RequestTimeoutError} (`TimeoutError`), which
204
+ * `wrapError` maps to `ErrorCodes.TIMEOUT`; the other sources keep their own
205
+ * reason (normally `AbortError`, mapped to `ErrorCodes.ABORTED`).
206
+ *
207
+ * The timeout is `timeoutMs` when given, otherwise `config.timeout`. Only a
208
+ * positive, finite value (at most 2^31-1 ms) applies; `undefined`, `0`, and
209
+ * `Infinity` mean no timeout, so a per-call `0` opts out of a configured one.
210
+ *
211
+ * Callers must call `dispose()` once the response body has been consumed,
212
+ * which clears the timer and removes the listeners this adds to the
213
+ * long-lived service and context signals.
214
+ *
215
+ * @param signal - The caller's abort signal for this request
216
+ * @param timeoutMs - Per-request timeout override in milliseconds
217
+ */
218
+ protected createRequestSignal(signal?: AbortSignal, timeoutMs?: number): RequestSignal;
147
219
  /**
148
220
  * Wrap an operation with error handling and telemetry.
149
221
  *
@@ -155,4 +227,4 @@ declare abstract class BaseService implements IService {
155
227
  protected withTelemetry<T>(action: string, key: string | undefined, operation: () => Promise<Result<T>>): Promise<Result<T>>;
156
228
  }
157
229
 
158
- export { BaseService as B };
230
+ export { BaseService as B, type RequestSignal as R, type ServiceConstructor as S, type BaseServiceOptions as a, type ServiceRegistration as b };
@@ -1,4 +1,55 @@
1
- import { I as IService, a as IServiceContext, S as ServiceSession, b as ServiceError, R as Result } from './types-qwMmB7qB.js';
1
+ import { I as IService, a as IServiceContext, S as ServiceSession, b as ServiceError, R as Result } from './types-CVwwxqXF.cjs';
2
+
3
+ /**
4
+ * Base Service Types
5
+ *
6
+ * Types specific to the base service infrastructure.
7
+ */
8
+
9
+ /**
10
+ * Service constructor type for registration.
11
+ * Used by the SDK to instantiate services.
12
+ */
13
+ interface ServiceConstructor<TConfig = Record<string, unknown>, TService extends IService = IService> {
14
+ /** Service identifier used for registration */
15
+ readonly serviceName: string;
16
+ /** Create a new instance of the service */
17
+ new (config?: TConfig): TService;
18
+ }
19
+ /**
20
+ * Service registration entry.
21
+ */
22
+ interface ServiceRegistration {
23
+ /** The service class constructor */
24
+ constructor: ServiceConstructor;
25
+ /** Configuration for this service instance */
26
+ config?: Record<string, unknown>;
27
+ }
28
+ /**
29
+ * Options for base service operations.
30
+ */
31
+ interface BaseServiceOptions {
32
+ /** Override the default timeout for this operation */
33
+ timeout?: number;
34
+ /** Custom abort signal for this operation */
35
+ signal?: AbortSignal;
36
+ }
37
+ /**
38
+ * A per-request abort signal and the cleanup that releases it.
39
+ * Created by `BaseService.createRequestSignal()`.
40
+ */
41
+ interface RequestSignal {
42
+ /**
43
+ * Aborts on service sign-out, context abort, the caller's signal, or when
44
+ * the request timeout elapses (reason: a `TimeoutError`).
45
+ */
46
+ readonly signal: AbortSignal;
47
+ /**
48
+ * Clear the timeout and detach from the parent signals. Call once the
49
+ * response has been consumed. Idempotent.
50
+ */
51
+ dispose(): void;
52
+ }
2
53
 
3
54
  /**
4
55
  * BaseService - Abstract base class for all TinyCloud services.
@@ -144,6 +195,27 @@ declare abstract class BaseService implements IService {
144
195
  * @returns A combined abort signal
145
196
  */
146
197
  protected combineSignals(...signals: (AbortSignal | undefined)[]): AbortSignal;
198
+ /**
199
+ * Create the abort signal for one request, bounded by the request timeout.
200
+ *
201
+ * The signal aborts when the service signs out, the context aborts, the
202
+ * caller's `signal` aborts, or the timeout elapses, whichever comes first.
203
+ * A timeout aborts with a {@link RequestTimeoutError} (`TimeoutError`), which
204
+ * `wrapError` maps to `ErrorCodes.TIMEOUT`; the other sources keep their own
205
+ * reason (normally `AbortError`, mapped to `ErrorCodes.ABORTED`).
206
+ *
207
+ * The timeout is `timeoutMs` when given, otherwise `config.timeout`. Only a
208
+ * positive, finite value (at most 2^31-1 ms) applies; `undefined`, `0`, and
209
+ * `Infinity` mean no timeout, so a per-call `0` opts out of a configured one.
210
+ *
211
+ * Callers must call `dispose()` once the response body has been consumed,
212
+ * which clears the timer and removes the listeners this adds to the
213
+ * long-lived service and context signals.
214
+ *
215
+ * @param signal - The caller's abort signal for this request
216
+ * @param timeoutMs - Per-request timeout override in milliseconds
217
+ */
218
+ protected createRequestSignal(signal?: AbortSignal, timeoutMs?: number): RequestSignal;
147
219
  /**
148
220
  * Wrap an operation with error handling and telemetry.
149
221
  *
@@ -155,4 +227,4 @@ declare abstract class BaseService implements IService {
155
227
  protected withTelemetry<T>(action: string, key: string | undefined, operation: () => Promise<Result<T>>): Promise<Result<T>>;
156
228
  }
157
229
 
158
- export { BaseService as B };
230
+ export { BaseService as B, type RequestSignal as R, type ServiceConstructor as S, type BaseServiceOptions as a, type ServiceRegistration as b };
@@ -71,6 +71,10 @@ var ErrorCodes = {
71
71
  AUTH_EXPIRED: "AUTH_EXPIRED",
72
72
  AUTH_REQUIRED: "AUTH_REQUIRED",
73
73
  AUTH_UNAUTHORIZED: "AUTH_UNAUTHORIZED",
74
+ /** HTTP 401: the delegation the invocation cites was revoked. */
75
+ AUTH_DELEGATION_REVOKED: "AUTH_DELEGATION_REVOKED",
76
+ /** HTTP 401: a delegation the cited one rests on was revoked. */
77
+ AUTH_DELEGATION_ANCESTOR_REVOKED: "AUTH_DELEGATION_ANCESTOR_REVOKED",
74
78
  NETWORK_ERROR: "NETWORK_ERROR",
75
79
  TIMEOUT: "TIMEOUT",
76
80
  ABORTED: "ABORTED",
@@ -82,6 +86,10 @@ var ErrorCodes = {
82
86
  KV_PRECONDITION_FAILED: "KV_PRECONDITION_FAILED",
83
87
  KV_CONFLICT: "KV_CONFLICT",
84
88
  KV_RESPONSE_TOO_LARGE: "KV_RESPONSE_TOO_LARGE",
89
+ /** HTTP 410 from the change feed: discard sync state and restart without a cursor; `meta.reason` says why. */
90
+ KV_SYNC_RESET_REQUIRED: "KV_SYNC_RESET_REQUIRED",
91
+ /** HTTP 403 from the change feed: the retention grant was refused; `meta.reason` says why. */
92
+ KV_RETENTION_GRANT_REFUSED: "KV_RETENTION_GRANT_REFUSED",
85
93
  // SQL-specific errors
86
94
  SQL_ERROR: "SQL_ERROR",
87
95
  SQL_PERMISSION_DENIED: "SQL_PERMISSION_DENIED",
@@ -125,11 +133,131 @@ function err(error) {
125
133
  }
126
134
 
127
135
  // src/errors.ts
128
- function timeoutError(service) {
136
+ var import_bootstrap = require("@tinycloud/bootstrap");
137
+
138
+ // src/encryption/networkId.ts
139
+ var URN_PREFIX = "urn:tinycloud:encryption:";
140
+ var NETWORK_NAME_RE = /^[a-z0-9][a-z0-9-]*$/;
141
+ var PKH_EIP155_DID_RE = /^did:pkh:eip155:(\d+):(0x[a-fA-F0-9]{40})$/;
142
+ var NetworkIdError = class extends Error {
143
+ constructor(message) {
144
+ super(message);
145
+ this.name = "NetworkIdError";
146
+ }
147
+ };
148
+ function parseNetworkId(networkId) {
149
+ if (typeof networkId !== "string" || networkId.length === 0) {
150
+ throw new NetworkIdError("networkId must be a non-empty string");
151
+ }
152
+ if (!networkId.startsWith(URN_PREFIX)) {
153
+ throw new NetworkIdError(
154
+ `networkId must start with ${URN_PREFIX} (got ${JSON.stringify(networkId)})`
155
+ );
156
+ }
157
+ const body = networkId.slice(URN_PREFIX.length);
158
+ const lastColon = body.lastIndexOf(":");
159
+ if (lastColon <= 0 || lastColon === body.length - 1) {
160
+ throw new NetworkIdError(
161
+ `networkId missing ownerDid or name segment (got ${JSON.stringify(networkId)})`
162
+ );
163
+ }
164
+ const ownerDid = body.slice(0, lastColon);
165
+ const name = body.slice(lastColon + 1);
166
+ if (!ownerDid.startsWith("did:")) {
167
+ throw new NetworkIdError(
168
+ `networkId ownerDid must be a DID (got ${JSON.stringify(ownerDid)})`
169
+ );
170
+ }
171
+ const didParts = ownerDid.split(":");
172
+ if (didParts.length < 3 || didParts.some((p) => p.length === 0)) {
173
+ throw new NetworkIdError(
174
+ `networkId ownerDid is not a well-formed DID (got ${JSON.stringify(ownerDid)})`
175
+ );
176
+ }
177
+ if (!NETWORK_NAME_RE.test(name)) {
178
+ throw new NetworkIdError(
179
+ `networkId name ${JSON.stringify(name)} must match ${NETWORK_NAME_RE.source}`
180
+ );
181
+ }
182
+ return { networkId, ownerDid, name };
183
+ }
184
+ function buildNetworkId(ownerDid, name) {
185
+ if (typeof ownerDid !== "string" || !ownerDid.startsWith("did:")) {
186
+ throw new NetworkIdError("ownerDid must be a DID");
187
+ }
188
+ if (typeof name !== "string" || !NETWORK_NAME_RE.test(name)) {
189
+ throw new NetworkIdError(
190
+ `network name ${JSON.stringify(name)} must match ${NETWORK_NAME_RE.source}`
191
+ );
192
+ }
193
+ const networkId = `${URN_PREFIX}${ownerDid}:${name}`;
194
+ parseNetworkId(networkId);
195
+ return networkId;
196
+ }
197
+ function isNetworkId(networkId) {
198
+ if (typeof networkId !== "string") {
199
+ return false;
200
+ }
201
+ try {
202
+ parseNetworkId(networkId);
203
+ return true;
204
+ } catch {
205
+ return false;
206
+ }
207
+ }
208
+ function parsePkhOwnerDid(ownerDid) {
209
+ const match = ownerDid.match(PKH_EIP155_DID_RE);
210
+ if (!match) return null;
211
+ return {
212
+ chainId: match[1],
213
+ address: match[2].toLowerCase()
214
+ };
215
+ }
216
+ function ownerDidMatches(a, b) {
217
+ const aPkh = parsePkhOwnerDid(a);
218
+ const bPkh = parsePkhOwnerDid(b);
219
+ if (aPkh && bPkh) {
220
+ return aPkh.chainId === bPkh.chainId && aPkh.address === bPkh.address;
221
+ }
222
+ return a === b;
223
+ }
224
+ function networkDiscoveryKey(name) {
225
+ if (!NETWORK_NAME_RE.test(name)) {
226
+ throw new NetworkIdError(
227
+ `network name ${JSON.stringify(name)} must match ${NETWORK_NAME_RE.source}`
228
+ );
229
+ }
230
+ return `.well-known/encryption/network/${name}`;
231
+ }
232
+ var ENCRYPTION_NETWORK_URN_PREFIX = URN_PREFIX;
233
+ var NETWORK_NAME_PATTERN = NETWORK_NAME_RE;
234
+
235
+ // src/errors.ts
236
+ var RequestTimeoutError = class extends Error {
237
+ constructor(timeoutMs) {
238
+ super(`Request timed out after ${timeoutMs}ms.`);
239
+ this.name = "TimeoutError";
240
+ this.timeoutMs = timeoutMs;
241
+ }
242
+ };
243
+ function isRequestTimeoutError(error) {
244
+ return error instanceof RequestTimeoutError || error instanceof Error && error.name === "TimeoutError" && typeof error.timeoutMs === "number";
245
+ }
246
+ function timeoutError(service, timeoutMs, cause) {
247
+ if (timeoutMs === void 0) {
248
+ return {
249
+ code: ErrorCodes.TIMEOUT,
250
+ message: "Request timed out.",
251
+ service,
252
+ ...cause === void 0 ? {} : { cause }
253
+ };
254
+ }
129
255
  return {
130
256
  code: ErrorCodes.TIMEOUT,
131
- message: "Request timed out.",
132
- service
257
+ message: `Request timed out after ${timeoutMs}ms.`,
258
+ service,
259
+ ...cause === void 0 ? {} : { cause },
260
+ meta: { timeoutMs }
133
261
  };
134
262
  }
135
263
  function abortedError(service) {
@@ -139,8 +267,17 @@ function abortedError(service) {
139
267
  service
140
268
  };
141
269
  }
270
+ var grantableActions = new Set(
271
+ import_bootstrap.CAPABILITY_REGISTRY.map(({ urn }) => urn).filter((urn) => !urn.endsWith("/*"))
272
+ );
273
+ var capabilityServices = new Set(
274
+ import_bootstrap.CAPABILITY_REGISTRY.map(({ service }) => service.slice("tinycloud.".length))
275
+ );
142
276
  function wrapError(service, error, defaultCode = ErrorCodes.NETWORK_ERROR) {
143
277
  if (error instanceof Error) {
278
+ if (isRequestTimeoutError(error)) {
279
+ return timeoutError(service, error.timeoutMs, error);
280
+ }
144
281
  if (error.name === "AbortError") {
145
282
  return abortedError(service);
146
283
  }
@@ -162,6 +299,7 @@ function wrapError(service, error, defaultCode = ErrorCodes.NETWORK_ERROR) {
162
299
  }
163
300
 
164
301
  // src/base/BaseService.ts
302
+ var MAX_TIMER_DELAY_MS = 2147483647;
165
303
  var BaseService = class {
166
304
  constructor() {
167
305
  /**
@@ -342,6 +480,64 @@ var BaseService = class {
342
480
  }
343
481
  return controller.signal;
344
482
  }
483
+ /**
484
+ * Create the abort signal for one request, bounded by the request timeout.
485
+ *
486
+ * The signal aborts when the service signs out, the context aborts, the
487
+ * caller's `signal` aborts, or the timeout elapses, whichever comes first.
488
+ * A timeout aborts with a {@link RequestTimeoutError} (`TimeoutError`), which
489
+ * `wrapError` maps to `ErrorCodes.TIMEOUT`; the other sources keep their own
490
+ * reason (normally `AbortError`, mapped to `ErrorCodes.ABORTED`).
491
+ *
492
+ * The timeout is `timeoutMs` when given, otherwise `config.timeout`. Only a
493
+ * positive, finite value (at most 2^31-1 ms) applies; `undefined`, `0`, and
494
+ * `Infinity` mean no timeout, so a per-call `0` opts out of a configured one.
495
+ *
496
+ * Callers must call `dispose()` once the response body has been consumed,
497
+ * which clears the timer and removes the listeners this adds to the
498
+ * long-lived service and context signals.
499
+ *
500
+ * @param signal - The caller's abort signal for this request
501
+ * @param timeoutMs - Per-request timeout override in milliseconds
502
+ */
503
+ createRequestSignal(signal, timeoutMs) {
504
+ const controller = new AbortController();
505
+ const detachers = [];
506
+ let timer;
507
+ const dispose = () => {
508
+ if (timer !== void 0) {
509
+ clearTimeout(timer);
510
+ timer = void 0;
511
+ }
512
+ for (const detach of detachers.splice(0)) {
513
+ detach();
514
+ }
515
+ };
516
+ const abort = (reason) => {
517
+ dispose();
518
+ controller.abort(reason);
519
+ };
520
+ const requestSignal = { signal: controller.signal, dispose };
521
+ const parents = [
522
+ this.abortController.signal,
523
+ this.context?.abortSignal,
524
+ signal
525
+ ].filter((parent) => parent !== void 0);
526
+ for (const parent of parents) {
527
+ if (parent.aborted) {
528
+ abort(parent.reason);
529
+ return requestSignal;
530
+ }
531
+ const onAbort = () => abort(parent.reason);
532
+ parent.addEventListener("abort", onAbort, { once: true });
533
+ detachers.push(() => parent.removeEventListener("abort", onAbort));
534
+ }
535
+ const timeout = timeoutMs ?? this._config.timeout;
536
+ if (typeof timeout === "number" && timeout > 0 && timeout <= MAX_TIMER_DELAY_MS) {
537
+ timer = setTimeout(() => abort(new RequestTimeoutError(timeout)), timeout);
538
+ }
539
+ return requestSignal;
540
+ }
345
541
  /**
346
542
  * Wrap an operation with error handling and telemetry.
347
543
  *
@@ -481,103 +677,6 @@ function canonicalHashHex(sha256, value) {
481
677
  return hexEncode(sha256(utf8Encode(canonical)));
482
678
  }
483
679
 
484
- // src/encryption/networkId.ts
485
- var URN_PREFIX = "urn:tinycloud:encryption:";
486
- var NETWORK_NAME_RE = /^[a-z0-9][a-z0-9-]*$/;
487
- var PKH_EIP155_DID_RE = /^did:pkh:eip155:(\d+):(0x[a-fA-F0-9]{40})$/;
488
- var NetworkIdError = class extends Error {
489
- constructor(message) {
490
- super(message);
491
- this.name = "NetworkIdError";
492
- }
493
- };
494
- function parseNetworkId(networkId) {
495
- if (typeof networkId !== "string" || networkId.length === 0) {
496
- throw new NetworkIdError("networkId must be a non-empty string");
497
- }
498
- if (!networkId.startsWith(URN_PREFIX)) {
499
- throw new NetworkIdError(
500
- `networkId must start with ${URN_PREFIX} (got ${JSON.stringify(networkId)})`
501
- );
502
- }
503
- const body = networkId.slice(URN_PREFIX.length);
504
- const lastColon = body.lastIndexOf(":");
505
- if (lastColon <= 0 || lastColon === body.length - 1) {
506
- throw new NetworkIdError(
507
- `networkId missing ownerDid or name segment (got ${JSON.stringify(networkId)})`
508
- );
509
- }
510
- const ownerDid = body.slice(0, lastColon);
511
- const name = body.slice(lastColon + 1);
512
- if (!ownerDid.startsWith("did:")) {
513
- throw new NetworkIdError(
514
- `networkId ownerDid must be a DID (got ${JSON.stringify(ownerDid)})`
515
- );
516
- }
517
- const didParts = ownerDid.split(":");
518
- if (didParts.length < 3 || didParts.some((p) => p.length === 0)) {
519
- throw new NetworkIdError(
520
- `networkId ownerDid is not a well-formed DID (got ${JSON.stringify(ownerDid)})`
521
- );
522
- }
523
- if (!NETWORK_NAME_RE.test(name)) {
524
- throw new NetworkIdError(
525
- `networkId name ${JSON.stringify(name)} must match ${NETWORK_NAME_RE.source}`
526
- );
527
- }
528
- return { networkId, ownerDid, name };
529
- }
530
- function buildNetworkId(ownerDid, name) {
531
- if (typeof ownerDid !== "string" || !ownerDid.startsWith("did:")) {
532
- throw new NetworkIdError("ownerDid must be a DID");
533
- }
534
- if (typeof name !== "string" || !NETWORK_NAME_RE.test(name)) {
535
- throw new NetworkIdError(
536
- `network name ${JSON.stringify(name)} must match ${NETWORK_NAME_RE.source}`
537
- );
538
- }
539
- const networkId = `${URN_PREFIX}${ownerDid}:${name}`;
540
- parseNetworkId(networkId);
541
- return networkId;
542
- }
543
- function isNetworkId(networkId) {
544
- if (typeof networkId !== "string") {
545
- return false;
546
- }
547
- try {
548
- parseNetworkId(networkId);
549
- return true;
550
- } catch {
551
- return false;
552
- }
553
- }
554
- function parsePkhOwnerDid(ownerDid) {
555
- const match = ownerDid.match(PKH_EIP155_DID_RE);
556
- if (!match) return null;
557
- return {
558
- chainId: match[1],
559
- address: match[2].toLowerCase()
560
- };
561
- }
562
- function ownerDidMatches(a, b) {
563
- const aPkh = parsePkhOwnerDid(a);
564
- const bPkh = parsePkhOwnerDid(b);
565
- if (aPkh && bPkh) {
566
- return aPkh.chainId === bPkh.chainId && aPkh.address === bPkh.address;
567
- }
568
- return a === b;
569
- }
570
- function networkDiscoveryKey(name) {
571
- if (!NETWORK_NAME_RE.test(name)) {
572
- throw new NetworkIdError(
573
- `network name ${JSON.stringify(name)} must match ${NETWORK_NAME_RE.source}`
574
- );
575
- }
576
- return `.well-known/encryption/network/${name}`;
577
- }
578
- var ENCRYPTION_NETWORK_URN_PREFIX = URN_PREFIX;
579
- var NETWORK_NAME_PATTERN = NETWORK_NAME_RE;
580
-
581
680
  // src/encryption/types.ts
582
681
  var DEFAULT_ENCRYPTION_ALG = "x25519-aes256gcm/v1";
583
682
  var ENVELOPE_VERSION = 1;