Compare commits

..
7 Commits
Author SHA1 Message Date
xrain e0754ad635 query 增加了自处理异常
Publish to npm / publish (push) Failing after 8s
2026-05-04 02:27:43 +08:00
xrain 39626de073 修复了退出登录 TOKEN没清空的问题
Publish to npm / publish (push) Failing after 14s
2026-05-04 00:15:23 +08:00
xrain 13c836b4ab 修改退出登录没带TOKEn
Publish to npm / publish (push) Failing after 14s
2026-05-03 23:11:55 +08:00
xrain 88be4210aa 修正文档 2026-04-26 10:44:40 +08:00
xrain 4257f72799 fix ci
Publish to npm / publish (push) Failing after 8s
2026-04-23 21:39:57 +08:00
xrain 46257ecf4a fix version 2026-04-23 21:39:38 +08:00
xrain a2f57bc419 增加了AppVersion
Publish to npm / publish (push) Failing after 12s
2026-04-23 20:16:38 +08:00
8 changed files with 1039 additions and 835 deletions
-2
View File
@@ -31,8 +31,6 @@ jobs:
run: npm ci run: npm ci
- name: Build - name: Build
env:
SimApiVersion: ${{ github.ref_name }}
run: npm run build run: npm run build
- name: Publish to npm - name: Publish to npm
-166
View File
@@ -1,166 +0,0 @@
# @simcu/simapi — AI 开发指南
> 面向 AI Agent 的代码结构说明,帮助理解、修改和扩展本库。
---
## 项目结构
```
simapi-vue/
├── src/
│ ├── types.ts # 类型定义,全部导出
│ ├── simapi.core.ts # 核心类 SimApiCore,零框架依赖
│ └── simapi.pinia.ts # Pinia StoreVue3 适配层
├── dist/ # 构建产物
├── package.json # exports: "." → core, "/pinia" → vue
├── vite.config.ts # 统一构建配置,生成 .mjs 和 .cjs
└── tsconfig.build.json # tsc 生成类型声明
```
---
## 核心类型(types.ts
```typescript
SimApiBaseResponse<T> // 标准响应 { code, message, data? }
SimApiOptions // configure() 入参 { debug?, auth?, api? }
SimApiAuthConfig // auth: { token_name, check_url, logout_url, login_url }
SimApiApiConfig // api: { endpoints, defaultEndpoint, businessCallback, responseCallback, timeout? }
SimApiBusinessCallback // { [code]: (data) => void },支持数字码或 'common'
```
---
## SimApiCoresimapi.core.ts
**职责**:纯 TS HTTP 客户端,基于原生 fetch API,不依赖任何框架。
**关键设计**
- **零依赖**:使用原生 fetch,无 axios 或其他 HTTP 库
- **无 Cookie**:所有请求使用 `credentials: 'omit'`,避免 CORS 问题
- **Token 传递**:通过请求头 `Token` 传递认证信息
- **超时控制**:通过 `fetchWithTimeout` 辅助函数实现
- `query()` 抛出异常的只有网络/HTTP 错误,业务错误码通过回调处理
- `isLoggedIn` 是 getter,基于 localStorage 中的 token 判断
- **版本号**`getVersion()` 返回的版本信息中,`uiSimApi` 由构建时注入的 `SimApiVersion` 填充,`uiApp` 由调用方的 `AppVersion` 填充(未注入时为 `0.0.0-develop`
**修改建议**
- 改请求方法(GET/PUT/DELETE):在 `fetchPost()` 内新增 `method` 参数分支,或新增 `fetchGet()`/`fetchPut()` 方法
- 改 Token 存储:替换 `localStorage``sessionStorage` 或内存变量,修改 `getToken()`/`setToken()`/`removeToken()`
- 改登录/登出逻辑:修改 `login()`/`logout()` 方法
- 改超时处理:修改 `fetchWithTimeout()` 函数
- **版本管理**:版本号通过 `declare const` 声明常量,构建时通过 Vite 的 `define` 注入。未指定时默认为 `0.0.0-develop`
**autoInit 设计约束**
- 仅读取 `window.simapi` 的顶级字段:`endpoints``defaultEndpoint``debug`
- 业务回调(`businessCallback`/`responseCallback`)不支持从 window 读取,必须在代码中通过 `setBusinessCallback` 注册
---
## Pinia Storesimapi.pinia.ts
**职责**Vue3 适配层,SimApiCore 的纯代理,不维护任何独立状态。
**关键设计**
- **无独立状态**:state 中只有一个 `_core` 实例,不维护 `debug``token` 等独立数据
- **单例 Core**:在 store state 中实例化 `SimApiCore`,整个应用共享一个实例
- **纯代理映射**:所有 getters 直接映射到 `this._core` 的属性,所有 actions 直接调用 `this._core` 的方法
- **响应式**:通过 Pinia 的响应式系统,当 core 状态变化时自动更新
**使用方式**
```typescript
// 任意组件
import { useSimApi } from '@simcu/simapi'
const api = useSimApi()
// 初始化(二选一)
// 方式一:从 window.simapi 读取
api.autoInit()
// 方式二:直接传入配置
api.configure({
api: { endpoints: { default: 'https://api.example.com' } },
})
// 所有方法与 SimApiCore 完全一致
await api.query('/users/list', { page: 1 })
```
---
## 构建流程
```
npm run build
→ vite build 输出 dist/index.mjs / index.cjs / pinia.mjs / pinia.cjs
→ tsc -p tsconfig.build.json 输出 *.d.ts 类型声明
```
**版本号注入:**
版本号通过 `vite.config.ts``define` 配置注入,从 npm config 读取:
```typescript
define: {
'SimApiVersion': JSON.stringify(process.env.npm_config_SimApiVersion || '0.0.0-develop'),
}
```
**本地构建示例:**
```bash
# 通过环境变量
# Windows PowerShell
$env:npm_config_SimApiVersion='1.0.0'; npm run build
# Linux/Mac
npm_config_SimApiVersion=1.0.0 npm run build
```
**GitHub Actions 自动发布:**
```yaml
env:
SimApiVersion: ${{ github.ref_name }}
run: npm run build
```
**dist 输出是平铺的**core 和 pinia 的编译产物全部在同一目录:
```
dist/
├── index.mjs # core ESM
├── index.cjs # core CJS
├── pinia.mjs # pinia ESM
├── pinia.cjs # pinia CJS
├── simapi.core.d.ts
├── simapi.pinia.d.ts
└── types.d.ts
```
---
## package.json exports
```json
".": { "import": "./dist/index.mjs", "types": "./dist/simapi.core.d.ts" }
"./pinia": { "import": "./dist/pinia.mjs", "types": "./dist/simapi.pinia.d.ts" }
```
---
## 注意事项
- Core 默认 `debug: true`,生产环境需手动 `configure({ debug: false })`
- `query()` 返回 `Promise<SimApiBaseResponse<T>>`code !== 200 时不 reject,通过 `businessCallback` 处理
- `login()` 成功后将 `result.data` 存入 localStorage
- **无 Cookie**:所有请求不发送 CookieToken 通过请求头传递
- **零依赖**:不需要安装 axios,使用原生 fetch
- 删除了 Angular 支持,如需恢复参考 git 历史
- **版本号管理**:使用 `declare const` + Vite `define` 注入
- **AppVersion** 不注入,留给调用方自己管理
+640 -286
View File
File diff suppressed because it is too large Load Diff
+18
View File
@@ -12,6 +12,7 @@
"tslib": "^2.3.0" "tslib": "^2.3.0"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "^25.6.0",
"concurrently": "^9.2.1", "concurrently": "^9.2.1",
"pinia": "^2.2.0", "pinia": "^2.2.0",
"typescript": "~5.9.3", "typescript": "~5.9.3",
@@ -433,6 +434,16 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/@types/node": {
"version": "25.6.0",
"resolved": "https://registry.npmjs.org/@types/node/-/node-25.6.0.tgz",
"integrity": "sha512-+qIYRKdNYJwY3vRCZMdJbPLJAtGjQBudzZzdzwQYkEPQd+PJGixUL5QfvCLDaULoLv+RhT3LDkwEfKaAkgSmNQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~7.19.0"
}
},
"node_modules/@vue/compiler-core": { "node_modules/@vue/compiler-core": {
"version": "3.5.32", "version": "3.5.32",
"resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.5.32.tgz", "resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.5.32.tgz",
@@ -1004,6 +1015,13 @@
"node": ">=14.17" "node": ">=14.17"
} }
}, },
"node_modules/undici-types": {
"version": "7.19.2",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.19.2.tgz",
"integrity": "sha512-qYVnV5OEm2AW8cJMCpdV20CDyaN3g0AjDlOGf1OW4iaDEx8MwdtChUp4zu4H0VP3nDRF/8RKWH+IPp9uW0YGZg==",
"dev": true,
"license": "MIT"
},
"node_modules/vite": { "node_modules/vite": {
"version": "5.4.21", "version": "5.4.21",
"resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz", "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz",
+1
View File
@@ -42,6 +42,7 @@
"tslib": "^2.3.0" "tslib": "^2.3.0"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "^25.6.0",
"concurrently": "^9.2.1", "concurrently": "^9.2.1",
"pinia": "^2.2.0", "pinia": "^2.2.0",
"typescript": "~5.9.3", "typescript": "~5.9.3",
+15 -7
View File
@@ -27,6 +27,8 @@ export type {
} from './types' } from './types'
declare const SimApiVersion: string; declare const SimApiVersion: string;
declare const AppVersion: string;
// ── Helper: Fetch with Timeout ──────────────────────────────────────── // ── Helper: Fetch with Timeout ────────────────────────────────────────
function fetchWithTimeout( function fetchWithTimeout(
@@ -88,11 +90,13 @@ export class SimApiCore {
defaultEndpoint: 'default', defaultEndpoint: 'default',
businessCallback: { businessCallback: {
401: () => localStorage.removeItem(this.auth.token_name), 401: () => localStorage.removeItem(this.auth.token_name),
common: () => {}, common: () => {
},
}, },
responseCallback: { responseCallback: {
success: (response: any) => response, success: (response: any) => response,
error: (_err: any) => {}, error: (_err: any) => {
},
}, },
timeout: 10000, timeout: 10000,
} }
@@ -203,7 +207,7 @@ export class SimApiCore {
*/ */
async getVersion(endpointName?: string): Promise<SimApiVersions> { async getVersion(endpointName?: string): Promise<SimApiVersions> {
const versions: SimApiVersions = { const versions: SimApiVersions = {
uiApp: '0.0.0-develop', uiApp: typeof AppVersion === 'undefined' ? "0.0.0-develop" : AppVersion,
uiSimApi: typeof SimApiVersion === 'undefined' ? "0.0.0-develop" : SimApiVersion, uiSimApi: typeof SimApiVersion === 'undefined' ? "0.0.0-develop" : SimApiVersion,
apiApp: '0.0.0', apiApp: '0.0.0',
apiSimApi: '0.0.0', apiSimApi: '0.0.0',
@@ -233,7 +237,8 @@ export class SimApiCore {
uri: string, uri: string,
params: any = {}, params: any = {},
endpointKey?: string, endpointKey?: string,
extraHeaders?: Record<string, string> extraHeaders?: Record<string, string>,
selfHandleError: boolean = false
): Promise<SimApiBaseResponse<T>> { ): Promise<SimApiBaseResponse<T>> {
const headers: Record<string, string> = {...extraHeaders, ...{}} const headers: Record<string, string> = {...extraHeaders, ...{}}
const queryId = this.genS4() const queryId = this.genS4()
@@ -267,11 +272,13 @@ export class SimApiCore {
const processedData = this.api.responseCallback.success(respData) as SimApiBaseResponse<T> const processedData = this.api.responseCallback.success(respData) as SimApiBaseResponse<T>
// 业务回调处理 // 业务回调处理
if (!selfHandleError) {
if (this.api.businessCallback.hasOwnProperty(processedData.code)) { if (this.api.businessCallback.hasOwnProperty(processedData.code)) {
this.api.businessCallback[processedData.code](processedData) this.api.businessCallback[processedData.code](processedData)
} else if (this.api.businessCallback['common'] && processedData.code !== 200) { } else if (this.api.businessCallback['common'] && processedData.code !== 200) {
this.api.businessCallback['common'](processedData) this.api.businessCallback['common'](processedData)
} }
}
// code != 200 时抛出业务错误 // code != 200 时抛出业务错误
if (processedData.code !== 200) { if (processedData.code !== 200) {
@@ -306,16 +313,17 @@ export class SimApiCore {
} }
async logout(url?: string | null): Promise<any> { async logout(url?: string | null): Promise<any> {
this.removeToken()
if (url !== null) { if (url !== null) {
return this.query(url ?? this.auth.logout_url).catch(() => true) this.query(url ?? this.auth.logout_url).catch(() => true)
} }
this.removeToken()
return true return true
} }
async checkLogin(url?: string | null): Promise<void> { async checkLogin(url?: string | null): Promise<void> {
if (url !== null) { if (url !== null) {
await this.query(url ?? this.auth.check_url).catch(() => {}) await this.query(url ?? this.auth.check_url).catch(() => {
})
} else if (this.getToken()) { } else if (this.getToken()) {
this.api.businessCallback[401]?.(null) this.api.businessCallback[401]?.(null)
} }
+3 -2
View File
@@ -73,9 +73,10 @@ export const useSimApi = defineStore('simapi', {
uri: string, uri: string,
params?: any, params?: any,
endpointKey?: string, endpointKey?: string,
extraHeaders?: Record<string, string> extraHeaders?: Record<string, string>,
selfHandleError: boolean = false
): Promise<SimApiBaseResponse<T>> { ): Promise<SimApiBaseResponse<T>> {
return this._core.query<T>(uri, params, endpointKey, extraHeaders) return this._core.query<T>(uri, params, endpointKey, extraHeaders, selfHandleError)
}, },
getEndpoint(name?: string): string { getEndpoint(name?: string): string {
+4 -14
View File
@@ -1,8 +1,7 @@
import { defineConfig, loadEnv } from 'vite' import { defineConfig } from 'vite'
import { readFileSync } from 'node:fs'
const pkg = JSON.parse(readFileSync('./package.json', 'utf-8'))
export default defineConfig(({ mode }) => { export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd())
return { return {
build: { build: {
outDir: 'dist', outDir: 'dist',
@@ -31,16 +30,7 @@ export default defineConfig(({ mode }) => {
} }
}, },
define: { define: {
// SimApiVersion 由环境变量注入,支持: SimApiVersion: JSON.stringify(pkg.version)
// - VITE_SimApiVersion (Vite .env 文件)
// - npm_config_SimApiVersion (npm 构建时)
// - SimApiVersion (直接环境变量,如 GitHub Actions)
'SimApiVersion': JSON.stringify(
env.VITE_SimApiVersion ||
process.env.npm_config_SimApiVersion ||
process.env.SimApiVersion ||
'0.0.0-develop'
),
} }
} }
}) })