diff --git a/src/topics/merge.js b/src/topics/merge.js index 1a06adefbb..5972e49446 100644 --- a/src/topics/merge.js +++ b/src/topics/merge.js @@ -1,82 +1,200 @@ 'use strict'; +const __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P((resolve) => { resolve(value); }); } + return new (P || (P = Promise))((resolve, reject) => { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +const __generator = (this && this.__generator) || function (thisArg, body) { + let _ = { label: 0, sent: function () { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }; let f; let y; let t; let + g = Object.create((typeof Iterator === 'function' ? Iterator : Object).prototype); + return g.next = verb(0), g.throw = verb(1), g.return = verb(2), typeof Symbol === 'function' && (g[Symbol.iterator] = function () { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError('Generator is already executing.'); + while (g && (g = 0, op[0] && (_ = 0)), _) { + try { + if (f = 1, y && (t = op[0] & 2 ? y.return : op[0] ? y.throw || ((t = y.return) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; const plugins = require('../plugins'); const posts = require('../posts'); -module.exports = function (Topics) { - Topics.merge = async function (tids, uid, options) { - options = options || {}; - - const topicsData = await Topics.getTopicsFields(tids, ['scheduled']); - if (topicsData.some(t => t.scheduled)) { - throw new Error('[[error:cant-merge-scheduled]]'); - } - - const oldestTid = findOldestTopic(tids); - let mergeIntoTid = oldestTid; - if (options.mainTid) { - mergeIntoTid = options.mainTid; - } else if (options.newTopicTitle) { - mergeIntoTid = await createNewTopic(options.newTopicTitle, oldestTid); +function topicsModule(Topics) { + const merge = function () { + const args = []; + for (let _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; } - - const otherTids = tids.sort((a, b) => a - b) - .filter(tid => tid && parseInt(tid, 10) !== parseInt(mergeIntoTid, 10)); - - for (const tid of otherTids) { - /* eslint-disable no-await-in-loop */ - const pids = await Topics.getPids(tid); - for (const pid of pids) { - await Topics.movePostToTopic(uid, pid, mergeIntoTid); - } - - await Topics.setTopicField(tid, 'mainPid', 0); - await Topics.delete(tid, uid); - await Topics.setTopicFields(tid, { - mergeIntoTid: mergeIntoTid, - mergerUid: uid, - mergedTimestamp: Date.now(), + return __awaiter(this, void 0, void 0, function () { + let tids; let uid; let _a; let options; let topicsData; let oldestTid; let mergeIntoTid; let otherTids; let _b; let otherTids_1; let tid; let pids; let _c; let pids_1; let + pid; + return __generator(this, function (_d) { + switch (_d.label) { + case 0: + tids = args[0], uid = args[1], _a = args[2], options = _a === void 0 ? {} : _a; + return [4 /* yield */, this.getTopicsFields(tids, ['scheduled'])]; + case 1: + topicsData = _d.sent(); + if (topicsData.some(t => t.scheduled)) { + throw new Error('[[error:cant-merge-scheduled]]'); + } + oldestTid = findOldestTopic(tids); + mergeIntoTid = oldestTid; + if (!options.mainTid) return [3 /* break */, 2]; + mergeIntoTid = options.mainTid; + return [3 /* break */, 4]; + case 2: + if (!options.newTopicTitle) return [3 /* break */, 4]; + return [4 /* yield */, createNewTopic.call(this, options.newTopicTitle, oldestTid)]; + case 3: + mergeIntoTid = _d.sent(); + _d.label = 4; + case 4: + otherTids = tids.sort((a, b) => a - b) + .filter(tid => tid && parseInt(tid.toString(), 10) !== parseInt(mergeIntoTid.toString(), 10)); + _b = 0, otherTids_1 = otherTids; + _d.label = 5; + case 5: + if (!(_b < otherTids_1.length)) return [3 /* break */, 15]; + tid = otherTids_1[_b]; + return [4 /* yield */, this.getPids(tid)]; + case 6: + pids = _d.sent(); + _c = 0, pids_1 = pids; + _d.label = 7; + case 7: + if (!(_c < pids_1.length)) return [3 /* break */, 10]; + pid = pids_1[_c]; + return [4 /* yield */, this.movePostToTopic(uid, pid, mergeIntoTid)]; + case 8: + _d.sent(); + _d.label = 9; + case 9: + _c++; + return [3 /* break */, 7]; + case 10: return [4 /* yield */, this.setTopicField(tid, 'mainPid', 0)]; + case 11: + _d.sent(); + return [4 /* yield */, this.delete(tid, uid)]; + case 12: + _d.sent(); + return [4 /* yield */, this.setTopicFields(tid, { + mergeIntoTid: mergeIntoTid, + mergerUid: uid, + mergedTimestamp: Date.now(), + })]; + case 13: + _d.sent(); + _d.label = 14; + case 14: + _b++; + return [3 /* break */, 5]; + case 15: return [4 /* yield */, Promise.all([ + posts.updateQueuedPostsTopic(mergeIntoTid, otherTids), + updateViewCount.call(this, mergeIntoTid, tids), + ])]; + case 16: + _d.sent(); + return [4 /* yield */, fireHook('action:topic.merge', { + uid: uid, + tids: tids, + mergeIntoTid: mergeIntoTid, + otherTids: otherTids, + })]; + case 17: + _d.sent(); + return [2 /* return */, mergeIntoTid]; + } }); - } - - await Promise.all([ - posts.updateQueuedPostsTopic(mergeIntoTid, otherTids), - updateViewCount(mergeIntoTid, tids), - ]); - - plugins.hooks.fire('action:topic.merge', { - uid: uid, - tids: tids, - mergeIntoTid: mergeIntoTid, - otherTids: otherTids, }); - return mergeIntoTid; }; - - async function createNewTopic(title, oldestTid) { - const topicData = await Topics.getTopicFields(oldestTid, ['uid', 'cid']); - const params = { - uid: topicData.uid, - cid: topicData.cid, - title: title, - }; - const result = await plugins.hooks.fire('filter:topic.mergeCreateNewTopic', { - oldestTid: oldestTid, - params: params, + function createNewTopic(title, oldestTid) { + return __awaiter(this, void 0, void 0, function () { + let topicData; let params; let + result; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /* yield */, this.getTopicFields(oldestTid, ['uid', 'cid'])]; + case 1: + topicData = _a.sent(); + params = { + uid: topicData.uid, + cid: topicData.cid, + title: title, + }; + return [4 /* yield */, fireHook('filter:topic.mergeCreateNewTopic', { + oldestTid: oldestTid, + params: params, + })]; + case 2: + result = _a.sent(); + return [2 /* return */, this.create(result.params)]; + } + }); }); - const tid = await Topics.create(result.params); - return tid; } - - async function updateViewCount(mergeIntoTid, tids) { - const topicData = await Topics.getTopicsFields(tids, ['viewcount']); - const totalViewCount = topicData.reduce( - (count, topic) => count + parseInt(topic.viewcount, 10), 0 - ); - await Topics.setTopicField(mergeIntoTid, 'viewcount', totalViewCount); + function updateViewCount(mergeIntoTid, tids) { + return __awaiter(this, void 0, void 0, function () { + let topicData; let + totalViewCount; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /* yield */, this.getTopicsFields(tids, ['viewcount'])]; + case 1: + topicData = _a.sent(); + totalViewCount = topicData.reduce((count, topic) => count + parseInt(topic.viewcount.toString(), 10), 0); + return [4 /* yield */, this.setTopicField(mergeIntoTid, 'viewcount', totalViewCount)]; + case 2: + _a.sent(); + return [2 /* return */, totalViewCount]; + } + }); + }); } - function findOldestTopic(tids) { - return Math.min.apply(null, tids); + return Math.min.apply(Math, tids); } -}; + function fireHook(hookName, hookData) { + return __awaiter(this, void 0, void 0, function () { + let err_1; + return __generator(this, (_a) => { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, , 3]); + return [4 /* yield */, plugins.hooks.fire(hookName, hookData)]; + case 1: return [2 /* return */, _a.sent()]; + case 2: + err_1 = _a.sent(); + console.error('Error in '.concat(hookName, ' hook:'), err_1); + return [2 /* return */, hookData]; + case 3: return [2]; + } + }); + }); + } + return { merge: merge }; +} +module.exports = topicsModule; diff --git a/src/topics/merge.ts b/src/topics/merge.ts new file mode 100644 index 0000000000..13e4e51745 --- /dev/null +++ b/src/topics/merge.ts @@ -0,0 +1,112 @@ +'use strict'; + +const plugins = require('../plugins'); +const posts = require('../posts'); + +interface TopicsType { + merge: (tids: number[], uid: number, options?: MergeOptions) => Promise; + getTopicsFields: (tids: number[], fields: string[]) => Promise; + getPids: (tid: number) => Promise; + movePostToTopic: (uid: number, pid: number, tid: number) => Promise; + setTopicField: (tid: number, field: string, value: any) => Promise; + delete: (tid: number, uid: number) => Promise; + setTopicFields: (tid: number, data: any) => Promise; + getTopicFields: (tid: number, fields: string[]) => Promise; + create: (params: any) => Promise; +} + +interface MergeOptions { + mainTid?: number; + newTopicTitle?: string; +} + +function topicsModule(Topics: TopicsType) { + const merge = async function (this: TopicsType, ...args: [number[], number, MergeOptions?]): Promise { + const [tids, uid, options = {}] = args; + const topicsData = await this.getTopicsFields(tids, ['scheduled']); + if (topicsData.some(t => t.scheduled)) { + throw new Error('[[error:cant-merge-scheduled]]'); + } + + const oldestTid = findOldestTopic(tids); + let mergeIntoTid = oldestTid; + if (options.mainTid) { + mergeIntoTid = options.mainTid; + } else if (options.newTopicTitle) { + mergeIntoTid = await createNewTopic.call(this, options.newTopicTitle, oldestTid); + } + + const otherTids = tids.sort((a, b) => a - b) + .filter(tid => tid && parseInt(tid.toString(), 10) !== parseInt(mergeIntoTid.toString(), 10)); + + for (const tid of otherTids) { + /* eslint-disable no-await-in-loop */ + const pids = await this.getPids(tid); + for (const pid of pids) { + await this.movePostToTopic(uid, pid, mergeIntoTid); + } + + await this.setTopicField(tid, 'mainPid', 0); + await this.delete(tid, uid); + await this.setTopicFields(tid, { + mergeIntoTid: mergeIntoTid, + mergerUid: uid, + mergedTimestamp: Date.now(), + }); + } + + await Promise.all([ + posts.updateQueuedPostsTopic(mergeIntoTid, otherTids), + updateViewCount.call(this, mergeIntoTid, tids), + ]); + + await fireHook('action:topic.merge', { + uid, + tids, + mergeIntoTid, + otherTids, + }); + + return mergeIntoTid; + }; + + async function createNewTopic(this: TopicsType, title: string, oldestTid: number): Promise { + const topicData = await this.getTopicFields(oldestTid, ['uid', 'cid']); + const params = { + uid: topicData.uid, + cid: topicData.cid, + title: title, + }; + const result = await fireHook('filter:topic.mergeCreateNewTopic', { + oldestTid, + params, + }); + return this.create(result.params); + } + + async function updateViewCount(this: TopicsType, mergeIntoTid: number, tids: number[]): Promise { + const topicData = await this.getTopicsFields(tids, ['viewcount']); + const totalViewCount = topicData.reduce( + (count: number, topic: any) => count + parseInt(topic.viewcount.toString(), 10), 0 + ); + await this.setTopicField(mergeIntoTid, 'viewcount', totalViewCount); + return totalViewCount; + } + + function findOldestTopic(tids: number[]): number { + return Math.min(...tids); + } + + async function fireHook(hookName: string, hookData: any): Promise { + try { + return await plugins.hooks.fire(hookName, hookData); + } catch (err) { + console.error(`Error in ${hookName} hook:`, err); + return hookData; + } + } + + return { merge }; +} + +module.exports = topicsModule; \ No newline at end of file diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000000..77dd9e067e --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,110 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig to read more about this file */ + + /* Projects */ + // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ + // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ + // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ + // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ + // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ + + /* Language and Environment */ + "target": "es2017", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "jsx": "preserve", /* Specify what JSX code is generated. */ + // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ + // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ + // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ + // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ + // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ + // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "commonjs", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ + // "types": [], /* Specify type package names to be included without being referenced in a source file. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ + // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ + // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ + // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ + // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ + // "noUncheckedSideEffectImports": true, /* Check side effect imports. */ + // "resolveJsonModule": true, /* Enable importing .json files. */ + // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ + // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ + + /* JavaScript Support */ + // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ + // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ + + /* Emit */ + // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + // "declarationMap": true, /* Create sourcemaps for d.ts files. */ + // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ + // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ + // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ + // "noEmit": true, /* Disable emitting files from a compilation. */ + // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ + // "outDir": "./", /* Specify an output folder for all emitted files. */ + // "removeComments": true, /* Disable emitting comments. */ + // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ + // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ + // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ + // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ + // "newLine": "crlf", /* Set the newline character for emitting files. */ + // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ + // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ + // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ + // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ + // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ + + /* Interop Constraints */ + // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ + // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ + // "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */ + // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ + // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ + // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ + // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ + // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ + // "strictBuiltinIteratorReturn": true, /* Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'. */ + // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ + // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ + // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ + // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ + // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ + // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ + // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ + // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ + // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ + // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ + // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ + // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ + // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ + + /* Completeness */ + // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ + "skipLibCheck": true /* Skip type checking all .d.ts files. */ + } +}