@stamprally/server 0.8.0 → 0.9.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.
package/dist/index.cjs CHANGED
@@ -2,54 +2,58 @@
2
2
 
3
3
  var core = require('@stamprally/core');
4
4
 
5
- // src/index.ts
6
-
7
5
  // src/persistence.ts
8
6
  var InMemoryServerPersistenceAdapter = class {
9
7
  #locks = /* @__PURE__ */ new Map();
10
8
  #idempotent = /* @__PURE__ */ new Map();
11
9
  #states = /* @__PURE__ */ new Map();
12
10
  #stocks;
11
+ #claims = /* @__PURE__ */ new Map();
13
12
  #auditLogs = [];
14
13
  constructor(options = {}) {
15
14
  this.#stocks = new Map(Object.entries(options.stocks ?? {}));
16
15
  }
17
- async acquireLock(lockKey, ttlMs) {
16
+ async acquireLock(key, ttlMs) {
18
17
  const now2 = Date.now();
19
- const expiresAt = this.#locks.get(lockKey);
20
- if (expiresAt !== void 0 && expiresAt > now2) return false;
21
- this.#locks.set(lockKey, now2 + Math.max(1, ttlMs));
18
+ const until = this.#locks.get(key);
19
+ if (until !== void 0 && until > now2) return false;
20
+ this.#locks.set(key, now2 + Math.max(1, ttlMs));
22
21
  return true;
23
22
  }
24
- async releaseLock(lockKey) {
25
- this.#locks.delete(lockKey);
23
+ async releaseLock(key) {
24
+ this.#locks.delete(key);
26
25
  }
27
26
  async decrementRewardStock(rewardId) {
28
- const stock = this.#stocks.get(rewardId);
29
- if (stock === void 0) return { success: true, remainingStock: Number.POSITIVE_INFINITY };
30
- if (stock <= 0) return { success: false, remainingStock: 0 };
31
- const remainingStock = stock - 1;
32
- this.#stocks.set(rewardId, remainingStock);
33
- return { success: true, remainingStock };
34
- }
35
- async getIdempotentResult(idempotencyKey) {
36
- const entry = this.#idempotent.get(idempotencyKey);
37
- if (entry === void 0) return null;
38
- if (entry.expiresAt <= Date.now()) {
39
- this.#idempotent.delete(idempotencyKey);
27
+ const current = this.#stocks.get(rewardId);
28
+ if (current === void 0) return { success: true, remainingStock: Number.POSITIVE_INFINITY };
29
+ if (current <= 0) return { success: false, remainingStock: 0 };
30
+ this.#stocks.set(rewardId, current - 1);
31
+ return { success: true, remainingStock: current - 1 };
32
+ }
33
+ async incrementRewardStock(rewardId) {
34
+ const current = this.#stocks.get(rewardId);
35
+ if (current !== void 0) this.#stocks.set(rewardId, current + 1);
36
+ }
37
+ async getIdempotentResult(key) {
38
+ const value = this.#idempotent.get(key);
39
+ if (value === void 0 || value.expiresAt <= Date.now()) {
40
+ this.#idempotent.delete(key);
40
41
  return null;
41
42
  }
42
- return structuredClone(entry.value);
43
+ return structuredClone(value.value);
43
44
  }
44
- async saveIdempotentResult(idempotencyKey, result, ttlMs) {
45
- this.#idempotent.set(idempotencyKey, {
45
+ async saveIdempotentResult(key, result, ttlMs) {
46
+ this.#idempotent.set(key, {
46
47
  value: structuredClone(result),
47
48
  expiresAt: Date.now() + Math.max(1, ttlMs)
48
49
  });
49
50
  }
51
+ async getUserClaimCount(rallyId, userId, rewardId) {
52
+ return this.#claims.get(`${rallyId}:${userId}:${rewardId}`) ?? 0;
53
+ }
50
54
  async getUserState(rallyId, userId) {
51
- const state = this.#states.get(`${rallyId}:${userId}`);
52
- return state === void 0 ? null : structuredClone(state);
55
+ const value = this.#states.get(`${rallyId}:${userId}`);
56
+ return value === void 0 ? null : structuredClone(value);
53
57
  }
54
58
  async saveUserState(rallyId, userId, state) {
55
59
  this.#states.set(`${rallyId}:${userId}`, structuredClone(state));
@@ -60,78 +64,65 @@ var InMemoryServerPersistenceAdapter = class {
60
64
  getAuditLogs() {
61
65
  return structuredClone(this.#auditLogs);
62
66
  }
67
+ recordClaim(rallyId, userId, rewardId) {
68
+ const key = `${rallyId}:${userId}:${rewardId}`;
69
+ this.#claims.set(key, (this.#claims.get(key) ?? 0) + 1);
70
+ }
63
71
  };
64
- function distanceMeters(aLat, aLon, bLat, bLon) {
65
- const radians = (degrees) => degrees * Math.PI / 180;
66
- const dLat = radians(bLat - aLat);
67
- const dLon = radians(bLon - aLon);
68
- const latA = radians(aLat);
69
- const latB = radians(bLat);
70
- const value = Math.sin(dLat / 2) ** 2 + Math.cos(latA) * Math.cos(latB) * Math.sin(dLon / 2) ** 2;
71
- return 6371e3 * 2 * Math.asin(Math.sqrt(Math.min(1, value)));
72
- }
73
- function initialState(config, now2) {
74
- return {
75
- rallyId: config.id,
76
- records: [],
77
- rewards: core.reconcileRewardStates(
78
- config.rewards.map((reward) => ({ ...reward, description: reward.description ?? "" })),
79
- [],
80
- 0,
81
- now2
82
- ),
83
- updatedAt: now2
84
- };
85
- }
86
72
  function json(body, status = 200) {
87
73
  return new Response(JSON.stringify(body), {
88
74
  status,
89
75
  headers: { "content-type": "application/json; charset=utf-8" }
90
76
  });
91
77
  }
92
- function requestBody(request) {
93
- return request.json().then((value) => {
94
- if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
95
- return value;
96
- }).catch(() => null);
78
+ function isObject(value) {
79
+ return typeof value === "object" && value !== null && !Array.isArray(value);
97
80
  }
98
- function adminReward(reward) {
99
- return { ...reward, description: reward.description ?? "" };
81
+ function requestId(prefix) {
82
+ return `${prefix}-${globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`}`;
100
83
  }
101
- function matchesCondition(condition, context, customValidators) {
102
- switch (condition.type) {
103
- case "qr":
104
- return context.type === "qr" && context.token === condition.secretToken;
105
- case "passcode":
106
- return context.type === "passcode" && (condition.caseSensitive === false ? context.code.toLocaleLowerCase() === condition.code.toLocaleLowerCase() : context.code === condition.code);
107
- case "gps":
108
- return context.type === "gps" && distanceMeters(
109
- condition.latitude,
110
- condition.longitude,
111
- context.latitude,
112
- context.longitude
113
- ) <= condition.radiusMeters;
114
- case "custom":
115
- return customValidators?.[condition.validatorName]?.(
116
- context.type === "custom" ? context.value : void 0,
117
- condition
118
- ) ?? false;
119
- }
84
+ function now(options, requested) {
85
+ return requested ?? options.now?.() ?? (/* @__PURE__ */ new Date()).toISOString();
86
+ }
87
+ function initialState(config, userId, timestamp) {
88
+ return {
89
+ rallyId: config.id,
90
+ userId,
91
+ records: [],
92
+ rewards: core.reconcileRewardStates(config.rewards, [], 0, timestamp),
93
+ updatedAt: timestamp
94
+ };
120
95
  }
121
- function audit(request, status, now2, errorCode) {
96
+ function getProof(context) {
97
+ return context.type === "qr" ? context.token : context.type === "passcode" ? context.code : context.type === "gps" ? { latitude: context.latitude, longitude: context.longitude } : context.type === "nfc" ? context.tagId : context.value;
98
+ }
99
+ async function evaluate(condition, context, validator, base) {
100
+ if (condition.type !== "custom") return core.evaluateConditionDetailed(condition, context).ok;
101
+ if (validator === void 0) return false;
102
+ const validationContext = {
103
+ rallyId: base.rallyId,
104
+ spotId: base.spotId,
105
+ proofData: getProof(context),
106
+ condition,
107
+ userState: base.state
108
+ };
109
+ const result = typeof validator === "function" ? await validator(validationContext) : await validator.validate(validationContext);
110
+ return result === true || typeof result === "object" && result.valid;
111
+ }
112
+ function audit(rallyId, userId, action, resourceId, key, status, timestamp, code) {
122
113
  return {
123
- id: `audit-${globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`}`,
124
- timestamp: now2,
125
- rallyId: request.rallyId,
126
- userId: request.userId,
127
- action: "CHECK_IN",
128
- resourceId: request.spotId,
114
+ id: requestId("audit"),
115
+ timestamp,
116
+ rallyId,
117
+ userId,
118
+ action,
119
+ resourceId,
129
120
  status,
130
- idempotencyKey: request.idempotencyKey,
131
- ...errorCode === void 0 ? {} : { metadata: { errorCode } }
121
+ idempotencyKey: key,
122
+ ...code === void 0 ? {} : { metadata: { errorCode: code } }
132
123
  };
133
124
  }
134
- var UniversalRallyServer = class {
125
+ var StampRallyServer = class {
135
126
  #config;
136
127
  #persistence;
137
128
  #options;
@@ -140,185 +131,87 @@ var UniversalRallyServer = class {
140
131
  this.#persistence = persistence;
141
132
  this.#options = options;
142
133
  }
143
- /** Web Standard endpoint handler. Authentication, when configured, supplies the user identity. */
134
+ async handle(request) {
135
+ if (request.method !== "POST")
136
+ return json({ ok: false, code: "METHOD_NOT_ALLOWED", message: "POST is required." }, 405);
137
+ const path = new URL(request.url).pathname;
138
+ if (path.endsWith("/check-in")) return this.handleCheckIn(request);
139
+ if (path.endsWith("/claim-reward")) return this.handleClaimReward(request);
140
+ if (path.endsWith("/sync")) return this.handleSync(request);
141
+ return json({ ok: false, code: "NOT_FOUND", message: "Route not found." }, 404);
142
+ }
144
143
  async handleCheckIn(request) {
145
- const body = await requestBody(request);
146
- const userId = await this.#authenticatedUser(request, body?.userId);
147
- if (this.#options.authenticate !== void 0 && userId === null)
148
- return json(
149
- { ok: false, error: { code: "UNAUTHORIZED", message: "Authentication is required." } },
150
- 401
151
- );
152
- if (body === null || userId === null || body.rallyId !== this.#config.id || body.spotId === "" || body.idempotencyKey === "")
144
+ const body = await this.#body(request);
145
+ const userId = await this.#user(request, body?.userId);
146
+ if (body === null || userId === null || body.rallyId !== this.#config.id || body.spotId === "" || body.idempotencyKey === "" || body.context === void 0)
153
147
  return json(
154
148
  {
155
149
  ok: false,
156
- error: {
157
- code: "INVALID_REQUEST",
158
- message: "rallyId, spotId, and idempotencyKey are required."
159
- }
150
+ code: "INVALID_REQUEST",
151
+ message: "rallyId, spotId, context, and idempotencyKey are required."
160
152
  },
161
153
  400
162
154
  );
163
- if (body.context === void 0)
164
- return json(
165
- { ok: false, error: { code: "INVALID_REQUEST", message: "context is required." } },
166
- 400
167
- );
168
155
  const result = await this.checkIn({ ...body, userId });
169
- return result.ok ? json(result) : json(result, result.code === "SPOT_NOT_FOUND" ? 404 : 422);
156
+ return json(result, result.ok ? 200 : result.code === "SPOT_NOT_FOUND" ? 404 : 422);
170
157
  }
171
158
  async handleClaimReward(request) {
172
- const body = await requestBody(request);
173
- const userId = await this.#authenticatedUser(request, body?.userId);
174
- if (this.#options.authenticate !== void 0 && userId === null)
175
- return json(
176
- { ok: false, error: { code: "UNAUTHORIZED", message: "Authentication is required." } },
177
- 401
178
- );
159
+ const body = await this.#body(request);
160
+ const userId = await this.#user(request, body?.userId);
179
161
  if (body === null || userId === null || body.rallyId !== this.#config.id || body.rewardId === "" || body.idempotencyKey === "")
180
162
  return json(
181
163
  {
182
164
  ok: false,
183
- error: {
184
- code: "INVALID_REQUEST",
185
- message: "rallyId, rewardId, and idempotencyKey are required."
186
- }
165
+ code: "INVALID_REQUEST",
166
+ message: "rallyId, rewardId, and idempotencyKey are required."
187
167
  },
188
168
  400
189
169
  );
190
- const key = `claim-reward:${body.rallyId}:${userId}:${body.rewardId}:${body.idempotencyKey}`;
191
- const previous = await this.#persistence.getIdempotentResult(key);
192
- if (previous !== null) return json(previous, previous.ok ? 200 : 422);
193
- const reward = this.#config.rewards.find((item) => item.id === body.rewardId);
194
- if (reward === void 0) {
195
- const failure = {
196
- ok: false,
197
- code: "REWARD_NOT_FOUND",
198
- message: "Reward was not found."
199
- };
200
- return json(await this.#rememberClaim(key, failure, body, userId), 404);
201
- }
202
- const timestamp = body.now ?? this.#options.now?.() ?? (/* @__PURE__ */ new Date()).toISOString();
203
- const current = await this.sync(body.rallyId, userId);
204
- const currentReward = current.rewards?.find((item) => item.rewardId === reward.id) ?? {
205
- rewardId: reward.id,
206
- status: "LOCKED"
207
- };
208
- const userClaims = await this.#getUserClaimCount(userId, reward.id);
209
- const local = core.consumeReward({
210
- reward: adminReward(reward),
211
- currentState: currentReward,
212
- now: timestamp,
213
- userId,
214
- userRedemptionCount: userClaims,
215
- ...body.staffPasscode === void 0 ? {} : { inputPasscode: body.staffPasscode },
216
- ...body.staffId === void 0 ? {} : { staffId: body.staffId }
217
- });
218
- if (!local.ok)
219
- return json(
220
- await this.#rememberClaim(
221
- key,
222
- {
223
- ok: false,
224
- code: local.error.code,
225
- message: "Reward cannot be claimed.",
226
- error: local.error
227
- },
228
- body,
229
- userId
230
- ),
231
- 422
232
- );
233
- const stock = await this.#persistence.decrementRewardStock(reward.id);
234
- if (!stock.success)
235
- return json(
236
- await this.#rememberClaim(
237
- key,
238
- { ok: false, code: "OUT_OF_STOCK", message: "Reward is out of stock." },
239
- body,
240
- userId
241
- ),
242
- 422
243
- );
244
- const next = {
245
- ...current,
246
- rewards: (current.rewards ?? []).map(
247
- (item) => item.rewardId === reward.id ? local.value : item
248
- ),
249
- updatedAt: timestamp
250
- };
251
- await this.#persistence.saveUserState(body.rallyId, userId, next);
252
- const success = local.value.claimTicketNumber === void 0 ? { ok: true, state: next } : { ok: true, state: next, claimTicketNumber: local.value.claimTicketNumber };
253
- await this.#persistence.saveIdempotentResult(
254
- key,
255
- success,
256
- this.#options.idempotencyTtlMs ?? 864e5
257
- );
258
- await this.#persistence.recordAuditLog({
259
- id: `audit-${globalThis.crypto?.randomUUID?.() ?? Date.now()}`,
260
- timestamp,
261
- rallyId: body.rallyId,
262
- userId,
263
- action: "CLAIM_REWARD",
264
- resourceId: reward.id,
265
- status: "SUCCESS",
266
- idempotencyKey: body.idempotencyKey
267
- });
268
- return json(success);
170
+ const result = await this.claimReward({ ...body, userId });
171
+ return json(result, result.ok ? 200 : result.code === "REWARD_NOT_FOUND" ? 404 : 422);
269
172
  }
270
173
  async handleSync(request) {
271
- const body = await requestBody(request);
272
- const userId = await this.#authenticatedUser(request, body?.userId);
273
- if (this.#options.authenticate !== void 0 && userId === null)
274
- return json(
275
- { ok: false, error: { code: "UNAUTHORIZED", message: "Authentication is required." } },
276
- 401
277
- );
174
+ const body = await this.#body(request);
175
+ const userId = await this.#user(request, body?.userId);
278
176
  if (body === null || userId === null || body.rallyId !== this.#config.id)
279
- return json(
280
- { ok: false, error: { code: "INVALID_REQUEST", message: "rallyId is required." } },
281
- 400
282
- );
177
+ return json({ ok: false, code: "INVALID_REQUEST", message: "rallyId is required." }, 400);
283
178
  return json({ ok: true, state: await this.sync(body.rallyId, userId) });
284
179
  }
285
- async handle(request) {
286
- if (request.method !== "POST")
287
- return json({ ok: false, error: { code: "METHOD_NOT_ALLOWED" } }, 405);
288
- const path = new URL(request.url).pathname;
289
- if (path.endsWith("/check-in")) return this.handleCheckIn(request);
290
- if (path.endsWith("/claim-reward")) return this.handleClaimReward(request);
291
- if (path.endsWith("/sync")) return this.handleSync(request);
292
- return json({ ok: false, error: { code: "NOT_FOUND" } }, 404);
293
- }
294
180
  async checkIn(request) {
295
181
  const key = `check-in:${request.rallyId}:${request.userId}:${request.idempotencyKey}`;
296
182
  const previous = await this.#persistence.getIdempotentResult(key);
297
183
  if (previous !== null) return previous;
298
184
  const lockKey = `state:${request.rallyId}:${request.userId}`;
299
- const locked = await this.#persistence.acquireLock(lockKey, this.#options.lockTtlMs ?? 5e3);
300
- if (!locked)
185
+ if (!await this.#persistence.acquireLock(lockKey, this.#options.lockTtlMs ?? 5e3))
301
186
  return { ok: false, code: "CONFLICT", message: "The user state is being updated." };
302
- const now2 = request.now ?? this.#options.now?.() ?? (/* @__PURE__ */ new Date()).toISOString();
187
+ const timestamp = now(this.#options, request.now);
303
188
  try {
304
189
  const spot = this.#config.spots.find((item) => item.id === request.spotId);
305
190
  if (spot === void 0)
306
191
  return this.#remember(
307
192
  key,
308
193
  { ok: false, code: "SPOT_NOT_FOUND", message: "Spot was not found." },
309
- request,
310
- now2
194
+ request.rallyId,
195
+ request.userId,
196
+ "CHECK_IN",
197
+ request.spotId,
198
+ request.idempotencyKey,
199
+ timestamp
311
200
  );
312
- const current = await this.#persistence.getUserState(request.rallyId, request.userId) ?? initialState(this.#config, now2);
201
+ const current = await this.#persistence.getUserState(request.rallyId, request.userId) ?? initialState(this.#config, request.userId, timestamp);
313
202
  if (current.records.some((record) => record.stampId === request.spotId))
314
203
  return this.#remember(
315
204
  key,
316
- { ok: false, code: "ALREADY_CLAIMED", message: "Spot was already claimed." },
317
- request,
318
- now2
205
+ { ok: false, code: "STAMP_ALREADY_ACQUIRED", message: "Spot was already claimed." },
206
+ request.rallyId,
207
+ request.userId,
208
+ "CHECK_IN",
209
+ request.spotId,
210
+ request.idempotencyKey,
211
+ timestamp
319
212
  );
320
213
  const acquired = new Set(current.records.map((record) => record.stampId));
321
- if (spot.prerequisites?.some((id2) => !acquired.has(id2)))
214
+ if (spot.prerequisites?.some((id) => !acquired.has(id)))
322
215
  return this.#remember(
323
216
  key,
324
217
  {
@@ -326,63 +219,202 @@ var UniversalRallyServer = class {
326
219
  code: "PREREQUISITES_NOT_MET",
327
220
  message: "Prerequisite spots are not complete."
328
221
  },
222
+ request.rallyId,
223
+ request.userId,
224
+ "CHECK_IN",
225
+ request.spotId,
226
+ request.idempotencyKey,
227
+ timestamp
228
+ );
229
+ for (const condition of spot.conditions)
230
+ if (!await evaluate(
231
+ condition,
232
+ request.context,
233
+ condition.type === "custom" ? this.#options.customValidators?.[condition.validatorName] : void 0,
234
+ { rallyId: request.rallyId, spotId: request.spotId, state: current }
235
+ ))
236
+ return this.#remember(
237
+ key,
238
+ { ok: false, code: "INVALID_PROOF", message: "Verification failed." },
239
+ request.rallyId,
240
+ request.userId,
241
+ "CHECK_IN",
242
+ request.spotId,
243
+ request.idempotencyKey,
244
+ timestamp
245
+ );
246
+ const next = {
247
+ ...current,
248
+ records: [...current.records, { stampId: request.spotId, acquiredAt: timestamp }],
249
+ rewards: core.reconcileRewardStates(
250
+ this.#config.rewards,
251
+ current.rewards,
252
+ current.records.length + 1,
253
+ timestamp
254
+ ),
255
+ updatedAt: timestamp
256
+ };
257
+ await this.#persistence.saveUserState(request.rallyId, request.userId, next);
258
+ return this.#remember(
259
+ key,
260
+ { ok: true, state: next },
261
+ request.rallyId,
262
+ request.userId,
263
+ "CHECK_IN",
264
+ request.spotId,
265
+ request.idempotencyKey,
266
+ timestamp
267
+ );
268
+ } finally {
269
+ await this.#persistence.releaseLock(lockKey);
270
+ }
271
+ }
272
+ async claimReward(request) {
273
+ const key = `claim:${request.rallyId}:${request.userId}:${request.rewardId}:${request.idempotencyKey}`;
274
+ const previous = await this.#persistence.getIdempotentResult(key);
275
+ if (previous !== null) return previous;
276
+ const reward = this.#config.rewards.find((item) => item.id === request.rewardId);
277
+ if (reward === void 0)
278
+ return this.#rememberClaim(
279
+ key,
280
+ { ok: false, code: "REWARD_NOT_FOUND", message: "Reward was not found." },
281
+ request,
282
+ now(this.#options, request.now)
283
+ );
284
+ const lockKey = `reward:${request.rallyId}:${reward.id}`;
285
+ if (!await this.#persistence.acquireLock(lockKey, this.#options.lockTtlMs ?? 5e3))
286
+ return { ok: false, code: "CONFLICT", message: "The reward is being claimed." };
287
+ const timestamp = now(this.#options, request.now);
288
+ let decremented = false;
289
+ try {
290
+ const checked = await this.#persistence.getIdempotentResult(key);
291
+ if (checked !== null) return checked;
292
+ const current = await this.#persistence.getUserState(request.rallyId, request.userId) ?? initialState(this.#config, request.userId, timestamp);
293
+ const claimCount = await this.#persistence.getUserClaimCount(
294
+ request.rallyId,
295
+ request.userId,
296
+ reward.id
297
+ );
298
+ const storedReward = current.rewards.find((item) => item.rewardId === reward.id) ?? {
299
+ rewardId: reward.id,
300
+ status: "LOCKED"
301
+ };
302
+ const currentReward = reward.redemptionMethod === "server_claim" && storedReward.status === "CONSUMED" && (reward.userClaimLimit === void 0 || claimCount < reward.userClaimLimit) ? { ...storedReward, status: "AVAILABLE" } : storedReward;
303
+ const local = core.consumeReward({
304
+ reward,
305
+ currentState: currentReward,
306
+ now: timestamp,
307
+ userRedemptionCount: claimCount,
308
+ ...request.staffPasscode === void 0 ? {} : { inputPasscode: request.staffPasscode },
309
+ ...request.staffId === void 0 ? {} : { staffId: request.staffId }
310
+ });
311
+ if (!local.ok)
312
+ return this.#rememberClaim(
313
+ key,
314
+ { ok: false, code: local.error.code, message: "Reward cannot be claimed." },
329
315
  request,
330
- now2
316
+ timestamp
331
317
  );
332
- if (!spot.conditions.every(
333
- (condition) => matchesCondition(condition, request.context, this.#options.customValidators)
334
- ))
335
- return this.#remember(
318
+ const stock = await this.#persistence.decrementRewardStock(reward.id);
319
+ if (!stock.success)
320
+ return this.#rememberClaim(
336
321
  key,
337
- { ok: false, code: "INVALID_PROOF", message: "Verification failed." },
322
+ { ok: false, code: "OUT_OF_STOCK", message: "Reward is out of stock." },
338
323
  request,
339
- now2
324
+ timestamp
340
325
  );
341
- const state = {
326
+ decremented = true;
327
+ const next = {
342
328
  ...current,
343
- records: [...current.records, { stampId: request.spotId, acquiredAt: now2 }],
344
- updatedAt: now2
329
+ rewards: current.rewards.map((item) => item.rewardId === reward.id ? local.value : item),
330
+ updatedAt: timestamp
331
+ };
332
+ try {
333
+ await this.#persistence.saveUserState(request.rallyId, request.userId, next);
334
+ const response = local.value.claimTicketNumber === void 0 ? { ok: true, state: next } : { ok: true, state: next, claimTicketNumber: local.value.claimTicketNumber };
335
+ await this.#persistence.recordAuditLog(
336
+ audit(
337
+ request.rallyId,
338
+ request.userId,
339
+ "CLAIM_REWARD",
340
+ reward.id,
341
+ request.idempotencyKey,
342
+ "SUCCESS",
343
+ timestamp
344
+ )
345
+ );
346
+ await this.#persistence.saveIdempotentResult(
347
+ key,
348
+ response,
349
+ this.#options.idempotencyTtlMs ?? 864e5
350
+ );
351
+ if (this.#persistence instanceof Object && "recordClaim" in this.#persistence && typeof this.#persistence.recordClaim === "function")
352
+ this.#persistence.recordClaim(request.rallyId, request.userId, reward.id);
353
+ return response;
354
+ } catch (error) {
355
+ await this.#persistence.incrementRewardStock(reward.id);
356
+ decremented = false;
357
+ throw error;
358
+ }
359
+ } catch (error) {
360
+ if (decremented) await this.#persistence.incrementRewardStock(reward.id);
361
+ return {
362
+ ok: false,
363
+ code: "PERSISTENCE_FAILED",
364
+ message: error instanceof Error ? error.message : "Reward claim failed."
345
365
  };
346
- await this.#persistence.saveUserState(request.rallyId, request.userId, state);
347
- return this.#remember(key, { ok: true, state }, request, now2);
348
366
  } finally {
349
367
  await this.#persistence.releaseLock(lockKey);
350
368
  }
351
369
  }
352
370
  async sync(rallyId, userId) {
353
- const now2 = this.#options.now?.() ?? (/* @__PURE__ */ new Date()).toISOString();
354
- return await this.#persistence.getUserState(rallyId, userId) ?? initialState(this.#config, now2);
371
+ return await this.#persistence.getUserState(rallyId, userId) ?? initialState(this.#config, userId, now(this.#options));
355
372
  }
356
- async #authenticatedUser(request, requestedUserId) {
357
- const authenticated = await this.#options.authenticate?.(request);
358
- if (this.#options.authenticate !== void 0) return authenticated ?? null;
359
- return requestedUserId ?? null;
373
+ async #body(request) {
374
+ try {
375
+ const value = await request.json();
376
+ return isObject(value) ? value : null;
377
+ } catch {
378
+ return null;
379
+ }
360
380
  }
361
- async #getUserClaimCount(userId, rewardId) {
362
- const state = await this.#persistence.getUserState(this.#config.id, userId);
363
- return state?.rewards?.find((item) => item.rewardId === rewardId)?.userRedemptionCount ?? 0;
381
+ async #user(request, requested) {
382
+ if (this.#options.authenticate !== void 0)
383
+ return await this.#options.authenticate(request) ?? null;
384
+ return requested ?? null;
364
385
  }
365
- async #rememberClaim(key, result, request, userId) {
386
+ async #remember(key, result, rallyId, userId, action, resourceId, idempotencyKey, timestamp) {
387
+ await this.#persistence.recordAuditLog(
388
+ audit(
389
+ rallyId,
390
+ userId,
391
+ action,
392
+ resourceId,
393
+ idempotencyKey,
394
+ result.ok ? "SUCCESS" : "REJECTED",
395
+ timestamp,
396
+ result.ok ? void 0 : result.code
397
+ )
398
+ );
366
399
  await this.#persistence.saveIdempotentResult(
367
400
  key,
368
401
  result,
369
402
  this.#options.idempotencyTtlMs ?? 864e5
370
403
  );
371
- await this.#persistence.recordAuditLog({
372
- id: `audit-${globalThis.crypto?.randomUUID?.() ?? Date.now()}`,
373
- timestamp: request.now ?? this.#options.now?.() ?? (/* @__PURE__ */ new Date()).toISOString(),
374
- rallyId: request.rallyId,
375
- userId,
376
- action: "CLAIM_REWARD",
377
- resourceId: request.rewardId,
378
- status: "REJECTED",
379
- idempotencyKey: request.idempotencyKey
380
- });
381
404
  return result;
382
405
  }
383
- async #remember(key, result, request, now2) {
406
+ async #rememberClaim(key, result, request, timestamp) {
384
407
  await this.#persistence.recordAuditLog(
385
- audit(request, result.ok ? "SUCCESS" : "REJECTED", now2, result.ok ? void 0 : result.code)
408
+ audit(
409
+ request.rallyId,
410
+ request.userId,
411
+ "CLAIM_REWARD",
412
+ request.rewardId,
413
+ request.idempotencyKey,
414
+ "REJECTED",
415
+ timestamp,
416
+ result.ok ? void 0 : result.code
417
+ )
386
418
  );
387
419
  await this.#persistence.saveIdempotentResult(
388
420
  key,
@@ -393,376 +425,7 @@ var UniversalRallyServer = class {
393
425
  }
394
426
  };
395
427
 
396
- // src/index.ts
397
- var InMemoryServerStorage = class {
398
- #states = /* @__PURE__ */ new Map();
399
- #stocks;
400
- #claims = /* @__PURE__ */ new Map();
401
- #auditLogs = [];
402
- constructor(options = {}) {
403
- this.#stocks = new Map(Object.entries(options.stocks ?? {}));
404
- }
405
- async getRewardStock(rewardId) {
406
- return this.#stocks.get(rewardId) ?? null;
407
- }
408
- async decrementRewardStock(rewardId) {
409
- const stock = this.#stocks.get(rewardId);
410
- if (stock === void 0) return true;
411
- if (stock <= 0) return false;
412
- this.#stocks.set(rewardId, stock - 1);
413
- return true;
414
- }
415
- async getUserClaims(userId, rewardId) {
416
- return this.#claims.get(`${userId}:${rewardId}`) ?? 0;
417
- }
418
- async recordAuditLog(log) {
419
- this.#auditLogs.push({ ...log });
420
- }
421
- async saveUserState(userId, state) {
422
- this.#states.set(userId, cloneUserState(state));
423
- }
424
- async getUserState(userId) {
425
- const state = this.#states.get(userId);
426
- return state === void 0 ? null : cloneUserState(state);
427
- }
428
- getAuditLogs() {
429
- return this.#auditLogs.map((log) => ({ ...log }));
430
- }
431
- recordClaim(userId, rewardId) {
432
- const key = `${userId}:${rewardId}`;
433
- this.#claims.set(key, (this.#claims.get(key) ?? 0) + 1);
434
- }
435
- };
436
- function cloneUserState(state) {
437
- return {
438
- ...state,
439
- records: state.records.map((record) => ({
440
- ...record,
441
- ...record.metadata === void 0 ? {} : { metadata: { ...record.metadata } }
442
- })),
443
- ...state.rewards === void 0 ? {} : { rewards: state.rewards.map((reward) => ({ ...reward })) }
444
- };
445
- }
446
- function jsonResponse(body, status = 200) {
447
- return new Response(JSON.stringify(body), {
448
- status,
449
- headers: { "content-type": "application/json; charset=utf-8" }
450
- });
451
- }
452
- function errorResponse(code, message, status) {
453
- return jsonResponse({ ok: false, error: { code, message } }, status);
454
- }
455
- function isObject(value) {
456
- return typeof value === "object" && value !== null && !Array.isArray(value);
457
- }
458
- function contextForClaim(method, proofData) {
459
- if (method === "token" || method === "qr" || method === "passcode") {
460
- return {
461
- type: "token",
462
- token: isObject(proofData) && typeof proofData.token === "string" ? proofData.token : String(proofData ?? "")
463
- };
464
- }
465
- if (method === "geo" || method === "geolocation") {
466
- const value = isObject(proofData) ? proofData : {};
467
- return {
468
- type: "geo",
469
- currentLatitude: typeof value.latitude === "number" ? value.latitude : typeof value.currentLatitude === "number" ? value.currentLatitude : Number.NaN,
470
- currentLongitude: typeof value.longitude === "number" ? value.longitude : typeof value.currentLongitude === "number" ? value.currentLongitude : Number.NaN
471
- };
472
- }
473
- return { type: "instant" };
474
- }
475
- function now() {
476
- return (/* @__PURE__ */ new Date()).toISOString();
477
- }
478
- function hasText(value) {
479
- return typeof value === "string" && value.trim() !== "";
480
- }
481
- function safeProofData(value) {
482
- return isObject(value) && typeof value.token === "string" ? { type: "token" } : value;
483
- }
484
- function proofFromContext(context) {
485
- if (context?.type === "token") return { token: context.token };
486
- if (context?.type === "geo") {
487
- return { latitude: context.currentLatitude, longitude: context.currentLongitude };
488
- }
489
- return void 0;
490
- }
491
- function id(prefix) {
492
- return `${prefix}-${globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`}`;
493
- }
494
- var StampRallyServer = class {
495
- #config;
496
- #storage;
497
- #idempotent = /* @__PURE__ */ new Map();
498
- #claims = /* @__PURE__ */ new Map();
499
- #queue = Promise.resolve();
500
- constructor(config, storage) {
501
- this.#config = config;
502
- this.#storage = storage;
503
- }
504
- handle(request) {
505
- const path = new URL(request.url).pathname;
506
- if (request.method !== "POST")
507
- return Promise.resolve(errorResponse("METHOD_NOT_ALLOWED", "POST is required.", 405));
508
- if (path.endsWith("/check-in")) return this.verifyCheckIn(request);
509
- if (path.endsWith("/claim-reward")) return this.claimReward(request);
510
- if (path.endsWith("/sync")) return this.syncProgress(request);
511
- return Promise.resolve(errorResponse("NOT_FOUND", "Route not found.", 404));
512
- }
513
- verifyCheckIn(request) {
514
- return this.#enqueue(() => this.#verifyCheckIn(request));
515
- }
516
- claimReward(request) {
517
- return this.#enqueue(() => this.#claimReward(request));
518
- }
519
- syncProgress(request) {
520
- return this.#enqueue(() => this.#syncProgress(request));
521
- }
522
- #enqueue(operation) {
523
- const next = this.#queue.then(operation, operation);
524
- this.#queue = next.then(
525
- () => void 0,
526
- () => void 0
527
- );
528
- return next;
529
- }
530
- async #authenticate(request) {
531
- return this.#config.authenticate === void 0 ? null : this.#config.authenticate(request);
532
- }
533
- async #parse(request) {
534
- try {
535
- const value = await request.json();
536
- return isObject(value) ? value : null;
537
- } catch {
538
- return null;
539
- }
540
- }
541
- async #verifyCheckIn(request) {
542
- const authenticatedUser = await this.#authenticate(request);
543
- const body = await this.#parse(request);
544
- const userId = body?.userId ?? authenticatedUser;
545
- if (userId === null || userId === void 0 || body === null || !hasText(userId) || !hasText(body.spotId) || !hasText(body.claimMethod) || !hasText(body.idempotencyKey)) {
546
- return errorResponse(
547
- "INVALID_REQUEST",
548
- "userId, spotId, and idempotencyKey are required.",
549
- 400
550
- );
551
- }
552
- if (authenticatedUser !== null && authenticatedUser !== userId)
553
- return errorResponse("UNAUTHORIZED", "User identity does not match authentication.", 401);
554
- const key = `check-in:${userId}:${body.idempotencyKey}`;
555
- const previous = this.#idempotent.get(key);
556
- if (previous !== void 0) return previous.clone();
557
- const timestamp = now();
558
- const current = await this.#storage.getUserState(userId) ?? emptyState(this.#config, timestamp);
559
- const result = core.processStamp(
560
- current,
561
- this.#config,
562
- body.spotId,
563
- contextForClaim(body.claimMethod, body.proofData),
564
- timestamp
565
- );
566
- if (!result.ok) {
567
- await this.#audit(
568
- userId,
569
- "CHECK_IN",
570
- body.spotId,
571
- body.idempotencyKey,
572
- "REJECTED",
573
- safeProofData(body.proofData),
574
- result.error
575
- );
576
- return this.#remember(key, jsonResponse({ ok: false, error: result.error }, 422));
577
- }
578
- const ttl = this.#config.proofTtlSeconds ?? 3600;
579
- const token = await core.createSecureToken(
580
- {
581
- type: "stamp_claim",
582
- rallyId: this.#config.id,
583
- userId,
584
- spotId: body.spotId,
585
- acquiredAt: timestamp,
586
- exp: Math.floor(Date.now() / 1e3) + ttl
587
- },
588
- this.#config.secretKey,
589
- { encrypt: true }
590
- );
591
- await this.#storage.saveUserState(userId, result.value.nextState);
592
- await this.#audit(
593
- userId,
594
- "CHECK_IN",
595
- body.spotId,
596
- body.idempotencyKey,
597
- "SUCCESS",
598
- safeProofData(body.proofData)
599
- );
600
- return this.#remember(
601
- key,
602
- jsonResponse({
603
- ok: true,
604
- state: result.value.nextState,
605
- proof: {
606
- token,
607
- rallyId: this.#config.id,
608
- userId,
609
- spotId: body.spotId,
610
- acquiredAt: timestamp
611
- }
612
- })
613
- );
614
- }
615
- async #claimReward(request) {
616
- const authenticatedUser = await this.#authenticate(request);
617
- const body = await this.#parse(request);
618
- const userId = body?.userId ?? authenticatedUser;
619
- if (userId === null || userId === void 0 || body === null || !hasText(userId) || !hasText(body.rewardId) || !hasText(body.idempotencyKey))
620
- return errorResponse(
621
- "INVALID_REQUEST",
622
- "userId, rewardId, and idempotencyKey are required.",
623
- 400
624
- );
625
- if (authenticatedUser !== null && authenticatedUser !== userId)
626
- return errorResponse("UNAUTHORIZED", "User identity does not match authentication.", 401);
627
- const key = `claim-reward:${userId}:${body.rewardId}:${body.idempotencyKey}`;
628
- const previous = this.#idempotent.get(key);
629
- if (previous !== void 0) return previous.clone();
630
- const reward = this.#config.rewards?.find((item) => item.id === body.rewardId);
631
- if (reward === void 0) {
632
- await this.#audit(userId, "CLAIM_REWARD", body.rewardId, body.idempotencyKey, "REJECTED");
633
- return this.#remember(key, errorResponse("REWARD_NOT_FOUND", "Reward was not found.", 404));
634
- }
635
- const timestamp = now();
636
- const current = await this.#storage.getUserState(userId) ?? emptyState(this.#config, timestamp);
637
- const rewardState = current.rewards?.find((item) => item.rewardId === reward.id);
638
- if (rewardState === void 0) {
639
- await this.#audit(userId, "CLAIM_REWARD", reward.id, body.idempotencyKey, "REJECTED");
640
- return this.#remember(key, errorResponse("NOT_AVAILABLE", "Reward is not available.", 422));
641
- }
642
- const userClaims = Math.max(
643
- await this.#storage.getUserClaims(userId, reward.id),
644
- this.#claims.get(`${userId}:${reward.id}`) ?? 0
645
- );
646
- const stock = await this.#storage.getRewardStock(reward.id);
647
- const userLimit = reward.userClaimLimit ?? reward.limitPerUser;
648
- const canReclaimServerReward = reward.redemptionMethod === "server_claim" && (userLimit === void 0 || userClaims < userLimit) && (stock === null || stock > 0);
649
- const claimableState = canReclaimServerReward && rewardState.status === "CONSUMED" ? { ...rewardState, status: "AVAILABLE" } : rewardState;
650
- const local = core.consumeReward({
651
- reward,
652
- currentState: claimableState,
653
- now: timestamp,
654
- ...body.staffPasscode === void 0 ? {} : { inputPasscode: body.staffPasscode },
655
- ...body.staffId === void 0 ? {} : { staffId: body.staffId },
656
- userId,
657
- userRedemptionCount: userClaims
658
- });
659
- if (!local.ok)
660
- return this.#remember(
661
- key,
662
- await this.#rewardError(userId, reward.id, body.idempotencyKey, local.error)
663
- );
664
- if (stock !== null && !await this.#storage.decrementRewardStock(reward.id))
665
- return this.#remember(
666
- key,
667
- await this.#rewardError(userId, reward.id, body.idempotencyKey, {
668
- code: "OUT_OF_STOCK",
669
- rewardId: reward.id
670
- })
671
- );
672
- const nextState = {
673
- ...current,
674
- rewards: (current.rewards ?? []).map(
675
- (item) => item.rewardId === reward.id ? local.value : item
676
- ),
677
- updatedAt: timestamp
678
- };
679
- await this.#storage.saveUserState(userId, nextState);
680
- const claimKey = `${userId}:${reward.id}`;
681
- this.#claims.set(claimKey, userClaims + 1);
682
- if (this.#storage instanceof InMemoryServerStorage)
683
- this.#storage.recordClaim(userId, reward.id);
684
- await this.#audit(userId, "CLAIM_REWARD", reward.id, body.idempotencyKey, "SUCCESS", {
685
- staffId: body.staffId
686
- });
687
- return this.#remember(
688
- key,
689
- jsonResponse({
690
- ok: true,
691
- state: nextState,
692
- claimTicketNumber: local.value.claimTicketNumber
693
- })
694
- );
695
- }
696
- async #rewardError(userId, rewardId, key, error) {
697
- await this.#audit(userId, "CLAIM_REWARD", rewardId, key, "REJECTED", void 0, error);
698
- return jsonResponse({ ok: false, error }, 422);
699
- }
700
- async #syncProgress(request) {
701
- const authenticatedUser = await this.#authenticate(request);
702
- const body = await this.#parse(request);
703
- if (body === null || body.userId === void 0)
704
- return errorResponse("INVALID_REQUEST", "userId is required.", 400);
705
- if (authenticatedUser !== null && authenticatedUser !== body.userId)
706
- return errorResponse("UNAUTHORIZED", "User identity does not match authentication.", 401);
707
- const queue = body.queue ?? body.operations ?? [];
708
- for (const operation of queue) {
709
- const userId = operation.userId ?? body.userId;
710
- const spotId = operation.spotId ?? operation.stampId;
711
- const claimMethod = operation.claimMethod ?? operation.context?.type;
712
- if (!hasText(userId) || !hasText(spotId) || !hasText(claimMethod)) continue;
713
- const synthetic = new Request(new URL("/api/check-in", request.url), {
714
- method: "POST",
715
- body: JSON.stringify({
716
- userId,
717
- spotId,
718
- claimMethod,
719
- proofData: operation.proofData ?? proofFromContext(operation.context),
720
- idempotencyKey: operation.idempotencyKey
721
- }),
722
- headers: { "content-type": "application/json" }
723
- });
724
- await this.#verifyCheckIn(synthetic);
725
- }
726
- const timestamp = now();
727
- const state = await this.#storage.getUserState(body.userId) ?? emptyState(this.#config, timestamp);
728
- await this.#storage.saveUserState(body.userId, state);
729
- return jsonResponse({ ok: true, state, accepted: queue.length });
730
- }
731
- async #audit(userId, action, resourceId, idempotencyKey, status, proofData, error) {
732
- await this.#storage.recordAuditLog({
733
- id: id("audit"),
734
- timestamp: now(),
735
- rallyId: this.#config.id,
736
- userId,
737
- action,
738
- resourceId,
739
- status,
740
- idempotencyKey,
741
- ...proofData === void 0 ? {} : { proofData },
742
- ...error === void 0 ? {} : {
743
- metadata: {
744
- errorCode: isObject(error) && typeof error.code === "string" ? error.code : "UNKNOWN"
745
- }
746
- }
747
- });
748
- }
749
- #remember(key, response) {
750
- this.#idempotent.set(key, response.clone());
751
- return response;
752
- }
753
- };
754
- function emptyState(config, timestamp) {
755
- return {
756
- rallyId: config.id,
757
- records: [],
758
- ...config.rewards === void 0 ? {} : { rewards: core.reconcileRewardStates(config.rewards, [], 0, timestamp) },
759
- updatedAt: timestamp
760
- };
761
- }
762
-
763
428
  exports.InMemoryServerPersistenceAdapter = InMemoryServerPersistenceAdapter;
764
- exports.InMemoryServerStorage = InMemoryServerStorage;
765
429
  exports.StampRallyServer = StampRallyServer;
766
- exports.UniversalRallyServer = UniversalRallyServer;
767
430
  //# sourceMappingURL=index.cjs.map
768
431
  //# sourceMappingURL=index.cjs.map