@dejadex/web 0.0.0-stage → 0.1.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 (113) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +214 -2
  3. package/dist/errors.d.ts +8 -0
  4. package/dist/errors.d.ts.map +1 -0
  5. package/dist/errors.js +9 -0
  6. package/dist/errors.js.map +1 -0
  7. package/dist/geometry/homography.d.ts +75 -0
  8. package/dist/geometry/homography.d.ts.map +1 -0
  9. package/dist/geometry/homography.js +146 -0
  10. package/dist/geometry/homography.js.map +1 -0
  11. package/dist/identify/assets.d.ts +39 -0
  12. package/dist/identify/assets.d.ts.map +1 -0
  13. package/dist/identify/assets.js +167 -0
  14. package/dist/identify/assets.js.map +1 -0
  15. package/dist/identify/decode.d.ts +6 -0
  16. package/dist/identify/decode.d.ts.map +1 -0
  17. package/dist/identify/decode.js +53 -0
  18. package/dist/identify/decode.js.map +1 -0
  19. package/dist/identify/engine.d.ts +32 -0
  20. package/dist/identify/engine.d.ts.map +1 -0
  21. package/dist/identify/engine.js +127 -0
  22. package/dist/identify/engine.js.map +1 -0
  23. package/dist/identify/identifier.d.ts +81 -0
  24. package/dist/identify/identifier.d.ts.map +1 -0
  25. package/dist/identify/identifier.js +327 -0
  26. package/dist/identify/identifier.js.map +1 -0
  27. package/dist/identify/manifest.d.ts +60 -0
  28. package/dist/identify/manifest.d.ts.map +1 -0
  29. package/dist/identify/manifest.js +211 -0
  30. package/dist/identify/manifest.js.map +1 -0
  31. package/dist/identify/preprocess.d.ts +52 -0
  32. package/dist/identify/preprocess.d.ts.map +1 -0
  33. package/dist/identify/preprocess.js +195 -0
  34. package/dist/identify/preprocess.js.map +1 -0
  35. package/dist/identify/router.d.ts +60 -0
  36. package/dist/identify/router.d.ts.map +1 -0
  37. package/dist/identify/router.js +83 -0
  38. package/dist/identify/router.js.map +1 -0
  39. package/dist/identify/runtime.d.ts +69 -0
  40. package/dist/identify/runtime.d.ts.map +1 -0
  41. package/dist/identify/runtime.js +140 -0
  42. package/dist/identify/runtime.js.map +1 -0
  43. package/dist/identify/search.d.ts +35 -0
  44. package/dist/identify/search.d.ts.map +1 -0
  45. package/dist/identify/search.js +99 -0
  46. package/dist/identify/search.js.map +1 -0
  47. package/dist/identify/server.d.ts +60 -0
  48. package/dist/identify/server.d.ts.map +1 -0
  49. package/dist/identify/server.js +149 -0
  50. package/dist/identify/server.js.map +1 -0
  51. package/dist/identify/shard.d.ts +31 -0
  52. package/dist/identify/shard.d.ts.map +1 -0
  53. package/dist/identify/shard.js +146 -0
  54. package/dist/identify/shard.js.map +1 -0
  55. package/dist/identify/types.d.ts +107 -0
  56. package/dist/identify/types.d.ts.map +1 -0
  57. package/dist/identify/types.js +7 -0
  58. package/dist/identify/types.js.map +1 -0
  59. package/dist/identify/worker.d.ts +2 -0
  60. package/dist/identify/worker.d.ts.map +1 -0
  61. package/dist/identify/worker.js +13 -0
  62. package/dist/identify/worker.js.map +1 -0
  63. package/dist/identify/workerProtocol.d.ts +54 -0
  64. package/dist/identify/workerProtocol.d.ts.map +1 -0
  65. package/dist/identify/workerProtocol.js +113 -0
  66. package/dist/identify/workerProtocol.js.map +1 -0
  67. package/dist/index.d.ts +20 -0
  68. package/dist/index.d.ts.map +1 -0
  69. package/dist/index.js +16 -0
  70. package/dist/index.js.map +1 -0
  71. package/dist/lease/verify.d.ts +69 -0
  72. package/dist/lease/verify.d.ts.map +1 -0
  73. package/dist/lease/verify.js +235 -0
  74. package/dist/lease/verify.js.map +1 -0
  75. package/dist/scanner.d.ts +10 -0
  76. package/dist/scanner.d.ts.map +1 -0
  77. package/dist/scanner.js +58 -0
  78. package/dist/scanner.js.map +1 -0
  79. package/dist/types.d.ts +180 -0
  80. package/dist/types.d.ts.map +1 -0
  81. package/dist/types.js +2 -0
  82. package/dist/types.js.map +1 -0
  83. package/dist/usage/meter.d.ts +83 -0
  84. package/dist/usage/meter.d.ts.map +1 -0
  85. package/dist/usage/meter.js +111 -0
  86. package/dist/usage/meter.js.map +1 -0
  87. package/dist/usage/store.d.ts +52 -0
  88. package/dist/usage/store.d.ts.map +1 -0
  89. package/dist/usage/store.js +198 -0
  90. package/dist/usage/store.js.map +1 -0
  91. package/package.json +64 -4
  92. package/src/errors.ts +24 -0
  93. package/src/geometry/homography.ts +178 -0
  94. package/src/identify/assets.ts +189 -0
  95. package/src/identify/decode.ts +54 -0
  96. package/src/identify/engine.ts +167 -0
  97. package/src/identify/identifier.ts +419 -0
  98. package/src/identify/manifest.ts +240 -0
  99. package/src/identify/preprocess.ts +227 -0
  100. package/src/identify/router.ts +115 -0
  101. package/src/identify/runtime.ts +197 -0
  102. package/src/identify/search.ts +115 -0
  103. package/src/identify/server.ts +167 -0
  104. package/src/identify/shard.ts +154 -0
  105. package/src/identify/types.ts +122 -0
  106. package/src/identify/worker.ts +13 -0
  107. package/src/identify/workerProtocol.ts +136 -0
  108. package/src/index.ts +71 -0
  109. package/src/lease/verify.ts +252 -0
  110. package/src/scanner.ts +56 -0
  111. package/src/types.ts +196 -0
  112. package/src/usage/meter.ts +165 -0
  113. package/src/usage/store.ts +245 -0
