vite-plugin-refresh-guard 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/LICENSE +21 -0
- package/README.md +149 -0
- package/SKILL.md +54 -0
- package/dist/checker-gSSR0d-T.d.ts +38 -0
- package/dist/chunk-ULA5FWKW.js +116 -0
- package/dist/client.d.ts +9 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.js +79 -0
- package/dist/react/UpdatePrompt.d.ts +15 -0
- package/dist/react/UpdatePrompt.js +91 -0
- package/dist/react/useVersionCheck.d.ts +21 -0
- package/dist/react/useVersionCheck.js +40 -0
- package/dist/types-DaLsj7ZU.d.ts +48 -0
- package/dist/vue/UpdatePrompt.vue +108 -0
- package/dist/vue/useVersionCheck.d.ts +22 -0
- package/dist/vue/useVersionCheck.js +33 -0
- package/package.json +88 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## v0.1.0 (2026-08-09)
|
|
4
|
+
|
|
5
|
+
Initial release.
|
|
6
|
+
|
|
7
|
+
- Vite plugin: emits `version.json` at build time, bakes `__REFRESH_GUARD_VERSION__` into the bundle, optional `virtual:refresh-guard-changelog` module
|
|
8
|
+
- Framework-agnostic `UpdateChecker` core: polling + visibility re-check + stale-chunk guard + reload-loop cooldown
|
|
9
|
+
- Three configurable modes: `silent`, `toast-auto` (default), `modal-blocking`
|
|
10
|
+
- Vue composable + `UpdatePrompt.vue`
|
|
11
|
+
- React hook + `UpdatePrompt` component
|
|
12
|
+
- `notifyExternalUpdate()` escape hatch to drive the same mode logic from `vite-plugin-pwa`'s `onNeedRefresh` or any other external signal
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 webkubor
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
# vite-plugin-refresh-guard
|
|
2
|
+
|
|
3
|
+
[](https://github.com/webkubor/vite-plugin-refresh-guard/actions/workflows/ci.yml)
|
|
4
|
+
[](https://www.npmjs.com/package/vite-plugin-refresh-guard)
|
|
5
|
+
[](./LICENSE)
|
|
6
|
+
[](https://vitejs.dev)
|
|
7
|
+
[](https://vuejs.org)
|
|
8
|
+
[](https://react.dev)
|
|
9
|
+
|
|
10
|
+
Configurable "there's a new version, here's what happens next" for Vite apps.
|
|
11
|
+
|
|
12
|
+
Most projects that solve this end up with one of three answers, usually picked by accident and
|
|
13
|
+
never revisited:
|
|
14
|
+
|
|
15
|
+
- **Silent** — just refresh in the background, the user never notices.
|
|
16
|
+
- **Toast, then auto-refresh** — a small non-blocking notice, then refresh after a short delay.
|
|
17
|
+
- **Blocking modal** — stop the user, make them click "update now" before they can continue.
|
|
18
|
+
|
|
19
|
+
This package makes that an explicit, per-project choice instead of copy-pasted glue code that
|
|
20
|
+
drifts every time someone touches it. Framework-agnostic core, thin Vue and React adapters.
|
|
21
|
+
|
|
22
|
+
## Install
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
npm i -D vite-plugin-refresh-guard
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
`vue`, `react`/`react-dom`, and `vite` are peer dependencies — install whichever you actually use.
|
|
29
|
+
|
|
30
|
+
## Quick start
|
|
31
|
+
|
|
32
|
+
**`vite.config.ts`**
|
|
33
|
+
|
|
34
|
+
```ts
|
|
35
|
+
import { defineConfig } from 'vite'
|
|
36
|
+
import { refreshGuard } from 'vite-plugin-refresh-guard'
|
|
37
|
+
|
|
38
|
+
export default defineConfig({
|
|
39
|
+
plugins: [refreshGuard()],
|
|
40
|
+
})
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
This does two things at build time:
|
|
44
|
+
1. Writes `version.json` into your build output (`{ version, buildId, commit, time }`).
|
|
45
|
+
2. Bakes the current version into your bundle as a global, `__REFRESH_GUARD_VERSION__`.
|
|
46
|
+
|
|
47
|
+
**Vue**
|
|
48
|
+
|
|
49
|
+
```vue
|
|
50
|
+
<script setup lang="ts">
|
|
51
|
+
import { useVersionCheck } from 'vite-plugin-refresh-guard/vue'
|
|
52
|
+
import UpdatePrompt from 'vite-plugin-refresh-guard/vue/UpdatePrompt.vue'
|
|
53
|
+
|
|
54
|
+
const { hasUpdate, latestInfo, applyUpdate, mode } = useVersionCheck(__REFRESH_GUARD_VERSION__, {
|
|
55
|
+
mode: 'toast-auto', // 'silent' | 'toast-auto' | 'modal-blocking'
|
|
56
|
+
})
|
|
57
|
+
</script>
|
|
58
|
+
|
|
59
|
+
<template>
|
|
60
|
+
<UpdatePrompt :visible="hasUpdate" :mode="mode" :version="latestInfo?.version" @refresh="applyUpdate" />
|
|
61
|
+
</template>
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
**React**
|
|
65
|
+
|
|
66
|
+
```tsx
|
|
67
|
+
import { useVersionCheck } from 'vite-plugin-refresh-guard/react'
|
|
68
|
+
import { UpdatePrompt } from 'vite-plugin-refresh-guard/react/UpdatePrompt'
|
|
69
|
+
|
|
70
|
+
function App() {
|
|
71
|
+
const { hasUpdate, latestInfo, applyUpdate, mode } = useVersionCheck(__REFRESH_GUARD_VERSION__, {
|
|
72
|
+
mode: 'modal-blocking',
|
|
73
|
+
})
|
|
74
|
+
return <UpdatePrompt visible={hasUpdate} mode={mode} version={latestInfo?.version} onRefresh={applyUpdate} />
|
|
75
|
+
}
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Add `/// <reference types="vite-plugin-refresh-guard/client" />` to your `env.d.ts` (or wherever
|
|
79
|
+
your other `vite/client` reference lives) so TypeScript knows about `__REFRESH_GUARD_VERSION__`.
|
|
80
|
+
|
|
81
|
+
Don't want the prebuilt UI? Use `useVersionCheck`'s `hasUpdate`/`latestInfo`/`applyUpdate` and
|
|
82
|
+
render your own — the components are a starting point, not a requirement.
|
|
83
|
+
|
|
84
|
+
## Picking a mode
|
|
85
|
+
|
|
86
|
+
| Mode | User sees | When to use it |
|
|
87
|
+
|---|---|---|
|
|
88
|
+
| `silent` | Nothing. Refreshes in the background. | Internal tools, dashboards nobody's mid-task in. Pairs well with `vite-plugin-pwa`'s own `registerType: 'autoUpdate'` doing the same job at the service-worker level — you may not need this package's polling at all in that case, just wire `notifyExternalUpdate()` (see below) if you want changelog display too. |
|
|
89
|
+
| `toast-auto` (default) | A small corner notice, then refresh after `autoRefreshDelay` (default 1.2s). | Most consumer-facing apps. Gives the user a beat to notice, doesn't block them. |
|
|
90
|
+
| `modal-blocking` | A centered, non-dismissible prompt. Refresh only on click. | Apps where refreshing mid-task loses real work (a half-filled form, an in-progress upload), or where you want confirmation before applying (matches what we found in ModelGo's console app). |
|
|
91
|
+
|
|
92
|
+
You're not locked into version.json polling only — `checker.notifyExternalUpdate(info)` (also
|
|
93
|
+
exposed by both adapters) feeds an update signal from anywhere else into the same mode logic,
|
|
94
|
+
most usefully from `vite-plugin-pwa`'s `registerSW({ onNeedRefresh })` callback if you're also
|
|
95
|
+
running a service worker and want its update event to drive the same toast/modal instead of
|
|
96
|
+
(or in addition to) polling.
|
|
97
|
+
|
|
98
|
+
## Options
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
interface VersionCheckerOptions {
|
|
102
|
+
versionUrl?: string // default '/version.json'
|
|
103
|
+
interval?: number // default 5 minutes; 0 disables polling
|
|
104
|
+
checkOnVisible?: boolean // re-check on tab focus, default true
|
|
105
|
+
mode?: 'silent' | 'toast-auto' | 'modal-blocking' // default 'toast-auto'
|
|
106
|
+
autoRefreshDelay?: number // toast-auto only, default 1200ms
|
|
107
|
+
refreshCooldown?: number // min ms between forced refreshes, default 90s — guards against reload loops
|
|
108
|
+
guardChunkErrors?: boolean // force-refresh once on a stale-chunk load failure, default true
|
|
109
|
+
onUpdateAvailable?: (info) => void | boolean // return false to take over the UI yourself
|
|
110
|
+
onBeforeRefresh?: () => void // flush analytics etc. right before location.reload()
|
|
111
|
+
}
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
Plugin options (`refreshGuard({ ... })`):
|
|
115
|
+
|
|
116
|
+
```ts
|
|
117
|
+
interface RefreshGuardPluginOptions {
|
|
118
|
+
version?: string // default: read from package.json
|
|
119
|
+
includeCommit?: boolean // default true; silently omitted outside a git repo
|
|
120
|
+
outFile?: string // default 'version.json'
|
|
121
|
+
changelog?: string | false // default 'CHANGELOG.md'; false disables the virtual module
|
|
122
|
+
}
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
## Changelog display (optional, decoupled from the refresh decision)
|
|
126
|
+
|
|
127
|
+
```ts
|
|
128
|
+
import { latestVersion, latestContent } from 'virtual:refresh-guard-changelog'
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
Parses `## vX.Y.Z (date)` headings (same format as Keep a Changelog / most auto-generated
|
|
132
|
+
changelogs) out of your `CHANGELOG.md` and exposes the latest section's version and markdown
|
|
133
|
+
body. This is independent of the refresh-trigger logic on purpose — showing "what's new" and
|
|
134
|
+
deciding "when do we reload" are different product decisions, and coupling them (as several
|
|
135
|
+
of the projects this package was extracted from originally did) is how you end up with two
|
|
136
|
+
mechanisms fighting each other.
|
|
137
|
+
|
|
138
|
+
## Why not just service workers?
|
|
139
|
+
|
|
140
|
+
`vite-plugin-pwa`'s `autoUpdate` mode is a perfectly good `silent` implementation if you're
|
|
141
|
+
already running a service worker — this package doesn't replace that. What it adds is: a
|
|
142
|
+
uniform way to also get a `toast-auto` or `modal-blocking` experience (which a bare service
|
|
143
|
+
worker can't give you a clean hook for without writing this exact plumbing yourself), a
|
|
144
|
+
non-PWA `version.json`-polling fallback for apps that don't want a service worker at all, and
|
|
145
|
+
the changelog-display layer. Use whichever pieces you need; they're independent.
|
|
146
|
+
|
|
147
|
+
## License
|
|
148
|
+
|
|
149
|
+
MIT
|
package/SKILL.md
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: refresh-guard
|
|
3
|
+
description: "vite-plugin-refresh-guard 的 agent 接入手册。给 Vite 前端项目加'检测新版本部署→通知→刷新'机制,三档强度可选(静默自动刷新 / toast提示+短延迟自动刷新 / 弹窗阻断必须手动点击),核心逻辑框架无关,Vue/React 各有一份薄适配层,另附一个独立可选的 CHANGELOG.md 展示层。在 Vite 项目里需要处理'部署新版本后用户还在用旧代码/旧chunk 404 白屏'问题,或者想把项目里手写的一次性 version-check 脚本换成可维护的通用方案时用这个。"
|
|
4
|
+
version: 0.1.0
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
# vite-plugin-refresh-guard
|
|
8
|
+
|
|
9
|
+
给 Vite 项目解决"部署了新版本,怎么让还开着页面的用户用上"这件事,把强度做成显式可配置的三档,而不是每个项目各写一份、后来者猜不透为什么这么写。
|
|
10
|
+
|
|
11
|
+
## 何时用
|
|
12
|
+
|
|
13
|
+
- 项目里散落着"轮询 version.json 强刷" / "监听 SW onNeedRefresh 弹窗" 这类手写代码,想统一成一套可维护的方案
|
|
14
|
+
- 用户反馈"部署后页面白屏 / 报 ChunkLoadError / 点按钮没反应"——大概率是旧 HTML 引用了新部署已经删掉的带 hash 的 JS/CSS 文件,需要接一个"检测到旧 chunk 加载失败就强刷"的兜底
|
|
15
|
+
- 新起一个 Vite 项目,问"要不要做版本更新提示"这类问题时,可以直接推荐并接入这个方案,不用现场设计
|
|
16
|
+
- 排查"弹了两次更新提示"或"刷新死循环"这类 bug——本包自带 `refreshCooldown` 防抖,检查是不是绕开了这层直接调 `location.reload()`
|
|
17
|
+
|
|
18
|
+
## 三档怎么选(不确定选哪个就问用户,别替他们决定)
|
|
19
|
+
|
|
20
|
+
- `silent`:用户无感,静默刷新。适合内部工具、没人会在页面上"正在做一半的事"的场景。如果项目已经在用 `vite-plugin-pwa` 的 `registerType:'autoUpdate'`,这一档可能根本不需要——service worker 自己就会做,本包这时候只用来接 changelog 展示层就够了
|
|
21
|
+
- `toast-auto`(默认):右下角小提示 + 短延迟(默认1.2s)自动刷新。大多数 to-C 产品用这个,给用户一个"哦要刷新了"的心理准备,但不打断
|
|
22
|
+
- `modal-blocking`:居中弹窗,不可点遮罩关闭,必须点"立即更新"才刷新。适合"刷新会丢失用户没保存的东西"的场景(表单填一半、正在上传)
|
|
23
|
+
|
|
24
|
+
## 接入步骤
|
|
25
|
+
|
|
26
|
+
1. 装包:`npm i -D vite-plugin-refresh-guard`(`vue`/`react`+`react-dom` 按项目实际技术栈装,都是可选 peerDependency)
|
|
27
|
+
|
|
28
|
+
2. `vite.config.ts` 加插件:
|
|
29
|
+
```ts
|
|
30
|
+
import { refreshGuard } from 'vite-plugin-refresh-guard'
|
|
31
|
+
export default defineConfig({ plugins: [refreshGuard()] })
|
|
32
|
+
```
|
|
33
|
+
这一步在构建期做两件事:产出 `version.json`(带 version/buildId/commit/time),并把当前版本号烘焙成全局常量 `__REFRESH_GUARD_VERSION__`。**只在 `vite build` 生效,`vite dev` 下不会生成 `version.json`**——这是预期行为,dev 模式已经有 HMR,不需要这套。
|
|
34
|
+
|
|
35
|
+
3. 应用入口按框架接一层(Vue 用 `vite-plugin-refresh-guard/vue` + `UpdatePrompt.vue`,React 用 `vite-plugin-refresh-guard/react` + `UpdatePrompt`),具体代码见 README「Quick start」——**不要自己抄一遍逻辑,直接 import 用**。
|
|
36
|
+
|
|
37
|
+
4. TypeScript 项目在 `env.d.ts`(或已有 `vite/client` reference 的地方)加一行:
|
|
38
|
+
```ts
|
|
39
|
+
/// <reference types="vite-plugin-refresh-guard/client" />
|
|
40
|
+
```
|
|
41
|
+
否则 `__REFRESH_GUARD_VERSION__` 和 `virtual:refresh-guard-changelog` 会报类型找不到。
|
|
42
|
+
|
|
43
|
+
5. 项目已经在用 `vite-plugin-pwa` 且想要它的更新事件也走同一套 UI(而不是让 SW 自己默默 autoUpdate):在 `registerSW({ onNeedRefresh })` 回调里调用 `checker.notifyExternalUpdate()`(Vue/React 的 `useVersionCheck()` 返回值里都有这个方法),别再另外接一套弹窗逻辑。
|
|
44
|
+
|
|
45
|
+
## 常见误用(帮用户避坑)
|
|
46
|
+
|
|
47
|
+
- **不要**在 `mode: 'modal-blocking'` 的弹窗外面又加一个背景点击关闭——设计上就是不可关闭的,加了等于白做这一档
|
|
48
|
+
- **不要**绕开 `checker.applyUpdate()` 直接手写 `location.reload()`——会跳过 `refreshCooldown` 防抖,遇到 `version.json` 缓存配置有问题时容易刷新死循环
|
|
49
|
+
- **不要**把"版本更新提示"和"CHANGELOG 展示"强行绑死成一套逻辑——这俩是两码事(一个决定"要不要刷新",一个决定"给用户看什么"),本包故意拆成独立的 `virtual:refresh-guard-changelog` 虚拟模块,各用各的,不想要 changelog 就在插件配置里 `changelog: false`
|
|
50
|
+
- 项目里如果已经有 `vite-plugin-pwa` 的 `autoUpdate` 在跑,别再叠加本包的 `interval` 轮询去做同一件"静默刷新"的事——两套机制同时静默触发过,历史上就出过"到底是谁刷新的"排查不清的问题,选一个就好
|
|
51
|
+
|
|
52
|
+
## 参考实现来源
|
|
53
|
+
|
|
54
|
+
三档强度分别对应三个真实项目里各自演化出来的做法(2026-08-09 调研整理):`silent` 参考自某电商后台的 `vite-plugin-pwa autoUpdate`;`toast-auto` 参考自某内容平台的手写 `version.js` 轮询+短延迟刷新;`modal-blocking` 参考自某控制台产品的 SW+轮询双保险+强制弹窗(三层抽象里做得最完整的一版,是本包 core/checker.ts 状态机设计的主要参照)。
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { V as VersionCheckerOptions, a as VersionInfo, b as UpdateEvent, c as UpdateListener } from './types-DaLsj7ZU.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Framework-agnostic engine: polls (or is told about) a new version, decides whether to refresh
|
|
5
|
+
* based on `mode`, and guards against reload loops / stale-chunk white-screens. Vue/React
|
|
6
|
+
* adapters are thin wrappers around this — use it directly if you're on something else.
|
|
7
|
+
*/
|
|
8
|
+
declare class UpdateChecker {
|
|
9
|
+
private opts;
|
|
10
|
+
private currentVersion;
|
|
11
|
+
private timer;
|
|
12
|
+
private autoRefreshTimer;
|
|
13
|
+
private listeners;
|
|
14
|
+
private _hasUpdate;
|
|
15
|
+
private _latestInfo;
|
|
16
|
+
private visibilityHandler;
|
|
17
|
+
private chunkErrorHandler;
|
|
18
|
+
/** @param currentVersion The version baked into *this* running build (e.g. `__APP_VERSION__` from your Vite define, or package.json version). */
|
|
19
|
+
constructor(currentVersion: string, options?: VersionCheckerOptions);
|
|
20
|
+
get hasUpdate(): boolean;
|
|
21
|
+
get latestInfo(): VersionInfo | null;
|
|
22
|
+
start(): void;
|
|
23
|
+
stop(): void;
|
|
24
|
+
/** Fetch versionUrl now and react if it differs from the running build. Returns whether an update was found. */
|
|
25
|
+
checkNow(): Promise<boolean>;
|
|
26
|
+
/**
|
|
27
|
+
* Feed an update signal from somewhere other than version.json polling — most commonly
|
|
28
|
+
* vite-plugin-pwa's `onNeedRefresh` callback. Goes through the same mode logic as checkNow().
|
|
29
|
+
*/
|
|
30
|
+
notifyExternalUpdate(info?: VersionInfo): void;
|
|
31
|
+
private handleUpdateFound;
|
|
32
|
+
/** Force the refresh now (what 'modal-blocking' UIs call on button click). Respects the cooldown guard. */
|
|
33
|
+
applyUpdate(): void;
|
|
34
|
+
on(event: UpdateEvent, listener: UpdateListener): () => void;
|
|
35
|
+
private emit;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export { UpdateChecker as U };
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
// src/core/checker.ts
|
|
2
|
+
var DEFAULTS = {
|
|
3
|
+
versionUrl: "/version.json",
|
|
4
|
+
interval: 5 * 60 * 1e3,
|
|
5
|
+
checkOnVisible: true,
|
|
6
|
+
mode: "toast-auto",
|
|
7
|
+
autoRefreshDelay: 1200,
|
|
8
|
+
refreshCooldown: 90 * 1e3,
|
|
9
|
+
guardChunkErrors: true
|
|
10
|
+
};
|
|
11
|
+
var COOLDOWN_KEY = "__refresh_guard_last_refresh__";
|
|
12
|
+
var CHUNK_ERROR_PATTERN = /error loading dynamically imported module|failed to fetch dynamically imported module/i;
|
|
13
|
+
var UpdateChecker = class {
|
|
14
|
+
/** @param currentVersion The version baked into *this* running build (e.g. `__APP_VERSION__` from your Vite define, or package.json version). */
|
|
15
|
+
constructor(currentVersion, options = {}) {
|
|
16
|
+
this.timer = null;
|
|
17
|
+
this.autoRefreshTimer = null;
|
|
18
|
+
this.listeners = /* @__PURE__ */ new Map();
|
|
19
|
+
this._hasUpdate = false;
|
|
20
|
+
this._latestInfo = null;
|
|
21
|
+
this.visibilityHandler = () => {
|
|
22
|
+
if (document.visibilityState === "visible") void this.checkNow();
|
|
23
|
+
};
|
|
24
|
+
this.chunkErrorHandler = (event) => {
|
|
25
|
+
const message = "reason" in event ? String(event.reason?.message || event.reason) : "";
|
|
26
|
+
if (event.type === "vite:preloadError" || CHUNK_ERROR_PATTERN.test(message)) {
|
|
27
|
+
event.preventDefault?.();
|
|
28
|
+
this.applyUpdate();
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
this.currentVersion = currentVersion;
|
|
32
|
+
this.opts = { ...DEFAULTS, ...options };
|
|
33
|
+
}
|
|
34
|
+
get hasUpdate() {
|
|
35
|
+
return this._hasUpdate;
|
|
36
|
+
}
|
|
37
|
+
get latestInfo() {
|
|
38
|
+
return this._latestInfo;
|
|
39
|
+
}
|
|
40
|
+
start() {
|
|
41
|
+
if (typeof window === "undefined") return;
|
|
42
|
+
if (this.opts.interval > 0) {
|
|
43
|
+
this.timer = setInterval(() => void this.checkNow(), this.opts.interval);
|
|
44
|
+
}
|
|
45
|
+
if (this.opts.checkOnVisible) {
|
|
46
|
+
document.addEventListener("visibilitychange", this.visibilityHandler);
|
|
47
|
+
}
|
|
48
|
+
if (this.opts.guardChunkErrors) {
|
|
49
|
+
window.addEventListener("vite:preloadError", this.chunkErrorHandler);
|
|
50
|
+
window.addEventListener("unhandledrejection", this.chunkErrorHandler);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
stop() {
|
|
54
|
+
if (this.timer) clearInterval(this.timer);
|
|
55
|
+
if (this.autoRefreshTimer) clearTimeout(this.autoRefreshTimer);
|
|
56
|
+
document.removeEventListener("visibilitychange", this.visibilityHandler);
|
|
57
|
+
window.removeEventListener("vite:preloadError", this.chunkErrorHandler);
|
|
58
|
+
window.removeEventListener("unhandledrejection", this.chunkErrorHandler);
|
|
59
|
+
}
|
|
60
|
+
/** Fetch versionUrl now and react if it differs from the running build. Returns whether an update was found. */
|
|
61
|
+
async checkNow() {
|
|
62
|
+
let info;
|
|
63
|
+
try {
|
|
64
|
+
const resp = await fetch(this.opts.versionUrl, { cache: "no-store" });
|
|
65
|
+
if (!resp.ok) return false;
|
|
66
|
+
info = await resp.json();
|
|
67
|
+
} catch {
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
if (!info?.version || info.version === this.currentVersion) return false;
|
|
71
|
+
this.handleUpdateFound(info);
|
|
72
|
+
return true;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Feed an update signal from somewhere other than version.json polling — most commonly
|
|
76
|
+
* vite-plugin-pwa's `onNeedRefresh` callback. Goes through the same mode logic as checkNow().
|
|
77
|
+
*/
|
|
78
|
+
notifyExternalUpdate(info = { version: "unknown" }) {
|
|
79
|
+
this.handleUpdateFound(info);
|
|
80
|
+
}
|
|
81
|
+
handleUpdateFound(info) {
|
|
82
|
+
if (this._hasUpdate) return;
|
|
83
|
+
this._hasUpdate = true;
|
|
84
|
+
this._latestInfo = info;
|
|
85
|
+
const suppress = this.opts.onUpdateAvailable?.(info) === false;
|
|
86
|
+
this.emit("update-available", info);
|
|
87
|
+
if (suppress) return;
|
|
88
|
+
if (this.opts.mode === "silent") {
|
|
89
|
+
this.applyUpdate();
|
|
90
|
+
} else if (this.opts.mode === "toast-auto") {
|
|
91
|
+
this.autoRefreshTimer = setTimeout(() => this.applyUpdate(), this.opts.autoRefreshDelay);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/** Force the refresh now (what 'modal-blocking' UIs call on button click). Respects the cooldown guard. */
|
|
95
|
+
applyUpdate() {
|
|
96
|
+
if (typeof window === "undefined") return;
|
|
97
|
+
const last = Number(sessionStorage.getItem(COOLDOWN_KEY) || 0);
|
|
98
|
+
if (Date.now() - last < this.opts.refreshCooldown) return;
|
|
99
|
+
sessionStorage.setItem(COOLDOWN_KEY, String(Date.now()));
|
|
100
|
+
this.opts.onBeforeRefresh?.();
|
|
101
|
+
this.emit("refreshing", this._latestInfo);
|
|
102
|
+
window.location.reload();
|
|
103
|
+
}
|
|
104
|
+
on(event, listener) {
|
|
105
|
+
if (!this.listeners.has(event)) this.listeners.set(event, /* @__PURE__ */ new Set());
|
|
106
|
+
this.listeners.get(event).add(listener);
|
|
107
|
+
return () => this.listeners.get(event)?.delete(listener);
|
|
108
|
+
}
|
|
109
|
+
emit(event, info) {
|
|
110
|
+
this.listeners.get(event)?.forEach((cb) => cb(info));
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
export {
|
|
115
|
+
UpdateChecker
|
|
116
|
+
};
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** Baked in by the `refreshGuard()` Vite plugin's `define`. Pass this straight into `useVersionCheck()` / `new UpdateChecker()`. */
|
|
2
|
+
declare const __REFRESH_GUARD_VERSION__: string
|
|
3
|
+
|
|
4
|
+
declare module 'virtual:refresh-guard-changelog' {
|
|
5
|
+
/** Latest version heading found in your changelog file, or null if none/disabled. */
|
|
6
|
+
export const latestVersion: string | null
|
|
7
|
+
/** Markdown body of that version's section (unprocessed), or '' if none/disabled. */
|
|
8
|
+
export const latestContent: string
|
|
9
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { Plugin } from 'vite';
|
|
2
|
+
|
|
3
|
+
interface RefreshGuardPluginOptions {
|
|
4
|
+
/** Version string to bake into version.json and the `__REFRESH_GUARD_VERSION__` define. Default: read from the project's package.json. */
|
|
5
|
+
version?: string;
|
|
6
|
+
/** Include the short git commit hash in version.json. Default: true — silently omitted outside a git repo (e.g. a tarball deploy), never throws. */
|
|
7
|
+
includeCommit?: boolean;
|
|
8
|
+
/** Filename for the emitted version manifest, relative to the build output dir. Default: 'version.json'. */
|
|
9
|
+
outFile?: string;
|
|
10
|
+
/**
|
|
11
|
+
* Path (relative to project root) to a changelog file to expose via `import { latestVersion, latestContent } from 'virtual:refresh-guard-changelog'`.
|
|
12
|
+
* Expects `## vX.Y.Z (date)` section headings, same format as Keep a Changelog. Default: 'CHANGELOG.md'. Set to `false` to disable the virtual module entirely.
|
|
13
|
+
*/
|
|
14
|
+
changelog?: string | false;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Vite plugin half of refresh-guard: bakes the current build's version into your bundle
|
|
18
|
+
* (as `__REFRESH_GUARD_VERSION__`) and emits a `version.json` manifest that the runtime
|
|
19
|
+
* checker (core/checker.ts, or the Vue/React adapters) polls to detect new deploys.
|
|
20
|
+
*
|
|
21
|
+
* Only runs at build time — `version.json` won't exist under plain `vite dev`, which is fine
|
|
22
|
+
* since HMR already covers that case; point a static-file server or `vite preview` at the
|
|
23
|
+
* build output to see it end to end.
|
|
24
|
+
*/
|
|
25
|
+
declare function refreshGuard(options?: RefreshGuardPluginOptions): Plugin;
|
|
26
|
+
|
|
27
|
+
export { type RefreshGuardPluginOptions, refreshGuard as default, refreshGuard };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { execSync } from "child_process";
|
|
3
|
+
import { existsSync, readFileSync } from "fs";
|
|
4
|
+
import { resolve } from "path";
|
|
5
|
+
var VIRTUAL_ID = "virtual:refresh-guard-changelog";
|
|
6
|
+
var RESOLVED_VIRTUAL_ID = "\0" + VIRTUAL_ID;
|
|
7
|
+
function readChangelog(root, changelogOption) {
|
|
8
|
+
if (changelogOption === false) return { latestVersion: null, latestContent: "" };
|
|
9
|
+
const path = resolve(root, changelogOption || "CHANGELOG.md");
|
|
10
|
+
if (!existsSync(path)) return { latestVersion: null, latestContent: "" };
|
|
11
|
+
const md = readFileSync(path, "utf-8");
|
|
12
|
+
const heading = md.match(/^##\s+(v?[\d.]+)/m);
|
|
13
|
+
if (!heading) return { latestVersion: null, latestContent: "" };
|
|
14
|
+
const sections = md.split(/^## /m);
|
|
15
|
+
const body = sections.length > 1 ? sections[1].replace(/^v?[\d.]+\s*\(.*?\)\s*\n?/, "").trim() : "";
|
|
16
|
+
return { latestVersion: heading[1], latestContent: body };
|
|
17
|
+
}
|
|
18
|
+
function refreshGuard(options = {}) {
|
|
19
|
+
let config;
|
|
20
|
+
let version = options.version;
|
|
21
|
+
const buildId = String(Date.now());
|
|
22
|
+
let commit = "";
|
|
23
|
+
return {
|
|
24
|
+
name: "vite-plugin-refresh-guard",
|
|
25
|
+
// `config()` runs before `configResolved()` — the version has to be settled here, not there,
|
|
26
|
+
// because the `define` this hook returns is what actually bakes __REFRESH_GUARD_VERSION__
|
|
27
|
+
// into the client bundle. Resolving it later would just be too late to matter.
|
|
28
|
+
config(userConfig) {
|
|
29
|
+
const root = userConfig.root || process.cwd();
|
|
30
|
+
if (!version) {
|
|
31
|
+
try {
|
|
32
|
+
const pkg = JSON.parse(readFileSync(resolve(root, "package.json"), "utf-8"));
|
|
33
|
+
version = pkg.version || "0.0.0";
|
|
34
|
+
} catch {
|
|
35
|
+
version = "0.0.0";
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return { define: { __REFRESH_GUARD_VERSION__: JSON.stringify(version) } };
|
|
39
|
+
},
|
|
40
|
+
configResolved(resolvedConfig) {
|
|
41
|
+
config = resolvedConfig;
|
|
42
|
+
if (options.includeCommit !== false) {
|
|
43
|
+
try {
|
|
44
|
+
commit = execSync("git rev-parse --short HEAD", { cwd: config.root, stdio: ["ignore", "pipe", "ignore"] }).toString().trim();
|
|
45
|
+
} catch {
|
|
46
|
+
commit = "";
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
},
|
|
50
|
+
resolveId(id) {
|
|
51
|
+
if (id === VIRTUAL_ID) return RESOLVED_VIRTUAL_ID;
|
|
52
|
+
},
|
|
53
|
+
load(id) {
|
|
54
|
+
if (id !== RESOLVED_VIRTUAL_ID) return;
|
|
55
|
+
const { latestVersion, latestContent } = readChangelog(config.root, options.changelog);
|
|
56
|
+
return `export const latestVersion = ${JSON.stringify(latestVersion)};
|
|
57
|
+
export const latestContent = ${JSON.stringify(latestContent)};
|
|
58
|
+
`;
|
|
59
|
+
},
|
|
60
|
+
generateBundle() {
|
|
61
|
+
const manifest = {
|
|
62
|
+
version: version ?? "0.0.0",
|
|
63
|
+
buildId,
|
|
64
|
+
commit: commit || void 0,
|
|
65
|
+
time: (/* @__PURE__ */ new Date()).toISOString()
|
|
66
|
+
};
|
|
67
|
+
this.emitFile({
|
|
68
|
+
type: "asset",
|
|
69
|
+
fileName: options.outFile || "version.json",
|
|
70
|
+
source: JSON.stringify(manifest, null, 2)
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
var index_default = refreshGuard;
|
|
76
|
+
export {
|
|
77
|
+
index_default as default,
|
|
78
|
+
refreshGuard
|
|
79
|
+
};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import * as react from 'react';
|
|
2
|
+
import { U as UpdateMode } from '../types-DaLsj7ZU.js';
|
|
3
|
+
|
|
4
|
+
interface UpdatePromptProps {
|
|
5
|
+
visible: boolean;
|
|
6
|
+
mode?: UpdateMode;
|
|
7
|
+
/** Optional: e.g. `latestVersion` from `virtual:refresh-guard-changelog`. */
|
|
8
|
+
version?: string | null;
|
|
9
|
+
/** Optional: e.g. `latestContent` from `virtual:refresh-guard-changelog`, rendered via dangerouslySetInnerHTML — pre-sanitize if it isn't your own trusted file. */
|
|
10
|
+
changelogHtml?: string;
|
|
11
|
+
onRefresh: () => void;
|
|
12
|
+
}
|
|
13
|
+
declare function UpdatePrompt({ visible, mode, version, changelogHtml, onRefresh }: UpdatePromptProps): react.ReactPortal | null;
|
|
14
|
+
|
|
15
|
+
export { UpdatePrompt, type UpdatePromptProps };
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// src/react/UpdatePrompt.tsx
|
|
2
|
+
import { createPortal } from "react-dom";
|
|
3
|
+
import { jsx, jsxs } from "react/jsx-runtime";
|
|
4
|
+
function UpdatePrompt({ visible, mode = "toast-auto", version = null, changelogHtml = "", onRefresh }) {
|
|
5
|
+
if (!visible || mode === "silent" || typeof document === "undefined") return null;
|
|
6
|
+
if (mode === "toast-auto") {
|
|
7
|
+
return createPortal(
|
|
8
|
+
/* @__PURE__ */ jsxs("div", { style: styles.toast, role: "status", children: [
|
|
9
|
+
/* @__PURE__ */ jsxs("span", { children: [
|
|
10
|
+
"\u53D1\u73B0\u65B0\u7248\u672C",
|
|
11
|
+
version ? ` ${version}` : "",
|
|
12
|
+
"\uFF0C\u5373\u5C06\u81EA\u52A8\u5237\u65B0\u2026"
|
|
13
|
+
] }),
|
|
14
|
+
/* @__PURE__ */ jsx("button", { type: "button", style: styles.toastBtn, onClick: onRefresh, children: "\u7ACB\u5373\u5237\u65B0" })
|
|
15
|
+
] }),
|
|
16
|
+
document.body
|
|
17
|
+
);
|
|
18
|
+
}
|
|
19
|
+
return createPortal(
|
|
20
|
+
/* @__PURE__ */ jsx("div", { style: styles.overlay, role: "alertdialog", "aria-modal": "true", children: /* @__PURE__ */ jsxs("div", { style: styles.modal, children: [
|
|
21
|
+
/* @__PURE__ */ jsxs("h3", { style: styles.title, children: [
|
|
22
|
+
"\u6709\u65B0\u7248\u672C\u53EF\u7528",
|
|
23
|
+
version ? `\uFF1A${version}` : ""
|
|
24
|
+
] }),
|
|
25
|
+
changelogHtml ? /* @__PURE__ */ jsx("div", { style: styles.body, dangerouslySetInnerHTML: { __html: changelogHtml } }) : /* @__PURE__ */ jsx("p", { style: { ...styles.body, color: "#6b7280" }, children: "\u5237\u65B0\u9875\u9762\u5373\u53EF\u4F7F\u7528\u6700\u65B0\u7248\u672C\u3002" }),
|
|
26
|
+
/* @__PURE__ */ jsx("button", { type: "button", style: styles.primaryBtn, onClick: onRefresh, children: "\u7ACB\u5373\u66F4\u65B0" })
|
|
27
|
+
] }) }),
|
|
28
|
+
document.body
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
var styles = {
|
|
32
|
+
toast: {
|
|
33
|
+
position: "fixed",
|
|
34
|
+
right: 16,
|
|
35
|
+
bottom: 16,
|
|
36
|
+
zIndex: 9999,
|
|
37
|
+
display: "flex",
|
|
38
|
+
alignItems: "center",
|
|
39
|
+
gap: 12,
|
|
40
|
+
padding: "10px 16px",
|
|
41
|
+
borderRadius: 8,
|
|
42
|
+
background: "#1f2937",
|
|
43
|
+
color: "#fff",
|
|
44
|
+
fontSize: 13,
|
|
45
|
+
boxShadow: "0 4px 16px rgba(0,0,0,0.2)"
|
|
46
|
+
},
|
|
47
|
+
toastBtn: {
|
|
48
|
+
flexShrink: 0,
|
|
49
|
+
padding: "4px 10px",
|
|
50
|
+
borderRadius: 6,
|
|
51
|
+
border: "1px solid rgba(255,255,255,0.3)",
|
|
52
|
+
background: "transparent",
|
|
53
|
+
color: "#fff",
|
|
54
|
+
fontSize: 12,
|
|
55
|
+
cursor: "pointer"
|
|
56
|
+
},
|
|
57
|
+
overlay: {
|
|
58
|
+
position: "fixed",
|
|
59
|
+
inset: 0,
|
|
60
|
+
zIndex: 9999,
|
|
61
|
+
display: "flex",
|
|
62
|
+
alignItems: "center",
|
|
63
|
+
justifyContent: "center",
|
|
64
|
+
background: "rgba(0,0,0,0.5)"
|
|
65
|
+
},
|
|
66
|
+
modal: {
|
|
67
|
+
width: "90vw",
|
|
68
|
+
maxWidth: 420,
|
|
69
|
+
padding: 24,
|
|
70
|
+
borderRadius: 12,
|
|
71
|
+
background: "#fff",
|
|
72
|
+
color: "#111827",
|
|
73
|
+
boxShadow: "0 12px 40px rgba(0,0,0,0.25)"
|
|
74
|
+
},
|
|
75
|
+
title: { margin: "0 0 12px", fontSize: 16, fontWeight: 700 },
|
|
76
|
+
body: { margin: "0 0 20px", fontSize: 13, lineHeight: 1.6, color: "#4b5563", maxHeight: "40vh", overflowY: "auto" },
|
|
77
|
+
primaryBtn: {
|
|
78
|
+
width: "100%",
|
|
79
|
+
padding: 10,
|
|
80
|
+
border: "none",
|
|
81
|
+
borderRadius: 8,
|
|
82
|
+
background: "#2563eb",
|
|
83
|
+
color: "#fff",
|
|
84
|
+
fontSize: 14,
|
|
85
|
+
fontWeight: 600,
|
|
86
|
+
cursor: "pointer"
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
export {
|
|
90
|
+
UpdatePrompt
|
|
91
|
+
};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { V as VersionCheckerOptions, a as VersionInfo, U as UpdateMode } from '../types-DaLsj7ZU.js';
|
|
2
|
+
import { U as UpdateChecker } from '../checker-gSSR0d-T.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* React hook wrapping the framework-agnostic UpdateChecker. Mounts/unmounts the checker with
|
|
6
|
+
* the component's lifecycle automatically.
|
|
7
|
+
*
|
|
8
|
+
* @param currentVersion Usually `__REFRESH_GUARD_VERSION__` (injected by the Vite plugin).
|
|
9
|
+
*/
|
|
10
|
+
declare function useVersionCheck(currentVersion: string, options?: VersionCheckerOptions): {
|
|
11
|
+
hasUpdate: boolean;
|
|
12
|
+
latestInfo: VersionInfo | null;
|
|
13
|
+
mode: UpdateMode;
|
|
14
|
+
applyUpdate: () => void;
|
|
15
|
+
checkNow: () => Promise<boolean>;
|
|
16
|
+
/** Feed a vite-plugin-pwa `onNeedRefresh` (or any other out-of-band) signal into the same mode logic. */
|
|
17
|
+
notifyExternalUpdate: (info?: VersionInfo) => void;
|
|
18
|
+
checker: UpdateChecker;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
export { useVersionCheck };
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import {
|
|
2
|
+
UpdateChecker
|
|
3
|
+
} from "../chunk-ULA5FWKW.js";
|
|
4
|
+
|
|
5
|
+
// src/react/useVersionCheck.ts
|
|
6
|
+
import { useEffect, useRef, useState } from "react";
|
|
7
|
+
function useVersionCheck(currentVersion, options = {}) {
|
|
8
|
+
const [hasUpdate, setHasUpdate] = useState(false);
|
|
9
|
+
const [latestInfo, setLatestInfo] = useState(null);
|
|
10
|
+
const checkerRef = useRef(null);
|
|
11
|
+
if (!checkerRef.current) {
|
|
12
|
+
checkerRef.current = new UpdateChecker(currentVersion, options);
|
|
13
|
+
}
|
|
14
|
+
useEffect(() => {
|
|
15
|
+
const checker2 = checkerRef.current;
|
|
16
|
+
const off = checker2.on("update-available", (info) => {
|
|
17
|
+
setHasUpdate(true);
|
|
18
|
+
setLatestInfo(info);
|
|
19
|
+
});
|
|
20
|
+
checker2.start();
|
|
21
|
+
return () => {
|
|
22
|
+
checker2.stop();
|
|
23
|
+
off();
|
|
24
|
+
};
|
|
25
|
+
}, []);
|
|
26
|
+
const checker = checkerRef.current;
|
|
27
|
+
return {
|
|
28
|
+
hasUpdate,
|
|
29
|
+
latestInfo,
|
|
30
|
+
mode: options.mode ?? "toast-auto",
|
|
31
|
+
applyUpdate: () => checker.applyUpdate(),
|
|
32
|
+
checkNow: () => checker.checkNow(),
|
|
33
|
+
/** Feed a vite-plugin-pwa `onNeedRefresh` (or any other out-of-band) signal into the same mode logic. */
|
|
34
|
+
notifyExternalUpdate: (info) => checker.notifyExternalUpdate(info),
|
|
35
|
+
checker
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
export {
|
|
39
|
+
useVersionCheck
|
|
40
|
+
};
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
type UpdateMode = 'silent' | 'toast-auto' | 'modal-blocking';
|
|
2
|
+
interface VersionInfo {
|
|
3
|
+
version: string;
|
|
4
|
+
buildId?: string;
|
|
5
|
+
commit?: string;
|
|
6
|
+
time?: string;
|
|
7
|
+
}
|
|
8
|
+
interface VersionCheckerOptions {
|
|
9
|
+
/** Where to fetch version info from. Default: '/version.json' (see the Vite plugin, which emits this file at build time). */
|
|
10
|
+
versionUrl?: string;
|
|
11
|
+
/** Poll interval in ms. Default: 5 minutes. Set to 0 to disable polling (e.g. if you only drive checks from a service-worker hook). */
|
|
12
|
+
interval?: number;
|
|
13
|
+
/** Re-check when the tab becomes visible again after being hidden. Default: true. */
|
|
14
|
+
checkOnVisible?: boolean;
|
|
15
|
+
/**
|
|
16
|
+
* How to react when a new version is detected — this is the one knob most projects actually need:
|
|
17
|
+
* - 'silent': just refresh in the background next time it's safe to (no UI). Matches hym-admin's PWA autoUpdate.
|
|
18
|
+
* - 'toast-auto': show a small non-blocking notice, then auto-refresh after `autoRefreshDelay`. Matches Studio.
|
|
19
|
+
* - 'modal-blocking': show a blocking prompt; user must click to refresh. Matches modelgo-console-web.
|
|
20
|
+
* Default: 'toast-auto'.
|
|
21
|
+
*/
|
|
22
|
+
mode?: UpdateMode;
|
|
23
|
+
/** For 'toast-auto': delay before the automatic refresh fires, in ms. Default: 1200. */
|
|
24
|
+
autoRefreshDelay?: number;
|
|
25
|
+
/**
|
|
26
|
+
* Minimum time between forced refreshes, in ms — guards against reload loops when the server
|
|
27
|
+
* keeps serving a "new" version.json (misconfigured cache headers, clock skew, etc.). Default: 90s.
|
|
28
|
+
*/
|
|
29
|
+
refreshCooldown?: number;
|
|
30
|
+
/**
|
|
31
|
+
* Also refresh once when a lazy-loaded chunk fails to load (stale HTML pointing at a JS/CSS
|
|
32
|
+
* hash that a new deploy already removed). Listens for `vite:preloadError` plus the matching
|
|
33
|
+
* dynamic-import rejection pattern. Default: true.
|
|
34
|
+
*/
|
|
35
|
+
guardChunkErrors?: boolean;
|
|
36
|
+
/**
|
|
37
|
+
* Called whenever a new version is first detected, before any built-in UI/refresh behavior runs.
|
|
38
|
+
* Return `false` to suppress the built-in reaction entirely and drive your own UI instead —
|
|
39
|
+
* call `checker.applyUpdate()` yourself when ready.
|
|
40
|
+
*/
|
|
41
|
+
onUpdateAvailable?: (info: VersionInfo) => void | boolean;
|
|
42
|
+
/** Called immediately before the actual page refresh happens (any mode). Good place to flush analytics, etc. */
|
|
43
|
+
onBeforeRefresh?: () => void;
|
|
44
|
+
}
|
|
45
|
+
type UpdateEvent = 'update-available' | 'refreshing';
|
|
46
|
+
type UpdateListener = (info: VersionInfo | null) => void;
|
|
47
|
+
|
|
48
|
+
export type { UpdateMode as U, VersionCheckerOptions as V, VersionInfo as a, UpdateEvent as b, UpdateListener as c };
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
<script setup lang="ts">
|
|
2
|
+
import { computed } from 'vue'
|
|
3
|
+
import type { UpdateMode } from '../core/types'
|
|
4
|
+
|
|
5
|
+
const props = withDefaults(defineProps<{
|
|
6
|
+
visible: boolean
|
|
7
|
+
mode?: UpdateMode
|
|
8
|
+
/** Optional: e.g. `latestVersion` from `virtual:refresh-guard-changelog`. */
|
|
9
|
+
version?: string | null
|
|
10
|
+
/** Optional: e.g. `latestContent` from `virtual:refresh-guard-changelog`, rendered as-is via v-html — pre-sanitize if it isn't your own trusted file. */
|
|
11
|
+
changelogHtml?: string
|
|
12
|
+
}>(), {
|
|
13
|
+
mode: 'toast-auto',
|
|
14
|
+
version: null,
|
|
15
|
+
changelogHtml: '',
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
const emit = defineEmits<{ refresh: [] }>()
|
|
19
|
+
|
|
20
|
+
// 'silent' has no UI by design — the checker just reloads in the background.
|
|
21
|
+
const shown = computed(() => props.visible && props.mode !== 'silent')
|
|
22
|
+
</script>
|
|
23
|
+
|
|
24
|
+
<template>
|
|
25
|
+
<Teleport to="body">
|
|
26
|
+
<div v-if="shown && mode === 'toast-auto'" class="rg-toast" role="status">
|
|
27
|
+
<span>发现新版本{{ version ? ` ${version}` : '' }},即将自动刷新…</span>
|
|
28
|
+
<button type="button" class="rg-toast-btn" @click="emit('refresh')">立即刷新</button>
|
|
29
|
+
</div>
|
|
30
|
+
|
|
31
|
+
<div v-if="shown && mode === 'modal-blocking'" class="rg-overlay" role="alertdialog" aria-modal="true">
|
|
32
|
+
<div class="rg-modal">
|
|
33
|
+
<h3 class="rg-title">有新版本可用{{ version ? `:${version}` : '' }}</h3>
|
|
34
|
+
<div v-if="changelogHtml" class="rg-body" v-html="changelogHtml" />
|
|
35
|
+
<p v-else class="rg-body rg-body-empty">刷新页面即可使用最新版本。</p>
|
|
36
|
+
<button type="button" class="rg-primary-btn" @click="emit('refresh')">立即更新</button>
|
|
37
|
+
</div>
|
|
38
|
+
</div>
|
|
39
|
+
</Teleport>
|
|
40
|
+
</template>
|
|
41
|
+
|
|
42
|
+
<style scoped>
|
|
43
|
+
.rg-toast {
|
|
44
|
+
position: fixed;
|
|
45
|
+
right: 16px;
|
|
46
|
+
bottom: 16px;
|
|
47
|
+
z-index: 9999;
|
|
48
|
+
display: flex;
|
|
49
|
+
align-items: center;
|
|
50
|
+
gap: 12px;
|
|
51
|
+
padding: 10px 16px;
|
|
52
|
+
border-radius: 8px;
|
|
53
|
+
background: #1f2937;
|
|
54
|
+
color: #fff;
|
|
55
|
+
font-size: 13px;
|
|
56
|
+
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
|
|
57
|
+
}
|
|
58
|
+
.rg-toast-btn {
|
|
59
|
+
flex-shrink: 0;
|
|
60
|
+
padding: 4px 10px;
|
|
61
|
+
border: 1px solid rgba(255, 255, 255, 0.3);
|
|
62
|
+
border-radius: 6px;
|
|
63
|
+
background: transparent;
|
|
64
|
+
color: #fff;
|
|
65
|
+
font-size: 12px;
|
|
66
|
+
cursor: pointer;
|
|
67
|
+
}
|
|
68
|
+
.rg-toast-btn:hover { background: rgba(255, 255, 255, 0.1); }
|
|
69
|
+
|
|
70
|
+
.rg-overlay {
|
|
71
|
+
position: fixed;
|
|
72
|
+
inset: 0;
|
|
73
|
+
z-index: 9999;
|
|
74
|
+
display: flex;
|
|
75
|
+
align-items: center;
|
|
76
|
+
justify-content: center;
|
|
77
|
+
background: rgba(0, 0, 0, 0.5);
|
|
78
|
+
}
|
|
79
|
+
.rg-modal {
|
|
80
|
+
width: 90vw;
|
|
81
|
+
max-width: 420px;
|
|
82
|
+
padding: 24px;
|
|
83
|
+
border-radius: 12px;
|
|
84
|
+
background: #fff;
|
|
85
|
+
color: #111827;
|
|
86
|
+
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.25);
|
|
87
|
+
}
|
|
88
|
+
.rg-title { margin: 0 0 12px; font-size: 16px; font-weight: 700; }
|
|
89
|
+
.rg-body { margin: 0 0 20px; font-size: 13px; line-height: 1.6; color: #4b5563; max-height: 40vh; overflow-y: auto; }
|
|
90
|
+
.rg-body-empty { color: #6b7280; }
|
|
91
|
+
.rg-primary-btn {
|
|
92
|
+
width: 100%;
|
|
93
|
+
padding: 10px;
|
|
94
|
+
border: none;
|
|
95
|
+
border-radius: 8px;
|
|
96
|
+
background: #2563eb;
|
|
97
|
+
color: #fff;
|
|
98
|
+
font-size: 14px;
|
|
99
|
+
font-weight: 600;
|
|
100
|
+
cursor: pointer;
|
|
101
|
+
}
|
|
102
|
+
.rg-primary-btn:hover { background: #1d4ed8; }
|
|
103
|
+
|
|
104
|
+
@media (prefers-color-scheme: dark) {
|
|
105
|
+
.rg-modal { background: #1f2937; color: #f3f4f6; }
|
|
106
|
+
.rg-body { color: #d1d5db; }
|
|
107
|
+
}
|
|
108
|
+
</style>
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { V as VersionCheckerOptions, a as VersionInfo, U as UpdateMode } from '../types-DaLsj7ZU.js';
|
|
2
|
+
import * as vue from 'vue';
|
|
3
|
+
import { U as UpdateChecker } from '../checker-gSSR0d-T.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Vue composable wrapping the framework-agnostic UpdateChecker. Mounts/unmounts the checker
|
|
7
|
+
* with the component's lifecycle automatically.
|
|
8
|
+
*
|
|
9
|
+
* @param currentVersion Usually `__REFRESH_GUARD_VERSION__` (injected by the Vite plugin).
|
|
10
|
+
*/
|
|
11
|
+
declare function useVersionCheck(currentVersion: string, options?: VersionCheckerOptions): {
|
|
12
|
+
hasUpdate: vue.Ref<boolean, boolean>;
|
|
13
|
+
latestInfo: vue.ShallowRef<VersionInfo | null, VersionInfo | null>;
|
|
14
|
+
mode: UpdateMode;
|
|
15
|
+
applyUpdate: () => void;
|
|
16
|
+
checkNow: () => Promise<boolean>;
|
|
17
|
+
/** Feed a vite-plugin-pwa `onNeedRefresh` (or any other out-of-band) signal into the same mode logic. */
|
|
18
|
+
notifyExternalUpdate: (info?: VersionInfo) => void;
|
|
19
|
+
checker: UpdateChecker;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export { useVersionCheck };
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import {
|
|
2
|
+
UpdateChecker
|
|
3
|
+
} from "../chunk-ULA5FWKW.js";
|
|
4
|
+
|
|
5
|
+
// src/vue/useVersionCheck.ts
|
|
6
|
+
import { onMounted, onUnmounted, ref, shallowRef } from "vue";
|
|
7
|
+
function useVersionCheck(currentVersion, options = {}) {
|
|
8
|
+
const hasUpdate = ref(false);
|
|
9
|
+
const latestInfo = shallowRef(null);
|
|
10
|
+
const checker = new UpdateChecker(currentVersion, options);
|
|
11
|
+
const off = checker.on("update-available", (info) => {
|
|
12
|
+
hasUpdate.value = true;
|
|
13
|
+
latestInfo.value = info;
|
|
14
|
+
});
|
|
15
|
+
onMounted(() => checker.start());
|
|
16
|
+
onUnmounted(() => {
|
|
17
|
+
checker.stop();
|
|
18
|
+
off();
|
|
19
|
+
});
|
|
20
|
+
return {
|
|
21
|
+
hasUpdate,
|
|
22
|
+
latestInfo,
|
|
23
|
+
mode: options.mode ?? "toast-auto",
|
|
24
|
+
applyUpdate: () => checker.applyUpdate(),
|
|
25
|
+
checkNow: () => checker.checkNow(),
|
|
26
|
+
/** Feed a vite-plugin-pwa `onNeedRefresh` (or any other out-of-band) signal into the same mode logic. */
|
|
27
|
+
notifyExternalUpdate: (info) => checker.notifyExternalUpdate(info),
|
|
28
|
+
checker
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
export {
|
|
32
|
+
useVersionCheck
|
|
33
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "vite-plugin-refresh-guard",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Configurable new-version detection + refresh for Vite apps: silent auto-refresh, toast-and-auto-refresh, or a blocking modal — pick the strength that fits your product, framework-agnostic core with Vue and React adapters.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/webkubor/vite-plugin-refresh-guard.git"
|
|
10
|
+
},
|
|
11
|
+
"keywords": [
|
|
12
|
+
"vite",
|
|
13
|
+
"vite-plugin",
|
|
14
|
+
"version-check",
|
|
15
|
+
"app-update",
|
|
16
|
+
"service-worker",
|
|
17
|
+
"pwa",
|
|
18
|
+
"refresh",
|
|
19
|
+
"changelog",
|
|
20
|
+
"vue",
|
|
21
|
+
"react"
|
|
22
|
+
],
|
|
23
|
+
"exports": {
|
|
24
|
+
".": {
|
|
25
|
+
"types": "./dist/index.d.ts",
|
|
26
|
+
"import": "./dist/index.js"
|
|
27
|
+
},
|
|
28
|
+
"./client": {
|
|
29
|
+
"types": "./dist/client.d.ts"
|
|
30
|
+
},
|
|
31
|
+
"./vue": {
|
|
32
|
+
"types": "./dist/vue/useVersionCheck.d.ts",
|
|
33
|
+
"import": "./dist/vue/useVersionCheck.js"
|
|
34
|
+
},
|
|
35
|
+
"./vue/UpdatePrompt.vue": "./dist/vue/UpdatePrompt.vue",
|
|
36
|
+
"./react": {
|
|
37
|
+
"types": "./dist/react/useVersionCheck.d.ts",
|
|
38
|
+
"import": "./dist/react/useVersionCheck.js"
|
|
39
|
+
},
|
|
40
|
+
"./react/UpdatePrompt": {
|
|
41
|
+
"types": "./dist/react/UpdatePrompt.d.ts",
|
|
42
|
+
"import": "./dist/react/UpdatePrompt.js"
|
|
43
|
+
}
|
|
44
|
+
},
|
|
45
|
+
"files": [
|
|
46
|
+
"dist",
|
|
47
|
+
"README.md",
|
|
48
|
+
"SKILL.md",
|
|
49
|
+
"CHANGELOG.md"
|
|
50
|
+
],
|
|
51
|
+
"scripts": {
|
|
52
|
+
"build": "tsup src/index.ts src/vue/useVersionCheck.ts src/react/useVersionCheck.ts src/react/UpdatePrompt.tsx --format esm --dts --clean && node scripts/copy-assets.mjs",
|
|
53
|
+
"typecheck": "tsc --noEmit",
|
|
54
|
+
"test": "vitest run",
|
|
55
|
+
"compat": "npm run typecheck && npm test && npm run build",
|
|
56
|
+
"prepublishOnly": "npm run build"
|
|
57
|
+
},
|
|
58
|
+
"peerDependencies": {
|
|
59
|
+
"react": ">=18",
|
|
60
|
+
"react-dom": ">=18",
|
|
61
|
+
"vite": ">=4 <9",
|
|
62
|
+
"vue": ">=3"
|
|
63
|
+
},
|
|
64
|
+
"peerDependenciesMeta": {
|
|
65
|
+
"vue": {
|
|
66
|
+
"optional": true
|
|
67
|
+
},
|
|
68
|
+
"react": {
|
|
69
|
+
"optional": true
|
|
70
|
+
},
|
|
71
|
+
"react-dom": {
|
|
72
|
+
"optional": true
|
|
73
|
+
}
|
|
74
|
+
},
|
|
75
|
+
"devDependencies": {
|
|
76
|
+
"@types/node": "^20.0.0",
|
|
77
|
+
"@types/react": "^18.0.0",
|
|
78
|
+
"@types/react-dom": "^18.0.0",
|
|
79
|
+
"jsdom": "^30.0.1",
|
|
80
|
+
"react": "^18.3.0",
|
|
81
|
+
"react-dom": "^18.3.0",
|
|
82
|
+
"tsup": "^8.0.0",
|
|
83
|
+
"typescript": "^5.4.0",
|
|
84
|
+
"vite": "^5.0.0",
|
|
85
|
+
"vitest": "^3.2.0",
|
|
86
|
+
"vue": "^3.4.0"
|
|
87
|
+
}
|
|
88
|
+
}
|