diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..af896d8 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,19 @@ +name: test +on: + push: + branches: [main] + pull_request: +jobs: + test: + runs-on: ubuntu-latest + env: + ELECTRON_SKIP_BINARY_DOWNLOAD: "1" + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + - run: npm ci + - run: npm test + - run: npm run smoke diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..93eea39 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +node_modules/ +dist/ +release/ +.smartspectra-key +*.log +.DS_Store diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..8823ab8 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Subomi + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/PRIVACY.md b/PRIVACY.md new file mode 100644 index 0000000..378d162 --- /dev/null +++ b/PRIVACY.md @@ -0,0 +1,65 @@ +# Consent and data handling + +Heartwritten reads your face through your camera to estimate your heart rate, +pulse wave, breathing and smiles while you write a letter. This page says what +happens to that data. + +## Before anything starts + +The app opens on a consent screen. The camera stays off until you tick +"I'm the only person on camera, and I agree to this" and press +**Turn on the camera**. A red dot shows while the camera is on, and +**Stop camera** turns it off at any point; the rest of the letter then +carries no heartbeat. + +You choose, before you start: + +- whether the reader sees where you smiled (on by default) +- whether the reader sees words you typed and took back (off by default) +- whether the SmartSpectra SDK sends telemetry to Presage (off by default) + +## What is kept + +- **Kept:** the letter's text, when each character was typed, and numbers + sampled four times a second: heart rate, a breathing value and (if you + allow it) a smile score. Six seconds of the pulse wave for the seal. +- **Never kept:** video, photos, frames or anything that shows your face. + Words you delete are dropped unless you chose to share them. + +## Where it goes + +- **While you write**, nothing is saved to disk. The letter exists only in + the app's memory. +- **The SmartSpectra SDK** measures on your computer. Presage's documentation + says all metric computation runs on-device and the SDK calls Presage's + service only to check the API key, so it needs a network connection while + measuring. Presage says its telemetry does not include frames or vitals. Telemetry + is off in Heartwritten unless you turn it on; if you do, Presage receives + session summaries and device details linked to your API key. +- **When you seal it**, the letter is packed into a token that lives in the link + (after the `#`, which browsers don't send to servers) or in an HTML file you + save. Heartwritten has no server and no account. Nobody has the letter until + you send the link or file to them. +- **The reader page** can't send anything: its Content Security Policy blocks + every network request, and it loads nothing from anywhere else. + +## How long it lasts, and deleting it + +- Closing the writer forgets the letter unless you copied the link or saved the + file. +- A sealed letter lasts as long as the link or file does. Delete the file, or + the message you sent the link in, to delete the letter. Anyone you've sent it + to keeps their copy, as with any letter. +- Heartwritten stores nothing else. Your API key stays in the file or + environment variable you put it in. + +## AI + +Heartwritten uses no AI model of its own. The physiological estimates come from +the SmartSpectra SDK. + +## Not medical + +Heart rate and breathing are camera estimates for feeling, not medicine. +Heartwritten makes no diagnosis, gives no health advice and isn't for +monitoring anyone. Only write with your own face on camera. diff --git a/README.md b/README.md index d2c8f88..97b3b6f 100644 --- a/README.md +++ b/README.md @@ -1 +1,118 @@ -# heartwritten \ No newline at end of file +# Heartwritten + +**Letters that carry the heartbeat you wrote them with.** + +You write a letter at your desk. While you type, your laptop camera reads your +heart rate, pulse wave, breathing and smiles with the +[Presage SmartSpectra SDK](https://physiology.presagetech.com). When you're +done, you seal it with a wax seal pressed from your own pulse wave. + +The person you send it to opens the envelope and watches the letter being +written again at your pace: the pauses where you thought, the sentence you +rushed, the ink warming where your heart sped up, the page rising and falling +with your breath, a soft glow where you smiled. At the end they see where your +heart was quickest and where it was steadiest. + +Nothing goes to a server. A sealed letter lives inside its link (in the part +after `#`, which browsers never send) or inside a single HTML file. + +## Try it + +You need Node 20 or newer and a webcam. + +``` +npm install +npm run start:sim +``` + +`start:sim` runs the whole app with simulated signals, so you can try it with +no key. Letters written this way are marked as samples, everywhere. + +To read the real thing: + +1. Get an API key from [physiology.presagetech.com](https://physiology.presagetech.com). +2. Put it in a file called `.smartspectra-key` in this folder (it's git-ignored), + or set `SMARTSPECTRA_API_KEY` in your shell. +3. Check the SDK and key work: `npm run smoke` +4. Write a letter: `npm start` + +The SDK ships native libraries for macOS on Apple silicon, Linux (x64 and arm64) +and Windows x64. Measurement runs on your computer; the SDK needs a network connection +only so Presage can check the key. + +To see a finished letter without the app, run `npm run sample` and open +`dist/sample-letter.html` in a browser. + +## Sharing by link + +The writer can save any letter as a file. To share by link instead, host the +reader page somewhere static and tell the writer its address: + +``` +npm run build # makes dist/reader/index.html, one self-contained file +``` + +Deploy `dist/reader` anywhere static (a `vercel.json` is included), then put +the address in `heartwritten.config.json`: + +```json +{ "readerUrl": "https://your-reader.example" } +``` + +or set `HEARTWRITTEN_READER_URL`. The reader has a Content Security Policy of +`default-src 'none'; connect-src 'none'`, so it can't send anything anywhere, +and the letter in the `#` part of the link never reaches the host's logs. + +## How it responds to human signals + +| Signal (SmartSpectra) | While writing | In the letter | +| --- | --- | --- | +| Pulse rate (`cardio.pulseRate`, stable values only) | Live number and a trace drawn in the ink colour | Ink colour per character: calm navy near the writer's own median, warming toward red as the heart quickens, cooling as it settles. A beating heart in the margin keeps time. The closing card finds the quickest and steadiest sentences. | +| Pulse wave (`cardio.arterialPressureTrace`) | Live trace | The wax seal: six seconds of the wave, wrapped into a ring and pressed into wax. Every seal is different. | +| Breathing (`breathing.upperTrace`, `breathing.rate`) | Breaths a minute | The paper rises and falls with the writer's breathing as it replays. | +| Smiles (`face.expression`, happy) | A small mark lights up | Words written while smiling glow softly. Optional. | +| Validation status | Plain-language hints: "move a little closer or further", "a little more light, please" | | + +Typing is recorded as timed edits, so the replay keeps the real rhythm. Long +pauses (over eight seconds) are shortened in the replay but noted in the margin. +Words you delete are dropped from the letter unless you choose to share them. + +## Privacy and consent + +The consent screen comes before the camera turns on, and says plainly what is +read, what is kept and where it goes. See [PRIVACY.md](PRIVACY.md) for the full +data handling, including the SDK's telemetry, which is off unless you turn it on. + +Heartwritten is for feeling, not medicine. Heart rate and breathing are camera +estimates. It makes no diagnosis and gives no health advice. + +## How it's built + +``` +app/main.cjs Electron main: window, camera permission, SDK IPC, key lookup +src/writer/ The writing desk (consent → write → seal) + sdk-source.js SmartSpectra renderer SDK, events decoded into metrics +src/reader/ The reader, built into one self-contained HTML file +src/shared/ + vitals.js Turns SDK metrics packets into steady pulse, breath and smile values + recorder.js Records timed edits and 4 Hz vitals while you write + letter-format.js Packs a letter into a compact, deflated, URL-safe token + playback.js Replays the edits and maps the heart to ink + summary.js Quickest and steadiest sentences, smiles, words taken back + seal.js Draws the wax seal from the pulse wave + sim-source.js Simulated SDK output for development and tests +test/ node --test: the core, plus the built pages in jsdom +``` + +`npm test` builds everything and runs 25 tests, including the reader replaying +a full letter and the writer going from consent to a sealed letter in +simulated mode. + +The Electron wiring follows Presage's `electron-quickstart` sample: the main +process binds the SDK's IPC, the preload exposes it, and the renderer runs +`SmartSpectraSDK` with the camera. + +## License + +MIT for this code (see [LICENSE](LICENSE)). The SmartSpectra SDK has its own +license from Presage Technologies. diff --git a/app/main.cjs b/app/main.cjs new file mode 100644 index 0000000..6cd53bc --- /dev/null +++ b/app/main.cjs @@ -0,0 +1,97 @@ +// main.cjs +// Electron main process for the Heartwritten writer. +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const { app, BrowserWindow, ipcMain, session } = require('electron'); + +const ROOT = path.join(__dirname, '..'); +const DIST = path.join(ROOT, 'dist'); + +// Packaged builds load the SDK's native runtime from resources/smartspectra. +if (app.isPackaged && !process.env.SMARTSPECTRA_CAPI_PATH) { + const LIB = { darwin: 'libsmartspectra_capi.dylib', win32: 'smartspectra_capi.dll', linux: 'libsmartspectra_capi.so' }[process.platform]; + if (LIB) process.env.SMARTSPECTRA_CAPI_PATH = path.join(process.resourcesPath, 'smartspectra', LIB); +} + +const SIMULATE = process.env.HEARTWRITTEN_SIMULATE === '1'; +// Where shared links open. Deploy dist/reader anywhere static and set this. +const READER_URL = process.env.HEARTWRITTEN_READER_URL || readConfig().readerUrl || ''; + +function readConfig() { + try { return JSON.parse(fs.readFileSync(path.join(ROOT, 'heartwritten.config.json'), 'utf8')); } catch { return {}; } +} + +// The key never ships in the repo: it comes from the environment or a local +// file that .gitignore keeps out of git. +function apiKey() { + if (process.env.SMARTSPECTRA_API_KEY) return process.env.SMARTSPECTRA_API_KEY.trim(); + for (const p of [path.join(ROOT, '.smartspectra-key'), path.join(app.getPath('userData'), 'smartspectra-key')]) { + try { const k = fs.readFileSync(p, 'utf8').trim(); if (k) return k; } catch { /* not there */ } + } + return ''; +} + +let mainWindow = null; + +function createWindow() { + mainWindow = new BrowserWindow({ + width: 1040, + height: 860, + minWidth: 720, + backgroundColor: '#e7dcc7', + title: 'Heartwritten', + webPreferences: { + preload: path.join(DIST, 'preload.cjs'), + contextIsolation: true, + sandbox: true, + nodeIntegration: false, + }, + }); + if (!SIMULATE) { + const { bindSmartSpectraIpc } = require('@smartspectra/node-sdk/main'); + bindSmartSpectraIpc(mainWindow); + } + lockDown(mainWindow); + mainWindow.loadFile(path.join(DIST, 'writer', 'index.html')); +} + +function lockDown(win) { + win.webContents.setWindowOpenHandler(() => ({ action: 'deny' })); + win.webContents.on('will-navigate', (e) => e.preventDefault()); +} + +// The reader opens in its own window with no preload and no camera. +function openPreview(token) { + if (!/^v1\.[A-Za-z0-9_-]+$/.test(token)) return false; + const win = new BrowserWindow({ + width: 900, height: 900, title: 'Your letter, as they will see it', backgroundColor: '#e9dfcc', + webPreferences: { contextIsolation: true, sandbox: true, nodeIntegration: false }, + }); + win.webContents.setWindowOpenHandler(() => ({ action: 'deny' })); + win.loadFile(path.join(DIST, 'reader', 'index.html'), { hash: token }); + return true; +} + +app.whenReady().then(() => { + // Camera only, video only, only for the writer page. + session.defaultSession.setPermissionRequestHandler((wc, permission, callback, details) => { + const url = (details && details.requestingUrl) || (wc && wc.getURL()) || ''; + const media = (details && details.mediaTypes) || []; + const ok = permission === 'media' && media.length === 1 && media[0] === 'video' + && url.startsWith('file://') && url.includes('/dist/writer/') + && mainWindow && wc === mainWindow.webContents; + callback(ok); + }); + + ipcMain.handle('hw:config', () => ({ hasKey: !!apiKey(), simulate: SIMULATE, readerUrl: READER_URL })); + ipcMain.handle('hw:api-key', (e) => (mainWindow && e.sender === mainWindow.webContents ? apiKey() : '')); + ipcMain.handle('hw:preview', (_e, token) => openPreview(token)); + + createWindow(); + app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) createWindow(); }); +}); + +app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit(); }); + diff --git a/docs/demo-script.md b/docs/demo-script.md new file mode 100644 index 0000000..ae4efbb --- /dev/null +++ b/docs/demo-script.md @@ -0,0 +1,25 @@ +# Demo video script (about 90 seconds) + +Record on your Mac with a real key, good light on your face and the room quiet. +Screen-record the app, with a small picture-in-picture of your face only for +shot 2. Write a short, real letter to someone (about 4 sentences) with one +moment that actually moves you, and one line that makes you smile. + +| # | Time | On screen | Voice-over | +| --- | --- | --- | --- | +| 1 | 0:00–0:08 | A typed message on a phone, then a scanned handwritten letter with a crossed-out word | "Handwritten letters told you how they felt to write. Typed ones don't." | +| 2 | 0:08–0:18 | Heartwritten consent screen; tick agree; camera on; live heart trace and bpm settle | "Heartwritten reads your heartbeat, breathing and smiles through the webcam, with Presage SmartSpectra. Nothing is saved, and nothing goes to a server." | +| 3 | 0:18–0:40 | Write the letter. Let the bpm visibly change at the emotional line. Smile once. Pause for a few seconds before the last line. | (Quiet. Let the typing and the live heart carry it.) | +| 4 | 0:40–0:48 | Press **Seal it with my heartbeat**; the wax seal presses in | "You seal it with your own pulse wave. No two seals are the same." | +| 5 | 0:48–1:15 | Open the link in a browser as the recipient. Tap the seal, it cracks. The letter writes itself: ink warming at the emotional line, the margin heart beating, a glow on the smiling words, "paused 9 seconds" in the margin | "They watch it written again, at your pace. The ink warms where your heart sped up. The page breathes with you." | +| 6 | 1:15–1:25 | The closing card: quickest and steadiest sentences | "And at the end, where your heart was quickest, and where it was steadiest." | +| 7 | 1:25–1:30 | The seal again, with the line "lives only in its link" | "Heartwritten. Letters that carry your heartbeat." | + +Tips: + +- Keep the camera picture out of shot 5: the letter is the point, and it shows + the recipient never sees your face. +- If the heart barely moves while writing, read the letter aloud once first, or + write about something you care about. Don't fake it with exercise; judges + will see the ink jump. +- Use the 1× replay speed for the emotional part, then skip to the end. diff --git a/docs/dev-post.md b/docs/dev-post.md new file mode 100644 index 0000000..70343dd --- /dev/null +++ b/docs/dev-post.md @@ -0,0 +1,80 @@ +--- +title: "Heartwritten: letters that carry the heartbeat you wrote them with" +tags: presagechallenge, devchallenge, electron, javascript +--- + +*This is a submission for the [Presage SmartSpectra SDK Challenge](https://dev.to/challenges/presage-2026-11-04).* + +## What I Built + +A handwritten letter used to tell you things the words didn't: where the pen pressed harder, where the writer stopped, the line they crossed out. Typed messages lost all of that. + +**Heartwritten** brings it back with the one signal that never lies about how a sentence felt to write: your heartbeat. + +You write a letter on your laptop. While you type, SmartSpectra reads your pulse, breathing and smiles through the webcam. When you're done you seal it with a wax seal pressed from six seconds of your own pulse wave, so no two seals are alike. + +The person you send it to taps the seal, it cracks, and they watch your letter being written again at your real pace: + +- the **ink warms** toward red where your heart sped up, and settles back to navy as you calmed down +- a small **heart in the margin beats** at your rate, sentence by sentence +- the **paper rises and falls** with your breathing +- words you wrote **while smiling glow** +- **pauses** stay in, and the long ones are noted in the margin ("paused 14 seconds") +- if you allow it, they see the words you **typed and took back** + +At the end, a card shows where your heart was quickest and where it was steadiest, with the sentences. + +There's no server and no account. A sealed letter lives entirely inside its link (in the part after `#`, which browsers never send anywhere) or in a single HTML file you can attach to an email. + +## Demo + + + + + +## Code + + + +Setup is in the README: `npm install`, add your SmartSpectra key, `npm start`. `npm run start:sim` runs the whole thing with simulated signals if you want to try it without a key. + +## How It Responds to Human Signals + +Every signal changes something you can see or hold in the finished letter. None of them is a number on a dashboard. + +| SmartSpectra signal | What it becomes | +| --- | --- | +| `cardio.pulseRate` (stable readings only) | The colour of each character's ink, measured against *your own* median for that letter, so a calm writer and an anxious one both get a full range. It also sets the beat of the margin heart, and finds the quickest and steadiest sentences. | +| `cardio.arterialPressureTrace` | The wax seal. Six seconds of the pulse wave, wrapped into a ring around your initial. | +| `breathing.upperTrace`, `breathing.rate` | The page breathing during replay. | +| `face.expression` (happy) | The glow on words you wrote smiling. Optional, and it's the only face metric I request. | +| Validation status | Gentle hints while you write: "move a little closer or further", "a little more light, please". | + +A few things I cared about: + +- **The signal follows the writing, not the clock.** Typing is recorded as timed edits and vitals at 4 Hz, and the replay lines them up, so the ink colour of a word is your heart rate *when you typed that word*. +- **Only trustworthy readings count.** Pulse values that SmartSpectra doesn't mark stable are ignored, and old readings go stale after six seconds rather than painting the rest of the letter. +- **Relative, not clinical.** The ink compares you to yourself in that letter. It never says a number is good or bad. +- **Graceful degradation.** If a key isn't allowed expressions, the app drops smiles and keeps going. If you stop the camera halfway, the rest of the letter simply carries no heartbeat. + +Under the hood it's an Electron app following Presage's quickstart pattern (main process binds the SDK IPC, the renderer runs `SmartSpectraSDK` with the camera), plus a reader page built into one self-contained HTML file. The letter is packed into a compact, deflated, URL-safe token, so a full page of writing with its heartbeat fits in a link of a few thousand characters. The repo has 25 tests, including the reader replaying a whole letter and the writer going from consent to a sealed letter. + +## Prize Categories + +Most Creative or Delightful Use. + +## Consent and Data Handling + +- **Consent first.** The app opens on a consent screen. The camera stays off until you confirm you're the only person on camera and agree. A red dot shows while it's on, and you can stop it at any time. +- **What's read:** heart rate, pulse wave, breathing and smiles, estimated by SmartSpectra from your face. Measurement runs on your computer; per Presage's docs, the SDK contacts Presage's service only to check the API key. +- **What's kept:** the text, when each character was typed, and numbers sampled four times a second. Never video, photos or frames. Words you delete are dropped unless you choose to share them. +- **Storage:** nothing is saved while you write. A sealed letter exists only in the link or file you choose to send. Heartwritten has no server, no database and no account. +- **Sharing:** only with whoever you send the link or file to. The reader page has a Content Security Policy that blocks every network request, so opening a letter sends nothing anywhere, and the `#` part of a link never reaches the host. +- **Retention and deletion:** a letter lasts as long as its link or file. Delete those and it's gone. Closing the writer forgets an unsent letter. +- **SDK telemetry:** off by default (`enableTelemetry: false`). You can turn it on in the consent screen; Presage says its telemetry contains session summaries and device details linked to the key, never frames or vitals. +- **AI:** none. All the physiology comes from SmartSpectra. +- **Not medical:** camera estimates for feeling, not medicine. No diagnosis, no health advice, and not for monitoring anyone. + +The full write-up is in [PRIVACY.md](https://github.com/ubmids/heartwritten/blob/main/PRIVACY.md). + + diff --git a/heartwritten.config.json b/heartwritten.config.json new file mode 100644 index 0000000..9a244ac --- /dev/null +++ b/heartwritten.config.json @@ -0,0 +1,3 @@ +{ + "readerUrl": "" +} diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..6a88373 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,1593 @@ +{ + "name": "heartwritten", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "heartwritten", + "version": "0.1.0", + "dependencies": { + "@smartspectra/node-sdk": "^3.5.0" + }, + "devDependencies": { + "electron": "^43.8.1", + "esbuild": "^0.25.12", + "jsdom": "^25.0.1" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@asamuzakjp/css-color": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-3.2.0.tgz", + "integrity": "sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@csstools/css-calc": "^2.1.3", + "@csstools/css-color-parser": "^3.0.9", + "@csstools/css-parser-algorithms": "^3.0.4", + "@csstools/css-tokenizer": "^3.0.3", + "lru-cache": "^10.4.3" + } + }, + "node_modules/@csstools/color-helpers": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.1.0.tgz", + "integrity": "sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@csstools/css-calc": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-2.1.4.tgz", + "integrity": "sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-color-parser": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-3.1.0.tgz", + "integrity": "sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "dependencies": { + "@csstools/color-helpers": "^5.1.0", + "@csstools/css-calc": "^2.1.4" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-parser-algorithms": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-3.0.5.tgz", + "integrity": "sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-tokenizer": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-3.0.4.tgz", + "integrity": "sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@electron-internal/extract-zip": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@electron-internal/extract-zip/-/extract-zip-1.0.8.tgz", + "integrity": "sha512-8iajeLFbzNwM0m3AsQZSZgYREWglAImyGvvFSWU34FgMW8sHlzdwj9QKvv9dgN7jMP591EFUF/sLOC3Jl9YIjQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=22.12.0" + } + }, + "node_modules/@electron/get": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@electron/get/-/get-5.1.0.tgz", + "integrity": "sha512-3kSBtG8ObcTVfXanm5vVJ6UnBLEVmVsRk1M+vGqCuMBV+XLCbJYuWQful+yIy0GQDsSlK0kHEriEHn7SPk4EnA==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.1.1", + "env-paths": "^3.0.0", + "graceful-fs": "^4.2.11", + "progress": "^2.0.3", + "semver": "^7.6.3", + "sumchecker": "^3.0.1" + }, + "engines": { + "node": ">=22.12.0" + }, + "optionalDependencies": { + "undici": "^7.24.4" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@protobufjs/aspromise": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", + "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/base64": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz", + "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/codegen": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.5.tgz", + "integrity": "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/eventemitter": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.1.tgz", + "integrity": "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/fetch": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.1.tgz", + "integrity": "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==", + "license": "BSD-3-Clause", + "dependencies": { + "@protobufjs/aspromise": "^1.1.1" + } + }, + "node_modules/@protobufjs/float": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz", + "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/path": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz", + "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/pool": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz", + "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/utf8": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.2.tgz", + "integrity": "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug==", + "license": "BSD-3-Clause" + }, + "node_modules/@smartspectra/node-sdk": { + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/@smartspectra/node-sdk/-/node-sdk-3.5.0.tgz", + "integrity": "sha512-SXTMzDP19gvdH6yI7v6tHmh/hDiAepoPnE+8U8QQoNvZLOGoouJJtkpbayG25KgfoWf+UP2y7Qql0R+eIqGzIw==", + "license": "SEE LICENSE IN LICENSE", + "dependencies": { + "@smartspectra/node-sdk-darwin-arm64": "3.5.0", + "@smartspectra/node-sdk-linux-arm64": "3.5.0", + "@smartspectra/node-sdk-linux-x64": "3.5.0", + "@smartspectra/node-sdk-win32-x64": "3.5.0", + "koffi": "^2.10.0", + "protobufjs": "^7.6.5" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@smartspectra/node-sdk-darwin-arm64": { + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/@smartspectra/node-sdk-darwin-arm64/-/node-sdk-darwin-arm64-3.5.0.tgz", + "integrity": "sha512-5RNNhEOu83CTNRFnu1nLj5PAyzXoLz0AH75yqYrcZXzNsYEF+vUPasbPTduNUp7c4tIELRAQUXPVaiyoMIsBVw==", + "license": "SEE LICENSE IN LICENSE" + }, + "node_modules/@smartspectra/node-sdk-linux-arm64": { + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/@smartspectra/node-sdk-linux-arm64/-/node-sdk-linux-arm64-3.5.0.tgz", + "integrity": "sha512-75X/B73kBY788l6z/kRCplHYMGPF+F5I4j3tL/uXbpN7WuiOKbwn+T+xxOMw3VFnaYVIi6+v4G4SUNqpTyH6qA==", + "license": "SEE LICENSE IN LICENSE" + }, + "node_modules/@smartspectra/node-sdk-linux-x64": { + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/@smartspectra/node-sdk-linux-x64/-/node-sdk-linux-x64-3.5.0.tgz", + "integrity": "sha512-j4jsdpuUtQmD9sKicEE9MfdYlLtC810rFqvkkvPZMwZmnswxkVoSzB0ZYyBT1T5PRG7SlzOmn4L41oVr4AwI+Q==", + "license": "SEE LICENSE IN LICENSE" + }, + "node_modules/@smartspectra/node-sdk-win32-x64": { + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/@smartspectra/node-sdk-win32-x64/-/node-sdk-win32-x64-3.5.0.tgz", + "integrity": "sha512-QO2bGu0TH+jGz7mx+iJNwHkTldInwQ2n8j5f1l740psEXd2hoP/pp1hXv4hYcFy3QIITTli1jln3NIJva8e5kw==", + "license": "SEE LICENSE IN LICENSE" + }, + "node_modules/@types/node": { + "version": "26.6.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz", + "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==", + "license": "MIT", + "dependencies": { + "undici-types": "~8.9.0" + } + }, + "node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dev": true, + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/cssstyle": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-4.6.0.tgz", + "integrity": "sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/css-color": "^3.2.0", + "rrweb-cssom": "^0.8.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/cssstyle/node_modules/rrweb-cssom": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.8.0.tgz", + "integrity": "sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==", + "dev": true, + "license": "MIT" + }, + "node_modules/data-urls": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz", + "integrity": "sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^14.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decimal.js": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", + "dev": true, + "license": "MIT" + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/electron": { + "version": "43.8.1", + "resolved": "https://registry.npmjs.org/electron/-/electron-43.8.1.tgz", + "integrity": "sha512-Qa6/xXODEn60oIkyuV8jXmyX84z6nicuBh7BOkPHVZlTTCG1MeTYjAkmxX+1B/kEkErPjs3WCP+JdtwkRaKRcQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@electron-internal/extract-zip": "^1.0.1", + "@electron/get": "^5.0.0", + "@types/node": "^24.9.0" + }, + "bin": { + "electron": "cli.js", + "install-electron": "install.js" + }, + "engines": { + "node": ">= 22.12.0" + } + }, + "node_modules/electron/node_modules/@types/node": { + "version": "24.19.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.2.tgz", + "integrity": "sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": ">=7.24.0 <7.24.7" + } + }, + "node_modules/electron/node_modules/undici-types": { + "version": "7.24.6", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz", + "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==", + "dev": true, + "license": "MIT" + }, + "node_modules/entities": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", + "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/env-paths": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-3.0.0.tgz", + "integrity": "sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/form-data": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", + "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.4", + "mime-types": "^2.1.35" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "dev": true, + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/html-encoding-sniffer": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz", + "integrity": "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-encoding": "^3.1.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/http-proxy-agent": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", + "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/jsdom": { + "version": "25.0.1", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-25.0.1.tgz", + "integrity": "sha512-8i7LzZj7BF8uplX+ZyOlIz86V6TAsSs+np6m1kpW9u0JWi4z/1t+FzcK1aek+ybTnAC4KhBL4uXCNT0wcUIeCw==", + "dev": true, + "license": "MIT", + "dependencies": { + "cssstyle": "^4.1.0", + "data-urls": "^5.0.0", + "decimal.js": "^10.4.3", + "form-data": "^4.0.0", + "html-encoding-sniffer": "^4.0.0", + "http-proxy-agent": "^7.0.2", + "https-proxy-agent": "^7.0.5", + "is-potential-custom-element-name": "^1.0.1", + "nwsapi": "^2.2.12", + "parse5": "^7.1.2", + "rrweb-cssom": "^0.7.1", + "saxes": "^6.0.0", + "symbol-tree": "^3.2.4", + "tough-cookie": "^5.0.0", + "w3c-xmlserializer": "^5.0.0", + "webidl-conversions": "^7.0.0", + "whatwg-encoding": "^3.1.1", + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^14.0.0", + "ws": "^8.18.0", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "canvas": "^2.11.2" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, + "node_modules/koffi": { + "version": "2.16.3", + "resolved": "https://registry.npmjs.org/koffi/-/koffi-2.16.3.tgz", + "integrity": "sha512-E9y1AsgYGlaxMhcZzHr8y96QF2U5XzA12GGVAfbWqIubTwPNMXQarfBzePNXHe0xtIEtNd6ifAv3GAKYGUeBAQ==", + "hasInstallScript": true, + "license": "MIT", + "funding": { + "url": "https://liberapay.com/Koromix" + } + }, + "node_modules/long": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", + "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", + "license": "Apache-2.0" + }, + "node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/nwsapi": { + "version": "2.2.28", + "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.28.tgz", + "integrity": "sha512-IlVB7OS7qrOsVYlpnFIkETjMwT9jwvmocJmmM+GZU/PAB3uGi9Ezd7vcWhWBUnSc0ya4ppmQITOyP1ez9gg8cg==", + "dev": true, + "license": "MIT" + }, + "node_modules/parse5": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz", + "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^6.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/progress": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz", + "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/protobufjs": { + "version": "7.6.6", + "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.6.6.tgz", + "integrity": "sha512-dYDWdjSl5RNb7SgPxGQcRU+GtvP7s2fpkrY0r432PcOIaZ0/rBcxEZnQN67iJhFuQiVw754JDoPruPCNdGsbjg==", + "hasInstallScript": true, + "license": "BSD-3-Clause", + "dependencies": { + "@protobufjs/aspromise": "^1.1.2", + "@protobufjs/base64": "^1.1.2", + "@protobufjs/codegen": "^2.0.5", + "@protobufjs/eventemitter": "^1.1.1", + "@protobufjs/fetch": "^1.1.1", + "@protobufjs/float": "^1.0.2", + "@protobufjs/path": "^1.1.2", + "@protobufjs/pool": "^1.1.0", + "@protobufjs/utf8": "^1.1.1", + "@types/node": ">=13.7.0", + "long": "^5.3.2" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/rrweb-cssom": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.7.1.tgz", + "integrity": "sha512-TrEMa7JGdVm0UThDJSx7ddw5nVm3UJS9o9CCIZ72B1vSyEZoziDqBYP3XIoi/12lKrJR8rE3jeFHMok2F/Mnsg==", + "dev": true, + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true, + "license": "MIT" + }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "dev": true, + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, + "node_modules/semver": { + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/sumchecker": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/sumchecker/-/sumchecker-3.0.1.tgz", + "integrity": "sha512-MvjXzkz/BOfyVDkG0oFOtBxHX2u3gKbMHIF/dXblZsgD3BWOFLmHovIpZY7BykJdAjcqRCBi1WYBNdEC9yI7vg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "debug": "^4.1.0" + }, + "engines": { + "node": ">= 8.0" + } + }, + "node_modules/symbol-tree": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", + "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", + "dev": true, + "license": "MIT" + }, + "node_modules/tldts": { + "version": "6.1.86", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.86.tgz", + "integrity": "sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^6.1.86" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "6.1.86", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-6.1.86.tgz", + "integrity": "sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==", + "dev": true, + "license": "MIT" + }, + "node_modules/tough-cookie": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-5.1.2.tgz", + "integrity": "sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^6.1.32" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz", + "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/undici": { + "version": "7.30.2", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.2.tgz", + "integrity": "sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA==", + "dev": true, + "license": "MIT", + "optional": true, + "engines": { + "node": ">=20.18.1" + } + }, + "node_modules/undici-types": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", + "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", + "license": "MIT" + }, + "node_modules/w3c-xmlserializer": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", + "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/whatwg-encoding": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz", + "integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==", + "deprecated": "Use @exodus/bytes instead for a more spec-conformant and faster implementation", + "dev": true, + "license": "MIT", + "dependencies": { + "iconv-lite": "0.6.3" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-mimetype": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz", + "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-url": { + "version": "14.2.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz", + "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tr46": "^5.1.0", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/ws": { + "version": "8.22.2", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.2.tgz", + "integrity": "sha512-/rEZ2ejown2N5gxVTHUu9bVVC7ttu0/Tgzf5hbTOixR3Fs7mbbXgn2DbdbcKgJOmpQMtrIUWivtYuVMnp/W/yA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "dev": true, + "license": "MIT" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..a1601a6 --- /dev/null +++ b/package.json @@ -0,0 +1,27 @@ +{ + "name": "heartwritten", + "version": "0.1.0", + "private": true, + "description": "Letters that carry the heartbeat you wrote them with. Built on the Presage SmartSpectra SDK.", + "type": "module", + "main": "app/main.cjs", + "scripts": { + "test": "node --test test/*.test.js", + "build": "node scripts/build.mjs", + "start": "npm run build && electron .", + "start:sim": "npm run build && HEARTWRITTEN_SIMULATE=1 electron .", + "smoke": "node scripts/sdk-smoke.mjs", + "sample": "node scripts/make-sample.mjs" + }, + "engines": { + "node": ">=20" + }, + "dependencies": { + "@smartspectra/node-sdk": "^3.5.0" + }, + "devDependencies": { + "electron": "^43.8.1", + "esbuild": "^0.25.12", + "jsdom": "^25.0.1" + } +} diff --git a/scripts/build.mjs b/scripts/build.mjs new file mode 100644 index 0000000..a122d83 --- /dev/null +++ b/scripts/build.mjs @@ -0,0 +1,40 @@ +// build.mjs: bundles the reader into one self-contained HTML file, then the +// writer (which embeds that file for "Save as a file") and the preload. +import { build } from 'esbuild'; +import { mkdir, readFile, writeFile, copyFile } from 'node:fs/promises'; + +const out = (p) => new URL(`../dist/${p}`, import.meta.url); +const src = (p) => new URL(`../src/${p}`, import.meta.url); + +await mkdir(out('reader/'), { recursive: true }); +await mkdir(out('writer/'), { recursive: true }); + +// 1. Reader: one HTML file, no external requests. +const js = await build({ + entryPoints: [src('reader/reader.js').pathname], + bundle: true, minify: true, format: 'iife', write: false, target: ['es2022'], +}); +const css = await readFile(src('reader/reader.css'), 'utf8'); +const html = (await readFile(src('reader/index.html'), 'utf8')) + .replace('/*__READER_CSS__*/', () => css) + .replace('/*__READER_JS__*/', () => js.outputFiles[0].text.replace(/<\/script/gi, '<\\/script')); +await writeFile(out('reader/index.html'), html); + +// 2. Writer renderer. +await build({ + entryPoints: [src('writer/writer.js').pathname], + bundle: true, format: 'iife', platform: 'browser', target: ['chrome120'], + outfile: out('writer/writer.js').pathname, loader: { '.html': 'text' }, logLevel: 'warning', +}); +await copyFile(src('writer/index.html'), out('writer/index.html')); +await copyFile(src('writer/writer.css'), out('writer/writer.css')); + +// 3. Preload: SmartSpectra's bridge plus ours, with only `electron` left external +// so it runs in a sandboxed preload. +await build({ + entryPoints: [src('writer/preload.cjs').pathname], + bundle: true, format: 'cjs', platform: 'node', external: ['electron'], + outfile: out('preload.cjs').pathname, logLevel: 'warning', +}); + +console.log(`built dist/ (reader ${(html.length / 1024).toFixed(1)} KB)`); diff --git a/scripts/make-sample.mjs b/scripts/make-sample.mjs new file mode 100644 index 0000000..8c9cd04 --- /dev/null +++ b/scripts/make-sample.mjs @@ -0,0 +1,53 @@ +// make-sample.mjs: writes a sample letter (simulated signals, marked as a +// sample) so the reader can be tried without the app. Prints its token and +// writes dist/sample-letter.html. +import { writeFile, readFile } from 'node:fs/promises'; +import { LetterRecorder } from '../src/shared/recorder.js'; +import { encodeLetter } from '../src/shared/letter-format.js'; + +let t = 0; +const now = () => t; +const rec = new LetterRecorder({ now }); +let bpm = 66; +let smile = 0; +let wavePhase = 0; +const feed = () => { + rec.sample({ bpm: bpm + Math.sin(t / 9000) * 2, breath: Math.sin((t / 1000) * (14 / 60) * Math.PI * 2), smile }); +}; +const typeText = (s, gap = 135) => { + for (const ch of s) { + t += gap + ((ch.charCodeAt(0) * 37) % 70) + (ch === ' ' ? 40 : 0) + (/[.,]/.test(ch) ? 260 : 0); + rec.edit(rec.text + ch); + feed(); + } +}; +const back = (n) => { for (let i = 0; i < n; i++) { t += 95; rec.edit(rec.text.slice(0, -1)); feed(); } }; +const pause = (ms) => { const end = t + ms; while (t < end) { t += 250; feed(); } }; + +typeText('Maya,\n\n'); +typeText('I wanted to write this down instead of saying it on the phone, because I always rush the good parts. '); +pause(4000); +typeText('So, slowly: '); +bpm = 79; typeText('they called this morning. '); +bpm = 91; smile = 0.9; typeText('I got it. I actually got it!'); +pause(2500); smile = 0; +typeText(' You were the first person I wanted to tell. '); +bpm = 84; +pause(14000); +typeText('I keep thinking about the night you sat on my floor and read my application out loud, and I was so sure it was '); +typeText('terrible'); back(8); typeText('not good enough'); +typeText('. You told me to send it anyway. '); +bpm = 68; +typeText('I don’t think I would have.\n\n'); +bpm = 64; +typeText('Thank you for believing in me before I did. Dinner is on me, wherever you want, as many times as you want.\n\n'); +smile = 0.85; typeText('See you Friday.'); smile = 0; +for (let i = 0; i < 180; i++) { wavePhase += (66 / 60) / 30; const p = wavePhase % 1; rec.pushWave([p < 0.15 ? Math.sin(p / 0.15 * Math.PI / 2) : Math.exp(-3.2 * (p - 0.15) / 0.85) + 0.12 * Math.exp(-(((p - 0.15) / 0.85 - 0.28) ** 2) / 0.004)]); } + +const letter = rec.finish({ from: 'Sam', to: 'Maya', day: '2026-11-12', sim: true, share: { edits: true, smiles: true } }); +const token = await encodeLetter(letter); +const reader = await readFile(new URL('../dist/reader/index.html', import.meta.url), 'utf8'); +await writeFile(new URL('../dist/sample-letter.html', import.meta.url), + reader.replace('', ``)); +await writeFile(new URL('../dist/sample-token.txt', import.meta.url), token); +console.log(`sample letter: ${rec.text.length} chars, written over ${(t / 60000).toFixed(1)} min, token ${token.length} chars`); diff --git a/scripts/sdk-smoke.mjs b/scripts/sdk-smoke.mjs new file mode 100644 index 0000000..7e05114 --- /dev/null +++ b/scripts/sdk-smoke.mjs @@ -0,0 +1,49 @@ +// sdk-smoke.mjs +// Headless check that the SmartSpectra SDK loads and that Heartwritten reads +// its packets. With a key and a short face video it runs a real measurement: +// +// SMARTSPECTRA_API_KEY=... npm run smoke -- path/to/face-clip.mp4 +// +// Without a key it only checks that the native runtime loads. + +import { createRequire } from 'node:module'; +import { VitalsTracker } from '../src/shared/vitals.js'; + +const require = createRequire(import.meta.url); +const ss = require('@smartspectra/node-sdk'); +const { decodeMetrics } = require('@smartspectra/node-sdk/messages'); + +console.log(`SmartSpectra SDK ${ss.SmartSpectraSDK.version} loaded on ${process.platform}-${process.arch}`); +try { + const cams = ss.SmartSpectraSDK.availableCameras(); + console.log(`Cameras found: ${cams.length}`); +} catch (e) { + console.log(`Camera discovery unavailable here (${e.message})`); +} + +const key = process.env.SMARTSPECTRA_API_KEY; +const clip = process.argv[2]; +if (!key || !clip) { + console.log('No key or clip given: load check passed. Pass both to run a real measurement.'); + process.exit(0); +} + +const metrics = [...ss.breathingMetrics, ...ss.cardioMetrics, ss.MetricType.EXPRESSIONS]; +const sdk = new ss.SmartSpectraSDK({ apiKey: key, requestedMetrics: metrics, enableTelemetry: false }); +const vitals = new VitalsTracker(); +let packets = 0; +sdk.on('metrics', (buf) => { packets++; vitals.ingest(decodeMetrics(buf)); }); +sdk.on('validationStatus', (code, _ts, hint) => { if (code !== 0) console.log(`validation ${code} ${hint || ''}`); }); +sdk.on('error', (code, msg) => console.error(`SDK error ${code}: ${msg}`)); +sdk.useFile(clip, { interframeDelayMs: 33 }); +sdk.start(); +sdk.waitUntilComplete(180000); +await sdk.destroy(); + +const snap = vitals.snapshot(); +console.log(`packets=${packets} bpm=${snap.bpm?.toFixed(1) ?? '—'} breathsPerMin=${vitals.breathRate ?? '—'} pulseSamples=${vitals.pulseTrace.length} smile=${snap.smile}`); +if (!packets || !vitals.pulseTrace.length) { + console.error('FAIL: no pulse data came back'); + process.exit(1); +} +console.log('PASS'); diff --git a/src/reader/index.html b/src/reader/index.html new file mode 100644 index 0000000..1f1f68f --- /dev/null +++ b/src/reader/index.html @@ -0,0 +1,72 @@ + + + + + + + +Heartwritten + + + + +
+
+

