diff --git a/.github/wiki/CODE_OF_CONDUCT.md b/.github/wiki/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..c880c1a --- /dev/null +++ b/.github/wiki/CODE_OF_CONDUCT.md @@ -0,0 +1,34 @@ +# Code of Conduct + +## Summary + +Be direct, be respectful, and focus on the work. + +## Standards + +Constructive behavior: + +- Technical criticism aimed at code and ideas, not people +- Clear and specific feedback with examples where possible +- Acknowledging when you are wrong or do not know something +- Staying on topic in issues and pull requests + +Unacceptable behavior: + +- Personal attacks, insults, or harassment +- Sustained off-topic disruption +- Publishing private information without consent + +## Scope + +This applies to all project spaces: GitHub issues, pull requests, discussions, and any other venue where project work happens. + +## Enforcement + +The project maintainer handles violations. Contact: aric.camarata@gmail.com. + +Reports are reviewed promptly. Responses range from a private note to a permanent ban, depending on severity and history. + +## Attribution + +This code of conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org), version 2.1. diff --git a/.github/wiki/SECURITY.md b/.github/wiki/SECURITY.md new file mode 100644 index 0000000..c1f7078 --- /dev/null +++ b/.github/wiki/SECURITY.md @@ -0,0 +1,31 @@ +# Security Policy + +## Supported Versions + +| Version | Supported | +| --- | --- | +| 2.x | Yes | +| 1.x | No | + +Only the latest major version receives security fixes. + +## Reporting a Vulnerability + +Do not open a public GitHub issue for security vulnerabilities. + +Email: aric.camarata@gmail.com + +Include: + +- A description of the vulnerability +- Steps to reproduce +- Potential impact +- Any suggested fix, if you have one + +You will receive an acknowledgment within 48 hours and a resolution timeline within 7 days. Once a fix is ready and deployed, the vulnerability will be disclosed publicly with credit to the reporter (unless you prefer to remain anonymous). + +## Scope + +This package is a WASM-based computation library. It performs no network requests, reads no files, and holds no credentials. The primary security concern would be a memory safety issue in the WASM binary or a supply-chain compromise of the npm package. + +The WASM binary is compiled from the [NREL SPA C source](https://midcdmz.nrel.gov/spa/) with Emscripten. The compiled output (`wasm/spa-module.js`) is checked into the repository so its contents can be audited directly. diff --git a/.github/wiki/_Footer.md b/.github/wiki/_Footer.md new file mode 100644 index 0000000..5c7e5c8 --- /dev/null +++ b/.github/wiki/_Footer.md @@ -0,0 +1 @@ +[npm](https://www.npmjs.com/package/solar-spa) · [GitHub](https://github.com/acamarata/solar-spa) · [Changelog](https://github.com/acamarata/solar-spa/blob/main/CHANGELOG.md) · MIT License diff --git a/.github/wiki/_Sidebar.md b/.github/wiki/_Sidebar.md new file mode 100644 index 0000000..2bf2d7a --- /dev/null +++ b/.github/wiki/_Sidebar.md @@ -0,0 +1,24 @@ +## solar-spa + +**[Home](Home)** + +**Reference** +- [API Reference](API-Reference) +- [Architecture](Architecture) +- [NREL SPA Algorithm](NREL-SPA-Algorithm) + +**Performance & Compatibility** +- [Performance](Performance) +- [Bundler Compatibility](Bundler-Compatibility) +- [WebAssembly in npm Packages](WebAssembly-in-npm-Packages) +- [Validation and Benchmarks](Validation-and-Benchmarks) + +**Contributing** +- [Contributing](Contributing) +- [Code of Conduct](CODE_OF_CONDUCT) +- [Security](SECURITY) + +**Links** +- [npm](https://www.npmjs.com/package/solar-spa) +- [GitHub](https://github.com/acamarata/solar-spa) +- [Changelog](https://github.com/acamarata/solar-spa/blob/main/CHANGELOG.md) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dee0a7b..3efce5d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,15 +16,14 @@ jobs: steps: - uses: actions/checkout@v4 - - uses: pnpm/action-setup@v4 - with: - version: 10 - - uses: actions/setup-node@v4 with: node-version: ${{ matrix.node-version }} cache: pnpm + - name: Enable corepack + run: corepack enable + - run: pnpm install --frozen-lockfile - name: Build TypeScript @@ -42,15 +41,14 @@ jobs: steps: - uses: actions/checkout@v4 - - uses: pnpm/action-setup@v4 - with: - version: 10 - - uses: actions/setup-node@v4 with: node-version: 24 cache: pnpm + - name: Enable corepack + run: corepack enable + - run: pnpm install --frozen-lockfile - run: pnpm run lint - run: pnpm run format:check @@ -61,15 +59,14 @@ jobs: steps: - uses: actions/checkout@v4 - - uses: pnpm/action-setup@v4 - with: - version: 10 - - uses: actions/setup-node@v4 with: node-version: 24 cache: pnpm + - name: Enable corepack + run: corepack enable + - run: pnpm install --frozen-lockfile - run: pnpm run typecheck @@ -79,15 +76,14 @@ jobs: steps: - uses: actions/checkout@v4 - - uses: pnpm/action-setup@v4 - with: - version: 10 - - uses: actions/setup-node@v4 with: node-version: 24 cache: pnpm + - name: Enable corepack + run: corepack enable + - run: pnpm install --frozen-lockfile - run: pnpm run build:ts diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..ae0dc4a --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,13 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +## [2.0.0] - 2026-05-28 + +### Added +- Initial release diff --git a/README.md b/README.md index 29e510c..3d6e8d8 100644 --- a/README.md +++ b/README.md @@ -4,9 +4,7 @@ [![CI](https://github.com/acamarata/solar-spa/actions/workflows/ci.yml/badge.svg)](https://github.com/acamarata/solar-spa/actions/workflows/ci.yml) [![license](https://img.shields.io/npm/l/solar-spa.svg)](https://github.com/acamarata/solar-spa/blob/main/LICENSE) -NREL Solar Position Algorithm compiled to WebAssembly. Calculates solar zenith, azimuth, incidence angle, sunrise, sunset, solar noon, and equation of time for any location and date. - -The algorithm is the [NREL SPA](https://midcdmz.nrel.gov/spa/) by Ibrahim Reda and Afshin Andreas, originally written in C. This package compiles the original C source to WASM via Emscripten and provides a TypeScript/JavaScript interface on top. +NREL Solar Position Algorithm compiled to WebAssembly. Calculates solar zenith, azimuth, incidence angle, sunrise, sunset, solar noon, and equation of time for any location and date. The WASM binary is inlined as base64, so there is no external `.wasm` file to locate — it works in Node.js, browsers, Webpack, Vite, Next.js, and web workers without configuration. ## Installation @@ -20,129 +18,25 @@ npm install solar-spa import { spa } from 'solar-spa'; const result = await spa( - new Date(2025, 5, 21, 12, 0, 0), // June 21, 2025 at noon - 40.7128, // latitude (NYC) - -74.0060, // longitude - { timezone: -4, elevation: 10 } // EDT (UTC-4), 10m elevation + new Date(2025, 5, 21, 12, 0, 0), // June 21, 2025 at noon + 40.7128, // latitude (NYC) + -74.0060, // longitude + { timezone: -4, elevation: 10 } // EDT (UTC-4), 10m elevation ); -console.log(result.zenith); // ~27 (degrees from vertical) -console.log(result.azimuth); // ~179 (degrees from north) -console.log(result.sunrise); // ~5.4 (fractional hours) -console.log(result.sunset); // ~20.5 (fractional hours) +console.log(result.zenith); // ~27 (degrees from vertical) +console.log(result.sunrise); // ~5.4 (fractional hours) +console.log(result.sunset); // ~20.5 (fractional hours) ``` -CommonJS works too: +CommonJS also works: ```js const { spa } = require('solar-spa'); ``` -## API - -### `spa(date, latitude, longitude, options?)` - -Returns a `Promise` with raw numeric values. - -**Parameters:** - -| Name | Type | Description | -| --- | --- | --- | -| `date` | `Date` | Date and time for the calculation | -| `latitude` | `number` | Observer latitude, -90 to 90 (negative = south) | -| `longitude` | `number` | Observer longitude, -180 to 180 (negative = west) | -| `options` | `object` | Optional. See below | - -**Options:** - -| Option | Type | Default | Description | -| --- | --- | --- | --- | -| `timezone` | `number` | auto | Hours from UTC. Auto-detected from the Date object if omitted | -| `elevation` | `number` | `0` | Meters above sea level | -| `pressure` | `number` | `1013.25` | Atmospheric pressure in millibars | -| `temperature` | `number` | `15` | Temperature in Celsius | -| `delta_ut1` | `number` | `0` | UT1-UTC correction in seconds | -| `delta_t` | `number` | `67` | TT-UTC difference in seconds | -| `slope` | `number` | `0` | Surface slope in degrees | -| `azm_rotation` | `number` | `0` | Surface azimuth rotation in degrees | -| `atmos_refract` | `number` | `0.5667` | Atmospheric refraction in degrees | -| `function` | `number` | `3` | SPA function code (see below) | - -**Result fields:** - -| Field | Unit | Description | -| --- | --- | --- | -| `zenith` | degrees | Topocentric zenith angle | -| `azimuth` | degrees | Topocentric azimuth, eastward from north | -| `azimuth_astro` | degrees | Topocentric azimuth, westward from south | -| `incidence` | degrees | Surface incidence angle | -| `sunrise` | fractional hours | Local sunrise time | -| `sunset` | fractional hours | Local sunset time | -| `suntransit` | fractional hours | Solar noon | -| `sun_transit_alt` | degrees | Sun transit altitude | -| `eot` | minutes | Equation of time | -| `error_code` | integer | 0 on success | - -### `spaFormatted(date, latitude, longitude, options?)` - -Same as `spa()`, but `sunrise`, `sunset`, and `suntransit` are returned as `HH:MM:SS` strings. Returns `"N/A"` for these fields during polar day or polar night. - -### `formatTime(hours)` - -Converts fractional hours to an `HH:MM:SS` string. Returns `"N/A"` for non-finite or negative values (polar night/day scenarios). - -### `init()` - -Pre-initializes the WASM module. Optional. The module initializes automatically on the first `spa()` call. Useful if you want to pay the initialization cost at application startup rather than on the first calculation. - -### Function Codes - -| Constant | Value | Computes | -| --- | --- | --- | -| `SPA_ZA` | `0` | Zenith and azimuth | -| `SPA_ZA_INC` | `1` | Zenith, azimuth, and incidence | -| `SPA_ZA_RTS` | `2` | Zenith, azimuth, and rise/transit/set | -| `SPA_ALL` | `3` | All output values | - -## Architecture - -The package has three layers: - -1. **C layer** (`src/spa.c`, `src/spa_wrapper.c`): The original NREL SPA algorithm with a thin wrapper that exposes a flat function signature suitable for WASM. - -2. **WASM layer** (`wasm/spa-module.js`): Compiled with Emscripten using `-sSINGLE_FILE=1`, which inlines the WASM binary as base64. No external `.wasm` file to resolve. This eliminates the bundler path-resolution issues that plague most WASM packages. - -3. **TypeScript layer** (`src/index.ts`, `src/types.ts`): Written in TypeScript and compiled by tsup to both CJS and native ESM with generated declaration files. Singleton WASM initialization, cached `cwrap` bindings, input validation, and named struct offset constants. - -### Build Flags - -The WASM binary is compiled with: - -- `-O3 -flto`: Maximum optimization with link-time optimization -- `-sSINGLE_FILE=1`: WASM inlined as base64 (no file path resolution) -- `-sMODULARIZE=1`: No global `Module` pollution -- `-sNO_FILESYSTEM=1`: No filesystem API bundled (saves ~15KB) -- `-sINITIAL_MEMORY=1048576`: 1MB fixed memory (SPA needs very little) -- `-sASSERTIONS=0`: No debug assertions in production -- `-sENVIRONMENT='node,web,worker'`: Works in Node.js, browsers, and web workers - -## Compatibility - -Tested in: - -- Node.js 20+ -- Modern browsers (Chrome, Firefox, Safari, Edge) -- Webpack 5 -- Vite -- Next.js (both Pages and App Router) -- Web Workers - -The `SINGLE_FILE` approach eliminates the `.wasm` file resolution problem that breaks most WASM packages in bundlers. There is no external binary to locate at runtime. - ## TypeScript -Full type definitions are generated from the TypeScript source and included with the package. Import types directly: - ```ts import { spa, SPA_ALL } from 'solar-spa'; import type { SpaResult, SpaOptions } from 'solar-spa'; @@ -150,21 +44,18 @@ import type { SpaResult, SpaOptions } from 'solar-spa'; ## Documentation -See the [Wiki](https://github.com/acamarata/solar-spa/wiki) for detailed documentation: API reference, architecture, performance, bundler compatibility, validation benchmarks, and more. +See the [Wiki](https://github.com/acamarata/solar-spa/wiki) for the full API reference, architecture notes, build flags, bundler compatibility, and validation benchmarks. ## Related -- [nrel-spa](https://github.com/acamarata/nrel-spa): Pure JavaScript port of the same algorithm. No WASM dependency, synchronous API. Better choice if you do not need WASM-level performance. -- [NREL SPA](https://midcdmz.nrel.gov/spa/): The original algorithm specification and C source. -- [pray-calc](https://github.com/acamarata/pray-calc): Islamic prayer time calculator built on nrel-spa. +- [nrel-spa](https://github.com/acamarata/nrel-spa): Pure JavaScript port of the same algorithm. Synchronous, no WASM dependency. +- [pray-calc](https://github.com/acamarata/pray-calc): Islamic prayer times built on nrel-spa. ## Acknowledgments -This package includes the Solar Position Algorithm (SPA) developed at the National Renewable Energy Laboratory (NREL) by Ibrahim Reda and Afshin Andreas. The C source files `spa.c` and `spa.h` are copyright Alliance for Sustainable Energy, LLC (2008-2011) and are distributed under the terms included in those files. +This package includes the Solar Position Algorithm (SPA) developed at the National Renewable Energy Laboratory (NREL) by Ibrahim Reda and Afshin Andreas. The C source files `spa.c` and `spa.h` are copyright Alliance for Sustainable Energy, LLC (2008-2011). -> Reda, I., Andreas, A. (2004). "Solar Position Algorithm for Solar Radiation Applications." *Solar Energy*, 76(5), 577-589. [doi:10.1016/j.solener.2003.12.003](https://doi.org/10.1016/j.solener.2003.12.003) - -The original C source and an online calculator are available at [midcdmz.nrel.gov/spa](https://midcdmz.nrel.gov/spa/). +> Reda, I., Andreas, A. (2004). "Solar Position Algorithm for Solar Radiation Applications." *Solar Energy*, 76(5), 577-589. ## License diff --git a/package.json b/package.json index a0f6b92..499a1f8 100644 --- a/package.json +++ b/package.json @@ -9,15 +9,11 @@ "types": "./dist/index.d.ts", "exports": { ".": { - "import": { - "types": "./dist/index.d.mts", - "default": "./dist/index.mjs" - }, - "require": { - "types": "./dist/index.d.ts", - "default": "./dist/index.cjs" - } - } + "types": "./dist/index.d.ts", + "import": "./dist/index.mjs", + "require": "./dist/index.cjs" + }, + "./package.json": "./package.json" }, "sideEffects": false, "files": [ @@ -41,7 +37,8 @@ "format": "prettier --write src/", "format:check": "prettier --check src/", "validate": "node validate.mjs", - "prepublishOnly": "pnpm run build:ts" + "prepublishOnly": "pnpm run build:ts", + "coverage": "c8 --reporter=lcov --reporter=text node --test" }, "keywords": [ "solar", @@ -81,5 +78,7 @@ "tsup": "^8.5.1", "typescript": "^5.9.3", "typescript-eslint": "^8.56.1" - } + }, + "type": "module", + "packageManager": "pnpm@10.11.1" } diff --git a/src/index.ts b/src/index.ts index 7afdd53..0802403 100644 --- a/src/index.ts +++ b/src/index.ts @@ -11,7 +11,7 @@ import { SPA_ALL } from './types.js'; // In CJS builds, require() is natively available. declare const __require: NodeRequire; const _loadModule = typeof __require === 'function' ? __require : require; -const createSpaModule: () => Promise = _loadModule('../wasm/spa-module.js'); +const createSpaModule: () => Promise = _loadModule('../wasm/spa-module.cjs'); // Singleton: the WASM module initializes once, all calls share it. let _module: SpaWasmModule | null = null; diff --git a/tsup.config.ts b/tsup.config.ts index de57165..dcc4b46 100644 --- a/tsup.config.ts +++ b/tsup.config.ts @@ -24,5 +24,5 @@ export default defineConfig({ return {}; }, // The WASM module is Emscripten CJS output, keep it external. - external: ['../wasm/spa-module.js'], + external: ['../wasm/spa-module.cjs'], }); diff --git a/wasm/spa-module.cjs b/wasm/spa-module.cjs new file mode 100644 index 0000000..d86b393 Binary files /dev/null and b/wasm/spa-module.cjs differ