@deveye/types 0.18.2 → 0.19.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.
@@ -1,11 +1,16 @@
1
1
  import type { ZodType } from 'zod';
2
2
  import type { ItemAccess } from '../domain/sharing';
3
+ import { normaliseDomainHost } from './domains';
3
4
  import { resolveExtras, type FeatureManifest } from './manifest';
4
5
  import {
5
6
  FeatureError,
6
7
  type DevEyeFacade,
8
+ type FeatureDomainsContext,
9
+ type SdkDns,
10
+ type SdkDomain,
7
11
  type FeatureServiceDeps,
8
12
  type FeatureStore,
13
+ type SdkAccount,
9
14
  type SdkCipher,
10
15
  type SdkDevice,
11
16
  type SdkFeatureContext,
@@ -111,6 +116,8 @@ export interface RecordedCalls {
111
116
  pinnedInstants: { deviceId: string; ts: number }[];
112
117
  /** Frames pushed through `live.publish`, in order. */
113
118
  livePublishes: { workspaceId: number; event: string; payload: unknown }[];
119
+ /** Accounts beaten through `live.accountChanged`, in order. */
120
+ accountChanges: number[];
114
121
  }
115
122
 
116
123
  function recordingNotify(
@@ -236,6 +243,20 @@ function fakeDerive(salt: string, info: string, length: number): Uint8Array {
236
243
  return out;
237
244
  }
238
245
 
246
+ function memoryDomains(domains: readonly SdkDomain[]) {
247
+ return {
248
+ in: (workspaceId: number) => domains.filter((d) => d.workspaceId === workspaceId),
249
+ byHost: (host: string) => domains.find((d) => d.host === normaliseDomainHost(host)) ?? null
250
+ };
251
+ }
252
+
253
+ /** Lookups that find nothing, unless the test says otherwise. */
254
+ const emptyDns: SdkDns = {
255
+ txt: () => Promise.resolve([]),
256
+ mx: () => Promise.resolve([]),
257
+ cname: () => Promise.resolve([])
258
+ };
259
+
239
260
  /** The named contracts a test hands to the module (`providers` override). */
240
261
  function fakeProviders(table: Readonly<Record<string, unknown>>): SdkProviders {
241
262
  return { get: <T>(key: string) => table[key] as T | undefined };
@@ -258,6 +279,12 @@ export interface TestContextOverrides<Repo> {
258
279
  isAdmin?: boolean;
259
280
  /** What `deveye.workspaces.list()` answers. Default none. */
260
281
  workspaces?: readonly SdkWorkspaceSummary[];
282
+ /** What `deveye.accounts.me()` answers. Default: an account named after `userId`. */
283
+ account?: SdkAccount;
284
+ /** The plan's limits, by YOUR quota key. An absent key is unlimited. Default none. */
285
+ quotaLimits?: Record<string, number>;
286
+ /** The workspaces the owner account owns, handed to a quota counter. Default: the workspace of the call. */
287
+ ownerWorkspaceIds?: readonly number[];
261
288
  canWrite?: boolean;
262
289
  /** Extra permissions the caller holds, as the grant would carry them. */
263
290
  extras?: Record<string, boolean | string>;
@@ -290,12 +317,19 @@ export interface TestContextOverrides<Repo> {
290
317
  unlocked?: boolean;
291
318
  /** The caller's role restrictions on items, by item id. Default none. */
292
319
  itemRestrictions?: Readonly<Record<string, ItemAccess>>;
320
+ /**
321
+ * Extra permissions overridden on one item, by item id then key. What
322
+ * `items.canExtra` answers there; elsewhere it follows `extras`.
323
+ */
324
+ itemExtras?: Readonly<Record<string, Readonly<Record<string, boolean>>>>;
293
325
  /**
294
326
  * Items projected INTO the workspace, as `itemId → home workspace id`.
295
327
  * Default none: every item is at home. `sharing.scope().cipherFor` is the
296
328
  * identity cipher either way.
297
329
  */
298
330
  shares?: Readonly<Record<string, number>>;
331
+ /** The feature's domains, every workspace mixed: `ctx.domains` answers for the active one. Default none. */
332
+ domains?: readonly SdkDomain[];
299
333
  /** The named contracts the host holds (`ctx.providers.get(key)`). */
300
334
  providers?: Readonly<Record<string, unknown>>;
301
335
  }
@@ -309,7 +343,8 @@ export function createTestContext<Repo = undefined>(
309
343
  audits: [],
310
344
  agentRequests: [],
311
345
  pinnedInstants: [],
312
- livePublishes: []
346
+ livePublishes: [],
347
+ accountChanges: []
313
348
  };
314
349
  const isOwner = overrides.isOwner ?? true;
315
350
  const workspaceId = overrides.workspaceId ?? 1;
@@ -332,11 +367,28 @@ export function createTestContext<Repo = undefined>(
332
367
  devices: recordingDevices(overrides.devices ?? []),
333
368
  telemetry: recordingTelemetry(recorded, overrides.snapshots ?? []),
334
369
  agents: recordingAgents(recorded),
370
+ accounts: {
371
+ me: () =>
372
+ Promise.resolve(
373
+ overrides.account ?? {
374
+ id: overrides.userId ?? 1,
375
+ email: `user${overrides.userId ?? 1}@deveye.test`,
376
+ username: `user${overrides.userId ?? 1}`,
377
+ isAdmin: overrides.isAdmin ?? false,
378
+ created: 0
379
+ }
380
+ )
381
+ },
335
382
  ...overrides.deveye
336
383
  };
337
384
  const restrictions = new Map<string, ItemAccess>(
338
385
  Object.entries(overrides.itemRestrictions ?? {})
339
386
  );
387
+ const extras = resolveExtras(
388
+ overrides.manifest?.extraPermissions,
389
+ isOwner,
390
+ overrides.extras ?? {}
391
+ );
340
392
  const homes = new Map<string, number>(Object.entries(overrides.shares ?? {}));
341
393
  const forgotten: string[] = [];
342
394
  const orders: { itemId: string; order: number }[] = [];
@@ -360,6 +412,25 @@ export function createTestContext<Repo = undefined>(
360
412
  live: {
361
413
  publish(event, payload) {
362
414
  recorded.livePublishes.push({ workspaceId, event, payload });
415
+ },
416
+ accountChanged(userId) {
417
+ recorded.accountChanges.push(userId);
418
+ }
419
+ },
420
+ quota: {
421
+ limit: (key) => Promise.resolve(overrides.quotaLimits?.[key] ?? null),
422
+ // The exact rule of the app: never counted when unlimited, refused
423
+ // once the count AFTER creation passes the limit.
424
+ async assert(key, countAfter) {
425
+ const limit = overrides.quotaLimits?.[key];
426
+ if (limit === undefined) return;
427
+ const count = await countAfter(overrides.ownerWorkspaceIds ?? [workspaceId]);
428
+ if (count > limit) {
429
+ throw new FeatureError('quota_exceeded', `quota « ${key} » reached`, {
430
+ key,
431
+ limit
432
+ });
433
+ }
363
434
  }
364
435
  },
365
436
  items: {
@@ -379,6 +450,11 @@ export function createTestContext<Repo = undefined>(
379
450
  }
380
451
  return Promise.resolve();
381
452
  },
453
+ canExtra(itemId, key) {
454
+ return Promise.resolve(
455
+ overrides.itemExtras?.[itemId]?.[key] ?? extras.canExtra(key)
456
+ );
457
+ },
382
458
  forget(itemId) {
383
459
  forgotten.push(itemId);
384
460
  return Promise.resolve();
@@ -406,7 +482,7 @@ export function createTestContext<Repo = undefined>(
406
482
  isOwner,
407
483
  isAdmin: overrides.isAdmin ?? false,
408
484
  canWrite: overrides.canWrite ?? true,
409
- ...resolveExtras(overrides.manifest?.extraPermissions, isOwner, overrides.extras ?? {}),
485
+ ...extras,
410
486
  repo: overrides.repo as Repo,
411
487
  store: memoryStore(),
412
488
  cipher: (mode) =>
@@ -418,6 +494,21 @@ export function createTestContext<Repo = undefined>(
418
494
  sendSyncChunk: () => 0,
419
495
  syncChunkBuffered: () => 0
420
496
  },
497
+ domains: {
498
+ list: () => Promise.resolve(memoryDomains(overrides.domains ?? []).in(workspaceId)),
499
+ get: (id) =>
500
+ Promise.resolve(
501
+ memoryDomains(overrides.domains ?? [])
502
+ .in(workspaceId)
503
+ .find((d) => d.id === id) ?? null
504
+ ),
505
+ verified: () =>
506
+ Promise.resolve(
507
+ memoryDomains(overrides.domains ?? [])
508
+ .in(workspaceId)
509
+ .filter((d) => d.verified)
510
+ )
511
+ },
421
512
  providers: fakeProviders(overrides.providers ?? {}),
422
513
  audit: (entry) => {
423
514
  recorded.audits.push({ action: entry.action, description: entry.description });
@@ -452,6 +543,10 @@ export interface TestServiceOverrides<Repo> {
452
543
  workspaceIds?: readonly number[];
453
544
  /** Devices every workspace reveals. Default none. */
454
545
  devices?: readonly SdkDevice[];
546
+ /** The accounts `deps.accounts` knows. Default none. */
547
+ accounts?: readonly SdkAccount[];
548
+ /** The plan's limits `deps.quotaFor` applies, by YOUR quota key. Default none (unlimited). */
549
+ quotaLimits?: Record<string, number>;
455
550
  /** What `deveyeFor(...).notify.hasRoute` answers. Default true. */
456
551
  hasRoute?: boolean;
457
552
  /** What `deveyeFor(...).notify.send` resolves. Default true; recorded either way. */
@@ -462,6 +557,8 @@ export interface TestServiceOverrides<Repo> {
462
557
  origins?: { app: string; public: string };
463
558
  /** Instants `telemetry.snapshot` answers (matched within a second). Default none. */
464
559
  snapshots?: readonly SdkTelemetrySnapshot[];
560
+ /** The feature's domains, every workspace mixed. Default none. */
561
+ domains?: readonly SdkDomain[];
465
562
  /** The named contracts the host holds (`deps.providers.get(key)`). */
466
563
  providers?: Readonly<Record<string, unknown>>;
467
564
  }
@@ -481,6 +578,7 @@ export function createTestServiceDeps<Repo = undefined>(
481
578
  agentRequests: [],
482
579
  pinnedInstants: [],
483
580
  livePublishes: [],
581
+ accountChanges: [],
484
582
  tickers: [],
485
583
  liveChanges: [],
486
584
  liveTopicChanges: []
@@ -547,8 +645,36 @@ export function createTestServiceDeps<Repo = undefined>(
547
645
  },
548
646
  publish(workspaceId, event, payload) {
549
647
  recorded.livePublishes.push({ workspaceId, event, payload });
648
+ },
649
+ accountChanged(userId) {
650
+ recorded.accountChanges.push(userId);
550
651
  }
551
652
  },
653
+ quotaFor: () => ({
654
+ limit: (key) => Promise.resolve(overrides.quotaLimits?.[key] ?? null),
655
+ async assert(key, countAfter) {
656
+ const limit = overrides.quotaLimits?.[key];
657
+ if (limit === undefined) return;
658
+ if ((await countAfter(overrides.workspaceIds ?? [1])) > limit) {
659
+ throw new FeatureError('quota_exceeded', `quota « ${key} » reached`, {
660
+ key,
661
+ limit
662
+ });
663
+ }
664
+ }
665
+ }),
666
+ accounts: {
667
+ find: (userId) =>
668
+ Promise.resolve((overrides.accounts ?? []).find((a) => a.id === userId) ?? null),
669
+ findByEmail: (email) =>
670
+ Promise.resolve(
671
+ (overrides.accounts ?? []).find(
672
+ (a) => a.email === email.trim().toLowerCase()
673
+ ) ?? null
674
+ ),
675
+ list: (userIds) =>
676
+ Promise.resolve((overrides.accounts ?? []).filter((a) => userIds.includes(a.id)))
677
+ },
552
678
  audit: (entry) => {
553
679
  recorded.audits.push({ action: entry.action, description: entry.description });
554
680
  },
@@ -564,6 +690,22 @@ export function createTestServiceDeps<Repo = undefined>(
564
690
  openBytes: (sealed) => sealedBytes.get(sealed) ?? null,
565
691
  derive: fakeDerive
566
692
  },
693
+ domains: {
694
+ findByHost: (host) =>
695
+ Promise.resolve(memoryDomains(overrides.domains ?? []).byHost(host)),
696
+ get: (workspaceId, id) =>
697
+ Promise.resolve(
698
+ memoryDomains(overrides.domains ?? [])
699
+ .in(workspaceId)
700
+ .find((d) => d.id === id) ?? null
701
+ ),
702
+ listVerified: (workspaceId) =>
703
+ Promise.resolve(
704
+ memoryDomains(overrides.domains ?? [])
705
+ .in(workspaceId)
706
+ .filter((d) => d.verified)
707
+ )
708
+ },
567
709
  providers: fakeProviders(overrides.providers ?? {}),
568
710
  createTicker({ intervalMs, tick }) {
569
711
  recorded.tickers.push({ intervalMs, tick });
@@ -572,3 +714,51 @@ export function createTestServiceDeps<Repo = undefined>(
572
714
  logger: silentLogger
573
715
  };
574
716
  }
717
+
718
+ /** A domain row for a test, verified by default. */
719
+ export function testDomain(over: Partial<SdkDomain> & { id: number; host: string }): SdkDomain {
720
+ return { workspaceId: 1, token: 'a'.repeat(32), verified: true, verifiedAt: 1, ...over };
721
+ }
722
+
723
+ /**
724
+ * What the `domains` hooks of a server entry receive, in memory: identity
725
+ * cipher, one store per workspace, and lookups that find nothing unless `dns`
726
+ * says otherwise.
727
+ */
728
+ export function createTestDomainsContext<Repo = undefined>(
729
+ overrides: {
730
+ repo?: Repo;
731
+ dns?: Partial<SdkDns>;
732
+ origins?: { app: string; public: string };
733
+ } = {}
734
+ ): FeatureDomainsContext<Repo> {
735
+ const stores = new Map<number, TestFeatureStore>();
736
+ const sealedBytes = new Map<string, Uint8Array>();
737
+ return {
738
+ repo: overrides.repo as Repo,
739
+ origins: overrides.origins ?? {
740
+ app: 'https://deveye.test',
741
+ public: 'https://public.deveye.test'
742
+ },
743
+ cipherFor: () => identityCipher,
744
+ storeFor(workspaceId) {
745
+ let store = stores.get(workspaceId);
746
+ if (!store) {
747
+ store = memoryStore();
748
+ stores.set(workspaceId, store);
749
+ }
750
+ return store;
751
+ },
752
+ keys: {
753
+ sealBytes: (plain) => {
754
+ const handle = `sealed:${sealedBytes.size}`;
755
+ sealedBytes.set(handle, Uint8Array.from(plain));
756
+ return handle;
757
+ },
758
+ openBytes: (sealed) => sealedBytes.get(sealed) ?? null,
759
+ derive: fakeDerive
760
+ },
761
+ dns: { ...emptyDns, ...overrides.dns },
762
+ logger: silentLogger
763
+ };
764
+ }