Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
header.js288 linesDownload Raw Back to esm
1// parse a 512-byte header block to a data object, or vice-versa
2// encode returns `true` if a pax extended header is needed, because
3// the data could not be faithfully encoded in a simple header.
4// (Also, check header.needPax to see if it needs a pax header.)
5import { posix as pathModule } from 'node:path';
6import * as large from './large-numbers.js';
7import * as types from './types.js';
8export class Header {
9    cksumValid = false;
10    needPax = false;
11    nullBlock = false;
12    block;
13    path;
14    mode;
15    uid;
16    gid;
17    size;
18    cksum;
19    #type = 'Unsupported';
20    linkpath;
21    uname;
22    gname;
23    devmaj = 0;
24    devmin = 0;
25    atime;
26    ctime;
27    mtime;
28    charset;
29    comment;
30    constructor(data, off = 0, ex, gex) {
31        if (Buffer.isBuffer(data)) {
32            this.decode(data, off || 0, ex, gex);
33        }
34        else if (data) {
35            this.#slurp(data);
36        }
37    }
38    decode(buf, off, ex, gex) {
39        if (!off) {
40            off = 0;
41        }
42        if (!buf || !(buf.length >= off + 512)) {
43            throw new Error('need 512 bytes for header');
44        }
45        this.path = ex?.path ?? decString(buf, off, 100);
46        this.mode = ex?.mode ?? gex?.mode ?? decNumber(buf, off + 100, 8);
47        this.uid = ex?.uid ?? gex?.uid ?? decNumber(buf, off + 108, 8);
48        this.gid = ex?.gid ?? gex?.gid ?? decNumber(buf, off + 116, 8);
49        this.size = ex?.size ?? gex?.size ?? decNumber(buf, off + 124, 12);
50        this.mtime =
51            ex?.mtime ?? gex?.mtime ?? decDate(buf, off + 136, 12);
52        this.cksum = decNumber(buf, off + 148, 12);
53        // if we have extended or global extended headers, apply them now
54        // See https://github.com/npm/node-tar/pull/187
55        // Apply global before local, so it overrides
56        if (gex)
57            this.#slurp(gex, true);
58        if (ex)
59            this.#slurp(ex);
60        // old tar versions marked dirs as a file with a trailing /
61        const t = decString(buf, off + 156, 1);
62        if (types.isCode(t)) {
63            this.#type = t || '0';
64        }
65        if (this.#type === '0' && this.path.slice(-1) === '/') {
66            this.#type = '5';
67        }
68        // tar implementations sometimes incorrectly put the stat(dir).size
69        // as the size in the tarball, even though Directory entries are
70        // not able to have any body at all.  In the very rare chance that
71        // it actually DOES have a body, we weren't going to do anything with
72        // it anyway, and it'll just be a warning about an invalid header.
73        if (this.#type === '5') {
74            this.size = 0;
75        }
76        this.linkpath = decString(buf, off + 157, 100);
77        if (buf.subarray(off + 257, off + 265).toString() ===
78            'ustar\u000000') {
79            /* c8 ignore start */
80            this.uname =
81                ex?.uname ?? gex?.uname ?? decString(buf, off + 265, 32);
82            this.gname =
83                ex?.gname ?? gex?.gname ?? decString(buf, off + 297, 32);
84            this.devmaj =
85                ex?.devmaj ?? gex?.devmaj ?? decNumber(buf, off + 329, 8) ?? 0;
86            this.devmin =
87                ex?.devmin ?? gex?.devmin ?? decNumber(buf, off + 337, 8) ?? 0;
88            /* c8 ignore stop */
89            if (buf[off + 475] !== 0) {
90                // definitely a prefix, definitely >130 chars.
91                const prefix = decString(buf, off + 345, 155);
92                this.path = prefix + '/' + this.path;
93            }
94            else {
95                const prefix = decString(buf, off + 345, 130);
96                if (prefix) {
97                    this.path = prefix + '/' + this.path;
98                }
99                /* c8 ignore start */
100                this.atime =
101                    ex?.atime ?? gex?.atime ?? decDate(buf, off + 476, 12);
102                this.ctime =
103                    ex?.ctime ?? gex?.ctime ?? decDate(buf, off + 488, 12);
104                /* c8 ignore stop */
105            }
106        }
107        let sum = 8 * 0x20;
108        for (let i = off; i < off + 148; i++) {
109            sum += buf[i];
110        }
111        for (let i = off + 156; i < off + 512; i++) {
112            sum += buf[i];
113        }
114        this.cksumValid = sum === this.cksum;
115        if (this.cksum === undefined && sum === 8 * 0x20) {
116            this.nullBlock = true;
117        }
118    }
119    #slurp(ex, gex = false) {
120        Object.assign(this, Object.fromEntries(Object.entries(ex).filter(([k, v]) => {
121            // we slurp in everything except for the path attribute in
122            // a global extended header, because that's weird. Also, any
123            // null/undefined values are ignored.
124            return !(v === null ||
125                v === undefined ||
126                (k === 'path' && gex) ||
127                (k === 'linkpath' && gex) ||
128                k === 'global');
129        })));
130    }
131    encode(buf, off = 0) {
132        if (!buf) {
133            buf = this.block = Buffer.alloc(512);
134        }
135        if (this.#type === 'Unsupported') {
136            this.#type = '0';
137        }
138        if (!(buf.length >= off + 512)) {
139            throw new Error('need 512 bytes for header');
140        }
141        const prefixSize = this.ctime || this.atime ? 130 : 155;
142        const split = splitPrefix(this.path || '', prefixSize);
143        const path = split[0];
144        const prefix = split[1];
145        this.needPax = !!split[2];
146        this.needPax = encString(buf, off, 100, path) || this.needPax;
147        this.needPax =
148            encNumber(buf, off + 100, 8, this.mode) || this.needPax;
149        this.needPax =
150            encNumber(buf, off + 108, 8, this.uid) || this.needPax;
151        this.needPax =
152            encNumber(buf, off + 116, 8, this.gid) || this.needPax;
153        this.needPax =
154            encNumber(buf, off + 124, 12, this.size) || this.needPax;
155        this.needPax =
156            encDate(buf, off + 136, 12, this.mtime) || this.needPax;
157        buf[off + 156] = this.#type.charCodeAt(0);
158        this.needPax =
159            encString(buf, off + 157, 100, this.linkpath) || this.needPax;
160        buf.write('ustar\u000000', off + 257, 8);
161        this.needPax =
162            encString(buf, off + 265, 32, this.uname) || this.needPax;
163        this.needPax =
164            encString(buf, off + 297, 32, this.gname) || this.needPax;
165        this.needPax =
166            encNumber(buf, off + 329, 8, this.devmaj) || this.needPax;
167        this.needPax =
168            encNumber(buf, off + 337, 8, this.devmin) || this.needPax;
169        this.needPax =
170            encString(buf, off + 345, prefixSize, prefix) || this.needPax;
171        if (buf[off + 475] !== 0) {
172            this.needPax =
173                encString(buf, off + 345, 155, prefix) || this.needPax;
174        }
175        else {
176            this.needPax =
177                encString(buf, off + 345, 130, prefix) || this.needPax;
178            this.needPax =
179                encDate(buf, off + 476, 12, this.atime) || this.needPax;
180            this.needPax =
181                encDate(buf, off + 488, 12, this.ctime) || this.needPax;
182        }
183        let sum = 8 * 0x20;
184        for (let i = off; i < off + 148; i++) {
185            sum += buf[i];
186        }
187        for (let i = off + 156; i < off + 512; i++) {
188            sum += buf[i];
189        }
190        this.cksum = sum;
191        encNumber(buf, off + 148, 8, this.cksum);
192        this.cksumValid = true;
193        return this.needPax;
194    }
195    get type() {
196        return (this.#type === 'Unsupported' ?
197            this.#type
198            : types.name.get(this.#type));
199    }
200    get typeKey() {
201        return this.#type;
202    }
203    set type(type) {
204        const c = String(types.code.get(type));
205        if (types.isCode(c) || c === 'Unsupported') {
206            this.#type = c;
207        }
208        else if (types.isCode(type)) {
209            this.#type = type;
210        }
211        else {
212            throw new TypeError('invalid entry type: ' + type);
213        }
214    }
215}
216const splitPrefix = (p, prefixSize) => {
217    const pathSize = 100;
218    let pp = p;
219    let prefix = '';
220    let ret = undefined;
221    const root = pathModule.parse(p).root || '.';
222    if (Buffer.byteLength(pp) < pathSize) {
223        ret = [pp, prefix, false];
224    }
225    else {
226        // first set prefix to the dir, and path to the base
227        prefix = pathModule.dirname(pp);
228        pp = pathModule.basename(pp);
229        do {
230            if (Buffer.byteLength(pp) <= pathSize &&
231                Buffer.byteLength(prefix) <= prefixSize) {
232                // both fit!
233                ret = [pp, prefix, false];
234            }
235            else if (Buffer.byteLength(pp) > pathSize &&
236                Buffer.byteLength(prefix) <= prefixSize) {
237                // prefix fits in prefix, but path doesn't fit in path
238                ret = [pp.slice(0, pathSize - 1), prefix, true];
239            }
240            else {
241                // make path take a bit from prefix
242                pp = pathModule.join(pathModule.basename(prefix), pp);
243                prefix = pathModule.dirname(prefix);
244            }
245        } while (prefix !== root && ret === undefined);
246        // at this point, found no resolution, just truncate
247        if (!ret) {
248            ret = [p.slice(0, pathSize - 1), '', true];
249        }
250    }
251    return ret;
252};
253const decString = (buf, off, size) => buf
254    .subarray(off, off + size)
255    .toString('utf8')
256    .replace(/\0.*/, '');
257const decDate = (buf, off, size) => numToDate(decNumber(buf, off, size));
258const numToDate = (num) => num === undefined ? undefined : new Date(num * 1000);
259const decNumber = (buf, off, size) => Number(buf[off]) & 0x80 ?
260    large.parse(buf.subarray(off, off + size))
261    : decSmallNumber(buf, off, size);
262const nanUndef = (value) => (isNaN(value) ? undefined : value);
263const decSmallNumber = (buf, off, size) => nanUndef(parseInt(buf
264    .subarray(off, off + size)
265    .toString('utf8')
266    .replace(/\0.*$/, '')
267    .trim(), 8));
268// the maximum encodable as a null-terminated octal, by field size
269const MAXNUM = {
270    12: 0o77777777777,
271    8: 0o7777777,
272};
273const encNumber = (buf, off, size, num) => num === undefined ? false
274    : num > MAXNUM[size] || num < 0 ?
275        (large.encode(num, buf.subarray(off, off + size)), true)
276        : (encSmallNumber(buf, off, size, num), false);
277const encSmallNumber = (buf, off, size, num) => buf.write(octalString(num, size), off, size, 'ascii');
278const octalString = (num, size) => padOctal(Math.floor(num).toString(8), size);
279const padOctal = (str, size) => (str.length === size - 1 ?
280    str
281    : new Array(size - str.length - 1).join('0') + str + ' ') + '\0';
282const encDate = (buf, off, size, date) => date === undefined ? false : (encNumber(buf, off, size, date.getTime() / 1000));
283// enough to fill the longest string we've got
284const NULLS = new Array(156).join('\0');
285// pad with nulls, return true if it's longer or non-ascii
286const encString = (buf, off, size, str) => str === undefined ? false : ((buf.write(str + NULLS, off, size, 'utf8'),
287    str.length !== Buffer.byteLength(str) || str.length > size));
288//# sourceMappingURL=header.js.map
codekingpro/portable-devtools · Team Ai