@@ -0,0 +1,245 @@
1
+ /**
2
+ * The device's usage queue: what was counted waits here, across reloads,
3
+ * until the host has delivered it. IndexedDB in the browser; an in-memory
4
+ * store for tests and for runtimes without IndexedDB (where usage then lives
5
+ * only as long as the page).
6
+ *
7
+ * Two stages:
8
+ * - a **tally** per (lease, session) collects the cards first identified in
9
+ * that session and the number of calls, as answers come in;
10
+ * - `seal` turns every open tally into a `UsageReport` with the lease's next
11
+ * `seq` and a fresh `reportId`, atomically. A sealed report never changes,
12
+ * so delivering it twice is harmless (the service dedupes by `reportId`).
13
+ *
14
+ * Database `dejadex-usage`, version 1:
15
+ * tallies key `<leaseId>\n<sessionId>` → Tally
16
+ * reports keyPath `report.reportId`, index `order` → { order, report }
17
+ * meta `deviceId`, `order`, `seq:<leaseId>`, `reported:<leaseId>`
18
+ */
19
+ import type { UsageReport } from '../types.js'
20
+
21
+ export interface Tally {
22
+ readonly leaseId: string
23
+ readonly sessionId: string
24
+ /** Distinct, in first-seen order. */
25
+ readonly cardIds: readonly string[]
26
+ readonly calls: number
27
+ /** Device clock (ms) of the latest addition. */
28
+ readonly at: number
29
+ }
30
+
31
+ export interface UsageStore {
32
+ /** A random per-install id (at least 128 bits), created on first use. */
33
+ deviceId(): Promise<string>
34
+ /** Adds cards (deduplicated) and calls to the open tally of (lease, session). */
35
+ tally(leaseId: string, sessionId: string, cardIds: readonly string[], calls: number, at: number): Promise<void>
36
+ /** Seals every open tally into a queued report; returns how many were sealed. */
37
+ seal(newReportId: () => string): Promise<number>
38
+ /** The oldest `limit` queued reports, in queue order. */
39
+ peek(limit: number): Promise<readonly UsageReport[]>
40
+ remove(reportIds: readonly string[]): Promise<void>
41
+ /** Records that these reports were delivered: each lease's highest delivered `seq`. */
42
+ markReported(reports: readonly UsageReport[]): Promise<void>
43
+ /** The highest delivered `seq` of a lease, or null when none was. */
44
+ reportedThrough(leaseId: string): Promise<number | null>
45
+ /** Queued reports plus open tallies. */
46
+ size(): Promise<number>
47
+ }
48
+
49
+ export function randomId(bytes = 16): string {
50
+ const b = new Uint8Array(bytes)
51
+ crypto.getRandomValues(b)
52
+ let out = ''
53
+ for (const x of b) out += x.toString(16).padStart(2, '0')
54
+ return out
55
+ }
56
+
57
+ const tallyKey = (leaseId: string, sessionId: string): string => `${leaseId}\n${sessionId}`
58
+
59
+ function merge(prev: Tally | undefined, leaseId: string, sessionId: string, cardIds: readonly string[], calls: number, at: number): Tally {
60
+ const cards = [...(prev?.cardIds ?? [])]
61
+ for (const id of cardIds) if (!cards.includes(id)) cards.push(id)
62
+ return { leaseId, sessionId, cardIds: cards, calls: (prev?.calls ?? 0) + calls, at }
63
+ }
64
+
65
+ const toReport = (t: Tally, seq: number, reportId: string): UsageReport => ({
66
+ reportId,
67
+ leaseId: t.leaseId,
68
+ seq,
69
+ sessionId: t.sessionId,
70
+ distinctCards: t.cardIds.length,
71
+ cardIds: [...t.cardIds],
72
+ calls: t.calls,
73
+ at: t.at,
74
+ })
75
+
76
+ export function memoryUsageStore(): UsageStore {
77
+ let device: string | null = null
78
+ const seq = new Map<string, number>()
79
+ const tallies = new Map<string, Tally>()
80
+ const queue: UsageReport[] = []
81
+ const reported = new Map<string, number>()
82
+ return {
83
+ async deviceId() {
84
+ device ??= randomId()
85
+ return device
86
+ },
87
+ async tally(leaseId, sessionId, cardIds, calls, at) {
88
+ const key = tallyKey(leaseId, sessionId)
89
+ tallies.set(key, merge(tallies.get(key), leaseId, sessionId, cardIds, calls, at))
90
+ },
91
+ async seal(newReportId) {
92
+ const open = [...tallies.values()]
93
+ tallies.clear()
94
+ for (const t of open) {
95
+ const next = (seq.get(t.leaseId) ?? 0) + 1
96
+ seq.set(t.leaseId, next)
97
+ queue.push(toReport(t, next, newReportId()))
98
+ }
99
+ return open.length
100
+ },
101
+ async peek(limit) {
102
+ return queue.slice(0, limit)
103
+ },
104
+ async remove(ids) {
105
+ const drop = new Set(ids)
106
+ for (let i = queue.length - 1; i >= 0; i--) if (drop.has((queue[i] as UsageReport).reportId)) queue.splice(i, 1)
107
+ },
108
+ async markReported(reports) {
109
+ for (const r of reports) reported.set(r.leaseId, Math.max(reported.get(r.leaseId) ?? 0, r.seq))
110
+ },
111
+ async reportedThrough(leaseId) {
112
+ return reported.get(leaseId) ?? null
113
+ },
114
+ async size() {
115
+ return queue.length + tallies.size
116
+ },
117
+ }
118
+ }
119
+
120
+ const DB_NAME = 'dejadex-usage'
121
+ const DB_VERSION = 1
122
+
123
+ function request<T>(req: IDBRequest<T>): Promise<T> {
124
+ return new Promise((resolve, reject) => {
125
+ req.onsuccess = () => resolve(req.result)
126
+ req.onerror = () => reject(req.error ?? new Error('IndexedDB request failed'))
127
+ })
128
+ }
129
+
130
+ function done(tx: IDBTransaction): Promise<void> {
131
+ return new Promise((resolve, reject) => {
132
+ tx.oncomplete = () => resolve()
133
+ tx.onabort = () => reject(tx.error ?? new Error('IndexedDB transaction aborted'))
134
+ tx.onerror = () => reject(tx.error ?? new Error('IndexedDB transaction failed'))
135
+ })
136
+ }
137
+
138
+ interface QueuedRow {
139
+ readonly order: number
140
+ readonly report: UsageReport
141
+ }
142
+
143
+ /** The IndexedDB store. `factory` defaults to the global `indexedDB`. */
144
+ export async function indexedDbUsageStore(factory: IDBFactory = indexedDB): Promise<UsageStore> {
145
+ const open = factory.open(DB_NAME, DB_VERSION)
146
+ open.onupgradeneeded = () => {
147
+ const db = open.result
148
+ if (!db.objectStoreNames.contains('tallies')) db.createObjectStore('tallies')
149
+ if (!db.objectStoreNames.contains('reports')) {
150
+ db.createObjectStore('reports', { keyPath: 'report.reportId' }).createIndex('order', 'order', { unique: true })
151
+ }
152
+ if (!db.objectStoreNames.contains('meta')) db.createObjectStore('meta')
153
+ }
154
+ const db = await request(open)
155
+
156
+ return {
157
+ async deviceId() {
158
+ const tx = db.transaction('meta', 'readwrite')
159
+ const meta = tx.objectStore('meta')
160
+ let id = (await request(meta.get('deviceId'))) as unknown
161
+ if (typeof id !== 'string') {
162
+ id = randomId()
163
+ meta.put(id, 'deviceId')
164
+ }
165
+ await done(tx)
166
+ return id as string
167
+ },
168
+ async tally(leaseId, sessionId, cardIds, calls, at) {
169
+ const tx = db.transaction('tallies', 'readwrite')
170
+ const store = tx.objectStore('tallies')
171
+ const key = tallyKey(leaseId, sessionId)
172
+ const prev = (await request(store.get(key))) as Tally | undefined
173
+ store.put(merge(prev, leaseId, sessionId, cardIds, calls, at), key)
174
+ await done(tx)
175
+ },
176
+ async seal(newReportId) {
177
+ const tx = db.transaction(['tallies', 'reports', 'meta'], 'readwrite')
178
+ const tallies = tx.objectStore('tallies')
179
+ const reports = tx.objectStore('reports')
180
+ const meta = tx.objectStore('meta')
181
+ const open = (await request(tallies.getAll())) as Tally[]
182
+ let order = ((await request(meta.get('order'))) as number | undefined) ?? 0
183
+ const seqs = new Map<string, number>()
184
+ for (const t of open) {
185
+ const key = `seq:${t.leaseId}`
186
+ let last = seqs.get(key)
187
+ if (last === undefined) last = ((await request(meta.get(key))) as number | undefined) ?? 0
188
+ const next = last + 1
189
+ seqs.set(key, next)
190
+ reports.put({ order: ++order, report: toReport(t, next, newReportId()) } satisfies QueuedRow)
191
+ }
192
+ for (const [key, value] of seqs) meta.put(value, key)
193
+ meta.put(order, 'order')
194
+ tallies.clear()
195
+ await done(tx)
196
+ return open.length
197
+ },
198
+ async peek(limit) {
199
+ const tx = db.transaction('reports', 'readonly')
200
+ const rows = (await request(tx.objectStore('reports').index('order').getAll(null, limit))) as QueuedRow[]
201
+ await done(tx)
202
+ return rows.map((r) => r.report)
203
+ },
204
+ async remove(ids) {
205
+ const tx = db.transaction('reports', 'readwrite')
206
+ const store = tx.objectStore('reports')
207
+ for (const id of ids) store.delete(id)
208
+ await done(tx)
209
+ },
210
+ async markReported(reports) {
211
+ const tx = db.transaction('meta', 'readwrite')
212
+ const meta = tx.objectStore('meta')
213
+ const top = new Map<string, number>()
214
+ for (const r of reports) top.set(r.leaseId, Math.max(top.get(r.leaseId) ?? 0, r.seq))
215
+ for (const [leaseId, seq] of top) {
216
+ const key = `reported:${leaseId}`
217
+ const prev = (await request(meta.get(key))) as number | undefined
218
+ if (prev === undefined || seq > prev) meta.put(seq, key)
219
+ }
220
+ await done(tx)
221
+ },
222
+ async reportedThrough(leaseId) {
223
+ const tx = db.transaction('meta', 'readonly')
224
+ const v = (await request(tx.objectStore('meta').get(`reported:${leaseId}`))) as number | undefined
225
+ await done(tx)
226
+ return v ?? null
227
+ },
228
+ async size() {
229
+ const tx = db.transaction(['reports', 'tallies'], 'readonly')
230
+ const [a, b] = await Promise.all([request(tx.objectStore('reports').count()), request(tx.objectStore('tallies').count())])
231
+ await done(tx)
232
+ return a + b
233
+ },
234
+ }
235
+ }
236
+
237
+ /** IndexedDB where it opens, else memory (private windows can refuse it). */
238
+ export async function defaultUsageStore(): Promise<UsageStore> {
239
+ try {
240
+ if (typeof indexedDB !== 'undefined') return await indexedDbUsageStore()
241
+ } catch {
242
+ // fall through to memory
243
+ }
244
+ return memoryUsageStore()
245
+ }