Selaa lähdekoodia

allow extra/missing spaces in meta: around // and start/end/keys (#616)

* allow extra/missing spaces in meta: around // and start/end/keys

* add a test
tophf 6 vuotta sitten
vanhempi
sitoutus
15e9317559
3 muutettua tiedostoa jossa 33 lisäystä ja 5 poistoa
  1. 7 4
      src/background/utils/script.js
  2. 4 1
      src/injected/web/index.js
  3. 22 0
      test/background/script.test.js

+ 7 - 4
src/background/utils/script.js

@@ -48,15 +48,18 @@ export function parseMeta(code) {
     [key]: metaTypes[key].default(),
   }), {});
   let flag = -1;
-  code.replace(/(?:^|\n)\s*\/\/\s*([@=]\S+)(.*)/g, (_match, group1, group2) => {
-    if (flag < 0 && group1 === metaStart) {
+  // Allow metadata lines to start with SPACE? '//' SPACE?
+  // Allow anything to follow the predefined text of the metaStart/End
+  // The spaces must be on the same line so [\t\x20] is used as \s also matches \r\n
+  code.replace(/(?:^|\n)\s*\/\/[\t\x20]*([@=]\S+)(.*)/g, (_match, group1, group2) => {
+    if (flag < 0 && group1.startsWith(metaStart)) {
       // start meta
       flag = 1;
-    } else if (flag > 0 && group1 === metaEnd) {
+    } else if (flag > 0 && group1.startsWith(metaEnd)) {
       // end meta
       flag = 0;
     }
-    if (flag === 1 && group1[0] === '@') {
+    if (flag === 1 && group1.startsWith('@')) {
       const [keyName, locale] = group1.slice(1).split(':');
       const camelKey = keyName.replace(/[-_](\w)/g, (m, g) => g.toUpperCase());
       const key = locale ? `${camelKey}:${locale.toLowerCase()}` : camelKey;

+ 4 - 1
src/injected/web/index.js

@@ -185,7 +185,10 @@ function wrapGM(script, code, cache, unsafeWindow) {
     b: val => val === 'true',
   };
   const pathMap = script.custom.pathMap || {};
-  const matches = code.match(/\/\/\s+==UserScript==\s+([\s\S]*?)\/\/\s+==\/UserScript==\s/);
+  // Allow metadata lines to start with SPACE? '//' SPACE?
+  // Allow anything to follow the predefined text of the metaStart/End
+  // The spaces must be on the same line so [\t\x20] is used as \s also matches \r\n
+  const matches = code.match(/(?:^|\n)\s*\/\/[\t\x20]*==UserScript==.*\n([\s\S]*?\n|)\s*\/\/[\t\x20]*==\/UserScript==/);
   const metaStr = matches ? matches[1] : '';
   const gmInfo = {
     uuid: script.props.uuid,

+ 22 - 0
test/background/script.test.js

@@ -45,3 +45,25 @@ test('parseMeta', (t) => {
   }));
   t.end();
 });
+
+test('parseMetaIrregularities', (t) => {
+  t.deepEqual(parseMeta(`\
+  //    ==UserScript==============
+// @name foo
+ //@namespace bar
+//==/UserScript===================
+  `), {
+    ...baseMeta,
+    name: 'foo',
+    namespace: 'bar',
+  });
+  t.deepEqual(parseMeta(`\
+/*
+//
+  ==UserScript==
+// @name foo
+//
+==/UserScript==
+*/`), baseMeta);
+  t.end();
+});