fix(documentation): update readme with comprehensive API documentation and hints file

- Updated readme.md with complete API reference and usage examples
- Added readme.hints.md with architecture and implementation details
- Improved documentation structure and clarity
- Version bump to 5.0.13
This commit is contained in:
Juergen Kunz
2025-07-28 12:00:51 +00:00
parent b4897d238f
commit ce338e27ea
7 changed files with 7813 additions and 4445 deletions

8
changelog.md Normal file
View File

@@ -0,0 +1,8 @@
# Changelog
## [5.0.13] - 2025-07-28
### Fixed
- Updated readme.md with comprehensive documentation including API reference, core features, and usage examples
- Added readme.hints.md with architecture and implementation details for future reference
- Improved documentation structure and clarity

View File

@@ -1,6 +1,6 @@
{
"name": "@push.rocks/smartenv",
"version": "5.0.12",
"version": "5.0.13",
"description": "A module for storing and accessing environment details across different platforms.",
"main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts",
@@ -40,10 +40,8 @@
"@git.zone/tsbuild": "^2.1.72",
"@git.zone/tsbundle": "^2.0.15",
"@git.zone/tsrun": "^1.2.44",
"@git.zone/tstest": "^1.0.86",
"@push.rocks/tapbundle": "^5.0.8",
"@types/node": "^20.11.24",
"@types/npm": "^7.19.3"
"@git.zone/tstest": "^2.3.2",
"@types/node": "^22.0.0"
},
"private": false,
"files": [
@@ -60,5 +58,6 @@
],
"browserslist": [
"last 1 chrome versions"
]
}
],
"packageManager": "pnpm@10.11.0+sha512.6540583f41cc5f628eb3d9773ecee802f4f9ef9923cc45b69890fb47991d4b092964694ec3a4f738a420c918a333062c8b925d312f42e4f0c263eb603551f977"
}

11958
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -1 +1,23 @@
# SmartEnv Hints
## Architecture Overview
- Single main class `Smartenv` that provides all functionality
- Uses dependency injection pattern with plugins imported from smartenv.plugins.ts
- Utilizes @push.rocks/smartpromise for async operations
## Key Implementation Details
- Runtime detection based on checking if `process` is defined
- Dynamic module loading using Function constructor for Node.js modules
- Script tag injection for browser module loading with duplicate prevention
- OS detection uses the native Node.js 'os' module loaded dynamically
## Testing Approach
- Tests use @git.zone/tstest with tap-based testing
- Test file demonstrates OS detection and CI environment detection
- Tests can run in both Node.js and browser environments
## Important Notes
- The `getSafeNodeModule` uses dynamic import via Function constructor to avoid bundler issues
- Browser module loading tracks loaded scripts to prevent duplicate loads
- All OS detection methods are async and return false in browser environments
- The package is isomorphic and designed for use in both Node.js and browser contexts

251
readme.md
View File

