@quran-lab/tajweedformer 0.0.0-stage → 2.0.1

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 (51) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/LICENSE +148 -0
  3. package/README.md +121 -2
  4. package/dist/tajweedformer-opus.mjs +2 -0
  5. package/dist/tajweedformer-opus.wasm +0 -0
  6. package/dist/tajweedformer-scorer.mjs +2 -0
  7. package/dist/tajweedformer-scorer.wasm +0 -0
  8. package/dist/tajweedformer.mjs +2 -0
  9. package/dist/tajweedformer.wasm +0 -0
  10. package/docs/api.md +167 -0
  11. package/examples/browser.html +69 -0
  12. package/examples/node.mjs +37 -0
  13. package/package.json +81 -6
  14. package/web/consent/copy.js +51 -0
  15. package/web/consent/decks.js +470 -0
  16. package/web/consent/element.js +170 -0
  17. package/web/consent/index.d.ts +128 -0
  18. package/web/consent/index.js +239 -0
  19. package/web/consent/state.js +162 -0
  20. package/web/consent/theme.js +31 -0
  21. package/web/consent/wording.js +126 -0
  22. package/web/index.d.ts +4 -0
  23. package/web/index.js +10 -0
  24. package/web/platform/client.js +484 -0
  25. package/web/platform/contributor-key.js +112 -0
  26. package/web/platform/index.d.ts +148 -0
  27. package/web/platform/index.js +8 -0
  28. package/web/platform/storage.js +50 -0
  29. package/web/platform/telemetry.js +314 -0
  30. package/web/platform/update-notice.js +60 -0
  31. package/web/scorer.d.ts +4 -0
  32. package/web/scorer.js +10 -0
  33. package/web/sharing/bitrate.js +69 -0
  34. package/web/sharing/encoder.js +176 -0
  35. package/web/sharing/index.d.ts +262 -0
  36. package/web/sharing/index.js +287 -0
  37. package/web/sharing/oggopus.js +325 -0
  38. package/web/sharing/outbox.js +670 -0
  39. package/web/sharing/resampler.js +122 -0
  40. package/web/sharing/uploader.js +178 -0
  41. package/web/tajweed/decode.js +213 -0
  42. package/web/tajweed/delivery.js +317 -0
  43. package/web/tajweed/engine.js +600 -0
  44. package/web/tajweed/heads.js +73 -0
  45. package/web/tajweed/index.d.ts +737 -0
  46. package/web/tajweed/index.js +12 -0
  47. package/web/tajweed/manifest.js +452 -0
  48. package/web/tajweed/node.d.ts +3 -0
  49. package/web/tajweed/node.js +59 -0
  50. package/web/tajweed/settings.js +483 -0
  51. package/web/tajweed/tajweedformer.js +369 -0
