kitcheck 0.0.0-stage → 0.1.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/src/rules.js ADDED
@@ -0,0 +1,521 @@
1
+ // The rules kitcheck runs. Each rule has an id, a default severity, a short
2
+ // description, and one or more hooks:
3
+ //
4
+ // document(doc, ctx) runs once per Elementor file
5
+ // element(el, info, doc, ctx) runs for every element in a file
6
+ // project(project, docs, ctx) runs once per folder, ZIP or file
7
+ //
8
+ // Hooks call ctx.report({ message, pointer?, element?, file? }).
9
+
10
+ import path from 'node:path';
11
+ import {
12
+ canHaveChildren,
13
+ CLASSIC_EL_TYPES,
14
+ classifyWidget,
15
+ isAtomicType,
16
+ MIN_VERSIONS,
17
+ TEMPLATE_TYPES,
18
+ } from './data/elementor.js';
19
+ import { isObject } from './document.js';
20
+ import { compareVersions } from './version.js';
21
+
22
+ const ID_PATTERN = /^[A-Za-z0-9_-]{1,32}$/;
23
+ const URL_PATTERN = /\bhttps?:\/\/[^\s"'<>()\\]+/gi;
24
+ const MEDIA_PATTERN =
25
+ /\.(png|jpe?g|gif|webp|avif|svg|ico|bmp|tiff?|mp4|webm|mov|ogv|mp3|wav|m4a|ogg|woff2?|ttf|otf|eot|json|lottie|pdf)([?#]|$)/i;
26
+ const PLACEHOLDER_PATTERN = /\/elementor\/assets\/images\/placeholder/i;
27
+ const DEV_TLDS = ['localhost', 'local', 'test', 'lan', 'internal', 'invalid'];
28
+ const DEV_LABELS = new Set(['staging', 'stage']);
29
+
30
+ export const rules = [
31
+ {
32
+ id: 'structure/empty',
33
+ severity: 'warning',
34
+ description: 'The file has no elements, so importing it creates an empty template.',
35
+ document(doc, ctx) {
36
+ if (doc.usage.elements === 0 && doc.format !== 'kit-manifest') {
37
+ ctx.report({ message: 'This file has no elements. Importing it creates an empty template.' });
38
+ }
39
+ },
40
+ },
41
+ {
42
+ id: 'structure/element',
43
+ severity: 'error',
44
+ description: 'Every element must be an object with an elType, and "elements" must be an array.',
45
+ element(el, info, doc, ctx) {
46
+ if (!isObject(el)) {
47
+ ctx.report({ pointer: info.pointer, message: `Expected an element object but found ${describe(el)}.` });
48
+ return;
49
+ }
50
+ if (typeof el.elType !== 'string' || el.elType === '') {
51
+ ctx.report({ pointer: info.pointer, element: el, message: 'This element has no "elType", so Elementor cannot render it.' });
52
+ }
53
+ if ('elements' in el && !Array.isArray(el.elements)) {
54
+ ctx.report({
55
+ pointer: `${info.pointer}/elements`,
56
+ element: el,
57
+ message: `"elements" must be an array but is ${describe(el.elements)}.`,
58
+ });
59
+ }
60
+ },
61
+ },
62
+ {
63
+ id: 'structure/unknown-type',
64
+ severity: 'warning',
65
+ description: 'The element type is not one Elementor uses.',
66
+ element(el, info, doc, ctx) {
67
+ if (!isObject(el) || typeof el.elType !== 'string' || el.elType === '') return;
68
+ if (CLASSIC_EL_TYPES.has(el.elType) || isAtomicType(el.elType)) return;
69
+ ctx.report({
70
+ pointer: info.pointer,
71
+ element: el,
72
+ message: `"${el.elType}" is not an Elementor element type. Expected section, column, container, widget or an atomic "e-" type.`,
73
+ });
74
+ },
75
+ },
76
+ {
77
+ id: 'structure/widget-type',
78
+ severity: 'error',
79
+ description: 'Widgets must say which widget they are.',
80
+ element(el, info, doc, ctx) {
81
+ if (!isObject(el) || el.elType !== 'widget') return;
82
+ if (typeof el.widgetType !== 'string' || el.widgetType === '') {
83
+ ctx.report({ pointer: info.pointer, element: el, message: 'This widget has no "widgetType", so Elementor cannot render it.' });
84
+ }
85
+ },
86
+ },
87
+ {
88
+ id: 'structure/nesting',
89
+ severity: 'error',
90
+ description: 'Sections hold columns, columns sit inside sections, and pages start with sections or containers.',
91
+ element(el, info, doc, ctx) {
92
+ if (!isObject(el)) return;
93
+ const parentType = isObject(info.parent) ? info.parent.elType : null;
94
+ if (el.elType === 'column' && parentType !== 'section') {
95
+ ctx.report({
96
+ pointer: info.pointer,
97
+ element: el,
98
+ message: parentType
99
+ ? `A column is inside a ${parentType}. Columns can only sit inside sections.`
100
+ : 'A column is at the top level. Columns can only sit inside sections.',
101
+ });
102
+ }
103
+ if (parentType === 'section' && el.elType !== 'column') {
104
+ ctx.report({
105
+ pointer: info.pointer,
106
+ element: el,
107
+ message: `A section contains a ${el.elType ?? 'element without an elType'}. Sections can only contain columns.`,
108
+ });
109
+ }
110
+ if (
111
+ info.parent === null &&
112
+ el.elType === 'widget' &&
113
+ doc.format !== 'clipboard' &&
114
+ !(doc.format === 'template' && doc.data.type === 'widget')
115
+ ) {
116
+ ctx.report({
117
+ pointer: info.pointer,
118
+ element: el,
119
+ message: 'A widget is at the top level. Put it inside a section or container.',
120
+ });
121
+ }
122
+ },
123
+ },
124
+ {
125
+ id: 'structure/widget-children',
126
+ severity: 'warning',
127
+ description: 'Only nested widgets (such as nested tabs) can contain other elements.',
128
+ element(el, info, doc, ctx) {
129
+ if (!isObject(el) || el.elType !== 'widget' || typeof el.widgetType !== 'string') return;
130
+ if (!Array.isArray(el.elements) || el.elements.length === 0) return;
131
+ if (canHaveChildren(el.widgetType) || classifyWidget(el.widgetType) === 'addon') return;
132
+ ctx.report({
133
+ pointer: `${info.pointer}/elements`,
134
+ element: el,
135
+ message: `The "${el.widgetType}" widget has ${el.elements.length} child element(s). Elementor ignores children of this widget.`,
136
+ });
137
+ },
138
+ },
139
+ {
140
+ id: 'structure/settings',
141
+ severity: 'error',
142
+ description: '"settings" must be an object.',
143
+ element(el, info, doc, ctx) {
144
+ if (!isObject(el) || !('settings' in el)) return;
145
+ const s = el.settings;
146
+ // PHP exports an empty settings object as an empty array.
147
+ if (isObject(s) || (Array.isArray(s) && s.length === 0)) return;
148
+ ctx.report({
149
+ pointer: `${info.pointer}/settings`,
150
+ element: el,
151
+ message: `"settings" must be an object but is ${describe(s)}.`,
152
+ });
153
+ },
154
+ },
155
+ {
156
+ id: 'ids/missing',
157
+ severity: 'error',
158
+ description: 'Every element needs an id.',
159
+ element(el, info, doc, ctx) {
160
+ if (!isObject(el)) return;
161
+ if (el.id === undefined || el.id === null || el.id === '') {
162
+ ctx.report({ pointer: info.pointer, element: el, message: 'This element has no "id". Elementor needs one to edit and style it.' });
163
+ }
164
+ },
165
+ },
166
+ {
167
+ id: 'ids/duplicate',
168
+ severity: 'error',
169
+ description: 'Element ids must be unique within a file.',
170
+ element(el, info, doc, ctx) {
171
+ if (!isObject(el) || typeof el.id !== 'string' || el.id === '') return;
172
+ const seen = (doc.state.ids ??= new Map());
173
+ if (seen.has(el.id)) {
174
+ ctx.report({
175
+ pointer: info.pointer,
176
+ element: el,
177
+ message: `The id "${el.id}" is also used ${where(ctx, seen.get(el.id))}. Duplicate ids make styles and edits apply to the wrong element.`,
178
+ });
179
+ } else {
180
+ seen.set(el.id, info.pointer);
181
+ }
182
+ },
183
+ },
184
+ {
185
+ id: 'ids/format',
186
+ severity: 'warning',
187
+ description: 'Element ids should be short strings of letters and numbers, like the ones Elementor creates.',
188
+ element(el, info, doc, ctx) {
189
+ if (!isObject(el) || el.id === undefined || el.id === null || el.id === '') return;
190
+ if (typeof el.id === 'string' && ID_PATTERN.test(el.id)) return;
191
+ ctx.report({
192
+ pointer: `${info.pointer}/id`,
193
+ element: el,
194
+ message: `The id ${JSON.stringify(el.id)} does not look like an Elementor id. Elementor uses short strings such as "3f2a9c1", and odd ids can break CSS selectors.`,
195
+ });
196
+ },
197
+ },
198
+ {
199
+ id: 'deps/pro',
200
+ severity: 'warning',
201
+ description: 'The file uses Elementor Pro features. Turn this rule off with --pro when the site has Pro.',
202
+ document(doc, ctx) {
203
+ if (ctx.options.pro) return;
204
+ for (const use of doc.usage.pro) {
205
+ ctx.report({
206
+ pointer: use.pointer,
207
+ element: use.element,
208
+ message: `Needs Elementor Pro: uses ${use.reason}. Without Pro this part will not work. Pass --pro if the site has Pro.`,
209
+ });
210
+ }
211
+ },
212
+ },
213
+ {
214
+ id: 'deps/addon',
215
+ severity: 'warning',
216
+ description: 'The file uses widgets from other plugins, which must be installed on the site.',
217
+ document(doc, ctx) {
218
+ for (const [type, entry] of doc.usage.addons) {
219
+ if (ctx.options.knownWidgets.has(type)) continue;
220
+ if (ctx.options.knownPrefixes.some((p) => type.startsWith(p))) continue;
221
+ const source = entry.plugin ? `It probably comes from ${entry.plugin}` : 'It probably comes from an addon plugin';
222
+ const times = entry.count > 1 ? ` (used ${entry.count} times)` : '';
223
+ ctx.report({
224
+ pointer: entry.pointer,
225
+ message: `"${type}" is not an Elementor or Elementor Pro widget${times}. ${source}, which must be active on the site or the widget will not render.`,
226
+ });
227
+ }
228
+ },
229
+ },
230
+ {
231
+ id: 'compat/target',
232
+ severity: 'error',
233
+ description: 'The file uses features newer than the Elementor version given with --target.',
234
+ document(doc, ctx) {
235
+ const target = ctx.options.target;
236
+ if (!target) return;
237
+ const checks = [
238
+ [doc.usage.firstContainer, MIN_VERSIONS.container, 'Flexbox containers'],
239
+ [doc.usage.firstAtomic, MIN_VERSIONS.atomic, 'Atomic (Elementor 4) elements'],
240
+ ];
241
+ for (const [pointer, min, feature] of checks) {
242
+ if (pointer && compareVersions(target, min) < 0) {
243
+ ctx.report({ pointer, message: `${feature} need Elementor ${min} or newer, but the target is ${target}.` });
244
+ }
245
+ }
246
+ },
247
+ },
248
+ {
249
+ id: 'assets/external',
250
+ severity: 'warning',
251
+ description: 'Images and other media load from a site that is not in the allowed hosts.',
252
+ element(el, info, doc, ctx) {
253
+ for (const hit of urlsIn(el, info.pointer)) {
254
+ if (!hit.media || hit.placeholder || hit.devHost) continue;
255
+ if (hostAllowed(hit.host, ctx.options.allowHosts)) continue;
256
+ ctx.report({
257
+ pointer: hit.pointer,
258
+ element: el,
259
+ message: `Media loads from ${hit.host} (${shorten(hit.url)}). Elementor downloads it during import, so it will be missing if that site goes offline or blocks the request. Bundle the file or add the host with --allow-host.`,
260
+ });
261
+ }
262
+ },
263
+ },
264
+ {
265
+ id: 'assets/insecure',
266
+ severity: 'warning',
267
+ description: 'A URL uses http:// instead of https://.',
268
+ element(el, info, doc, ctx) {
269
+ for (const hit of urlsIn(el, info.pointer)) {
270
+ if (!hit.url.toLowerCase().startsWith('http://') || hit.devHost) continue;
271
+ ctx.report({
272
+ pointer: hit.pointer,
273
+ element: el,
274
+ message: `${shorten(hit.url)} uses http://. Browsers block or warn about insecure content on https sites.`,
275
+ });
276
+ }
277
+ },
278
+ },
279
+ {
280
+ id: 'links/dev-host',
281
+ severity: 'warning',
282
+ description: 'A URL points at a local or staging site.',
283
+ element(el, info, doc, ctx) {
284
+ for (const hit of urlsIn(el, info.pointer)) {
285
+ if (!hit.devHost) continue;
286
+ ctx.report({
287
+ pointer: hit.pointer,
288
+ element: el,
289
+ message: `${shorten(hit.url)} points at a local or staging site (${hit.host}), which will not work for anyone else.`,
290
+ });
291
+ }
292
+ },
293
+ },
294
+ {
295
+ id: 'security/script',
296
+ severity: 'warning',
297
+ description: 'Settings contain JavaScript (script tags, inline event handlers or javascript: links).',
298
+ element(el, info, doc, ctx) {
299
+ if (!isObject(el)) return;
300
+ const found = new Map();
301
+ forEachString(el.settings, `${info.pointer}/settings`, (value, pointer) => {
302
+ if (/<script\b/i.test(value) && !found.has('a <script> tag')) found.set('a <script> tag', pointer);
303
+ if (/<[a-z][^>]*\son[a-z]+\s*=/i.test(value) && !found.has('an inline event handler')) found.set('an inline event handler', pointer);
304
+ if (/^\s*javascript:/i.test(value) || /=\s*["']?\s*javascript:/i.test(value)) {
305
+ if (!found.has('a javascript: link')) found.set('a javascript: link', pointer);
306
+ }
307
+ });
308
+ for (const [what, pointer] of found) {
309
+ ctx.report({
310
+ pointer,
311
+ element: el,
312
+ message: `Contains ${what}. Check that it is meant to be there: scripts in templates run for every visitor.`,
313
+ });
314
+ }
315
+ },
316
+ },
317
+ {
318
+ id: 'meta/title',
319
+ severity: 'warning',
320
+ description: 'Library templates should have a title.',
321
+ document(doc, ctx) {
322
+ if (doc.format !== 'template' || !('version' in doc.data)) return;
323
+ if (typeof doc.data.title !== 'string' || doc.data.title.trim() === '') {
324
+ ctx.report({ pointer: '/title', message: 'The template has no title, so it imports as "(no title)".' });
325
+ }
326
+ },
327
+ },
328
+ {
329
+ id: 'meta/type',
330
+ severity: 'warning',
331
+ description: 'Library templates should have a template type Elementor knows.',
332
+ document(doc, ctx) {
333
+ if (doc.format !== 'template' || !('version' in doc.data)) return;
334
+ const type = doc.data.type;
335
+ if (typeof type !== 'string' || type === '') {
336
+ ctx.report({ pointer: '/type', message: 'The template has no "type". Elementor uses it to decide where the template can be used.' });
337
+ } else if (!TEMPLATE_TYPES.has(type)) {
338
+ ctx.report({ pointer: '/type', message: `"${type}" is not a template type Elementor knows. Elementor may reject the import.` });
339
+ }
340
+ },
341
+ },
342
+ {
343
+ id: 'kit/missing-file',
344
+ severity: 'error',
345
+ description: 'A kit manifest lists a template file that is not in the kit.',
346
+ project(project, docs, ctx) {
347
+ for (const manifest of docs.filter((d) => d.format === 'kit-manifest')) {
348
+ eachManifestTemplate(manifest, (entry, index, dir) => {
349
+ if (typeof entry.source !== 'string' || entry.source === '') return;
350
+ const target = path.posix.normalize(path.posix.join(dir, entry.source));
351
+ if (!project.paths.has(target)) {
352
+ ctx.report({
353
+ file: manifest.file.display,
354
+ pointer: `/templates/${index}/source`,
355
+ message: `The manifest lists "${entry.source}", but that file is not in the kit.`,
356
+ });
357
+ }
358
+ });
359
+ }
360
+ },
361
+ },
362
+ {
363
+ id: 'kit/screenshot',
364
+ severity: 'warning',
365
+ description: 'A kit manifest lists a screenshot that is not in the kit.',
366
+ project(project, docs, ctx) {
367
+ for (const manifest of docs.filter((d) => d.format === 'kit-manifest')) {
368
+ eachManifestTemplate(manifest, (entry, index, dir) => {
369
+ if (typeof entry.screenshot !== 'string' || entry.screenshot === '') return;
370
+ if (/^https?:\/\//i.test(entry.screenshot)) return;
371
+ const target = path.posix.normalize(path.posix.join(dir, entry.screenshot));
372
+ if (!project.paths.has(target)) {
373
+ ctx.report({
374
+ file: manifest.file.display,
375
+ pointer: `/templates/${index}/screenshot`,
376
+ message: `The manifest lists the screenshot "${entry.screenshot}", but that file is not in the kit.`,
377
+ });
378
+ }
379
+ });
380
+ }
381
+ },
382
+ },
383
+ {
384
+ id: 'kit/plugins',
385
+ severity: 'warning',
386
+ description: "A kit manifest's plugin list leaves out plugins its templates need.",
387
+ project(project, docs, ctx) {
388
+ const manifest = docs.find((d) => d.format === 'kit-manifest' && pluginList(d.data));
389
+ if (!manifest) return;
390
+ const plugins = pluginList(manifest.data);
391
+ const pointer = Array.isArray(manifest.data.required_plugins) ? '/required_plugins' : '/plugins';
392
+ const text = JSON.stringify(plugins).toLowerCase();
393
+ const templates = docs.filter((d) => d.format !== 'kit-manifest');
394
+
395
+ const proUsers = templates.filter((d) => d.usage.pro.length > 0);
396
+ if (proUsers.length > 0 && !/elementor[\s_-]*pro/.test(text)) {
397
+ ctx.report({
398
+ file: manifest.file.display,
399
+ pointer,
400
+ message: `${proUsers.length} template(s) use Elementor Pro features, but the manifest does not list Elementor Pro as a required plugin.`,
401
+ });
402
+ }
403
+
404
+ const addonTypes = new Set(templates.flatMap((d) => [...d.usage.addons.keys()]));
405
+ const others = plugins.filter((p) => !/elementor/i.test(JSON.stringify(p)) || /addon|kit|jet|essential|premium|happy|plus/i.test(JSON.stringify(p)));
406
+ if (addonTypes.size > 0 && others.length === 0) {
407
+ ctx.report({
408
+ file: manifest.file.display,
409
+ pointer,
410
+ message: `Templates use widgets from other plugins (${[...addonTypes].slice(0, 5).join(', ')}${addonTypes.size > 5 ? ', ...' : ''}), but the manifest lists no plugins besides Elementor.`,
411
+ });
412
+ }
413
+ },
414
+ },
415
+ ];
416
+
417
+ /** Rules that do not come from a hook, reported by the engine itself. */
418
+ export const engineRules = [
419
+ { id: 'json/invalid', severity: 'error', description: 'The file is not valid JSON.' },
420
+ {
421
+ id: 'format/unknown',
422
+ severity: 'error',
423
+ description: 'A file named on the command line is not an Elementor template, copied elements, element data or kit manifest.',
424
+ },
425
+ { id: 'input/unreadable', severity: 'error', description: 'A file, folder or ZIP could not be read.' },
426
+ ];
427
+
428
+ export const allRules = [...engineRules, ...rules];
429
+
430
+ // ---------------------------------------------------------------------------
431
+ // Helpers
432
+
433
+ function where(ctx, pointer) {
434
+ const pos = ctx.locate?.(pointer);
435
+ return pos ? `on line ${pos.line}` : `at ${pointer}`;
436
+ }
437
+
438
+ function eachManifestTemplate(manifest, fn) {
439
+ const list = manifest.data.templates;
440
+ if (!Array.isArray(list)) return; // Elementor's own kits key templates by id; nothing to check.
441
+ const dir = path.posix.dirname(manifest.file.rel);
442
+ list.forEach((entry, index) => {
443
+ if (isObject(entry)) fn(entry, index, dir === '.' ? '' : dir);
444
+ });
445
+ }
446
+
447
+ function pluginList(data) {
448
+ if (Array.isArray(data.required_plugins)) return data.required_plugins;
449
+ if (Array.isArray(data.plugins)) return data.plugins;
450
+ return null;
451
+ }
452
+
453
+ function urlsIn(el, pointer) {
454
+ if (!isObject(el)) return [];
455
+ const hits = [];
456
+ forEachString(el.settings, `${pointer}/settings`, (value, ptr) => {
457
+ for (const match of value.matchAll(URL_PATTERN)) {
458
+ const url = match[0].replace(/[.,;:!?]+$/, '');
459
+ let host;
460
+ try {
461
+ host = new URL(url).hostname.toLowerCase();
462
+ } catch {
463
+ continue;
464
+ }
465
+ hits.push({
466
+ url,
467
+ host,
468
+ pointer: ptr,
469
+ media: MEDIA_PATTERN.test(new URL(url).pathname) || /\/wp-content\/uploads\//i.test(url),
470
+ placeholder: PLACEHOLDER_PATTERN.test(url),
471
+ devHost: isDevHost(host),
472
+ });
473
+ }
474
+ });
475
+ return hits;
476
+ }
477
+
478
+ function forEachString(value, pointer, fn) {
479
+ if (typeof value === 'string') {
480
+ fn(value, pointer);
481
+ } else if (Array.isArray(value)) {
482
+ value.forEach((item, i) => forEachString(item, `${pointer}/${i}`, fn));
483
+ } else if (isObject(value)) {
484
+ for (const [key, item] of Object.entries(value)) {
485
+ forEachString(item, `${pointer}/${escapePointer(key)}`, fn);
486
+ }
487
+ }
488
+ }
489
+
490
+ function escapePointer(key) {
491
+ return key.replaceAll('~', '~0').replaceAll('/', '~1');
492
+ }
493
+
494
+ export function isDevHost(host) {
495
+ const h = host.replace(/^\[|\]$/g, '');
496
+ if (h === 'localhost' || h === '0.0.0.0' || h === '::1') return true;
497
+ if (/^127\./.test(h) || /^10\./.test(h) || /^192\.168\./.test(h)) return true;
498
+ if (/^172\.(1[6-9]|2\d|3[01])\./.test(h)) return true;
499
+ const labels = h.split('.');
500
+ if (labels.length > 1 && DEV_TLDS.includes(labels[labels.length - 1])) return true;
501
+ if (labels.length > 2 && DEV_LABELS.has(labels[0])) return true;
502
+ return false;
503
+ }
504
+
505
+ function hostAllowed(host, allowHosts) {
506
+ for (const allowed of allowHosts) {
507
+ if (host === allowed || host.endsWith(`.${allowed}`)) return true;
508
+ }
509
+ return false;
510
+ }
511
+
512
+ function shorten(url) {
513
+ return url.length > 80 ? `${url.slice(0, 77)}...` : url;
514
+ }
515
+
516
+ function describe(value) {
517
+ if (value === null) return 'null';
518
+ if (Array.isArray(value)) return 'an array';
519
+ if (typeof value === 'object') return 'an object';
520
+ return `a ${typeof value} (${JSON.stringify(value).slice(0, 40)})`;
521
+ }
package/src/version.js ADDED
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Compare two version strings such as "3.21" and "3.21.4".
3
+ * Returns a negative number, zero or a positive number. Pre-release
4
+ * suffixes ("-beta1") are ignored.
5
+ */
6
+ export function compareVersions(a, b) {
7
+ const pa = parts(a);
8
+ const pb = parts(b);
9
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
10
+ const diff = (pa[i] ?? 0) - (pb[i] ?? 0);
11
+ if (diff !== 0) return diff;
12
+ }
13
+ return 0;
14
+ }
15
+
16
+ export function isVersion(value) {
17
+ return typeof value === 'string' && /^\d+(\.\d+){0,2}([-+].*)?$/.test(value.trim());
18
+ }
19
+
20
+ function parts(version) {
21
+ return String(version)
22
+ .trim()
23
+ .split(/[-+]/)[0]
24
+ .split('.')
25
+ .map((n) => Number.parseInt(n, 10) || 0);
26
+ }
package/src/zip.js ADDED
@@ -0,0 +1,76 @@
1
+ // Minimal ZIP reader with no dependencies. Supports the "stored" and
2
+ // "deflate" methods, which covers ZIP files made by Elementor, Envato kit
3
+ // tools, macOS, Windows and the zip command. ZIP64 archives are not supported.
4
+
5
+ import { inflateRawSync } from 'node:zlib';
6
+
7
+ const EOCD_SIGNATURE = 0x06054b50;
8
+ const CENTRAL_SIGNATURE = 0x02014b50;
9
+ const LOCAL_SIGNATURE = 0x04034b50;
10
+
11
+ /**
12
+ * Read every file entry in a ZIP archive.
13
+ * @param {Buffer} buffer
14
+ * @returns {{ name: string, read: () => Buffer }[]}
15
+ */
16
+ export function readZip(buffer) {
17
+ const eocd = findEndOfCentralDirectory(buffer);
18
+ const count = buffer.readUInt16LE(eocd + 10);
19
+ let offset = buffer.readUInt32LE(eocd + 16);
20
+
21
+ if (count === 0xffff || offset === 0xffffffff) {
22
+ throw new Error('ZIP64 archives are not supported');
23
+ }
24
+
25
+ const entries = [];
26
+ for (let i = 0; i < count; i++) {
27
+ if (buffer.readUInt32LE(offset) !== CENTRAL_SIGNATURE) {
28
+ throw new Error('Corrupt ZIP central directory');
29
+ }
30
+ const flags = buffer.readUInt16LE(offset + 8);
31
+ const method = buffer.readUInt16LE(offset + 10);
32
+ const compressedSize = buffer.readUInt32LE(offset + 20);
33
+ const nameLength = buffer.readUInt16LE(offset + 28);
34
+ const extraLength = buffer.readUInt16LE(offset + 30);
35
+ const commentLength = buffer.readUInt16LE(offset + 32);
36
+ const localOffset = buffer.readUInt32LE(offset + 42);
37
+ const nameBytes = buffer.subarray(offset + 46, offset + 46 + nameLength);
38
+ // Bit 11 means the name is UTF-8. Older tools use CP437, which matches
39
+ // ASCII for the file names templates use.
40
+ const name = nameBytes.toString(flags & 0x800 ? 'utf8' : 'latin1');
41
+ offset += 46 + nameLength + extraLength + commentLength;
42
+
43
+ if (name.endsWith('/')) continue; // directory entry
44
+
45
+ entries.push({
46
+ name,
47
+ read: () => readEntry(buffer, localOffset, method, compressedSize, flags, name),
48
+ });
49
+ }
50
+ return entries;
51
+ }
52
+
53
+ function findEndOfCentralDirectory(buffer) {
54
+ // The EOCD record is at least 22 bytes and may be followed by a comment
55
+ // of up to 65535 bytes.
56
+ const min = Math.max(0, buffer.length - 22 - 0xffff);
57
+ for (let i = buffer.length - 22; i >= min; i--) {
58
+ if (buffer.readUInt32LE(i) === EOCD_SIGNATURE) return i;
59
+ }
60
+ throw new Error('Not a ZIP file (no end of central directory record)');
61
+ }
62
+
63
+ function readEntry(buffer, localOffset, method, compressedSize, flags, name) {
64
+ if (flags & 0x1) throw new Error(`${name} is encrypted`);
65
+ if (buffer.readUInt32LE(localOffset) !== LOCAL_SIGNATURE) {
66
+ throw new Error(`Corrupt ZIP entry: ${name}`);
67
+ }
68
+ const nameLength = buffer.readUInt16LE(localOffset + 26);
69
+ const extraLength = buffer.readUInt16LE(localOffset + 28);
70
+ const start = localOffset + 30 + nameLength + extraLength;
71
+ const data = buffer.subarray(start, start + compressedSize);
72
+
73
+ if (method === 0) return Buffer.from(data);
74
+ if (method === 8) return inflateRawSync(data);
75
+ throw new Error(`${name} uses unsupported compression method ${method}`);
76
+ }