@peers-app/peers-sdk 0.19.14 → 0.20.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 (59) hide show
  1. package/dist/contracts/__tests__/builder.test.js +24 -0
  2. package/dist/contracts/__tests__/contract-events.test.d.ts +1 -0
  3. package/dist/contracts/__tests__/contract-events.test.js +199 -0
  4. package/dist/contracts/__tests__/contract-observables.test.d.ts +1 -0
  5. package/dist/contracts/__tests__/contract-observables.test.js +290 -0
  6. package/dist/contracts/__tests__/contract-provider-router.test.d.ts +1 -0
  7. package/dist/contracts/__tests__/contract-provider-router.test.js +193 -0
  8. package/dist/contracts/__tests__/contract-proxy.test.d.ts +1 -0
  9. package/dist/contracts/__tests__/contract-proxy.test.js +424 -0
  10. package/dist/contracts/__tests__/contract-resolvers.test.d.ts +1 -0
  11. package/dist/contracts/__tests__/contract-resolvers.test.js +148 -0
  12. package/dist/contracts/__tests__/contract-subscription-lifecycle.test.d.ts +1 -0
  13. package/dist/contracts/__tests__/contract-subscription-lifecycle.test.js +353 -0
  14. package/dist/contracts/__tests__/contract-table-events.test.d.ts +1 -0
  15. package/dist/contracts/__tests__/contract-table-events.test.js +209 -0
  16. package/dist/contracts/__tests__/contract-transport.test.d.ts +1 -0
  17. package/dist/contracts/__tests__/contract-transport.test.js +163 -0
  18. package/dist/contracts/__tests__/persistent-registry.test.d.ts +1 -0
  19. package/dist/contracts/__tests__/persistent-registry.test.js +109 -0
  20. package/dist/contracts/__tests__/playground.test.d.ts +1 -0
  21. package/dist/contracts/__tests__/playground.test.js +213 -0
  22. package/dist/contracts/__tests__/validate.test.js +122 -0
  23. package/dist/contracts/builder.d.ts +9 -1
  24. package/dist/contracts/builder.js +13 -0
  25. package/dist/contracts/contract-provider-router.d.ts +72 -0
  26. package/dist/contracts/contract-provider-router.js +164 -0
  27. package/dist/contracts/contract-proxy.d.ts +333 -0
  28. package/dist/contracts/contract-proxy.js +663 -0
  29. package/dist/contracts/contract-resolvers.d.ts +66 -0
  30. package/dist/contracts/contract-resolvers.js +138 -0
  31. package/dist/contracts/contract-transport.d.ts +94 -0
  32. package/dist/contracts/contract-transport.js +159 -0
  33. package/dist/contracts/contracts.table.d.ts +1 -1
  34. package/dist/contracts/contracts.table.js +2 -2
  35. package/dist/contracts/index.d.ts +6 -1
  36. package/dist/contracts/index.js +25 -1
  37. package/dist/contracts/persistent-registry.js +3 -1
  38. package/dist/contracts/system/logs-contract.d.ts +24 -0
  39. package/dist/contracts/system/logs-contract.js +60 -0
  40. package/dist/contracts/types.d.ts +27 -4
  41. package/dist/contracts/validate.d.ts +2 -2
  42. package/dist/contracts/validate.js +44 -2
  43. package/dist/data/orm/decorators.d.ts +6 -0
  44. package/dist/data/orm/decorators.js +21 -0
  45. package/dist/data/user-trust-levels.d.ts +2 -0
  46. package/dist/data/user-trust-levels.js +2 -1
  47. package/dist/data/user-trust-levels.test.d.ts +1 -0
  48. package/dist/data/user-trust-levels.test.js +37 -0
  49. package/dist/device/binary-peer-connection-v2.d.ts +2 -0
  50. package/dist/device/binary-peer-connection-v2.js +12 -2
  51. package/dist/device/binary-peer-connection-v2.test.js +23 -0
  52. package/dist/device/get-trust-level-fn.d.ts +6 -0
  53. package/dist/device/get-trust-level-fn.js +12 -7
  54. package/dist/device/get-trust-level-fn.test.js +16 -2
  55. package/dist/logging/console-logs.table.d.ts +3 -0
  56. package/dist/logging/console-logs.table.js +2 -1
  57. package/dist/system-ids.d.ts +11 -0
  58. package/dist/system-ids.js +12 -1
  59. package/package.json +1 -1
