@jskit-ai/rewarded-core 0.2.15 → 0.2.17

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.
@@ -4,6 +4,7 @@ import test from "node:test";
4
4
  import { ActionProvider } from "@jskit-ai/kernel/server/actions";
5
5
  import { EventProvider } from "@jskit-ai/kernel/server/runtime";
6
6
  import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
7
+ import { CrudContractsProvider } from "@jskit-ai/crud-core/server/crudContracts";
7
8
  import { createCapabilityRuntime, defineProvider } from "@jskit-ai/kernel/shared/capabilities";
8
9
  import { RewardedCoreFeature } from "../src/server/RewardedCoreFeature.js";
9
10
  import {
@@ -23,18 +24,31 @@ function valueProvider(id, capability, value) {
23
24
  });
24
25
  }
25
26
 
26
- function createRewardedRuntime(grantPolicy, observed = {}) {
27
- const knex = Object.assign(() => {}, {
28
- async transaction(callback) {
29
- return callback({});
27
+ // A resource runtime that records which feature owns each table and answers stand-in handles.
28
+ function resourceRuntime(observed) {
29
+ return {
30
+ own(featureId, owns) {
31
+ return Object.freeze(Object.fromEntries(owns.map((entry) => {
32
+ const { name } = entry.resource || entry;
33
+ if (observed.resources) {
34
+ observed.resources[name] = featureId;
35
+ }
36
+ return [name, Object.freeze({ name })];
37
+ })));
38
+ },
39
+ declareSystemScope() {
40
+ throw new Error("Rewarded works in the caller's scope only.");
30
41
  }
31
- });
42
+ };
43
+ }
44
+
45
+ function createRewardedRuntime(grantPolicy, observed = {}) {
32
46
  return createCapabilityRuntime({
33
47
  inputs: { "runtime.logger": silentLogger },
34
48
  providers: [
35
49
  EventProvider, ActionProvider,
36
50
  valueProvider("test.grant-policy", "rewarded.grant-policy", grantPolicy),
37
- valueProvider("test.database", "runtime.database", { knex }),
51
+ valueProvider("test.resources", "runtime.resources", resourceRuntime(observed)),
38
52
  valueProvider("test.http", "runtime.http", {
39
53
  router: {
40
54
  register(method, path, contract, handler) {
@@ -42,14 +56,7 @@ function createRewardedRuntime(grantPolicy, observed = {}) {
42
56
  }
43
57
  }
44
58
  }),
45
- valueProvider("test.json-rest-api", "runtime.json-rest-api", {
46
- resources: observed.resources ?? {},
47
- async addResource(name, config) {
48
- if (observed.resources) {
49
- observed.resources[name] = { config };
50
- }
51
- }
52
- }),
59
+ CrudContractsProvider,
53
60
  RewardedRulesFeature,
54
61
  RewardedProviderConfigsFeature,
55
62
  RewardedWatchSessionsFeature,
@@ -92,7 +99,12 @@ test("Rewarded composes standard resource capabilities around one explicit domai
92
99
  assert.ok(definitions.every((entry) => !Object.hasOwn(entry, "dependencies")));
93
100
  assert.equal(typeof rewarded.getCurrentState, "function");
94
101
  assert.equal(routes.length, 24);
95
- assert.equal(Object.keys(resources).length, 4);
102
+ assert.deepEqual(resources, {
103
+ rewardedRules: "rewarded.rules",
104
+ rewardedProviderConfigs: "rewarded.provider-configs",
105
+ rewardedWatchSessions: "rewarded.watch-sessions",
106
+ rewardedUnlockReceipts: "rewarded.unlock-receipts"
107
+ });
96
108
 
97
109
  await runtime.shutdown();
98
110
  });
@@ -5,6 +5,11 @@ import rulesMigration from "../migrations/rewarded_rules_initial.cjs";
5
5
  import unlockReceiptsMigration from "../migrations/rewarded_unlock_receipts_initial.cjs";
6
6
  import watchSessionsMigration from "../migrations/rewarded_watch_sessions_initial.cjs";
7
7
  import foreignKeysMigration from "../migrations/constraints/rewarded_foreign_keys.cjs";
8
+ import { checkForeignKeys } from "@jskit-ai/resource-runtime/server";
9
+ import { rewardedProviderConfigTableResource } from "../src/shared/rewardedProviderConfigResource.js";
10
+ import { rewardedRuleTableResource } from "../src/shared/rewardedRuleResource.js";
11
+ import { rewardedUnlockReceiptTableResource } from "../src/shared/rewardedUnlockReceiptResource.js";
12
+ import { rewardedWatchSessionTableResource } from "../src/shared/rewardedWatchSessionResource.js";
8
13
  import { openOwnDatabase } from "./mysqlDatabase.js";
9
14
 
10
15
  // Knex's filename order within rewarded-core's migrations/ directory.
@@ -68,6 +73,9 @@ test("a fresh MySQL database migrates rewarded-core before users and workspaces
68
73
  }
69
74
  await foreignKeysMigration.up(knex);
70
75
  assert.deepEqual(await foreignKeys(knex), ALL_KEYS);
76
+ // The table resources declare exactly those keys.
77
+ const resources = [rewardedProviderConfigTableResource, rewardedRuleTableResource, rewardedUnlockReceiptTableResource, rewardedWatchSessionTableResource];
78
+ assert.deepEqual(await checkForeignKeys({ knex, resources, tables: TABLES }), { missing: [], undeclared: [] });
71
79
 
72
80
  // Keys that already exist are left as they are.
73
81
  await foreignKeysMigration.up(knex);
@@ -1,22 +1,15 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
3
  import knexLib from "knex";
4
- import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
5
- import { toDatabaseDateTimeUtc } from "@jskit-ai/database-runtime/shared";
6
- import { createCrudJsonApiRepository } from "@jskit-ai/crud-core/server/jsonApiRepository";
7
- import {
8
- addResourceIfMissing,
9
- createJsonRestApiHost,
10
- createJsonRestResourceScopeOptions
11
- } from "@jskit-ai/json-rest-api-core/server/jsonRestApiHost";
4
+ import { createTestResourceRuntime } from "@jskit-ai/resource-runtime/test";
12
5
  import providerConfigsMigration from "../migrations/rewarded_provider_configs_initial.cjs";
13
6
  import rulesMigration from "../migrations/rewarded_rules_initial.cjs";
14
7
  import watchSessionsMigration from "../migrations/rewarded_watch_sessions_initial.cjs";
15
8
  import unlockReceiptsMigration from "../migrations/rewarded_unlock_receipts_initial.cjs";
16
- import { resource as providerConfigsResource } from "../src/shared/rewardedProviderConfigResource.js";
17
- import { resource as rulesResource } from "../src/shared/rewardedRuleResource.js";
18
- import { resource as watchSessionsResource } from "../src/shared/rewardedWatchSessionResource.js";
19
- import { resource as unlockReceiptsResource } from "../src/shared/rewardedUnlockReceiptResource.js";
9
+ import { rewardedProviderConfigTableResource as providerConfigsResource } from "../src/shared/rewardedProviderConfigResource.js";
10
+ import { rewardedRuleTableResource as rulesResource } from "../src/shared/rewardedRuleResource.js";
11
+ import { rewardedWatchSessionTableResource as watchSessionsResource } from "../src/shared/rewardedWatchSessionResource.js";
12
+ import { rewardedUnlockReceiptTableResource as unlockReceiptsResource } from "../src/shared/rewardedUnlockReceiptResource.js";
20
13
  import { createService } from "../src/server/service.js";
21
14
  import { openOwnDatabase } from "./mysqlDatabase.js";
22
15
 
@@ -77,64 +70,58 @@ test(`rewarded grants use real resources and atomic transactions (${databaseUrl
77
70
  await knex("users").insert([{ id: 7 }, { id: 8 }]);
78
71
  await knex("workspaces").insert([{ id: 1 }, { id: 2 }]);
79
72
 
80
- const api = await createJsonRestApiHost({ knex, logger: silentLogger });
81
- const repositories = {};
82
- for (const [scopeName, resource, migration] of RESOURCES) {
83
- await addResourceIfMissing(api, scopeName, createJsonRestResourceScopeOptions(resource, {
84
- writeSerializers: { "datetime-utc": toDatabaseDateTimeUtc }
85
- }));
86
- if (databaseUrl) {
73
+ if (databaseUrl) {
74
+ for (const [, , migration] of RESOURCES) {
87
75
  await migration.up(knex);
88
- } else {
89
- // The shipped ON UPDATE defaults are MySQL-specific; SQLite verifies the resource workflow.
90
- await api.resources[scopeName].createKnexTable();
91
76
  }
92
- repositories[scopeName] = createCrudJsonApiRepository({ api, resource, resourceScopeName: scopeName });
93
77
  }
78
+ // Each write of a test case reports itself from its resource's afterWrite hook, in the write's transaction.
79
+ const transactions = new Map();
80
+ const writes = [];
81
+ let authorize = true;
82
+ let failReceipt = false;
83
+ const receiptFailure = new Error("Receipt storage hook failed");
84
+ const owns = RESOURCES.map(([name, resource]) => ({
85
+ resource,
86
+ hooks: {
87
+ async afterWrite({ operation, ids, options }) {
88
+ const testCase = options.context?.testCase;
89
+ if (!testCase) return;
90
+ assert.equal(options.trx, transactions.get(testCase));
91
+ writes.push({ testCase, operation, name });
92
+ if (name === "rewardedUnlockReceipts" && failReceipt) {
93
+ assert.ok(await repositories.rewardedUnlockReceipts.get(ids[0], {}, options),
94
+ "The receipt write must occur before injecting the rollback failure.");
95
+ throw receiptFailure;
96
+ }
97
+ }
98
+ }
99
+ }));
100
+ // The shipped ON UPDATE defaults are MySQL-specific; SQLite builds the tables from the resource schemas.
101
+ const runtime = await createTestResourceRuntime({ knex, createTables: !databaseUrl });
102
+ const repositories = await runtime.own("rewarded.test", owns);
94
103
 
95
104
  const context = actorContext();
96
- const provider = await repositories.rewardedProviderConfigs.createDocument({
105
+ const provider = await repositories.rewardedProviderConfigs.create({
97
106
  surface: "app", enabled: true, placement: "/test/rewarded", provider: "google-publisher-tag"
98
107
  }, { context });
99
- await repositories.rewardedRules.createDocument({
108
+ await repositories.rewardedRules.create({
100
109
  gateKey: "progress", surface: "app", enabled: true,
101
110
  unlockMinutes: 30, cooldownMinutes: 0, dailyLimit: null,
102
111
  title: "Log progress", description: "Rewarded workflow test"
103
112
  }, { context });
104
113
 
105
- const transactions = new Map();
106
- const events = [];
107
- let authorize = true;
108
- let failReceipt = false;
109
- const receiptFailure = new Error("Receipt storage hook failed");
110
- await api.customize({
111
- hooks: Object.fromEntries(["afterDataCallPatch", "afterDataCallPost", "afterCommit", "afterRollback"].map((event) => [event, {
112
- functionName: `rewarded-integration-${event}`,
113
- async handler({ scopeName, context: hookContext }) {
114
- if (!hookContext.testCase) return;
115
- assert.equal(hookContext.transaction, transactions.get(hookContext.testCase));
116
- events.push({ event, scopeName, testCase: hookContext.testCase });
117
- if (event === "afterDataCallPost" && scopeName === "rewardedUnlockReceipts" && failReceipt) {
118
- const receipt = await hookContext.transaction("rewarded_unlock_receipts")
119
- .where({ id: hookContext.id }).first();
120
- assert.ok(receipt, "The receipt write must occur before injecting the rollback failure.");
121
- throw receiptFailure;
122
- }
123
- }
124
- }]))
125
- });
126
114
  const service = createService({
127
115
  rewardedProviderConfigsRepository: repositories.rewardedProviderConfigs,
128
116
  rewardedRulesRepository: repositories.rewardedRules,
129
117
  rewardedWatchSessionsRepository: repositories.rewardedWatchSessions,
130
118
  rewardedUnlockReceiptsRepository: repositories.rewardedUnlockReceipts,
131
119
  grantPolicy: {
132
- async authorizeGrant({ session, context: grantContext, trx }) {
133
- transactions.set(grantContext.testCase, trx);
134
- const stored = await trx("rewarded_watch_sessions").where({ id: session.id }).first();
135
- assert.equal(String(stored.user_id), grantContext.scopeValues.userId);
136
- assert.equal(String(stored.workspace_id), grantContext.scopeValues.workspaceId);
137
- assert.equal(events.some((entry) => entry.event === "afterCommit" && entry.testCase === grantContext.testCase), false);
120
+ async authorizeGrant({ session, context: grantContext, options }) {
121
+ transactions.set(grantContext.testCase, options.trx);
122
+ const stored = await repositories.rewardedWatchSessions.get(session.id, {}, options);
123
+ assert.equal(stored.id, session.id);
124
+ assert.equal(writes.some((entry) => entry.testCase === grantContext.testCase), false);
138
125
  return authorize;
139
126
  }
140
127
  }
@@ -145,20 +132,18 @@ test(`rewarded grants use real resources and atomic transactions (${databaseUrl
145
132
  await t.test("grant commits the session and receipt with one shared hook transaction", async () => {
146
133
  const started = await service.startGate(gate, { context });
147
134
  successfulSession = started.session.id;
148
- assert.equal(started.session.providerConfigId, provider.data.id);
135
+ assert.equal(started.session.providerConfigId, provider.id);
149
136
  const result = await service.grantReward({ ...gate, sessionId: successfulSession }, {
150
137
  context: actorContext("1", "7", "success")
151
138
  });
152
139
  assert.equal(result.unlocked, true);
153
140
  assert.equal(result.session.status, "rewarded");
154
141
  assert.equal(result.unlock.watchSessionId, successfulSession);
155
- assert.equal(result.unlock.providerConfigId, provider.data.id);
142
+ assert.equal(result.unlock.providerConfigId, provider.id);
156
143
  assert.ok(Date.parse(result.unlock.unlockedUntil) > Date.parse(result.unlock.grantedAt));
157
- assert.deepEqual(events.filter((entry) => entry.testCase === "success").map(({ event, scopeName }) => [event, scopeName]), [
158
- ["afterDataCallPatch", "rewardedWatchSessions"],
159
- ["afterDataCallPost", "rewardedUnlockReceipts"],
160
- ["afterCommit", "rewardedWatchSessions"],
161
- ["afterCommit", "rewardedUnlockReceipts"]
144
+ assert.deepEqual(writes.filter((entry) => entry.testCase === "success").map(({ operation, name }) => [operation, name]), [
145
+ ["patch", "rewardedWatchSessions"],
146
+ ["create", "rewardedUnlockReceipts"]
162
147
  ]);
163
148
  assert.equal(transactions.get("success").isCompleted(), true);
164
149
  assert.equal((await knex("rewarded_watch_sessions").where({ id: successfulSession }).first()).status, "rewarded");
@@ -173,7 +158,7 @@ test(`rewarded grants use real resources and atomic transactions (${databaseUrl
173
158
  });
174
159
  assert.equal(replay.unlock.id, String(before.id));
175
160
  assert.equal((await knex("rewarded_unlock_receipts").select()).length, 1);
176
- assert.deepEqual(events.filter((entry) => entry.testCase === "replay"), []);
161
+ assert.deepEqual(writes.filter((entry) => entry.testCase === "replay"), []);
177
162
  });
178
163
 
179
164
  await t.test("another user or workspace cannot grant or discover the owner's unlock", async () => {
@@ -181,71 +166,65 @@ test(`rewarded grants use real resources and atomic transactions (${databaseUrl
181
166
  const scopedContext = actorContext(workspaceId, userId, `denied-${workspaceId}-${userId}`);
182
167
  await assert.rejects(service.grantReward({ ...gate, sessionId: successfulSession }, {
183
168
  context: scopedContext
184
- }), { statusCode: 404, transactionOutcome: "rolledBack" });
169
+ }), { statusCode: 404, code: "rewarded.session.notFound" });
185
170
  assert.equal(transactions.has(scopedContext.testCase), false, "Ownership denial must precede grant authorization.");
186
- assert.equal((await repositories.rewardedUnlockReceipts.queryDocuments({}, { context: scopedContext })).data.length, 0);
171
+ assert.equal((await repositories.rewardedUnlockReceipts.query({ page: { size: 10 } }, { context: scopedContext })).records.length, 0);
187
172
  }
188
173
  assert.equal((await knex("rewarded_unlock_receipts").select()).length, 1);
189
174
  });
190
175
 
191
176
  await t.test("a receipt failure rolls back both persisted writes and allows a clean retry", async () => {
192
- const session = await repositories.rewardedWatchSessions.createDocument({
193
- gateKey: "progress", providerConfigId: provider.data.id, status: "started",
177
+ const session = await repositories.rewardedWatchSessions.create({
178
+ gateKey: "progress", providerConfigId: provider.id, status: "started",
194
179
  startedAt: new Date().toISOString()
195
180
  }, { context });
196
- const grant = { ...gate, sessionId: session.data.id };
181
+ const grant = { ...gate, sessionId: session.id };
197
182
  authorize = false;
183
+ // The transaction rolls back, and the work's own refusal reaches the caller.
198
184
  await assert.rejects(service.grantReward(grant, { context: actorContext("1", "7", "unauthorized") }), {
199
- statusCode: 403, transactionOutcome: "rolledBack"
185
+ statusCode: 403, code: "rewarded.session.grantNotAuthorized"
200
186
  });
201
- assert.equal((await knex("rewarded_watch_sessions").where({ id: session.data.id }).first()).status, "started");
187
+ assert.equal((await knex("rewarded_watch_sessions").where({ id: session.id }).first()).status, "started");
202
188
  authorize = true;
203
189
  failReceipt = true;
204
- await assert.rejects(service.grantReward(grant, { context: actorContext("1", "7", "rollback") }), (error) => {
205
- assert.equal(error.transactionOutcome, "rolledBack");
206
- assert.match(error.message, /Receipt storage hook failed/u);
207
- return true;
208
- });
209
- const stored = await knex("rewarded_watch_sessions").where({ id: session.data.id }).first();
190
+ // The rows below prove the rollback; the hook's own failure reaches the caller.
191
+ await assert.rejects(service.grantReward(grant, { context: actorContext("1", "7", "rollback") }), /Receipt storage hook failed/u);
192
+ const stored = await knex("rewarded_watch_sessions").where({ id: session.id }).first();
210
193
  assert.equal(stored.status, "started");
211
194
  assert.equal(stored.rewarded_at, null);
212
195
  assert.equal(stored.completed_at, null);
213
- assert.equal((await knex("rewarded_unlock_receipts").where({ watch_session_id: session.data.id }).select()).length, 0);
214
- const rollbackEvents = events.filter((entry) => entry.testCase === "rollback");
215
- assert.deepEqual(rollbackEvents.slice(0, 2).map(({ event, scopeName }) => [event, scopeName]), [
216
- ["afterDataCallPatch", "rewardedWatchSessions"],
217
- ["afterDataCallPost", "rewardedUnlockReceipts"]
218
- ]);
219
- assert.deepEqual(rollbackEvents.slice(2).map(({ event }) => event), ["afterRollback", "afterRollback"]);
220
- assert.deepEqual(rollbackEvents.slice(2).map(({ scopeName }) => scopeName).sort(), [
221
- "rewardedUnlockReceipts", "rewardedWatchSessions"
196
+ assert.equal((await knex("rewarded_unlock_receipts").where({ watch_session_id: session.id }).select()).length, 0);
197
+ assert.deepEqual(writes.filter((entry) => entry.testCase === "rollback").map(({ operation, name }) => [operation, name]), [
198
+ ["patch", "rewardedWatchSessions"],
199
+ ["create", "rewardedUnlockReceipts"]
222
200
  ]);
201
+ assert.equal(transactions.get("rollback").isCompleted(), true);
223
202
  failReceipt = false;
224
203
  const retry = await service.grantReward(grant, { context: actorContext("1", "7", "retry") });
225
204
  assert.equal(retry.session.status, "rewarded");
226
- assert.equal((await knex("rewarded_unlock_receipts").where({ watch_session_id: session.data.id }).select()).length, 1);
205
+ assert.equal((await knex("rewarded_unlock_receipts").where({ watch_session_id: session.id }).select()).length, 1);
227
206
  });
228
207
 
229
208
  await t.test("a daily limit above one page of receipts is counted exactly and reached", async () => {
230
- await repositories.rewardedRules.createDocument({
209
+ await repositories.rewardedRules.create({
231
210
  gateKey: "daily", surface: "app", enabled: true,
232
211
  unlockMinutes: 30, cooldownMinutes: 0, dailyLimit: 120,
233
212
  title: "Daily", description: "Daily limit test"
234
213
  }, { context });
235
214
  const dayStart = new Date(new Date().setUTCHours(0, 0, 0, 0));
236
215
  // Expired receipts: today's count against the limit, yesterday's and another user's do not.
237
- const grantReceipt = (grantedAt, receiptContext = context) => repositories.rewardedUnlockReceipts.createDocument({
216
+ const receipts = (count, grantedAt) => Array.from({ length: count }, () => ({
238
217
  gateKey: "daily", grantedAt: grantedAt.toISOString(), unlockedUntil: dayStart.toISOString()
239
- }, { context: receiptContext });
240
- for (let index = 0; index < 119; index += 1) await grantReceipt(dayStart);
241
- for (let index = 0; index < 5; index += 1) await grantReceipt(new Date(dayStart.getTime() - 3600000));
242
- for (let index = 0; index < 5; index += 1) await grantReceipt(dayStart, actorContext("1", "8"));
218
+ }));
219
+ await repositories.rewardedUnlockReceipts.createMany(receipts(119, dayStart), { context });
220
+ await repositories.rewardedUnlockReceipts.createMany(receipts(5, new Date(dayStart.getTime() - 3600000)), { context });
221
+ await repositories.rewardedUnlockReceipts.createMany(receipts(5, dayStart), { context: actorContext("1", "8") });
243
222
  const dailyGate = { workspaceSlug: "alpha", gateKey: "daily" };
244
223
 
245
224
  const open = await service.getCurrentState(dailyGate, { context });
246
225
  assert.equal(open.reason, "reward-required");
247
226
  assert.equal(open.dailyLimitRemaining, 1);
248
- await grantReceipt(dayStart);
227
+ await repositories.rewardedUnlockReceipts.create(receipts(1, dayStart)[0], { context });
249
228
  const reached = await service.getCurrentState(dailyGate, { context });
250
229
  assert.equal(reached.reason, "daily-limit-reached");
251
230
  assert.equal(reached.dailyLimitRemaining, 0);
@@ -3,56 +3,34 @@ import test from "node:test";
3
3
 
4
4
  import { createService } from "../src/server/service.js";
5
5
 
6
- function createRecordDocument(type, id, attributes = {}) {
7
- return {
8
- data: {
9
- type,
10
- id: String(id),
11
- attributes: {
12
- ...attributes
13
- }
14
- }
15
- };
16
- }
17
-
18
- function createCollectionDocument(type, rows = []) {
19
- return {
20
- data: rows.map((entry, index) => ({
21
- type,
22
- id: String(entry?.id ?? index + 1),
23
- attributes: {
24
- ...entry
25
- }
26
- }))
27
- };
6
+ // A page of records, as a handle's query() answers it.
7
+ function page(records = []) {
8
+ return { records, page: { size: records.length, hasMore: false, next: null } };
28
9
  }
29
10
 
30
11
  function createRuleRepository(rows = []) {
31
12
  return {
32
- async queryDocuments() {
33
- return createCollectionDocument("rewardedRules", rows);
13
+ async query() {
14
+ return page(rows);
34
15
  }
35
16
  };
36
17
  }
37
18
 
38
19
  function createProviderConfigRepository(rows = []) {
39
20
  return {
40
- async queryDocuments() {
41
- return createCollectionDocument("rewardedProviderConfigs", rows);
21
+ async query() {
22
+ return page(rows);
42
23
  }
43
24
  };
44
25
  }
45
26
 
46
27
  function createUnlockReceiptRepository(rows = [], createdRecord = null) {
47
28
  return {
48
- async queryDocuments() {
49
- return createCollectionDocument("rewardedUnlockReceipts", rows);
29
+ async query() {
30
+ return page(rows);
50
31
  },
51
- async createDocument(payload) {
52
- return createRecordDocument("rewardedUnlockReceipts", createdRecord?.id || "301", {
53
- ...(createdRecord || {}),
54
- ...payload
55
- });
32
+ async create(attributes) {
33
+ return { ...(createdRecord || {}), ...attributes, id: createdRecord?.id || "301" };
56
34
  }
57
35
  };
58
36
  }
@@ -67,24 +45,21 @@ function createWatchSessionRepository({
67
45
 
68
46
  return {
69
47
  calls,
70
- async queryDocuments() {
71
- return createCollectionDocument("rewardedWatchSessions", []);
48
+ async query() {
49
+ return page([]);
72
50
  },
73
- async getDocumentById() {
74
- return session ? createRecordDocument("rewardedWatchSessions", session.id, session) : null;
51
+ async get() {
52
+ return session ? { ...session } : null;
75
53
  },
76
- async patchDocumentById(recordId, patch) {
54
+ async patch(recordId, attributes) {
77
55
  calls.patches.push({
78
56
  recordId,
79
- patch
80
- });
81
- return createRecordDocument("rewardedWatchSessions", patchedSession?.id || recordId, {
82
- ...(patchedSession || session || {}),
83
- ...patch
57
+ patch: attributes
84
58
  });
59
+ return { ...(patchedSession || session || {}), ...attributes, id: patchedSession?.id || recordId };
85
60
  },
86
- withTransaction(work) {
87
- return work("trx-1");
61
+ withTransaction(options, work) {
62
+ return work(Object.freeze({ ...options, trx: "trx-1" }));
88
63
  }
89
64
  };
90
65
  }
@@ -205,9 +180,9 @@ test("getCurrentState ignores caller surface overrides and evaluates the app-sur
205
180
  const service = createService({
206
181
  grantPolicy: { authorizeGrant: async () => true },
207
182
  rewardedRulesRepository: {
208
- async queryDocuments(query) {
209
- recordedRuleQueries.push(query);
210
- return createCollectionDocument("rewardedRules", [
183
+ async query(params) {
184
+ recordedRuleQueries.push(params);
185
+ return page([
211
186
  {
212
187
  id: "11",
213
188
  gateKey: "progress-logging",
@@ -223,9 +198,9 @@ test("getCurrentState ignores caller surface overrides and evaluates the app-sur
223
198
  }
224
199
  },
225
200
  rewardedProviderConfigsRepository: {
226
- async queryDocuments(query) {
227
- recordedConfigQueries.push(query);
228
- return createCollectionDocument("rewardedProviderConfigs", [
201
+ async query(params) {
202
+ recordedConfigQueries.push(params);
203
+ return page([
229
204
  {
230
205
  id: "21",
231
206
  surface: "app",
@@ -251,8 +226,8 @@ test("getCurrentState ignores caller surface overrides and evaluates the app-sur
251
226
  }
252
227
  );
253
228
 
254
- assert.equal(recordedRuleQueries[0]?.surface, "app");
255
- assert.equal(recordedConfigQueries[0]?.surface, "app");
229
+ assert.equal(recordedRuleQueries[0]?.filters.surface, "app");
230
+ assert.equal(recordedConfigQueries[0]?.filters.surface, "app");
256
231
  assert.equal(response.surface, "app");
257
232
  assert.equal(response.reason, "reward-required");
258
233
  });
@@ -269,12 +244,12 @@ test("grantReward patches the watch session and creates an unlock receipt", asyn
269
244
  });
270
245
  const createdReceiptPayloads = [];
271
246
  const unlockReceiptsRepository = {
272
- async queryDocuments() {
273
- return createCollectionDocument("rewardedUnlockReceipts", []);
247
+ async query() {
248
+ return page([]);
274
249
  },
275
- async createDocument(payload) {
276
- createdReceiptPayloads.push(payload);
277
- return createRecordDocument("rewardedUnlockReceipts", "51", payload);
250
+ async create(attributes) {
251
+ createdReceiptPayloads.push(attributes);
252
+ return { ...attributes, id: "51" };
278
253
  }
279
254
  };
280
255
 
@@ -336,16 +311,17 @@ test("grant policy sees stored session and server context and rejects before wri
336
311
  rewardedProviderConfigsRepository: createProviderConfigRepository([]),
337
312
  rewardedWatchSessionsRepository: watch,
338
313
  rewardedUnlockReceiptsRepository: {
339
- async createDocument() { throw new Error("Must not write a receipt"); }
314
+ async create() { throw new Error("Must not write a receipt"); }
340
315
  }
341
316
  };
342
317
  for (const decision of [false, undefined, "true"]) {
343
- const service = createService({ ...dependencies, grantPolicy: { authorizeGrant: async ({ session, context, trx }) => {
318
+ const service = createService({ ...dependencies, grantPolicy: { authorizeGrant: async ({ session, context, options }) => {
344
319
  calls += 1;
345
320
  assert.equal(session.id, "41");
346
321
  assert.equal(session.gateKey, "bonus");
347
322
  assert.equal(context, REQUEST_CONTEXT);
348
- assert.ok(trx);
323
+ assert.equal(options.context, REQUEST_CONTEXT);
324
+ assert.ok(options.trx, "the policy reads inside the grant's transaction");
349
325
  return decision;
350
326
  } } });
351
327
  await assert.rejects(service.grantReward({ workspaceSlug: "alpha", sessionId: "41",