hashquiz 1.0.0-beta.2 → 1.0.0-beta.4
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/LICENSE.md +7 -7
- package/README.md +49 -8
- package/bin/hashquiz.js +1015 -176
- package/package.json +2 -1
- package/supabase/config.toml +388 -0
- package/supabase/functions/_shared/solo-core.js +3811 -0
- package/supabase/functions/solo-submit/index.ts +97 -0
- package/supabase/migrations/20261126090000_solo_live.sql +160 -0
- package/supabase/migrations/20261126120000_solo_hardening.sql +73 -0
- package/web/apple-touch-icon.png +0 -0
- package/web/assets/SoloCatalog-C2yyeNv7.css +1 -0
- package/web/assets/SoloCatalog-CkqJ5Tx_.js +1 -0
- package/web/assets/SoloEndView-D4O71skZ.js +1 -0
- package/web/assets/SoloEndView-DiG29AY1.css +1 -0
- package/web/assets/SoloIntroView-BZVJulM4.css +1 -0
- package/web/assets/SoloIntroView-BffbrN2m.js +1 -0
- package/web/assets/SoloLeaderboard-CZv7b2Vs.css +1 -0
- package/web/assets/SoloLeaderboard-yKT1v7Ii.js +1 -0
- package/web/assets/SoloQuestionView-7ZBgZtDL.js +65 -0
- package/web/assets/SoloQuestionView-D4uFu3tV.css +1 -0
- package/web/assets/decks-DUUEsbbr.js +49 -0
- package/web/assets/decks-i0k875Ku.js +1 -0
- package/web/assets/deps-B9JMgire.js +1 -0
- package/web/assets/index-B3S7raZa.js +32 -0
- package/web/assets/index-mrY1X_tz.css +1 -0
- package/web/assets/solo-8S92cge3.css +1 -0
- package/web/assets/solo-backend-DxFnwiPI.js +1 -0
- package/web/favicon-32.png +0 -0
- package/web/favicon.svg +8 -0
- package/web/host/apple-touch-icon.png +0 -0
- package/web/host/assets/index-CtXpIwsc.css +1 -0
- package/web/host/assets/{index-B8SRSGSJ.js → index-CuMMk6nf.js} +5 -5
- package/web/host/favicon-32.png +0 -0
- package/web/host/favicon.svg +8 -0
- package/web/host/index.html +8 -5
- package/web/index.html +8 -5
- package/web/assets/index-4A6VG5Dt.css +0 -1
- package/web/assets/index-AtaLR7F0.js +0 -31
- package/web/host/assets/index-Bld0lMZN.css +0 -1
package/bin/hashquiz.js
CHANGED
|
@@ -3516,7 +3516,7 @@ function splitBlocks(content) {
|
|
|
3516
3516
|
const metaBlock = pieces[0];
|
|
3517
3517
|
const rest = pieces.slice(1);
|
|
3518
3518
|
if (rest.length % 2 !== 0) {
|
|
3519
|
-
throw new Error(`Malformed .
|
|
3519
|
+
throw new Error(`Malformed .hashquiz.md file: expected an even number of blocks after the meta section, got ${rest.length}`);
|
|
3520
3520
|
}
|
|
3521
3521
|
const questionBlocks = [];
|
|
3522
3522
|
for (let i = 0;i < rest.length; i += 2) {
|
|
@@ -3574,6 +3574,7 @@ ${rawBlock}
|
|
|
3574
3574
|
author: typeof data["author"] === "string" ? data["author"] : undefined,
|
|
3575
3575
|
tags: Array.isArray(data["tags"]) ? data["tags"] : [],
|
|
3576
3576
|
oneShoot: data["one-shoot"] !== false,
|
|
3577
|
+
solo: data["solo"] === true,
|
|
3577
3578
|
maxQuestions: typeof data["max-questions"] === "number" && data["max-questions"] > 0 ? data["max-questions"] : undefined,
|
|
3578
3579
|
maxTimeSec: parseMaxTime(data["max-time"]),
|
|
3579
3580
|
targetDifficulty: ["easy", "medium", "hard"].includes(data["target-difficulty"]) ? data["target-difficulty"] : undefined
|
|
@@ -3624,7 +3625,7 @@ function parseQuestion(rawBlock) {
|
|
|
3624
3625
|
function parseQuizFile(content) {
|
|
3625
3626
|
const blocks = splitBlocks(content);
|
|
3626
3627
|
if (blocks.length === 0) {
|
|
3627
|
-
return { meta: { title: "", theme: "default", tags: [] }, questions: [] };
|
|
3628
|
+
return { meta: { title: "", theme: "default", tags: [], solo: false }, questions: [] };
|
|
3628
3629
|
}
|
|
3629
3630
|
const [metaBlock, ...questionBlocks] = blocks;
|
|
3630
3631
|
const meta = parseMeta(metaBlock);
|
|
@@ -3665,7 +3666,7 @@ function validateQuiz(quiz) {
|
|
|
3665
3666
|
errors.push({
|
|
3666
3667
|
questionIndex: i,
|
|
3667
3668
|
field: "choices",
|
|
3668
|
-
message: `Question ${i + 1} has ${q.choices.length} choices;
|
|
3669
|
+
message: `Question ${i + 1} has ${q.choices.length} choices; HashQuiz supports at most 4`
|
|
3669
3670
|
});
|
|
3670
3671
|
}
|
|
3671
3672
|
}
|
|
@@ -3697,16 +3698,101 @@ function calcPoints(timeRemaining, isCorrect) {
|
|
|
3697
3698
|
return Math.max(10, Math.round(50 + timeRemaining * 5));
|
|
3698
3699
|
}
|
|
3699
3700
|
|
|
3700
|
-
// packages/core/src/
|
|
3701
|
+
// packages/core/src/selection.ts
|
|
3701
3702
|
var POSITIONAL_IDS = ["a", "b", "c", "d"];
|
|
3702
|
-
function
|
|
3703
|
-
const
|
|
3704
|
-
for (let i =
|
|
3703
|
+
function shuffle(arr) {
|
|
3704
|
+
const a = [...arr];
|
|
3705
|
+
for (let i = a.length - 1;i > 0; i--) {
|
|
3706
|
+
const j = Math.floor(Math.random() * (i + 1));
|
|
3707
|
+
[a[i], a[j]] = [a[j], a[i]];
|
|
3708
|
+
}
|
|
3709
|
+
return a;
|
|
3710
|
+
}
|
|
3711
|
+
function selectQuestions(quiz) {
|
|
3712
|
+
const { maxQuestions, maxTimeSec, targetDifficulty } = quiz.meta;
|
|
3713
|
+
const all = quiz.questions;
|
|
3714
|
+
if (!maxQuestions && !maxTimeSec && !targetDifficulty)
|
|
3715
|
+
return all;
|
|
3716
|
+
const DIFF_RANK = { easy: 0, medium: 1, hard: 2 };
|
|
3717
|
+
if (targetDifficulty) {
|
|
3718
|
+
const targetRank = DIFF_RANK[targetDifficulty];
|
|
3719
|
+
const guardrailSet = new Set;
|
|
3720
|
+
const uniqueTags = [...new Set(all.flatMap((q) => q.tags))];
|
|
3721
|
+
for (const tag of uniqueTags) {
|
|
3722
|
+
const hardForTag = shuffle(all.filter((q) => q.difficulty === "hard" && q.tags.includes(tag)));
|
|
3723
|
+
for (const q of hardForTag) {
|
|
3724
|
+
if (!guardrailSet.has(q)) {
|
|
3725
|
+
guardrailSet.add(q);
|
|
3726
|
+
break;
|
|
3727
|
+
}
|
|
3728
|
+
}
|
|
3729
|
+
}
|
|
3730
|
+
const guardrail = [...guardrailSet];
|
|
3731
|
+
const pool = all.filter((q) => !guardrailSet.has(q));
|
|
3732
|
+
const targetPool = shuffle(pool.filter((q) => q.difficulty === targetDifficulty));
|
|
3733
|
+
const belowPool = shuffle(pool.filter((q) => DIFF_RANK[q.difficulty] < targetRank));
|
|
3734
|
+
const abovePool = shuffle(pool.filter((q) => DIFF_RANK[q.difficulty] > targetRank));
|
|
3735
|
+
const totalN = maxQuestions !== undefined ? Math.min(maxQuestions, all.length) : all.length;
|
|
3736
|
+
const slots = Math.max(0, totalN - guardrail.length);
|
|
3737
|
+
const targetCount = Math.round(slots * 0.6);
|
|
3738
|
+
const belowCount = slots - targetCount;
|
|
3739
|
+
const targetSample = targetPool.slice(0, targetCount);
|
|
3740
|
+
const belowSample = belowPool.slice(0, belowCount);
|
|
3741
|
+
const usedSet = new Set([...guardrail, ...targetSample, ...belowSample]);
|
|
3742
|
+
const shortfall = slots - targetSample.length - belowSample.length;
|
|
3743
|
+
const fallback = shuffle([...targetPool, ...belowPool].filter((q) => !usedSet.has(q)));
|
|
3744
|
+
const extra = fallback.slice(0, Math.max(0, shortfall));
|
|
3745
|
+
let selected = [...guardrail, ...targetSample, ...belowSample, ...extra];
|
|
3746
|
+
if (maxTimeSec !== undefined) {
|
|
3747
|
+
selected.sort((a, b) => DIFF_RANK[a.difficulty] - DIFF_RANK[b.difficulty]);
|
|
3748
|
+
let total = 0;
|
|
3749
|
+
selected = selected.filter((q) => {
|
|
3750
|
+
if (total + q.timer <= maxTimeSec) {
|
|
3751
|
+
total += q.timer;
|
|
3752
|
+
return true;
|
|
3753
|
+
}
|
|
3754
|
+
return false;
|
|
3755
|
+
});
|
|
3756
|
+
}
|
|
3757
|
+
selected.sort((a, b) => DIFF_RANK[a.difficulty] - DIFF_RANK[b.difficulty]);
|
|
3758
|
+
return selected;
|
|
3759
|
+
}
|
|
3760
|
+
const indices = all.map((_, i) => i);
|
|
3761
|
+
for (let i = indices.length - 1;i > 0; i--) {
|
|
3705
3762
|
const j = Math.floor(Math.random() * (i + 1));
|
|
3706
|
-
[
|
|
3763
|
+
[indices[i], indices[j]] = [indices[j], indices[i]];
|
|
3764
|
+
}
|
|
3765
|
+
let selectedIndices;
|
|
3766
|
+
if (maxQuestions !== undefined) {
|
|
3767
|
+
selectedIndices = indices.slice(0, maxQuestions);
|
|
3768
|
+
} else {
|
|
3769
|
+
selectedIndices = [];
|
|
3770
|
+
let total = 0;
|
|
3771
|
+
for (const idx of indices) {
|
|
3772
|
+
const timer = all[idx].timer;
|
|
3773
|
+
if (total + timer <= maxTimeSec) {
|
|
3774
|
+
selectedIndices.push(idx);
|
|
3775
|
+
total += timer;
|
|
3776
|
+
}
|
|
3777
|
+
}
|
|
3707
3778
|
}
|
|
3708
|
-
|
|
3709
|
-
return
|
|
3779
|
+
selectedIndices.sort((a, b) => a - b);
|
|
3780
|
+
return selectedIndices.map((i) => all[i]);
|
|
3781
|
+
}
|
|
3782
|
+
function shuffleWithOrder(question) {
|
|
3783
|
+
const order = question.choices.map((_, i) => i);
|
|
3784
|
+
for (let i = order.length - 1;i > 0; i--) {
|
|
3785
|
+
const j = Math.floor(Math.random() * (i + 1));
|
|
3786
|
+
[order[i], order[j]] = [order[j], order[i]];
|
|
3787
|
+
}
|
|
3788
|
+
const renamed = order.map((o, i) => ({ ...question.choices[o], id: POSITIONAL_IDS[i] ?? question.choices[o].id }));
|
|
3789
|
+
return { question: { ...question, choices: renamed }, order };
|
|
3790
|
+
}
|
|
3791
|
+
function serveQuestions(quiz) {
|
|
3792
|
+
return selectQuestions(quiz).map((q) => {
|
|
3793
|
+
const { question, order } = shuffleWithOrder(q);
|
|
3794
|
+
return { ...question, deckIndex: quiz.questions.indexOf(q), choiceOrder: order };
|
|
3795
|
+
});
|
|
3710
3796
|
}
|
|
3711
3797
|
function toPublic(question, idx, oneShoot) {
|
|
3712
3798
|
return {
|
|
@@ -3721,6 +3807,7 @@ function toPublic(question, idx, oneShoot) {
|
|
|
3721
3807
|
};
|
|
3722
3808
|
}
|
|
3723
3809
|
|
|
3810
|
+
// packages/core/src/game.ts
|
|
3724
3811
|
class GameEngine {
|
|
3725
3812
|
state;
|
|
3726
3813
|
quiz;
|
|
@@ -3768,90 +3855,11 @@ class GameEngine {
|
|
|
3768
3855
|
this.state.players.delete(playerId);
|
|
3769
3856
|
this.transport.broadcast(this.channel, GameEvents.playerLeft(playerId));
|
|
3770
3857
|
}
|
|
3771
|
-
shuffle(arr) {
|
|
3772
|
-
const a = [...arr];
|
|
3773
|
-
for (let i = a.length - 1;i > 0; i--) {
|
|
3774
|
-
const j = Math.floor(Math.random() * (i + 1));
|
|
3775
|
-
[a[i], a[j]] = [a[j], a[i]];
|
|
3776
|
-
}
|
|
3777
|
-
return a;
|
|
3778
|
-
}
|
|
3779
|
-
selectQuestions() {
|
|
3780
|
-
const { maxQuestions, maxTimeSec, targetDifficulty } = this.quiz.meta;
|
|
3781
|
-
const all = this.quiz.questions;
|
|
3782
|
-
if (!maxQuestions && !maxTimeSec && !targetDifficulty)
|
|
3783
|
-
return all;
|
|
3784
|
-
const DIFF_RANK = { easy: 0, medium: 1, hard: 2 };
|
|
3785
|
-
if (targetDifficulty) {
|
|
3786
|
-
const targetRank = DIFF_RANK[targetDifficulty];
|
|
3787
|
-
const guardrailSet = new Set;
|
|
3788
|
-
const uniqueTags = [...new Set(all.flatMap((q) => q.tags))];
|
|
3789
|
-
for (const tag of uniqueTags) {
|
|
3790
|
-
const hardForTag = this.shuffle(all.filter((q) => q.difficulty === "hard" && q.tags.includes(tag)));
|
|
3791
|
-
for (const q of hardForTag) {
|
|
3792
|
-
if (!guardrailSet.has(q)) {
|
|
3793
|
-
guardrailSet.add(q);
|
|
3794
|
-
break;
|
|
3795
|
-
}
|
|
3796
|
-
}
|
|
3797
|
-
}
|
|
3798
|
-
const guardrail = [...guardrailSet];
|
|
3799
|
-
const pool = all.filter((q) => !guardrailSet.has(q));
|
|
3800
|
-
const targetPool = this.shuffle(pool.filter((q) => q.difficulty === targetDifficulty));
|
|
3801
|
-
const belowPool = this.shuffle(pool.filter((q) => DIFF_RANK[q.difficulty] < targetRank));
|
|
3802
|
-
const abovePool = this.shuffle(pool.filter((q) => DIFF_RANK[q.difficulty] > targetRank));
|
|
3803
|
-
const totalN = maxQuestions !== undefined ? Math.min(maxQuestions, all.length) : all.length;
|
|
3804
|
-
const slots = Math.max(0, totalN - guardrail.length);
|
|
3805
|
-
const targetCount = Math.round(slots * 0.6);
|
|
3806
|
-
const belowCount = slots - targetCount;
|
|
3807
|
-
const targetSample = targetPool.slice(0, targetCount);
|
|
3808
|
-
const belowSample = belowPool.slice(0, belowCount);
|
|
3809
|
-
const usedSet = new Set([...guardrail, ...targetSample, ...belowSample]);
|
|
3810
|
-
const shortfall = slots - targetSample.length - belowSample.length;
|
|
3811
|
-
const fallback = this.shuffle([...targetPool, ...belowPool].filter((q) => !usedSet.has(q)));
|
|
3812
|
-
const extra = fallback.slice(0, Math.max(0, shortfall));
|
|
3813
|
-
let selected = [...guardrail, ...targetSample, ...belowSample, ...extra];
|
|
3814
|
-
if (maxTimeSec !== undefined) {
|
|
3815
|
-
selected.sort((a, b) => DIFF_RANK[a.difficulty] - DIFF_RANK[b.difficulty]);
|
|
3816
|
-
let total = 0;
|
|
3817
|
-
selected = selected.filter((q) => {
|
|
3818
|
-
if (total + q.timer <= maxTimeSec) {
|
|
3819
|
-
total += q.timer;
|
|
3820
|
-
return true;
|
|
3821
|
-
}
|
|
3822
|
-
return false;
|
|
3823
|
-
});
|
|
3824
|
-
}
|
|
3825
|
-
selected.sort((a, b) => DIFF_RANK[a.difficulty] - DIFF_RANK[b.difficulty]);
|
|
3826
|
-
return selected;
|
|
3827
|
-
}
|
|
3828
|
-
const indices = all.map((_, i) => i);
|
|
3829
|
-
for (let i = indices.length - 1;i > 0; i--) {
|
|
3830
|
-
const j = Math.floor(Math.random() * (i + 1));
|
|
3831
|
-
[indices[i], indices[j]] = [indices[j], indices[i]];
|
|
3832
|
-
}
|
|
3833
|
-
let selectedIndices;
|
|
3834
|
-
if (maxQuestions !== undefined) {
|
|
3835
|
-
selectedIndices = indices.slice(0, maxQuestions);
|
|
3836
|
-
} else {
|
|
3837
|
-
selectedIndices = [];
|
|
3838
|
-
let total = 0;
|
|
3839
|
-
for (const idx of indices) {
|
|
3840
|
-
const timer = all[idx].timer;
|
|
3841
|
-
if (total + timer <= maxTimeSec) {
|
|
3842
|
-
selectedIndices.push(idx);
|
|
3843
|
-
total += timer;
|
|
3844
|
-
}
|
|
3845
|
-
}
|
|
3846
|
-
}
|
|
3847
|
-
selectedIndices.sort((a, b) => a - b);
|
|
3848
|
-
return selectedIndices.map((i) => all[i]);
|
|
3849
|
-
}
|
|
3850
3858
|
async start() {
|
|
3851
3859
|
if (this.state.status !== "lobby")
|
|
3852
3860
|
return;
|
|
3853
3861
|
this.state.status = "active";
|
|
3854
|
-
this.activeQuestions = this.
|
|
3862
|
+
this.activeQuestions = serveQuestions(this.quiz);
|
|
3855
3863
|
this.state.totalQuestions = this.activeQuestions.length;
|
|
3856
3864
|
await this.transport.broadcast(this.channel, GameEvents.gameStarted());
|
|
3857
3865
|
await this._broadcastCurrentQuestion();
|
|
@@ -3979,21 +3987,118 @@ class GameEngine {
|
|
|
3979
3987
|
}
|
|
3980
3988
|
// packages/core/src/runtime-config.ts
|
|
3981
3989
|
function configFromEnv(env) {
|
|
3982
|
-
const pick = (name) => env[`HASHQUIZ_${name}`] || env[`
|
|
3983
|
-
const grace = pick("GRACE_MS")
|
|
3990
|
+
const pick = (name) => env[`HASHQUIZ_${name}`] || env[`VITE_${name}`] || undefined;
|
|
3991
|
+
const grace = pick("GRACE_MS");
|
|
3984
3992
|
const n = grace !== undefined ? Number(grace) : NaN;
|
|
3985
3993
|
return {
|
|
3986
3994
|
transport: pick("TRANSPORT") === "supabase" ? "supabase" : "local",
|
|
3987
3995
|
supabaseUrl: pick("SUPABASE_URL"),
|
|
3988
3996
|
supabaseAnonKey: pick("SUPABASE_ANON_KEY"),
|
|
3989
|
-
graceMs: Number.isFinite(n) && n >= 0 ? n : undefined
|
|
3997
|
+
graceMs: Number.isFinite(n) && n >= 0 ? n : undefined,
|
|
3998
|
+
soloScoring: pick("SOLO_SCORING") === "edge" ? "edge" : "browser",
|
|
3999
|
+
playerUrl: pick("PLAYER_URL")
|
|
3990
4000
|
};
|
|
3991
4001
|
}
|
|
3992
4002
|
function renderConfigScript(config) {
|
|
3993
|
-
return `window.
|
|
4003
|
+
return `window.__HASHQUIZ_CONFIG__ = ${JSON.stringify(config)};
|
|
3994
4004
|
`;
|
|
3995
4005
|
}
|
|
3996
|
-
// packages/
|
|
4006
|
+
// packages/core/src/solo-verify.ts
|
|
4007
|
+
var fail = (reason) => ({ ok: false, reason });
|
|
4008
|
+
function verifySoloRun(quiz, sub) {
|
|
4009
|
+
const raw = sub;
|
|
4010
|
+
if (typeof raw !== "object" || raw === null)
|
|
4011
|
+
return fail("invalid submission");
|
|
4012
|
+
const { deckId, deckVersion, pseudo: rawPseudo, answers: rawAnswers } = raw;
|
|
4013
|
+
if (typeof deckId !== "string" || deckId.length < 1 || deckId.length > 200)
|
|
4014
|
+
return fail("invalid deckId");
|
|
4015
|
+
if (typeof deckVersion !== "string" || deckVersion.length < 1 || deckVersion.length > 64)
|
|
4016
|
+
return fail("invalid deckVersion");
|
|
4017
|
+
if (typeof rawPseudo !== "string")
|
|
4018
|
+
return fail("pseudo must be 1-24 characters");
|
|
4019
|
+
if (!Array.isArray(rawAnswers))
|
|
4020
|
+
return fail("invalid answers");
|
|
4021
|
+
for (const a of rawAnswers) {
|
|
4022
|
+
if (typeof a !== "object" || a === null || !Array.isArray(a.choices)) {
|
|
4023
|
+
return fail("invalid answer");
|
|
4024
|
+
}
|
|
4025
|
+
}
|
|
4026
|
+
const pseudo = rawPseudo.trim();
|
|
4027
|
+
if (pseudo.length < 1 || pseudo.length > 24)
|
|
4028
|
+
return fail("pseudo must be 1-24 characters");
|
|
4029
|
+
const questions = quiz.questions;
|
|
4030
|
+
const answers = rawAnswers;
|
|
4031
|
+
if (answers.length < 1)
|
|
4032
|
+
return fail("no answers");
|
|
4033
|
+
const seen = new Set;
|
|
4034
|
+
for (const a of answers) {
|
|
4035
|
+
if (!Number.isInteger(a.deckIndex) || a.deckIndex < 0 || a.deckIndex >= questions.length) {
|
|
4036
|
+
return fail("unknown question");
|
|
4037
|
+
}
|
|
4038
|
+
if (seen.has(a.deckIndex))
|
|
4039
|
+
return fail("duplicate question");
|
|
4040
|
+
seen.add(a.deckIndex);
|
|
4041
|
+
}
|
|
4042
|
+
for (const a of answers) {
|
|
4043
|
+
const q = questions[a.deckIndex];
|
|
4044
|
+
if (!Number.isInteger(a.answerTimeMs) || a.answerTimeMs < 0 || a.answerTimeMs > Math.round(q.timer * 1000)) {
|
|
4045
|
+
return fail("invalid answer time");
|
|
4046
|
+
}
|
|
4047
|
+
const picked = new Set;
|
|
4048
|
+
for (const c of a.choices) {
|
|
4049
|
+
if (!Number.isInteger(c) || c < 0 || c >= q.choices.length || picked.has(c)) {
|
|
4050
|
+
return fail("invalid choice");
|
|
4051
|
+
}
|
|
4052
|
+
picked.add(c);
|
|
4053
|
+
}
|
|
4054
|
+
}
|
|
4055
|
+
const { maxQuestions, maxTimeSec, targetDifficulty } = quiz.meta;
|
|
4056
|
+
if (maxTimeSec) {
|
|
4057
|
+
const total = answers.reduce((sum, a) => sum + questions[a.deckIndex].timer, 0);
|
|
4058
|
+
if (total > maxTimeSec)
|
|
4059
|
+
return fail("over max time");
|
|
4060
|
+
}
|
|
4061
|
+
const n = questions.length;
|
|
4062
|
+
const cap = maxQuestions ? Math.min(maxQuestions, n) : n;
|
|
4063
|
+
if (maxQuestions && answers.length > cap)
|
|
4064
|
+
return fail("too many answers");
|
|
4065
|
+
if (!maxTimeSec && !targetDifficulty && answers.length !== cap)
|
|
4066
|
+
return fail("wrong answer count");
|
|
4067
|
+
let score = 0;
|
|
4068
|
+
let correctCount = 0;
|
|
4069
|
+
let totalTimeMs = 0;
|
|
4070
|
+
const verified = answers.map((a, position) => {
|
|
4071
|
+
const q = questions[a.deckIndex];
|
|
4072
|
+
const correct = new Set;
|
|
4073
|
+
q.choices.forEach((c, i) => {
|
|
4074
|
+
if (c.isCorrect)
|
|
4075
|
+
correct.add(i);
|
|
4076
|
+
});
|
|
4077
|
+
const isCorrect = a.choices.length === correct.size && a.choices.every((c) => correct.has(c));
|
|
4078
|
+
const points = calcPoints(Math.max(0, q.timer - a.answerTimeMs / 1000), isCorrect);
|
|
4079
|
+
score += points;
|
|
4080
|
+
if (isCorrect)
|
|
4081
|
+
correctCount++;
|
|
4082
|
+
totalTimeMs += a.answerTimeMs;
|
|
4083
|
+
return { deckIndex: a.deckIndex, choices: [...a.choices], answerTimeMs: a.answerTimeMs, position, isCorrect, points };
|
|
4084
|
+
});
|
|
4085
|
+
return {
|
|
4086
|
+
ok: true,
|
|
4087
|
+
run: {
|
|
4088
|
+
deckId,
|
|
4089
|
+
deckVersion,
|
|
4090
|
+
pseudo,
|
|
4091
|
+
score,
|
|
4092
|
+
correctCount,
|
|
4093
|
+
questionCount: answers.length,
|
|
4094
|
+
totalTimeMs,
|
|
4095
|
+
answers: verified
|
|
4096
|
+
}
|
|
4097
|
+
};
|
|
4098
|
+
}
|
|
4099
|
+
// packages/core/src/solo-backend.ts
|
|
4100
|
+
var EMAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
|
|
4101
|
+
// packages/backend-local/src/index.ts
|
|
3997
4102
|
class LocalTransport {
|
|
3998
4103
|
subscribers = new Map;
|
|
3999
4104
|
presenceStore = new Map;
|
|
@@ -4054,9 +4159,462 @@ class LocalTransport {
|
|
|
4054
4159
|
}
|
|
4055
4160
|
}
|
|
4056
4161
|
|
|
4162
|
+
// packages/backend-local/src/solo/store.ts
|
|
4163
|
+
import { Database } from "bun:sqlite";
|
|
4164
|
+
import { mkdirSync } from "fs";
|
|
4165
|
+
import { dirname } from "path";
|
|
4166
|
+
var DEFAULT_SOLO_DB = ".hashquiz/solo.db";
|
|
4167
|
+
var SCHEMA = `
|
|
4168
|
+
CREATE TABLE IF NOT EXISTS solo_runs (
|
|
4169
|
+
id TEXT PRIMARY KEY,
|
|
4170
|
+
deck_id TEXT NOT NULL,
|
|
4171
|
+
deck_version TEXT NOT NULL,
|
|
4172
|
+
room_id TEXT,
|
|
4173
|
+
pseudo TEXT NOT NULL CHECK (length(pseudo) BETWEEN 1 AND 24),
|
|
4174
|
+
score INTEGER NOT NULL,
|
|
4175
|
+
correct_count INTEGER NOT NULL,
|
|
4176
|
+
question_count INTEGER NOT NULL,
|
|
4177
|
+
total_time_ms INTEGER NOT NULL,
|
|
4178
|
+
finished_at TEXT NOT NULL
|
|
4179
|
+
) STRICT;
|
|
4180
|
+
CREATE INDEX IF NOT EXISTS solo_runs_leaderboard_idx
|
|
4181
|
+
ON solo_runs (deck_id, score DESC, total_time_ms, finished_at);
|
|
4182
|
+
CREATE TABLE IF NOT EXISTS solo_answers (
|
|
4183
|
+
run_id TEXT NOT NULL REFERENCES solo_runs (id) ON DELETE CASCADE,
|
|
4184
|
+
position INTEGER NOT NULL,
|
|
4185
|
+
deck_index INTEGER NOT NULL,
|
|
4186
|
+
choices TEXT NOT NULL,
|
|
4187
|
+
is_correct INTEGER NOT NULL CHECK (is_correct IN (0, 1)),
|
|
4188
|
+
answer_time_ms INTEGER NOT NULL,
|
|
4189
|
+
points INTEGER NOT NULL,
|
|
4190
|
+
PRIMARY KEY (run_id, position)
|
|
4191
|
+
) STRICT;
|
|
4192
|
+
CREATE TABLE IF NOT EXISTS leads (
|
|
4193
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
4194
|
+
email TEXT NOT NULL CHECK (length(email) <= 254),
|
|
4195
|
+
consent INTEGER NOT NULL CHECK (consent = 1),
|
|
4196
|
+
deck_id TEXT CHECK (length(deck_id) <= 200),
|
|
4197
|
+
created_at TEXT NOT NULL
|
|
4198
|
+
) STRICT;
|
|
4199
|
+
`;
|
|
4200
|
+
var RANKED_COLS = "id, pseudo, score, total_time_ms AS totalTimeMs, finished_at AS finishedAt";
|
|
4201
|
+
|
|
4202
|
+
class SoloStore {
|
|
4203
|
+
db;
|
|
4204
|
+
insertRunStmt;
|
|
4205
|
+
insertAnswerStmt;
|
|
4206
|
+
topStmt;
|
|
4207
|
+
runStmt;
|
|
4208
|
+
countStmt;
|
|
4209
|
+
rankStmt;
|
|
4210
|
+
leadStmt;
|
|
4211
|
+
insertAll;
|
|
4212
|
+
constructor(db) {
|
|
4213
|
+
this.db = db;
|
|
4214
|
+
db.run("PRAGMA journal_mode = WAL");
|
|
4215
|
+
db.run("PRAGMA foreign_keys = ON");
|
|
4216
|
+
db.run(SCHEMA);
|
|
4217
|
+
db.run("PRAGMA user_version = 1");
|
|
4218
|
+
this.insertRunStmt = db.prepare(`INSERT INTO solo_runs (id, deck_id, deck_version, pseudo, score, correct_count, question_count, total_time_ms, finished_at)
|
|
4219
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
|
4220
|
+
this.insertAnswerStmt = db.prepare(`INSERT INTO solo_answers (run_id, position, deck_index, choices, is_correct, answer_time_ms, points)
|
|
4221
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`);
|
|
4222
|
+
this.topStmt = db.prepare(`SELECT ${RANKED_COLS} FROM solo_runs WHERE deck_id = ?
|
|
4223
|
+
ORDER BY score DESC, total_time_ms ASC, finished_at ASC LIMIT ?`);
|
|
4224
|
+
this.runStmt = db.prepare(`SELECT ${RANKED_COLS} FROM solo_runs WHERE id = ?`);
|
|
4225
|
+
this.countStmt = db.prepare("SELECT count(*) AS n FROM solo_runs WHERE deck_id = ?");
|
|
4226
|
+
this.rankStmt = db.prepare(`SELECT 1 + (
|
|
4227
|
+
SELECT count(*) FROM solo_runs o
|
|
4228
|
+
WHERE o.deck_id = r.deck_id AND (
|
|
4229
|
+
o.score > r.score
|
|
4230
|
+
OR (o.score = r.score AND o.total_time_ms < r.total_time_ms)
|
|
4231
|
+
OR (o.score = r.score AND o.total_time_ms = r.total_time_ms AND o.finished_at < r.finished_at)
|
|
4232
|
+
)
|
|
4233
|
+
) AS rank
|
|
4234
|
+
FROM solo_runs r WHERE r.id = ?`);
|
|
4235
|
+
this.leadStmt = db.prepare("INSERT INTO leads (email, consent, deck_id, created_at) VALUES (?, 1, ?, ?)");
|
|
4236
|
+
this.insertAll = db.transaction((id, run, finishedAt) => {
|
|
4237
|
+
this.insertRunStmt.run(id, run.deckId, run.deckVersion, run.pseudo, run.score, run.correctCount, run.questionCount, run.totalTimeMs, finishedAt);
|
|
4238
|
+
for (const a of run.answers) {
|
|
4239
|
+
this.insertAnswerStmt.run(id, a.position, a.deckIndex, JSON.stringify(a.choices), a.isCorrect ? 1 : 0, a.answerTimeMs, a.points);
|
|
4240
|
+
}
|
|
4241
|
+
});
|
|
4242
|
+
}
|
|
4243
|
+
static open(path) {
|
|
4244
|
+
if (path !== ":memory:")
|
|
4245
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
4246
|
+
return new SoloStore(new Database(path));
|
|
4247
|
+
}
|
|
4248
|
+
insertRun(run, finishedAt = new Date().toISOString()) {
|
|
4249
|
+
const n = run.answers.length;
|
|
4250
|
+
if (n < 1 || n > 200)
|
|
4251
|
+
throw new Error("solo run must have between 1 and 200 answers");
|
|
4252
|
+
if (n !== run.questionCount)
|
|
4253
|
+
throw new Error("solo run answer count does not match questionCount");
|
|
4254
|
+
const id = crypto.randomUUID();
|
|
4255
|
+
this.insertAll(id, run, finishedAt);
|
|
4256
|
+
return id;
|
|
4257
|
+
}
|
|
4258
|
+
top(deckId, limit) {
|
|
4259
|
+
return this.topStmt.all(deckId, limit);
|
|
4260
|
+
}
|
|
4261
|
+
run(runId) {
|
|
4262
|
+
return this.runStmt.get(runId) ?? null;
|
|
4263
|
+
}
|
|
4264
|
+
count(deckId) {
|
|
4265
|
+
return this.countStmt.get(deckId)?.n ?? 0;
|
|
4266
|
+
}
|
|
4267
|
+
rank(runId) {
|
|
4268
|
+
return this.rankStmt.get(runId)?.rank ?? null;
|
|
4269
|
+
}
|
|
4270
|
+
insertLead(email, deckId) {
|
|
4271
|
+
if (!EMAIL_RE.test(email))
|
|
4272
|
+
throw new Error("invalid email");
|
|
4273
|
+
this.leadStmt.run(email, deckId, new Date().toISOString());
|
|
4274
|
+
}
|
|
4275
|
+
close() {
|
|
4276
|
+
this.db.close();
|
|
4277
|
+
}
|
|
4278
|
+
}
|
|
4279
|
+
// packages/backend-local/src/solo/protocol.ts
|
|
4280
|
+
var SOLO_WS_ROLE = "solo";
|
|
4281
|
+
var soloTopic = (deckId) => `solo:${deckId}`;
|
|
4282
|
+
|
|
4283
|
+
// packages/backend-local/src/solo/server.ts
|
|
4284
|
+
var SOLO_MAX_BODY = 65536;
|
|
4285
|
+
var DEFAULT_LIMIT = 20;
|
|
4286
|
+
var MAX_LIMIT = 100;
|
|
4287
|
+
var CORS = {
|
|
4288
|
+
"access-control-allow-origin": "*",
|
|
4289
|
+
"access-control-allow-methods": "GET, POST, OPTIONS",
|
|
4290
|
+
"access-control-allow-headers": "content-type"
|
|
4291
|
+
};
|
|
4292
|
+
var json = (status, body) => new Response(JSON.stringify(body), { status, headers: { ...CORS, "content-type": "application/json" } });
|
|
4293
|
+
var empty = (status) => new Response(null, { status, headers: CORS });
|
|
4294
|
+
var reason = (status, r) => json(status, { reason: r });
|
|
4295
|
+
|
|
4296
|
+
class TooLarge extends Error {
|
|
4297
|
+
}
|
|
4298
|
+
async function readBody(req) {
|
|
4299
|
+
const declared = Number(req.headers.get("content-length"));
|
|
4300
|
+
if (Number.isFinite(declared) && declared > SOLO_MAX_BODY)
|
|
4301
|
+
throw new TooLarge;
|
|
4302
|
+
if (!req.body)
|
|
4303
|
+
return "";
|
|
4304
|
+
const reader = req.body.getReader();
|
|
4305
|
+
const chunks = [];
|
|
4306
|
+
let size = 0;
|
|
4307
|
+
for (;; ) {
|
|
4308
|
+
const { done, value } = await reader.read();
|
|
4309
|
+
if (done)
|
|
4310
|
+
break;
|
|
4311
|
+
size += value.byteLength;
|
|
4312
|
+
if (size > SOLO_MAX_BODY) {
|
|
4313
|
+
await reader.cancel();
|
|
4314
|
+
throw new TooLarge;
|
|
4315
|
+
}
|
|
4316
|
+
chunks.push(value);
|
|
4317
|
+
}
|
|
4318
|
+
return new TextDecoder().decode(Buffer.concat(chunks));
|
|
4319
|
+
}
|
|
4320
|
+
async function parseBody(req) {
|
|
4321
|
+
let text;
|
|
4322
|
+
try {
|
|
4323
|
+
text = await readBody(req);
|
|
4324
|
+
} catch (e) {
|
|
4325
|
+
if (e instanceof TooLarge)
|
|
4326
|
+
return { ok: false, res: reason(413, "body too large") };
|
|
4327
|
+
throw e;
|
|
4328
|
+
}
|
|
4329
|
+
try {
|
|
4330
|
+
return { ok: true, value: JSON.parse(text) };
|
|
4331
|
+
} catch {
|
|
4332
|
+
return { ok: false, res: reason(422, "invalid json") };
|
|
4333
|
+
}
|
|
4334
|
+
}
|
|
4335
|
+
function clampLimit(raw) {
|
|
4336
|
+
const n = raw === null ? NaN : Math.trunc(Number(raw));
|
|
4337
|
+
if (!Number.isFinite(n))
|
|
4338
|
+
return DEFAULT_LIMIT;
|
|
4339
|
+
return Math.min(MAX_LIMIT, Math.max(1, n));
|
|
4340
|
+
}
|
|
4341
|
+
var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
4342
|
+
function createSoloHttpHandler(o) {
|
|
4343
|
+
async function submitRun(req) {
|
|
4344
|
+
const body = await parseBody(req);
|
|
4345
|
+
if (!body.ok)
|
|
4346
|
+
return body.res;
|
|
4347
|
+
if (!isRecord(body.value))
|
|
4348
|
+
return reason(422, "invalid submission");
|
|
4349
|
+
const { deckId, deckVersion, pseudo, answers } = body.value;
|
|
4350
|
+
if (typeof deckId !== "string")
|
|
4351
|
+
return reason(422, "invalid deckId");
|
|
4352
|
+
if (typeof deckVersion !== "string")
|
|
4353
|
+
return reason(422, "invalid deckVersion");
|
|
4354
|
+
const sub = { deckId, deckVersion, pseudo, answers };
|
|
4355
|
+
const found = await o.decks.resolve(deckId, deckVersion);
|
|
4356
|
+
if (!found.ok)
|
|
4357
|
+
return reason(found.reason === "decks unavailable" ? 503 : 422, found.reason);
|
|
4358
|
+
const verified = verifySoloRun(found.deck.quiz, sub);
|
|
4359
|
+
if (!verified.ok)
|
|
4360
|
+
return reason(422, verified.reason);
|
|
4361
|
+
const runId = o.store.insertRun(verified.run, new Date().toISOString());
|
|
4362
|
+
o.publish(soloTopic(deckId), { type: "solo_new_run", deckId });
|
|
4363
|
+
let rank = null;
|
|
4364
|
+
try {
|
|
4365
|
+
rank = o.store.rank(runId);
|
|
4366
|
+
} catch (e) {
|
|
4367
|
+
console.error("Failed to rank solo run:", e);
|
|
4368
|
+
}
|
|
4369
|
+
return json(200, { runId, rank });
|
|
4370
|
+
}
|
|
4371
|
+
async function submitLead(req) {
|
|
4372
|
+
const body = await parseBody(req);
|
|
4373
|
+
if (!body.ok)
|
|
4374
|
+
return body.res;
|
|
4375
|
+
if (!isRecord(body.value))
|
|
4376
|
+
return reason(422, "invalid lead");
|
|
4377
|
+
const { email, deckId } = body.value;
|
|
4378
|
+
if (typeof email !== "string" || email.length > 254 || !EMAIL_RE.test(email))
|
|
4379
|
+
return reason(422, "invalid email");
|
|
4380
|
+
if (deckId !== undefined && deckId !== null && (typeof deckId !== "string" || deckId.length > 200)) {
|
|
4381
|
+
return reason(422, "invalid deckId");
|
|
4382
|
+
}
|
|
4383
|
+
o.store.insertLead(email, typeof deckId === "string" ? deckId : null);
|
|
4384
|
+
return empty(204);
|
|
4385
|
+
}
|
|
4386
|
+
return async (req) => {
|
|
4387
|
+
const url = new URL(req.url);
|
|
4388
|
+
if (!url.pathname.startsWith("/solo/"))
|
|
4389
|
+
return null;
|
|
4390
|
+
if (req.method === "OPTIONS")
|
|
4391
|
+
return empty(204);
|
|
4392
|
+
try {
|
|
4393
|
+
return await dispatch(req, url);
|
|
4394
|
+
} catch (e) {
|
|
4395
|
+
console.error("Solo store failed:", e);
|
|
4396
|
+
return reason(500, "store failed");
|
|
4397
|
+
}
|
|
4398
|
+
};
|
|
4399
|
+
async function dispatch(req, url) {
|
|
4400
|
+
const parts = url.pathname.slice("/solo/".length).split("/");
|
|
4401
|
+
const route = parts[0];
|
|
4402
|
+
let id;
|
|
4403
|
+
try {
|
|
4404
|
+
id = parts.length === 2 && parts[1] ? decodeURIComponent(parts[1]) : undefined;
|
|
4405
|
+
} catch {
|
|
4406
|
+
return reason(404, "not found");
|
|
4407
|
+
}
|
|
4408
|
+
const deck = url.searchParams.get("deck");
|
|
4409
|
+
if (req.method === "POST" && parts.length === 1) {
|
|
4410
|
+
if (route === "runs")
|
|
4411
|
+
return submitRun(req);
|
|
4412
|
+
if (route === "leads")
|
|
4413
|
+
return submitLead(req);
|
|
4414
|
+
}
|
|
4415
|
+
if (req.method === "GET") {
|
|
4416
|
+
if (route === "runs" && parts.length === 1) {
|
|
4417
|
+
if (!deck)
|
|
4418
|
+
return reason(422, "missing deck");
|
|
4419
|
+
return json(200, o.store.top(deck, clampLimit(url.searchParams.get("limit"))));
|
|
4420
|
+
}
|
|
4421
|
+
if (route === "runs" && id) {
|
|
4422
|
+
const run = o.store.run(id);
|
|
4423
|
+
return run ? json(200, run) : reason(404, "unknown run");
|
|
4424
|
+
}
|
|
4425
|
+
if (route === "count" && parts.length === 1) {
|
|
4426
|
+
if (!deck)
|
|
4427
|
+
return reason(422, "missing deck");
|
|
4428
|
+
return json(200, { count: o.store.count(deck) });
|
|
4429
|
+
}
|
|
4430
|
+
if (route === "rank" && id) {
|
|
4431
|
+
const rank = o.store.rank(id);
|
|
4432
|
+
return rank === null ? reason(404, "unknown run") : json(200, { rank });
|
|
4433
|
+
}
|
|
4434
|
+
}
|
|
4435
|
+
return reason(404, "not found");
|
|
4436
|
+
}
|
|
4437
|
+
}
|
|
4438
|
+
var isCount = (v) => typeof v === "number" && Number.isInteger(v) && v >= 0;
|
|
4439
|
+
function validState(s) {
|
|
4440
|
+
if (!isRecord(s) || typeof s.pseudo !== "string")
|
|
4441
|
+
return null;
|
|
4442
|
+
const pseudo = s.pseudo.trim();
|
|
4443
|
+
if (pseudo.length < 1 || pseudo.length > 24)
|
|
4444
|
+
return null;
|
|
4445
|
+
if (!isCount(s.index) || !isCount(s.total) || !isCount(s.score))
|
|
4446
|
+
return null;
|
|
4447
|
+
return { pseudo, index: s.index, total: s.total, score: s.score };
|
|
4448
|
+
}
|
|
4449
|
+
|
|
4450
|
+
class SoloPresenceHub {
|
|
4451
|
+
publish;
|
|
4452
|
+
decks = new Map;
|
|
4453
|
+
constructor(publish) {
|
|
4454
|
+
this.publish = publish;
|
|
4455
|
+
}
|
|
4456
|
+
open(conn) {
|
|
4457
|
+
const msg = { type: "solo_presence", deckId: conn.deckId, players: this.list(conn.deckId) };
|
|
4458
|
+
conn.send(JSON.stringify(msg));
|
|
4459
|
+
}
|
|
4460
|
+
message(conn, raw) {
|
|
4461
|
+
if (raw.length > SOLO_MAX_BODY)
|
|
4462
|
+
return;
|
|
4463
|
+
let msg;
|
|
4464
|
+
try {
|
|
4465
|
+
msg = JSON.parse(raw);
|
|
4466
|
+
} catch {
|
|
4467
|
+
return;
|
|
4468
|
+
}
|
|
4469
|
+
if (!isRecord(msg))
|
|
4470
|
+
return;
|
|
4471
|
+
if (msg.type === "solo_track") {
|
|
4472
|
+
const state = validState(msg.state);
|
|
4473
|
+
if (!state)
|
|
4474
|
+
return;
|
|
4475
|
+
let rows = this.decks.get(conn.deckId);
|
|
4476
|
+
if (!rows)
|
|
4477
|
+
this.decks.set(conn.deckId, rows = new Map);
|
|
4478
|
+
rows.set(conn.key, { conn, player: { key: conn.key, ...state } });
|
|
4479
|
+
this.changed(conn.deckId);
|
|
4480
|
+
} else if (msg.type === "solo_untrack") {
|
|
4481
|
+
this.remove(conn);
|
|
4482
|
+
}
|
|
4483
|
+
}
|
|
4484
|
+
close(conn) {
|
|
4485
|
+
this.remove(conn);
|
|
4486
|
+
}
|
|
4487
|
+
list(deckId) {
|
|
4488
|
+
return [...this.decks.get(deckId)?.values() ?? []].map((r) => ({ ...r.player }));
|
|
4489
|
+
}
|
|
4490
|
+
remove(conn) {
|
|
4491
|
+
const rows = this.decks.get(conn.deckId);
|
|
4492
|
+
if (rows?.get(conn.key)?.conn !== conn)
|
|
4493
|
+
return;
|
|
4494
|
+
rows.delete(conn.key);
|
|
4495
|
+
if (rows.size === 0)
|
|
4496
|
+
this.decks.delete(conn.deckId);
|
|
4497
|
+
this.changed(conn.deckId);
|
|
4498
|
+
}
|
|
4499
|
+
changed(deckId) {
|
|
4500
|
+
this.publish(soloTopic(deckId), { type: "solo_presence", deckId, players: this.list(deckId) });
|
|
4501
|
+
}
|
|
4502
|
+
}
|
|
4503
|
+
// packages/core/src/decks.ts
|
|
4504
|
+
function deckVersion(content) {
|
|
4505
|
+
let hash = 2166136261;
|
|
4506
|
+
for (let i = 0;i < content.length; i++) {
|
|
4507
|
+
hash ^= content.charCodeAt(i);
|
|
4508
|
+
hash = Math.imul(hash, 16777619) >>> 0;
|
|
4509
|
+
}
|
|
4510
|
+
return (hash >>> 0).toString(16).padStart(8, "0");
|
|
4511
|
+
}
|
|
4512
|
+
function toDecks(entries) {
|
|
4513
|
+
return entries.flatMap(({ id, content }) => {
|
|
4514
|
+
try {
|
|
4515
|
+
const quiz = parseQuizFile(content);
|
|
4516
|
+
return [{ id, name: quiz.meta.title || id, version: deckVersion(content), quiz }];
|
|
4517
|
+
} catch (e) {
|
|
4518
|
+
console.error(`Skipping deck ${id}:`, e);
|
|
4519
|
+
return [];
|
|
4520
|
+
}
|
|
4521
|
+
}).sort((a, b) => a.name.localeCompare(b.name));
|
|
4522
|
+
}
|
|
4523
|
+
|
|
4524
|
+
// packages/core/src/solo-decks.ts
|
|
4525
|
+
function parseManifest(json) {
|
|
4526
|
+
const valid = Array.isArray(json) && json.every((e) => typeof e === "object" && e !== null && typeof e.id === "string" && typeof e.content === "string");
|
|
4527
|
+
if (!valid)
|
|
4528
|
+
throw new Error("invalid decks manifest");
|
|
4529
|
+
return json.map(({ id, content }) => ({ id, content }));
|
|
4530
|
+
}
|
|
4531
|
+
|
|
4532
|
+
class SoloDeckSource {
|
|
4533
|
+
load;
|
|
4534
|
+
decks = null;
|
|
4535
|
+
loadedAt = 0;
|
|
4536
|
+
lastForcedAt = -Infinity;
|
|
4537
|
+
lastFailedAt = -Infinity;
|
|
4538
|
+
inflight = null;
|
|
4539
|
+
ttlMs;
|
|
4540
|
+
minRefetchMs;
|
|
4541
|
+
now;
|
|
4542
|
+
constructor(load, opts = {}) {
|
|
4543
|
+
this.load = load;
|
|
4544
|
+
this.ttlMs = opts.ttlMs ?? 300000;
|
|
4545
|
+
this.minRefetchMs = opts.minRefetchMs ?? 1e4;
|
|
4546
|
+
this.now = opts.now ?? Date.now;
|
|
4547
|
+
}
|
|
4548
|
+
async resolve(deckId, deckVersion) {
|
|
4549
|
+
if (!this.decks || this.now() - this.loadedAt > this.ttlMs)
|
|
4550
|
+
await this.reload();
|
|
4551
|
+
if (!this.decks)
|
|
4552
|
+
return { ok: false, reason: "decks unavailable" };
|
|
4553
|
+
let found = this.lookup(deckId, deckVersion);
|
|
4554
|
+
if (!found.ok && this.now() - this.lastForcedAt >= this.minRefetchMs) {
|
|
4555
|
+
this.lastForcedAt = this.now();
|
|
4556
|
+
await this.reload();
|
|
4557
|
+
found = this.lookup(deckId, deckVersion);
|
|
4558
|
+
}
|
|
4559
|
+
return found;
|
|
4560
|
+
}
|
|
4561
|
+
lookup(deckId, version) {
|
|
4562
|
+
const deck = this.decks?.get(deckId);
|
|
4563
|
+
if (!deck)
|
|
4564
|
+
return { ok: false, reason: "unknown deck" };
|
|
4565
|
+
if (deck.version !== version)
|
|
4566
|
+
return { ok: false, reason: "deck version mismatch" };
|
|
4567
|
+
return { ok: true, deck };
|
|
4568
|
+
}
|
|
4569
|
+
reload() {
|
|
4570
|
+
if (this.inflight)
|
|
4571
|
+
return this.inflight;
|
|
4572
|
+
if (this.now() - this.lastFailedAt < this.minRefetchMs)
|
|
4573
|
+
return Promise.resolve();
|
|
4574
|
+
this.inflight = this.load().then((entries) => {
|
|
4575
|
+
this.decks = new Map(toDecks(entries).filter((d) => d.quiz.meta.solo).map((d) => [d.id, d]));
|
|
4576
|
+
this.loadedAt = this.now();
|
|
4577
|
+
}).catch((e) => {
|
|
4578
|
+
this.lastFailedAt = this.now();
|
|
4579
|
+
console.error("Failed to load solo decks:", e);
|
|
4580
|
+
}).finally(() => {
|
|
4581
|
+
this.inflight = null;
|
|
4582
|
+
});
|
|
4583
|
+
return this.inflight;
|
|
4584
|
+
}
|
|
4585
|
+
}
|
|
4586
|
+
|
|
4057
4587
|
// packages/server/src/server.ts
|
|
4058
|
-
import { readFileSync } from "fs";
|
|
4588
|
+
import { readFileSync as readFileSync2 } from "fs";
|
|
4059
4589
|
import { networkInterfaces } from "os";
|
|
4590
|
+
import { resolve } from "path";
|
|
4591
|
+
|
|
4592
|
+
// packages/server/src/web-assets.ts
|
|
4593
|
+
import { readdirSync, readFileSync, statSync } from "fs";
|
|
4594
|
+
import { join, relative, sep } from "path";
|
|
4595
|
+
var SKIP = new Set(["node_modules", "dist", ".git"]);
|
|
4596
|
+
function collectDecks(dir) {
|
|
4597
|
+
const out = [];
|
|
4598
|
+
const walk = (d) => {
|
|
4599
|
+
for (const name of readdirSync(d)) {
|
|
4600
|
+
if (SKIP.has(name) || name.startsWith("."))
|
|
4601
|
+
continue;
|
|
4602
|
+
const p = join(d, name);
|
|
4603
|
+
if (statSync(p).isDirectory())
|
|
4604
|
+
walk(p);
|
|
4605
|
+
else if (name.endsWith(".hashquiz.md")) {
|
|
4606
|
+
out.push({ id: relative(dir, p).split(sep).join("/"), content: readFileSync(p, "utf-8") });
|
|
4607
|
+
}
|
|
4608
|
+
}
|
|
4609
|
+
};
|
|
4610
|
+
walk(dir);
|
|
4611
|
+
return out.sort((a, b) => a.id.localeCompare(b.id));
|
|
4612
|
+
}
|
|
4613
|
+
function renderDecksJson(dir) {
|
|
4614
|
+
return JSON.stringify(collectDecks(dir));
|
|
4615
|
+
}
|
|
4616
|
+
|
|
4617
|
+
// packages/server/src/server.ts
|
|
4060
4618
|
function getLocalIP() {
|
|
4061
4619
|
const nets = networkInterfaces();
|
|
4062
4620
|
for (const ifaces of Object.values(nets)) {
|
|
@@ -4068,14 +4626,26 @@ function getLocalIP() {
|
|
|
4068
4626
|
}
|
|
4069
4627
|
return "localhost";
|
|
4070
4628
|
}
|
|
4629
|
+
function soloConn(ws, deckId, key) {
|
|
4630
|
+
return {
|
|
4631
|
+
deckId,
|
|
4632
|
+
key,
|
|
4633
|
+
send(data) {
|
|
4634
|
+
if (ws.readyState === WebSocket.OPEN)
|
|
4635
|
+
ws.send(data);
|
|
4636
|
+
}
|
|
4637
|
+
};
|
|
4638
|
+
}
|
|
4071
4639
|
function generateJoinCode() {
|
|
4072
4640
|
return Math.random().toString(36).slice(2, 8).toUpperCase();
|
|
4073
4641
|
}
|
|
4642
|
+
var SOLO_PARAM_MAX = 200;
|
|
4643
|
+
var isSolo = (d) => d.role === SOLO_WS_ROLE;
|
|
4074
4644
|
var DEFAULT_GRACE_MS = 60000;
|
|
4075
4645
|
function resolveGraceMs(opt) {
|
|
4076
4646
|
if (typeof opt === "number" && Number.isFinite(opt) && opt >= 0)
|
|
4077
4647
|
return opt;
|
|
4078
|
-
const raw = process.env["
|
|
4648
|
+
const raw = process.env["HASHQUIZ_GRACE_MS"];
|
|
4079
4649
|
if (raw) {
|
|
4080
4650
|
const n = Number(raw);
|
|
4081
4651
|
if (Number.isFinite(n) && n >= 0)
|
|
@@ -4130,7 +4700,7 @@ function buildQuizInfo(quiz) {
|
|
|
4130
4700
|
return { title, description, tags, totalQuestions: totalN, targetDifficulty, difficultyDistribution: dist };
|
|
4131
4701
|
}
|
|
4132
4702
|
|
|
4133
|
-
class
|
|
4703
|
+
class HashQuizServer {
|
|
4134
4704
|
engine;
|
|
4135
4705
|
transport;
|
|
4136
4706
|
joinCode;
|
|
@@ -4139,13 +4709,15 @@ class QuizvServer {
|
|
|
4139
4709
|
quizMeta;
|
|
4140
4710
|
graceMs;
|
|
4141
4711
|
graceTimers = new Map;
|
|
4712
|
+
server = null;
|
|
4713
|
+
solo = null;
|
|
4142
4714
|
constructor(options2) {
|
|
4143
4715
|
this.port = options2.port ?? 3030;
|
|
4144
4716
|
this.quizFile = options2.quizFile;
|
|
4145
4717
|
this.joinCode = generateJoinCode();
|
|
4146
4718
|
this.transport = new LocalTransport;
|
|
4147
4719
|
this.graceMs = resolveGraceMs(options2.graceMs);
|
|
4148
|
-
const content =
|
|
4720
|
+
const content = readFileSync2(options2.quizFile, "utf-8");
|
|
4149
4721
|
const quiz = parseQuizFile(content);
|
|
4150
4722
|
const result = validateQuiz(quiz);
|
|
4151
4723
|
if (!result.valid) {
|
|
@@ -4158,15 +4730,54 @@ class QuizvServer {
|
|
|
4158
4730
|
}
|
|
4159
4731
|
this.engine = new GameEngine(quiz, this.transport, this.joinCode);
|
|
4160
4732
|
this.quizMeta = buildQuizInfo(quiz);
|
|
4733
|
+
if (options2.decksDir)
|
|
4734
|
+
this.solo = this._createSolo(options2.decksDir, options2.soloDbPath);
|
|
4735
|
+
}
|
|
4736
|
+
_createSolo(decksDir, dbPath) {
|
|
4737
|
+
const path = dbPath ?? resolve(DEFAULT_SOLO_DB);
|
|
4738
|
+
let store;
|
|
4739
|
+
try {
|
|
4740
|
+
store = SoloStore.open(path);
|
|
4741
|
+
} catch (err) {
|
|
4742
|
+
console.warn(`Local solo disabled: cannot open the solo leaderboard ${path} (${err.message})`);
|
|
4743
|
+
return null;
|
|
4744
|
+
}
|
|
4745
|
+
const decks = new SoloDeckSource(async () => parseManifest(collectDecks(decksDir)), { ttlMs: Infinity, minRefetchMs: 1000 });
|
|
4746
|
+
const publish = (topic, msg) => {
|
|
4747
|
+
this.server?.publish(topic, JSON.stringify(msg));
|
|
4748
|
+
};
|
|
4749
|
+
return { http: createSoloHttpHandler({ decks, store, publish }), hub: new SoloPresenceHub(publish), store };
|
|
4750
|
+
}
|
|
4751
|
+
stop() {
|
|
4752
|
+
this.server?.stop(true);
|
|
4753
|
+
this.server = null;
|
|
4754
|
+
for (const t of this.graceTimers.values())
|
|
4755
|
+
clearTimeout(t);
|
|
4756
|
+
this.graceTimers.clear();
|
|
4757
|
+
this.solo?.store.close();
|
|
4758
|
+
this.solo = null;
|
|
4161
4759
|
}
|
|
4162
4760
|
start() {
|
|
4163
4761
|
const self = this;
|
|
4164
4762
|
const server = Bun.serve({
|
|
4165
4763
|
port: this.port,
|
|
4166
|
-
fetch(req, server) {
|
|
4764
|
+
async fetch(req, server) {
|
|
4167
4765
|
const url = new URL(req.url);
|
|
4168
4766
|
if (req.headers.get("upgrade") === "websocket") {
|
|
4169
4767
|
const role = url.searchParams.get("role") ?? "player";
|
|
4768
|
+
if (role === SOLO_WS_ROLE) {
|
|
4769
|
+
if (!self.solo)
|
|
4770
|
+
return new Response("Solo is not enabled", { status: 404 });
|
|
4771
|
+
const deckId = url.searchParams.get("deck");
|
|
4772
|
+
const key = url.searchParams.get("key") ?? crypto.randomUUID();
|
|
4773
|
+
const sane = (v) => !!v && v.length <= SOLO_PARAM_MAX;
|
|
4774
|
+
if (!sane(deckId) || !sane(key))
|
|
4775
|
+
return new Response("Invalid deck or key", { status: 400 });
|
|
4776
|
+
const data = { role, deckId, key };
|
|
4777
|
+
if (server.upgrade(req, { data }))
|
|
4778
|
+
return;
|
|
4779
|
+
return new Response("WebSocket upgrade failed", { status: 400 });
|
|
4780
|
+
}
|
|
4170
4781
|
const playerId = url.searchParams.get("id") ?? crypto.randomUUID();
|
|
4171
4782
|
if (role === "player" && url.searchParams.get("code") !== self.joinCode) {
|
|
4172
4783
|
return new Response("Invalid join code", { status: 403 });
|
|
@@ -4176,6 +4787,11 @@ class QuizvServer {
|
|
|
4176
4787
|
return;
|
|
4177
4788
|
return new Response("WebSocket upgrade failed", { status: 400 });
|
|
4178
4789
|
}
|
|
4790
|
+
if (self.solo) {
|
|
4791
|
+
const res = await self.solo.http(req);
|
|
4792
|
+
if (res)
|
|
4793
|
+
return res;
|
|
4794
|
+
}
|
|
4179
4795
|
if (url.pathname === "/play" || url.pathname === "/play/") {
|
|
4180
4796
|
return new Response(self._playerHTML(), {
|
|
4181
4797
|
headers: { "Content-Type": "text/html" }
|
|
@@ -4187,7 +4803,16 @@ class QuizvServer {
|
|
|
4187
4803
|
},
|
|
4188
4804
|
websocket: {
|
|
4189
4805
|
open(ws) {
|
|
4190
|
-
const
|
|
4806
|
+
const data = ws.data;
|
|
4807
|
+
if (isSolo(data)) {
|
|
4808
|
+
if (!self.solo)
|
|
4809
|
+
return;
|
|
4810
|
+
ws.subscribe(soloTopic(data.deckId));
|
|
4811
|
+
data.conn = soloConn(ws, data.deckId, data.key);
|
|
4812
|
+
self.solo.hub.open(data.conn);
|
|
4813
|
+
return;
|
|
4814
|
+
}
|
|
4815
|
+
const { role, playerId } = data;
|
|
4191
4816
|
ws.subscribe(`game:${self.joinCode}`);
|
|
4192
4817
|
if (role === "host") {
|
|
4193
4818
|
const localIP = getLocalIP();
|
|
@@ -4203,6 +4828,12 @@ class QuizvServer {
|
|
|
4203
4828
|
}
|
|
4204
4829
|
},
|
|
4205
4830
|
message(ws, raw) {
|
|
4831
|
+
const data = ws.data;
|
|
4832
|
+
if (isSolo(data)) {
|
|
4833
|
+
if (data.conn)
|
|
4834
|
+
self.solo?.hub.message(data.conn, String(raw));
|
|
4835
|
+
return;
|
|
4836
|
+
}
|
|
4206
4837
|
try {
|
|
4207
4838
|
const msg = JSON.parse(String(raw));
|
|
4208
4839
|
const { playerId } = ws.data;
|
|
@@ -4265,7 +4896,13 @@ class QuizvServer {
|
|
|
4265
4896
|
} catch {}
|
|
4266
4897
|
},
|
|
4267
4898
|
close(ws) {
|
|
4268
|
-
const
|
|
4899
|
+
const data = ws.data;
|
|
4900
|
+
if (isSolo(data)) {
|
|
4901
|
+
if (data.conn)
|
|
4902
|
+
self.solo?.hub.close(data.conn);
|
|
4903
|
+
return;
|
|
4904
|
+
}
|
|
4905
|
+
const { role, playerId } = data;
|
|
4269
4906
|
if (role === "host")
|
|
4270
4907
|
return;
|
|
4271
4908
|
if (!self.engine.state.players.has(playerId))
|
|
@@ -4286,11 +4923,12 @@ class QuizvServer {
|
|
|
4286
4923
|
}
|
|
4287
4924
|
}
|
|
4288
4925
|
});
|
|
4926
|
+
this.server = server;
|
|
4289
4927
|
this.transport.attachServer(server);
|
|
4290
4928
|
const localIP = getLocalIP();
|
|
4291
4929
|
const playerURL = `http://${localIP}:${this.port}/play`;
|
|
4292
4930
|
console.log(`
|
|
4293
|
-
|
|
4931
|
+
HashQuiz Dev Server
|
|
4294
4932
|
\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
4295
4933
|
Host: http://localhost:${this.port}
|
|
4296
4934
|
Players: ${playerURL}
|
|
@@ -4312,7 +4950,7 @@ class QuizvServer {
|
|
|
4312
4950
|
<html lang="en">
|
|
4313
4951
|
<head>
|
|
4314
4952
|
<meta charset="UTF-8">
|
|
4315
|
-
<title>
|
|
4953
|
+
<title>HashQuiz Host \u2014 ${this.joinCode}</title>
|
|
4316
4954
|
<style>
|
|
4317
4955
|
body { font-family: system-ui; background: #0a0a0f; color: #fff; padding: 2rem; }
|
|
4318
4956
|
button { background: #7c3aed; color: #fff; border: none; padding: 0.75rem 1.5rem;
|
|
@@ -4329,7 +4967,7 @@ class QuizvServer {
|
|
|
4329
4967
|
</style>
|
|
4330
4968
|
</head>
|
|
4331
4969
|
<body>
|
|
4332
|
-
<h1>
|
|
4970
|
+
<h1>HashQuiz Host Control</h1>
|
|
4333
4971
|
<p id="ws-status">Connecting...</p>
|
|
4334
4972
|
<div id="status">
|
|
4335
4973
|
<p>Join code: <strong>${this.joinCode}</strong></p>
|
|
@@ -4432,7 +5070,7 @@ class QuizvServer {
|
|
|
4432
5070
|
<head>
|
|
4433
5071
|
<meta charset="UTF-8">
|
|
4434
5072
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
4435
|
-
<title>
|
|
5073
|
+
<title>HashQuiz Player</title>
|
|
4436
5074
|
<style>
|
|
4437
5075
|
body { font-family: system-ui; background: #0a0a0f; color: #fff; padding: 1rem;
|
|
4438
5076
|
max-width: 480px; margin: 0 auto; }
|
|
@@ -4449,7 +5087,7 @@ class QuizvServer {
|
|
|
4449
5087
|
</head>
|
|
4450
5088
|
<body>
|
|
4451
5089
|
<div id="join-screen">
|
|
4452
|
-
<h1>Join
|
|
5090
|
+
<h1>Join HashQuiz</h1>
|
|
4453
5091
|
<input id="code" placeholder="Join code (e.g. ABC123)" style="text-transform:uppercase;letter-spacing:0.15em" />
|
|
4454
5092
|
<input id="pseudo" placeholder="Your name" />
|
|
4455
5093
|
<input id="email" type="email" placeholder="Email (optional)" />
|
|
@@ -4592,44 +5230,68 @@ class QuizvServer {
|
|
|
4592
5230
|
}
|
|
4593
5231
|
|
|
4594
5232
|
// packages/server/src/dev.ts
|
|
4595
|
-
import { existsSync as existsSync2, statSync, watch } from "fs";
|
|
4596
|
-
import { join, resolve as
|
|
5233
|
+
import { existsSync as existsSync2, statSync as statSync2, watch } from "fs";
|
|
5234
|
+
import { dirname as dirname2, join as join2, resolve as resolve4 } from "path";
|
|
4597
5235
|
import { spawn } from "child_process";
|
|
4598
5236
|
|
|
4599
5237
|
// packages/server/src/web-dist.ts
|
|
4600
5238
|
import { existsSync } from "fs";
|
|
4601
|
-
import { resolve } from "path";
|
|
5239
|
+
import { resolve as resolve2 } from "path";
|
|
4602
5240
|
function findWebDist() {
|
|
4603
5241
|
const here = import.meta.dirname;
|
|
4604
5242
|
const candidates = [
|
|
4605
|
-
|
|
4606
|
-
|
|
5243
|
+
resolve2(here, "../web"),
|
|
5244
|
+
resolve2(here, "../../../dist")
|
|
4607
5245
|
];
|
|
4608
|
-
return candidates.find((d) => existsSync(
|
|
5246
|
+
return candidates.find((d) => existsSync(resolve2(d, "host/index.html"))) ?? null;
|
|
4609
5247
|
}
|
|
4610
5248
|
function findMonorepoRoot() {
|
|
4611
|
-
const root =
|
|
4612
|
-
return existsSync(
|
|
5249
|
+
const root = resolve2(import.meta.dirname, "../../..");
|
|
5250
|
+
return existsSync(resolve2(root, "apps/host/vite.config.ts")) ? root : null;
|
|
5251
|
+
}
|
|
5252
|
+
|
|
5253
|
+
// packages/server/src/vite-plugin.ts
|
|
5254
|
+
import { resolve as resolve3 } from "path";
|
|
5255
|
+
function repoDecksDir(repoRoot) {
|
|
5256
|
+
return resolve3(repoRoot, process.env.HASHQUIZ_DECKS_DIR ?? "examples");
|
|
4613
5257
|
}
|
|
4614
5258
|
|
|
4615
5259
|
// packages/server/src/dev.ts
|
|
4616
|
-
function
|
|
4617
|
-
const
|
|
4618
|
-
|
|
5260
|
+
function resolveDevTarget(arg, opts) {
|
|
5261
|
+
const target = resolve4(arg);
|
|
5262
|
+
if (!existsSync2(target))
|
|
5263
|
+
throw new Error(`${arg} not found`);
|
|
5264
|
+
if (statSync2(target).isDirectory()) {
|
|
5265
|
+
const first = collectDecks(target)[0];
|
|
5266
|
+
if (!first)
|
|
5267
|
+
throw new Error(`no .hashquiz.md deck in ${arg}`);
|
|
5268
|
+
return { quizFile: join2(target, first.id), decksDir: target };
|
|
5269
|
+
}
|
|
5270
|
+
const decksDir = opts.decksFlag ? resolve4(opts.decksFlag) : opts.repoRoot ? repoDecksDir(opts.repoRoot) : dirname2(target);
|
|
5271
|
+
return { quizFile: target, decksDir };
|
|
5272
|
+
}
|
|
5273
|
+
function devCommand(arg, port, decksFlag) {
|
|
5274
|
+
const repo = findMonorepoRoot();
|
|
5275
|
+
const { quizFile: absPath, decksDir } = resolveDevTarget(arg, { decksFlag, repoRoot: repo });
|
|
5276
|
+
const server = new HashQuizServer({ quizFile: absPath, port, decksDir });
|
|
4619
5277
|
server.start();
|
|
5278
|
+
console.log(` Room deck: ${absPath}
|
|
5279
|
+
Decks: ${decksDir}
|
|
5280
|
+
`);
|
|
4620
5281
|
const children = [];
|
|
4621
|
-
const repo = findMonorepoRoot();
|
|
4622
5282
|
if (repo) {
|
|
4623
|
-
|
|
4624
|
-
|
|
5283
|
+
const env = { ...process.env, HASHQUIZ_DECKS_DIR: decksDir };
|
|
5284
|
+
for (const app of ["apps/host", "apps/player"]) {
|
|
5285
|
+
children.push(spawn("bun", ["run", "dev"], { cwd: resolve4(repo, app), stdio: "inherit", shell: false, env }));
|
|
5286
|
+
}
|
|
4625
5287
|
} else {
|
|
4626
5288
|
const web = findWebDist();
|
|
4627
5289
|
if (!web) {
|
|
4628
5290
|
console.error("Prebuilt web apps not found: reinstall the hashquiz package.");
|
|
4629
5291
|
process.exit(1);
|
|
4630
5292
|
}
|
|
4631
|
-
serveStatic(web, 3031, "/host/");
|
|
4632
|
-
serveStatic(web, 3032, "/");
|
|
5293
|
+
serveStatic(web, 3031, "/host/", decksDir);
|
|
5294
|
+
serveStatic(web, 3032, "/", decksDir);
|
|
4633
5295
|
console.log(` Host app: http://localhost:3031/host/
|
|
4634
5296
|
Player app: http://localhost:3032/
|
|
4635
5297
|
`);
|
|
@@ -4643,67 +5305,46 @@ function devCommand(quizFile, port) {
|
|
|
4643
5305
|
process.on("SIGTERM", stop);
|
|
4644
5306
|
watch(absPath, () => {
|
|
4645
5307
|
console.log(`
|
|
4646
|
-
\uD83D\uDCC4 ${
|
|
5308
|
+
\uD83D\uDCC4 ${absPath} changed. Restart server to reload.
|
|
4647
5309
|
`);
|
|
4648
5310
|
});
|
|
4649
5311
|
}
|
|
4650
|
-
function serveStatic(root, port, home) {
|
|
4651
|
-
const config = renderConfigScript({ transport: "local" });
|
|
5312
|
+
function serveStatic(root, port, home, decksDir) {
|
|
5313
|
+
const config = renderConfigScript({ transport: "local", soloScoring: "browser" });
|
|
4652
5314
|
Bun.serve({
|
|
4653
5315
|
port,
|
|
4654
5316
|
hostname: "0.0.0.0",
|
|
4655
5317
|
fetch(req) {
|
|
4656
5318
|
const { pathname } = new URL(req.url);
|
|
4657
|
-
if (pathname === "/
|
|
5319
|
+
if (pathname === "/hashquiz-config.js") {
|
|
4658
5320
|
return new Response(config, { headers: { "Content-Type": "text/javascript" } });
|
|
4659
5321
|
}
|
|
5322
|
+
if (pathname === "/decks.json" || pathname === "/host/decks.json") {
|
|
5323
|
+
return new Response(renderDecksJson(decksDir), { headers: { "Content-Type": "application/json" } });
|
|
5324
|
+
}
|
|
4660
5325
|
if (pathname === "/" && home !== "/")
|
|
4661
5326
|
return Response.redirect(home, 302);
|
|
4662
|
-
const file =
|
|
5327
|
+
const file = resolve4(join2(root, decodeURIComponent(pathname)));
|
|
4663
5328
|
if (!file.startsWith(root))
|
|
4664
5329
|
return new Response("Not found", { status: 404 });
|
|
4665
|
-
if (existsSync2(file) &&
|
|
5330
|
+
if (existsSync2(file) && statSync2(file).isFile())
|
|
4666
5331
|
return new Response(Bun.file(file));
|
|
4667
|
-
const index = pathname.startsWith("/host") ?
|
|
5332
|
+
const index = pathname.startsWith("/host") ? join2(root, "host/index.html") : join2(root, "index.html");
|
|
4668
5333
|
return new Response(Bun.file(index));
|
|
4669
5334
|
}
|
|
4670
5335
|
});
|
|
4671
5336
|
}
|
|
4672
5337
|
|
|
4673
5338
|
// packages/server/src/build.ts
|
|
4674
|
-
import { cpSync, existsSync as existsSync3, mkdirSync, rmSync, writeFileSync } from "fs";
|
|
4675
|
-
import { resolve as
|
|
4676
|
-
|
|
4677
|
-
// packages/server/src/web-assets.ts
|
|
4678
|
-
import { readdirSync, readFileSync as readFileSync2, statSync as statSync2 } from "fs";
|
|
4679
|
-
import { join as join2, relative, sep } from "path";
|
|
4680
|
-
var SKIP = new Set(["node_modules", "dist", ".git"]);
|
|
4681
|
-
function collectDecks(dir) {
|
|
4682
|
-
const out = [];
|
|
4683
|
-
const walk = (d) => {
|
|
4684
|
-
for (const name of readdirSync(d)) {
|
|
4685
|
-
if (SKIP.has(name) || name.startsWith("."))
|
|
4686
|
-
continue;
|
|
4687
|
-
const p = join2(d, name);
|
|
4688
|
-
if (statSync2(p).isDirectory())
|
|
4689
|
-
walk(p);
|
|
4690
|
-
else if (name.endsWith(".quizv.md")) {
|
|
4691
|
-
out.push({ id: relative(dir, p).split(sep).join("/"), content: readFileSync2(p, "utf-8") });
|
|
4692
|
-
}
|
|
4693
|
-
}
|
|
4694
|
-
};
|
|
4695
|
-
walk(dir);
|
|
4696
|
-
return out.sort((a, b) => a.id.localeCompare(b.id));
|
|
4697
|
-
}
|
|
4698
|
-
|
|
4699
|
-
// packages/server/src/build.ts
|
|
5339
|
+
import { cpSync, existsSync as existsSync3, mkdirSync as mkdirSync2, rmSync, writeFileSync } from "fs";
|
|
5340
|
+
import { resolve as resolve5 } from "path";
|
|
4700
5341
|
function buildSite({ decksDir, outDir, env = process.env }) {
|
|
4701
|
-
const decksAbs =
|
|
5342
|
+
const decksAbs = resolve5(decksDir);
|
|
4702
5343
|
if (!existsSync3(decksAbs))
|
|
4703
5344
|
throw new Error(`Decks folder not found: ${decksDir}`);
|
|
4704
5345
|
const decks = collectDecks(decksAbs);
|
|
4705
5346
|
if (decks.length === 0)
|
|
4706
|
-
throw new Error(`No .
|
|
5347
|
+
throw new Error(`No .hashquiz.md file found in ${decksDir}`);
|
|
4707
5348
|
const problems = [];
|
|
4708
5349
|
for (const { id, content } of decks) {
|
|
4709
5350
|
try {
|
|
@@ -4722,36 +5363,227 @@ function buildSite({ decksDir, outDir, env = process.env }) {
|
|
|
4722
5363
|
`)}`);
|
|
4723
5364
|
const web = findWebDist();
|
|
4724
5365
|
if (!web)
|
|
4725
|
-
throw new Error("Prebuilt web apps not found (in the
|
|
4726
|
-
const out =
|
|
5366
|
+
throw new Error("Prebuilt web apps not found (in the hashquiz repo, run `bun run build:web` first)");
|
|
5367
|
+
const out = resolve5(outDir);
|
|
4727
5368
|
if (out === decksAbs)
|
|
4728
5369
|
throw new Error("--out must differ from the decks folder");
|
|
4729
5370
|
rmSync(out, { recursive: true, force: true });
|
|
4730
|
-
|
|
5371
|
+
mkdirSync2(out, { recursive: true });
|
|
4731
5372
|
cpSync(web, out, { recursive: true });
|
|
4732
|
-
|
|
4733
|
-
writeFileSync(
|
|
5373
|
+
const manifest = JSON.stringify(decks);
|
|
5374
|
+
writeFileSync(resolve5(out, "host/decks.json"), manifest);
|
|
5375
|
+
writeFileSync(resolve5(out, "decks.json"), manifest);
|
|
5376
|
+
writeFileSync(resolve5(out, "hashquiz-config.js"), renderConfigScript(configFromEnv(env)));
|
|
4734
5377
|
return decks.length;
|
|
4735
5378
|
}
|
|
4736
5379
|
|
|
5380
|
+
// packages/backend-supabase/src/cli/edge-bundle.ts
|
|
5381
|
+
import { existsSync as existsSync4 } from "fs";
|
|
5382
|
+
import { mkdir } from "fs/promises";
|
|
5383
|
+
import { dirname as dirname3, join as join3 } from "path";
|
|
5384
|
+
var EDGE_CORE_FILE = "functions/_shared/solo-core.js";
|
|
5385
|
+
var EDGE_CORE_BANNER = `import { Buffer } from "node:buffer";
|
|
5386
|
+
`;
|
|
5387
|
+
function edgeCoreEntry() {
|
|
5388
|
+
const entry = join3(import.meta.dir, "../edge/solo-core.ts");
|
|
5389
|
+
return existsSync4(entry) ? entry : null;
|
|
5390
|
+
}
|
|
5391
|
+
async function bundleEdgeCore(outFile) {
|
|
5392
|
+
const entry = edgeCoreEntry();
|
|
5393
|
+
if (!entry)
|
|
5394
|
+
throw new Error("edge bundle: solo-core.ts entry not found (sources required)");
|
|
5395
|
+
const result = await Bun.build({ entrypoints: [entry], target: "browser", format: "esm" });
|
|
5396
|
+
if (!result.success) {
|
|
5397
|
+
throw new Error(`edge bundle failed:
|
|
5398
|
+
${result.logs.map((l) => String(l)).join(`
|
|
5399
|
+
`)}`);
|
|
5400
|
+
}
|
|
5401
|
+
await mkdir(dirname3(outFile), { recursive: true });
|
|
5402
|
+
await Bun.write(outFile, EDGE_CORE_BANNER + stripModulePathComments(await result.outputs[0].text()));
|
|
5403
|
+
}
|
|
5404
|
+
function stripModulePathComments(code) {
|
|
5405
|
+
return code.replace(/^\/\/ [^\n]*\.(?:[cm]?[jt]sx?|json)\n/gm, "");
|
|
5406
|
+
}
|
|
5407
|
+
if (false) {}
|
|
5408
|
+
// packages/backend-supabase/src/cli/deploy.ts
|
|
5409
|
+
import { existsSync as existsSync5, statSync as statSync3 } from "fs";
|
|
5410
|
+
import { cp, mkdtemp, rm } from "fs/promises";
|
|
5411
|
+
import { tmpdir } from "os";
|
|
5412
|
+
import { basename, join as join4, resolve as resolve6 } from "path";
|
|
5413
|
+
var USAGE = "Usage: hashquiz supabase deploy --project <ref> [--site-url <url>] [--dry-run]";
|
|
5414
|
+
var SECRET_ENV = ["SUPABASE_ACCESS_TOKEN", "SUPABASE_DB_PASSWORD"];
|
|
5415
|
+
function supabaseDeploySteps(o) {
|
|
5416
|
+
const bin = o.supabaseBin ?? "supabase";
|
|
5417
|
+
const wd = ["--workdir", o.workdir];
|
|
5418
|
+
const remote = `--remote=${o.projectRef}`;
|
|
5419
|
+
return [
|
|
5420
|
+
{ label: "link project", argv: [bin, "link", "--project-ref", o.projectRef, ...wd] },
|
|
5421
|
+
{ label: "push migrations", argv: [bin, "db", "push", remote, ...wd, "--yes"] },
|
|
5422
|
+
{ label: "deploy solo-submit", argv: [bin, "functions", "deploy", "solo-submit", remote, ...wd] },
|
|
5423
|
+
{ label: "set HASHQUIZ_SITE_URL", argv: [bin, "secrets", "set", `HASHQUIZ_SITE_URL=${o.siteUrl}`, remote, ...wd] }
|
|
5424
|
+
];
|
|
5425
|
+
}
|
|
5426
|
+
function isProject(dir) {
|
|
5427
|
+
return existsSync5(join4(dir, "config.toml"));
|
|
5428
|
+
}
|
|
5429
|
+
function findSupabaseDir() {
|
|
5430
|
+
const here = import.meta.dirname;
|
|
5431
|
+
const candidates = [
|
|
5432
|
+
resolve6(here, "../supabase"),
|
|
5433
|
+
resolve6(here, "../../supabase")
|
|
5434
|
+
];
|
|
5435
|
+
return candidates.find(isProject) ?? null;
|
|
5436
|
+
}
|
|
5437
|
+
async function copySupabaseProject(src, destSupabaseDir, edgeCore) {
|
|
5438
|
+
const coreFile = resolve6(src, EDGE_CORE_FILE);
|
|
5439
|
+
if (edgeCore === "copy" && !existsSync5(coreFile)) {
|
|
5440
|
+
throw new Error(`supabase: ${EDGE_CORE_FILE} missing in ${src} (run \`bun run build:edge\`)`);
|
|
5441
|
+
}
|
|
5442
|
+
await cp(join4(src, "config.toml"), join4(destSupabaseDir, "config.toml"));
|
|
5443
|
+
for (const dir of ["migrations", "functions"]) {
|
|
5444
|
+
if (!existsSync5(join4(src, dir)))
|
|
5445
|
+
continue;
|
|
5446
|
+
await cp(join4(src, dir), join4(destSupabaseDir, dir), {
|
|
5447
|
+
recursive: true,
|
|
5448
|
+
filter: (p) => {
|
|
5449
|
+
if (basename(p).startsWith(".env") && !statSync3(p).isDirectory())
|
|
5450
|
+
return false;
|
|
5451
|
+
return edgeCore === "copy" || resolve6(p) !== coreFile;
|
|
5452
|
+
}
|
|
5453
|
+
});
|
|
5454
|
+
}
|
|
5455
|
+
if (edgeCore === "build")
|
|
5456
|
+
await bundleEdgeCore(join4(destSupabaseDir, EDGE_CORE_FILE));
|
|
5457
|
+
}
|
|
5458
|
+
function normalizeSiteUrl(raw) {
|
|
5459
|
+
let url;
|
|
5460
|
+
try {
|
|
5461
|
+
url = new URL(raw);
|
|
5462
|
+
} catch {
|
|
5463
|
+
return null;
|
|
5464
|
+
}
|
|
5465
|
+
if (url.protocol !== "http:" && url.protocol !== "https:")
|
|
5466
|
+
return null;
|
|
5467
|
+
return raw.replace(/\/+$/, "");
|
|
5468
|
+
}
|
|
5469
|
+
var defaultRunner = async (argv, env) => {
|
|
5470
|
+
try {
|
|
5471
|
+
const proc = Bun.spawn(argv, { env, stdio: ["inherit", "inherit", "inherit"] });
|
|
5472
|
+
return await proc.exited;
|
|
5473
|
+
} catch {
|
|
5474
|
+
return 127;
|
|
5475
|
+
}
|
|
5476
|
+
};
|
|
5477
|
+
function masker(env) {
|
|
5478
|
+
const secrets = SECRET_ENV.map((k) => env[k]).filter((v) => !!v && v.length >= 8);
|
|
5479
|
+
return (line) => secrets.reduce((l, s) => l.split(s).join("***"), line);
|
|
5480
|
+
}
|
|
5481
|
+
async function supabaseDeploy(args, env, run, log) {
|
|
5482
|
+
const mask = masker(env);
|
|
5483
|
+
const say = (line) => log(mask(line));
|
|
5484
|
+
const value = (name) => {
|
|
5485
|
+
const i = args.indexOf(name);
|
|
5486
|
+
const v = i !== -1 ? args[i + 1] : undefined;
|
|
5487
|
+
return v && !v.startsWith("--") ? v : undefined;
|
|
5488
|
+
};
|
|
5489
|
+
const projectRef = value("--project");
|
|
5490
|
+
if (!projectRef) {
|
|
5491
|
+
say(`\u2717 supabase deploy: --project <ref> is required
|
|
5492
|
+
${USAGE}`);
|
|
5493
|
+
return 1;
|
|
5494
|
+
}
|
|
5495
|
+
const rawSiteUrl = value("--site-url") ?? env.HASHQUIZ_SITE_URL;
|
|
5496
|
+
if (!rawSiteUrl) {
|
|
5497
|
+
say(`\u2717 supabase deploy: --site-url <url> or HASHQUIZ_SITE_URL is required (the site serving decks.json)
|
|
5498
|
+
${USAGE}`);
|
|
5499
|
+
return 1;
|
|
5500
|
+
}
|
|
5501
|
+
const siteUrl = normalizeSiteUrl(rawSiteUrl);
|
|
5502
|
+
if (!siteUrl) {
|
|
5503
|
+
say("\u2717 supabase deploy: the site url must be an http(s) URL, e.g. https://quiz.example.com");
|
|
5504
|
+
return 1;
|
|
5505
|
+
}
|
|
5506
|
+
const missing = SECRET_ENV.filter((k) => !env[k]);
|
|
5507
|
+
if (missing.length) {
|
|
5508
|
+
say(`\u2717 supabase deploy: set ${missing.join(" and ")} in the environment`);
|
|
5509
|
+
return 1;
|
|
5510
|
+
}
|
|
5511
|
+
const supabaseBin = env.SUPABASE_BIN || "supabase";
|
|
5512
|
+
if (args.includes("--dry-run")) {
|
|
5513
|
+
const steps = supabaseDeploySteps({ projectRef, siteUrl, workdir: "<workdir>", supabaseBin });
|
|
5514
|
+
say(`supabase deploy (dry run): ${SECRET_ENV.map((k) => `${k}=***`).join(" ")}`);
|
|
5515
|
+
steps.forEach((s, i) => say(` ${i + 1}. ${s.label}: ${s.argv.join(" ")}`));
|
|
5516
|
+
return 0;
|
|
5517
|
+
}
|
|
5518
|
+
const src = findSupabaseDir();
|
|
5519
|
+
if (!src) {
|
|
5520
|
+
say("\u2717 supabase deploy: the Supabase project (supabase/config.toml) was not found");
|
|
5521
|
+
return 1;
|
|
5522
|
+
}
|
|
5523
|
+
const tmp = await mkdtemp(join4(tmpdir(), "hashquiz-supabase-"));
|
|
5524
|
+
try {
|
|
5525
|
+
try {
|
|
5526
|
+
await copySupabaseProject(src, join4(tmp, "supabase"), edgeCoreEntry() ? "build" : "copy");
|
|
5527
|
+
} catch (e) {
|
|
5528
|
+
say(`\u2717 supabase deploy: ${e instanceof Error ? e.message : String(e)}`);
|
|
5529
|
+
return 1;
|
|
5530
|
+
}
|
|
5531
|
+
const steps = supabaseDeploySteps({ projectRef, siteUrl, workdir: tmp, supabaseBin });
|
|
5532
|
+
for (const [i, step] of steps.entries()) {
|
|
5533
|
+
say(`\u2192 ${i + 1}/${steps.length} ${step.label}`);
|
|
5534
|
+
const code = await run(step.argv, env);
|
|
5535
|
+
if (code !== 0) {
|
|
5536
|
+
say(`\u2717 supabase deploy: ${step.label} failed (exit ${code}): ${step.argv.join(" ")}`);
|
|
5537
|
+
return 1;
|
|
5538
|
+
}
|
|
5539
|
+
}
|
|
5540
|
+
say(`\u2713 Deployed solo-submit to ${projectRef}; it reads ${siteUrl}/decks.json`);
|
|
5541
|
+
return 0;
|
|
5542
|
+
} finally {
|
|
5543
|
+
await rm(tmp, { recursive: true, force: true });
|
|
5544
|
+
}
|
|
5545
|
+
}
|
|
5546
|
+
async function supabaseCommand(args, env, run = defaultRunner, log = console.log) {
|
|
5547
|
+
const [sub, ...rest] = args;
|
|
5548
|
+
if (sub === "deploy")
|
|
5549
|
+
return supabaseDeploy(rest, env, run, log);
|
|
5550
|
+
log(`${sub ? `Unknown supabase command: ${sub}
|
|
5551
|
+
` : ""}${USAGE}`);
|
|
5552
|
+
return 1;
|
|
5553
|
+
}
|
|
4737
5554
|
// packages/server/src/cli.ts
|
|
4738
5555
|
import { readFileSync as readFileSync3 } from "fs";
|
|
4739
|
-
import { resolve as
|
|
5556
|
+
import { resolve as resolve7 } from "path";
|
|
4740
5557
|
var [, , command, arg, ...flags] = process.argv;
|
|
4741
5558
|
function printUsage() {
|
|
4742
5559
|
console.log(`
|
|
4743
|
-
hashquiz <command> [options] (
|
|
5560
|
+
hashquiz <command> [options] (hashquiz from the sources)
|
|
4744
5561
|
|
|
4745
5562
|
Commands:
|
|
4746
|
-
dev <quiz.
|
|
4747
|
-
|
|
5563
|
+
dev <quiz.hashquiz.md | decks-dir> [--decks <dir>]
|
|
5564
|
+
Start the local dev stack. A file is the room
|
|
5565
|
+
deck; a folder is the decks folder (room deck =
|
|
5566
|
+
its first deck by id). Solo runs are stored in
|
|
5567
|
+
.hashquiz/solo.db.
|
|
5568
|
+
check <quiz.hashquiz.md> Validate quiz file format
|
|
4748
5569
|
build [decks-dir] Build the static site (host + player) for a decks
|
|
4749
5570
|
folder (default: decks). Reads HASHQUIZ_TRANSPORT,
|
|
4750
|
-
HASHQUIZ_SUPABASE_URL, HASHQUIZ_SUPABASE_ANON_KEY
|
|
4751
|
-
|
|
5571
|
+
HASHQUIZ_SUPABASE_URL, HASHQUIZ_SUPABASE_ANON_KEY,
|
|
5572
|
+
HASHQUIZ_SOLO_SCORING, HASHQUIZ_PLAYER_URL
|
|
5573
|
+
(or their VITE_* names) from the environment.
|
|
5574
|
+
supabase deploy --project <ref> [--site-url <url>] [--dry-run]
|
|
5575
|
+
Deploy the solo backend to a Supabase project:
|
|
5576
|
+
migrations, the solo-submit Edge Function and its
|
|
5577
|
+
HASHQUIZ_SITE_URL secret (the site serving
|
|
5578
|
+
decks.json; flag or env). Needs the Supabase CLI
|
|
5579
|
+
(or SUPABASE_BIN), SUPABASE_ACCESS_TOKEN and
|
|
5580
|
+
SUPABASE_DB_PASSWORD.
|
|
4752
5581
|
|
|
4753
5582
|
Options:
|
|
4754
5583
|
--port <number> Port to listen on (default: 3030)
|
|
5584
|
+
--decks <dir> Decks folder for dev with a file (default: the
|
|
5585
|
+
repo's examples/ from the sources, else the
|
|
5586
|
+
file's folder)
|
|
4755
5587
|
--out <dir> Output folder for build (default: dist)
|
|
4756
5588
|
`);
|
|
4757
5589
|
}
|
|
@@ -4767,12 +5599,17 @@ function flag(name) {
|
|
|
4767
5599
|
var port = parseInt(flag("--port") ?? "3030");
|
|
4768
5600
|
var positional = args.find((a, i) => !a.startsWith("--") && !(i > 0 && args[i - 1].startsWith("--")));
|
|
4769
5601
|
if (command === "dev") {
|
|
4770
|
-
if (!
|
|
4771
|
-
console.error(`Error: provide a .
|
|
4772
|
-
|
|
5602
|
+
if (!positional) {
|
|
5603
|
+
console.error(`Error: provide a .hashquiz.md file or a decks folder
|
|
5604
|
+
hashquiz dev quiz.hashquiz.md`);
|
|
5605
|
+
process.exit(1);
|
|
5606
|
+
}
|
|
5607
|
+
try {
|
|
5608
|
+
devCommand(positional, port, flag("--decks"));
|
|
5609
|
+
} catch (e) {
|
|
5610
|
+
console.error(`\u2717 ${e instanceof Error ? e.message : String(e)}`);
|
|
4773
5611
|
process.exit(1);
|
|
4774
5612
|
}
|
|
4775
|
-
devCommand(arg, port);
|
|
4776
5613
|
} else if (command === "build") {
|
|
4777
5614
|
const decksDir = positional ?? "decks";
|
|
4778
5615
|
const outDir = flag("--out") ?? "dist";
|
|
@@ -4783,14 +5620,16 @@ if (command === "dev") {
|
|
|
4783
5620
|
console.error(`\u2717 ${e instanceof Error ? e.message : String(e)}`);
|
|
4784
5621
|
process.exit(1);
|
|
4785
5622
|
}
|
|
5623
|
+
} else if (command === "supabase") {
|
|
5624
|
+
process.exit(await supabaseCommand(args, process.env));
|
|
4786
5625
|
} else if (command === "check") {
|
|
4787
5626
|
if (!arg) {
|
|
4788
|
-
console.error(`Error: provide a .
|
|
4789
|
-
|
|
5627
|
+
console.error(`Error: provide a .hashquiz.md file path
|
|
5628
|
+
hashquiz check quiz.hashquiz.md`);
|
|
4790
5629
|
process.exit(1);
|
|
4791
5630
|
}
|
|
4792
5631
|
try {
|
|
4793
|
-
const content = readFileSync3(
|
|
5632
|
+
const content = readFileSync3(resolve7(arg), "utf-8");
|
|
4794
5633
|
const quiz = parseQuizFile(content);
|
|
4795
5634
|
const result = validateQuiz(quiz);
|
|
4796
5635
|
if (result.valid) {
|