@@ -1,107 +1,240 @@
# @push.rocks/smartenv
store things about your environment and let them travel across modules
A cross-platform TypeScript library for detecting and managing runtime environments. It provides comprehensive environment detection capabilities and safe module loading for both Node.js and browser contexts.
## Install
To install `@push.rocks/smartenv`, you need Node.js and npm installed. Then, run the following command:
To install `@push.rocks/smartenv`, you need Node.js and pnpm installed. Then, run the following command:
```bash
npm install @push.rocks/smartenv --save
pnpm install @push.rocks/smartenv --save
```
## Usage
`@push.rocks/smartenv` is a valuable utility for managing and accessing environment-specific information within your application, enabling your code to adapt to different environments, such as development, testing, and production seamlessly. Here we delve into how to utilize `@push.rocks/smartenv` effectively within a TypeScript project. We'll cover initializing the package, checking the execution environment, loading modules conditionally based on the environment, and accessing environment variables securely.
`@push.rocks/smartenv` is a powerful utility for managing and accessing environment-specific information within your application. It enables your code to adapt seamlessly to different environments such as development, testing, and production.
### Getting Started
First, ensure to import `Smartenv` from the package:
First, import the `Smartenv` class from the package:
```typescript
import { Smartenv } from '@push.rocks/smartenv';
```
### Initializing Smartenv
You can begin by creating an instance of `Smartenv`. This instance will be your gateway to accessing and managing the environment properties throughout your application.
Create an instance of `Smartenv` to access all environment detection and module loading features:
```typescript
const smartEnv = new Smartenv();
```
### Checking Execution Environment
`Smartenv` offers straightforward methods to determine whether your code is running in a Node.js or browser environment. This can be particularly useful for isomorphic code.
## Core Features
- **Runtime Environment Detection**: Instantly detect whether your code is running in Node.js or browser
- **Operating System Detection**: Identify Mac, Windows, or Linux platforms in Node.js environments
- **CI Environment Detection**: Detect if running in a continuous integration environment
- **Safe Module Loading**: Load modules conditionally based on the runtime environment
- **Browser Information**: Access user agent information in browser contexts
- **Node.js Version**: Get the current Node.js version when running in Node.js
## API Reference
### Environment Detection
#### `isNode: boolean`
Returns `true` if running in a Node.js environment.
```typescript
// Check if running in a Node.js environment
console.log(`Is Node: ${smartEnv.isNode}`);
// Check if running in a browser environment
console.log(`Is Browser: ${smartEnv.isBrowser}`);
```
### Loading Modules Conditionally
One of the core functionalities of `@push.rocks/smartenv` is to load modules based on the execution environment. This feature is immensely useful for isomorphic applications that need to run both in the browser and Node.js environments.
```typescript
// Node.js module and equivalent browser module URLs
const nodeModuleName = 'example-node-module';
const browserModuleUrl = 'https://example.com/example-browser-module.js';
// Function to access the module in the browser
const getBrowserModule = () => window.exampleBrowserModule;
const module = await smartEnv.getEnvAwareModule({
nodeModuleName: nodeModuleName,
webUrlArg: browserModuleUrl,
getFunction: getBrowserModule
});
console.log(module);
```
### Accessing Environment Variables Securely
For Node.js environments, accessing environment variables is a common task. `Smartenv` does not directly manipulate environment variables but encourages best practices for accessing them, ensuring your application remains secure and performs optimally.
```typescript
if(smartEnv.isNode) {
console.log(`Your environment variable value: ${process.env.YOUR_ENV_VAR}`);
if (smartEnv.isNode) {
console.log('Running in Node.js');
}
```
### Detecting CI Environments
Detect if your application is running in a Continuous Integration (CI) environment. This can be useful for modifying behavior during testing or deployment.
#### `isBrowser: boolean`
Returns `true` if running in a browser environment.
```typescript
console.log(`Is CI: ${smartEnv.isCI}`);
if (smartEnv.isBrowser) {
console.log('Running in browser');
}
```
### Platform-Specific Checks
`Smartenv` enables you to perform checks for specific operating systems when running in a Node.js environment, which can be particularly useful for tasks that depend on OS-specific features or paths.
#### `runtimeEnv: string`
Returns the runtime environment as a string ('node' or 'browser').
```typescript
console.log(`Runtime: ${smartEnv.runtimeEnv}`);
```
#### `isCI: boolean`
Returns `true` if running in a CI environment (checks for CI environment variable).
```typescript
if (smartEnv.isCI) {
console.log('Running in CI environment');
}
```
### Platform Detection (Node.js only)
#### `isMacAsync(): Promise<boolean>`
Asynchronously checks if running on macOS.
```typescript
const isMac = await smartEnv.isMacAsync();
const isWindows = await smartEnv.isWindowsAsync();
const isLinux = await smartEnv.isLinuxAsync();
console.log(`Is Mac: ${isMac}, Is Windows: ${isWindows}, Is Linux: ${isLinux}`);
if (isMac) {
console.log('Running on macOS');
}
```
### Printing Environment for Debugging
To assist with debugging, `Smartenv` offers a method to print the current environment and some relevant information to the console. This feature is particularly useful during development or when troubleshooting environment-specific issues.
#### `isWindowsAsync(): Promise<boolean>`
Asynchronously checks if running on Windows.
```typescript
smartEnv.printEnv();
const isWindows = await smartEnv.isWindowsAsync();
if (isWindows) {
console.log('Running on Windows');
}
```
### Usage within Browser
While `Smartenv` primarily facilitates handling different environments in server-side applications, it also provides functionalities to manage and load scripts dynamically in the browser. This allows for more flexible and environment-aware code sharing between server and client-side.
#### `isLinuxAsync(): Promise<boolean>`
Asynchronously checks if running on Linux.
For instance, using `getSafeWebModule` to dynamically load a script only if it hasn't been already and then utilizing a globally available function or object that the script provides.
```typescript
const isLinux = await smartEnv.isLinuxAsync();
if (isLinux) {
console.log('Running on Linux');
}
```
### Conclusion
`@push.rocks/smartenv` is a comprehensive solution for managing environment-specific logic and configurations in your JavaScript and TypeScript projects. By leveraging its functionalities, developers can create more robust, flexible, and maintainable applications that seamlessly adapt to different execution contexts, whether in Node.js, the browser, or CI environments.
### Runtime Information
Always refer to the official documentation and source code for the most up-to-date usage examples and features.
#### `nodeVersion: string`
Returns the Node.js version (only available in Node.js environment).
```typescript
if (smartEnv.isNode) {
console.log(`Node.js version: ${smartEnv.nodeVersion}`);
}
```
#### `userAgent: string`
Returns the browser user agent string (only available in browser environment).
```typescript
if (smartEnv.isBrowser) {
console.log(`Browser: ${smartEnv.userAgent}`);
}
```
### Module Loading
#### `getEnvAwareModule(options)`
Loads a module appropriate for the current environment. In Node.js, it uses dynamic import; in browsers, it loads a script via URL.
```typescript
const module = await smartEnv.getEnvAwareModule({
nodeModuleName: 'node-fetch',
webUrlArg: 'https://unpkg.com/whatwg-fetch@3.6.2/dist/fetch.umd.js',
getFunction: () => window.fetch
});
```
#### `getSafeNodeModule<T>(moduleName, runAfterFunc?)`
Safely loads a Node.js module with error handling. Only works in Node.js environment.
```typescript
const fs = await smartEnv.getSafeNodeModule('fs');
if (fs) {
// Use fs module
}
// With post-load function
const express = await smartEnv.getSafeNodeModule('express', async (mod) => {
console.log('Express loaded successfully');
});
```
#### `getSafeWebModule(url, getFunction)`
Safely loads a web module via script tag. Only works in browser environment. Prevents duplicate loading of the same script.
```typescript
const jQuery = await smartEnv.getSafeWebModule(
'https://code.jquery.com/jquery-3.6.0.min.js',
() => window.jQuery
);
```
### Debugging
#### `printEnv()`
Prints the current environment information to the console for debugging purposes.
```typescript
await smartEnv.printEnv();
// Output in Node.js: "running on NODE" + version
// Output in browser: "running on BROWSER" + user agent
```
## Common Use Cases
### 1. Isomorphic Module Loading
```typescript
// Define environment-specific implementations
const cryptoModule = await smartEnv.getEnvAwareModule({
nodeModuleName: 'crypto',
webUrlArg: 'https://unpkg.com/crypto-js@4.1.1/crypto-js.js',
getFunction: () => window.CryptoJS
});
```
### 2. Platform-Specific Operations
```typescript
if (smartEnv.isNode) {
const os = await smartEnv.getSafeNodeModule('os');
console.log(`Home directory: ${os.homedir()}`);
} else {
console.log('Browser environment - no filesystem access');
}
```
### 3. CI/CD Pipeline Detection
```typescript
if (smartEnv.isCI) {
// Run extended tests or different build configuration
console.log('Running in CI - enabling extended test suite');
} else {
console.log('Local development environment');
}
```
### 4. Dynamic Script Loading in Browser
```typescript
if (smartEnv.isBrowser) {
// Load analytics only in browser
await smartEnv.getSafeWebModule(
'https://www.google-analytics.com/analytics.js',
() => window.ga
);
}
```
## TypeScript Support
The package is written in TypeScript and provides full type definitions. The main type export is:
```typescript
export interface IEnvObject {
name: string;
value: string;
}
```
## License and Legal Information

View File

@@ -1,4 +1,4 @@
import { tap, expect } from '@push.rocks/tapbundle';
import { tap, expect } from '@git.zone/tstest/tapbundle';
import * as smartenv from '../ts/index.js';
let testEnv: smartenv.Smartenv;

View File

@@ -32,7 +32,7 @@ export class Smartenv {
public async getSafeNodeModule<T = any>(moduleNameArg: string, runAfterFunc?: (moduleArg: T) => Promise<any>): Promise<T> {
if (!this.isNode) {
console.error(`You tried to load a node module in a wrong context: ${moduleNameArg}`);
console.error(`You tried to load a node module in a wrong context: ${moduleNameArg}. This does not throw.`);
return;
}
// tslint:disable-next-line: function-constructor