generate-ip 2.1.1 → 2.2.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 CHANGED
@@ -1,16 +1,29 @@
1
1
  # > generate-ip
2
2
 
3
- ### Randomly generate IPv4 and IPv6 addresses.
3
+ ### Randomly generate, format, and validate IP addresses.
4
4
 
5
5
  <a href="#%EF%B8%8F-mit-license"><img height=31 src="https://img.shields.io/badge/License-MIT-orange.svg?logo=internetarchive&logoColor=white&labelColor=464646&style=for-the-badge"></a>
6
- <a href="https://github.com/adamlui/js-utils/releases/tag/generate-ip-2.1.1"><img height=31 src="https://img.shields.io/badge/Latest_Build-2.1.1-44cc11.svg?logo=icinga&logoColor=white&labelColor=464646&style=for-the-badge"></a>
6
+ <a href="https://github.com/adamlui/js-utils/releases/tag/generate-ip-2.2.0"><img height=31 src="https://img.shields.io/badge/Latest_Build-2.2.0-44cc11.svg?logo=icinga&logoColor=white&labelColor=464646&style=for-the-badge"></a>
7
7
  <a href="https://www.npmjs.com/package/generate-ip?activeTab=code"><img height=31 src="https://img.shields.io/npm/unpacked-size/generate-ip?style=for-the-badge&logo=ebox&logoColor=white&labelColor=464646&color=blue"></a>
8
- <a href="https://sonarcloud.io/component_measures?metric=new_vulnerabilities&id=adamlui_js-utils:generate-ip/generate-ip.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%3Agenerate-ip%2Fsrc%2Fgenerate-ip.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
+ <a href="https://github.com/adamlui/js-utils/blob/generate-ip-2.2.0/generate-ip/dist/generate-ip.min.js"><img height=31 src="https://img.shields.io/github/size/adamlui/js-utils/generate-ip/dist/generate-ip.min.js??branch=generate-ip-2.2.0&label=Minified%20Size&logo=databricks&logoColor=white&labelColor=464646&color=ff69b4&style=for-the-badge"></a>
9
+ <a href="https://sonarcloud.io/component_measures?metric=new_vulnerabilities&id=adamlui_js-utils:generate-ip/src/generate-ip.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%3Agenerate-ip%2Fsrc%2Fgenerate-ip.js%26metricKeys%3Dvulnerabilities&query=%24.component.measures.0.value&style=for-the-badge&logo=sonarcloud&logoColor=white&labelColor=464646&label=Vulnerabilities&color=gold"></a>
10
+ <a href="https://www.jsdelivr.com/package/npm/generate-ip?tab=stats"><img height=31 src="https://img.shields.io/jsdelivr/npm/hw/generate-ip?style=for-the-badge&logo=jsdelivr&logoColor=white&label=jsDelivr%20Hits&labelColor=464646&color=49c5d8"></a>
9
11
 
10
12
  <br>
11
13
 
12
14
  <img height=6px width="100%" src="https://raw.githubusercontent.com/adamlui/js-utils/main/docs/images/aqua-separator.png">
13
15
 
16
+ ## 💡 About
17
+
18
+ **generate-ip** is a lightweight, easy-to-use library that allows you to randomly generate, format & validate IPv4/IPv6 address(es).
19
+
20
+ - **No external dependencies —** Only built-in crypto methods used for secure randomization
21
+ - **Multi-protocol support —** IPv4 + IPv6 addresses supported
22
+ - **Command line usable —** Just type `generate-ip`, that's it
23
+ - **Multi-environment support —** Use in Node.js or the web browser
24
+
25
+ <img height=6px width="100%" src="https://raw.githubusercontent.com/adamlui/js-utils/main/docs/images/aqua-separator.png">
26
+
14
27
  ## ⚡ Installation
15
28
 
16
29
  As a **global utility**:
@@ -39,56 +52,42 @@ $ npm install generate-ip
39
52
 
40
53
  ### <img height=18 src="https://i.imgur.com/JIeAdsr.png"> Node.js
41
54
 
42
- #### ESM:
55
+ #### ES module*:
43
56
 
44
57
  ```js
45
58
  import { ipv4, ipv6 } from 'generate-ip';
46
59
  ```
47
60
 
48
- #### CJS:
61
+ #### CommonJS:
49
62
 
50
63
  ```js
51
64
  const { ipv4, ipv6 } = require('generate-ip');
52
65
  ```
53
66
 
67
+ ###### _*Node.js version 14 or higher required_
68
+
54
69
  ### <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
