nt 0.7.3 → 0.8.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/dist/schema.js ADDED
@@ -0,0 +1,273 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.validate = exports.checkTorrent = exports.announceList = exports.isValidPathSegment = void 0;
40
+ const torrent_1 = __importDefault(require("./torrent"));
41
+ const util = __importStar(require("./util"));
42
+ /**
43
+ * Check if field that should be a buffer and exists is a buffer.
44
+ */
45
+ const checkBuffer = (torrent, field) => {
46
+ return torrent[field] && !Buffer.isBuffer(torrent[field])
47
+ ? `\`${field}\` is not a buffer`
48
+ : null;
49
+ };
50
+ /**
51
+ * Checks that a path segment is safe and does not traverse directories.
52
+ */
53
+ const isValidPathSegment = (buf) => {
54
+ if (!Buffer.isBuffer(buf) || buf.length === 0)
55
+ return false;
56
+ const str = buf.toString('utf8');
57
+ if (str === '.' || str === '..')
58
+ return false;
59
+ if (str.includes('/') || str.includes('\\') || str.includes('\0'))
60
+ return false;
61
+ if (/^[a-zA-Z]:/.test(str))
62
+ return false;
63
+ return true;
64
+ };
65
+ exports.isValidPathSegment = isValidPathSegment;
66
+ /**
67
+ * Checks announce fields are correct.
68
+ */
69
+ const checkAnnounce = (torrent) => {
70
+ let err;
71
+ if (torrent.announce) {
72
+ err = checkBuffer(torrent, 'announce');
73
+ if (err)
74
+ return err;
75
+ if (!util.isURL(torrent.announce))
76
+ return '`announce` is not a URL';
77
+ }
78
+ return null;
79
+ };
80
+ /**
81
+ * Checks announce list field.
82
+ */
83
+ const announceList = (list) => {
84
+ if (list) {
85
+ if (!Array.isArray(list))
86
+ return '`announce-list` is not a list';
87
+ for (const item of list) {
88
+ if (!Array.isArray(item)) {
89
+ return '`announce-list` is not a list of lists';
90
+ }
91
+ for (const ann of item) {
92
+ if (!Buffer.isBuffer(ann)) {
93
+ return 'Item in `announce-list` is not a buffer';
94
+ }
95
+ if (!util.isURL(ann)) {
96
+ return 'Item in `announce-list` list is not a URL';
97
+ }
98
+ }
99
+ }
100
+ }
101
+ return null;
102
+ };
103
+ exports.announceList = announceList;
104
+ /**
105
+ * Check if the creation date exists and is an integer.
106
+ */
107
+ const checkCreationDate = (date) => {
108
+ return date != null && !util.isInteger(date)
109
+ ? '`creation date` is not an integer'
110
+ : null;
111
+ };
112
+ /**
113
+ * Check md5 sum of torrent is correct.
114
+ */
115
+ const md5sumRegexp = /^[a-f0-9]{32}$/i;
116
+ const checkmd5sum = (parent) => {
117
+ if (parent.md5sum != null) {
118
+ if (!Buffer.isBuffer(parent.md5sum))
119
+ return '`md5sum` is not a buffer';
120
+ if (!md5sumRegexp.test(parent.md5sum.toString())) {
121
+ return '`md5sum` is not a 32 length hex in file';
122
+ }
123
+ }
124
+ return null;
125
+ };
126
+ /**
127
+ * Converts all buffers in the torrent object to utf8 strings.
128
+ * Except for the key `info.pieces` which will remain a buffer.
129
+ */
130
+ const buf2str = (torrent, currentPath) => {
131
+ Object.keys(torrent).forEach((key) => {
132
+ const val = torrent[key];
133
+ if (Buffer.isBuffer(val)) {
134
+ if (currentPath !== '.info' || key !== 'pieces') {
135
+ torrent[key] = val.toString('utf8');
136
+ }
137
+ }
138
+ else if (typeof val === 'object') {
139
+ buf2str(val, `${currentPath}.${key}`);
140
+ }
141
+ });
142
+ };
143
+ /**
144
+ * Checks torrent metadata is correct.
145
+ */
146
+ const checkTorrent = (torrentInput) => {
147
+ let err;
148
+ if (typeof torrentInput !== 'object' || torrentInput === null) {
149
+ return 'Torrent is not a hash';
150
+ }
151
+ const torrent = torrentInput;
152
+ err = checkAnnounce(torrent);
153
+ if (err)
154
+ return err;
155
+ err = (0, exports.announceList)(torrent['announce-list']);
156
+ if (err)
157
+ return err;
158
+ err = checkCreationDate(torrent['creation date']);
159
+ if (err)
160
+ return err;
161
+ err = checkBuffer(torrent, 'comment');
162
+ if (err)
163
+ return err;
164
+ err = checkBuffer(torrent, 'created by');
165
+ if (err)
166
+ return err;
167
+ err = checkBuffer(torrent, 'encoding');
168
+ if (err)
169
+ return err;
170
+ if (torrent.info == null)
171
+ return '`info` field not found';
172
+ const info = torrent.info;
173
+ // Multi file mode.
174
+ if (info.files != null) {
175
+ if (!Array.isArray(info.files))
176
+ return '`info.files` is not a list';
177
+ for (const fileItem of info.files) {
178
+ const file = fileItem;
179
+ if (file.length == null) {
180
+ return '`length` field not found in file';
181
+ }
182
+ if (!util.isInteger(file.length) || file.length < 0) {
183
+ return '`length` is not a positive integer in file';
184
+ }
185
+ err = checkmd5sum(file);
186
+ if (err)
187
+ return err;
188
+ if (!file.path)
189
+ return '`path` field not found in file';
190
+ if (!Array.isArray(file.path))
191
+ return '`path` is not a list in file';
192
+ if (file.path.length === 0)
193
+ return '`path` is empty in file';
194
+ if (!file.path.every(Buffer.isBuffer)) {
195
+ return '`path` is not a list of buffers in file';
196
+ }
197
+ if (!file.path.every(exports.isValidPathSegment)) {
198
+ return '`path` contains invalid path segments in file';
199
+ }
200
+ }
201
+ if (info.length != null) {
202
+ return 'Cannot have `info.length` in multi file mode';
203
+ }
204
+ if (info.md5sum != null) {
205
+ return 'Cannot have `info.md5sum` in multi file mode';
206
+ }
207
+ // Single file mode.
208
+ }
209
+ else {
210
+ if (info.length == null) {
211
+ return '`info.length` not found in single file mode';
212
+ }
213
+ if (!util.isInteger(info.length) || info.length < 0) {
214
+ return '`info.length` is not a positive integer in file';
215
+ }
216
+ err = checkmd5sum(info);
217
+ if (err)
218
+ return err;
219
+ }
220
+ if (info.name == null)
221
+ return '`info.name` not found';
222
+ err = checkBuffer(info, 'name');
223
+ if (err)
224
+ return err;
225
+ if (!(0, exports.isValidPathSegment)(info.name)) {
226
+ return '`name` contains invalid characters';
227
+ }
228
+ if (info['piece length'] == null) {
229
+ return '`info.piece length` not found';
230
+ }
231
+ const pieceLength = info['piece length'];
232
+ if (!util.isInteger(pieceLength) || pieceLength <= 0) {
233
+ return '`info.piece length` is not a positive integer';
234
+ }
235
+ const pieceLengthNum = pieceLength;
236
+ if (pieceLengthNum < 16384 || (pieceLengthNum & (pieceLengthNum - 1)) !== 0) {
237
+ return '`info.piece length` must be a power of 2 and at least 16384';
238
+ }
239
+ if (info.pieces == null)
240
+ return '`info.pieces` not found';
241
+ if (!Buffer.isBuffer(info.pieces)) {
242
+ return '`info.pieces` is not a buffer';
243
+ }
244
+ if (info.pieces.length % 20 !== 0) {
245
+ return '`info.pieces` length is not divisible by 20';
246
+ }
247
+ if (info.private != null && info.private !== 0 && info.private !== 1) {
248
+ return '`info.private` can only be 0 or 1';
249
+ }
250
+ err = checkBuffer(info, 'source');
251
+ if (err)
252
+ return err;
253
+ return null;
254
+ };
255
+ exports.checkTorrent = checkTorrent;
256
+ /**
257
+ * Checks a torrent object, makes sure its metadata matches the schema.
258
+ */
259
+ const validate = (torrent, callback) => {
260
+ const errmsg = (0, exports.checkTorrent)(torrent);
261
+ if (errmsg !== null) {
262
+ const err = Error(errmsg);
263
+ err.name = 'SchemaError';
264
+ callback(err);
265
+ return;
266
+ }
267
+ // Convert all buffers into strings that are not hash pieces.
268
+ buf2str(torrent, '');
269
+ // Put metadata into torrent object and call callback with the result.
270
+ callback(null, new torrent_1.default(torrent));
271
+ };
272
+ exports.validate = validate;
273
+ //# sourceMappingURL=schema.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.js","sourceRoot":"","sources":["../src/schema.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,wDAA0D;AAC1D,6CAA+B;AAI/B;;GAEG;AACH,MAAM,WAAW,GAAG,CAAC,OAAgB,EAAE,KAAa,EAAiB,EAAE;IACrE,OAAO,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;QACvD,CAAC,CAAC,KAAK,KAAK,oBAAoB;QAChC,CAAC,CAAC,IAAI,CAAC;AACX,CAAC,CAAC;AAEF;;GAEG;AACI,MAAM,kBAAkB,GAAG,CAAC,GAAY,EAAW,EAAE;IAC1D,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAC5D,MAAM,GAAG,GAAG,GAAG,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;IACjC,IAAI,GAAG,KAAK,GAAG,IAAI,GAAG,KAAK,IAAI;QAAE,OAAO,KAAK,CAAC;IAC9C,I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,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC;QAClC,OAAO,+BAA+B,CAAC;IACzC,CAAC;IACD,IAAI,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,EAAE,KAAK,CAAC,EAAE,CAAC;QAClC,OAAO,6CAA6C,CAAC;IACvD,CAAC;IACD,IAAI,IAAI,CAAC,OAAO,IAAI,IAAI,IAAI,IAAI,CAAC,OAAO,KAAK,CAAC,IAAI,IAAI,CAAC,OAAO,KAAK,CAAC,EAAE,CAAC;QACrE,OAAO,mCAAmC,CAAC;IAC7C,CAAC;IACD,GAAG,GAAG,WAAW,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;IAClC,IAAI,GAAG;QAAE,OAAO,GAAG,CAAC;IACpB,OAAO,IAAI,CAAC;AACd,CAAC,CAAC;AAjGW,QAAA,YAAY,gBAiGvB;AAEF;;GAEG;AACI,MAAM,QAAQ,GAAG,CACtB,OAAgB,EAChB,QAAwD,EAClD,EAAE;IACR,MAAM,MAAM,GAAG,IAAA,oBAAY,EAAC,OAAO,CAAC,CAAC;IACrC,IAAI,MAAM,KAAK,IAAI,EAAE,CAAC;QACpB,MAAM,GAAG,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC;QAC1B,GAAG,CAAC,IAAI,GAAG,aAAa,CAAC;QACzB,QAAQ,CAAC,GAAG,CAAC,CAAC;QACd,OAAO;IACT,CAAC;IAED,6DAA6D;IAC7D,OAAO,CAAC,OAAkB,EAAE,EAAE,CAAC,CAAC;IAEhC,sEAAsE;IACtE,QAAQ,CAAC,IAAI,EAAE,IAAI,iBAAO,CAAC,OAA0B,CAAC,CAAC,CAAC;AAC1D,CAAC,CAAC;AAjBW,QAAA,QAAQ,YAiBnB"}
@@ -0,0 +1,48 @@
1
+ import fs from 'node:fs';
2
+ import MemoryStream from 'memorystream';
3
+ import Hasher, { type FileEntry, type HasherOptions } from './hasher';
4
+ export interface TorrentInfo {
5
+ name?: string;
6
+ 'piece length': number;
7
+ pieces: Buffer | null;
8
+ private?: 0 | 1;
9
+ source?: string;
10
+ length?: number;
11
+ md5sum?: string;
12
+ files?: FileEntry[];
13
+ [key: string]: unknown;
14
+ }
15
+ export interface TorrentMetadata {
16
+ announce?: string;
17
+ 'announce-list'?: Array<Array<string | Buffer>>;
18
+ 'creation date'?: number;
19
+ comment?: string;
20
+ 'created by'?: string;
21
+ encoding?: string;
22
+ info: TorrentInfo;
23
+ [key: string]: unknown;
24
+ }
25
+ export default class Torrent {
26
+ metadata: TorrentMetadata;
27
+ /**
28
+ * @constructor
29
+ */
30
+ constructor(metadata: TorrentMetadata);
31
+ /**
32
+ * Returns info hash of torrent
33
+ */
34
+ infoHash(): string;
35
+ /**
36
+ * Creates a readable stream that emits raw torrent data.
37
+ */
38
+ createReadStream(): MemoryStream;
39
+ /**
40
+ * Shortcut to pipe the readable stream created by Torrent#createReadStream
41
+ * to a writable stream of a file, then return it.
42
+ */
43
+ createWriteStream(filepath: string, options?: BufferEncoding | Record<string, unknown>): fs.WriteStream;
44
+ /**
45
+ * Hash checks torrent.
46
+ */
47
+ hashCheck(dir: string, options?: HasherOptions): Hasher;
48
+ }
@@ -0,0 +1,117 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ const node_crypto_1 = __importDefault(require("node:crypto"));
40
+ const node_fs_1 = __importDefault(require("node:fs"));
41
+ const b = __importStar(require("bncode"));
42
+ const memorystream_1 = __importDefault(require("memorystream"));
43
+ const hasher_1 = __importDefault(require("./hasher"));
44
+ const util_1 = require("./util");
45
+ class Torrent {
46
+ metadata;
47
+ /**
48
+ * @constructor
49
+ */
50
+ constructor(metadata) {
51
+ this.metadata = metadata;
52
+ }
53
+ /**
54
+ * Returns info hash of torrent
55
+ */
56
+ infoHash() {
57
+ return node_crypto_1.default
58
+ .createHash('sha1')
59
+ .update(b.encode(this.metadata.info))
60
+ .digest('hex');
61
+ }
62
+ /**
63
+ * Creates a readable stream that emits raw torrent data.
64
+ */
65
+ createReadStream() {
66
+ const memStream = new memorystream_1.default();
67
+ memStream.readable = true;
68
+ // Bencode data and emit it from readstream.
69
+ const data = b.encode(this.metadata);
70
+ process.nextTick(() => {
71
+ memStream.write(data, () => {
72
+ memStream.emit('end');
73
+ });
74
+ });
75
+ return memStream;
76
+ }
77
+ /**
78
+ * Shortcut to pipe the readable stream created by Torrent#createReadStream
79
+ * to a writable stream of a file, then return it.
80
+ */
81
+ createWriteStream(filepath, options) {
82
+ const rs = this.createReadStream();
83
+ const ws = node_fs_1.default.createWriteStream(filepath, options);
84
+ rs.pipe(ws);
85
+ return ws;
86
+ }
87
+ /**
88
+ * Hash checks torrent.
89
+ */
90
+ hashCheck(dir, options) {
91
+ options = options || {};
92
+ const info = this.metadata.info;
93
+ // Check if this is a single or multi file mode torrent.
94
+ const files = info.files || [
95
+ { path: [info.name], length: info.length },
96
+ ];
97
+ // Call the hasher.
98
+ const hashOptions = { maxFiles: options.maxFiles };
99
+ const hasher = new hasher_1.default(dir, files, info['piece length'], hashOptions);
100
+ let percentMatched = 0;
101
+ let piecesMatched = 0;
102
+ const pieces = info.pieces.length / 20;
103
+ hasher.on('hash', (index, hash, file, position, length) => {
104
+ // Check that hash matches.
105
+ if ((0, util_1.buffersMatch)(info.pieces, hash, index * 20)) {
106
+ percentMatched = Math.round((++piecesMatched / pieces) * 10000) / 100;
107
+ hasher.emit('match', index, hash, percentMatched, file, position, length);
108
+ }
109
+ else {
110
+ hasher.emit('matcherror', index, file, position, length);
111
+ }
112
+ });
113
+ return hasher;
114
+ }
115
+ }
116
+ exports.default = Torrent;
117
+ //# sourceMappingURL=torrent.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"torrent.js","sourceRoot":"","sources":["../src/torrent.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,8DAAiC;AACjC,sDAAyB;AACzB,0CAA4B;AAC5B,gEAAwC;AAExC,sDAAsE;AACtE,iCAAsC;AAyBtC,MAAqB,OAAO;IACnB,QAAQ,CAAkB;IAEjC;;OAEG;IACH,YAAY,QAAyB;QACnC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC3B,CAAC;IAED;;OAEG;IACH,QAAQ;QACN,OAAO,qBAAM;aACV,UAAU,CAAC,MAAM,CAAC;aAClB,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;aACpC,MAAM,CAAC,KAAK,CAAC,CAAC;IACnB,CAAC;IAED;;OAE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AAC,CAAC;QACzE,IAAI,cAAc,GAAG,CAAC,CAAC;QACvB,IAAI,aAAa,GAAG,CAAC,CAAC;QACtB,MAAM,MAAM,GAAI,IAAI,CAAC,MAAiB,CAAC,MAAM,GAAG,EAAE,CAAC;QAEnD,MAAM,CAAC,EAAE,CACP,MAAM,EACN,CACE,KAAa,EACb,IAAY,EACZ,IAAY,EACZ,QAAgB,EAChB,MAAc,EACd,EAAE;YACF,2BAA2B;YAC3B,IAAI,IAAA,mBAAY,EAAC,IAAI,CAAC,MAAgB,EAAE,IAAI,EAAE,KAAK,GAAG,EAAE,CAAC,EAAE,CAAC;gBAC1D,cAAc,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,aAAa,GAAG,MAAM,CAAC,GAAG,KAAK,CAAC,GAAG,GAAG,CAAC;gBACtE,MAAM,CAAC,IAAI,CACT,OAAO,EACP,KAAK,EACL,IAAI,EACJ,cAAc,EACd,IAAI,EACJ,QAAQ,EACR,MAAM,CACP,CAAC;YACJ,CAAC;iBAAM,CAAC;gBACN,MAAM,CAAC,IAAI,CAAC,YAAY,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC;YAC3D,CAAC;QACH,CAAC,CACF,CAAC;QAEF,OAAO,MAAM,CAAC;IAChB,CAAC;CACF;AAzGD,0BAyGC"}
package/dist/util.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Returns true if str is a URL.
3
+ */
4
+ export declare const isURL: (str: string | Buffer) => boolean;
5
+ /**
6
+ * Returns true if n is an integer.
7
+ */
8
+ export declare const isInteger: (n: unknown) => boolean;
9
+ /**
10
+ * Splits a path into an array, platform safe.
11
+ */
12
+ export declare const splitPath: (filepath: string) => string[];
13
+ /**
14
+ * Returns true if part of buffer `b` beginning at `start` matches buffer `a`.
15
+ */
16
+ export declare const buffersMatch: (a: Buffer, b: Buffer, start: number) => boolean;
package/dist/util.js ADDED
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.buffersMatch = exports.splitPath = exports.isInteger = exports.isURL = void 0;
7
+ const node_path_1 = __importDefault(require("node:path"));
8
+ const urlRegexp = /^(http|udp|ftp|dht)s?:\/\//;
9
+ /**
10
+ * Returns true if str is a URL.
11
+ */
12
+ const isURL = (str) => urlRegexp.test(str.toString());
13
+ exports.isURL = isURL;
14
+ /**
15
+ * Returns true if n is an integer.
16
+ */
17
+ const isInteger = (n) => !Number.isNaN(Number.parseInt(String(n), 10));
18
+ exports.isInteger = isInteger;
19
+ /**
20
+ * Splits a path into an array, platform safe.
21
+ */
22
+ const splitPath = (filepath) => filepath.split(node_path_1.default.sep);
23
+ exports.splitPath = splitPath;
24
+ /**
25
+ * Returns true if part of buffer `b` beginning at `start` matches buffer `a`.
26
+ */
27
+ const buffersMatch = (a, b, start) => {
28
+ for (let i = 0, l = b.length; i < l; i++) {
29
+ if (a[start + i] !== b[i]) {
30
+ return false;
31
+ }
32
+ }
33
+ return true;
34
+ };
35
+ exports.buffersMatch = buffersMatch;
36
+ //# sourceMappingURL=util.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"util.js","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":";;;;;;AAAA,0DAA6B;AAE7B,MAAM,SAAS,GAAG,4BAA4B,CAAC;AAE/C;;GAEG;AACI,MAAM,KAAK,GAAG,CAAC,GAAoB,EAAW,EAAE,CACrD,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC;AADpB,QAAA,KAAK,SACe;AAEjC;;GAEG;AACI,MAAM,SAAS,GAAG,CAAC,CAAU,EAAW,EAAE,CAC/C,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;AADnC,QAAA,SAAS,aAC0B;AAEhD;;GAEG;AACI,MAAM,SAAS,GAAG,CAAC,QAAgB,EAAY,EAAE,CACtD,QAAQ,CAAC,KAAK,CAAC,mBAAI,CAAC,GAAG,CAAC,CAAC;AADd,QAAA,SAAS,aACK;AAE3B;;GAEG;AACI,MAAM,YAAY,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,KAAa,EAAW,EAAE;IAC3E,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC;QACzC,IAAI,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;YAC1B,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC,CAAC;AARW,QAAA,YAAY,gBAQvB"}
package/package.json CHANGED
@@ -6,22 +6,24 @@
6
6
  "bittorremt",
