Browse Source

Primer commit para que funcione en mi host

Celestino Rey 1 tuần trước cách đây
commit
aaa3a426f4
100 tập tin đã thay đổi với 9415 bổ sung0 xóa
  1. 25 0
      .editorconfig
  2. 56 0
      .github/ISSUE_TEMPLATE/bug_report.md
  3. 11 0
      .github/PULL_REQUEST_TEMPLATE.md
  4. 6 0
      .gitignore
  5. 16 0
      .yarn/patches/@ai-sdk-mcp-npm-1.0.37-8cd89b8972.patch
  6. 831 0
      .yarn/patches/@codemirror-autocomplete-npm-6.18.4.patch
  7. 381 0
      .yarn/patches/@codemirror-search-npm-6.5.8.patch
  8. 44 0
      .yarn/patches/body-parser-npm-1.20.4.patch
  9. 13 0
      .yarn/patches/cypress-multi-reporters-npm-2.0.5.patch
  10. 13 0
      .yarn/patches/forwarded-npm-0.2.0.patch
  11. 13 0
      .yarn/patches/mocha-multi-reporters-npm-1.5.1-0a1088aed5.patch
  12. 13 0
      .yarn/patches/multer-npm-2.1.1.patch
  13. 76 0
      .yarn/patches/node-fetch-npm-2.7.0.patch
  14. 13 0
      .yarn/patches/passport-oauth2-npm-1.6.1.patch
  15. 22 0
      .yarn/patches/pdfjs-dist-npm-5.1.91.patch
  16. 1583 0
      .yarn/patches/referer-parser-npm-0.0.3.patch
  17. 30 0
      .yarn/patches/retry-request-npm-7.0.2-a41087680c.patch
  18. 30 0
      .yarn/patches/retry-request-npm-8.0.2-448ad084c8.patch
  19. 57 0
      .yarn/patches/sandboxed-module-npm-2.0.4-f8b45aacc9.patch
  20. 57 0
      .yarn/patches/send-npm-0.19.0.patch
  21. 57 0
      .yarn/patches/teeny-request-npm-10.1.0.patch
  22. 58 0
      .yarn/patches/teeny-request-npm-9.0.0-4d571e3c55.patch
  23. 81 0
      .yarn/patches/thread-loader-npm-4.0.2-dab5735f54.patch
  24. 25 0
      .yarnrc.yml
  25. 38 0
      CONTRIBUTING.md
  26. 661 0
      LICENSE
  27. 80 0
      README.md
  28. 152 0
      Yamls/docker-compose.yml
  29. 13 0
      Yamls/mongo-claim0-persistentvolumeclaim.yaml
  30. 13 0
      Yamls/mongo-claim1-persistentvolumeclaim.yaml
  31. 54 0
      Yamls/mongo-deployment.yaml
  32. 13 0
      Yamls/redis-claim0-persistentvolumeclaim.yaml
  33. 36 0
      Yamls/redis-deployment.yaml
  34. 13 0
      Yamls/sharelatex-claim0-persistentvolumeclaim.yaml
  35. 67 0
      Yamls/sharelatex-deployment.yaml
  36. 19 0
      Yamls/sharelatex-service.yaml
  37. 3 0
      bin/shared/mongodb-init-replica-set.js
  38. 3 0
      develop/.gitignore
  39. 76 0
      develop/README.md
  40. 3 0
      develop/bin/build
  41. 3 0
      develop/bin/dev
  42. 3 0
      develop/bin/down
  43. 9 0
      develop/bin/logs
  44. 3 0
      develop/bin/shell
  45. 3 0
      develop/bin/up
  46. 0 0
      develop/compiles/.gitkeep
  47. 24 0
      develop/dev.env
  48. 128 0
      develop/docker-compose.dev.yml
  49. 175 0
      develop/docker-compose.yml
  50. 23 0
      develop/webpack.config.dev-env.js
  51. BIN
      doc/logo.png
  52. BIN
      doc/screenshot.png
  53. 23 0
      docker-compose.debug.yml
  54. 152 0
      docker-compose.yml
  55. 18 0
      dockerfiles/cypress/Dockerfile
  56. 13 0
      libraries/access-token-encryptor/.mocharc.cjs
  57. 1 0
      libraries/access-token-encryptor/.nvmrc
  58. 661 0
      libraries/access-token-encryptor/LICENSE
  59. 59 0
      libraries/access-token-encryptor/Makefile
  60. 3 0
      libraries/access-token-encryptor/README.md
  61. 9 0
      libraries/access-token-encryptor/buildscript.txt
  62. 1 0
      libraries/access-token-encryptor/index.js
  63. 164 0
      libraries/access-token-encryptor/lib/js/AccessTokenEncryptor.js
  64. 28 0
      libraries/access-token-encryptor/package.json
  65. 27 0
      libraries/access-token-encryptor/scripts/helpers/format-usage-stats.js
  66. 108 0
      libraries/access-token-encryptor/scripts/helpers/re-encrypt-tokens.js
  67. 9 0
      libraries/access-token-encryptor/test/mocha-multi-reporters.cjs
  68. 13 0
      libraries/access-token-encryptor/test/setup.js
  69. 305 0
      libraries/access-token-encryptor/test/unit/js/AccessTokenEncryptorTests.js
  70. 4 0
      libraries/access-token-encryptor/tsconfig.json
  71. 160 0
      libraries/eslint-plugin/french-typography-in-locales.js
  72. 25 0
      libraries/eslint-plugin/index.js
  73. 93 0
      libraries/eslint-plugin/locale-variables-match-en.js
  74. 37 0
      libraries/eslint-plugin/no-consecutive-spaces-in-locales.js
  75. 21 0
      libraries/eslint-plugin/no-generated-editor-themes.js
  76. 69 0
      libraries/eslint-plugin/no-orphan-locale-keys.js
  77. 36 0
      libraries/eslint-plugin/no-straight-apostrophes-in-locales.js
  78. 52 0
      libraries/eslint-plugin/no-throw-in-callback.js
  79. 43 0
      libraries/eslint-plugin/no-unnecessary-trans.js
  80. 20 0
      libraries/eslint-plugin/package.json
  81. 84 0
      libraries/eslint-plugin/prefer-kebab-url-ignore.js
  82. 91 0
      libraries/eslint-plugin/prefer-kebab-url.js
  83. 111 0
      libraries/eslint-plugin/require-cio-snake-case-properties.js
  84. 49 0
      libraries/eslint-plugin/require-loading-label.js
  85. 28 0
      libraries/eslint-plugin/require-script-runner.js
  86. 139 0
      libraries/eslint-plugin/require-vi-doMock-valid-path.js
  87. 455 0
      libraries/eslint-plugin/rules.test.js
  88. 60 0
      libraries/eslint-plugin/should-unescape-trans.js
  89. 43 0
      libraries/eslint-plugin/sorted-keys-in-locales.js
  90. 4 0
      libraries/eslint-plugin/tsconfig.json
  91. 13 0
      libraries/fetch-utils/.mocharc.cjs
  92. 1 0
      libraries/fetch-utils/.nvmrc
  93. 59 0
      libraries/fetch-utils/Makefile
  94. 9 0
      libraries/fetch-utils/buildscript.txt
  95. 354 0
      libraries/fetch-utils/index.js
  96. 33 0
      libraries/fetch-utils/package.json
  97. 9 0
      libraries/fetch-utils/test/mocha-multi-reporters.cjs
  98. 4 0
      libraries/fetch-utils/test/setup.js
  99. 450 0
      libraries/fetch-utils/test/unit/FetchUtilsTests.js
  100. 139 0
      libraries/fetch-utils/test/unit/helpers/TestServer.js

+ 25 - 0
.editorconfig

@@ -0,0 +1,25 @@
+root = true
+
+[*]
+charset = utf-8
+indent_style = space
+indent_size = 2
+end_of_line = lf
+insert_final_newline = true
+trim_trailing_whitespace = true
+
+[Makefile]
+indent_style = tab
+
+[*.go]
+indent_style = tab
+
+[*.{pug,coffee}]
+indent_style = tab
+
+[*.{pug,patch}]
+trim_trailing_whitespace = false
+
+[Jenkinsfile]
+insert_final_newline = false
+max_line_length = off

+ 56 - 0
.github/ISSUE_TEMPLATE/bug_report.md

@@ -0,0 +1,56 @@
+---
+name: Bug report
+about: Report a bug
+title: ''
+labels: type:bug
+assignees: ''
+---
+
+<!--
+
+Note: If you are using www.overleaf.com and have a problem,
+      or if you would like to request a new feature please contact
+      the support team at support@overleaf.com
+
+      This form should only be used to report bugs in the
+      Community Edition release of Overleaf.
+
+-->
+
+<!-- BUG REPORT TEMPLATE -->
+
+## Steps to Reproduce
+
+<!-- Describe the steps leading up to when / where you found the bug. -->
+<!-- Screenshots may be helpful here. -->
+
+1.
+2.
+3.
+
+## Expected Behaviour
+
+<!-- What should have happened when you completed the steps above? -->
+
+## Observed Behaviour
+
+<!-- What actually happened when you completed the steps above? -->
+<!-- Screenshots may be helpful here. -->
+
+## Context
+
+<!-- How has this issue affected you? What were you trying to accomplish? -->
+
+## Technical Info
+
+<!-- Provide any technical details that may be applicable (or N/A if not applicable). -->
+
+- URL:
+- Browser Name and version:
+- Operating System and version (desktop or mobile):
+- Signed in as:
+- Project and/or file:
+
+## Analysis
+
+<!--- Optionally, document investigation of / suggest a fix for the bug, e.g. 'comes from this line / commit' -->

+ 11 - 0
.github/PULL_REQUEST_TEMPLATE.md

