npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@kivii.com/bridge

v1.1.9

Published

Kivii Bridge - A comprehensive toolkit library with request handling, logging, and utility functions

Readme

Kivii Bridge

一个轻量级的综合性工具库,提供请求处理、日志记录、配置管理等常用功能,支持依赖注入和模块化设计。

✨ 特性

  • 🚀 轻量级:核心库体积小,按需加载
  • 🔧 依赖注入:支持模块替换和扩展
  • 🪝 Hook 钩子:灵活的事件钩子系统,支持请求拦截和响应处理
  • 📦 多格式支持:UMD、ESM、CommonJS
  • 🌐 跨平台:支持浏览器和 Node.js 环境
  • Type*Script:完整的类型定义
  • 🛠️ 可扩展:模块化设计,易于扩展
  • 🎭 Mock 支持:内置 Mock 请求模块,轻松切换到测试数据
  • 📥 文件下载:支持进度监控、自动下载、表单下载、错误处理

📦 安装

pnpm

pnpm add "@kivii.com/bridge"

🚀 快速开始

浏览器环境

<!-- 使用 UMD 格式 -->
<script src="https://unpkg.com/@kivii.com/bridge/dist/kivii.bridge.min.js"></script>
<script>
  // 访问全局 Kivii 实例
  kivii.logger.info('应用已加载');
</script>

Vue 3 插件方式

import { createApp } from 'vue';
import App from './App.vue';
import { kivii } from '@kivii.com/bridge'; // 直接引入就能用,内部已经做全局声明window.kivii

const app = createApp(App);

app.mount('#app');

在组件中使用:

<script setup>
  // 发送请求
  const response = await kivii.request.send({
    url: '/api/data',
    method: 'GET',
  });

  // 下载文件
  const downloadFile = async () => {
    const result = await kivii.downloader.download({
      url: 'https://example.com/file.pdf',
      onProgress: progress => {
        console.log(`下载进度: ${progress.percentage}%`);
      },
    });
    console.log('下载完成:', result.filename);
  };
</script>

📁 目录结构

src/
├── core/                    # 核心模块
│   ├── Config.ts           # 配置管理器
│   └── Kivii.ts            # 主应用类
├── interfaces/             # 接口定义
│   ├── ILogger.ts          # 日志接口
│   ├── IRequest.ts         # 请求接口
│   └── index.ts            # 接口导出
├── modules/                # 实现模块
│   ├── AxiosRequest.ts     # Axios 请求实现
│   ├── MockRequest.ts      # Mock 请求实现
│   ├── Downloader.ts       # 文件下载实现
│   ├── ConsoleLogger.ts    # 控制台日志实现
│   └── index.ts            # 模块导出
├── config/                 # 默认配置
│   ├── logger.ts           # 日志配置
│   ├── request.ts          # 请求配置
│   └── index.ts            # 配置导出
├── utils/                  # 工具函数
├── examples/               # 使用示例
├── docs/                   # 文档
└── index.ts                # 入口文件

📚 核心功能

配置管理

// 初始化配置
kivii.config.init({
  request: {
    baseURL: 'https://api.example.com',
    timeout: 5000,
  },
  logger: {
    enabled: true,
    level: 'info',
  },
});

// 单独设置配置
kivii.config.set('version', '1.0.0');

// 获取配置
const baseURL = kivii.config.get('request.baseURL');
const appName = kivii.config.get('name');

📖 详细文档:配置管理 API

网络请求

// 示例一
kivii.request
  .send({
    url: 'ai/chat/test',
    method: 'POST',
    data: { message: 'Hello, world!' },
  })
  .then((res: any) => {
    console.log(res);
  })
  .catch((err: any) => {
    console.error(err);
  });

// 示例二
const response = await kivii.request.get('ai/chat/test');
console.log(response);

// 示例三 封装成方法后必须使用async
const getChatTest = async () => {
  return await kivii.request.get('ai/chat/test');
};
const response3 = await getChatTest(); // 或 getChatTest().then((res: any) => { console.log(res); })
console.log(response3);

错误处理(Request 模块)

当使用 kivii.request.send(...)kivii.request.get/post/... 时,库在遇到服务器返回非 2xx 状态码时会通过 Promise reject 抛出错误。为了兼顾标准 Error 语义与实用性,抛出的 Error 实例会在自身上附带服务端响应的详细信息,调用方可以直接访问这些字段来获取服务端返回体和状态。

