@agentshouse/app-bridge 0.1.0-alpha.9 → 0.1.0-c094380be07ea

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 (69) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +21 -79
  3. package/dist/calls.d.ts +117 -0
  4. package/dist/calls.js +1 -0
  5. package/dist/index.d.ts +152 -0
  6. package/dist/index.js +1 -0
  7. package/dist/mdmodel/blocks.d.ts +10 -0
  8. package/dist/mdmodel/condition.d.ts +149 -0
  9. package/dist/mdmodel/definition.d.ts +65 -0
  10. package/dist/mdmodel/divide.d.ts +2 -0
  11. package/dist/mdmodel/document.d.ts +15 -0
  12. package/dist/mdmodel/fields.d.ts +5 -0
  13. package/dist/mdmodel/index.d.ts +18 -0
  14. package/dist/mdmodel/paths.d.ts +17 -0
  15. package/dist/mdmodel/profile.d.ts +5 -0
  16. package/dist/mdmodel/project.d.ts +20 -0
  17. package/dist/mdmodel/references.d.ts +3 -0
  18. package/dist/mdmodel/types.d.ts +143 -0
  19. package/dist/mdmodel/validate.d.ts +7 -0
  20. package/dist/mdmodel/version.d.ts +1 -0
  21. package/dist/mdmodel/yaml.d.ts +55 -0
  22. package/dist/mdruntime/acquisition.d.ts +13 -0
  23. package/dist/mdruntime/adapter.d.ts +477 -0
  24. package/dist/mdruntime/binary.d.ts +22 -0
  25. package/dist/mdruntime/change-set.d.ts +34 -0
  26. package/dist/mdruntime/change.d.ts +88 -0
  27. package/dist/mdruntime/client.d.ts +81 -0
  28. package/dist/mdruntime/collection.d.ts +38 -0
  29. package/dist/mdruntime/connection.d.ts +138 -0
  30. package/dist/mdruntime/conversation.d.ts +103 -0
  31. package/dist/mdruntime/durability.d.ts +14 -0
  32. package/dist/mdruntime/failure.d.ts +12 -0
  33. package/dist/mdruntime/file.d.ts +19 -0
  34. package/dist/mdruntime/model.d.ts +56 -0
  35. package/dist/mdruntime/observation.d.ts +29 -0
  36. package/dist/mdruntime/open.d.ts +1 -0
  37. package/dist/mdruntime/outcome.d.ts +46 -0
  38. package/dist/mdruntime/overlay.d.ts +26 -0
  39. package/dist/mdruntime/query.d.ts +246 -0
  40. package/dist/mdruntime/reach.d.ts +45 -0
  41. package/dist/mdruntime/readiness.d.ts +52 -0
  42. package/dist/mdruntime/recovery.d.ts +24 -0
  43. package/dist/mdruntime/replica.d.ts +45 -0
  44. package/dist/mdruntime/room-draft.d.ts +143 -0
  45. package/dist/mdruntime/rows.d.ts +36 -0
  46. package/dist/mdruntime/save.d.ts +63 -0
  47. package/dist/mdruntime/search.d.ts +83 -0
  48. package/dist/mdruntime/shared.d.ts +10 -0
  49. package/dist/mdruntime/status.d.ts +26 -0
  50. package/dist/mdruntime/store.d.ts +159 -0
  51. package/dist/mdruntime/transfer.d.ts +9 -0
  52. package/dist/mdruntime/turn.d.ts +6 -0
  53. package/dist/mdruntime/wire.d.ts +104 -0
  54. package/dist/test-host.d.ts +33 -0
  55. package/dist/test-host.js +200 -0
  56. package/docs/families.md +136 -0
  57. package/package.json +11 -14
  58. package/client/src/bridge.d.ts +0 -35
  59. package/client/src/bridge.js +0 -229
  60. package/client/src/index.d.ts +0 -3
  61. package/client/src/index.js +0 -2
  62. package/client/src/test-host.d.ts +0 -30
  63. package/client/src/test-host.js +0 -159
  64. package/client/src/wire.d.ts +0 -69
  65. package/client/src/wire.js +0 -1
  66. package/src/apps/remainder.d.ts +0 -2
  67. package/src/apps/remainder.js +0 -16
  68. package/src/apps/tab.d.ts +0 -6
  69. package/src/apps/tab.js +0 -27
