commit 533aec8ba2e9c6dd9d2136479faccd87ce21f93a Author: ztimson Date: Sun Jun 21 22:14:04 2026 -0400 init diff --git a/.env b/.env new file mode 100644 index 0000000..d8c6062 --- /dev/null +++ b/.env @@ -0,0 +1 @@ +INFLUX_TOKEN= diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d97f3f9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +dist +node_modules +.env.local diff --git a/client/.gitignore b/client/.gitignore new file mode 100644 index 0000000..cd68f14 --- /dev/null +++ b/client/.gitignore @@ -0,0 +1,39 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +lerna-debug.log* + +node_modules +.DS_Store +dist +dist-ssr +coverage +*.local + +# Editor directories and files +.vscode/* +!.vscode/extensions.json +.idea +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? + +*.tsbuildinfo + +.eslintcache + +# Cypress +/cypress/videos/ +/cypress/screenshots/ + +# Vitest +__screenshots__/ + +# Vite +*.timestamp-*-*.mjs diff --git a/client/.vscode/extensions.json b/client/.vscode/extensions.json new file mode 100644 index 0000000..a7cea0b --- /dev/null +++ b/client/.vscode/extensions.json @@ -0,0 +1,3 @@ +{ + "recommendations": ["Vue.volar"] +} diff --git a/client/README.md b/client/README.md new file mode 100644 index 0000000..9808dc5 --- /dev/null +++ b/client/README.md @@ -0,0 +1,42 @@ +# client + +This template should help get you started developing with Vue 3 in Vite. + +## Recommended IDE Setup + +[VS Code](https://code.visualstudio.com/) + [Vue (Official)](https://marketplace.visualstudio.com/items?itemName=Vue.volar) (and disable Vetur). + +## Recommended Browser Setup + +- Chromium-based browsers (Chrome, Edge, Brave, etc.): + - [Vue.js devtools](https://chromewebstore.google.com/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd) + - [Turn on Custom Object Formatter in Chrome DevTools](http://bit.ly/object-formatters) +- Firefox: + - [Vue.js devtools](https://addons.mozilla.org/en-US/firefox/addon/vue-js-devtools/) + - [Turn on Custom Object Formatter in Firefox DevTools](https://fxdx.dev/firefox-devtools-custom-object-formatters/) + +## Type Support for `.vue` Imports in TS + +TypeScript cannot handle type information for `.vue` imports by default, so we replace the `tsc` CLI with `vue-tsc` for type checking. In editors, we need [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) to make the TypeScript language service aware of `.vue` types. + +## Customize configuration + +See [Vite Configuration Reference](https://vite.dev/config/). + +## Project Setup + +```sh +npm install +``` + +### Compile and Hot-Reload for Development + +```sh +npm run dev +``` + +### Type-Check, Compile and Minify for Production + +```sh +npm run build +``` diff --git a/client/env.d.ts b/client/env.d.ts new file mode 100644 index 0000000..11f02fe --- /dev/null +++ b/client/env.d.ts @@ -0,0 +1 @@ +/// diff --git a/client/index.html b/client/index.html new file mode 100644 index 0000000..9e5fc8f --- /dev/null +++ b/client/index.html @@ -0,0 +1,13 @@ + + + + + + + Vite App + + +
+ + + diff --git a/client/package.json b/client/package.json new file mode 100644 index 0000000..f47261e --- /dev/null +++ b/client/package.json @@ -0,0 +1,27 @@ +{ + "name": "weather-station", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "start": "vite", + "build": "vue-tsc --build && vue build" + }, + "dependencies": { + "vue": "^3.5.38" + }, + "devDependencies": { + "@tsconfig/node24": "^24.0.4", + "@types/node": "^24.13.2", + "@vitejs/plugin-vue": "^6.0.7", + "@vue/tsconfig": "^0.9.1", + "npm-run-all2": "^9.0.2", + "typescript": "~6.0.0", + "vite": "^8.0.16", + "vite-plugin-vue-devtools": "^8.1.2", + "vue-tsc": "^3.3.5" + }, + "engines": { + "node": "^22.18.0 || >=24.12.0" + } +} diff --git a/client/public/favicon.ico b/client/public/favicon.ico new file mode 100644 index 0000000..df36fcf Binary files /dev/null and b/client/public/favicon.ico differ diff --git a/client/src/App.vue b/client/src/App.vue new file mode 100644 index 0000000..51bda8c --- /dev/null +++ b/client/src/App.vue @@ -0,0 +1,77 @@ + + + + + + + diff --git a/client/src/assets/base.css b/client/src/assets/base.css new file mode 100644 index 0000000..8816868 --- /dev/null +++ b/client/src/assets/base.css @@ -0,0 +1,86 @@ +/* color palette from */ +:root { + --vt-c-white: #ffffff; + --vt-c-white-soft: #f8f8f8; + --vt-c-white-mute: #f2f2f2; + + --vt-c-black: #181818; + --vt-c-black-soft: #222222; + --vt-c-black-mute: #282828; + + --vt-c-indigo: #2c3e50; + + --vt-c-divider-light-1: rgba(60, 60, 60, 0.29); + --vt-c-divider-light-2: rgba(60, 60, 60, 0.12); + --vt-c-divider-dark-1: rgba(84, 84, 84, 0.65); + --vt-c-divider-dark-2: rgba(84, 84, 84, 0.48); + + --vt-c-text-light-1: var(--vt-c-indigo); + --vt-c-text-light-2: rgba(60, 60, 60, 0.66); + --vt-c-text-dark-1: var(--vt-c-white); + --vt-c-text-dark-2: rgba(235, 235, 235, 0.64); +} + +/* semantic color variables for this project */ +:root { + --color-background: var(--vt-c-white); + --color-background-soft: var(--vt-c-white-soft); + --color-background-mute: var(--vt-c-white-mute); + + --color-border: var(--vt-c-divider-light-2); + --color-border-hover: var(--vt-c-divider-light-1); + + --color-heading: var(--vt-c-text-light-1); + --color-text: var(--vt-c-text-light-1); + + --section-gap: 160px; +} + +@media (prefers-color-scheme: dark) { + :root { + --color-background: var(--vt-c-black); + --color-background-soft: var(--vt-c-black-soft); + --color-background-mute: var(--vt-c-black-mute); + + --color-border: var(--vt-c-divider-dark-2); + --color-border-hover: var(--vt-c-divider-dark-1); + + --color-heading: var(--vt-c-text-dark-1); + --color-text: var(--vt-c-text-dark-2); + } +} + +*, +*::before, +*::after { + box-sizing: border-box; + margin: 0; + font-weight: normal; +} + +body { + min-height: 100vh; + color: var(--color-text); + background: var(--color-background); + transition: + color 0.5s, + background-color 0.5s; + line-height: 1.6; + font-family: + Inter, + -apple-system, + BlinkMacSystemFont, + 'Segoe UI', + Roboto, + Oxygen, + Ubuntu, + Cantarell, + 'Fira Sans', + 'Droid Sans', + 'Helvetica Neue', + sans-serif; + font-size: 15px; + text-rendering: optimizeLegibility; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} diff --git a/client/src/assets/logo.svg b/client/src/assets/logo.svg new file mode 100644 index 0000000..7565660 --- /dev/null +++ b/client/src/assets/logo.svg @@ -0,0 +1 @@ + diff --git a/client/src/assets/main.css b/client/src/assets/main.css new file mode 100644 index 0000000..36fb845 --- /dev/null +++ b/client/src/assets/main.css @@ -0,0 +1,35 @@ +@import './base.css'; + +#app { + max-width: 1280px; + margin: 0 auto; + padding: 2rem; + font-weight: normal; +} + +a, +.green { + text-decoration: none; + color: hsla(160, 100%, 37%, 1); + transition: 0.4s; + padding: 3px; +} + +@media (hover: hover) { + a:hover { + background-color: hsla(160, 100%, 37%, 0.2); + } +} + +@media (min-width: 1024px) { + body { + display: flex; + place-items: center; + } + + #app { + display: grid; + grid-template-columns: 1fr 1fr; + padding: 0 2rem; + } +} diff --git a/client/src/components/CurrentWeather.vue b/client/src/components/CurrentWeather.vue new file mode 100644 index 0000000..165b868 --- /dev/null +++ b/client/src/components/CurrentWeather.vue @@ -0,0 +1,99 @@ + + + + + diff --git a/client/src/components/ForecastStrip.vue b/client/src/components/ForecastStrip.vue new file mode 100644 index 0000000..67d9fcf --- /dev/null +++ b/client/src/components/ForecastStrip.vue @@ -0,0 +1,62 @@ + + + + + diff --git a/client/src/components/GraphModal.vue b/client/src/components/GraphModal.vue new file mode 100644 index 0000000..bf5ea39 --- /dev/null +++ b/client/src/components/GraphModal.vue @@ -0,0 +1,87 @@ + + + + + diff --git a/client/src/components/MapView.vue b/client/src/components/MapView.vue new file mode 100644 index 0000000..7f34aaf --- /dev/null +++ b/client/src/components/MapView.vue @@ -0,0 +1,169 @@ + + + + + diff --git a/client/src/components/MetricCard.vue b/client/src/components/MetricCard.vue new file mode 100644 index 0000000..8b52692 --- /dev/null +++ b/client/src/components/MetricCard.vue @@ -0,0 +1,76 @@ + + + + + diff --git a/client/src/components/MetricChart.vue b/client/src/components/MetricChart.vue new file mode 100644 index 0000000..91b87c5 --- /dev/null +++ b/client/src/components/MetricChart.vue @@ -0,0 +1,160 @@ + + + + + diff --git a/client/src/main.ts b/client/src/main.ts new file mode 100644 index 0000000..0ac3a5f --- /dev/null +++ b/client/src/main.ts @@ -0,0 +1,6 @@ +import './assets/main.css' + +import { createApp } from 'vue' +import App from './App.vue' + +createApp(App).mount('#app') diff --git a/client/src/services/api.ts b/client/src/services/api.ts new file mode 100644 index 0000000..4abbcf8 --- /dev/null +++ b/client/src/services/api.ts @@ -0,0 +1,16 @@ +const BASE = import.meta.env.DEV ? 'http://localhost:3000' : '' + +export type DataRow = Record + +async function get(path: string, params: Record = {}): Promise { + const url = new URL(`${BASE}${path}`, window.location.origin) + Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v)) + const res = await fetch(url.toString()) + return res.json() +} + +export const api = { + current: (fields?: string) => get('/api/data', fields ? { fields } : {}), + hourly: (start?: string, end?: string, fields?: string) => get('/api/hourly', { ...(start ? { start } : {}), ...(end ? { end } : {}), ...(fields ? { fields } : {}) }), + daily: (start?: string, end?: string, fields?: string) => get('/api/daily', { ...(start ? { start } : {}), ...(end ? { end } : {}), ...(fields ? { fields } : {}) }), +} diff --git a/client/src/services/units.ts b/client/src/services/units.ts new file mode 100644 index 0000000..8afc98f --- /dev/null +++ b/client/src/services/units.ts @@ -0,0 +1,79 @@ +export interface MetricMeta { + label: string + unit: string + icon: string + group: string + precision: number + color: string +} + +export const METRICS: Record = { + // Environment + env_temp_c: { label: 'Temperature', unit: 'Β°C', icon: '🌑️', group: 'Environment', precision: 1, color: '#f97316' }, + env_temp_f: { label: 'Temperature', unit: 'Β°F', icon: '🌑️', group: 'Environment', precision: 1, color: '#f97316' }, + env_humidity: { label: 'Humidity', unit: '%', icon: 'πŸ’§', group: 'Environment', precision: 1, color: '#38bdf8' }, + env_dew_point_c: { label: 'Dew Point', unit: 'Β°C', icon: '🌫️', group: 'Environment', precision: 1, color: '#818cf8' }, + env_heat_index_c: { label: 'Feels Like', unit: 'Β°C', icon: 'πŸ€”', group: 'Environment', precision: 1, color: '#fb923c' }, + env_pressure_hpa: { label: 'Pressure', unit: ' hPa', icon: 'πŸ“Š', group: 'Environment', precision: 1, color: '#a78bfa' }, + env_pressure_slp: { label: 'Sea Level Pressure', unit: ' hPa', icon: 'πŸ“Š', group: 'Environment', precision: 1, color: '#a78bfa' }, + env_abs_humidity: { label: 'Absolute Humidity', unit: ' g/mΒ³', icon: 'πŸ’¦', group: 'Environment', precision: 2, color: '#67e8f9' }, + env_vpd_kpa: { label: 'Vapour Pressure Deficit', unit: ' kPa', icon: '🌿', group: 'Environment', precision: 2, color: '#4ade80' }, + env_aqi_score: { label: 'Air Quality', unit: '/100', icon: '🏭', group: 'Environment', precision: 0, color: '#34d399' }, + env_gas_ohms: { label: 'Gas Resistance', unit: ' Ξ©', icon: 'βš—οΈ', group: 'Environment', precision: 0, color: '#fbbf24' }, + // Light + light_lux: { label: 'Illuminance', unit: ' lux', icon: 'β˜€οΈ', group: 'Light', precision: 0, color: '#fde68a' }, + light_uvi: { label: 'UV Index', unit: '', icon: 'πŸ•ΆοΈ', group: 'Light', precision: 1, color: '#f472b6' }, + light_solar_wm2: { label: 'Solar Irradiance', unit: ' W/mΒ²', icon: '⚑', group: 'Light', precision: 1, color: '#fcd34d' }, + light_uv_dose_mj: { label: 'UV Dose Today', unit: ' mJ/cmΒ²', icon: 'πŸ“‘', group: 'Light', precision: 2, color: '#f9a8d4' }, + light_burn_time_min: { label: 'Burn Time', unit: ' min', icon: 'πŸ”₯', group: 'Light', precision: 0, color: '#fb7185' }, + light_cloud_pct: { label: 'Cloud Cover', unit: '%', icon: '☁️', group: 'Light', precision: 0, color: '#94a3b8' }, + light_dli: { label: 'Daily Light Integral', unit: ' mol/mΒ²', icon: '🌱', group: 'Light', precision: 3, color: '#86efac' }, + light_visibility_km: { label: 'Visibility', unit: ' km', icon: 'πŸ‘οΈ', group: 'Light', precision: 1, color: '#7dd3fc' }, + // Wind + wind_speed_kmh: { label: 'Wind Speed', unit: ' km/h', icon: 'πŸ’¨', group: 'Wind', precision: 1, color: '#93c5fd' }, + wind_gusts_kmh: { label: 'Wind Gusts', unit: ' km/h', icon: '🌬️', group: 'Wind', precision: 1, color: '#60a5fa' }, + wind_direction_deg: { label: 'Wind Direction', unit: 'Β°', icon: '🧭', group: 'Wind', precision: 0, color: '#818cf8' }, + // Seismic + seismic_magnitude: { label: 'Seismic Magnitude', unit: ' g', icon: '🌍', group: 'Seismic', precision: 4, color: '#f87171' }, + seismic_ax: { label: 'Accel X', unit: ' g', icon: 'πŸ“', group: 'Seismic', precision: 3, color: '#fca5a5' }, + seismic_ay: { label: 'Accel Y', unit: ' g', icon: 'πŸ“', group: 'Seismic', precision: 3, color: '#fca5a5' }, + seismic_az: { label: 'Accel Z', unit: ' g', icon: 'πŸ“', group: 'Seismic', precision: 3, color: '#fca5a5' }, + // Compass + compass_heading: { label: 'Compass Heading', unit: 'Β°', icon: '🧭', group: 'Compass', precision: 1, color: '#c084fc' }, + // Ground + ground_distance_cm: { label: 'Ground Distance', unit: ' cm', icon: 'πŸ“', group: 'Ground', precision: 0, color: '#a3e635' }, + ground_accumulation_depth_cm: { label: 'Accumulation Depth', unit: ' cm', icon: '❄️', group: 'Ground', precision: 1, color: '#bfdbfe' }, + ground_lidar_strength: { label: 'LIDAR Strength', unit: '', icon: 'πŸ“‘', group: 'Ground', precision: 0, color: '#6ee7b7' }, + // Lightning + lightning_distance_km: { label: 'Lightning Distance', unit: ' km', icon: '⚑', group: 'Lightning', precision: 0, color: '#fde047' }, + lightning_strikes_per_hour: { label: 'Strike Rate', unit: '/hr', icon: '⚑', group: 'Lightning', precision: 1, color: '#facc15' }, + // Moon + moon_illumination_pct: { label: 'Moon Illumination', unit: '%', icon: 'πŸŒ™', group: 'Celestial', precision: 0, color: '#e2e8f0' }, + // Sun + sun_elevation: { label: 'Solar Elevation', unit: 'Β°', icon: 'β˜€οΈ', group: 'Celestial', precision: 1, color: '#fef08a' }, + // Space + space_kp_index: { label: 'Kp Index', unit: '', icon: '🌌', group: 'Space', precision: 1, color: '#818cf8' }, + space_solar_wind_speed_kms: { label: 'Solar Wind', unit: ' km/s', icon: 'β˜„οΈ', group: 'Space', precision: 0, color: '#c4b5fd' }, + space_imf_bz: { label: 'IMF Bz', unit: ' nT', icon: '🧲', group: 'Space', precision: 1, color: '#a5b4fc' }, + // Marine + wave_height: { label: 'Wave Height', unit: ' m', icon: '🌊', group: 'Marine', precision: 2, color: '#38bdf8' }, + swell_wave_height: { label: 'Swell Height', unit: ' m', icon: '🌊', group: 'Marine', precision: 2, color: '#7dd3fc' }, + wave_period: { label: 'Wave Period', unit: ' s', icon: '⏱️', group: 'Marine', precision: 1, color: '#bae6fd' }, + // AQ + pm2_5: { label: 'PM2.5', unit: ' ΞΌg/mΒ³', icon: '🏭', group: 'Air Quality', precision: 1, color: '#fca5a5' }, + pm10: { label: 'PM10', unit: ' ΞΌg/mΒ³', icon: '🏭', group: 'Air Quality', precision: 1, color: '#fdba74' }, + ozone: { label: 'Ozone', unit: ' ΞΌg/mΒ³', icon: '🌐', group: 'Air Quality', precision: 1, color: '#6ee7b7' }, + // Forecast + forecast_precipitation_mm: { label: 'Precipitation', unit: ' mm', icon: '🌧️', group: 'Forecast', precision: 1, color: '#38bdf8' }, + forecast_precipitation_probability: { label: 'Rain Chance', unit: '%', icon: 'πŸŒ‚', group: 'Forecast', precision: 0, color: '#60a5fa' }, +} + +export function formatValue(key: string, value: number | string | null): string { + if (value === null || value === undefined) return 'β€”' + const meta = METRICS[key] + if (!meta) return String(value) + if (typeof value === 'number') return `${value.toFixed(meta.precision)}${meta.unit}` + return `${value}${meta.unit}` +} + +export const GROUPS = [...new Set(Object.values(METRICS).map(m => m.group))] diff --git a/client/src/services/weather.ts b/client/src/services/weather.ts new file mode 100644 index 0000000..942f8cc --- /dev/null +++ b/client/src/services/weather.ts @@ -0,0 +1,28 @@ +import { ref, computed } from 'vue' +import { api, type DataRow } from './api' + +export const current = ref({}) +export const hourly = ref([]) +export const daily = ref([]) +export const loading = ref(false) +export const lastFetch = ref(null) + +export async function fetchAll() { + loading.value = true + const [c, h, d] = await Promise.allSettled([api.current(), api.hourly(), api.daily()]) + if (c.status === 'fulfilled') current.value = c.value + if (h.status === 'fulfilled') hourly.value = h.value + if (d.status === 'fulfilled') daily.value = d.value + lastFetch.value = new Date() + loading.value = false +} + +export async function fetchHistoricHourly(start: string, end: string): Promise { + return api.hourly(start, end) +} + +export async function fetchHistoricDaily(start: string, end: string): Promise { + return api.daily(start, end) +} + +export const isDaytime = computed(() => current.value.sun_is_day === 1) diff --git a/client/src/views/Dashboard.vue b/client/src/views/Dashboard.vue new file mode 100644 index 0000000..25efec9 --- /dev/null +++ b/client/src/views/Dashboard.vue @@ -0,0 +1,138 @@ + + + + + diff --git a/client/tsconfig.app.json b/client/tsconfig.app.json new file mode 100644 index 0000000..c0f2d86 --- /dev/null +++ b/client/tsconfig.app.json @@ -0,0 +1,18 @@ +{ + "extends": "@vue/tsconfig/tsconfig.dom.json", + "include": ["env.d.ts", "src/**/*", "src/**/*.vue"], + "exclude": ["src/**/__tests__/*"], + "compilerOptions": { + // Extra safety for array and object lookups, but may have false positives. + "noUncheckedIndexedAccess": true, + + // Path mapping for cleaner imports. + "paths": { + "@/*": ["./src/*"] + }, + + // `vue-tsc --build` produces a .tsbuildinfo file for incremental type-checking. + // Specified here to keep it out of the root directory. + "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo" + } +} diff --git a/client/tsconfig.json b/client/tsconfig.json new file mode 100644 index 0000000..66b5e57 --- /dev/null +++ b/client/tsconfig.json @@ -0,0 +1,11 @@ +{ + "files": [], + "references": [ + { + "path": "./tsconfig.node.json" + }, + { + "path": "./tsconfig.app.json" + } + ] +} diff --git a/client/tsconfig.node.json b/client/tsconfig.node.json new file mode 100644 index 0000000..c9b2bad --- /dev/null +++ b/client/tsconfig.node.json @@ -0,0 +1,27 @@ +// TSConfig for modules that run in Node.js environment via either transpilation or type-stripping. +{ + "extends": "@tsconfig/node24/tsconfig.json", + "include": [ + "vite.config.*", + "vitest.config.*", + "cypress.config.*", + "playwright.config.*", + "eslint.config.*" + ], + "compilerOptions": { + // Most tools use transpilation instead of Node.js's native type-stripping. + // Bundler mode provides a smoother developer experience. + "module": "preserve", + "moduleResolution": "bundler", + + // Include Node.js types and avoid accidentally including other `@types/*` packages. + "types": ["node"], + + // Disable emitting output during `vue-tsc --build`, which is used for type-checking only. + "noEmit": true, + + // `vue-tsc --build` produces a .tsbuildinfo file for incremental type-checking. + // Specified here to keep it out of the root directory. + "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo" + } +} diff --git a/client/vite.config.ts b/client/vite.config.ts new file mode 100644 index 0000000..5ca13e6 --- /dev/null +++ b/client/vite.config.ts @@ -0,0 +1,20 @@ +import { fileURLToPath, URL } from 'node:url' + +import { defineConfig } from 'vite' +import vue from '@vitejs/plugin-vue' +import vueDevTools from 'vite-plugin-vue-devtools' + +// https://vite.dev/config/ +export default defineConfig({ + plugins: [vue()], + serve: { port: 5173 }, + build: { + outDir: '../server/public', + emptyOutDir: true, + }, + resolve: { + alias: { + '@': fileURLToPath(new URL('./src', import.meta.url)), + }, + }, +}) diff --git a/server/celestial.mjs b/server/celestial.mjs new file mode 100644 index 0000000..05bf7c0 --- /dev/null +++ b/server/celestial.mjs @@ -0,0 +1,213 @@ +const RAD = Math.PI / 180 +const DEG = 180 / Math.PI + +function jdn(date) { + return (date instanceof Date ? date : new Date(date)) / 86400000 + 2440587.5 +} + +function jdnToDate(jd) { + return new Date((jd - 2440587.5) * 86400000) +} + +function sunPosition(lat, lon, date = new Date()) { + const d = jdn(date) - 2451545.0 + const L = (280.46 + 0.9856474 * d) % 360 + const g = (357.528 + 0.9856003 * d) % 360 + const lam = L + 1.915 * Math.sin(g * RAD) + 0.02 * Math.sin(2 * g * RAD) + const eps = 23.439 - 0.0000004 * d + const sinL = Math.sin(lam * RAD) + const ra = Math.atan2(Math.cos(eps * RAD) * sinL, Math.cos(lam * RAD)) * DEG + const dec = Math.asin(Math.sin(eps * RAD) * sinL) * DEG + const UT = date.getUTCHours() + date.getUTCMinutes() / 60 + date.getUTCSeconds() / 3600 + const GMST = (6.697375 + 0.0657098242 * d + UT) % 24 + const LMST = (GMST + lon / 15) % 24 + const ha = LMST * 15 - ra + const elev = Math.asin( + Math.sin(lat * RAD) * Math.sin(dec * RAD) + + Math.cos(lat * RAD) * Math.cos(dec * RAD) * Math.cos(ha * RAD) + ) * DEG + const az = Math.atan2( + -Math.sin(ha * RAD), + Math.tan(dec * RAD) * Math.cos(lat * RAD) - Math.sin(lat * RAD) * Math.cos(ha * RAD) + ) * DEG + return { + sun_elevation: Math.round(elev * 10) / 10, + sun_azimuth: Math.round(((az + 360) % 360) * 10) / 10, + } +} + +function sunriseSunset(lat, lon, date = new Date()) { + const d = Math.floor(jdn(date)) - 2451545 + const noon = 2451545 + 0.0009 + ((-lon) / 360) + Math.round(d - (-lon) / 360) + const M = (357.5291 + 0.98560028 * (noon - 2451545)) % 360 + const C = 1.9148 * Math.sin(M * RAD) + 0.02 * Math.sin(2 * M * RAD) + 0.0003 * Math.sin(3 * M * RAD) + const lam = (M + C + 180 + 102.9372) % 360 + const jnoon = noon + 0.0053 * Math.sin(M * RAD) - 0.0069 * Math.sin(2 * lam * RAD) + const dec = Math.asin(Math.sin(23.4397 * RAD) * Math.sin(lam * RAD)) * DEG + const cosH = (Math.sin(-0.8333 * RAD) - Math.sin(lat * RAD) * Math.sin(dec * RAD)) / (Math.cos(lat * RAD) * Math.cos(dec * RAD)) + + if (Math.abs(cosH) > 1) { + return { sun_sunrise: null, sun_sunset: null, sun_solar_noon: jdnToDate(jnoon).toISOString(), sun_polar: cosH < -1 ? 'day' : 'night' } + } + + const H = Math.acos(cosH) * DEG + const rise = jdnToDate(jnoon - H / 360) + const set = jdnToDate(jnoon + H / 360) + const noon_d = jdnToDate(jnoon) + + // Round to nearest second, drop milliseconds + const fmt = d => new Date(Math.round(d.getTime() / 1000) * 1000).toISOString() + + return { + sun_sunrise: fmt(rise), + sun_sunset: fmt(set), + sun_solar_noon: fmt(noon_d), + sun_day_length_hours: Math.round((set - rise) / 36000) / 100, + sun_golden_hour_morning_start: fmt(new Date(rise - 30 * 60000)), + sun_golden_hour_morning_end: fmt(new Date(rise + 30 * 60000)), + sun_golden_hour_evening_start: fmt(new Date(set - 30 * 60000)), + sun_golden_hour_evening_end: fmt(new Date(set + 30 * 60000)), + } +} + +// Smooth sunspot number approximation from solar flux F10.7 +// SSN β‰ˆ 1.61 * F10.7 - 63.7 (linear regression, valid for F10.7 > 70) +export function ssnFromFlux(f107) { + if (!f107) return null + return Math.max(0, Math.round(1.61 * f107 - 63.7)) +} + +export function sunActivityLabel(f107) { + if (!f107) return null + if (f107 < 80) return 'Very Low' + if (f107 < 100) return 'Low' + if (f107 < 150) return 'Moderate' + if (f107 < 200) return 'High' + return 'Very High' +} + +function moonPhase(date = new Date()) { + const jd = jdn(date) + const cycle = 29.53058867 + const known = 2451550.1 + const phase = ((jd - known) % cycle + cycle) % cycle + const illum = Math.round((1 - Math.cos(phase / cycle * 2 * Math.PI)) / 2 * 100) + let name + if (phase < 1.85) name = 'New Moon' + else if (phase < 7.38) name = 'Waxing Crescent' + else if (phase < 9.22) name = 'First Quarter' + else if (phase < 14.76) name = 'Waxing Gibbous' + else if (phase < 16.61) name = 'Full Moon' + else if (phase < 22.15) name = 'Waning Gibbous' + else if (phase < 23.99) name = 'Last Quarter' + else name = 'Waning Crescent' + return { moon_phase: name, moon_illumination_pct: illum } +} + +function nextMoonEvents(date = new Date()) { + const cycle = 29.53058867 + const jd = jdn(date) + const known = 2451550.1 + const phase = ((jd - known) % cycle + cycle) % cycle + const toNew = (cycle - phase) % cycle + const toFull = phase < 14.76 ? 14.76 - phase : cycle - phase + 14.76 + return { + moon_next_new: jdnToDate(jd + toNew).toISOString(), + moon_next_full: jdnToDate(jd + toFull).toISOString(), + } +} + +function moonriseMoonset(lat, lon, date = new Date()) { + const base = new Date(date) + base.setUTCHours(0, 0, 0, 0) + let prev = null + let moonrise = null + let moonset = null + + // Scan 48h in 10min steps β€” covers edge cases where moon rises/sets next UTC day + for (let m = 0; m <= 2880; m += 10) { + const t = new Date(base.getTime() + m * 60000) + const d = jdn(t) - 2451545 + const L = (218.316 + 13.176396 * d) % 360 + const M = (134.963 + 13.064993 * d) % 360 + const F = (93.272 + 13.229350 * d) % 360 + const lon_ = L + 6.289 * Math.sin(M * RAD) + const b = 5.128 * Math.sin(F * RAD) + const dec = Math.asin( + Math.sin(b * RAD) * Math.cos(23.4397 * RAD) + + Math.cos(b * RAD) * Math.sin(23.4397 * RAD) * Math.sin(lon_ * RAD) + ) * DEG + const GMST = (6.697375 + 0.0657098242 * d + (t.getUTCHours() + t.getUTCMinutes() / 60)) % 24 + const LMST = (GMST + lon / 15) % 24 + const ra = Math.atan2( + Math.sin(lon_ * RAD) * Math.cos(23.4397 * RAD) - Math.tan(b * RAD) * Math.sin(23.4397 * RAD), + Math.cos(lon_ * RAD) + ) * DEG + const ha = LMST * 15 - ra + const elev = Math.asin( + Math.sin(lat * RAD) * Math.sin(dec * RAD) + + Math.cos(lat * RAD) * Math.cos(dec * RAD) * Math.cos(ha * RAD) + ) * DEG + + if (prev !== null) { + if (prev < 0 && elev >= 0 && !moonrise) moonrise = new Date(t.getTime() - 5 * 60000).toISOString() + if (prev >= 0 && elev < 0 && !moonset) moonset = new Date(t.getTime() - 5 * 60000).toISOString() + } + prev = elev + if (moonrise && moonset) break + } + + return { moon_moonrise: moonrise, moon_moonset: moonset } +} + +function nextSolsticeEquinox(date = new Date()) { + const y = date.getFullYear() + const events = [ + { name: 'March Equinox', date: new Date(Date.UTC(y, 2, 20)) }, + { name: 'June Solstice', date: new Date(Date.UTC(y, 5, 21)) }, + { name: 'September Equinox', date: new Date(Date.UTC(y, 8, 22)) }, + { name: 'December Solstice', date: new Date(Date.UTC(y, 11, 21)) }, + { name: 'March Equinox', date: new Date(Date.UTC(y+1, 2, 20)) }, + ] + const next = events.find(e => e.date > date) + const prev = [...events].reverse().find(e => e.date <= date) + return { + season_next_event: next.name, + season_next_event_date: next.date.toISOString(), + season_last_event: prev?.name || null, + season_last_event_date: prev?.date.toISOString() || null, + } +} + +export function getCelestialCurrent(lat, lon, date = new Date()) { + return { + ...sunPosition(lat, lon, date), + ...sunriseSunset(lat, lon, date), + ...moonPhase(date), + ...nextMoonEvents(date), + ...moonriseMoonset(lat, lon, date), + ...nextSolsticeEquinox(date), + } +} + +export function getCelestialHourly(lat, lon, hours) { + return hours.map(({ time }) => { + const d = new Date(time) + const pos = sunPosition(lat, lon, d) + const phase = moonPhase(d) + return { time, ...pos, moon_illumination_pct: phase.moon_illumination_pct, moon_phase: phase.moon_phase } + }) +} + +export function getCelestialDaily(lat, lon, days) { + return days.map(({ time }) => { + const d = new Date(time) + return { + time, + ...sunriseSunset(lat, lon, d), + ...moonPhase(d), + ...nextMoonEvents(d), + ...moonriseMoonset(lat, lon, d), + } + }) +} diff --git a/server/config.mjs b/server/config.mjs new file mode 100644 index 0000000..f1fcca8 --- /dev/null +++ b/server/config.mjs @@ -0,0 +1,20 @@ +import { config } from 'dotenv' +import { resolve, dirname } from 'path' +import { fileURLToPath } from 'url' + +const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..') + +export function cfg() { + config({ path: resolve(ROOT, '.env'), override: true }) + config({ path: resolve(ROOT, '.env.local'), override: true }) + return { + PORT: process.env.PORT || 3000, + INFLUX_URL: process.env.INFLUX_URL || 'http://localhost:8086', + INFLUX_TOKEN: process.env.INFLUX_TOKEN || '', + INFLUX_ORG: process.env.INFLUX_ORG || 'weather', + INFLUX_BUCKET: process.env.INFLUX_BUCKET || 'station', + DEFAULT_LAT: parseFloat(process.env.DEFAULT_LAT || '0'), + DEFAULT_LON: parseFloat(process.env.DEFAULT_LON || '0'), + DEFAULT_ALT: parseFloat(process.env.DEFAULT_ALT || '0'), + } +} diff --git a/server/icons.mjs b/server/icons.mjs new file mode 100644 index 0000000..0554499 --- /dev/null +++ b/server/icons.mjs @@ -0,0 +1,52 @@ +import { existsSync, mkdirSync, writeFileSync } from 'fs' +import { resolve, dirname } from 'path' +import { fileURLToPath } from 'url' + +const DIR = resolve(dirname(fileURLToPath(import.meta.url)), 'public', 'icons') + +export const WMO = { + 0: { label: 'Clear Sky', icon: '01d' }, + 1: { label: 'Mainly Clear', icon: '01d' }, + 2: { label: 'Partly Cloudy', icon: '02d' }, + 3: { label: 'Overcast', icon: '04d' }, + 45: { label: 'Fog', icon: '50d' }, + 48: { label: 'Icy Fog', icon: '50d' }, + 51: { label: 'Light Drizzle', icon: '09d' }, + 53: { label: 'Drizzle', icon: '09d' }, + 55: { label: 'Heavy Drizzle', icon: '09d' }, + 61: { label: 'Light Rain', icon: '10d' }, + 63: { label: 'Rain', icon: '10d' }, + 65: { label: 'Heavy Rain', icon: '10d' }, + 71: { label: 'Light Snow', icon: '13d' }, + 73: { label: 'Snow', icon: '13d' }, + 75: { label: 'Heavy Snow', icon: '13d' }, + 77: { label: 'Snow Grains', icon: '13d' }, + 80: { label: 'Light Showers', icon: '09d' }, + 81: { label: 'Showers', icon: '09d' }, + 82: { label: 'Heavy Showers', icon: '09d' }, + 85: { label: 'Snow Showers', icon: '13d' }, + 86: { label: 'Heavy Snow Showers', icon: '13d' }, + 95: { label: 'Thunderstorm', icon: '11d' }, + 96: { label: 'Thunderstorm w/ Hail', icon: '11d' }, + 99: { label: 'Thunderstorm w/ Hail', icon: '11d' }, +} + +export function weatherFromCode(code, isDay = true) { + const w = WMO[code] ?? { label: 'Unknown', icon: '01d' } + const icon = isDay ? w.icon : w.icon.replace('d', 'n') + return { weather_code: code, weather_label: w.label, weather_icon: `/icons/${icon}.png` } +} + +export async function downloadIcons() { + if (!existsSync(DIR)) mkdirSync(DIR, { recursive: true }) + const icons = new Set(Object.values(WMO).map(w => [w.icon, w.icon.replace('d','n')]).flat()) + await Promise.all([...icons].map(async icon => { + const path = resolve(DIR, `${icon}.png`) + if (existsSync(path)) return + const res = await fetch(`https://openweathermap.org/img/wn/${icon}@2x.png`) + const buf = Buffer.from(await res.arrayBuffer()) + writeFileSync(path, buf) + console.log(` πŸ“₯ Downloaded icon: ${icon}.png`) + })) + console.log('βœ… Weather icons ready') +} diff --git a/server/influx.mjs b/server/influx.mjs new file mode 100644 index 0000000..3b665d9 --- /dev/null +++ b/server/influx.mjs @@ -0,0 +1,148 @@ +import { InfluxDB } from '@influxdata/influxdb-client' +import { cfg } from './config.mjs' + +let client, currentUrl, currentToken + +function getClient() { + const c = cfg() + if (c.INFLUX_URL !== currentUrl || c.INFLUX_TOKEN !== currentToken) { + client = new InfluxDB({ url: c.INFLUX_URL, token: c.INFLUX_TOKEN }) + currentUrl = c.INFLUX_URL + currentToken = c.INFLUX_TOKEN + } + return { client, c } +} + +async function query(flux) { + const { client, c } = getClient() + const api = client.getQueryApi(c.INFLUX_ORG) + const rows = [] + return new Promise((resolve, reject) => { + api.queryRows(flux, { + next(row, meta) { rows.push(meta.toObject(row)) }, + error(err) { reject(err) }, + complete() { resolve(rows) }, + }) + }) +} + +function truncateToHour(iso) { + const d = new Date(iso) + d.setMinutes(0, 0, 0) + const pad = n => String(n).padStart(2, '0') + return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}T${pad(d.getHours())}:00` +} + +function truncateToDay(iso) { + return new Date(iso).toISOString().slice(0, 10) +} + +function extractRow(row) { + const out = {} + for (const [k, v] of Object.entries(row)) { + if (!k.startsWith('_') && k !== 'result' && k !== 'table') out[k] = v + } + return out +} + +export async function queryCurrent() { + const { c } = getClient() + const flux = ` + from(bucket: "${c.INFLUX_BUCKET}") + |> range(start: -1h) + |> filter(fn: (r) => r._measurement =~ /.*/) + |> last() + |> pivot(rowKey: ["_time"], columnKey: ["_field"], valueColumn: "_value") + ` + const rows = await query(flux) + const result = {} + for (const row of rows) { + Object.assign(result, extractRow(row)) + } + return result +} + +export async function queryHourly(start, end) { + const { c } = getClient() + const flux = ` + from(bucket: "${c.INFLUX_BUCKET}") + |> range(start: ${start}, stop: ${end}) + |> filter(fn: (r) => r._measurement =~ /.*/) + |> aggregateWindow(every: 1h, fn: mean, createEmpty: false) + |> pivot(rowKey: ["_time"], columnKey: ["_field"], valueColumn: "_value") + ` + const rows = await query(flux) + return rows.map(row => ({ + time: truncateToHour(row._time), + ...extractRow(row), + })) +} + +export async function queryDaily(start, end) { + const { c } = getClient() + const measurements = ['environment', 'light', 'seismic', 'compass', 'ground', 'accumulation', 'lightning', 'gps'] + const results = {} + + for (const m of measurements) { + const [means, mins, maxs] = await Promise.all([ + query(` + from(bucket: "${c.INFLUX_BUCKET}") + |> range(start: ${start}, stop: ${end}) + |> filter(fn: (r) => r._measurement == "${m}") + |> aggregateWindow(every: 1d, fn: mean, createEmpty: false) + |> pivot(rowKey: ["_time"], columnKey: ["_field"], valueColumn: "_value") + `), + query(` + from(bucket: "${c.INFLUX_BUCKET}") + |> range(start: ${start}, stop: ${end}) + |> filter(fn: (r) => r._measurement == "${m}") + |> aggregateWindow(every: 1d, fn: min, createEmpty: false) + |> pivot(rowKey: ["_time"], columnKey: ["_field"], valueColumn: "_value") + `), + query(` + from(bucket: "${c.INFLUX_BUCKET}") + |> range(start: ${start}, stop: ${end}) + |> filter(fn: (r) => r._measurement == "${m}") + |> aggregateWindow(every: 1d, fn: max, createEmpty: false) + |> pivot(rowKey: ["_time"], columnKey: ["_field"], valueColumn: "_value") + `), + ]) + + // Mean values are the base β€” flat field names, no suffix + for (const row of means) { + const time = truncateToDay(row._time) + if (!results[time]) results[time] = { time } + Object.assign(results[time], extractRow(row)) + } + + // Only promote temp min/max to named fields, ignore the rest + for (const row of mins) { + const time = truncateToDay(row._time) + if (!results[time]) results[time] = { time } + if (row.env_temp_c != null) results[time].env_temp_min_c = row.env_temp_c + } + for (const row of maxs) { + const time = truncateToDay(row._time) + if (!results[time]) results[time] = { time } + if (row.env_temp_c != null) results[time].env_temp_max_c = row.env_temp_c + } + } + + return Object.values(results).sort((a, b) => a.time.localeCompare(b.time)) +} + +export async function getCoords() { + const { c } = getClient() + const flux = ` + from(bucket: "${c.INFLUX_BUCKET}") + |> range(start: -24h) + |> filter(fn: (r) => r._measurement == "gps") + |> last() + |> pivot(rowKey: ["_time"], columnKey: ["_field"], valueColumn: "_value") + ` + const rows = await query(flux) + if (rows.length && rows[0].gps_lat && rows[0].gps_lon) { + return { lat: rows[0].gps_lat, lon: rows[0].gps_lon, alt: rows[0].gps_alt_m || c.DEFAULT_ALT } + } + return { lat: c.DEFAULT_LAT, lon: c.DEFAULT_LON, alt: c.DEFAULT_ALT } +} diff --git a/server/openmeteo.mjs b/server/openmeteo.mjs new file mode 100644 index 0000000..b1cd5f1 --- /dev/null +++ b/server/openmeteo.mjs @@ -0,0 +1,273 @@ +import { createWriteStream, existsSync, mkdirSync } from 'fs' +import { resolve, dirname } from 'path' +import { fileURLToPath } from 'url' +import { pipeline } from 'stream/promises' + +const DIR = dirname(fileURLToPath(import.meta.url)) +const ICON_DIR = resolve(DIR, 'public', 'icons') +const CACHE = {} +const CACHE_MS = 15 * 60 * 1000 + +if (!existsSync(ICON_DIR)) mkdirSync(ICON_DIR, { recursive: true }) + +// WMO weather code map +const WMO = { + 0: { label: 'Clear Sky' }, + 1: { label: 'Mainly Clear' }, + 2: { label: 'Partly Cloudy' }, + 3: { label: 'Overcast' }, + 45: { label: 'Fog' }, + 48: { label: 'Icy Fog' }, + 51: { label: 'Light Drizzle' }, + 53: { label: 'Drizzle' }, + 55: { label: 'Heavy Drizzle' }, + 61: { label: 'Light Rain' }, + 63: { label: 'Rain' }, + 65: { label: 'Heavy Rain' }, + 71: { label: 'Light Snow' }, + 73: { label: 'Snow' }, + 75: { label: 'Heavy Snow' }, + 77: { label: 'Snow Grains' }, + 80: { label: 'Light Showers' }, + 81: { label: 'Showers' }, + 82: { label: 'Heavy Showers' }, + 85: { label: 'Snow Showers' }, + 86: { label: 'Heavy Snow Showers' }, + 95: { label: 'Thunderstorm' }, + 96: { label: 'Thunderstorm w/ Hail' }, + 99: { label: 'Thunderstorm w/ Heavy Hail' }, +} + +// OWM icon mapping by WMO code + is_day +const OWM_ICONS = { + 0: { day: '01d', night: '01n' }, + 1: { day: '01d', night: '01n' }, + 2: { day: '02d', night: '02n' }, + 3: { day: '04d', night: '04n' }, + 45: { day: '50d', night: '50n' }, + 48: { day: '50d', night: '50n' }, + 51: { day: '09d', night: '09n' }, + 53: { day: '09d', night: '09n' }, + 55: { day: '09d', night: '09n' }, + 61: { day: '10d', night: '10n' }, + 63: { day: '10d', night: '10n' }, + 65: { day: '10d', night: '10n' }, + 71: { day: '13d', night: '13n' }, + 73: { day: '13d', night: '13n' }, + 75: { day: '13d', night: '13n' }, + 77: { day: '13d', night: '13n' }, + 80: { day: '09d', night: '09n' }, + 81: { day: '09d', night: '09n' }, + 82: { day: '09d', night: '09n' }, + 85: { day: '13d', night: '13n' }, + 86: { day: '13d', night: '13n' }, + 95: { day: '11d', night: '11n' }, + 96: { day: '11d', night: '11n' }, + 99: { day: '11d', night: '11n' }, +} + +async function ensureIcon(code, isDay) { + const variant = isDay ? 'day' : 'night' + const owmCode = OWM_ICONS[code]?.[variant] || '01d' + const filename = `${owmCode}.png` + const filepath = resolve(ICON_DIR, filename) + if (!existsSync(filepath)) { + const url = `https://openweathermap.org/img/wn/${owmCode}@2x.png` + const res = await fetch(url) + await pipeline(res.body, createWriteStream(filepath)) + } + return `/icons/${filename}` +} + +export async function resolveWeather(code, isDay = 1) { + const label = WMO[code]?.label || 'Unknown' + const icon = await ensureIcon(code, isDay).catch(() => null) + return { forecast_weather_label: label, forecast_weather_icon: icon, forecast_weathercode: code } +} + +async function cachedFetch(key, url) { + const now = Date.now() + if (CACHE[key] && now - CACHE[key].ts < CACHE_MS) return CACHE[key].data + const res = await fetch(url) + const data = await res.json() + CACHE[key] = { ts: now, data } + return data +} + +const HOURLY_WEATHER = [ + 'temperature_2m', 'relative_humidity_2m', 'precipitation', 'precipitation_probability', + 'weathercode', 'windspeed_10m', 'winddirection_10m', 'windgusts_10m', + 'pressure_msl', 'cloudcover', 'visibility', 'cape', 'uv_index', 'is_day', + 'et0_fao_evapotranspiration', 'dewpoint_2m', 'apparent_temperature', + 'snowfall', 'snow_depth', 'freezinglevel_height', +].join(',') + +const DAILY_WEATHER = [ + 'temperature_2m_max', 'temperature_2m_min', 'precipitation_sum', + 'precipitation_probability_max', 'windspeed_10m_max', 'windgusts_10m_max', + 'winddirection_10m_dominant', 'weathercode', 'sunrise', 'sunset', + 'uv_index_max', 'snowfall_sum', 'precipitation_hours', 'shortwave_radiation_sum', +].join(',') + +const HOURLY_AQ = [ + 'pm10', 'pm2_5', 'carbon_monoxide', 'nitrogen_dioxide', 'sulphur_dioxide', + 'ozone', 'aerosol_optical_depth', 'dust', 'uv_index', + 'alder_pollen', 'birch_pollen', 'grass_pollen', + 'mugwort_pollen', 'olive_pollen', 'ragweed_pollen', +].join(',') + +const HOURLY_MARINE = [ + 'wave_height', 'wave_direction', 'wave_period', + 'wind_wave_height', 'swell_wave_height', 'swell_wave_direction', 'swell_wave_period', +].join(',') + +function zipHourly(data, prefix = '') { + if (!data?.hourly) return [] + return data.hourly.time.map((time, i) => { + const row = { time } + for (const [k, v] of Object.entries(data.hourly)) { + if (k !== 'time') row[prefix + k] = v[i] + } + return row + }) +} + +function zipDaily(data, prefix = '') { + if (!data?.daily) return [] + return data.daily.time.map((time, i) => { + const row = { time } + for (const [k, v] of Object.entries(data.daily)) { + if (k !== 'time') row[prefix + k] = v[i] + } + return row + }) +} + +// Remap Open-Meteo field names to our prefixed convention +function remapWeatherFields(row) { + const map = { + temperature_2m: 'env_temp_c', + apparent_temperature: 'env_heat_index_c', + dewpoint_2m: 'env_dew_point_c', + relative_humidity_2m: 'env_humidity', + pressure_msl: 'env_pressure_slp', + cloudcover: 'light_cloud_pct', + uv_index: 'light_uvi', + visibility: 'light_visibility_km', + windspeed_10m: 'wind_speed_kmh', + winddirection_10m: 'wind_direction_deg', + windgusts_10m: 'wind_gusts_kmh', + weathercode: 'forecast_weathercode', + precipitation: 'forecast_precipitation_mm', + precipitation_probability: 'forecast_precipitation_probability', + snowfall: 'forecast_snowfall_mm', + snow_depth: 'forecast_snow_depth_m', + cape: 'forecast_cape', + is_day: 'sun_is_day', + freezinglevel_height: 'forecast_freezing_level_m', + et0_fao_evapotranspiration: 'forecast_evapotranspiration_mm', + // daily + temperature_2m_max: 'env_temp_max_c', + temperature_2m_min: 'env_temp_min_c', + precipitation_sum: 'forecast_precipitation_mm', + precipitation_probability_max: 'forecast_precipitation_probability', + windspeed_10m_max: 'wind_speed_max_kmh', + windgusts_10m_max: 'wind_gusts_max_kmh', + winddirection_10m_dominant: 'wind_direction_deg', + uv_index_max: 'light_uvi_max', + snowfall_sum: 'forecast_snowfall_mm', + shortwave_radiation_sum: 'light_solar_wm2_sum', + sunrise: 'sun_sunrise', + sunset: 'sun_sunset', + } + const out = {} + for (const [k, v] of Object.entries(row)) { + out[map[k] || k] = v + } + return out +} + +export async function getOpenMeteo(lat, lon, start, end) { + const base = start && end + ? `&start_date=${start.slice(0,10)}&end_date=${end.slice(0,10)}&past_days=0` + : `&forecast_days=7` + + const [weather, aq, marine] = await Promise.allSettled([ + cachedFetch(`weather_${lat}_${lon}_${start}_${end}`, + `https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lon}&hourly=${HOURLY_WEATHER}&daily=${DAILY_WEATHER}¤t_weather=true&timezone=auto${base}`), + cachedFetch(`aq_${lat}_${lon}_${start}_${end}`, + `https://air-quality-api.open-meteo.com/v1/air-quality?latitude=${lat}&longitude=${lon}&hourly=${HOURLY_AQ}&timezone=auto${base}`), + cachedFetch(`marine_${lat}_${lon}_${start}_${end}`, + `https://marine-api.open-meteo.com/v1/marine?latitude=${lat}&longitude=${lon}&hourly=${HOURLY_MARINE}&daily=wave_height_max,wave_direction_dominant,wave_period_max&timezone=auto${base}`), + ]) + + const w = weather.status === 'fulfilled' ? weather.value : {} + const a = aq.status === 'fulfilled' ? aq.value : {} + const m = marine.status === 'fulfilled' ? marine.value : {} + + // Build hourly merged map + const hourlyMap = {} + for (const row of zipHourly(w)) { + const remapped = remapWeatherFields(row) + hourlyMap[row.time] = remapped + } + for (const row of zipHourly(a)) { + const { time, ...rest } = row + hourlyMap[time] = { ...hourlyMap[time], ...rest } + } + for (const row of zipHourly(m)) { + const { time, ...rest } = row + hourlyMap[time] = { ...hourlyMap[time], ...rest } + } + + // Build daily merged map + const dailyMap = {} + for (const row of zipDaily(w)) { + const remapped = remapWeatherFields(row) + dailyMap[row.time] = remapped + } + for (const row of zipDaily(m)) { + const { time, ...rest } = row + dailyMap[time] = { ...dailyMap[time], ...rest } + } + + // Resolve current weather + let current = null + if (w.current_weather) { + const cw = w.current_weather + const wInfo = await resolveWeather(cw.weathercode, cw.is_day).catch(() => ({})) + current = { + wind_speed_kmh: cw.windspeed, + wind_direction_deg: cw.winddirection, + sun_is_day: cw.is_day, + ...wInfo, + } + } + + // Resolve weather labels + icons for all hourly/daily rows + const hourlyArr = await Promise.all( + Object.values(hourlyMap) + .sort((a, b) => a.time.localeCompare(b.time)) + .map(async row => { + if (row.forecast_weathercode != null) { + const wInfo = await resolveWeather(row.forecast_weathercode, row.sun_is_day ?? 1).catch(() => ({})) + return { ...row, ...wInfo } + } + return row + }) + ) + + const dailyArr = await Promise.all( + Object.values(dailyMap) + .sort((a, b) => a.time.localeCompare(b.time)) + .map(async row => { + if (row.forecast_weathercode != null) { + const wInfo = await resolveWeather(row.forecast_weathercode, 1).catch(() => ({})) + return { ...row, ...wInfo } + } + return row + }) + ) + + return { current, hourly: hourlyArr, daily: dailyArr } +} diff --git a/server/package-lock.json b/server/package-lock.json new file mode 100644 index 0000000..48e0ac4 --- /dev/null +++ b/server/package-lock.json @@ -0,0 +1,990 @@ +{ + "name": "weather-station-api", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "weather-station-api", + "version": "1.0.0", + "dependencies": { + "@influxdata/influxdb-client": "^1.33.2", + "@scalar/express-api-reference": "^0.10.4", + "dotenv": "^16.3.1", + "express": "^4.18.2", + "yaml": "^2.9.0" + } + }, + "node_modules/@influxdata/influxdb-client": { + "version": "1.35.0", + "resolved": "https://registry.npmjs.org/@influxdata/influxdb-client/-/influxdb-client-1.35.0.tgz", + "integrity": "sha512-woWMi8PDpPQpvTsRaUw4Ig+nOGS/CWwAwS66Fa1Vr/EkW+NEwxI8YfPBsdBMn33jK2Y86/qMiiuX/ROHIkJLTw==", + "license": "MIT" + }, + "node_modules/@scalar/client-side-rendering": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/@scalar/client-side-rendering/-/client-side-rendering-0.2.4.tgz", + "integrity": "sha512-IQC39aQQXKsZXOqQw0LNiZ/gQ1WxHpF+WLTo/hurn0S/FmNHlBGUAhFyt1BeDSUYxics7ixgzQatKJDggafBTw==", + "license": "MIT", + "dependencies": { + "@scalar/schemas": "0.5.0", + "@scalar/types": "0.14.0", + "@scalar/validation": "0.6.0" + }, + "engines": { + "node": ">=22" + } + }, + "node_modules/@scalar/express-api-reference": { + "version": "0.10.4", + "resolved": "https://registry.npmjs.org/@scalar/express-api-reference/-/express-api-reference-0.10.4.tgz", + "integrity": "sha512-/FkuP+B9ppWiQbf0Bhygx8CwoLXiEGFgS7OK14FM/JH0SeAaGfQiacUgPEpxJYI2qnqFHkrys8YH2jl400wDfg==", + "license": "MIT", + "dependencies": { + "@scalar/client-side-rendering": "0.2.4" + }, + "engines": { + "node": ">=22" + } + }, + "node_modules/@scalar/helpers": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/@scalar/helpers/-/helpers-0.8.2.tgz", + "integrity": "sha512-qNbqUjSB3S4Gr4A0oANcm5G1Ip+EqBxICYKhe9YzmnaBpbmW6shxqpiivApTvvuDf+uIhR3uMwWyVQbYcGLsxA==", + "license": "MIT", + "engines": { + "node": ">=22" + } + }, + "node_modules/@scalar/schemas": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/@scalar/schemas/-/schemas-0.5.0.tgz", + "integrity": "sha512-aV0PWqFpQft9a6d4Z6HOTHKDaA+K4AquxSPfBDI1c5f6lMe5l3zViww/iBQA/Yw+V1+Y2iwSVzhuxaktC1UiMg==", + "license": "MIT", + "dependencies": { + "@scalar/helpers": "0.8.2", + "@scalar/validation": "0.6.0" + }, + "engines": { + "node": ">=22" + } + }, + "node_modules/@scalar/types": { + "version": "0.14.0", + "resolved": "https://registry.npmjs.org/@scalar/types/-/types-0.14.0.tgz", + "integrity": "sha512-aS1FvHbKhBC51mWqXmhkPe6lmhCd9+u//DQ1YTiCWOz4/fXAdWfwHvW9UZ7AzzcGwGiCo9diE81xV+UvSI1qIg==", + "license": "MIT", + "dependencies": { + "@scalar/helpers": "0.8.2", + "nanoid": "^5.1.6", + "type-fest": "^5.3.1", + "zod": "^4.3.5" + }, + "engines": { + "node": ">=22" + } + }, + "node_modules/@scalar/validation": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/@scalar/validation/-/validation-0.6.0.tgz", + "integrity": "sha512-tpmmG+/xRE2Kn9RpflU3AIyZv08v10+E1ZrJCx7z6+/91zHVxy0M73kC1LT4/8PbYNt85ywyC8+n+D99JdMcGA==", + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "license": "MIT", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==", + "license": "MIT" + }, + "node_modules/body-parser": { + "version": "1.20.5", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.5.tgz", + "integrity": "sha512-3grm+/2tUOvu2cjJkvsIxrv/wVpfXQW4PsQHYm7yk4vfpu7Ekl6nEsYBoJUL6qDwZUx8wUhQ8tR2qz+ad9c9OA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "~1.2.0", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "on-finished": "~2.4.1", + "qs": "~6.15.1", + "raw-body": "~2.5.3", + "type-is": "~1.6.18", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "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==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "license": "MIT", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz", + "integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==", + "license": "MIT" + }, + "node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "license": "MIT", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/dotenv": { + "version": "16.6.1", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz", + "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "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==", + "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/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "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==", + "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==", + "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==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "4.22.2", + "resolved": "https://registry.npmjs.org/express/-/express-4.22.2.tgz", + "integrity": "sha512-IuL+Elrou2ZvCFHs18/CIzy2Nzvo25nZ1/D2eIZlz7c+QUayAcYoiM2BthCjs+EBHVpjYjcuLDAiCWgeIX3X1Q==", + "license": "MIT", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "~1.20.5", + "content-disposition": "~0.5.4", + "content-type": "~1.0.4", + "cookie": "~0.7.1", + "cookie-signature": "~1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "~1.3.1", + "fresh": "~0.5.2", + "http-errors": "~2.0.0", + "merge-descriptors": "1.0.3", + "methods": "~1.1.2", + "on-finished": "~2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "~0.1.12", + "proxy-addr": "~2.0.7", + "qs": "~6.15.1", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "~0.19.0", + "serve-static": "~1.16.2", + "setprototypeof": "1.2.0", + "statuses": "~2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/finalhandler": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz", + "integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "on-finished": "~2.4.1", + "parseurl": "~1.3.3", + "statuses": "~2.0.2", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "license": "MIT", + "engines": { + "node": ">= 0.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==", + "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==", + "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==", + "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==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "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==", + "license": "MIT", + "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==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "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==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/merge-descriptors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", + "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=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==", + "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==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "5.1.15", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.1.15.tgz", + "integrity": "sha512-kBg3RpGtIe+RpTbyXwoI6pk5yD7KUiI3sygUqgeBMRst42KmhB4RZC7eiO9Wa1HIpaCCtpE2DJ6OI4Wi5ebwFw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.js" + }, + "engines": { + "node": "^18 || >=20" + } + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.13.tgz", + "integrity": "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA==", + "license": "MIT" + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/qs": { + "version": "6.15.2", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.2.tgz", + "integrity": "sha512-Rzq0KEyX/w/tEybncDgdkZrJgVUsUMk3xjh3t5bv3S1HTAtg+uOYt72+ZfwiQwKdysThkTBdL/rTi6HDmX9Ddw==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz", + "integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "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==", + "license": "MIT" + }, + "node_modules/send": { + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz", + "integrity": "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "~0.5.2", + "http-errors": "~2.0.1", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "~2.4.1", + "range-parser": "~1.2.1", + "statuses": "~2.0.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/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==", + "license": "MIT" + }, + "node_modules/serve-static": { + "version": "1.16.3", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.3.tgz", + "integrity": "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==", + "license": "MIT", + "dependencies": { + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "~0.19.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/side-channel": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/tagged-tag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/tagged-tag/-/tagged-tag-1.0.0.tgz", + "integrity": "sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng==", + "license": "MIT", + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/type-fest": { + "version": "5.7.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-5.7.0.tgz", + "integrity": "sha512-1URUxUqfHFM1c+zfSPsa3gnkO7Aq21qyH75SIduNYz4SzY964rn1X2vCMQaHSHhktiw+0kPa2iyb6PUpXqB6Vg==", + "license": "(MIT OR CC0-1.0)", + "dependencies": { + "tagged-tag": "^1.0.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", + "license": "MIT", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/yaml": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz", + "integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==", + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" + } + }, + "node_modules/zod": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz", + "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + } + } +} diff --git a/server/package.json b/server/package.json new file mode 100644 index 0000000..f4caada --- /dev/null +++ b/server/package.json @@ -0,0 +1,13 @@ +{ + "name": "weather-station", + "version": "1.0.0", + "type": "module", + "main": "index.mjs", + "dependencies": { + "@influxdata/influxdb-client": "^1.33.2", + "@scalar/express-api-reference": "^0.10.4", + "dotenv": "^16.3.1", + "express": "^4.18.2", + "yaml": "^2.9.0" + } +} diff --git a/server/public/icons/01d.png b/server/public/icons/01d.png new file mode 100644 index 0000000..ed42ad9 Binary files /dev/null and b/server/public/icons/01d.png differ diff --git a/server/public/icons/01n.png b/server/public/icons/01n.png new file mode 100644 index 0000000..85efa16 Binary files /dev/null and b/server/public/icons/01n.png differ diff --git a/server/public/icons/02d.png b/server/public/icons/02d.png new file mode 100644 index 0000000..fabd9c3 Binary files /dev/null and b/server/public/icons/02d.png differ diff --git a/server/public/icons/02n.png b/server/public/icons/02n.png new file mode 100644 index 0000000..288a40e Binary files /dev/null and b/server/public/icons/02n.png differ diff --git a/server/public/icons/04d.png b/server/public/icons/04d.png new file mode 100644 index 0000000..9c64ea8 Binary files /dev/null and b/server/public/icons/04d.png differ diff --git a/server/public/icons/04n.png b/server/public/icons/04n.png new file mode 100644 index 0000000..9c64ea8 Binary files /dev/null and b/server/public/icons/04n.png differ diff --git a/server/public/icons/09d.png b/server/public/icons/09d.png new file mode 100644 index 0000000..0f14cb6 Binary files /dev/null and b/server/public/icons/09d.png differ diff --git a/server/server.mjs b/server/server.mjs new file mode 100644 index 0000000..8a6b2bb --- /dev/null +++ b/server/server.mjs @@ -0,0 +1,142 @@ +import express from 'express' +import { resolve, dirname } from 'path' +import { fileURLToPath } from 'url' +import { cfg } from './config.mjs' +import { queryCurrent, queryHourly, queryDaily, getCoords } from './influx.mjs' +import { getCelestialCurrent, getCelestialHourly, getCelestialDaily } from './celestial.mjs' +import { getSpaceWeather } from './space.mjs' +import { getOpenMeteo } from './openmeteo.mjs' +import { apiReference } from '@scalar/express-api-reference' +import { spec } from './spec.mjs' +import { existsSync } from 'fs' + +const app = express() +const DIR = dirname(fileURLToPath(import.meta.url)) +const CLIENT_DIST = resolve(DIR, 'public') + +app.use(express.json()) +app.use('/icons', express.static(resolve(DIR, 'public', 'icons'))) +app.use((req, res, next) => { res.setHeader('Access-Control-Allow-Origin', '*'); next() }) +app.use(express.static(CLIENT_DIST)) + +function filterFields(obj, fields) { + if (!fields) return obj + const keys = new Set(fields.split(',').map(f => f.trim())) + return Object.fromEntries(Object.entries(obj).filter(([k]) => keys.has(k))) +} + +function filterArr(arr, fields) { + if (!fields) return arr + return arr.map(row => filterFields(row, fields)) +} + +function mergeRows(arrays) { + const map = {} + for (const arr of arrays) { + for (const row of arr) { + map[row.time] = { ...map[row.time], ...row } + } + } + return Object.values(map).sort((a, b) => a.time.localeCompare(b.time)) +} + +// ── GET /api/data ───────────────────────────────────────────────────────────── + +app.get('/api/data', async (req, res) => { + const { fields } = req.query + const coords = await getCoords() + + const [sensor, space, meteo] = await Promise.allSettled([ + queryCurrent(), + getSpaceWeather(), + getOpenMeteo(coords.lat, coords.lon), + ]) + + const celestial = getCelestialCurrent(coords.lat, coords.lon) + + const data = { + ...(sensor.status === 'fulfilled' ? sensor.value : {}), + ...celestial, + ...(space.status === 'fulfilled' ? space.value : {}), + ...(meteo.status === 'fulfilled' && meteo.value.current ? meteo.value.current : {}), + } + + res.json(filterFields(data, fields)) +}) + +// ── GET /api/hourly ─────────────────────────────────────────────────────────── +app.get('/api/hourly', async (req, res) => { + const { fields } = req.query + const start = req.query.start || new Date(new Date().setHours(0,0,0,0)).toISOString() + const end = req.query.end || new Date().toISOString() + const coords = await getCoords() + + const [sensor, meteo, space] = await Promise.allSettled([ + queryHourly(start, end), + getOpenMeteo(coords.lat, coords.lon, start, end), + getSpaceWeather(), + ]) + + const sensorRows = sensor.status === 'fulfilled' ? sensor.value : [] + const meteoHourly = meteo.status === 'fulfilled' ? meteo.value.hourly : [] + const spaceData = space.status === 'fulfilled' ? space.value : {} + const seedRows = sensorRows.length ? sensorRows : meteoHourly + const celestial = getCelestialHourly(coords.lat, coords.lon, seedRows) + + // Spread space weather into every hourly row + const result = mergeRows([sensorRows, meteoHourly, celestial]) + .map(row => ({ ...spaceData, ...row })) + + res.json(filterArr(result, fields)) +}) + +// ── GET /api/daily ------------------------------------------------------------ + +app.get('/api/daily', async (req, res) => { + const { fields } = req.query + const start = req.query.start || new Date(new Date().setHours(0,0,0,0)).toISOString() + const end = req.query.end || new Date().toISOString() + const coords = await getCoords() + + const [sensor, meteo, space] = await Promise.allSettled([ + queryDaily(start, end), + getOpenMeteo(coords.lat, coords.lon, start, end), + getSpaceWeather(), + ]) + + const sensorRows = sensor.status === 'fulfilled' ? sensor.value : [] + const meteoDaily = meteo.status === 'fulfilled' ? meteo.value.daily : [] + const spaceData = space.status === 'fulfilled' ? space.value : {} + const seedRows = sensorRows.length ? sensorRows : meteoDaily + const celestial = getCelestialDaily(coords.lat, coords.lon, seedRows) + + const result = mergeRows([sensorRows, meteoDaily, celestial]) + .map(row => ({ ...spaceData, ...row })) + + res.json(filterArr(result, fields)) +}) + +// ── DOCS ---------------------------------------------------------------------- + +app.get('/openapi.json', (req, res) => res.json(spec)) +app.get('/openapi.yaml', async (req, res) => { + const { stringify } = await import('yaml') + res.setHeader('Content-Type', 'text/yaml') + res.send(stringify(spec)) +}) + +// Scalar UI +app.use('/docs', apiReference({ spec: { url: '/openapi.json' }, theme: 'default' })) + + +// ── SPA Redirect -------------------------------------------------------------- + app.get('*', (req, res) => { + const index = resolve(CLIENT_DIST, 'index.html') + if (existsSync(index)) res.sendFile(index) + else res.status(404).send('Client not built yet β€” run npm run build in /client') +}) + +// ── Start ───────────────────────────────────────────────────────────────────── + +const c = cfg() +app.listen(c.PORT, () => console.log(`🌦 Weather API β€” http://localhost:${c.PORT}`)) diff --git a/server/space.mjs b/server/space.mjs new file mode 100644 index 0000000..a5e6a53 --- /dev/null +++ b/server/space.mjs @@ -0,0 +1,69 @@ +import { ssnFromFlux, sunActivityLabel } from './celestial.mjs' + +const CACHE = {} +const CACHE_MS = 10 * 60 * 1000 + +async function cachedFetch(key, url) { + const now = Date.now() + if (CACHE[key] && now - CACHE[key].ts < CACHE_MS) return CACHE[key].data + const res = await fetch(url) + const data = await res.json() + CACHE[key] = { ts: now, data } + return data +} + +async function getKpAp() { + const data = await cachedFetch('kp', 'https://services.swpc.noaa.gov/products/noaa-planetary-k-index.json') + // First row is always the header + const rows = Array.isArray(data) ? data.slice(1).filter(r => Array.isArray(r)) : [] + if (!rows.length) return {} + const latest = rows[rows.length - 1] + const kp = parseFloat(latest[1]) + const ap = parseFloat(latest[2]) + return { + space_kp_index: isNaN(kp) ? null : kp, + space_ap_index: isNaN(ap) ? null : ap, + space_geomagnetic_storm: kp >= 7 ? 'Severe' : kp >= 6 ? 'Strong' : kp >= 5 ? 'Moderate' : kp >= 4 ? 'Minor' : 'None', + } +} + +async function getSolarWind() { + const [plasma, mag] = await Promise.all([ + cachedFetch('plasma', 'https://services.swpc.noaa.gov/products/solar-wind/plasma.json'), + cachedFetch('mag', 'https://services.swpc.noaa.gov/products/solar-wind/mag.json'), + ]) + // Skip header row, find last valid row + const pRows = Array.isArray(plasma) ? plasma.slice(1).filter(r => Array.isArray(r) && r[2] !== null) : [] + const mRows = Array.isArray(mag) ? mag.slice(1).filter(r => Array.isArray(r) && r[3] !== null) : [] + const p = pRows[pRows.length - 1] || [] + const m = mRows[mRows.length - 1] || [] + return { + space_solar_wind_speed_kms: p[2] != null ? parseFloat(p[2]) : null, + space_solar_wind_density: p[1] != null ? parseFloat(p[1]) : null, + space_solar_wind_temp: p[3] != null ? parseFloat(p[3]) : null, + space_imf_bz: m[3] != null ? parseFloat(m[3]) : null, + space_imf_bt: m[6] != null ? parseFloat(m[6]) : null, + } +} + +async function getSolarFlux() { + const data = await cachedFetch('flux', 'https://services.swpc.noaa.gov/products/10cm-flux-30-day.json') + // Format: [["yyyy-mm-dd", flux, ...], ...] β€” no header row on this one + const rows = Array.isArray(data) ? data.filter(r => Array.isArray(r) && !isNaN(parseFloat(r[1]))) : [] + if (!rows.length) return {} + const f107 = parseFloat(rows[rows.length - 1][1]) + return { + space_solar_flux_f107: isNaN(f107) ? null : f107, + sun_ssn: ssnFromFlux(f107), + sun_activity_label: sunActivityLabel(f107), + } +} + +export async function getSpaceWeather() { + const [kpAp, wind, flux] = await Promise.allSettled([getKpAp(), getSolarWind(), getSolarFlux()]) + return { + ...(kpAp.status === 'fulfilled' ? kpAp.value : {}), + ...(wind.status === 'fulfilled' ? wind.value : {}), + ...(flux.status === 'fulfilled' ? flux.value : {}), + } +} diff --git a/server/spec.mjs b/server/spec.mjs new file mode 100644 index 0000000..dbc4de4 --- /dev/null +++ b/server/spec.mjs @@ -0,0 +1,215 @@ +export const spec = { + openapi: '3.0.0', + info: { + title: 'Weather Station', + version: '1.0.0', + description: 'Hyperlocal weather station β€” sensor data, forecasts, celestial & space weather', + }, + servers: [{ url: 'http://localhost:3000' }], + paths: { + '/api/data': { + get: { + summary: 'Current conditions', + description: 'Latest reading of all metrics β€” sensor, forecast, celestial & space weather merged into a single flat object', + parameters: [ + { name: 'fields', in: 'query', required: false, schema: { type: 'string' }, + description: 'Comma-separated list of fields to return. Omit for all.' } + ], + responses: { + 200: { + description: 'Current conditions', + content: { 'application/json': { schema: { $ref: '#/components/schemas/DataRow' } } } + } + } + } + }, + '/api/hourly': { + get: { + summary: 'Hourly data', + description: 'Hourly aggregated sensor data merged with Open-Meteo hourly forecast, celestial positions and space weather. Defaults to today.', + parameters: [ + { name: 'start', in: 'query', required: false, schema: { type: 'string', format: 'date-time' }, + description: 'ISO8601 start timestamp. Defaults to today 00:00.' }, + { name: 'end', in: 'query', required: false, schema: { type: 'string', format: 'date-time' }, + description: 'ISO8601 end timestamp. Defaults to now.' }, + { name: 'fields', in: 'query', required: false, schema: { type: 'string' }, + description: 'Comma-separated list of fields to return. Omit for all.' }, + ], + responses: { + 200: { + description: 'Array of hourly rows', + content: { 'application/json': { schema: { type: 'array', items: { $ref: '#/components/schemas/DataRow' } } } } + } + } + } + }, + '/api/daily': { + get: { + summary: 'Daily data', + description: 'Daily aggregated sensor data (mean/min/max) merged with Open-Meteo daily forecast and celestial events. Defaults to today.', + parameters: [ + { name: 'start', in: 'query', required: false, schema: { type: 'string', format: 'date-time' }, + description: 'ISO8601 start timestamp. Defaults to today 00:00.' }, + { name: 'end', in: 'query', required: false, schema: { type: 'string', format: 'date-time' }, + description: 'ISO8601 end timestamp. Defaults to now.' }, + { name: 'fields', in: 'query', required: false, schema: { type: 'string' }, + description: 'Comma-separated list of fields to return. Omit for all.' }, + ], + responses: { + 200: { + description: 'Array of daily rows', + content: { 'application/json': { schema: { type: 'array', items: { $ref: '#/components/schemas/DataRow' } } } } + } + } + } + }, + }, + components: { + schemas: { + DataRow: { + type: 'object', + properties: { + time: { type: 'string', description: 'ISO8601 timestamp or date' }, + // Environment + env_temp_c: { type: 'number', description: 'Temperature (Β°C)' }, + env_temp_f: { type: 'number', description: 'Temperature (Β°F)' }, + env_temp_min_c: { type: 'number', description: 'Daily min temperature (Β°C)' }, + env_temp_max_c: { type: 'number', description: 'Daily max temperature (Β°C)' }, + env_humidity: { type: 'number', description: 'Relative humidity (%)' }, + env_dew_point_c: { type: 'number', description: 'Dew point (Β°C)' }, + env_heat_index_c: { type: 'number', description: 'Feels like / heat index (Β°C)' }, + env_pressure_hpa: { type: 'number', description: 'Station pressure (hPa)' }, + env_pressure_slp: { type: 'number', description: 'Sea level pressure (hPa)' }, + env_pressure_rate: { type: 'number', description: 'Pressure change rate (hPa/hr)' }, + env_pressure_trend: { type: 'string', enum: ['Rising','Falling','Stable'], description: 'Pressure trend label' }, + env_abs_humidity: { type: 'number', description: 'Absolute humidity (g/mΒ³)' }, + env_vpd_kpa: { type: 'number', description: 'Vapour pressure deficit (kPa)' }, + env_gas_ohms: { type: 'number', description: 'BME680 gas resistance (Ξ©)' }, + env_aqi_score: { type: 'number', description: 'Air quality index score (0–100)' }, + env_aqi_label: { type: 'string', enum: ['Excellent','Good','Fair','Poor','Very Poor'] }, + env_frost_risk: { type: 'string', enum: ['None','Low','Moderate','High'] }, + // Light + light_lux: { type: 'number', description: 'Illuminance (lux)' }, + light_uvi: { type: 'number', description: 'UV index' }, + light_solar_wm2: { type: 'number', description: 'Solar irradiance (W/mΒ²)' }, + light_uv_dose_mj: { type: 'number', description: 'Accumulated UV dose today (mJ/cmΒ²)' }, + light_burn_time_min: { type: 'number', description: 'Time to sunburn skin type 2 (min)' }, + light_cloud_pct: { type: 'number', description: 'Estimated cloud cover (%)' }, + light_cloud_label: { type: 'string', enum: ['Clear','Partly Cloudy','Mostly Cloudy','Overcast'] }, + light_dli: { type: 'number', description: 'Daily light integral (mol/mΒ²/day)' }, + light_daylight_hours: { type: 'number', description: 'Hours above daylight threshold today' }, + light_visibility_km: { type: 'number', description: 'Estimated visibility (km)' }, + light_uvi_max: { type: 'number', description: 'Daily max UV index' }, + light_solar_wm2_sum: { type: 'number', description: 'Daily solar radiation sum (MJ/mΒ²)' }, + // Wind (Open-Meteo) + wind_speed_kmh: { type: 'number', description: 'Wind speed (km/h)' }, + wind_direction_deg: { type: 'number', description: 'Wind direction (Β°)' }, + wind_gusts_kmh: { type: 'number', description: 'Wind gusts (km/h)' }, + wind_speed_max_kmh: { type: 'number', description: 'Daily max wind speed (km/h)' }, + wind_gusts_max_kmh: { type: 'number', description: 'Daily max wind gusts (km/h)' }, + // Forecast + forecast_weathercode: { type: 'number', description: 'WMO weather code' }, + forecast_weather_label: { type: 'string', description: 'Human readable weather label' }, + forecast_weather_icon: { type: 'string', description: 'Local icon path e.g. /icons/01d.png' }, + forecast_precipitation_mm: { type: 'number', description: 'Precipitation (mm)' }, + forecast_precipitation_probability: { type: 'number', description: 'Precipitation probability (%)' }, + forecast_snowfall_mm: { type: 'number', description: 'Snowfall (mm)' }, + forecast_snow_depth_m: { type: 'number', description: 'Snow depth (m)' }, + forecast_cape: { type: 'number', description: 'Convective available potential energy (J/kg)' }, + forecast_freezing_level_m: { type: 'number', description: 'Freezing level altitude (m)' }, + forecast_evapotranspiration_mm:{ type: 'number', description: 'Evapotranspiration (mm)' }, + // Seismic + seismic_ax: { type: 'number', description: 'Peak acceleration X axis (g)' }, + seismic_ay: { type: 'number', description: 'Peak acceleration Y axis (g)' }, + seismic_az: { type: 'number', description: 'Peak acceleration Z axis (g, includes gravity)' }, + seismic_magnitude: { type: 'number', description: 'Peak seismic magnitude (g, gravity removed)' }, + // Compass + compass_heading: { type: 'number', description: 'Magnetic heading (Β°)' }, + compass_x: { type: 'number' }, + compass_y: { type: 'number' }, + compass_z: { type: 'number' }, + // Ground / Accumulation + ground_distance_cm: { type: 'number', description: 'LIDAR ground distance (cm)' }, + ground_lidar_strength: { type: 'number', description: 'LIDAR signal strength' }, + ground_calibrated_baseline_cm: { type: 'number', description: 'Calibrated baseline distance (cm)' }, + ground_accumulation_depth_cm: { type: 'number', description: 'Snow/flood depth (cm)' }, + ground_accumulation_type: { type: 'string', enum: ['snow','slush','ice','flood'], description: 'Accumulation type' }, + // Lightning + lightning_distance_km: { type: 'number', description: 'Lightning strike distance (km)' }, + lightning_energy: { type: 'number', description: 'Lightning energy' }, + lightning_strikes_per_hour: { type: 'number', description: 'Strike rate (strikes/hr)' }, + lightning_storm_trend: { type: 'string', enum: ['Approaching','Retreating','Stationary'] }, + lightning_false_positive: { type: 'number', description: '1 if disturber/false positive' }, + lightning_detector_sensitivity:{ type: 'number', description: 'AS3935 noise floor setting (0–7)' }, + // GPS + gps_lat: { type: 'number', description: 'Latitude (Β°)' }, + gps_lon: { type: 'number', description: 'Longitude (Β°)' }, + gps_alt_m: { type: 'number', description: 'Altitude (m)' }, + gps_satellites: { type: 'number', description: 'Satellites in view' }, + gps_speed_kmh: { type: 'number', description: 'Ground speed (km/h)' }, + gps_heading: { type: 'number', description: 'GPS heading (Β°)' }, + // Sun + sun_elevation: { type: 'number', description: 'Solar elevation angle (Β°)' }, + sun_azimuth: { type: 'number', description: 'Solar azimuth (Β°)' }, + sun_sunrise: { type: 'string', description: 'Sunrise time (ISO8601)' }, + sun_sunset: { type: 'string', description: 'Sunset time (ISO8601)' }, + sun_solar_noon: { type: 'string', description: 'Solar noon (ISO8601)' }, + sun_day_length_hours: { type: 'number', description: 'Day length (hours)' }, + sun_golden_hour_morning_start: { type: 'string' }, + sun_golden_hour_morning_end: { type: 'string' }, + sun_golden_hour_evening_start: { type: 'string' }, + sun_golden_hour_evening_end: { type: 'string' }, + sun_is_day: { type: 'number', description: '1 if daytime' }, + sun_ssn: { type: 'number', description: 'Estimated sunspot number' }, + sun_activity_label: { type: 'string', enum: ['Very Low','Low','Moderate','High','Very High'] }, + // Moon + moon_phase: { type: 'string', description: 'Moon phase name' }, + moon_illumination_pct: { type: 'number', description: 'Moon illumination (%)' }, + moon_moonrise: { type: 'string', description: 'Moonrise time (ISO8601)' }, + moon_moonset: { type: 'string', description: 'Moonset time (ISO8601)' }, + moon_next_full: { type: 'string', description: 'Next full moon (ISO8601)' }, + moon_next_new: { type: 'string', description: 'Next new moon (ISO8601)' }, + // Season + season_next_event: { type: 'string', description: 'Next solstice/equinox name' }, + season_next_event_date: { type: 'string' }, + season_last_event: { type: 'string' }, + season_last_event_date: { type: 'string' }, + // Space weather + space_kp_index: { type: 'number', description: 'Planetary K index (0–9)' }, + space_ap_index: { type: 'number', description: 'Ap geomagnetic index' }, + space_geomagnetic_storm: { type: 'string', enum: ['None','Minor','Moderate','Strong','Severe'] }, + space_solar_wind_speed_kms: { type: 'number', description: 'Solar wind speed (km/s)' }, + space_solar_wind_density: { type: 'number', description: 'Solar wind proton density (p/cmΒ³)' }, + space_solar_wind_temp: { type: 'number', description: 'Solar wind temperature (K)' }, + space_imf_bz: { type: 'number', description: 'IMF Bz component (nT)' }, + space_imf_bt: { type: 'number', description: 'IMF total field Bt (nT)' }, + space_solar_flux_f107: { type: 'number', description: 'Solar flux F10.7 index' }, + // Marine + wave_height: { type: 'number', description: 'Significant wave height (m)' }, + wave_direction: { type: 'number', description: 'Wave direction (Β°)' }, + wave_period: { type: 'number', description: 'Wave period (s)' }, + swell_wave_height: { type: 'number', description: 'Swell wave height (m)' }, + swell_wave_direction: { type: 'number', description: 'Swell direction (Β°)' }, + swell_wave_period: { type: 'number', description: 'Swell period (s)' }, + wind_wave_height: { type: 'number', description: 'Wind wave height (m)' }, + wave_height_max: { type: 'number', description: 'Daily max wave height (m)' }, + // AQ + pm10: { type: 'number', description: 'PM10 (ΞΌg/mΒ³)' }, + pm2_5: { type: 'number', description: 'PM2.5 (ΞΌg/mΒ³)' }, + carbon_monoxide: { type: 'number', description: 'CO (ΞΌg/mΒ³)' }, + nitrogen_dioxide: { type: 'number', description: 'NOβ‚‚ (ΞΌg/mΒ³)' }, + sulphur_dioxide: { type: 'number', description: 'SOβ‚‚ (ΞΌg/mΒ³)' }, + ozone: { type: 'number', description: 'O₃ (ΞΌg/mΒ³)' }, + aerosol_optical_depth: { type: 'number' }, + dust: { type: 'number', description: 'Dust (ΞΌg/mΒ³)' }, + alder_pollen: { type: 'number', description: 'Alder pollen (grains/mΒ³)' }, + birch_pollen: { type: 'number', description: 'Birch pollen (grains/mΒ³)' }, + grass_pollen: { type: 'number', description: 'Grass pollen (grains/mΒ³)' }, + mugwort_pollen: { type: 'number', description: 'Mugwort pollen (grains/mΒ³)' }, + olive_pollen: { type: 'number', description: 'Olive pollen (grains/mΒ³)' }, + ragweed_pollen: { type: 'number', description: 'Ragweed pollen (grains/mΒ³)' }, + } + } + } + } +} diff --git a/setup.sh b/setup.sh new file mode 100755 index 0000000..ff6f85e --- /dev/null +++ b/setup.sh @@ -0,0 +1,71 @@ +#!/bin/bash +set -e + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +USER_NAME="$(whoami)" + +echo "πŸ”§ Setting up Weather Station..." + +# ── InfluxDB ────────────────────────────────────────────────────────────────── + +if ! command -v influxd &> /dev/null; then + echo "πŸ“¦ Installing InfluxDB..." + curl https://repos.influxdata.com/influxdata-archive.key | gpg --dearmor | sudo tee /usr/share/keyrings/influxdata-archive-keyring.gpg > /dev/null + echo "deb [signed-by=/usr/share/keyrings/influxdata-archive-keyring.gpg] https://repos.influxdata.com/debian stable main" | sudo tee /etc/apt/sources.list.d/influxdata.list + sudo apt update && sudo apt install -y influxdb2 + sudo systemctl enable --now influxdb +else + echo "βœ… InfluxDB already installed, skipping..." +fi + +# ── Node.js ─────────────────────────────────────────────────────────────────── + +if ! command -v node &> /dev/null; then + echo "πŸ“¦ Installing Node.js..." + curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash - + sudo apt install -y nodejs +else + echo "βœ… Node.js already installed, skipping..." +fi + +# ── Python venv ─────────────────────────────────────────────────────────────── + +if [ ! -d "$SCRIPT_DIR/sensors/venv" ]; then + echo "🐍 Setting up Python environment..." + cd "$SCRIPT_DIR/sensors" + python3 -m venv venv + venv/bin/pip install --upgrade pip + venv/bin/pip install -r requirements.txt +else + echo "βœ… Python environment already set up, skipping..." +fi + +# ── Systemd service ─────────────────────────────────────────────────────────── + +if ! systemctl is-enabled --quiet weather-sensors 2>/dev/null; then + echo "βš™οΈ Installing systemd service..." + sudo tee /etc/systemd/system/weather-sensors.service > /dev/null <