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

memento-mock

v1.0.0

Published

Memento JavaScript Bridge Mock for development environment

Readme

memento-mock - Memento JavaScript Bridge Mock

用于在开发环境中模拟 Memento 应用的 JavaScript Bridge 环境,使前端项目可以在浏览器中独立开发和测试,无需依赖真实的 Memento 应用。

安装

方式一:NPM 安装(推荐)

npm install memento-mock --save-dev

方式二:本地构建

cd packages/memento-mock
npm install
npm run build

构建产物在 dist/ 目录下:

  • memento-mock.js - 浏览器 UMD 版本(未压缩)
  • memento-mock.min.js - 浏览器 UMD 版本(压缩)
  • index.js - CommonJS 模块
  • index.esm.js - ES Module

使用方法

1. 直接在 HTML 中通过 <script> 标签引入

开发环境:

<!DOCTYPE html>
<html>
<head>
  <title>My App</title>
</head>
<body>
  <!-- 仅在开发环境加载 Memento Mock -->
  <script src="node_modules/memento-mock/dist/memento-mock.js"></script>

  <!-- 或使用 CDN(如果发布到 CDN) -->
  <!-- <script src="https://unpkg.com/memento-mock@latest/dist/memento-mock.min.js"></script> -->

  <script>
    // Memento API 已自动注入到 window.Memento
    Memento.ready(() => {
      console.log('Memento is ready!');

      // 调用插件 API
      Memento.plugins.chat.sendMessage({ content: 'Hello' })
        .then(res => console.log(res));

      // 调用系统 API
      Memento.system.getDeviceInfo()
        .then(info => console.log(info));

      // 显示 Toast
      Memento.ui.toast('Hello Memento!');

      // 存储数据
      Memento.storage.write('myKey', { value: 123 });
    });
  </script>
</body>
</html>

生产环境(自动使用 Memento preload):

<!DOCTYPE html>
<html>
<head>
  <title>My App</title>
</head>
<body>
  <!-- 生产环境不引入 mock,直接使用 Memento 应用注入的 Bridge -->
  <script>
    Memento.ready(() => {
      // 相同的代码,在真实环境中运行
      Memento.plugins.chat.sendMessage({ content: 'Hello' });
    });
  </script>
</body>
</html>

2. 在现代前端项目中使用(Vite / Webpack / Create React App 等)

2.1 TypeScript + Vite 项目

安装依赖:

npm install memento-mock --save-dev

配置 Vite(vite.config.ts):

import { defineConfig } from 'vite';

export default defineConfig({
  // 仅在开发环境注入 Memento Mock
  define: {
    'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
  }
});

在入口文件中条件导入(main.ts / index.tsx):

// 仅在开发环境加载 Memento Mock
if (process.env.NODE_ENV === 'development' && typeof window.Memento === 'undefined') {
  import('memento-mock').then((module) => {
    module.default(); // 手动初始化
    console.log('Memento Mock loaded');
  });
}

// 应用代码
function App() {
  const handleClick = async () => {
    await Memento.ui.toast('Hello from Vite!');
    const info = await Memento.system.getDeviceInfo();
    console.log(info);
  };

  return <button onClick={handleClick}>Test Memento</button>;
}

类型支持(TypeScript):

创建 src/types/memento.d.ts

import type { MementoAPI } from 'memento-mock';

declare global {
  interface Window {
    Memento: MementoAPI;
  }
}

// 全局变量
declare const Memento: MementoAPI;

2.2 Webpack 项目

安装依赖:

npm install memento-mock --save-dev

配置 Webpack(webpack.config.js):

const webpack = require('webpack');

module.exports = {
  // ...
  plugins: [
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
    })
  ]
};

在入口文件中条件导入(index.js):

// 仅在开发环境加载 Memento Mock
if (process.env.NODE_ENV === 'development' && typeof window.Memento === 'undefined') {
  import('memento-mock').then((module) => {
    module.default();
    console.log('Memento Mock loaded');
  });
}

// 应用代码
document.querySelector('#btn').addEventListener('click', async () => {
  await Memento.ui.toast('Hello from Webpack!');
});

2.3 Create React App (CRA)

安装依赖:

npm install memento-mock --save-dev

在 src/index.tsx 中条件导入:

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

// CRA 自动设置 NODE_ENV
if (process.env.NODE_ENV === 'development' && typeof window.Memento === 'undefined') {
  import('memento-mock').then((module) => {
    module.default();
    console.log('Memento Mock loaded');

    // 在 Mock 加载完成后渲染应用
    const root = ReactDOM.createRoot(document.getElementById('root')!);
    root.render(<App />);
  });
} else {
  // 生产环境或 Memento 已存在
  const root = ReactDOM.createRoot(document.getElementById('root')!);
  root.render(<App />);
}