55
70
 
56
- #### HTML script tag:
71
+ #### <> HTML script tag:
57
72
 
58
73
  ```html
59
- <script src="https://cdn.jsdelivr.net/npm/generate-ip@2.1.1/dist/generate-ip.min.js"></script>
74
+ <script src="https://cdn.jsdelivr.net/npm/generate-ip@2.2.0/dist/generate-ip.min.js"></script>
60
75
  ```
61
76
 
62
77
  #### ES6:
63
78
 
64
79
  ```js
65
80
  (async () => {
66
- await import('https://cdn.jsdelivr.net/npm/generate-ip@2.1.1/dist/generate-ip.min.js');
81
+ await import('https://cdn.jsdelivr.net/npm/generate-ip@2.2.0/dist/generate-ip.min.js');
67
82
  // Your code here...
68
83
  })();
69
84
  ```
70
85
 
71
- #### ES5:
72
-
73
- ```js
74
- var xhr = new XMLHttpRequest();
75
- xhr.open('GET', 'https://cdn.jsdelivr.net/npm/generate-ip@2.1.1/dist/generate-ip.min.js');
76
- xhr.onload = function() {
77
- if (xhr.status === 200) {
78
- var generateIP = document.createElement('script');
79
- generateIP.textContent = xhr.responseText;
80
- document.head.append(generateIP);
81
- // Your code here...
82
- }
83
- };
84
- xhr.send();
85
- ```
86
-
87
86
  ### <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
88
87
 
89
88
  ```js
90
89
  ...
91
- // @require https://cdn.jsdelivr.net/npm/generate-ip@2.1.1/dist/generate-ip.min.js
90
+ // @require https://cdn.jsdelivr.net/npm/generate-ip@2.2.0/dist/generate-ip.min.js
92
91
  // ==/UserScript==
93
92
 
94
93
  // Your code here...
@@ -96,13 +95,17 @@ xhr.send();
96
95
 
97
96
  <br>
98
97
 
98
+ 📝 **Note:** To always import the latest version (not recommended in production!) remove the `@2.2.0` version tag from the jsDelivr URL: `https://cdn.jsdelivr.net/npm/generate-ip/dist/generate-ip.min.js`
99
+
100
+ <br>
101
+
99
102
  <img height=6px width="100%" src="https://raw.githubusercontent.com/adamlui/js-utils/main/docs/images/aqua-separator.png">
100
103
 
101
104
  ## 📋 API usage
102
105
 
103
106
  ### `ipv4` methods
104
107
 
