network-speed-js 0.0.2 → 1.0.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.
@@ -0,0 +1,167 @@
1
+ var h = Object.defineProperty;
2
+ var S = (t, e, r) => e in t ? h(t, e, { enumerable: !0, configurable: !0, writable: !0, value: r }) : t[e] = r;
3
+ var u = (t, e, r) => S(t, typeof e != "symbol" ? e + "" : e, r);
4
+ function d(t) {
5
+ const e = t.responseEnd - t.responseStart;
6
+ if (e <= 0 || t.transferSize === 0)
7
+ return null;
8
+ const r = t.transferSize * 8 / e / 1e3, s = t.transferSize / e;
9
+ return {
10
+ name: t.name,
11
+ speedMbps: Number(r.toFixed(2)),
12
+ speedKBps: Number(s.toFixed(2)),
13
+ downloadTime: Number(e.toFixed(2)),
14
+ transferSize: t.transferSize
15
+ };
16
+ }
17
+ function y() {
18
+ return performance.getEntriesByType("resource").filter(
19
+ (e) => e instanceof PerformanceResourceTiming && e.transferSize > 0
20
+ ).map(d).filter((e) => e !== null);
21
+ }
22
+ function b(t) {
23
+ performance.getEntriesByName(t).forEach(() => {
24
+ performance.clearResourceTimings();
25
+ });
26
+ }
27
+ function w(t, e = { fast: 10, medium: 2 }) {
28
+ return t >= e.fast ? "fast" : t >= e.medium ? "medium" : t > 0 ? "slow" : "unknown";
29
+ }
30
+ class T {
31
+ constructor(e = {}) {
32
+ u(this, "options");
33
+ u(this, "observer", null);
34
+ this.options = {
35
+ intranetUrl: e.intranetUrl || "",
36
+ internetUrl: e.internetUrl || "",
37
+ timeout: e.timeout || 1e4,
38
+ autoDetect: e.autoDetect ?? !0,
39
+ thresholds: e.thresholds || { fast: 10, medium: 2 }
40
+ };
41
+ }
42
+ /**
43
+ * 执行测速
44
+ */
45
+ async test() {
46
+ return this.options.autoDetect ? this.testWithAutoDetect() : this.testSingleUrl(this.options.internetUrl, !1);
47
+ }
48
+ /**
49
+ * 自动检测内外网并测速
50
+ */
51
+ async testWithAutoDetect() {
52
+ if (this.options.intranetUrl)
53
+ try {
54
+ return await this.testSingleUrl(this.options.intranetUrl, !0);
55
+ } catch {
56
+ console.log("内网测速失败,切换到外网测速");
57
+ }
58
+ return this.testSingleUrl(this.options.internetUrl, !1);
59
+ }
60
+ /**
61
+ * 测试单个URL
62
+ */
63
+ testSingleUrl(e, r) {
64
+ return new Promise((s, i) => {
65
+ const n = `${e}?t=${Date.now()}`;
66
+ b(n);
67
+ const c = new PerformanceObserver((f) => {
68
+ for (const l of f.getEntries())
69
+ if (l.entryType === "resource" && l.name.includes(e)) {
70
+ const o = d(l);
71
+ if (o) {
72
+ const m = {
73
+ speedMbps: o.speedMbps,
74
+ speedKBps: o.speedKBps,
75
+ networkType: w(
76
+ o.speedMbps,
77
+ this.options.thresholds
78
+ ),
79
+ isIntranet: r,
80
+ duration: o.downloadTime,
81
+ transferSize: o.transferSize,
82
+ resourceUrl: e
83
+ };
84
+ c.disconnect(), s(m);
85
+ }
86
+ }
87
+ });
88
+ c.observe({ entryTypes: ["resource"] });
89
+ const a = new Image(), p = setTimeout(() => {
90
+ c.disconnect(), i(new Error(`测速超时: ${e}`));
91
+ }, this.options.timeout);
92
+ a.onload = () => {
93
+ clearTimeout(p);
94
+ }, a.onerror = () => {
95
+ clearTimeout(p), c.disconnect(), i(new Error(`资源加载失败: ${e}`));
96
+ }, a.src = n;
97
+ });
98
+ }
99
+ /**
100
+ * 监听特定资源的性能数据
101
+ */
102
+ observeResource(e, r) {
103
+ const s = new PerformanceObserver((i) => {
104
+ for (const n of i.getEntries())
105
+ n.entryType === "resource" && n.name.includes(e) && r(n);
106
+ });
107
+ return s.observe({ entryTypes: ["resource"] }), () => s.disconnect();
108
+ }
109
+ /**
110
+ * 更新配置
111
+ */
112
+ updateOptions(e) {
113
+ this.options = { ...this.options, ...e };
114
+ }
115
+ /**
116
+ * 销毁实例
117
+ */
118
+ destroy() {
119
+ this.observer && (this.observer.disconnect(), this.observer = null);
120
+ }
121
+ }
122
+ class g {
123
+ constructor(e = {}) {
124
+ u(this, "tester");
125
+ this.tester = new T(e);
126
+ }
127
+ /**
128
+ * 执行网速测试
129
+ */
130
+ async test() {
131
+ return this.tester.test();
132
+ }
133
+ /**
134
+ * 获取所有已加载资源的速度信息
135
+ */
136
+ getAllResourcesSpeeds() {
137
+ return y();
138
+ }
139
+ /**
140
+ * 监听特定资源的性能数据
141
+ */
142
+ observeResource(e, r) {
143
+ return this.tester.observeResource(e, r);
144
+ }
145
+ /**
146
+ * 更新配置
147
+ */
148
+ updateOptions(e) {
149
+ this.tester.updateOptions(e);
150
+ }
151
+ /**
152
+ * 销毁SDK实例
153
+ */
154
+ destroy() {
155
+ this.tester.destroy();
156
+ }
157
+ }
158
+ function E(t) {
159
+ return new g(t);
160
+ }
161
+ export {
162
+ g as NetworkSpeedSDK,
163
+ d as calcSpeedByResource,
164
+ E as createNetworkSpeedSDK,
165
+ w as evaluateNetworkType,
166
+ y as getAllResourcesSpeeds
167
+ };
@@ -0,0 +1 @@
1
+ (function(r,s){typeof exports=="object"&&typeof module<"u"?s(exports):typeof define=="function"&&define.amd?define(["exports"],s):(r=typeof globalThis<"u"?globalThis:r||self,s(r.NetworkSpeedJS={}))})(this,function(r){"use strict";var v=Object.defineProperty;var U=(r,s,n)=>s in r?v(r,s,{enumerable:!0,configurable:!0,writable:!0,value:n}):r[s]=n;var d=(r,s,n)=>U(r,typeof s!="symbol"?s+"":s,n);function s(t){const e=t.responseEnd-t.responseStart;if(e<=0||t.transferSize===0)return null;const o=t.transferSize*8/e/1e3,i=t.transferSize/e;return{name:t.name,speedMbps:Number(o.toFixed(2)),speedKBps:Number(i.toFixed(2)),downloadTime:Number(e.toFixed(2)),transferSize:t.transferSize}}function n(){return performance.getEntriesByType("resource").filter(e=>e instanceof PerformanceResourceTiming&&e.transferSize>0).map(s).filter(e=>e!==null)}function y(t){performance.getEntriesByName(t).forEach(()=>{performance.clearResourceTimings()})}function m(t,e={fast:10,medium:2}){return t>=e.fast?"fast":t>=e.medium?"medium":t>0?"slow":"unknown"}class w{constructor(e={}){d(this,"options");d(this,"observer",null);this.options={intranetUrl:e.intranetUrl||"",internetUrl:e.internetUrl||"",timeout:e.timeout||1e4,autoDetect:e.autoDetect??!0,thresholds:e.thresholds||{fast:10,medium:2}}}async test(){return this.options.autoDetect?this.testWithAutoDetect():this.testSingleUrl(this.options.internetUrl,!1)}async testWithAutoDetect(){if(this.options.intranetUrl)try{return await this.testSingleUrl(this.options.intranetUrl,!0)}catch{console.log("内网测速失败,切换到外网测速")}return this.testSingleUrl(this.options.internetUrl,!1)}testSingleUrl(e,o){return new Promise((i,a)=>{const c=`${e}?t=${Date.now()}`;y(c);const l=new PerformanceObserver(T=>{for(const p of T.getEntries())if(p.entryType==="resource"&&p.name.includes(e)){const u=s(p);if(u){const g={speedMbps:u.speedMbps,speedKBps:u.speedKBps,networkType:m(u.speedMbps,this.options.thresholds),isIntranet:o,duration:u.downloadTime,transferSize:u.transferSize,resourceUrl:e};l.disconnect(),i(g)}}});l.observe({entryTypes:["resource"]});const f=new Image,S=setTimeout(()=>{l.disconnect(),a(new Error(`测速超时: ${e}`))},this.options.timeout);f.onload=()=>{clearTimeout(S)},f.onerror=()=>{clearTimeout(S),l.disconnect(),a(new Error(`资源加载失败: ${e}`))},f.src=c})}observeResource(e,o){const i=new PerformanceObserver(a=>{for(const c of a.getEntries())c.entryType==="resource"&&c.name.includes(e)&&o(c)});return i.observe({entryTypes:["resource"]}),()=>i.disconnect()}updateOptions(e){this.options={...this.options,...e}}destroy(){this.observer&&(this.observer.disconnect(),this.observer=null)}}class h{constructor(e={}){d(this,"tester");this.tester=new w(e)}async test(){return this.tester.test()}getAllResourcesSpeeds(){return n()}observeResource(e,o){return this.tester.observeResource(e,o)}updateOptions(e){this.tester.updateOptions(e)}destroy(){this.tester.destroy()}}function b(t){return new h(t)}r.NetworkSpeedSDK=h,r.calcSpeedByResource=s,r.createNetworkSpeedSDK=b,r.evaluateNetworkType=m,r.getAllResourcesSpeeds=n,Object.defineProperty(r,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,24 +1,63 @@
1
1
  {
2
2
  "name": "network-speed-js",
3
3
  "private": false,
4
- "description": "A small tool for testing network speed. It also has the ability to test internal and external networks.",
5
- "version": "0.0.2",
4
+ "description": "A framework-agnostic network speed testing SDK based on Performance API with intranet/internet auto-detection support",
5
+ "version": "1.0.0",
6
+ "author": "Sunny-117",
7
+ "license": "MIT",
8
+ "keywords": [
9
+ "network",
10
+ "speed",
11
+ "test",
12
+ "performance",
13
+ "bandwidth",
14
+ "sdk",
15
+ "typescript",
16
+ "framework-agnostic",
17
+ "vue",
18
+ "react",
19
+ "angular"
20
+ ],
21
+ "main": "dist/network-speed-js.umd.js",
6
22
  "module": "dist/network-speed-js.js",
23
+ "types": "dist/index.d.ts",
7
24
  "type": "module",
25
+ "files": [
26
+ "dist",
27
+ "README.md"
28
+ ],
29
+ "exports": {
30
+ ".": {
31
+ "import": "./dist/network-speed-js.js",
32
+ "require": "./dist/network-speed-js.umd.js",
33
+ "types": "./dist/index.d.ts"
34
+ }
35
+ },
8
36
  "scripts": {
9
37
  "dev": "vite",
10
- "build": "vue-tsc && vite build",
11
- "preview": "vite preview"
38
+ "build": "vite build",
39
+ "preview": "vite preview",
40
+ "prepublishOnly": "npm run build"
41
+ },
42
+ "peerDependencies": {
43
+ "vue": "^3.3.11"
12
44
  },
13
45
  "dependencies": {
14
- "axios": "^1.6.2",
15
- "element-plus": "^2.4.4",
16
46
  "vue": "^3.3.11"
17
47
  },
18
48
  "devDependencies": {
49
+ "@types/node": "^25.0.10",
19
50
  "@vitejs/plugin-vue": "^4.5.2",
20
51
  "typescript": "^5.2.2",
21
52
  "vite": "^5.0.8",
22
53
  "vue-tsc": "^1.8.25"
23
- }
54
+ },
55
+ "repository": {
56
+ "type": "git",
57
+ "url": "https://github.com/Sunny-117/network-speed-js.git"
58
+ },
59
+ "bugs": {
60
+ "url": "https://github.com/Sunny-117/network-speed-js/issues"
61
+ },
62
+ "homepage": "https://github.com/Sunny-117/network-speed-js#readme"
24
63
  }
package/.eslintrc.js DELETED
@@ -1,3 +0,0 @@
1
- module.exports = {
2
- "no-unused-vars": ["error", { varsIgnorePattern: ".*", args: "none" }],
3
- };
@@ -1,3 +0,0 @@
1
- {
2
- "recommendations": ["Vue.volar", "Vue.vscode-typescript-vue-plugin"]
3
- }
package/index.html DELETED
@@ -1,13 +0,0 @@
1
- <!doctype html>
2
- <html lang="en">
3
- <head>
4
- <meta charset="UTF-8" />
5
- <link rel="icon" type="image/svg+xml" href="/vite.svg" />
6
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
- <title>Vite + Vue + TS</title>
8
- </head>
9
- <body>
10
- <div id="app"></div>
11
- <script type="module" src="/src/main.ts"></script>
12
- </body>
13
- </html>
@@ -1,3 +0,0 @@
1
- {
2
- "recommendations": ["Vue.volar", "Vue.vscode-typescript-vue-plugin"]
3
- }
@@ -1,18 +0,0 @@
1
- # Vue 3 + TypeScript + Vite
2
-
3
- This template should help get you started developing with Vue 3 and TypeScript in Vite. The template uses Vue 3 `<script setup>` SFCs, check out the [script setup docs](https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup) to learn more.
4
-
5
- ## Recommended IDE Setup
6
-
7
- - [VS Code](https://code.visualstudio.com/) + [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) (and disable Vetur) + [TypeScript Vue Plugin (Volar)](https://marketplace.visualstudio.com/items?itemName=Vue.vscode-typescript-vue-plugin).
8
-
9
- ## Type Support For `.vue` Imports in TS
10
-
11
- TypeScript cannot handle type information for `.vue` imports by default, so we replace the `tsc` CLI with `vue-tsc` for type checking. In editors, we need [TypeScript Vue Plugin (Volar)](https://marketplace.visualstudio.com/items?itemName=Vue.vscode-typescript-vue-plugin) to make the TypeScript language service aware of `.vue` types.
12
-
13
- If the standalone TypeScript plugin doesn't feel fast enough to you, Volar has also implemented a [Take Over Mode](https://github.com/johnsoncodehk/volar/discussions/471#discussioncomment-1361669) that is more performant. You can enable it by the following steps:
14
-
15
- 1. Disable the built-in TypeScript Extension
16
- 1. Run `Extensions: Show Built-in Extensions` from VSCode's command palette
17
- 2. Find `TypeScript and JavaScript Language Features`, right click and select `Disable (Workspace)`
18
- 2. Reload the VSCode window by running `Developer: Reload Window` from the command palette.
@@ -1,13 +0,0 @@
1
- <!doctype html>
2
- <html lang="en">
3
- <head>
4
- <meta charset="UTF-8" />
5
- <link rel="icon" type="image/svg+xml" href="/vite.svg" />
6
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
- <title>Vite + Vue + TS</title>
8
- </head>
9
- <body>
10
- <div id="app"></div>
11
- <script type="module" src="/src/main.ts"></script>
12
- </body>
13
- </html>
@@ -1,21 +0,0 @@
1
- {
2
- "name": "playground",
3
- "private": true,
4
- "version": "0.0.0",
5
- "type": "module",
6
- "scripts": {
7
- "dev": "vite",
8
- "build": "vue-tsc && vite build",
9
- "preview": "vite preview"
10
- },
11
- "dependencies": {
12
- "network-speed-js": "^0.0.1",
13
- "vue": "^3.3.11"
14
- },
15
- "devDependencies": {
16
- "@vitejs/plugin-vue": "^4.5.2",
17
- "typescript": "^5.2.2",
18
- "vite": "^5.0.8",
19
- "vue-tsc": "^1.8.25"
20
- }
21
- }
@@ -1,7 +0,0 @@
1
- lockfileVersion: 5.3
2
-
3
- specifiers:
4
- network-speed-js: ^0.0.1
5
-
6
- dependencies:
7
- network-speed-js: link:../../../../../.nvm/versions/node/v16.14.2/pnpm-global/5/node_modules/network-speed-js