@@ -0,0 +1,83 @@
1
+ import type { ChangeSet } from './change-set.js';
2
+ import { type CoveredRoom, type Filter, type PendingRoom } from './query.js';
3
+ import type { Open } from './open.js';
4
+ export type DocumentPart = Open<'fields' | 'sections' | 'preamble' | 'path'>;
5
+ export type SearchRequest = {
6
+ text: string;
7
+ documents?: Filter;
8
+ conversations?: readonly string[];
9
+ limit?: number;
10
+ };
11
+ export type DocumentHit = {
12
+ room: string;
13
+ path: string;
14
+ type: string;
15
+ score: number;
16
+ matches: Readonly<Record<string, readonly DocumentPart[]>>;
17
+ };
18
+ export type MessageHit = {
19
+ conversation: string;
20
+ identity: string;
21
+ score: number;
22
+ matches: Readonly<Record<string, readonly Open<'text'>[]>>;
23
+ };
24
+ export type SearchCoverage = {
25
+ rooms: readonly CoveredRoom[];
26
+ conversations: readonly string[];
27
+ index: string;
28
+ overlay: readonly string[];
29
+ };
30
+ export type PendingConversation = {
31
+ conversation: string;
32
+ awaits: 'index';
33
+ };
34
+ export type SearchPending = {
35
+ pending: readonly (PendingRoom | PendingConversation)[];
36
+ };
37
+ export type SearchHits = {
38
+ documents: readonly DocumentHit[];
39
+ messages: readonly MessageHit[];
40
+ };
41
+ export type SearchResult = (SearchHits & {
42
+ coverage: SearchCoverage;
43
+ }) | SearchPending;
44
+ export type SearchedDocument = {
45
+ room: string;
46
+ path: string;
47
+ type: string;
48
+ fields: Readonly<Record<string, unknown>>;
49
+ preamble: string;
50
+ sections: Readonly<Record<string, string>>;
51
+ };
52
+ export type SearchedMessage = {
53
+ conversation: string;
54
+ identity: string;
55
+ text: string;
56
+ };
57
+ export type SearchSource = {
58
+ room(room: string): readonly string[];
59
+ document(room: string, path: string): SearchedDocument | null;
60
+ };
61
+ export type SearchPlan = {
62
+ text: string;
63
+ documents: unknown;
64
+ conversations: readonly string[] | null;
65
+ limit: number | null;
66
+ };
67
+ export type SearchIndex = {
68
+ generation(): string;
69
+ rooms(): ReadonlySet<string>;
70
+ conversations(): ReadonlySet<string>;
71
+ indexRoom(room: string): Promise<void>;
72
+ indexMessages(conversation: string, messages: readonly SearchedMessage[], whole: boolean): void;
73
+ forget(rooms: readonly string[]): void;
74
+ changed(set: ChangeSet): void;
75
+ changes(): number;
76
+ caughtUp(): Promise<void>;
77
+ search(plan: SearchPlan, documents: readonly {
78
+ room: string;
79
+ path: string;
80
+ }[] | null, conversations: readonly string[]): SearchHits;
81
+ };
82
+ export declare function searchPlanOf(input: unknown): SearchPlan;
83
+ export declare function createSearchIndex(source: SearchSource): SearchIndex;
@@ -0,0 +1,10 @@
1
+ export type Paths<V> = Readonly<Record<string, V>>;
2
+ type Weigh<V> = (key: string, value: V) => number;
3
+ export declare function shared<V>(map: Paths<V>): Paths<V>;
4
+ export declare function patched<V>(base: Paths<V>, set: Iterable<readonly [string, V]>, removed?: Iterable<string>): Paths<V>;
5
+ export declare function tally<V>(map: Paths<V>, weigh: Weigh<V>): number;
6
+ export declare function sizeOf<V>(map: Paths<V>): number;
7
+ export declare function differing<V>(left: Paths<V>, right: Paths<V>, same?: (left: V, right: V) => boolean): ReadonlySet<string>;
8
+ export declare function drafted<V>(base: Paths<V>): Record<string, V>;
9
+ export declare function settled<V>(draft: Record<string, V>): Paths<V>;
10
+ export {};
@@ -0,0 +1,26 @@
1
+ import type { Open } from './open.js';
2
+ import type { ProviderRefusal } from './adapter.js';
3
+ import type { ReturnReason } from './room-draft.js';
4
+ export type AttentionEntry = {
5
+ room: string;
6
+ path: string;
7
+ returned: ReturnReason;
8
+ } | {
9
+ room: string;
10
+ refusal: ProviderRefusal;
11
+ };
12
+ export type SyncStatus = {
13
+ state: Open<'pending' | 'syncing' | 'synced'>;
14
+ lastCompleted: string | null;
15
+ providerUnreachable: boolean;
16
+ attentionRequired: readonly AttentionEntry[];
17
+ reset: string | null;
18
+ };
19
+ export type CycleProgress = {
20
+ complete: boolean;
21
+ reachable: boolean;
22
+ };
23
+ export declare const STARTING: SyncStatus;
24
+ export declare function transferring(status: SyncStatus): SyncStatus;
25
+ export declare function saving(status: SyncStatus): SyncStatus;
26
+ export declare function same(one: SyncStatus, other: SyncStatus): boolean;
@@ -0,0 +1,159 @@
1
+ import type { ModelState } from './model.js';
2
+ import type { Capability, HeadChange, Member, OperationScopes, ProviderLimit, ReplicaAdmission, TypedSelection } from './adapter.js';
3
+ import type { AcceptedMessage, KeptReceipt } from './adapter.js';
4
+ import type { ChangeBatch } from './change.js';
5
+ import { type HeldBinary } from './overlay.js';
6
+ import type { ChatDraftFile } from './file.js';
7
+ import type { Submission } from './outcome.js';
8
+ import type { RoomDraftRecord, SavedDraft } from './room-draft.js';
9
+ export declare const STORE_SCHEMA = 25;
10
+ export declare const AUTHORED_SCHEMA = 2;
11
+ export type ReplicaRecord = {
12
+ locator: string;
13
+ name: string;
14
+ handle: string;
15
+ operations: OperationScopes;
16
+ replica: ReplicaAdmission;
17
+ model: ModelState;
18
+ typedSelection: TypedSelection | null;
19
+ selectionModel: ModelState;
20
+ providerOwnedPaths: readonly string[];
21
+ roomVersion: string;
22
+ transfer: string;
23
+ documents: Readonly<Record<string, string>>;
24
+ binaries: Readonly<Record<string, HeldBinary>>;
25
+ revisions: Readonly<Record<string, string>>;
26
+ changes: Readonly<Record<string, HeadChange>>;
27
+ written: Readonly<Record<string, string>>;
28
+ };
29
+ export type StagedLayer = Pick<ReplicaRecord, 'documents' | 'binaries' | 'revisions' | 'changes' | 'written'>;
30
+ export type TransferRecord = {
31
+ locator: string;
32
+ transfer: string;
33
+ selection: string;
34
+ from: string;
35
+ last: string;
36
+ pageToken: string | null;
37
+ models: {
38
+ collection: ModelState;
39
+ selection: ModelState;
40
+ };
41
+ };
42
+ export type PendingState = {
43
+ readonly drafts: readonly SavedDraft[];
44
+ readonly submission: Submission;
45
+ readonly lost: boolean;
46
+ readonly upload?: unknown;
47
+ readonly accepted?: string;
48
+ };
49
+ export type TargetRecord = {
50
+ established: boolean;
51
+ search: boolean;
52
+ };
53
+ export type QueueRecord = {
54
+ locator: string;
55
+ pending: readonly {
56
+ batch: ChangeBatch;
57
+ state: PendingState;
58
+ }[];
59
+ };
60
+ export type PresentationRecord = {
61
+ app: string;
62
+ value: unknown;
63
+ };
64
+ export type HeldConversation = {
65
+ conversation: string;
66
+ read: string | null | undefined;
67
+ partial: boolean;
68
+ };
69
+ export type ConversationWrite = {
70
+ conversation: string;
71
+ messages: readonly AcceptedMessage[];
72
+ read?: {
73
+ at: string | null;
74
+ partial: boolean;
75
+ };
76
+ };
77
+ export type ChatSubmission = {
78
+ readonly operation: string;
79
+ readonly text: string;
80
+ readonly files: readonly ChatDraftFile[];
81
+ readonly turn: string | null;
82
+ };
83
+ export type ChatDraftRecord = {
84
+ conversation: string;
85
+ text: string;
86
+ files: readonly ChatDraftFile[];
87
+ revision: string;
88
+ submitted?: readonly ChatSubmission[];
89
+ };
90
+ export type RecordWrite = {
91
+ next: ReplicaRecord;
92
+ previous: ReplicaRecord | null;
93
+ stored?: StagedLayer;
94
+ };
95
+ export type AuthoredWrite = {
96
+ locator: string;
97
+ queue: readonly ChangeBatch[];
98
+ saved?: ReadonlyMap<string, readonly SavedDraft[]>;
99
+ roomDrafts?: readonly RoomDraftRecord[];
100
+ consumedRoomDrafts?: readonly string[];
101
+ };
102
+ export type RuntimeStore = {
103
+ all(): Promise<readonly ReplicaRecord[]>;
104
+ keepAuthored(input: AuthoredWrite): Promise<void>;
105
+ write(input: RecordWrite): Promise<void>;
106
+ revokeModels(records: readonly ReplicaRecord[]): Promise<void>;
107
+ lastCompleted(): Promise<string | null>;
108
+ complete(at: string): Promise<void>;
109
+ providerLimits(): Promise<readonly ProviderLimit[]>;
110
+ capabilities(): Promise<readonly Capability[]>;
111
+ declare(limits: readonly ProviderLimit[], capabilities: readonly Capability[]): Promise<void>;
112
+ member(): Promise<Member | null>;
113
+ keepMember(member: Member | null): Promise<void>;
114
+ targets(): Promise<Readonly<Record<string, TargetRecord>>>;
115
+ keepTargets(targets: Readonly<Record<string, TargetRecord>>): Promise<void>;
116
+ queues(): Promise<readonly QueueRecord[]>;
117
+ submit(locator: string, id: string, submission: Submission, lost: boolean): Promise<void>;
118
+ accept(locator: string, id: string, roomVersion: string): Promise<void>;
119
+ keepUpload(locator: string, id: string, upload: unknown): Promise<void>;
120
+ roomDrafts(): Promise<readonly RoomDraftRecord[]>;
121
+ presentation(): Promise<readonly PresentationRecord[]>;
122
+ present(record: PresentationRecord): Promise<void>;
123
+ conversations(): Promise<readonly HeldConversation[]>;
124
+ keepMessages(write: ConversationWrite): Promise<void>;
125
+ messageWindow(conversation: string, limit: number | undefined): Promise<AcceptedMessage[]>;
126
+ messagesAfter(conversation: string, identity: string | null): Promise<AcceptedMessage[]>;
127
+ messageIdentities(conversation: string): Promise<readonly string[]>;
128
+ turnArrived(conversation: string, turn: string): Promise<boolean>;
129
+ dropConversations(conversations: readonly string[]): Promise<void>;
130
+ chatDrafts(): Promise<readonly ChatDraftRecord[]>;
131
+ keepChatDraft(record: ChatDraftRecord): Promise<void>;
132
+ dropChatDraft(conversation: string): Promise<void>;
133
+ keepRoomDraft(record: RoomDraftRecord): Promise<void>;
134
+ discardRoomDraft(locator: string, path: string): Promise<void>;
135
+ fences(): Promise<readonly string[]>;
136
+ erase(locators: readonly string[]): Promise<void>;
137
+ discard(locator: string): Promise<void>;
138
+ transfers(): Promise<readonly TransferRecord[]>;
139
+ staged(record: TransferRecord): Promise<StagedLayer>;
140
+ stage(record: TransferRecord, page: StagedLayer): Promise<void>;
141
+ abandon(locator: string): Promise<void>;
142
+ receivedHeads(): Promise<readonly KeptReceipt[]>;
143
+ receivedParts(key: string, count: number): Promise<readonly unknown[]>;
144
+ keepReceived(key: string, head: unknown, part?: {
145
+ index: number;
146
+ value: unknown;
147
+ }): Promise<void>;
148
+ dropReceived(keys: readonly string[]): Promise<void>;
149
+ generation(): Promise<string | null>;
150
+ rememberGeneration(value: string): Promise<void>;
151
+ close(): void;
152
+ };
153
+ export declare function authoredHolder(): Promise<string | null>;
154
+ export declare function authoredBy(holder: string): Promise<boolean>;
155
+ export declare function authoredBinding(): Promise<string | null>;
156
+ export declare function bindAuthored(binding: string): Promise<void>;
157
+ export declare function removeRuntimeStore(holder?: string): Promise<boolean>;
158
+ export declare function openDatabase(name: string, version: number, upgrade: (opening: IDBOpenDBRequest, oldVersion: number) => void): Promise<IDBDatabase>;
159
+ export declare function openRuntimeStore(fenced: (locator: string) => boolean): Promise<RuntimeStore>;
@@ -0,0 +1,9 @@
1
+ import type { Refusal } from '../mdmodel/index.js';
2
+ export type Unconfirmed = {
3
+ kind: 'unconfirmed';
4
+ };
5
+ export type Refused = {
6
+ kind: 'refused';
7
+ refusal: Refusal;
8
+ };
9
+ export declare const unconfirmed: Unconfirmed;
@@ -0,0 +1,6 @@
1
+ export declare function yielded(): Promise<void>;
2
+ export declare const ROW_WEIGHT = 256;
3
+ export type Later<T> = T | Promise<T>;
4
+ export declare function after<T, R>(value: Later<T>, next: (value: T) => R): Later<R>;
5
+ export declare function inUnits<T>(items: Iterable<T>, each: (item: T) => number): Later<void>;
6
+ export declare function inChunks<T>(items: readonly T[], weigh: (item: T) => number, each: (chunk: readonly T[]) => void): Promise<void>;
@@ -0,0 +1,104 @@
1
+ import type { ConnectionRefusal } from './connection.js';
2
+ import type { Described } from './failure.js';
3
+ export type RuntimePort = {
4
+ postMessage(message: unknown): void;
5
+ addEventListener(type: 'message' | 'close', listener: (event: {
6
+ data?: unknown;
7
+ }) => void): void;
8
+ start(): void;
9
+ };
10
+ export type WireReach = 'within' | 'app' | 'runtime' | 'actions' | 'whole';
11
+ declare const MEMBERS: {
12
+ readonly rooms: 'within';
13
+ readonly query: 'within';
14
+ readonly search: 'within';
15
+ readonly types: 'within';
16
+ readonly save: 'within';
17
+ readonly history: 'within';
18
+ readonly 'binaryFile.read': 'within';
19
+ readonly 'binaryFile.readReference': 'within';
20
+ readonly call: 'actions';
21
+ readonly reached: 'within';
22
+ readonly log: 'whole';
23
+ readonly persistence: 'runtime';
24
+ readonly retry: 'runtime';
25
+ readonly reauthorize: 'runtime';
26
+ readonly 'roomDraft.list': 'within';
27
+ readonly 'roomDraft.read': 'within';
28
+ readonly 'roomDraft.write': 'within';
29
+ readonly 'roomDraft.discard': 'within';
30
+ readonly 'presentation.read': 'app';
31
+ readonly 'presentation.write': 'app';
32
+ readonly 'conversation.list': 'within';
33
+ readonly 'conversation.read': 'within';
34
+ readonly 'conversation.create': 'within';
35
+ readonly 'conversation.send': 'within';
36
+ readonly 'conversation.answer': 'within';
37
+ readonly 'conversation.interrupt': 'within';
38
+ readonly 'conversation.kill': 'within';
39
+ readonly 'conversation.cancel': 'within';
40
+ readonly 'conversation.delete': 'within';
41
+ readonly 'chatDraft.write': 'within';
42
+ readonly 'chatDraft.discard': 'within';
43
+ };
44
+ declare const TOPICS: {
45
+ readonly rooms: 'within';
46
+ readonly readiness: 'within';
47
+ readonly 'connection-refusal': 'runtime';
48
+ readonly 'storage-loss': 'runtime';
49
+ readonly 'deployment-facts': 'runtime';
50
+ readonly 'sync-status': 'within';
51
+ readonly 'service-mode': 'runtime';
52
+ readonly member: 'runtime';
53
+ readonly query: 'within';
54
+ readonly queue: 'within';
55
+ readonly 'room-drafts': 'within';
56
+ readonly presentation: 'app';
57
+ readonly conversation: 'within';
58
+ readonly conversations: 'within';
59
+ readonly agents: 'within';
60
+ };
61
+ export declare const WIRE_REACH: {
62
+ readonly members: Readonly<Record<string, WireReach>>;
63
+ readonly topics: Readonly<Record<string, WireReach>>;
64
+ };
65
+ export type WireMember = keyof typeof MEMBERS;
66
+ export type WireTopic = keyof typeof TOPICS;
67
+ export type WireRequest = {
68
+ kind: 'hello';
69
+ } | {
70
+ kind: 'call';
71
+ id: number;
72
+ member: WireMember;
73
+ input: readonly unknown[];
74
+ } | {
75
+ kind: 'observe';
76
+ id: number;
77
+ topic: WireTopic;
78
+ input: readonly unknown[];
79
+ } | {
80
+ kind: 'stop';
81
+ id: number;
82
+ };
83
+ export type WireAnswer = {
84
+ kind: 'result';
85
+ id: number;
86
+ value: unknown;
87
+ } | ({
88
+ kind: 'failure';
89
+ id: number;
90
+ } & Described) | {
91
+ kind: 'event';
92
+ id: number;
93
+ value: unknown;
94
+ } | {
95
+ kind: 'refusal';
96
+ refusal: ConnectionRefusal;
97
+ } | {
98
+ kind: 'ended';
99
+ };
100
+ export declare const AUTHORIZATION_ENDED = "the host authorization ended";
101
+ export declare const PORT_CLOSED = "the port closed";
102
+ export declare function request(message: unknown): WireRequest | null;
103
+ export declare function answer(message: unknown): WireAnswer | null;
104
+ export {};
@@ -0,0 +1,33 @@
1
+ import type { MdRuntimeClient } from './mdruntime/client.js';
2
+ import type { HouseActivation, HouseAnalyticsChoice, HouseAppMessage, HouseExternalAnswer, HouseExternalRequest, HouseNavigationMode, HouseRefusal, HouseSourceDownload, HouseSourceTop, HouseStatus, HouseTab, HouseTask } from './index.js';
3
+ export interface HouseBridgeNavigation {
4
+ readonly mode: HouseNavigationMode;
5
+ readonly address: string;
6
+ }
7
+ export interface HouseBridgeTestHost {
8
+ readonly navigations: readonly HouseBridgeNavigation[];
9
+ readonly ceremonies: readonly string[];
10
+ readonly consents: readonly HouseAnalyticsChoice[];
11
+ readonly tabs: readonly HouseTab[];
12
+ readonly externalCalls: readonly HouseExternalRequest[];
13
+ address(): string;
14
+ open(address: string): void;
15
+ publish(status: HouseStatus): void;
16
+ message(message: HouseAppMessage): void;
17
+ attachRuntime(runtime: MdRuntimeClient): void;
18
+ checkpoint(): Promise<HouseTask>;
19
+ restore(task: HouseTask | null): Promise<boolean>;
20
+ settle(activation: HouseActivation): void;
21
+ }
22
+ export interface HouseBridgeTestHostOptions {
23
+ readonly address?: string;
24
+ readonly status?: HouseStatus;
25
+ readonly sources?: readonly {
26
+ readonly top: HouseSourceTop;
27
+ readonly download: HouseSourceDownload;
28
+ }[];
29
+ readonly screenshots?: Readonly<Record<string, Blob>>;
30
+ readonly siteScreenshots?: Readonly<Record<string, Blob>>;
31
+ readonly external?: (request: HouseExternalRequest) => HouseExternalAnswer | HouseRefusal | null | Promise<HouseExternalAnswer | HouseRefusal | null>;
32
+ }
33
+ export declare function createHouseBridgeTestHost(options?: HouseBridgeTestHostOptions): HouseBridgeTestHost;
@@ -0,0 +1,200 @@
1
+ const HOST_ORIGIN = 'https://house.invalid';
2
+ const ADDRESS_MAX_CHARS = 64 * 1024;
3
+ function sameOriginPath(value) {
4
+ if (typeof value !== 'string')
5
+ return null;
6
+ if (value.charAt(0) !== '/' || value.slice(0, 2) === '//')
7
+ return null;
8
+ if (value.length > ADDRESS_MAX_CHARS)
9
+ return null;
10
+ const target = new URL(value, HOST_ORIGIN);
11
+ return target.origin === HOST_ORIGIN ? `${target.pathname}${target.search}${target.hash}` : null;
12
+ }
13
+ function appAddress(address) {
14
+ return address.startsWith('/') ? address : `/${address}`;
15
+ }
16
+ function ceremonyRefused(path) {
17
+ return Object.assign(new Error('house_ceremony_refused'), {
18
+ name: 'HouseCeremonyRefused',
19
+ code: 'house_ceremony_refused',
20
+ retryable: false,
21
+ path,
22
+ });
23
+ }
24
+ function navigationRefused(address) {
25
+ return Object.assign(new Error('house_navigation_refused'), {
26
+ name: 'HouseNavigationRefused',
27
+ code: 'house_navigation_refused',
28
+ retryable: false,
29
+ address,
30
+ });
31
+ }
32
+ function followHeld(listeners, listener, held) {
33
+ let following = true;
34
+ queueMicrotask(() => {
35
+ if (!following)
36
+ return;
37
+ listeners.add(listener);
38
+ const value = held();
39
+ if (value !== null)
40
+ listener(value);
41
+ });
42
+ return () => {
43
+ following = false;
44
+ listeners.delete(listener);
45
+ };
46
+ }
47
+ export function createHouseBridgeTestHost(options = {}) {
48
+ const navigations = [];
49
+ const ceremonies = [];
50
+ const consents = [];
51
+ const tabs = [];
52
+ const externalCalls = [];
53
+ const addressListeners = new Set();
54
+ const statusListeners = new Set();
55
+ const messageListeners = new Set();
56
+ let current = appAddress(options.address ?? '/');
57
+ let published = options.status ?? null;
58
+ let shown = null;
59
+ let seen = null;
60
+ let cooperation = null;
61
+ let attached = () => { };
62
+ const runtime = new Promise((resolve) => {
63
+ attached = resolve;
64
+ });
65
+ function arrive(target) {
66
+ current = target;
67
+ queueMicrotask(() => {
68
+ shown = target;
69
+ for (const listener of addressListeners)
70
+ listener(target);
71
+ });
72
+ }
73
+ function publish(next) {
74
+ published = next;
75
+ queueMicrotask(() => {
76
+ seen = next;
77
+ for (const listener of statusListeners)
78
+ listener(next);
79
+ });
80
+ }
81
+ function navigate(mode, asked) {
82
+ let path = asked;
83
+ if (/^https?:\/\//i.test(asked)) {
84
+ try {
85
+ const target = new URL(asked);
86
+ path = target.origin === HOST_ORIGIN ? target.pathname + target.search + target.hash : '';
87
+ }
88
+ catch {
89
+ path = '';
90
+ }
91
+ }
92
+ const target = sameOriginPath(path);
93
+ if (target === null)
94
+ return Promise.reject(navigationRefused(asked));
95
+ navigations.push({ mode, address: target });
96
+ arrive(target);
97
+ return new Promise((resolve) => {
98
+ queueMicrotask(() => resolve(target));
99
+ });
100
+ }
101
+ const bridge = {
102
+ runtime,
103
+ address: () => shown,
104
+ onAddress(listener) {
105
+ return followHeld(addressListeners, listener, () => shown);
106
+ },
107
+ push: (asked) => navigate('push', asked),
108
+ replace: (asked) => navigate('replace', asked),
109
+ ceremony(path) {
110
+ const target = sameOriginPath(path);
111
+ if (target === null)
112
+ return Promise.reject(ceremonyRefused(path));
113
+ ceremonies.push(target);
114
+ return new Promise(() => { });
115
+ },
116
+ install: () => Promise.resolve('manual'),
117
+ notifications: () => Promise.resolve('unavailable'),
118
+ setBadge: () => Promise.resolve(),
119
+ setTab(tab) {
120
+ tabs.push(tab);
121
+ },
122
+ sourceTop: (app) => Promise.resolve(options.sources?.find((entry) => entry.top.app_ref === app)?.top ?? null),
123
+ sourceDownload: (app) => Promise.resolve(options.sources?.find((entry) => entry.top.app_ref === app)?.download ?? null),
124
+ callExternal(request) {
125
+ externalCalls.push(request);
126
+ return Promise.resolve(options.external?.(request) ?? null);
127
+ },
128
+ readScreenshot: (app) => Promise.resolve(options.screenshots?.[app] ?? null),
129
+ readSiteScreenshot: (site) => Promise.resolve(options.siteScreenshots?.[site] ?? null),
130
+ status: () => seen,
131
+ onStatus(listener) {
132
+ return followHeld(statusListeners, listener, () => seen);
133
+ },
134
+ messages(listener) {
135
+ messageListeners.add(listener);
136
+ return () => {
137
+ messageListeners.delete(listener);
138
+ };
139
+ },
140
+ analyticsConsent(choice) {
141
+ if (published === null || !published.analytics.measures)
142
+ return;
143
+ if (choice !== 'accept' && choice !== 'decline')
144
+ return;
145
+ consents.push(choice);
146
+ publish({ ...published, analytics: { measures: true, choice } });
147
+ },
148
+ cooperate(given) {
149
+ cooperation = given;
150
+ return () => {
151
+ if (cooperation === given)
152
+ cooperation = null;
153
+ };
154
+ },
155
+ };
156
+ function cooperating() {
157
+ if (cooperation === null)
158
+ throw new Error('the App registered no cooperation');
159
+ return cooperation;
160
+ }
161
+ Object.defineProperty(globalThis, 'houseBridge', { value: bridge, configurable: true });
162
+ if (published !== null)
163
+ publish(published);
164
+ arrive(current);
165
+ return {
166
+ navigations,
167
+ ceremonies,
168
+ consents,
169
+ tabs,
170
+ externalCalls,
171
+ address: () => current,
172
+ open(asked) {
173
+ arrive(appAddress(asked));
174
+ },
175
+ publish,
176
+ message({ from, body }) {
177
+ queueMicrotask(() => {
178
+ for (const listener of messageListeners)
179
+ listener({ from, body });
180
+ });
181
+ },
182
+ attachRuntime(client) {
183
+ attached(client);
184
+ },
185
+ async checkpoint() {
186
+ const held = cooperating();
187
+ await held.checkpoint();
188
+ await held.persist();
189
+ return JSON.parse(JSON.stringify((await held.capture()) ?? null));
190
+ },
191
+ async restore(task) {
192
+ const held = cooperating();
193
+ await held.restore(task);
194
+ return (await held.ready()) === true;
195
+ },
196
+ settle(activation) {
197
+ cooperating().settle(activation);
198
+ },
199
+ };
200
+ }