105
- Use the `ipv4` methods to [**generate**](#ipv4generateoptions) and [**validate**](#ipv4validateaddress-options) IPv4 addresses.
108
+ 💡 Use the `ipv4` methods to [**generate**](#ipv4generateoptions) and [**validate**](#ipv4validateaddress-options) IPv4 addresses.
106
109
 
107
110
  #
108
111
 
@@ -112,15 +115,7 @@ Generates **one** IPv4 address if `qty` option is not given, returning a string:
112
115
 
113
116
  ```js
114
117
  const ip = ipv4.generate();
115
- console.log(ip);
116
-
117
- /* sample output:
118
-
119
- ipv4.generate() » Generating IPv4 address...
120
- ipv4.generate() » IPv4 address generated!
121
- ipv4.generate() » Check returned string.
122
- '36.42.224.208'
123
- */
118
+ console.log(ip); // sample output: '36.42.224.208'
124
119
  ```
125
120
 
126
121
  ...or **multiple** IPv4 addresses if `qty` option is given, returning an array of strings:
@@ -173,7 +168,7 @@ Name | Type | Description | Default Value
173
168
 
174
169
  ### `ipv6` methods
175
170
 
176
- Use the `ipv6` methods to [**generate**](#ipv6generateoptions), [**format**](#ipv6formatipv6address-options), and [**validate**](#ipv6validateaddress-options) IPv6 addresses.
171
+ 💡 Use the `ipv6` methods to [**generate**](#ipv6generateoptions), [**format**](#ipv6formatipv6address-options), and [**validate**](#ipv6validateaddress-options) IPv6 addresses.
177
172
 
178
173
  #
179
174
 
@@ -183,15 +178,7 @@ Generates **one** IPv6 address if `qty` option is not given, returning a string:
183
178
 
184
179
  ```js
185
180
  const ip = ipv6.generate();
186
- console.log(ip);
187
-
188
- /* sample output:
189
-
190
- ipv6.generate() » Generating IPv6 address...
191
- ipv6.generate() » IPv6 address generated!
192
- ipv6.generate() » Check returned string.
193
- '1379:6748:810c:5e16:b6c9:ae2:939f:8f2a'
194
- */
181
+ console.log(ip); // sample output: '1379:6748:810c:5e16:b6c9:ae2:939f:8f2a'
195
182
  ```
196
183
 
197
184
  ...or **multiple** IPv6 addresses if `qty` option is given, returning an array of strings:
@@ -242,7 +229,7 @@ console.log(formattedAddress);
242
229
  ipv6.format() » Expanding '::' into zero series...
243
230
  ipv6.format() » Adding leading zeros...
244
231
  ipv6.format() » IP formatted successfully!
245
- ipv6.format() » Check returned string.
232
+ ipv6.format() » 000d:0000:0000:0000:0000:0000:ffff:192.1.56.10/96
246
233
  '000d:0000:0000:0000:0000:0000:ffff:192.1.56.10/96'
247
234
  */
248
235
  ```
@@ -291,13 +278,23 @@ When installed [globally](#-installation), **generate-ip** can also be used from
291
278
  $ generate-ip
292
279
  ```
293
280
 
294
- Generated IP is logged to the console + copied to the clipboard.
281
+ Sample output:
282
+
283
+ <img src="https://github.com/adamlui/js-utils/blob/main/generate-ip/media/images/sample-cli-output.jpg">
284
+
285
+ 📝 **Note:** To generate multiple IP addresses, pass `--qty=n` where `n` is the number of IPs to generate.
295
286
 
296
287
  #
297
288
 
298
289
  ### Command line options
299
290
 
300
291
  ```
292
+ Parameter options:
293
+ --qty=n Generate n IP address(es).
294
+
295
+ Boolean options:
296
+ -q, --quiet Suppress all logging except errors.
297
+
301
298
  Info commands:
302
299
  -h, --help Display help screen.
303
300
  -v, --version Show version number.
@@ -309,7 +306,7 @@ Info commands:
309
306
 
310
307
  ## 🏛️ MIT License
311
308
 
312
- **Copyright © 2024 [Adam Lui](https://github.com/adamlui)**
309
+ **Copyright © 2024 [Adam Lui](https://github.com/adamlui) & contributors**
313
310
 
314
311
  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:
315
312
 
@@ -321,6 +318,6 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI
321
318
 
322
319
  <img height=6px width="100%" src="https://raw.githubusercontent.com/adamlui/js-utils/main/docs/images/aqua-separator.png">
323
320
 
324
- <a href="https://github.com/adamlui/js-utils">**Home**</a> /
321
+ <a href="https://github.com/adamlui/js-utils">**JavaScript utilities**</a> /
325
322
  <a href="https://github.com/adamlui/js-utils/discussions">Discuss</a> /
326
323
  <a href="#-generate-ip">Back to top ↑</a>
package/dist/cli.min.js CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
- const e=require(__dirname.match(/src/)?"./generate-ip":"./generate-ip.min")["ipv4"],o=require("child_process")["execSync"],s="",r="",n="",t="",c={infoCmds:{help:/^--?h(?:elp)?$/,version:/^--?ve?r?s?i?o?n?$/}};let i=!1,a;for(const m of Object.keys(c))for(const f of Object.keys(c[m]))i||process.argv.forEach(e=>{e.startsWith("-")&&(a=c[m][f].test(e)?void(i=!0):e)});if(a&&(console.error(`
3
- ${r}ERROR: Arg [${a}] not recognized.`+s),console.info(`
4
- ${n}Valid arguments are below.`+s),l(["infoCmds"]),process.exit(1)),process.argv.some(e=>c.infoCmds.help.test(e)))l();else if(process.argv.some(e=>c.infoCmds.version.test(e)))console.info("v"+require("./package.json").version);else{const h=e.generate({verbose:!1});p(h),console.log(t+h+s)}function l(e=["cmdFormat","formatOptions","infoCmds"]){const o={cmdFormat:[`
5
- ${n}generate-ip [commands]`+s],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,n=[],o=e.match(/\S+|\s+/g);let s="";o.forEach(e=>{var o=r-(0===n.length?0:29);s.length+e.length>o&&(n.push(0===n.length?s:s.trimStart()),s=""),s+=e}),n.push(0===n.length?s:s.trimStart()),n.forEach((e,o)=>console.info(0===o?e:" ".repeat(29)+e))}})})}function p(e){e=e.replace(/\s+$/,"").replace(/"/g,'""'),"darwin"===process.platform?o(`printf "${e}" | pbcopy`):"linux"===process.platform?o(`printf "${e}" | xclip -selection clipboard`):"win32"===process.platform&&o(`Set-Clipboard -Value "${e}"`,{shell:"powershell"})}
2
+ const e=require(__dirname.match(/src/)?"./generate-ip":"./generate-ip.min")["ipv4"],o=require("child_process")["execSync"],n="",t="",i="",a={},p={paramOptions:{qty:/^--?qu?a?n?ti?t?y=.*$/},flags:{quietMode:/^--?q(?:uiet)?(?:-?mode)?$/},infoCmds:{help:/^--?h(?:elp)?$/,version:/^--?ve?r?s?i?o?n?$/}};if(process.argv.forEach(o=>{var e,s,r;o.startsWith("-")&&(e=Object.keys(p.paramOptions).find(e=>p.paramOptions[e].test(o)),r=Object.keys(p.flags).find(e=>p.flags[e].test(o)),s=Object.keys(p.infoCmds).find(e=>p.infoCmds[e].test(o)),r?a[r]=!0:e?(r=o.split("=")[1],a[e]=parseInt(r)||r):s||(console.error(`
3
+ ${t}ERROR: Arg [${o}] not recognized.`+n),console.info(`
4
+ ${i}Valid arguments are below.`+n),c(["paramOptions","flags","infoCmds"]),process.exit(1)))}),process.argv.some(e=>p.infoCmds.help.test(e)))c();else if(process.argv.some(e=>p.infoCmds.version.test(e)))console.info("v"+require("./package.json").version);else{a.qty&&(isNaN(a.qty)||a.qty<1)&&(console.error(`
5
+ ${t}Error: [qty] argument can only be > 0.`+n),process.exit(1));const r=e.generate({qty:a.qty||1,verbose:!a.quietMode});a.quietMode||(1<a.qty&&console.info(`[ ${r.join(", ")} ]`),console.info("\nCopying to clipboard...")),s(Array.isArray(r)?r.join("\n"):r)}function c(e=["cmdFormat","paramOptions","flags","infoCmds"]){const o={cmdFormat:[`
6
+ ${i}generate-ip [options|commands]`+n],paramOptions:["\nParameter options:"," --qty=n Generate n IP address(es)."],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,n=[],o=e.match(/\S+|\s+/g);let s="";o.forEach(e=>{var o=r-(0===n.length?0:29);s.length+e.length>o&&(n.push(0===n.length?s:s.trimStart()),s=""),s+=e}),n.push(0===n.length?s:s.trimStart()),n.forEach((e,o)=>console.info(0===o?e:" ".repeat(29)+e))}})})}function s(e){e=e.replace(/\s+$/,"").replace(/"/g,'""'),"darwin"===process.platform?o(`printf "${e}" | pbcopy`):"linux"===process.platform?o(`printf "${e}" | xclip -selection clipboard`):"win32"===process.platform&&o(`Set-Clipboard -Value "${e}"`,{shell:"powershell"})}
@@ -1,9 +1 @@
1
- let s;try{s=require("crypto").randomInt}catch(e){const n=window.crypto||window.msCrypto;s=(e,o)=>{var r=n?.getRandomValues(new Uint32Array(1))[0]/4294967295||Math.random();return Math.floor(r*(o-e))+e}}const a={generate:function(o={}){var e={verbose:!0,qty:1};for(const t in o={...e,...o}){if(!Object.prototype.hasOwnProperty.call(e,t))return console.error(`ipv4.generate() » ERROR: \`${t}\` is an invalid option.
2
- `+`ipv4.generate() » Valid options: [ ${Object.keys(e).join(", ")} ]`);if(["verbose"].includes(t)&&"boolean"!=typeof o[t])return console.error(`ipv4.generate() » ERROR: [${t}] option can only be \`true\` or \`false\`.`);if(["qty"].includes(t)&&(isNaN(o[t])||o[t]<1))return console.error(`ipv4.generate() » ERROR: [${t}] option can only be an integer > 0.`)}o.verbose&&console.info(`ipv4.generate() » Generating IPv4 address${1<o.qty?"es":""}...`);var r=[];if(1<o.qty)for(let e=0;e<o.qty;e++)r.push(this.generate({verbose:!1}));else{var n=[];for(let e=0;e<4;e++)n.push(s(0,256));r.push(n.join("."))}return o.verbose&&console.info(`ipv4.generate() » IPv4 address${1<o.qty?"es":""} generated!`+("undefined"!=typeof require&&require.main!==module?`
3
- ipv4.generate() » Check returned ${1<o.qty?"array":"string"}.`:"")),1<o.qty?r:r[0]},validate:function(e,o={}){var r={verbose:!0};if(o={...r,...o},"string"!=typeof e)return console.error("ipv4.validate() » ERROR: 1st arg <address> must be a string.");for(const n in o){if(!Object.prototype.hasOwnProperty.call(r,n))return console.error(`ipv4.validate() » ERROR: \`${n}\` is an invalid option.
4
- `+`ipv4.validate() » Valid options: [ ${Object.keys(r).join(", ")} ]`);if("boolean"!=typeof o[n])return console.error(`ipv4.validate() » ERROR: [${n}] option can only be set to \`true\` or \`false\`.`)}o.verbose&&console.info("ipv4.validate() » Validating IPv4 address...");e=e.split("."),e=!(4!==e.length||e.some(e=>!/^\d+$/.test(e)||parseInt(e,10)<0||255<parseInt(e,10)));return o.verbose&&console.info(`ipv4.validate() » IP is ${e?"":"in"}valid IPv4 address!`),e}},e={generate:function(o={}){var e={verbose:!0,qty:1,leadingZeros:!1,doubleColon:!0};for(const n in o={...e,...o}){if(!Object.prototype.hasOwnProperty.call(e,n))return console.error(`ipv6.generate() » ERROR: \`${n}\` is an invalid option.
5
- `+`ipv6.generate() » Valid options: [ ${Object.keys(e).join(", ")} ]`);if(["verbose","leadingZeros","doubleColon"].includes(n)&&"boolean"!=typeof o[n])return console.error(`ipv6.generate() » ERROR: [${n}] option can only be \`true\` or \`false\`.`);if(["qty"].includes(n)&&(isNaN(o[n])||o[n]<1))return console.error(`ipv6.generate() » ERROR: [${n}] option can only be an integer > 0.`)}o.verbose&&console.info(`ipv6.generate() » Generating IPv6 address${1<o.qty?"es":""}...`);var r=[];if(1<o.qty)for(let e=0;e<o.qty;e++)r.push(this.generate({verbose:!1}));else{const t=[],{qty:i,...a}=o;for(let e=0;e<8;e++){let o="";for(let e=0;e<4;e++)o+=s(0,16).toString(16);t.push(o)}r.push(this.format(t.join(":"),{...a,verbose:!1}))}return o.verbose&&console.info(`ipv6.generate() » IPv6 address${1<o.qty?"es":""} generated!`+("undefined"!=typeof require&&require.main!==module?`
6
- ipv6.generate() » Check returned ${1<o.qty?"array":"string"}.`:"")),1<o.qty?r:r[0]},format:function(e,o={}){var r,n,t={verbose:!0,leadingZeros:!1,doubleColon:!0};if(o={...t,...o},"string"!=typeof e)return console.error("ipv6.format() » ERROR: 1st arg <address> must be a string.");if(!this.validate(e,{verbose:!1}))return console.error(`ipv6.format() » ERROR:
7
- - ${e} is not a valid IPv6 address.`);for(const s in o){if(!Object.prototype.hasOwnProperty.call(t,s))return console.error(`ipv6.format() » ERROR: \`${s}\` is an invalid option.
8
- `+`ipv6.format() » Valid options: [ ${Object.keys(t).join(", ")} ]`);if("boolean"!=typeof o[s])return console.error(`ipv6.format() » ERROR: [${s}] option can only be \`true\` or \`false\`.`)}let i=e;if(i=o.doubleColon?(o.verbose&&console.info("ipv6.format() » Replacing zero series w/ '::'..."),i.replace(/:(?:0+:)+/,"::")):(o.verbose&&console.info("ipv6.format() » Expanding '::' into zero series..."),n=i.split(":").filter(Boolean).length,r=o.leadingZeros?"0000":"0",n=Array(8-n).fill(r).join(":"),i.replace("::",`:${n}:`)),o.leadingZeros){o.verbose&&console.info("ipv6.format() » Adding leading zeros...");var a=i.split(":");for(let e=0;e<a.length;e++)for(;a[e].length<4;)a[e]="0"+a[e];i=a.join(":")}else o.verbose&&console.info("ipv6.format() » Stripping leading zeros..."),i=e.replace(/(^|(?<=:))0+(?!:)/g,"$1");return o.verbose&&(i!==e?console.info("ipv6.format() » IP formatted successfully!\nipv6.format() » Check returned string."):console.info("ipv6.format() » IP already formatted to specs.")),i},validate:function(e,o={}){var r={verbose:!0};if(o={...r,...o},"string"!=typeof e)return console.error("ipv6.validate() » ERROR: 1st arg <address> must be a string.");for(const i in o){if(!Object.prototype.hasOwnProperty.call(r,i))return console.error(`ipv6.validate() » ERROR: \`${i}\` is an invalid option.
9
- `+`ipv6.validate() » Valid options: [ ${Object.keys(r).join(", ")} ]`);if("boolean"!=typeof o[i])return console.error(`ipv6.validate() » ERROR: [${i}] option can only be \`true\` or \`false\`.`)}o.verbose&&console.info("ipv6.validate() » Validating IPv6 address...");const n=e.split(/::?/),t=n[n.length-1];e=!(e.includes("::")&&2<e.split("::").length||/:{3,}/g.test(e)||n.length<2||8<n.length||n.some(e=>!(/^[\dA-Fa-f]{1,4}$/.test(e)||e===t&&a.validate(t.replace(/\/(?:0|(?:[1-2]?\d)|32|96)$/,""),{verbose:!1}))));return o.verbose&&console.info(`ipv6.validate() » IP is ${e?"":"in"}valid IPv6 address!`),e}};try{module.exports={ipv4:a,ipv6:e}}catch(e){}try{window.ipv4=a,window.ipv6=e}catch(e){}
1
+ let d;try{d=require("crypto").randomInt}catch(e){const n=window.crypto||window.msCrypto;d=(e,o)=>{var r=n?.getRandomValues(new Uint32Array(1))[0]/4294967295||Math.random();return Math.floor(r*(o-e))+e}}const p={generate:function(o={}){const r={verbose:!0,qty:1},e=JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:").replace(/"/g,"'").replace(/\n\s*/g," "),n=Object.keys(r).join(", "),t=Object.keys(r).filter(e=>"boolean"==typeof r[e]),i=Object.keys(r).filter(e=>Number.isInteger(r[e]));var a=()=>{console.info(`ipv4.generate() » Valid options: [ ${n} ]`),console.info("ipv4.generate() » If omitted, default settings are: "+e)};if("object"==typeof o){for(const v in o){if(!Object.prototype.hasOwnProperty.call(r,v))return console.error(`ipv4.generate() » ERROR: \`${v}\` is an invalid option.`),void a();if(t.includes(v)&&"boolean"!=typeof o[v])return console.error(`ipv4.generate() » ERROR: [${v}] option can only be \`true\` or \`false\`.`);if(i.includes(v)&&(o[v]=parseInt(o[v],10),isNaN(o[v])||o[v]<1))return console.error(`ipv4.generate() » ERROR: [${v}] option can only be an integer > 0.`)}(o={...r,...o}).verbose&&console.info(`ipv4.generate() » Generating IPv4 address${1<o.qty?"es":""}...`);var s=[];if(1<o.qty)for(let e=0;e<o.qty;e++)s.push(this.generate({...o,qty:1,verbose:!1}));else{var l=[];for(let e=0;e<4;e++)l.push(d(0,256));s.push(l.join("."))}var p=1<o.qty?s:s[0];return o.verbose&&(console.info(`ipv4.generate() » IPv4 address${1<o.qty?"es":""} generated!`),1===o.qty?console.info("ipv4.generate() » "+p):"undefined"==typeof require||require.main.filename.endsWith("cli.js")||console.info("ipv4.generate() » Check returned array.")),p}console.error("ipv4.generate() » ERROR: [options] can only be an object of key/values."),console.info("ipv4.generate() » Example valid call: ipv4.generate({ verbose: false, qty: 3 })"),a()},validate:function(e,o={}){var r={verbose:!0};if("string"!=typeof e)return console.error("ipv4.validate() » ERROR: 1st arg <address> must be a string.");const n=JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:").replace(/"/g,"'").replace(/\n\s*/g," "),t=Object.keys(r).join(", ");var i=()=>{console.info(`ipv4.validate() » Valid options: [ ${t} ]`),console.info("ipv4.validate() » If omitted, default settings are: "+n)};if("object"==typeof o){for(const a in o){if(!Object.prototype.hasOwnProperty.call(r,a))return console.error(`ipv4.validate() » ERROR: \`${a}\` is an invalid option.`),void i();if("boolean"!=typeof o[a])return console.error(`ipv4.validate() » ERROR: [${a}] option can only be \`true\` or \`false\`.`)}(o={...r,...o}).verbose&&console.info("ipv4.validate() » Validating IPv4 address...");e=e.split("."),e=!(4!==e.length||e.some(e=>!/^\d+$/.test(e)||parseInt(e,10)<0||255<parseInt(e,10)));return o.verbose&&console.info(`ipv4.validate() » IP is ${e?"":"in"}valid IPv4 address!`),e}console.error("ipv4.validate() » ERROR: 2nd arg [options] can only be an object of key/values."),console.info("ipv4.validate() » Example valid call: ipv4.validate('0.0.255.255', { verbose: false })"),i()}},e={generate:function(o={}){const r={verbose:!0,qty:1,leadingZeros:!1,doubleColon:!0},e=JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:").replace(/"/g,"'").replace(/\n\s*/g," "),n=Object.keys(r).join(", "),t=Object.keys(r).filter(e=>"boolean"==typeof r[e]),i=Object.keys(r).filter(e=>Number.isInteger(r[e]));var a=()=>{console.info(`ipv6.generate() » Valid options: [ ${n} ]`),console.info("ipv6.generate() » If omitted, default settings are: "+e)};if("object"==typeof o){for(const p in o){if(!Object.prototype.hasOwnProperty.call(r,p))return console.error(`ipv6.generate() » ERROR: \`${p}\` is an invalid option.`),void a();if(t.includes(p)&&"boolean"!=typeof o[p])return console.error(`ipv6.generate() » ERROR: [${p}] option can only be \`true\` or \`false\`.`);if(i.includes(p)&&(o[p]=parseInt(o[p],10),isNaN(o[p])||o[p]<1))return console.error(`ipv6.generate() » ERROR: [${p}] option can only be an integer > 0.`)}(o={...r,...o}).verbose&&console.info(`ipv6.generate() » Generating IPv6 address${1<o.qty?"es":""}...`);var s=[];if(1<o.qty)for(let e=0;e<o.qty;e++)s.push(this.generate({...o,qty:1,verbose:!1}));else{const v=[],{qty:c,...f}=o;for(let e=0;e<8;e++){let o="";for(let e=0;e<4;e++)o+=d(0,16).toString(16);v.push(o)}s.push(this.format(v.join(":"),{...f,verbose:!1}))}var l=1<o.qty?s:s[0];return o.verbose&&(console.info(`ipv6.generate() » IPv6 address${1<o.qty?"es":""} generated!`),console.info(1===o.qty?"ipv6.generate() » "+l:"ipv6.generate() » Check returned array.")),l}console.error("ipv6.generate() » ERROR: [options] can only be an object of key/values."),console.info("ipv6.generate() » Example valid call: ipv6.generate({ leadingZeros: true, qty: 5 })"),a()},format:function(o,r={}){var n={verbose:!0,leadingZeros:!1,doubleColon:!0};if("string"!=typeof o)return console.error("ipv6.format() » ERROR: 1st arg <address> must be a string.");if(!this.validate(o,{verbose:!1}))return console.error(`ipv6.format() » ERROR: ${o} is not a valid IPv6 address.`);const e=JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:").replace(/"/g,"'").replace(/\n\s*/g," "),t=Object.keys(n).join(", ");var i,a,s=()=>{console.info(`ipv6.format() » Valid options: [ ${t} ]`),console.info("ipv6.format() » If omitted, default settings are: "+e)};if("object"==typeof r){for(const p in r){if(!Object.prototype.hasOwnProperty.call(n,p))return console.error(`ipv6.format() » ERROR: \`${p}\` is an invalid option.`),void s();if("boolean"!=typeof r[p])return console.error(`ipv6.format() » ERROR: [${p}] option can only be \`true\` or \`false\`.`)}r={...n,...r};let e=o;if(e=r.doubleColon?(r.verbose&&console.info("ipv6.format() » Replacing zero series w/ '::'..."),e.replace(/:(?:0+:)+/,"::")):(r.verbose&&console.info("ipv6.format() » Expanding '::' into zero series..."),a=e.split(":").filter(Boolean).length,i=r.leadingZeros?"0000":"0",a=Array(8-a).fill(i).join(":"),e.replace("::",`:${a}:`)),r.leadingZeros){r.verbose&&console.info("ipv6.format() » Adding leading zeros...");var l=e.split(":");for(let e=0;e<l.length;e++)for(;l[e].length<4;)l[e]="0"+l[e];e=l.join(":")}else r.verbose&&console.info("ipv6.format() » Stripping leading zeros..."),e=o.replace(/(^|(?<=:))0+(?!:)/g,"$1");return r.verbose&&(e!==o?console.info("ipv6.format() » IP formatted successfully!"):console.info("ipv6.format() » IP already formatted to specs."),console.info("ipv6.format() » "+e)),e}console.error("ipv6.format() » ERROR: 2nd arg [options] can only be an object of key/values."),console.info("ipv6.format() » Example valid call: ipv6.format('0d::ffff:192.1.56.10/96', { leadingZeros: true, doubleColon: false })"),s()},validate:function(e,o={}){var r={verbose:!0};if("string"!=typeof e)return console.error("ipv6.validate() » ERROR: 1st arg <address> must be a string.");const n=JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:").replace(/"/g,"'").replace(/\n\s*/g," "),t=Object.keys(r).join(", ");var i=()=>{console.info(`ipv6.validate() » Valid options: [ ${t} ]`),console.info("ipv6.validate() » If omitted, default settings are: "+n)};if("object"==typeof o){for(const l in o){if(!Object.prototype.hasOwnProperty.call(r,l))return console.error(`ipv6.validate() » ERROR: \`${l}\` is an invalid option.`),void i();if("boolean"!=typeof o[l])return console.error(`ipv6.validate() » ERROR: [${l}] option can only be \`true\` or \`false\`.`)}(o={...r,...o}).verbose&&console.info("ipv6.validate() » Validating IPv6 address...");const a=e.split(/::?/),s=a[a.length-1];e=!(e.includes("::")&&2<e.split("::").length||/:{3,}/g.test(e)||a.length<2||8<a.length||a.some(e=>!(/^[\dA-Fa-f]{1,4}$/.test(e)||e===s&&p.validate(s.replace(/\/(?:0|(?:[1-2]?\d)|32|96)$/,""),{verbose:!1}))));return o.verbose&&console.info(`ipv6.validate() » IP is ${e?"":"in"}valid IPv6 address!`),e}console.error("ipv6.validate() » ERROR: 2nd arg [options] can only be an object of key/values."),console.info("ipv6.validate() » Example valid call: ipv6.validate('0:0:0:0:0:ffff:192.1.56.10/96', { verbose: false })"),i()}};try{module.exports={ipv4:p,ipv6:e}}catch(e){}try{window.ipv4=p,window.ipv6=e}catch(e){}
package/docs/LICENSE.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # 🏛️ MIT License
2
2
 
