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

micro-iframe-bridge

v1.0.2

Published

A powerful iframe communication bridge for micro-frontend applications

Readme

@micro-comm/iframe-bridge

一个强大的 iframe 通信桥接器,专为微前端应用设计。

🚀 特性

  • 类型安全: 完整的 TypeScript 支持
  • 框架无关: 支持 React、Vue 等多种框架
  • 安全可靠: 内置消息验证和加密机制
  • 易于使用: 提供 Hook 和类两种使用方式
  • 功能丰富: 支持空间管理、用户认证、主题切换等
  • 插件系统: 支持自定义插件扩展
  • 性能优化: 消息队列、重试机制、错误处理

📦 安装

npm install @micro-comm/iframe-bridge
# 或
yarn add @micro-comm/iframe-bridge
# 或
pnpm add @micro-comm/iframe-bridge

🎯 快速开始

主应用 (Host App)

import { useHostComm } from '@micro-comm/iframe-bridge/react';

function App() {
  const {
    currentSpace,
    sendThemeChange,
    sendAuthCheck
  } = useHostComm({
    onSpaceEnter: (spaceInfo) => {
      console.log('用户进入空间:', spaceInfo);
      // 更新菜单或其他 UI
    },
    onSpaceExit: () => {
      console.log('用户退出空间');
      // 重置菜单
    },
    onUserLogin: (authInfo) => {
      console.log('用户登录:', authInfo);
    }
  });

  const handleThemeChange = () => {
    sendThemeChange({ mode: 'dark' }, 'child-app-name');
  };

  return (
    <div>
      <h1>主应用</h1>
      {currentSpace && <div>当前空间: {currentSpace.spaceName}</div>}
      <iframe 
        src="/child-app" 
        data-app-name="child-app-name"
      />
    </div>
  );
}

子应用 (Child App)

import { useChildComm } from '@micro-comm/iframe-bridge/react';

function ChildApp() {
  const {
    sendEnterSpace,
    sendExitSpace,
    sendUserLogin,
    currentTheme
  } = useChildComm({
    appName: 'child-app-name',
    onThemeChange: (theme) => {
      console.log('主题变化:', theme);
      // 应用新主题
    },
    onAuthCheck: (authData) => {
      console.log('认证检查:', authData);
      if (authData.requireAuth) {
        // 跳转到登录页
      }
    }
  });

  const handleEnterSpace = () => {
    sendEnterSpace({
      spaceId: '123',
      spaceName: '我的空间',
      tenantId: '456'
    });
  };

  const handleLogin = () => {
    sendUserLogin({
      token: 'jwt-token',
      userInfo: {
        userId: '123',
        username: 'john',
        displayName: 'John Doe'
      },
      expiresAt: Date.now() + 3600000
    });
  };

  return (
    <div style={{ theme: currentTheme?.mode }}>
      <h2>子应用</h2>
      <button onClick={handleEnterSpace}>进入空间</button>
      <button onClick={handleLogin}>用户登录</button>
    </div>
  );
}

📚 API 文档

主应用 API

useHostComm Hook

const {
  bridge,              // 桥接器实例
  isReady,            // 是否已初始化
  currentSpace,       // 当前空间信息
  currentUser,        // 当前用户信息
  connectedApps,      // 连接的子应用列表
  sendThemeChange,    // 发送主题变化
  sendAuthCheck,      // 发送认证检查
  addMiddleware,      // 添加中间件
  addPlugin          // 添加插件
} = useHostComm(config);

HostBridge 类

import { HostBridge } from '@micro-comm/iframe-bridge/host';

const bridge = new HostBridge({
  security: {
    allowedOrigins: ['https://child-app.com'],
    validateMessage: true
  },
  debug: true
});

// 注册事件处理器
bridge.on('onSpaceEnter', (spaceInfo) => {
  console.log('空间进入:', spaceInfo);
});

// 发送消息
await bridge.sendThemeChange({ mode: 'dark' }, 'child-app');

子应用 API

useChildComm Hook

const {
  bridge,              // 桥接器实例
  isReady,            // 是否已初始化
  isConnected,        // 是否已连接到主应用
  currentTheme,       // 当前主题配置
  requireAuth,        // 是否需要认证
  sendEnterSpace,     // 发送进入空间消息
  sendExitSpace,      // 发送退出空间消息
  sendUserLogin,      // 发送用户登录消息
  sendUserLogout,     // 发送用户登出消息
  sendTokenRefresh,   // 发送 Token 刷新消息
  sendRouteChange,    // 发送路由变化消息
  sendAppError       // 发送应用错误消息
} = useChildComm({
  appName: 'my-child-app'
});

ChildBridge 类

import { ChildBridge } from '@micro-comm/iframe-bridge/child';

const bridge = new ChildBridge({
  appName: 'my-child-app',
  targetOrigin: 'https://main-app.com'
});

// 发送进入空间消息
await bridge.sendEnterSpace({
  spaceId: '123',
  spaceName: '我的空间',
  tenantId: '456'
});

🔌 插件系统

内置插件

日志插件

import { LoggerPlugin } from '@micro-comm/iframe-bridge';

const loggerPlugin = new LoggerPlugin({
  logAllMessages: true,
  logPerformance: true,
  messageFilter: (message) => message.type !== 'HEARTBEAT'
});

bridge.addPlugin(loggerPlugin);

安全插件

import { SecurityPlugin } from '@micro-comm/iframe-bridge';

const securityPlugin = new SecurityPlugin({
  requireHttps: true,
  rateLimitPerSecond: 50,
  maxMessageSize: 1024 * 1024, // 1MB
  blockedMessageTypes: ['DANGEROUS_ACTION']
});

bridge.addPlugin(securityPlugin);

自定义插件

import { BridgePlugin } from '@micro-comm/iframe-bridge';

class CustomPlugin implements BridgePlugin {
  name = 'CustomPlugin';

  install(bridge) {
    bridge.use(async (message, next) => {
      // 自定义逻辑
      console.log('处理消息:', message);
      await next();
    });
  }

  uninstall(bridge) {
    // 清理逻辑
  }
}

bridge.addPlugin(new CustomPlugin());

🛡️ 安全特性

消息验证

const bridge = new HostBridge({
  security: {
    allowedOrigins: ['https://trusted-app.com'],
    validateMessage: true,
    enableEncryption: true,
    encryptionKey: 'your-secret-key'
  }
});

频率限制

const securityPlugin = new SecurityPlugin({
  rateLimitPerSecond: 100,  // 每秒最多100条消息
  detectSuspiciousActivity: true
});

消息过滤

const securityPlugin = new SecurityPlugin({
  allowedMessageTypes: [
    MessageType.ENTER_SPACE,
    MessageType.EXIT_SPACE,
    MessageType.USER_LOGIN
  ]
});

🔧 中间件

// 日志中间件
bridge.use(async (message, next) => {
  console.log('收到消息:', message);
  await next();
  console.log('消息处理完成');
});

// 认证中间件
bridge.use(async (message, next) => {
  if (needAuth(message.type) && !isAuthenticated()) {
    throw new Error('未认证');
  }
  await next();
});

// 性能监控中间件
bridge.use(async (message, next) => {
  const start = performance.now();
  await next();
  const duration = performance.now() - start;
  console.log(`消息处理耗时: ${duration}ms`);
});

📋 完整示例

查看 examples 目录获取完整的示例代码:

🤝 贡献

欢迎提交 Issue 和 Pull Request!

📄 许可证

MIT License