使用 Memento API(App.tsx):

import React from 'react';

function App() {
  const handleTest = async () => {
    // 等待 Memento 就绪
    Memento.ready(async () => {
      await Memento.ui.toast('Hello from React!');

      const deviceInfo = await Memento.system.getDeviceInfo();
      console.log('Device Info:', deviceInfo);

      await Memento.storage.write('lastVisit', new Date().toISOString());
      const lastVisit = await Memento.storage.read('lastVisit');
      console.log('Last Visit:', lastVisit);
    });
  };

  return (
    <div>
      <h1>My Memento App</h1>
      <button onClick={handleTest}>Test Memento API</button>
    </div>
  );
}

export default App;

2.4 Vue 3 + Vite 项目

安装依赖:

npm install memento-mock --save-dev

在 main.ts 中条件导入:

import { createApp } from 'vue';
import App from './App.vue';

// 仅在开发环境加载 Memento Mock
if (import.meta.env.DEV && typeof window.Memento === 'undefined') {
  import('@memento/mock').then((module) => {
    module.default();
    console.log('Memento Mock loaded');

    // 挂载应用
    createApp(App).mount('#app');
  });
} else {
  createApp(App).mount('#app');
}

使用 Memento API(App.vue):

<template>
  <div>
    <h1>My Memento App</h1>
    <button @click="handleTest">Test Memento API</button>
  </div>
</template>

<script setup lang="ts">
const handleTest = async () => {
  Memento.ready(async () => {
    await Memento.ui.toast('Hello from Vue!');

    const deviceInfo = await Memento.system.getDeviceInfo();
    console.log('Device Info:', deviceInfo);
  });
};
</script>

3. 使用本地构建的 dist 文件

如果没有发布到 npm,可以直接复制 dist/memento-mock.js 到项目中:

# 构建 npm 包
cd packages/memento-mock
npm install
npm run build

# 复制到其他项目
cp dist/memento-mock.js /path/to/your/project/public/

在项目中引用:

<script src="/memento-mock.js"></script>
<script>
  Memento.ready(() => {
    Memento.ui.toast('Hello!');
  });
</script>

API 说明

插件 API

// 调用任意插件的任意方法
Memento.plugins.<pluginId>.<methodName>(params)
  .then(response => {
    console.log(response.data);
  });

// 示例
Memento.plugins.chat.sendMessage({ content: 'Hello' });
Memento.plugins.diary.createEntry({ date: '2024-01-01', content: 'My diary' });

系统 API

Memento.system.getCurrentTime();        // 获取当前时间
Memento.system.getDeviceInfo();         // 获取设备信息
Memento.system.getAppInfo();            // 获取应用信息
Memento.system.formatDate({ date: new Date(), format: 'YYYY-MM-DD' });
Memento.system.getTimestamp();          // 获取时间戳
Memento.system.getCustomDate({ days: 7 }); // 获取相对日期

UI API

Memento.ui.toast('Message', { duration: 3000 });  // 显示 Toast
Memento.ui.alert('Alert message');                 // 显示警告
Memento.ui.dialog({                                // 显示对话框
  title: 'Confirm',
  message: 'Are you sure?',
  showCancel: true
}).then(result => {
  console.log(result.action); // 'ok' | 'cancel' | 'dismiss'
});

存储 API

await Memento.storage.write('key', { value: 123 });  // 写入数据
const data = await Memento.storage.read('key');      // 读取数据
await Memento.storage.delete('key');                 // 删除数据
await Memento.storage.clear();                       // 清空所有数据
const keys = await Memento.storage.keys();           // 获取所有键

工具 API

Memento.utils.log('Debug message');             // 日志
Memento.utils.error('Error message');           // 错误
Memento.utils.warn('Warning message');          // 警告
const state = Memento.utils.getStorageState();  // 获取存储状态
await Memento.utils.resetStorage();             // 重置存储

注意事项

  1. 仅用于开发环境:生产环境会自动使用 Memento 应用注入的真实 Bridge,不需要引入 Mock
  2. 数据持久化:Mock 使用 localStorage 模拟存储,数据前缀为 MementoMock_
  3. 类型支持:TypeScript 项目可以从 @memento/mock 导入类型定义
  4. 自动初始化:通过 <script> 标签加载时会自动初始化,模块化导入需要手动调用 initMementoMock()

License

MIT