3
- **Copyright © 2024 [Adam Lui](https://github.com/adamlui)**
3
+ **Copyright © 2024 [Adam Lui](https://github.com/adamlui) & contributors**
4
4
 
5
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
6
 
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "generate-ip",
3
- "version": "2.1.1",
4
- "description": "Randomly generate IPv4 and IPv6 addresses.",
3
+ "version": "2.2.0",
4
+ "description": "Randomly generate, format, and validate IP addresses.",
5
5
  "author": {
6
6
  "name": "Adam Lui",
7
7
  "email": "adam@kudoai.com",
8
8
  "url": "https://github.com/adamlui"
9
9
  },
10
- "homepage": "https://github.com/adamlui/js-utils",
10
+ "homepage": "https://js-utils.com/generate-ip",
11
11
  "license": "MIT",
12
12
  "main": "dist/generate-ip.min.js",
13
13
  "files": [
@@ -18,6 +18,10 @@
18
18
  "generateip": "dist/cli.min.js",
19
19
  "generate-ip": "dist/cli.min.js"
20
20
  },
21
+ "directories": {
22
+ "lib": "./src",
23
+ "doc": "./docs"
24
+ },
21
25
  "scripts": {
22
26
  "test": "echo \"Error: no test specified\" && exit 1",
23
27
  "build": "minify-js src dist",
@@ -45,13 +49,13 @@
45
49
  "mac"
46
50
  ],
47
51
  "bugs": {
48
- "url": "https://github.com/adamlui/js-utils/issues"
52
+ "url": "https://js-utils.com/issues"
49
53
  },
50
54
  "funding": {
51
55
  "type": "github",
52
56
  "url": "https://github.com/sponsors/adamlui"
53
57
  },
54
58
  "devDependencies": {
55
- "@adamlui/minify.js": "^1.4.7"
59
+ "@adamlui/minify.js": "^1.4.9"
56
60
  }
57
61
  }