removed scaffold
This commit is contained in:
@@ -0,0 +1,16 @@
|
||||
# Microsoft Azure AD Configuration
|
||||
CLIENT_SECRET=7aD8Q~d5K~_PzQv6KqDdrEnmyXHE60eVDpbcnaK_
|
||||
TENANT_ID=3fd97ea7-b124-41f1-855f-52d8ac3b16c7
|
||||
CLIENT_ID=3c846e71-9609-40e1-b458-0eb805e21b9f
|
||||
REDIRECT_URI=https://pocketbase.ccllc.pro/api/oauth2-redirect
|
||||
|
||||
# PocketBase Configuration
|
||||
PB_DB=https://pocketbase.ccllc.pro
|
||||
PB_AUTH_COLLECTION=Users
|
||||
|
||||
#PocketBase Tables
|
||||
PB_Job_Collection=Job_Info_TestEnv
|
||||
PB_Notes_Collection=Notes
|
||||
PB_App_Preferences_Collection=app_preferences_settings
|
||||
PB_User_Preferences_Collection=user_preferences_settings
|
||||
PB_Attachments_Collection=Attachments
|
||||
@@ -1,2 +1,33 @@
|
||||
# Prism-Notes
|
||||
# Prism Notes
|
||||
|
||||
PocketBase + Microsoft Graph OAuth capture app. Frontend is a Tailwind-powered note and audio capture page; backend is a Bun/Hono server that validates PocketBase tokens and can mint Graph tokens (client credentials flow).
|
||||
|
||||
## What you get
|
||||
- `server.ts` — Bun + Hono server with `/health`, `/api/graph/status`, `/api/submit`, and static `index.html` serving.
|
||||
- `index.html` — Microsoft OAuth via PocketBase plus note/audio capture UI.
|
||||
- `tsconfig.json`, `package.json`, `bun.lock` — project configuration.
|
||||
|
||||
## Setup
|
||||
1) Install Bun (https://bun.sh).
|
||||
2) Add a `.env` file at the project root with the variables below.
|
||||
3) Install deps: `bun install`
|
||||
4) Run dev server: `bun run --watch server.ts` (default port 5500).
|
||||
|
||||
Open http://localhost:5500 and sign in with Microsoft.
|
||||
|
||||
## Environment variables
|
||||
| Name | Description |
|
||||
| --- | --- |
|
||||
| `CLIENT_ID` | Azure AD app (client) ID |
|
||||
| `CLIENT_SECRET` | Azure AD client secret |
|
||||
| `TENANT_ID` | Azure AD tenant ID |
|
||||
| `REDIRECT_URI` | Redirect URI configured in the Azure app |
|
||||
| `PB_DB` | PocketBase URL (e.g., http://127.0.0.1:8090) |
|
||||
| `PB_COLLECTION` | Collection to store submissions (default `Job_Info_TestEnv`) |
|
||||
| `PB_AUTH_COLLECTION` | Auth collection for token refresh (default `Users`) |
|
||||
| `PORT` | Server port (default 5500) |
|
||||
|
||||
## Notes
|
||||
- `getGraphToken()` in `server.ts` is ready for Graph API calls; extend with additional routes as needed.
|
||||
- `/api/submit` validates the provided `pbToken` then writes the payload to `PB_COLLECTION`; adjust fields to match your schema.
|
||||
- Static file serving uses `index.html` from the repo root.
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
{
|
||||
"lockfileVersion": 1,
|
||||
"configVersion": 1,
|
||||
"workspaces": {
|
||||
"": {
|
||||
"name": "pbandgraph-scaffold",
|
||||
"dependencies": {
|
||||
"@azure/msal-node": "^2.6.7",
|
||||
"@microsoft/microsoft-graph-client": "^3.0.7",
|
||||
"dotenv": "^17.2.3",
|
||||
"hono": "^4.10.8",
|
||||
"pocketbase": "^0.26.5",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bun": "latest",
|
||||
"@types/node": "latest",
|
||||
},
|
||||
},
|
||||
},
|
||||
"packages": {
|
||||
"@azure/msal-common": ["@azure/msal-common@14.16.1", "", {}, "sha512-nyxsA6NA4SVKh5YyRpbSXiMr7oQbwark7JU9LMeg6tJYTSPyAGkdx61wPT4gyxZfxlSxMMEyAsWaubBlNyIa1w=="],
|
||||
|
||||
"@azure/msal-node": ["@azure/msal-node@2.16.3", "", { "dependencies": { "@azure/msal-common": "14.16.1", "jsonwebtoken": "^9.0.0", "uuid": "^8.3.0" } }, "sha512-CO+SE4weOsfJf+C5LM8argzvotrXw252/ZU6SM2Tz63fEblhH1uuVaaO4ISYFuN4Q6BhTo7I3qIdi8ydUQCqhw=="],
|
||||
|
||||
"@babel/runtime": ["@babel/runtime@7.28.4", "", {}, "sha512-Q/N6JNWvIvPnLDvjlE1OUBLPQHH6l3CltCEsHIujp45zQUSSh8K+gHnaEX45yAT1nyngnINhvWtzN+Nb9D8RAQ=="],
|
||||
|
||||
"@microsoft/microsoft-graph-client": ["@microsoft/microsoft-graph-client@3.0.7", "", { "dependencies": { "@babel/runtime": "^7.12.5", "tslib": "^2.2.0" } }, "sha512-/AazAV/F+HK4LIywF9C+NYHcJo038zEnWkteilcxC1FM/uK/4NVGDKGrxx7nNq1ybspAroRKT4I1FHfxQzxkUw=="],
|
||||
|
||||
"@types/bun": ["@types/bun@1.3.5", "", { "dependencies": { "bun-types": "1.3.5" } }, "sha512-RnygCqNrd3srIPEWBd5LFeUYG7plCoH2Yw9WaZGyNmdTEei+gWaHqydbaIRkIkcbXwhBT94q78QljxN0Sk838w=="],
|
||||
|
||||
"@types/node": ["@types/node@25.0.3", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-W609buLVRVmeW693xKfzHeIV6nJGGz98uCPfeXI1ELMLXVeKYZ9m15fAMSaUPBHYLGFsVRcMmSCksQOrZV9BYA=="],
|
||||
|
||||
"buffer-equal-constant-time": ["buffer-equal-constant-time@1.0.1", "", {}, "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA=="],
|
||||
|
||||
"bun-types": ["bun-types@1.3.5", "", { "dependencies": { "@types/node": "*" } }, "sha512-inmAYe2PFLs0SUbFOWSVD24sg1jFlMPxOjOSSCYqUgn4Hsc3rDc7dFvfVYjFPNHtov6kgUeulV4SxbuIV/stPw=="],
|
||||
|
||||
"dotenv": ["dotenv@17.2.3", "", {}, "sha512-JVUnt+DUIzu87TABbhPmNfVdBDt18BLOWjMUFJMSi/Qqg7NTYtabbvSNJGOJ7afbRuv9D/lngizHtP7QyLQ+9w=="],
|
||||
|
||||
"ecdsa-sig-formatter": ["ecdsa-sig-formatter@1.0.11", "", { "dependencies": { "safe-buffer": "^5.0.1" } }, "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ=="],
|
||||
|
||||
"hono": ["hono@4.11.1", "", {}, "sha512-KsFcH0xxHes0J4zaQgWbYwmz3UPOOskdqZmItstUG93+Wk1ePBLkLGwbP9zlmh1BFUiL8Qp+Xfu9P7feJWpGNg=="],
|
||||
|
||||
"jsonwebtoken": ["jsonwebtoken@9.0.3", "", { "dependencies": { "jws": "^4.0.1", "lodash.includes": "^4.3.0", "lodash.isboolean": "^3.0.3", "lodash.isinteger": "^4.0.4", "lodash.isnumber": "^3.0.3", "lodash.isplainobject": "^4.0.6", "lodash.isstring": "^4.0.1", "lodash.once": "^4.0.0", "ms": "^2.1.1", "semver": "^7.5.4" } }, "sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g=="],
|
||||
|
||||
"jwa": ["jwa@2.0.1", "", { "dependencies": { "buffer-equal-constant-time": "^1.0.1", "ecdsa-sig-formatter": "1.0.11", "safe-buffer": "^5.0.1" } }, "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg=="],
|
||||
|
||||
"jws": ["jws@4.0.1", "", { "dependencies": { "jwa": "^2.0.1", "safe-buffer": "^5.0.1" } }, "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA=="],
|
||||
|
||||
"lodash.includes": ["lodash.includes@4.3.0", "", {}, "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w=="],
|
||||
|
||||
"lodash.isboolean": ["lodash.isboolean@3.0.3", "", {}, "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg=="],
|
||||
|
||||
"lodash.isinteger": ["lodash.isinteger@4.0.4", "", {}, "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA=="],
|
||||
|
||||
"lodash.isnumber": ["lodash.isnumber@3.0.3", "", {}, "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw=="],
|
||||
|
||||
"lodash.isplainobject": ["lodash.isplainobject@4.0.6", "", {}, "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA=="],
|
||||
|
||||
"lodash.isstring": ["lodash.isstring@4.0.1", "", {}, "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw=="],
|
||||
|
||||
"lodash.once": ["lodash.once@4.1.1", "", {}, "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg=="],
|
||||
|
||||
"ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
|
||||
|
||||
"pocketbase": ["pocketbase@0.26.5", "", {}, "sha512-SXcq+sRvVpNxfLxPB1C+8eRatL7ZY4o3EVl/0OdE3MeR9fhPyZt0nmmxLqYmkLvXCN9qp3lXWV/0EUYb3MmMXQ=="],
|
||||
|
||||
"safe-buffer": ["safe-buffer@5.2.1", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="],
|
||||
|
||||
"semver": ["semver@7.7.3", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q=="],
|
||||
|
||||
"tslib": ["tslib@2.8.1", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
|
||||
|
||||
"undici-types": ["undici-types@7.16.0", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
|
||||
|
||||
"uuid": ["uuid@8.3.2", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg=="],
|
||||
}
|
||||
}
|
||||
+696
@@ -0,0 +1,696 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>PB + Microsoft Graph</title>
|
||||
<script src="https://cdn.tailwindcss.com"></script>
|
||||
<script>
|
||||
tailwind.config = {
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
primary: '#4c51bf',
|
||||
secondary: '#5b21b6',
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
</head>
|
||||
<body class="min-h-screen bg-gradient-to-br from-primary to-secondary p-4 sm:p-8 flex justify-center items-center font-sans relative">
|
||||
<!-- Top-right display name -->
|
||||
<div id="userDisplay" class="hidden absolute top-4 right-4 text-white text-sm font-semibold drop-shadow">
|
||||
<span id="userDisplayName"></span>
|
||||
</div>
|
||||
|
||||
<!-- Bottom-left email -->
|
||||
<div id="userEmail" class="hidden absolute bottom-4 left-4 text-white text-sm drop-shadow">
|
||||
<span id="userEmailValue"></span>
|
||||
</div>
|
||||
|
||||
<!-- Bottom-right version -->
|
||||
<div class="absolute bottom-4 right-4 text-white/80 text-xs drop-shadow">
|
||||
v1.0.0-alpha3
|
||||
</div>
|
||||
|
||||
<!-- Login Container -->
|
||||
<div id="loginContainer" class="bg-white rounded-2xl shadow-2xl max-w-md w-full p-8">
|
||||
<div class="text-center mb-8">
|
||||
<h1 class="text-4xl font-bold text-gray-800 mb-2">PB + Microsoft Graph</h1>
|
||||
<p class="text-gray-600">Sign in with Microsoft</p>
|
||||
</div>
|
||||
|
||||
<div class="space-y-6">
|
||||
<p class="text-gray-700 text-center">Sign in with your Microsoft account</p>
|
||||
<button type="button" id="loginBtn" class="w-full py-3 px-4 bg-gradient-to-br from-primary to-secondary text-white font-semibold rounded-lg hover:opacity-95 transition-opacity shadow-lg hover:shadow-xl">
|
||||
Login with Microsoft
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div id="loginError" class="hidden mt-4 p-3 bg-red-50 border border-red-200 text-red-700 rounded-lg text-sm"></div>
|
||||
</div>
|
||||
|
||||
<!-- Note + Audio Container -->
|
||||
<div id="noteContainer" class="hidden bg-white rounded-2xl shadow-2xl max-w-xl w-full p-8 space-y-6">
|
||||
<div class="flex items-center justify-between">
|
||||
<h2 class="text-2xl font-bold text-gray-800">New Note</h2>
|
||||
<span id="graphStatus" class="text-xs px-2 py-1 rounded bg-gray-100 text-gray-600">Graph: checking…</span>
|
||||
</div>
|
||||
<div class="space-y-4">
|
||||
<div class="flex items-center justify-between">
|
||||
<label class="block text-sm font-medium text-gray-700">Note Text</label>
|
||||
<button id="voiceBtn" class="flex items-center gap-2 px-3 py-1 rounded bg-purple-600 text-white text-sm font-semibold hover:bg-purple-700 transition-colors" title="Click to speak">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
|
||||
<path fill-rule="evenodd" d="M7 4a3 3 0 016 0v4a3 3 0 11-6 0V4zm4 10.93A7.001 7.001 0 0017 8a1 1 0 10-2 0A5 5 0 015 8a1 1 0 00-2 0 7.001 7.001 0 006 6.93V17H6a1 1 0 100 2h8a1 1 0 100-2h-3v-2.07z" clip-rule="evenodd" />
|
||||
</svg>
|
||||
<span id="voiceBtnText">Speak</span>
|
||||
</button>
|
||||
</div>
|
||||
<textarea id="noteText" rows="4" class="w-full rounded-lg border border-gray-300 p-3 focus:outline-none focus:ring-2 focus:ring-primary" placeholder="Type your note or click 'Speak' to dictate..."></textarea>
|
||||
<div id="voiceStatus" class="hidden text-xs text-gray-600 flex items-center gap-2">
|
||||
<span class="inline-block w-2 h-2 bg-red-600 rounded-full animate-pulse"></span>
|
||||
<span id="voiceStatusText">Listening...</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<div class="flex items-center gap-3">
|
||||
<button id="recordBtn" class="px-4 py-2 rounded bg-primary text-white font-semibold disabled:opacity-50">Record Audio</button>
|
||||
<button id="stopBtn" class="px-4 py-2 rounded bg-gray-200 text-gray-800 font-semibold disabled:opacity-50" disabled>Stop</button>
|
||||
<button id="testMicBtn" class="px-4 py-2 rounded bg-blue-600 text-white font-semibold text-sm">Test Mic</button>
|
||||
<a id="clearAudioLink" href="#" class="text-sm text-gray-600 underline hidden">Clear audio</a>
|
||||
</div>
|
||||
<audio id="audioPreview" controls class="hidden w-full"></audio>
|
||||
<div id="recordStatus" class="text-xs text-gray-500">No audio recorded.</div>
|
||||
<div id="micTestResults" class="hidden p-3 bg-blue-50 border border-blue-200 rounded text-xs space-y-1">
|
||||
<div><strong>Mic Test Results:</strong></div>
|
||||
<div>Peak Level: <span id="micPeakLevel">0</span>%</div>
|
||||
<div>Average Level: <span id="micAvgLevel">0</span>%</div>
|
||||
<div>Status: <span id="micStatus">Testing...</span></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center gap-3">
|
||||
<button id="submitNoteBtn" class="px-4 py-2 rounded bg-secondary text-white font-semibold">Submit Note</button>
|
||||
<div id="submitStatus" class="text-sm text-gray-600"></div>
|
||||
</div>
|
||||
<hr class="my-4"/>
|
||||
<div class="space-y-2">
|
||||
<div class="flex items-center gap-3">
|
||||
<button id="loadLastBtn" class="px-4 py-2 rounded bg-gray-800 text-white font-semibold">Load Last Note</button>
|
||||
<span id="loadStatus" class="text-sm text-gray-600"></span>
|
||||
</div>
|
||||
<div id="lastNote" class="hidden space-y-2">
|
||||
<div class="text-sm text-gray-700"><strong>Note:</strong> <span id="lastNoteText"></span></div>
|
||||
<details class="text-xs text-gray-500">
|
||||
<summary class="cursor-pointer select-none">Show raw note content</summary>
|
||||
<pre id="lastNoteRaw" class="mt-2 p-2 bg-gray-50 border border-gray-200 rounded overflow-x-auto"></pre>
|
||||
</details>
|
||||
<audio id="lastNoteAudio" controls class="w-full"></audio>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/pocketbase/dist/pocketbase.umd.js"></script>
|
||||
<script>
|
||||
const APP_VERSION = '1.0.0-alpha3';
|
||||
console.log(`App version: ${APP_VERSION}`);
|
||||
// Initialize PocketBase client
|
||||
const pb = new PocketBase('https://pocketbase.ccllc.pro');
|
||||
|
||||
// Collections (from .env in scaffold)
|
||||
const NOTES_COLLECTION = 'Notes';
|
||||
const ATTACHMENTS_COLLECTION = 'Attachments';
|
||||
const ATTACHMENTS_FILE_FIELD = 'file';
|
||||
const ATTACHMENTS_PBID_FIELD = 'pb_id';
|
||||
const NOTE_BODY_HTML_FIELD = 'body_html';
|
||||
const NOTE_BODY_PLAIN_FIELD = 'body_plain';
|
||||
const NOTE_USERNAME_FIELD = 'Username';
|
||||
let displayNameCache = 'Unknown User';
|
||||
let mediaRecorder = null;
|
||||
let recordedChunks = [];
|
||||
let recordedBlob = null;
|
||||
let recognition = null;
|
||||
let isRecognizing = false;
|
||||
|
||||
// --- Voice Recognition Setup ---
|
||||
let voiceStartPosition = 0; // Track where voice input started
|
||||
let lastInterimLength = 0; // Track interim text length
|
||||
|
||||
function setupVoiceRecognition() {
|
||||
// Check for Web Speech API support
|
||||
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
|
||||
if (!SpeechRecognition) {
|
||||
console.warn('Web Speech API not supported in this browser');
|
||||
document.getElementById('voiceBtn').disabled = true;
|
||||
document.getElementById('voiceBtn').title = 'Speech recognition not supported';
|
||||
return null;
|
||||
}
|
||||
|
||||
recognition = new SpeechRecognition();
|
||||
recognition.continuous = true;
|
||||
recognition.interimResults = true;
|
||||
recognition.lang = 'en-US';
|
||||
|
||||
recognition.onstart = () => {
|
||||
isRecognizing = true;
|
||||
const noteTextArea = document.getElementById('noteText');
|
||||
voiceStartPosition = noteTextArea.value.length; // Remember where we started
|
||||
lastInterimLength = 0;
|
||||
document.getElementById('voiceStatus').classList.remove('hidden');
|
||||
document.getElementById('voiceBtn').classList.add('bg-red-600', 'hover:bg-red-700');
|
||||
document.getElementById('voiceBtn').classList.remove('bg-purple-600', 'hover:bg-purple-700');
|
||||
document.getElementById('voiceBtnText').textContent = 'Stop';
|
||||
};
|
||||
|
||||
recognition.onresult = (event) => {
|
||||
const noteTextArea = document.getElementById('noteText');
|
||||
let finalTranscript = '';
|
||||
let interimTranscript = '';
|
||||
|
||||
// Build transcript from all results
|
||||
for (let i = 0; i < event.results.length; i++) {
|
||||
const transcript = event.results[i][0].transcript;
|
||||
if (event.results[i].isFinal) {
|
||||
finalTranscript += transcript + ' ';
|
||||
} else {
|
||||
interimTranscript += transcript;
|
||||
}
|
||||
}
|
||||
|
||||
// Remove the previous interim text (if any) and add new text
|
||||
const baseText = noteTextArea.value.substring(0, voiceStartPosition);
|
||||
noteTextArea.value = baseText + finalTranscript + interimTranscript;
|
||||
|
||||
// Update status
|
||||
document.getElementById('voiceStatusText').textContent =
|
||||
interimTranscript ? `Listening: "${interimTranscript}"` : 'Listening...';
|
||||
|
||||
// Move cursor to end
|
||||
noteTextArea.scrollTop = noteTextArea.scrollHeight;
|
||||
};
|
||||
|
||||
recognition.onerror = (event) => {
|
||||
console.error('Speech recognition error:', event.error);
|
||||
let errorMsg = 'Error: ';
|
||||
switch(event.error) {
|
||||
case 'no-speech':
|
||||
errorMsg += 'No speech detected. Try again.';
|
||||
break;
|
||||
case 'audio-capture':
|
||||
errorMsg += 'No microphone found.';
|
||||
break;
|
||||
case 'not-allowed':
|
||||
errorMsg += 'Microphone permission denied.';
|
||||
break;
|
||||
default:
|
||||
errorMsg += event.error;
|
||||
}
|
||||
document.getElementById('voiceStatusText').textContent = errorMsg;
|
||||
setTimeout(() => stopVoiceRecognition(), 2000);
|
||||
};
|
||||
|
||||
recognition.onend = () => {
|
||||
if (isRecognizing) {
|
||||
// If we're still supposed to be recognizing, restart
|
||||
try {
|
||||
recognition.start();
|
||||
} catch (e) {
|
||||
console.log('Recognition ended:', e);
|
||||
stopVoiceRecognition();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return recognition;
|
||||
}
|
||||
|
||||
function startVoiceRecognition() {
|
||||
if (!recognition) {
|
||||
recognition = setupVoiceRecognition();
|
||||
if (!recognition) return;
|
||||
}
|
||||
|
||||
// Capture the current text length as the starting position
|
||||
const noteTextArea = document.getElementById('noteText');
|
||||
voiceStartPosition = noteTextArea.value.length;
|
||||
lastInterimLength = 0;
|
||||
|
||||
try {
|
||||
recognition.start();
|
||||
} catch (e) {
|
||||
console.log('Recognition already started or error:', e);
|
||||
}
|
||||
}
|
||||
|
||||
function stopVoiceRecognition() {
|
||||
isRecognizing = false;
|
||||
if (recognition) {
|
||||
try {
|
||||
recognition.stop();
|
||||
} catch (e) {
|
||||
console.log('Error stopping recognition:', e);
|
||||
}
|
||||
}
|
||||
document.getElementById('voiceStatus').classList.add('hidden');
|
||||
document.getElementById('voiceBtn').classList.remove('bg-red-600', 'hover:bg-red-700');
|
||||
document.getElementById('voiceBtn').classList.add('bg-purple-600', 'hover:bg-purple-700');
|
||||
document.getElementById('voiceBtnText').textContent = 'Speak';
|
||||
}
|
||||
|
||||
// Voice button click handler
|
||||
document.getElementById('voiceBtn').addEventListener('click', () => {
|
||||
if (isRecognizing) {
|
||||
stopVoiceRecognition();
|
||||
} else {
|
||||
startVoiceRecognition();
|
||||
}
|
||||
});
|
||||
|
||||
// --- Rich text helpers (TipTap-style JSON) ---
|
||||
function tiptapDocFromText(text) {
|
||||
const safe = (text || '').replace(/\r\n|\r|\n/g, '\n');
|
||||
const lines = safe.split('\n');
|
||||
const content = lines.map(line => ({
|
||||
type: 'paragraph',
|
||||
content: line ? [{ type: 'text', text: line }] : []
|
||||
}));
|
||||
return { type: 'doc', content };
|
||||
}
|
||||
|
||||
function tiptapToPlainText(doc) {
|
||||
if (!doc) return '';
|
||||
try {
|
||||
const parts = [];
|
||||
const walk = (node) => {
|
||||
if (!node) return;
|
||||
if (Array.isArray(node)) {
|
||||
node.forEach(walk);
|
||||
return;
|
||||
}
|
||||
if (node.type === 'text' && node.text) {
|
||||
parts.push(node.text);
|
||||
return;
|
||||
}
|
||||
if (node.type === 'hardBreak') {
|
||||
parts.push('\n');
|
||||
return;
|
||||
}
|
||||
if (node.content) {
|
||||
let beforeLen = parts.length;
|
||||
walk(node.content);
|
||||
// Add newline between block nodes
|
||||
const blockTypes = ['paragraph', 'heading', 'blockquote', 'codeBlock'];
|
||||
if (blockTypes.includes(node.type) && parts.length !== beforeLen) {
|
||||
parts.push('\n');
|
||||
}
|
||||
}
|
||||
};
|
||||
walk(doc);
|
||||
return parts.join('').replace(/\n{3,}/g, '\n\n').trim();
|
||||
} catch (e) {
|
||||
return typeof doc === 'string' ? doc : JSON.stringify(doc);
|
||||
}
|
||||
}
|
||||
|
||||
// --- HTML helpers for PocketBase editor fields ---
|
||||
function plainTextToHTML(text) {
|
||||
const safe = (text || '').replace(/\r\n|\r|\n/g, '\n');
|
||||
const lines = safe.split('\n');
|
||||
// Wrap each line in <p>, preserve blank lines
|
||||
const html = lines.map(line => `<p>${escapeHtml(line)}</p>`).join('');
|
||||
return html;
|
||||
}
|
||||
|
||||
function escapeHtml(str) {
|
||||
return String(str)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
function htmlToPlainText(html) {
|
||||
try {
|
||||
const div = document.createElement('div');
|
||||
div.innerHTML = html || '';
|
||||
return (div.innerText || '').trim();
|
||||
} catch {
|
||||
return html || '';
|
||||
}
|
||||
}
|
||||
|
||||
// Update auth UI based on login state
|
||||
function updateAuthUI() {
|
||||
const loginContainer = document.getElementById('loginContainer');
|
||||
const userDisplay = document.getElementById('userDisplay');
|
||||
const userEmail = document.getElementById('userEmail');
|
||||
if (pb.authStore.isValid) {
|
||||
loginContainer.classList.add('hidden');
|
||||
userDisplay.classList.remove('hidden');
|
||||
userEmail.classList.remove('hidden');
|
||||
document.getElementById('noteContainer').classList.remove('hidden');
|
||||
} else {
|
||||
loginContainer.classList.remove('hidden');
|
||||
userDisplay.classList.add('hidden');
|
||||
userEmail.classList.add('hidden');
|
||||
document.getElementById('loginError').classList.add('hidden');
|
||||
document.getElementById('noteContainer').classList.add('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
// Check for tokens and log success
|
||||
async function checkTokens() {
|
||||
const pbToken = pb.authStore.token;
|
||||
|
||||
if (!pbToken) {
|
||||
console.log('❌ No PocketBase token found');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('✓ PocketBase token:', pbToken ? '(present)' : '(missing)');
|
||||
|
||||
try {
|
||||
const healthResp = await fetch('/health');
|
||||
const health = await healthResp.json();
|
||||
if (health.ok) {
|
||||
console.log('✓ Backend health check passed');
|
||||
}
|
||||
const graphBadge = document.getElementById('graphStatus');
|
||||
const graphResp = await fetch('/api/graph/status');
|
||||
if (graphResp.ok) {
|
||||
const gs = await graphResp.json();
|
||||
graphBadge.textContent = `Graph: active (exp ${new Date(gs.expiresOnISO).toLocaleTimeString()})`;
|
||||
graphBadge.className = 'text-xs px-2 py-1 rounded bg-green-100 text-green-700';
|
||||
console.log('✓ Graph token active');
|
||||
} else {
|
||||
graphBadge.textContent = 'Graph: error';
|
||||
graphBadge.className = 'text-xs px-2 py-1 rounded bg-red-100 text-red-700';
|
||||
console.log('❌ Graph token status failed');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('❌ Failed to check backend:', error.message);
|
||||
const graphBadge = document.getElementById('graphStatus');
|
||||
graphBadge.textContent = 'Graph: error';
|
||||
graphBadge.className = 'text-xs px-2 py-1 rounded bg-red-100 text-red-700';
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureUserLogged() {
|
||||
// If already have a valid token, just refresh to get model details
|
||||
if (pb.authStore.isValid && pb.authStore.token) {
|
||||
try {
|
||||
const refresh = await pb.collection('Users').authRefresh();
|
||||
const record = refresh?.record || pb.authStore.record || pb.authStore.model;
|
||||
const meta = refresh?.meta || {};
|
||||
const model = pb.authStore.model;
|
||||
const displayName = record?.name || model?.name || meta?.name || record?.email || model?.email || meta?.email || 'Unknown User';
|
||||
const email = record?.email || model?.email || meta?.email || '(no email)';
|
||||
displayNameCache = displayName;
|
||||
document.getElementById('userDisplayName').textContent = displayName;
|
||||
document.getElementById('userEmailValue').textContent = email;
|
||||
console.log('User record:', record);
|
||||
console.log('User meta:', meta);
|
||||
console.log('Auth store model:', model);
|
||||
console.log(`User display name: ${displayName}`);
|
||||
console.log(`User email: ${email}`);
|
||||
console.log('PB token:', pb.authStore.token ? '(present)' : '(missing)');
|
||||
updateAuthUI();
|
||||
await checkTokens();
|
||||
return true;
|
||||
} catch (e) {
|
||||
console.warn('Existing token invalid, clearing and reauth needed', e);
|
||||
pb.authStore.clear();
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Handle login button click
|
||||
document.getElementById('loginBtn').addEventListener('click', async (e) => {
|
||||
e.preventDefault();
|
||||
const loginBtn = document.getElementById('loginBtn');
|
||||
const loginError = document.getElementById('loginError');
|
||||
|
||||
loginBtn.disabled = true;
|
||||
loginBtn.textContent = 'Checking session...';
|
||||
loginError.classList.add('hidden');
|
||||
|
||||
// If we already have a valid token, just use it
|
||||
const hadToken = await ensureUserLogged();
|
||||
if (hadToken) {
|
||||
loginBtn.disabled = false;
|
||||
loginBtn.textContent = 'Login with Microsoft';
|
||||
return;
|
||||
}
|
||||
|
||||
// Otherwise perform OAuth
|
||||
loginBtn.textContent = 'Logging in...';
|
||||
try {
|
||||
const authData = await pb.collection('Users').authWithOAuth2({ provider: 'microsoft' });
|
||||
console.log('✓ Logged in with Microsoft');
|
||||
const record = authData?.record || pb.authStore.record || pb.authStore.model;
|
||||
const meta = authData?.meta || {};
|
||||
const model = pb.authStore.model;
|
||||
const displayName = record?.name || model?.name || meta?.name || record?.email || model?.email || meta?.email || 'Unknown User';
|
||||
const email = record?.email || model?.email || meta?.email || '(no email)';
|
||||
displayNameCache = displayName;
|
||||
document.getElementById('userDisplayName').textContent = displayName;
|
||||
document.getElementById('userEmailValue').textContent = email;
|
||||
console.log('User record:', record);
|
||||
console.log('User meta:', meta);
|
||||
console.log('Auth store model:', model);
|
||||
console.log(`User display name: ${displayName}`);
|
||||
console.log(`User email: ${email}`);
|
||||
console.log('PB token:', pb.authStore.token ? '(present)' : '(missing)');
|
||||
updateAuthUI();
|
||||
await checkTokens();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
loginError.textContent = `Login failed: ${error.message}`;
|
||||
loginError.classList.remove('hidden');
|
||||
} finally {
|
||||
loginBtn.disabled = false;
|
||||
loginBtn.textContent = 'Login with Microsoft';
|
||||
}
|
||||
});
|
||||
|
||||
// Initial auth UI update
|
||||
updateAuthUI();
|
||||
|
||||
// If already logged in, use existing token
|
||||
if (pb.authStore.isValid && pb.authStore.token) {
|
||||
ensureUserLogged();
|
||||
}
|
||||
|
||||
// --- Audio recording setup ---
|
||||
async function setupRecorder() {
|
||||
const stream = await navigator.mediaDevices.getUserMedia({
|
||||
audio: {
|
||||
autoGainControl: true
|
||||
}
|
||||
});
|
||||
recordedChunks = [];
|
||||
recordedBlob = null;
|
||||
mediaRecorder = new MediaRecorder(stream);
|
||||
mediaRecorder.ondataavailable = (e) => {
|
||||
if (e.data && e.data.size > 0) recordedChunks.push(e.data);
|
||||
};
|
||||
mediaRecorder.onstop = () => {
|
||||
recordedBlob = new Blob(recordedChunks, { type: mediaRecorder.mimeType });
|
||||
const audioEl = document.getElementById('audioPreview');
|
||||
audioEl.src = URL.createObjectURL(recordedBlob);
|
||||
audioEl.volume = 1.0;
|
||||
audioEl.classList.remove('hidden');
|
||||
document.getElementById('clearAudioLink').classList.remove('hidden');
|
||||
document.getElementById('recordStatus').textContent = `Audio recorded (${mediaRecorder.mimeType}).`;
|
||||
};
|
||||
}
|
||||
|
||||
async function startRecording() {
|
||||
if (!mediaRecorder) await setupRecorder();
|
||||
recordedChunks = [];
|
||||
recordedBlob = null;
|
||||
mediaRecorder.start();
|
||||
document.getElementById('recordStatus').textContent = 'Recording…';
|
||||
document.getElementById('recordBtn').disabled = true;
|
||||
document.getElementById('stopBtn').disabled = false;
|
||||
}
|
||||
|
||||
function stopRecording() {
|
||||
if (mediaRecorder && mediaRecorder.state === 'recording') {
|
||||
mediaRecorder.stop();
|
||||
document.getElementById('recordBtn').disabled = false;
|
||||
document.getElementById('stopBtn').disabled = true;
|
||||
}
|
||||
}
|
||||
|
||||
function clearAudio() {
|
||||
recordedChunks = [];
|
||||
recordedBlob = null;
|
||||
const audioEl = document.getElementById('audioPreview');
|
||||
audioEl.src = '';
|
||||
audioEl.classList.add('hidden');
|
||||
document.getElementById('clearAudioLink').classList.add('hidden');
|
||||
document.getElementById('recordStatus').textContent = 'No audio recorded.';
|
||||
}
|
||||
|
||||
document.getElementById('recordBtn').addEventListener('click', startRecording);
|
||||
document.getElementById('stopBtn').addEventListener('click', stopRecording);
|
||||
document.getElementById('clearAudioLink').addEventListener('click', (e) => { e.preventDefault(); clearAudio(); });
|
||||
|
||||
// --- Test mic input levels ---
|
||||
async function testMicrophone() {
|
||||
const resultsDiv = document.getElementById('micTestResults');
|
||||
resultsDiv.classList.remove('hidden');
|
||||
document.getElementById('micStatus').textContent = 'Testing... speak normally';
|
||||
|
||||
try {
|
||||
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
||||
const recorder = new MediaRecorder(stream);
|
||||
let testChunks = [];
|
||||
|
||||
recorder.ondataavailable = (e) => {
|
||||
if (e.data.size > 0) testChunks.push(e.data);
|
||||
};
|
||||
|
||||
recorder.onstop = () => {
|
||||
stream.getTracks().forEach(track => track.stop());
|
||||
|
||||
const totalSize = testChunks.reduce((sum, chunk) => sum + chunk.size, 0);
|
||||
// Rough estimation: 16kHz, 16-bit, mono = 32KB per second of audio
|
||||
// Expected for good audio is ~30-60KB for 2 seconds
|
||||
const estimatedLevel = Math.min(100, Math.round((totalSize / 32000) * 100));
|
||||
|
||||
document.getElementById('micPeakLevel').textContent = estimatedLevel;
|
||||
document.getElementById('micAvgLevel').textContent = totalSize + ' bytes';
|
||||
|
||||
if (totalSize < 10000) {
|
||||
document.getElementById('micStatus').textContent = '⚠️ Very low - check mic or volume';
|
||||
} else if (totalSize < 25000) {
|
||||
document.getElementById('micStatus').textContent = '⚠️ Low - increase mic gain or speak louder';
|
||||
} else if (totalSize > 80000) {
|
||||
document.getElementById('micStatus').textContent = '⚠️ Too loud - may distort';
|
||||
} else {
|
||||
document.getElementById('micStatus').textContent = '✓ Good level';
|
||||
}
|
||||
};
|
||||
|
||||
recorder.start();
|
||||
setTimeout(() => recorder.stop(), 2000);
|
||||
} catch (e) {
|
||||
document.getElementById('micStatus').textContent = `Error: ${e.message}`;
|
||||
console.error('Mic test error:', e);
|
||||
}
|
||||
}
|
||||
|
||||
document.getElementById('testMicBtn').addEventListener('click', testMicrophone);
|
||||
|
||||
// --- Submit note ---
|
||||
async function submitNote() {
|
||||
const statusEl = document.getElementById('submitStatus');
|
||||
statusEl.textContent = '';
|
||||
const noteText = document.getElementById('noteText').value.trim();
|
||||
if (!pb.authStore.isValid) {
|
||||
statusEl.textContent = 'Not authenticated.';
|
||||
return;
|
||||
}
|
||||
if (!noteText) {
|
||||
statusEl.textContent = 'Please enter note text.';
|
||||
return;
|
||||
}
|
||||
try {
|
||||
// Create note record with display name and timestamp
|
||||
const timestamp = new Date().toISOString();
|
||||
const noteRecord = await pb.collection(NOTES_COLLECTION).create({
|
||||
[NOTE_BODY_HTML_FIELD]: plainTextToHTML(noteText),
|
||||
[NOTE_BODY_PLAIN_FIELD]: noteText,
|
||||
[NOTE_USERNAME_FIELD]: `${displayNameCache} - ${timestamp}`,
|
||||
userId: pb.authStore.model?.id || pb.authStore.record?.id,
|
||||
});
|
||||
let attachmentRecord = null;
|
||||
if (recordedBlob) {
|
||||
const file = new File([recordedBlob], 'note-audio.webm', { type: recordedBlob.type || 'audio/webm' });
|
||||
const fd = new FormData();
|
||||
fd.append(ATTACHMENTS_FILE_FIELD, file);
|
||||
fd.append(ATTACHMENTS_PBID_FIELD, noteRecord.id);
|
||||
attachmentRecord = await pb.collection(ATTACHMENTS_COLLECTION).create(fd);
|
||||
}
|
||||
statusEl.textContent = `Saved note ${noteRecord.id}` + (attachmentRecord ? ` with audio ${attachmentRecord.id}` : '');
|
||||
clearAudio();
|
||||
document.getElementById('noteText').value = '';
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
statusEl.textContent = `Error saving: ${e.message}`;
|
||||
}
|
||||
}
|
||||
|
||||
document.getElementById('submitNoteBtn').addEventListener('click', submitNote);
|
||||
|
||||
// --- Load last note and attachment ---
|
||||
async function loadLastNote() {
|
||||
const loadStatus = document.getElementById('loadStatus');
|
||||
const lastNoteBox = document.getElementById('lastNote');
|
||||
loadStatus.textContent = '';
|
||||
lastNoteBox.classList.add('hidden');
|
||||
try {
|
||||
const notes = await pb.collection(NOTES_COLLECTION).getList(1, 1, { sort: '-created' });
|
||||
if (!notes.items.length) {
|
||||
loadStatus.textContent = 'No notes found.';
|
||||
return;
|
||||
}
|
||||
const note = notes.items[0];
|
||||
function extractPlain(r) {
|
||||
// Try actual schema fields in order
|
||||
const candidates = [
|
||||
r[NOTE_BODY_PLAIN_FIELD],
|
||||
r[NOTE_BODY_HTML_FIELD],
|
||||
r.note,
|
||||
r.content,
|
||||
r.body,
|
||||
];
|
||||
for (const c of candidates) {
|
||||
if (c === undefined || c === null) continue;
|
||||
if (typeof c === 'string' && c.trim()) return c;
|
||||
if (typeof c === 'object') {
|
||||
const maybe = tiptapToPlainText(c);
|
||||
if (maybe && maybe.trim()) return maybe;
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
let plain = extractPlain(note);
|
||||
// If `plain` is HTML, convert to text
|
||||
if (plain && /<\/?[a-z]/i.test(plain)) {
|
||||
plain = htmlToPlainText(plain);
|
||||
}
|
||||
document.getElementById('lastNoteText').textContent = plain || '(empty)';
|
||||
// Show raw for debugging
|
||||
const rawEl = document.getElementById('lastNoteRaw');
|
||||
rawEl.textContent = JSON.stringify({ body_html: note[NOTE_BODY_HTML_FIELD], body_plain: note[NOTE_BODY_PLAIN_FIELD], Username: note[NOTE_USERNAME_FIELD] }, null, 2);
|
||||
// Find attachment by pb_id
|
||||
const atts = await pb.collection(ATTACHMENTS_COLLECTION).getList(1, 1, {
|
||||
sort: '-created',
|
||||
filter: `${ATTACHMENTS_PBID_FIELD} = "${note.id}"`,
|
||||
});
|
||||
if (atts.items.length) {
|
||||
const att = atts.items[0];
|
||||
const url = pb.files.getUrl(att, att[ATTACHMENTS_FILE_FIELD]);
|
||||
const lastAudio = document.getElementById('lastNoteAudio');
|
||||
lastAudio.src = url;
|
||||
lastAudio.volume = 1.0;
|
||||
} else {
|
||||
document.getElementById('lastNoteAudio').src = '';
|
||||
}
|
||||
lastNoteBox.classList.remove('hidden');
|
||||
loadStatus.textContent = 'Loaded.';
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
loadStatus.textContent = `Error: ${e.message}`;
|
||||
}
|
||||
}
|
||||
|
||||
document.getElementById('loadLastBtn').addEventListener('click', loadLastNote);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"name": "prism-notes",
|
||||
"version": "1.0.0-alpha3",
|
||||
"description": "Prism Notes: PocketBase + Microsoft Graph OAuth capture app",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "bun run --watch server.ts",
|
||||
"start": "bun run server.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@azure/msal-node": "^2.6.7",
|
||||
"@microsoft/microsoft-graph-client": "^3.0.7",
|
||||
"dotenv": "^16.4.5",
|
||||
"hono": "^4.10.8",
|
||||
"pocketbase": "^0.26.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bun": "latest",
|
||||
"@types/node": "latest"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import { Hono } from 'hono';
|
||||
import { serveStatic } from 'hono/bun';
|
||||
import { cors } from 'hono/cors';
|
||||
import PocketBase from 'pocketbase';
|
||||
import { ConfidentialClientApplication } from '@azure/msal-node';
|
||||
import { readFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
|
||||
// Load env from local .env
|
||||
const envPath = join(import.meta.dir, '.env');
|
||||
try {
|
||||
const envContent = readFileSync(envPath, 'utf-8');
|
||||
envContent.split('\n').forEach(line => {
|
||||
const trimmed = line.trim();
|
||||
if (trimmed && !trimmed.startsWith('#')) {
|
||||
const [key, ...valueParts] = trimmed.split('=');
|
||||
if (key && valueParts.length > 0) {
|
||||
process.env[key.trim()] = valueParts.join('=').trim();
|
||||
}
|
||||
}
|
||||
});
|
||||
console.log('✓ Loaded env from .env');
|
||||
} catch (e) {
|
||||
console.warn('⚠ Could not load .env:', (e as Error).message);
|
||||
}
|
||||
|
||||
const app = new Hono();
|
||||
|
||||
// Enable CORS
|
||||
app.use('/*', cors({
|
||||
origin: '*',
|
||||
credentials: true,
|
||||
}));
|
||||
|
||||
// PocketBase client
|
||||
const pb = new PocketBase(process.env.PB_DB || 'http://127.0.0.1:8090');
|
||||
|
||||
// Use user's PocketBase token
|
||||
function setUserPocketBaseAuth(token: string) {
|
||||
pb.authStore.save(token, null);
|
||||
}
|
||||
|
||||
// MSAL config for Graph token (client credentials)
|
||||
const msalConfig = {
|
||||
auth: {
|
||||
clientId: process.env.CLIENT_ID || '',
|
||||
authority: `https://login.microsoftonline.com/${process.env.TENANT_ID}`,
|
||||
clientSecret: process.env.CLIENT_SECRET || '',
|
||||
},
|
||||
};
|
||||
const cca = new ConfidentialClientApplication(msalConfig);
|
||||
|
||||
// Simple in-memory cache for Graph token
|
||||
let graphTokenCache: { token: string; expiresOn: number } | null = null;
|
||||
|
||||
async function getGraphToken(): Promise<{ token: string; expiresOn: number }> {
|
||||
const now = Date.now();
|
||||
if (graphTokenCache && graphTokenCache.expiresOn - 60000 > now) {
|
||||
return graphTokenCache;
|
||||
}
|
||||
const result = await cca.acquireTokenByClientCredential({
|
||||
scopes: ['https://graph.microsoft.com/.default'],
|
||||
});
|
||||
if (!result || !result.accessToken) {
|
||||
throw new Error('Failed to acquire Graph token');
|
||||
}
|
||||
const expiresOn = result.expiresOn ? new Date(result.expiresOn).getTime() : now + 55 * 60 * 1000;
|
||||
graphTokenCache = { token: result.accessToken, expiresOn };
|
||||
return graphTokenCache;
|
||||
}
|
||||
|
||||
// Health check
|
||||
app.get('/health', (c) => {
|
||||
return c.json({ ok: true, pbDB: process.env.PB_DB });
|
||||
});
|
||||
|
||||
// Graph token status (acquires if missing/expired)
|
||||
app.get('/api/graph/status', async (c) => {
|
||||
try {
|
||||
const tokenInfo = await getGraphToken();
|
||||
return c.json({ active: true, expiresOnISO: new Date(tokenInfo.expiresOn).toISOString() });
|
||||
} catch (e) {
|
||||
return c.json({ active: false, error: (e as Error)?.message || 'Failed to acquire token' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// Submit endpoint (example)
|
||||
app.post('/api/submit', async (c) => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
const pbToken = body.pbToken;
|
||||
|
||||
if (!pbToken) {
|
||||
return c.json({ success: false, message: 'Missing pbToken' }, 401);
|
||||
}
|
||||
|
||||
// Validate user token
|
||||
setUserPocketBaseAuth(pbToken);
|
||||
try {
|
||||
await pb.collection(process.env.PB_AUTH_COLLECTION || 'Users').authRefresh();
|
||||
} catch (e) {
|
||||
console.error('auth_validation_failed', { message: (e as Error)?.message });
|
||||
return c.json({ success: false, message: 'Invalid token' }, 401);
|
||||
}
|
||||
|
||||
// Store in PocketBase collection (adjust fields as needed)
|
||||
const record = await pb
|
||||
.collection(process.env.PB_COLLECTION || 'Job_Info_TestEnv')
|
||||
.create({
|
||||
...body,
|
||||
submittedBy: pb.authStore.model?.email || 'unknown',
|
||||
submittedAt: new Date().toISOString(),
|
||||
});
|
||||
|
||||
console.log('submission_success', { recordId: record.id });
|
||||
return c.json({ success: true, message: 'Feedback submitted successfully', recordId: record.id });
|
||||
} catch (err) {
|
||||
console.error('submit_error', { message: (err as Error)?.message });
|
||||
return c.json({ success: false, message: 'Internal error' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// Serve static index.html
|
||||
app.get('/', async (c) => {
|
||||
const html = await Bun.file(new URL('./index.html', import.meta.url)).text();
|
||||
return c.html(html);
|
||||
});
|
||||
|
||||
const PORT = Number(process.env.PORT || 5500);
|
||||
console.log(`PBandGraph server running at http://localhost:${PORT}`);
|
||||
|
||||
export default {
|
||||
port: PORT,
|
||||
fetch: app.fetch,
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ESNext",
|
||||
"module": "ESNext",
|
||||
"lib": ["ESNext", "DOM", "DOM.Iterable"],
|
||||
"types": ["bun-types", "node", "bun"],
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"composite": true,
|
||||
"strict": true,
|
||||
"downlevelIteration": true,
|
||||
"skipLibCheck": true,
|
||||
"jsx": "react-jsx",
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"allowJs": true,
|
||||
"esModuleInterop": true,
|
||||
"resolveJsonModule": true
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user