Compare commits
43
Commits
9268514219
...
main
No files matched your search
@@ -59,3 +59,9 @@ data/episode-plays.json
|
|||||||
# Episode workflow progress — lives only in the server data volume
|
# Episode workflow progress — lives only in the server data volume
|
||||||
data/podcast-workflow.json
|
data/podcast-workflow.json
|
||||||
data/nuggets-workflow.json
|
data/nuggets-workflow.json
|
||||||
|
|
||||||
|
# Live download counters — server data volume only
|
||||||
|
data/download-counts.json
|
||||||
|
|
||||||
|
# Generated audio (upload via Admin → Asset Manager, do not commit)
|
||||||
|
audio-out/
|
||||||
@@ -42,7 +42,7 @@
|
|||||||
"seriesImageUrl": "/images/titus-cover.png",
|
"seriesImageUrl": "/images/titus-cover.png",
|
||||||
"seriesListenUrl": "/spotify",
|
"seriesListenUrl": "/spotify",
|
||||||
"seriesListenBtnLabel": "Listen to Series",
|
"seriesListenBtnLabel": "Listen to Series",
|
||||||
"seriesDownloadsBtnLabel": "View Downloads",
|
"seriesDownloadsBtnLabel": "View Resources",
|
||||||
"studyGuideTitle": "Companion Study Guide",
|
"studyGuideTitle": "Companion Study Guide",
|
||||||
"studyGuideDescription": "Go deeper in your study with the official Verse by Verse companion guide — now available on Amazon.",
|
"studyGuideDescription": "Go deeper in your study with the official Verse by Verse companion guide — now available on Amazon.",
|
||||||
"studyGuideDownloadUrl": "",
|
"studyGuideDownloadUrl": "",
|
||||||
@@ -1007,7 +1007,7 @@
|
|||||||
],
|
],
|
||||||
"shareHeading": "Help one more person hear the Word this week.",
|
"shareHeading": "Help one more person hear the Word this week.",
|
||||||
"shareP": "Scan the QR code or text the show link to a friend who needs encouragement today.",
|
"shareP": "Scan the QR code or text the show link to a friend who needs encouragement today.",
|
||||||
"prismVideoUrl": "/images/PRISM.mp4",
|
"prismVideoUrl": "https://files.versebyversewithnate.us/images/PRISM.mp4",
|
||||||
"prismEyebrow": "Featured Video",
|
"prismEyebrow": "Featured Video",
|
||||||
"prismHeading": "PRISM",
|
"prismHeading": "PRISM",
|
||||||
"prismIntro": "What if every time you opened your Bible, you had a clear, repeatable method to actually dig in?",
|
"prismIntro": "What if every time you opened your Bible, you had a clear, repeatable method to actually dig in?",
|
||||||
@@ -1030,7 +1030,7 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "downloads",
|
"id": "downloads",
|
||||||
"title": "Downloads",
|
"title": "Resources",
|
||||||
"description": "Main guide, extra downloads, and past study files.",
|
"description": "Main guide, extra downloads, and past study files.",
|
||||||
"path": "/resources"
|
"path": "/resources"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -43,7 +43,7 @@
|
|||||||
"seriesImageUrl": "/images/titus-cover.png",
|
"seriesImageUrl": "/images/titus-cover.png",
|
||||||
"seriesListenUrl": "/spotify",
|
"seriesListenUrl": "/spotify",
|
||||||
"seriesListenBtnLabel": "Listen to Series",
|
"seriesListenBtnLabel": "Listen to Series",
|
||||||
"seriesDownloadsBtnLabel": "View Downloads",
|
"seriesDownloadsBtnLabel": "View Resources",
|
||||||
"studyGuideTitle": "Companion Study Guide",
|
"studyGuideTitle": "Companion Study Guide",
|
||||||
"studyGuideDescription": "Go deeper in your study with the official Verse by Verse companion guide — now available on Amazon.",
|
"studyGuideDescription": "Go deeper in your study with the official Verse by Verse companion guide — now available on Amazon.",
|
||||||
"studyGuideDownloadUrl": "",
|
"studyGuideDownloadUrl": "",
|
||||||
@@ -1061,7 +1061,7 @@
|
|||||||
"shareHeading": "Help one more person hear the Word this week.",
|
"shareHeading": "Help one more person hear the Word this week.",
|
||||||
"shareP": "Scan the QR code or text the show link to a friend who needs encouragement today.",
|
"shareP": "Scan the QR code or text the show link to a friend who needs encouragement today.",
|
||||||
"shareQrImageUrl": "/images/qr-code.jpg",
|
"shareQrImageUrl": "/images/qr-code.jpg",
|
||||||
"prismVideoUrl": "/images/PRISM.mp4",
|
"prismVideoUrl": "https://files.versebyversewithnate.us/images/PRISM.mp4",
|
||||||
"prismEyebrow": "Featured Video",
|
"prismEyebrow": "Featured Video",
|
||||||
"prismHeading": "PRISM",
|
"prismHeading": "PRISM",
|
||||||
"prismIntro": "What if every time you opened your Bible, you had a clear, repeatable method to actually dig in?",
|
"prismIntro": "What if every time you opened your Bible, you had a clear, repeatable method to actually dig in?",
|
||||||
@@ -1084,7 +1084,7 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "downloads",
|
"id": "downloads",
|
||||||
"title": "Downloads",
|
"title": "Resources",
|
||||||
"description": "Main guide, extra downloads, and past study files.",
|
"description": "Main guide, extra downloads, and past study files.",
|
||||||
"path": "/resources"
|
"path": "/resources"
|
||||||
},
|
},
|
||||||
|
|||||||
Generated
+1258
-1125
File diff suppressed because it is too large.
Load diff
+2
-2
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "siteforge",
|
"name": "siteforge",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "2.25.2",
|
"version": "2.46.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
@@ -38,7 +38,7 @@
|
|||||||
"react-dom": "^19.2.4",
|
"react-dom": "^19.2.4",
|
||||||
"react-markdown": "^10.1.0",
|
"react-markdown": "^10.1.0",
|
||||||
"react-router-dom": "^7.13.1",
|
"react-router-dom": "^7.13.1",
|
||||||
"react-simple-maps": "^3.0.0",
|
"react-simple-maps": "^5.0.5",
|
||||||
"remark-gfm": "^4.0.1",
|
"remark-gfm": "^4.0.1",
|
||||||
"resend": "^6.10.0",
|
"resend": "^6.10.0",
|
||||||
"tar": "^7.5.19"
|
"tar": "^7.5.19"
|
||||||
|
|||||||
Binary file not shown.
+965
-16
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,148 @@
|
|||||||
|
// Generates the /salvation audio from the narration files in scripts/salvation/ using ElevenLabs.
|
||||||
|
// There are three tracks: the case, then the listener chooses Guilty or Not guilty.
|
||||||
|
//
|
||||||
|
// node --env-file=.env scripts/generate-salvation-audio.mjs --list-voices # find your voice id
|
||||||
|
// node --env-file=.env scripts/generate-salvation-audio.mjs --sample # ~40 seconds, to test the voice (cheap)
|
||||||
|
// node --env-file=.env scripts/generate-salvation-audio.mjs # generate all three MP3s
|
||||||
|
// node --env-file=.env scripts/generate-salvation-audio.mjs --only=guilty # just one: case | guilty | not-guilty
|
||||||
|
//
|
||||||
|
// Needs, in your local .env (never commit it):
|
||||||
|
// ELEVENLABS_API_KEY=...
|
||||||
|
// ELEVENLABS_VOICE_ID=... (from --list-voices, or your cloned voice)
|
||||||
|
// Optional:
|
||||||
|
// ELEVENLABS_MODEL=eleven_multilingual_v2
|
||||||
|
// ELEVENLABS_STABILITY=0.5 (lower = more expressive, higher = steadier)
|
||||||
|
// ELEVENLABS_SPEED=1
|
||||||
|
//
|
||||||
|
// Output goes to audio-out/ (git-ignored). Upload the MP3s in Admin → Asset Manager, then paste their
|
||||||
|
// URLs into Admin → Gospel Page.
|
||||||
|
import { readFile, writeFile, mkdir } from 'node:fs/promises'
|
||||||
|
import path from 'node:path'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
|
||||||
|
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
||||||
|
const API = 'https://api.elevenlabs.io/v1'
|
||||||
|
const apiKey = process.env.ELEVENLABS_API_KEY
|
||||||
|
const voiceId = process.env.ELEVENLABS_VOICE_ID
|
||||||
|
const model = process.env.ELEVENLABS_MODEL || 'eleven_multilingual_v2'
|
||||||
|
const MAX_CHARS = 4500
|
||||||
|
let totalCost = 0
|
||||||
|
|
||||||
|
function fail(message) {
|
||||||
|
console.error(`\n${message}\n`)
|
||||||
|
process.exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!apiKey) fail('ELEVENLABS_API_KEY is not set. Add it to your local .env file (not to chat or to git).')
|
||||||
|
|
||||||
|
async function listVoices() {
|
||||||
|
const res = await fetch(`${API}/voices`, { headers: { 'xi-api-key': apiKey } })
|
||||||
|
if (!res.ok) fail(`Could not list voices (${res.status}). Check the API key.`)
|
||||||
|
const { voices = [] } = await res.json()
|
||||||
|
console.log('\nYour voices (name: voice id)\n')
|
||||||
|
for (const v of voices) console.log(` ${v.name}${v.category ? ` [${v.category}]` : ''}: ${v.voice_id}`)
|
||||||
|
console.log('\nPut the one you want in .env as ELEVENLABS_VOICE_ID=...\n')
|
||||||
|
}
|
||||||
|
|
||||||
|
// Split on paragraph boundaries so each request stays under MAX_CHARS and never cuts a sentence.
|
||||||
|
function chunkText(text) {
|
||||||
|
const paragraphs = text.split(/\n{2,}/).map(p => p.trim()).filter(Boolean)
|
||||||
|
const chunks = []
|
||||||
|
let current = ''
|
||||||
|
for (const p of paragraphs) {
|
||||||
|
if (current && current.length + p.length + 2 > MAX_CHARS) { chunks.push(current); current = '' }
|
||||||
|
current = current ? `${current}\n\n${p}` : p
|
||||||
|
}
|
||||||
|
if (current) chunks.push(current)
|
||||||
|
return chunks
|
||||||
|
}
|
||||||
|
|
||||||
|
async function speak(text, previous, next) {
|
||||||
|
const res = await fetch(`${API}/text-to-speech/${voiceId}?output_format=mp3_44100_128`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'xi-api-key': apiKey, 'Content-Type': 'application/json', Accept: 'audio/mpeg' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
text,
|
||||||
|
model_id: model,
|
||||||
|
voice_settings: {
|
||||||
|
stability: Number(process.env.ELEVENLABS_STABILITY ?? 0.5),
|
||||||
|
similarity_boost: 0.75,
|
||||||
|
style: 0,
|
||||||
|
use_speaker_boost: true,
|
||||||
|
speed: Number(process.env.ELEVENLABS_SPEED ?? 1),
|
||||||
|
},
|
||||||
|
...(previous ? { previous_text: previous.slice(-600) } : {}),
|
||||||
|
...(next ? { next_text: next.slice(0, 600) } : {}),
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
if (!res.ok) {
|
||||||
|
const detail = await res.text().catch(() => '')
|
||||||
|
fail(`ElevenLabs returned ${res.status}.\n${detail.slice(0, 400)}`)
|
||||||
|
}
|
||||||
|
const cost = res.headers.get('character-cost')
|
||||||
|
if (cost) totalCost += Number(cost) || 0
|
||||||
|
return Buffer.from(await res.arrayBuffer())
|
||||||
|
}
|
||||||
|
|
||||||
|
const TRACKS = [
|
||||||
|
{ id: 'case', file: 'narration-1-case.txt', out: 'salvation-case.mp3' },
|
||||||
|
{ id: 'guilty', file: 'narration-2-guilty.txt', out: 'salvation-guilty.mp3' },
|
||||||
|
{ id: 'not-guilty', file: 'narration-3-not-guilty.txt', out: 'salvation-not-guilty.mp3' },
|
||||||
|
]
|
||||||
|
|
||||||
|
async function renderTrack(text, outPath) {
|
||||||
|
const chunks = chunkText(text)
|
||||||
|
const parts = []
|
||||||
|
for (let i = 0; i < chunks.length; i += 1) {
|
||||||
|
process.stdout.write(` part ${i + 1}/${chunks.length}… `)
|
||||||
|
parts.push(await speak(chunks[i], chunks[i - 1], chunks[i + 1]))
|
||||||
|
console.log('done')
|
||||||
|
}
|
||||||
|
await writeFile(outPath, Buffer.concat(parts))
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
if (process.argv.includes('--list-voices')) { await listVoices(); return }
|
||||||
|
if (!voiceId) fail('ELEVENLABS_VOICE_ID is not set. Run with --list-voices to find it, then add it to .env.')
|
||||||
|
|
||||||
|
const outDir = path.join(ROOT, 'audio-out')
|
||||||
|
await mkdir(outDir, { recursive: true })
|
||||||
|
|
||||||
|
if (process.argv.includes('--sample')) {
|
||||||
|
const full = (await readFile(path.join(ROOT, 'scripts/salvation', TRACKS[0].file), 'utf8')).trim()
|
||||||
|
// Whole paragraphs only, so the sample never stops mid-sentence (about 700 characters).
|
||||||
|
let sample = ''
|
||||||
|
for (const para of full.split(/\n{2,}/)) {
|
||||||
|
if (sample && sample.length + para.length > 750) break
|
||||||
|
sample = sample ? `${sample}\n\n${para}` : para
|
||||||
|
}
|
||||||
|
// Don't end on a lone heading like "The Accuser."
|
||||||
|
const lastBreak = sample.lastIndexOf('\n\n')
|
||||||
|
if (lastBreak > 0 && sample.length - lastBreak < 40) sample = sample.slice(0, lastBreak)
|
||||||
|
console.log(`\nSample: ${sample.length} characters (model ${model}).\n`)
|
||||||
|
const out = path.join(outDir, 'salvation-sample.mp3')
|
||||||
|
await renderTrack(sample, out)
|
||||||
|
if (totalCost) console.log(`\nElevenLabs reported ${totalCost.toLocaleString()} credits used.`)
|
||||||
|
console.log(`\nSaved ${out}\nIf the voice sounds right, run again without --sample.\n`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const only = (process.argv.find(a => a.startsWith('--only=')) || '').split('=')[1]
|
||||||
|
const tracks = only ? TRACKS.filter(t => t.id === only) : TRACKS
|
||||||
|
if (!tracks.length) fail(`Unknown --only value "${only}". Use: case, guilty or not-guilty.`)
|
||||||
|
|
||||||
|
const texts = []
|
||||||
|
for (const t of tracks) texts.push((await readFile(path.join(ROOT, 'scripts/salvation', t.file), 'utf8')).trim())
|
||||||
|
const chars = texts.reduce((n, t) => n + t.length, 0)
|
||||||
|
console.log(`\n${tracks.length} track(s), ${chars.toLocaleString()} characters in total (model ${model}).`)
|
||||||
|
console.log('This uses about that many ElevenLabs credits.\n')
|
||||||
|
|
||||||
|
for (const [i, t] of tracks.entries()) {
|
||||||
|
console.log(` ${t.id} (${texts[i].length.toLocaleString()} characters)`)
|
||||||
|
await renderTrack(texts[i], path.join(outDir, t.out))
|
||||||
|
}
|
||||||
|
if (totalCost) console.log(`\nElevenLabs reported ${totalCost.toLocaleString()} credits used.`)
|
||||||
|
console.log(`\nSaved to ${outDir}:\n${tracks.map(t => ` ${t.out}`).join('\n')}\nListen to each one before you upload it. Check the Scripture names and references.\n`)
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch(err => fail(err?.message ?? String(err)))
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
The Gospel, in a Courtroom.
|
||||||
|
|
||||||
|
Imagine a courtroom. Not a courtroom on earth, but the highest court there is: the Court of Heaven. God is the Judge. Satan is the accuser. The charges are your sins, and you are the one on trial. But before the verdict is read, a Substitute has stepped forward to take your place. Let me walk you through the case.
|
||||||
|
|
||||||
|
The Judge.
|
||||||
|
|
||||||
|
God is perfectly just. He will not overlook wrongdoing. Nothing is hidden from him, and he judges rightly. In the book of Genesis, chapter eighteen, verse twenty-five, Scripture asks: "Will not the Judge of all the earth do right?" And in Acts, chapter seventeen, verse thirty-one: "For He has set a day when He will judge the world with justice by the Man He has appointed."
|
||||||
|
|
||||||
|
The Accuser.
|
||||||
|
|
||||||
|
Every courtroom has an accuser, and ours is Satan. His very name means "adversary." Scripture calls him the accuser of the brothers, who brings charges against us before God. He does not have to invent anything. He only has to point to what we have actually done. Revelation, chapter twelve, verse ten, calls him "the accuser of our brothers, who accuses them before our God day and night." And First Peter, chapter five, verse eight, warns: "Your adversary the devil prowls around like a roaring lion, looking for someone to devour."
|
||||||
|
|
||||||
|
The Charges.
|
||||||
|
|
||||||
|
So what are the charges? The charges are the sins you have committed.
|
||||||
|
|
||||||
|
Sin is breaking God's law. That includes the wrong things we knowingly do, the good things we fail to do, and the things we say and think in secret.
|
||||||
|
|
||||||
|
It also includes breaking his law without knowing it. Not knowing the law has never made anyone innocent. God's standard is written on every conscience, so that no one is without excuse. Even sin done unknowingly still leaves a person guilty.
|
||||||
|
|
||||||
|
And God does not grade on a curve. Stumbling at one point means you have broken the whole law. We have all sinned. That includes you, and it includes me.
|
||||||
|
|
||||||
|
First John, chapter three, verse four: "Everyone who practices sin practices lawlessness; indeed, sin is lawlessness." James, chapter two, verse ten: "For whoever keeps the whole law but stumbles at just one point is guilty of breaking all of it." Romans, chapter three, verse ten: "There is no one righteous, not even one." And Romans, chapter three, verse twenty-three: "For all have sinned and fall short of the glory of God."
|
||||||
|
|
||||||
|
The Verdict.
|
||||||
|
|
||||||
|
The evidence is clear, and there is no defense. We cannot argue our way out, and our good deeds cannot cancel our guilt. The sentence for sin is death: separation from the God who made us. Romans, chapter three, verse nineteen: "...so that every mouth may be silenced and the whole world held accountable to God." And Romans, chapter six, verse twenty-three: "For the wages of sin is death..."
|
||||||
|
|
||||||
|
But that is not the end of the story.
|
||||||
|
|
||||||
|
The Substitute.
|
||||||
|
|
||||||
|
Then God himself stepped forward to take your place.
|
||||||
|
|
||||||
|
Jesus is God. The eternal Son took on flesh and was born as a baby in Bethlehem, and he came for one purpose: to take the place of sinners like you and me. He did not come to be served. He came to give his life, and the cross was always where the road was heading.
|
||||||
|
|
||||||
|
He lived the perfect life you could not live. On the cross he took the sentence that belonged to you, and he rose again on the third day to prove the payment was accepted.
|
||||||
|
|
||||||
|
John, chapter one, verse fourteen: "The Word became flesh and dwelt among us." Matthew, chapter one, verse twenty-one: "She will bear a Son, and you are to name Him Jesus, because He will save His people from their sins." Mark, chapter ten, verse forty-five: "For even the Son of Man did not come to be served, but to serve, and to give His life as a ransom for many." First Peter, chapter three, verse eighteen: "For Christ also suffered once for sins, the righteous for the unrighteous, to bring you to God." Second Corinthians, chapter five, verse twenty-one: "God made Him who knew no sin to be sin for us, so that in Him we might become the righteousness of God." And Romans, chapter five, verse eight: "But God proves His love for us in this: While we were still sinners, Christ died for us."
|
||||||
|
|
||||||
|
The Pardon.
|
||||||
|
|
||||||
|
The pardon is a gift. It cannot be earned or bought. You receive it by turning from your sin and trusting Jesus alone. When you do, God declares you forgiven and counts you righteous because of what Christ has done.
|
||||||
|
|
||||||
|
Ephesians, chapter two, verses eight and nine: "For by grace you have been saved through faith, and this is not from yourselves, but it is the gift of God, not by works, so that no one can boast." And Romans, chapter ten, verse nine: "If you confess with your mouth that Jesus is Lord, and believe in your heart that God raised Him from the dead, you will be saved."
|
||||||
|
|
||||||
|
The Result.
|
||||||
|
|
||||||
|
Case closed. The accuser has nothing left to say. Our sins were real charges, but they have been answered, because the penalty has been paid in full by the Substitute. The one who trusts in Christ is not waiting nervously for a verdict. The verdict has already been given in their favor.
|
||||||
|
|
||||||
|
Romans, chapter eight, verse one: "Therefore, there is now no condemnation for those who are in Christ Jesus." And verses thirty-three and thirty-four: "Who can bring an accusation against those whom God has chosen? It is God who justifies. Who then can condemn? Christ Jesus, who died, more than that, was raised to life, is at the right hand of God, and He is interceding for us."
|
||||||
|
|
||||||
|
Before you plead.
|
||||||
|
|
||||||
|
Before you plead, read what Jesus did for you. Everything you have just heard tells you that the Substitute took your place. The record shows you how: the night he was arrested, the trials where he was declared innocent and condemned anyway, the long road to the cross, and the empty tomb on the third day.
|
||||||
|
|
||||||
|
Please do not skip it. It is the story of what Jesus did for you, told by four witnesses and woven into one account. Take your time and read it slowly. You can pause this audio at any time, read the record, and then come back and press play. When you are ready, continue.
|
||||||
|
|
||||||
|
How do you plead?
|
||||||
|
|
||||||
|
The court is not asking whether you are a good person. It is asking you to be honest about the charges, and to decide where you will stand: on your own record, or on what Jesus has done in your place.
|
||||||
|
|
||||||
|
You have two choices.
|
||||||
|
|
||||||
|
You can plead guilty. That means: I admit it. I have broken God's law, whether I knew it or not, and I cannot save myself. I am not asking the court to find me innocent. I am asking for the pardon Jesus paid for with his life. And here is what happens: the Judge declares you forgiven, and counts you righteous because of Christ. The accuser has nothing left to say.
|
||||||
|
|
||||||
|
Or you can plead not guilty. That means: I stand on my own record. I believe I have kept God's law well enough to be found innocent, and I do not need anyone to take my place. That plea has a cost, and I will explain it if you choose it.
|
||||||
|
|
||||||
|
Now look at the two buttons below the player. When you are ready, press the one that matches your plea, and I will walk you through what happens next.
|
||||||
|
|
||||||
|
Take a moment. Be honest with God, and honest with yourself.
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
You have pleaded guilty. That is the beginning of the good news.
|
||||||
|
|
||||||
|
You are not earning anything by saying this. You are receiving a gift. Romans, chapter six, verse twenty-three: "For the wages of sin is death, but the gift of God is eternal life in Christ Jesus our Lord." Here is what to do next.
|
||||||
|
|
||||||
|
First, tell God. Words do not save you. Trusting Jesus does. But you can say it to him in your own words, or you can pray this prayer. If you mean it, pray it out loud with me.
|
||||||
|
|
||||||
|
"Lord God, I plead guilty. I have sinned against you, and I cannot save myself. I believe Jesus Christ took my place on the cross, died for my sins, and rose again. I turn from my sin, and I trust him alone. Thank you for the pardon I could never earn. Make me new, and help me follow you. Amen."
|
||||||
|
|
||||||
|
Second, believe it is finished. If you meant that prayer, God has forgiven you. Romans, chapter eight, verse one: "Therefore, there is now no condemnation for those who are in Christ Jesus." Your feelings may go up and down, but the verdict does not change.
|
||||||
|
|
||||||
|
Third, tell someone. Tell a Christian friend or family member what you decided.
|
||||||
|
|
||||||
|
Fourth, start reading. Begin with the Gospel of John, then keep going through the New Testament, and talk to God every day.
|
||||||
|
|
||||||
|
Fifth, find a church. Join a Bible-teaching church where you can grow, and be baptized as a public sign of your faith. Acts, chapter two, verse thirty-eight.
|
||||||
|
|
||||||
|
And if you prayed that prayer and meant it, we would love to rejoice with you. Press the button below that says, Let us know. You can leave your name and your email, and someone from our team will reach out to you personally. It is completely optional.
|
||||||
|
|
||||||
|
Welcome to the family of God.
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
You have pleaded not guilty. Please be sure you understand what that means.
|
||||||
|
|
||||||
|
Pleading not guilty is not just saying, "I am not a bad person." It is telling the Judge, "I have kept your law perfectly, and I need no one to take my place."
|
||||||
|
|
||||||
|
God's standard is not "better than most people." It is perfection. Matthew, chapter five, verse forty-eight: "Be perfect, therefore, as your heavenly Father is perfect." And breaking that standard at even one point makes a person guilty of breaking all of it. James, chapter two, verse ten: "For whoever keeps the whole law but stumbles at just one point is guilty of breaking all of it." That includes the things done without knowing they were wrong.
|
||||||
|
|
||||||
|
So test your plea honestly.
|
||||||
|
|
||||||
|
Have you ever told a lie, even a small one?
|
||||||
|
|
||||||
|
Have you ever taken something that was not yours?
|
||||||
|
|
||||||
|
Have you ever used God's name carelessly, or put something else ahead of him: money, a person, yourself?
|
||||||
|
|
||||||
|
Have you ever hated someone in your heart, or looked at someone with lust? Jesus said those count too. Matthew, chapter five.
|
||||||
|
|
||||||
|
If the answer to any of those is yes, then by God's own standard, the plea does not hold. First John, chapter one, verse eight: "If we say that we have no sin, we are deceiving ourselves, and the truth is not in us."
|
||||||
|
|
||||||
|
And here is what a not guilty plea costs. It means standing before the Judge on your own record, with no Substitute. The sentence for sin stands. Romans, chapter six, verse twenty-three. But that is not what God wants for you. He says he takes no pleasure in anyone's death. Ezekiel, chapter thirty-three, verse eleven. And the offer of pardon is open right now. Second Corinthians, chapter six, verse two: "Now is the day of salvation."
|
||||||
|
|
||||||
|
If you are not sure, that is okay. Questions and doubts are fine. Asking honestly is not the same as refusing.
|
||||||
|
|
||||||
|
If you would like to change your plea, press the button below that says, Change my plea to guilty. You can also read the record of what Jesus did for you, or ask us a question. Whatever you decide, thank you for listening honestly. The offer of the pardon is still open.
|
||||||
@@ -28,6 +28,7 @@ import {
|
|||||||
loadStudySessionsFromDisk,
|
loadStudySessionsFromDisk,
|
||||||
queueStudySessionsWrite,
|
queueStudySessionsWrite,
|
||||||
loadNewsletterIssuesFromDisk,
|
loadNewsletterIssuesFromDisk,
|
||||||
|
loadNuggetsTagsFromDisk,
|
||||||
createBackupSnapshot,
|
createBackupSnapshot,
|
||||||
refreshContentCaches,
|
refreshContentCaches,
|
||||||
queueHitStatsWrite,
|
queueHitStatsWrite,
|
||||||
@@ -38,10 +39,12 @@ import {
|
|||||||
sanitizeUserAgent,
|
sanitizeUserAgent,
|
||||||
shouldCountHit,
|
shouldCountHit,
|
||||||
recordHit,
|
recordHit,
|
||||||
|
isKnownSitePath,
|
||||||
scheduleStudyReminders,
|
scheduleStudyReminders,
|
||||||
scheduleReengagementEmails,
|
scheduleReengagementEmails,
|
||||||
scheduleWeeklyDigestEmails,
|
scheduleWeeklyDigestEmails,
|
||||||
backfillCompletedStudies,
|
backfillCompletedStudies,
|
||||||
|
backfillReminderDefault,
|
||||||
} from './server/study-helpers.js'
|
} from './server/study-helpers.js'
|
||||||
import { recordVisitor } from './server/routes/analytics.js'
|
import { recordVisitor } from './server/routes/analytics.js'
|
||||||
|
|
||||||
@@ -75,6 +78,7 @@ import { register as registerFeed } from './server/routes/feed.js'
|
|||||||
import { register as registerQrCodes } from './server/routes/qr-codes.js'
|
import { register as registerQrCodes } from './server/routes/qr-codes.js'
|
||||||
import { register as registerBiblePassage } from './server/routes/bible-passage.js'
|
import { register as registerBiblePassage } from './server/routes/bible-passage.js'
|
||||||
import { register as registerNewsletter } from './server/routes/newsletter.js'
|
import { register as registerNewsletter } from './server/routes/newsletter.js'
|
||||||
|
import { register as registerSalvation } from './server/routes/salvation.js'
|
||||||
import { register as registerPublic } from './server/routes/public.js'
|
import { register as registerPublic } from './server/routes/public.js'
|
||||||
|
|
||||||
preferIpv4ForSeafile()
|
preferIpv4ForSeafile()
|
||||||
@@ -96,12 +100,12 @@ app.use((_req, res, next) => {
|
|||||||
'Content-Security-Policy',
|
'Content-Security-Policy',
|
||||||
[
|
[
|
||||||
"default-src 'self'",
|
"default-src 'self'",
|
||||||
"script-src 'self' 'unsafe-inline' https://www.truthforlife.org https://ajax.googleapis.com",
|
"script-src 'self' 'unsafe-inline' https://www.truthforlife.org https://ajax.googleapis.com https://storage.ko-fi.com https://static.cloudflareinsights.com",
|
||||||
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",
|
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://www.truthforlife.org",
|
||||||
"font-src 'self' https://fonts.gstatic.com",
|
"font-src 'self' https://fonts.gstatic.com",
|
||||||
"img-src 'self' data: https:",
|
"img-src 'self' data: https:",
|
||||||
"media-src 'self' https:",
|
"media-src 'self' https:",
|
||||||
"frame-src https:",
|
"frame-src 'self' https:",
|
||||||
"connect-src 'self' https:",
|
"connect-src 'self' https:",
|
||||||
].join('; '),
|
].join('; '),
|
||||||
)
|
)
|
||||||
@@ -135,12 +139,14 @@ registerFeed(app)
|
|||||||
registerQrCodes(app)
|
registerQrCodes(app)
|
||||||
registerBiblePassage(app)
|
registerBiblePassage(app)
|
||||||
registerNewsletter(app)
|
registerNewsletter(app)
|
||||||
|
registerSalvation(app)
|
||||||
|
|
||||||
// Hit-counting middleware (must come before public routes)
|
// Hit-counting middleware (must come before public routes)
|
||||||
app.use((req, res, next) => {
|
app.use((req, res, next) => {
|
||||||
if (shouldCountHit(req)) {
|
if (shouldCountHit(req)) {
|
||||||
const ua = sanitizeUserAgent(req.get('user-agent'))
|
const ua = sanitizeUserAgent(req.get('user-agent'))
|
||||||
const botDetection = detectBot(ua)
|
const knownPath = isKnownSitePath(req.path)
|
||||||
|
const botDetection = knownPath ? detectBot(ua) : { isBot: true, reason: 'unknown-path' }
|
||||||
recordHit(req.path, botDetection.isBot, botDetection.reason)
|
recordHit(req.path, botDetection.isBot, botDetection.reason)
|
||||||
queueHitStatsWrite()
|
queueHitStatsWrite()
|
||||||
if (hasVisitorConsent(req) && !botDetection.isBot && !isValidAdminSession(req)) {
|
if (hasVisitorConsent(req) && !botDetection.isBot && !isValidAdminSession(req)) {
|
||||||
@@ -194,6 +200,7 @@ Promise.all([
|
|||||||
loadWebhooksFromDisk(),
|
loadWebhooksFromDisk(),
|
||||||
loadStudySessionsFromDisk(),
|
loadStudySessionsFromDisk(),
|
||||||
loadNewsletterIssuesFromDisk(),
|
loadNewsletterIssuesFromDisk(),
|
||||||
|
loadNuggetsTagsFromDisk(),
|
||||||
refreshContentCaches(),
|
refreshContentCaches(),
|
||||||
])
|
])
|
||||||
.catch(err => {
|
.catch(err => {
|
||||||
@@ -204,6 +211,11 @@ Promise.all([
|
|||||||
.catch(err => {
|
.catch(err => {
|
||||||
console.error('[study] completed-study backfill failed:', err)
|
console.error('[study] completed-study backfill failed:', err)
|
||||||
})
|
})
|
||||||
|
.then(() => backfillReminderDefault())
|
||||||
|
.then(updated => { if (updated > 0) console.log(`[study] turned lesson reminders on for ${updated} existing accounts`) })
|
||||||
|
.catch(err => {
|
||||||
|
console.error('[study] reminder-default backfill failed:', err)
|
||||||
|
})
|
||||||
.finally(() => {
|
.finally(() => {
|
||||||
createBackupSnapshot('startup').catch(() => {})
|
createBackupSnapshot('startup').catch(() => {})
|
||||||
setInterval(() => {
|
setInterval(() => {
|
||||||
|
|||||||
+4
-2
@@ -73,6 +73,7 @@ export const AUDIT_LOG_FILE = path.join(DATA_DIR, 'audit-log.json')
|
|||||||
export const WEBHOOKS_FILE = path.join(DATA_DIR, 'webhooks.json')
|
export const WEBHOOKS_FILE = path.join(DATA_DIR, 'webhooks.json')
|
||||||
export const STUDY_SESSIONS_FILE = path.join(DATA_DIR, 'study-sessions.json')
|
export const STUDY_SESSIONS_FILE = path.join(DATA_DIR, 'study-sessions.json')
|
||||||
export const NEWSLETTER_ISSUES_FILE = path.join(DATA_DIR, 'newsletter-issues.json')
|
export const NEWSLETTER_ISSUES_FILE = path.join(DATA_DIR, 'newsletter-issues.json')
|
||||||
|
export const NUGGETS_TAGS_FILE = path.join(DATA_DIR, 'nuggets-tags.json')
|
||||||
export const MAX_EPISODE_SCRIPT_LENGTH = 200_000 // ~150k words, well beyond any sermon
|
export const MAX_EPISODE_SCRIPT_LENGTH = 200_000 // ~150k words, well beyond any sermon
|
||||||
|
|
||||||
// Seafile integration for Nuggets episode uploads
|
// Seafile integration for Nuggets episode uploads
|
||||||
@@ -121,8 +122,8 @@ export const MAX_STUDY_COMMENTS = 10000
|
|||||||
export const MAX_STUDY_COMMENT_LENGTH = 2000
|
export const MAX_STUDY_COMMENT_LENGTH = 2000
|
||||||
export const MAX_STUDY_USERS = 5000
|
export const MAX_STUDY_USERS = 5000
|
||||||
export const MAX_STUDY_ENROLLMENTS_PER_USER = 100
|
export const MAX_STUDY_ENROLLMENTS_PER_USER = 100
|
||||||
export const MAX_STUDY_NOTES_PER_USER = 500
|
export const MAX_STUDY_NOTES_PER_USER = 3000
|
||||||
export const MAX_STUDY_NOTE_LENGTH = 12000
|
export const MAX_STUDY_NOTE_LENGTH = 200000
|
||||||
export const EMAIL_CHANGE_TOKEN_TTL_MS = 24 * 60 * 60 * 1000
|
export const EMAIL_CHANGE_TOKEN_TTL_MS = 24 * 60 * 60 * 1000
|
||||||
export const EMAIL_VERIFY_TOKEN_TTL_MS = 7 * 24 * 60 * 60 * 1000
|
export const EMAIL_VERIFY_TOKEN_TTL_MS = 7 * 24 * 60 * 60 * 1000
|
||||||
export const PASSWORD_RESET_TOKEN_TTL_MS = 60 * 60 * 1000
|
export const PASSWORD_RESET_TOKEN_TTL_MS = 60 * 60 * 1000
|
||||||
@@ -171,6 +172,7 @@ export const EMPTY_HIT_STATS = {
|
|||||||
byPath: {},
|
byPath: {},
|
||||||
byPathReal: {},
|
byPathReal: {},
|
||||||
byPathBot: {},
|
byPathBot: {},
|
||||||
|
byPathUnknown: {},
|
||||||
byDay: {},
|
byDay: {},
|
||||||
byDayReal: {},
|
byDayReal: {},
|
||||||
byDayBot: {},
|
byDayBot: {},
|
||||||
|
|||||||
+29
-1
@@ -37,6 +37,7 @@ import {
|
|||||||
WEBHOOKS_FILE,
|
WEBHOOKS_FILE,
|
||||||
STUDY_SESSIONS_FILE,
|
STUDY_SESSIONS_FILE,
|
||||||
NEWSLETTER_ISSUES_FILE,
|
NEWSLETTER_ISSUES_FILE,
|
||||||
|
NUGGETS_TAGS_FILE,
|
||||||
EMPTY_HIT_STATS,
|
EMPTY_HIT_STATS,
|
||||||
EMPTY_VISITOR_STATS,
|
EMPTY_VISITOR_STATS,
|
||||||
DEFAULT_REPLY_TEMPLATES,
|
DEFAULT_REPLY_TEMPLATES,
|
||||||
@@ -166,6 +167,7 @@ export function loadHitStatsFromDisk() {
|
|||||||
byPath: parsed?.byPath && typeof parsed.byPath === 'object' ? parsed.byPath : {},
|
byPath: parsed?.byPath && typeof parsed.byPath === 'object' ? parsed.byPath : {},
|
||||||
byPathReal: parsed?.byPathReal && typeof parsed.byPathReal === 'object' ? parsed.byPathReal : {},
|
byPathReal: parsed?.byPathReal && typeof parsed.byPathReal === 'object' ? parsed.byPathReal : {},
|
||||||
byPathBot: parsed?.byPathBot && typeof parsed.byPathBot === 'object' ? parsed.byPathBot : {},
|
byPathBot: parsed?.byPathBot && typeof parsed.byPathBot === 'object' ? parsed.byPathBot : {},
|
||||||
|
byPathUnknown: parsed?.byPathUnknown && typeof parsed.byPathUnknown === 'object' ? parsed.byPathUnknown : {},
|
||||||
byDay: parsed?.byDay && typeof parsed.byDay === 'object' ? parsed.byDay : {},
|
byDay: parsed?.byDay && typeof parsed.byDay === 'object' ? parsed.byDay : {},
|
||||||
byDayReal: parsed?.byDayReal && typeof parsed.byDayReal === 'object' ? parsed.byDayReal : {},
|
byDayReal: parsed?.byDayReal && typeof parsed.byDayReal === 'object' ? parsed.byDayReal : {},
|
||||||
byDayBot: parsed?.byDayBot && typeof parsed.byDayBot === 'object' ? parsed.byDayBot : {},
|
byDayBot: parsed?.byDayBot && typeof parsed.byDayBot === 'object' ? parsed.byDayBot : {},
|
||||||
@@ -1165,7 +1167,7 @@ export async function restoreFromBackup(filename) {
|
|||||||
// (These are defined here rather than study-helpers to avoid circular imports)
|
// (These are defined here rather than study-helpers to avoid circular imports)
|
||||||
|
|
||||||
export function normalizeMessageType(value) {
|
export function normalizeMessageType(value) {
|
||||||
if (value === 'question' || value === 'testimony' || value === 'topic') return value
|
if (value === 'question' || value === 'testimony' || value === 'topic' || value === 'gospel' || value === 'community') return value
|
||||||
return 'general'
|
return 'general'
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1249,6 +1251,7 @@ function sanitizeLoadedHitStats(value) {
|
|||||||
byPath: value?.byPath && typeof value.byPath === 'object' ? value.byPath : {},
|
byPath: value?.byPath && typeof value.byPath === 'object' ? value.byPath : {},
|
||||||
byPathReal: value?.byPathReal && typeof value.byPathReal === 'object' ? value.byPathReal : {},
|
byPathReal: value?.byPathReal && typeof value.byPathReal === 'object' ? value.byPathReal : {},
|
||||||
byPathBot: value?.byPathBot && typeof value.byPathBot === 'object' ? value.byPathBot : {},
|
byPathBot: value?.byPathBot && typeof value.byPathBot === 'object' ? value.byPathBot : {},
|
||||||
|
byPathUnknown: value?.byPathUnknown && typeof value.byPathUnknown === 'object' ? value.byPathUnknown : {},
|
||||||
byDay: value?.byDay && typeof value.byDay === 'object' ? value.byDay : {},
|
byDay: value?.byDay && typeof value.byDay === 'object' ? value.byDay : {},
|
||||||
byDayReal: value?.byDayReal && typeof value.byDayReal === 'object' ? value.byDayReal : {},
|
byDayReal: value?.byDayReal && typeof value.byDayReal === 'object' ? value.byDayReal : {},
|
||||||
byDayBot: value?.byDayBot && typeof value.byDayBot === 'object' ? value.byDayBot : {},
|
byDayBot: value?.byDayBot && typeof value.byDayBot === 'object' ? value.byDayBot : {},
|
||||||
@@ -1418,6 +1421,7 @@ export function sanitizeStudyUsers(value) {
|
|||||||
remindersPausedUntil: typeof item?.remindersPausedUntil === 'string' ? item.remindersPausedUntil : null,
|
remindersPausedUntil: typeof item?.remindersPausedUntil === 'string' ? item.remindersPausedUntil : null,
|
||||||
reminderFrequency: item?.reminderFrequency === 'weekly' ? 'weekly' : 'immediate',
|
reminderFrequency: item?.reminderFrequency === 'weekly' ? 'weekly' : 'immediate',
|
||||||
weeklyDigestSentAt: typeof item?.weeklyDigestSentAt === 'string' ? item.weeklyDigestSentAt : null,
|
weeklyDigestSentAt: typeof item?.weeklyDigestSentAt === 'string' ? item.weeklyDigestSentAt : null,
|
||||||
|
remindersDefaultedAt: typeof item?.remindersDefaultedAt === 'string' ? item.remindersDefaultedAt : null,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
return out.slice(0, MAX_STUDY_USERS)
|
return out.slice(0, MAX_STUDY_USERS)
|
||||||
@@ -1588,3 +1592,27 @@ export function loadNewsletterIssuesFromDisk() {
|
|||||||
state.newsletterIssues = []
|
state.newsletterIssues = []
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Nuggets Episode Tags ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function queueNuggetsTagsWrite() {
|
||||||
|
state.nuggetsEpisodeTagsWritePromise = state.nuggetsEpisodeTagsWritePromise
|
||||||
|
.then(async () => {
|
||||||
|
await mkdir(DATA_DIR, { recursive: true })
|
||||||
|
await writeFile(NUGGETS_TAGS_FILE, JSON.stringify({ tags: state.nuggetsEpisodeTags }, null, 2), 'utf8')
|
||||||
|
})
|
||||||
|
.catch(err => {
|
||||||
|
console.error('[nuggets-tags] failed to write:', err)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function loadNuggetsTagsFromDisk() {
|
||||||
|
return readFile(NUGGETS_TAGS_FILE, 'utf8')
|
||||||
|
.then(raw => {
|
||||||
|
const parsed = JSON.parse(raw)
|
||||||
|
state.nuggetsEpisodeTags = parsed?.tags && typeof parsed.tags === 'object' ? parsed.tags : {}
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
state.nuggetsEpisodeTags = {}
|
||||||
|
})
|
||||||
|
}
|
||||||
+11
-6
@@ -4,7 +4,7 @@ import { loadPodcastWorkflow, laneSeasonOf } from './routes/podcast-workflow.js'
|
|||||||
// The Spotify (Anchor) RSS feed only lists episodes that are live, so a season + episode number
|
// The Spotify (Anchor) RSS feed only lists episodes that are live, so a season + episode number
|
||||||
// showing up there means the episode has been published. That drives two things on the public site:
|
// showing up there means the episode has been published. That drives two things on the public site:
|
||||||
// - highlights marked "hold until released" stay hidden until their episode is in the feed
|
// - highlights marked "hold until released" stay hidden until their episode is in the feed
|
||||||
// - study lessons with no audio of their own pick it up from the matching feed episode
|
// - highlights and study lessons with no audio of their own pick it up from the matching feed episode
|
||||||
|
|
||||||
const SNAPSHOT_TTL_MS = 5 * 60 * 1000
|
const SNAPSHOT_TTL_MS = 5 * 60 * 1000
|
||||||
|
|
||||||
@@ -44,7 +44,7 @@ export async function applyFeedRelease(content) {
|
|||||||
|
|
||||||
const links = Array.isArray(content.podcastFeaturedLinks) ? content.podcastFeaturedLinks : []
|
const links = Array.isArray(content.podcastFeaturedLinks) ? content.podcastFeaturedLinks : []
|
||||||
const studies = Array.isArray(content.studies) ? content.studies : []
|
const studies = Array.isArray(content.studies) ? content.studies : []
|
||||||
if (!links.some(l => l?.holdUntilReleased) && studies.length === 0) return content
|
if (links.length === 0 && studies.length === 0) return content
|
||||||
|
|
||||||
const [index, wf] = await Promise.all([getFeedIndex(), loadPodcastWorkflow()])
|
const [index, wf] = await Promise.all([getFeedIndex(), loadPodcastWorkflow()])
|
||||||
const seasonA = laneSeasonOf('A', wf, content)
|
const seasonA = laneSeasonOf('A', wf, content)
|
||||||
@@ -52,11 +52,16 @@ export async function applyFeedRelease(content) {
|
|||||||
|
|
||||||
const nextLinks = links.flatMap(link => {
|
const nextLinks = links.flatMap(link => {
|
||||||
// General highlights aren't tied to a series, so there's no season to match against
|
// General highlights aren't tied to a series, so there's no season to match against
|
||||||
if (!link?.holdUntilReleased || link.lane === 'general') return [link]
|
if (!link || link.lane === 'general') return [link]
|
||||||
const season = link.lane === 'second' ? seasonB : seasonA
|
const season = link.lane === 'second' ? seasonB : seasonA
|
||||||
const item = season && link.episodeNumber ? index.get(`${season}-${link.episodeNumber}`) : null
|
const item = season && link.episodeNumber ? index.get(`${season}-${String(link.episodeNumber).trim()}`) : null
|
||||||
if (!item) return []
|
if (!item) return link.holdUntilReleased ? [] : [link]
|
||||||
return [{ ...link, url: link.url || item.link || '' }]
|
// Highlights with no audio of their own pick it up from the matching feed episode
|
||||||
|
return [{
|
||||||
|
...link,
|
||||||
|
url: link.url || item.link || '',
|
||||||
|
embedUrl: link.embedUrl?.trim() ? link.embedUrl : (item.audioUrl || link.embedUrl),
|
||||||
|
}]
|
||||||
})
|
})
|
||||||
|
|
||||||
const studyLane = study => {
|
const studyLane = study => {
|
||||||
|
|||||||
@@ -341,9 +341,11 @@ function sanitizeStudies(value) {
|
|||||||
title: typeof item.title === 'string' ? item.title.trim().slice(0, 160) : '',
|
title: typeof item.title === 'string' ? item.title.trim().slice(0, 160) : '',
|
||||||
description: typeof item.description === 'string' ? item.description.trim().slice(0, 800) : '',
|
description: typeof item.description === 'string' ? item.description.trim().slice(0, 800) : '',
|
||||||
homepageEyebrow: typeof item.homepageEyebrow === 'string' ? item.homepageEyebrow.trim().slice(0, 80) : '',
|
homepageEyebrow: typeof item.homepageEyebrow === 'string' ? item.homepageEyebrow.trim().slice(0, 80) : '',
|
||||||
|
imageUrl: sanitizeUrl(item.imageUrl) || '',
|
||||||
showOnHomepage: item.showOnHomepage === true,
|
showOnHomepage: item.showOnHomepage === true,
|
||||||
showNewTag: item.showNewTag === true,
|
showNewTag: item.showNewTag === true,
|
||||||
newTagLabel: typeof item.newTagLabel === 'string' ? item.newTagLabel.trim().slice(0, 24) : '',
|
newTagLabel: typeof item.newTagLabel === 'string' ? item.newTagLabel.trim().slice(0, 24) : '',
|
||||||
|
guideSource: typeof item.guideSource === 'string' && /^(none|primary|second|book:[A-Za-z0-9_-]{1,80})$/.test(item.guideSource.trim()) ? item.guideSource.trim() : '',
|
||||||
status: item.status === 'planned' ? 'planned' : (item.status === 'complete' ? 'complete' : 'active'),
|
status: item.status === 'planned' ? 'planned' : (item.status === 'complete' ? 'complete' : 'active'),
|
||||||
lane: item.lane === 'A' || item.lane === 'B' ? item.lane : '',
|
lane: item.lane === 'A' || item.lane === 'B' ? item.lane : '',
|
||||||
startsAt: sanitizeIsoDate(item.startsAt),
|
startsAt: sanitizeIsoDate(item.startsAt),
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ import {
|
|||||||
buildLastNDaysStats,
|
buildLastNDaysStats,
|
||||||
shouldCountHit,
|
shouldCountHit,
|
||||||
recordHit,
|
recordHit,
|
||||||
|
isKnownSitePath,
|
||||||
getStudyCatalog,
|
getStudyCatalog,
|
||||||
} from '../study-helpers.js'
|
} from '../study-helpers.js'
|
||||||
|
|
||||||
@@ -260,6 +261,7 @@ export function register(app) {
|
|||||||
const ip = getClientIp(req)
|
const ip = getClientIp(req)
|
||||||
if (!pageviewAllowed(ip)) { res.json({ ok: false, reason: 'rate-limited' }); return }
|
if (!pageviewAllowed(ip)) { res.json({ ok: false, reason: 'rate-limited' }); return }
|
||||||
const rawPath = typeof req.body?.path === 'string' ? req.body.path : '/'
|
const rawPath = typeof req.body?.path === 'string' ? req.body.path : '/'
|
||||||
|
if (!isKnownSitePath(rawPath)) { res.json({ ok: false, reason: 'unknown-path' }); return }
|
||||||
const rawReferrer = typeof req.body?.referrer === 'string' ? req.body.referrer : ''
|
const rawReferrer = typeof req.body?.referrer === 'string' ? req.body.referrer : ''
|
||||||
recordHit(rawPath, false)
|
recordHit(rawPath, false)
|
||||||
queueHitStatsWrite()
|
queueHitStatsWrite()
|
||||||
@@ -391,6 +393,13 @@ export function register(app) {
|
|||||||
firstHitAt: state.hitStats.firstHitAt,
|
firstHitAt: state.hitStats.firstHitAt,
|
||||||
lastHitAt: state.hitStats.lastHitAt,
|
lastHitAt: state.hitStats.lastHitAt,
|
||||||
topPaths, topPathsReal, topPathsBot,
|
topPaths, topPathsReal, topPathsBot,
|
||||||
|
topUnknownPaths: Object.entries(state.hitStats.byPathUnknown ?? {})
|
||||||
|
.sort((a, b) => b[1] - a[1]).slice(0, 25).map(([path, hits]) => ({ path, hits })),
|
||||||
|
uniqueVisitors7d: new Set(
|
||||||
|
state.visitorStats.recentVisits
|
||||||
|
.filter(v => Date.now() - new Date(v.at).getTime() <= 7 * 24 * 60 * 60 * 1000)
|
||||||
|
.map(v => v.visitorId),
|
||||||
|
).size,
|
||||||
last7Days, last7DaysReal, last7DaysBot,
|
last7Days, last7DaysReal, last7DaysBot,
|
||||||
last30DaysTotal, last30DaysRealTotal, last30DaysBotTotal,
|
last30DaysTotal, last30DaysRealTotal, last30DaysBotTotal,
|
||||||
botReasons,
|
botReasons,
|
||||||
|
|||||||
@@ -29,7 +29,12 @@ BIBLE_BOOKS.forEach((b, index) => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
function parseReference(reference) {
|
function parseReference(reference) {
|
||||||
const stripped = reference.replace(/^[a-z]+/i, '')
|
// Accept a leading book name ("Titus 1:1-2", "1 John 2:3"), en/em dashes and verse-part letters ("1:13a")
|
||||||
|
const stripped = reference
|
||||||
|
.replace(/[–—]/g, '-')
|
||||||
|
.replace(/(\d)[a-z]\b/gi, '$1')
|
||||||
|
.replace(/^\s*(?:[1-3]\s*)?[a-z][a-z .]*?\s*(?=\d+:)/i, '')
|
||||||
|
.trim()
|
||||||
const match = stripped.match(/^(\d+):(\d+)(?:-(\d+))?$/)
|
const match = stripped.match(/^(\d+):(\d+)(?:-(\d+))?$/)
|
||||||
if (!match) return null
|
if (!match) return null
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -222,6 +222,81 @@ export function register(app) {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// Collects a visitor's details, then hands back the Amazon / Apple Books link for a guide or book.
|
||||||
|
// The destination always comes from the saved site content, never from the request.
|
||||||
|
app.post('/api/store-link', studyDownloadRateLimit, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { source, store, firstName, lastName, email, subscribe, _honey } = req.body ?? {}
|
||||||
|
if (_honey) { res.json({ ok: true }); return }
|
||||||
|
|
||||||
|
if (typeof source !== 'string' || !source || (store !== 'amazon' && store !== 'apple')) {
|
||||||
|
res.status(400).json({ message: 'That link is not available.' }); return
|
||||||
|
}
|
||||||
|
if (!firstName || typeof firstName !== 'string' || firstName.trim().length < 1 || firstName.trim().length > 100) {
|
||||||
|
res.status(400).json({ message: 'First name is required.' }); return
|
||||||
|
}
|
||||||
|
if (!lastName || typeof lastName !== 'string' || lastName.trim().length < 1 || lastName.trim().length > 100) {
|
||||||
|
res.status(400).json({ message: 'Last name is required.' }); return
|
||||||
|
}
|
||||||
|
if (!email || typeof email !== 'string' || !/^[a-zA-Z0-9._%+\-]{1,64}@[a-zA-Z0-9.\-]{1,253}\.[a-zA-Z]{2,}$/.test(email.trim())) {
|
||||||
|
res.status(400).json({ message: 'A valid email address is required.' }); return
|
||||||
|
}
|
||||||
|
|
||||||
|
const published = await loadSiteContentFile(DATA_FILE)
|
||||||
|
const content = published?.siteContent ?? {}
|
||||||
|
const pick = (amazon, apple) => (store === 'amazon' ? amazon : apple)
|
||||||
|
let label = ''
|
||||||
|
let url = ''
|
||||||
|
|
||||||
|
if (source === 'page:primary-guide') {
|
||||||
|
label = content.studyGuideTitle
|
||||||
|
url = pick(content.studyGuideUrl, content.studyGuideAppleBooksUrl)
|
||||||
|
} else if (source === 'page:second-guide') {
|
||||||
|
const guide = content.secondSeries?.guide
|
||||||
|
label = guide?.title
|
||||||
|
url = pick(guide?.amazonUrl, guide?.appleBooksUrl)
|
||||||
|
} else if (source.startsWith('page:book-guide--')) {
|
||||||
|
const id = source.slice('page:book-guide--'.length)
|
||||||
|
const guide = (Array.isArray(content.finishedBooks) ? content.finishedBooks : []).find(b => b?.id === id)?.guide
|
||||||
|
label = guide?.title
|
||||||
|
url = pick(guide?.amazonUrl, guide?.appleBooksUrl)
|
||||||
|
} else if (source.startsWith('page:custom--')) {
|
||||||
|
const id = source.slice('page:custom--'.length)
|
||||||
|
const link = (content.customLinks ?? []).find(l => l?.id === id && l.placement === 'resources')
|
||||||
|
label = link?.label
|
||||||
|
url = pick(link?.amazonUrl, link?.appleBooksUrl)
|
||||||
|
} else if (source.startsWith('book:')) {
|
||||||
|
const id = source.slice('book:'.length)
|
||||||
|
const book = (content.customLinks ?? []).find(l => l?.id === id && l.placement === 'books')
|
||||||
|
label = book?.label
|
||||||
|
url = pick(book?.amazonUrl || book?.url, book?.appleBooksUrl)
|
||||||
|
}
|
||||||
|
|
||||||
|
const destination = sanitizeUrl(url)
|
||||||
|
if (!destination) { res.status(404).json({ message: 'That link is not available.' }); return }
|
||||||
|
|
||||||
|
const name = `${firstName.trim()} ${lastName.trim()}`.trim()
|
||||||
|
const trimmedEmail = email.trim()
|
||||||
|
const wantsSubscribe = subscribe !== false
|
||||||
|
const storeName = store === 'amazon' ? 'Amazon' : 'Apple Books'
|
||||||
|
|
||||||
|
addContactSubmission({
|
||||||
|
name,
|
||||||
|
email: trimmedEmail,
|
||||||
|
message: `Requested ${storeName} link: ${label || source}`,
|
||||||
|
messageType: 'general',
|
||||||
|
subscribe: wantsSubscribe,
|
||||||
|
})
|
||||||
|
if (wantsSubscribe) await syncContactToResend(name, trimmedEmail)
|
||||||
|
incrementDownloadCount(`store:${source}:${store}`)
|
||||||
|
|
||||||
|
res.json({ ok: true, url: destination })
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[store-link] request error:', err)
|
||||||
|
res.status(500).json({ message: 'Failed to process your request. Please try again.' })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
app.get('/api/admin-download-stats', requireAdminAuth, (_req, res) => {
|
app.get('/api/admin-download-stats', requireAdminAuth, (_req, res) => {
|
||||||
res.json({ counts: state.downloadCounts })
|
res.json({ counts: state.downloadCounts })
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -88,15 +88,22 @@ table[align="left"] { float: none !important; margin-left: auto !important; marg
|
|||||||
</style>
|
</style>
|
||||||
</head>`
|
</head>`
|
||||||
|
|
||||||
|
const topBar = `
|
||||||
|
<div style="background:#050505;border-bottom:1px solid rgba(184,151,42,0.25);padding:14px 20px;font-family:Georgia,serif">
|
||||||
|
<div style="max-width:640px;margin:0 auto;display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap">
|
||||||
|
<a href="${BASE}/" style="color:#e8d9b5;text-decoration:none;font-size:15px;letter-spacing:0.04em">Verse by Verse with Nate</a>
|
||||||
|
<a href="${BASE}/newsletter" style="color:#B8972A;text-decoration:none;font-size:12px;letter-spacing:0.14em;text-transform:uppercase">← All issues</a>
|
||||||
|
</div></div>`
|
||||||
|
|
||||||
const ctaBlock = `
|
const ctaBlock = `
|
||||||
<table border="0" width="100%" cellpadding="0" cellspacing="0" role="presentation" align="center">
|
<table border="0" width="100%" cellpadding="0" cellspacing="0" role="presentation" align="center">
|
||||||
<tbody><tr><td align="center" style="padding:32px 20px 48px;background-color:#080807">
|
<tbody><tr><td align="center" style="padding:40px 20px 56px;background-color:#080807;border-top:1px solid rgba(184,151,42,0.2)">
|
||||||
<table width="580" border="0" cellpadding="0" cellspacing="0" role="presentation" style="max-width:580px;width:100%">
|
<table width="580" border="0" cellpadding="0" cellspacing="0" role="presentation" style="max-width:580px;width:100%">
|
||||||
<tbody><tr><td align="center" style="padding:0">
|
<tbody><tr><td align="center" style="padding:0;font-family:Georgia,serif">
|
||||||
<p style="margin:0 0 16px;font-family:Georgia,serif;font-size:13px;color:#6b6044">
|
<p style="margin:0 0 8px;font-size:12px;letter-spacing:0.18em;text-transform:uppercase;color:#B8972A">Stay in the Word</p>
|
||||||
<a href="${BASE}/newsletter" style="color:#6b6044;text-decoration:none">← Newsletter Archive</a>
|
<p style="margin:0 0 22px;font-size:22px;line-height:1.3;color:#f0e9cc">Get the next issue in your inbox</p>
|
||||||
</p>
|
<a href="${BASE}/subscribe" style="display:inline-block;padding:13px 34px;font-size:12px;letter-spacing:0.16em;text-transform:uppercase;color:#0c0c08;background:#B8972A;text-decoration:none;border-radius:4px;font-weight:bold">Subscribe by Email</a>
|
||||||
<a href="${BASE}/subscribe" style="display:inline-block;padding:12px 32px;font-family:Georgia,serif;font-size:12px;letter-spacing:0.16em;text-transform:uppercase;color:#B8972A;border:1px solid #B8972A;text-decoration:none">Subscribe by Email</a>
|
<p style="margin:26px 0 0;font-size:13px"><a href="${BASE}/newsletter" style="color:#8a7e55;text-decoration:none">← Back to the newsletter archive</a></p>
|
||||||
</td></tr></tbody></table>
|
</td></tr></tbody></table>
|
||||||
</td></tr></tbody></table>
|
</td></tr></tbody></table>
|
||||||
</body>`
|
</body>`
|
||||||
@@ -104,6 +111,7 @@ table[align="left"] { float: none !important; margin-left: auto !important; marg
|
|||||||
let html = stripUnsubscribeLink(issue.html)
|
let html = stripUnsubscribeLink(issue.html)
|
||||||
html = html.replace(/<title>[\s\S]*?<\/title>/i, '')
|
html = html.replace(/<title>[\s\S]*?<\/title>/i, '')
|
||||||
html = /<\/head>/i.test(html) ? html.replace(/<\/head>/i, metaBlock) : html.replace(/<head[^>]*>/i, m => `${m}${metaBlock.replace('</head>', '')}`)
|
html = /<\/head>/i.test(html) ? html.replace(/<\/head>/i, metaBlock) : html.replace(/<head[^>]*>/i, m => `${m}${metaBlock.replace('</head>', '')}`)
|
||||||
|
html = html.replace(/<body[^>]*>/i, m => `${m}${topBar}`)
|
||||||
html = /<\/body>/i.test(html) ? html.replace(/<\/body>/i, ctaBlock) : `${html}${ctaBlock}`
|
html = /<\/body>/i.test(html) ? html.replace(/<\/body>/i, ctaBlock) : `${html}${ctaBlock}`
|
||||||
return html
|
return html
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import { parseRssItems } from '../rss-helpers.js'
|
import { parseRssItems } from '../rss-helpers.js'
|
||||||
import { state } from '../state.js'
|
import { state } from '../state.js'
|
||||||
|
import { requireAdminAuth } from '../auth.js'
|
||||||
|
import { queueNuggetsTagsWrite } from '../data.js'
|
||||||
|
|
||||||
let cache = null // { url, episodes }
|
let cache = null // { url, episodes }
|
||||||
let cacheAt = 0
|
let cacheAt = 0
|
||||||
@@ -37,12 +39,47 @@ export async function fetchNuggetsEpisodes() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function withTags(episodes) {
|
||||||
|
return episodes.map(ep => ({ ...ep, tags: state.nuggetsEpisodeTags[ep.audioUrl] ?? [] }))
|
||||||
|
}
|
||||||
|
|
||||||
|
function cleanTags(input) {
|
||||||
|
const list = Array.isArray(input) ? input : []
|
||||||
|
const seen = new Set()
|
||||||
|
const out = []
|
||||||
|
for (const t of list) {
|
||||||
|
const tag = String(t ?? '').trim().replace(/\s+/g, ' ').slice(0, 40)
|
||||||
|
const key = tag.toLowerCase()
|
||||||
|
if (tag && !seen.has(key)) { seen.add(key); out.push(tag) }
|
||||||
|
}
|
||||||
|
return out.slice(0, 12)
|
||||||
|
}
|
||||||
|
|
||||||
export function register(app) {
|
export function register(app) {
|
||||||
|
app.get('/api/admin/nuggets/episode-tags', requireAdminAuth, async (_req, res) => {
|
||||||
|
try {
|
||||||
|
const episodes = await fetchNuggetsEpisodes()
|
||||||
|
res.json({ episodes: withTags(episodes).map(({ title, pubDate, audioUrl, episode, tags }) => ({ title, pubDate, audioUrl, episode, tags })) })
|
||||||
|
} catch (err) {
|
||||||
|
res.status(502).json({ message: 'Could not load episodes from the feed.' })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
app.put('/api/admin/nuggets/episode-tags', requireAdminAuth, (req, res) => {
|
||||||
|
const audioUrl = String(req.body?.audioUrl ?? '')
|
||||||
|
if (!audioUrl) { res.status(400).json({ message: 'audioUrl is required.' }); return }
|
||||||
|
const tags = cleanTags(req.body?.tags)
|
||||||
|
if (tags.length) state.nuggetsEpisodeTags[audioUrl] = tags
|
||||||
|
else delete state.nuggetsEpisodeTags[audioUrl]
|
||||||
|
queueNuggetsTagsWrite()
|
||||||
|
res.json({ ok: true, tags })
|
||||||
|
})
|
||||||
|
|
||||||
app.get('/api/nuggets/episodes', async (_req, res) => {
|
app.get('/api/nuggets/episodes', async (_req, res) => {
|
||||||
const configured = Boolean(feedUrl())
|
const configured = Boolean(feedUrl())
|
||||||
try {
|
try {
|
||||||
const episodes = await fetchNuggetsEpisodes()
|
const episodes = await fetchNuggetsEpisodes()
|
||||||
res.json({ episodes: episodes.slice(0, 6), configured })
|
res.json({ episodes: withTags(episodes.slice(0, 6)), configured })
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('[nuggets/episodes] RSS fetch error:', err.message)
|
console.error('[nuggets/episodes] RSS fetch error:', err.message)
|
||||||
res.json({ episodes: [], configured })
|
res.json({ episodes: [], configured })
|
||||||
@@ -53,7 +90,7 @@ export function register(app) {
|
|||||||
const configured = Boolean(feedUrl())
|
const configured = Boolean(feedUrl())
|
||||||
try {
|
try {
|
||||||
const episodes = await fetchNuggetsEpisodes()
|
const episodes = await fetchNuggetsEpisodes()
|
||||||
res.json({ episodes, configured })
|
res.json({ episodes: withTags(episodes), configured })
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('[nuggets/episodes/all] RSS fetch error:', err.message)
|
console.error('[nuggets/episodes/all] RSS fetch error:', err.message)
|
||||||
res.json({ episodes: [], configured })
|
res.json({ episodes: [], configured })
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ import {
|
|||||||
} from '../config.js'
|
} from '../config.js'
|
||||||
import { state } from '../state.js'
|
import { state } from '../state.js'
|
||||||
import { loadSiteContentFile } from '../data.js'
|
import { loadSiteContentFile } from '../data.js'
|
||||||
import { sanitizeRedirectRules } from '../study-helpers.js'
|
import { sanitizeRedirectRules, isKnownSitePath } from '../study-helpers.js'
|
||||||
import { fetchAllEpisodes } from './episodes.js'
|
import { fetchAllEpisodes } from './episodes.js'
|
||||||
import { fetchNuggetsEpisodes } from './nuggets.js'
|
import { fetchNuggetsEpisodes } from './nuggets.js'
|
||||||
import { BIBLE_BOOKS } from '../../shared/bible-books.js'
|
import { BIBLE_BOOKS } from '../../shared/bible-books.js'
|
||||||
@@ -67,7 +67,7 @@ export function register(app) {
|
|||||||
const root = canonical.endsWith('/') ? canonical.slice(0, -1) : canonical
|
const root = canonical.endsWith('/') ? canonical.slice(0, -1) : canonical
|
||||||
|
|
||||||
res.type('text/plain').send(
|
res.type('text/plain').send(
|
||||||
['User-agent: *', 'Allow: /', 'Disallow: /salvation', `Sitemap: ${root}/sitemap.xml`].join('\n'),
|
['User-agent: *', 'Allow: /', `Sitemap: ${root}/sitemap.xml`].join('\n'),
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -111,6 +111,8 @@ export function register(app) {
|
|||||||
for (const ep of highlights) {
|
for (const ep of highlights) {
|
||||||
if (ep.id) urls.push(`${root}/episodes/${encodeURIComponent(ep.id)}`)
|
if (ep.id) urls.push(`${root}/episodes/${encodeURIComponent(ep.id)}`)
|
||||||
}
|
}
|
||||||
|
// The standalone gospel page
|
||||||
|
if (!urls.includes(`${root}/salvation`)) urls.push(`${root}/salvation`)
|
||||||
// Newsletter archive + published issues
|
// Newsletter archive + published issues
|
||||||
urls.push(`${root}/newsletter`)
|
urls.push(`${root}/newsletter`)
|
||||||
for (const issue of state.newsletterIssues) {
|
for (const issue of state.newsletterIssues) {
|
||||||
@@ -215,7 +217,8 @@ export function register(app) {
|
|||||||
if (!sec.id || !sec.reference || !sec.releasedAt) continue
|
if (!sec.id || !sec.reference || !sec.releasedAt) continue
|
||||||
if (new Date(sec.releasedAt) > cutoff) continue
|
if (new Date(sec.releasedAt) > cutoff) continue
|
||||||
entries.push({
|
entries.push({
|
||||||
reference: `${bookName} ${sec.reference}`,
|
// Section references often already include the book ("Titus 1:1-2"); only prepend when they don't
|
||||||
|
reference: /^\s*(?:[1-3]\s*)?[A-Za-z]/.test(sec.reference) ? sec.reference.trim() : `${bookName} ${sec.reference}`,
|
||||||
sourceType: 'study',
|
sourceType: 'study',
|
||||||
sourceTitle: s.title || s.slug,
|
sourceTitle: s.title || s.slug,
|
||||||
sectionTitle: sec.title || '',
|
sectionTitle: sec.title || '',
|
||||||
@@ -272,6 +275,8 @@ export function register(app) {
|
|||||||
app.use(async (_req, res) => {
|
app.use(async (_req, res) => {
|
||||||
try {
|
try {
|
||||||
const html = await readFile(INDEX_FILE, 'utf8')
|
const html = await readFile(INDEX_FILE, 'utf8')
|
||||||
|
// Unknown URLs still render the app's "Page not found" screen, but with a real 404 status
|
||||||
|
if (!isKnownSitePath(_req.path)) res.status(404)
|
||||||
res.type('html').send(injectSeoIntoHtml(html, state.cachedSiteContent))
|
res.type('html').send(injectSeoIntoHtml(html, state.cachedSiteContent))
|
||||||
} catch {
|
} catch {
|
||||||
res.status(503).send('Frontend build not found. Run "npm run build" first.')
|
res.status(503).send('Frontend build not found. Run "npm run build" first.')
|
||||||
|
|||||||
@@ -0,0 +1,307 @@
|
|||||||
|
import { Resend } from 'resend'
|
||||||
|
import { escapeHtml, sanitizeUrl } from '../helpers.js'
|
||||||
|
import { state } from '../state.js'
|
||||||
|
import { getResendFromAddress, getResendInboxAddress, getResendReplyToAddress, getCanonicalBaseUrl, sendResendEmailWithRetry } from '../email.js'
|
||||||
|
|
||||||
|
// A visitor who finished the /salvation page can tell us they prayed to receive Christ.
|
||||||
|
// Nothing is stored on the server: the response is emailed once to the site inbox and that is all.
|
||||||
|
const hits = new Map()
|
||||||
|
// One confirmation per address per hour, so the form can't be used to mail someone repeatedly.
|
||||||
|
const confirmedAt = new Map()
|
||||||
|
const CONFIRM_COOLDOWN_MS = 60 * 60 * 1000
|
||||||
|
|
||||||
|
function mayConfirm(address) {
|
||||||
|
const key = address.toLowerCase()
|
||||||
|
const now = Date.now()
|
||||||
|
const last = confirmedAt.get(key)
|
||||||
|
if (typeof last === 'number' && now - last < CONFIRM_COOLDOWN_MS) return false
|
||||||
|
confirmedAt.set(key, now)
|
||||||
|
if (confirmedAt.size > 2000) {
|
||||||
|
for (const [k, v] of confirmedAt) { if (now - v > CONFIRM_COOLDOWN_MS) confirmedAt.delete(k) }
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
function rateLimit(req, res, next) {
|
||||||
|
const ip = req.ip ?? 'unknown'
|
||||||
|
const now = Date.now()
|
||||||
|
const windowMs = 10 * 60 * 1000
|
||||||
|
const entry = hits.get(ip) ?? { count: 0, start: now }
|
||||||
|
if (now - entry.start > windowMs) { entry.count = 0; entry.start = now }
|
||||||
|
entry.count += 1
|
||||||
|
hits.set(ip, entry)
|
||||||
|
if (hits.size > 2000) {
|
||||||
|
for (const [k, v] of hits) { if (now - v.start > windowMs) hits.delete(k) }
|
||||||
|
}
|
||||||
|
if (entry.count > 3) {
|
||||||
|
res.status(429).json({ message: 'Please wait a few minutes before trying again.' })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
next()
|
||||||
|
}
|
||||||
|
|
||||||
|
function clean(value, max) {
|
||||||
|
return typeof value === 'string' ? value.trim().replace(/\s+/g, ' ').slice(0, max) : ''
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// The notification the site owner receives. Styled to match the other admin emails
|
||||||
|
// (dark header, gold accent, cream cards) and written to be acted on, not just read.
|
||||||
|
function buildSalvationEmail({ name, email, message, when }) {
|
||||||
|
const who = name || 'Someone'
|
||||||
|
const subject = name ? `A new decision for Christ: ${name}` : 'A new decision for Christ on your salvation page'
|
||||||
|
const nameLine = name || 'Name not given'
|
||||||
|
const safeName = escapeHtml(nameLine)
|
||||||
|
const safeEmail = escapeHtml(email)
|
||||||
|
const safeWhen = escapeHtml(when)
|
||||||
|
|
||||||
|
const followUp = email
|
||||||
|
? [
|
||||||
|
'Reply to this email within a day or two. A short, warm note is plenty.',
|
||||||
|
'Congratulate them, and ask them to tell you their story.',
|
||||||
|
'Point them to the Gospel of John, a Bible-teaching church, and baptism.',
|
||||||
|
'Invite them to Start Here at versebyversewithnate.us/start-here.',
|
||||||
|
'Pray for them by name.',
|
||||||
|
]
|
||||||
|
: ['They did not leave an email address, so there is no way to reply.', 'Pray for them. God knows exactly who they are.']
|
||||||
|
|
||||||
|
const text = [
|
||||||
|
`A VERDICT HAS COME IN`,
|
||||||
|
``,
|
||||||
|
`${who} pleaded guilty and accepted Christ's pardon on the "The Gospel, in a Courtroom" page and says they prayed to receive Jesus as their Savior.`,
|
||||||
|
``,
|
||||||
|
`"There is joy in the presence of the angels of God over one sinner who repents." (Luke 15:10)`,
|
||||||
|
``,
|
||||||
|
`DETAILS`,
|
||||||
|
`Name: ${nameLine}`,
|
||||||
|
`Email: ${email || 'Not given'}`,
|
||||||
|
`When: ${when}`,
|
||||||
|
``,
|
||||||
|
`THEIR MESSAGE`,
|
||||||
|
message || '(They did not leave a message.)',
|
||||||
|
``,
|
||||||
|
`SUGGESTED FOLLOW-UP`,
|
||||||
|
...followUp.map((t, i) => `${i + 1}. ${t}`),
|
||||||
|
``,
|
||||||
|
`This email is the only record of this response. Nothing is stored on the website, so keep it somewhere safe.`,
|
||||||
|
email ? `Reply directly to this email to reach ${who}.` : '',
|
||||||
|
].filter(l => l !== '').join('\n')
|
||||||
|
|
||||||
|
const row = (label, value, last = false) =>
|
||||||
|
`<tr><td style="width:96px;padding:11px 0;font-family:Arial,sans-serif;font-size:12px;font-weight:700;letter-spacing:0.08em;text-transform:uppercase;color:#8a6d35;${last ? '' : 'border-bottom:1px solid #efe4cc;'}">${label}</td>` +
|
||||||
|
`<td style="padding:11px 0;font-family:Arial,sans-serif;font-size:15px;color:#201a10;${last ? '' : 'border-bottom:1px solid #efe4cc;'}">${value}</td></tr>`
|
||||||
|
|
||||||
|
const steps = followUp
|
||||||
|
.map(t => `<li style="margin:0 0 8px;font-family:Arial,sans-serif;font-size:15px;line-height:1.55;color:#201a10;">${escapeHtml(t)}</li>`)
|
||||||
|
.join('')
|
||||||
|
|
||||||
|
const messageBlock = message
|
||||||
|
? `<tr><td style="padding:0 28px 22px;">
|
||||||
|
<div style="font-family:Arial,sans-serif;font-size:12px;font-weight:700;letter-spacing:0.14em;text-transform:uppercase;color:#8a6d35;margin:0 0 8px;">Their message</div>
|
||||||
|
<div style="background:#fbf7ef;border-left:4px solid #c8860a;border-radius:4px;padding:16px 18px;font-family:Georgia,serif;font-size:16px;line-height:1.7;color:#201a10;white-space:pre-wrap;">${escapeHtml(message)}</div>
|
||||||
|
</td></tr>`
|
||||||
|
: `<tr><td style="padding:0 28px 22px;font-family:Arial,sans-serif;font-size:14px;color:#735a2b;font-style:italic;">They did not leave a message.</td></tr>`
|
||||||
|
|
||||||
|
const replyButton = email
|
||||||
|
? `<tr><td align="center" style="padding:0 28px 26px;">
|
||||||
|
<a href="mailto:${safeEmail}?subject=${encodeURIComponent('Welcome to the family of God')}" style="display:inline-block;background:#c8860a;color:#111111;font-family:Arial,sans-serif;font-size:14px;font-weight:700;letter-spacing:0.1em;text-transform:uppercase;text-decoration:none;padding:14px 30px;border-radius:4px;">Reply to ${escapeHtml(who)}</a>
|
||||||
|
</td></tr>`
|
||||||
|
: ''
|
||||||
|
|
||||||
|
const html = `<!doctype html><html><body style="margin:0;padding:0;background:#f5f1e8;">
|
||||||
|
<table width="100%" cellpadding="0" cellspacing="0" border="0" role="presentation" style="background:#f5f1e8;"><tr><td align="center" style="padding:28px 14px;">
|
||||||
|
<table width="100%" cellpadding="0" cellspacing="0" border="0" role="presentation" style="max-width:640px;background:#ffffff;border:1px solid #e1d3b2;border-radius:14px;overflow:hidden;">
|
||||||
|
<tr><td style="background:#111111;padding:30px 28px 26px;text-align:center;border-bottom:4px solid #c8860a;">
|
||||||
|
<div style="font-family:Arial,sans-serif;font-size:12px;letter-spacing:0.34em;text-transform:uppercase;color:#c8860a;">The Court of Heaven</div>
|
||||||
|
<div style="font-size:40px;line-height:1;margin:14px 0 6px;color:#c8860a;">⚖</div>
|
||||||
|
<h1 style="margin:0;font-family:Georgia,serif;font-size:30px;line-height:1.2;color:#f4ead5;">A Verdict Has Come In</h1>
|
||||||
|
<p style="margin:10px 0 0;font-family:Georgia,serif;font-style:italic;font-size:17px;color:#d9c9a3;">${escapeHtml(who)} pleaded guilty and accepted the pardon.</p>
|
||||||
|
</td></tr>
|
||||||
|
<tr><td style="padding:28px 28px 8px;">
|
||||||
|
<p style="margin:0 0 14px;font-family:Georgia,serif;font-size:17px;line-height:1.7;color:#201a10;">Someone just worked through <em>The Gospel, in a Courtroom</em> on your website, pleaded guilty, and says they prayed to receive Jesus as their Savior.</p>
|
||||||
|
<p style="margin:0 0 20px;font-family:Georgia,serif;font-style:italic;font-size:16px;line-height:1.6;color:#57452b;border-left:3px solid #c8860a;padding-left:14px;">“There is joy in the presence of the angels of God over one sinner who repents.” <span style="font-style:normal;font-size:13px;color:#8a6d35;">Luke 15:10</span></p>
|
||||||
|
</td></tr>
|
||||||
|
<tr><td style="padding:0 28px 22px;">
|
||||||
|
<table width="100%" cellpadding="0" cellspacing="0" border="0" role="presentation" style="border-top:2px solid #c8860a;">
|
||||||
|
${row('Name', safeName)}
|
||||||
|
${row('Email', email ? `<a href="mailto:${safeEmail}" style="color:#8f5f05;text-decoration:none;">${safeEmail}</a>` : '<span style="color:#735a2b;font-style:italic;">Not given</span>')}
|
||||||
|
${row('When', safeWhen, true)}
|
||||||
|
</table>
|
||||||
|
</td></tr>
|
||||||
|
${messageBlock}
|
||||||
|
${replyButton}
|
||||||
|
<tr><td style="padding:0 28px 26px;">
|
||||||
|
<div style="background:#f7f2e5;border:1px solid #e8dcc1;border-radius:10px;padding:18px 22px;">
|
||||||
|
<div style="font-family:Arial,sans-serif;font-size:12px;font-weight:700;letter-spacing:0.14em;text-transform:uppercase;color:#8a6d35;margin:0 0 12px;">Suggested follow-up</div>
|
||||||
|
<ol style="margin:0;padding-left:20px;">${steps}</ol>
|
||||||
|
</div>
|
||||||
|
</td></tr>
|
||||||
|
<tr><td style="background:#f7f2e5;border-top:1px solid #e8dcc1;padding:16px 28px;">
|
||||||
|
<p style="margin:0;font-family:Arial,sans-serif;font-size:12px;line-height:1.6;color:#735a2b;"><strong>Keep this email.</strong> It is the only record of this response. Nothing is stored on the website. ${email ? 'Replying to this message goes straight to them.' : ''}</p>
|
||||||
|
</td></tr>
|
||||||
|
</table>
|
||||||
|
</td></tr></table></body></html>`
|
||||||
|
|
||||||
|
return { subject, text, html }
|
||||||
|
}
|
||||||
|
|
||||||
|
// The warm, one-time confirmation the visitor receives at the address they gave.
|
||||||
|
function buildSalvationConfirmationEmail({ name }) {
|
||||||
|
const base = getCanonicalBaseUrl().replace(/\/$/, '')
|
||||||
|
const greeting = name ? `Hi ${name},` : 'Hi friend,'
|
||||||
|
const subject = 'We received your message. Welcome to the family of God'
|
||||||
|
const steps = [
|
||||||
|
['Read the Gospel of John.', 'Start there, then keep going through the New Testament.'],
|
||||||
|
['Talk to God every day.', 'Prayer is simply talking with him, in your own words.'],
|
||||||
|
['Tell someone.', 'Share your decision with a Christian friend or family member.'],
|
||||||
|
['Find a church.', 'Join a Bible-teaching church, and be baptized as a public sign of your faith (Acts 2:38).'],
|
||||||
|
]
|
||||||
|
|
||||||
|
const text = [
|
||||||
|
greeting,
|
||||||
|
'',
|
||||||
|
'Thank you for letting us know that you prayed to receive Jesus. We are rejoicing with you, and your message has been received.',
|
||||||
|
'Someone from our team will reach out to you personally soon.',
|
||||||
|
'',
|
||||||
|
'"Therefore, there is now no condemnation for those who are in Christ Jesus." (Romans 8:1)',
|
||||||
|
'You are no longer a defendant. You are a child of the Judge.',
|
||||||
|
'',
|
||||||
|
'WHAT TO DO NEXT',
|
||||||
|
...steps.map(([h, b], i) => `${i + 1}. ${h} ${b}`),
|
||||||
|
'',
|
||||||
|
`A good path through the podcast and studies: ${base}/start-here`,
|
||||||
|
`Questions? Ask here: ${base}/contact?source=salvation`,
|
||||||
|
'',
|
||||||
|
'Grace and peace,',
|
||||||
|
'Verse by Verse with Nate',
|
||||||
|
'',
|
||||||
|
`You are receiving this one-time email because this address was entered on ${base}/salvation. If that was not you, you can safely ignore it.`,
|
||||||
|
].join('\n')
|
||||||
|
|
||||||
|
const stepRows = steps
|
||||||
|
.map(([h, b], i) =>
|
||||||
|
`<tr><td valign="top" style="width:34px;padding:0 0 14px;"><div style="width:26px;height:26px;border-radius:13px;background:#c8860a;color:#111;font-family:Arial,sans-serif;font-size:13px;font-weight:700;line-height:26px;text-align:center;">${i + 1}</div></td>` +
|
||||||
|
`<td style="padding:2px 0 14px;font-family:Arial,sans-serif;font-size:15px;line-height:1.55;color:#201a10;"><strong>${escapeHtml(h)}</strong> ${escapeHtml(b)}</td></tr>`)
|
||||||
|
.join('')
|
||||||
|
|
||||||
|
const html = `<!doctype html><html><body style="margin:0;padding:0;background:#f5f1e8;">
|
||||||
|
<table width="100%" cellpadding="0" cellspacing="0" border="0" role="presentation" style="background:#f5f1e8;"><tr><td align="center" style="padding:28px 14px;">
|
||||||
|
<table width="100%" cellpadding="0" cellspacing="0" border="0" role="presentation" style="max-width:600px;background:#ffffff;border:1px solid #e1d3b2;border-radius:14px;overflow:hidden;">
|
||||||
|
<tr><td style="background:#111111;padding:30px 28px 26px;text-align:center;border-bottom:4px solid #c8860a;">
|
||||||
|
<div style="font-family:Arial,sans-serif;font-size:12px;letter-spacing:0.34em;text-transform:uppercase;color:#c8860a;">Verse by Verse with Nate</div>
|
||||||
|
<div style="width:54px;height:54px;border-radius:27px;background:#c8860a;color:#111111;font-family:Arial,sans-serif;font-size:30px;font-weight:700;line-height:54px;margin:16px auto 10px;">✓</div>
|
||||||
|
<h1 style="margin:0;font-family:Georgia,serif;font-size:28px;line-height:1.25;color:#f4ead5;">Your message was received</h1>
|
||||||
|
<p style="margin:10px 0 0;font-family:Georgia,serif;font-style:italic;font-size:17px;color:#d9c9a3;">Welcome to the family of God.</p>
|
||||||
|
</td></tr>
|
||||||
|
<tr><td style="padding:30px 28px 6px;">
|
||||||
|
<p style="margin:0 0 16px;font-family:Georgia,serif;font-size:18px;line-height:1.6;color:#201a10;">${escapeHtml(greeting)}</p>
|
||||||
|
<p style="margin:0 0 16px;font-family:Georgia,serif;font-size:17px;line-height:1.7;color:#201a10;">Thank you for letting us know that you prayed to receive Jesus. We are rejoicing with you, and your message has been received.</p>
|
||||||
|
<p style="margin:0 0 22px;font-family:Georgia,serif;font-size:17px;line-height:1.7;color:#201a10;"><strong>Someone from our team will reach out to you personally soon.</strong></p>
|
||||||
|
</td></tr>
|
||||||
|
<tr><td style="padding:0 28px 26px;">
|
||||||
|
<div style="background:#fbf7ef;border-left:4px solid #c8860a;border-radius:4px;padding:18px 20px;">
|
||||||
|
<p style="margin:0 0 8px;font-family:Georgia,serif;font-style:italic;font-size:17px;line-height:1.6;color:#201a10;">“Therefore, there is now no condemnation for those who are in Christ Jesus.” <span style="font-style:normal;font-size:13px;color:#8a6d35;">Romans 8:1</span></p>
|
||||||
|
<p style="margin:0;font-family:Georgia,serif;font-size:15px;line-height:1.6;color:#57452b;">You are no longer a defendant. You are a child of the Judge.</p>
|
||||||
|
</div>
|
||||||
|
</td></tr>
|
||||||
|
<tr><td style="padding:0 28px 8px;">
|
||||||
|
<div style="font-family:Arial,sans-serif;font-size:12px;font-weight:700;letter-spacing:0.14em;text-transform:uppercase;color:#8a6d35;margin:0 0 14px;">What to do next</div>
|
||||||
|
<table width="100%" cellpadding="0" cellspacing="0" border="0" role="presentation">${stepRows}</table>
|
||||||
|
</td></tr>
|
||||||
|
<tr><td align="center" style="padding:6px 28px 8px;">
|
||||||
|
<a href="${escapeHtml(base)}/start-here" style="display:inline-block;background:#c8860a;color:#111111;font-family:Arial,sans-serif;font-size:14px;font-weight:700;letter-spacing:0.1em;text-transform:uppercase;text-decoration:none;padding:14px 28px;border-radius:4px;">Start Here</a>
|
||||||
|
</td></tr>
|
||||||
|
<tr><td align="center" style="padding:6px 28px 26px;font-family:Arial,sans-serif;font-size:14px;color:#57452b;">
|
||||||
|
Have a question? <a href="${escapeHtml(base)}/contact?source=salvation" style="color:#8f5f05;">Ask us here</a>, or just reply to this email.
|
||||||
|
</td></tr>
|
||||||
|
<tr><td style="padding:0 28px 28px;">
|
||||||
|
<p style="margin:0;font-family:Georgia,serif;font-size:16px;line-height:1.6;color:#201a10;">Grace and peace,<br><strong>Verse by Verse with Nate</strong></p>
|
||||||
|
</td></tr>
|
||||||
|
<tr><td style="background:#f7f2e5;border-top:1px solid #e8dcc1;padding:16px 28px;">
|
||||||
|
<p style="margin:0;font-family:Arial,sans-serif;font-size:12px;line-height:1.6;color:#735a2b;">You are receiving this one-time email because this address was entered at ${escapeHtml(base)}/salvation. If that was not you, you can safely ignore it.</p>
|
||||||
|
</td></tr>
|
||||||
|
</table>
|
||||||
|
</td></tr></table></body></html>`
|
||||||
|
|
||||||
|
return { subject, text, html }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function register(app) {
|
||||||
|
// The /salvation page is static HTML, so it asks the server for the narration URLs set in Admin → Gospel Page.
|
||||||
|
app.get('/api/salvation-audio', (_req, res) => {
|
||||||
|
const c = state.cachedSiteContent ?? {}
|
||||||
|
res.set('Cache-Control', 'public, max-age=300')
|
||||||
|
res.json({
|
||||||
|
url: sanitizeUrl(c.salvationAudioUrl) || '',
|
||||||
|
guiltyUrl: sanitizeUrl(c.salvationAudioGuiltyUrl) || '',
|
||||||
|
notGuiltyUrl: sanitizeUrl(c.salvationAudioNotGuiltyUrl) || '',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
app.post('/api/salvation-response', rateLimit, async (req, res) => {
|
||||||
|
const { name, email, message, _honey } = req.body ?? {}
|
||||||
|
if (_honey) { res.json({ ok: true }); return }
|
||||||
|
|
||||||
|
const safeName = clean(name, 100)
|
||||||
|
const safeEmail = clean(email, 200)
|
||||||
|
const safeMessage = typeof message === 'string' ? message.trim().slice(0, 2000) : ''
|
||||||
|
if (safeEmail && !/^[a-zA-Z0-9._%+\-]{1,64}@[a-zA-Z0-9.\-]{1,253}\.[a-zA-Z]{2,}$/.test(safeEmail)) {
|
||||||
|
res.status(400).json({ message: 'That email address does not look right. You can also leave it blank.' })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!process.env.RESEND_API_KEY) {
|
||||||
|
console.error('[salvation] RESEND_API_KEY env var not set')
|
||||||
|
res.status(503).json({ message: 'We could not send this right now.' })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const when = new Date().toLocaleString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: 'numeric', minute: '2-digit', timeZone: 'America/New_York', timeZoneName: 'short' })
|
||||||
|
const { subject, text, html } = buildSalvationEmail({ name: safeName, email: safeEmail, message: safeMessage, when })
|
||||||
|
|
||||||
|
try {
|
||||||
|
const resend = new Resend(process.env.RESEND_API_KEY)
|
||||||
|
await sendResendEmailWithRetry({
|
||||||
|
resend,
|
||||||
|
context: 'salvation-response',
|
||||||
|
payload: {
|
||||||
|
from: getResendFromAddress(),
|
||||||
|
to: [getResendInboxAddress()],
|
||||||
|
...(safeEmail ? { replyTo: safeEmail } : {}),
|
||||||
|
subject,
|
||||||
|
tags: [{ name: 'flow', value: 'salvation-response' }],
|
||||||
|
text,
|
||||||
|
html,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// Best effort: a failed or skipped confirmation must never turn a delivered decision into an error.
|
||||||
|
let confirmationSent = false
|
||||||
|
if (safeEmail && mayConfirm(safeEmail)) {
|
||||||
|
try {
|
||||||
|
const confirmation = buildSalvationConfirmationEmail({ name: safeName })
|
||||||
|
await sendResendEmailWithRetry({
|
||||||
|
resend,
|
||||||
|
context: 'salvation-confirmation',
|
||||||
|
payload: {
|
||||||
|
from: getResendFromAddress(),
|
||||||
|
to: [safeEmail],
|
||||||
|
replyTo: getResendReplyToAddress(),
|
||||||
|
subject: confirmation.subject,
|
||||||
|
tags: [{ name: 'flow', value: 'salvation-confirmation' }],
|
||||||
|
text: confirmation.text,
|
||||||
|
html: confirmation.html,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
confirmationSent = true
|
||||||
|
} catch (confirmErr) {
|
||||||
|
console.error('[salvation] confirmation email failed:', confirmErr?.message ?? confirmErr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
res.json({ ok: true, confirmationSent })
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[salvation] email failed:', err?.message ?? err)
|
||||||
|
res.status(502).json({ message: 'We could not send this right now.' })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { noteEntriesToText } from '../../shared/note-format.js'
|
||||||
import { randomUUID, timingSafeEqual } from 'node:crypto'
|
import { randomUUID, timingSafeEqual } from 'node:crypto'
|
||||||
import rateLimit from 'express-rate-limit'
|
import rateLimit from 'express-rate-limit'
|
||||||
import { Document, Packer, Paragraph, HeadingLevel, TextRun } from 'docx'
|
import { Document, Packer, Paragraph, HeadingLevel, TextRun } from 'docx'
|
||||||
@@ -87,7 +88,7 @@ export function register(app) {
|
|||||||
const sectionId = dashIndex >= 0 ? noteKey.slice(dashIndex + 2) : noteKey
|
const sectionId = dashIndex >= 0 ? noteKey.slice(dashIndex + 2) : noteKey
|
||||||
if (!studyEntries[studySlug]) studyEntries[studySlug] = {}
|
if (!studyEntries[studySlug]) studyEntries[studySlug] = {}
|
||||||
studyEntries[studySlug][sectionId] = studyEntries[studySlug][sectionId] || {}
|
studyEntries[studySlug][sectionId] = studyEntries[studySlug][sectionId] || {}
|
||||||
studyEntries[studySlug][sectionId].noteText = noteText.trim()
|
studyEntries[studySlug][sectionId].noteText = noteEntriesToText(noteText) || noteText.trim()
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const [studySlug, studyProgress] of Object.entries(progress.byStudy)) {
|
for (const [studySlug, studyProgress] of Object.entries(progress.byStudy)) {
|
||||||
|
|||||||
@@ -117,7 +117,8 @@ export function register(app) {
|
|||||||
passwordHash: hashStudyPassword(password),
|
passwordHash: hashStudyPassword(password),
|
||||||
displayName,
|
displayName,
|
||||||
subscribeNewsletter: subscribe,
|
subscribeNewsletter: subscribe,
|
||||||
studyRemindersEnabled: false,
|
studyRemindersEnabled: true,
|
||||||
|
remindersDefaultedAt: now,
|
||||||
pendingEmailChange: null,
|
pendingEmailChange: null,
|
||||||
emailVerified: false,
|
emailVerified: false,
|
||||||
pendingEmailVerification: {
|
pendingEmailVerification: {
|
||||||
|
|||||||
@@ -147,7 +147,11 @@ export function register(app) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
const rawNote = typeof req.body?.note === 'string' ? req.body.note : ''
|
const rawNote = typeof req.body?.note === 'string' ? req.body.note : ''
|
||||||
const note = rawNote.trim().slice(0, MAX_STUDY_NOTE_LENGTH)
|
const note = rawNote.trim()
|
||||||
|
if (note.length > MAX_STUDY_NOTE_LENGTH) {
|
||||||
|
res.status(413).json({ message: 'This lesson\'s notes are too long to save. Please trim some text.' })
|
||||||
|
return
|
||||||
|
}
|
||||||
const notes = await loadUserNotes(user.id)
|
const notes = await loadUserNotes(user.id)
|
||||||
|
|
||||||
if (!note) {
|
if (!note) {
|
||||||
|
|||||||
@@ -96,6 +96,9 @@ export const state = {
|
|||||||
// newsletterIssues: Array<{ id, resendBroadcastId, slug, title, subject, description, html, sentAt, publishedAt, public }>
|
// newsletterIssues: Array<{ id, resendBroadcastId, slug, title, subject, description, html, sentAt, publishedAt, public }>
|
||||||
newsletterIssues: [],
|
newsletterIssues: [],
|
||||||
newsletterIssuesWritePromise: Promise.resolve(),
|
newsletterIssuesWritePromise: Promise.resolve(),
|
||||||
|
// nuggetsEpisodeTags: { [audioUrl]: string[] } — admin-assigned tags for Nuggets RSS episodes
|
||||||
|
nuggetsEpisodeTags: {},
|
||||||
|
nuggetsEpisodeTagsWritePromise: Promise.resolve(),
|
||||||
|
|
||||||
|
|
||||||
auditLog: [],
|
auditLog: [],
|
||||||
|
|||||||
@@ -476,6 +476,21 @@ export function normalizeHitPath(pathname) {
|
|||||||
return pathname
|
return pathname
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Top-level URL segments the SPA / static pages actually serve. Anything else is a probe or
|
||||||
|
// scanner hit, which must not count as a real visit or add a new key to the per-path stats.
|
||||||
|
const KNOWN_SITE_SEGMENTS = new Set([
|
||||||
|
'start-here', 'study', 'finished', 'episodes', 'nuggets', 'resources', 'downloads', 'about', 'contact',
|
||||||
|
'questions', 'newsletter', 'scripture', 'thanks', 'subscribe', 'certificate', 'host', 'admin', 'preview',
|
||||||
|
'privacy', 'terms', 'salvation', 'qr',
|
||||||
|
])
|
||||||
|
|
||||||
|
const MAX_UNKNOWN_PATHS = 300
|
||||||
|
|
||||||
|
export function isKnownSitePath(pathname) {
|
||||||
|
const first = String(pathname ?? '/').split('/')[1] ?? ''
|
||||||
|
return first === '' || KNOWN_SITE_SEGMENTS.has(first)
|
||||||
|
}
|
||||||
|
|
||||||
export function shouldCountHit(req) {
|
export function shouldCountHit(req) {
|
||||||
if (req.method !== 'GET') return false
|
if (req.method !== 'GET') return false
|
||||||
if (req.path.startsWith('/api/')) return false
|
if (req.path.startsWith('/api/')) return false
|
||||||
@@ -580,6 +595,21 @@ export function recordHit(pathname, isBot = false, botReason = null) {
|
|||||||
state.hitStats.lastHitAt = nowIso
|
state.hitStats.lastHitAt = nowIso
|
||||||
state.hitStats.firstHitAt = state.hitStats.firstHitAt ?? nowIso
|
state.hitStats.firstHitAt = state.hitStats.firstHitAt ?? nowIso
|
||||||
|
|
||||||
|
if (isBot && botReason === 'unknown-path') {
|
||||||
|
// Probe/scanner URLs: keep a bounded list for the admin view instead of one stats key per URL
|
||||||
|
const unknown = (state.hitStats.byPathUnknown ??= {})
|
||||||
|
const key = safePath.slice(0, 120)
|
||||||
|
if (key in unknown || Object.keys(unknown).length < MAX_UNKNOWN_PATHS) unknown[key] = (unknown[key] ?? 0) + 1
|
||||||
|
else unknown['(other)'] = (unknown['(other)'] ?? 0) + 1
|
||||||
|
state.hitStats.botHits += 1
|
||||||
|
state.hitStats.byPathBot['(unknown)'] = (state.hitStats.byPathBot['(unknown)'] ?? 0) + 1
|
||||||
|
state.hitStats.byDayBot[dayKey] = (state.hitStats.byDayBot[dayKey] ?? 0) + 1
|
||||||
|
state.hitStats.botReasons[botReason] = (state.hitStats.botReasons[botReason] ?? 0) + 1
|
||||||
|
state.hitStats.byPath['(unknown)'] = (state.hitStats.byPath['(unknown)'] ?? 0) + 1
|
||||||
|
state.hitStats.byDay[dayKey] = (state.hitStats.byDay[dayKey] ?? 0) + 1
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
if (isBot) {
|
if (isBot) {
|
||||||
state.hitStats.botHits += 1
|
state.hitStats.botHits += 1
|
||||||
state.hitStats.byPathBot[safePath] = (state.hitStats.byPathBot[safePath] ?? 0) + 1
|
state.hitStats.byPathBot[safePath] = (state.hitStats.byPathBot[safePath] ?? 0) + 1
|
||||||
@@ -706,6 +736,23 @@ export function extractResendMessageId(result) {
|
|||||||
return ''
|
return ''
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// One-off pass: lesson reminders are now on by default, so switch them on for accounts that
|
||||||
|
// predate the default. Each account is marked as it is handled, so a later opt-out sticks.
|
||||||
|
export async function backfillReminderDefault() {
|
||||||
|
const now = new Date().toISOString()
|
||||||
|
let updated = 0
|
||||||
|
for (const user of state.studyUsers) {
|
||||||
|
if (user.remindersDefaultedAt) continue
|
||||||
|
if (user.studyRemindersEnabled !== true) {
|
||||||
|
user.studyRemindersEnabled = true
|
||||||
|
updated++
|
||||||
|
}
|
||||||
|
user.remindersDefaultedAt = now
|
||||||
|
}
|
||||||
|
if (state.studyUsers.some(user => user.remindersDefaultedAt === now)) queueStudyUsersWrite()
|
||||||
|
return updated
|
||||||
|
}
|
||||||
|
|
||||||
// ── Study reminder scheduler ───────────────────────────────────────────────
|
// ── Study reminder scheduler ───────────────────────────────────────────────
|
||||||
|
|
||||||
export async function scheduleStudyReminders(sendStudyReminderEmail) {
|
export async function scheduleStudyReminders(sendStudyReminderEmail) {
|
||||||
|
|||||||
+32
-1
@@ -67,7 +67,7 @@ export const BIBLE_BOOKS = [
|
|||||||
{ id: 'TH2', name: '2 Thessalonians', aliases: ['2 thess'] },
|
{ id: 'TH2', name: '2 Thessalonians', aliases: ['2 thess'] },
|
||||||
{ id: 'TI1', name: '1 Timothy', aliases: ['1 tim'] },
|
{ id: 'TI1', name: '1 Timothy', aliases: ['1 tim'] },
|
||||||
{ id: 'TI2', name: '2 Timothy', aliases: ['2 tim'] },
|
{ id: 'TI2', name: '2 Timothy', aliases: ['2 tim'] },
|
||||||
{ id: 'TIT', name: 'Titus' },
|
{ id: 'TIT', name: 'Titus', aliases: ['tit'] },
|
||||||
{ id: 'PHM', name: 'Philemon', aliases: ['philem'] },
|
{ id: 'PHM', name: 'Philemon', aliases: ['philem'] },
|
||||||
{ id: 'HEB', name: 'Hebrews', aliases: ['heb'] },
|
{ id: 'HEB', name: 'Hebrews', aliases: ['heb'] },
|
||||||
{ id: 'JAM', name: 'James', aliases: ['jas'] },
|
{ id: 'JAM', name: 'James', aliases: ['jas'] },
|
||||||
@@ -85,3 +85,34 @@ export function bookNumberFor(usfmId) {
|
|||||||
const index = BIBLE_BOOKS.findIndex(b => b.id === usfmId)
|
const index = BIBLE_BOOKS.findIndex(b => b.id === usfmId)
|
||||||
return index === -1 ? null : index + 1
|
return index === -1 ? null : index + 1
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let referenceBookLookup = null
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks a passage reference the way the Scripture Index and passage fetch read it.
|
||||||
|
* `bookHint` is the study's Bible Book field (or slug) and is used when the reference
|
||||||
|
* has no book of its own ("1:1-2"). Returns null when it will work, otherwise a short
|
||||||
|
* message explaining what to change.
|
||||||
|
*/
|
||||||
|
export function checkPassageReference(reference, bookHint) {
|
||||||
|
if (!referenceBookLookup) {
|
||||||
|
referenceBookLookup = new Set()
|
||||||
|
for (const b of BIBLE_BOOKS) {
|
||||||
|
for (const key of [b.name.toLowerCase(), ...(b.aliases ?? [])]) {
|
||||||
|
referenceBookLookup.add(key)
|
||||||
|
referenceBookLookup.add(key.replace(/\s+/g, ''))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const clean = String(reference ?? '').replace(/[–—]/g, '-').replace(/(\d)[a-z]\b/gi, '$1').trim()
|
||||||
|
if (!clean) return null
|
||||||
|
const m = clean.match(/^(?:(.*?)\s+)?(\d+):(\d+)(?:-(?:(\d+):)?(\d+))?$/)
|
||||||
|
if (!m) return 'Use the form 1:1-2 (chapter:verse, optional range). It will be listed under "Other references" in the Scripture Index until fixed.'
|
||||||
|
const book = (m[1] ?? String(bookHint ?? '')).toLowerCase().replace(/\.\s*/g, ' ').trim()
|
||||||
|
if (!book || !referenceBookLookup.has(book)) {
|
||||||
|
return m[1]
|
||||||
|
? `"${m[1]}" is not a recognized Bible book name.`
|
||||||
|
: 'Set this study\'s "Bible Book" field (e.g. titus) so this reference can be matched to a book.'
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
Vendored
+14
@@ -0,0 +1,14 @@
|
|||||||
|
export type NoteAnchorId = 'scripture' | 'commentary' | 'questions' | 'general'
|
||||||
|
export interface NoteEntry {
|
||||||
|
id: string
|
||||||
|
anchor: NoteAnchorId
|
||||||
|
html: string
|
||||||
|
updatedAt: string | null
|
||||||
|
}
|
||||||
|
export const NOTE_ANCHORS: NoteAnchorId[]
|
||||||
|
export const NOTE_ANCHOR_LABELS: Record<NoteAnchorId, string>
|
||||||
|
export function newNoteId(): string
|
||||||
|
export function parseNoteEntries(raw: string): NoteEntry[]
|
||||||
|
export function serializeNoteEntries(entries: NoteEntry[]): string
|
||||||
|
export function noteHtmlToText(html: string): string
|
||||||
|
export function noteEntriesToText(raw: string): string
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
// Lesson note storage format, shared by the client and the server.
|
||||||
|
//
|
||||||
|
// Each lesson's notes are stored as one string. Current format (v2):
|
||||||
|
// {"v":2,"entries":[{"id","anchor","html","updatedAt"}]}
|
||||||
|
// Legacy format (v1) was a JSON object of { anchor: html }, and older still was
|
||||||
|
// plain text. Both are still read and are upgraded to v2 on the next save.
|
||||||
|
|
||||||
|
export const NOTE_ANCHORS = ['scripture', 'commentary', 'questions', 'general']
|
||||||
|
|
||||||
|
export const NOTE_ANCHOR_LABELS = {
|
||||||
|
scripture: 'Scripture Text',
|
||||||
|
commentary: 'Commentary',
|
||||||
|
questions: 'Reflection Questions',
|
||||||
|
general: 'General Notes',
|
||||||
|
}
|
||||||
|
|
||||||
|
export function newNoteId() {
|
||||||
|
return `n${Date.now().toString(36)}${Math.random().toString(36).slice(2, 7)}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseNoteEntries(raw) {
|
||||||
|
if (typeof raw !== 'string' || !raw.trim()) return []
|
||||||
|
let parsed = null
|
||||||
|
try {
|
||||||
|
parsed = JSON.parse(raw)
|
||||||
|
} catch {
|
||||||
|
// Legacy plain-text note.
|
||||||
|
return [{ id: newNoteId(), anchor: 'general', html: raw, updatedAt: null }]
|
||||||
|
}
|
||||||
|
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
||||||
|
return [{ id: newNoteId(), anchor: 'general', html: raw, updatedAt: null }]
|
||||||
|
}
|
||||||
|
if (parsed.v === 2 && Array.isArray(parsed.entries)) {
|
||||||
|
return parsed.entries
|
||||||
|
.filter(e => e && typeof e.html === 'string' && e.html.trim())
|
||||||
|
.map(e => ({
|
||||||
|
id: typeof e.id === 'string' && e.id ? e.id : newNoteId(),
|
||||||
|
anchor: NOTE_ANCHORS.includes(e.anchor) ? e.anchor : 'general',
|
||||||
|
html: e.html,
|
||||||
|
updatedAt: typeof e.updatedAt === 'string' ? e.updatedAt : null,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
return Object.entries(parsed)
|
||||||
|
.filter(([, html]) => typeof html === 'string' && html.trim())
|
||||||
|
.map(([anchor, html]) => ({
|
||||||
|
id: `legacy-${anchor}`,
|
||||||
|
anchor: NOTE_ANCHORS.includes(anchor) ? anchor : 'general',
|
||||||
|
html,
|
||||||
|
updatedAt: null,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
export function serializeNoteEntries(entries) {
|
||||||
|
const kept = entries.filter(e => e.html && e.html.trim())
|
||||||
|
if (kept.length === 0) return ''
|
||||||
|
return JSON.stringify({ v: 2, entries: kept })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function noteHtmlToText(html) {
|
||||||
|
return String(html)
|
||||||
|
.replace(/<\/(p|li|h[1-6]|blockquote)>/gi, '\n')
|
||||||
|
.replace(/<br\s*\/?>/gi, '\n')
|
||||||
|
.replace(/<[^>]*>/g, '')
|
||||||
|
.replace(/ /g, ' ')
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>')
|
||||||
|
.replace(/"/g, '"')
|
||||||
|
.replace(/'/g, "'")
|
||||||
|
.replace(/&/g, '&')
|
||||||
|
.replace(/\n{3,}/g, '\n\n')
|
||||||
|
.trim()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Plain-text rendering of a whole lesson's notes (used by the Word export).
|
||||||
|
export function noteEntriesToText(raw) {
|
||||||
|
return parseNoteEntries(raw)
|
||||||
|
.map(e => `${NOTE_ANCHOR_LABELS[e.anchor]}\n${noteHtmlToText(e.html)}`)
|
||||||
|
.join('\n\n')
|
||||||
|
}
|
||||||
+206
-3
@@ -1,3 +1,4 @@
|
|||||||
|
import { checkPassageReference } from '../shared/bible-books.js'
|
||||||
import DOMPurify from 'dompurify'
|
import DOMPurify from 'dompurify'
|
||||||
import React, { useEffect, useRef, useState } from 'react'
|
import React, { useEffect, useRef, useState } from 'react'
|
||||||
import { DndContext, closestCenter, PointerSensor, useSensor, useSensors } from '@dnd-kit/core'
|
import { DndContext, closestCenter, PointerSensor, useSensor, useSensors } from '@dnd-kit/core'
|
||||||
@@ -616,6 +617,8 @@ export interface AdminStats {
|
|||||||
topPaths: Array<{ path: string; hits: number }>
|
topPaths: Array<{ path: string; hits: number }>
|
||||||
topPathsReal: Array<{ path: string; hits: number }>
|
topPathsReal: Array<{ path: string; hits: number }>
|
||||||
topPathsBot: Array<{ path: string; hits: number }>
|
topPathsBot: Array<{ path: string; hits: number }>
|
||||||
|
topUnknownPaths?: Array<{ path: string; hits: number }>
|
||||||
|
uniqueVisitors7d?: number
|
||||||
last7Days: Array<{ day: string; hits: number }>
|
last7Days: Array<{ day: string; hits: number }>
|
||||||
last7DaysReal: Array<{ day: string; hits: number }>
|
last7DaysReal: Array<{ day: string; hits: number }>
|
||||||
last7DaysBot: Array<{ day: string; hits: number }>
|
last7DaysBot: Array<{ day: string; hits: number }>
|
||||||
@@ -736,11 +739,11 @@ type StringField = Exclude<keyof SiteContent, 'customLinks' | 'customBlocks' | '
|
|||||||
type AdminView =
|
type AdminView =
|
||||||
| 'dashboard'
|
| 'dashboard'
|
||||||
| 'homepage:hero' | 'homepage:share' | 'homepage:prism' | 'homepage:where-to-next'
|
| 'homepage:hero' | 'homepage:share' | 'homepage:prism' | 'homepage:where-to-next'
|
||||||
| 'start-here'
|
| 'start-here' | 'salvation'
|
||||||
| 'about:show-copy' | 'about:bio' | 'about:testimonials'
|
| 'about:show-copy' | 'about:bio' | 'about:testimonials'
|
||||||
| 'contact:profile' | 'contact:copy'
|
| 'contact:profile' | 'contact:copy'
|
||||||
| 'podcast:current-series' | 'podcast:highlights' | 'podcast:finished-books' | 'podcast:scripts' | 'podcast:workflow' | 'podcast:season-check' | 'podcast:rss'
|
| 'podcast:current-series' | 'podcast:highlights' | 'podcast:finished-books' | 'podcast:scripts' | 'podcast:workflow' | 'podcast:season-check' | 'podcast:rss'
|
||||||
| 'nuggets:settings' | 'nuggets:hosts' | 'nuggets:upload-portal' | 'nuggets:announcement' | 'nuggets:guidelines' | 'nuggets:history' | 'nuggets:workflow'
|
| 'nuggets:settings' | 'nuggets:hosts' | 'nuggets:upload-portal' | 'nuggets:announcement' | 'nuggets:guidelines' | 'nuggets:history' | 'nuggets:workflow' | 'nuggets:tags'
|
||||||
| 'downloads' | 'custom-links' | 'content-blocks' | 'books' | 'recommended-resources'
|
| 'downloads' | 'custom-links' | 'content-blocks' | 'books' | 'recommended-resources'
|
||||||
| 'inbox'
|
| 'inbox'
|
||||||
| 'questions' | 'study-comments' | 'analytics' | 'assets' | 'colossians-study' | 'qr-codes'
|
| 'questions' | 'study-comments' | 'analytics' | 'assets' | 'colossians-study' | 'qr-codes'
|
||||||
@@ -772,6 +775,7 @@ const ADMIN_NAV: NavGroup[] = [
|
|||||||
{ kind: 'leaf', view: 'homepage:where-to-next', label: 'Where to Next' },
|
{ kind: 'leaf', view: 'homepage:where-to-next', label: 'Where to Next' },
|
||||||
]},
|
]},
|
||||||
{ kind: 'leaf', view: 'start-here', label: 'Start Here' },
|
{ kind: 'leaf', view: 'start-here', label: 'Start Here' },
|
||||||
|
{ kind: 'leaf', view: 'salvation', label: 'Gospel Page' },
|
||||||
{ kind: 'parent', id: 'about', label: 'About', children: [
|
{ kind: 'parent', id: 'about', label: 'About', children: [
|
||||||
{ kind: 'leaf', view: 'about:show-copy', label: 'Show Copy' },
|
{ kind: 'leaf', view: 'about:show-copy', label: 'Show Copy' },
|
||||||
{ kind: 'leaf', view: 'about:bio', label: 'Nate Bio' },
|
{ kind: 'leaf', view: 'about:bio', label: 'Nate Bio' },
|
||||||
@@ -802,6 +806,7 @@ const ADMIN_NAV: NavGroup[] = [
|
|||||||
{ kind: 'leaf', view: 'nuggets:announcement', label: 'Announcement' },
|
{ kind: 'leaf', view: 'nuggets:announcement', label: 'Announcement' },
|
||||||
{ kind: 'leaf', view: 'nuggets:guidelines', label: 'Recording Guidelines' },
|
{ kind: 'leaf', view: 'nuggets:guidelines', label: 'Recording Guidelines' },
|
||||||
{ kind: 'leaf', view: 'nuggets:workflow', label: 'Episode Workflow' },
|
{ kind: 'leaf', view: 'nuggets:workflow', label: 'Episode Workflow' },
|
||||||
|
{ kind: 'leaf', view: 'nuggets:tags', label: 'Episode Tags' },
|
||||||
{ kind: 'leaf', view: 'nuggets:history', label: 'Upload History' },
|
{ kind: 'leaf', view: 'nuggets:history', label: 'Upload History' },
|
||||||
]},
|
]},
|
||||||
{ kind: 'leaf', view: 'colossians-study', label: 'Studies' },
|
{ kind: 'leaf', view: 'colossians-study', label: 'Studies' },
|
||||||
@@ -879,6 +884,7 @@ const ADMIN_SECTION_LINKS: Partial<Record<AdminView, AdminSectionLink[]>> = {
|
|||||||
{ id: 'global-header', label: 'Header' },
|
{ id: 'global-header', label: 'Header' },
|
||||||
{ id: 'global-platforms', label: 'Platform URLs' },
|
{ id: 'global-platforms', label: 'Platform URLs' },
|
||||||
{ id: 'global-banner', label: 'Analytics Banner' },
|
{ id: 'global-banner', label: 'Analytics Banner' },
|
||||||
|
{ id: 'global-verse', label: 'Verse of the Week' },
|
||||||
{ id: 'global-welcome-email', label: 'Welcome Email' },
|
{ id: 'global-welcome-email', label: 'Welcome Email' },
|
||||||
],
|
],
|
||||||
'start-here': [
|
'start-here': [
|
||||||
@@ -1022,6 +1028,7 @@ const FIELDS: Array<{ key: StringField; label: string; multiline?: boolean; sect
|
|||||||
{ key: 'platformCreatorUrl', label: 'Platform — Creator Profile URL', section: 'global' },
|
{ key: 'platformCreatorUrl', label: 'Platform — Creator Profile URL', section: 'global' },
|
||||||
{ key: 'platformKofiUrl', label: 'Platform — Ko-fi URL', section: 'global' },
|
{ key: 'platformKofiUrl', label: 'Platform — Ko-fi URL', section: 'global' },
|
||||||
{ key: 'platformKofiQrUrl', label: 'Platform — Ko-fi QR Code Image URL', section: 'global' },
|
{ key: 'platformKofiQrUrl', label: 'Platform — Ko-fi QR Code Image URL', section: 'global' },
|
||||||
|
{ key: 'verseOfTheWeek', label: 'Scripture Index — Verse of the Week (optional)', section: 'global' },
|
||||||
{ key: 'welcomeEmailSubject', label: 'Welcome Email — Subject', section: 'global' },
|
{ key: 'welcomeEmailSubject', label: 'Welcome Email — Subject', section: 'global' },
|
||||||
{ key: 'welcomeEmailGreetingPrefix', label: 'Welcome Email — Greeting Prefix', section: 'global' },
|
{ key: 'welcomeEmailGreetingPrefix', label: 'Welcome Email — Greeting Prefix', section: 'global' },
|
||||||
{ key: 'welcomeEmailIntro', label: 'Welcome Email — Intro Paragraph', multiline: true, section: 'global' },
|
{ key: 'welcomeEmailIntro', label: 'Welcome Email — Intro Paragraph', multiline: true, section: 'global' },
|
||||||
@@ -1627,6 +1634,115 @@ function NuggetsHistoryAdmin() {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Nuggets Episode Tags admin ─────────────────────────────────────────────
|
||||||
|
interface NuggetsTagEpisode {
|
||||||
|
title: string
|
||||||
|
pubDate: string
|
||||||
|
audioUrl: string
|
||||||
|
episode: string
|
||||||
|
tags: string[]
|
||||||
|
}
|
||||||
|
|
||||||
|
function NuggetsTagsAdmin() {
|
||||||
|
const [episodes, setEpisodes] = useState<NuggetsTagEpisode[]>([])
|
||||||
|
const [loading, setLoading] = useState(true)
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
const [drafts, setDrafts] = useState<Record<string, string>>({})
|
||||||
|
const [filter, setFilter] = useState('')
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetch('/api/admin/nuggets/episode-tags')
|
||||||
|
.then(r => r.ok ? r.json() : Promise.reject(r.status))
|
||||||
|
.then(d => setEpisodes(Array.isArray(d.episodes) ? d.episodes : []))
|
||||||
|
.catch(() => setError('Could not load episodes. Check the RSS feed URL in Show Settings.'))
|
||||||
|
.finally(() => setLoading(false))
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const allTags = Array.from(new Set(episodes.flatMap(e => e.tags))).sort((a, b) => a.localeCompare(b))
|
||||||
|
|
||||||
|
async function saveTags(audioUrl: string, tags: string[]) {
|
||||||
|
const prev = episodes
|
||||||
|
setEpisodes(eps => eps.map(e => e.audioUrl === audioUrl ? { ...e, tags } : e))
|
||||||
|
try {
|
||||||
|
const r = await fetch('/api/admin/nuggets/episode-tags', {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ audioUrl, tags }),
|
||||||
|
})
|
||||||
|
if (!r.ok) throw new Error()
|
||||||
|
const d = await r.json()
|
||||||
|
setEpisodes(eps => eps.map(e => e.audioUrl === audioUrl ? { ...e, tags: d.tags ?? tags } : e))
|
||||||
|
} catch {
|
||||||
|
setEpisodes(prev)
|
||||||
|
setError('Could not save tags. Please try again.')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function addTags(ep: NuggetsTagEpisode) {
|
||||||
|
const raw = (drafts[ep.audioUrl] ?? '').split(',').map(t => t.trim()).filter(Boolean)
|
||||||
|
if (!raw.length) return
|
||||||
|
setDrafts(d => ({ ...d, [ep.audioUrl]: '' }))
|
||||||
|
saveTags(ep.audioUrl, [...ep.tags, ...raw.filter(t => !ep.tags.some(x => x.toLowerCase() === t.toLowerCase()))])
|
||||||
|
}
|
||||||
|
|
||||||
|
const visible = filter.trim()
|
||||||
|
? episodes.filter(e => `${e.title} ${e.tags.join(' ')}`.toLowerCase().includes(filter.toLowerCase()))
|
||||||
|
: episodes
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="admin-panel-section" aria-label="Nuggets episode tags">
|
||||||
|
<div className="admin-panel-head">
|
||||||
|
<h2>Nuggets — Episode Tags</h2>
|
||||||
|
<p>Tag episodes by topic or book. Visitors can filter the Nuggets page by these tags. Type a tag and press Enter (or separate several with commas).</p>
|
||||||
|
</div>
|
||||||
|
{error && <p className="admin-stats-note" role="alert">{error}</p>}
|
||||||
|
{loading ? <p className="admin-stats-note">Loading…</p> : (
|
||||||
|
<>
|
||||||
|
<datalist id="nuggets-tag-suggestions">
|
||||||
|
{allTags.map(t => <option key={t} value={t} />)}
|
||||||
|
</datalist>
|
||||||
|
{episodes.length > 0 && (
|
||||||
|
<div className="admin-field" style={{ maxWidth: 320, marginBottom: 12 }}>
|
||||||
|
<input type="text" placeholder="Filter by title or tag…" value={filter} onChange={e => setFilter(e.target.value)} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{visible.length === 0 ? (
|
||||||
|
<p className="admin-stats-note">{episodes.length === 0 ? 'No episodes found in the feed yet.' : 'No results match that filter.'}</p>
|
||||||
|
) : visible.map(ep => (
|
||||||
|
<div key={ep.audioUrl} style={{ padding: '10px 0', borderBottom: '1px solid var(--color-border, #e5e0d5)' }}>
|
||||||
|
<div style={{ fontWeight: 600, marginBottom: 6 }}>
|
||||||
|
{ep.episode ? `Ep. ${ep.episode} — ` : ''}{ep.title}
|
||||||
|
<span style={{ fontWeight: 400, opacity: 0.6, marginLeft: 8, fontSize: '0.8rem' }}>
|
||||||
|
{Number.isNaN(new Date(ep.pubDate).getTime()) ? '' : new Date(ep.pubDate).toLocaleDateString()}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, alignItems: 'center' }}>
|
||||||
|
{ep.tags.map(t => (
|
||||||
|
<span key={t} style={{ display: 'inline-flex', alignItems: 'center', gap: 4, background: 'rgba(201,168,76,0.15)', borderRadius: 999, padding: '2px 10px', fontSize: '0.82rem' }}>
|
||||||
|
{t}
|
||||||
|
<button type="button" aria-label={`Remove tag ${t}`} onClick={() => saveTags(ep.audioUrl, ep.tags.filter(x => x !== t))} style={{ border: 'none', background: 'none', cursor: 'pointer', padding: 0, fontSize: '1rem', lineHeight: 1 }}>×</button>
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
list="nuggets-tag-suggestions"
|
||||||
|
placeholder="Add tag…"
|
||||||
|
aria-label={`Add tag to ${ep.title}`}
|
||||||
|
value={drafts[ep.audioUrl] ?? ''}
|
||||||
|
onChange={e => setDrafts(d => ({ ...d, [ep.audioUrl]: e.target.value }))}
|
||||||
|
onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); addTags(ep) } }}
|
||||||
|
onBlur={() => addTags(ep)}
|
||||||
|
style={{ width: 160 }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
// ── Nuggets Episode Workflow admin ─────────────────────────────────────────
|
// ── Nuggets Episode Workflow admin ─────────────────────────────────────────
|
||||||
type WorkflowStepKey = 'listen' | 'coldOpen' | 'recordColdOpen' | 'edit' | 'spotify'
|
type WorkflowStepKey = 'listen' | 'coldOpen' | 'recordColdOpen' | 'edit' | 'spotify'
|
||||||
|
|
||||||
@@ -2311,6 +2427,13 @@ export default function AdminPage({ content, onSave, onLogout }: Props) {
|
|||||||
const [commentsLoaded, setCommentsLoaded] = useState(false)
|
const [commentsLoaded, setCommentsLoaded] = useState(false)
|
||||||
const [commentFilter, setCommentFilter] = useState<'all' | 'pending' | 'approved'>('all')
|
const [commentFilter, setCommentFilter] = useState<'all' | 'pending' | 'approved'>('all')
|
||||||
const [commentSearch, setCommentSearch] = useState('')
|
const [commentSearch, setCommentSearch] = useState('')
|
||||||
|
// Load moderation queue as soon as the section is opened; a failed load leaves the manual button available
|
||||||
|
const commentsAutoTried = useRef(false)
|
||||||
|
useEffect(() => {
|
||||||
|
if (adminView !== 'study-comments' || commentsLoaded || commentsAutoTried.current) return
|
||||||
|
commentsAutoTried.current = true
|
||||||
|
void loadStudyComments()
|
||||||
|
}, [adminView, commentsLoaded])
|
||||||
|
|
||||||
// Episode scripts state
|
// Episode scripts state
|
||||||
const [scriptsList, setScriptsList] = useState<Array<{ key: string; episodeNumber: string; title: string; filename: string; season: string | null; uploadedAt: string | null; wordCount: number }>>([])
|
const [scriptsList, setScriptsList] = useState<Array<{ key: string; episodeNumber: string; title: string; filename: string; season: string | null; uploadedAt: string | null; wordCount: number }>>([])
|
||||||
@@ -4019,7 +4142,7 @@ const [dashboardNow, setDashboardNow] = useState(() => new Date())
|
|||||||
<div className="admin-dashboard-card">
|
<div className="admin-dashboard-card">
|
||||||
<div className="admin-dashboard-card-value">{thisWeekReal.toLocaleString()}</div>
|
<div className="admin-dashboard-card-value">{thisWeekReal.toLocaleString()}</div>
|
||||||
<div className="admin-dashboard-card-label">Real Visits (7 Days)</div>
|
<div className="admin-dashboard-card-label">Real Visits (7 Days)</div>
|
||||||
<div className="admin-dashboard-card-sub">{thisWeekHits.toLocaleString()} total · {stats?.visitors?.uniqueVisitors?.toLocaleString() ?? '—'} unique all time</div>
|
<div className="admin-dashboard-card-sub">{thisWeekHits.toLocaleString()} total · {stats?.uniqueVisitors7d?.toLocaleString() ?? '—'} unique this week · {stats?.visitors?.uniqueVisitors?.toLocaleString() ?? '—'} all time (consented)</div>
|
||||||
<button type="button" className="admin-dashboard-card-action" onClick={() => navigateTo('analytics')}>Full Analytics →</button>
|
<button type="button" className="admin-dashboard-card-action" onClick={() => navigateTo('analytics')}>Full Analytics →</button>
|
||||||
</div>
|
</div>
|
||||||
<div className="admin-dashboard-card">
|
<div className="admin-dashboard-card">
|
||||||
@@ -5801,6 +5924,20 @@ const [dashboardNow, setDashboardNow] = useState(() => new Date())
|
|||||||
<h2>Books</h2>
|
<h2>Books</h2>
|
||||||
<p>Amazon books shown in the Reading List section on the Resources page. Add a cover image, description, and Amazon link for each book.</p>
|
<p>Amazon books shown in the Reading List section on the Resources page. Add a cover image, description, and Amazon link for each book.</p>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="admin-field" style={{ marginBottom: '1.25rem' }}>
|
||||||
|
<label htmlFor="gate-store-links" style={{ display: 'flex', gap: 8, alignItems: 'center', cursor: 'pointer' }}>
|
||||||
|
<input
|
||||||
|
id="gate-store-links"
|
||||||
|
type="checkbox"
|
||||||
|
checked={form.gateStoreLinks !== false}
|
||||||
|
onChange={e => setForm(f => ({ ...f, gateStoreLinks: e.target.checked }))}
|
||||||
|
/>
|
||||||
|
Ask for name and email before sending visitors to Amazon or Apple Books
|
||||||
|
</label>
|
||||||
|
<p className="admin-field-help">
|
||||||
|
Applies to the Amazon and Apple Books buttons on the Reading List and on the study guide and download pages. Each visitor is added to your Inbox as a contact, and subscribed if they leave the box ticked. Turn it off to send visitors straight to the store.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
{(form.customLinks ?? []).filter(l => l.placement === 'books').length === 0 && <p className="admin-stats-note">No books yet.</p>}
|
{(form.customLinks ?? []).filter(l => l.placement === 'books').length === 0 && <p className="admin-stats-note">No books yet.</p>}
|
||||||
{(form.customLinks ?? []).filter(l => l.placement === 'books').map(book => (
|
{(form.customLinks ?? []).filter(l => l.placement === 'books').map(book => (
|
||||||
<div key={book.id} className="admin-array-row">
|
<div key={book.id} className="admin-array-row">
|
||||||
@@ -5987,6 +6124,13 @@ const [dashboardNow, setDashboardNow] = useState(() => new Date())
|
|||||||
<label htmlFor={`study-description-${activeStudy.id}`}>Description</label>
|
<label htmlFor={`study-description-${activeStudy.id}`}>Description</label>
|
||||||
<textarea id={`study-description-${activeStudy.id}`} rows={3} value={activeStudy.description} placeholder="Brief description for the study hub card" onChange={e => updateStudyProgram(activeStudy.id, 'description', e.target.value)} />
|
<textarea id={`study-description-${activeStudy.id}`} rows={3} value={activeStudy.description} placeholder="Brief description for the study hub card" onChange={e => updateStudyProgram(activeStudy.id, 'description', e.target.value)} />
|
||||||
</div>
|
</div>
|
||||||
|
<div className="admin-field">
|
||||||
|
<label htmlFor={`study-image-${activeStudy.id}`}>Cover Image URL</label>
|
||||||
|
<input id={`study-image-${activeStudy.id}`} type="text" value={activeStudy.imageUrl ?? ''} placeholder="/uploads/study-cover.jpg" onChange={e => updateStudyProgram(activeStudy.id, 'imageUrl', e.target.value)} />
|
||||||
|
{renderImageAssetSelector(activeStudy.imageUrl ?? '', value => updateStudyProgram(activeStudy.id, 'imageUrl', value), `study-image-${activeStudy.id}-asset`)}
|
||||||
|
{renderImagePreview(activeStudy.imageUrl ?? '', `${activeStudy.title || 'Study'} cover`)}
|
||||||
|
<p className="admin-field-help">Shown as the backdrop of this study’s featured card on the homepage. A wide or square image works best.</p>
|
||||||
|
</div>
|
||||||
<div className="admin-field">
|
<div className="admin-field">
|
||||||
<label htmlFor={`study-home-eyebrow-${activeStudy.id}`}>Homepage Card Eyebrow</label>
|
<label htmlFor={`study-home-eyebrow-${activeStudy.id}`}>Homepage Card Eyebrow</label>
|
||||||
<input id={`study-home-eyebrow-${activeStudy.id}`} type="text" value={activeStudy.homepageEyebrow ?? ''} placeholder="New Study" onChange={e => updateStudyProgram(activeStudy.id, 'homepageEyebrow', e.target.value)} />
|
<input id={`study-home-eyebrow-${activeStudy.id}`} type="text" value={activeStudy.homepageEyebrow ?? ''} placeholder="New Study" onChange={e => updateStudyProgram(activeStudy.id, 'homepageEyebrow', e.target.value)} />
|
||||||
@@ -5999,6 +6143,19 @@ const [dashboardNow, setDashboardNow] = useState(() => new Date())
|
|||||||
<label htmlFor={`study-chapters-${activeStudy.id}`}>Number of Chapters</label>
|
<label htmlFor={`study-chapters-${activeStudy.id}`}>Number of Chapters</label>
|
||||||
<input id={`study-chapters-${activeStudy.id}`} type="number" min="1" max="999" value={activeStudy.numberOfChapters} placeholder="4" onChange={e => updateStudyProgram(activeStudy.id, 'numberOfChapters', Number(e.target.value) || 1)} />
|
<input id={`study-chapters-${activeStudy.id}`} type="number" min="1" max="999" value={activeStudy.numberOfChapters} placeholder="4" onChange={e => updateStudyProgram(activeStudy.id, 'numberOfChapters', Number(e.target.value) || 1)} />
|
||||||
</div>
|
</div>
|
||||||
|
<div className="admin-field">
|
||||||
|
<label htmlFor={`study-guide-source-${activeStudy.id}`}>Study Guide Download</label>
|
||||||
|
<select id={`study-guide-source-${activeStudy.id}`} value={activeStudy.guideSource ?? ''} onChange={e => updateStudyProgram(activeStudy.id, 'guideSource', e.target.value)}>
|
||||||
|
<option value="">Automatic (guide of the series or book linked to this study)</option>
|
||||||
|
<option value="none">None — don’t show a guide button</option>
|
||||||
|
{form.studyGuideTitle && <option value="primary">Current series guide: {form.studyGuideTitle}</option>}
|
||||||
|
{form.secondSeries?.guide?.title && <option value="second">Second series guide: {form.secondSeries.guide.title}</option>}
|
||||||
|
{(form.finishedBooks ?? []).filter(b => b.guide?.title).map(b => (
|
||||||
|
<option key={b.id} value={`book:${b.id}`}>{b.title}: {b.guide?.title}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<p className="admin-field-help">Adds a “Download Study Guide” button to this study’s page. Visitors enter their name and email to get the file.</p>
|
||||||
|
</div>
|
||||||
<div className="admin-field" style={{ display: 'flex', alignItems: 'center', gap: '0.6rem' }}>
|
<div className="admin-field" style={{ display: 'flex', alignItems: 'center', gap: '0.6rem' }}>
|
||||||
<input id={`study-home-feature-${activeStudy.id}`} type="checkbox" checked={activeStudy.showOnHomepage === true} onChange={e => updateStudyProgram(activeStudy.id, 'showOnHomepage', e.target.checked)} />
|
<input id={`study-home-feature-${activeStudy.id}`} type="checkbox" checked={activeStudy.showOnHomepage === true} onChange={e => updateStudyProgram(activeStudy.id, 'showOnHomepage', e.target.checked)} />
|
||||||
<label htmlFor={`study-home-feature-${activeStudy.id}`}>Feature this study card on homepage</label>
|
<label htmlFor={`study-home-feature-${activeStudy.id}`}>Feature this study card on homepage</label>
|
||||||
@@ -6149,6 +6306,10 @@ const [dashboardNow, setDashboardNow] = useState(() => new Date())
|
|||||||
<div className="admin-field">
|
<div className="admin-field">
|
||||||
<label htmlFor={`sl-reference-${activeLesson.id}`}>Passage Reference</label>
|
<label htmlFor={`sl-reference-${activeLesson.id}`}>Passage Reference</label>
|
||||||
<input id={`sl-reference-${activeLesson.id}`} type="text" value={activeLesson.reference} placeholder="1:1-2" onChange={e => updateStudySection(activeStudy.id, activeLesson.id, 'reference', e.target.value)} />
|
<input id={`sl-reference-${activeLesson.id}`} type="text" value={activeLesson.reference} placeholder="1:1-2" onChange={e => updateStudySection(activeStudy.id, activeLesson.id, 'reference', e.target.value)} />
|
||||||
|
{(() => {
|
||||||
|
const refProblem = checkPassageReference(activeLesson.reference, activeStudy.bibleBook?.trim() || activeStudy.slug)
|
||||||
|
return refProblem ? <p className="admin-field-warning" role="alert" style={{ color: '#e0a030', fontSize: '0.85rem', margin: '0.35rem 0 0' }}>⚠ {refProblem}</p> : null
|
||||||
|
})()}
|
||||||
</div>
|
</div>
|
||||||
<div className="admin-field">
|
<div className="admin-field">
|
||||||
<label htmlFor={`sl-title-${activeLesson.id}`}>Section Title</label>
|
<label htmlFor={`sl-title-${activeLesson.id}`}>Section Title</label>
|
||||||
@@ -6277,6 +6438,19 @@ const [dashboardNow, setDashboardNow] = useState(() => new Date())
|
|||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
|
|
||||||
|
</>}
|
||||||
|
{tabOf('global', 'global-footer') === 'global-verse' && <>
|
||||||
|
<div className="admin-panel-subhead" id="global-verse"><h3>Verse of the Week</h3></div>
|
||||||
|
<div className="admin-field">
|
||||||
|
<label htmlFor="field-verseOfTheWeek">Verse of the Week (optional)</label>
|
||||||
|
<input id="field-verseOfTheWeek" type="text" placeholder="Titus 2:11-12" value={(form.verseOfTheWeek as string) ?? ''} onChange={e => handleChange('verseOfTheWeek', e.target.value)} />
|
||||||
|
<p className="admin-field-hint">Shown at the top of the Scripture Index. Leave blank and the site picks a different covered passage each week automatically. Use a full reference with the book name.</p>
|
||||||
|
{(() => {
|
||||||
|
const vowProblem = checkPassageReference(String(form.verseOfTheWeek ?? ''), '')
|
||||||
|
return vowProblem ? <p className="admin-field-warning" role="alert" style={{ color: '#e0a030', fontSize: '0.85rem', margin: '0.35rem 0 0' }}>⚠ {vowProblem}</p> : null
|
||||||
|
})()}
|
||||||
|
</div>
|
||||||
|
|
||||||
</>}
|
</>}
|
||||||
{tabOf('global', 'global-footer') === 'global-welcome-email' && <>
|
{tabOf('global', 'global-footer') === 'global-welcome-email' && <>
|
||||||
<div className="admin-panel-subhead" id="global-welcome-email"><h3>Welcome Email</h3></div>
|
<div className="admin-panel-subhead" id="global-welcome-email"><h3>Welcome Email</h3></div>
|
||||||
@@ -6592,6 +6766,7 @@ const [dashboardNow, setDashboardNow] = useState(() => new Date())
|
|||||||
{/* NUGGETS UPLOAD HISTORY */}
|
{/* NUGGETS UPLOAD HISTORY */}
|
||||||
{adminView === 'nuggets:workflow' && <NuggetsWorkflowAdmin />}
|
{adminView === 'nuggets:workflow' && <NuggetsWorkflowAdmin />}
|
||||||
{adminView === 'nuggets:history' && <NuggetsHistoryAdmin />}
|
{adminView === 'nuggets:history' && <NuggetsHistoryAdmin />}
|
||||||
|
{adminView === 'nuggets:tags' && <NuggetsTagsAdmin />}
|
||||||
|
|
||||||
{/* STUDY COMMENTS */}
|
{/* STUDY COMMENTS */}
|
||||||
{adminView === 'study-comments' && (() => {
|
{adminView === 'study-comments' && (() => {
|
||||||
@@ -6876,6 +7051,34 @@ const [dashboardNow, setDashboardNow] = useState(() => new Date())
|
|||||||
</section>
|
</section>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* GOSPEL PAGE (/salvation) */}
|
||||||
|
{adminView === 'salvation' && (
|
||||||
|
<section className="admin-panel-section" aria-label="Gospel page">
|
||||||
|
<div className="admin-panel-head">
|
||||||
|
<h2>Gospel Page</h2>
|
||||||
|
<p>Settings for <a href="/salvation" target="_blank" rel="noopener noreferrer">/salvation</a>, The Gospel in a Courtroom.</p>
|
||||||
|
</div>
|
||||||
|
<div className="admin-panel-subhead">
|
||||||
|
<h3>Audio narration</h3>
|
||||||
|
<p>A choose-your-path audio version. Listeners hear The Case, then choose Guilty or Not guilty and hear the matching track. Leave the first field blank to hide the player. If the two plea tracks are blank, the plea buttons just select the plea on the page.</p>
|
||||||
|
</div>
|
||||||
|
{([
|
||||||
|
['salvationAudioUrl', '1. The Case (MP3)'],
|
||||||
|
['salvationAudioGuiltyUrl', '2. Guilty: next steps and prayer (MP3)'],
|
||||||
|
['salvationAudioNotGuiltyUrl', '3. Not guilty: what it means (MP3)'],
|
||||||
|
] as const).map(([key, label]) => (
|
||||||
|
<div className="admin-field" key={key}>
|
||||||
|
<label htmlFor={`field-${key}`}>{label}</label>
|
||||||
|
<input id={`field-${key}`} type="text" placeholder="https://…/salvation-case.mp3" value={form[key] ?? ''} onChange={e => handleChange(key, e.target.value)} />
|
||||||
|
{form[key]?.trim() && <audio controls preload="none" src={form[key].trim()} style={{ width: '100%', marginTop: 8 }} />}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<p className="admin-stats-note">
|
||||||
|
To make the files: put your ElevenLabs key and voice in your local <code>.env</code>, try <code>node --env-file=.env scripts/generate-salvation-audio.mjs --sample</code> first, then run it without <code>--sample</code> to make all three. Upload the MP3s in Asset Manager and paste their URLs here, then Save and Publish.
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* LEGAL */}
|
{/* LEGAL */}
|
||||||
{adminView === 'legal' && (
|
{adminView === 'legal' && (
|
||||||
<section className="admin-panel-section" aria-label="Legal Pages">
|
<section className="admin-panel-section" aria-label="Legal Pages">
|
||||||
|
|||||||
+961
-576
File diff suppressed because it is too large.
Load diff
+1394
-984
File diff suppressed because it is too large.
Load diff
@@ -28,6 +28,7 @@ const TYPE_LABEL: Record<string, string> = {
|
|||||||
community: 'Community Question',
|
community: 'Community Question',
|
||||||
testimony: 'Testimony',
|
testimony: 'Testimony',
|
||||||
topic: 'Topic Request',
|
topic: 'Topic Request',
|
||||||
|
gospel: 'Gospel Courtroom Question',
|
||||||
general: 'General Message',
|
general: 'General Message',
|
||||||
}
|
}
|
||||||
const KIND_LABEL: Record<Kind, string> = { email: 'Email', newsletter: 'Newsletter signup', download: 'Download request', message: 'Contact form' }
|
const KIND_LABEL: Record<Kind, string> = { email: 'Email', newsletter: 'Newsletter signup', download: 'Download request', message: 'Contact form' }
|
||||||
|
|||||||
@@ -308,7 +308,7 @@ export function AnalyticsPanel({
|
|||||||
<article>
|
<article>
|
||||||
<h3>Unique Visitors</h3>
|
<h3>Unique Visitors</h3>
|
||||||
<p>{stats.visitors.uniqueVisitors.toLocaleString()}</p>
|
<p>{stats.visitors.uniqueVisitors.toLocaleString()}</p>
|
||||||
<small>Tracked with consent</small>
|
<small>{stats.uniqueVisitors7d != null ? `${stats.uniqueVisitors7d.toLocaleString()} this week · ` : ''}Tracked with consent</small>
|
||||||
</article>
|
</article>
|
||||||
<article>
|
<article>
|
||||||
<h3>Returning Rate</h3>
|
<h3>Returning Rate</h3>
|
||||||
@@ -399,6 +399,23 @@ export function AnalyticsPanel({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="admin-analytics-grid" style={{ marginTop: '1rem' }}>
|
||||||
|
<div className="admin-analytics-card admin-analytics-card--wide">
|
||||||
|
<h3 className="admin-analytics-card-title">Probed URLs (not real pages)</h3>
|
||||||
|
{(stats.topUnknownPaths ?? []).length === 0 ? (
|
||||||
|
<p className="admin-stats-note">No probe traffic recorded yet. Requests for URLs that are not site pages (like /.env or /wp-login) are listed here and counted as bots.</p>
|
||||||
|
) : (
|
||||||
|
<ul className="admin-bot-reason-list">
|
||||||
|
{(stats.topUnknownPaths ?? []).map(row => (
|
||||||
|
<li key={row.path} className="admin-bot-reason-item">
|
||||||
|
<span style={{ wordBreak: 'break-all' }}>{row.path}</span>
|
||||||
|
<strong>{row.hits.toLocaleString()}</strong>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<div className="admin-analytics-grid" style={{ marginTop: '1rem' }}>
|
<div className="admin-analytics-grid" style={{ marginTop: '1rem' }}>
|
||||||
<div className="admin-analytics-card admin-analytics-card--wide">
|
<div className="admin-analytics-card admin-analytics-card--wide">
|
||||||
<h3 className="admin-analytics-card-title">Top Pages — Real vs Bot ({rangeLabel})</h3>
|
<h3 className="admin-analytics-card-title">Top Pages — Real vs Bot ({rangeLabel})</h3>
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import type { ChangeEvent } from 'react'
|
|||||||
import { useNavigate, useSearchParams } from 'react-router-dom'
|
import { useNavigate, useSearchParams } from 'react-router-dom'
|
||||||
|
|
||||||
const EMAIL_REGEX = /^[a-zA-Z0-9._%+-]{1,64}@[a-zA-Z0-9.-]{1,253}\.[a-zA-Z]{2,}$/
|
const EMAIL_REGEX = /^[a-zA-Z0-9._%+-]{1,64}@[a-zA-Z0-9.-]{1,253}\.[a-zA-Z]{2,}$/
|
||||||
|
const MAX_MESSAGE = 3000
|
||||||
|
|
||||||
interface ContactFields {
|
interface ContactFields {
|
||||||
firstName: string
|
firstName: string
|
||||||
@@ -12,18 +13,27 @@ interface ContactFields {
|
|||||||
messageType: string
|
messageType: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const TYPES: { value: string; label: string; hint: string; placeholder: string }[] = [
|
||||||
|
{ value: 'question', label: 'Bible question', hint: 'Ask anything about Scripture. Answers are posted on the Q&A page.', placeholder: 'What would you like to know?' },
|
||||||
|
{ value: 'gospel', label: 'Gospel courtroom', hint: 'A question about the gospel courtroom: the Judge, the accuser, the charges, the Substitute, the pardon or your plea. It goes to Nate privately and is not posted publicly.', placeholder: 'What would you like to ask about the courtroom, the verdict or the pardon?' },
|
||||||
|
{ value: 'community', label: 'Community question', hint: 'A question about a study discussion or the community.', placeholder: 'What’s on your mind?' },
|
||||||
|
{ value: 'testimony', label: 'Testimony', hint: 'Share what God is doing in your life. Every one is read.', placeholder: 'Tell your story…' },
|
||||||
|
{ value: 'topic', label: 'Topic request', hint: 'Suggest a passage or topic for a future episode.', placeholder: 'Which passage or topic?' },
|
||||||
|
{ value: 'general', label: 'General message', hint: 'Anything else you’d like to say.', placeholder: 'Write your message…' },
|
||||||
|
]
|
||||||
|
|
||||||
export default function ContactForm() {
|
export default function ContactForm() {
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
const [searchParams] = useSearchParams()
|
const [searchParams] = useSearchParams()
|
||||||
const source = searchParams.get('source')
|
const source = searchParams.get('source')
|
||||||
const studyName = searchParams.get('study')
|
const studyName = searchParams.get('study')
|
||||||
|
|
||||||
const [fields, setFields] = useState<ContactFields>({
|
const [fields, setFields] = useState<ContactFields>({
|
||||||
firstName: '',
|
firstName: '',
|
||||||
lastName: '',
|
lastName: '',
|
||||||
email: '',
|
email: '',
|
||||||
message: '',
|
message: '',
|
||||||
messageType: source === 'community' ? 'community' : 'question',
|
messageType: source === 'community' ? 'community' : source === 'salvation' ? 'gospel' : 'question',
|
||||||
})
|
})
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -42,6 +52,8 @@ export default function ContactForm() {
|
|||||||
const [errorMsg, setErrorMsg] = useState('')
|
const [errorMsg, setErrorMsg] = useState('')
|
||||||
const [fieldErrors, setFieldErrors] = useState<{ email?: string }>({})
|
const [fieldErrors, setFieldErrors] = useState<{ email?: string }>({})
|
||||||
|
|
||||||
|
const activeType = TYPES.find(t => t.value === fields.messageType) ?? TYPES[0]
|
||||||
|
|
||||||
function handleChange(e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) {
|
function handleChange(e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) {
|
||||||
const { name, value } = e.target
|
const { name, value } = e.target
|
||||||
setFields(f => ({ ...f, [name]: value }))
|
setFields(f => ({ ...f, [name]: value }))
|
||||||
@@ -59,10 +71,6 @@ export default function ContactForm() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleSelectChange(e: ChangeEvent<HTMLSelectElement>) {
|
|
||||||
setFields(f => ({ ...f, [e.target.name]: e.target.value }))
|
|
||||||
}
|
|
||||||
|
|
||||||
async function handleSubmit(e: React.FormEvent) {
|
async function handleSubmit(e: React.FormEvent) {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
setStatus('submitting')
|
setStatus('submitting')
|
||||||
@@ -90,7 +98,7 @@ export default function ContactForm() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<form className="contact-form" onSubmit={handleSubmit} noValidate>
|
<form className="cx-form" onSubmit={handleSubmit} noValidate>
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
className="contact-honeypot"
|
className="contact-honeypot"
|
||||||
@@ -100,14 +108,37 @@ export default function ContactForm() {
|
|||||||
value={honey}
|
value={honey}
|
||||||
onChange={e => setHoney(e.target.value)}
|
onChange={e => setHoney(e.target.value)}
|
||||||
/>
|
/>
|
||||||
<label>
|
|
||||||
First Name
|
<fieldset className="cx-types">
|
||||||
<input type="text" name="firstName" required autoComplete="given-name" value={fields.firstName} onChange={handleChange} />
|
<legend>What is this about?</legend>
|
||||||
</label>
|
<div className="cx-type-row" role="radiogroup">
|
||||||
<label>
|
{TYPES.map(t => (
|
||||||
Last Name
|
<label key={t.value} className="cx-type">
|
||||||
<input type="text" name="lastName" required autoComplete="family-name" value={fields.lastName} onChange={handleChange} />
|
<input
|
||||||
</label>
|
type="radio"
|
||||||
|
name="messageType"
|
||||||
|
value={t.value}
|
||||||
|
checked={fields.messageType === t.value}
|
||||||
|
onChange={() => setFields(f => ({ ...f, messageType: t.value }))}
|
||||||
|
/>
|
||||||
|
<span>{t.label}</span>
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<p className="cx-hint" aria-live="polite">{activeType.hint}</p>
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
|
<div className="cx-row">
|
||||||
|
<label>
|
||||||
|
First name
|
||||||
|
<input type="text" name="firstName" required autoComplete="given-name" value={fields.firstName} onChange={handleChange} />
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
Last name
|
||||||
|
<input type="text" name="lastName" required autoComplete="family-name" value={fields.lastName} onChange={handleChange} />
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
<label>
|
<label>
|
||||||
Email
|
Email
|
||||||
<input
|
<input
|
||||||
@@ -122,41 +153,37 @@ export default function ContactForm() {
|
|||||||
/>
|
/>
|
||||||
{fieldErrors.email && <span id="contact-email-error" className="study-signup-field-error">{fieldErrors.email}</span>}
|
{fieldErrors.email && <span id="contact-email-error" className="study-signup-field-error">{fieldErrors.email}</span>}
|
||||||
</label>
|
</label>
|
||||||
<label>
|
|
||||||
Message Type
|
|
||||||
<select name="messageType" value={fields.messageType} onChange={handleSelectChange}>
|
|
||||||
<option value="question">Bible Question</option>
|
|
||||||
<option value="community">Community Question</option>
|
|
||||||
<option value="testimony">Testimony</option>
|
|
||||||
<option value="topic">Topic Request</option>
|
|
||||||
<option value="general">General Message</option>
|
|
||||||
</select>
|
|
||||||
</label>
|
|
||||||
<label>
|
<label>
|
||||||
Message
|
Message
|
||||||
<textarea name="message" rows={6} required value={fields.message} onChange={handleChange} />
|
<textarea
|
||||||
</label>
|
name="message"
|
||||||
{fields.messageType === 'question' && (
|
rows={6}
|
||||||
<label className="contact-consent">
|
required
|
||||||
<input
|
maxLength={MAX_MESSAGE}
|
||||||
type="checkbox"
|
placeholder={activeType.placeholder}
|
||||||
checked={notifyOnAnswer}
|
value={fields.message}
|
||||||
onChange={e => setNotifyOnAnswer(e.target.checked)}
|
onChange={handleChange}
|
||||||
/>
|
|
||||||
<span>Email me when this question is answered.</span>
|
|
||||||
</label>
|
|
||||||
)}
|
|
||||||
<label className="contact-consent">
|
|
||||||
<input
|
|
||||||
type="checkbox"
|
|
||||||
checked={subscribe}
|
|
||||||
onChange={e => setSubscribe(e.target.checked)}
|
|
||||||
/>
|
/>
|
||||||
<span>Send me updates from Verse by Verse with Nate. I can unsubscribe anytime.</span>
|
<span className="cx-count">{fields.message.length} / {MAX_MESSAGE}</span>
|
||||||
</label>
|
</label>
|
||||||
{status === 'error' && <p className="contact-error">{errorMsg}</p>}
|
|
||||||
<button type="submit" className="btn-primary" disabled={status === 'submitting'}>
|
<div className="cx-checks">
|
||||||
{status === 'submitting' ? 'Sending…' : 'Send Message'}
|
{fields.messageType === 'question' && (
|
||||||
|
<label className="cx-check">
|
||||||
|
<input type="checkbox" checked={notifyOnAnswer} onChange={e => setNotifyOnAnswer(e.target.checked)} />
|
||||||
|
<span>Email me when this question is answered.</span>
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
<label className="cx-check">
|
||||||
|
<input type="checkbox" checked={subscribe} onChange={e => setSubscribe(e.target.checked)} />
|
||||||
|
<span>Send me updates from Verse by Verse with Nate. I can unsubscribe anytime.</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{status === 'error' && <p className="contact-error" role="alert">{errorMsg}</p>}
|
||||||
|
<button type="submit" className="btn-primary cx-submit" disabled={status === 'submitting'}>
|
||||||
|
{status === 'submitting' ? 'Sending…' : 'Send message'}
|
||||||
</button>
|
</button>
|
||||||
</form>
|
</form>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -5,14 +5,17 @@ import { useEffect } from 'react'
|
|||||||
interface NoteCardProps {
|
interface NoteCardProps {
|
||||||
anchorLabel: string
|
anchorLabel: string
|
||||||
html: string
|
html: string
|
||||||
|
updatedAt?: string | null
|
||||||
|
onDelete?: () => void
|
||||||
autoSaveMsg?: string
|
autoSaveMsg?: string
|
||||||
onChange: (html: string) => void
|
onChange: (html: string) => void
|
||||||
onClose: () => void
|
onClose: () => void
|
||||||
}
|
}
|
||||||
|
|
||||||
export function NoteCard({ anchorLabel, html, autoSaveMsg, onChange, onClose }: NoteCardProps) {
|
export function NoteCard({ anchorLabel, html, updatedAt, onDelete, autoSaveMsg, onChange, onClose }: NoteCardProps) {
|
||||||
const editor = useEditor({
|
const editor = useEditor({
|
||||||
extensions: [StarterKit],
|
extensions: [StarterKit],
|
||||||
|
shouldRerenderOnTransaction: true,
|
||||||
content: html || '<p></p>',
|
content: html || '<p></p>',
|
||||||
onUpdate({ editor }) {
|
onUpdate({ editor }) {
|
||||||
const next = editor.getHTML()
|
const next = editor.getHTML()
|
||||||
@@ -32,6 +35,8 @@ export function NoteCard({ anchorLabel, html, autoSaveMsg, onChange, onClose }:
|
|||||||
|
|
||||||
if (!editor) return null
|
if (!editor) return null
|
||||||
|
|
||||||
|
const wordCount = editor.getText().split(/\s+/).filter(Boolean).length
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="note-card">
|
<div className="note-card">
|
||||||
<div className="note-card-header">
|
<div className="note-card-header">
|
||||||
@@ -71,6 +76,27 @@ export function NoteCard({ anchorLabel, html, autoSaveMsg, onChange, onClose }:
|
|||||||
aria-label="Numbered list"
|
aria-label="Numbered list"
|
||||||
title="Numbered list"
|
title="Numbered list"
|
||||||
>1.</button>
|
>1.</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={`note-tool${editor.isActive('heading', { level: 3 }) ? ' note-tool--active' : ''}`}
|
||||||
|
onMouseDown={e => { e.preventDefault(); editor.chain().focus().toggleHeading({ level: 3 }).run() }}
|
||||||
|
aria-label="Heading"
|
||||||
|
title="Heading"
|
||||||
|
>H</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={`note-tool${editor.isActive('blockquote') ? ' note-tool--active' : ''}`}
|
||||||
|
onMouseDown={e => { e.preventDefault(); editor.chain().focus().toggleBlockquote().run() }}
|
||||||
|
aria-label="Quote"
|
||||||
|
title="Quote"
|
||||||
|
>❝</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={`note-tool${editor.isActive('strike') ? ' note-tool--active' : ''}`}
|
||||||
|
onMouseDown={e => { e.preventDefault(); editor.chain().focus().toggleStrike().run() }}
|
||||||
|
aria-label="Strikethrough"
|
||||||
|
title="Strikethrough"
|
||||||
|
><s>S</s></button>
|
||||||
<div className="note-tool-divider" />
|
<div className="note-tool-divider" />
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -91,6 +117,19 @@ export function NoteCard({ anchorLabel, html, autoSaveMsg, onChange, onClose }:
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<EditorContent editor={editor} className="note-card-editor" />
|
<EditorContent editor={editor} className="note-card-editor" />
|
||||||
|
<div className="note-card-footer">
|
||||||
|
{onDelete && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="note-card-delete"
|
||||||
|
onClick={() => { if (window.confirm('Delete this note?')) onDelete() }}
|
||||||
|
>Delete note</button>
|
||||||
|
)}
|
||||||
|
<span>
|
||||||
|
{updatedAt ? `Edited ${new Date(updatedAt).toLocaleString('en-US', { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' })} · ` : ''}
|
||||||
|
{wordCount.toLocaleString()} {wordCount === 1 ? 'word' : 'words'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,226 @@
|
|||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import type { ReactNode } from 'react'
|
||||||
|
import { Link } from 'react-router-dom'
|
||||||
|
import type { SiteContent } from '../content'
|
||||||
|
import { StoreLink } from './StoreLink'
|
||||||
|
|
||||||
|
type TabKey = 'downloads' | 'books' | 'recommended'
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
content: SiteContent
|
||||||
|
downloadPath: (resourceId: string) => string
|
||||||
|
// Shown when there are no downloads, books or recommended resources at all
|
||||||
|
fallback: ReactNode
|
||||||
|
}
|
||||||
|
|
||||||
|
// A description that stays short in the grid; long ones get a Read more toggle
|
||||||
|
function ClampedText({ text, className, lines = 3, threshold = 150 }: { text: string; className: string; lines?: number; threshold?: number }) {
|
||||||
|
const [open, setOpen] = useState(false)
|
||||||
|
const long = text.length > threshold
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<p
|
||||||
|
className={`${className}${long && !open ? ' res-clamped' : ''}`}
|
||||||
|
style={long && !open ? { WebkitLineClamp: lines } : undefined}
|
||||||
|
>
|
||||||
|
{text}
|
||||||
|
</p>
|
||||||
|
{long && (
|
||||||
|
<button type="button" className="res-more" onClick={() => setOpen(o => !o)} aria-expanded={open}>
|
||||||
|
{open ? 'Show less' : 'Read more'}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ResourcesHub({ content, downloadPath, fallback }: Props) {
|
||||||
|
const links = content.customLinks ?? []
|
||||||
|
// Ask for name and email before sending visitors to Amazon / Apple Books (on unless switched off in the admin)
|
||||||
|
const gated = content.gateStoreLinks !== false
|
||||||
|
const resources = links.filter(l => l.placement === 'resources')
|
||||||
|
const books = links.filter(l => l.placement === 'books')
|
||||||
|
const recommended = links.filter(l => l.placement === 'recommended')
|
||||||
|
|
||||||
|
const featured: { key: string; to: string; title: string; description: string; image: string; alt: string }[] = []
|
||||||
|
if (content.studyGuideTitle) {
|
||||||
|
featured.push({
|
||||||
|
key: 'primary',
|
||||||
|
to: '/downloads/primary-guide',
|
||||||
|
title: content.studyGuideTitle,
|
||||||
|
description: content.studyGuideDescription ?? '',
|
||||||
|
image: content.seriesImageUrl || '/images/titus-cover.png',
|
||||||
|
alt: content.seriesTitle,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (content.secondSeries?.guide?.title) {
|
||||||
|
featured.push({
|
||||||
|
key: 'second',
|
||||||
|
to: '/downloads/second-guide',
|
||||||
|
title: content.secondSeries.guide.title,
|
||||||
|
description: content.secondSeries.guide.description ?? '',
|
||||||
|
image: content.secondSeries.imageUrl ?? '',
|
||||||
|
alt: content.secondSeries.title,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const counts: Record<TabKey, number> = {
|
||||||
|
downloads: featured.length + resources.length,
|
||||||
|
books: books.length,
|
||||||
|
recommended: recommended.length,
|
||||||
|
}
|
||||||
|
const available = (Object.keys(counts) as TabKey[]).filter(k => counts[k] > 0)
|
||||||
|
|
||||||
|
const fromHash = (): TabKey | null => {
|
||||||
|
const h = typeof window !== 'undefined' ? window.location.hash.replace('#', '') : ''
|
||||||
|
return h === 'downloads' || h === 'books' || h === 'recommended' ? h : null
|
||||||
|
}
|
||||||
|
const [picked, setPicked] = useState<TabKey | null>(fromHash)
|
||||||
|
const [activeTag, setActiveTag] = useState<string | null>(null)
|
||||||
|
|
||||||
|
// Links like /resources#books, and the browser's back/forward buttons, switch the tab too
|
||||||
|
useEffect(() => {
|
||||||
|
const onHash = () => setPicked(fromHash())
|
||||||
|
window.addEventListener('hashchange', onHash)
|
||||||
|
return () => window.removeEventListener('hashchange', onHash)
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
if (available.length === 0) return <>{fallback}</>
|
||||||
|
|
||||||
|
const tab: TabKey = picked && counts[picked] > 0 ? picked : available[0]
|
||||||
|
const choose = (k: TabKey) => {
|
||||||
|
setPicked(k)
|
||||||
|
try { window.history.replaceState(null, '', `#${k}`) } catch { /* ignore */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
const tags = Array.from(new Set(resources.flatMap(r => r.tags ?? []))).filter(Boolean)
|
||||||
|
const shownResources = resources.filter(r => !activeTag || (r.tags ?? []).includes(activeTag))
|
||||||
|
const labels: Record<TabKey, string> = { downloads: 'Downloads', books: 'Reading List', recommended: 'Recommended' }
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="res-hub" aria-label="Resources">
|
||||||
|
<div className="section-inner">
|
||||||
|
{available.length > 1 && (
|
||||||
|
<div className="res-tabs" role="tablist" aria-label="Resource types">
|
||||||
|
{available.map(k => (
|
||||||
|
<button
|
||||||
|
key={k}
|
||||||
|
type="button"
|
||||||
|
role="tab"
|
||||||
|
id={`res-tab-${k}`}
|
||||||
|
aria-selected={tab === k}
|
||||||
|
aria-controls="res-panel"
|
||||||
|
className={`res-tab${tab === k ? ' res-tab--on' : ''}`}
|
||||||
|
onClick={() => choose(k)}
|
||||||
|
>
|
||||||
|
{labels[k]} <span>{counts[k]}</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div id="res-panel" role="tabpanel" aria-labelledby={`res-tab-${tab}`}>
|
||||||
|
{tab === 'downloads' && (
|
||||||
|
<>
|
||||||
|
{featured.length > 0 && (
|
||||||
|
<div className="res-featured">
|
||||||
|
{featured.map(f => (
|
||||||
|
<Link key={f.key} to={f.to} className="res-feature">
|
||||||
|
{f.image && <img src={f.image} alt={f.alt} className="res-feature-img" loading="lazy" />}
|
||||||
|
<div className="res-feature-body">
|
||||||
|
<span className="res-badge">Featured</span>
|
||||||
|
<span className="res-title">{f.title}</span>
|
||||||
|
{f.description && <p className="res-desc res-clamped" style={{ WebkitLineClamp: 2 }}>{f.description}</p>}
|
||||||
|
<span className="res-action">Download free guide →</span>
|
||||||
|
</div>
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{tags.length > 0 && (
|
||||||
|
<div className="res-tags" role="group" aria-label="Filter by topic">
|
||||||
|
<button type="button" className={`res-chip${activeTag === null ? ' res-chip--on' : ''}`} onClick={() => setActiveTag(null)}>All topics</button>
|
||||||
|
{tags.map(t => (
|
||||||
|
<button key={t} type="button" className={`res-chip${activeTag === t ? ' res-chip--on' : ''}`} onClick={() => setActiveTag(prev => (prev === t ? null : t))}>{t}</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{shownResources.length > 0 ? (
|
||||||
|
<div className="res-grid">
|
||||||
|
{shownResources.map(r => (
|
||||||
|
<Link key={r.id} to={downloadPath(r.id)} className="res-card">
|
||||||
|
{r.imageUrl && <img src={r.imageUrl} alt={r.label} className="res-card-img" loading="lazy" />}
|
||||||
|
<div className="res-card-body">
|
||||||
|
<span className="res-title">{r.label}</span>
|
||||||
|
{r.description && <p className="res-desc res-clamped" style={{ WebkitLineClamp: 3 }}>{r.description}</p>}
|
||||||
|
{(r.tags ?? []).length > 0 && <span className="res-card-tags">{(r.tags ?? []).join(' · ')}</span>}
|
||||||
|
<span className="res-action">Open download →</span>
|
||||||
|
</div>
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
resources.length > 0 && <p className="res-empty">No downloads tagged "{activeTag}".</p>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{tab === 'books' && (
|
||||||
|
<div className="res-grid">
|
||||||
|
{books.map(book => (
|
||||||
|
<div key={book.id} className="res-book">
|
||||||
|
{book.imageUrl && <img src={book.imageUrl} alt={book.label} className="res-book-cover" loading="lazy" />}
|
||||||
|
<div className="res-book-body">
|
||||||
|
<span className="res-title">{book.label}</span>
|
||||||
|
{book.description && <ClampedText text={book.description} className="res-desc" lines={3} />}
|
||||||
|
<div className="res-book-actions">
|
||||||
|
{(book.amazonUrl || book.url) && (
|
||||||
|
<StoreLink
|
||||||
|
source={`book:${book.id}`}
|
||||||
|
store="amazon"
|
||||||
|
href={book.amazonUrl || book.url}
|
||||||
|
gated={gated}
|
||||||
|
className="btn-primary res-btn"
|
||||||
|
>
|
||||||
|
{book.amazonUrl ? (book.amazonLabel || 'View on Amazon') : (book.amazonLabel || 'Learn More')}
|
||||||
|
</StoreLink>
|
||||||
|
)}
|
||||||
|
{book.appleBooksUrl && (
|
||||||
|
<StoreLink
|
||||||
|
source={`book:${book.id}`}
|
||||||
|
store="apple"
|
||||||
|
href={book.appleBooksUrl}
|
||||||
|
gated={gated}
|
||||||
|
className="btn-secondary res-btn"
|
||||||
|
>
|
||||||
|
{book.appleBooksLabel || 'Apple Books'}
|
||||||
|
</StoreLink>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{tab === 'recommended' && (
|
||||||
|
<div className="res-grid">
|
||||||
|
{recommended.map(item => (
|
||||||
|
<a key={item.id} href={item.url} target="_blank" rel="noopener noreferrer" className="res-card">
|
||||||
|
{item.imageUrl && <img src={item.imageUrl} alt={item.label} className="res-card-img" loading="lazy" />}
|
||||||
|
<div className="res-card-body">
|
||||||
|
<span className="res-title">{item.label}</span>
|
||||||
|
{item.description && <p className="res-desc res-clamped" style={{ WebkitLineClamp: 3 }}>{item.description}</p>}
|
||||||
|
<span className="res-action">Visit →</span>
|
||||||
|
</div>
|
||||||
|
</a>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
import { useEffect, useRef, useState } from 'react'
|
||||||
|
import type { ReactNode } from 'react'
|
||||||
|
|
||||||
|
const SAVED_KEY = 'vbn-store-link-contact'
|
||||||
|
|
||||||
|
interface Saved { firstName: string; lastName: string; email: string }
|
||||||
|
|
||||||
|
function readSaved(): Saved {
|
||||||
|
try {
|
||||||
|
const raw = localStorage.getItem(SAVED_KEY)
|
||||||
|
if (raw) {
|
||||||
|
const d = JSON.parse(raw) as Partial<Saved>
|
||||||
|
return { firstName: d.firstName ?? '', lastName: d.lastName ?? '', email: d.email ?? '' }
|
||||||
|
}
|
||||||
|
} catch { /* private mode or bad data */ }
|
||||||
|
return { firstName: '', lastName: '', email: '' }
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
// Which guide or book this link belongs to (the server finds the real address from this)
|
||||||
|
source: string
|
||||||
|
store: 'amazon' | 'apple'
|
||||||
|
// The address used when the sign-up step is switched off
|
||||||
|
href: string
|
||||||
|
className?: string
|
||||||
|
children: ReactNode
|
||||||
|
gated: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
// A button that asks for name and email, then sends the visitor on to Amazon or Apple Books.
|
||||||
|
// With the gate switched off it is just a normal link.
|
||||||
|
export function StoreLink({ source, store, href, className, children, gated }: Props) {
|
||||||
|
const [open, setOpen] = useState(false)
|
||||||
|
const [fields, setFields] = useState<Saved>({ firstName: '', lastName: '', email: '' })
|
||||||
|
const [subscribe, setSubscribe] = useState(true)
|
||||||
|
const [honey, setHoney] = useState('')
|
||||||
|
const [status, setStatus] = useState<'idle' | 'sending' | 'error'>('idle')
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
const firstRef = useRef<HTMLInputElement>(null)
|
||||||
|
const storeName = store === 'amazon' ? 'Amazon' : 'Apple Books'
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return
|
||||||
|
const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setOpen(false) }
|
||||||
|
document.addEventListener('keydown', onKey)
|
||||||
|
const t = window.setTimeout(() => firstRef.current?.focus(), 30)
|
||||||
|
return () => { document.removeEventListener('keydown', onKey); window.clearTimeout(t) }
|
||||||
|
}, [open])
|
||||||
|
|
||||||
|
if (!gated) {
|
||||||
|
return <a href={href} target="_blank" rel="noopener noreferrer" className={className}>{children}</a>
|
||||||
|
}
|
||||||
|
|
||||||
|
const openDialog = () => {
|
||||||
|
setFields(readSaved())
|
||||||
|
setStatus('idle')
|
||||||
|
setError('')
|
||||||
|
setOpen(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submit(e: React.FormEvent) {
|
||||||
|
e.preventDefault()
|
||||||
|
setStatus('sending')
|
||||||
|
setError('')
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/store-link', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ source, store, ...fields, subscribe, _honey: honey }),
|
||||||
|
})
|
||||||
|
const data = (await res.json().catch(() => ({}))) as { url?: string; message?: string }
|
||||||
|
if (!res.ok || !data.url) {
|
||||||
|
setError(data.message ?? 'Something went wrong. Please try again.')
|
||||||
|
setStatus('error')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try { localStorage.setItem(SAVED_KEY, JSON.stringify(fields)) } catch { /* ignore */ }
|
||||||
|
window.location.assign(data.url)
|
||||||
|
} catch {
|
||||||
|
setError('Could not connect. Please try again later.')
|
||||||
|
setStatus('error')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const set = (name: keyof Saved) => (e: React.ChangeEvent<HTMLInputElement>) => setFields(f => ({ ...f, [name]: e.target.value }))
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<button type="button" className={className} onClick={openDialog}>{children}</button>
|
||||||
|
{open && (
|
||||||
|
<div className="sl-overlay" onMouseDown={e => { if (e.target === e.currentTarget) setOpen(false) }}>
|
||||||
|
<div className="sl-dialog" role="dialog" aria-modal="true" aria-labelledby={`sl-title-${source}-${store}`}>
|
||||||
|
<h3 id={`sl-title-${source}-${store}`}>One quick step</h3>
|
||||||
|
<p className="sl-lead">Tell us where to send updates, then we'll take you straight to {storeName}.</p>
|
||||||
|
<form onSubmit={submit} noValidate>
|
||||||
|
<input type="text" className="contact-honeypot" tabIndex={-1} autoComplete="off" aria-hidden="true" value={honey} onChange={e => setHoney(e.target.value)} />
|
||||||
|
<div className="sl-row">
|
||||||
|
<label>
|
||||||
|
First name
|
||||||
|
<input ref={firstRef} type="text" required autoComplete="given-name" value={fields.firstName} onChange={set('firstName')} />
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
Last name
|
||||||
|
<input type="text" required autoComplete="family-name" value={fields.lastName} onChange={set('lastName')} />
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<label>
|
||||||
|
Email
|
||||||
|
<input type="email" required autoComplete="email" value={fields.email} onChange={set('email')} />
|
||||||
|
</label>
|
||||||
|
<label className="sl-check">
|
||||||
|
<input type="checkbox" checked={subscribe} onChange={e => setSubscribe(e.target.checked)} />
|
||||||
|
<span>Subscribe me to updates from Verse by Verse with Nate. I can unsubscribe anytime.</span>
|
||||||
|
</label>
|
||||||
|
{status === 'error' && <p className="sl-error" role="alert">{error}</p>}
|
||||||
|
<div className="sl-actions">
|
||||||
|
<button type="submit" className="btn-primary" disabled={status === 'sending'}>
|
||||||
|
{status === 'sending' ? 'One moment…' : `Continue to ${storeName}`}
|
||||||
|
</button>
|
||||||
|
<button type="button" className="btn-secondary" onClick={() => setOpen(false)}>Cancel</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
+55
-1
@@ -11,9 +11,14 @@ export interface StudyProgram {
|
|||||||
description: string
|
description: string
|
||||||
bibleBook?: string
|
bibleBook?: string
|
||||||
homepageEyebrow?: string
|
homepageEyebrow?: string
|
||||||
|
// Cover image for the study, used as the backdrop of the featured card on the homepage
|
||||||
|
imageUrl?: string
|
||||||
showOnHomepage?: boolean
|
showOnHomepage?: boolean
|
||||||
showNewTag?: boolean
|
showNewTag?: boolean
|
||||||
newTagLabel?: string
|
newTagLabel?: string
|
||||||
|
// Which companion guide the study offers for download: '' = automatic (the guide of the series or
|
||||||
|
// finished book linked to this study), 'none', 'primary', 'second', or 'book:<finished book id>'
|
||||||
|
guideSource?: string
|
||||||
// 'complete' = finished and self-paced (still open for enrollment). A study whose lessons
|
// 'complete' = finished and self-paced (still open for enrollment). A study whose lessons
|
||||||
// have all been released is treated as complete even if left as 'active'.
|
// have all been released is treated as complete even if left as 'active'.
|
||||||
status: 'active' | 'planned' | 'complete'
|
status: 'active' | 'planned' | 'complete'
|
||||||
@@ -280,6 +285,10 @@ export interface SiteContent {
|
|||||||
shareQrImageUrl: string
|
shareQrImageUrl: string
|
||||||
// ── PRISM Video ──
|
// ── PRISM Video ──
|
||||||
prismVideoUrl: string
|
prismVideoUrl: string
|
||||||
|
// Audio narration of the /salvation page (served to the static page via /api/salvation-audio)
|
||||||
|
salvationAudioUrl: string
|
||||||
|
salvationAudioGuiltyUrl: string
|
||||||
|
salvationAudioNotGuiltyUrl: string
|
||||||
prismEyebrow: string
|
prismEyebrow: string
|
||||||
prismHeading: string
|
prismHeading: string
|
||||||
prismIntro: string
|
prismIntro: string
|
||||||
@@ -310,6 +319,7 @@ export interface SiteContent {
|
|||||||
platformCreatorUrl: string
|
platformCreatorUrl: string
|
||||||
platformKofiUrl?: string
|
platformKofiUrl?: string
|
||||||
platformKofiQrUrl?: string
|
platformKofiQrUrl?: string
|
||||||
|
verseOfTheWeek?: string
|
||||||
// ── Welcome Email ──
|
// ── Welcome Email ──
|
||||||
welcomeEmailSubject: string
|
welcomeEmailSubject: string
|
||||||
welcomeEmailGreetingPrefix: string
|
welcomeEmailGreetingPrefix: string
|
||||||
@@ -396,6 +406,8 @@ export interface SiteContent {
|
|||||||
qaAnsweredEmailSignoff: string
|
qaAnsweredEmailSignoff: string
|
||||||
// ── Header ──
|
// ── Header ──
|
||||||
headerFollowLabel: string
|
headerFollowLabel: string
|
||||||
|
// Ask for name and email before sending visitors to Amazon or Apple Books (default on)
|
||||||
|
gateStoreLinks?: boolean
|
||||||
// ── Cookie banner ──
|
// ── Cookie banner ──
|
||||||
cookieBannerText: string
|
cookieBannerText: string
|
||||||
// ── Arrays ──
|
// ── Arrays ──
|
||||||
@@ -520,7 +532,10 @@ export const DEFAULTS: SiteContent = {
|
|||||||
shareHeading: 'Help one more person hear the Word this week.',
|
shareHeading: 'Help one more person hear the Word this week.',
|
||||||
shareP: 'Scan the QR code or text the show link to a friend who needs encouragement today.',
|
shareP: 'Scan the QR code or text the show link to a friend who needs encouragement today.',
|
||||||
shareQrImageUrl: '/images/qr-code.jpg',
|
shareQrImageUrl: '/images/qr-code.jpg',
|
||||||
prismVideoUrl: '/images/PRISM.mp4',
|
prismVideoUrl: 'https://files.versebyversewithnate.us/images/PRISM.mp4',
|
||||||
|
salvationAudioUrl: '',
|
||||||
|
salvationAudioGuiltyUrl: '',
|
||||||
|
salvationAudioNotGuiltyUrl: '',
|
||||||
prismEyebrow: 'Featured Video',
|
prismEyebrow: 'Featured Video',
|
||||||
prismHeading: 'PRISM',
|
prismHeading: 'PRISM',
|
||||||
prismIntro:
|
prismIntro:
|
||||||
@@ -557,6 +572,7 @@ export const DEFAULTS: SiteContent = {
|
|||||||
platformCreatorUrl: 'https://creators.spotify.com/pod/profile/nmemmert/',
|
platformCreatorUrl: 'https://creators.spotify.com/pod/profile/nmemmert/',
|
||||||
platformKofiUrl: 'https://ko-fi.com/versebyversewithnate',
|
platformKofiUrl: 'https://ko-fi.com/versebyversewithnate',
|
||||||
platformKofiQrUrl: '/images/kofi-qr.png',
|
platformKofiQrUrl: '/images/kofi-qr.png',
|
||||||
|
verseOfTheWeek: '',
|
||||||
welcomeEmailSubject: 'Welcome to Verse by Verse with Nate',
|
welcomeEmailSubject: 'Welcome to Verse by Verse with Nate',
|
||||||
welcomeEmailGreetingPrefix: 'Glad you\'re here',
|
welcomeEmailGreetingPrefix: 'Glad you\'re here',
|
||||||
welcomeEmailIntro: 'Thanks for subscribing to Verse by Verse with Nate - a Bible teaching podcast where we slow down, dig into the text, and pull out the nuggets God has for us word by word.',
|
welcomeEmailIntro: 'Thanks for subscribing to Verse by Verse with Nate - a Bible teaching podcast where we slow down, dig into the text, and pull out the nuggets God has for us word by word.',
|
||||||
@@ -698,3 +714,41 @@ export function getAllHighlights(content: Pick<SiteContent, 'podcastFeaturedLink
|
|||||||
...(content.finishedBooks ?? []).flatMap(book => book.highlights ?? []),
|
...(content.finishedBooks ?? []).flatMap(book => book.highlights ?? []),
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface StudyGuideLink {
|
||||||
|
// Page id under /downloads/ (primary-guide, second-guide, book-guide--<id>)
|
||||||
|
pageId: string
|
||||||
|
title: string
|
||||||
|
// Direct file link, when the guide has one; otherwise the button opens the guide's page (store links)
|
||||||
|
downloadUrl?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
// The companion guide a study offers, either chosen explicitly in admin or found through the
|
||||||
|
// series / finished book that is linked to the study.
|
||||||
|
export function getStudyGuideLink(
|
||||||
|
content: Pick<SiteContent, 'seriesStudySlug' | 'studyGuideTitle' | 'studyGuideUrl' | 'studyGuideDownloadUrl' | 'studyGuideAppleBooksUrl' | 'secondSeries' | 'finishedBooks'>,
|
||||||
|
study: Pick<StudyProgram, 'slug' | 'guideSource'>,
|
||||||
|
): StudyGuideLink | null {
|
||||||
|
const source = study.guideSource ?? ''
|
||||||
|
if (source === 'none') return null
|
||||||
|
|
||||||
|
const primary = (): StudyGuideLink | null =>
|
||||||
|
content.studyGuideTitle && (content.studyGuideUrl || content.studyGuideDownloadUrl || content.studyGuideAppleBooksUrl)
|
||||||
|
? { pageId: 'primary-guide', title: content.studyGuideTitle, downloadUrl: content.studyGuideDownloadUrl || undefined }
|
||||||
|
: null
|
||||||
|
const second = (): StudyGuideLink | null =>
|
||||||
|
content.secondSeries?.guide?.title ? { pageId: 'second-guide', title: content.secondSeries.guide.title, downloadUrl: content.secondSeries.guide.downloadUrl || undefined } : null
|
||||||
|
const book = (id: string): StudyGuideLink | null => {
|
||||||
|
const found = (content.finishedBooks ?? []).find(b => b.id === id)
|
||||||
|
return found?.guide?.title ? { pageId: `book-guide--${found.id}`, title: found.guide.title, downloadUrl: found.guide.downloadUrl || undefined } : null
|
||||||
|
}
|
||||||
|
|
||||||
|
if (source === 'primary') return primary()
|
||||||
|
if (source === 'second') return second()
|
||||||
|
if (source.startsWith('book:')) return book(source.slice('book:'.length))
|
||||||
|
|
||||||
|
if (content.seriesStudySlug && content.seriesStudySlug === study.slug) return primary()
|
||||||
|
if (content.secondSeries?.studySlug && content.secondSeries.studySlug === study.slug) return second()
|
||||||
|
const linkedBook = (content.finishedBooks ?? []).find(b => b.studySlug === study.slug && b.guide?.title)
|
||||||
|
return linkedBook ? book(linkedBook.id) : null
|
||||||
|
}
|
||||||
+399
-243
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,25 @@
|
|||||||
|
import test from 'node:test'
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { isKnownSitePath } from '../server/study-helpers.js'
|
||||||
|
|
||||||
|
test('real site pages are known paths', () => {
|
||||||
|
for (const p of ['/', '/study', '/study/titus/titus-abc', '/episodes/123', '/salvation', '/scripture', '/privacy']) {
|
||||||
|
assert.equal(isKnownSitePath(p), true, p)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test('scanner and probe paths are not known paths', () => {
|
||||||
|
for (const p of ['/.env', '/.git/config', '/wp-login', '/actuator/health', '/cgi-bin/x', '/random-path-123']) {
|
||||||
|
assert.equal(isKnownSitePath(p), false, p)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
import { checkPassageReference } from '../shared/bible-books.js'
|
||||||
|
|
||||||
|
test('passage reference check accepts what the index can read and flags what it cannot', () => {
|
||||||
|
assert.equal(checkPassageReference('Titus 1:1-2', ''), null)
|
||||||
|
assert.equal(checkPassageReference('1:10–13a', 'titus'), null)
|
||||||
|
assert.match(checkPassageReference('1:1-2', ''), /Bible Book/)
|
||||||
|
assert.match(checkPassageReference('Foo 1:1', 'titus'), /not a recognized/)
|
||||||
|
assert.match(checkPassageReference('chapter one', 'titus'), /Use the form/)
|
||||||
|
})
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import test from 'node:test'
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { parseNoteEntries, serializeNoteEntries, noteEntriesToText } from '../shared/note-format.js'
|
||||||
|
|
||||||
|
test('legacy anchor map upgrades to entries and round-trips as v2', () => {
|
||||||
|
const entries = parseNoteEntries(JSON.stringify({ scripture: '<p>a</p>', general: '', commentary: '<p>b</p>' }))
|
||||||
|
assert.deepEqual(entries.map(e => e.anchor), ['scripture', 'commentary'])
|
||||||
|
const again = parseNoteEntries(serializeNoteEntries(entries))
|
||||||
|
assert.equal(again.length, 2)
|
||||||
|
assert.equal(JSON.parse(serializeNoteEntries(entries)).v, 2)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('plain-text legacy notes become a general entry', () => {
|
||||||
|
const entries = parseNoteEntries('just some text')
|
||||||
|
assert.equal(entries.length, 1)
|
||||||
|
assert.equal(entries[0].anchor, 'general')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('multiple entries per anchor are kept and empty ones dropped', () => {
|
||||||
|
const raw = serializeNoteEntries([
|
||||||
|
{ id: '1', anchor: 'general', html: '<p>one</p>', updatedAt: '2026-01-01T00:00:00.000Z' },
|
||||||
|
{ id: '2', anchor: 'general', html: '<p>two</p>', updatedAt: null },
|
||||||
|
{ id: '3', anchor: 'general', html: ' ', updatedAt: null },
|
||||||
|
])
|
||||||
|
assert.equal(parseNoteEntries(raw).length, 2)
|
||||||
|
assert.equal(serializeNoteEntries([]), '')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('plain-text export strips markup', () => {
|
||||||
|
const text = noteEntriesToText(serializeNoteEntries([{ id: '1', anchor: 'scripture', html: '<p>Hi & bye</p>', updatedAt: null }]))
|
||||||
|
assert.equal(text, 'Scripture Text\nHi & bye')
|
||||||
|
})
|
||||||
+3
-8
@@ -25,10 +25,10 @@ export default defineConfig({
|
|||||||
navigateFallback: '/index.html',
|
navigateFallback: '/index.html',
|
||||||
// Allowlist-only approach: SW only serves index.html for known SPA routes.
|
// Allowlist-only approach: SW only serves index.html for known SPA routes.
|
||||||
// Everything else (admin-configured redirects, /spotify, /apple, /amazon,
|
// Everything else (admin-configured redirects, /spotify, /apple, /amazon,
|
||||||
// feed.xml, robots.txt, etc.) goes to the server so server-side redirects work.
|
// feed.xml, robots.txt, the static /salvation page, etc.) goes to the server so server-side redirects work.
|
||||||
navigateFallbackAllowlist: [
|
navigateFallbackAllowlist: [
|
||||||
/^\/$/, // exact root
|
/^\/$/, // exact root
|
||||||
/^\/(start-here|about|contact|resources|thanks|preview|privacy|terms|salvation)(\/.*)?$/,
|
/^\/(start-here|about|contact|resources|thanks|preview|privacy|terms)(\/.*)?$/,
|
||||||
/^\/(study|studys|episodes|finished|downloads|subscribe|certificate)(\/.*)?$/,
|
/^\/(study|studys|episodes|finished|downloads|subscribe|certificate)(\/.*)?$/,
|
||||||
/^\/(questions|admin|email|contacts|calendar)(\/.*)?$/,
|
/^\/(questions|admin|email|contacts|calendar)(\/.*)?$/,
|
||||||
],
|
],
|
||||||
@@ -39,7 +39,7 @@ export default defineConfig({
|
|||||||
options: { cacheName: 'api-content', expiration: { maxAgeSeconds: 3600 } },
|
options: { cacheName: 'api-content', expiration: { maxAgeSeconds: 3600 } },
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
urlPattern: /\/images\//,
|
urlPattern: /\/images\/.*\.(?!mp4|webm|mov)[a-z0-9]+(\?.*)?$/i,
|
||||||
handler: 'CacheFirst',
|
handler: 'CacheFirst',
|
||||||
options: { cacheName: 'images', expiration: { maxEntries: 60, maxAgeSeconds: 86400 * 30 } },
|
options: { cacheName: 'images', expiration: { maxEntries: 60, maxAgeSeconds: 86400 * 30 } },
|
||||||
},
|
},
|
||||||
@@ -47,11 +47,6 @@ export default defineConfig({
|
|||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
resolve: {
|
|
||||||
alias: {
|
|
||||||
'react-simple-maps': 'react-simple-maps/dist/index.es.js',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
server: {
|
server: {
|
||||||
proxy: {
|
proxy: {
|
||||||
'/api': 'http://localhost:4173',
|
'/api': 'http://localhost:4173',
|
||||||
|
|||||||
Reference in new issue
Block a user