@@ -0,0 +1,209 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const event_registry_1 = require("../../data/orm/event-registry");
4
+ const field_type_1 = require("../../types/field-type");
5
+ const utils_1 = require("../../utils");
6
+ const contract_proxy_1 = require("../contract-proxy");
7
+ const contract_transport_1 = require("../contract-transport");
8
+ /** Contract-member name of the single table under test. */
9
+ const TABLE_NAME = "Widgets";
10
+ /** Flush pending micro/macrotasks so fire-and-forget subscribe requests land. */
11
+ const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
12
+ /** Build a `dataChanged` payload matching the real `Table.dataChanged` shape. */
13
+ const mkEvent = (id, op = "insert") => ({ dataObject: { id }, op, source: "local" });
14
+ /** A minimal contract that declares exactly one table (no generic events). */
15
+ function makeContract(contractId) {
16
+ return {
17
+ contractId,
18
+ version: 1,
19
+ devTag: "dev",
20
+ name: "Table Events Test Contract",
21
+ description: "For contract table dataChanged proxy tests",
22
+ tables: [
23
+ {
24
+ name: TABLE_NAME,
25
+ description: "Widgets",
26
+ primaryKeyName: "id",
27
+ fields: [{ name: "id", type: field_type_1.FieldType.id, description: "ID" }],
28
+ },
29
+ ],
30
+ tools: [],
31
+ observables: [],
32
+ events: [],
33
+ };
34
+ }
35
+ /**
36
+ * Wire a consumer to a provider session over an in-process transport pair. The provider
37
+ * "table" is a fake exposing a `save` method plus `dataChanged: emitter.event`, mirroring
38
+ * the real {@link Table.dataChanged}. The emitter is built through an {@link EventRegistry}
39
+ * scoped by a unique `dataContextId`, so the actual `${tableName}_DataChanged_${dataContextId}`
40
+ * name path drives delivery (proves dataContext scoping) and never collides across tests.
41
+ */
42
+ function wire(opts = {}) {
43
+ const contractId = (0, utils_1.newid)();
44
+ const dataContextId = (0, utils_1.newid)();
45
+ const registry = new event_registry_1.EventRegistry(dataContextId);
46
+ const emitter = registry.getEmitter(`${TABLE_NAME}_DataChanged`);
47
+ const save = jest.fn(async (record) => record);
48
+ const table = { dataChanged: emitter.event, save };
49
+ const resolution = {
50
+ contractId,
51
+ version: 1,
52
+ // Fake table stands in for a real Table<Widget>; the session only touches
53
+ // `dataChanged` (an Event) and dispatched method names.
54
+ tables: { [TABLE_NAME]: table },
55
+ };
56
+ const [consumerTransport, providerTransport] = (0, contract_transport_1.inProcessTransportPair)();
57
+ const session = (0, contract_proxy_1.createContractProviderSession)(resolution, providerTransport, {
58
+ permissionCheck: opts.permissionCheck,
59
+ context: opts.context,
60
+ });
61
+ const consumer = (0, contract_proxy_1.createContractConsumer)(makeContract(contractId), consumerTransport);
62
+ return {
63
+ consumer,
64
+ session,
65
+ emitter,
66
+ save,
67
+ contractId,
68
+ consumerTransport,
69
+ providerTransport,
70
+ };
71
+ }
72
+ describe("contract table dataChanged — end-to-end", () => {
73
+ it("delivers a dataChanged payload to a subscribed consumer", async () => {
74
+ const { consumer, session, emitter } = wire();
75
+ const received = [];
76
+ consumer.tables[TABLE_NAME].dataChanged.subscribe((v) => received.push(v));
77
+ await flush();
78
+ await emitter.emit(mkEvent("w1"));
79
+ expect(received).toEqual([mkEvent("w1")]);
80
+ session.dispose();
81
+ consumer.dispose();
82
+ });
83
+ });
84
+ describe("contract table dataChanged — subscription gating", () => {
85
+ it("pushes nothing on the notify channel when nobody is subscribed", async () => {
86
+ const { emitter, providerTransport, session, consumer } = wire();
87
+ const notifySpy = jest.spyOn(providerTransport, "emit");
88
+ await emitter.emit(mkEvent("w0"));
89
+ expect(notifySpy).not.toHaveBeenCalled();
90
+ session.dispose();
91
+ consumer.dispose();
92
+ });
93
+ });
94
+ describe("contract table dataChanged — unsubscribe + refcount", () => {
95
+ it("stops delivering after unsubscribe and detaches the live subscription", async () => {
96
+ const { consumer, session, emitter, providerTransport } = wire();
97
+ const originalSubscribe = emitter.event.subscribe;
98
+ const liveUnsubscribe = jest.fn();
99
+ jest.spyOn(emitter.event, "subscribe").mockImplementation((handler) => {
100
+ const subscription = originalSubscribe(handler);
101
+ return {
102
+ unsubscribe: () => {
103
+ liveUnsubscribe();
104
+ return subscription.unsubscribe();
105
+ },
106
+ };
107
+ });
108
+ const received = [];
109
+ const sub = consumer.tables[TABLE_NAME].dataChanged.subscribe((v) => received.push(v));
110
+ await flush();
111
+ await emitter.emit(mkEvent("a"));
112
+ expect(received).toEqual([mkEvent("a")]);
113
+ const notifySpy = jest.spyOn(providerTransport, "emit");
114
+ sub.unsubscribe();
115
+ await flush();
116
+ // Refcount reached 0, so the provider detached its live handler: no further pushes.
117
+ expect(liveUnsubscribe).toHaveBeenCalledTimes(1);
118
+ await emitter.emit(mkEvent("b", "update"));
119
+ expect(notifySpy).not.toHaveBeenCalled();
120
+ expect(received).toEqual([mkEvent("a")]);
121
+ session.dispose();
122
+ consumer.dispose();
123
+ });
124
+ });
125
+ describe("contract table dataChanged — fan-out", () => {
126
+ it("delivers to multiple subscribers through a single live subscription", async () => {
127
+ const { consumer, session, emitter, providerTransport } = wire();
128
+ const liveSubscribeSpy = jest.spyOn(emitter.event, "subscribe");
129
+ const a = [];
130
+ const b = [];
131
+ consumer.tables[TABLE_NAME].dataChanged.subscribe((v) => a.push(v));
132
+ consumer.tables[TABLE_NAME].dataChanged.subscribe((v) => b.push(v));
133
+ await flush();
134
+ // One live subscription is shared across both consumer subscriptions (refcount by key).
135
+ expect(liveSubscribeSpy).toHaveBeenCalledTimes(1);
136
+ const notifySpy = jest.spyOn(providerTransport, "emit");
137
+ await emitter.emit(mkEvent("x"));
138
+ expect(a).toEqual([mkEvent("x")]);
139
+ expect(b).toEqual([mkEvent("x")]);
140
+ // One push per subscriptionId fanned out from the single emit.
141
+ expect(notifySpy).toHaveBeenCalledTimes(2);
142
+ session.dispose();
143
+ consumer.dispose();
144
+ });
145
+ });
146
+ describe("contract table dataChanged — permission gating", () => {
147
+ it("rejects a denied subscribe and attaches no live subscription", async () => {
148
+ const consoleError = jest.spyOn(console, "error").mockImplementation();
149
+ const localUserId = (0, utils_1.newid)();
150
+ const { providerTransport, emitter, session, consumer } = wire({
151
+ permissionCheck: contract_proxy_1.sameUserContractPermissionCheck,
152
+ context: { localUserId, callerUserId: (0, utils_1.newid)() },
153
+ });
154
+ const liveSubscribeSpy = jest.spyOn(emitter.event, "subscribe");
155
+ const received = [];
156
+ consumer.tables[TABLE_NAME].dataChanged.subscribe((value) => received.push(value));
157
+ await flush();
158
+ // No live subscription attached, so emitting the event pushes nothing.
159
+ const notifySpy = jest.spyOn(providerTransport, "emit");
160
+ await emitter.emit(mkEvent("z"));
161
+ expect(notifySpy).not.toHaveBeenCalled();
162
+ expect(liveSubscribeSpy).not.toHaveBeenCalled();
163
+ expect(received).toEqual([]);
164
+ expect(consoleError).toHaveBeenCalledWith("Contract subscribe failed", expect.objectContaining({ message: expect.stringMatching(/Permission denied/) }));
165
+ session.dispose();
166
+ consumer.dispose();
167
+ });
168
+ });
169
+ describe("contract table dataChanged — methods coexist", () => {
170
+ it("forwards table methods as calls alongside dataChanged subscriptions", async () => {
171
+ const { consumer, session, save } = wire();
172
+ const saved = await consumer.tables[TABLE_NAME].save({ id: "w9", label: "hi" });
173
+ expect(save).toHaveBeenCalledWith({ id: "w9", label: "hi" });
174
+ expect(saved).toEqual({ id: "w9", label: "hi" });
175
+ session.dispose();
176
+ consumer.dispose();
177
+ });
178
+ });
179
+ describe("contract table dataChanged — teardown", () => {
180
+ it("session.dispose() detaches live subscriptions and stops pushes", async () => {
181
+ const { consumer, session, emitter, providerTransport } = wire();
182
+ const received = [];
183
+ consumer.tables[TABLE_NAME].dataChanged.subscribe((v) => received.push(v));
184
+ await flush();
185
+ await emitter.emit(mkEvent("1"));
186
+ expect(received).toEqual([mkEvent("1")]);
187
+ const notifySpy = jest.spyOn(providerTransport, "emit");
188
+ session.dispose();
189
+ await emitter.emit(mkEvent("2", "update"));
190
+ expect(notifySpy).not.toHaveBeenCalled();
191
+ expect(received).toEqual([mkEvent("1")]);
192
+ consumer.dispose();
193
+ });
194
+ it("consumer.dispose() unsubscribes the provider and drops later pushes", async () => {
195
+ const { consumer, session, emitter, providerTransport } = wire();
196
+ const received = [];
197
+ consumer.tables[TABLE_NAME].dataChanged.subscribe((v) => received.push(v));
198
+ await flush();
199
+ await emitter.emit(mkEvent("1"));
200
+ expect(received).toEqual([mkEvent("1")]);
201
+ const notifySpy = jest.spyOn(providerTransport, "emit");
202
+ consumer.dispose();
203
+ await flush();
204
+ await emitter.emit(mkEvent("2", "update"));
205
+ expect(notifySpy).not.toHaveBeenCalled();
206
+ expect(received).toEqual([mkEvent("1")]);
207
+ session.dispose();
208
+ });
209
+ });
@@ -0,0 +1,163 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const field_type_1 = require("../../types/field-type");
4
+ const utils_1 = require("../../utils");
5
+ const contract_proxy_1 = require("../contract-proxy");
6
+ const contract_transport_1 = require("../contract-transport");
7
+ describe("inProcessTransportPair", () => {
8
+ it("delivers a request to the peer handler and resolves with its return (ack)", async () => {
9
+ const [a, b] = (0, contract_transport_1.inProcessTransportPair)();
10
+ b.on(contract_transport_1.CONTRACT_REQUEST_CHANNEL, (x, y) => x + y);
11
+ await expect(a.emit(contract_transport_1.CONTRACT_REQUEST_CHANNEL, 2, 3)).resolves.toBe(5);
12
+ });
13
+ it("awaits async handlers before resolving the emit", async () => {
14
+ const [a, b] = (0, contract_transport_1.inProcessTransportPair)();
15
+ b.on(contract_transport_1.CONTRACT_REQUEST_CHANNEL, async (value) => {
16
+ await new Promise((r) => setTimeout(r, 5));
17
+ return `handled:${value}`;
18
+ });
19
+ await expect(a.emit(contract_transport_1.CONTRACT_REQUEST_CHANNEL, "x")).resolves.toBe("handled:x");
20
+ });
21
+ it("propagates a thrown handler error as a rejected emit", async () => {
22
+ const [a, b] = (0, contract_transport_1.inProcessTransportPair)();
23
+ b.on(contract_transport_1.CONTRACT_REQUEST_CHANNEL, () => {
24
+ throw new Error("boom");
25
+ });
26
+ await expect(a.emit(contract_transport_1.CONTRACT_REQUEST_CHANNEL, {})).rejects.toThrow("boom");
27
+ });
28
+ it("propagates a rejected async handler as a rejected emit", async () => {
29
+ const [a, b] = (0, contract_transport_1.inProcessTransportPair)();
30
+ b.on(contract_transport_1.CONTRACT_REQUEST_CHANNEL, async () => {
31
+ throw new Error("async-boom");
32
+ });
33
+ await expect(a.emit(contract_transport_1.CONTRACT_REQUEST_CHANNEL, {})).rejects.toThrow("async-boom");
34
+ });
35
+ it("resolves undefined when the peer has no handler for the channel", async () => {
36
+ const [a] = (0, contract_transport_1.inProcessTransportPair)();
37
+ await expect(a.emit("no-such-channel", 1)).resolves.toBeUndefined();
38
+ });
39
+ it("stops delivering after unsubscribe", async () => {
40
+ const [a, b] = (0, contract_transport_1.inProcessTransportPair)();
41
+ const handler = jest.fn(() => "ok");
42
+ const unsubscribe = b.on(contract_transport_1.CONTRACT_REQUEST_CHANNEL, handler);
43
+ await expect(a.emit(contract_transport_1.CONTRACT_REQUEST_CHANNEL, 1)).resolves.toBe("ok");
44
+ expect(handler).toHaveBeenCalledTimes(1);
45
+ unsubscribe();
46
+ await expect(a.emit(contract_transport_1.CONTRACT_REQUEST_CHANNEL, 1)).resolves.toBeUndefined();
47
+ expect(handler).toHaveBeenCalledTimes(1);
48
+ });
49
+ it("is bidirectional: either end can emit and handle", async () => {
50
+ const [a, b] = (0, contract_transport_1.inProcessTransportPair)();
51
+ a.on("ping", (msg) => `a-got:${msg}`);
52
+ b.on("ping", (msg) => `b-got:${msg}`);
53
+ // a -> b uses b's handler; b -> a uses a's handler.
54
+ await expect(a.emit("ping", "hi")).resolves.toBe("b-got:hi");
55
+ await expect(b.emit("ping", "yo")).resolves.toBe("a-got:yo");
56
+ });
57
+ it("supports provider->consumer pushes on the notify channel (fire-and-forget)", async () => {
58
+ const [consumer, provider] = (0, contract_transport_1.inProcessTransportPair)();
59
+ const received = [];
60
+ consumer.on(contract_transport_1.CONTRACT_NOTIFY_CHANNEL, (payload) => {
61
+ received.push(payload);
62
+ });
63
+ // The provider pushes and ignores the returned promise, exactly as a notification would.
64
+ void provider.emit(contract_transport_1.CONTRACT_NOTIFY_CHANNEL, { event: "changed", id: "abc" });
65
+ // The ack is still available if awaited, but pushes typically drop it.
66
+ await expect(provider.emit(contract_transport_1.CONTRACT_NOTIFY_CHANNEL, { event: "again" })).resolves.toBeUndefined();
67
+ expect(received).toEqual([{ event: "changed", id: "abc" }, { event: "again" }]);
68
+ });
69
+ it("rejects multiple request handlers instead of using last-result-wins", () => {
70
+ const [, provider] = (0, contract_transport_1.inProcessTransportPair)();
71
+ provider.on(contract_transport_1.CONTRACT_REQUEST_CHANNEL, () => "first");
72
+ expect(() => provider.on(contract_transport_1.CONTRACT_REQUEST_CHANNEL, () => "second")).toThrow(/one provider router/);
73
+ });
74
+ });
75
+ describe("connectionContractTransport", () => {
76
+ it("delegates emit to the underlying emitter", async () => {
77
+ const emit = jest.fn(async () => "result");
78
+ const emitter = { emit, on: jest.fn() };
79
+ const transport = (0, contract_transport_1.connectionContractTransport)(emitter);
80
+ await expect(transport.emit(contract_transport_1.CONTRACT_REQUEST_CHANNEL, { a: 1 })).resolves.toBe("result");
81
+ expect(emit).toHaveBeenCalledWith(contract_transport_1.CONTRACT_REQUEST_CHANNEL, { a: 1 });
82
+ });
83
+ it("removes only the requested handler from a shared channel dispatcher", async () => {
84
+ const listeners = new Map();
85
+ const on = jest.fn((channel, listener) => {
86
+ listeners.set(channel, listener);
87
+ });
88
+ const emitter = { emit: jest.fn(), on };
89
+ const transportA = (0, contract_transport_1.connectionContractTransport)(emitter);
90
+ const transportB = (0, contract_transport_1.connectionContractTransport)(emitter);
91
+ const handlerA = jest.fn();
92
+ const handlerB = jest.fn();
93
+ const unsubscribeA = transportA.on(contract_transport_1.CONTRACT_NOTIFY_CHANNEL, handlerA);
94
+ transportB.on(contract_transport_1.CONTRACT_NOTIFY_CHANNEL, handlerB);
95
+ expect(on).toHaveBeenCalledTimes(1);
96
+ await listeners.get(contract_transport_1.CONTRACT_NOTIFY_CHANNEL)?.("first");
97
+ expect(handlerA).toHaveBeenCalledWith("first");
98
+ expect(handlerB).toHaveBeenCalledWith("first");
99
+ unsubscribeA();
100
+ unsubscribeA();
101
+ await listeners.get(contract_transport_1.CONTRACT_NOTIFY_CHANNEL)?.("second");
102
+ expect(handlerA).toHaveBeenCalledTimes(1);
103
+ expect(handlerB).toHaveBeenLastCalledWith("second");
104
+ });
105
+ it("lets two consumers share notify traffic and dispose independently", async () => {
106
+ const listeners = new Map();
107
+ const emitter = {
108
+ emit: jest.fn(async () => undefined),
109
+ on: (channel, listener) => {
110
+ listeners.set(channel, listener);
111
+ },
112
+ };
113
+ const transport = (0, contract_transport_1.connectionContractTransport)(emitter);
114
+ const contract = {
115
+ contractId: (0, utils_1.newid)(),
116
+ version: 1,
117
+ devTag: "dev",
118
+ name: "Shared transport",
119
+ description: "Shared notify channel",
120
+ tables: [],
121
+ tools: [],
122
+ observables: [],
123
+ events: [
124
+ {
125
+ name: "changed",
126
+ description: "Changed",
127
+ payloadFields: [{ name: "id", type: field_type_1.FieldType.id }],
128
+ },
129
+ ],
130
+ };
131
+ const consumerA = (0, contract_proxy_1.createContractConsumer)(contract, transport);
132
+ const consumerB = (0, contract_proxy_1.createContractConsumer)(contract, transport);
133
+ const receivedA = [];
134
+ const receivedB = [];
135
+ consumerA.events.changed.subscribe((value) => receivedA.push(value));
136
+ consumerB.events.changed.subscribe((value) => receivedB.push(value));
137
+ const subscribeCalls = emitter.emit.mock.calls
138
+ .filter(([channel, call]) => channel === contract_transport_1.CONTRACT_REQUEST_CHANNEL && call.operation === "subscribe")
139
+ .map(([, call]) => call);
140
+ const consumerASubscriptionId = subscribeCalls[0].subscriptionId;
141
+ const consumerBSubscriptionId = subscribeCalls[1].subscriptionId;
142
+ await listeners.get(contract_transport_1.CONTRACT_NOTIFY_CHANNEL)?.({
143
+ subscriptionId: consumerASubscriptionId,
144
+ value: "for-a",
145
+ });
146
+ expect(receivedA).toEqual(["for-a"]);
147
+ expect(receivedB).toEqual([]);
148
+ await listeners.get(contract_transport_1.CONTRACT_NOTIFY_CHANNEL)?.({
149
+ subscriptionId: consumerBSubscriptionId,
150
+ value: "before",
151
+ });
152
+ expect(receivedA).toEqual(["for-a"]);
153
+ expect(receivedB).toEqual(["before"]);
154
+ consumerA.dispose();
155
+ await listeners.get(contract_transport_1.CONTRACT_NOTIFY_CHANNEL)?.({
156
+ subscriptionId: consumerBSubscriptionId,
157
+ value: "after",
158
+ });
159
+ expect(receivedA).toEqual(["for-a"]);
160
+ expect(receivedB).toEqual(["before", "after"]);
161
+ consumerB.dispose();
162
+ });
163
+ });
@@ -0,0 +1,109 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const field_type_1 = require("../../types/field-type");
4
+ const utils_1 = require("../../utils");
5
+ const contract_providers_table_1 = require("../contract-providers.table");
6
+ const contracts_table_1 = require("../contracts.table");
7
+ const persistent_registry_1 = require("../persistent-registry");
8
+ const registry_1 = require("../registry");
9
+ jest.mock("../contract-providers.table", () => ({ ContractProviders: jest.fn() }));
10
+ jest.mock("../contracts.table", () => ({ Contracts: jest.fn() }));
11
+ const contracts = contracts_table_1.Contracts;
12
+ const contractProviders = contract_providers_table_1.ContractProviders;
13
+ const dataContext = {};
14
+ const contractRecords = [];
15
+ const providerRecords = [];
16
+ const contractsTable = {
17
+ findOne: jest.fn(async (filter) => contractRecords.find((record) => Object.entries(filter).every(([key, value]) => record[key] === value))),
18
+ list: jest.fn(async () => [...contractRecords]),
19
+ save: jest.fn(async (record) => {
20
+ const index = contractRecords.findIndex((existing) => existing.contractId === record.contractId && existing.version === record.version);
21
+ if (index >= 0) {
22
+ contractRecords[index] = record;
23
+ }
24
+ else {
25
+ contractRecords.push(record);
26
+ }
27
+ return record;
28
+ }),
29
+ };
30
+ const providersTable = {
31
+ findOne: jest.fn(async (filter) => providerRecords.find((record) => Object.entries(filter).every(([key, value]) => record[key] === value))),
32
+ list: jest.fn(async () => [...providerRecords]),
33
+ save: jest.fn(async (record) => {
34
+ const index = providerRecords.findIndex((existing) => existing.contractProviderId === record.contractProviderId);
35
+ if (index >= 0) {
36
+ providerRecords[index] = record;
37
+ }
38
+ else {
39
+ providerRecords.push(record);
40
+ }
41
+ return record;
42
+ }),
43
+ };
44
+ beforeEach(() => {
45
+ contractRecords.length = 0;
46
+ providerRecords.length = 0;
47
+ jest.clearAllMocks();
48
+ contracts.mockReturnValue(contractsTable);
49
+ contractProviders.mockReturnValue(providersTable);
50
+ });
51
+ function makeDefinition() {
52
+ return {
53
+ contractId: (0, utils_1.newid)(),
54
+ version: 1,
55
+ devTag: "dev",
56
+ name: "Event Contract",
57
+ description: "Persists events",
58
+ tables: [],
59
+ tools: [],
60
+ observables: [],
61
+ events: [
62
+ {
63
+ name: "widgetChanged",
64
+ description: "A widget changed",
65
+ payloadFields: [{ name: "widgetId", type: field_type_1.FieldType.id, description: "Changed widget" }],
66
+ },
67
+ ],
68
+ };
69
+ }
70
+ describe("PersistentContractRegistry event definitions", () => {
71
+ it("persists and hydrates event names, descriptions, and payload fields", async () => {
72
+ const definition = makeDefinition();
73
+ const providerPackageId = (0, utils_1.newid)();
74
+ const persistent = new persistent_registry_1.PersistentContractRegistry(new registry_1.ContractRegistry(), dataContext);
75
+ await persistent.persist(definition, providerPackageId, true);
76
+ expect(JSON.parse(contractRecords[0].shape).events).toEqual(definition.events);
77
+ const hydratedRegistry = new registry_1.ContractRegistry();
78
+ await new persistent_registry_1.PersistentContractRegistry(hydratedRegistry, dataContext).hydrate();
79
+ expect(hydratedRegistry.getDefinition(definition.contractId, definition.version)).toEqual(definition);
80
+ });
81
+ it("hydrates old persisted shapes without events as an empty event list", async () => {
82
+ const definition = makeDefinition();
83
+ const providerPackageId = (0, utils_1.newid)();
84
+ contractRecords.push({
85
+ contractId: definition.contractId,
86
+ version: definition.version,
87
+ devTag: definition.devTag,
88
+ name: definition.name,
89
+ description: definition.description,
90
+ shape: JSON.stringify({
91
+ tables: definition.tables,
92
+ tools: definition.tools,
93
+ observables: definition.observables,
94
+ }),
95
+ registeredAt: new Date(0).toISOString(),
96
+ });
97
+ providerRecords.push({
98
+ contractProviderId: (0, utils_1.newid)(),
99
+ contractId: definition.contractId,
100
+ version: definition.version,
101
+ providerPackageId,
102
+ isActive: true,
103
+ registeredAt: new Date(0).toISOString(),
104
+ });
105
+ const registry = new registry_1.ContractRegistry();
106
+ await new persistent_registry_1.PersistentContractRegistry(registry, dataContext).hydrate();
107
+ expect(registry.getDefinition(definition.contractId, definition.version)?.events).toEqual([]);
108
+ });
109
+ });
@@ -0,0 +1 @@
1
+ export {};