@@ -0,0 +1,148 @@
1
+ // Types for @quran-lab/tajweedformer/platform: the Quran Lab platform client.
2
+
3
+ export declare const SDK_VERSION: '2.0.1';
4
+ export declare const API_URL: string;
5
+ export declare const CDN_URL: string;
6
+
7
+ /** Persistence for small JSON state. */
8
+ export interface StateStore { kind: string; get(key: string): any; set(key: string, value: unknown): void }
9
+ export declare function memoryState(): StateStore;
10
+ /** localStorage (per origin), falling back to memory. */
11
+ export declare function localState(prefix?: string): StateStore;
12
+ /** Node: a directory of JSON files (0600). */
13
+ export declare function dirState(dir: string): Promise<StateStore>;
14
+
15
+ export declare class PlatformError extends Error { readonly status: number; readonly code: string }
16
+
17
+ export interface SignedConfig {
18
+ v: 1; app: string; channel: string; issued_at: number; expires_at: number;
19
+ models: Record<string, { revision: string; source: string; model_id?: string; folder?: string }>;
20
+ recommended: { model: string; model_id: string; folder: string; revision: string; source: string } | null;
21
+ denylist: Record<string, string>[];
22
+ flags: { analytics?: boolean; issues?: boolean; contributions?: boolean; upload_trust?: Record<string, 'off' | 'capped' | 'attested'>; [k: string]: unknown };
23
+ tajweed?: unknown;
24
+ /** where model files are served (qlab-api signs it): {base}/{model}/{revision}/{folder}/ */
25
+ base?: string;
26
+ /** the newest SDK for this platform (2.0.1); other unknown fields are ignored too */
27
+ sdk_latest?: { version: string; severity: string; url: string };
28
+ }
29
+
30
+ export interface QuranLabOptions {
31
+ /** the developer key qlk_v1_... (a web key in browsers, origin-locked; a desktop key from Node) */
32
+ key: string;
33
+ appVersion?: string;
34
+ appName?: string;
35
+ /** 'web' in browsers; in Node 'web' (with origin), 'linux' or 'windows' */
36
+ platform?: 'web' | 'linux' | 'windows';
37
+ /** web: the page's origin (default location.origin); desktop: the reverse-DNS or package id */
38
+ bundleId?: string;
39
+ /** Node with a web key: the Origin header to send */
40
+ origin?: string;
41
+ /** telemetry: on by default, anonymous; 'off' is the one developer opt-out (never a prompt) */
42
+ analytics?: 'on' | 'off';
43
+ issues?: boolean;
44
+ /** @deprecated ignored since 2.0.1: Quran Lab decides per app whether the sharing sheet is offered (signed
45
+ * config, flags.contributions); the SDK still asks the learner before anything is recorded for upload */
46
+ contributions?: boolean;
47
+ audience?: 'general' | 'children';
48
+ state?: StateStore;
49
+ /** pinned Ed25519 config keys (default: Quran Lab's) */
50
+ trustedKeys?: (string | Uint8Array)[];
51
+ apiUrl?: string;
52
+ /** model files: default the signed config's base, else https://cdn.quranlab.ai/models */
53
+ modelsUrl?: string;
54
+ /** given alone (no modelsUrl): model files from the old {cdnUrl}/hf/ path */
55
+ cdnUrl?: string;
56
+ fetch?: typeof fetch;
57
+ clock?: () => number;
58
+ /** a development build: logs "Quran Lab SDK X is available" once per launch when the signed config's sdk_latest is
59
+ * newer (default: process.env.NODE_ENV !== 'production' where it resolves; a plain browser page stays silent) */
60
+ debug?: boolean;
61
+ /** telemetry deltas on the SDK's schedule (default true): every 15 minutes while visible, when hidden or left */
62
+ autoSend?: boolean;
63
+ /** where visibilitychange and pagehide come from (default the page's document and window) */
64
+ lifecycle?: { document?: EventTarget & { visibilityState?: string }; window?: EventTarget | null };
65
+ }
66
+ export declare const DELTA_INTERVAL_MS: number;
67
+ /** -1, 0 or 1 for dotted numeric versions; null for a pre-release or junk */
68
+ export declare function compareVersions(a: string, b: string): -1 | 0 | 1 | null;
69
+ /** the signed config's sdk_latest when well formed, else null */
70
+ export declare function sdkLatestOf(cfg: unknown): { version: string; severity: string; url: string } | null;
71
+ export declare function isDevelopment(debug?: boolean): boolean;
72
+ export declare function noticeSdkLatest(cfg: unknown, current: string, o?: { debug?: boolean; warn?: (m: string) => void }): boolean;
73
+ export declare function resetSdkLatestNoticeForTests(): void;
74
+
75
+ export declare class QuranLab {
76
+ constructor(o: QuranLabOptions);
77
+ /** configure and run the launch sequence (token, register, config, pending telemetry and issues);
78
+ * never throws for network trouble */
79
+ static configure(o: QuranLabOptions): Promise<QuranLab>;
80
+ readonly config: SignedConfig | null;
81
+ readonly flags: SignedConfig['flags'];
82
+ /** the error-table code that stopped the network for this launch, or null */
83
+ readonly stopped: string | null;
84
+ readonly lastError?: Error;
85
+ readonly telemetry: Telemetry;
86
+ token(): Promise<string>;
87
+ launch(): Promise<void>;
88
+ /** at most once per UTC day per install; null when this install already registered today */
89
+ register(): Promise<{ ok: boolean; app_id: string; store_status: string } | null>;
90
+ /** the app came back to the foreground: a launch counted, register on a new day */
91
+ foreground(): void;
92
+ /** the app goes to the background: the delta sealed and sent (keepalive) */
93
+ background(): Promise<number>;
94
+ /** a send point: seal the delta and send the reports due */
95
+ sendTelemetry(reason?: string, o?: { keepalive?: boolean }): Promise<number>;
96
+ stopSchedule(): void;
97
+ refreshConfig(): Promise<SignedConfig | null>;
98
+ /** refresh every ms (60 s) while the app is in use */
99
+ startRefresh(ms?: number): void;
100
+ stopRefresh(): void;
101
+ modelSource(): Promise<{ url: string; headers: Record<string, string> }>;
102
+ flush(o?: { keepalive?: boolean }): Promise<number>;
103
+ reportIssue(kind: string, code: string, frames?: string[]): boolean;
104
+ contributor(): string;
105
+ resetContributor(): void;
106
+ contributionSummary(): Promise<{ you: { sessions: number; minutes: number }; app: { contributors: number; minutes: number } | null;
107
+ all: { contributors: number; minutes: number } } | null>;
108
+ sharingAllowed(): boolean;
109
+ }
110
+
111
+ export declare function verifySignedConfig(body: Uint8Array, signatureHeader: string | null, keyId: string | null,
112
+ trustedKeys: (string | Uint8Array)[], now?: number): Promise<SignedConfig>;
113
+ export declare function keyId(rawPublicKey: string | Uint8Array): Promise<string>;
114
+
115
+ export declare class Telemetry {
116
+ enabled: boolean;
117
+ /** +n on a 2.0.1 counter: launches, ayahs, words, share_asked, share_yes, share_no */
118
+ count(field: string, n?: number): void;
119
+ /** seal what was counted since the last send point (one report per UTC day, a fresh report_id each) */
120
+ seal(): number;
121
+ /** the sealed reports not yet accepted, oldest first, with the exact bytes sent */
122
+ reports(): { report_id: string; day: string; body: string; attempts: number; next: number }[];
123
+ /** the sealed reports as payloads (v2 with the 2.0.1 fields) */
124
+ pending(): object[];
125
+ clear(): void;
126
+ }
127
+ export declare const COUNTERS: readonly string[];
128
+ export declare function newReportId(): string;
129
+ export declare function bucket(kind: string, value: number): string;
130
+ export declare function utcDay(t?: number): string;
131
+ export declare function deviceInfo(): { class: string; soc?: string; os_major: number; ram_tier?: string };
132
+
133
+ export interface ContributorKey {
134
+ contributor: string;
135
+ /** always false: the private half never leaves WebCrypto */
136
+ extractable: false;
137
+ publicKeyRaw: Uint8Array;
138
+ publicKeySpki: Uint8Array;
139
+ sign(bytes: Uint8Array): Promise<Uint8Array>;
140
+ }
141
+ export declare function contributorKey(contributor: string, opts?: { create?: boolean }): Promise<ContributorKey | null>;
142
+ export declare function forgetContributorKey(contributor: string): Promise<void>;
143
+ export declare function recoveryCodeFromBytes(bytes: Uint8Array): string;
144
+ export declare function normaliseRecoveryCode(code: string): string;
145
+ export declare function recoveryHash(code: string): Promise<string>;
146
+ export declare function newRecoveryCode(): string;
147
+ export declare function deletionMessage(m: { app: string; contributor: string; nonce: string; timestamp: number }): Uint8Array;
148
+ export declare function b64url(bytes: Uint8Array): string;
@@ -0,0 +1,8 @@
1
+ // @quran-lab/tajweedformer/platform: the Quran Lab platform client:
2
+ // key, token, register, the signed config, telemetry v2 (on by default, anonymous), issues.
3
+ // import { QuranLab } from '@quran-lab/tajweedformer/platform';
4
+ export { QuranLab, PlatformError, verifySignedConfig, keyId, SDK_VERSION, API_URL, CDN_URL, DELTA_INTERVAL_MS } from './client.js';
5
+ export { Telemetry, bucket, utcDay, deviceInfo, COUNTERS, newReportId } from './telemetry.js';
6
+ export { memoryState, localState, dirState } from './storage.js';
7
+ export { compareVersions, sdkLatestOf, noticeSdkLatest, isDevelopment, resetSdkLatestNoticeForTests } from './update-notice.js';
8
+ export { contributorKey, forgetContributorKey, recoveryCodeFromBytes, normaliseRecoveryCode, recoveryHash, newRecoveryCode, deletionMessage, b64url } from './contributor-key.js';
@@ -0,0 +1,50 @@
1
+ // Small persistent state for the platform client (tokens, the signed config, telemetry days, the
2
+ // sharing state, the bucket, the first-launch flag): JSON values by key.
3
+ // browsers: localStorage (per origin), wrapped in try/catch (private modes can throw)
4
+ // Node: a JSON file per key in a directory (nodeStateStore in ../tajweed/node.js style, here)
5
+ // tests: memoryState()
6
+
7
+ /** In memory. */
8
+ export function memoryState() {
9
+ const m = new Map();
10
+ return {
11
+ kind: 'memory',
12
+ get(k) { return m.has(k) ? JSON.parse(m.get(k)) : null; },
13
+ set(k, v) { if (v === null || v === undefined) m.delete(k); else m.set(k, JSON.stringify(v)); },
14
+ };
15
+ }
16
+
17
+ /** localStorage, prefixed "quranlab.". Falls back to memory when storage throws. */
18
+ export function localState(prefix = 'quranlab.') {
19
+ const mem = memoryState();
20
+ const ls = (() => { try { return globalThis.localStorage || null; } catch (_) { return null; } })();
21
+ return {
22
+ kind: ls ? 'localStorage' : 'memory',
23
+ get(k) {
24
+ try { const v = ls ? ls.getItem(prefix + k) : null; return v === null ? mem.get(k) : JSON.parse(v); } catch (_) { return mem.get(k); }
25
+ },
26
+ set(k, v) {
27
+ mem.set(k, v);
28
+ try { if (ls) { if (v === null || v === undefined) ls.removeItem(prefix + k); else ls.setItem(prefix + k, JSON.stringify(v)); } } catch (_) { /* kept in memory */ }
29
+ },
30
+ };
31
+ }
32
+
33
+ /** A directory of JSON files (Node). Synchronous on purpose: tiny files, called rarely. */
34
+ export async function dirState(dir) {
35
+ const fs = await import('node:fs');
36
+ const path = await import('node:path');
37
+ fs.mkdirSync(dir, { recursive: true });
38
+ const file = (k) => path.join(dir, encodeURIComponent(k) + '.json');
39
+ return {
40
+ kind: 'directory',
41
+ get(k) { try { return JSON.parse(fs.readFileSync(file(k), 'utf8')); } catch (_) { return null; } },
42
+ set(k, v) {
43
+ const f = file(k);
44
+ if (v === null || v === undefined) { fs.rmSync(f, { force: true }); return; }
45
+ const tmp = `${f}.${process.pid}.tmp`;
46
+ fs.writeFileSync(tmp, JSON.stringify(v), { mode: 0o600 });
47
+ fs.renameSync(tmp, f);
48
+ },
49
+ };
50
+ }
@@ -0,0 +1,314 @@
1
+ // Telemetry v2 (PLATFORM_CLIENT.md section 6): on by default, anonymous by construction. Only sums
2
+ // and histograms per UTC day: no audio, no text or phonemes, no identifiers, no time finer than the
3
+ // day. Since 2.0.1 it goes as deltas during the day: what was counted since the last send point is
4
+ // sealed into a report with a fresh random report_id (kept in storage before it is sent, so a retry sends
5
+ // the same bytes and the server counts it once), one report per UTC day it covers, at most 7 days kept.
6
+ // The send points (every 15 minutes while the app is in use, when it goes to the background, at launch)
7
+ // are the platform client's (client.js).
8
+ // Tried and rejected: sending the whole day again with a day-scoped id (the server would have to diff
9
+ // days); one report spanning midnight (a delta belongs to one day, as the server's points do).
10
+
11
+ import { CLASSES, CHECKS } from '../tajweed/settings.js';
12
+
13
+ const B = {
14
+ latency_ms: [['le_5', 5], ['le_10', 10], ['le_20', 20], ['le_40', 40], ['le_80', 80], ['le_160', 160], ['le_320', 320], ['gt_320', Infinity]],
15
+ rtf: [['le_0_1', 0.1], ['le_0_25', 0.25], ['le_0_5', 0.5], ['le_1', 1], ['gt_1', Infinity]],
16
+ ms: [['le_250', 250], ['le_500', 500], ['le_1000', 1000], ['le_2000', 2000], ['le_4000', 4000], ['gt_4000', Infinity]],
17
+ pct: [['le_1', 1], ['le_2', 2], ['le_5', 5], ['le_10', 10], ['le_20', 20], ['gt_20', Infinity]],
18
+ margin: [['le_0_5', 0.5], ['le_1', 1], ['le_2', 2], ['le_4', 4], ['le_8', 8], ['gt_8', Infinity]],
19
+ confidence: [['le_0_5', 0.5], ['le_0_7', 0.7], ['le_0_8', 0.8], ['le_0_9', 0.9], ['le_0_95', 0.95], ['gt_0_95', Infinity]],
20
+ word: [['le_3', 3], ['le_4', 4], ['le_5', 5], ['le_6', 6], ['le_7', 7], ['gt_7', Infinity]],
21
+ };
22
+ /** The bucket a value falls in ("le_x" is <= x). */
23
+ export function bucket(kind, v) { for (const [k, hi] of B[kind]) if (v <= hi) return k; return B[kind][B[kind].length - 1][0]; }
24
+ const bump = (h, kind, v, n = 1) => { const k = bucket(kind, v); h[k] = (h[k] || 0) + n; };
25
+
26
+ /** UTC day "YYYY-MM-DD". */
27
+ export const utcDay = (t = Date.now()) => new Date(t).toISOString().slice(0, 10);
28
+
29
+ const FALLBACKS = ['non_finite', 'deadline', 'ane_unavailable', 'npu_unavailable', 'model_load', 'thermal', 'memory', 'other'];
30
+ const CAP = 10_000_000;
31
+ const DAY_MS = 86_400_000;
32
+ /** The 2.0.1 counters at the top level of a report (each left out when zero). */
33
+ export const COUNTERS = Object.freeze(['launches', 'ayahs', 'words', 'share_asked', 'share_yes', 'share_no']);
34
+ /** At most this many rule keys per report (the server's limit). */
35
+ export const MAX_RULE_KEYS = 32;
36
+ const RULE_KEY = /^[a-z][a-z0-9_]{0,23}$/;
37
+ /** A fresh report id: 16 random bytes, 32 lower-case hex. */
38
+ export function newReportId() {
39
+ const b = new Uint8Array(16);
40
+ globalThis.crypto.getRandomValues(b);
41
+ return [...b].map((x) => x.toString(16).padStart(2, '0')).join('');
42
+ }
43
+ // a verdict or a check that ran: its status is not off and it is not disabled (absent settings: ran)
44
+ const ran = (x) => x === undefined || x === null || (x.status !== 'off' && x.enabled !== false);
45
+
46
+ /**
47
+ * The day's counters, persisted in `state` under "telemetry.days" ({ day: payload-in-progress }).
48
+ * `device` is { class, soc?, os_major, ram_tier? }, `product` the platform's (productOf), `platform` the token app's.
49
+ */
50
+ // The telemetry product of a platform, as the server checks it (PRODUCT_OF): a desktop app running this SDK in Node
51
+ // reports as the native product of its platform, a page as web.
52
+ export const PRODUCT_OF = Object.freeze({ web: 'web', windows: 'native', linux: 'native', macos: 'apple', ios: 'apple', android: 'android' });
53
+ export const productOf = (platform) => PRODUCT_OF[platform] || 'web';
54
+
55
+ export class Telemetry {
56
+ constructor({ state, platform = 'web', product = productOf(platform), sdkVersion = '2.0.1', appVersion = '0', device, clock = Date.now, enabled = true }) {
57
+ Object.assign(this, { state, product, platform, sdkVersion, appVersion, device, clock });
58
+ this.enabled = enabled;
59
+ this.coldStartDone = false;
60
+ }
61
+
62
+ _days() { return this.state.get('telemetry.days') || {}; }
63
+ _save(d) { this.state.set('telemetry.days', d); }
64
+ _today() {
65
+ const days = this._days();
66
+ const day = utcDay(this.clock());
67
+ if (!days[day]) {
68
+ days[day] = { v: 2, day, product: this.product, platform: this.platform, sdk_version: this.sdkVersion, app_version: this.appVersion,
69
+ device: this.device, cohorts: [], coverage: {}, downloads: [] };
70
+ }
71
+ return { days, d: days[day] };
72
+ }
73
+ _edit(fn) {
74
+ if (!this.enabled) return;
75
+ const { days, d } = this._today();
76
+ fn(d);
77
+ // keep at most 7 days
78
+ const keys = Object.keys(days).sort();
79
+ while (keys.length > 7) delete days[keys.shift()];
80
+ this._save(days);
81
+ }
82
+
83
+ /** The cohort of a model's settings: revision, context, backend, preset (custom when any raw site
84
+ * threshold is set), word level. */
85
+ static cohortKey(tf) {
86
+ const e = tf.settings.effective();
87
+ const app = tf.settings.app || {};
88
+ const ov = { ...((tf.settings.remote && tf.settings.remote.overrides) || {}), ...(app.overrides || {}) };
89
+ const custom = Object.values(ov).some((o) => o && Object.prototype.hasOwnProperty.call(o, 'threshold'));
90
+ const wl = tf.settings.wordLevel ? tf.settings.wordLevel() : null;
91
+ let word = 'off', wordBucket = '';
92
+ if (wl && wl.enabled) {
93
+ if (wl.preset) word = wl.preset; else { word = 'custom'; wordBucket = bucket('word', wl.threshold); }
94
+ }
95
+ return {
96
+ revision: String((tf.folder && tf.folder.manifest && (tf.folder.manifest.model_id + '+' + tf.folder.manifest.revision)) || 'unknown').slice(0, 64),
97
+ context: tf.context, backend: 'cpu', preset: custom ? 'custom' : e.preset, word_level: word, word_bucket: wordBucket,
98
+ site_overrides: Math.min(8, Object.keys(ov).filter((k) => CLASSES.includes(k)).length),
99
+ };
100
+ }
101
+
102
+ _cohort(d, key) {
103
+ let c = d.cohorts.find((x) => ['revision', 'context', 'backend', 'preset', 'word_level', 'word_bucket'].every((k) => x[k] === key[k]));
104
+ if (!c) {
105
+ c = { ...key, sessions: 0, minutes: 0, chunks: 0, aborted: 0, fallbacks: {}, self_test: { pass: 0, fail: 0 }, latency_ms: {}, rtf: {},
106
+ cold_start_ms: {}, model_load_ms: {}, thermal: { transitions: 0, throttled_sessions: 0 }, checks_on: {}, classes: {},
107
+ session_flag_pct: {}, margin: {}, confidence: {}, madd: { c2: 0, c4: 0, c6: 0, flagged: 0 }, words: { scored: 0, flagged: 0 } };
108
+ d.cohorts.push(c);
109
+ }
110
+ c.site_overrides = key.site_overrides;
111
+ return c;
112
+ }
113
+
114
+ modelLoaded(tf, ms) { this._edit((d) => bump(this._cohort(d, Telemetry.cohortKey(tf)).model_load_ms, 'ms', ms)); }
115
+
116
+ /** A take ended: audio seconds, chunk timings (ms each), whether it was the launch's first. */
117
+ session(tf, { seconds, chunkMs = [], aborted = false, firstMs = null }) {
118
+ const chunk = tf.info.chunkMs || 320;
119
+ this._edit((d) => {
120
+ const c = this._cohort(d, Telemetry.cohortKey(tf));
121
+ if (aborted) c.aborted++; else c.sessions++;
122
+ c.minutes = Math.round((c.minutes + seconds / 60) * 1000) / 1000;
123
+ c.chunks = Math.min(CAP, c.chunks + chunkMs.length);
124
+ for (const ms of chunkMs) { bump(c.latency_ms, 'latency_ms', ms); bump(c.rtf, 'rtf', ms / chunk); }
125
+ if (!this.coldStartDone && firstMs !== null) { bump(c.cold_start_ms, 'ms', firstMs); this.coldStartDone = true; }
126
+ const eff = tf.settings.effective();
127
+ const on = { letters: false, vowels: false, length: false, madd: eff.madd.enabled, gemination: eff.gemination.enabled,
128
+ qalqalah: eff.qalqalah.enabled, lazim: eff.lazim.enabled };
129
+ for (const [cls, s] of Object.entries(eff.sites)) {
130
+ const k = { vowel_sub: 'vowels', vowel_del: 'vowels', vowel_ins: 'vowels', short_to_long: 'length', long_to_short: 'length' }[cls] || 'letters';
131
+ if (s.enabled) on[k] = true;
132
+ }
133
+ for (const k of CHECKS) if (on[k]) c.checks_on[k] = (c.checks_on[k] || 0) + 1;
134
+ });
135
+ }
136
+
137
+ /** The decoded layer of a take: margin and confidence per emitted token. */
138
+ decoded(tf, decoded) {
139
+ this._edit((d) => {
140
+ const c = this._cohort(d, Telemetry.cohortKey(tf));
141
+ for (const t of decoded.tokens) {
142
+ bump(c.margin, 'margin', t.margin);
143
+ if (t.confidence !== null) bump(c.confidence, 'confidence', t.confidence);
144
+ }
145
+ });
146
+ }
147
+
148
+ /** A scored ayah: per class sites and flags, the session's flag %, madd counts, words, coverage; and the 2.0.1
149
+ * counters: ayahs, surah_ayahs, words, rule_checks / rule_flags (a verdict counts only when its check ran). */
150
+ scored(tf, r) {
151
+ this._edit((d) => {
152
+ d.ayahs = Math.min(CAP, (d.ayahs || 0) + 1);
153
+ if (Number.isInteger(r.surah) && r.surah >= 1 && r.surah <= 114) {
154
+ d.surah_ayahs = d.surah_ayahs || {};
155
+ d.surah_ayahs[String(r.surah)] = (d.surah_ayahs[String(r.surah)] || 0) + 1;
156
+ }
157
+ const eff = r.settings || {};
158
+ const rule = (key, checked, flagged) => {
159
+ if (!checked || !RULE_KEY.test(key)) return;
160
+ d.rule_checks = d.rule_checks || {};
161
+ d.rule_flags = d.rule_flags || {};
162
+ if (!(key in d.rule_checks) && Object.keys(d.rule_checks).length >= MAX_RULE_KEYS) return;
163
+ d.rule_checks[key] = Math.min(CAP, (d.rule_checks[key] || 0) + 1);
164
+ if (flagged) d.rule_flags[key] = Math.min(d.rule_checks[key], (d.rule_flags[key] || 0) + 1);
165
+ };
166
+ for (const s of r.sites || []) rule(s.class, ran(s) && ran(eff.sites && eff.sites[s.class]), s.flagged);
167
+ for (const m of r.madd || []) rule('madd', ran(m) && ran(eff.madd), m.flagged);
168
+ for (const q of r.qalqalah || []) rule('qalqalah', ran(q) && ran(eff.qalqalah), q.flagged);
169
+ for (const g of r.gemination || []) rule('gemination', ran(g) && ran(eff.gemination), g.flagged);
170
+ for (const w of r.words || []) {
171
+ if (w.score === null || w.score === undefined) continue;
172
+ d.words = Math.min(CAP, (d.words || 0) + 1);
173
+ rule('word', true, w.flagged === true);
174
+ }
175
+ const c = this._cohort(d, Telemetry.cohortKey(tf));
176
+ for (const s of r.sites) {
177
+ const k = (c.classes[s.class] = c.classes[s.class] || { sites: 0, flagged: 0 });
178
+ k.sites++;
179
+ if (s.flagged) k.flagged++;
180
+ }
181
+ const n = r.summary.sites || 0;
182
+ bump(c.session_flag_pct, 'pct', n ? (100 * r.summary.flagged) / n : 0);
183
+ for (const m of r.madd) {
184
+ if (m.count === 2) c.madd.c2++; else if (m.count === 4) c.madd.c4++; else if (m.count === 6) c.madd.c6++;
185
+ if (m.flagged) c.madd.flagged++;
186
+ }
187
+ c.words.scored += r.words.filter((w) => w.score !== null).length;
188
+ c.words.flagged += r.words.filter((w) => w.flagged).length;
189
+ d.coverage[String(r.surah)] = (d.coverage[String(r.surah)] || 0) + 1;
190
+ });
191
+ }
192
+
193
+ fallback(tf, reason) {
194
+ const k = FALLBACKS.includes(reason) ? reason : 'other';
195
+ this._edit((d) => { const c = this._cohort(d, Telemetry.cohortKey(tf)); c.fallbacks[k] = (c.fallbacks[k] || 0) + 1; });
196
+ }
197
+
198
+ download({ revision, profile, bytes, success, resumed }) {
199
+ this._edit((d) => {
200
+ let x = d.downloads.find((y) => y.revision === revision && y.profile === profile);
201
+ if (!x) { x = { revision, profile, bytes: 0, success: 0, failed: 0, resumed: 0 }; d.downloads.push(x); }
202
+ x.bytes += bytes; if (success) x.success++; else x.failed++; if (resumed) x.resumed++;
203
+ });
204
+ }
205
+
206
+ /** +n on a 2.0.1 counter (COUNTERS: launches, share_asked, share_yes, share_no, ...). */
207
+ count(field, n = 1) {
208
+ if (!COUNTERS.includes(field)) throw new RangeError(`telemetry counter ${field}`);
209
+ this._edit((d) => { d[field] = Math.min(CAP, (d[field] || 0) + n); });
210
+ }
211
+
212
+ /**
213
+ * A send point: what was counted since the last one is sealed, one report per UTC day it covers, each with a
214
+ * fresh report_id and its exact body, stored before anything is sent. Reports older than 7 days are deleted.
215
+ * Returns the number of reports sealed.
216
+ */
217
+ seal() {
218
+ const days = this._days();
219
+ const sealed = this._sealed();
220
+ let n = 0;
221
+ for (const day of Object.keys(days).sort()) {
222
+ const body = Telemetry.wire(days[day]);
223
+ delete days[day];
224
+ if (!Telemetry.hasContent(body)) continue;
225
+ const reportId = newReportId();
226
+ sealed.push({ report_id: reportId, day, body: JSON.stringify({ ...body, report_id: reportId }), attempts: 0, next: 0 });
227
+ n++;
228
+ }
229
+ this._putSealed(this._fresh(sealed));
230
+ this._save(days);
231
+ return n;
232
+ }
233
+
234
+ _sealed() { return this.state.get('telemetry.sealed') || []; }
235
+ _putSealed(s) { this.state.set('telemetry.sealed', s.length ? s : null); }
236
+ _fresh(s) {
237
+ const oldest = utcDay(this.clock() - 7 * DAY_MS);
238
+ return s.filter((r) => r.day >= oldest).sort((a, b) => (a.day < b.day ? -1 : a.day > b.day ? 1 : 0));
239
+ }
240
+
241
+ /** Sealed reports not yet accepted, oldest first: { report_id, day, body (the exact JSON sent), attempts, next }. */
242
+ reports() { return this._fresh(this._sealed()); }
243
+ /** The sealed reports as payloads (what is sent), oldest first. */
244
+ pending() { return this.reports().map((r) => JSON.parse(r.body)); }
245
+ /** A report was accepted (202) or refused for good (400, 413): deleted. */
246
+ dropReport(id) { this._putSealed(this._sealed().filter((r) => r.report_id !== id)); }
247
+ /** A report to retry later with the same bytes: 1 min, then 10 min, then the next launch. */
248
+ deferReport(id) {
249
+ const s = this._sealed();
250
+ const r = s.find((x) => x.report_id === id);
251
+ if (!r) return;
252
+ r.attempts += 1;
253
+ r.next = r.attempts === 1 ? this.clock() + 60_000 : r.attempts === 2 ? this.clock() + 600_000 : -1; // -1: the next launch
254
+ this._putSealed(s);
255
+ }
256
+ /** At launch: reports waiting for the next launch are due again. */
257
+ launched() {
258
+ const s = this._sealed();
259
+ for (const r of s) if (r.next === -1) r.next = 0;
260
+ this._putSealed(s);
261
+ }
262
+ /** Reports due now. */
263
+ due() { const now = this.clock(); return this.reports().filter((r) => r.next !== -1 && r.next <= now); }
264
+
265
+ /** Drop a day's open counts (kept for 2.0.0 callers). */
266
+ drop(day) { const d = this._days(); delete d[day]; this._save(d); }
267
+ /** Drop everything, open counts and sealed reports (flags.analytics false). */
268
+ clear() { this.state.set('telemetry.days', null); this.state.set('telemetry.sealed', null); }
269
+
270
+ /** Whether a report body carries anything (a delta with no count is not sent). */
271
+ static hasContent(b) {
272
+ return b.cohorts.length > 0 || !!b.coverage || !!b.downloads || COUNTERS.some((k) => b[k] > 0) || !!b.surah_ayahs || !!b.rule_checks;
273
+ }
274
+
275
+ /** The closed v2 body: empty optional parts removed, cohorts beyond 16 merged into the largest. */
276
+ static wire(p) {
277
+ let cohorts = p.cohorts.slice().sort((a, b) => b.sessions - a.sessions);
278
+ if (cohorts.length > 16) {
279
+ const keep = cohorts.slice(0, 16), rest = cohorts.slice(16);
280
+ for (const r of rest) { keep[0].sessions += r.sessions; keep[0].minutes += r.minutes; keep[0].chunks += r.chunks; keep[0].aborted += r.aborted; }
281
+ cohorts = keep;
282
+ }
283
+ const out = { v: 2, day: p.day, product: p.product, platform: p.platform, sdk_version: p.sdk_version, app_version: p.app_version,
284
+ device: p.device, cohorts };
285
+ if (Object.keys(p.coverage || {}).length) out.coverage = p.coverage;
286
+ if ((p.downloads || []).length) out.downloads = p.downloads;
287
+ // the 2.0.1 fields, each left out when zero or empty
288
+ for (const k of COUNTERS) if (p[k] > 0) out[k] = p[k];
289
+ if (p.surah_ayahs && Object.keys(p.surah_ayahs).length) out.surah_ayahs = p.surah_ayahs;
290
+ if (p.rule_checks && Object.keys(p.rule_checks).length) {
291
+ out.rule_checks = p.rule_checks;
292
+ const flags = Object.fromEntries(Object.entries(p.rule_flags || {}).filter(([k, v]) => v > 0 && k in p.rule_checks));
293
+ if (Object.keys(flags).length) out.rule_flags = flags;
294
+ }
295
+ return out;
296
+ }
297
+ }
298
+
299
+ /** The device fields the spec allows, from what a browser or Node can tell without an identifier. */
300
+ export function deviceInfo() {
301
+ const nav = globalThis.navigator;
302
+ const isNode = typeof process !== 'undefined' && process.versions && process.versions.node && !globalThis.window;
303
+ const ramGb = nav && typeof nav.deviceMemory === 'number' ? nav.deviceMemory : null;
304
+ const tier = (g) => (g === null ? undefined : g < 2 ? 'lt2' : g < 4 ? '2_4' : g < 8 ? '4_8' : g < 16 ? '8_16' : 'ge16');
305
+ if (isNode) {
306
+ const major = Number(process.versions.node.split('.')[0]) || 1;
307
+ return { class: 'node', soc: 'wasm', os_major: Math.max(1, Math.min(99, major)) };
308
+ }
309
+ const ua = (nav && nav.userAgent) || '';
310
+ const m = /(?:Chrome|Firefox|Version)\/(\d+)/.exec(ua);
311
+ const d = { class: 'browser', soc: 'wasm', os_major: Math.max(1, Math.min(99, Math.floor((m ? Number(m[1]) : 10) / 10))) };
312
+ if (ramGb !== null) d.ram_tier = tier(ramGb);
313
+ return d;
314
+ }
@@ -0,0 +1,60 @@
1
+ // "A newer SDK is available", for the developer only. The signed /v1/config may carry `sdk_latest: {version,
2
+ // severity, url}` for the app's platform. When this SDK is older, one console.warn per page load or process, and
3
+ // only outside production:
4
+ // Quran Lab SDK <version> is available (<severity>), you have <this version>: <url>
5
+ // Production (and anything that cannot tell) stays silent. A missing or malformed field is ignored, never thrown.
6
+ // Tried and rejected: warning per configured client (two clients or two configs in one launch would repeat it);
7
+ // semver pre-release ordering (a pre-release or junk version simply counts as not newer).
8
+
9
+ const NUMERIC = /^\d+(\.\d+)*$/;
10
+ let warned = false;
11
+
12
+ /** -1, 0 or 1 for two dotted numeric versions; null when either is not one (a pre-release, junk). */
13
+ export function compareVersions(a, b) {
14
+ if (typeof a !== 'string' || typeof b !== 'string' || !NUMERIC.test(a) || !NUMERIC.test(b)) return null;
15
+ const x = a.split('.').map(Number), y = b.split('.').map(Number);
16
+ for (let i = 0; i < Math.max(x.length, y.length); i++) {
17
+ const d = (x[i] || 0) - (y[i] || 0);
18
+ if (d) return d < 0 ? -1 : 1;
19
+ }
20
+ return 0;
21
+ }
22
+
23
+ /** The field when it is well formed ({version: dotted numbers, severity: a string, url: https}), else null. */
24
+ export function sdkLatestOf(cfg) {
25
+ const s = cfg && typeof cfg === 'object' ? cfg.sdk_latest : null;
26
+ if (!s || typeof s !== 'object' || Array.isArray(s)) return null;
27
+ if (typeof s.version !== 'string' || !NUMERIC.test(s.version)) return null;
28
+ if (typeof s.severity !== 'string' || !s.severity.length) return null;
29
+ if (typeof s.url !== 'string') return null;
30
+ try { if (new URL(s.url).protocol !== 'https:') return null; } catch (_) { return null; }
31
+ return { version: s.version, severity: s.severity, url: s.url };
32
+ }
33
+
34
+ /** Outside production: an explicit debug flag wins; else NODE_ENV where it resolves (Node, or a bundler that
35
+ * substitutes process.env.NODE_ENV); else (a plain browser page) production. */
36
+ export function isDevelopment(debug) {
37
+ if (debug === true || debug === false) return debug;
38
+ try {
39
+ // eslint-disable-next-line no-undef
40
+ const env = process.env.NODE_ENV;
41
+ if (typeof env === 'string') return env !== 'production';
42
+ return typeof process !== 'undefined' && !!process.versions && !!process.versions.node;
43
+ } catch (_) { return false; }
44
+ }
45
+
46
+ /** Warns once per launch when cfg's sdk_latest is newer than `current`; returns whether it warned now. */
47
+ export function noticeSdkLatest(cfg, current, { debug, warn = (m) => console.warn(m) } = {}) {
48
+ try {
49
+ if (warned) return false;
50
+ const l = sdkLatestOf(cfg);
51
+ if (!l || compareVersions(current, l.version) !== -1) return false;
52
+ if (!isDevelopment(debug)) return false;
53
+ warned = true;
54
+ warn(`Quran Lab SDK ${l.version} is available (${l.severity}), you have ${current}: ${l.url}`);
55
+ return true;
56
+ } catch (_) { return false; }
57
+ }
58
+
59
+ /** A new launch (tests). */
60
+ export function resetSdkLatestNoticeForTests() { warned = false; }
@@ -0,0 +1,4 @@
1
+ // Type definitions for @quran-lab/tajweedformer/scorer (the scorer without the streaming engine).
2
+ export * from './tajweed/index.js';
3
+ import { TajweedFormer } from './tajweed/index.js';
4
+ export default TajweedFormer;
package/web/scorer.js ADDED
@@ -0,0 +1,10 @@
1
+ // @quran-lab/tajweedformer/scorer: the TajweedFormer scorer without the streaming engine
2
+ // (dist/tajweedformer-scorer, scripts/build_scorer.sh). Scores heads from any source: the Neural
3
+ // Engine, an NPU, a server, saved heads. Models load for scoring only; streams throw.
4
+ // import { TajweedFormer } from '@quran-lab/tajweedformer/scorer';
5
+ import createTajweedScorer from '../dist/tajweedformer-scorer.mjs';
6
+ import { bindTajweed } from './tajweed/tajweedformer.js';
7
+ export * from './tajweed/index.js';
8
+
9
+ export const TajweedFormer = bindTajweed(createTajweedScorer, { scoreOnly: true });
10
+ export default TajweedFormer;