Heartwritten

+

Letters that carry the heartbeat they were written with. Open one from the link you were sent.

+
+ +
+
+

+

+

+ +

Tap the seal to open it.

+ +
+

This letter lives only in its link. Opening it sends nothing anywhere.

+
+ +
+
+ +
+

+

+
+

+ +
+
+ + +
+
+ + + + diff --git a/src/reader/reader.css b/src/reader/reader.css new file mode 100644 index 0000000..f2a4d9a --- /dev/null +++ b/src/reader/reader.css @@ -0,0 +1,152 @@ +:root { + --paper: #fbf6ec; + --paper-edge: #efe5d2; + --desk: #e9dfcc; + --ink: #1f2942; + --muted: #6d6556; + --wax: #a3232a; + --glow: rgba(232, 176, 60, 0.32); + --serif: "Iowan Old Style", "Palatino Linotype", Palatino, "Book Antiqua", Georgia, serif; + --hand: "Snell Roundhand", "Segoe Script", "Bradley Hand", "Apple Chancery", cursive; + color-scheme: light dark; +} +@media (prefers-color-scheme: dark) { + :root { --desk: #1c1a17; --muted: #a49a88; } +} +* { box-sizing: border-box; } +html, body { margin: 0; min-height: 100%; } +body { + background: radial-gradient(120% 90% at 50% 0%, color-mix(in srgb, var(--desk) 70%, #fff 30%), var(--desk)); + color: var(--ink); + font: 18px/1.65 var(--serif); + -webkit-font-smoothing: antialiased; + min-height: 100vh; +} +main { max-width: 860px; margin: 0 auto; padding: 48px 16px 64px; } +button { font: inherit; cursor: pointer; } + +.view { display: none; } +body[data-view="empty"] .view-empty, +body[data-view="envelope"] .view-envelope, +body[data-view="breaking"] .view-envelope, +body[data-view="letter"] .view-letter { display: block; } + +.wordmark { font-style: italic; font-weight: 400; font-size: 44px; margin: 18vh 0 8px; text-align: center; } +.view-empty p { text-align: center; color: var(--muted); max-width: 34em; margin: 0 auto; } + +/* Envelope */ +.envelope { + margin: 8vh auto 0; max-width: 520px; padding: 48px 32px 40px; text-align: center; + background: linear-gradient(160deg, var(--paper), var(--paper-edge)); + border-radius: 6px; box-shadow: 0 1px 0 #fff inset, 0 30px 60px -30px rgba(40, 25, 5, 0.45), 0 2px 6px rgba(40, 25, 5, 0.12); + position: relative; color: #1f2942; +} +.envelope::before { /* the flap */ + content: ""; position: absolute; inset: 0 0 auto 0; height: 46%; + background: linear-gradient(to bottom right, transparent 49.5%, rgba(120, 90, 40, 0.10) 50%, transparent 50.5%), + linear-gradient(to bottom left, transparent 49.5%, rgba(120, 90, 40, 0.10) 50%, transparent 50.5%); + pointer-events: none; +} +.eyebrow { font-size: 13px; letter-spacing: 0.14em; text-transform: uppercase; color: var(--muted); margin: 0 0 8px; } +.envelope .eyebrow { color: #7d7262; } +.to { font-weight: 400; font-style: italic; font-size: 38px; margin: 0; } +.from { margin: 4px 0 26px; color: #6d6556; } +.seal-button { background: none; border: 0; padding: 0; border-radius: 50%; display: inline-block; } +.seal-button:focus-visible { outline: 3px solid #c99a3b; outline-offset: 6px; } +.seal { display: block; width: 168px; height: 168px; animation: heartbeat var(--beat, 0.9s) ease-in-out infinite; transform-origin: 50% 52%; } +.seal svg { width: 100%; height: 100%; } +.hint { color: #7d7262; font-size: 15px; margin: 14px 0 0; } +.fine { color: var(--muted); font-size: 13px; text-align: center; margin-top: 28px; } +.badge { display: inline-block; margin: 16px auto 0; font-size: 12px; letter-spacing: 0.04em; padding: 4px 10px; border-radius: 99px; background: #f1e0b6; color: #5b4310; } +@keyframes heartbeat { + 0%, 100% { transform: scale(1); } + 12% { transform: scale(1.045); } + 24% { transform: scale(0.995); } + 36% { transform: scale(1.025); } + 50% { transform: scale(1); } +} +body[data-view="breaking"] .seal { animation: crack 0.9s cubic-bezier(.5,0,.2,1) forwards; } +body[data-view="breaking"] .envelope { animation: lift 0.9s ease forwards; } +@keyframes crack { + 0% { transform: scale(1) rotate(0); filter: none; } + 30% { transform: scale(1.08) rotate(-4deg); } + 100% { transform: scale(0.6) rotate(18deg) translateY(40px); opacity: 0; filter: blur(2px); } +} +@keyframes lift { to { transform: translateY(-12px); opacity: 0; } } + +/* Letter */ +.desk { display: grid; grid-template-columns: 92px 1fr; gap: 20px; align-items: start; } +.margin { position: sticky; top: 32px; text-align: center; color: var(--muted); font-size: 14px; } +.heart { color: var(--ink); display: inline-block; transition: color 1.2s ease; transform-origin: 50% 60%; } +.heart.beat { animation: thump 0.42s ease-out; } +@keyframes thump { 0% { transform: scale(1); } 18% { transform: scale(1.28); } 38% { transform: scale(0.96); } 60% { transform: scale(1.1); } 100% { transform: scale(1); } } +.bpm { margin: 2px 0 18px; font-variant-numeric: tabular-nums; } +.bpm span { font-size: 22px; color: var(--ink); display: block; line-height: 1.1; } +@media (prefers-color-scheme: dark) { .bpm span { color: #eadfca; } } +.bpm small { letter-spacing: 0.12em; text-transform: uppercase; font-size: 11px; } +.pauses { list-style: none; padding: 0; margin: 0; font-style: italic; font-size: 13px; line-height: 1.4; } +.pauses li { margin-bottom: 8px; animation: fadein 1.2s ease; } +.took-back { font-style: italic; font-size: 13px; line-height: 1.4; } +@keyframes fadein { from { opacity: 0; transform: translateY(4px); } } + +.paper { + --breath: 0; + background: linear-gradient(170deg, var(--paper), var(--paper-edge)); + color: #1f2942; + padding: 44px 48px 40px; border-radius: 4px; min-height: 60vh; + box-shadow: 0 1px 0 #fff inset, 0 calc(26px + var(--breath) * 6px) calc(56px + var(--breath) * 10px) -30px rgba(40, 25, 5, 0.42), 0 2px 6px rgba(40, 25, 5, 0.1); + transform: translateY(calc(var(--breath) * -2px)) scale(calc(1 + var(--breath) * 0.004)); + transition: transform 0.25s linear, box-shadow 0.25s linear; + animation: unfold 0.9s cubic-bezier(.2,.7,.2,1); +} +@keyframes unfold { from { transform: translateY(24px) scaleY(0.92); opacity: 0; } } +.salutation { font-style: italic; font-size: 22px; margin: 0 0 14px; } +.body-text { font-size: 20px; line-height: 1.75; white-space: pre-wrap; overflow-wrap: anywhere; min-height: 3em; } +.body-text span { transition: color 0.6s ease; } +.body-text .smiled { background: linear-gradient(transparent 62%, var(--glow) 62%, var(--glow) 92%, transparent 92%); border-radius: 2px; } +.caret { display: inline-block; width: 2px; height: 1.1em; background: #1f2942; vertical-align: -0.18em; margin-left: 1px; animation: blink 1.1s steps(1) infinite; } +.finished .caret { display: none; } +@keyframes blink { 50% { opacity: 0; } } +.signature { font-family: var(--hand); font-size: 30px; margin: 24px 0 0; text-align: right; min-height: 1.2em; } + +.controls { display: flex; flex-wrap: wrap; gap: 8px; justify-content: center; margin: 22px 0 0 112px; } +.controls button, .summary-actions button { + background: transparent; border: 1px solid color-mix(in srgb, var(--muted) 45%, transparent); color: var(--muted); + border-radius: 99px; padding: 6px 14px; font-size: 14px; +} +.controls button[aria-pressed="true"] { background: var(--ink); color: var(--paper); border-color: var(--ink); } +@media (prefers-color-scheme: dark) { .controls button[aria-pressed="true"] { background: #eadfca; color: #1c1a17; border-color: #eadfca; } } +.controls button:focus-visible, .summary-actions button:focus-visible { outline: 2px solid #c99a3b; outline-offset: 2px; } +.finished .controls { display: none; } + +.summary { margin: 28px 0 0 112px; padding: 28px 32px; border-radius: 6px; background: color-mix(in srgb, var(--paper) 70%, transparent); color: #1f2942; animation: fadein 1s ease; } +.summary h2 { font-weight: 400; font-style: italic; font-size: 24px; margin: 0 0 10px; } +.summary p { margin: 8px 0; } +.summary .sum-lead { color: #6d6556; } +.summary .q span { color: #7d7262; font-size: 14px; white-space: nowrap; margin-left: 6px; } +.summary q { font-style: italic; } +.legend { font-size: 13px; color: #7d7262; display: flex; gap: 14px; flex-wrap: wrap; } +.ink::before { content: ""; display: inline-block; width: 10px; height: 10px; border-radius: 50%; margin-right: 6px; vertical-align: -1px; } +.ink.calm::before { background: rgb(31, 41, 66); } +.ink.warm::before { background: rgb(168, 38, 44); } +.ink.glow::before { background: rgba(232, 176, 60, 0.6); } +.summary-actions { display: flex; gap: 8px; margin-top: 16px; } +.summary-actions button { color: #6d6556; } +.summary .fine { text-align: left; margin-top: 18px; color: #7d7262; } + +@media (max-width: 640px) { + main { padding: 24px 16px 48px; } + .desk { grid-template-columns: 1fr; } + .margin { position: sticky; top: 0; z-index: 2; display: flex; align-items: center; gap: 10px; justify-content: flex-start; padding: 8px 0; background: var(--desk); } + .bpm { margin: 0; display: flex; gap: 4px; align-items: baseline; } + .bpm span { display: inline; } + .pauses, .took-back { display: none; } + .paper { padding: 28px 22px; } + .body-text { font-size: 18px; } + .controls, .summary { margin-left: 0; } + .to { font-size: 30px; } +} +@media (prefers-reduced-motion: reduce) { + .seal, .heart.beat, .paper { animation: none !important; } + .paper { transform: none; transition: none; } +} diff --git a/src/reader/reader.js b/src/reader/reader.js new file mode 100644 index 0000000..d5c4906 --- /dev/null +++ b/src/reader/reader.js @@ -0,0 +1,218 @@ +// reader.js +// The page a letter opens in. It reads the letter from the link's #fragment +// (or from the file it was saved into), never from a server, and replays it. + +import { decodeLetter, extractToken, finalText } from '../shared/letter-format.js'; +import { Player, bpmAt, inkFor, sampleAt } from '../shared/playback.js'; +import { summarize, median, formatDuration, excerpt } from '../shared/summary.js'; +import { sealSvg } from '../shared/seal.js'; + +const $ = (id) => document.getElementById(id); + +function embeddedToken() { + const el = document.getElementById('letter-data'); + return el ? extractToken(el.textContent.trim()) : null; +} + +function esc(s) { + return String(s).replace(/[<>&"']/g, (c) => ({ '<': '<', '>': '>', '&': '&', '"': '"', "'": ''' }[c])); +} + +function dayLabel(day) { + if (!/^\d{4}-\d{2}-\d{2}$/.test(day || '')) return ''; + const d = new Date(`${day}T12:00:00`); + return d.toLocaleDateString(undefined, { day: 'numeric', month: 'long', year: 'numeric' }); +} + +export async function boot() { + const token = extractToken(location.hash) || embeddedToken(); + if (!token) return showEmpty(); + let letter; + try { + letter = await decodeLetter(token); + } catch (e) { + return showEmpty('This link doesn’t hold a whole letter. It may have been cut short when it was shared.'); + } + showEnvelope(letter); +} + +function showEmpty(message) { + document.body.dataset.view = 'empty'; + if (message) $('empty-text').textContent = message; +} + +// --------------------------------------------------------------------------- +// The envelope + +function showEnvelope(letter) { + document.body.dataset.view = 'envelope'; + const base = median(letter.vit.bpm); + const initial = (letter.from || '').trim().charAt(0); + $('seal').innerHTML = sealSvg(letter.wave.v, { initial, bpm: base }); + const to = letter.to ? `For ${esc(letter.to)}` : 'A letter for you'; + const from = letter.from ? `sealed with ${esc(letter.from)}’s heartbeat` : 'sealed with a heartbeat'; + $('envelope-to').innerHTML = to; + $('envelope-from').innerHTML = from; + $('envelope-day').textContent = dayLabel(letter.day); + $('sim-badge').hidden = !letter.sim; + if (base > 0) $('seal').style.setProperty('--beat', `${(60 / base).toFixed(3)}s`); + const open = () => openLetter(letter); + $('seal-button').addEventListener('click', open, { once: true }); +} + +// --------------------------------------------------------------------------- +// Replay + +const state = { speed: 1, sound: false, audio: null, raf: 0, player: null, startedAt: 0, at: 0, paused: false }; + +function openLetter(letter) { + document.body.dataset.view = 'breaking'; + setTimeout(() => startReplay(letter), 900); +} + +function startReplay(letter) { + document.body.dataset.view = 'letter'; + const player = new Player(letter); + state.player = player; + state.letter = letter; + state.baseline = median(letter.vit.bpm); + state.pauses = player.timeline.pauses; + state.at = 0; + state.last = performance.now(); + state.nextBeat = 0; + $('salutation').textContent = letter.to ? `To ${letter.to},` : ''; + $('signature').textContent = ''; + $('letter-day').textContent = dayLabel(letter.day); + $('replay-sim').hidden = !letter.sim; + render(true); + cancelAnimationFrame(state.raf); + state.raf = requestAnimationFrame(frame); +} + +function frame(now) { + const dt = Math.min(100, now - state.last); + state.last = now; + if (!state.paused) state.at += dt * state.speed; + const p = state.player; + const changed = p.advance(state.at); + if (changed) render(); + pulse(now); + if (p.done) return finish(); + state.raf = requestAnimationFrame(frame); +} + +// The heart in the margin beats at the writer's rate at this point in the +// letter; the page rises and falls with their breathing. +function pulse(now) { + const { letter } = state; + const t = state.player.writerTime + Math.max(0, state.at - lastOpAt()); + const bpm = bpmAt(letter, t); + const heart = $('heart'); + $('heart-bpm').textContent = bpm > 0 ? String(bpm) : '·'; + heart.style.color = inkFor(bpm, state.baseline); + if (bpm > 0 && now >= state.nextBeat) { + state.nextBeat = now + (60000 / bpm) / Math.max(1, state.speed * 0.6 + 0.4); + heart.classList.remove('beat'); + void heart.offsetWidth; + heart.classList.add('beat'); + if (state.sound) thump(); + } + const br = sampleAt(letter.vit.br, letter.vit.hz, t) / 100; + $('paper').style.setProperty('--breath', br.toFixed(3)); +} + +function lastOpAt() { + const { ops } = state.player.timeline; + const k = state.player.i - 1; + return k >= 0 ? ops[k].at : 0; +} + +function render() { + const { player, letter, baseline } = state; + const chars = player.chars; + let html = ''; + let i = 0; + const smileAt = (t) => letter.share.smiles && sampleAt(letter.vit.sm, letter.vit.hz, t) >= 6; + while (i < chars.length) { + const t = chars[i].t; + let j = i; + let run = ''; + while (j < chars.length && chars[j].t === t) { run += chars[j].ch; j++; } + const bpm = bpmAt(letter, t); + const cls = smileAt(t) ? ' class="smiled"' : ''; + run = esc(run).replace(/\n/g, '
'); + html += `${run}`; + i = j; + } + $('body-text').innerHTML = html + ''; + // Long pauses are noted in the margin, in order. + const notes = state.pauses.filter((pz) => pz.at <= state.at); + $('pauses').innerHTML = notes.map((pz) => `
  • paused ${formatDuration(pz.ms)}
  • `).join(''); + $('took-back').textContent = letter.share.edits && player.tookBack + ? `${player.tookBack} character${player.tookBack === 1 ? '' : 's'} taken back` + : ''; +} + +function finish() { + const { letter } = state; + render(); + $('signature').textContent = letter.from ? `— ${letter.from}` : ''; + document.body.classList.add('finished'); + const s = summarize(letter); + const rows = []; + rows.push(`

    Written in ${formatDuration(s.writtenMs)}, ${s.words} words.

    `); + if (s.low > 0 && s.high > 0) rows.push(`

    ${esc(letter.from || 'Their')}${letter.from ? '’s' : ''} heart ran between ${s.low} and ${s.high} beats a minute while writing.

    `); + if (s.quickest) rows.push(`

    Quickest at ${esc(excerpt(s.quickest.text))} ${s.quickest.bpm} bpm

    `); + if (s.steadiest) rows.push(`

    Steadiest at ${esc(excerpt(s.steadiest.text))} ${s.steadiest.bpm} bpm

    `); + if (s.smiles) rows.push(`

    ${letter.from ? esc(letter.from) : 'They'} smiled ${s.smiles === 1 ? 'once' : `${s.smiles} times`}; the words glow where.

    `); + if (s.tookBack) rows.push(`

    ${s.tookBack} characters were written and taken back.

    `); + $('summary-body').innerHTML = rows.join(''); + $('summary').hidden = false; + $('copy-text').onclick = async () => { + try { await navigator.clipboard.writeText(finalText(letter)); $('copy-text').textContent = 'Copied'; } catch { /* clipboard blocked */ } + }; +} + +// --------------------------------------------------------------------------- +// Controls + +function thump() { + if (!state.audio) state.audio = new AudioContext(); + const ctx = state.audio; + const o = ctx.createOscillator(); + const g = ctx.createGain(); + o.frequency.setValueAtTime(64, ctx.currentTime); + o.frequency.exponentialRampToValueAtTime(38, ctx.currentTime + 0.16); + g.gain.setValueAtTime(0.0001, ctx.currentTime); + g.gain.exponentialRampToValueAtTime(0.5, ctx.currentTime + 0.012); + g.gain.exponentialRampToValueAtTime(0.0001, ctx.currentTime + 0.22); + o.connect(g).connect(ctx.destination); + o.start(); + o.stop(ctx.currentTime + 0.25); +} + +function wireControls() { + for (const b of document.querySelectorAll('[data-speed]')) { + b.addEventListener('click', () => { + state.speed = Number(b.dataset.speed); + for (const o of document.querySelectorAll('[data-speed]')) o.setAttribute('aria-pressed', String(o === b)); + }); + } + $('skip').addEventListener('click', () => { if (state.player) state.at = Infinity; }); + $('sound').addEventListener('click', () => { + state.sound = !state.sound; + $('sound').setAttribute('aria-pressed', String(state.sound)); + $('sound').textContent = state.sound ? 'Heartbeat sound on' : 'Hear the heartbeat'; + }); + $('replay').addEventListener('click', () => { + document.body.classList.remove('finished'); + $('summary').hidden = true; + startReplay(state.letter); + }); + window.addEventListener('hashchange', () => location.reload()); +} + +if (typeof document !== 'undefined' && !globalThis.__HW_NO_AUTOBOOT__) { + wireControls(); + boot(); +} diff --git a/src/shared/letter-format.js b/src/shared/letter-format.js new file mode 100644 index 0000000..efdb2c8 --- /dev/null +++ b/src/shared/letter-format.js @@ -0,0 +1,201 @@ +// letter-format.js +// The wire format of a Heartwritten letter, and how it is packed into a link. +// +// A letter is plain data. It never goes to a server: the writer app packs it +// into the #fragment of a link (browsers never send the fragment over the +// network) or into a self-contained .html file. +// +// Decoded shape (version 1): +// { +// v: 1, +// from: "Subomi", // optional, as typed by the writer +// to: "Deola", // optional +// day: "2026-11-12", // the day it was sealed, no time of day +// sim: 0 | 1, // 1 when the signals were simulated (sample letters) +// share: { edits: bool, smiles: bool }, +// ops: [[t, pos, del, ins], ...] // replayable edits, t = ms since start +// vit: { hz, bpm: [...], br: [...], sm: [...] } // signals sampled over time +// wave: { hz, v: [...] } // a few seconds of the pulse wave, for the seal +// } +// +// On the wire the ops and samples are delta- and integer-coded, then the JSON +// is deflated and base64url-encoded. + +export const FORMAT_VERSION = 1; +export const LINK_PREFIX = 'v1.'; +// Times are stored in 10 ms ticks to keep the numbers small. +const TICK_MS = 10; + +const MAX_TEXT = 20000; +const MAX_OPS = 40000; +const MAX_SAMPLES = 20000; + +/** Turn a decoded letter into the compact JSON-able form. */ +export function pack(letter) { + validate(letter); + let prevT = 0; + const ops = letter.ops.map(([t, pos, del, ins]) => { + const tick = Math.round(t / TICK_MS); + const dt = tick - prevT; + prevT = tick; + return ins ? [dt, pos, del, ins] : [dt, pos, del]; + }); + return { + v: FORMAT_VERSION, + f: letter.from || undefined, + to: letter.to || undefined, + d: letter.day || undefined, + s: letter.sim ? 1 : undefined, + sh: (letter.share.edits ? 1 : 0) | (letter.share.smiles ? 2 : 0), + o: ops, + vh: letter.vit.hz, + b: deltaCode(letter.vit.bpm), + r: deltaCode(letter.vit.br), + m: letter.share.smiles ? letter.vit.sm : undefined, + wh: letter.wave.hz, + w: deltaCode(letter.wave.v), + }; +} + +/** Inverse of pack(). Throws on anything malformed. */ +export function unpack(p) { + if (!p || p.v !== FORMAT_VERSION) throw new Error('Unsupported letter version'); + let t = 0; + const ops = (p.o || []).map((op) => { + t += op[0]; + return [t * TICK_MS, op[1], op[2], op[3] || '']; + }); + const share = { edits: !!(p.sh & 1), smiles: !!(p.sh & 2) }; + const bpm = deltaDecode(p.b || []); + const letter = { + v: FORMAT_VERSION, + from: p.f || '', + to: p.to || '', + day: p.d || '', + sim: p.s ? 1 : 0, + share, + ops, + vit: { + hz: p.vh || 1, + bpm, + br: deltaDecode(p.r || []), + sm: share.smiles && Array.isArray(p.m) ? p.m : new Array(bpm.length).fill(0), + }, + wave: { hz: p.wh || 25, v: deltaDecode(p.w || []) }, + }; + validate(letter); + return letter; +} + +/** Checks the shape and bounds of a decoded letter. */ +export function validate(letter) { + const fail = (why) => { throw new Error(`Invalid letter: ${why}`); }; + if (!letter || typeof letter !== 'object') fail('not an object'); + if (!Array.isArray(letter.ops) || letter.ops.length > MAX_OPS) fail('ops'); + let len = 0; + let lastT = -1; + for (const op of letter.ops) { + if (!Array.isArray(op) || op.length < 3) fail('op shape'); + const [t, pos, del, ins = ''] = op; + if (!isInt(t) || t < lastT) fail('op time'); + if (!isInt(pos) || pos < 0 || pos > len) fail('op position'); + if (!isInt(del) || del < 0 || pos + del > len) fail('op delete'); + if (typeof ins !== 'string') fail('op insert'); + len = len - del + ins.length; + if (len > MAX_TEXT) fail('text too long'); + lastT = t; + } + const vit = letter.vit; + if (!vit || !(vit.hz > 0) || vit.hz > 50) fail('vit.hz'); + for (const k of ['bpm', 'br', 'sm']) { + if (!Array.isArray(vit[k]) || vit[k].length > MAX_SAMPLES) fail(`vit.${k}`); + if (!vit[k].every(isInt)) fail(`vit.${k} values`); + } + if (!letter.wave || !Array.isArray(letter.wave.v) || letter.wave.v.length > 2000) fail('wave'); + if (!(letter.wave.hz > 0) || letter.wave.hz > 120) fail('wave.hz'); + for (const k of ['from', 'to']) { + if (letter[k] != null && (typeof letter[k] !== 'string' || letter[k].length > 80)) fail(k); + } + if (!letter.share || typeof letter.share !== 'object') fail('share'); + return true; +} + +/** Replays the ops and returns the final text. */ +export function finalText(letter) { + let s = ''; + for (const [, pos, del, ins = ''] of letter.ops) s = s.slice(0, pos) + ins + s.slice(pos + del); + return s; +} + +// --------------------------------------------------------------------------- +// Link encoding + +/** Letter -> "v1." */ +export async function encodeLetter(letter) { + const json = JSON.stringify(pack(letter)); + const bytes = await deflate(new TextEncoder().encode(json)); + return LINK_PREFIX + toBase64Url(bytes); +} + +/** "v1.<...>" (or a whole URL / fragment containing it) -> letter */ +export async function decodeLetter(token) { + const raw = extractToken(token); + if (!raw) throw new Error('No letter in this link'); + const bytes = fromBase64Url(raw.slice(LINK_PREFIX.length)); + if (bytes.length > 2_000_000) throw new Error('Letter too large'); + const json = new TextDecoder().decode(await inflate(bytes)); + return unpack(JSON.parse(json)); +} + +/** Pulls the letter token out of a URL, a hash or a bare token. */ +export function extractToken(input) { + if (typeof input !== 'string') return null; + const at = input.indexOf(LINK_PREFIX); + if (at === -1) return null; + const tok = input.slice(at).split(/[&\s]/)[0]; + return /^v1\.[A-Za-z0-9_-]+$/.test(tok) ? tok : null; +} + +export function buildLink(base, token) { + const clean = String(base || '').split('#')[0]; + return `${clean}#${token}`; +} + +// --------------------------------------------------------------------------- +// helpers + +function isInt(n) { return Number.isInteger(n); } + +function deltaCode(arr) { + let prev = 0; + return arr.map((x) => { const d = x - prev; prev = x; return d; }); +} + +function deltaDecode(arr) { + let acc = 0; + return arr.map((d) => (acc += d)); +} + +async function pipeThrough(bytes, stream) { + const out = new Blob([bytes]).stream().pipeThrough(stream); + return new Uint8Array(await new Response(out).arrayBuffer()); +} + +async function deflate(bytes) { return pipeThrough(bytes, new CompressionStream('deflate-raw')); } +async function inflate(bytes) { return pipeThrough(bytes, new DecompressionStream('deflate-raw')); } + +export function toBase64Url(bytes) { + let bin = ''; + for (let i = 0; i < bytes.length; i += 0x8000) { + bin += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000)); + } + return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); +} + +export function fromBase64Url(s) { + const b64 = s.replace(/-/g, '+').replace(/_/g, '/') + '==='.slice((s.length + 3) % 4); + const bin = atob(b64); + const out = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); + return out; +} diff --git a/src/shared/playback.js b/src/shared/playback.js new file mode 100644 index 0000000..d5fd830 --- /dev/null +++ b/src/shared/playback.js @@ -0,0 +1,145 @@ +// playback.js +// Replays a letter: the words reappear at the pace they were written, long +// pauses are shortened (but remembered), and every character keeps the +// heart rate its writer had when it was typed. Pure logic; the reader page +// draws what this returns. + +import { finalText } from './letter-format.js'; + +export const DEFAULTS = { + maxGapMs: 1400, // no silence in the replay lasts longer than this + longPauseMs: 8000, // pauses longer than this get a quiet note in the margin + speed: 1, // 1 = the writer's real typing pace (after gap capping) +}; + +/** + * Build the replay timeline. Returns + * { ops: [{at, t, pos, del, ins}], pauses: [{at, t, ms, pos}], duration, writtenMs } + * where `t` is the writer's real time and `at` the replay time. + */ +export function buildTimeline(letter, opts = {}) { + const o = { ...DEFAULTS, ...opts }; + const ops = []; + const pauses = []; + let at = 0; + let prevT = null; + let len = 0; + for (const [t, pos, del, ins = ''] of letter.ops) { + if (prevT != null) { + const gap = t - prevT; + at += Math.min(gap, o.maxGapMs) / o.speed; + if (gap >= o.longPauseMs) pauses.push({ at, t: prevT, ms: gap, pos }); + } else { + at = 600 / o.speed; // a beat of stillness before the first word + } + // Long pastes would appear all at once; spread them like typing. + if (ins.length > 12 && del === 0) { + const chunk = 3; + for (let k = 0; k < ins.length; k += chunk) { + ops.push({ at: at + (k / chunk) * (24 / o.speed), t, pos: pos + k, del: 0, ins: ins.slice(k, k + chunk) }); + } + at += Math.ceil(ins.length / chunk) * (24 / o.speed); + } else { + ops.push({ at, t, pos, del, ins }); + } + len = len - del + ins.length; + prevT = t; + } + const writtenMs = letter.ops.length ? letter.ops[letter.ops.length - 1][0] - letter.ops[0][0] : 0; + return { ops, pauses, duration: at, writtenMs, length: len }; +} + +/** Value of a sampled series at writer-time t (ms). */ +export function sampleAt(series, hz, tMs) { + if (!series || !series.length) return 0; + const i = Math.min(series.length - 1, Math.max(0, Math.floor((tMs / 1000) * hz))); + return series[i]; +} + +/** Heart rate at writer-time t, looking a little either side when unknown. */ +export function bpmAt(letter, tMs) { + const { bpm, hz } = letter.vit; + if (!bpm.length) return 0; + const i = Math.min(bpm.length - 1, Math.max(0, Math.floor((tMs / 1000) * hz))); + for (let d = 0; d < hz * 4; d++) { + if (bpm[i - d] > 0) return bpm[i - d]; + if (bpm[i + d] > 0) return bpm[i + d]; + } + return 0; +} + +/** + * Incremental player. Call advance(atMs) every frame; it applies every op + * due by then and reports what changed. + */ +export class Player { + constructor(letter, opts) { + this.letter = letter; + this.timeline = buildTimeline(letter, opts); + this.reset(); + } + + reset() { + this.i = 0; + this.chars = []; // [{ch, t}] the visible text, each char with its typing time + this.at = 0; + this.tookBack = 0; + } + + get done() { return this.i >= this.timeline.ops.length; } + + /** Writer-time currently being replayed. */ + get writerTime() { + const ops = this.timeline.ops; + if (!ops.length) return 0; + const k = Math.min(this.i, ops.length) - 1; + return k < 0 ? ops[0].t : ops[k].t; + } + + advance(atMs) { + this.at = atMs; + const ops = this.timeline.ops; + let changed = false; + while (this.i < ops.length && ops[this.i].at <= atMs) { + const { t, pos, del, ins } = ops[this.i++]; + this.chars.splice(pos, del, ...splitUnits(ins, t)); + this.tookBack += del; + changed = true; + } + return changed; + } + + text() { return this.chars.map((c) => c.ch).join(''); } +} + +function splitUnits(s, t) { + // One entry per UTF-16 unit, to stay aligned with editor positions. The two + // halves of an emoji share a time, so the reader draws them in one run. + const out = []; + for (let k = 0; k < s.length; k++) out.push({ ch: s[k], t }); + return out; +} + +/** + * Ink colour for a heartbeat relative to the writer's own resting level. + * Calm is deep ink blue, a quickened heart turns the ink warm red. + */ +export function inkFor(bpm, baseline) { + if (!(bpm > 0) || !(baseline > 0)) return 'rgb(31, 41, 66)'; + const d = Math.max(-1, Math.min(1, (bpm - baseline) / 18)); + const calm = [31, 41, 66]; + const warm = [168, 38, 44]; + const cool = [24, 54, 92]; + const [a, b, f] = d >= 0 ? [calm, warm, d] : [calm, cool, -d]; + const mix = a.map((x, k) => Math.round(x + (b[k] - x) * f)); + return `rgb(${mix[0]}, ${mix[1]}, ${mix[2]})`; +} + +/** Final characters of the letter, each with the time it was typed. */ +export function finalChars(letter) { + const p = new Player(letter, { maxGapMs: Infinity }); + p.advance(Infinity); + return p.chars; +} + +export { finalText }; diff --git a/src/shared/recorder.js b/src/shared/recorder.js new file mode 100644 index 0000000..0d71836 --- /dev/null +++ b/src/shared/recorder.js @@ -0,0 +1,156 @@ +// recorder.js +// Records a letter while it is being written: every edit with its time, and +// the writer's signals sampled on a fixed clock. Pure logic, no DOM, so it is +// tested in Node. + +import { FORMAT_VERSION } from './letter-format.js'; + +export const VITALS_HZ = 4; // signals are sampled four times a second +export const WAVE_HZ = 30; // the pulse wave kept for the seal +export const WAVE_SECONDS = 6; + +/** + * Smallest single edit that turns `prev` into `next`: + * returns { pos, del, ins } or null when nothing changed. + * Works for typing, backspace, paste, cut, autocorrect and IME commits. + * With repeated characters ("aa" -> "aaa") the reported position may be one + * of several equivalent ones; the resulting text is the same either way. + */ +export function diffText(prev, next) { + if (prev === next) return null; + let start = 0; + const max = Math.min(prev.length, next.length); + while (start < max && prev[start] === next[start]) start++; + let endPrev = prev.length; + let endNext = next.length; + while (endPrev > start && endNext > start && prev[endPrev - 1] === next[endNext - 1]) { + endPrev--; endNext--; + } + return { pos: start, del: endPrev - start, ins: next.slice(start, endNext) }; +} + +export class LetterRecorder { + constructor({ now = () => Date.now() } = {}) { + this._now = now; + this.reset(); + } + + reset() { + this.t0 = null; + this.text = ''; + this.charTimes = []; // insertion time of each character of `text` + this.ops = []; + this.samples = { bpm: [], br: [], sm: [] }; + this.wave = []; // rolling pulse wave, values -127..127 + this.tookBack = 0; // characters deleted along the way + } + + /** ms since the first keystroke (or since start() was called). */ + elapsed() { + if (this.t0 == null) return 0; + return Math.max(0, this._now() - this.t0); + } + + start() { if (this.t0 == null) this.t0 = this._now(); } + + /** Feed the full editor value after every input event. */ + edit(nextText) { + this.start(); + const d = diffText(this.text, nextText); + if (!d) return null; + const t = this.elapsed(); + const last = this.ops[this.ops.length - 1]; + const tRounded = Math.max(Math.round(t), last ? last[0] : 0); + this.ops.push([tRounded, d.pos, d.del, d.ins]); + this.charTimes.splice(d.pos, d.del, ...new Array(d.ins.length).fill(tRounded)); + this.tookBack += d.del; + this.text = nextText; + return d; + } + + /** + * Called on the sampling clock with the latest live signals. + * bpm: number|null, breath: -1..1|null, smile: 0..1|null + */ + sample({ bpm, breath, smile }) { + if (this.t0 == null) return; + const due = Math.floor((this.elapsed() / 1000) * VITALS_HZ) + 1; + while (this.samples.bpm.length < due) { + this.samples.bpm.push(bpm > 0 ? Math.round(bpm) : 0); + this.samples.br.push(breath == null ? 0 : clampInt(breath * 100, -100, 100)); + this.samples.sm.push(smile == null ? 0 : clampInt(smile * 9, 0, 9)); + } + } + + /** Append pulse-wave samples (already resampled to WAVE_HZ, any scale). */ + pushWave(values) { + for (const v of values) this.wave.push(v); + const keep = WAVE_HZ * 20; + if (this.wave.length > keep) this.wave.splice(0, this.wave.length - keep); + } + + /** + * Seal the letter. With share.edits off, the deletions are dropped and + * the letter is rebuilt as if each final character had been typed once, + * at the time it was typed. + */ + finish({ from = '', to = '', day = '', sim = false, share = { edits: false, smiles: true } } = {}) { + const ops = share.edits ? this.ops.map((o) => o.slice()) : opsFromCharTimes(this.text, this.charTimes); + const sm = share.smiles ? this.samples.sm.slice() : this.samples.sm.map(() => 0); + return { + v: FORMAT_VERSION, + from: from.slice(0, 80), + to: to.slice(0, 80), + day, + sim: sim ? 1 : 0, + share: { edits: !!share.edits, smiles: !!share.smiles }, + ops, + vit: { hz: VITALS_HZ, bpm: this.samples.bpm.slice(), br: this.samples.br.slice(), sm }, + wave: { hz: WAVE_HZ, v: normalizeWave(this.wave.slice(-WAVE_HZ * WAVE_SECONDS)) }, + }; + } +} + +/** + * Rebuild a forward-only edit list from the final text and the time each + * character was typed: characters appear in the order they were typed, each + * at its place in the final text. Runs typed at the same moment are merged. + */ +export function opsFromCharTimes(text, times) { + // Work in UTF-16 indices to stay aligned with the editor's value. + const idx = Array.from({ length: text.length }, (_, i) => i); + idx.sort((a, b) => times[a] - times[b] || a - b); + const ops = []; + // Fenwick tree for "how many revealed characters sit before index i". + const tree = new Int32Array(text.length + 1); + const add = (i) => { for (i++; i <= text.length; i += i & -i) tree[i]++; }; + const before = (i) => { let s = 0; for (; i > 0; i -= i & -i) s += tree[i]; return s; }; + for (const i of idx) { + const pos = before(i); + const t = times[i]; + const last = ops[ops.length - 1]; + if (last && last[0] === t && last[1] + last[3].length === pos) { + last[3] += text[i]; + } else { + ops.push([t, pos, 0, text[i]]); + } + add(i); + } + return ops; +} + +/** Scale a wave to integers in -100..100 around its median. */ +export function normalizeWave(values) { + const vals = values.filter((v) => Number.isFinite(v)); + if (vals.length < 2) return []; + const sorted = [...vals].sort((a, b) => a - b); + const med = sorted[Math.floor(sorted.length / 2)]; + let span = 0; + for (const v of vals) span = Math.max(span, Math.abs(v - med)); + if (span === 0) return vals.map(() => 0); + return vals.map((v) => clampInt(((v - med) / span) * 100, -100, 100)); +} + +function clampInt(x, lo, hi) { + return Math.max(lo, Math.min(hi, Math.round(x))); +} diff --git a/src/shared/seal.js b/src/shared/seal.js new file mode 100644 index 0000000..036cedb --- /dev/null +++ b/src/shared/seal.js @@ -0,0 +1,114 @@ +// seal.js +// A wax seal drawn from the writer's own pulse. The wave recorded in the last +// seconds before sealing is wrapped once around the seal, so no two seals +// look alike. Returns an SVG string; deterministic for the same input. + +const SIZE = 200; +const C = SIZE / 2; + +function hash(values) { + let h = 2166136261; + for (const v of values) { h ^= (v + 1000) & 0xffff; h = Math.imul(h, 16777619); } + return h >>> 0; +} + +function rng(seed) { + let s = seed || 1; + return () => { s ^= s << 13; s ^= s >>> 17; s ^= s << 5; return ((s >>> 0) % 10000) / 10000; }; +} + +function polar(r, a) { return [C + r * Math.cos(a), C + r * Math.sin(a)]; } + +function pathFrom(points) { + return `${points.map(([x, y], i) => `${i ? 'L' : 'M'}${x.toFixed(1)} ${y.toFixed(1)}`).join(' ')} Z`; +} + +function smooth(values, k) { + if (!values.length) return values; + return values.map((_, i) => { + let s = 0; let n = 0; + for (let d = -k; d <= k; d++) { + const j = (i + d + values.length) % values.length; + s += values[j]; n++; + } + return s / n; + }); +} + +function escapeXml(s) { + return String(s).replace(/[<>&"']/g, (c) => ({ '<': '<', '>': '>', '&': '&', '"': '"', "'": ''' }[c])); +} + +/** + * @param {number[]} wave pulse wave, -100..100 (may be empty) + * @param {object} opts { initial, bpm, id } + */ +export function sealSvg(wave, { initial = '', bpm = 0, id = 'seal' } = {}) { + const w = wave && wave.length >= 16 ? wave : flatline(120); + const rand = rng(hash(w)); + const uid = `${id}-${hash(w).toString(36)}`; + + // Melted wax edge: an irregular blob, a little different every time. + const edge = []; + const blobs = 7 + Math.floor(rand() * 4); + const phase = rand() * Math.PI * 2; + for (let i = 0; i < 160; i++) { + const a = (i / 160) * Math.PI * 2; + const r = 88 + 4.5 * Math.sin(a * blobs + phase) + 2.2 * Math.sin(a * (blobs + 5) + phase * 2) + (rand() - 0.5) * 1.6; + edge.push(polar(r, a)); + } + + // Pressed rim. + const rim = []; + for (let i = 0; i < 120; i++) rim.push(polar(70, (i / 120) * Math.PI * 2)); + + // The pulse ring: the wave wrapped once around the seal. + const sm = smooth(w, 1); + const ring = []; + const N = sm.length; + for (let i = 0; i < N; i++) { + const a = (i / N) * Math.PI * 2 - Math.PI / 2; + ring.push(polar(56 + (sm[i] / 100) * 9, a)); + } + + const letter = escapeXml((initial || '♥').slice(0, 2).toUpperCase()); + const bpmText = bpm > 0 ? `${Math.round(bpm)} BPM` : ''; + + return ` + + + + + + + + + + + + + + + + + + + + + + ${letter} + ${bpmText ? `${bpmText}` : ''} + + +`; +} + +function flatline(n) { + // A gentle placeholder beat when no wave was captured. + const out = []; + for (let i = 0; i < n; i++) { + const p = (i % 30) / 30; + out.push(Math.round(p < 0.12 ? Math.sin(p / 0.12 * Math.PI) * 80 : p < 0.3 ? -Math.sin((p - 0.12) / 0.18 * Math.PI) * 20 : 0)); + } + return out; +} diff --git a/src/shared/sim-source.js b/src/shared/sim-source.js new file mode 100644 index 0000000..e02647b --- /dev/null +++ b/src/shared/sim-source.js @@ -0,0 +1,83 @@ +// sim-source.js +// A stand-in for the camera, for development and tests only. It emits +// packets shaped like SmartSpectra's decoded Metrics so the rest of the app +// runs the same code path. The app labels every simulated session and every +// letter written with it, so a simulated letter can't pass for a real one. + +export class SimulatedSource { + constructor({ seed = 7, restingBpm = 66, now = () => performance.now() } = {}) { + this.rest = restingBpm; + this.now = now; + this.seed = seed; + this.handlers = {}; + this.timer = null; + this.excite = 0; // 0..1, nudged by bump() + } + + on(event, fn) { this.handlers[event] = fn; return this; } + + emit(event, ...args) { const h = this.handlers[event]; if (h) h(...args); } + + /** Pretend something stirred the writer's heart. */ + bump(amount = 0.6) { this.excite = Math.min(1, this.excite + amount); } + + start() { + this.t0 = this.now(); + this.lastUs = 0; + this.phase = 0; + this.breathPhase = 0; + this.smileUntil = 0; + this.emit('processingStatus', 3); + this.emit('validationStatus', 0, 0, ''); + this.timer = setInterval(() => this.tick(), 200); + } + + stop() { + clearInterval(this.timer); + this.timer = null; + this.emit('processingStatus', 1); + } + + bpmNow(tS) { + const drift = 3 * Math.sin(tS / 23) + 1.5 * Math.sin(tS / 7.3 + this.seed); + return this.rest + drift + this.excite * 22; + } + + /** Build one packet covering the time since the previous one. */ + tick() { + const nowUs = Math.round((this.now() - this.t0) * 1000); + const fromUs = this.lastUs; + this.lastUs = nowUs; + this.excite *= 0.985; + const bpm = this.bpmNow(nowUs / 1e6); + const trace = []; + const breath = []; + for (let t = fromUs; t < nowUs; t += 33333) { + this.phase += (bpm / 60) * 0.033333; + this.breathPhase += (14 / 60) * 0.033333; + trace.push({ value: ppg(this.phase % 1), timestamp: t, stable: true, confidence: 80 }); + breath.push({ value: Math.sin(this.breathPhase * Math.PI * 2), timestamp: t, stable: true }); + } + const tS = nowUs / 1e6; + if (tS > this.smileUntil + 25 && Math.sin(tS * 1.7 + this.seed) > 0.995) this.smileUntil = tS + 2.5; + const happy = tS < this.smileUntil ? 82 : 4; + this.emit('metrics', { + cardio: { + pulseRate: [{ value: bpm, confidence: 78, stable: true, timestamp: nowUs }], + arterialPressureTrace: trace, + }, + breathing: { + rate: [{ value: 14, confidence: 70, stable: true, timestamp: nowUs }], + upperTrace: breath, + }, + face: { expression: [{ stable: true, timestamp: nowUs, scores: [{ type: 5, confidence: happy }, { type: 6, confidence: 100 - happy }] }] }, + }, nowUs); + } +} + +// A rough pulse-wave shape: quick rise, slow fall, a small notch. +function ppg(p) { + if (p < 0.15) return Math.sin((p / 0.15) * (Math.PI / 2)); + const d = (p - 0.15) / 0.85; + return Math.exp(-3.2 * d) + 0.12 * Math.exp(-((d - 0.28) ** 2) / 0.004) - 0.05; +} diff --git a/src/shared/summary.js b/src/shared/summary.js new file mode 100644 index 0000000..142f576 --- /dev/null +++ b/src/shared/summary.js @@ -0,0 +1,98 @@ +// summary.js +// The closing card a reader sees: how long the letter took, where the +// writer's heart was quickest and steadiest, and how often they smiled. +// Wellness wording only: these are camera estimates for feeling, not medicine. + +import { bpmAt, finalChars } from './playback.js'; + +export function median(xs) { + const v = xs.filter((x) => x > 0).sort((a, b) => a - b); + if (!v.length) return 0; + const m = Math.floor(v.length / 2); + return v.length % 2 ? v[m] : Math.round((v[m - 1] + v[m]) / 2); +} + +function percentile(xs, p) { + const v = xs.filter((x) => x > 0).sort((a, b) => a - b); + if (!v.length) return 0; + return v[Math.min(v.length - 1, Math.max(0, Math.round((p / 100) * (v.length - 1))))]; +} + +/** Split text into sentences with their start/end indices. */ +export function sentences(text) { + const out = []; + const re = /[^.!?\n]+[.!?]*["”’)]*|\n+/g; + let m; + while ((m = re.exec(text))) { + const raw = m[0]; + const lead = raw.length - raw.trimStart().length; + const s = raw.trim(); + if (!s) continue; + out.push({ text: s, start: m.index + lead, end: m.index + lead + s.length }); + } + return out; +} + +export function summarize(letter) { + const chars = finalChars(letter); + const text = chars.map((c) => c.ch).join(''); + const baseline = median(letter.vit.bpm); + const scored = []; + for (const s of sentences(text)) { + if (s.text.replace(/\W/g, '').length < 12) continue; // too short to mean much + const bs = []; + for (let i = s.start; i < s.end; i++) { + const b = bpmAt(letter, chars[i].t); + if (b > 0) bs.push(b); + } + if (bs.length < 6) continue; + scored.push({ text: s.text, bpm: Math.round(bs.reduce((a, b) => a + b, 0) / bs.length) }); + } + let quickest = null; + let steadiest = null; + for (const s of scored) { + if (!quickest || s.bpm > quickest.bpm) quickest = s; + if (!steadiest || s.bpm < steadiest.bpm) steadiest = s; + } + // Only call out a difference that is actually there. + if (quickest && steadiest && quickest.bpm - steadiest.bpm < 4) { quickest = null; steadiest = null; } + if (quickest && quickest === steadiest) steadiest = null; + + let smiles = 0; + const sm = letter.vit.sm; + for (let i = 0; i < sm.length; i++) { + if (sm[i] >= 6 && (i === 0 || sm[i - 1] < 6)) smiles++; + } + + const ops = letter.ops; + const writtenMs = ops.length ? ops[ops.length - 1][0] : 0; + return { + words: (text.match(/\S+/g) || []).length, + writtenMs, + baseline, + low: percentile(letter.vit.bpm, 5), + high: percentile(letter.vit.bpm, 95), + quickest, + steadiest, + smiles: letter.share.smiles ? smiles : null, + tookBack: letter.share.edits ? ops.reduce((n, op) => n + op[2], 0) : null, + }; +} + +export function formatDuration(ms) { + const s = Math.round(ms / 1000); + if (s < 60) return `${s} second${s === 1 ? '' : 's'}`; + const m = Math.floor(s / 60); + const r = s % 60; + if (m < 60) return r ? `${m} min ${r} s` : `${m} min`; + const h = Math.floor(m / 60); + return `${h} h ${m % 60} min`; +} + +/** Short excerpt for quoting a sentence on the closing card. */ +export function excerpt(s, max = 64) { + if (s.length <= max) return s; + const cut = s.slice(0, max); + const sp = cut.lastIndexOf(' '); + return `${cut.slice(0, sp > max * 0.6 ? sp : max).trimEnd()}…`; +} diff --git a/src/shared/vitals.js b/src/shared/vitals.js new file mode 100644 index 0000000..85d645a --- /dev/null +++ b/src/shared/vitals.js @@ -0,0 +1,146 @@ +// vitals.js +// Turns SmartSpectra `metrics` packets into the few live signals Heartwritten +// uses. Each packet from the SDK is a windowed slice (only what is new since +// the last packet), so this keeps its own small rolling state. +// +// Signals used: +// cardio.pulseRate[] -> heart rate, only when `stable` +// cardio.arterialPressureTrace[] -> the pulse wave (the seal, the live ink line) +// breathing.upperTrace[] -> the breathing wave (the page breathes with it) +// breathing.rate[] -> breaths per minute (shown live) +// face.expression[] -> HAPPY confidence (a smile in the margin) + +export const HAPPY = 5; // presage.smartspectra.ExpressionType.HAPPY +const PULSE_STALE_MS = 6000; // forget a heart rate this old +const BREATH_WINDOW_S = 20; + +export function tsToUs(ts) { + if (ts == null) return 0; + if (typeof ts === 'number') return ts; + if (typeof ts === 'bigint') return Number(ts); + if (typeof ts.toNumber === 'function') return ts.toNumber(); + return Number(ts); +} + +export class VitalsTracker { + constructor() { this.reset(); } + + reset() { + this.bpm = null; // latest stable heart rate + this.bpmAtUs = 0; + this.breathRate = null; + this.breathTrace = []; // [{t, v}] last BREATH_WINDOW_S seconds + this.pulseTrace = []; // [{t, v}] last 10 seconds + this.smile = 0; // 0..1 + this.lastUs = 0; + this.packets = 0; + } + + /** Feed one decoded Metrics message. Returns the list of new pulse-wave values. */ + ingest(m) { + this.packets++; + const newWave = []; + const cardio = m && m.cardio; + const breathing = m && m.breathing; + const face = m && m.face; + + for (const s of (cardio && cardio.pulseRate) || []) { + const t = tsToUs(s.timestamp); + this.lastUs = Math.max(this.lastUs, t); + if (s.stable && Number.isFinite(s.value) && s.value > 25 && s.value < 230) { + this.bpm = s.value; + this.bpmAtUs = t; + } + } + for (const s of (cardio && cardio.arterialPressureTrace) || []) { + if (!Number.isFinite(s.value)) continue; + const t = tsToUs(s.timestamp); + this.lastUs = Math.max(this.lastUs, t); + this.pulseTrace.push({ t, v: s.value }); + newWave.push(s); + } + for (const s of (breathing && breathing.upperTrace) || []) { + if (!Number.isFinite(s.value)) continue; + const t = tsToUs(s.timestamp); + this.lastUs = Math.max(this.lastUs, t); + this.breathTrace.push({ t, v: s.value }); + } + for (const s of (breathing && breathing.rate) || []) { + if (s.stable && Number.isFinite(s.value)) this.breathRate = s.value; + } + const expr = face && face.expression; + if (expr && expr.length) { + const latest = expr[expr.length - 1]; + const happy = (latest.scores || []).find((x) => x.type === HAPPY); + this.smile = happy ? clamp01((happy.confidence || 0) / 100) : 0; + } + + trimOlderThan(this.pulseTrace, this.lastUs - 10e6); + trimOlderThan(this.breathTrace, this.lastUs - BREATH_WINDOW_S * 1e6); + if (this.bpm != null && this.lastUs - this.bpmAtUs > PULSE_STALE_MS * 1000) this.bpm = null; + return resample(newWave, 30); + } + + /** Where the latest breath sits within the recent range, -1 (out) .. 1 (in). */ + breathPhase() { + const tr = this.breathTrace; + if (tr.length < 8) return null; + let lo = Infinity; let hi = -Infinity; + for (const { v } of tr) { if (v < lo) lo = v; if (v > hi) hi = v; } + if (hi - lo < 1e-9) return 0; + return ((tr[tr.length - 1].v - lo) / (hi - lo)) * 2 - 1; + } + + /** The live signals the recorder samples. */ + snapshot() { + return { bpm: this.bpm, breath: this.breathPhase(), smile: this.smile }; + } +} + +/** Resample timestamped samples ({timestamp, value}) to `hz`, linear. */ +export function resample(samples, hz) { + if (samples.length < 2) return samples.map((s) => s.value); + const pts = samples.map((s) => ({ t: tsToUs(s.timestamp), v: s.value })).sort((a, b) => a.t - b.t); + const step = 1e6 / hz; + const out = []; + let j = 0; + for (let t = pts[0].t; t <= pts[pts.length - 1].t; t += step) { + while (j < pts.length - 2 && pts[j + 1].t < t) j++; + const a = pts[j]; const b = pts[j + 1]; + const f = b.t === a.t ? 0 : (t - a.t) / (b.t - a.t); + out.push(a.v + (b.v - a.v) * Math.max(0, Math.min(1, f))); + } + return out; +} + +/** Plain-language hints for the SDK's validation codes. */ +export const HINTS = { + 0: 'Reading you clearly', + 1: 'I can’t see your face yet', + 2: 'Just one face, please', + 3: 'Slide a little to the centre', + 4: 'Move a little closer or further', + 5: 'A little more light, please', + 6: 'Too bright, ease the light', + 7: 'Sit back so your shoulders show', + 10: 'Tuning the camera…', + 11: 'The camera is running slowly', + 12: 'Keep your head still while you think', + 13: 'Lean back a little', + 14: 'Lean in a little', + 15: 'Lower the camera, or sit taller', + 16: 'Raise the camera a little', + 17: 'Look toward the screen', +}; + +export function hintFor(code, fallback) { + return HINTS[code] || fallback || 'Settling in…'; +} + +function clamp01(x) { return Math.max(0, Math.min(1, x)); } + +function trimOlderThan(arr, tMin) { + let k = 0; + while (k < arr.length && arr[k].t < tMin) k++; + if (k) arr.splice(0, k); +} diff --git a/src/writer/index.html b/src/writer/index.html new file mode 100644 index 0000000..d7d49e9 --- /dev/null +++ b/src/writer/index.html @@ -0,0 +1,93 @@ + + + + + +Heartwritten + + + +
    + + + + + +
    +
    +
    +
    + +
    + — bpm + — breaths/min + ◡ +
    +
    +
    +

    Settling in…

    + + +
    +
    + +
    + + + +
    + +
    + Nothing is recorded until you type. + + +
    +
    + + +
    +
    +
    +

    Sealed.

    +

    + + +
    + + + +
    +

    The camera is off. This letter isn’t saved anywhere on this computer; it exists in that link and any file you save. Closing this window forgets it.

    +
    +
    + +
    + + + diff --git a/src/writer/preload.cjs b/src/writer/preload.cjs new file mode 100644 index 0000000..4001726 --- /dev/null +++ b/src/writer/preload.cjs @@ -0,0 +1,14 @@ +// preload.cjs +// Bundled into dist/preload.cjs. It installs SmartSpectra's own bridge +// (window.__smartspectraBridge) and a tiny Heartwritten bridge. Nothing +// else from Node or Electron reaches the page. +'use strict'; + +require('@smartspectra/node-sdk/preload'); +const { contextBridge, ipcRenderer } = require('electron'); + +contextBridge.exposeInMainWorld('heartwritten', { + getConfig: () => ipcRenderer.invoke('hw:config'), + getApiKey: () => ipcRenderer.invoke('hw:api-key'), + openPreview: (token) => ipcRenderer.invoke('hw:preview', String(token)), +}); diff --git a/src/writer/sdk-source.js b/src/writer/sdk-source.js new file mode 100644 index 0000000..0cc9ac4 --- /dev/null +++ b/src/writer/sdk-source.js @@ -0,0 +1,77 @@ +// sdk-source.js +// The live camera source: SmartSpectra's Electron renderer SDK. It emits the +// same events as SimulatedSource, with each metrics packet already decoded. + +import { + SmartSpectraSDK, breathingMetrics, cardioMetrics, MetricType, SmartSpectraErrorCode, +} from '@smartspectra/node-sdk/renderer'; +import { decodeMetrics } from '@smartspectra/node-sdk/messages'; + +export class SmartSpectraSource { + constructor({ apiKey, telemetry = false, smiles = true }) { + this.apiKey = apiKey; + this.telemetry = telemetry; + this.smiles = smiles; + this.handlers = {}; + this.sdk = null; + this.simulated = false; + } + + on(event, fn) { this.handlers[event] = fn; return this; } + + emit(event, ...args) { const h = this.handlers[event]; if (h) h(...args); } + + metrics() { + // Breathing and cardio for the heart and the breath; EXPRESSIONS alone + // (not the whole face bundle) for smiles, since landmarks aren't needed. + const m = [...breathingMetrics, ...cardioMetrics]; + if (this.smiles) m.push(MetricType.EXPRESSIONS); + return m; + } + + build() { + this.sdk = new SmartSpectraSDK({ + apiKey: this.apiKey, + requestedMetrics: this.metrics(), + enableTelemetry: this.telemetry, + enableAccumulatedOutput: false, + }); + this.sdk.on('streamAvailable', (stream) => this.emit('stream', stream)); + this.sdk.on('processingStatus', (s) => this.emit('processingStatus', s)); + this.sdk.on('validationStatus', (code, ts, hint) => this.emit('validationStatus', code, ts, hint)); + this.sdk.on('metrics', (buf, ts) => { + try { this.emit('metrics', decodeMetrics(buf), ts); } catch (e) { console.error('decode failed', e); } + }); + this.sdk.on('error', (code, message, retryable) => this.onError(code, message, retryable)); + } + + async start() { + if (!this.sdk) this.build(); + try { + await this.sdk.start(); + } catch (err) { + this.onError(err.code, err.message, err.retryable); + } + } + + async onError(code, message, retryable) { + // A key that isn't allowed expressions still gets the heart and breath. + if (code === SmartSpectraErrorCode.kMetricNotAuthorized && this.smiles) { + this.smiles = false; + this.emit('notice', 'Smiles aren’t available with this key, so they’re left out.'); + await this.stop(); + return this.start(); + } + this.emit('error', code, message, retryable); + } + + async stop() { + if (!this.sdk) return; + const sdk = this.sdk; + this.sdk = null; + try { await sdk.stop(); } catch { /* already stopped */ } + try { sdk.destroy(); } catch { /* already destroyed */ } + } +} + +export { SmartSpectraErrorCode }; diff --git a/src/writer/writer.css b/src/writer/writer.css new file mode 100644 index 0000000..cf5db27 --- /dev/null +++ b/src/writer/writer.css @@ -0,0 +1,78 @@ +:root { + --paper: #fbf6ec; + --paper-edge: #efe5d2; + --desk: #e7dcc7; + --ink: #1f2942; + --muted: #6d6556; + --line: rgba(31, 41, 66, 0.12); + --wax: #a3232a; + --serif: "Iowan Old Style", "Palatino Linotype", Palatino, Georgia, serif; + --sans: -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif; +} +* { box-sizing: border-box; } +html, body { margin: 0; height: 100%; } +body { background: var(--desk); color: var(--ink); font: 16px/1.55 var(--serif); -webkit-font-smoothing: antialiased; } +main { max-width: 900px; margin: 0 auto; padding: 28px 24px; min-height: 100%; } +button { font: 15px var(--sans); cursor: pointer; border-radius: 99px; padding: 9px 18px; border: 1px solid rgba(31, 41, 66, 0.25); background: transparent; color: var(--ink); } +button:disabled { opacity: 0.45; cursor: default; } +button.primary { background: var(--ink); color: var(--paper); border-color: var(--ink); } +button.quiet { border-color: transparent; color: var(--muted); } +button:focus-visible, input:focus-visible, textarea:focus-visible { outline: 2px solid #c99a3b; outline-offset: 2px; } + +.step { display: none; } +body[data-step="consent"] .step-consent, +body[data-step="write"] .step-write, +body[data-step="sealed"] .step-sealed { display: block; } + +.card { background: linear-gradient(165deg, var(--paper), var(--paper-edge)); border-radius: 6px; padding: 36px 40px; box-shadow: 0 24px 50px -28px rgba(40, 25, 5, 0.45), 0 1px 4px rgba(40, 25, 5, 0.1); } +.card.center { text-align: center; } +.wordmark { font-style: italic; font-weight: 400; font-size: 42px; margin: 0 0 6px; } +.lede { font-size: 19px; margin: 0 0 18px; } +.facts { padding-left: 18px; margin: 0 0 18px; } +.facts li { margin-bottom: 8px; } +.choices { border: 1px solid var(--line); border-radius: 6px; padding: 12px 16px; margin: 0 0 14px; font: 15px/1.5 var(--sans); } +.choices legend { padding: 0 6px; color: var(--muted); } +.choices label, .agree { display: block; margin: 6px 0; font: 15px/1.5 var(--sans); } +.agree { font-weight: 600; margin: 12px 0 16px; } +.row { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; } +.row.center { justify-content: center; margin-top: 18px; } +.note { color: var(--muted); font: 13px/1.4 var(--sans); } +.fine { color: var(--muted); font: 12px/1.5 var(--sans); margin-top: 18px; } + +/* Live strip */ +.live { display: grid; grid-template-columns: 88px 1fr 200px; gap: 16px; align-items: center; margin-bottom: 16px; } +.cam { position: relative; width: 88px; height: 88px; border-radius: 50%; overflow: hidden; background: #2b2a28; box-shadow: 0 0 0 3px var(--paper); } +.cam video { width: 100%; height: 100%; object-fit: cover; transform: scaleX(-1); } +.rec { position: absolute; right: 10px; top: 10px; width: 9px; height: 9px; border-radius: 50%; background: #d23c3c; box-shadow: 0 0 0 2px var(--paper); } +.camera-off .rec { background: #888; } +.live-heart canvas { width: 100%; height: 64px; display: block; } +.live-stats { display: flex; gap: 18px; font: 13px var(--sans); color: var(--muted); align-items: center; } +.live-stats b { font: 600 20px var(--sans); color: var(--ink); font-variant-numeric: tabular-nums; } +.smile-dot { font-size: 20px; opacity: 0.25; transition: opacity 0.4s, color 0.4s; } +.smile-dot.on { opacity: 1; color: #c48a1a; } +.live-side { text-align: right; } +.hint { margin: 0 0 6px; font: 14px var(--sans); color: #8a4b18; } +.hint[data-ok="true"] { color: #2f6b45; } +.sim { display: inline-block; margin: 0 0 6px; font: 12px var(--sans); background: #f1e0b6; color: #5b4310; border-radius: 99px; padding: 2px 10px; } + +.paper { background: linear-gradient(170deg, var(--paper), var(--paper-edge)); border-radius: 4px; padding: 28px 40px 22px; box-shadow: 0 24px 50px -30px rgba(40, 25, 5, 0.45), 0 1px 4px rgba(40, 25, 5, 0.1); } +.paper label { display: flex; gap: 10px; align-items: baseline; font-style: italic; color: var(--muted); } +.paper input { border: 0; border-bottom: 1px solid var(--line); background: transparent; font: italic 20px var(--serif); color: var(--ink); padding: 2px 4px; flex: 0 1 260px; } +.field-from { justify-content: flex-end; margin-top: 8px; } +textarea { width: 100%; min-height: 46vh; border: 0; resize: vertical; background: repeating-linear-gradient(transparent 0 33px, var(--line) 33px 34px); background-attachment: local; font: 20px/34px var(--serif); color: var(--ink); padding: 8px 2px; margin: 10px 0; } +textarea:focus { outline: none; } +.write-foot { display: flex; gap: 16px; align-items: center; justify-content: space-between; margin-top: 14px; } + +/* Sealed */ +.seal { width: 190px; height: 190px; margin: 0 auto 6px; animation: press 0.7s cubic-bezier(.2,.9,.3,1.3); } +.seal svg { width: 100%; height: 100%; } +@keyframes press { from { transform: scale(1.6) rotate(-10deg); opacity: 0; } } +.step-sealed h2 { font-style: italic; font-weight: 400; font-size: 34px; margin: 0; } +.link-row { display: flex; gap: 8px; max-width: 620px; margin: 10px auto 4px; } +.link-row input { flex: 1; font: 13px ui-monospace, Menlo, monospace; padding: 9px 12px; border-radius: 99px; border: 1px solid var(--line); background: #fff8; color: var(--ink); min-width: 0; } + +@media (prefers-color-scheme: dark) { + body { background: #1d1b18; } + .note, .fine, .live-stats { color: #a89f8e; } + .live-stats b { color: #f0e6d2; } +} diff --git a/src/writer/writer.js b/src/writer/writer.js new file mode 100644 index 0000000..e17e491 --- /dev/null +++ b/src/writer/writer.js @@ -0,0 +1,234 @@ +// writer.js +// The writing desk. Consent first, then the camera, then the letter. + +import { LetterRecorder } from '../shared/recorder.js'; +import { VitalsTracker, hintFor } from '../shared/vitals.js'; +import { encodeLetter, buildLink, finalText } from '../shared/letter-format.js'; +import { inkFor } from '../shared/playback.js'; +import { median, formatDuration } from '../shared/summary.js'; +import { sealSvg } from '../shared/seal.js'; +import { SimulatedSource } from '../shared/sim-source.js'; +import readerHtml from '../../dist/reader/index.html'; + +const $ = (id) => document.getElementById(id); +const bridge = window.heartwritten || null; + +const app = { + cfg: { hasKey: false, simulate: true, readerUrl: '' }, + source: null, + simulated: true, + tracker: new VitalsTracker(), + recorder: new LetterRecorder(), + sampler: 0, + drawer: 0, + bpmHistory: [], + token: '', + letter: null, +}; + +function setStep(step) { document.body.dataset.step = step; } + +async function init() { + if (bridge) app.cfg = await bridge.getConfig(); + app.simulated = app.cfg.simulate || !app.cfg.hasKey; + $('mode-note').textContent = app.simulated + ? 'No SmartSpectra key found, so the signals will be simulated and the letter marked as a sample. See the README to add your key.' + : ''; + $('agree').addEventListener('change', () => { $('begin').disabled = !$('agree').checked; }); + $('begin').addEventListener('click', begin); + $('body').addEventListener('input', onType); + $('seal-it').addEventListener('click', seal); + $('stop-camera').addEventListener('click', stopCamera); + $('copy').addEventListener('click', copyLink); + $('preview-letter').addEventListener('click', previewLetter); + $('save-file').addEventListener('click', saveFile); + $('again').addEventListener('click', () => location.reload()); +} + +// --------------------------------------------------------------------------- +// Camera + +async function begin() { + $('begin').disabled = true; + const share = choices(); + if (app.simulated) { + app.source = new SimulatedSource(); + $('sim-flag').hidden = false; + } else { + const { SmartSpectraSource } = await import('./sdk-source.js'); + const apiKey = await bridge.getApiKey(); + app.source = new SmartSpectraSource({ apiKey, telemetry: share.telemetry, smiles: share.smiles }); + } + const src = app.source; + src.on('stream', (stream) => { $('preview').srcObject = stream; $('preview').play().catch(() => {}); }); + src.on('validationStatus', (code, _ts, hint) => { + $('hint').textContent = hintFor(code, hint); + $('hint').dataset.ok = String(code === 0); + }); + src.on('metrics', (m) => onMetrics(m)); + src.on('notice', (msg) => { $('notice').textContent = msg; }); + src.on('error', (code, message) => { + $('hint').textContent = code === 2 ? 'Your SmartSpectra key wasn’t accepted.' : `The camera stopped: ${message}`; + $('hint').dataset.ok = 'false'; + }); + setStep('write'); + await src.start(); + app.sampler = setInterval(() => app.recorder.sample(app.tracker.snapshot()), 250); + app.drawer = requestAnimationFrame(drawWave); + $('body').focus(); +} + +async function stopCamera() { + const src = app.source; + app.source = null; + if (src) await src.stop(); + app.tracker.reset(); + $('preview').srcObject = null; + $('hint').textContent = 'Camera off. The rest of the letter keeps no heartbeat.'; + $('hint').dataset.ok = 'false'; + $('stop-camera').disabled = true; + document.body.classList.add('camera-off'); +} + +function onMetrics(m) { + const wave = app.tracker.ingest(m); + if (wave.length) app.recorder.pushWave(wave); + const t = app.tracker; + if (t.bpm) { + app.bpmHistory.push(t.bpm); + if (app.bpmHistory.length > 400) app.bpmHistory.shift(); + } + $('live-bpm').textContent = t.bpm ? Math.round(t.bpm) : '—'; + $('live-br').textContent = t.breathRate ? Math.round(t.breathRate) : '—'; + $('live-smile').classList.toggle('on', choices().smiles && t.smile >= 0.6); +} + +function drawWave() { + const c = $('wave'); + const ctx = c.getContext && c.getContext('2d'); + if (!ctx) return; + const W = c.width; const H = c.height; + ctx.clearRect(0, 0, W, H); + const tr = app.tracker.pulseTrace; + if (tr.length > 4) { + const tEnd = tr[tr.length - 1].t; + const span = 6e6; + let lo = Infinity; let hi = -Infinity; + for (const { t, v } of tr) if (t >= tEnd - span) { lo = Math.min(lo, v); hi = Math.max(hi, v); } + const range = hi - lo || 1; + ctx.lineWidth = 2.2; + ctx.lineJoin = 'round'; + ctx.strokeStyle = inkFor(app.tracker.bpm, median(app.bpmHistory)); + ctx.beginPath(); + let first = true; + for (const { t, v } of tr) { + if (t < tEnd - span) continue; + const x = ((t - (tEnd - span)) / span) * W; + const y = H - 6 - ((v - lo) / range) * (H - 12); + if (first) { ctx.moveTo(x, y); first = false; } else ctx.lineTo(x, y); + } + ctx.stroke(); + } + app.drawer = requestAnimationFrame(drawWave); +} + +// --------------------------------------------------------------------------- +// Writing + +function onType(e) { + app.recorder.edit(e.target.value); + if (app.simulated && app.source && e.data === '!') app.source.bump(0.5); + $('seal-it').disabled = !e.target.value.trim(); + updateClock(); +} + +function updateClock() { + const words = (app.recorder.text.match(/\S+/g) || []).length; + $('clock').textContent = `Writing for ${formatDuration(app.recorder.elapsed())} · ${words} word${words === 1 ? '' : 's'} · nothing saved yet`; +} +setInterval(() => { if (app.recorder.t0 != null && document.body.dataset.step === 'write') updateClock(); }, 1000); + +function choices() { + return { + smiles: $('opt-smiles').checked, + edits: $('opt-edits').checked, + telemetry: $('opt-telemetry').checked, + }; +} + +function today() { + const d = new Date(); + return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; +} + +// --------------------------------------------------------------------------- +// Sealing + +async function seal() { + $('seal-it').disabled = true; + clearInterval(app.sampler); + cancelAnimationFrame(app.drawer); + const src = app.source; + app.source = null; + if (src) await src.stop(); + $('preview').srcObject = null; + + const { smiles, edits } = choices(); + const letter = app.recorder.finish({ + from: $('from').value.trim(), + to: $('to').value.trim(), + day: today(), + sim: app.simulated, + share: { smiles, edits }, + }); + app.letter = letter; + app.token = await encodeLetter(letter); + const base = median(letter.vit.bpm); + $('seal').innerHTML = sealSvg(letter.wave.v, { initial: letter.from.charAt(0), bpm: base }); + const bits = []; + if (letter.to) bits.push(`For ${letter.to}`); + bits.push(`written in ${formatDuration(app.recorder.elapsed())}`); + if (base) bits.push(`your heart around ${base} bpm`); + $('sealed-sub').textContent = `${bits.join(' · ')}.`; + const link = app.cfg.readerUrl ? buildLink(app.cfg.readerUrl, app.token) : ''; + $('link').value = link || 'Set a reader address to share by link, or save it as a file.'; + $('copy').disabled = !link; + $('link-note').textContent = link.length > 6000 + ? 'This is a long letter, so the link is long. Some chat apps cut long links; if it won’t open for them, send the file instead.' + : (app.simulated ? 'Marked as a sample letter, because the signals were simulated.' : ''); + setStep('sealed'); +} + +async function copyLink() { + try { + await navigator.clipboard.writeText($('link').value); + $('copy').textContent = 'Copied'; + setTimeout(() => { $('copy').textContent = 'Copy link'; }, 1600); + } catch { + $('link').select(); + } +} + +function previewLetter() { + if (bridge) return bridge.openPreview(app.token); + return window.open(`../reader/index.html#${app.token}`, '_blank', 'noopener'); +} + +export function letterFileHtml(token) { + return readerHtml.replace('', + ``); +} + +function saveFile() { + const html = letterFileHtml(app.token); + const name = (app.letter.to || 'you').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'you'; + const a = document.createElement('a'); + a.href = URL.createObjectURL(new Blob([html], { type: 'text/html' })); + a.download = `a-letter-for-${name}.html`; + a.click(); + setTimeout(() => URL.revokeObjectURL(a.href), 4000); +} + +export { finalText }; + +if (!globalThis.__HW_NO_AUTOBOOT__) init(); diff --git a/test/core.test.js b/test/core.test.js new file mode 100644 index 0000000..a34bf3a --- /dev/null +++ b/test/core.test.js @@ -0,0 +1,254 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; + +import { + encodeLetter, decodeLetter, pack, unpack, validate, finalText, extractToken, buildLink, +} from '../src/shared/letter-format.js'; +import { diffText, LetterRecorder, opsFromCharTimes, normalizeWave, VITALS_HZ } from '../src/shared/recorder.js'; +import { VitalsTracker, resample, hintFor } from '../src/shared/vitals.js'; +import { Player, buildTimeline, bpmAt, inkFor, finalChars } from '../src/shared/playback.js'; +import { summarize, sentences, median, formatDuration, excerpt } from '../src/shared/summary.js'; +import { sealSvg } from '../src/shared/seal.js'; +import { SimulatedSource } from '../src/shared/sim-source.js'; + +// A fake clock the recorder can read. +function clock() { + let t = 1_000_000; + const now = () => t; + now.tick = (ms) => { t += ms; }; + return now; +} + +// Types `s` into the recorder one char at a time, `gap` ms apart. +function type(rec, now, s, gap = 120) { + for (const ch of s) { now.tick(gap); rec.edit(rec.text + ch); } +} + +function backspace(rec, now, n, gap = 90) { + for (let i = 0; i < n; i++) { now.tick(gap); rec.edit(rec.text.slice(0, -1)); } +} + +function sampleLetter({ edits = true, smiles = true } = {}) { + const now = clock(); + const rec = new LetterRecorder({ now }); + let bpm = 64; + const feed = () => rec.sample({ bpm, breath: Math.sin(now() / 700), smile: bpm > 80 ? 0.9 : 0.1 }); + for (const ch of 'Dear Deola, I have news. ') { now.tick(150); rec.edit(rec.text + ch); feed(); } + bpm = 88; + for (const ch of 'I got the job I told you about!') { now.tick(130); rec.edit(rec.text + ch); feed(); } + backspace(rec, now, 1); feed(); + rec.edit(`${rec.text}.`); feed(); + now.tick(12000); feed(); // a long pause + bpm = 62; + for (const ch of ' Thank you for believing in me when I did not.') { now.tick(160); rec.edit(rec.text + ch); feed(); } + rec.pushWave(Array.from({ length: 300 }, (_, i) => Math.sin(i / 4))); + return rec.finish({ from: 'Subomi', to: 'Deola', day: '2026-11-12', share: { edits, smiles } }); +} + +test('diffText finds the smallest edit', () => { + assert.deepEqual(diffText('', 'a'), { pos: 0, del: 0, ins: 'a' }); + assert.deepEqual(diffText('abc', 'abXc'), { pos: 2, del: 0, ins: 'X' }); + assert.deepEqual(diffText('hello world', 'hello'), { pos: 5, del: 6, ins: '' }); + assert.deepEqual(diffText('I love it', 'I adore it'), { pos: 2, del: 3, ins: 'ador' }); + assert.equal(diffText('same', 'same'), null); +}); + +test('recorder replays to the exact final text, with and without edits', () => { + for (const edits of [true, false]) { + const letter = sampleLetter({ edits }); + const expected = 'Dear Deola, I have news. I got the job I told you about. Thank you for believing in me when I did not.'; + assert.equal(finalText(letter), expected); + assert.equal(finalChars(letter).map((c) => c.ch).join(''), expected); + validate(letter); + } +}); + +test('with edits off, nothing deleted survives in the letter', () => { + const now = clock(); + const rec = new LetterRecorder({ now }); + type(rec, now, 'I miss you'); + backspace(rec, now, 8); + type(rec, now, 'am fine'); + const hidden = rec.finish({ share: { edits: false, smiles: true } }); + const json = JSON.stringify(pack(hidden)); + assert.ok(!json.includes('miss'), 'deleted words must not be in the payload'); + assert.ok(hidden.ops.every((op) => op[2] === 0), 'no deletions'); + assert.equal(finalText(hidden), 'I am fine'); + const shown = rec.finish({ share: { edits: true, smiles: true } }); + const p = new Player(shown); + let sawIt = false; + for (let at = 0; !p.done; at += 40) { p.advance(at); if (p.text().includes('I miss you')) sawIt = true; } + assert.ok(sawIt, 'with edits on, the reader sees the words that were taken back'); +}); + +test('opsFromCharTimes keeps typing order for edits made mid-text', () => { + // "ac" typed first, then "b" inserted between them later. + const ops = opsFromCharTimes('abc', [0, 500, 10]); + const letter = { ops, vit: { hz: 1, bpm: [], br: [], sm: [] }, wave: { hz: 25, v: [] }, share: {} }; + assert.equal(finalText(letter), 'abc'); + assert.deepEqual(ops.map((o) => o[0]), [0, 10, 500]); +}); + +test('smiles off means no smile samples are kept', () => { + const letter = sampleLetter({ smiles: false }); + assert.ok(letter.vit.sm.every((x) => x === 0)); + const packed = pack(letter); + assert.equal(packed.m, undefined); +}); + +test('pack/unpack and link encoding round-trip', async () => { + const letter = sampleLetter(); + assert.deepEqual(unpack(pack(letter)), letter); + const token = await encodeLetter(letter); + assert.match(token, /^v1\.[A-Za-z0-9_-]+$/); + const link = buildLink('https://example.test/read/', token); + const back = await decodeLetter(link); + assert.deepEqual(back, letter); + assert.equal(extractToken(`https://x.test/#${token}`), token); + assert.equal(extractToken('https://x.test/#nothing'), null); +}); + +test('a long letter still fits in a reasonable link', async () => { + const now = clock(); + const rec = new LetterRecorder({ now }); + const para = 'It has been a strange and lovely year, and I keep wanting to tell you about the small things. '; + for (let i = 0; i < 16; i++) { // ~1,500 characters over ~4 minutes + for (const ch of para) { now.tick(160); rec.edit(rec.text + ch); rec.sample({ bpm: 70 + (i % 5), breath: 0.2, smile: 0 }); } + } + rec.pushWave(Array.from({ length: 300 }, (_, i) => Math.sin(i / 4))); + const token = await encodeLetter(rec.finish({ share: { edits: true, smiles: true } })); + assert.ok(token.length < 12000, `token is ${token.length} chars`); +}); + +test('decoder rejects tampered or hostile letters', async () => { + const bad = [ + { ...pack(sampleLetter()), v: 9 }, + { ...pack(sampleLetter()), o: [[0, 5, 0, 'x']] }, // insert past the end + { ...pack(sampleLetter()), o: [[0, 0, 3, '']] }, // delete what isn't there + { ...pack(sampleLetter()), vh: 999 }, + ]; + for (const p of bad) assert.throws(() => unpack(p)); + await assert.rejects(decodeLetter('v1.!!!')); + await assert.rejects(decodeLetter('no letter here')); +}); + +test('vitals tracker reads SDK-shaped packets', () => { + const v = new VitalsTracker(); + v.ingest({ cardio: { pulseRate: [{ value: 72, stable: false, timestamp: 1e6 }] } }); + assert.equal(v.bpm, null, 'unstable readings are ignored'); + const wave = v.ingest({ + cardio: { + pulseRate: [{ value: 71.6, stable: true, confidence: 60, timestamp: { toNumber: () => 2e6 } }], + arterialPressureTrace: Array.from({ length: 30 }, (_, i) => ({ value: Math.sin(i), timestamp: 2e6 + i * 33333 })), + }, + breathing: { rate: [{ value: 13, stable: true }], upperTrace: Array.from({ length: 20 }, (_, i) => ({ value: i, timestamp: 2e6 + i * 50000 })) }, + face: { expression: [{ scores: [{ type: 5, confidence: 90 }, { type: 6, confidence: 10 }] }] }, + }); + assert.equal(v.bpm, 71.6); + assert.equal(v.breathRate, 13); + assert.ok(wave.length >= 28 && wave.length <= 31); + const snap = v.snapshot(); + assert.equal(snap.smile, 0.9); + assert.equal(snap.breath, 1, 'latest breath sample is the top of the range'); + // Heart rate goes stale when no fresh stable value arrives. + v.ingest({ cardio: { arterialPressureTrace: [{ value: 0, timestamp: 9e6 }] } }); + assert.equal(v.bpm, null); +}); + +test('resample produces evenly spaced values', () => { + const s = [{ value: 0, timestamp: 0 }, { value: 10, timestamp: 1e6 }]; + const r = resample(s, 10); + assert.equal(r.length, 11); + assert.equal(r[5], 5); +}); + +test('hints read like a person talking', () => { + assert.equal(hintFor(5), 'A little more light, please'); + assert.equal(hintFor(999, 'SDK hint'), 'SDK hint'); +}); + +test('timeline shortens long pauses and remembers them', () => { + const letter = sampleLetter(); + const tl = buildTimeline(letter); + assert.ok(tl.pauses.length >= 1, 'the 12 s pause is noted'); + assert.ok(tl.pauses[0].ms >= 12000); + assert.ok(tl.duration < tl.writtenMs, 'replay is shorter than the writing'); + for (let i = 1; i < tl.ops.length; i++) assert.ok(tl.ops[i].at >= tl.ops[i - 1].at); +}); + +test('player shows the writer taking a word back', () => { + const letter = sampleLetter({ edits: true }); + const p = new Player(letter); + let sawBang = false; + for (let at = 0; !p.done; at += 50) { + p.advance(at); + if (p.text().endsWith('about!')) sawBang = true; + } + assert.ok(sawBang, 'the exclamation mark appears before it is replaced'); + assert.equal(p.tookBack, 1); + assert.equal(p.text(), finalText(letter)); +}); + +test('ink warms with a quicker heart and stays calm otherwise', () => { + assert.equal(inkFor(66, 66), 'rgb(31, 41, 66)'); + assert.equal(inkFor(0, 66), 'rgb(31, 41, 66)'); + const warm = inkFor(90, 66).match(/\d+/g).map(Number); + assert.ok(warm[0] > 150 && warm[2] < 50); +}); + +test('summary finds the quickest and steadiest sentences', () => { + const s = summarize(sampleLetter()); + assert.match(s.quickest.text, /got the job/); + assert.match(s.steadiest.text, /believing in me/); + assert.ok(s.quickest.bpm > s.steadiest.bpm); + assert.equal(s.tookBack, 1); + assert.ok(s.smiles >= 1); + assert.ok(s.words > 15); + assert.equal(median([0, 60, 70, 80]), 70); + assert.equal(formatDuration(75_000), '1 min 15 s'); + assert.equal(excerpt('a '.repeat(80)).endsWith('…'), true); +}); + +test('summary says nothing about the heart when it barely moved', () => { + const now = clock(); + const rec = new LetterRecorder({ now }); + for (const ch of 'One calm sentence here. And another calm sentence.') { now.tick(150); rec.edit(rec.text + ch); rec.sample({ bpm: 70, breath: 0, smile: 0 }); } + const s = summarize(rec.finish({})); + assert.equal(s.quickest, null); + assert.equal(s.steadiest, null); +}); + +test('sentences splits on punctuation and new lines', () => { + assert.deepEqual(sentences('Hi there. How are you?\nGood!').map((s) => s.text), ['Hi there.', 'How are you?', 'Good!']); +}); + +test('bpmAt looks past gaps in the signal', () => { + const letter = { vit: { hz: VITALS_HZ, bpm: [0, 0, 70, 0, 0], br: [], sm: [] } }; + assert.equal(bpmAt(letter, 0), 70); + assert.equal(bpmAt(letter, 1000), 70); +}); + +test('seal is deterministic, unique per pulse and safe to inline', () => { + const a = sealSvg(normalizeWave(Array.from({ length: 180 }, (_, i) => Math.sin(i / 5))), { initial: 'S', bpm: 68 }); + const b = sealSvg(normalizeWave(Array.from({ length: 180 }, (_, i) => Math.sin(i / 5))), { initial: 'S', bpm: 68 }); + const c = sealSvg(normalizeWave(Array.from({ length: 180 }, (_, i) => Math.sin(i / 3))), { initial: 'S', bpm: 68 }); + assert.equal(a, b); + assert.notEqual(a, c); + assert.match(a, /^$/); + assert.match(a, /68 BPM/); + const evil = sealSvg([], { initial: '', ''); + const { win, doc, errors } = load(html, 'file:///app/dist/writer/index.html'); + const js = await readFile(new URL('dist/writer/writer.js', root), 'utf8'); + win.eval(js); + + assert.equal(doc.body.dataset.step, 'consent', 'nothing starts before consent'); + assert.ok(doc.getElementById('begin').disabled, 'camera button waits for agreement'); + assert.match(doc.getElementById('mode-note').textContent, /simulated/); + doc.getElementById('opt-edits').checked = true; + const agree = doc.getElementById('agree'); + agree.checked = true; + agree.dispatchEvent(new win.Event('change')); + assert.equal(doc.getElementById('begin').disabled, false); + doc.getElementById('begin').click(); + assert.ok(await until(() => doc.body.dataset.step === 'write')); + assert.equal(doc.getElementById('sim-flag').hidden, false, 'simulated signals are labelled'); + assert.ok(await until(() => doc.getElementById('live-bpm').textContent !== '—', 3000), 'live heart rate shows'); + + doc.getElementById('to').value = 'Maya'; + doc.getElementById('from').value = 'Sam'; + const body = doc.getElementById('body'); + for (const ch of 'Hello Maya. I got it!') { + body.value += ch; + body.dispatchEvent(new win.InputEvent('input', { data: ch })); + await wait(15); + } + await wait(600); + assert.equal(doc.getElementById('seal-it').disabled, false); + doc.getElementById('seal-it').click(); + assert.ok(await until(() => doc.body.dataset.step === 'sealed'), 'sealed'); + assert.ok(doc.querySelector('#seal svg')); + assert.match(doc.getElementById('sealed-sub').textContent, /For Maya/); + assert.match(doc.getElementById('link-note').textContent, /sample/); + assert.deepEqual(errors, []); + win.close(); +}); diff --git a/vercel.json b/vercel.json new file mode 100644 index 0000000..e00e093 --- /dev/null +++ b/vercel.json @@ -0,0 +1,12 @@ +{ + "installCommand": "ELECTRON_SKIP_BINARY_DOWNLOAD=1 npm ci", + "buildCommand": "node scripts/build.mjs", + "outputDirectory": "dist/reader", + "headers": [ + { "source": "/(.*)", "headers": [ + { "key": "Referrer-Policy", "value": "no-referrer" }, + { "key": "X-Content-Type-Options", "value": "nosniff" }, + { "key": "Cache-Control", "value": "public, max-age=300" } + ] } + ] +}