### Full i18n Setup Example
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/api-reference/i18n.md
Demonstrates a complete setup for the i18n module, including resource definition, fallback languages, missing key handling, and basic UI integration for language switching.
```typescript
import { createI18n } from "@ziweijs/i18n";
import React from "react";
const i18n = createI18n({
lang: "en",
resources: {
en: {
app: { title: "Ziwei Chart" },
star: { ZiWei: "Purple Subtlety" },
},
zh: {
app: { title: "紫微命盤" },
star: { ZiWei: "紫微" },
},
},
fallbackLanguages: ["en"],
onMissing: ({ key, languagesTried }) => {
console.warn(`Missing: ${key} in ${languagesTried.join(", ")}`);
},
});
export function App() {
return (
{i18n.$t("app.title")}
);
}
```
--------------------------------
### Local Development Setup
Source: https://github.com/lzm0x219/ziwei/blob/main/packages/react/README.md
Install project dependencies and run the development server for the @ziweijs/react package. This is useful for local development and testing.
```bash
pnpm install
pnpm dev --filter @ziweijs/react
```
--------------------------------
### Complete Ziwei Configuration Example
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/configuration.md
A comprehensive example demonstrating how to set up custom dependencies like i18n, global configurations, and a frozen reference time for creating Ziwei instances.
```typescript
import {
createZiWeiBySolar,
createZiWeiRuntime,
createZiWeiI18n,
getGlobalConfigs,
} from "@ziweijs/core";
// Set up custom dependencies
const i18n = createZiWeiI18n("zh-Hant"); // Traditional Chinese
const configs = {
...getGlobalConfigs(),
division: {
year: "spring", // 立春 boundary
month: "last", // Leap months to previous
day: "current", // Late Zi = current day
},
star: "onlyMajor", // 14 main stars only
};
const now = () => new Date(2024, 0, 1); // Frozen reference time
// Create runtime
const runtime = createZiWeiRuntime({ i18n, configs, now });
// Use with creator
const { createZiWeiBySolar: createSolar } = await import("@ziweijs/core");
const natal = createSolar(
{
name: "张三",
gender: "Yang",
date: new Date(1990, 5, 15, 14, 30),
language: "zh-Hant",
timezone: 8,
useTrueSolarTime: true,
},
{ runtime }
);
console.log(`${natal.name} (${natal.gender})`);
console.log(`五行局: ${natal.fiveElementSchemeName}`);
console.log(`大限方向: ${natal.decadeDirection === 1 ? '顺行' : '逆行'}`);
```
--------------------------------
### Install @ziweijs/react
Source: https://github.com/lzm0x219/ziwei/blob/main/packages/react/README.md
Install the @ziweijs/react package along with its core dependencies. Ensure your React version is compatible (19.2+ recommended).
```bash
pnpm add @ziweijs/react @ziweijs/core react react-dom
```
--------------------------------
### Complete Ziwei Doushu React Example
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/api-reference/react-components.md
A comprehensive example demonstrating the usage of ZiWei and ZiWeiSimulator components for displaying a birth chart or using the simulator. It includes state management for mode switching and basic styling.
```typescript
import React, { useState } from "react";
import ZiWei, { DestinyBoard, ZiWeiSimulator } from "@ziweijs/react";
import type { GenderKey, StemKey, BranchKey } from "@ziweijs/core";
export function ZiweiApp() {
const [mode, setMode] = useState<"chart" | "simulator">("chart");
return (
);
}
```
--------------------------------
### DestinyBoard Usage Example
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/api-reference/react-components.md
Demonstrates how to use the DestinyBoard component with data generated by createZiWeiBySolar. Ensure you have the necessary imports from '@ziweijs/react' and '@ziweijs/core'.
```typescript
import DestinyBoard from "@ziweijs/react";
import { createZiWeiBySolar } from "@ziweijs/core";
const natal = createZiWeiBySolar({
name: "Example",
gender: "Yang",
date: new Date(2000, 0, 1),
});
export function Chart() {
return (
);
}
```
--------------------------------
### Usage Example for Yin-Yang Constants
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/api-reference/constants.md
Demonstrates how to use the YIN_YANG and YIN_YANG_HANS constants to check for Yin and log its Chinese representation.
```typescript
import { YIN_YANG, YIN_YANG_HANS } from "@ziweijs/core";
if (stemIndex % 2 === YIN_YANG.Yin) {
console.log(YIN_YANG_HANS.Yin); // "阴"
}
```
--------------------------------
### Basic i18n Setup and Usage
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/api-reference/i18n.md
Demonstrates how to create an i18n instance with multiple languages and nested resources. Shows how to translate strings using the `$t` method and switch the current language.
```typescript
import { createI18n } from "@ziweijs/i18n";
const i18n = createI18n({
lang: "en",
resources: {
en: {
star: {
ZiWei: "Purple Subtlety",
TaiYang: "Sun",
},
palace: {
Ming: "Life Palace",
},
},
zh: {
star: {
ZiWei: "紫微",
TaiYang: "太阳",
},
palace: {
Ming: "命宫",
},
},
},
fallbackLanguages: ["zh"],
separator: ".",
});
console.log(i18n.$t("star.ZiWei")); // "Purple Subtlety"
i18n.setCurrentLanguage("zh");
console.log(i18n.$t("star.ZiWei")); // "紫微"
```
--------------------------------
### Create Runtime with Custom Configurations
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/configuration.md
Initialize a ZiWei runtime with custom configurations, starting from global defaults and overriding specific settings like division and star modes.
```typescript
import { createZiWeiRuntime, getGlobalConfigs } from "@ziweijs/core";
const customConfigs = {
...getGlobalConfigs(), // Start with defaults
division: {
year: "spring",
month: "last",
day: "normal",
},
star: "onlyMajor",
};
const runtime = createZiWeiRuntime({
configs: customConfigs,
});
```
--------------------------------
### Configure Year Division to Use Start of Spring
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/configuration.md
Customize the runtime to use the Start of Spring (立春) solar term for year boundary assignment instead of the traditional lunar new year.
```typescript
import { createZiWeiRuntime } from "@ziweijs/core";
const runtime = createZiWeiRuntime({
configs: {
division: {
year: "spring", // Use 立春 instead of 正月初一
month: "normal",
day: "normal",
},
},
});
```
--------------------------------
### ZiWeiSimulator Usage Example
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/api-reference/react-components.md
Shows how to use the ZiWeiSimulator component with essential props like side, birthYearStemKey, ziweiBranchKey, and mainPalaceBranchKey. Note that this component does not render decade data.
```typescript
import { ZiWeiSimulator } from "@ziweijs/react";
export function Simulator() {
return (
);
}
```
--------------------------------
### Core Calculation Engine Layers
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/architecture.md
The core package is structured in layers, starting with constants and pure functions, progressing to domain logic, input processing, domain objects, and finally the SDK and public API. Infrastructure, utilities, and types support these layers.
```typescript
/* Layer 1: Constants */
// Heavenly stems (天干), earthly branches (地支)
// Star names and classifications (主星, 辅星, 杂星)
// Palaces (十二宫), five element schemes (五行局)
// Transformation rules (四化)
// All static enums and lookup tables
```
```typescript
/* Layer 2: Rules (Pure Functions) */
// src/rules/
// - palace.ts: Main palace calculation, palace stem-branch derivation
// - star.ts: Star position and transformation logic
// - element.ts: Five element scheme determination
// - date.ts: Date-related calculations
// No state, no dependencies, fully testable
```
```typescript
/* Layer 3: Services (Domain Logic) */
// src/services/
// - natal.ts: Combines rules to produce complete natal chart
// - palace.ts: Constructs 12 palace objects with stars
// - star.ts: Applies transformations to stars
// - decade.ts: Calculates decade (大限) and yearly data
// Accesses runtime dependencies (i18n, configs)
```
```typescript
/* Layer 4: Pipelines (Input Processing) */
// src/pipelines/
// - natal.ts: Entry points for different date formats
// - calculateNatalBySolar: Solar date input
// - calculateNatalByLunisolar: Lunisolar date input
// - calculateNatalByStemBranch: Direct stem-branch input
// Handles time zone, true solar time, calendar conversion
// Assembles parameters for service layer
```
```typescript
/* Layer 5: Models (Domain Objects) */
// src/models/
// - natal.ts: Creates `Natal` instance with helper methods
// - palace.ts: Creates `Palace` instance with `flying()` method
// - star.ts: Creates `Star` instance (minimal, mostly data)
// Lightweight factories wrapping data with behavior
```
```typescript
/* Layer 6: SDK & Public API */
// src/sdk.ts, src/public.ts, src/index.ts
// - createZiWeiBySolar(), createZiWeiByLunisolar(), createZiWeiByStemBranch()
// - withZiWeiRuntime() for scoped calculations
// - createZiWeiRuntime() for custom dependency injection
// Re-exports all public types, constants, utilities
```
```typescript
/* Layer 7: Infrastructure */
// src/infra/
// - configs/: Global configuration defaults (year/month/day division, star mode)
// - i18n/: i18n instance creation with Simplified/Traditional Chinese locales
```
```typescript
/* Layer 8: Utilities */
// src/utils/
// - calendar.ts: Solar ↔ lunisolar conversion
// - trueSolarTime.ts: True solar time correction (NOAA)
// - format.ts: Text formatting for dates
// - math.ts: Index wrapping, palace calculations
// - sexagenary.ts: Sexagenary (干支) parsing and conversion
// - memoize.ts: Caching helper (internal)
```
```typescript
/* Layer 9: Types */
// src/typings/
// - Natal, Palace, Star interfaces
// - Input parameter types: CreateZiWeiSolarParams, etc.
// - Type keys: StemKey, BranchKey, StarKey, etc.
// - Value objects: StemVO, BranchVO, TransformationVO, etc.
```
--------------------------------
### Get Default Global Configurations
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/configuration.md
Retrieves a fresh copy of the default global configuration. Mutations to the returned object do not affect the defaults.
```typescript
function getGlobalConfigs(): GlobalConfigs
```
```typescript
{
division: {
year: "normal",
month: "normal",
day: "normal",
},
star: "normal",
}
```
```typescript
import { getGlobalConfigs } from "@ziweijs/core";
const defaults = getGlobalConfigs();
console.log(defaults.star); // "normal"
// Customize by spreading
const customConfigs = {
...defaults,
star: "onlyMajor",
};
```
--------------------------------
### Render ZiWei Natal Chart
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/api-reference/react-components.md
Example of how to use the ZiWei component to display a natal chart. Ensure you import ZiWei and the GenderKey type. The date format must be 'YYYY-MM-DD-HH'.
```typescript
import ZiWei from "@ziweijs/react";
import type { GenderKey } from "@ziweijs/core";
export function Profile() {
return (
);
}
```
--------------------------------
### getCurrentLanguage()
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/api-reference/i18n.md
Gets the currently active language code.
```APIDOC
## getCurrentLanguage()
### Description
Gets the currently active language code.
### Method Signature
```typescript
getCurrentLanguage(): LanguageKey
```
### Returns
`LanguageKey` — Current language key (e.g., `"en"`, `"zh-Hans"`)
### Example
```typescript
const lang = i18n.getCurrentLanguage(); // "en"
```
```
--------------------------------
### getStemAndBranchByYear
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/api-reference/utilities.md
Gets the stem and branch for a given year.
```APIDOC
## getStemAndBranchByYear
### Description
Gets the stem and branch for a given year.
### Method
```typescript
function getStemAndBranchByYear(year: number): {
stemKey: StemKey;
branchKey: BranchKey;
}
```
### Parameters
#### Path Parameters
- **year** (number) - Required - Year number
### Returns
Stem and branch keys for the year
### Request Example
```typescript
import { getStemAndBranchByYear } from "@ziweijs/core";
const result = getStemAndBranchByYear(2000);
// { stemKey: "Geng", branchKey: "Chen" }
```
```
--------------------------------
### i18n Instance Creation and Usage
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/architecture.md
Use `createI18n` to initialize the i18n system. The returned instance provides methods for translation ($t), language management, and checking key existence. Resources are flattened to dot notation and keys are validated.
```typescript
createI18n(options)
├─ Flatten resources (nested → dot notation)
├─ Validate language keys
├─ Initialize cache
└─ Return I18n instance
├─ $t(key, defaultValue?) → string
├─ setCurrentLanguage(lang)
├─ onLanguageChange(callback) → unsubscribe
├─ has(key, lang?) → boolean
└─ getCacheStats() → {size, enabled}
```
--------------------------------
### createZiWeiRuntime
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/api-reference/sdk.md
Creates a runtime context container holding i18n, global configs, and time provider.
```APIDOC
## createZiWeiRuntime
### Description
Creates a runtime context container holding i18n, global configs, and time provider.
### Method
```typescript
function createZiWeiRuntime(options: ZiWeiRuntimeOptions = {}): ZiWeiRuntime
```
### Parameters
#### Path Parameters
This method does not have path parameters.
#### Query Parameters
This method does not have query parameters.
#### Request Body
This method does not have a request body.
### Parameters
- **options.i18n** (I18n) - Optional - Custom i18n instance (defaults to `createZiWeiI18n()`)
- **options.configs** (GlobalConfigs) - Optional - Custom global configs (defaults to `getGlobalConfigs()`)
- **options.now** (() => Date) - Optional - Custom time provider (defaults to `() => new Date()`)
### Returns
`ZiWeiRuntime` object with properties:
- `i18n: I18n` — Translation instance
- `configs: GlobalConfigs` — Configuration settings
- `now: () => Date` — Current time provider
### Example
```typescript
import { createZiWeiRuntime } from "@ziweijs/core";
const runtime = createZiWeiRuntime({
now: () => new Date(2024, 0, 1),
});
```
```
--------------------------------
### StarMetaVO Interface Definition
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/types.md
Represents metadata for a 'Star', including its key, starting index, direction, and optional galaxy.
```typescript
interface StarMetaVO {
key?: StarKey; // Unique identifier
startIndex: number; // Starting palace index
direction: 1 | -1; // Forward (1) or backward (-1)
galaxy?: StarGalaxy; // Northern, Southern, or Central
}
```
--------------------------------
### Get Current Language
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/api-reference/i18n.md
getCurrentLanguage() returns the active language code. This is useful for debugging or logging the current locale.
```typescript
const lang = i18n.getCurrentLanguage(); // "en"
```
--------------------------------
### Import Calendar Utilities
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/api-reference/utilities.md
Import functions for date calculations, including Ziwei dates, hours, lunisolar dates, and stem/branch.
```typescript
// Calendar utilities
import {
calculateZiWeiDate,
calculateHourByIndex,
calculateLunisolarDateBySolar,
getStemAndBranchByYear,
calculateNatalDateBySolar,
} from "@ziweijs/core";
```
--------------------------------
### Configure Batch Operations with ZiWei Runtime
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/configuration.md
Create a reusable ZiWei runtime creator with specific configurations for batch processing multiple ZiWei calculations.
```typescript
import { withZiWeiRuntime } from "@ziweijs/core";
const creator = withZiWeiRuntime({
configs: {
division: { year: "spring", month: "last", day: "normal" },
star: "onlyMajor",
},
});
const natal1 = creator.createZiWeiBySolar({
name: "Person 1",
gender: "Yang",
date: new Date(1990, 5, 15),
});
const natal2 = creator.createZiWeiByLunisolar({
name: "Person 2",
gender: "Yin",
date: "1990-5-15-8",
});
// Both use the same configuration
```
--------------------------------
### Retrieve Translated String
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/api-reference/i18n.md
Use $t to get a translated string for a given key. An optional default value can be provided if the key is not found.
```typescript
i18n.$t("star.ZiWei");
i18n.$t("unknown", "—");
```
--------------------------------
### Get Zodiac Name from Branch Key
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/api-reference/constants.md
Shows how to retrieve the Chinese zodiac name using a branch key from BRANCH_KEYS and ZODIAC_HANS.
```typescript
import { ZODIAC_HANS, BRANCH_KEYS } from "@ziweijs/core";
const branchKey = BRANCH_KEYS[0]; // "Zi"
const zodiacName = ZODIAC_HANS[branchKey]; // "鼠"
```
--------------------------------
### Configuration Options
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/INDEX.md
Details the runtime configuration options for Ziwei.js calculations, including date divisions, star placement, and custom functions.
```APIDOC
## Configuration Options
### Description
Customize the behavior of Ziwei.js calculations with various configuration settings.
### Division Options
Control how dates are classified:
- `division.year`: Sets the year boundary ('normal' for lunar new year, 'spring' for 立春).
- `division.month`: Defines leap month handling ('normal', 'last', 'next').
- `division.day`: Specifies handling for the Zi hour (23:00-01:00) ('normal' for next day, 'current' for the same day).
### Star Placement
Determine which stars are included in calculations:
- `star`: Options include 'normal' (all stars), 'onlyMajor' (14 main stars), or 'onlyTransformation' (transformation-related stars).
### Functions
- `getGlobalConfigs()`: Retrieves the default global configuration object.
- `createZiWeiI18n(lang?)`: Creates an i18n instance for a specified language.
- Custom `now()` function: Allows injecting a custom time function for testing or SSR scenarios.
```
--------------------------------
### i18n Singleton
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/configuration.md
Provides a pre-created i18n instance, defaulting to Simplified Chinese, for immediate use.
```APIDOC
## i18n Singleton
### Description
A pre-created i18n instance with Simplified Chinese default.
### Usage
```typescript
import { i18n } from "@ziweijs/core";
const starName = i18n.$t("star.ZiWei"); // "紫微"
```
```
--------------------------------
### Configure ZiWei SDK Functions
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/configuration.md
Apply custom configurations, including division and star modes, directly when using ZiWei SDK functions like createZiWeiBySolar.
```typescript
import { createZiWeiBySolar } from "@ziweijs/core";
const natal = createZiWeiBySolar(
{
name: "李四",
gender: "Yin",
date: new Date(1985, 11, 25),
},
{
configs: {
division: {
year: "normal",
month: "normal",
day: "current",
},
star: "onlyMajor",
},
}
);
```
--------------------------------
### Get Cache Statistics
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/api-reference/i18n.md
getCacheStats() returns an object containing the current cache size and whether caching is enabled. This is useful for monitoring and debugging.
```typescript
const stats = i18n.getCacheStats();
console.log(`Cached: ${stats.size}, Enabled: ${stats.enabled}`);
```
--------------------------------
### Project Directory Structure
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/INDEX.md
This snippet displays the directory structure of the Ziwei project, indicating the location of various documentation files and generated README.
```bash
OUTPUT/
├─ INDEX.md (this file)
├─ architecture.md
├─ configuration.md
├─ types.md
├─ api-reference/
│ ├─ sdk.md
│ ├─ natal-and-palaces.md
│ ├─ constants.md
│ ├─ utilities.md
│ ├─ react-components.md
│ └─ i18n.md
└─ README (auto-generated summary)
```
--------------------------------
### Get Available Languages
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/api-reference/i18n.md
getAvailableLanguages() returns a frozen array of all language keys supported by the i18n instance. This can be used to populate language selectors.
```typescript
const langs = i18n.getAvailableLanguages();
console.log(langs); // ["en", "zh"]
lans.forEach(lang => {
i18n.setCurrentLanguage(lang);
console.log(i18n.$t("star.ZiWei"));
});
```
--------------------------------
### Get Stem and Branch By Year
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/api-reference/utilities.md
Retrieves the stem and branch keys for a given year. This is useful for determining the cyclical calendar designation of a year.
```typescript
import { getStemAndBranchByYear } from "@ziweijs/core";
const result = getStemAndBranchByYear(2000);
// { stemKey: "Geng", branchKey: "Chen" }
```
--------------------------------
### Create Ziwei Runtime
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/api-reference/sdk.md
Creates a runtime context container. Use this to initialize the Ziwei environment with custom options for i18n, configurations, or time providers.
```typescript
function createZiWeiRuntime(options: ZiWeiRuntimeOptions = {}): ZiWeiRuntime
```
```typescript
import { createZiWeiRuntime } from "@ziweijs/core";
const runtime = createZiWeiRuntime({
now: () => new Date(2024, 0, 1),
});
```
--------------------------------
### Get Fallback Languages
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/api-reference/i18n.md
getFallbackLanguages() retrieves the current fallback language chain. This indicates the order in which languages are tried if a key is missing in the current language.
```typescript
const fallbacks = i18n.getFallbackLanguages();
console.log(fallbacks); // ["zh", "en"]
```
--------------------------------
### React Component Structure
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/architecture.md
The `` or `` components from @ziweijs/react serve as entry points. They manage runtime context and render the ``, which in turn composes various sub-components like ``, ``, and ``.
```typescript
or
├─ Create natal using @ziweijs/core
├─ Provide runtime context
└─ Render
├─ Calculate palace coordinates
├─ × 12
│ ├─ (stars in palace)
│ ├─ (自化)
│ └─ Star transformation decorations
├─ (central area)
└─ (person info)
```
--------------------------------
### Import Math Utilities
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/api-reference/utilities.md
Import specific math utilities for index manipulation.
```typescript
// Math utilities
import { wrapIndex, relativeIndex, oppositeIndex } from "@ziweijs/core";
```
--------------------------------
### ZiWeiRuntime Type Definition
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/types.md
Defines the runtime context container, holding essential dependencies like i18n, configs, and a function to get the current date.
```typescript
type ZiWeiRuntime = {
i18n: I18n;
configs: GlobalConfigs;
now: () => Date;
}
```
--------------------------------
### Core Package Directory Structure
Source: https://github.com/lzm0x219/ziwei/blob/main/docs/core-architecture.md
Overview of the @ziweijs/core package's internal directory structure, highlighting the organization of constants, infrastructure, context, rules, services, pipelines, models, typings, and utilities.
```text
packages/core/
├─ src/
│ ├─ constants/ # 天干地支、星曜、五行局等静态枚举
│ ├─ infra/
│ │ ├─ configs/ # GlobalConfigs 默认值与合法选项
│ │ └─ i18n/ # createZiWeiI18n、内置 zh-Hans/zh-Hant 资源
│ ├─ context/ # createZiWeiRuntime、defaultRuntime
│ ├─ rules/ # 起宫、布星、五行局、化曜等纯算法
│ ├─ services/ # calculateNatal/Palaces/Stars/Decade 等领域组合
│ ├─ pipelines/ # calculateNatalBySolar/Lunisolar 调度入口
│ ├─ models/ # createNatal/Palace/Star 等领域对象工厂
│ ├─ typings/ # 公共类型定义、VO 接口
│ ├─ utils/
│ │ ├─ calendar.ts # 日历换算(阳历/阴历)、闰月/子时策略、干支推导
│ │ ├─ trueSolarTime.ts # 真太阳时(NOAA 公式)
│ │ ├─ format.ts # 日期/时辰文本格式化
│ │ ├─ math.ts # wrapIndex 等数学辅助
│ │ ├─ memoize.ts # 轻量缓存辅助
│ │ └─ sexagenary.ts # 干支算法
│ ├─ sdk.ts # 默认 runtime 封装的 createZiWeiBy*
│ ├─ public.ts # 单一出口,聚合 re-export
│ └─ index.ts # re-export public.ts,供 bundler tree-shaking
└─ docs/ # 设计/架构文档(当前文件)
```
--------------------------------
### Import and Use Hour Ranges
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/api-reference/constants.md
Demonstrates how to import the HOUR_RANGES constant and access specific hour range strings using an index.
```typescript
import { HOUR_RANGES } from "@ziweijs/core";
const hourIndex = 2; // Yin hour
console.log(HOUR_RANGES[hourIndex]); // "03:00~04:59"
```
--------------------------------
### i18n Error Handling with onMissing Callback
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/api-reference/i18n.md
Illustrates how to configure the `onMissing` callback to handle cases where a translation key is not found. This example logs a warning and the languages that were attempted.
```typescript
const i18n = createI18n({
lang: "en",
resources: { en: { greeting: "Hello" } },
onMissing: (info) => {
console.warn(`Missing translation: ${info.key}`);
console.warn(`Languages tried: ${info.languagesTried.join(", ")}`);
},
});
i18n.$t("nonexistent.key"); // Logs warning, returns fallback text
```
--------------------------------
### Import Formatting Utilities
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/api-reference/utilities.md
Import functions for formatting solar and lunisolar dates into human-readable text.
```typescript
// Formatting
import { getSolarDateText, getLunisolarDateText } from "@ziweijs/core";
```
--------------------------------
### Custom Ziwei Runtime Configuration
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/INDEX.md
Create a custom runtime with specific configurations for date divisions, leap months, and star display. Use `createZiWeiRuntime` and pass it to the chart creation function.
```typescript
import {
createZiWeiRuntime,
createZiWeiI18n,
getGlobalConfigs,
createZiWeiBySolar,
} from "@ziweijs/core";
const i18n = createZiWeiI18n("zh-Hant"); // Traditional Chinese
const configs = {
...getGlobalConfigs(),
division: {
year: "spring", // Use 立春
month: "last", // Leap months to previous
day: "normal",
},
star: "onlyMajor", // Only 14 main stars
};
const runtime = createZiWeiRuntime({ i18n, configs });
const natal = createZiWeiBySolar(
{
name: "陈六",
gender: "Yin",
date: new Date(1985, 11, 25),
},
{ runtime }
);
```
--------------------------------
### Import Sexagenary Utility
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/api-reference/utilities.md
Import the function for calculating lunisolar dates from sexagenary information.
```typescript
// Sexagenary
import { calculateLunisolarDateBySexagenary } from "@ziweijs/core";
```
--------------------------------
### calculateLunisolarDateBySexagenary
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/api-reference/utilities.md
Converts a sexagenary (干支) date to lunisolar date. It requires the sexagenary date string and an options object specifying the start year of the 60-year cycle to search within.
```APIDOC
## calculateLunisolarDateBySexagenary
### Description
Converts a sexagenary (干支) date to lunisolar date. It requires the sexagenary date string and an options object specifying the start year of the 60-year cycle to search within.
### Method
```typescript
function calculateLunisolarDateBySexagenary(
sexagenaryDate: string,
options: { cycleStartYear: number }
): SexagenaryToLunisolarResult
```
### Parameters
#### Path Parameters
- **sexagenaryDate** (string) - Required - 8-character sexagenary format: `"甲子乙丑丙寅丁卯"`
- **options.cycleStartYear** (number) - Required - Start year of 60-year cycle to search within
### Returns
Object with:
- `solarTime` (SolarTime) — Corresponding solar time
- `lunarHour` (LunarHour) — Corresponding lunisolar time
### Throws
- `RangeError` if sexagenary date not found within the 60-year window
### Notes
- Since sexagenary dates repeat every 60 years, `cycleStartYear` is needed to resolve ambiguity
- Searches within the range `[cycleStartYear, cycleStartYear + 59]`
### Example
```typescript
import { calculateLunisolarDateBySexagenary } from "@ziweijs/core";
const result = calculateLunisolarDateBySexagenary(
"甲子乙丑丙寅丁卯",
{ cycleStartYear: 1984 }
);
console.log(result.solarTime); // Solar date
console.log(result.lunarHour); // Lunisolar date
```
```
--------------------------------
### SDK Functions
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/INDEX.md
Main entry points for creating natal charts using the Ziwei.js SDK.
```APIDOC
## SDK Functions
Main entry points for creating natal charts:
- **`createZiWeiBySolar(params, options)`** — Create chart from solar (Gregorian) date
- **`createZiWeiByLunisolar(params, options)`** — Create chart from lunisolar (Chinese calendar) date
- **`createZiWeiByStemBranch(params, options)`** — Create chart from stem-branch positions
- **`withZiWeiRuntime(options)`** — Scoped creator functions sharing custom runtime
- **`createZiWeiRuntime(options)`** — Create runtime context with dependencies
All functions return fully computed natal chart data or palace arrays.
```
--------------------------------
### withZiWeiRuntime
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/api-reference/sdk.md
Creates a scoped set of creator functions that share a custom runtime instance. This is beneficial for performing batch operations or ensuring consistency across multiple chart calculations.
```APIDOC
## withZiWeiRuntime
### Description
Creates a scoped set of creator functions sharing a custom runtime instance. Useful for batch operations or ensuring consistency across multiple charts.
### Method
```typescript
function withZiWeiRuntime(options?: CreateZiWeiOptions): {
createZiWeiBySolar(params: CreateZiWeiSolarParams): Natal;
createZiWeiByLunisolar(params: CreateZiWeiLunisolarParams): Natal;
}
```
### Parameters
#### Path Parameters
- **options** (CreateZiWeiOptions) - Optional - Runtime configuration (i18n, configs, now function)
### Returns
Object with two methods sharing the same runtime:
- `createZiWeiBySolar(params)` → `Natal`
- `createZiWeiByLunisolar(params)` → `Natal`
### Example
```typescript
import { withZiWeiRuntime } from "@ziweijs/core";
const creator = withZiWeiRuntime({ now: () => new Date(2000, 0, 1) });
const natal1 = creator.createZiWeiBySolar({
name: "Person A",
gender: "Yang",
date: new Date(1990, 5, 15),
});
const natal2 = creator.createZiWeiByLunisolar({
name: "Person B",
gender: "Yin",
date: "1990-5-15-8",
});
// Both use the same frozen reference time for consistent decade calculation
```
```
--------------------------------
### Calculate Lunisolar Date by Sexagenary
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/api-reference/utilities.md
Converts a sexagenary date to its corresponding lunisolar date. Requires a cycle start year to resolve 60-year ambiguities. Throws RangeError if the date is not found within the specified cycle.
```typescript
function calculateLunisolarDateBySexagenary(
sexagenaryDate: string,
options: { cycleStartYear: number }
): SexagenaryToLunisolarResult
```
```typescript
import { calculateLunisolarDateBySexagenary } from "@ziweijs/core";
const result = calculateLunisolarDateBySexagenary(
"甲子乙丑丙寅丁卯",
{ cycleStartYear: 1984 }
);
console.log(result.solarTime); // Solar date
console.log(result.lunarHour); // Lunisolar date
```
--------------------------------
### Integrate i18n with Ziwei Runtime
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/api-reference/i18n.md
Demonstrates how to create and use a Ziwei-specific i18n instance within the Ziwei runtime for localized output. Ensure the correct language code is provided during initialization.
```typescript
import { createZiWeiI18n } from "@ziweijs/core";
import { createZiWeiRuntime, createZiWeiBySolar } from "@ziweijs/core";
// Create Ziwei-specific i18n
const i18n = createZiWeiI18n("zh-Hant"); // Traditional Chinese
// Use in runtime
const runtime = createZiWeiRuntime({ i18n });
// Create chart
const natal = createZiWeiBySolar(
{
name: "Test",
gender: "Yang",
date: new Date(2000, 0, 1),
},
{ runtime }
);
console.log(natal.palaces[0].name); // "命宮" (Traditional Chinese)
```
--------------------------------
### Calculate Decade and Flowing Years
Source: https://github.com/lzm0x219/ziwei/blob/main/docs/core-architecture.md
Determines the current major cycle index using the runtime's current time or a reference date, then generates lists for the twelve major cycles and the starting points of flowing years for each palace.
```typescript
services/decade.calculateDecadeByDate(runtime.now() or options.referenceDate)
```
--------------------------------
### Source Organization Structure
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/architecture.md
Illustrates the directory structure and layering of the Ziwei project's core packages. Lower layers are independently testable and do not depend on higher layers.
```tree
packages/core/src/
├─ constants/ # Static enums & lookup tables
├─ rules/ # Pure calculation logic
├─ services/ # Domain composition
├─ pipelines/ # Input format handling
├─ models/ # Domain object factories
├─ infra/ # Config & i18n
├─ utils/ # General-purpose helpers
├─ typings/ # Type definitions
├─ context/ # Runtime container
├─ sdk.ts # Public SDK functions
├─ public.ts # Public re-exports
└─ index.ts # Entry point (re-exports public.ts)
```
--------------------------------
### Core SDK Functions
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/README.md
Provides functions for creating Ziwei charts from various date and positional inputs, as well as managing the runtime environment.
```APIDOC
## Core SDK Functions
### Description
Provides functions for creating Ziwei charts from various date and positional inputs, as well as managing the runtime environment.
### Functions
- `createZiWeiBySolar(solarDate: Date): ZiWeiChart`
- Creates a Ziwei chart from a solar date.
- `createZiWeiByLunisolar(lunisolarDate: LunisolarDate): ZiWeiChart`
- Creates a Ziwei chart from a lunisolar date.
- `createZiWeiByStemBranch(stemBranchPositions: StemBranchPositions): ZiWeiChart`
- Creates a Ziwei chart from stem-branch positions.
- `withZiWeiRuntime(options?: ZiWeiRuntimeOptions): ZiWeiRuntime`
- Manages runtime configuration and provides access to Ziwei functionalities.
- `createZiWeiRuntime(options?: ZiWeiRuntimeOptions): ZiWeiRuntime`
- Initializes and returns a Ziwei runtime instance.
```
--------------------------------
### Checking Ziwei Dou Shu Transformations
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/INDEX.md
Demonstrates how to retrieve and log the four transformations (Lu, Quan, Ke, Ji) for a specific palace, such as the Ming Palace, after creating a Ziwei object by solar input.
```typescript
const natal = createZiWeiBySolar({...});
const mingPalace = natal.palaces[0]; // 命宫
const [lu, quan, ke, ji] = mingPalace.flying(); // [禄, 权, 科, 忌]
console.log(`禄 in: ${lu}`);
console.log(`权 in: ${quan}`);
console.log(`科 in: ${ke}`);
console.log(`忌 in: ${ji}`);
```
--------------------------------
### Main Module Exports
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/api-reference/react-components.md
Exports the primary components for rendering Ziwei charts and simulations. Includes components for destiny boards and the main Ziwei chart, as well as a simulator for rapid testing.
```typescript
// Main components
export { default as DestinyBoard } from "./components/DestinyBoard";
export { default as ZiWei } from "./ZiWei";
export { ZiWeiSimulator } from "./ZiWeiSimulator";
// Colors
export * from "./theme/color";
```
--------------------------------
### Define StarType Type
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/types.md
Categorizes stars into major, minor, or miscellaneous types.
```typescript
type StarType = "major" | "minor" | "miscellaneous"
```
--------------------------------
### Import and Use Star Names
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/api-reference/constants.md
Shows how to import STAR_HANS and access the 'name' and 'abbr' properties of a specific star, like ZiWei.
```typescript
import { STAR_HANS, STAR_HANT } from "@ziweijs/core";
console.log(STAR_HANS.ZiWei.name); // "紫微"
console.log(STAR_HANS.ZiWei.abbr); // "紫"
```
--------------------------------
### Create Ziwei Natal Object
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/architecture.md
Demonstrates how to create a Ziwei Natal object using solar date input and access its properties.
```typescript
const natal = createZiWeiBySolar({
name: "张三",
gender: "Yang",
date: new Date(1990, 5, 15, 14, 30),
});
console.log(natal.palaces[0].flying());
```
--------------------------------
### React Components
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/README.md
Provides a set of React components for visualizing Ziwei Doushu charts and interactive exploration.
```APIDOC
## React Components
### Description
Provides a set of React components for visualizing Ziwei Doushu charts and interactive exploration.
### Core Components
- ``
- Main component for rendering a natal chart.
- ``
- Component for interactive exploration of charts.
- ``
- Core component responsible for rendering the destiny board.
### Supporting Components
- Sub-components
- Hooks
- Contexts
- Styling utilities.
```
--------------------------------
### Import True Solar Time Utility
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/api-reference/utilities.md
Import the function for calculating true solar time.
```typescript
// True solar time
import { calculateTrueSolarTime } from "@ziweijs/core";
```
--------------------------------
### Lookup Stem Transformations
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/api-reference/constants.md
Illustrates how to find transformation details for a given stem key using STEM_TRANSFORMATIONS.
```typescript
import { STEM_TRANSFORMATIONS } from "@ziweijs/core";
const stemKey = "Jia";
const transformations = STEM_TRANSFORMATIONS[stemKey];
// ["LianZhen" (禄), "PoJun" (权), "WuQu" (科), "TaiYang" (忌)]
```
--------------------------------
### Accessing Ziwei Runtime Configurations
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/configuration.md
Access configurations and i18n within a service using the Ziwei runtime context. This pattern ensures calculations respect configured options without tight coupling.
```typescript
import type { ZiWeiRuntime } from "@ziweijs/core";
export function exampleService(ctx: ZiWeiRuntime, data: any) {
const { configs } = ctx;
if (configs.star === "onlyMajor") {
console.log("Calculating major stars only");
}
const text = ctx.i18n.$t(`some.key`);
const currentTime = ctx.now();
}
```
--------------------------------
### Create Ziwei Chart by Solar Input
Source: https://github.com/lzm0x219/ziwei/blob/main/docs/core-architecture.md
Initiates the Ziwei chart calculation using solar date parameters. SDK calls this function, which then uses the default runtime to execute the necessary calculations.
```typescript
createZiWeiBySolar(params, options)
```
--------------------------------
### Helper Functions
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/README.md
Offers a collection of utility functions for mathematical operations, calendar calculations, date formatting, and more.
```APIDOC
## Helper Functions
### Description
Offers a collection of utility functions for mathematical operations, calendar calculations, date formatting, and more.
### Math Utilities
- `wrapIndex(index: number, max: number): number`
- `relativeIndex(base: number, target: number, max: number): number`
- `oppositeIndex(index: number, max: number): number`
### Calendar Utilities
- `calculateZiWeiDate(date: Date): ZiWeiDate`
- `calculateHourByIndex(index: number): Hour`
- Lunar conversions
### True Solar Time
- NOAA algorithm implementation for accurate solar time calculations.
### Formatting Utilities
- Date formatting
- Lunisolar formatting
### Sexagenary Utilities
- Sexagenary date parsing.
```
--------------------------------
### Rendering Ziwei Dou Shu with Custom Colors
Source: https://github.com/lzm0x219/ziwei/blob/main/_autodocs/INDEX.md
Shows how to import and use color constants for major stars and transformations from the '@ziweijs/react' library to create a custom color palette for consistent theming.
```typescript
import { COLOR_MAJOR_STARS, COLOR_TRANSFORMATIONS } from "@ziweijs/react";
// Use color constants for consistent theming
const palette = {
stars: COLOR_MAJOR_STARS,
transformations: COLOR_TRANSFORMATIONS,
};
```