@adamlui/geolocate 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.
package/README.md ADDED
@@ -0,0 +1,193 @@
1
+ # <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.com/adamlui/js-utils/blob/main/geolocate/media/images/icons/wire-globe/white/icon32.png"><img height=28 src="https://github.com/adamlui/js-utils/blob/main/geolocate/media/images/icons/wire-globe/black/icon32.png"></picture> geolocate
2
+
3
+ ### Fetch IP geolocation data from the CLI.
4
+
5
+ <a href="https://github.com/adamlui/js-utils/releases/tag/geolocate-1.0.0"><img height=31 src="https://img.shields.io/badge/Latest_Build-1.0.0-44cc11.svg?logo=icinga&logoColor=white&labelColor=464646&style=for-the-badge"></a>
6
+ <a href="https://www.npmjs.com/package/@adamlui/geolocate?activeTab=code"><img height=31 src="https://img.shields.io/npm/unpacked-size/%40adamlui%2Fgeolocate?style=for-the-badge&logo=ebox&logoColor=white&labelColor=464646&color=blue"></a>
7
+ <a href="https://sonarcloud.io/component_measures?metric=new_vulnerabilities&id=adamlui_js-utils:geolocate/src/geolocate.js"><img height=31 src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fsonarcloud.io%2Fapi%2Fmeasures%2Fcomponent%3Fcomponent%3Dadamlui_js-utils%3Ageolocate%2Fsrc%2Fgeolocate.js%26metricKeys%3Dvulnerabilities&query=%24.component.measures.0.value&style=for-the-badge&logo=sonarcloud&logoColor=white&labelColor=464646&label=Vulnerabilities&color=gold"></a>
8
+
9
+ <br>
10
+
11
+ <img height=6px width="100%" src="https://raw.githubusercontent.com/adamlui/js-utils/main/docs/images/aqua-separator.png">
12
+
13
+ ## ⚡ Installation
14
+
15
+ As a **global utility**:
16
+
17
+ ```
18
+ $ npm install -g @adamlui/geolocate
19
+ ```
20
+
21
+ As a **dev dependency**, from your project root:
22
+
23
+ ```
24
+ $ npm install -D @adamlui/geolocate
25
+ ```
26
+
27
+ As a **runtime dependency**, from your project root:
28
+
29
+ ```
30
+ $ npm install @adamlui/geolocate
31
+ ```
32
+
33
+ <br>
34
+
35
+ <img height=6px width="100%" src="https://raw.githubusercontent.com/adamlui/js-utils/main/docs/images/aqua-separator.png">
36
+
37
+ ## 💻 Command line usage
38
+
39
+ The basic **global command** is:
40
+
41
+ ```
42
+ $ geolocate
43
+ ```
44
+
45
+ Sample output:
46
+
47
+ <img src="https://github.com/adamlui/js-utils/blob/main/geolocate/media/images/screenshots/cli-geolocate-8.8.8.8.jpg">
48
+
49
+ **💡 Note:** If no IPv4 address is passed, your own one will be used.
50
+
51
+ ### Command line options
52
+
53
+ ```
54
+ Boolean options:
55
+ -q, --quiet Suppress all logging except errors.
56
+
57
+ Info commands:
58
+ -h, --help Display help screen.
59
+ -v, --version Show version number.
60
+ ```
61
+
62
+ <br>
63
+
64
+ <img height=6px width="100%" src="https://raw.githubusercontent.com/adamlui/js-utils/main/docs/images/aqua-separator.png">
65
+
66
+ ## 🔌 Importing the API
67
+
68
+ You can also import **geolocate** into your app to use its API methods.
69
+
70
+ ### <img height=18 src="https://i.imgur.com/JIeAdsr.png"> Node.js
71
+
72
+ #### ES module*:
73
+
74
+ ```js
75
+ import * as geo from '@adamlui/geolocate';
76
+ ```
77
+
78
+ #### CommonJS:
79
+
80
+ ```js
81
+ const geo = require('@adamlui/geolocate');
82
+ ```
83
+
84
+ ###### _*Node.js version 14 or higher required_
85
+
86
+ ### <picture><source media="(prefers-color-scheme: dark)" srcset="https://i.imgur.com/JSEb19A.png"><img width=16 src="https://i.imgur.com/5VPxf9y.png"></picture> Web
87
+
88
+ #### <> HTML script tag:
89
+
90
+ ```html
91
+ <script src="https://cdn.jsdelivr.net/npm/@adamlui/geolocate@1.0.0/dist/generate-ip.min.js"></script>
92
+ ```
93
+
94
+ #### ES6:
95
+
96
+ ```js
97
+ (async () => {
98
+ await import('https://cdn.jsdelivr.net/npm/@adamlui/geolocate@1.0.0/dist/generate-ip.min.js');
99
+ // Your code here...
100
+ })();
101
+ ```
102
+
103
+ ### <img height=17 src="https://raw.githubusercontent.com/KudoAI/chatgpt.js/main/starters/media/images/icons/tampermonkey-icon28.png"><img height=17.5 src="https://raw.githubusercontent.com/KudoAI/chatgpt.js/main/starters/media/images/icons/violentmonkey-icon100.png"> Greasemonkey
104
+
105
+ ```js
106
+ ...
107
+ // @require https://cdn.jsdelivr.net/npm/@adamlui/geolocate@1.0.0/dist/geolocate.min.js
108
+ // ==/UserScript==
109
+
110
+ // Your code here...
111
+ ```
112
+
113
+ <br>
114
+
115
+ 📝 **Note:** To always import the latest version (not recommended in production!) remove the `@1.0.0` version tag from the jsDelivr URL: `https://cdn.jsdelivr.net/npm/@adamlui/geolocate/dist/geolocate.min.js`
116
+
117
+ <br>
118
+
119
+ <img height=6px width="100%" src="https://raw.githubusercontent.com/adamlui/js-utils/main/docs/images/aqua-separator.png">
120
+
121
+ ## 📋 API usage
122
+
123
+ ### `locate([ip])`
124
+
125
+ Asynchronous method to fetch geolocation data for the `ip` passed, returned as an object.
126
+
127
+ **💡 Note:** If no `ip` is supplied, your own one will be used.
128
+
129
+ ```js
130
+ // Using await syntax
131
+ const location = await geo.locate('192.12.85.186');
132
+ console.log(location);
133
+
134
+ // Using .then() syntax
135
+ geo.locate('192.12.85.186').then(location => {
136
+ console.log(location);
137
+ });
138
+
139
+ /* outputs:
140
+ {
141
+ ip: '8.8.8.8',
142
+ country: 'United States',
143
+ countryCode: 'US',
144
+ region: 'VA',
145
+ regionName: 'Virginia',
146
+ city: 'Ashburn',
147
+ zip: '20149',
148
+ lat: 39.03,
149
+ lon: -77.5,
150
+ timezone: 'America/New_York',
151
+ isp: 'Google LLC'
152
+ }
153
+ */
154
+ ```
155
+
156
+ #
157
+
158
+ ### `getOwnIP()`
159
+
160
+ Asynchronous method to fetch/return your own IP as a string:
161
+
162
+ ```js
163
+ // Using await syntax
164
+ const ip = await geo.getOwnIP();
165
+ console.log(ip); // outputs your IP
166
+
167
+ // Using .then() syntax
168
+ geo.getOwnIP().then(ip => {
169
+ console.log(ip); // outputs your IP
170
+ });
171
+ ```
172
+
173
+ <br>
174
+
175
+ <img height=6px width="100%" src="https://raw.githubusercontent.com/adamlui/js-utils/main/docs/images/aqua-separator.png">
176
+
177
+ ## 🏛️ MIT License
178
+
179
+ **Copyright © 2023 [Adam Lui](https://github.com/adamlui)**
180
+
181
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
182
+
183
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
184
+
185
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
186
+
187
+ <br>
188
+
189
+ <img height=6px width="100%" src="https://raw.githubusercontent.com/adamlui/js-utils/main/docs/images/aqua-separator.png">
190
+
191
+ <a href="https://github.com/adamlui/js-utils">**JavaScript utilities**</a> /
192
+ <a href="https://github.com/adamlui/js-utils/discussions">Discuss</a> /
193
+ <a href="#-geolocate">Back to top ↑</a>
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ (async()=>{const e=require(__dirname.match(/src/)?"./geolocate":"./geolocate.min"),o=require("generate-ip")["ipv4"],s=require("child_process")["execSync"],r="",t={},n={flags:{quietMode:/^--?q(?:uiet)?(?:-?mode)?$/},infoCmds:{help:/^--?h(?:elp)?$/,version:/^--?ve?r?s?i?o?n?$/}};if(process.argv.forEach(o=>{var e,s;o.startsWith("-")&&(e=Object.keys(n.flags).find(e=>n.flags[e].test(o)),s=Object.keys(n.infoCmds).find(e=>n.infoCmds[e].test(o)),e?t[e]=!0:s||(console.error(`
3
+ ERROR: Arg [${o}] not recognized.`),console.info(`
4
+ ${r}Valid arguments are below.`),f(["flags","infoCmds"]),process.exit(1)))}),process.argv.some(e=>n.infoCmds.help.test(e)))f();else if(process.argv.some(e=>n.infoCmds.version.test(e)))console.info("v"+require("./package.json").version);else{var i,a=process.argv.slice(2),l=[];for(let e=0;e<a.length;e++)a[e].startsWith("-")||(o.validate(a[e],{verbose:!1})?l.push(a[e]):(i=0==e?"st":1==e?"nd":"th",console.error(`ERROR: ${e+1+i} arg '${a[e]}' is not a valid IPv4 address.`),console.info("Type 'geolocate --help' for help."),process.exit(1)));0==l.length&&l.push(await e.getOwnIP()),l.forEach(e=>g(`Fetching geolocation data for ${e}...`));var c=[];for(const h of l)c.push(await e.locate(h));1==c.length&&g(c[0]),g("Copying to clipboard..."),p=(p=JSON.stringify(c)).replace(/\s+$/,"").replace(/"/g,'""'),"darwin"===process.platform?s(`printf "${p}" | pbcopy`):"linux"===process.platform?s(`printf "${p}" | xclip -selection clipboard`):"win32"===process.platform&&s(`Set-Clipboard -Value "${p}"`,{shell:"powershell"})}var p;function f(e=["cmdFormat","flags","infoCmds"]){const o={cmdFormat:[`
5
+ ${r}geolocate [ip] [options|commands]`],flags:["\nBoolean options:"," -q, --quiet Suppress all logging except errors."],infoCmds:["\nInfo commands:"," -h, --help Display help screen."," -v, --version Show version number."]};e.forEach(e=>{o[e]?.forEach(e=>{{const r=process.stdout.columns||80,t=[],o=e.match(/\S+|\s+/g);let s="";o.forEach(e=>{var o=r-(0===t.length?0:29);s.length+e.length>o&&(t.push(0===t.length?s:s.trimStart()),s=""),s+=e}),t.push(0===t.length?s:s.trimStart()),t.forEach((e,o)=>console.info(0===o?e:" ".repeat(29)+e))}})})}function g(e){t.quietMode||console.info(e)}})();
@@ -0,0 +1 @@
1
+ async function e(t){let r;try{r=require("generate-ip").ipv4.validate}catch(e){await import("https://cdn.jsdelivr.net/npm/generate-ip/dist/generate-ip.min.js"),r=ipv4.validate}if(r&&!r(t,{verbose:!1}))return console.error("geolocate() » ERROR: Invalid IP address passed.");try{let e;if("undefined"!=typeof fetch)e=await fetch("http://ip-api.com/json/"+t);else{if("function"!=typeof require)return console.error("geolocate() » ERROR: Environment not supported.");e=await require("axios").get("http://ip-api.com/json/"+t)}const{status:o,org:i,as:n,query:c,...a}=await e.json();return{ip:t,...a}}catch(e){console.error("geolocate() »",e)}}async function t(){return fetch("https://ifconfig.me/ip").then(e=>e.text()).catch(()=>fetch("http://ip-api.com/json/").then(e=>e.json()).then(e=>e.query)).catch(async()=>{try{var e=require("child_process")["exec"],t=require("util")["promisify"],{stdout:r,stderr:o}=await t(e)("curl -s ifconfig.me");return o?console.error("getOwnIP() »",o):r.trim()}catch(e){console.error("getOwnIP() »",e)}})}const r={geolocate:e,locate:e,getOwnIP:t};try{module.exports={...r}}catch(e){}try{window.geo={...r}}catch(e){}
@@ -0,0 +1,9 @@
1
+ # 🏛️ MIT License
2
+
3
+ **Copyright © 2024 [Adam Lui](https://github.com/adamlui)**
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,5 @@
1
+ # 🛡️ Security Policy
2
+
3
+ If you find a vulnerability, please open a [draft security advisory](https://github.com/adamlui/js-utils/security/advisories/new).
4
+
5
+ Pull requests are also welcome, but for safety reasons, send an email to <adam@kudoai.com> and wait for a response before making it public.
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@adamlui/geolocate",
3
+ "version": "1.0.0",
4
+ "description": "Fetch IP geolocation data from the CLI.",
5
+ "author": {
6
+ "name": "Adam Lui",
7
+ "email": "adam@kudoai.com",
8
+ "url": "https://github.com/adamlui"
9
+ },
10
+ "homepage": "https://js-utils.com/geolocate",
11
+ "license": "MIT",
12
+ "main": "dist/geolocate.min.js",
13
+ "files": [
14
+ "dist",
15
+ "docs/"
16
+ ],
17
+ "bin": {
18
+ "geolocate": "dist/cli.min.js"
19
+ },
20
+ "scripts": {
21
+ "test": "echo \"Error: no test specified\" && exit 1",
22
+ "build": "minify-js src dist"
23
+ },
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/adamlui/js-utils.git"
27
+ },
28
+ "keywords": [
29
+ "geolocate",
30
+ "geolocation",
31
+ "ip",
32
+ "networking"
33
+ ],
34
+ "bugs": {
35
+ "url": "https://github.com/adamlui/js-utils/issues"
36
+ },
37
+ "dependencies": {
38
+ "generate-ip": "^2.2.0"
39
+ },
40
+ "devDependencies": {
41
+ "@adamlui/minify.js": "^1.4.10"
42
+ }
43
+ }