7
7
  "file"
8
8
  ],
9
- "version": "0.7.3",
9
+ "version": "0.8.0",
10
10
  "repository": {
11
11
  "type": "git",
12
12
  "url": "git://github.com/fent/node-torrent.git"
13
13
  },
14
14
  "author": "fent <fentbox@gmail.com> (https://github.com/fent)",
15
- "main": "./lib/index.js",
16
- "types": "./lib/index.d.ts",
15
+ "main": "./dist/index.js",
17
16
  "files": [
18
- "lib"
17
+ "dist"
19
18
  ],
20
- "directories": {
21
- "lib": "./lib"
22
- },
23
19
  "scripts": {
24
- "test": "nyc mocha test/*-test.js"
20
+ "prepare": "tsc -p tsconfig.build.json",
21
+ "build": "tsc -p tsconfig.build.json",
22
+ "lint": "biome check .",
23
+ "lint:fix": "biome check --write .",
24
+ "test": "nyc --extension .ts --reporter=lcov --reporter=text-summary npm run test:unit && npm run test:package",
25
+ "test:unit": "mocha --require ts-node/register --ignore test/export-test.ts test/*-test.ts",
26
+ "test:package": "mocha --require ts-node/register test/export-test.ts"
25
27
  },
26
28
  "dependencies": {
27
29
  "async": "^3.2.0",
@@ -32,13 +34,17 @@
32
34
  "streamspeed": "~2.0.0"
33
35
  },
34
36
  "devDependencies": {
37
+ "@biomejs/biome": "2.5.15",
38
+ "@types/mocha": "^10.0.10",
39
+ "@types/node": "^20.19.43",
35
40
  "chai": "6.2.1",
36
41
  "mocha": "12.0.3",
37
- "nyc": "18.0.0"
42
+ "nyc": "18.0.0",
43
+ "ts-node": "^10.9.2",
44
+ "typescript": "^5.9.3"
38
45
  },
39
46
  "engines": {
40
47
  "node": ">=6"
41
48
  },
42
- "license": "MIT",
43
- "snyk": true
49
+ "license": "MIT"
44
50
  }