@@ -0,0 +1,11 @@
+## Description
+
+<!-- Goal of the pull request -->
+
+## Related issues / Pull Requests
+
+<!-- Fixes #xyz, Contributes to #xyz, Related to #xyz-->
+
+## Contributor Agreement
+
+- [ ] I confirm I have signed the [Contributor License Agreement](https://github.com/overleaf/overleaf/blob/main/CONTRIBUTING.md#contributor-license-agreement)

+ 6 - 0
.gitignore

@@ -0,0 +1,6 @@
+# docker image build
+.dockerignore
+
+# user defined files
+.env
+docker-compose.override.yml

+ 16 - 0
.yarn/patches/@ai-sdk-mcp-npm-1.0.37-8cd89b8972.patch

@@ -0,0 +1,16 @@
+diff --git a/dist/index.mjs b/dist/index.mjs
+index b781835b37a1262510bdd66d8d3b399a076e9d68..312c314186d85bb3bc2ab2620e99bca259ef7167 100644
+--- a/dist/index.mjs
++++ b/dist/index.mjs
+@@ -44,10 +44,9 @@ import { z as z2 } from "zod/v4";
+ 
+ // src/tool/types.ts
+ import { z } from "zod/v4";
+-var LATEST_PROTOCOL_VERSION = "2025-11-25";
++var LATEST_PROTOCOL_VERSION = "2025-06-18";
+ var SUPPORTED_PROTOCOL_VERSIONS = [
+   LATEST_PROTOCOL_VERSION,
+-  "2025-06-18",
+   "2025-03-26",
+   "2024-11-05"
+ ];

+ 831 - 0
.yarn/patches/@codemirror-autocomplete-npm-6.18.4.patch

@@ -0,0 +1,831 @@
+diff --git a/dist/index.cjs b/dist/index.cjs
+index 39215ae..b44cb76 100644
+--- a/dist/index.cjs
++++ b/dist/index.cjs
+@@ -187,16 +187,23 @@ Helper function that returns a transaction spec which inserts a
+ completion's text in the main selection range, and any other
+ selection range that has the same text in front of it.
+ */
+-function insertCompletionText(state$1, text, from, to) {
++function insertCompletionText(state$1, text, from, to, extend) {
+     let { main } = state$1.selection, fromOff = from - main.from, toOff = to - main.from;
+     return Object.assign(Object.assign({}, state$1.changeByRange(range => {
+         if (range != main && from != to &&
+             state$1.sliceDoc(range.from + fromOff, range.from + toOff) != state$1.sliceDoc(from, to))
+             return { range };
+-        let lines = state$1.toText(text);
++        let change = {
++            from: range.from + fromOff,
++            to: to == main.from ? range.to : range.from + toOff,
++            insert: text instanceof state.Text ? text : state$1.toText(text),
++        };
++        if (extend) {
++            extend(state$1, change);
++        }
+         return {
+-            changes: { from: range.from + fromOff, to: to == main.from ? range.to : range.from + toOff, insert: lines },
+-            range: state.EditorSelection.cursor(range.from + fromOff + lines.length)
++            changes: change,
++            range: state.EditorSelection.cursor(change.from + change.insert.length)
+         };
+     })), { scrollIntoView: true, userEvent: "input.complete" });
+ }
+@@ -389,7 +396,9 @@ const completionConfig = state.Facet.define({
+             filterStrict: false,
+             compareCompletions: (a, b) => a.label.localeCompare(b.label),
+             interactionDelay: 75,
+-            updateSyncTime: 100
++            updateSyncTime: 100,
++            // overleaf: default to at top which is default CM6 behaviour
++            unfilteredResultsAtEnd: false
+         }, {
+             defaultKeymap: (a, b) => a && b,
+             closeOnBlur: (a, b) => a && b,
+@@ -744,6 +753,7 @@ function score(option) {
+         (option.type ? 1 : 0);
+ }
+ function sortOptions(active, state) {
++    var _a;
+     let options = [];
+     let sections = null;
+     let addOption = (option) => {
+@@ -763,7 +773,8 @@ function sortOptions(active, state) {
+             let getMatch = a.result.getMatch;
+             if (a.result.filter === false) {
+                 for (let option of a.result.options) {
+-                    addOption(new Option(option, a.source, getMatch ? getMatch(option) : [], 1e9 - options.length));
++                    let defaultScore = conf.unfilteredResultsAtEnd ? -1e9 : 1e9;
++                    addOption(new Option(option, a.source, getMatch ? getMatch(option) : [], defaultScore - options.length));
+                 }
+             }
+             else {
+@@ -790,15 +801,42 @@ function sortOptions(active, state) {
+         }
+     }
+     let result = [], prev = null;
++    const priorityIndices = new Map();
+     let compare = conf.compareCompletions;
+     for (let opt of options.sort((a, b) => (b.score - a.score) || compare(a.completion, b.completion))) {
++        // overleaf: Deduplicate results with dedup options
++        //           The goal is to keep only the highest priority option, in the
++        //           highest scoring position.
++        const key = (_a = opt.completion.deduplicate) === null || _a === void 0 ? void 0 : _a.key;
++        if (key) {
++            // Handle merging specifically for deduplicated items item
++            const currentOptionIndex = priorityIndices.get(key);
++            if (currentOptionIndex === undefined) {
++                priorityIndices.set(key, result.length);
++                result.push(opt);
++                prev = opt.completion;
++            }
++            else {
++                if (result[currentOptionIndex].completion.deduplicate.priority < opt.completion.deduplicate.priority) {
++                    result[currentOptionIndex] = opt;
++                    if (currentOptionIndex === result.length - 1) {
++                        prev = opt.completion;
++                    }
++                }
++            }
++            continue;
++        }
++        // overleaf: end
+         let cur = opt.completion;
+-        if (!prev || prev.label != cur.label || prev.detail != cur.detail ||
+-            (prev.type != null && cur.type != null && prev.type != cur.type) ||
+-            prev.apply != cur.apply || prev.boost != cur.boost)
++        if (!prev || prev.label != cur.label)
++            result.push(opt);
++        // overleaf: we're already handling deduplication, so skip extra merges
++        else if (prev.deduplicate)
+             result.push(opt);
+         else if (score(opt.completion) > score(prev))
+             result[result.length - 1] = opt;
++        else if (opt.completion.info)
++            result[result.length - 1] = opt;
+         prev = opt.completion;
+     }
+     return result;
+@@ -817,8 +855,9 @@ class CompletionDialog {
+             : new CompletionDialog(this.options, makeAttrs(id, selected), this.tooltip, this.timestamp, selected, this.disabled);
+     }
+     static build(active, state, id, prev, conf, didSetActive) {
+-        if (prev && !didSetActive && active.some(s => s.isPending))
+-            return prev.setDisabled();
++        // Overleaf: avoid setting the previous completion state to disabled while completion sources are pending
++        // if (prev && !didSetActive && active.some(s => s.isPending))
++        //   return prev.setDisabled()
+         let options = sortOptions(active, state);
+         if (!options.length)
+             return prev && active.some(a => a.isPending) ? prev.setDisabled() : null;
+@@ -1017,13 +1056,14 @@ const completionState = state.StateField.define({
+         view.EditorView.contentAttributes.from(f, state => state.attrs)
+     ]
+ });
++const getCompletionTooltip = (state) => { var _a; return (_a = state.field(completionState, false)) === null || _a === void 0 ? void 0 : _a.tooltip; };
+ function applyCompletion(view, option) {
+     const apply = option.completion.apply || option.completion.label;
+     let result = view.state.field(completionState).active.find(a => a.source == option.source);
+     if (!(result instanceof ActiveResult))
+         return false;
+     if (typeof apply == "string")
+-        view.dispatch(Object.assign(Object.assign({}, insertCompletionText(view.state, apply, result.from, result.to)), { annotations: pickedCompletion.of(option.completion) }));
++        view.dispatch(Object.assign(Object.assign({}, insertCompletionText(view.state, apply, result.from, result.to, option.completion.extend)), { annotations: pickedCompletion.of(option.completion) }));
+     else
+         apply(view, option.completion, result.from, result.to);
+     return true;
+@@ -1559,20 +1599,42 @@ interpreted as indicating a placeholder.
+ function snippet(template) {
+     let snippet = Snippet.parse(template);
+     return (editor, completion, from, to) => {
+-        let { text, ranges } = snippet.instantiate(editor.state, from);
+-        let { main } = editor.state.selection;
+-        let spec = {
+-            changes: { from, to: to == main.from ? main.to : to, insert: state.Text.of(text) },
+-            scrollIntoView: true,
+-            annotations: completion ? [pickedCompletion.of(completion), state.Transaction.userEvent.of("input.complete")] : undefined
+-        };
++        let { main } = editor.state.selection, fromOff = from - main.from, toOff = to - main.from;
++        let ranges = [];
++        let totalOffset = 0;
++        let spec = Object.assign(Object.assign({}, editor.state.changeByRange(range => {
++            if (range != main && from != to &&
++                editor.state.sliceDoc(range.from + fromOff, range.from + toOff) != editor.state.sliceDoc(from, to))
++                return { range };
++            let { text, ranges: fieldRanges } = snippet.instantiate(editor.state, range.from + fromOff);
++            let change = {
++                from: range.from + fromOff,
++                to: range.from + toOff,
++                insert: state.Text.of(text)
++            };
++            let originalTo = change.to;
++            let offset = change.insert.length + fromOff;
++            if (completion.extend) {
++                completion.extend(editor.state, change);
++                offset += originalTo - change.to;
++            }
++            for (const fieldRange of fieldRanges) {
++                ranges.push(new FieldRange(fieldRange.field, fieldRange.from + totalOffset, fieldRange.to + totalOffset));
++            }
++            totalOffset += offset;
++            return {
++                changes: change,
++                range: state.EditorSelection.cursor(change.from + change.insert.length)
++            };
++        })), { scrollIntoView: true, annotations: completion ? [pickedCompletion.of(completion), state.Transaction.userEvent.of("input.complete")] : undefined, effects: [] });
+         if (ranges.length)
+             spec.selection = fieldSelection(ranges, 0);
+         if (ranges.some(r => r.field > 0)) {
+             let active = new ActiveSnippet(ranges, 0);
+-            let effects = spec.effects = [setActive.of(active)];
+-            if (editor.state.field(snippetState, false) === undefined)
+-                effects.push(state.StateEffect.appendConfig.of([snippetState, addSnippetKeymap, snippetPointerHandler, baseTheme]));
++            spec.effects.push(setActive.of(active));
++            if (editor.state.field(snippetState, false) === undefined) {
++                spec.effects.push(state.StateEffect.appendConfig.of([snippetState, addSnippetKeymap, snippetPointerHandler, baseTheme]));
++            }
+         }
+         editor.dispatch(editor.state.update(spec));
+     };
+@@ -1746,7 +1808,8 @@ const completeAnyWord = context => {
+ const defaults = {
+     brackets: ["(", "[", "{", "'", '"'],
+     before: ")]}:;>",
+-    stringPrefixes: []
++    stringPrefixes: [],
++    buildInsert: (state, range, open, close) => open + close,
+ };
+ const closeBracketEffect = state.StateEffect.define({
+     map(value, mapping) {
+@@ -1854,8 +1917,8 @@ function insertBracket(state$1, bracket) {
+     for (let tok of tokens) {
+         let closed = closing(state.codePointAt(tok, 0));
+         if (bracket == tok)
+-            return closed == tok ? handleSame(state$1, tok, tokens.indexOf(tok + tok + tok) > -1, conf)
+-                : handleOpen(state$1, tok, closed, conf.before || defaults.before);
++            return closed == tok ? handleSame(state$1, tok, tokens.indexOf(tok + tok) > -1, tokens.indexOf(tok + tok + tok) > -1, conf)
++                : handleOpen(state$1, tok, closed, conf.before || defaults.before, conf);
+         if (bracket == closed && closedBracketAt(state$1, state$1.selection.main.from))
+             return handleClose(state$1, tok, closed);
+     }
+@@ -1877,17 +1940,21 @@ function prevChar(doc, pos) {
+     let prev = doc.sliceString(pos - 2, pos);
+     return state.codePointSize(state.codePointAt(prev, 0)) == prev.length ? prev : prev.slice(1);
+ }
+-function handleOpen(state$1, open, close, closeBefore) {
++function handleOpen(state$1, open, close, closeBefore, config) {
++    let buildInsert = config.buildInsert || defaults.buildInsert;
+     let dont = null, changes = state$1.changeByRange(range => {
++        var _a;
+         if (!range.empty)
+             return { changes: [{ insert: open, from: range.from }, { insert: close, from: range.to }],
+                 effects: closeBracketEffect.of(range.to + open.length),
+                 range: state.EditorSelection.range(range.anchor + open.length, range.head + open.length) };
+         let next = nextChar(state$1.doc, range.head);
+-        if (!next || /\s/.test(next) || closeBefore.indexOf(next) > -1)
+-            return { changes: { insert: open + close, from: range.head },
+-                effects: closeBracketEffect.of(range.head + open.length),
++        if (!next || /\s/.test(next) || closeBefore.indexOf(next) > -1) {
++            const insert = (_a = buildInsert(state$1, range, open, close)) !== null && _a !== void 0 ? _a : open + close;
++            return { changes: { insert, from: range.head },
++                effects: insert === open ? [] : closeBracketEffect.of(range.head + open.length),
+                 range: state.EditorSelection.cursor(range.head + open.length) };
++        }
+         return { range: dont = range };
+     });
+     return dont ? null : state$1.update(changes, {
+@@ -1909,18 +1976,36 @@ function handleClose(state$1, _open, close) {
+ }
+ // Handles cases where the open and close token are the same, and
+ // possibly triple quotes (as in `"""abc"""`-style quoting).
+-function handleSame(state$1, token, allowTriple, config) {
++function handleSame(state$1, token, allowDouble, allowTriple, config) {
+     let stringPrefixes = config.stringPrefixes || defaults.stringPrefixes;
++    let buildInsert = config.buildInsert || defaults.buildInsert;
+     let dont = null, changes = state$1.changeByRange(range => {
++        var _a, _b, _c;
+         if (!range.empty)
+             return { changes: [{ insert: token, from: range.from }, { insert: token, from: range.to }],
+                 effects: closeBracketEffect.of(range.to + token.length),
+                 range: state.EditorSelection.range(range.anchor + token.length, range.head + token.length) };
+         let pos = range.head, next = nextChar(state$1.doc, pos), start;
+-        if (next == token) {
++        if (allowTriple && state$1.sliceDoc(pos - 2 * token.length, pos) == token + token &&
++            (start = canStartStringAt(state$1, pos - 2 * token.length, stringPrefixes)) > -1 &&
++            nodeStart(state$1, start)) {
++            return { changes: { insert: token + token + token + token, from: pos },
++                effects: closeBracketEffect.of(pos + token.length),
++                range: state.EditorSelection.cursor(pos + token.length) };
++        }
++        else if (allowDouble && state$1.sliceDoc(pos - token.length, pos) == token &&
++            (start = canStartStringAt(state$1, pos - token.length, stringPrefixes)) > -1 &&
++            nodeStart(state$1, start)) {
++            let insert = (_a = buildInsert(state$1, range, token, token)) !== null && _a !== void 0 ? _a : token + token;
++            return { changes: { insert, from: pos },
++                effects: insert === token ? [] : closeBracketEffect.of(pos + token.length),
++                range: state.EditorSelection.cursor(pos + token.length) };
++        }
++        else if (next == token) {
+             if (nodeStart(state$1, pos)) {
+-                return { changes: { insert: token + token, from: pos },
+-                    effects: closeBracketEffect.of(pos + token.length),
++                let insert = (_b = buildInsert(state$1, range, token, token)) !== null && _b !== void 0 ? _b : token + token;
++                return { changes: { insert, from: pos },
++                    effects: insert === token ? [] : closeBracketEffect.of(pos + token.length),
+                     range: state.EditorSelection.cursor(pos + token.length) };
+             }
+             else if (closedBracketAt(state$1, pos)) {
+@@ -1930,18 +2015,13 @@ function handleSame(state$1, token, allowTriple, config) {
+                     range: state.EditorSelection.cursor(pos + content.length) };
+             }
+         }
+-        else if (allowTriple && state$1.sliceDoc(pos - 2 * token.length, pos) == token + token &&
+-            (start = canStartStringAt(state$1, pos - 2 * token.length, stringPrefixes)) > -1 &&
+-            nodeStart(state$1, start)) {
+-            return { changes: { insert: token + token + token + token, from: pos },
+-                effects: closeBracketEffect.of(pos + token.length),
+-                range: state.EditorSelection.cursor(pos + token.length) };
+-        }
+         else if (state$1.charCategorizer(pos)(next) != state.CharCategory.Word) {
+-            if (canStartStringAt(state$1, pos, stringPrefixes) > -1 && !probablyInString(state$1, pos, token, stringPrefixes))
+-                return { changes: { insert: token + token, from: pos },
+-                    effects: closeBracketEffect.of(pos + token.length),
++            if (canStartStringAt(state$1, pos, stringPrefixes) > -1 && !probablyInString(state$1, pos, token, stringPrefixes)) {
++                const insert = (_c = buildInsert(state$1, range, token, token)) !== null && _c !== void 0 ? _c : token + token;
++                return { changes: { insert, from: pos },
++                    effects: insert === token ? [] : closeBracketEffect.of(pos + token.length),
+                     range: state.EditorSelection.cursor(pos + token.length) };
++            }
+         }
+         return { range: dont = range };
+     });
+@@ -2086,6 +2166,7 @@ exports.completionKeymap = completionKeymap;
+ exports.completionStatus = completionStatus;
+ exports.currentCompletions = currentCompletions;
+ exports.deleteBracketPair = deleteBracketPair;
++exports.getCompletionTooltip = getCompletionTooltip;
+ exports.hasNextSnippetField = hasNextSnippetField;
+ exports.hasPrevSnippetField = hasPrevSnippetField;
+ exports.ifIn = ifIn;
+@@ -2093,8 +2174,10 @@ exports.ifNotIn = ifNotIn;
+ exports.insertBracket = insertBracket;
+ exports.insertCompletionText = insertCompletionText;
+ exports.moveCompletionSelection = moveCompletionSelection;
++exports.nextChar = nextChar;
+ exports.nextSnippetField = nextSnippetField;
+ exports.pickedCompletion = pickedCompletion;
++exports.prevChar = prevChar;
+ exports.prevSnippetField = prevSnippetField;
+ exports.selectedCompletion = selectedCompletion;
+ exports.selectedCompletionIndex = selectedCompletionIndex;
+diff --git a/dist/index.d.cts b/dist/index.d.cts
+index b57b8f6..fce47ab 100644
+--- a/dist/index.d.cts
++++ b/dist/index.d.cts
+@@ -1,6 +1,6 @@
+ import * as _codemirror_state from '@codemirror/state';
+-import { EditorState, ChangeDesc, TransactionSpec, Transaction, StateCommand, Facet, Extension, StateEffect } from '@codemirror/state';
+-import { EditorView, Rect, KeyBinding, Command } from '@codemirror/view';
++import { EditorState, Text, ChangeDesc, TransactionSpec, StateCommand, Transaction, Facet, SelectionRange, Extension, StateEffect } from '@codemirror/state';
++import { EditorView, Rect, KeyBinding, Tooltip, Command } from '@codemirror/view';
+ import * as _lezer_common from '@lezer/common';
+ 
+ /**
+@@ -73,6 +73,19 @@ interface Completion {
+     a `{name}` object.
+     */
+     section?: string | CompletionSection;
++    /**
++    Can be used to alter the change created when the completion is applied
++    */
++    extend?: ExtendCompletion;
++    /**
++    If multiple sources return the same result, use this field to specifiy a
++    deduplication key as well as a priority. For each unique key, only the
++    completion with the highest priority will be shown.
++    */
++    deduplicate?: {
++        key: string;
++        priority: number;
++    };
+ }
+ /**
+ The type returned from
+@@ -306,12 +319,17 @@ This annotation is added to transactions that are produced by
+ picking a completion.
+ */
+ declare const pickedCompletion: _codemirror_state.AnnotationType<Completion>;
++type ExtendCompletion = (state: EditorState, change: {
++    from: number;
++    to: number;
++    insert: string | Text;
++}) => void;
+ /**
+ Helper function that returns a transaction spec which inserts a
+ completion's text in the main selection range, and any other
+ selection range that has the same text in front of it.
+ */
+-declare function insertCompletionText(state: EditorState, text: string, from: number, to: number): TransactionSpec;
++declare function insertCompletionText(state: EditorState, text: string | Text, from: number, to: number, extend?: ExtendCompletion): TransactionSpec;
+ 
+ interface CompletionConfig {
+     /**
+@@ -441,6 +459,10 @@ interface CompletionConfig {
+     milliseconds.
+     */
+     updateSyncTime?: number;
++    /**
++    overleaf: Move unfiltered results after the filtered ones
++    */
++    unfilteredResultsAtEnd?: boolean;
+ }
+ 
+ /**
+@@ -514,6 +536,8 @@ applies the snippet.
+ */
+ declare function snippetCompletion(template: string, completion: Completion): Completion;
+ 
++declare const getCompletionTooltip: (state: EditorState) => Tooltip | undefined | null;
++
+ /**
+ Returns a command that moves the completion selection forward or
+ backward by the given amount.
+@@ -562,6 +586,11 @@ interface CloseBracketConfig {
+     these prefixes before the opening quote.
+     */
+     stringPrefixes?: string[];
++    /**
++    An optional callback for overriding the content that's inserted
++    based on surrounding characters
++    */
++    buildInsert?: (state: EditorState, range: SelectionRange, open: string, close: string) => string;
+ }
+ /**
+ Extension to enable bracket-closing behavior. When a closeable
+@@ -593,6 +622,8 @@ to programmatically insert brackets—the
+ take care of running this for user input.)
+ */
+ declare function insertBracket(state: EditorState, bracket: string): Transaction | null;
++declare function nextChar(doc: Text, pos: number): string;
++declare function prevChar(doc: Text, pos: number): string;
+ 
+ /**
+ Returns an extension that enables autocompletion.
+@@ -636,4 +667,5 @@ the currently selected completion.
+ */
+ declare function setSelectedCompletion(index: number): StateEffect<unknown>;
+ 
+-export { type CloseBracketConfig, type Completion, CompletionContext, type CompletionInfo, type CompletionResult, type CompletionSection, type CompletionSource, acceptCompletion, autocompletion, clearSnippet, closeBrackets, closeBracketsKeymap, closeCompletion, completeAnyWord, completeFromList, completionKeymap, completionStatus, currentCompletions, deleteBracketPair, hasNextSnippetField, hasPrevSnippetField, ifIn, ifNotIn, insertBracket, insertCompletionText, moveCompletionSelection, nextSnippetField, pickedCompletion, prevSnippetField, selectedCompletion, selectedCompletionIndex, setSelectedCompletion, snippet, snippetCompletion, snippetKeymap, startCompletion };
++export { CompletionContext, acceptCompletion, autocompletion, clearSnippet, closeBrackets, closeBracketsKeymap, closeCompletion, completeAnyWord, completeFromList, completionKeymap, completionStatus, currentCompletions, deleteBracketPair, getCompletionTooltip, hasNextSnippetField, hasPrevSnippetField, ifIn, ifNotIn, insertBracket, insertCompletionText, moveCompletionSelection, nextChar, nextSnippetField, pickedCompletion, prevChar, prevSnippetField, selectedCompletion, selectedCompletionIndex, setSelectedCompletion, snippet, snippetCompletion, snippetKeymap, startCompletion };
++export type { CloseBracketConfig, Completion, CompletionInfo, CompletionResult, CompletionSection, CompletionSource };
+diff --git a/dist/index.d.ts b/dist/index.d.ts
+index b57b8f6..fce47ab 100644
+--- a/dist/index.d.ts
++++ b/dist/index.d.ts
+@@ -1,6 +1,6 @@
+ import * as _codemirror_state from '@codemirror/state';
+-import { EditorState, ChangeDesc, TransactionSpec, Transaction, StateCommand, Facet, Extension, StateEffect } from '@codemirror/state';
+-import { EditorView, Rect, KeyBinding, Command } from '@codemirror/view';
++import { EditorState, Text, ChangeDesc, TransactionSpec, StateCommand, Transaction, Facet, SelectionRange, Extension, StateEffect } from '@codemirror/state';
++import { EditorView, Rect, KeyBinding, Tooltip, Command } from '@codemirror/view';
+ import * as _lezer_common from '@lezer/common';
+ 
+ /**
+@@ -73,6 +73,19 @@ interface Completion {
+     a `{name}` object.
+     */
+     section?: string | CompletionSection;
++    /**
++    Can be used to alter the change created when the completion is applied
++    */
++    extend?: ExtendCompletion;
++    /**
++    If multiple sources return the same result, use this field to specifiy a
++    deduplication key as well as a priority. For each unique key, only the
++    completion with the highest priority will be shown.
++    */
++    deduplicate?: {
++        key: string;
++        priority: number;
++    };
+ }
+ /**
+ The type returned from
+@@ -306,12 +319,17 @@ This annotation is added to transactions that are produced by
+ picking a completion.
+ */
+ declare const pickedCompletion: _codemirror_state.AnnotationType<Completion>;
++type ExtendCompletion = (state: EditorState, change: {
++    from: number;
++    to: number;
++    insert: string | Text;
++}) => void;
+ /**
+ Helper function that returns a transaction spec which inserts a
+ completion's text in the main selection range, and any other
+ selection range that has the same text in front of it.
+ */
+-declare function insertCompletionText(state: EditorState, text: string, from: number, to: number): TransactionSpec;
++declare function insertCompletionText(state: EditorState, text: string | Text, from: number, to: number, extend?: ExtendCompletion): TransactionSpec;
+ 
+ interface CompletionConfig {
+     /**
+@@ -441,6 +459,10 @@ interface CompletionConfig {
+     milliseconds.
+     */
+     updateSyncTime?: number;
++    /**
++    overleaf: Move unfiltered results after the filtered ones
++    */
++    unfilteredResultsAtEnd?: boolean;
+ }
+ 
+ /**
+@@ -514,6 +536,8 @@ applies the snippet.
+ */
+ declare function snippetCompletion(template: string, completion: Completion): Completion;
+ 
++declare const getCompletionTooltip: (state: EditorState) => Tooltip | undefined | null;
++
+ /**
+ Returns a command that moves the completion selection forward or
+ backward by the given amount.
+@@ -562,6 +586,11 @@ interface CloseBracketConfig {
+     these prefixes before the opening quote.
+     */
+     stringPrefixes?: string[];
++    /**
++    An optional callback for overriding the content that's inserted
++    based on surrounding characters
++    */
++    buildInsert?: (state: EditorState, range: SelectionRange, open: string, close: string) => string;
+ }
+ /**
+ Extension to enable bracket-closing behavior. When a closeable
+@@ -593,6 +622,8 @@ to programmatically insert brackets—the
+ take care of running this for user input.)
+ */
+ declare function insertBracket(state: EditorState, bracket: string): Transaction | null;
++declare function nextChar(doc: Text, pos: number): string;
++declare function prevChar(doc: Text, pos: number): string;
+ 
+ /**
+ Returns an extension that enables autocompletion.
+@@ -636,4 +667,5 @@ the currently selected completion.
+ */
+ declare function setSelectedCompletion(index: number): StateEffect<unknown>;
+ 
+-export { type CloseBracketConfig, type Completion, CompletionContext, type CompletionInfo, type CompletionResult, type CompletionSection, type CompletionSource, acceptCompletion, autocompletion, clearSnippet, closeBrackets, closeBracketsKeymap, closeCompletion, completeAnyWord, completeFromList, completionKeymap, completionStatus, currentCompletions, deleteBracketPair, hasNextSnippetField, hasPrevSnippetField, ifIn, ifNotIn, insertBracket, insertCompletionText, moveCompletionSelection, nextSnippetField, pickedCompletion, prevSnippetField, selectedCompletion, selectedCompletionIndex, setSelectedCompletion, snippet, snippetCompletion, snippetKeymap, startCompletion };
++export { CompletionContext, acceptCompletion, autocompletion, clearSnippet, closeBrackets, closeBracketsKeymap, closeCompletion, completeAnyWord, completeFromList, completionKeymap, completionStatus, currentCompletions, deleteBracketPair, getCompletionTooltip, hasNextSnippetField, hasPrevSnippetField, ifIn, ifNotIn, insertBracket, insertCompletionText, moveCompletionSelection, nextChar, nextSnippetField, pickedCompletion, prevChar, prevSnippetField, selectedCompletion, selectedCompletionIndex, setSelectedCompletion, snippet, snippetCompletion, snippetKeymap, startCompletion };
++export type { CloseBracketConfig, Completion, CompletionInfo, CompletionResult, CompletionSection, CompletionSource };
+diff --git a/dist/index.js b/dist/index.js
+index 4729223..9361a53 100644
+--- a/dist/index.js
++++ b/dist/index.js
+@@ -1,4 +1,4 @@
+-import { Annotation, StateEffect, EditorSelection, codePointAt, codePointSize, fromCodePoint, Facet, combineConfig, StateField, Prec, Text, Transaction, MapMode, RangeValue, RangeSet, CharCategory } from '@codemirror/state';
++import { Annotation, StateEffect, Text, EditorSelection, codePointAt, codePointSize, fromCodePoint, Facet, combineConfig, StateField, Prec, Transaction, MapMode, RangeValue, RangeSet, CharCategory } from '@codemirror/state';
+ import { Direction, logException, showTooltip, EditorView, ViewPlugin, getTooltip, Decoration, WidgetType, keymap } from '@codemirror/view';
+ import { syntaxTree, indentUnit } from '@codemirror/language';
+ 
+@@ -185,16 +185,23 @@ Helper function that returns a transaction spec which inserts a
+ completion's text in the main selection range, and any other
+ selection range that has the same text in front of it.
+ */
+-function insertCompletionText(state, text, from, to) {
++function insertCompletionText(state, text, from, to, extend) {
+     let { main } = state.selection, fromOff = from - main.from, toOff = to - main.from;
+     return Object.assign(Object.assign({}, state.changeByRange(range => {
+         if (range != main && from != to &&
+             state.sliceDoc(range.from + fromOff, range.from + toOff) != state.sliceDoc(from, to))
+             return { range };
+-        let lines = state.toText(text);
++        let change = {
++            from: range.from + fromOff,
++            to: to == main.from ? range.to : range.from + toOff,
++            insert: text instanceof Text ? text : state.toText(text),
++        };
++        if (extend) {
++            extend(state, change);
++        }
+         return {
+-            changes: { from: range.from + fromOff, to: to == main.from ? range.to : range.from + toOff, insert: lines },
+-            range: EditorSelection.cursor(range.from + fromOff + lines.length)
++            changes: change,
++            range: EditorSelection.cursor(change.from + change.insert.length)
+         };
+     })), { scrollIntoView: true, userEvent: "input.complete" });
+ }
+@@ -387,7 +394,9 @@ const completionConfig = /*@__PURE__*/Facet.define({
+             filterStrict: false,
+             compareCompletions: (a, b) => a.label.localeCompare(b.label),
+             interactionDelay: 75,
+-            updateSyncTime: 100
++            updateSyncTime: 100,
++            // overleaf: default to at top which is default CM6 behaviour
++            unfilteredResultsAtEnd: false
+         }, {
+             defaultKeymap: (a, b) => a && b,
+             closeOnBlur: (a, b) => a && b,
+@@ -742,6 +751,7 @@ function score(option) {
+         (option.type ? 1 : 0);
+ }
+ function sortOptions(active, state) {
++    var _a;
+     let options = [];
+     let sections = null;
+     let addOption = (option) => {
+@@ -761,7 +771,8 @@ function sortOptions(active, state) {
+             let getMatch = a.result.getMatch;
+             if (a.result.filter === false) {
+                 for (let option of a.result.options) {
+-                    addOption(new Option(option, a.source, getMatch ? getMatch(option) : [], 1e9 - options.length));
++                    let defaultScore = conf.unfilteredResultsAtEnd ? -1e9 : 1e9;
++                    addOption(new Option(option, a.source, getMatch ? getMatch(option) : [], defaultScore - options.length));
+                 }
+             }
+             else {
+@@ -788,15 +799,42 @@ function sortOptions(active, state) {
+         }
+     }
+     let result = [], prev = null;
++    const priorityIndices = new Map();
+     let compare = conf.compareCompletions;
+     for (let opt of options.sort((a, b) => (b.score - a.score) || compare(a.completion, b.completion))) {
++        // overleaf: Deduplicate results with dedup options
++        //           The goal is to keep only the highest priority option, in the
++        //           highest scoring position.
++        const key = (_a = opt.completion.deduplicate) === null || _a === void 0 ? void 0 : _a.key;
++        if (key) {
++            // Handle merging specifically for deduplicated items item
++            const currentOptionIndex = priorityIndices.get(key);
++            if (currentOptionIndex === undefined) {
++                priorityIndices.set(key, result.length);
++                result.push(opt);
++                prev = opt.completion;
++            }
++            else {
++                if (result[currentOptionIndex].completion.deduplicate.priority < opt.completion.deduplicate.priority) {
++                    result[currentOptionIndex] = opt;
++                    if (currentOptionIndex === result.length - 1) {
++                        prev = opt.completion;
++                    }
++                }
++            }
++            continue;
++        }
++        // overleaf: end
+         let cur = opt.completion;
+-        if (!prev || prev.label != cur.label || prev.detail != cur.detail ||
+-            (prev.type != null && cur.type != null && prev.type != cur.type) ||
+-            prev.apply != cur.apply || prev.boost != cur.boost)
++        if (!prev || prev.label != cur.label)
++            result.push(opt);
++        // overleaf: we're already handling deduplication, so skip extra merges
++        else if (prev.deduplicate)
+             result.push(opt);
+         else if (score(opt.completion) > score(prev))
+             result[result.length - 1] = opt;
++        else if (opt.completion.info)
++            result[result.length - 1] = opt;
+         prev = opt.completion;
+     }
+     return result;
+@@ -815,8 +853,9 @@ class CompletionDialog {
+             : new CompletionDialog(this.options, makeAttrs(id, selected), this.tooltip, this.timestamp, selected, this.disabled);
+     }
+     static build(active, state, id, prev, conf, didSetActive) {
+-        if (prev && !didSetActive && active.some(s => s.isPending))
+-            return prev.setDisabled();
++        // Overleaf: avoid setting the previous completion state to disabled while completion sources are pending
++        // if (prev && !didSetActive && active.some(s => s.isPending))
++        //   return prev.setDisabled()
+         let options = sortOptions(active, state);
+         if (!options.length)
+             return prev && active.some(a => a.isPending) ? prev.setDisabled() : null;
+@@ -1015,13 +1054,14 @@ const completionState = /*@__PURE__*/StateField.define({
+         EditorView.contentAttributes.from(f, state => state.attrs)
+     ]
+ });
++const getCompletionTooltip = (state) => { var _a; return (_a = state.field(completionState, false)) === null || _a === void 0 ? void 0 : _a.tooltip; };
+ function applyCompletion(view, option) {
+     const apply = option.completion.apply || option.completion.label;
+     let result = view.state.field(completionState).active.find(a => a.source == option.source);
+     if (!(result instanceof ActiveResult))
+         return false;
+     if (typeof apply == "string")
+-        view.dispatch(Object.assign(Object.assign({}, insertCompletionText(view.state, apply, result.from, result.to)), { annotations: pickedCompletion.of(option.completion) }));
++        view.dispatch(Object.assign(Object.assign({}, insertCompletionText(view.state, apply, result.from, result.to, option.completion.extend)), { annotations: pickedCompletion.of(option.completion) }));
+     else
+         apply(view, option.completion, result.from, result.to);
+     return true;
+@@ -1557,20 +1597,42 @@ interpreted as indicating a placeholder.
+ function snippet(template) {
+     let snippet = Snippet.parse(template);
+     return (editor, completion, from, to) => {
+-        let { text, ranges } = snippet.instantiate(editor.state, from);
+-        let { main } = editor.state.selection;
+-        let spec = {
+-            changes: { from, to: to == main.from ? main.to : to, insert: Text.of(text) },
+-            scrollIntoView: true,
+-            annotations: completion ? [pickedCompletion.of(completion), Transaction.userEvent.of("input.complete")] : undefined
+-        };
++        let { main } = editor.state.selection, fromOff = from - main.from, toOff = to - main.from;
++        let ranges = [];
++        let totalOffset = 0;
++        let spec = Object.assign(Object.assign({}, editor.state.changeByRange(range => {
++            if (range != main && from != to &&
++                editor.state.sliceDoc(range.from + fromOff, range.from + toOff) != editor.state.sliceDoc(from, to))
++                return { range };
++            let { text, ranges: fieldRanges } = snippet.instantiate(editor.state, range.from + fromOff);
++            let change = {
++                from: range.from + fromOff,
++                to: range.from + toOff,
++                insert: Text.of(text)
++            };
++            let originalTo = change.to;
++            let offset = change.insert.length + fromOff;
++            if (completion.extend) {
++                completion.extend(editor.state, change);
++                offset += originalTo - change.to;
++            }
++            for (const fieldRange of fieldRanges) {
++                ranges.push(new FieldRange(fieldRange.field, fieldRange.from + totalOffset, fieldRange.to + totalOffset));
++            }
++            totalOffset += offset;
++            return {
++                changes: change,
++                range: EditorSelection.cursor(change.from + change.insert.length)
++            };
++        })), { scrollIntoView: true, annotations: completion ? [pickedCompletion.of(completion), Transaction.userEvent.of("input.complete")] : undefined, effects: [] });
+         if (ranges.length)
+             spec.selection = fieldSelection(ranges, 0);
+         if (ranges.some(r => r.field > 0)) {
+             let active = new ActiveSnippet(ranges, 0);
+-            let effects = spec.effects = [setActive.of(active)];
+-            if (editor.state.field(snippetState, false) === undefined)
+-                effects.push(StateEffect.appendConfig.of([snippetState, addSnippetKeymap, snippetPointerHandler, baseTheme]));
++            spec.effects.push(setActive.of(active));
++            if (editor.state.field(snippetState, false) === undefined) {
++                spec.effects.push(StateEffect.appendConfig.of([snippetState, addSnippetKeymap, snippetPointerHandler, baseTheme]));
++            }
+         }
+         editor.dispatch(editor.state.update(spec));
+     };
+@@ -1744,7 +1806,8 @@ const completeAnyWord = context => {
+ const defaults = {
+     brackets: ["(", "[", "{", "'", '"'],
+     before: ")]}:;>",
+-    stringPrefixes: []
++    stringPrefixes: [],
++    buildInsert: (state, range, open, close) => open + close,
+ };
+ const closeBracketEffect = /*@__PURE__*/StateEffect.define({
+     map(value, mapping) {
+@@ -1852,8 +1915,8 @@ function insertBracket(state, bracket) {
+     for (let tok of tokens) {
+         let closed = closing(codePointAt(tok, 0));
+         if (bracket == tok)
+-            return closed == tok ? handleSame(state, tok, tokens.indexOf(tok + tok + tok) > -1, conf)
+-                : handleOpen(state, tok, closed, conf.before || defaults.before);
++            return closed == tok ? handleSame(state, tok, tokens.indexOf(tok + tok) > -1, tokens.indexOf(tok + tok + tok) > -1, conf)
++                : handleOpen(state, tok, closed, conf.before || defaults.before, conf);
+         if (bracket == closed && closedBracketAt(state, state.selection.main.from))
+             return handleClose(state, tok, closed);
+     }
+@@ -1875,17 +1938,21 @@ function prevChar(doc, pos) {
+     let prev = doc.sliceString(pos - 2, pos);
+     return codePointSize(codePointAt(prev, 0)) == prev.length ? prev : prev.slice(1);
+ }
+-function handleOpen(state, open, close, closeBefore) {
++function handleOpen(state, open, close, closeBefore, config) {
++    let buildInsert = config.buildInsert || defaults.buildInsert;
+     let dont = null, changes = state.changeByRange(range => {
++        var _a;
+         if (!range.empty)
+             return { changes: [{ insert: open, from: range.from }, { insert: close, from: range.to }],
+                 effects: closeBracketEffect.of(range.to + open.length),
+                 range: EditorSelection.range(range.anchor + open.length, range.head + open.length) };
+         let next = nextChar(state.doc, range.head);
+-        if (!next || /\s/.test(next) || closeBefore.indexOf(next) > -1)
+-            return { changes: { insert: open + close, from: range.head },
+-                effects: closeBracketEffect.of(range.head + open.length),
++        if (!next || /\s/.test(next) || closeBefore.indexOf(next) > -1) {
++            const insert = (_a = buildInsert(state, range, open, close)) !== null && _a !== void 0 ? _a : open + close;
++            return { changes: { insert, from: range.head },
++                effects: insert === open ? [] : closeBracketEffect.of(range.head + open.length),
+                 range: EditorSelection.cursor(range.head + open.length) };
++        }
+         return { range: dont = range };
+     });
+     return dont ? null : state.update(changes, {
+@@ -1907,18 +1974,36 @@ function handleClose(state, _open, close) {
+ }
+ // Handles cases where the open and close token are the same, and
+ // possibly triple quotes (as in `"""abc"""`-style quoting).
+-function handleSame(state, token, allowTriple, config) {
++function handleSame(state, token, allowDouble, allowTriple, config) {
+     let stringPrefixes = config.stringPrefixes || defaults.stringPrefixes;
++    let buildInsert = config.buildInsert || defaults.buildInsert;
+     let dont = null, changes = state.changeByRange(range => {
++        var _a, _b, _c;
+         if (!range.empty)
+             return { changes: [{ insert: token, from: range.from }, { insert: token, from: range.to }],
+                 effects: closeBracketEffect.of(range.to + token.length),
+                 range: EditorSelection.range(range.anchor + token.length, range.head + token.length) };
+         let pos = range.head, next = nextChar(state.doc, pos), start;
+-        if (next == token) {
++        if (allowTriple && state.sliceDoc(pos - 2 * token.length, pos) == token + token &&
++            (start = canStartStringAt(state, pos - 2 * token.length, stringPrefixes)) > -1 &&
++            nodeStart(state, start)) {
++            return { changes: { insert: token + token + token + token, from: pos },
++                effects: closeBracketEffect.of(pos + token.length),
++                range: EditorSelection.cursor(pos + token.length) };
++        }
++        else if (allowDouble && state.sliceDoc(pos - token.length, pos) == token &&
++            (start = canStartStringAt(state, pos - token.length, stringPrefixes)) > -1 &&
++            nodeStart(state, start)) {
++            let insert = (_a = buildInsert(state, range, token, token)) !== null && _a !== void 0 ? _a : token + token;
++            return { changes: { insert, from: pos },
++                effects: insert === token ? [] : closeBracketEffect.of(pos + token.length),
++                range: EditorSelection.cursor(pos + token.length) };
++        }
++        else if (next == token) {
+             if (nodeStart(state, pos)) {
+-                return { changes: { insert: token + token, from: pos },
+-                    effects: closeBracketEffect.of(pos + token.length),
++                let insert = (_b = buildInsert(state, range, token, token)) !== null && _b !== void 0 ? _b : token + token;
++                return { changes: { insert, from: pos },
++                    effects: insert === token ? [] : closeBracketEffect.of(pos + token.length),
+                     range: EditorSelection.cursor(pos + token.length) };
+             }
+             else if (closedBracketAt(state, pos)) {
+@@ -1928,18 +2013,13 @@ function handleSame(state, token, allowTriple, config) {
+                     range: EditorSelection.cursor(pos + content.length) };
+             }
+         }
+-        else if (allowTriple && state.sliceDoc(pos - 2 * token.length, pos) == token + token &&
+-            (start = canStartStringAt(state, pos - 2 * token.length, stringPrefixes)) > -1 &&
+-            nodeStart(state, start)) {
+-            return { changes: { insert: token + token + token + token, from: pos },
+-                effects: closeBracketEffect.of(pos + token.length),
+-                range: EditorSelection.cursor(pos + token.length) };
+-        }
+         else if (state.charCategorizer(pos)(next) != CharCategory.Word) {
+-            if (canStartStringAt(state, pos, stringPrefixes) > -1 && !probablyInString(state, pos, token, stringPrefixes))
+-                return { changes: { insert: token + token, from: pos },
+-                    effects: closeBracketEffect.of(pos + token.length),
++            if (canStartStringAt(state, pos, stringPrefixes) > -1 && !probablyInString(state, pos, token, stringPrefixes)) {
++                const insert = (_c = buildInsert(state, range, token, token)) !== null && _c !== void 0 ? _c : token + token;
++                return { changes: { insert, from: pos },
++                    effects: insert === token ? [] : closeBracketEffect.of(pos + token.length),
+                     range: EditorSelection.cursor(pos + token.length) };
++            }
+         }
+         return { range: dont = range };
+     });
+@@ -2071,4 +2151,4 @@ function setSelectedCompletion(index) {
+     return setSelectedEffect.of(index);
+ }
+ 
+-export { CompletionContext, acceptCompletion, autocompletion, clearSnippet, closeBrackets, closeBracketsKeymap, closeCompletion, completeAnyWord, completeFromList, completionKeymap, completionStatus, currentCompletions, deleteBracketPair, hasNextSnippetField, hasPrevSnippetField, ifIn, ifNotIn, insertBracket, insertCompletionText, moveCompletionSelection, nextSnippetField, pickedCompletion, prevSnippetField, selectedCompletion, selectedCompletionIndex, setSelectedCompletion, snippet, snippetCompletion, snippetKeymap, startCompletion };
++export { CompletionContext, acceptCompletion, autocompletion, clearSnippet, closeBrackets, closeBracketsKeymap, closeCompletion, completeAnyWord, completeFromList, completionKeymap, completionStatus, currentCompletions, deleteBracketPair, getCompletionTooltip, hasNextSnippetField, hasPrevSnippetField, ifIn, ifNotIn, insertBracket, insertCompletionText, moveCompletionSelection, nextChar, nextSnippetField, pickedCompletion, prevChar, prevSnippetField, selectedCompletion, selectedCompletionIndex, setSelectedCompletion, snippet, snippetCompletion, snippetKeymap, startCompletion };

+ 381 - 0
.yarn/patches/@codemirror-search-npm-6.5.8.patch

@@ -0,0 +1,381 @@
+diff --git a/dist/index.cjs b/dist/index.cjs
+index 46231ae..fb0f9aa 100644
+--- a/dist/index.cjs
++++ b/dist/index.cjs
+@@ -592,6 +592,7 @@ class SearchQuery {
+         this.valid = !!this.search && (!this.regexp || validRegExp(this.search));
+         this.unquoted = this.unquote(this.search);
+         this.wholeWord = !!config.wholeWord;
++        this.scope = config.scope;
+     }
+     /**
+     @internal
+@@ -606,7 +607,7 @@ class SearchQuery {
+     eq(other) {
+         return this.search == other.search && this.replace == other.replace &&
+             this.caseSensitive == other.caseSensitive && this.regexp == other.regexp &&
+-            this.wholeWord == other.wholeWord;
++            this.wholeWord == other.wholeWord && this.scope == other.scope;
+     }
+     /**
+     @internal
+@@ -631,7 +632,12 @@ class QueryType {
+     }
+ }
+ function stringCursor(spec, state, from, to) {
+-    return new SearchCursor(state.doc, spec.unquoted, from, to, spec.caseSensitive ? undefined : x => x.toLowerCase(), spec.wholeWord ? stringWordTest(state.doc, state.charCategorizer(state.selection.main.head)) : undefined);
++    const test = spec.wholeWord ? stringWordTest(state.doc, state.charCategorizer(state.selection.main.head)) : undefined;
++    const testWithinScope = (from, to, buffer, bufferPos) => {
++        return (!test || test(from, to, buffer, bufferPos))
++            && (!spec.scope || spec.scope.some(range => from >= range.from && from <= range.to && to >= range.from && to <= range.to));
++    };
++    return new SearchCursor(state.doc, spec.unquoted, from, to, spec.caseSensitive ? undefined : x => x.toLowerCase(), testWithinScope);
+ }
+ function stringWordTest(doc, categorizer) {
+     return (from, to, buf, bufPos) => {
+@@ -695,9 +701,14 @@ class StringQuery extends QueryType {
+     }
+ }
+ function regexpCursor(spec, state, from, to) {
++    const test = spec.wholeWord ? regexpWordTest(state.charCategorizer(state.selection.main.head)) : undefined;
++    const testWithinScope = (from, to, match) => {
++        return (!test || test(from, to, match))
++            && (!spec.scope || spec.scope.some(range => from >= range.from && from <= range.to && to >= range.from && to <= range.to));
++    };
+     return new RegExpCursor(state.doc, spec.search, {
+         ignoreCase: !spec.caseSensitive,
+-        test: spec.wholeWord ? regexpWordTest(state.charCategorizer(state.selection.main.head)) : undefined
++        test: testWithinScope,
+     }, from, to);
+ }
+ function charBefore(str, index) {
+@@ -737,10 +748,18 @@ class RegExpQuery extends QueryType {
+             this.prevMatchInRange(state, curTo, state.doc.length);
+     }
+     getReplacement(result) {
+-        return this.spec.unquote(this.spec.replace).replace(/\$([$&\d+])/g, (m, i) => i == "$" ? "$"
+-            : i == "&" ? result.match[0]
+-                : i != "0" && +i < result.match.length ? result.match[i]
+-                    : m);
++        return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g, (m, i) => {
++            if (i == "&")
++                return result.match[0];
++            if (i == "$")
++                return "$";
++            for (let l = i.length; l > 0; l--) {
++                let n = +i.slice(0, l);
++                if (n > 0 && n < result.match.length)
++                    return result.match[n] + i.slice(l);
++            }
++            return m;
++        });
+     }
+     matchAll(state, limit) {
+         let cursor = regexpCursor(this.spec, state, 0, state.doc.length), ranges = [];
+@@ -1227,7 +1246,9 @@ const searchExtensions = [
+ exports.RegExpCursor = RegExpCursor;
+ exports.SearchCursor = SearchCursor;
+ exports.SearchQuery = SearchQuery;
++exports.StringQuery = StringQuery;
+ exports.closeSearchPanel = closeSearchPanel;
++exports.createSearchPanel = createSearchPanel;
+ exports.findNext = findNext;
+ exports.findPrevious = findPrevious;
+ exports.getSearchQuery = getSearchQuery;
+@@ -1242,4 +1263,6 @@ exports.searchPanelOpen = searchPanelOpen;
+ exports.selectMatches = selectMatches;
+ exports.selectNextOccurrence = selectNextOccurrence;
+ exports.selectSelectionMatches = selectSelectionMatches;
++exports.selectWord = selectWord;
+ exports.setSearchQuery = setSearchQuery;
++exports.togglePanel = togglePanel;
+diff --git a/dist/index.d.cts b/dist/index.d.cts
+index 08f5696..663d192 100644
+--- a/dist/index.d.cts
++++ b/dist/index.d.cts
+@@ -1,6 +1,6 @@
+ import * as _codemirror_state from '@codemirror/state';
+ import { Text, Extension, StateCommand, EditorState, SelectionRange, StateEffect } from '@codemirror/state';
+-import { Command, KeyBinding, EditorView, Panel } from '@codemirror/view';
++import { Command, EditorView, Panel, KeyBinding } from '@codemirror/view';
+ 
+ /**
+ A search cursor provides an iterator over text matches in a
+@@ -161,6 +161,7 @@ the `"cm-selectionMatch"` class for the highlighting. When
+ itself will be highlighted with `"cm-selectionMatch-main"`.
+ */
+ declare function highlightSelectionMatches(options?: HighlightOptions): Extension;
++declare const selectWord: StateCommand;
+ /**
+ Select next occurrence of the current selection. Expand selection
+ to the surrounding word when the selection is empty.
+@@ -264,6 +265,13 @@ declare class SearchQuery {
+     */
+     readonly wholeWord: boolean;
+     /**
++    When set, only include search matches within these ranges
++    */
++    readonly scope?: Readonly<{
++        from: number;
++        to: number;
++    }[]>;
++    /**
+     Create a query object.
+     */
+     constructor(config: {
+@@ -293,6 +301,13 @@ declare class SearchQuery {
+         Enable whole-word matching.
+         */
+         wholeWord?: boolean;
++        /**
++        The ranges to match within
++        */
++        scope?: Readonly<{
++            from: number;
++            to: number;
++        }[]>;
+     });
+     /**
+     Compare this query to another query.
+@@ -307,6 +322,34 @@ declare class SearchQuery {
+         to: number;
+     }>;
+ }
++type SearchResult = typeof SearchCursor.prototype.value;
++declare abstract class QueryType<Result extends SearchResult = SearchResult> {
++    readonly spec: SearchQuery;
++    constructor(spec: SearchQuery);
++    abstract nextMatch(state: EditorState, curFrom: number, curTo: number): Result | null;
++    abstract prevMatch(state: EditorState, curFrom: number, curTo: number): Result | null;
++    abstract getReplacement(result: Result): string;
++    abstract matchAll(state: EditorState, limit: number): readonly Result[] | null;
++    abstract highlight(state: EditorState, from: number, to: number, add: (from: number, to: number) => void): void;
++}
++declare class StringQuery extends QueryType<SearchResult> {
++    constructor(spec: SearchQuery);
++    nextMatch(state: EditorState, curFrom: number, curTo: number): {
++        from: number;
++        to: number;
++    } | null;
++    private prevMatchInRange;
++    prevMatch(state: EditorState, curFrom: number, curTo: number): {
++        from: number;
++        to: number;
++    } | null;
++    getReplacement(_result: SearchResult): string;
++    matchAll(state: EditorState, limit: number): {
++        from: number;
++        to: number;
++    }[] | null;
++    highlight(state: EditorState, from: number, to: number, add: (from: number, to: number) => void): void;
++}
+ /**
+ A state effect that updates the current search query. Note that
+ this only has an effect if the search state has been initialized
+@@ -315,6 +358,7 @@ by running [`openSearchPanel`](https://codemirror.net/6/docs/ref/#search.openSea
+ once).
+ */
+ declare const setSearchQuery: _codemirror_state.StateEffectType<SearchQuery>;
++declare const togglePanel: _codemirror_state.StateEffectType<boolean>;
+ /**
+ Get the current search query from an editor state.
+ */
+@@ -353,6 +397,7 @@ Replace all instances of the search query with the given
+ replacement.
+ */
+ declare const replaceAll: Command;
++declare function createSearchPanel(view: EditorView): Panel;
+ /**
+ Make sure the search panel is open and focused.
+ */
+@@ -372,4 +417,4 @@ Default search-related key bindings.
+ */
+ declare const searchKeymap: readonly KeyBinding[];
+ 
+-export { RegExpCursor, SearchCursor, SearchQuery, closeSearchPanel, findNext, findPrevious, getSearchQuery, gotoLine, highlightSelectionMatches, openSearchPanel, replaceAll, replaceNext, search, searchKeymap, searchPanelOpen, selectMatches, selectNextOccurrence, selectSelectionMatches, setSearchQuery };
++export { RegExpCursor, SearchCursor, SearchQuery, StringQuery, closeSearchPanel, createSearchPanel, findNext, findPrevious, getSearchQuery, gotoLine, highlightSelectionMatches, openSearchPanel, replaceAll, replaceNext, search, searchKeymap, searchPanelOpen, selectMatches, selectNextOccurrence, selectSelectionMatches, selectWord, setSearchQuery, togglePanel };
+diff --git a/dist/index.d.ts b/dist/index.d.ts
+index 08f5696..663d192 100644
+--- a/dist/index.d.ts
++++ b/dist/index.d.ts
+@@ -1,6 +1,6 @@
+ import * as _codemirror_state from '@codemirror/state';
+ import { Text, Extension, StateCommand, EditorState, SelectionRange, StateEffect } from '@codemirror/state';
+-import { Command, KeyBinding, EditorView, Panel } from '@codemirror/view';
++import { Command, EditorView, Panel, KeyBinding } from '@codemirror/view';
+ 
+ /**
+ A search cursor provides an iterator over text matches in a
+@@ -161,6 +161,7 @@ the `"cm-selectionMatch"` class for the highlighting. When
+ itself will be highlighted with `"cm-selectionMatch-main"`.
+ */
+ declare function highlightSelectionMatches(options?: HighlightOptions): Extension;
++declare const selectWord: StateCommand;
+ /**
+ Select next occurrence of the current selection. Expand selection
+ to the surrounding word when the selection is empty.
+@@ -264,6 +265,13 @@ declare class SearchQuery {
+     */
+     readonly wholeWord: boolean;
+     /**
++    When set, only include search matches within these ranges
++    */
++    readonly scope?: Readonly<{
++        from: number;
++        to: number;
++    }[]>;
++    /**
+     Create a query object.
+     */
+     constructor(config: {
+@@ -293,6 +301,13 @@ declare class SearchQuery {
+         Enable whole-word matching.
+         */
+         wholeWord?: boolean;
++        /**
++        The ranges to match within
++        */
++        scope?: Readonly<{
++            from: number;
++            to: number;
++        }[]>;
+     });
+     /**
+     Compare this query to another query.
+@@ -307,6 +322,34 @@ declare class SearchQuery {
+         to: number;
+     }>;
+ }
++type SearchResult = typeof SearchCursor.prototype.value;
++declare abstract class QueryType<Result extends SearchResult = SearchResult> {
++    readonly spec: SearchQuery;
++    constructor(spec: SearchQuery);
++    abstract nextMatch(state: EditorState, curFrom: number, curTo: number): Result | null;
++    abstract prevMatch(state: EditorState, curFrom: number, curTo: number): Result | null;
++    abstract getReplacement(result: Result): string;
++    abstract matchAll(state: EditorState, limit: number): readonly Result[] | null;
++    abstract highlight(state: EditorState, from: number, to: number, add: (from: number, to: number) => void): void;
++}
++declare class StringQuery extends QueryType<SearchResult> {
++    constructor(spec: SearchQuery);
++    nextMatch(state: EditorState, curFrom: number, curTo: number): {
++        from: number;
++        to: number;
++    } | null;
++    private prevMatchInRange;
++    prevMatch(state: EditorState, curFrom: number, curTo: number): {
++        from: number;
++        to: number;
++    } | null;
++    getReplacement(_result: SearchResult): string;
++    matchAll(state: EditorState, limit: number): {
++        from: number;
++        to: number;
++    }[] | null;
++    highlight(state: EditorState, from: number, to: number, add: (from: number, to: number) => void): void;
++}
+ /**
+ A state effect that updates the current search query. Note that
+ this only has an effect if the search state has been initialized
+@@ -315,6 +358,7 @@ by running [`openSearchPanel`](https://codemirror.net/6/docs/ref/#search.openSea
+ once).
+ */
+ declare const setSearchQuery: _codemirror_state.StateEffectType<SearchQuery>;
++declare const togglePanel: _codemirror_state.StateEffectType<boolean>;
+ /**
+ Get the current search query from an editor state.
+ */
+@@ -353,6 +397,7 @@ Replace all instances of the search query with the given
+ replacement.
+ */
+ declare const replaceAll: Command;
++declare function createSearchPanel(view: EditorView): Panel;
+ /**
+ Make sure the search panel is open and focused.
+ */
+@@ -372,4 +417,4 @@ Default search-related key bindings.
+ */
+ declare const searchKeymap: readonly KeyBinding[];
+ 
+-export { RegExpCursor, SearchCursor, SearchQuery, closeSearchPanel, findNext, findPrevious, getSearchQuery, gotoLine, highlightSelectionMatches, openSearchPanel, replaceAll, replaceNext, search, searchKeymap, searchPanelOpen, selectMatches, selectNextOccurrence, selectSelectionMatches, setSearchQuery };
++export { RegExpCursor, SearchCursor, SearchQuery, StringQuery, closeSearchPanel, createSearchPanel, findNext, findPrevious, getSearchQuery, gotoLine, highlightSelectionMatches, openSearchPanel, replaceAll, replaceNext, search, searchKeymap, searchPanelOpen, selectMatches, selectNextOccurrence, selectSelectionMatches, selectWord, setSearchQuery, togglePanel };
+diff --git a/dist/index.js b/dist/index.js
+index 22172ef..08a9974 100644
+--- a/dist/index.js
++++ b/dist/index.js
+@@ -590,6 +590,7 @@ class SearchQuery {
+         this.valid = !!this.search && (!this.regexp || validRegExp(this.search));
+         this.unquoted = this.unquote(this.search);
+         this.wholeWord = !!config.wholeWord;
++        this.scope = config.scope;
+     }
+     /**
+     @internal
+@@ -604,7 +605,7 @@ class SearchQuery {
+     eq(other) {
+         return this.search == other.search && this.replace == other.replace &&
+             this.caseSensitive == other.caseSensitive && this.regexp == other.regexp &&
+-            this.wholeWord == other.wholeWord;
++            this.wholeWord == other.wholeWord && this.scope == other.scope;
+     }
+     /**
+     @internal
+@@ -629,7 +630,12 @@ class QueryType {
+     }
+ }
+ function stringCursor(spec, state, from, to) {
+-    return new SearchCursor(state.doc, spec.unquoted, from, to, spec.caseSensitive ? undefined : x => x.toLowerCase(), spec.wholeWord ? stringWordTest(state.doc, state.charCategorizer(state.selection.main.head)) : undefined);
++    const test = spec.wholeWord ? stringWordTest(state.doc, state.charCategorizer(state.selection.main.head)) : undefined;
++    const testWithinScope = (from, to, buffer, bufferPos) => {
++        return (!test || test(from, to, buffer, bufferPos))
++            && (!spec.scope || spec.scope.some(range => from >= range.from && from <= range.to && to >= range.from && to <= range.to));
++    };
++    return new SearchCursor(state.doc, spec.unquoted, from, to, spec.caseSensitive ? undefined : x => x.toLowerCase(), testWithinScope);
+ }
+ function stringWordTest(doc, categorizer) {
+     return (from, to, buf, bufPos) => {
+@@ -693,9 +699,14 @@ class StringQuery extends QueryType {
+     }
+ }
+ function regexpCursor(spec, state, from, to) {
++    const test = spec.wholeWord ? regexpWordTest(state.charCategorizer(state.selection.main.head)) : undefined;
++    const testWithinScope = (from, to, match) => {
++        return (!test || test(from, to, match))
++            && (!spec.scope || spec.scope.some(range => from >= range.from && from <= range.to && to >= range.from && to <= range.to));
++    };
+     return new RegExpCursor(state.doc, spec.search, {
+         ignoreCase: !spec.caseSensitive,
+-        test: spec.wholeWord ? regexpWordTest(state.charCategorizer(state.selection.main.head)) : undefined
++        test: testWithinScope,
+     }, from, to);
+ }
+ function charBefore(str, index) {
+@@ -735,10 +746,18 @@ class RegExpQuery extends QueryType {
+             this.prevMatchInRange(state, curTo, state.doc.length);
+     }
+     getReplacement(result) {
+-        return this.spec.unquote(this.spec.replace).replace(/\$([$&\d+])/g, (m, i) => i == "$" ? "$"
+-            : i == "&" ? result.match[0]
+-                : i != "0" && +i < result.match.length ? result.match[i]
+-                    : m);
++        return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g, (m, i) => {
++            if (i == "&")
++                return result.match[0];
++            if (i == "$")
++                return "$";
++            for (let l = i.length; l > 0; l--) {
++                let n = +i.slice(0, l);
++                if (n > 0 && n < result.match.length)
++                    return result.match[n] + i.slice(l);
++            }
++            return m;
++        });
+     }
+     matchAll(state, limit) {
+         let cursor = regexpCursor(this.spec, state, 0, state.doc.length), ranges = [];
+@@ -1222,4 +1241,4 @@ const searchExtensions = [
+     baseTheme
+ ];
+ 
+-export { RegExpCursor, SearchCursor, SearchQuery, closeSearchPanel, findNext, findPrevious, getSearchQuery, gotoLine, highlightSelectionMatches, openSearchPanel, replaceAll, replaceNext, search, searchKeymap, searchPanelOpen, selectMatches, selectNextOccurrence, selectSelectionMatches, setSearchQuery };
++export { RegExpCursor, SearchCursor, SearchQuery, StringQuery, closeSearchPanel, createSearchPanel, findNext, findPrevious, getSearchQuery, gotoLine, highlightSelectionMatches, openSearchPanel, replaceAll, replaceNext, search, searchKeymap, searchPanelOpen, selectMatches, selectNextOccurrence, selectSelectionMatches, selectWord, setSearchQuery, togglePanel };

+ 44 - 0
.yarn/patches/body-parser-npm-1.20.4.patch

@@ -0,0 +1,44 @@
+diff --git a/lib/read.js b/lib/read.js
+index fce6283..6131c31 100644
+--- a/lib/read.js
++++ b/lib/read.js
+@@ -18,7 +18,7 @@ var iconv = require('iconv-lite')
+ var onFinished = require('on-finished')
+ var unpipe = require('unpipe')
+ var zlib = require('zlib')
+-
++var Stream = require('stream')
+ /**
+  * Module exports.
+  */
+@@ -166,25 +166,25 @@ function contentstream (req, debug, inflate) {
+     case 'deflate':
+       stream = zlib.createInflate()
+       debug('inflate body')
+-      req.pipe(stream)
++      // req.pipe(stream)
+       break
+     case 'gzip':
+       stream = zlib.createGunzip()
+       debug('gunzip body')
+-      req.pipe(stream)
++      // req.pipe(stream)
+       break
+     case 'identity':
+       stream = req
+       stream.length = length
+-      break
++      return req
+     default:
+       throw createError(415, 'unsupported content encoding "' + encoding + '"', {
+         encoding: encoding,
+         type: 'encoding.unsupported'
+       })
+   }
+-
+-  return stream
++  var pass = new Stream.PassThrough(); Stream.pipeline(req, stream, pass, () => {})
++  return pass
+ }
+ 
+ /**

+ 13 - 0
.yarn/patches/cypress-multi-reporters-npm-2.0.5.patch

@@ -0,0 +1,13 @@
+diff --git a/lib/MultiReporters.js b/lib/MultiReporters.js
+index 98dc4ef..b2a97bf 100644
+--- a/lib/MultiReporters.js
++++ b/lib/MultiReporters.js
+@@ -160,7 +160,7 @@ MultiReporters.prototype.getCustomOptions = function (options) {
+         debug('options file (custom)', customOptionsFile);
+ 
+         try {
+-            if ('.js' === path.extname(customOptionsFile)) {
++            if (['.js', '.cjs'].includes(path.extname(customOptionsFile))) {
+                 customOptions = require(customOptionsFile);
+             }
+             else {

+ 13 - 0
.yarn/patches/forwarded-npm-0.2.0.patch

@@ -0,0 +1,13 @@
+diff --git a/index.js b/index.js
+index b2b6bdd..75e6254 100644
+--- a/index.js
++++ b/index.js
+@@ -46,7 +46,7 @@ function forwarded (req) {
+ function getSocketAddr (req) {
+   return req.socket
+     ? req.socket.remoteAddress
+-    : req.connection.remoteAddress
++    : req.connection && req.connection.remoteAddress
+ }
+ 
+ /**

+ 13 - 0
.yarn/patches/mocha-multi-reporters-npm-1.5.1-0a1088aed5.patch

@@ -0,0 +1,13 @@
+diff --git a/lib/MultiReporters.js b/lib/MultiReporters.js
+index d61e019711d5ac7f82c0fb90548bb0eb41ebbb85..e7a9515e05287621301b831191884a84d72ad0a1 100644
+--- a/lib/MultiReporters.js
++++ b/lib/MultiReporters.js
+@@ -153,7 +153,7 @@ MultiReporters.prototype.getCustomOptions = function (options) {
+         debug('options file (custom)', customOptionsFile);
+ 
+         try {
+-            if ('.js' === path.extname(customOptionsFile)) {
++            if (['.js', '.cjs'].includes(path.extname(customOptionsFile))) {
+                 customOptions = require(customOptionsFile);
+             }
+             else {

+ 13 - 0
.yarn/patches/multer-npm-2.1.1.patch

@@ -0,0 +1,13 @@
+diff --git a/lib/make-middleware.js b/lib/make-middleware.js
+index ee50988..de77364 100644
+--- a/lib/make-middleware.js
++++ b/lib/make-middleware.js
+@@ -164,7 +164,7 @@ function makeMiddleware (setup) {
+       if (fieldname == null) return abortWithCode('MISSING_FIELD_NAME')
+ 
+       // don't attach to the files object, if there is no file
+-      if (!filename) return fileStream.resume()
++      if (!filename) filename = 'undefined'
+ 
+       // Work around bug in Busboy (https://github.com/mscdex/busboy/issues/6)
+       if (limits && Object.prototype.hasOwnProperty.call(limits, 'fieldNameSize')) {

+ 76 - 0
.yarn/patches/node-fetch-npm-2.7.0.patch

@@ -0,0 +1,76 @@
+diff --git a/lib/index.js b/lib/index.js
+index 567ff5d..8eb45f7 100644
+--- a/lib/index.js
++++ b/lib/index.js
+@@ -545,8 +545,8 @@ function clone(instance) {
+ 		// tee instance body
+ 		p1 = new PassThrough();
+ 		p2 = new PassThrough();
+-		body.pipe(p1);
+-		body.pipe(p2);
++		Stream.pipeline(body, p1, () => {});
++		Stream.pipeline(body, p2, () => {});
+ 		// set instance body to teed body and return the other teed body
+ 		instance[INTERNALS].body = p1;
+ 		body = p2;
+@@ -648,14 +648,14 @@ function writeToStream(dest, instance) {
+ 		// body is null
+ 		dest.end();
+ 	} else if (isBlob(body)) {
+-		body.stream().pipe(dest);
++		Stream.pipeline(body.stream(), dest, () => {});
+ 	} else if (Buffer.isBuffer(body)) {
+ 		// body is buffer
+ 		dest.write(body);
+ 		dest.end();
+ 	} else {
+ 		// body is stream
+-		body.pipe(dest);
++		Stream.pipeline(body, dest, () => {});
+ 	}
+ }
+ 
+@@ -1638,7 +1638,7 @@ function fetch(url, opts) {
+ 			res.once('end', function () {
+ 				if (signal) signal.removeEventListener('abort', abortAndFinalize);
+ 			});
+-			let body = res.pipe(new PassThrough$1());
++			let body = Stream.pipeline(res, new PassThrough(), error => { if (error) reject(error); });
+ 
+ 			const response_options = {
+ 				url: request.url,
+@@ -1679,7 +1679,7 @@ function fetch(url, opts) {
+ 
+ 			// for gzip
+ 			if (codings == 'gzip' || codings == 'x-gzip') {
+-				body = body.pipe(zlib.createGunzip(zlibOptions));
++				body = Stream.pipeline(body, zlib.createGunzip(zlibOptions), error => { if (error) reject(error); });
+ 				response = new Response(body, response_options);
+ 				resolve(response);
+ 				return;
+@@ -1689,13 +1689,13 @@ function fetch(url, opts) {
+ 			if (codings == 'deflate' || codings == 'x-deflate') {
+ 				// handle the infamous raw deflate response from old servers
+ 				// a hack for old IIS and Apache servers
+-				const raw = res.pipe(new PassThrough$1());
++				const raw = Stream.pipeline(res, new PassThrough(), error => { if (error) reject(error); });
+ 				raw.once('data', function (chunk) {
+ 					// see http://stackoverflow.com/questions/37519828
+ 					if ((chunk[0] & 0x0F) === 0x08) {
+-						body = body.pipe(zlib.createInflate());
++						body = Stream.pipeline(body, zlib.createInflate(), error => { if (error) reject(error); });
+ 					} else {
+-						body = body.pipe(zlib.createInflateRaw());
++						body = Stream.pipeline(body, zlib.createInflateRaw(), error => { if (error) reject(error); });
+ 					}
+ 					response = new Response(body, response_options);
+ 					resolve(response);
+@@ -1712,7 +1712,7 @@ function fetch(url, opts) {
+ 
+ 			// for br
+ 			if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') {
+-				body = body.pipe(zlib.createBrotliDecompress());
++				body = Stream.pipeline(body, zlib.createBrotliDecompress(), error => { if (error) reject(error); });
+ 				response = new Response(body, response_options);
+ 				resolve(response);
+ 				return;

+ 13 - 0
.yarn/patches/passport-oauth2-npm-1.6.1.patch

@@ -0,0 +1,13 @@
+diff --git a/lib/utils.js b/lib/utils.js
+index 486f9e1..4584507 100644
+--- a/lib/utils.js
++++ b/lib/utils.js
+@@ -24,7 +24,7 @@ exports.originalURL = function(req, options) {
+   var trustProxy = options.proxy;
+   
+   var proto = (req.headers['x-forwarded-proto'] || '').toLowerCase()
+-    , tls = req.connection.encrypted || (trustProxy && 'https' == proto.split(/\s*,\s*/)[0])
++    , tls = (req.connection && req.connection.encrypted) || (trustProxy && 'https' == proto.split(/\s*,\s*/)[0])
+     , host = (trustProxy && req.headers['x-forwarded-host']) || req.headers.host
+     , protocol = tls ? 'https' : 'http'
+     , path = req.url || '';

+ 22 - 0
.yarn/patches/pdfjs-dist-npm-5.1.91.patch

@@ -0,0 +1,22 @@
+diff --git a/build/pdf.worker.mjs b/build/pdf.worker.mjs
+index 6c5c6f1..bb6b7d1 100644
+--- a/build/pdf.worker.mjs
++++ b/build/pdf.worker.mjs
+@@ -1830,7 +1830,7 @@ async function __wbg_init(module_or_path) {
+     }
+   }
+   if (typeof module_or_path === 'undefined') {
+-    module_or_path = new URL('qcms_bg.wasm', import.meta.url);
++    module_or_path = new URL(/* webpackIgnore: true */ 'qcms_bg.wasm', import.meta.url);
+   }
+   const imports = __wbg_get_imports();
+   if (typeof module_or_path === 'string' || typeof Request === 'function' && module_or_path instanceof Request || typeof URL === 'function' && module_or_path instanceof URL) {
+@@ -5358,7 +5358,7 @@ var OpenJPEG = (() => {
+       if (Module["locateFile"]) {
+         return locateFile("openjpeg.wasm");
+       }
+-      return new URL("openjpeg.wasm", import.meta.url).href;
++      return new URL(/* webpackIgnore: true */ "openjpeg.wasm", import.meta.url).href;
+     }
+     function getBinarySync(file) {
+       if (file == wasmBinaryFile && wasmBinary) {

+ 1583 - 0
.yarn/patches/referer-parser-npm-0.0.3.patch

@@ -0,0 +1,1583 @@
+diff --git a/package.json b/package.json
+--- a/package.json
++++ b/package.json
+@@ -1,6 +1,6 @@
+ {
+   "name": "referer-parser",
+-  "version": "0.0.3",
++  "version": "0.0.4",
+   "description": "library for extracting marketing attribution data (such as search terms) from referrer URLs",
+   "main": "index.js",
+   "scripts": {
+@@ -15,9 +15,9 @@
+     }
+   ],
+   "dependencies": {
+-    "js-yaml": "~2.1.0"
++    "js-yaml": "^4.1.0"
+   },
+   "devDependencies": {
+-    "mocha": "~1.12.0"
++    "mocha": "~10.2.0"
+   }
+ }
+diff --git a/index.js b/index.js
+--- a/index.js
++++ b/index.js
+@@ -123,11 +123,10 @@
+           ref_path, include_path
+       )
+     } catch (e) {
+-      console.error(e)
+       return null
+     }
+   } else return referer
+ };
+ 
+ // var r = new Referer("http://www.google.com/search?q=gateway+oracle+cards+denise+linn&hl=en&client=safari")
+-// console.log(r.uri)
+\ No newline at end of file
++// console.log(r.uri)
+diff --git a/data/referers.yml b/data/referers.yml
+--- a/data/referers.yml
++++ b/data/referers.yml
+@@ -1,9 +1,3 @@
+-#################################### DO NOT EDIT THIS FILE ####################################
+-#                                                                                             #  
+-#             This file will be overwritten the next time ./sync_yaml.sh is run!              #
+-#                                                                                             #
+-#################################### DO NOT EDIT THIS FILE ####################################
+-
+ # #######################################################################################################
+ #
+ # ALL SUPPORTED REFERERS
+@@ -14,6 +8,7 @@
+ # 2. Email providers
+ # 3. Social providers
+ # 4. Search providers
++# 5. Paid media
+ 
+ 
+ # #######################################################################################################
+@@ -35,7 +30,6 @@
+       - sites.google.com
+       - groups.google.com
+       - groups.google.co.uk
+-      - news.google.co.uk
+ 
+   Yahoo!:
+     domains:
+@@ -57,6 +51,15 @@
+       - omg.yahoo.com
+       - match.yahoo.net
+ 
++  Yandex Maps:
++    parameters:
++      - text
++    domains:
++      - maps.yandex.ru
++      - maps.yandex.ua
++      - maps.yandex.com
++      - maps.yandex.by
++      - n.maps.yandex.ru
+ 
+ # #######################################################################################################
+ #
+@@ -64,23 +67,167 @@
+ 
+ email:
+ 
++  126 Mail:
++    domains:
++      - mail.126.com
++
++  163 Mail:
++    domains:
++      - mail.163.com
++
++  2degrees:
++    domains:
++      - webmail.2degreesbroadband.co.nz
++
++  Adam Internet:
++    domains:
++      - webmail.adam.com.au
++
++  AOL Mail:
++    domains:
++      - mail.aol.com
++
++  Beeline:
++    domains:
++      - post.ru
++
++  Bigpond:
++    domains:
++      - webmail.bigpond.com
++      - webmail2.bigpond.com
++      - email.telstra.com
++      - basic.messaging.bigpond.com
++
++  Commander:
++    domains:
++      - webmail.commander.net.au
++
++  Daum Mail:
++    domains:
++      - mail2.daum.net
++      - mail.daum.net
++
++  Dodo:
++    domains:
++      - webmail.dodo.com.au
++
++  E1.ru:
++    domains:
++      - mail.e1.ru
++
++  Freenet:
++    domains:
++      - webmail.freenet.de
++
+   Gmail:
+     domains:
+       - mail.google.com
++      - inbox.google.com
++
++  iiNet:
++    domains:
++      - webmail.iinet.net.au
++      - mail.iinet.net.au
++
++  Inbox.com:
++    domains:
++      - inbox.com
++
++  iPrimus:
++    domains:
++      - webmail.iprimus.com.au
++
++  Mail.ru:
++    domains:
++      - e.mail.ru
++      - touch.mail.ru
++
++  Mastermail:
++    domains:
++      - mastermail.ru
++      - m.mastermail.ru
++
++  Mynet Mail:
++    domains:
++      - mail.mynet.com
++
++  Naver Mail:
++    domains:
++      - mail.naver.com
++
++  Netspace:
++    domains:
++      - webmail.netspace.net.au
++
++  Optus Zoo:
++    domains:
++      - webmail.optuszoo.com.au
++      - webmail.optusnet.com.au
++
++  Orange Webmail:
++    domains:
++      - orange.fr/webmail
+ 
+   Outlook.com:
+     domains:
+       - mail.live.com
++      - outlook.live.com
++
++  QIP:
++    domains:
++      - mail.qip.ru
++
++  QQ Mail:
++    domains:
++      - mail.qq.com
++      - exmail.qq.com
++
++  Rambler:
++    domains:
++      - mail.rambler.ru 
++
++  Seznam Mail:
++    domains:
++      - email.seznam.cz
++
++  Sibmail:
++    domains:
++      - sibmail.com
++
++  Ukr.net:
++    domains:
++      - mail.ukr.net
++
++  Virgin:
++    domains:
++      - webmail.virginbroadband.com.au
++
++  Vodafone:
++    domains:
++      - webmail.vodafone.co.nz
++
++  Westnet:
++    domains:
++      - webmail.westnet.com.au
++
++  Yandex:
++    domains:
++      - mail.yandex.ru
++      - mail.yandex.com
++      - mail.yandex.kz
++      - mail.yandex.ua
++      - mail.yandex.by
+ 
+   Yahoo! Mail:
+     domains:
+       - mail.yahoo.net
+       - mail.yahoo.com
+       - mail.yahoo.co.uk
++      - mail.yahoo.co.jp
+ 
+-  Orange Webmail:
++  Zoho:
+     domains:
+-      - orange.fr/webmail
++      - mail.zoho.com
+ 
+ # #######################################################################################################
+ #
+@@ -92,6 +239,9 @@
+     domains:
+       - facebook.com
+       - fb.me
++      - m.facebook.com
++      - l.facebook.com
++      - lm.facebook.com
+ 
+   Qzone:
+     domains:
+@@ -106,6 +256,20 @@
+       - twitter.com
+       - t.co
+ 
++  Instagram:
++    domains:
++      - instagram.com
++      - l.instagram.com
++
++  Youtube:
++    domains:
++      - youtube.com
++      - youtu.be
++
++  Vimeo:
++    domains:
++      - vimeo.com
++
+   Renren:
+     domains:
+       - renren.com
+@@ -117,6 +281,7 @@
+   LinkedIn:
+     domains:
+       - linkedin.com
++      - lnkd.in
+ 
+   Bebo:
+     domains:
+@@ -124,7 +289,9 @@
+ 
+   Vkontakte:
+     domains:
++      - m.vk.com
+       - vk.com
++      - away.vk.com
+       - vkontakte.ru
+ 
+   Tagged:
+@@ -133,7 +300,7 @@
+ 
+   Orkut:
+     domains:
+-      - orkut.com 
++      - orkut.com
+ 
+   Myspace:
+     domains:
+@@ -187,6 +354,7 @@
+   Odnoklassniki:
+     domains:
+       - odnoklassniki.ru
++      - ok.ru
+ 
+   Viadeo:
+     domains:
+@@ -194,7 +362,7 @@
+ 
+   Flickr:
+     domains:
+-      - flickr.com 
++      - flickr.com
+ 
+   WeeWorld:
+     domains:
+@@ -226,7 +394,7 @@
+ 
+   Skyrock:
+     domains:
+-      - skyrock.com 
++      - skyrock.com
+ 
+   BlackPlanet:
+     domains:
+@@ -263,6 +431,8 @@
+   Pinterest:
+     domains:
+       - pinterest.com
++      - pinterest.ca
++      - pinterest.com.au
+ 
+   Plaxo:
+     domains:
+@@ -278,7 +448,7 @@
+ 
+   XING:
+     domains:
+-      - xing.com 
++      - xing.com
+ 
+   Taringa!:
+     domains:
+@@ -287,6 +457,7 @@
+   Tumblr:
+     domains:
+       - tumblr.com
++      - t.umblr.com
+ 
+   Nasza-klasa.pl:
+     domains:
+@@ -310,7 +481,7 @@
+ 
+   Buzznet:
+     domains:
+-      - wayn.com
++      - buzznet.com
+ 
+   Multiply:
+     domains:
+@@ -349,6 +520,67 @@
+       - weibo.com
+       - t.cn
+ 
++  Delicious:
++    domains:
++      - delicious.com
++
++  Pocket:
++    domains:
++      - getpocket.com
++
++  ITU Sozluk:
++    domains:
++      - itusozluk.com
++
++  Instela:
++    domains:
++      - instela.com
++
++  Eksi Sozluk:
++    domains:
++      - Sozluk.com
++      - sourtimes.org
++
++  Uludag Sozluk:
++    domains:
++      - uludagsozluk.com
++      - ulusozluk.com
++
++  Inci Sozluk:
++    domains:
++      - inci.sozlukspot.com
++      - incisozluk.com
++      - incisozluk.cc
++
++  Hocam.com:
++    domains:
++      - hocam.com
++
++  Donanimhaber:
++    domains:
++      - donanimhaber.com
++
++  Disqus:
++    domains:
++      - redirect.disqus.com
++      - disq.us
++      - disqus.com
++
++  Quora:
++    domains:
++      - quora.com
++
++  Skype:
++    domains:
++      - web.skype.com
++
++  WhatsApp:
++    domains:
++      - web.whatsapp.com
++
++  Whirlpool:
++    domains:
++      - forums.whirlpool.net.au
+ 
+ # #######################################################################################################
+ #
+@@ -357,24 +589,44 @@
+ search:
+ 
+   1.cz:
+-    parameters: 
++    parameters:
+       - q
+     domains:
+       - 1.cz
+ 
+   # 123people TODO
+ 
++  1&1:
++    parameters:
++      - q
++    domains:
++      - search.1and1.com
++
+   1und1:
+-    parameters: 
++    parameters:
+       - su
+     domains:
+       - search.1und1.de
+ 
++  2gis:
++    domains:
++      - 2gis.ru
++      - www.2gis.ru
++      - link.2gis.ru
++      - www.link.2gis.ru
++
++  360.cn:
++    parameters:
++      - q
++    domains:
++      - so.360.cn
++      - www.so.com
++
+   Abacho:
+-    parameters: 
++    parameters:
+       - q
+     domains:
+-      - www.abacho.de 
++      - www.abacho.de
+       - www.abacho.com
+       - www.abacho.co.uk
+       - www.se.abacho.com
+@@ -386,45 +638,45 @@
+       - www.abacho.it
+ 
+   ABCsøk:
+-    parameters: 
++    parameters:
+       - q
+     domains:
+       - abcsolk.no
+       - verden.abcsok.no
+ 
+   Acoon:
+-    parameters: 
++    parameters:
+       - begriff
+     domains:
+       - www.acoon.de
+ 
+   Alexa:
+-    parameters: 
++    parameters:
+       - q
+     domains:
+       - alexa.com
+       - search.toolbars.alexa.com
+ 
+   Alice Adsl:
+-    parameters: 
++    parameters:
+       - q
+     domains:
+       - rechercher.aliceadsl.fr
+ 
+   AllTheWeb:
+-    parameters: 
++    parameters:
+       - q
+-    domains: 
++    domains:
+       - www.alltheweb.com
+ 
+   all.by:
+-    parameters: 
++    parameters:
+       - query
+     domains:
+       - all.by
+ 
+   Altavista:
+-    parameters: 
++    parameters:
+       - q
+     domains:
+       - www.altavista.com
+@@ -435,18 +687,28 @@
+       - be-nl.altavista.com
+       - be-fr.altavista.com
+ 
++  Amazon:
++    parameters:
++      - keywords
++    domains:
++      - amazon.com
++      - www.amazon.com
++
+   AOL:
+-    parameters: 
++    parameters:
+       - q
++      - query
+     domains:
+       - search.aol.com
+       - search.aol.it
+       - aolsearch.aol.com
++      - aolsearch.com
+       - www.aolrecherche.aol.fr
+       - www.aolrecherches.aol.fr
+       - www.aolimages.aol.fr
+       - aim.search.aol.com
+       - www.recherche.aol.fr
++      - recherche.aol.fr
+       - find.web.aol.com
+       - recherche.aol.ca
+       - aolsearch.aol.co.uk
+@@ -465,13 +727,13 @@
+       - search-intl.netscape.com
+ 
+   Apollo Latvia:
+-    parameters: 
++    parameters:
+       - q
+-    domains: 
++    domains:
+       - apollo.lv/portal/search/
+ 
+   APOLL07:
+-    parameters: 
++    parameters:
+       - query
+     domains:
+       - apollo7.de
+@@ -484,35 +746,36 @@
+       - www.apontador.com.br
+ 
+   Aport:
+-    parameters: 
++    parameters:
+       - r
+     domains:
+       - sm.aport.ru
+ 
+   arama:
+-    parameters: 
++    parameters:
+       - q
+     domains:
+       - arama.com
+ 
+   Arcor:
+-    parameters: 
++    parameters:
+       - Keywords
+     domains:
+       - www.arcor.de
+ 
+   Arianna:
+-    parameters: 
++    parameters:
+       - query
+     domains:
+       - arianna.libero.it
+       - www.arianna.com
+ 
+   Ask:
+-    parameters: 
++    parameters:
+       - q
+     domains:
+       - ask.com
++      - www.ask.com
+       - web.ask.com
+       - int.ask.com
+       - mws.ask.com
+@@ -528,28 +791,34 @@
+       - www.search-results.com
+       - int.search-results.com
+ 
++  Ask Toolbar:
++    parameters:
++      - searchfor
++    domains:
++      - search.tb.ask.com
++
+   Atlas:
+-    parameters: 
++    parameters:
+       - q
+     domains:
+       - searchatlas.centrum.cz
+ 
+   Austronaut:
+-    parameters: 
++    parameters:
+       - q
+     domains:
+       - www2.austronaut.at
+       - www1.astronaut.at
+ 
+   Babylon:
+-    parameters: 
++    parameters:
+       - q
+-    domains: 
++    domains:
+      - search.babylon.com
+      - searchassist.babylon.com
+ 
+   Baidu:
+-    parameters: 
++    parameters:
+       - wd
+       - word
+       - kw
+@@ -561,9 +830,10 @@
+       - tieba.baidu.com
+       - news.baidu.com
+       - web.gougou.com
++      - m.baidu.com
+ 
+   Biglobe:
+-    parameters: 
++    parameters:
+       - q
+     domains:
+       - cgi.search.biglobe.ne.jp
+@@ -612,6 +882,12 @@
+     domains:
+       - search.bluewin.ch
+ 
++  British Telecommunications:
++    parameters:
++      - p
++    domains:
++      - search.bt.com
++
+   canoe.ca:
+     parameters:
+       - q
+@@ -625,6 +901,12 @@
+       - serach.centrum.cz
+       - morfeo.centrum.cz
+ 
++  Certified-Toolbar:
++    parameters:
++      - q
++    domains:
++      - search.certified-toolbar.com
++
+   Charter:
+     parameters:
+       - q
+@@ -674,6 +956,12 @@
+       - daemon-search.com
+       - my.daemon-search.com
+ 
++  Dalesearch:
++    parameters:
++      - q
++    domains:
++      - www.dalesearch.com
++
+   DasOertliche:
+     parameters:
+       - kw
+@@ -717,7 +1005,13 @@
+       - dmoz.org
+       - editors.dmoz.org
+ 
+-  DuckDuckGoL:
++  Dodo:
++    parameters:
++      - q
++    domains:
++      - google.dodo.com.au
++
++  DuckDuckGo:
+     parameters:
+       - q
+     domains:
+@@ -799,6 +1093,18 @@
+     domains:
+       - recherche.francite.com
+ 
++  Finderoo:
++    parameters:
++      - q
++    domains:
++      - www.finderoo.com
++
++  Findwide:
++    parameters:
++      - k
++    domains:
++      - search.findwide.com
++
+   Fireball:
+     parameters:
+       - q
+@@ -852,6 +1158,12 @@
+     domains:
+       - suche.freenet.de
+ 
++  Freshweather:
++    parameters:
++      - q
++    domains:
++      - www.fresh-weather.com
++
+   FriendFeed:
+     parameters:
+       - q
+@@ -870,6 +1182,12 @@
+     domains:
+       - geona.net
+ 
++  Genieo:
++    parameters:
++      - q
++    domains:
++      - search.genieo.com
++
+   Gigablast:
+     parameters:
+       - q
+@@ -877,6 +1195,13 @@
+       - www.gigablast.com
+       - dir.gigablast.com
+ 
++  Globososo:
++    parameters:
++      - q
++    domains:
++      - searches.globososo.com
++      - search.globososo.com
++
+   GMX:
+     parameters:
+       - su
+@@ -1003,7 +1328,6 @@
+       - www.google.jo
+       - www.google.co.jp
+       - www.google.co.ke
+-      - www.google.com.kh
+       - www.google.ki
+       - www.google.kg
+       - www.google.co.kr
+@@ -1084,6 +1408,7 @@
+       - www.google.tm
+       - www.google.to
+       - www.google.com.tn
++      - www.google.tn
+       - www.google.com.tr
+       - www.google.tt
+       - www.google.com.tw
+@@ -1200,7 +1525,6 @@
+       - google.jo
+       - google.co.jp
+       - google.co.ke
+-      - google.com.kh
+       - google.ki
+       - google.kg
+       - google.co.kr
+@@ -1302,6 +1626,7 @@
+       - google.co.za
+       - google.co.zm
+       - google.co.zw
++      - google.tn
+       # powered by Google
+       - search.avg.com
+       - isearch.avg.com
+@@ -1414,7 +1739,6 @@
+       - blogsearch.google.com.hk
+       - blogsearch.google.com.jm
+       - blogsearch.google.com.kh
+-      - blogsearch.google.com.kh
+       - blogsearch.google.com.kw
+       - blogsearch.google.com.lb
+       - blogsearch.google.com.lc
+@@ -1616,7 +1940,6 @@
+       - google.com.hk/imgres
+       - google.com.jm/imgres
+       - google.com.kh/imgres
+-      - google.com.kh/imgres
+       - google.com.kw/imgres
+       - google.com.lb/imgres
+       - google.com.lc/imgres
+@@ -1813,7 +2136,6 @@
+       - images.google.com.hk
+       - images.google.com.jm
+       - images.google.com.kh
+-      - images.google.com.kh
+       - images.google.com.kw
+       - images.google.com.lb
+       - images.google.com.lc
+@@ -1933,7 +2255,6 @@
+       - images.google.us
+       - images.google.vg
+       - images.google.vu
+-      - images.google.ws
+ 
+   Google News:
+     parameters:
+@@ -2015,7 +2336,6 @@
+       - news.google.com.hk
+       - news.google.com.jm
+       - news.google.com.kh
+-      - news.google.com.kh
+       - news.google.com.kw
+       - news.google.com.lb
+       - news.google.com.lc
+@@ -2217,7 +2537,6 @@
+       - google.com.hk/products
+       - google.com.jm/products
+       - google.com.kh/products
+-      - google.com.kh/products
+       - google.com.kw/products
+       - google.com.lb/products
+       - google.com.lc/products
+@@ -2414,7 +2733,6 @@
+       - www.google.com.hk/products
+       - www.google.com.jm/products
+       - www.google.com.kh/products
+-      - www.google.com.kh/products
+       - www.google.com.kw/products
+       - www.google.com.lb/products
+       - www.google.com.lc/products
+@@ -2561,7 +2879,7 @@
+       - www.highbeam.com
+ 
+   Hit-Parade:
+-    parameters: 
++    parameters:
+       - p7
+     domains:
+       - req.-hit-parade.com
+@@ -2605,6 +2923,21 @@
+     domains:
+       - www.ilse.nl
+ 
++  Inbox.com:
++    parameters:
++      - q
++    domains:
++      - inbox.com/search/
++
++  Indeed:
++    domains:
++      - de.indeed.com
++      - at.indeed.com
++      - fr.indeed.com
++      - it.indeed.com
++      - ch.indeed.com
++      - au.indeed.com
++
+   InfoSpace:
+     parameters:
+       - q
+@@ -2624,6 +2957,13 @@
+       - search.searchcompletion.com
+       - clusty.com
+ 
++  Flyingbird:
++    parameters:
++      - q
++    domains:
++      - inspsearch.com
++      - viview.inspsearch.com
++
+   Interia:
+     parameters:
+       - q
+@@ -2636,6 +2976,12 @@
+     domains:
+       - start.iplay.com
+ 
++  I.ua:
++    parameters:
++      - q
++    domains:
++      - search.i.ua
++
+   IXquick:
+     parameters:
+       - query
+@@ -2685,6 +3031,12 @@
+     domains:
+       - www.kvasir.no
+ 
++  kununu:
++    parameters:
++      - q
++    domains:
++      - kununu.com
++
+   Latne:
+     parameters:
+       - q
+@@ -2698,6 +3050,18 @@
+       - www.toile.com
+       - web.toile.com
+ 
++  Lilo:
++    parameters:
++      - q
++    domains:
++      - search.lilo.org
++
++  Liveinternet:
++    parameters:
++      - q
++    domains:
++      - liveinternet.ru
++
+   Looksmart:
+     parameters:
+       - key
+@@ -2728,6 +3092,8 @@
+     parameters:
+       - q
+     domains:
++      - mail.ru
++      - m.mail.ru
+       - go.mail.ru
+ 
+   Mamma:
+@@ -2737,6 +3103,18 @@
+       - www.mamma.com
+       - mamma75.mamma.com
+ 
++  Marktplaats:
++    parameters:
++      - query
++    domains:
++      - www.marktplaats.nl
++
++  Maxwebsearch:
++    parameters:
++      - query
++    domains:
++      - maxwebsearch.com
++
+   Meta:
+     parameters:
+       - q
+@@ -2771,12 +3149,27 @@
+       - www.meinestadt.de
+ 
+   Mister Wong:
+-    parameters: 
++    parameters:
+       - Keywords
+     domains:
+       - www.mister-wong.com
+       - www.mister-wong.de
+ 
++  Monster:
++    parameters:
++      - q
++    domains:
++      - www.monster.be
++      - www.monster.cz
++      - www.monster.de
++      - www.monster.fi
++      - www.monster.fr
++      - www.monster.ie
++      - www.monster.it
++      - www.monster.lu
++      - www.monster.ch
++      - www.monster.co.uk
++
+   Monstercrawler:
+     parameters:
+       - qry
+@@ -2802,6 +3195,7 @@
+       - searchfor
+       - searchFor
+     domains:
++      - mysearch.com
+       - www.mysearch.com
+       - ms114.mysearch.com
+       - ms146.mysearch.com
+@@ -2828,6 +3222,13 @@
+     domains:
+       - search.naver.com
+ 
++  Naver Images:
++    parameters:
++      - query
++    domains:
++      - image.search.naver.com
++      - imagesearch.naver.com
++
+   Needtofind:
+     parameters:
+       - searchfor
+@@ -2873,9 +3274,11 @@
+   Orange:
+     parameters:
+       - q
++      - kw
+     domains:
+       - busca.orange.es
+       - search.orange.co.uk
++      - lemoteur.orange.fr
+ 
+   Paperball:
+     parameters:
+@@ -2905,7 +3308,7 @@
+     parameters:
+       - q
+     domains:
+-      - www.plazoo.com
++      - poisk.ru
+ 
+   PriceRunner:
+     parameters:
+@@ -2914,7 +3317,7 @@
+       - www.pricerunner.co.uk
+ 
+   qip:
+-    parameters: 
++    parameters:
+       - query
+     domains:
+       - search.qip.ru
+@@ -2928,6 +3331,13 @@
+       - www.qualigo.de
+       - www.qualigo.nl
+ 
++  Qwant:
++    parameters:
++      - q
++    domains:
++      - www.qwant.com
++      - lite.qwant.com
++
+   Rakuten:
+     parameters:
+       - qt
+@@ -2935,7 +3345,7 @@
+       - websearch.rakuten.co.jp
+ 
+   Rambler:
+-    parameters: 
++    parameters:
+      - query
+      - words
+     domains:
+@@ -2943,8 +3353,7 @@
+ 
+   RPMFind:
+     parameters:
+-      - rpmfind.net
+-      - fr2.rpmfind.net
++      - query
+     domains:
+       - rpmfind.net
+       - fr2.rpmfind.net
+@@ -2963,6 +3372,12 @@
+ 
+   # Add Scour.com
+ 
++  Search This:
++    parameters:
++      - q
++    domains:
++      - www.searchthis.com
++
+   Search.com:
+     parameters:
+       - q
+@@ -3013,11 +3428,20 @@
+     domains:
+       - www.skynet.be
+ 
++  The Smart Search:
++    parameters:
++      - q
++    domains:
++      - thesmartsearch.net
++      - www.thesmartsearch.net
++
+   Sogou:
+     parameters:
+       - query
++      - w
+     domains:
+       - www.sougou.com
++      - www.soso.com
+ 
+   Softonic:
+     parameters:
+@@ -3025,11 +3449,30 @@
+     domains:
+       - search.softonic.com
+ 
+-  soso.com:
++  SoSoDesk:
+     parameters:
+-      - w
++      - q
+     domains:
+-      - www.soso.com
++      - sosodesktop.com
++      - search.sosodesktop.com
++
++  Shenma:
++    parameters:
++      - q
++    domains:
++      - so.m.sm.cn
++      - yz.m.sm.cn
++      - m.sm.cn
++      - quark.sm.cn
++      - m.sp.sm.cn
++      - m.yz2.sm.cn
++      - m.yz.sm.cn
++
++  Snapdo:
++    parameters:
++      - q
++    domains:
++      - search.snapdo.com
+ 
+   Startpagina:
+     parameters:
+@@ -3043,6 +3486,16 @@
+     domains:
+       - www.startsiden.no
+ 
++  StepStone:
++    domains:
++      - www.stepstone.de
++      - www.stepstone.at
++      - www.stepstone.be
++      - www.stepstone.fr
++      - www.stepstone.nl
++      - www.stepstone.dk
++      - www.stepstone.se
++
+   suche.info:
+     parameters:
+       - q
+@@ -3068,11 +3521,17 @@
+       - www.talktalk.co.uk
+ 
+   Technorati:
+-    parameters: 
++    parameters:
+       - q
+     domains:
+       - technorati.com
+ 
++  Telstra:
++    parameters:
++      - find
++    domains:
++      - search.media.telstra.com.au
++
+   Teoma:
+     parameters:
+       - q
+@@ -3135,12 +3594,24 @@
+     domains:
+       - www.trusted--search.com
+ 
++  Tut.by:
++    parameters:
++      - query
++    domains:
++      - search.tut.by
++
+   Twingly:
+     parameters:
+       - q
+     domains:
+       - www.twingly.com
+ 
++  UKR.net:
++    parameters:
++      - q
++    domains:
++      - search.ukr.net
++
+   uol.com.br:
+     parameters:
+       - q
+@@ -3179,6 +3650,7 @@
+   Voila:
+     parameters:
+       - rdata
++      - kw
+     domains:
+       - search.ke.voila.fr
+       - www.lemoteur.fr
+@@ -3199,7 +3671,7 @@
+       - www.walhello.nl
+ 
+   Web.de:
+-    parameters: 
++    parameters:
+       - su
+     domains:
+       - suche.web.de
+@@ -3266,6 +3738,8 @@
+       - au.yahoo.com
+       - br.search.yahoo.com
+       - br.yahoo.com
++      - ca.search.yahoo.com
++      - ca.yahoo.com
+       - cade.searchde.yahoo.com
+       - cade.yahoo.com
+       - chinese.searchinese.yahoo.com
+@@ -3279,13 +3753,15 @@
+       - es.search.yahoo.com
+       - es.yahoo.com
+       - espanol.searchpanol.yahoo.com
+-      - espanol.searchpanol.yahoo.com
+-      - espanol.yahoo.com
+       - espanol.yahoo.com
+       - fr.search.yahoo.com
+       - fr.yahoo.com
++      - hk.search.yahoo.com
++      - hk.yahoo.com
+       - ie.search.yahoo.com
+       - ie.yahoo.com
++      - in.search.yahoo.com
++      - in.yahoo.com
+       - it.search.yahoo.com
+       - it.yahoo.com
+       - kr.search.yahoo.com
+@@ -3299,17 +3775,18 @@
+       - one.cn.yahoo.com
+       - one.searchn.yahoo.com
+       - qc.search.yahoo.com
+-      - qc.search.yahoo.com
+-      - qc.search.yahoo.com
+-      - qc.yahoo.com
+       - qc.yahoo.com
+-      - se.search.yahoo.com
++      - ru.search.yahoo.com
++      - ru.yahoo.com
+       - se.search.yahoo.com
+       - se.yahoo.com
+       - search.searcharch.yahoo.com
+-      - search.yahoo.com
++      - tw.search.yahoo.com
++      - tw.yahoo.com
+       - uk.search.yahoo.com
+       - uk.yahoo.com
++      - us.search.yahoo.com
++      - us.yahoo.com
+       - www.yahoo.co.jp
+       - search.yahoo.co.jp
+       # powered by Yahoo
+@@ -3338,9 +3815,15 @@
+       - yandex.ru
+       - yandex.ua
+       - yandex.com
++      - yandex.by
+       - www.yandex.ru
+       - www.yandex.ua
+       - www.yandex.com
++      - www.yandex.by
++      - clck.yandex.ru
++      - clck.yandex.ua
++      - clck.yandex.com
++      - clck.yandex.by
+ 
+   Yandex Images:
+     parameters:
+@@ -3349,11 +3832,12 @@
+       - images.yandex.ru
+       - images.yandex.ua
+       - images.yandex.com
++      - images.yandex.by
+ 
+   Yasni:
+     parameters:
+       - query
+-    domains: 
++    domains:
+       - www.yasni.de
+       - www.yasni.com
+       - www.yasni.co.uk
+@@ -3366,7 +3850,7 @@
+     domains:
+       - www.yatedo.com
+       - www.yatedo.fr
+-    
++
+   # Add Yellowmap:
+ 
+   Yippy:
+@@ -3415,3 +3899,227 @@
+       - q
+     domains:
+       - zoohoo.cz
++
++
++
++# #######################################################################################################
++#
++# PAID MEDIA
++
++paid:
++
++  Acuity Ads:
++    domains:
++      - acuityplatform.com
++
++  Adform:
++    domains:
++      - adform.net
++
++  ADFOX:
++    domains:
++      - adfox.ru
++      - www.adfox.ru
++      - ads.adfox.ru
++      - www.ads.adfox.ru
++
++  Adition:
++    domains:
++      - adition.com
++
++  AdNET:
++    domains:
++      - adnet.de
++
++  AdRoll:
++    domains:
++      - adroll.com
++
++  AdSpirit:
++    domains:
++      - adspirit.de
++      - rtbcity.com
++      - plusperformance.com
++
++  AppNexus:
++    domains:
++      - ib.adnxs.com
++      - adnxs.com
++      - 247realmedia.com
++
++  AudienceScience:
++    domains:
++      - wunderloop.net
++
++  BidSwitch:
++    domains:
++      - bidswitch.net
++
++  Casale Media:
++    domains:
++      - casalemedia.com
++
++  Criteo:
++    domains:
++      - cas.jp.as.criteo.com
++      - cas.criteo.com
++
++  Doubleclick:
++    domains:
++      - ad.doubleclick.net
++      - ad-apac.doubleclick.net
++      - s0.2mdn.net
++      - s1.2mdn.net
++      - dp.g.doubleclick.net
++      - pubads.g.doubleclick.net
++
++  Eyeota:
++    domains:
++      - eyeota.net
++
++  Flashtalking:
++    domains:
++      - flashtalking.com
++      - servedby.flashtalking.com
++
++  Fluct:
++    domains:
++      - adingo.jp
++
++  Google:
++    domains:
++      - www.googleadservices.com
++      - partner.googleadservices.com
++      - googleads.g.doubleclick.net
++      - tpc.googlesyndication.com
++      - googleadservices.com
++      - imasdk.googleapis.com
++
++  LifeStreet:
++    domains:
++      - lfstmedia.com
++
++  LowerMyBills:
++    parameters:
++      - leadid
++    domains:
++      - lowermybills.com
++
++  Jivox:
++    domains:
++      - jivox.com
++
++  MicroAd:
++    domains:
++      - microad.jp
++
++  Mixpo:
++    domains:
++      - mixpo.com
++
++  Mozo:
++    domains:
++      - mozo.com.au
++      - a.mozo.com.au
++
++  Neustar AdAdvisor:
++    domains:
++      - adadvisor.net
++
++  ONE by AOL:
++    domains:
++      - nexage.com
++
++  OpenX:
++    domains:
++      - us-ads.openx.net
++      - openx.net
++      - servedbyopenx.com
++      - openxenterprise.com
++
++  Outbrain:
++    domains:
++      - paid.outbrain.com
++
++  Plista:
++    domains:
++      - farm.plista.com
++
++  Price.ru:
++    domains:
++      - price.ru
++      - v.price.ru
++
++  PubMatic:
++    domains:
++      - sshowads.pubmatic.com
++
++  Rubicon Project:
++    domains:
++      - optimized-by.rubiconproject.com
++
++  Sizmek:
++    domains:
++      - bs.serving-sys.com
++
++  Sociomantic Labs:
++    domains:
++      - sociomantic.com
++
++  Sonobi:
++    domains:
++      - sonobi.com
++
++  Sovrn:
++    domains:
++      - lijit.com
++
++  SteelHouse:
++    domains:
++      - steelhousemedia.com
++
++  StickyADS.tv:
++    domains:
++      - stickyadstv.com
++      - sfx.stickyadstv.com
++
++  Taboola:
++    domains:
++      - trc.taboola.com
++      - api.taboola.com
++      - taboola.com
++
++  Torg.Mail.ru:
++    domains:
++      - torg.mail.ru
++
++  Tribal Fusion:
++    domains:
++      - cdnx.tribalfusion.com
++
++  White Pages:
++    domains:
++      - www.whitepages.com.au
++      - mobile.whitepages.com.au
++
++  Yandex.Direct:
++    domains:
++      - an.yandex.ru
++      - yabs.yandex.ru
++      - yabs.yandex.ua
++      - yabs.yandex.com
++      - yabs.yandex.by
++
++  Yandex.Market:
++    domains:
++      - market.yandex.ru
++      - m.market.yandex.ru
++
++  Yieldmo:
++    domains:
++      - yieldmo.com
++
++  ZEDO:
++    domains:
++      - zedo.com
++      - z1.zedo.com

+ 30 - 0
.yarn/patches/retry-request-npm-7.0.2-a41087680c.patch

@@ -0,0 +1,30 @@
+diff --git a/index.js b/index.js
+index 2fae107d03b30aff9320d135ec79c049c51f298a..32ec707ddbf8937e3e130c3deac1060c308bf439 100644
+--- a/index.js
++++ b/index.js
+@@ -1,6 +1,6 @@
+ 'use strict';
+ 
+-const {PassThrough} = require('stream');
++const {PassThrough, pipeline} = require('stream');
+ const extend = require('extend');
+ 
+ let debug = () => {};
+@@ -185,7 +185,7 @@ function retryRequest(requestOpts, opts, callback) {
+         .on('complete', (...params) => handleFinish(params))
+         .on('finish', (...params) => handleFinish(params));
+ 
+-      requestStream.pipe(delayStream);
++      pipeline(requestStream, delayStream, () => {});
+     } else {
+       activeRequest = opts.request(requestOpts, onResponse);
+     }
+@@ -251,7 +251,7 @@ function retryRequest(requestOpts, opts, callback) {
+     // No more attempts need to be made, just continue on.
+     if (streamMode) {
+       retryStream.emit('response', response);
+-      delayStream.pipe(retryStream);
++      pipeline(delayStream, retryStream, () => {});
+       requestStream.on('error', err => {
+         retryStream.destroy(err);
+       });

+ 30 - 0
.yarn/patches/retry-request-npm-8.0.2-448ad084c8.patch

@@ -0,0 +1,30 @@
+diff --git a/index.js b/index.js
+index 298a351097d70a7fb005b6961f4d58247e391d8f..6a809ace0349d40cb2b6732ad66fd8ad208698ca 100644
+--- a/index.js
++++ b/index.js
+@@ -1,6 +1,6 @@
+ 'use strict';
+ 
+-const {PassThrough} = require('stream');
++const {PassThrough, pipeline} = require('stream');
+ const extend = require('extend');
+ 
+ let debug = () => {};
+@@ -185,7 +185,7 @@ function retryRequest(requestOpts, opts, callback) {
+         .on('complete', (...params) => handleFinish(params))
+         .on('finish', (...params) => handleFinish(params));
+ 
+-      requestStream.pipe(delayStream);
++      pipeline(requestStream, delayStream, () => {});
+     } else {
+       activeRequest = opts.request(requestOpts, onResponse);
+     }
+@@ -251,7 +251,7 @@ function retryRequest(requestOpts, opts, callback) {
+     // No more attempts need to be made, just continue on.
+     if (streamMode) {
+       retryStream.emit('response', response);
+-      delayStream.pipe(retryStream);
++      pipeline(delayStream, retryStream, () => {});
+       requestStream.on('error', err => {
+         retryStream.destroy(err);
+       });

+ 57 - 0
.yarn/patches/sandboxed-module-npm-2.0.4-f8b45aacc9.patch

@@ -0,0 +1,57 @@
+diff --git a/lib/sandboxed_module.js b/lib/sandboxed_module.js
+index 1cd6743..4718b97 100644
+--- a/lib/sandboxed_module.js
++++ b/lib/sandboxed_module.js
+@@ -4,7 +4,7 @@ var Module = require('module');
+ var fs = require('fs');
+ var vm = require('vm');
+ var path = require('path');
+-var builtinModules = require('./builtin_modules.json');
++var builtinModules = Module.builtinModules || require('./builtin_modules.json');
+ var parent = module.parent;
+ var globalOptions = {};
+ var registeredBuiltInSourceTransformers = ['coffee'];
+@@ -157,12 +157,20 @@ SandboxedModule.prototype._createRecursiveRequireProxy = function() {
+   var cache = Object.create(null);
+   var required = this._getRequires();
+   for (var key in required) {
+-    var injectedFilename = requireLike(this.filename).resolve(key);
+-    cache[injectedFilename] = required[key];
++    // Under Yarn PnP, resolution from a transitive dependency's context may fail
++    // for packages not declared in that dependency's package.json. Silently skip
++    // cache pre-population on failure; the mock will still be injected via the
++    // inject map in requireInterceptor or resolved via RecursiveRequireProxy fallback.
++    try {
++      var injectedFilename = requireLike(this.filename).resolve(key);
++      cache[injectedFilename] = required[key];
++    } catch (e) {}
+   }
+   cache[this.filename] = this.exports;
+   var globals = this.globals;
+ 
++  // Store the top-level module's filename for PnP fallback resolution
++  var topLevelFilename = this.filename;
+   var options;
+   if(!this._options.sourceTransformersSingleOnly && this._options.sourceTransformers){
+     options = {
+@@ -208,8 +216,18 @@ SandboxedModule.prototype._createRecursiveRequireProxy = function() {
+       if (request in cache) return cache[request];
+       return require(request);
+     }
+-    // cached modules
+-    var requestedFilename = requireLike(this.filename).resolve(request);
++    // Resolve the requested module filename.
++    // Under Yarn PnP, packages can only resolve their declared dependencies.
++    // When sandboxed-module loads a transitive dependency, the resolution context
++    // may not have access to all needed packages. Fall back to resolving from
++    // the top-level module's context (the module under test).
++    var requestedFilename;
++    try {
++      requestedFilename = requireLike(this.filename).resolve(request);
++    } catch (e) {
++      if (this.filename === topLevelFilename) throw e;
++      requestedFilename = requireLike(topLevelFilename).resolve(request);
++    }
+     if (requestedFilename in cache) return cache[requestedFilename];
+     var sandboxedModule = createInnerSandboxedModule(requestedFilename)
+     return sandboxedModule.exports;

+ 57 - 0
.yarn/patches/send-npm-0.19.0.patch

@@ -0,0 +1,57 @@
+diff --git a/index.js b/index.js
+index 768f8ca..a882f4d 100644
+--- a/index.js
++++ b/index.js
+@@ -788,29 +788,29 @@ SendStream.prototype.stream = function stream (path, options) {
+   // pipe
+   var stream = fs.createReadStream(path, options)
+   this.emit('stream', stream)
+-  stream.pipe(res)
+-
+-  // cleanup
+-  function cleanup () {
+-    destroy(stream, true)
+-  }
+-
+-  // response finished, cleanup
+-  onFinished(res, cleanup)
+-
+-  // error handling
+-  stream.on('error', function onerror (err) {
+-    // clean up stream early
+-    cleanup()
+-
+-    // error
+-    self.onStatError(err)
+-  })
+-
+-  // end
+-  stream.on('end', function onend () {
+-    self.emit('end')
+-  })
++  Stream.pipeline(stream, res, err => { if (err) { self.onStatError(err) } else { self.emit('end') } })
++
++  // // cleanup
++  // function cleanup () {
++  //   destroy(stream, true)
++  // }
++  //
++  // // response finished, cleanup
++  // onFinished(res, cleanup)
++  //
++  // // error handling
++  // stream.on('error', function onerror (err) {
++  //   // clean up stream early
++  //   cleanup()
++  //
++  //   // error
++  //   self.onStatError(err)
++  // })
++  //
++  // // end
++  // stream.on('end', function onend () {
++  //   self.emit('end')
++  // })
+ }
+ 
+ /**

+ 57 - 0
.yarn/patches/teeny-request-npm-10.1.0.patch

@@ -0,0 +1,57 @@
+diff --git a/build/src/index.js b/build/src/index.js
+index a101736..a87f6b9 100644
+--- a/build/src/index.js
++++ b/build/src/index.js
+@@ -130,6 +130,9 @@ function createMultipartStream(boundary, multipart) {
+         }
+         else {
+             part.body.pipe(stream, { end: false });
++            part.body.on('error', (err) => {
++                stream.destroy(err);
++            });
+             part.body.on('end', () => {
+                 stream.write('\r\n');
+                 stream.write(finale);
+@@ -184,25 +187,25 @@ function teenyRequest(reqOpts, callback) {
+         // Stream mode
+         const requestStream = streamEvents(new stream_1.PassThrough());
+         // eslint-disable-next-line @typescript-eslint/no-explicit-any
+-        let responseStream;
+-        requestStream.once('reading', () => {
+-            if (responseStream) {
+-                (0, stream_1.pipeline)(responseStream, requestStream, () => { });
+-            }
+-            else {
+-                requestStream.once('response', () => {
+-                    (0, stream_1.pipeline)(responseStream, requestStream, () => { });
+-                });
+-            }
+-        });
++        // let responseStream;
++        // requestStream.once('reading', () => {
++        //     if (responseStream) {
++        //         (0, stream_1.pipeline)(responseStream, requestStream, () => { });
++        //     }
++        //     else {
++        //         requestStream.once('response', () => {
++        //             (0, stream_1.pipeline)(responseStream, requestStream, () => { });
++        //         });
++        //     }
++        // });
+         options.compress = false;
+         teenyRequest.stats.requestStarting();
+-        fetch(uri, options).then(res => {
++        (0, node_fetch_1.default)(uri, options).then(res => {
+-            teenyRequest.stats.requestFinished();
+-            responseStream = res.body;
+-            responseStream.on('error', (err) => {
+-                requestStream.emit('error', err);
+-            });
++            teenyRequest.stats.requestFinished(); (0, stream_1.pipeline)(res.body, requestStream, () => {});
++            // responseStream = res.body;
++            // responseStream.on('error', (err) => {
++            //     requestStream.emit('error', err);
++            // });
+             const response = fetchToRequestResponse(options, res);
+             requestStream.emit('response', response);
+         }, err => {

+ 58 - 0
.yarn/patches/teeny-request-npm-9.0.0-4d571e3c55.patch

@@ -0,0 +1,58 @@
+diff --git a/build/src/index.js b/build/src/index.js
+index af5d15e260e2a47588c7c536447fe84bd3f86136..2b63d0c0b1eb6595c7a0bb314c1df792454c1a72 100644
+--- a/build/src/index.js
++++ b/build/src/index.js
+@@ -115,6 +115,9 @@ function createMultipartStream(boundary, multipart) {
+         }
+         else {
+             part.body.pipe(stream, { end: false });
++            part.body.on('error', (err) => {
++                stream.destroy(err);
++            });
+             part.body.on('end', () => {
+                 stream.write('\r\n');
+                 stream.write(finale);
+@@ -168,25 +171,27 @@ function teenyRequest(reqOpts, callback) {
+         // Stream mode
+         const requestStream = streamEvents(new stream_1.PassThrough());
+         // eslint-disable-next-line @typescript-eslint/no-explicit-any
+-        let responseStream;
+-        requestStream.once('reading', () => {
+-            if (responseStream) {
+-                (0, stream_1.pipeline)(responseStream, requestStream, () => { });
+-            }
+-            else {
+-                requestStream.once('response', () => {
+-                    (0, stream_1.pipeline)(responseStream, requestStream, () => { });
+-                });
+-            }
+-        });
++        // let responseStream;
++        // requestStream.once('reading', () => {
++        //    if (responseStream) {
++        //        (0, stream_1.pipeline)(responseStream, requestStream, () => { });
++        //    }
++        //    else {
++        //        requestStream.once('response', () => {
++        //            (0, stream_1.pipeline)(responseStream, requestStream, () => { });
++        //        });
++        //    }
++        // });
++
++
+         options.compress = false;
+         teenyRequest.stats.requestStarting();
+         (0, node_fetch_1.default)(uri, options).then(res => {
+-            teenyRequest.stats.requestFinished();
+-            responseStream = res.body;
+-            responseStream.on('error', (err) => {
+-                requestStream.emit('error', err);
+-            });
++            teenyRequest.stats.requestFinished(); stream_1.pipeline(res.body, requestStream, () => {});
++        //    responseStream = res.body;
++        //    responseStream.on('error', (err) => {
++        //        requestStream.emit('error', err);
++        //    });
+             const response = fetchToRequestResponse(options, res);
+             requestStream.emit('response', response);
+         }, err => {

+ 81 - 0
.yarn/patches/thread-loader-npm-4.0.2-dab5735f54.patch

@@ -0,0 +1,81 @@
+diff --git a/dist/WorkerPool.js b/dist/WorkerPool.js
+index 4145779f08eefafd0c18394806b6409c595ac5bb..aa16dd6a0f463804455164493a1e75e80cdf656a 100644
+--- a/dist/WorkerPool.js
++++ b/dist/WorkerPool.js
+@@ -258,6 +258,19 @@ class PoolWorker {
+           finalCallback();
+           break;
+         }
++      case 'logMessage':
++        {
++          const {
++            data: { loggerName, methodName, args }
++          } = message;
++          const {
++            data: jobData
++          } = this.jobs[id];
++          const logger = jobData.getLogger(loggerName);
++          logger[methodName].apply(logger, args);
++          finalCallback();
++          break;
++        }
+       case 'emitWarning':
+         {
+           const {
+diff --git a/dist/index.js b/dist/index.js
+index 75cd30fb63dc864057c1afc866f43fc7cc0a8020..d834af6ce1e2cd4473c4ae1b325d63eb1190c17e 100644
+--- a/dist/index.js
++++ b/dist/index.js
+@@ -43,6 +43,7 @@ function pitch() {
+     sourceMap: this.sourceMap,
+     emitError: this.emitError,
+     emitWarning: this.emitWarning,
++    getLogger: this.getLogger,
+     loadModule: this.loadModule,
+     resolve: this.resolve,
+     getResolve: this.getResolve,
+diff --git a/dist/worker.js b/dist/worker.js
+index 8e67959e4b7c9fd0db116509b1459636ba13a097..aca94f1442906baf179ada8e6a56501bbf71c480 100644
+--- a/dist/worker.js
++++ b/dist/worker.js
+@@ -90,6 +90,22 @@ function writeJson(data) {
+   writePipeWrite(lengthBuffer);
+   writePipeWrite(messageBuffer);
+ }
++const LOGGER_METHODS = ['error', 'warn', 'info', 'log', 'debug', 'trace', 'group', 'groupEnd', 'groupCollapsed', 'status', 'clear', 'profile', 'profileEnd'];
++class Logger {
++  constructor(id, loggerName) {
++    this.id = id
++    this.loggerName = loggerName
++    for (const methodName of LOGGER_METHODS) {
++      this[methodName] = (...args) => {
++        writeJson({
++          type: 'logMessage',
++          id: this.id,
++          data: { loggerName, methodName, args }
++        })
++      }
++    }
++  }
++}
+ const queue = (0, _queue.default)(({
+   id,
+   data
+@@ -190,6 +206,7 @@ const queue = (0, _queue.default)(({
+           }
+           return options;
+         },
++        getLogger: (name) => new Logger(id, name),
+         emitWarning: warning => {
+           writeJson({
+             type: 'emitWarning',
+@@ -211,6 +228,9 @@ const queue = (0, _queue.default)(({
+           module._compile(code, filename); // eslint-disable-line no-underscore-dangle
+           return module.exports;
+         },
++        addDependency: filename => {
++          buildDependencies.push(filename);
++        },
+         addBuildDependency: filename => {
+           buildDependencies.push(filename);
+         },

+ 25 - 0
.yarnrc.yml

@@ -0,0 +1,25 @@
+approvedGitRepositories:
+  - "**"
+
+enableGlobalCache: false
+
+enableScripts: true
+
+enableTelemetry: false
+
+nodeLinker: node-modules
+
+npmMinimalAgeGate: 3d
+
+supportedArchitectures:
+  cpu:
+    - current
+    - arm64
+    - x64
+  libc:
+    - current
+    - glibc
+  os:
+    - current
+    - darwin
+    - linux

+ 38 - 0
CONTRIBUTING.md

@@ -0,0 +1,38 @@
+# Contributing to Overleaf
+
+Thank you for reading this! If you'd like to report a bug or join in the development
+of Overleaf, then here are some notes on how to do that.
+
+## Reporting bugs and opening issues
+
+If you'd like to report a bug or open an issue, please **[check if there is an existing issue](https://github.com/overleaf/overleaf/issues).**
+If there is then please add any more information that you have, or give it a 👍.
+
+When submitting an issue please describe the issue as clearly as possible, including how to
+reproduce the bug, which situations it appears in, what you expected to happen, and what actually happens.
+If you can include a screenshot for front end issues that is very helpful.
+
+**Note**: If you are using [www.overleaf.com](www.overleaf.com) and have a problem, or if you would like to request a new feature, please contact the Support team at support@overleaf.com. Raise an issue here only to report bugs in the Community Edition release of Overleaf.
+
+## Pull Requests
+
+See [our wiki](https://github.com/overleaf/overleaf/wiki)
+for how to manage the Overleaf development environment and for our developer guidelines.
+
+We love pull requests, so be bold with them! Don't be afraid of going ahead
+and changing something, or adding a new feature. We're very happy to work with you
+to get your changes merged into Overleaf.
+
+If you're looking for something to work on, have a look at the [open issues](https://github.com/overleaf/overleaf/issues).
+
+## Security
+
+Please see [our security policy](https://github.com/overleaf/overleaf/security/policy) if you would like to report a potential security vulnerability.
+
+## Contributor License Agreement
+
+Before we can accept any contributions of code, we need you to agree to our
+[Contributor License Agreement](https://docs.google.com/forms/d/e/1FAIpQLSef79XH3mb7yIiMzZw-yALEegS-wyFetvjTiNBfZvf_IHD2KA/viewform?usp=sf_link).
+This is to ensure that you own the copyright of your contribution, and that you
+agree to give us a license to use it in both the open source version, and the version
+of Overleaf running at www.overleaf.com, which may have additional changes.

+ 661 - 0
LICENSE

@@ -0,0 +1,661 @@
+                    GNU AFFERO GENERAL PUBLIC LICENSE
+                       Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+  A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate.  Many developers of free software are heartened and
+encouraged by the resulting cooperation.  However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+  The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community.  It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server.  Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+  An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals.  This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU Affero General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Remote Network Interaction; Use with the GNU General Public License.
+
+  Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software.  This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero General Public License from time to time.  Such new versions
+will be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source.  For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code.  There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+<http://www.gnu.org/licenses/>.

+ 80 - 0
README.md

@@ -0,0 +1,80 @@
+<h1 align="center">
+  <br>
+  <a href="https://www.overleaf.com"><img src="doc/logo.png" alt="Overleaf" width="300"></a>
+</h1>
+
+<h4 align="center">An open-source online real-time collaborative LaTeX editor.</h4>
+
+<p align="center">
+  <a href="https://github.com/overleaf/overleaf/wiki">Wiki</a> •
+  <a href="https://www.overleaf.com/for/enterprises">Server Pro</a> •
+  <a href="#contributing">Contributing</a> •
+  <a href="https://mailchi.mp/overleaf.com/community-edition-and-server-pro">Mailing List</a> •
+  <a href="#authors">Authors</a> •
+  <a href="#license">License</a>
+</p>
+
+<img src="doc/screenshot.png" alt="A screenshot of a project being edited in Overleaf Community Edition">
+<p align="center">
+  Figure 1: A screenshot of a project being edited in Overleaf Community Edition.
+</p>
+
+## Community Edition
+
+[Overleaf](https://www.overleaf.com) is an open-source online real-time collaborative LaTeX editor. We run a hosted version at [www.overleaf.com](https://www.overleaf.com), but you can also run your own local version, and contribute to the development of Overleaf.
+
+> [!CAUTION]
+> Overleaf Community Edition is intended for use in environments where **all** users are trusted. Community Edition is **not** appropriate for scenarios where isolation of users is required due to Sandbox Compiles not being available. When not using Sandboxed Compiles, users have full read and write access to the `sharelatex` container resources (filesystem, network, environment variables) when running LaTeX compiles.
+
+For more information on Sandbox Compiles check out our [documentation](https://docs.overleaf.com/on-premises/configuration/overleaf-toolkit/server-pro-only-configuration/sandboxed-compiles).
+
+## Enterprise
+
+If you want help installing and maintaining Overleaf in your lab or workplace, we offer an officially supported version called [Overleaf Server Pro](https://www.overleaf.com/for/enterprises). It also includes more features for security (SSO with LDAP or SAML), administration and collaboration (e.g. tracked changes). [Find out more!](https://www.overleaf.com/for/enterprises)
+
+## Keeping up to date
+
+Sign up to the [mailing list](https://mailchi.mp/overleaf.com/community-edition-and-server-pro) to get updates on Overleaf releases and development.
+
+## Installation
+
+We have detailed installation instructions in the [Overleaf Toolkit](https://github.com/overleaf/toolkit/).
+
+## Upgrading
+
+If you are upgrading from a previous version of Overleaf, please see the [Release Notes section on the Wiki](https://github.com/overleaf/overleaf/wiki#release-notes) for all of the versions between your current version and the version you are upgrading to.
+
+## Overleaf Docker Image
+
+This repo contains two dockerfiles, [`Dockerfile-base`](server-ce/Dockerfile-base), which builds the
+`sharelatex/sharelatex-base` image, and [`Dockerfile`](server-ce/Dockerfile) which builds the
+`sharelatex/sharelatex` (or "community") image.
+
+The Base image generally contains the basic dependencies like `wget`, plus `texlive`.
+We split this out because it's a pretty heavy set of
+dependencies, and it's nice to not have to rebuild all of that every time.
+
+The `sharelatex/sharelatex` image extends the base image and adds the actual Overleaf code
+and services.
+
+Use `make build-base` and `make build-community` from `server-ce/` to build these images.
+
+We use the [Phusion base-image](https://github.com/phusion/baseimage-docker)
+(which is extended by our `base` image) to provide us with a VM-like container
+in which to run the Overleaf services. Baseimage uses the `runit` service
+manager to manage services, and we add our init-scripts from the `server-ce/runit`
+folder.
+
+## Contributing
+
+Please see the [CONTRIBUTING](CONTRIBUTING.md) file for information on contributing to the development of Overleaf.
+
+## Authors
+
+[The Overleaf Team](https://www.overleaf.com/about)
+
+## License
+
+The code in this repository is released under the GNU AFFERO GENERAL PUBLIC LICENSE, version 3. A copy can be found in the [`LICENSE`](LICENSE) file.
+
+Copyright (c) Overleaf, 2014-2025.

+ 152 - 0
Yamls/docker-compose.yml

@@ -0,0 +1,152 @@
+services:
+  sharelatex:
+    restart: always
+    # Server Pro users:
+    # image: quay.io/sharelatex/sharelatex-pro
+    image: sharelatex/sharelatex
+    container_name: sharelatex
+    depends_on:
+      mongo:
+        condition: service_healthy
+      redis:
+        condition: service_started
+    ports:
+      - 80:80
+    stop_grace_period: 60s
+    volumes:
+      - ~/sharelatex_data:/var/lib/overleaf
+      ########################################################################
+      ####  Server Pro: Uncomment the following line to mount the docker  ####
+      ####             socket, required for Sibling Containers to work    ####
+      ########################################################################
+      # - /var/run/docker.sock:/var/run/docker.sock
+    environment:
+      OVERLEAF_APP_NAME: Overleaf Community Edition
+
+      OVERLEAF_MONGO_URL: mongodb://mongo/sharelatex
+
+      # Same property, unfortunately with different names in
+      # different locations
+      OVERLEAF_REDIS_HOST: redis
+      REDIS_HOST: redis
+
+      # IMPORTANT: Required for invite token generation
+      # OVERLEAF_INVITE_TOKEN_SECRET: generate with `openssl rand -base64 32`
+
+      ENABLED_LINKED_FILE_TYPES: "project_file,project_output_file"
+
+      # Enables Thumbnail generation using ImageMagick
+      ENABLE_CONVERSIONS: "true"
+
+      # Disables email confirmation requirement
+      EMAIL_CONFIRMATION_DISABLED: "true"
+
+      ## Set for SSL via nginx-proxy
+      #VIRTUAL_HOST: 103.112.212.22
+
+      # OVERLEAF_SITE_URL: http://overleaf.example.com
+      # OVERLEAF_NAV_TITLE: Overleaf Community Edition
+      # OVERLEAF_HEADER_IMAGE_URL: http://example.com/mylogo.png
+      # OVERLEAF_ADMIN_EMAIL: support@it.com
+
+      # OVERLEAF_LEFT_FOOTER: '[{"text": "Another page I want to link to can be found <a href=\"here\">here</a>"} ]'
+      # OVERLEAF_RIGHT_FOOTER: '[{"text": "Hello I am on the Right"} ]'
+
+      # OVERLEAF_EMAIL_FROM_ADDRESS: "hello@example.com"
+
+      # OVERLEAF_EMAIL_AWS_SES_ACCESS_KEY_ID:
+      # OVERLEAF_EMAIL_AWS_SES_SECRET_KEY:
+
+      # OVERLEAF_EMAIL_SMTP_HOST: smtp.example.com
+      # OVERLEAF_EMAIL_SMTP_PORT: 587
+      # OVERLEAF_EMAIL_SMTP_SECURE: false
+      # OVERLEAF_EMAIL_SMTP_USER:
+      # OVERLEAF_EMAIL_SMTP_PASS:
+      # OVERLEAF_EMAIL_SMTP_TLS_REJECT_UNAUTH: true
+      # OVERLEAF_EMAIL_SMTP_IGNORE_TLS: false
+      # OVERLEAF_EMAIL_SMTP_NAME: '127.0.0.1'
+      # OVERLEAF_EMAIL_SMTP_LOGGER: true
+      # OVERLEAF_CUSTOM_EMAIL_FOOTER: "This system is run by department x"
+
+      # ENABLE_CRON_RESOURCE_DELETION: true
+
+      ################
+      ## Server Pro ##
+      ################
+
+      ## The Community Edition is intended for use in environments where all users are trusted and is not appropriate for
+      ## scenarios where isolation of users is required. Sandboxed Compiles are not available in the Community Edition,
+      ## so the following environment variables must be commented out to avoid compile issues.
+      ##
+      ## Sandboxed Compiles: https://docs.overleaf.com/on-premises/configuration/overleaf-toolkit/server-pro-only-configuration/sandboxed-compiles
+      SANDBOXED_COMPILES: "true"
+      ### Bind-mount source for /var/lib/overleaf/data/compiles inside the container.
+      SANDBOXED_COMPILES_HOST_DIR_COMPILES: "/home/user/sharelatex_data/data/compiles"
+      ### Bind-mount source for /var/lib/overleaf/data/output inside the container.
+      SANDBOXED_COMPILES_HOST_DIR_OUTPUT: "/home/user/sharelatex_data/data/output"
+      ### Backwards compatibility (before Server Pro 5.5)
+      DOCKER_RUNNER: "true"
+      SANDBOXED_COMPILES_SIBLING_CONTAINERS: "true"
+
+      ## Works with test LDAP server shown at bottom of docker compose
+      # OVERLEAF_LDAP_URL: 'ldap://ldap:389'
+      # OVERLEAF_LDAP_SEARCH_BASE: 'ou=people,dc=planetexpress,dc=com'
+      # OVERLEAF_LDAP_SEARCH_FILTER: '(uid={{username}})'
+      # OVERLEAF_LDAP_BIND_DN: 'cn=admin,dc=planetexpress,dc=com'
+      # OVERLEAF_LDAP_BIND_CREDENTIALS: 'GoodNewsEveryone'
+      # OVERLEAF_LDAP_EMAIL_ATT: 'mail'
+      # OVERLEAF_LDAP_NAME_ATT: 'cn'
+      # OVERLEAF_LDAP_LAST_NAME_ATT: 'sn'
+      # OVERLEAF_LDAP_UPDATE_USER_DETAILS_ON_LOGIN: 'true'
+
+      # OVERLEAF_TEMPLATES_USER_ID: "578773160210479700917ee5"
+      # OVERLEAF_NEW_PROJECT_TEMPLATE_LINKS: '[ {"name":"All Templates","url":"/templates/all"}]'
+
+      # OVERLEAF_PROXY_LEARN: "true"
+
+  mongo:
+    restart: always
+    image: mongo:8.0
+    container_name: mongo
+    command: "--replSet overleaf"
+    volumes:
+      - ~/mongo_data:/data/db
+      - ./bin/shared/mongodb-init-replica-set.js:/docker-entrypoint-initdb.d/mongodb-init-replica-set.js
+    environment:
+      MONGO_INITDB_DATABASE: sharelatex
+    extra_hosts:
+      # Required when using the automatic database setup for initializing the replica set.
+      # This override is not needed when running the setup after starting up mongo.
+      - mongo:127.0.0.1
+    healthcheck:
+      test: echo 'db.stats().ok' | mongosh localhost:27017/test --quiet
+      interval: 10s
+      timeout: 10s
+      retries: 5
+
+  redis:
+    restart: always
+    image: redis:6.2
+    container_name: redis
+    volumes:
+      - ~/redis_data:/data
+
+  # ldap:
+  #    restart: always
+  #    image: rroemhild/test-openldap
+  #    container_name: ldap
+
+  # See https://github.com/jwilder/nginx-proxy for documentation on how to configure the nginx-proxy container,
+  # and https://github.com/overleaf/overleaf/wiki/HTTPS-reverse-proxy-using-Nginx for an example of some recommended
+  # settings. We recommend using a properly managed nginx instance outside of the Overleaf Server Pro setup,
+  # but the example here can be used if you'd prefer to run everything with docker-compose
+
+  # nginx-proxy:
+  #     image: jwilder/nginx-proxy
+  #     container_name: nginx-proxy
+  #     ports:
+  #       - "80:80"
+  #       - "443:443"
+  #     volumes:
+  #       - /var/run/docker.sock:/tmp/docker.sock:ro
+  #       - /home/overleaf/tmp:/etc/nginx/certs

+ 13 - 0
Yamls/mongo-claim0-persistentvolumeclaim.yaml

@@ -0,0 +1,13 @@
+apiVersion: v1
+kind: PersistentVolumeClaim
+metadata:
+  labels:
+    io.kompose.service: mongo-claim0
+  name: mongo-claim0
+  namespace: sharelatex
+spec:
+  accessModes:
+    - ReadWriteOnce
+  resources:
+    requests:
+      storage: 100Mi

+ 13 - 0
Yamls/mongo-claim1-persistentvolumeclaim.yaml

@@ -0,0 +1,13 @@
+apiVersion: v1
+kind: PersistentVolumeClaim
+metadata:
+  labels:
+    io.kompose.service: mongo-claim1
+  name: mongo-claim1
+  namespace: sharelatex
+spec:
+  accessModes:
+    - ReadWriteOnce
+  resources:
+    requests:
+      storage: 100Mi

+ 54 - 0
Yamls/mongo-deployment.yaml

@@ -0,0 +1,54 @@
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+  annotations:
+    kompose.cmd: kompose convert
+    kompose.version: 1.34.0 (cbf2835db)
+  labels:
+    io.kompose.service: mongo
+  name: mongo
+  namespace: sharelatex
+spec:
+  replicas: 1
+  selector:
+    matchLabels:
+      io.kompose.service: mongo
+  strategy:
+    type: Recreate
+  template:
+    metadata:
+      annotations:
+        kompose.cmd: kompose convert
+        kompose.version: 1.34.0 (cbf2835db)
+      labels:
+        io.kompose.service: mongo
+    spec:
+      containers:
+        - args:
+            - --replSet
+            - overleaf
+          env:
+            - name: MONGO_INITDB_DATABASE
+              value: sharelatex
+          image: mongo:8.0
+          livenessProbe:
+            exec:
+              command:
+                - echo 'db.stats().ok' | mongosh localhost:27017/test --quiet
+            failureThreshold: 5
+            periodSeconds: 10
+            timeoutSeconds: 10
+          name: mongo
+          volumeMounts:
+            - mountPath: /data/db
+              name: mongo-claim0
+            - mountPath: /docker-entrypoint-initdb.d/mongodb-init-replica-set.js
+              name: mongo-claim1
+      restartPolicy: Always
+      volumes:
+        - name: mongo-claim0
+          persistentVolumeClaim:
+            claimName: mongo-claim0
+        - name: mongo-claim1
+          persistentVolumeClaim:
+            claimName: mongo-claim1

+ 13 - 0
Yamls/redis-claim0-persistentvolumeclaim.yaml

@@ -0,0 +1,13 @@
+apiVersion: v1
+kind: PersistentVolumeClaim
+metadata:
+  labels:
+    io.kompose.service: redis-claim0
+  name: redis-claim0
+  namespace: sharelatex
+spec:
+  accessModes:
+    - ReadWriteOnce
+  resources:
+    requests:
+      storage: 100Mi

+ 36 - 0
Yamls/redis-deployment.yaml

@@ -0,0 +1,36 @@
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+  annotations:
+    kompose.cmd: kompose convert
+    kompose.version: 1.34.0 (cbf2835db)
+  labels:
+    io.kompose.service: redis
+  name: redis
+  namespace: sharelatex
+spec:
+  replicas: 1
+  selector:
+    matchLabels:
+      io.kompose.service: redis
+  strategy:
+    type: Recreate
+  template:
+    metadata:
+      annotations:
+        kompose.cmd: kompose convert
+        kompose.version: 1.34.0 (cbf2835db)
+      labels:
+        io.kompose.service: redis
+    spec:
+      containers:
+        - image: redis:6.2
+          name: redis
+          volumeMounts:
+            - mountPath: /data
+              name: redis-claim0
+      restartPolicy: Always
+      volumes:
+        - name: redis-claim0
+          persistentVolumeClaim:
+            claimName: redis-claim0

+ 13 - 0
Yamls/sharelatex-claim0-persistentvolumeclaim.yaml

@@ -0,0 +1,13 @@
+apiVersion: v1
+kind: PersistentVolumeClaim
+metadata:
+  labels:
+    io.kompose.service: sharelatex-claim0
+  name: sharelatex-claim0
+  namespace: sharelatex
+spec:
+  accessModes:
+    - ReadWriteOnce
+  resources:
+    requests:
+      storage: 100Mi

+ 67 - 0
Yamls/sharelatex-deployment.yaml

@@ -0,0 +1,67 @@
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+  annotations:
+    kompose.cmd: kompose convert
+    kompose.version: 1.34.0 (cbf2835db)
+  labels:
+    io.kompose.service: sharelatex
+  name: sharelatex
+  namespace: sharelatex
+spec:
+  replicas: 1
+  selector:
+    matchLabels:
+      io.kompose.service: sharelatex
+  strategy:
+    type: Recreate
+  template:
+    metadata:
+      annotations:
+        kompose.cmd: kompose convert
+        kompose.version: 1.34.0 (cbf2835db)
+      labels:
+        io.kompose.service: sharelatex
+    spec:
+      containers:
+        - env:
+            - name: DOCKER_RUNNER
+              value: "true"
+            - name: EMAIL_CONFIRMATION_DISABLED
+              value: "true"
+            - name: ENABLED_LINKED_FILE_TYPES
+              value: project_file,project_output_file
+            - name: ENABLE_CONVERSIONS
+              value: "true"
+            - name: OVERLEAF_APP_NAME
+              value: Overleaf Community Edition
+            - name: OVERLEAF_MONGO_URL
+              value: mongodb://mongo/sharelatex
+            - name: OVERLEAF_REDIS_HOST
+              value: redis
+            - name: REDIS_HOST
+              value: redis
+            - name: OVERLEAF_INVITE_TOKEN_SECRET
+              value: "PPjzQiz5SHyxq8SKIFOx2rXp6OoP/DFmx/QghJsqAPI="
+            - name: SANDBOXED_COMPILES
+              value: "true"
+            - name: SANDBOXED_COMPILES_HOST_DIR_COMPILES
+              value: /home/user/sharelatex_data/data/compiles
+            - name: SANDBOXED_COMPILES_HOST_DIR_OUTPUT
+              value: /home/user/sharelatex_data/data/output
+            - name: SANDBOXED_COMPILES_SIBLING_CONTAINERS
+              value: "true"
+          image: sharelatex/sharelatex
+          name: sharelatex
+          ports:
+            - containerPort: 80
+              protocol: TCP
+          volumeMounts:
+            - mountPath: /var/lib/overleaf
+              name: sharelatex-claim0
+      restartPolicy: Always
+      terminationGracePeriodSeconds: 60
+      volumes:
+        - name: sharelatex-claim0
+          persistentVolumeClaim:
+            claimName: sharelatex-claim0

+ 19 - 0
Yamls/sharelatex-service.yaml

@@ -0,0 +1,19 @@
+apiVersion: v1
+kind: Service
+metadata:
+  annotations:
+    kompose.cmd: kompose convert
+    kompose.version: 1.34.0 (cbf2835db)
+  labels:
+    io.kompose.service: sharelatex
+  name: sharelatex
+  namespace: sharelatex
+spec:
+  type: NodePort
+  ports:
+    - name: "80"
+      port: 80
+      nodePort: 30360
+      targetPort: 80
+  selector:
+    io.kompose.service: sharelatex

+ 3 - 0
bin/shared/mongodb-init-replica-set.js

@@ -0,0 +1,3 @@
+/* eslint-disable no-undef */
+
+rs.initiate({ _id: 'overleaf', members: [{ _id: 0, host: 'mongo:27017' }] })

+ 3 - 0
develop/.gitignore

@@ -0,0 +1,3 @@
+/compiles/*
+!.gitkeep
+.env

+ 76 - 0
develop/README.md

@@ -0,0 +1,76 @@
+# Overleaf Community Edition, development environment
+
+## Building and running
+
+In this `develop` directory, build the services:
+
+```shell
+bin/build
+```
+
+> [!NOTE]
+> If Docker is running out of RAM while building the services in parallel, create a `.env` file in this directory containing `COMPOSE_PARALLEL_LIMIT=1`.
+
+Then start the services:
+
+```shell
+bin/up
+```
+
+Once the services are running, open <http://localhost/launchpad> to create the first admin account.
+
+## Development
+
+To avoid running `bin/build && bin/up` after every code change, you can run Overleaf
+Community Edition in _development mode_, where services will automatically update on code changes.
+
+To do this, use the included `bin/dev` script:
+
+```shell
+bin/dev
+```
+
+This will start all services using `node --watch`, which will automatically monitor the code and restart the services as necessary.
+
+To improve performance, you can start only a subset of the services in development mode by providing a space-separated list to the `bin/dev` script:
+
+```shell
+bin/dev [service1] [service2] ... [serviceN]
+```
+
+> [!NOTE]
+> Starting the `web` service in _development mode_ will only update the `web`
+> service when backend code changes. In order to automatically update frontend
+> code as well, make sure to start the `webpack` service in _development mode_
+> as well.
+
+If no services are named, all services will start in development mode.
+
+## Debugging
+
+When run in _development mode_ most services expose a debugging port to which
+you can attach a debugger such as
+[the inspector in Chrome's Dev Tools](chrome://inspect/) or one integrated into
+an IDE. The following table shows the port exposed on the **host machine** for
+each service:
+
+| Service            | Port |
+| ------------------ | ---- |
+| `web`              | 9229 |
+| `clsi`             | 9230 |
+| `chat`             | 9231 |
+| `docstore`         | 9233 |
+| `document-updater` | 9234 |
+| `filestore`        | 9235 |
+| `notifications`    | 9236 |
+| `real-time`        | 9237 |
+| `history-v1`       | 9239 |
+| `project-history`  | 9240 |
+
+To attach to a service using Chrome's _remote debugging_, go to
+<chrome://inspect/> and make sure _Discover network targets_ is checked. Next
+click _Configure..._ and add an entry `localhost:[service port]` for each of the
+services you want to attach a debugger to.
+
+After adding an entry, the service will show up as a _Remote Target_ that you
+can inspect and debug.

+ 3 - 0
develop/bin/build

@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+
+docker compose build --pull "$@"

+ 3 - 0
develop/bin/dev

@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+
+docker-compose -f docker-compose.yml -f docker-compose.dev.yml up --no-deps --detach "$@"

+ 3 - 0
develop/bin/down

@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+
+docker compose down "$@"

+ 9 - 0
develop/bin/logs

@@ -0,0 +1,9 @@
+#!/usr/bin/env bash
+
+docker compose logs --follow --tail 10 --no-color "$@" \
+  | ggrep --line-buffered --invert-match "global.gc" \
+  | ggrep --line-buffered --invert-match "health.check" \
+  | ggrep --line-buffered --invert-match "slow event loop" \
+  | ggrep --line-buffered --invert-match "process.memoryUsage" \
+  | ggrep --line-buffered --only-matching "[{].*" \
+  | bunyan --output short

+ 3 - 0
develop/bin/shell

@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+
+docker compose exec -it "$@" /bin/bash

+ 3 - 0
develop/bin/up

@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+
+docker compose up --detach "$@"

+ 0 - 0
develop/compiles/.gitkeep


+ 24 - 0
develop/dev.env

@@ -0,0 +1,24 @@
+CHAT_HOST=chat
+CLSI_HOST=clsi
+DOWNLOAD_HOST=clsi-nginx
+DOCSTORE_HOST=docstore
+DOCUMENT_UPDATER_HOST=document-updater
+FILESTORE_HOST=filestore
+GRACEFUL_SHUTDOWN_DELAY_SECONDS=0
+HISTORY_V1_HOST=history-v1
+HISTORY_REDIS_HOST=redis
+LISTEN_ADDRESS=0.0.0.0
+MONGO_HOST=mongo
+MONGO_URL=mongodb://mongo/sharelatex?directConnection=true
+NOTIFICATIONS_HOST=notifications
+PROJECT_HISTORY_HOST=project-history
+QUEUES_REDIS_HOST=redis
+DSMP_REDIS_HOST=redis
+REALTIME_HOST=real-time
+REDIS_HOST=redis
+SESSION_SECRET=foo
+V1_HISTORY_HOST=history-v1
+WEBPACK_HOST=webpack
+WEB_API_PASSWORD=overleaf
+WEB_API_USER=overleaf
+WEB_HOST=web

+ 128 - 0
develop/docker-compose.dev.yml

@@ -0,0 +1,128 @@
+services:
+  clsi:
+    command: ["node", "--watch", "app.js"]
+    environment:
+      - NODE_OPTIONS=--inspect=0.0.0.0:9229
+    ports:
+      - "127.0.0.1:9230:9229"
+    volumes:
+      - ../services/clsi/app:/overleaf/services/clsi/app
+      - ../services/clsi/app.js:/overleaf/services/clsi/app.js
+      - ../services/clsi/config:/overleaf/services/clsi/config
+
+  chat:
+    command: ["node", "--watch", "app.js"]
+    environment:
+      - NODE_OPTIONS=--inspect=0.0.0.0:9229
+    ports:
+      - "127.0.0.1:9231:9229"
+    volumes:
+      - ../services/chat/app:/overleaf/services/chat/app
+      - ../services/chat/app.js:/overleaf/services/chat/app.js
+      - ../services/chat/config:/overleaf/services/chat/config
+
+  docstore:
+    command: ["node", "--watch", "app.js"]
+    environment:
+      - NODE_OPTIONS=--inspect=0.0.0.0:9229
+    ports:
+      - "127.0.0.1:9233:9229"
+    volumes:
+      - ../services/docstore/app:/overleaf/services/docstore/app
+      - ../services/docstore/app.js:/overleaf/services/docstore/app.js
+      - ../services/docstore/config:/overleaf/services/docstore/config
+
+  document-updater:
+    command: ["node", "--watch", "app.js"]
+    environment:
+      - NODE_OPTIONS=--inspect=0.0.0.0:9229
+    ports:
+      - "127.0.0.1:9234:9229"
+    volumes:
+      - ../services/document-updater/app:/overleaf/services/document-updater/app
+      - ../services/document-updater/app.js:/overleaf/services/document-updater/app.js
+      - ../services/document-updater/config:/overleaf/services/document-updater/config
+
+  filestore:
+    command: ["node", "--watch", "app.js"]
+    environment:
+      - NODE_OPTIONS=--inspect=0.0.0.0:9229
+    ports:
+      - "127.0.0.1:9235:9229"
+    volumes:
+      - ../services/filestore/app:/overleaf/services/filestore/app
+      - ../services/filestore/app.js:/overleaf/services/filestore/app.js
+      - ../services/filestore/config:/overleaf/services/filestore/config
+
+  history-v1:
+    command: ["node", "--watch", "app.js"]
+    environment:
+      - NODE_OPTIONS=--inspect=0.0.0.0:9229
+    ports:
+      - "127.0.0.1:9239:9229"
+    volumes:
+      - ../services/history-v1/api:/overleaf/services/history-v1/api
+      - ../services/history-v1/app.js:/overleaf/services/history-v1/app.js
+      - ../services/history-v1/config:/overleaf/services/history-v1/config
+      - ../services/history-v1/storage:/overleaf/services/history-v1/storage
+      - ../services/history-v1/knexfile.js:/overleaf/services/history-v1/knexfile.js
+      - ../services/history-v1/migrations:/overleaf/services/history-v1/migrations
+
+  notifications:
+    command: ["node", "--watch", "app.ts"]
+    environment:
+      - NODE_OPTIONS=--inspect=0.0.0.0:9229
+    ports:
+      - "127.0.0.1:9236:9229"
+    volumes:
+      - ../services/notifications/app:/overleaf/services/notifications/app
+      - ../services/notifications/app.ts:/overleaf/services/notifications/app.ts
+      - ../services/notifications/config:/overleaf/services/notifications/config
+
+  project-history:
+    command: ["node", "--watch", "app.js"]
+    environment:
+      - NODE_OPTIONS=--inspect=0.0.0.0:9229
+    ports:
+      - "127.0.0.1:9240:9229"
+    volumes:
+      - ../services/project-history/app:/overleaf/services/project-history/app
+      - ../services/project-history/app.js:/overleaf/services/project-history/app.js
+      - ../services/project-history/config:/overleaf/services/project-history/config
+
+  real-time:
+    command: ["node", "--watch", "app.js"]
+    environment:
+      - NODE_OPTIONS=--inspect=0.0.0.0:9229
+    ports:
+      - "127.0.0.1:9237:9229"
+    volumes:
+      - ../services/real-time/app:/overleaf/services/real-time/app
+      - ../services/real-time/app.js:/overleaf/services/real-time/app.js
+      - ../services/real-time/config:/overleaf/services/real-time/config
+
+  web:
+    command: ["node", "--watch", "app.mjs", "--watch-locales"]
+    environment:
+      - NODE_OPTIONS=--inspect=0.0.0.0:9229
+    ports:
+      - "127.0.0.1:9229:9229"
+    volumes:
+      - ../services/web/app:/overleaf/services/web/app
+      - ../services/web/app.mjs:/overleaf/services/web/app.mjs
+      - ../services/web/config:/overleaf/services/web/config
+      - ../services/web/locales:/overleaf/services/web/locales
+      - ../services/web/modules:/overleaf/services/web/modules
+      - ../services/web/public:/overleaf/services/web/public
+
+  webpack:
+    volumes:
+      - ../services/web/app:/overleaf/services/web/app
+      - ../services/web/config:/overleaf/services/web/config
+      - ../services/web/frontend:/overleaf/services/web/frontend
+      - ../services/web/locales:/overleaf/services/web/locales
+      - ../services/web/modules:/overleaf/services/web/modules
+      - ../services/web/public:/overleaf/services/web/public
+      - ../services/web/transform:/overleaf/services/web/transform
+      - ../services/web/types:/overleaf/services/web/types
+      - ../services/web/webpack-plugins:/overleaf/services/web/webpack-plugins

+ 175 - 0
develop/docker-compose.yml

@@ -0,0 +1,175 @@
+volumes:
+  clsi-cache:
+  filestore-public-files:
+  filestore-template-files:
+  filestore-uploads:
+  filestore-user-files:
+  mongo-data:
+  redis-data:
+  sharelatex-data:
+  web-data:
+  history-v1-buckets:
+
+services:
+  chat:
+    build:
+      context: ..
+      dockerfile: services/chat/Dockerfile
+    env_file:
+      - dev.env
+
+  clsi:
+    build:
+      context: ..
+      dockerfile: services/clsi/Dockerfile
+      target: with-texlive
+    env_file:
+      - dev.env
+    environment:
+      - SANDBOXED_COMPILES=false
+    user: root
+    volumes:
+      - ${PWD}/compiles:/overleaf/services/clsi/compiles
+      - ${PWD}/output:/overleaf/services/clsi/output
+      - ${DOCKER_SOCKET_PATH:-/var/run/docker.sock}:/var/run/docker.sock
+      - clsi-cache:/overleaf/services/clsi/cache
+
+  clsi-nginx:
+    image: nginx:1.28
+    read_only: true
+    tmpfs:
+      - /tmp
+      - /var/cache/nginx
+      - /run
+    volumes:
+      - ${PWD}/output:/output:ro
+      - ../services/clsi/nginx.conf:/etc/nginx/conf.d/nginx.conf:ro
+
+  docstore:
+    build:
+      context: ..
+      dockerfile: services/docstore/Dockerfile
+    env_file:
+      - dev.env
+
+  document-updater:
+    build:
+      context: ..
+      dockerfile: services/document-updater/Dockerfile
+    env_file:
+      - dev.env
+
+  filestore:
+    build:
+      context: ..
+      dockerfile: services/filestore/Dockerfile
+    env_file:
+      - dev.env
+    #    environment:
+    #      - ENABLE_CONVERSIONS=true
+    volumes:
+      - filestore-public-files:/overleaf/services/filestore/public_files
+      - filestore-template-files:/overleaf/services/filestore/template_files
+      - filestore-uploads:/overleaf/services/filestore/uploads
+
+  history-v1:
+    build:
+      context: ..
+      dockerfile: services/history-v1/Dockerfile
+    env_file:
+      - dev.env
+    environment:
+      OVERLEAF_EDITOR_ANALYTICS_BUCKET: "/buckets/analytics"
+      OVERLEAF_EDITOR_BLOBS_BUCKET: "/buckets/blobs"
+      OVERLEAF_EDITOR_CHUNKS_BUCKET: "/buckets/chunks"
+      OVERLEAF_EDITOR_PROJECT_BLOBS_BUCKET: "/buckets/project_blobs"
+      OVERLEAF_EDITOR_ZIPS_BUCKET: "/buckets/zips"
+      PERSISTOR_BACKEND: fs
+    volumes:
+      - history-v1-buckets:/buckets
+
+  mongo:
+    image: mongo:8
+    command: --replSet overleaf
+    ports:
+      - "127.0.0.1:27017:27017" # for debugging
+    volumes:
+      - mongo-data:/data/db
+      - ../bin/shared/mongodb-init-replica-set.js:/docker-entrypoint-initdb.d/mongodb-init-replica-set.js
+    environment:
+      MONGO_INITDB_DATABASE: sharelatex
+    extra_hosts:
+      # Required when using the automatic database setup for initializing the
+      # replica set. This override is not needed when running the setup after
+      # starting up mongo.
+      - mongo:127.0.0.1
+
+  notifications:
+    build:
+      context: ..
+      dockerfile: services/notifications/Dockerfile
+    env_file:
+      - dev.env
+
+  project-history:
+    build:
+      context: ..
+      dockerfile: services/project-history/Dockerfile
+    env_file:
+      - dev.env
+
+  real-time:
+    build:
+      context: ..
+      dockerfile: services/real-time/Dockerfile
+    env_file:
+      - dev.env
+
+  redis:
+    image: redis:7
+    ports:
+      - "127.0.0.1:6379:6379" # for debugging
+    volumes:
+      - redis-data:/data
+
+  web:
+    build:
+      context: ..
+      dockerfile: services/web/Dockerfile
+      target: dev
+    env_file:
+      - dev.env
+    environment:
+      - APP_NAME=Overleaf Community Edition
+      - ENABLED_LINKED_FILE_TYPES=project_file,project_output_file
+      - EMAIL_CONFIRMATION_DISABLED=true
+      - NODE_ENV=development
+      - OVERLEAF_ALLOW_PUBLIC_ACCESS=true
+    command: ["node", "app.mjs"]
+    volumes:
+      - sharelatex-data:/var/lib/overleaf
+      - web-data:/overleaf/services/web/data
+    depends_on:
+      - mongo
+      - redis
+      - chat
+      - clsi
+      - docstore
+      - document-updater
+      - filestore
+      - history-v1
+      - notifications
+      - project-history
+      - real-time
+
+  webpack:
+    build:
+      context: ..
+      dockerfile: services/web/Dockerfile
+      target: webpack
+    command:
+      ["npx", "webpack", "serve", "--config", "webpack.config.dev-env.js"]
+    ports:
+      - "127.0.0.1:80:3808"
+    volumes:
+      - ./webpack.config.dev-env.js:/overleaf/services/web/webpack.config.dev-env.js

+ 23 - 0
develop/webpack.config.dev-env.js

@@ -0,0 +1,23 @@
+const { merge } = require('webpack-merge')
+
+const base = require('./webpack.config.dev')
+
+module.exports = merge(base, {
+  devServer: {
+    allowedHosts: 'auto',
+    devMiddleware: {
+      index: false,
+    },
+    proxy: [
+      {
+        context: '/socket.io/**',
+        target: 'http://real-time:3026',
+        ws: true,
+      },
+      {
+        context: ['!**/*.js', '!**/*.css', '!**/*.json'],
+        target: 'http://web:3000',
+      },
+    ],
+  },
+})

BIN
doc/logo.png


BIN
doc/screenshot.png


+ 23 - 0
docker-compose.debug.yml

@@ -0,0 +1,23 @@
+version: "2.2"
+services:
+  sharelatex:
+    ports:
+      - 30000:30000
+      - 30150:30150
+      - 30120:30120
+      - 30050:30050
+      - 30420:30420
+      - 30030:30030
+      - 30160:30160
+      - 30360:30360
+      - 30130:30130
+      - 30100:30100
+      - 30540:30540
+      - 30640:30640
+      - 40000:40000
+
+      # Server Pro
+      - 30070:30070
+      - 30400:30400
+    environment:
+      DEBUG_NODE: "true"

+ 152 - 0
docker-compose.yml

@@ -0,0 +1,152 @@
+services:
+  sharelatex:
+    restart: always
+    # Server Pro users:
+    # image: quay.io/sharelatex/sharelatex-pro
+    image: sharelatex/sharelatex
+    container_name: sharelatex
+    depends_on:
+      mongo:
+        condition: service_healthy
+      redis:
+        condition: service_started
+    ports:
+      - 80:80
+    stop_grace_period: 60s
+    volumes:
+      - ~/sharelatex_data:/var/lib/overleaf
+      ########################################################################
+      ####  Server Pro: Uncomment the following line to mount the docker  ####
+      ####             socket, required for Sibling Containers to work    ####
+      ########################################################################
+      # - /var/run/docker.sock:/var/run/docker.sock
+    environment:
+      OVERLEAF_APP_NAME: Overleaf Community Edition
+
+      OVERLEAF_MONGO_URL: mongodb://mongo/sharelatex
+
+      # Same property, unfortunately with different names in
+      # different locations
+      OVERLEAF_REDIS_HOST: redis
+      REDIS_HOST: redis
+
+      # IMPORTANT: Required for invite token generation
+      # OVERLEAF_INVITE_TOKEN_SECRET: generate with `openssl rand -base64 32`
+
+      ENABLED_LINKED_FILE_TYPES: "project_file,project_output_file"
+
+      # Enables Thumbnail generation using ImageMagick
+      ENABLE_CONVERSIONS: "true"
+
+      # Disables email confirmation requirement
+      EMAIL_CONFIRMATION_DISABLED: "true"
+
+      ## Set for SSL via nginx-proxy
+      #VIRTUAL_HOST: 103.112.212.22
+
+      # OVERLEAF_SITE_URL: http://overleaf.example.com
+      # OVERLEAF_NAV_TITLE: Overleaf Community Edition
+      # OVERLEAF_HEADER_IMAGE_URL: http://example.com/mylogo.png
+      # OVERLEAF_ADMIN_EMAIL: support@it.com
+
+      # OVERLEAF_LEFT_FOOTER: '[{"text": "Another page I want to link to can be found <a href=\"here\">here</a>"} ]'
+      # OVERLEAF_RIGHT_FOOTER: '[{"text": "Hello I am on the Right"} ]'
+
+      # OVERLEAF_EMAIL_FROM_ADDRESS: "hello@example.com"
+
+      # OVERLEAF_EMAIL_AWS_SES_ACCESS_KEY_ID:
+      # OVERLEAF_EMAIL_AWS_SES_SECRET_KEY:
+
+      # OVERLEAF_EMAIL_SMTP_HOST: smtp.example.com
+      # OVERLEAF_EMAIL_SMTP_PORT: 587
+      # OVERLEAF_EMAIL_SMTP_SECURE: false
+      # OVERLEAF_EMAIL_SMTP_USER:
+      # OVERLEAF_EMAIL_SMTP_PASS:
+      # OVERLEAF_EMAIL_SMTP_TLS_REJECT_UNAUTH: true
+      # OVERLEAF_EMAIL_SMTP_IGNORE_TLS: false
+      # OVERLEAF_EMAIL_SMTP_NAME: '127.0.0.1'
+      # OVERLEAF_EMAIL_SMTP_LOGGER: true
+      # OVERLEAF_CUSTOM_EMAIL_FOOTER: "This system is run by department x"
+
+      # ENABLE_CRON_RESOURCE_DELETION: true
+
+      ################
+      ## Server Pro ##
+      ################
+
+      ## The Community Edition is intended for use in environments where all users are trusted and is not appropriate for
+      ## scenarios where isolation of users is required. Sandboxed Compiles are not available in the Community Edition,
+      ## so the following environment variables must be commented out to avoid compile issues.
+      ##
+      ## Sandboxed Compiles: https://docs.overleaf.com/on-premises/configuration/overleaf-toolkit/server-pro-only-configuration/sandboxed-compiles
+      SANDBOXED_COMPILES: "true"
+      ### Bind-mount source for /var/lib/overleaf/data/compiles inside the container.
+      SANDBOXED_COMPILES_HOST_DIR_COMPILES: "/home/user/sharelatex_data/data/compiles"
+      ### Bind-mount source for /var/lib/overleaf/data/output inside the container.
+      SANDBOXED_COMPILES_HOST_DIR_OUTPUT: "/home/user/sharelatex_data/data/output"
+      ### Backwards compatibility (before Server Pro 5.5)
+      DOCKER_RUNNER: "true"
+      SANDBOXED_COMPILES_SIBLING_CONTAINERS: "true"
+
+      ## Works with test LDAP server shown at bottom of docker compose
+      # OVERLEAF_LDAP_URL: 'ldap://ldap:389'
+      # OVERLEAF_LDAP_SEARCH_BASE: 'ou=people,dc=planetexpress,dc=com'
+      # OVERLEAF_LDAP_SEARCH_FILTER: '(uid={{username}})'
+      # OVERLEAF_LDAP_BIND_DN: 'cn=admin,dc=planetexpress,dc=com'
+      # OVERLEAF_LDAP_BIND_CREDENTIALS: 'GoodNewsEveryone'
+      # OVERLEAF_LDAP_EMAIL_ATT: 'mail'
+      # OVERLEAF_LDAP_NAME_ATT: 'cn'
+      # OVERLEAF_LDAP_LAST_NAME_ATT: 'sn'
+      # OVERLEAF_LDAP_UPDATE_USER_DETAILS_ON_LOGIN: 'true'
+
+      # OVERLEAF_TEMPLATES_USER_ID: "578773160210479700917ee5"
+      # OVERLEAF_NEW_PROJECT_TEMPLATE_LINKS: '[ {"name":"All Templates","url":"/templates/all"}]'
+
+      # OVERLEAF_PROXY_LEARN: "true"
+
+  mongo:
+    restart: always
+    image: mongo:8.0
+    container_name: mongo
+    command: "--replSet overleaf"
+    volumes:
+      - ~/mongo_data:/data/db
+      - ./bin/shared/mongodb-init-replica-set.js:/docker-entrypoint-initdb.d/mongodb-init-replica-set.js
+    environment:
+      MONGO_INITDB_DATABASE: sharelatex
+    extra_hosts:
+      # Required when using the automatic database setup for initializing the replica set.
+      # This override is not needed when running the setup after starting up mongo.
+      - mongo:127.0.0.1
+    healthcheck:
+      test: echo 'db.stats().ok' | mongosh localhost:27017/test --quiet
+      interval: 10s
+      timeout: 10s
+      retries: 5
+
+  redis:
+    restart: always
+    image: redis:6.2
+    container_name: redis
+    volumes:
+      - ~/redis_data:/data
+
+  # ldap:
+  #    restart: always
+  #    image: rroemhild/test-openldap
+  #    container_name: ldap
+
+  # See https://github.com/jwilder/nginx-proxy for documentation on how to configure the nginx-proxy container,
+  # and https://github.com/overleaf/overleaf/wiki/HTTPS-reverse-proxy-using-Nginx for an example of some recommended
+  # settings. We recommend using a properly managed nginx instance outside of the Overleaf Server Pro setup,
+  # but the example here can be used if you'd prefer to run everything with docker-compose
+
+  # nginx-proxy:
+  #     image: jwilder/nginx-proxy
+  #     container_name: nginx-proxy
+  #     ports:
+  #       - "80:80"
+  #       - "443:443"
+  #     volumes:
+  #       - /var/run/docker.sock:/tmp/docker.sock:ro
+  #       - /home/overleaf/tmp:/etc/nginx/certs

+ 18 - 0
dockerfiles/cypress/Dockerfile

@@ -0,0 +1,18 @@
+FROM cypress/included:15.12.0
+ARG USER_UID=1000
+ARG USER_GID=1000
+
+# Corepack setup, shared between all the images.
+ENV PATH="/overleaf/node_modules/.bin:$PATH"
+ENV COREPACK_HOME=/opt/corepack
+RUN corepack enable && corepack install -g yarn@4.14.1
+ENV COREPACK_ENABLE_NETWORK=0
+
+WORKDIR /overleaf
+
+RUN sed -i s/node:x:1000:/node:x:${USER_GID}:/ /etc/group \
+&&  sed -i s_node:x:1000:1000::/home/node:/bin/bash_node:x:${USER_UID}:${USER_GID}::/home/node:/bin/bash_ /etc/passwd \
+&&  chown -R node:node /home/node \
+&&  chown node:node /overleaf
+
+USER node

+ 13 - 0
libraries/access-token-encryptor/.mocharc.cjs

@@ -0,0 +1,13 @@
+let reporterOptions = {}
+if (process.env.CI) {
+  reporterOptions = {
+    reporter: require.resolve('mocha-multi-reporters'),
+    'reporter-options': ['configFile=./test/mocha-multi-reporters.cjs'],
+  }
+}
+const all = {
+  require: 'test/setup.js',
+  ...reporterOptions,
+}
+
+module.exports = all

+ 1 - 0
libraries/access-token-encryptor/.nvmrc

@@ -0,0 +1 @@
+24.14.1

+ 661 - 0
libraries/access-token-encryptor/LICENSE

@@ -0,0 +1,661 @@
+                    GNU AFFERO GENERAL PUBLIC LICENSE
+                       Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+  A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate.  Many developers of free software are heartened and
+encouraged by the resulting cooperation.  However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+  The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community.  It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server.  Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+  An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals.  This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU Affero General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Remote Network Interaction; Use with the GNU General Public License.
+
+  Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software.  This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero General Public License from time to time.  Such new versions
+will be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source.  For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code.  There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+<http://www.gnu.org/licenses/>.

+ 59 - 0
libraries/access-token-encryptor/Makefile

@@ -0,0 +1,59 @@
+# Run the test commands in the scope of the monorepo.
+# Eslint and prettier (plus some configs) are on the root.
+RUN_LINTING = ../../bin/run -w /overleaf/libraries/access-token-encryptor monorepo yarn run --silent
+RUN_LINTING_MONOREPO = ../../bin/run monorepo yarn run --silent
+
+WITH_CACHE_FOLDER = \
+	lint \
+	lint_ci \
+	lint_fix \
+	format \
+	format_ci \
+	format_fix \
+	typecheck \
+	typecheck_ci \
+
+$(WITH_CACHE_FOLDER): ../../node_modules/.cache/prettier/
+../../node_modules/.cache/prettier/:
+	mkdir -p $@
+
+$(WITH_CACHE_FOLDER): ../../node_modules/.cache/eslint/
+../../node_modules/.cache/eslint/:
+	mkdir -p $@
+
+format:
+	$(RUN_LINTING_MONOREPO) format libraries/access-token-encryptor
+
+format_ci:
+	$(RUN_LINTING_MONOREPO) format libraries/access-token-encryptor
+
+format_fix:
+	$(RUN_LINTING_MONOREPO) format:fix libraries/access-token-encryptor
+
+lint:
+	$(RUN_LINTING) lint
+
+lint_ci:
+	-$(RUN_LINTING) lint --format json --output-file reports/eslint.json
+	sed -i 's_"filePath":"/overleaf_"filePath":"$(MONOREPO)_g' reports/eslint.json
+
+lint_fix:
+	$(RUN_LINTING) lint:fix
+
+typecheck:
+	$(RUN_LINTING) types:check
+
+typecheck_ci:
+	$(RUN_LINTING) types:check
+
+test: test_unit
+test_unit:
+ifneq (,$(wildcard test/unit))
+	$(RUN_LINTING) test:unit
+endif
+
+test: test_acceptance
+test_acceptance:
+ifneq (,$(wildcard test/acceptance))
+	$(RUN_LINTING) test:acceptance
+endif

+ 3 - 0
libraries/access-token-encryptor/README.md

@@ -0,0 +1,3 @@
+# Access Token Encryptor
+
+Used in third-party-references, to encrypt access tokens

+ 9 - 0
libraries/access-token-encryptor/buildscript.txt

@@ -0,0 +1,9 @@
+access-token-encryptor
+--dependencies=None
+--env-add=
+--env-pass-through=
+--esmock-loader=False
+--is-library=True
+--node-version=24.14.1
+--pipeline-owner=32
+--public-repo=False

+ 1 - 0
libraries/access-token-encryptor/index.js

@@ -0,0 +1 @@
+module.exports = require('./lib/js/AccessTokenEncryptor')

+ 164 - 0
libraries/access-token-encryptor/lib/js/AccessTokenEncryptor.js

@@ -0,0 +1,164 @@
+const { promisify } = require('node:util')
+const crypto = require('node:crypto')
+
+const ALGORITHM = 'aes-256-ctr'
+
+const cryptoHkdf = promisify(crypto.hkdf)
+const cryptoRandomBytes = promisify(crypto.randomBytes)
+
+class AbstractAccessTokenScheme {
+  constructor(cipherLabel, cipherPassword) {
+    this.cipherLabel = cipherLabel
+    this.cipherPassword = cipherPassword
+  }
+
+  /**
+   * @param {Object} json
+   * @return {Promise<string>}
+   */
+  async encryptJson(json) {
+    throw new Error('encryptJson is not implemented')
+  }
+
+  /**
+   * @param {string} encryptedJson
+   * @return {Promise<Object>}
+   */
+  async decryptToJson(encryptedJson) {
+    throw new Error('decryptToJson is not implemented')
+  }
+}
+
+class AccessTokenSchemeWithGenericKeyFn extends AbstractAccessTokenScheme {
+  /**
+   * @param {Buffer} salt
+   * @return {Promise<Buffer>}
+   */
+  async keyFn(salt) {
+    throw new Error('keyFn is not implemented')
+  }
+
+  async encryptJson(json) {
+    const plainText = JSON.stringify(json)
+
+    const bytes = await cryptoRandomBytes(32)
+    const salt = bytes.slice(0, 16)
+    const iv = bytes.slice(16, 32)
+    const key = await this.keyFn(salt)
+
+    const cipher = crypto.createCipheriv(ALGORITHM, key, iv)
+    const cipherText =
+      cipher.update(plainText, 'utf8', 'base64') + cipher.final('base64')
+
+    return [
+      this.cipherLabel,
+      salt.toString('hex'),
+      cipherText,
+      iv.toString('hex'),
+    ].join(':')
+  }
+
+  async decryptToJson(encryptedJson) {
+    const [, salt, cipherText, iv] = encryptedJson.split(':', 4)
+    const key = await this.keyFn(Buffer.from(salt, 'hex'))
+
+    const decipher = crypto.createDecipheriv(
+      ALGORITHM,
+      key,
+      Buffer.from(iv, 'hex')
+    )
+    const plainText =
+      decipher.update(cipherText, 'base64', 'utf8') + decipher.final('utf8')
+    try {
+      return JSON.parse(plainText)
+    } catch (e) {
+      throw new Error('error decrypting token')
+    }
+  }
+}
+
+class AccessTokenSchemeV3 extends AccessTokenSchemeWithGenericKeyFn {
+  async keyFn(salt) {
+    const optionalInfo = ''
+    return await cryptoHkdf(
+      'sha512',
+      this.cipherPassword,
+      salt,
+      optionalInfo,
+      32
+    )
+  }
+}
+
+class AccessTokenEncryptor {
+  constructor(settings) {
+    /**
+     * @type {Map<string, AbstractAccessTokenScheme>}
+     */
+    this.schemeByCipherLabel = new Map()
+    for (const cipherLabel of Object.keys(settings.cipherPasswords)) {
+      if (!cipherLabel) {
+        throw new Error('cipherLabel cannot be empty')
+      }
+      if (cipherLabel.match(/:/)) {
+        throw new Error(
+          `cipherLabel must not contain a colon (:), got ${cipherLabel}`
+        )
+      }
+      const [, version] = cipherLabel.split('-')
+      if (!version) {
+        throw new Error(
+          `cipherLabel must contain version suffix (e.g. 2042.1-v42), got ${cipherLabel}`
+        )
+      }
+
+      const cipherPassword = settings.cipherPasswords[cipherLabel]
+      if (!cipherPassword) {
+        throw new Error(`cipherPasswords['${cipherLabel}'] is missing`)
+      }
+      if (cipherPassword.length < 16) {
+        throw new Error(`cipherPasswords['${cipherLabel}'] is too short`)
+      }
+
+      let scheme
+      switch (version) {
+        case 'v3':
+          scheme = new AccessTokenSchemeV3(cipherLabel, cipherPassword)
+          break
+        default:
+          throw new Error(`unknown version '${version}' for ${cipherLabel}`)
+      }
+      this.schemeByCipherLabel.set(cipherLabel, scheme)
+    }
+
+    /** @type {AbstractAccessTokenScheme} */
+    this.defaultScheme = this.schemeByCipherLabel.get(settings.cipherLabel)
+    if (!this.defaultScheme) {
+      throw new Error(`unknown default cipherLabel ${settings.cipherLabel}`)
+    }
+  }
+
+  promises = {
+    encryptJson: async json => await this.defaultScheme.encryptJson(json),
+    decryptToJson: async encryptedJson => {
+      const [label] = encryptedJson.split(':', 1)
+      const scheme = this.schemeByCipherLabel.get(label)
+      if (!scheme) {
+        throw new Error('unknown access-token-encryptor label ' + label)
+      }
+      return await scheme.decryptToJson(encryptedJson)
+    },
+  }
+
+  encryptJson(json, callback) {
+    this.promises.encryptJson(json).then(s => callback(null, s), callback)
+  }
+
+  decryptToJson(encryptedJson, callback) {
+    this.promises
+      .decryptToJson(encryptedJson)
+      .then(o => callback(null, o), callback)
+  }
+}
+
+module.exports = AccessTokenEncryptor

+ 28 - 0
libraries/access-token-encryptor/package.json

@@ -0,0 +1,28 @@
+{
+  "name": "@overleaf/access-token-encryptor",
+  "version": "3.0.0",
+  "description": "",
+  "main": "index.js",
+  "scripts": {
+    "test": "yarn run lint && yarn run types:check && yarn run test:unit",
+    "lint": "eslint --cache --cache-location ../../.cache/eslint/ --ext .cjs,.js,.jsx,.mjs,.ts --max-warnings 0 --format unix .",
+    "lint:fix": "eslint --cache --cache-location ../../.cache/eslint/ --fix --ext .cjs,.js,.jsx,.mjs,.ts .",
+    "test:ci": "yarn run test:unit",
+    "test:unit": "mocha --exit test/**/*.{js,cjs}",
+    "types:check": "tsc --noEmit"
+  },
+  "author": "",
+  "license": "AGPL-3.0-only",
+  "dependencies": {
+    "lodash": "^4.18.1"
+  },
+  "devDependencies": {
+    "chai": "^4.3.6",
+    "chai-as-promised": "^7.1.1",
+    "mocha": "^11.1.0",
+    "mocha-junit-reporter": "^2.2.1",
+    "mocha-multi-reporters": "^1.5.1",
+    "sandboxed-module": "^2.0.4",
+    "typescript": "^5.0.4"
+  }
+}

+ 27 - 0
libraries/access-token-encryptor/scripts/helpers/format-usage-stats.js

@@ -0,0 +1,27 @@
+function formatTokenUsageStats(STATS) {
+  const prettyStats = []
+  const sortedStats = Object.entries(STATS).sort((a, b) =>
+    a[0] > b[0] ? 1 : -1
+  )
+  const totalByName = {}
+  for (const [key, n] of sortedStats) {
+    const [name, version, collectionName, path, label] = key.split(':')
+    totalByName[name] = (totalByName[name] || 0) + n
+    prettyStats.push({ name, version, collectionName, path, label, n })
+  }
+  for (const row of prettyStats) {
+    row.percentage = ((100 * row.n) / totalByName[row.name])
+      .toFixed(2)
+      .padStart(6)
+  }
+
+  if (prettyStats.length === 0) {
+    console.warn('---')
+    console.warn('Found 0 access tokens.')
+    console.warn('---')
+  } else {
+    console.table(prettyStats)
+  }
+}
+
+module.exports = { formatTokenUsageStats }

+ 108 - 0
libraries/access-token-encryptor/scripts/helpers/re-encrypt-tokens.js

@@ -0,0 +1,108 @@
+const _ = require('lodash')
+const { formatTokenUsageStats } = require('./format-usage-stats')
+
+const LOG_EVERY_IN_S = parseInt(process.env.LOG_EVERY_IN_S || '5', 10)
+const DRY_RUN = !process.argv.includes('--dry-run=false')
+
+/**
+ * @param {AccessTokenEncryptor} accessTokenEncryptor
+ * @param {string} encryptedJson
+ * @return {Promise<string>}
+ */
+async function reEncryptTokens(accessTokenEncryptor, encryptedJson) {
+  return await new Promise((resolve, reject) => {
+    accessTokenEncryptor.decryptToJson(encryptedJson, (err, json) => {
+      if (err) return reject(err)
+      accessTokenEncryptor.encryptJson(json, (err, reEncryptedJson) => {
+        if (err) return reject(err)
+        resolve(reEncryptedJson)
+      })
+    })
+  })
+}
+
+/**
+ * @param {AccessTokenEncryptor} accessTokenEncryptor
+ * @param {Collection} collection
+ * @param {Object} paths
+ * @param {Object} queryOptions
+ * @return {Promise<{}>}
+ */
+async function reEncryptTokensInCollection({
+  accessTokenEncryptor,
+  collection,
+  paths,
+  queryOptions,
+}) {
+  const { collectionName } = collection
+  const stats = {}
+
+  let processed = 0
+  let updatedNUsers = 0
+  let lastLog = 0
+  const logProgress = () => {
+    if (DRY_RUN) {
+      console.warn(
+        `processed ${processed} | Would have updated ${updatedNUsers} users`
+      )
+    } else {
+      console.warn(`processed ${processed} | Updated ${updatedNUsers} users`)
+    }
+  }
+
+  const projection = { _id: 1 }
+  for (const path of Object.values(paths)) {
+    projection[path] = 1
+  }
+  const cursor = collection.find(
+    {},
+    {
+      ...queryOptions,
+      projection,
+    }
+  )
+
+  for await (const doc of cursor) {
+    processed++
+
+    let update = null
+    for (const [name, path] of Object.entries(paths)) {
+      const blob = _.get(doc, path)
+      if (!blob) continue
+      // Schema: LABEL-VERSION:SALT:CIPHERTEXT:IV
+      const [label] = blob.split(':')
+      let [, version] = label.split('-')
+      version = version || 'v2'
+
+      const key = [name, version, collectionName, path, label].join(':')
+      stats[key] = (stats[key] || 0) + 1
+
+      if (version === 'v2') {
+        update = update || {}
+        update[path] = await reEncryptTokens(accessTokenEncryptor, blob)
+      }
+    }
+
+    if (Date.now() - lastLog >= LOG_EVERY_IN_S * 1000) {
+      logProgress()
+      lastLog = Date.now()
+    }
+    if (update) {
+      updatedNUsers++
+
+      const { _id } = doc
+      if (DRY_RUN) {
+        console.log('Would upgrade tokens for user', _id, Object.keys(update))
+      } else {
+        console.log('Upgrading tokens for user', _id, Object.keys(update))
+        await collection.updateOne({ _id }, { $set: update })
+      }
+    }
+  }
+  logProgress()
+  formatTokenUsageStats(stats)
+}
+
+module.exports = {
+  reEncryptTokensInCollection,
+}

+ 9 - 0
libraries/access-token-encryptor/test/mocha-multi-reporters.cjs

@@ -0,0 +1,9 @@
+module.exports = {
+  reporterEnabled: 'spec, mocha-junit-reporter',
+  mochaJunitReporterReporterOptions: {
+    mochaFile: `reports/junit-mocha-${process.env.MOCHA_GREP}.xml`,
+    includePending: true,
+    jenkinsMode: true,
+    output: true,
+  },
+}

+ 13 - 0
libraries/access-token-encryptor/test/setup.js

@@ -0,0 +1,13 @@
+const chai = require('chai')
+const chaiAsPromised = require('chai-as-promised')
+const SandboxedModule = require('sandboxed-module')
+
+chai.use(chaiAsPromised)
+
+SandboxedModule.configure({
+  sourceTransformers: {
+    removeNodePrefix: function (source) {
+      return source.replace(/require\(['"]node:/g, "require('")
+    },
+  },
+})

+ 305 - 0
libraries/access-token-encryptor/test/unit/js/AccessTokenEncryptorTests.js

@@ -0,0 +1,305 @@
+const chai = require('chai')
+chai.should()
+const { expect } = chai
+const modulePath = '../../../index.js'
+const SandboxedModule = require('sandboxed-module')
+
+describe('AccessTokenEncryptor', function () {
+  beforeEach(function () {
+    this.testObject = { hello: 'world' }
+    this.encrypted2015 =
+      '2015.1:473a66fb5d816bc716f278ab819d88a5:+mTg7O9sgUND8pNQFG6h2GE='
+    this.encrypted2016 =
+      '2016.1:76a7d64a444ccee1a515b49c44844a69:m5YSkexUsLjcF4gLncm72+k='
+    this.encrypted2019 =
+      '2019.1:627143b2ab185a020c8720253a4c984e:7gnY6Ez3/Y3UWgLHLfBtJsE=:bf75cecb6aeea55b3c060e1122d2a82d'
+    this.encrypted2023 =
+      '2023.1-v3:a6dd3781dd6ce93a4134874b505a209c:9TdIDAc8V9SeR0ffSn63Jj4=:d8b2de0b733c81b949993dce229abb4c'
+    this.badLabel = 'xxxxxx:c7a39310056b694c:jQf+Uh5Den3JREtvc82GW5Q='
+    this.badKey = '2015.1:d7a39310056b694c:jQf+Uh5Den3JREtvc82GW5Q='
+    this.badCipherText = '2015.1:c7a39310056b694c:xQf+Uh5Den3JREtvc82GW5Q='
+    this.settings = {
+      cipherLabel: '2023.1-v3',
+      cipherPasswords: {
+        '2023.1-v3': '44444444444444444444444444444444444444',
+      },
+    }
+    this.AccessTokenEncryptor = SandboxedModule.require(modulePath, {
+      globals: {
+        Buffer,
+      },
+    })
+    this.encryptor = new this.AccessTokenEncryptor(this.settings)
+  })
+
+  describe('invalid settings', function () {
+    it('should flag missing label', function () {
+      expect(
+        () =>
+          new this.AccessTokenEncryptor({
+            cipherLabel: '',
+            cipherPasswords: { '': '' },
+          })
+      ).to.throw(/cipherLabel cannot be empty/)
+    })
+
+    it('should flag invalid label with colon', function () {
+      expect(
+        () =>
+          new this.AccessTokenEncryptor({
+            cipherLabel: '2023:1-v2',
+            cipherPasswords: { '2023:1-v2': '' },
+          })
+      ).to.throw(/colon/)
+    })
+
+    it('should flag missing password', function () {
+      expect(
+        () =>
+          new this.AccessTokenEncryptor({
+            cipherPasswords: { '2023.1-v3': '' },
+            cipherVersions: { '2023.1-v3': 'v3' },
+          })
+      ).to.throw(/cipherPasswords.+ missing/)
+      expect(
+        () =>
+          new this.AccessTokenEncryptor({
+            cipherLabel: '2023.1-v3',
+            cipherPasswords: { '2023.1-v3': undefined },
+          })
+      ).to.throw(/cipherPasswords.+ missing/)
+    })
+
+    it('should flag short password', function () {
+      expect(
+        () =>
+          new this.AccessTokenEncryptor({
+            cipherLabel: '2023.1-v3',
+            cipherPasswords: { '2023.1-v3': 'foo' },
+          })
+      ).to.throw(/cipherPasswords.+ too short/)
+    })
+
+    it('should flag missing version', function () {
+      expect(
+        () =>
+          new this.AccessTokenEncryptor({
+            cipherLabel: '2023.1',
+            cipherPasswords: { 2023.1: '11111111111111111111111111111111' },
+          })
+      ).to.throw(/must contain version suffix/)
+      expect(
+        () =>
+          new this.AccessTokenEncryptor({
+            cipherLabel: '2023.1-',
+            cipherPasswords: { '2023.1-': '11111111111111111111111111111111' },
+          })
+      ).to.throw(/must contain version suffix/)
+    })
+
+    it('should flag invalid version', function () {
+      expect(
+        () =>
+          new this.AccessTokenEncryptor({
+            cipherLabel: '2023.1-v0',
+            cipherPasswords: {
+              '2023.1-v0': '11111111111111111111111111111111',
+            },
+          })
+      ).to.throw(/unknown version/)
+    })
+
+    it('should flag unknown default scheme', function () {
+      expect(
+        () =>
+          new this.AccessTokenEncryptor({
+            cipherLabel: '2000.1-v3',
+            cipherPasswords: {
+              '2023.1-v3': '11111111111111111111111111111111',
+            },
+          })
+      ).to.throw(/unknown default cipherLabel/)
+    })
+  })
+
+  describe('sync', function () {
+    describe('encrypt', function () {
+      it('should encrypt the object', function (done) {
+        this.encryptor.encryptJson(this.testObject, (err, encrypted) => {
+          expect(err).to.be.null
+          encrypted.should.match(
+            /^2023.1-v3:[0-9a-f]{32}:[a-zA-Z0-9=+/]+:[0-9a-f]{32}$/
+          )
+          done()
+        })
+      })
+
+      it('should encrypt the object differently the next time', function (done) {
+        this.encryptor.encryptJson(this.testObject, (err, encrypted1) => {
+          expect(err).to.be.null
+          this.encryptor.encryptJson(this.testObject, (err, encrypted2) => {
+            expect(err).to.be.null
+            encrypted1.should.not.equal(encrypted2)
+            done()
+          })
+        })
+      })
+    })
+
+    describe('decrypt', function () {
+      it('should decrypt the string to get the same object', function (done) {
+        this.encryptor.encryptJson(this.testObject, (err, encrypted) => {
+          expect(err).to.be.null
+          this.encryptor.decryptToJson(encrypted, (err, decrypted) => {
+            expect(err).to.be.null
+            expect(decrypted).to.deep.equal(this.testObject)
+            done()
+          })
+        })
+      })
+
+      it('should not be able to decrypt 2015 string', function (done) {
+        this.encryptor.decryptToJson(this.encrypted2015, (err, decrypted) => {
+          expect(err).to.exist
+          expect(err.message).to.equal(
+            'unknown access-token-encryptor label 2015.1'
+          )
+          expect(decrypted).to.not.exist
+          done()
+        })
+      })
+
+      it('should not be able to decrypt a 2016 string', function (done) {
+        this.encryptor.decryptToJson(this.encrypted2016, (err, decrypted) => {
+          expect(err).to.exist
+          expect(err.message).to.equal(
+            'unknown access-token-encryptor label 2016.1'
+          )
+          expect(decrypted).to.not.exist
+          done()
+        })
+      })
+
+      it('should not be able to decrypt a 2019 string', function (done) {
+        this.encryptor.decryptToJson(this.encrypted2019, (err, decrypted) => {
+          expect(err).to.exist
+          expect(err.message).to.equal(
+            'unknown access-token-encryptor label 2019.1'
+          )
+          expect(decrypted).to.not.exist
+          done()
+        })
+      })
+
+      it('should decrypt an 2023 string to get the same object', function (done) {
+        this.encryptor.decryptToJson(this.encrypted2023, (err, decrypted) => {
+          expect(err).to.be.null
+          expect(decrypted).to.deep.equal(this.testObject)
+          done()
+        })
+      })
+
+      it('should return an error when decrypting an invalid label', function (done) {
+        this.encryptor.decryptToJson(this.badLabel, (err, decrypted) => {
+          expect(err).to.be.instanceof(Error)
+          expect(decrypted).to.be.undefined
+          done()
+        })
+      })
+
+      it('should return an error when decrypting an invalid key', function (done) {
+        this.encryptor.decryptToJson(this.badKey, (err, decrypted) => {
+          expect(err).to.be.instanceof(Error)
+          expect(decrypted).to.be.undefined
+          done()
+        })
+      })
+
+      it('should return an error when decrypting an invalid ciphertext', function (done) {
+        this.encryptor.decryptToJson(this.badCipherText, (err, decrypted) => {
+          expect(err).to.be.instanceof(Error)
+          expect(decrypted).to.be.undefined
+          done()
+        })
+      })
+    })
+  })
+
+  describe('async', function () {
+    describe('encrypt', function () {
+      it('should encrypt the object', async function () {
+        const encrypted = await this.encryptor.promises.encryptJson(
+          this.testObject
+        )
+        encrypted.should.match(
+          /^2023.1-v3:[0-9a-f]{32}:[a-zA-Z0-9=+/]+:[0-9a-f]{32}$/
+        )
+      })
+
+      it('should encrypt the object differently the next time', async function () {
+        const encrypted1 = await this.encryptor.promises.encryptJson(
+          this.testObject
+        )
+        const encrypted2 = await this.encryptor.promises.encryptJson(
+          this.testObject
+        )
+        encrypted1.should.not.equal(encrypted2)
+      })
+    })
+
+    describe('decrypt', function () {
+      it('should decrypt the string to get the same object', async function () {
+        const encrypted = await this.encryptor.promises.encryptJson(
+          this.testObject
+        )
+        const decrypted = await this.encryptor.promises.decryptToJson(encrypted)
+        expect(decrypted).to.deep.equal(this.testObject)
+      })
+
+      it('should not be able to decrypt 2015 string', async function () {
+        await expect(
+          this.encryptor.promises.decryptToJson(this.encrypted2015)
+        ).to.eventually.be.rejectedWith(
+          'unknown access-token-encryptor label 2015.1'
+        )
+      })
+
+      it('should not be able to decrypt a 2016 string', async function () {
+        await expect(
+          this.encryptor.promises.decryptToJson(this.encrypted2016)
+        ).to.be.rejectedWith('unknown access-token-encryptor label 2016.1')
+      })
+
+      it('should not be able to decrypt a 2019 string', async function () {
+        await expect(
+          this.encryptor.promises.decryptToJson(this.encrypted2019)
+        ).to.be.rejectedWith('unknown access-token-encryptor label 2019.1')
+      })
+
+      it('should decrypt an 2023 string to get the same object', async function () {
+        const decrypted = await this.encryptor.promises.decryptToJson(
+          this.encrypted2023
+        )
+        expect(decrypted).to.deep.equal(this.testObject)
+      })
+
+      it('should return an error when decrypting an invalid label', async function () {
+        await expect(
+          this.encryptor.promises.decryptToJson(this.badLabel)
+        ).to.be.rejectedWith('unknown access-token-encryptor label xxxxxx')
+      })
+
+      it('should return an error when decrypting an invalid key', async function () {
+        await expect(
+          this.encryptor.promises.decryptToJson(this.badKey)
+        ).to.be.rejectedWith('unknown access-token-encryptor label 2015.1')
+      })
+
+      it('should return an error when decrypting an invalid ciphertext', async function () {
+        await expect(
+          this.encryptor.promises.decryptToJson(this.badCipherText)
+        ).to.be.rejectedWith('unknown access-token-encryptor label 2015.1')
+      })
+    })
+  })
+})

+ 4 - 0
libraries/access-token-encryptor/tsconfig.json

@@ -0,0 +1,4 @@
+{
+  "extends": "../../tsconfig.backend.json",
+  "include": ["**/*.js", "**/*.cjs", "**/*.ts"]
+}

+ 160 - 0
libraries/eslint-plugin/french-typography-in-locales.js

@@ -0,0 +1,160 @@
+// French typographic spacing rules for JSON string values.
+// Per https://typographisme.net/post/Les-espaces-typographiques-et-le-web
+//   - NNBSP  before ? ! ;
+//   - NBSP   before :
+//   - NBSP   inside guillemets (after «, before ») — keeps the
+//     guillemet attached to its content so it cannot be orphaned at a
+//     line break
+//   - NNBSP  between digit groups (thousands separator)
+//   - NBSP   between a number and a following word/unit (50 Mo, 5 jours)
+//   - NBSP   before %
+//   - point médian "·" instead of parenthetical (e) for inclusive writing
+
+const NBSP = ' '
+const NNBSP = ' '
+
+function autoFix(value) {
+  let v = value
+  // Normalize whitespace before ? ! ; to NNBSP
+  v = v.replace(/\s*([?!;])/g, `${NNBSP}$1`)
+  v = v.replace(/([^\s])([?!;])/g, `$1${NNBSP}$2`)
+  // Normalize whitespace before : (after a letter, not before /) to NBSP
+  v = v.replace(/(\p{L})\s*:(?!\/)/gu, `$1${NBSP}:`)
+  // NBSP after «
+  v = v.replace(/«\s*/g, `«${NBSP}`)
+  // NBSP before »
+  v = v.replace(/\s*»/g, `${NBSP}»`)
+  // NNBSP between digits (thousands separator)
+  v = v.replace(/(\d)\s+(\d)/g, `$1${NNBSP}$2`)
+  // NBSP between digit and following letter (number + unit/word)
+  v = v.replace(/(\d)\s+(\p{L})/gu, `$1${NBSP}$2`)
+  // NBSP before %
+  v = v.replace(/(\d)\s*%/g, `$1${NBSP}%`)
+  return v
+}
+
+function lint(value) {
+  const violations = []
+  for (const m of value.matchAll(/(.)([?!;])/g)) {
+    if (m[1] !== NNBSP) {
+      violations.push({
+        message: `expected NNBSP before "${m[2]}", got ${JSON.stringify(m[1])}`,
+        fixable: true,
+      })
+    }
+  }
+  for (const m of value.matchAll(/(\p{L})(\s*):(?!\/)/gu)) {
+    if (m[2] !== NBSP) {
+      violations.push({
+        message: `expected NBSP before ":" after letter ${JSON.stringify(m[1])}, got ${JSON.stringify(m[2])}`,
+        fixable: true,
+      })
+    }
+  }
+  for (const m of value.matchAll(/«(.)/g)) {
+    if (m[1] !== NBSP) {
+      violations.push({
+        message: `expected NBSP after "«", got ${JSON.stringify(m[1])}`,
+        fixable: true,
+      })
+    }
+  }
+  for (const m of value.matchAll(/(.)»/g)) {
+    if (m[1] !== NBSP) {
+      violations.push({
+        message: `expected NBSP before "»", got ${JSON.stringify(m[1])}`,
+        fixable: true,
+      })
+    }
+  }
+  for (const m of value.matchAll(/(\d)(\s)(\d)/g)) {
+    if (m[2] !== NNBSP) {
+      violations.push({
+        message: `expected NNBSP between digits "${m[1]}${m[3]}", got ${JSON.stringify(m[2])}`,
+        fixable: true,
+      })
+    }
+  }
+  for (const m of value.matchAll(/(\d)(\s)(\p{L})/gu)) {
+    if (m[2] !== NBSP) {
+      violations.push({
+        message: `expected NBSP between digit "${m[1]}" and "${m[3]}", got ${JSON.stringify(m[2])}`,
+        fixable: true,
+      })
+    }
+  }
+  for (const m of value.matchAll(/(\d)(\s*)%/g)) {
+    if (m[2] !== NBSP) {
+      violations.push({
+        message: `expected NBSP before "%" after "${m[1]}", got ${JSON.stringify(m[2])}`,
+        fixable: true,
+      })
+    }
+  }
+  if (value.includes('(e)')) {
+    violations.push({
+      message:
+        'expected point médian "·" instead of "(e)" for inclusive writing',
+      fixable: false, // suggestion-only
+    })
+  }
+  return violations
+}
+
+module.exports = {
+  meta: {
+    type: 'problem',
+    fixable: 'code',
+    hasSuggestions: true,
+    docs: {
+      description:
+        'Enforce French typographic spacing in JSON string values (NNBSP before ? ! ;, NBSP before : and inside « », etc.).',
+    },
+    schema: [],
+  },
+  create(context) {
+    return {
+      Member(node) {
+        if (node.value.type !== 'String') return
+        const original = node.value.value
+        const violations = lint(original)
+        if (violations.length === 0) return
+
+        const fixed = autoFix(original)
+        const replacement = JSON.stringify(fixed)
+        const inclusiveSuggestion = original.includes('(e)')
+          ? JSON.stringify(original.replace(/\(e\)/g, '·e'))
+          : null
+
+        for (const v of violations) {
+          context.report({
+            node: node.value,
+            message: v.message,
+            ...(v.fixable && fixed !== original
+              ? {
+                  fix(fixer) {
+                    return fixer.replaceText(node.value, replacement)
+                  },
+                }
+              : {}),
+            ...(!v.fixable && inclusiveSuggestion
+              ? {
+                  suggest: [
+                    {
+                      desc: 'Replace "(e)" with "·e"',
+                      fix(fixer) {
+                        return fixer.replaceText(
+                          node.value,
+                          inclusiveSuggestion
+                        )
+                      },
+                    },
+                  ],
+                }
+              : {}),
+          })
+        }
+      },
+    }
+  },
+}

+ 25 - 0
libraries/eslint-plugin/index.js

@@ -0,0 +1,25 @@
+const pkg = require('./package.json')
+
+module.exports = {
+  meta: {
+    name: pkg.name,
+    version: pkg.version,
+  },
+  rules: {
+    'no-unnecessary-trans': require('./no-unnecessary-trans'),
+    'prefer-kebab-url': require('./prefer-kebab-url'),
+    'should-unescape-trans': require('./should-unescape-trans'),
+    'no-generated-editor-themes': require('./no-generated-editor-themes'),
+    'require-script-runner': require('./require-script-runner'),
+    'require-vi-doMock-valid-path': require('./require-vi-doMock-valid-path'),
+    'require-loading-label': require('./require-loading-label'),
+    'require-cio-snake-case-properties': require('./require-cio-snake-case-properties'),
+    'no-throw-in-callback': require('./no-throw-in-callback'),
+    'no-consecutive-spaces-in-locales': require('./no-consecutive-spaces-in-locales'),
+    'no-straight-apostrophes-in-locales': require('./no-straight-apostrophes-in-locales'),
+    'french-typography-in-locales': require('./french-typography-in-locales'),
+    'sorted-keys-in-locales': require('./sorted-keys-in-locales'),
+    'locale-variables-match-en': require('./locale-variables-match-en'),
+    'no-orphan-locale-keys': require('./no-orphan-locale-keys'),
+  },
+}

+ 93 - 0
libraries/eslint-plugin/locale-variables-match-en.js

@@ -0,0 +1,93 @@
+// Ensure variable placeholders (`__name__`) in non-en locale values match
+// those in the corresponding en.json key.
+//
+// Apply this rule to all non-en locale JSON files.
+
+const fs = require('node:fs')
+const Path = require('node:path')
+
+// Placeholders always available in translations (injected by the i18n layer
+// or globally defined as defaults).
+const GLOBALS = new Set(['__appName__'])
+
+// Keys whose translations are allowed to omit specific base placeholders.
+const IGNORE_NESTING_FOR = {
+  over_x_templates_easy_getting_started: ['__templates__'],
+  all_packages_and_templates: ['__templatesLink__'],
+}
+
+function extractPlaceholders(str) {
+  return Array.from(str.matchAll(/__.*?__/g), m => m[0])
+}
+
+const enCache = new Map()
+function loadEn(localesDir) {
+  if (enCache.has(localesDir)) return enCache.get(localesDir)
+  const path = Path.join(localesDir, 'en.json')
+  const data = JSON.parse(fs.readFileSync(path, 'utf8'))
+  enCache.set(localesDir, data)
+  return data
+}
+
+module.exports = {
+  meta: {
+    type: 'problem',
+    docs: {
+      description:
+        'Ensure variable placeholders in non-en locale values match the en.json base.',
+    },
+    schema: [],
+    messages: {
+      missing:
+        'Translation for key "{{key}}" is missing placeholder(s) {{placeholders}} present in en.json.',
+      extra:
+        'Translation for key "{{key}}" has placeholder(s) {{placeholders}} not present in en.json.',
+    },
+  },
+  create(context) {
+    const filename = context.filename
+    const localesDir = Path.dirname(filename)
+    if (Path.basename(filename) === 'en.json') return {}
+
+    let base
+    try {
+      base = loadEn(localesDir)
+    } catch {
+      return {}
+    }
+
+    return {
+      Member(node) {
+        if (node.value.type !== 'String') return
+        const key = node.name.value
+        if (!(key in base)) return // orphan key — covered by no-orphan-locale-keys
+
+        const basePlaceholders = extractPlaceholders(base[key])
+        const targetPlaceholders = extractPlaceholders(node.value.value)
+        const ignored = IGNORE_NESTING_FOR[key] || []
+
+        const missing = basePlaceholders.filter(
+          p => !targetPlaceholders.includes(p) && !ignored.includes(p)
+        )
+        const extra = targetPlaceholders.filter(
+          p => !basePlaceholders.includes(p) && !GLOBALS.has(p)
+        )
+
+        if (missing.length > 0) {
+          context.report({
+            node: node.value,
+            messageId: 'missing',
+            data: { key, placeholders: missing.join(', ') },
+          })
+        }
+        if (extra.length > 0) {
+          context.report({
+            node: node.value,
+            messageId: 'extra',
+            data: { key, placeholders: extra.join(', ') },
+          })
+        }
+      },
+    }
+  },
+}

+ 37 - 0
libraries/eslint-plugin/no-consecutive-spaces-in-locales.js

@@ -0,0 +1,37 @@
+// Reject runs of two or more consecutive whitespace characters in JSON string
+// values. Catches ASCII spaces, NBSP, NNBSP, tabs, and other Unicode whitespace.
+
+const CONSECUTIVE_WHITESPACE = /\s{2,}/
+
+module.exports = {
+  meta: {
+    type: 'problem',
+    fixable: 'code',
+    docs: {
+      description:
+        'Disallow runs of two or more consecutive whitespace characters in JSON string values (typically locale files).',
+    },
+    schema: [],
+    messages: {
+      consecutiveSpaces:
+        'Locale value contains a run of consecutive whitespace. Collapse to a single space.',
+    },
+  },
+  create(context) {
+    return {
+      Member(node) {
+        if (node.value.type !== 'String') return
+        const original = node.value.value
+        if (!CONSECUTIVE_WHITESPACE.test(original)) return
+        const fixed = original.replace(/\s{2,}/g, ' ')
+        context.report({
+          node: node.value,
+          messageId: 'consecutiveSpaces',
+          fix(fixer) {
+            return fixer.replaceText(node.value, JSON.stringify(fixed))
+          },
+        })
+      },
+    }
+  },
+}

+ 21 - 0
libraries/eslint-plugin/no-generated-editor-themes.js

@@ -0,0 +1,21 @@
+module.exports = {
+  meta: {
+    type: 'error',
+    docs: {
+      description:
+        'Prohibit CodeMirror themes that are generated in a function',
+    },
+  },
+  create(context) {
+    return {
+      ':matches(ArrowFunctionExpression, FunctionDeclaration, FunctionExpression) CallExpression > MemberExpression[object.name="EditorView"]:matches([property.name="theme"],[property.name="baseTheme"])'(
+        node
+      ) {
+        context.report({
+          node,
+          message: `EditorView.theme and EditorView.baseTheme each add CSS to the page for every instance of the theme. Store the theme in a variable and reuse it instead.`,
+        })
+      },
+    }
+  },
+}

+ 69 - 0
libraries/eslint-plugin/no-orphan-locale-keys.js

@@ -0,0 +1,69 @@
+// Detect translation keys in non-en locale files that don't exist in
+// en.json (orphans).
+
+const fs = require('node:fs')
+const Path = require('node:path')
+
+const enCache = new Map()
+function loadEnKeys(localesDir) {
+  if (enCache.has(localesDir)) return enCache.get(localesDir)
+  const path = Path.join(localesDir, 'en.json')
+  const data = JSON.parse(fs.readFileSync(path, 'utf8'))
+  const keys = new Set(Object.keys(data))
+  enCache.set(localesDir, keys)
+  return keys
+}
+
+module.exports = {
+  meta: {
+    type: 'problem',
+    fixable: 'code',
+    docs: {
+      description:
+        'Detect translation keys in non-en locale files that are not present in en.json.',
+    },
+    schema: [],
+    messages: {
+      orphan:
+        'Translation key "{{key}}" is not present in en.json (orphan key).',
+    },
+  },
+  create(context) {
+    const filename = context.filename
+    const localesDir = Path.dirname(filename)
+    if (Path.basename(filename) === 'en.json') return {}
+
+    let enKeys
+    try {
+      enKeys = loadEnKeys(localesDir)
+    } catch {
+      return {}
+    }
+
+    return {
+      'Document > Object'(node) {
+        const orphans = node.members.filter(m => !enKeys.has(m.name.value))
+        if (orphans.length === 0) return
+
+        const text = context.sourceCode.text
+        const parsed = JSON.parse(text)
+        for (const member of orphans) {
+          delete parsed[member.name.value]
+        }
+        const sortedRemaining = Object.keys(parsed).sort()
+        const cleaned = JSON.stringify(parsed, sortedRemaining, 2) + '\n'
+
+        for (const member of orphans) {
+          context.report({
+            node: member,
+            messageId: 'orphan',
+            data: { key: member.name.value },
+            fix(fixer) {
+              return fixer.replaceTextRange([0, text.length], cleaned)
+            },
+          })
+        }
+      },
+    }
+  },
+}

+ 36 - 0
libraries/eslint-plugin/no-straight-apostrophes-in-locales.js

@@ -0,0 +1,36 @@
+// Reject straight apostrophes (') in JSON string values. Straight apostrophes
+// in Angular templates can lead to XSS; use the right single quotation mark
+// ’ (U+2019) instead. See https://github.com/overleaf/issues/issues/4478
+
+module.exports = {
+  meta: {
+    type: 'problem',
+    fixable: 'code',
+    docs: {
+      description:
+        'Disallow straight apostrophes in JSON string values (typically locale files).',
+    },
+    schema: [],
+    messages: {
+      straightApostrophe:
+        "Locale value contains a straight apostrophe ('). Use the right single quotation mark ’ (U+2019) instead.",
+    },
+  },
+  create(context) {
+    return {
+      Member(node) {
+        if (node.value.type !== 'String') return
+        const original = node.value.value
+        if (!original.includes("'")) return
+        const fixed = original.replace(/'/g, '’')
+        context.report({
+          node: node.value,
+          messageId: 'straightApostrophe',
+          fix(fixer) {
+            return fixer.replaceText(node.value, JSON.stringify(fixed))
+          },
+        })
+      },
+    }
+  },
+}

+ 52 - 0
libraries/eslint-plugin/no-throw-in-callback.js

@@ -0,0 +1,52 @@
+const CALLBACK_PARAM_NAMES = new Set(['cb', 'callback', 'done', 'next'])
+
+function isCallbackParam(param) {
+  return (
+    param && param.type === 'Identifier' && CALLBACK_PARAM_NAMES.has(param.name)
+  )
+}
+
+module.exports = {
+  meta: {
+    type: 'error',
+    docs: {
+      description: 'Disallow throw statements inside callback-based functions',
+    },
+    messages: {
+      noThrowInCallback:
+        'Pass the error to the callback instead of throwing in callback-based code.',
+    },
+  },
+  create(context) {
+    // Stack tracks whether each enclosing function is a callback-style function.
+    // A callback-style function is non-async and has a last param named cb/callback/done/next.
+    const stack = []
+
+    function enterFunction(node) {
+      const params = node.params
+      const isCallback =
+        !node.async &&
+        params.length > 0 &&
+        isCallbackParam(params[params.length - 1])
+      stack.push(isCallback)
+    }
+
+    function exitFunction() {
+      stack.pop()
+    }
+
+    return {
+      FunctionDeclaration: enterFunction,
+      'FunctionDeclaration:exit': exitFunction,
+      FunctionExpression: enterFunction,
+      'FunctionExpression:exit': exitFunction,
+      ArrowFunctionExpression: enterFunction,
+      'ArrowFunctionExpression:exit': exitFunction,
+      ThrowStatement(node) {
+        if (stack[stack.length - 1]) {
+          context.report({ node, messageId: 'noThrowInCallback' })
+        }
+      },
+    }
+  },
+}

+ 43 - 0
libraries/eslint-plugin/no-unnecessary-trans.js

@@ -0,0 +1,43 @@
+module.exports = {
+  meta: {
+    type: 'problem',
+    fixable: 'code',
+    docs: {
+      description: 'Prohibit Trans with no components or values',
+    },
+  },
+  create(context) {
+    return {
+      'JSXOpeningElement[name.name="Trans"]'(node) {
+        const attributes = new Map(
+          node.attributes.map(attr => [attr.name.name, attr])
+        )
+
+        if (!attributes.has('components')) {
+          if (node.parent.children.length > 0) {
+            context.report({
+              node,
+              message: `Trans components must not have child elements`,
+            })
+          } else if (attributes.has('values')) {
+            context.report({
+              node,
+              message: `Use t('…') when there are no components`,
+            })
+          } else {
+            context.report({
+              node,
+              message: `Use t('…') when there are no components`,
+              fix(fixer) {
+                const i18nKey = attributes.get('i18nKey').value.value
+
+                // Note: Prettier can fix indentation
+                return fixer.replaceText(node.parent, `{t('${i18nKey}')}`)
+              },
+            })
+          }
+        }
+      },
+    }
+  },
+}

+ 20 - 0
libraries/eslint-plugin/package.json

@@ -0,0 +1,20 @@
+{
+  "name": "@overleaf/eslint-plugin",
+  "version": "0.1.0",
+  "author": "Overleaf (https://www.overleaf.com)",
+  "license": "AGPL-3.0-only",
+  "main": "index.js",
+  "dependencies": {
+    "lodash": "^4.18.1"
+  },
+  "devDependencies": {
+    "@eslint/json": "^2.0.0",
+    "@typescript-eslint/parser": "^8.59.4"
+  },
+  "peerDependencies": {
+    "eslint": "^10.4.0"
+  },
+  "scripts": {
+    "test": "node rules.test.js"
+  }
+}

+ 84 - 0
libraries/eslint-plugin/prefer-kebab-url-ignore.js

@@ -0,0 +1,84 @@
+// URL parts should be kebab-case, but we didn't have this rule in the past.
+// The ESLint rule `prefer-kebab-url` will ignore these "legacy" URL parts.
+
+const ignoreWords = {
+  snake: new Set([
+    'clear_saml_data',
+    'confirm_link',
+    'confirm_university_domain',
+    'create_recurly_account',
+    'current_history_content',
+    'current_user',
+    'default_email',
+    'disable_managed_users',
+    'doc_snapshot',
+    'enable_history_ranges_support',
+    'features_override',
+    'generate_password_reset_url',
+    'get_assignment',
+    'get_clone',
+    'health_check',
+    'institutional_emails',
+    'latest_template',
+    'link_after_saml_response',
+    'linked_file',
+    'metrics_segmentation',
+    'new_users',
+    'no_autostart_post_gateway',
+    'personal_info',
+    'planned_maintenance',
+    'refresh_features',
+    'register_admin',
+    'register_ldap_admin',
+    'register_saml_admin',
+    'restore_file',
+    'revert_file',
+    'saved_vers',
+    'send_test_email',
+    'session_maintenance',
+    'set_in_session',
+    'sign_in_to_link',
+    'split_test',
+    'sso_configuration_test',
+    'sso_email',
+    'sso_enrollment',
+    'track_changes',
+    'update_admin',
+    'user_details',
+  ]),
+  camel: new Set([
+    'addWorkflowScope',
+    'aiErrorAssistant',
+    'aiFeatureUsage',
+    'beginAuth',
+    'brandVariationId',
+    'closeEditor',
+    'completeRegistration',
+    'deactivateOldProjects',
+    'deletedSubscription',
+    'disconnectAllUsers',
+    'editingSession',
+    'emailSubscription',
+    'enableManagedUsers',
+    'externalCollaboration',
+    'flushProjectToTpds',
+    'indexAll',
+    'offboardManagedUser',
+    'openEditor',
+    'perfTest',
+    'pollDropboxForUser',
+    'resendInvite',
+    'resendManagedUserInvite',
+    'salesContactForm',
+    'showSupport',
+  ]),
+  other: new Set([
+    'Project',
+    'disableSSO',
+    'enableSSO',
+    'resendSSOLinkInvite',
+    'usersCSV',
+  ]),
+}
+
+module.exports = { ignoreWords }

+ 91 - 0
libraries/eslint-plugin/prefer-kebab-url.js

@@ -0,0 +1,91 @@
+const _ = require('lodash')
+const { ignoreWords } = require('./prefer-kebab-url-ignore')
+
+const removeTextBetweenBrackets = text => {
+  while (text.includes('[') || text.includes('(')) {
+    text = text.replaceAll(/\[[^[\]]*]/g, '')
+    text = text.replaceAll(/\([^()]*\)/g, '')
+  }
+  return text
+}
+
+const shouldIgnoreWord = str =>
+  str.includes(':') ||
+  str.includes('(') ||
+  str === '*' ||
+  str.match(/^[a-z0-9.]+$/) ||
+  ignoreWords.snake.has(str) ||
+  ignoreWords.camel.has(str) ||
+  ignoreWords.other.has(str)
+
+const getSuggestion = routePath => {
+  if (typeof routePath === 'string') {
+    const kebabed = routePath
+      .split('/')
+      .map(word => (shouldIgnoreWord(word) ? word : _.kebabCase(word)))
+      .join('/')
+    return kebabed === routePath ? null : `'${kebabed}'`
+  }
+
+  if (routePath instanceof RegExp) {
+    const words = removeTextBetweenBrackets(routePath.source).match(/[\w-]+/g)
+    if (!words) return routePath
+
+    let newSource = routePath.source
+    for (const word of words) {
+      if (!shouldIgnoreWord(word)) {
+        newSource = newSource.replaceAll(
+          new RegExp(`\\b${word}\\b`, 'g'),
+          _.kebabCase(word)
+        )
+      }
+    }
+
+    const kebabed = new RegExp(newSource, routePath.flags)
+    return kebabed.source.toString() === routePath.source.toString()
+      ? null
+      : kebabed
+  }
+}
+
+module.exports = {
+  meta: {
+    type: 'problem',
+    fixable: 'code',
+    hasSuggestions: true,
+    docs: {
+      description: 'Enforce using kebab-case for URL paths',
+    },
+  },
+  create: context => ({
+    CallExpression(node) {
+      if (
+        node.callee.type === 'MemberExpression' &&
+        node.arguments[0]?.type === 'Literal' &&
+        [/app/i, /router/i].some(callee =>
+          typeof callee === 'string'
+            ? node.callee.object.name === callee
+            : callee.test(node.callee.object.name)
+        ) &&
+        ['get', 'post', 'put', 'delete'].includes(node.callee.property.name)
+      ) {
+        const routePath = node.arguments[0].value
+
+        const suggestion = getSuggestion(routePath)
+
+        if (suggestion) {
+          context.report({
+            node: node.arguments[0],
+            message: 'Route path should be in kebab-case.',
+            suggest: [
+              {
+                desc: `Change to kebab-case: ${suggestion}`,
+                fix: fixer => fixer.replaceText(node.arguments[0], suggestion),
+              },
+            ],
+          })
+        }
+      }
+    },
+  }),
+}

+ 111 - 0
libraries/eslint-plugin/require-cio-snake-case-properties.js

@@ -0,0 +1,111 @@
+'use strict'
+
+const SNAKE_CASE_RE = /^[a-z][a-z0-9]*(_[a-z0-9]+)*$/
+
+function isSnakeCase(name) {
+  return SNAKE_CASE_RE.test(name)
+}
+
+function getStaticKeyName(property) {
+  if (property.computed) return null
+  if (property.key.type === 'Identifier') return property.key.name
+  if (property.key.type === 'Literal' && typeof property.key.value === 'string')
+    return property.key.value
+  return null
+}
+
+/**
+ * Check if a node is a call to CustomerIoHandler.updateUserAttributes()
+ * and return the attributes argument (2nd argument)
+ */
+function getUpdateUserAttributesArg(node) {
+  if (
+    node.callee.type === 'MemberExpression' &&
+    node.callee.object.type === 'Identifier' &&
+    node.callee.object.name === 'CustomerIoHandler' &&
+    node.callee.property.name === 'updateUserAttributes' &&
+    node.arguments[1]?.type === 'ObjectExpression'
+  ) {
+    return node.arguments[1]
+  }
+  return null
+}
+
+/**
+ * Check if a node is a call to Modules[.promises].hooks.fire('setUserProperties', ...)
+ * and return the attributes argument (3rd argument)
+ */
+function getSetUserPropertiesArg(node) {
+  const callee = node.callee
+  if (callee.type !== 'MemberExpression' || callee.property.name !== 'fire') {
+    return null
+  }
+
+  // Check first argument is 'setUserProperties'
+  if (
+    !node.arguments[0] ||
+    node.arguments[0].type !== 'Literal' ||
+    node.arguments[0].value !== 'setUserProperties'
+  ) {
+    return null
+  }
+
+  // Match: Modules.hooks.fire or Modules.promises.hooks.fire
+  const obj = callee.object
+  if (obj.type === 'MemberExpression' && obj.property.name === 'hooks') {
+    const parent = obj.object
+    // Modules.hooks
+    if (parent.type === 'Identifier' && parent.name === 'Modules') {
+      if (node.arguments[2]?.type === 'ObjectExpression') {
+        return node.arguments[2]
+      }
+    }
+    // Modules.promises.hooks
+    if (
+      parent.type === 'MemberExpression' &&
+      parent.property.name === 'promises' &&
+      parent.object.type === 'Identifier' &&
+      parent.object.name === 'Modules'
+    ) {
+      if (node.arguments[2]?.type === 'ObjectExpression') {
+        return node.arguments[2]
+      }
+    }
+  }
+
+  return null
+}
+
+module.exports = {
+  meta: {
+    type: 'problem',
+    docs: {
+      description:
+        'Enforce snake_case for Customer.io user property attribute names',
+    },
+  },
+  create(context) {
+    return {
+      CallExpression(node) {
+        const attrsNode =
+          getUpdateUserAttributesArg(node) || getSetUserPropertiesArg(node)
+        if (!attrsNode) return
+
+        for (const property of attrsNode.properties) {
+          if (property.type === 'SpreadElement') continue
+
+          const keyName = getStaticKeyName(property)
+          if (keyName === null) continue // skip computed/dynamic keys
+
+          if (!isSnakeCase(keyName)) {
+            context.report({
+              node: property.key,
+              message: `Customer.io attribute '{{name}}' must be in snake_case.`,
+              data: { name: keyName },
+            })
+          }
+        }
+      },
+    }
+  },
+}

+ 49 - 0
libraries/eslint-plugin/require-loading-label.js

@@ -0,0 +1,49 @@
+module.exports = {
+  meta: {
+    type: 'problem',
+    fixable: null,
+    docs: {
+      description:
+        'Require loadingLabel prop when isLoading is specified on OLButton',
+    },
+    schema: [],
+  },
+  create(context) {
+    return {
+      'JSXOpeningElement[name.name="OLButton"]'(node) {
+        const attributes = new Map(
+          node.attributes.map(attr => [attr.name?.name, attr])
+        )
+
+        const isLoadingAttr = attributes.get('isLoading')
+        const loadingLabelAttr = attributes.get('loadingLabel')
+
+        if (isLoadingAttr && !loadingLabelAttr) {
+          const isLoadingValue = isLoadingAttr.value
+
+          if (
+            !isLoadingValue ||
+            (isLoadingValue.type === 'JSXExpressionContainer' &&
+              isLoadingValue.expression.type === 'Literal' &&
+              isLoadingValue.expression.value === true)
+          ) {
+            context.report({
+              node: isLoadingAttr,
+              message:
+                'Button with isLoading prop must also specify loadingLabel',
+            })
+          } else if (
+            isLoadingValue.type === 'JSXExpressionContainer' &&
+            isLoadingValue.expression.type !== 'Literal'
+          ) {
+            context.report({
+              node: isLoadingAttr,
+              message:
+                'Button with isLoading prop must also specify loadingLabel',
+            })
+          }
+        }
+      },
+    }
+  },
+}

+ 28 - 0
libraries/eslint-plugin/require-script-runner.js

@@ -0,0 +1,28 @@
+module.exports = {
+  meta: {
+    type: 'suggestion',
+    docs: {
+      description: 'Require Script Runner for scripts',
+    },
+  },
+  create(context) {
+    let hasImport = false
+
+    return {
+      ImportDeclaration(node) {
+        if (node.source.value.endsWith('lib/ScriptRunner.mjs')) {
+          hasImport = true
+        }
+      },
+      'Program:exit'() {
+        if (!hasImport) {
+          context.report({
+            loc: { line: 1, column: 0 },
+            message:
+              'Please use Script Runner for scripts. Refer to the developer manual (https://manual.dev-overleaf.com/development/code/web_scripts/#monitor-script-execution-and-usage-with-script-runner) for more information.',
+          })
+        }
+      },
+    }
+  },
+}

+ 139 - 0
libraries/eslint-plugin/require-vi-doMock-valid-path.js

@@ -0,0 +1,139 @@
+const path = require('node:path')
+const fs = require('node:fs')
+
+module.exports = {
+  meta: {
+    type: 'problem',
+    docs: {
+      description: 'Ensure vi.doMock first argument is a resolvable path.',
+      category: 'Best Practices',
+      recommended: false,
+      url: '',
+    },
+    fixable: 'code',
+    hasSuggestions: true,
+    schema: [],
+    messages: {
+      unresolvablePath:
+        'The path "{{pathValue}}" in vi.doMock() cannot be resolved relative to the current file.',
+      notAStringLiteral:
+        'The first argument of vi.doMock() must be (or resolve to) a string literal representing a path.',
+      noArguments: 'vi.doMock() called with no arguments.',
+    },
+  },
+  create(context) {
+    const currentFilePath = context.filename
+    // ESLint can sometimes pass <text> or <input> for snippets not in a file
+    if (currentFilePath === '<text>' || currentFilePath === '<input>') {
+      return {}
+    }
+    const currentDirectory = path.dirname(currentFilePath)
+
+    function canResolve(modulePath) {
+      try {
+        require.resolve(path.resolve(currentDirectory, modulePath))
+        return true
+      } catch (e) {
+        const absolutePath = path.resolve(currentDirectory, modulePath)
+        const extensions = [
+          '',
+          '.js',
+          '.mjs',
+          '.ts',
+          '.jsx',
+          '.tsx',
+          '.json',
+          '.node',
+          '/index.js',
+          '/index.ts',
+        ] // Add common extensions
+        for (const ext of extensions) {
+          if (fs.existsSync(absolutePath + ext)) {
+            return true
+          }
+        }
+        return false
+      }
+    }
+
+    return {
+      CallExpression(node) {
+        if (
+          node.callee.type === 'MemberExpression' &&
+          node.callee.object.type === 'Identifier' &&
+          node.callee.object.name === 'vi' &&
+          node.callee.property.type === 'Identifier' &&
+          node.callee.property.name === 'doMock'
+        ) {
+          if (node.arguments.length === 0) {
+            context.report({
+              node,
+              messageId: 'noArguments',
+            })
+            return
+          }
+
+          const firstArg = node.arguments[0]
+          let pathValue = firstArg.value
+
+          if (
+            firstArg.type !== 'Literal' ||
+            typeof firstArg.value !== 'string'
+          ) {
+            if (firstArg.type === 'Identifier') {
+              const scope = context.sourceCode.getScope(node)
+              const variable = scope.variables.find(
+                v => v.name === firstArg.name
+              )
+              if (
+                variable &&
+                variable.defs.length > 0 &&
+                variable.defs[0].node.init &&
+                variable.defs[0].node.init.type === 'Literal' &&
+                typeof variable.defs[0].node.init.value === 'string'
+              ) {
+                pathValue = variable.defs[0].node.init.value
+                if (canResolve(pathValue)) {
+                  return
+                }
+                // If the first argument was a variable that didn't resolve then we can't auto-fix it
+              }
+            }
+            context.report({
+              node: firstArg,
+              messageId: 'notAStringLiteral',
+            })
+            return
+          }
+
+          if (!pathValue.startsWith('.')) {
+            return
+          }
+
+          if (!canResolve(pathValue)) {
+            const mjsPath = pathValue.replace('.js', '.mjs')
+            const additionalReportOptions = {}
+            if (canResolve(mjsPath)) {
+              additionalReportOptions.fix = fixer =>
+                fixer.replaceText(firstArg, `'${mjsPath}'`)
+              additionalReportOptions.suggest = [
+                {
+                  desc: `Replace with "${pathValue.replace('.js', '.mjs')}"`,
+                  fix: fixer => fixer.replaceText(firstArg, `'${mjsPath}'`),
+                },
+              ]
+            }
+            context.report({
+              node: firstArg,
+              messageId: 'unresolvablePath',
+              data: {
+                pathValue,
+              },
+              ...additionalReportOptions,
+            })
+          }
+        }
+      },
+    }
+  },
+}

+ 455 - 0
libraries/eslint-plugin/rules.test.js

@@ -0,0 +1,455 @@
+const { RuleTester } = require('eslint')
+const tsParser = require('@typescript-eslint/parser')
+const json = require('@eslint/json').default
+const noThrowInCallback = require('./no-throw-in-callback')
+const preferKebabUrl = require('./prefer-kebab-url')
+const noUnnecessaryTrans = require('./no-unnecessary-trans')
+const shouldUnescapeTrans = require('./should-unescape-trans')
+const noGeneratedEditorThemes = require('./no-generated-editor-themes')
+const viDoMockValidPath = require('./require-vi-doMock-valid-path')
+const requireCioSnakeCaseProperties = require('./require-cio-snake-case-properties')
+const noConsecutiveSpacesInLocales = require('./no-consecutive-spaces-in-locales')
+const noStraightApostrophesInLocales = require('./no-straight-apostrophes-in-locales')
+const frenchTypographyInLocales = require('./french-typography-in-locales')
+const sortedKeysInLocales = require('./sorted-keys-in-locales')
+
+const ruleTester = new RuleTester({
+  languageOptions: {
+    parser: tsParser,
+    ecmaVersion: 'latest',
+    parserOptions: { ecmaFeatures: { jsx: true } },
+  },
+})
+
+const jsonRuleTester = new RuleTester({
+  plugins: { json },
+  language: 'json/json',
+})
+
+ruleTester.run('prefer-kebab-url', preferKebabUrl, {
+  valid: [
+    { code: `app.get('/foo-bar')` },
+    { code: `app.get('/foo-bar/:id')` },
+    { code: `router.post('/foo-bar')` },
+    { code: `router.get('/foo-bar/:id/:name/:age')` },
+    { code: `webRouter.get('/foo-bar/:user_id/(ProjectName)/get-info')` },
+    { code: `webApp.post('/foo-bar/:user_id/(ProjectName)/get-info')` },
+    {
+      code: `router.get(/^\\/download\\/project\\/([^/]*)\\/output\\/output\\.pdf$/)`,
+    },
+    {
+      code: `webRouter.get(/^\\/project\\/([^/]*)\\/user\\/([0-9a-f]+)\\/build\\/([0-9a-f-]+)\\/output\\/(.*)$/)`,
+    },
+  ],
+  invalid: [
+    {
+      code: `app.get('/fooBar')`,
+      errors: [
+        { message: 'Route path should be in kebab-case.', suggestions: 1 },
+      ],
+    },
+    {
+      code: `app.get('/fooBar/:id')`,
+      errors: [
+        { message: 'Route path should be in kebab-case.', suggestions: 1 },
+      ],
+    },
+    {
+      code: `webRouter.get('/foo_bar/:id/FooBar/:name/fooBar')`,
+      errors: [
+        { message: 'Route path should be in kebab-case.', suggestions: 1 },
+      ],
+    },
+    {
+      code: `router.get(/^\\/downLoad\\/pro-ject\\/([^/]*)\\/OutPut\\/out-put\\.pdf$/)`,
+      errors: [
+        { message: 'Route path should be in kebab-case.', suggestions: 1 },
+      ],
+    },
+  ],
+})
+
+ruleTester.run('no-unnecessary-trans', noUnnecessaryTrans, {
+  valid: [
+    { code: `<Trans i18nKey="test" components={{ strong: <strong/> }}/>` },
+  ],
+  invalid: [
+    {
+      code: `<Trans i18nKey="test" values={{ test: 'foo '}}/>`,
+      errors: [{ message: `Use t('…') when there are no components` }],
+    },
+    {
+      code: `<Trans i18nKey="test" />`,
+      errors: [{ message: `Use t('…') when there are no components` }],
+      output: `{t('test')}`,
+    },
+  ],
+})
+
+ruleTester.run('should-unescape-trans', shouldUnescapeTrans, {
+  valid: [
+    {
+      code: `<Trans i18nKey="test" components={{ strong: <strong/> }}/>`,
+    },
+    {
+      code: `<Trans i18nKey="test" values={{ foo: 'bar' }} components={{ strong: <strong/> }} shouldUnescape tOptions={{ interpolation: { escapeValue: true } }}/>`,
+    },
+  ],
+  invalid: [
+    {
+      code: `<Trans i18nKey="test" values={{ foo: 'bar' }} components={{ strong: <strong/> }} />`,
+      errors: [{ message: 'Trans with values must have shouldUnescape' }],
+      output: `<Trans i18nKey="test" values={{ foo: 'bar' }}\nshouldUnescape components={{ strong: <strong/> }} />`,
+    },
+    {
+      code: `<Trans i18nKey="test" values={{ foo: 'bar' }} components={{ strong: <strong/> }} shouldUnescape />`,
+      errors: [
+        {
+          message:
+            'Trans with shouldUnescape must have tOptions.interpolation.escapeValue',
+        },
+      ],
+      output: `<Trans i18nKey="test" values={{ foo: 'bar' }} components={{ strong: <strong/> }} shouldUnescape\ntOptions={{ interpolation: { escapeValue: true } }} />`,
+    },
+  ],
+})
+
+const noGeneratedEditorThemesError =
+  'EditorView.theme and EditorView.baseTheme each add CSS to the page for every instance of the theme. Store the theme in a variable and reuse it instead.'
+ruleTester.run('no-generated-editor-themes', noGeneratedEditorThemes, {
+  valid: [
+    {
+      code: `EditorView.theme({ '.cm-editor': { color: 'black' } })`,
+    },
+    {
+      code: `const theme = EditorView.theme({ '.cm-editor': { color: 'black' } })`,
+    },
+  ],
+  invalid: [
+    {
+      code: `function createTheme() { return EditorView.theme({ '.cm-editor': { color: 'black' } }) }`,
+      errors: [
+        {
+          message: noGeneratedEditorThemesError,
+        },
+      ],
+    },
+    {
+      code: `() => EditorView.theme({ '.cm-editor': { color: 'black' } })`,
+      errors: [
+        {
+          message: noGeneratedEditorThemesError,
+        },
+      ],
+    },
+    {
+      code: `class Foo { createTheme() { return EditorView.theme({ '.cm-editor': { color: 'black' } }) } }`,
+      errors: [
+        {
+          message: noGeneratedEditorThemesError,
+        },
+      ],
+    },
+  ],
+})
+
+ruleTester.run('domock-require-valid-path', viDoMockValidPath, {
+  valid: [
+    {
+      code: 'vi.doMock("./require-vi-doMock-valid-path.js")',
+      filename: __filename,
+    },
+    {
+      code: 'const filename = "./require-vi-doMock-valid-path.js"; vi.doMock(filename);',
+      filename: __filename,
+    },
+  ],
+  invalid: [
+    {
+      code: "vi.doMock('./require-vi-doMock-valid-path2')",
+      filename: __filename,
+      errors: [
+        {
+          message:
+            'The path "./require-vi-doMock-valid-path2" in vi.doMock() cannot be resolved relative to the current file.',
+          suggestions: [],
+        },
+      ],
+    },
+    {
+      code: 'const filename = "./require-vi-doMock-valid-path2.js"; vi.doMock(filename);',
+      filename: __filename,
+      errors: [
+        {
+          message:
+            'The first argument of vi.doMock() must be (or resolve to) a string literal representing a path.',
+          suggestions: [],
+        },
+      ],
+    },
+  ],
+})
+
+ruleTester.run(
+  'require-cio-snake-case-properties',
+  requireCioSnakeCaseProperties,
+  {
+    valid: [
+      // updateUserAttributes with snake_case keys
+      {
+        code: `CustomerIoHandler.updateUserAttributes(userId, { plan_type: 'free', group_size: 10 })`,
+      },
+      // Modules.promises.hooks.fire with snake_case keys
+      {
+        code: `Modules.promises.hooks.fire('setUserProperties', userId, { plan_type: 'free', last_active: 123 })`,
+      },
+      // Modules.hooks.fire with snake_case keys
+      {
+        code: `Modules.hooks.fire('setUserProperties', userId, { plan_type: 'free' })`,
+      },
+      // Single-word keys are valid snake_case
+      {
+        code: `CustomerIoHandler.updateUserAttributes(userId, { email: 'a@b.com', role: 'admin' })`,
+      },
+      // Computed/dynamic keys are skipped
+      {
+        code: `CustomerIoHandler.updateUserAttributes(userId, { [dynamicKey]: true })`,
+      },
+      // Spread elements are skipped
+      {
+        code: `CustomerIoHandler.updateUserAttributes(userId, { ...existingAttrs })`,
+      },
+      // Unrelated function calls are not checked
+      {
+        code: `SomeOtherHandler.updateUserAttributes(userId, { camelCase: true })`,
+      },
+      // fire() with a different event name is not checked
+      {
+        code: `Modules.promises.hooks.fire('someOtherEvent', userId, { camelCase: true })`,
+      },
+    ],
+    invalid: [
+      // camelCase key in updateUserAttributes
+      {
+        code: `CustomerIoHandler.updateUserAttributes(userId, { planType: 'free' })`,
+        errors: [
+          {
+            message: `Customer.io attribute 'planType' must be in snake_case.`,
+          },
+        ],
+      },
+      // kebab-case string key
+      {
+        code: `CustomerIoHandler.updateUserAttributes(userId, { 'plan-type': 'free' })`,
+        errors: [
+          {
+            message: `Customer.io attribute 'plan-type' must be in snake_case.`,
+          },
+        ],
+      },
+      // PascalCase key
+      {
+        code: `CustomerIoHandler.updateUserAttributes(userId, { PlanType: 'free' })`,
+        errors: [
+          {
+            message: `Customer.io attribute 'PlanType' must be in snake_case.`,
+          },
+        ],
+      },
+      // camelCase in Modules.promises.hooks.fire
+      {
+        code: `Modules.promises.hooks.fire('setUserProperties', userId, { planType: 'free' })`,
+        errors: [
+          {
+            message: `Customer.io attribute 'planType' must be in snake_case.`,
+          },
+        ],
+      },
+      // camelCase in Modules.hooks.fire
+      {
+        code: `Modules.hooks.fire('setUserProperties', userId, { planType: 'free' })`,
+        errors: [
+          {
+            message: `Customer.io attribute 'planType' must be in snake_case.`,
+          },
+        ],
+      },
+      // Multiple invalid keys report multiple errors
+      {
+        code: `CustomerIoHandler.updateUserAttributes(userId, { planType: 'free', groupSize: 10, plan_term: 'annual' })`,
+        errors: [
+          {
+            message: `Customer.io attribute 'planType' must be in snake_case.`,
+          },
+          {
+            message: `Customer.io attribute 'groupSize' must be in snake_case.`,
+          },
+        ],
+      },
+    ],
+  }
+)
+
+const noThrowInCallbackMessage =
+  'Pass the error to the callback instead of throwing in callback-based code.'
+ruleTester.run('no-throw-in-callback', noThrowInCallback, {
+  valid: [
+    // Calling the callback with an error is fine
+    { code: `function foo(cb) { cb(new Error()) }` },
+    // async functions may throw (they return a rejected promise)
+    { code: `async function foo(cb) { throw new Error() }` },
+    // Last param not a callback name — not a callback-style function
+    { code: `function foo(data) { throw new Error() }` },
+    // No params at all
+    { code: `function foo() { throw new Error() }` },
+    // throw inside a nested non-callback function is fine
+    { code: `function foo(cb) { [1].map(function() { throw new Error() }) }` },
+    // throw inside a nested async arrow is fine
+    { code: `function foo(cb) { [1].map(async () => { throw new Error() }) }` },
+  ],
+  invalid: [
+    {
+      code: `function foo(cb) { throw new Error() }`,
+      errors: [{ message: noThrowInCallbackMessage }],
+    },
+    {
+      code: `function foo(callback) { throw new Error() }`,
+      errors: [{ message: noThrowInCallbackMessage }],
+    },
+    {
+      code: `function foo(done) { throw new Error() }`,
+      errors: [{ message: noThrowInCallbackMessage }],
+    },
+    {
+      code: `function foo(next) { throw new Error() }`,
+      errors: [{ message: noThrowInCallbackMessage }],
+    },
+    {
+      code: `function foo(data, cb) { throw new Error() }`,
+      errors: [{ message: noThrowInCallbackMessage }],
+    },
+    {
+      code: `const foo = (cb) => { throw new Error() }`,
+      errors: [{ message: noThrowInCallbackMessage }],
+    },
+    // throw in a nested callback-style function inside another callback function
+    {
+      code: `function foo(cb) { bar(function(done) { throw new Error() }) }`,
+      errors: [{ message: noThrowInCallbackMessage }],
+    },
+  ],
+})
+
+jsonRuleTester.run(
+  'no-consecutive-spaces-in-locales',
+  noConsecutiveSpacesInLocales,
+  {
+    valid: [
+      { code: '{ "key": "one space" }' },
+      { code: '{ "key": "no whitespace" }' },
+    ],
+    invalid: [
+      {
+        code: '{ "key": "two  spaces" }',
+        errors: [{ messageId: 'consecutiveSpaces' }],
+        output: '{ "key": "two spaces" }',
+      },
+      {
+        code: '{ "key": "three   spaces" }',
+        errors: [{ messageId: 'consecutiveSpaces' }],
+        output: '{ "key": "three spaces" }',
+      },
+      {
+        // \t then space → two consecutive whitespace chars
+        code: '{ "key": "tab\\t and" }',
+        errors: [{ messageId: 'consecutiveSpaces' }],
+        output: '{ "key": "tab and" }',
+      },
+    ],
+  }
+)
+
+jsonRuleTester.run(
+  'no-straight-apostrophes-in-locales',
+  noStraightApostrophesInLocales,
+  {
+    valid: [
+      { code: '{ "key": "no apostrophe" }' },
+      { code: '{ "key": "it’s curly" }' },
+    ],
+    invalid: [
+      {
+        code: `{ "key": "it's straight" }`,
+        errors: [{ messageId: 'straightApostrophe' }],
+        output: '{ "key": "it’s straight" }',
+      },
+    ],
+  }
+)
+
+jsonRuleTester.run('sorted-keys-in-locales', sortedKeysInLocales, {
+  valid: [
+    { code: '{\n  "a": "1",\n  "b": "2"\n}\n' },
+    { code: '{}' },
+    { code: '{ "only": "one" }' },
+  ],
+  invalid: [
+    {
+      code: '{\n  "b": "2",\n  "a": "1"\n}\n',
+      errors: [{ messageId: 'unsorted' }],
+      output: '{\n  "a": "1",\n  "b": "2"\n}\n',
+    },
+  ],
+})
+
+jsonRuleTester.run('french-typography-in-locales', frenchTypographyInLocales, {
+  valid: [
+    { code: '{ "key": "Bonjour ?" }' },
+    { code: '{ "key": "Liste :" }' },
+    { code: '{ "key": "« contenu »" }' },
+    { code: '{ "key": "abc 123" }' },
+    { code: '{ "key": "10 %" }' },
+  ],
+  invalid: [
+    {
+      code: '{ "key": "Bonjour?" }',
+      errors: 1,
+      output: '{ "key": "Bonjour ?" }',
+    },
+    {
+      code: '{ "key": "Bonjour ?" }',
+      errors: 1,
+      output: '{ "key": "Bonjour ?" }',
+    },
+    {
+      code: '{ "key": "Liste:" }',
+      errors: 1,
+      output: '{ "key": "Liste :" }',
+    },
+    {
+      code: '{ "key": "«contenu»" }',
+      errors: 2,
+      output: '{ "key": "« contenu »" }',
+    },
+    {
+      code: '{ "key": "10%" }',
+      errors: 1,
+      output: '{ "key": "10 %" }',
+    },
+    {
+      code: '{ "key": "sûr(e)" }',
+      errors: [
+        {
+          message:
+            'expected point médian "·" instead of "(e)" for inclusive writing',
+          suggestions: [
+            {
+              desc: 'Replace "(e)" with "·e"',
+              output: '{ "key": "sûr·e" }',
+            },
+          ],
+        },
+      ],
+    },
+  ],
+})

+ 60 - 0
libraries/eslint-plugin/should-unescape-trans.js

@@ -0,0 +1,60 @@
+module.exports = {
+  meta: {
+    type: 'problem',
+    fixable: 'code',
+    docs: {
+      description: 'Ensure that Trans with values has shouldUnescape',
+    },
+  },
+  create(context) {
+    return {
+      'JSXOpeningElement[name.name="Trans"]'(node) {
+        const attributes = new Map(
+          node.attributes.map(attr => [attr.name.name, attr])
+        )
+
+        if (attributes.has('values') && !attributes.has('shouldUnescape')) {
+          context.report({
+            node,
+            message: 'Trans with values must have shouldUnescape',
+            fix(fixer) {
+              return fixer.insertTextAfter(
+                attributes.get('values'),
+                '\nshouldUnescape' // Note: Prettier can fix indentation
+              )
+            },
+          })
+        }
+
+        if (attributes.has('values') && attributes.has('shouldUnescape')) {
+          const tOptions = attributes.get('tOptions')
+          if (!tOptions) {
+            context.report({
+              node,
+              message:
+                'Trans with shouldUnescape must have tOptions.interpolation.escapeValue',
+              fix(fixer) {
+                return fixer.insertTextAfter(
+                  attributes.get('shouldUnescape'),
+                  '\ntOptions={{ interpolation: { escapeValue: true } }}' // Note: Prettier can fix indentation
+                )
+              },
+            })
+          } else {
+            const property = tOptions.value.expression.properties
+              .find(p => p.key.name === 'interpolation')
+              ?.value.properties.find(p => p.key.name === 'escapeValue')
+
+            if (property?.value.value !== true) {
+              context.report({
+                node,
+                message:
+                  'Trans with shouldUnescape must have tOptions.interpolation.escapeValue set to true',
+              })
+            }
+          }
+        }
+      },
+    }
+  },
+}

+ 43 - 0
libraries/eslint-plugin/sorted-keys-in-locales.js

@@ -0,0 +1,43 @@
+// Enforce alphabetically sorted top-level keys in JSON files.
+
+module.exports = {
+  meta: {
+    type: 'problem',
+    fixable: 'code',
+    docs: {
+      description:
+        'Require top-level keys to be sorted alphabetically in JSON files (typically locale files).',
+    },
+    schema: [],
+    messages: {
+      unsorted:
+        'Top-level keys are not sorted alphabetically. Key "{{key}}" should come before "{{predecessor}}".',
+    },
+  },
+  create(context) {
+    return {
+      'Document > Object'(node) {
+        const members = node.members
+        for (let i = 1; i < members.length; i++) {
+          const prev = members[i - 1].name.value
+          const curr = members[i].name.value
+          if (curr < prev) {
+            const text = context.sourceCode.text
+            const parsed = JSON.parse(text)
+            const sortedKeys = Object.keys(parsed).sort()
+            const sorted = JSON.stringify(parsed, sortedKeys, 2) + '\n'
+            context.report({
+              node: members[i],
+              messageId: 'unsorted',
+              data: { key: curr, predecessor: prev },
+              fix(fixer) {
+                return fixer.replaceTextRange([0, text.length], sorted)
+              },
+            })
+            return // one violation per file is enough; the fix re-sorts everything
+          }
+        }
+      },
+    }
+  },
+}

+ 4 - 0
libraries/eslint-plugin/tsconfig.json

@@ -0,0 +1,4 @@
+{
+  "extends": "../../tsconfig.backend.json",
+  "include": ["**/*.js"]
+}

+ 13 - 0
libraries/fetch-utils/.mocharc.cjs

@@ -0,0 +1,13 @@
+let reporterOptions = {}
+if (process.env.CI) {
+  reporterOptions = {
+    reporter: require.resolve('mocha-multi-reporters'),
+    'reporter-options': ['configFile=./test/mocha-multi-reporters.cjs'],
+  }
+}
+const all = {
+  require: 'test/setup.js',
+  ...reporterOptions,
+}
+
+module.exports = all

+ 1 - 0
libraries/fetch-utils/.nvmrc

@@ -0,0 +1 @@
+24.14.1

+ 59 - 0
libraries/fetch-utils/Makefile

@@ -0,0 +1,59 @@
+# Run the test commands in the scope of the monorepo.
+# Eslint and prettier (plus some configs) are on the root.
+RUN_LINTING = ../../bin/run -w /overleaf/libraries/fetch-utils monorepo yarn run --silent
+RUN_LINTING_MONOREPO = ../../bin/run monorepo yarn run --silent
+
+WITH_CACHE_FOLDER = \
+	lint \
+	lint_ci \
+	lint_fix \
+	format \
+	format_ci \
+	format_fix \
+	typecheck \
+	typecheck_ci \
+
+$(WITH_CACHE_FOLDER): ../../node_modules/.cache/prettier/
+../../node_modules/.cache/prettier/:
+	mkdir -p $@
+
+$(WITH_CACHE_FOLDER): ../../node_modules/.cache/eslint/
+../../node_modules/.cache/eslint/:
+	mkdir -p $@
+
+format:
+	$(RUN_LINTING_MONOREPO) format libraries/fetch-utils
+
+format_ci:
+	$(RUN_LINTING_MONOREPO) format libraries/fetch-utils
+
+format_fix:
+	$(RUN_LINTING_MONOREPO) format:fix libraries/fetch-utils
+
+lint:
+	$(RUN_LINTING) lint
+
+lint_ci:
+	-$(RUN_LINTING) lint --format json --output-file reports/eslint.json
+	sed -i 's_"filePath":"/overleaf_"filePath":"$(MONOREPO)_g' reports/eslint.json
+
+lint_fix:
+	$(RUN_LINTING) lint:fix
+
+typecheck:
+	$(RUN_LINTING) types:check
+
+typecheck_ci:
+	$(RUN_LINTING) types:check
+
+test: test_unit
+test_unit:
+ifneq (,$(wildcard test/unit))
+	$(RUN_LINTING) test:unit
+endif
+
+test: test_acceptance
+test_acceptance:
+ifneq (,$(wildcard test/acceptance))
+	$(RUN_LINTING) test:acceptance
+endif

+ 9 - 0
libraries/fetch-utils/buildscript.txt

@@ -0,0 +1,9 @@
+fetch-utils
+--dependencies=None
+--env-add=
+--env-pass-through=
+--esmock-loader=False
+--is-library=True
+--node-version=24.14.1
+--pipeline-owner=32
+--public-repo=False

+ 354 - 0
libraries/fetch-utils/index.js

@@ -0,0 +1,354 @@
+const _ = require('lodash')
+const { Readable } = require('node:stream')
+const OError = require('@overleaf/o-error')
+const fetch = require('node-fetch')
+const http = require('node:http')
+const https = require('node:https')
+
+let logger
+
+function setLogger(loggerInstance) {
+  logger = loggerInstance
+}
+
+/**
+ * @import { Response } from 'node-fetch'
+ */
+
+/**
+ * Make a request and return the parsed JSON response.
+ *
+ * @param {string | URL} url - request URL
+ * @param {any} [opts] - fetch options
+ * @return {Promise<any>} the parsed JSON response
+ * @throws {RequestFailedError} if the response has a failure status code
+ */
+async function fetchJson(url, opts = {}) {
+  const { json } = await fetchJsonWithResponse(url, opts)
+  return json
+}
+
+async function fetchJsonWithResponse(url, opts = {}) {
+  const { fetchOpts, detachSignal } = parseOpts(opts, url)
+  fetchOpts.headers = fetchOpts.headers ?? {}
+  fetchOpts.headers.Accept = fetchOpts.headers.Accept ?? 'application/json'
+
+  const response = await performRequest(url, fetchOpts, detachSignal)
+  if (!response.ok) {
+    const body = await maybeGetResponseBody(response)
+    throw new RequestFailedError(url, opts, response, body)
+  }
+
+  const json = await response.json()
+  return { json, response }
+}
+
+/**
+ * Make a request and return a stream.
+ *
+ * If the response body is destroyed, the request is aborted.
+ *
+ * @param {string | URL} url - request URL
+ * @param {any} [opts] - fetch options
+ * @return {Promise<Readable>}
+ * @throws {RequestFailedError} if the response has a failure status code
+ */
+async function fetchStream(url, opts = {}) {
+  const { stream } = await fetchStreamWithResponse(url, opts)
+  return stream
+}
+
+async function fetchStreamWithResponse(url, opts = {}) {
+  const { fetchOpts, abortController, detachSignal } = parseOpts(opts, url)
+  const response = await performRequest(url, fetchOpts, detachSignal)
+
+  if (!response.ok) {
+    const body = await maybeGetResponseBody(response)
+    throw new RequestFailedError(url, opts, response, body)
+  }
+
+  abortOnDestroyedResponse(abortController, response)
+
+  const stream = response.body
+  return { stream, response }
+}
+
+/**
+ * Make a request and discard the response.
+ *
+ * @param {string | URL} url - request URL
+ * @param {any} [opts] - fetch options
+ * @return {Promise<Response>}
+ * @throws {RequestFailedError} if the response has a failure status code
+ */
+async function fetchNothing(url, opts = {}) {
+  const { fetchOpts, detachSignal } = parseOpts(opts, url)
+  const response = await performRequest(url, fetchOpts, detachSignal)
+  if (!response.ok) {
+    const body = await maybeGetResponseBody(response)
+    throw new RequestFailedError(url, opts, response, body)
+  }
+  await discardResponseBody(response)
+  return response
+}
+
+/**
+ * Make a request and extract the redirect from the response.
+ *
+ * @param {string | URL} url - request URL
+ * @param {any} [opts] - fetch options
+ * @return {Promise<string>}
+ * @throws {RequestFailedError} if the response has a non redirect status code or missing Location header
+ */
+async function fetchRedirect(url, opts = {}) {
+  const { location } = await fetchRedirectWithResponse(url, opts)
+  return location
+}
+
+/**
+ * Make a request and extract the redirect from the response.
+ *
+ * @param {string | URL} url - request URL
+ * @param {object} opts - fetch options
+ * @return {Promise<{location: string, response: Response}>}
+ * @throws {RequestFailedError} if the response has a non redirect status code or missing Location header
+ */
+async function fetchRedirectWithResponse(url, opts = {}) {
+  const { fetchOpts, detachSignal } = parseOpts(opts, url)
+  fetchOpts.redirect = 'manual'
+  const response = await performRequest(url, fetchOpts, detachSignal)
+  if (response.status < 300 || response.status >= 400) {
+    const body = await maybeGetResponseBody(response)
+    throw new RequestFailedError(url, opts, response, body)
+  }
+  const location = response.headers.get('Location')
+  if (!location) {
+    const body = await maybeGetResponseBody(response)
+    throw new RequestFailedError(url, opts, response, body).withCause(
+      new OError('missing Location response header on 3xx response', {
+        headers: Object.fromEntries(response.headers.entries()),
+      })
+    )
+  }
+  await discardResponseBody(response)
+  return { location, response }
+}
+
+/**
+ * Make a request and return a string.
+ *
+ * @param {string | URL} url - request URL
+ * @param {any} [opts] - fetch options
+ * @return {Promise<string>}
+ * @throws {RequestFailedError} if the response has a failure status code
+ */
+async function fetchString(url, opts = {}) {
+  const { body } = await fetchStringWithResponse(url, opts)
+  return body
+}
+
+async function fetchStringWithResponse(url, opts = {}) {
+  const { fetchOpts, detachSignal } = parseOpts(opts, url)
+  const response = await performRequest(url, fetchOpts, detachSignal)
+  if (!response.ok) {
+    const body = await maybeGetResponseBody(response)
+    throw new RequestFailedError(url, opts, response, body)
+  }
+  const body = await response.text()
+  return { body, response }
+}
+
+class RequestFailedError extends OError {
+  constructor(url, opts, response, body) {
+    super('request failed', {
+      url,
+      method: opts.method ?? 'GET',
+      status: response.status,
+    })
+
+    this.response = response
+    if (body != null) {
+      this.body = body
+    }
+  }
+}
+
+function parseOpts(opts, url) {
+  const fetchOpts = _.omit(opts, ['json', 'signal', 'basicAuth'])
+  if (opts.json) {
+    setupJsonBody(fetchOpts, opts.json)
+  }
+  if (opts.basicAuth) {
+    setupBasicAuth(fetchOpts, opts.basicAuth)
+  }
+
+  const abortController = new AbortController()
+  fetchOpts.signal = abortController.signal
+  let detachSignal
+  if (opts.signal) {
+    detachSignal = abortOnSignal(abortController, opts.signal)
+  } else {
+    let overTimeoutStart
+    const stack = new Error().stack
+    const timeout = setTimeout(() => {
+      overTimeoutStart = process.hrtime.bigint()
+    }, 120000)
+    detachSignal = () => {
+      clearTimeout(timeout)
+      if (overTimeoutStart && logger) {
+        logger.warn(
+          {
+            url,
+            method: opts.method ?? 'GET',
+            overTimeoutMs:
+              Number(process.hrtime.bigint() - overTimeoutStart) / 1e6,
+            stack,
+          },
+          'Fetch request did not complete within 120 seconds'
+        )
+      }
+    }
+  }
+  if (opts.body instanceof Readable) {
+    abortOnDestroyedRequest(abortController, fetchOpts.body)
+  }
+  return { fetchOpts, abortController, detachSignal }
+}
+
+function setupJsonBody(fetchOpts, json) {
+  fetchOpts.body = JSON.stringify(json)
+  fetchOpts.headers = fetchOpts.headers ?? {}
+  fetchOpts.headers['Content-Type'] = 'application/json'
+}
+
+function setupBasicAuth(fetchOpts, basicAuth) {
+  fetchOpts.headers = fetchOpts.headers ?? {}
+  fetchOpts.headers.Authorization =
+    'Basic ' +
+    Buffer.from(`${basicAuth.user}:${basicAuth.password}`).toString('base64')
+}
+
+function abortOnSignal(abortController, signal) {
+  const listener = () => {
+    abortController.abort(signal.reason)
+  }
+  if (signal.aborted) {
+    abortController.abort(signal.reason)
+  }
+  signal.addEventListener('abort', listener)
+  return () => {
+    signal.removeEventListener('abort', listener)
+  }
+}
+
+function abortOnDestroyedRequest(abortController, stream) {
+  stream.on('close', () => {
+    if (!stream.readableEnded) {
+      abortController.abort()
+    }
+  })
+}
+
+function abortOnDestroyedResponse(abortController, response) {
+  response.body.on('close', () => {
+    if (!response.bodyUsed) {
+      abortController.abort()
+    }
+  })
+}
+
+async function performRequest(url, fetchOpts, detachSignal) {
+  let response
+  try {
+    response = await fetch(url, fetchOpts)
+  } catch (err) {
+    detachSignal()
+    if (fetchOpts.body instanceof Readable) {
+      fetchOpts.body.destroy()
+    }
+    throw OError.tag(err, err.message, {
+      url,
+      method: fetchOpts.method ?? 'GET',
+    })
+  }
+  response.body.on('close', detachSignal)
+  if (fetchOpts.body instanceof Readable) {
+    response.body.on('close', () => {
+      if (!fetchOpts.body.readableEnded) {
+        fetchOpts.body.destroy()
+      }
+    })
+  }
+  return response
+}
+
+async function discardResponseBody(response) {
+  // eslint-disable-next-line no-unused-vars
+  for await (const chunk of response.body) {
+    // discard the body
+  }
+}
+
+/**
+ * @param {Response} response
+ */
+async function maybeGetResponseBody(response) {
+  try {
+    return await response.text()
+  } catch (err) {
+    return null
+  }
+}
+
+// Define custom http and https agents with support for connect timeouts
+
+class ConnectTimeoutError extends OError {
+  constructor(options) {
+    super('connect timeout', options)
+  }
+}
+
+function withTimeout(createConnection, options, callback) {
+  if (options.connectTimeout) {
+    // Wrap createConnection in a timeout
+    const timer = setTimeout(() => {
+      socket.destroy(new ConnectTimeoutError(options))
+    }, options.connectTimeout)
+    const socket = createConnection(options, (err, stream) => {
+      clearTimeout(timer)
+      callback(err, stream)
+    })
+    return socket
+  } else {
+    // Fallback to default createConnection
+    return createConnection(options, callback)
+  }
+}
+
+class CustomHttpAgent extends http.Agent {
+  createConnection(options, callback) {
+    return withTimeout(super.createConnection.bind(this), options, callback)
+  }
+}
+class CustomHttpsAgent extends https.Agent {
+  createConnection(options, callback) {
+    return withTimeout(super.createConnection.bind(this), options, callback)
+  }
+}
+
+module.exports = {
+  fetchJson,
+  fetchJsonWithResponse,
+  fetchStream,
+  fetchStreamWithResponse,
+  fetchNothing,
+  fetchRedirect,
+  fetchRedirectWithResponse,
+  fetchString,
+  fetchStringWithResponse,
+  RequestFailedError,
+  ConnectTimeoutError,
+  CustomHttpAgent,
+  CustomHttpsAgent,
+  setLogger,
+}

+ 33 - 0
libraries/fetch-utils/package.json

@@ -0,0 +1,33 @@
+{
+  "name": "@overleaf/fetch-utils",
+  "version": "0.1.0",
+  "description": "utilities for node-fetch",
+  "main": "index.js",
+  "scripts": {
+    "test": "yarn run lint && yarn run types:check && yarn run test:unit",
+    "lint": "eslint --cache --cache-location ../../.cache/eslint/ --ext .cjs,.js,.jsx,.mjs,.ts --max-warnings 0 --format unix .",
+    "lint:fix": "eslint --cache --cache-location ../../.cache/eslint/ --fix --ext .cjs,.js,.jsx,.mjs,.ts .",
+    "test:ci": "yarn run test:unit",
+    "test:unit": "mocha --exit test/**/*.{js,cjs}",
+    "types:check": "tsc --noEmit"
+  },
+  "author": "Overleaf (https://www.overleaf.com)",
+  "license": "AGPL-3.0-only",
+  "devDependencies": {
+    "@types/node-fetch": "^2.6.13",
+    "body-parser": "1.20.4",
+    "chai": "^4.3.6",
+    "chai-as-promised": "^7.1.1",
+    "express": "4.22.1",
+    "mocha": "^11.1.0",
+    "mocha-junit-reporter": "^2.2.1",
+    "mocha-multi-reporters": "^1.5.1",
+    "selfsigned": "^5.5.0",
+    "typescript": "^5.0.4"
+  },
+  "dependencies": {
+    "@overleaf/o-error": "workspace:*",
+    "lodash": "^4.18.1",
+    "node-fetch": "^2.7.0"
+  }
+}

+ 9 - 0
libraries/fetch-utils/test/mocha-multi-reporters.cjs

@@ -0,0 +1,9 @@
+module.exports = {
+  reporterEnabled: 'spec, mocha-junit-reporter',
+  mochaJunitReporterReporterOptions: {
+    mochaFile: `reports/junit-mocha-${process.env.MOCHA_GREP}.xml`,
+    includePending: true,
+    jenkinsMode: true,
+    output: true,
+  },
+}

+ 4 - 0
libraries/fetch-utils/test/setup.js

@@ -0,0 +1,4 @@
+const chai = require('chai')
+const chaiAsPromised = require('chai-as-promised')
+
+chai.use(chaiAsPromised)

+ 450 - 0
libraries/fetch-utils/test/unit/FetchUtilsTests.js

@@ -0,0 +1,450 @@
+const { expect } = require('chai')
+const fs = require('node:fs')
+const events = require('node:events')
+const { FetchError, AbortError } = require('node-fetch')
+const { Readable } = require('node:stream')
+const { pipeline } = require('node:stream/promises')
+const { once } = require('node:events')
+const { TestServer } = require('./helpers/TestServer')
+const selfsigned = require('selfsigned')
+const {
+  fetchJson,
+  fetchStream,
+  fetchNothing,
+  fetchRedirect,
+  fetchString,
+  RequestFailedError,
+  CustomHttpAgent,
+  CustomHttpsAgent,
+} = require('../..')
+
+const HTTP_PORT = 30001
+const HTTPS_PORT = 30002
+
+const dns = require('node:dns')
+const _originalLookup = dns.lookup
+// Custom DNS resolver function
+dns.lookup = (hostname, options, callback) => {
+  if (hostname === 'example.com') {
+    // If the hostname is our test case, return the ip address for the test server
+    if (options?.all) {
+      callback(null, [{ address: '127.0.0.1', family: 4 }])
+    } else {
+      callback(null, '127.0.0.1', 4)
+    }
+  } else {
+    // Otherwise, use the default lookup
+    _originalLookup(hostname, options, callback)
+  }
+}
+
+describe('fetch-utils', function () {
+  let PUBLIC_CERT
+
+  before(async function () {
+    this.server = new TestServer()
+    const attrs = [{ name: 'commonName', value: 'example.com' }]
+    const pems = await selfsigned.generate(attrs, { days: 365, keySize: 2048 })
+
+    const PRIVATE_KEY = pems.private
+    PUBLIC_CERT = pems.cert
+    await this.server.start(HTTP_PORT, HTTPS_PORT, {
+      key: PRIVATE_KEY,
+      cert: PUBLIC_CERT,
+    })
+    this.url = path => `http://example.com:${HTTP_PORT}${path}`
+    this.httpsUrl = path => `https://example.com:${HTTPS_PORT}${path}`
+  })
+
+  beforeEach(function () {
+    this.server.lastReq = undefined
+  })
+
+  after(async function () {
+    await this.server.stop()
+  })
+
+  describe('fetchJson', function () {
+    it('parses a JSON response', async function () {
+      const json = await fetchJson(this.url('/json/hello'))
+      expect(json).to.deep.equal({ msg: 'hello' })
+    })
+
+    it('parses JSON in the request', async function () {
+      const json = await fetchJson(this.url('/json/add'), {
+        method: 'POST',
+        json: { a: 2, b: 3 },
+      })
+      expect(json).to.deep.equal({ sum: 5 })
+    })
+
+    it('accepts stringified JSON as body', async function () {
+      const json = await fetchJson(this.url('/json/add'), {
+        method: 'POST',
+        body: JSON.stringify({ a: 2, b: 3 }),
+        headers: { 'Content-Type': 'application/json' },
+      })
+      expect(json).to.deep.equal({ sum: 5 })
+    })
+
+    it('throws a FetchError when the payload is not JSON', async function () {
+      await expect(fetchJson(this.url('/hello'))).to.be.rejectedWith(FetchError)
+    })
+
+    it('aborts the request if JSON parsing fails', async function () {
+      await expect(fetchJson(this.url('/large'))).to.be.rejectedWith(FetchError)
+      await expectRequestAborted(this.server.lastReq)
+    })
+
+    it('handles errors when the payload is JSON', async function () {
+      await expect(fetchJson(this.url('/json/500'))).to.be.rejectedWith(
+        RequestFailedError
+      )
+      await expectRequestAborted(this.server.lastReq)
+    })
+
+    it('handles errors when the payload is not JSON', async function () {
+      await expect(fetchJson(this.url('/500'))).to.be.rejectedWith(
+        RequestFailedError
+      )
+      await expectRequestAborted(this.server.lastReq)
+    })
+
+    it('supports abort signals', async function () {
+      await expect(
+        abortOnceReceived(
+          signal => fetchJson(this.url('/hang'), { signal }),
+          this.server
+        )
+      ).to.be.rejectedWith(AbortError)
+      await expectRequestAborted(this.server.lastReq)
+    })
+
+    it('supports basic auth', async function () {
+      const json = await fetchJson(this.url('/json/basic-auth'), {
+        basicAuth: { user: 'user', password: 'pass' },
+      })
+      expect(json).to.deep.equal({ key: 'verysecret' })
+    })
+
+    it("destroys the request body if it doesn't get consumed", async function () {
+      const stream = Readable.from(infiniteIterator())
+      await fetchJson(this.url('/json/ignore-request'), {
+        method: 'POST',
+        body: stream,
+      })
+      expect(stream.destroyed).to.be.true
+    })
+  })
+
+  describe('fetchStream', function () {
+    it('returns a stream', async function () {
+      const stream = await fetchStream(this.url('/large'))
+      const text = await streamToString(stream)
+      expect(text).to.equal(this.server.largePayload)
+    })
+
+    it('aborts the request when the stream is destroyed', async function () {
+      const stream = await fetchStream(this.url('/large'))
+      stream.destroy()
+      await expectRequestAborted(this.server.lastReq)
+    })
+
+    it('aborts the request when the request body is destroyed before transfer', async function () {
+      const stream = Readable.from(infiniteIterator())
+      const promise = fetchStream(this.url('/hang'), {
+        method: 'POST',
+        body: stream,
+      })
+      stream.destroy()
+      await expect(promise).to.be.rejectedWith(AbortError)
+      await wait(80)
+      expect(this.server.lastReq).to.be.undefined
+    })
+
+    it('aborts the request when the request body is destroyed during transfer', async function () {
+      const stream = Readable.from(infiniteIterator())
+      // Note: this test won't work on `/hang`
+      const promise = fetchStream(this.url('/sink'), {
+        method: 'POST',
+        body: stream,
+      })
+      await once(this.server.events, 'request-received')
+      stream.destroy()
+      await expect(promise).to.be.rejectedWith(AbortError)
+      await expectRequestAborted(this.server.lastReq)
+    })
+
+    it('handles errors', async function () {
+      await expect(fetchStream(this.url('/500'))).to.be.rejectedWith(
+        RequestFailedError
+      )
+      await expectRequestAborted(this.server.lastReq)
+    })
+
+    it('supports abort signals', async function () {
+      await expect(
+        abortOnceReceived(
+          signal => fetchStream(this.url('/hang'), { signal }),
+          this.server
+        )
+      ).to.be.rejectedWith(AbortError)
+      await expectRequestAborted(this.server.lastReq)
+    })
+
+    it('destroys the request body when an error occurs', async function () {
+      const stream = Readable.from(infiniteIterator())
+      await expect(
+        abortOnceReceived(
+          signal =>
+            fetchStream(this.url('/hang'), {
+              method: 'POST',
+              body: stream,
+              signal,
+            }),
+          this.server
+        )
+      ).to.be.rejectedWith(AbortError)
+      expect(stream.destroyed).to.be.true
+    })
+
+    it('detaches from signal on success', async function () {
+      const signal = AbortSignal.timeout(10_000)
+      for (let i = 0; i < 20; i++) {
+        const s = await fetchStream(this.url('/hello'), { signal })
+        expect(events.getEventListeners(signal, 'abort')).to.have.length(1)
+        await pipeline(s, fs.createWriteStream('/dev/null'))
+        expect(events.getEventListeners(signal, 'abort')).to.have.length(0)
+      }
+    })
+
+    it('detaches from signal on error', async function () {
+      const signal = AbortSignal.timeout(10_000)
+      for (let i = 0; i < 20; i++) {
+        try {
+          await fetchStream(this.url('/500'), { signal })
+        } catch (err) {
+          if (err instanceof RequestFailedError && err.response.status === 500)
+            continue
+          throw err
+        } finally {
+          expect(events.getEventListeners(signal, 'abort')).to.have.length(0)
+        }
+      }
+    })
+  })
+
+  describe('fetchNothing', function () {
+    it('closes the connection', async function () {
+      await fetchNothing(this.url('/large'))
+      await expectRequestAborted(this.server.lastReq)
+    })
+
+    it('aborts the request when the request body is destroyed before transfer', async function () {
+      const stream = Readable.from(infiniteIterator())
+      const promise = fetchNothing(this.url('/hang'), {
+        method: 'POST',
+        body: stream,
+      })
+      stream.destroy()
+      await expect(promise).to.be.rejectedWith(AbortError)
+      expect(this.server.lastReq).to.be.undefined
+    })
+
+    it('aborts the request when the request body is destroyed during transfer', async function () {
+      const stream = Readable.from(infiniteIterator())
+      // Note: this test won't work on `/hang`
+      const promise = fetchNothing(this.url('/sink'), {
+        method: 'POST',
+        body: stream,
+      })
+      await once(this.server.events, 'request-received')
+      stream.destroy()
+      await expect(promise).to.be.rejectedWith(AbortError)
+      await wait(80)
+      await expectRequestAborted(this.server.lastReq)
+    })
+
+    it("doesn't abort the request if the request body ends normally", async function () {
+      const stream = Readable.from('hello there')
+      await fetchNothing(this.url('/sink'), { method: 'POST', body: stream })
+    })
+
+    it('handles errors', async function () {
+      await expect(fetchNothing(this.url('/500'))).to.be.rejectedWith(
+        RequestFailedError
+      )
+      await expectRequestAborted(this.server.lastReq)
+    })
+
+    it('supports abort signals', async function () {
+      await expect(
+        abortOnceReceived(
+          signal => fetchNothing(this.url('/hang'), { signal }),
+          this.server
+        )
+      ).to.be.rejectedWith(AbortError)
+      await expectRequestAborted(this.server.lastReq)
+    })
+
+    it('destroys the request body when an error occurs', async function () {
+      const stream = Readable.from(infiniteIterator())
+      await expect(
+        abortOnceReceived(
+          signal =>
+            fetchNothing(this.url('/hang'), {
+              method: 'POST',
+              body: stream,
+              signal,
+            }),
+          this.server
+        )
+      ).to.be.rejectedWith(AbortError)
+      expect(stream.destroyed).to.be.true
+    })
+  })
+
+  describe('fetchString', function () {
+    it('returns a string', async function () {
+      const body = await fetchString(this.url('/hello'))
+      expect(body).to.equal('hello')
+    })
+
+    it('handles errors', async function () {
+      await expect(fetchString(this.url('/500'))).to.be.rejectedWith(
+        RequestFailedError
+      )
+      await expectRequestAborted(this.server.lastReq)
+    })
+  })
+
+  describe('fetchRedirect', function () {
+    it('returns the immediate redirect', async function () {
+      const body = await fetchRedirect(this.url('/redirect/1'))
+      expect(body).to.equal(this.url('/redirect/2'))
+    })
+
+    it('rejects status 200', async function () {
+      await expect(fetchRedirect(this.url('/hello'))).to.be.rejectedWith(
+        RequestFailedError
+      )
+      await expectRequestAborted(this.server.lastReq)
+    })
+
+    it('rejects empty redirect', async function () {
+      await expect(fetchRedirect(this.url('/redirect/empty-location')))
+        .to.be.rejectedWith(RequestFailedError)
+        .and.eventually.have.property('cause')
+        .and.to.have.property('message')
+        .to.equal('missing Location response header on 3xx response')
+      await expectRequestAborted(this.server.lastReq)
+    })
+
+    it('handles errors', async function () {
+      await expect(fetchRedirect(this.url('/500'))).to.be.rejectedWith(
+        RequestFailedError
+      )
+      await expectRequestAborted(this.server.lastReq)
+    })
+  })
+
+  describe('CustomHttpAgent', function () {
+    it('makes an http request successfully', async function () {
+      const agent = new CustomHttpAgent({ connectTimeout: 100 })
+      const body = await fetchString(this.url('/hello'), { agent })
+      expect(body).to.equal('hello')
+    })
+
+    it('times out when accessing a non-routable address', async function () {
+      const agent = new CustomHttpAgent({ connectTimeout: 10 })
+      await expect(fetchString('http://10.255.255.255/', { agent }))
+        .to.be.rejectedWith(FetchError)
+        .and.eventually.have.property('message')
+        .and.to.equal(
+          'request to http://10.255.255.255/ failed, reason: connect timeout'
+        )
+    })
+  })
+
+  describe('CustomHttpsAgent', function () {
+    it('makes an https request successfully', async function () {
+      const agent = new CustomHttpsAgent({
+        connectTimeout: 100,
+        ca: PUBLIC_CERT,
+      })
+      const body = await fetchString(this.httpsUrl('/hello'), { agent })
+      expect(body).to.equal('hello')
+    })
+
+    it('rejects an untrusted server', async function () {
+      const agent = new CustomHttpsAgent({
+        connectTimeout: 100,
+      })
+      await expect(fetchString(this.httpsUrl('/hello'), { agent }))
+        .to.be.rejectedWith(FetchError)
+        .and.eventually.have.property('code')
+        .and.to.equal('DEPTH_ZERO_SELF_SIGNED_CERT')
+    })
+
+    it('times out when accessing a non-routable address', async function () {
+      const agent = new CustomHttpsAgent({ connectTimeout: 10 })
+      await expect(fetchString('https://10.255.255.255/', { agent }))
+        .to.be.rejectedWith(FetchError)
+        .and.eventually.have.property('message')
+        .and.to.equal(
+          'request to https://10.255.255.255/ failed, reason: connect timeout'
+        )
+    })
+  })
+})
+
+async function streamToString(stream) {
+  let s = ''
+  for await (const chunk of stream) {
+    s += chunk
+  }
+  return s
+}
+
+async function* infiniteIterator() {
+  let i = 1
+  while (true) {
+    yield `chunk ${i++}\n`
+  }
+}
+
+/**
+ * @param {(signal: AbortSignal) => Promise<any>} func
+ * @param {TestServer} server
+ */
+async function abortOnceReceived(func, server) {
+  const controller = new AbortController()
+  const promise = func(controller.signal)
+  expect(events.getEventListeners(controller.signal, 'abort')).to.have.length(1)
+  await once(server.events, 'request-received')
+  controller.abort()
+  try {
+    return await promise
+  } finally {
+    expect(events.getEventListeners(controller.signal, 'abort')).to.have.length(
+      0
+    )
+  }
+}
+
+async function expectRequestAborted(req) {
+  if (!req.destroyed) {
+    try {
+      await once(req, 'close')
+    } catch (err) {
+      // `once` throws if req emits an 'error' event.
+      // We ignore `Error: aborted` when the request is aborted.
+      if (err.message !== 'aborted') {
+        throw err
+      }
+    }
+  }
+  expect(req.destroyed).to.be.true
+}
+
+const wait = ms => new Promise(resolve => setTimeout(resolve, ms))

+ 139 - 0
libraries/fetch-utils/test/unit/helpers/TestServer.js

@@ -0,0 +1,139 @@
+const express = require('express')
+const bodyParser = require('body-parser')
+const { EventEmitter } = require('node:events')
+const http = require('node:http')
+const https = require('node:https')
+const { promisify } = require('node:util')
+
+class TestServer {
+  constructor() {
+    this.app = express()
+    this.events = new EventEmitter()
+
+    this.app.use(bodyParser.json())
+    this.app.use((req, res, next) => {
+      this.events.emit('request-received')
+      this.lastReq = req
+      next()
+    })
+
+    // Plain text endpoints
+
+    this.app.get('/hello', (req, res) => {
+      res.send('hello')
+    })
+
+    this.largePayload = 'x'.repeat(16 * 1024 * 1024)
+    this.app.get('/large', (req, res) => {
+      res.send(this.largePayload)
+    })
+
+    this.app.get('/204', (req, res) => {
+      res.status(204).end()
+    })
+
+    this.app.get('/empty', (req, res) => {
+      res.end()
+    })
+
+    this.app.get('/500', (req, res) => {
+      res.sendStatus(500)
+    })
+
+    this.app.post('/sink', (req, res) => {
+      req.on('data', () => {})
+      req.on('end', () => {
+        res.status(204).end()
+      })
+    })
+
+    // JSON endpoints
+
+    this.app.get('/json/hello', (req, res) => {
+      res.json({ msg: 'hello' })
+    })
+
+    this.app.post('/json/add', (req, res) => {
+      const { a, b } = req.body
+      res.json({ sum: a + b })
+    })
+
+    this.app.get('/json/500', (req, res) => {
+      res.status(500).json({ error: 'Internal server error' })
+    })
+
+    this.app.get('/json/basic-auth', (req, res) => {
+      const expectedAuth =
+        'Basic ' + Buffer.from('user:pass').toString('base64')
+      if (req.headers.authorization === expectedAuth) {
+        res.json({ key: 'verysecret' })
+      } else {
+        res.status(401).json({ error: 'unauthorized' })
+      }
+    })
+
+    this.app.post('/json/ignore-request', (req, res) => {
+      res.json({ msg: 'hello' })
+    })
+
+    // Never returns
+
+    this.app.get('/hang', (req, res) => {})
+    this.app.post('/hang', (req, res) => {})
+
+    // Redirect
+
+    this.app.get('/redirect/1', (req, res) => {
+      res.redirect('/redirect/2')
+    })
+    this.app.get('/redirect/2', (req, res) => {
+      res.send('body after redirect')
+    })
+    this.app.get('/redirect/empty-location', (req, res) => {
+      res.sendStatus(302)
+    })
+  }
+
+  start(port, httpsPort, httpsOptions) {
+    const startHttp = new Promise((resolve, reject) => {
+      this.server = http.createServer(this.app).listen(port, err => {
+        if (err) {
+          reject(err)
+        } else {
+          resolve()
+        }
+      })
+    })
+    const startHttps = new Promise((resolve, reject) => {
+      this.https_server = https
+        .createServer(httpsOptions, this.app)
+        .listen(httpsPort, err => {
+          if (err) {
+            reject(err)
+          } else {
+            resolve()
+          }
+        })
+    })
+    return Promise.all([startHttp, startHttps])
+  }
+
+  stop() {
+    const promises = []
+    if (this.server) {
+      const stopHttp = promisify(this.server.close).bind(this.server)
+      this.server.closeAllConnections()
+      promises.push(stopHttp())
+    }
+    if (this.https_server) {
+      const stopHttps = promisify(this.https_server.close).bind(
+        this.https_server
+      )
+      this.https_server.closeAllConnections()
+      promises.push(stopHttps())
+    }
+    return Promise.all(promises)
+  }
+}
+
+module.exports = { TestServer }

Một số tệp đã không được hiển thị bởi vì quá nhiều tập tin thay đổi trong này khác