当存在服务器响应时,Error 实例上通常会包含以下字段:

  • status:HTTP 状态码(例如 404
  • statusText:状态文本(例如 Not Found
  • data:服务端返回的响应体(通常为 JSON)
  • headers:响应头(已转换为普通对象)
  • config:请求的部分配置信息(urlmethodtimeout

注意:浏览器 DevTools 在打印 Error 时默认只展示 messagestack,不会自动把这些附加字段展开显示。调试时可以用下面的方式查看完整信息:

kivii.request.send({...})
  .then(res => console.log('Request response:', res))
  .catch(err => {
    // 以对象形式查看 Error,包含附加字段
    console.dir(err);
    // 或展开为普通对象以便控制台一目了然
    console.log('as plain obj', { ...err });
    console.log('status:', err.status);
    console.log('data:', err.data);
  });

📖 详细文档:Request 模块 API

日志记录

kivii.logger.debug('调试信息', { userId: 123 });
kivii.logger.info('应用启动成功');
kivii.logger.warn('警告信息');
kivii.logger.error('错误信息', new Error('Something went wrong'));

📖 详细文档:Logger 模块 API

Hook 钩子系统

// 配置式注册钩子
kivii.config.init({
  hooks: {
    // 请求前:添加认证令牌
    'request.before': config => {
      const token = localStorage.getItem('token');
      if (token) {
        config.headers = config.headers || {};
        config.headers.Authorization = `Bearer ${token}`;
      }
      return config;
    },

    // 响应后:处理 404
    'request.response.status:404': response => {
      response.data.message = '页面未找到';
      return response;
    },

    // 错误处理
    'request.error': error => {
      console.error('请求失败:', error.message);
      return error;
    },
  },
});

// 编程式注册钩子
kivii.hook.register('request.before', config => {
  console.log('发送请求:', config.method, config.url);
  return config;
});

kivii.hook.register('request.response', response => {
  console.log('响应已接收:', response.status);
  return response;
});

📖 详细文档:Hook 模块 API

Mock 请求

// main.ts
import kivii from '@kivii.com/bridge';
import { MockRequest, AxiosRequest } from '@kivii.com/bridge';

// 注册 MockRequest 模块
kivii.register(new MockRequest());

// 配置 mock 数据
kivii.config.set('mock', {
  api: {
    users: [
      { id: 1, name: 'John Doe', email: '[email protected]' },
      { id: 2, name: 'Jane Doe', email: '[email protected]' },
    ],
    test: ({ method, params, data }) => {
      // 自定义方法
    },
  },
});

// 使用 mock 数据发送请求
const response = await kivii.request.get('/api/users');
console.log(response.data); // [{ id: 1, name: 'John Doe', ... }, ...]

// 切换到真实请求直接在main.ts里注释 kivii.register(new MockRequest());

📖 详细文档:Mock 模块 API

文件下载

// 简单下载
const result = await kivii.downloader.download({
  url: 'https://example.com/file.pdf',
});

// 完整示例
const result = await kivii.downloader.download({
  url: '/Storages/Zip',
  method: 'POST',
  header: {
    Authorization: 'Bearer ',
  },
  params: {
    Kvids: '14D96D8B-E187-4DD3-99D2-AECD38695DA7',
    FolderPath: '/Certificate/Check/Files',
  },
  filename: '自定义文件名.zip', // 自定义文件名
  timeout: 30000, // 超时设置
  autoDownload: true, // 是否自动下载
  onProgress: progress => {
    console.log(`进度: ${progress.percentage}%`);
    console.log(`速度: ${progress.speed} bytes/s`);
  },
  onSuccess: result => {
    console.log(result);
  },
  onError: error => {
    console.log(error);
  },
});

// 表单方式下载(适用于需要 POST 数据的场景)
kivii.downloader.form({
  url: '/api/files/download', // 支持相对路径,会自动拼接 baseUrl
  method: 'POST',
  header: {
    Authorization: 'Bearer your-token-here',
  },
  data: {
    Kvids: '14D96D8B-E187-4DD3-99D2-AECD38695DA7',
    FolderPath: '/Certificate/Check/Files',
  },
});

📖 详细文档:Downloader 模块 API

依赖注入

import kivii from '@kivii.com/bridge';

// 自定义请求模块
class CustomRequest extends IRequest {
  async send(config) {
    const response = await fetch(config.url, {
      method: config.method,
      headers: config.headers,
      body: JSON.stringify(config.data),
    });
    return await response.json();
  }
}

// 注册自定义模块
kivii.register(new CustomRequest());

🧪 测试

项目使用 Jest 进行单元测试,测试覆盖率达到 95.61%

运行测试

# 运行所有测试
pnpm test

# 运行测试并生成覆盖率报告
pnpm test -- --coverage

# 监听模式运行测试
pnpm test:watch

详细测试文档请查看 测试文档

📖 文档索引

核心文档

快速链接